Initial commit - Horux Despachos NL
This commit is contained in:
222
apps/web/app/(dashboard)/configuracion/facturacion/page.tsx
Normal file
222
apps/web/app/(dashboard)/configuracion/facturacion/page.tsx
Normal file
@@ -0,0 +1,222 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Header } from '@/components/layouts/header';
|
||||
import { Card, CardContent, CardHeader, CardTitle, Button, Label } from '@horux/shared-ui';
|
||||
import { Receipt, Save, AlertCircle } from 'lucide-react';
|
||||
import { apiClient } from '@/lib/api/client';
|
||||
import { getUsosCfdi } from '@/lib/api/catalogos';
|
||||
|
||||
interface PreferenciasFacturacion {
|
||||
factPreferencia: 'publico_general' | 'mis_datos';
|
||||
factUsoCfdi: string;
|
||||
factRegimenPreferido: string | null;
|
||||
regimenesActivos: { clave: string; descripcion: string }[];
|
||||
}
|
||||
|
||||
export default function PreferenciasFacturacionPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
|
||||
const { data: prefs, isLoading } = useQuery<PreferenciasFacturacion>({
|
||||
queryKey: ['preferencias-facturacion'],
|
||||
queryFn: () => apiClient.get<PreferenciasFacturacion>('/facturacion/preferencias-facturacion').then(r => r.data),
|
||||
});
|
||||
|
||||
const { data: usosCfdiAll = [] } = useQuery({
|
||||
queryKey: ['usos-cfdi'],
|
||||
queryFn: getUsosCfdi,
|
||||
});
|
||||
|
||||
// Solo se permiten 2 usos para auto-facturación de pagos del SaaS:
|
||||
// G03 (Gastos en general) — el más común para servicios deducibles.
|
||||
// S01 (Sin efectos fiscales) — para clientes que no requieren deducir.
|
||||
const ALLOWED_USOS = ['G03', 'S01'];
|
||||
const usosCfdi = usosCfdiAll.filter(u => ALLOWED_USOS.includes(u.clave));
|
||||
|
||||
const [form, setForm] = useState<PreferenciasFacturacion>({
|
||||
factPreferencia: 'mis_datos',
|
||||
factUsoCfdi: 'G03',
|
||||
factRegimenPreferido: null,
|
||||
regimenesActivos: [],
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (prefs) setForm(prefs);
|
||||
}, [prefs]);
|
||||
|
||||
const onSave = async () => {
|
||||
setSaving(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await apiClient.put('/facturacion/preferencias-facturacion', {
|
||||
factPreferencia: form.factPreferencia,
|
||||
factUsoCfdi: form.factUsoCfdi,
|
||||
factRegimenPreferido: form.factRegimenPreferido,
|
||||
});
|
||||
queryClient.invalidateQueries({ queryKey: ['preferencias-facturacion'] });
|
||||
setMessage({ kind: 'ok', text: 'Preferencias guardadas. Aplicará a futuros pagos auto-facturados.' });
|
||||
} catch (err: any) {
|
||||
setMessage({ kind: 'err', text: err?.response?.data?.message || err?.message || 'Error al guardar' });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const isPubGen = form.factPreferencia === 'publico_general';
|
||||
const tieneRegimenes = form.regimenesActivos.length > 0;
|
||||
const advertirSinRegimenes = form.factPreferencia === 'mis_datos' && !tieneRegimenes;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header title="Preferencias de Facturación" />
|
||||
<main className="p-6 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Receipt className="h-5 w-5" />
|
||||
Auto-facturación de pagos de suscripción
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
Cuando MercadoPago confirma un pago de tu suscripción, Horux 360 emite automáticamente
|
||||
un CFDI. Aquí defines a qué nombre y con qué uso CFDI.
|
||||
</p>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="text-muted-foreground text-sm">Cargando…</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{/* Toggle preferencia */}
|
||||
<div className="space-y-2">
|
||||
<Label>Receptor de la factura</Label>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setForm(f => ({ ...f, factPreferencia: 'mis_datos' }))}
|
||||
className={`text-left rounded-lg border-2 p-4 transition-colors ${
|
||||
form.factPreferencia === 'mis_datos'
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium">Mis datos fiscales</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Usa el RFC, razón social, CP y régimen registrados en tu CSF.
|
||||
Recomendado para que los pagos sean deducibles para tu empresa.
|
||||
</p>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setForm(f => ({ ...f, factPreferencia: 'publico_general' }))}
|
||||
className={`text-left rounded-lg border-2 p-4 transition-colors ${
|
||||
form.factPreferencia === 'publico_general'
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium">Público en general</div>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Factura genérica (XAXX010101000) sin datos fiscales del receptor.
|
||||
No deducible para tu empresa.
|
||||
</p>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advertencia si sin CSF y eligió "mis datos" */}
|
||||
{advertirSinRegimenes && (
|
||||
<div className="flex items-start gap-2 rounded-lg border border-amber-300 bg-amber-50 p-3">
|
||||
<AlertCircle className="h-4 w-4 text-amber-700 mt-0.5 shrink-0" />
|
||||
<div className="text-sm text-amber-800">
|
||||
No tienes regímenes fiscales registrados. Sube tu FIEL en
|
||||
<strong> /configuracion</strong> para que el sistema descargue tu CSF y
|
||||
sincronice automáticamente. Mientras tanto, las facturas saldrán a
|
||||
Público en General aunque la preferencia esté en "Mis datos".
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Uso CFDI (solo si "mis datos") */}
|
||||
{!isPubGen && (
|
||||
<div className="space-y-2">
|
||||
<Label>Uso CFDI</Label>
|
||||
<select
|
||||
value={form.factUsoCfdi}
|
||||
onChange={e => setForm(f => ({ ...f, factUsoCfdi: e.target.value }))}
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
{usosCfdi.map(u => (
|
||||
<option key={u.clave} value={u.clave}>
|
||||
{u.clave} — {u.descripcion}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Por defecto G03 (Gastos en general). Tu contador puede recomendarte otro.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Régimen preferido (solo si "mis datos" Y tiene varios) */}
|
||||
{!isPubGen && form.regimenesActivos.length > 1 && (
|
||||
<div className="space-y-2">
|
||||
<Label>Régimen fiscal a usar</Label>
|
||||
<select
|
||||
value={form.factRegimenPreferido || ''}
|
||||
onChange={e => setForm(f => ({
|
||||
...f,
|
||||
factRegimenPreferido: e.target.value || null,
|
||||
}))}
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">Automático (primer régimen activo)</option>
|
||||
{form.regimenesActivos.map(r => (
|
||||
<option key={r.clave} value={r.clave}>
|
||||
{r.clave} — {r.descripcion}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tienes varios regímenes activos. Elige cuál usar al facturar tus pagos.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPubGen && form.regimenesActivos.length === 1 && (
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Régimen fiscal:{' '}
|
||||
<strong>
|
||||
{form.regimenesActivos[0].clave} — {form.regimenesActivos[0].descripcion}
|
||||
</strong>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Mensaje + botón */}
|
||||
{message && (
|
||||
<div className={`rounded-lg px-3 py-2 text-sm ${
|
||||
message.kind === 'ok'
|
||||
? 'bg-green-50 border border-green-200 text-green-800'
|
||||
: 'bg-red-50 border border-red-200 text-red-800'
|
||||
}`}>
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={onSave} disabled={saving}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
{saving ? 'Guardando…' : 'Guardar preferencias'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user