@innertia-solutions/innertia-nuxt 0.1.91 → 0.1.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/components/Ai/ModelPrices.vue +105 -0
  3. package/components/Ai/UsageReport.vue +127 -0
  4. package/components/Ai/UsageSummary.vue +13 -0
  5. package/components/Ai/__tests__/sfc-compile.test.ts +26 -0
  6. package/components/Billing/AccountStatement.vue +121 -0
  7. package/components/Billing/ActivityLog.vue +44 -0
  8. package/components/Billing/Adjustments.vue +169 -0
  9. package/components/Billing/ClientTerms.vue +70 -0
  10. package/components/Billing/ClientTotals.vue +65 -0
  11. package/components/Billing/CreditNoteForm.vue +82 -0
  12. package/components/Billing/Invoices.vue +394 -0
  13. package/components/Billing/Overview.vue +130 -0
  14. package/components/Billing/Plans.vue +146 -0
  15. package/components/Billing/Reconciliation.vue +309 -0
  16. package/components/Billing/Reports.vue +87 -0
  17. package/components/Billing/Settings.vue +112 -0
  18. package/components/Billing/SpaceSubscription.vue +202 -0
  19. package/components/Billing/StatusBanner.vue +36 -0
  20. package/components/Billing/UsageTable.vue +32 -0
  21. package/components/Billing/__tests__/sfc-compile.test.ts +29 -0
  22. package/composables/useAiUsage/index.ts +48 -0
  23. package/composables/useAiUsage/internal/__tests__/aiUsage.test.ts +50 -0
  24. package/composables/useAiUsage/internal/aiUsage.ts +140 -0
  25. package/composables/useBilling/index.ts +257 -0
  26. package/composables/useBilling/internal/__tests__/billing.test.ts +78 -0
  27. package/composables/useBilling/internal/__tests__/collections.test.ts +120 -0
  28. package/composables/useBilling/internal/billing.ts +587 -0
  29. package/docs/ai-usage.md +38 -0
  30. package/docs/billing.md +110 -0
  31. package/nuxt.config.ts +1 -1
  32. package/package.json +1 -1
@@ -0,0 +1,70 @@
1
+ <script setup lang="ts">
2
+ import { errorMessage } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.ClientTerms — collection terms of a client: late fee interest (percent, per month or per day,
6
+ * cap over the invoice total, exemption) and whether payment reminders are sent. Changes are audited.
7
+ * Backend: GET|PUT {endpoint}/clients/{clientId}/terms.
8
+ *
9
+ * <Billing.ClientTerms :client-id="client.id" :can-edit="isOwner" />
10
+ */
11
+ const props = withDefaults(defineProps<{ endpoint?: string; clientId: string; canEdit?: boolean }>(), { endpoint: 'platform/billing', canEdit: true })
12
+
13
+ const toast = useToast()
14
+ const billing = useBillingPlatform({ base: props.endpoint })
15
+ const query = billing.terms(computed(() => props.clientId))
16
+ const form = reactive({ late_fee_percent: '' as string | number, late_fee_basis: 'monthly', late_fee_cap_percent: '' as string | number, late_fee_exempt: false, reminders_enabled: true })
17
+
18
+ watch(() => query.data.value, (t: any) => {
19
+ if (t) Object.assign(form, { late_fee_percent: t.late_fee_percent ?? 0, late_fee_basis: t.late_fee_basis, late_fee_cap_percent: t.late_fee_cap_percent ?? '', late_fee_exempt: t.late_fee_exempt, reminders_enabled: t.reminders_enabled })
20
+ }, { immediate: true })
21
+
22
+ const example = computed(() => {
23
+ const p = Number(form.late_fee_percent) || 0
24
+ if (p <= 0 || form.late_fee_exempt) return 'Sin interés por mora.'
25
+ const daily = form.late_fee_basis === 'daily' ? p : p / 30
26
+ return `Una deuda vencida de $ 100.000 genera $ ${Math.round(100000 * daily / 100 * 30).toLocaleString('es-CL')} en 30 días (se cobra en el cierre siguiente).`
27
+ })
28
+
29
+ async function save() {
30
+ try {
31
+ await billing.saveTerms.mutateAsync({
32
+ clientId: props.clientId,
33
+ body: {
34
+ late_fee_percent: Number(form.late_fee_percent) || 0,
35
+ late_fee_basis: form.late_fee_basis,
36
+ late_fee_cap_percent: form.late_fee_cap_percent === '' ? null : Number(form.late_fee_cap_percent),
37
+ late_fee_exempt: form.late_fee_exempt,
38
+ reminders_enabled: form.reminders_enabled,
39
+ },
40
+ })
41
+ toast.success('Condiciones guardadas.')
42
+ } catch (e: any) {
43
+ toast.error(errorMessage(e, 'No se pudieron guardar las condiciones.'))
44
+ }
45
+ }
46
+
47
+ const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
48
+ </script>
49
+
50
+ <template>
51
+ <form class="bg-card border border-card-line rounded-card p-4 grid gap-3 sm:grid-cols-2 text-sm" @submit.prevent="save">
52
+ <p class="sm:col-span-2 font-medium text-foreground">Interés por mora</p>
53
+ <label class="block space-y-1"><span class="font-medium">Tasa (%)</span>
54
+ <input v-model="form.late_fee_percent" type="number" min="0" max="50" step="0.01" :class="inputClass" :disabled="!canEdit" />
55
+ </label>
56
+ <label class="block space-y-1"><span class="font-medium">Base</span>
57
+ <select v-model="form.late_fee_basis" :class="inputClass" :disabled="!canEdit"><option value="monthly">Mensual</option><option value="daily">Diaria</option></select>
58
+ </label>
59
+ <label class="block space-y-1"><span class="font-medium">Tope (% del total de la factura)</span>
60
+ <input v-model="form.late_fee_cap_percent" type="number" min="0" step="0.01" :class="inputClass" :disabled="!canEdit" placeholder="Sin tope" />
61
+ </label>
62
+ <label class="flex items-center gap-2 self-end h-9"><input v-model="form.late_fee_exempt" type="checkbox" class="rounded" :disabled="!canEdit" /> Cliente exento de interés</label>
63
+ <p class="sm:col-span-2 text-xs text-muted-foreground">{{ example }}</p>
64
+ <p class="sm:col-span-2 font-medium text-foreground pt-2">Recordatorios</p>
65
+ <label class="sm:col-span-2 flex items-center gap-2"><input v-model="form.reminders_enabled" type="checkbox" class="rounded" :disabled="!canEdit" /> Enviar recordatorios de pago por correo a este cliente</label>
66
+ <div v-if="canEdit" class="sm:col-span-2 flex justify-end">
67
+ <App.Button text="Guardar" severity="primary" size="sm" :loading="billing.saveTerms.isPending.value" @click="save" />
68
+ </div>
69
+ </form>
70
+ </template>
@@ -0,0 +1,65 @@
1
+ <script setup lang="ts">
2
+ import { formatMoney, subscriptionStatus } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.ClientTotals — per client: MRR (monthly base of billable subscriptions), open balance,
6
+ * overdue and drafts, with its spaces (Prod/Pruebas badge, subscription status, plan).
7
+ * Backend: GET {endpoint}/clients/totals. Emits `select-client` / `select-space` for navigation.
8
+ *
9
+ * <Billing.ClientTotals @select-space="key => navigateTo(`/platform/spaces/${key}`)" />
10
+ */
11
+ const props = withDefaults(defineProps<{ endpoint?: string }>(), { endpoint: 'platform/billing' })
12
+ const emit = defineEmits<{ 'select-client': [id: string]; 'select-space': [key: string] }>()
13
+
14
+ const { clientTotals } = useBillingPlatform({ base: props.endpoint })
15
+ const data = computed<any>(() => clientTotals.data.value)
16
+ const filter = ref<'all' | 'balance' | 'overdue'>('all')
17
+ const rows = computed<any[]>(() => (data.value?.data ?? []).filter((c: any) =>
18
+ filter.value === 'all' ? true : filter.value === 'overdue' ? c.overdue > 0 : c.balance > 0))
19
+ </script>
20
+
21
+ <template>
22
+ <div class="space-y-4">
23
+ <div v-if="data" class="grid gap-3 sm:grid-cols-3">
24
+ <App.StatCard label="MRR" :value="formatMoney(data.totals.mrr)" hint="Base mensual de las suscripciones vigentes" />
25
+ <App.StatCard label="Por cobrar" :value="formatMoney(data.totals.balance)" />
26
+ <App.StatCard label="Vencido" :value="formatMoney(data.totals.overdue)" :value-class="data.totals.overdue > 0 ? 'text-danger' : 'text-foreground'" />
27
+ </div>
28
+
29
+ <div class="flex gap-2 text-sm">
30
+ <button v-for="f in [['all', 'Todos'], ['balance', 'Con saldo'], ['overdue', 'Con mora']]" :key="f[0]" type="button"
31
+ class="px-3 py-1 rounded-control border" :class="filter === f[0] ? 'border-primary text-primary' : 'border-card-line text-muted-foreground'"
32
+ @click="filter = f[0] as any">{{ f[1] }}</button>
33
+ </div>
34
+
35
+ <div class="bg-card border border-card-line rounded-card overflow-hidden">
36
+ <div v-if="clientTotals.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
37
+ <div v-else-if="clientTotals.isError.value" class="p-8 text-center text-sm text-muted-foreground">
38
+ No se pudieron cargar los totales.
39
+ <button type="button" class="text-primary hover:underline" @click="clientTotals.refetch()">Reintentar</button>
40
+ </div>
41
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin clientes para este filtro.</div>
42
+ <ul v-else class="divide-y divide-card-line">
43
+ <li v-for="c in rows" :key="c.client_id" class="px-5 py-3 space-y-2">
44
+ <div class="flex flex-wrap items-center gap-3 text-sm">
45
+ <button type="button" class="flex-1 text-left font-medium text-foreground hover:underline" @click="emit('select-client', c.client_id)">
46
+ {{ c.name }} <span class="text-xs font-normal text-muted-foreground">{{ c.invoicing_mode === 'per_space' ? 'Factura por espacio' : 'Factura consolidada' }}</span>
47
+ </button>
48
+ <span class="text-muted-foreground">MRR {{ formatMoney(c.mrr) }}</span>
49
+ <span>Saldo {{ formatMoney(c.balance) }}</span>
50
+ <span :class="c.overdue > 0 ? 'text-danger font-medium' : 'text-muted-foreground'">Vencido {{ formatMoney(c.overdue) }}</span>
51
+ <App.Tag v-if="c.drafts" :text="`${c.drafts} borrador${c.drafts > 1 ? 'es' : ''}`" severity="info" size="xs" />
52
+ </div>
53
+ <div class="flex flex-wrap gap-2">
54
+ <button v-for="s in c.spaces" :key="s.key" type="button" class="flex items-center gap-1.5 rounded-control border border-card-line px-2 py-1 text-xs hover:bg-muted/50" @click="emit('select-space', s.key)">
55
+ <span class="text-foreground">{{ s.name }}</span>
56
+ <App.Tag :text="s.environment === 'testing' ? 'Pruebas' : 'Prod'" :severity="s.environment === 'testing' ? 'secondary' : 'primary'" size="xs" />
57
+ <App.Tag v-if="s.environment !== 'testing'" :text="s.subscription ? `${s.subscription.plan ?? ''} · ${subscriptionStatus(s.subscription.status).label}` : 'Sin suscripción'"
58
+ :severity="subscriptionStatus(s.subscription?.status).severity" size="xs" />
59
+ </button>
60
+ </div>
61
+ </li>
62
+ </ul>
63
+ </div>
64
+ </div>
65
+ </template>
@@ -0,0 +1,82 @@
1
+ <script setup lang="ts">
2
+ import { CREDIT_NOTE_TARGETS, creditNotePayload, formatMoney, errorMessage, type CreditNoteForm, type Invoice } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.CreditNoteForm — modal to create a credit note (NC-000001) with reason: to an open invoice
6
+ * (amount with VAT), to the client balance (credit for the next invoice) or to the next charge of a
7
+ * space (net amount). With `invoice` it opens fixed on that invoice.
8
+ * Backend: POST {endpoint}/credit-notes; open invoices from GET {endpoint}/reconciliation/open-invoices.
9
+ *
10
+ * <Billing.CreditNoteForm v-model="open" :client-id="client.id" :spaces="spaces" />
11
+ * <Billing.CreditNoteForm v-model="open" :client-id="invoice.client_id" :invoice="invoice" @created="reload" />
12
+ */
13
+ const props = withDefaults(defineProps<{
14
+ endpoint?: string
15
+ clientId: string
16
+ invoice?: Invoice | null
17
+ spaces?: { value: string; label: string }[]
18
+ }>(), { endpoint: 'platform/billing', invoice: null, spaces: () => [] })
19
+ const emit = defineEmits<{ created: [note: any] }>()
20
+ const open = defineModel<boolean>({ default: false })
21
+
22
+ const toast = useToast()
23
+ const billing = useBillingPlatform({ base: props.endpoint })
24
+ const form = reactive<CreditNoteForm>({ target: 'invoice', amount: '', reason: '', invoice_id: '', tenant_key: '' })
25
+ const candidates = ref<Invoice[]>([])
26
+
27
+ watch(open, async (v) => {
28
+ if (!v) return
29
+ Object.assign(form, { target: 'invoice', amount: '', reason: '', invoice_id: props.invoice?.id ?? '', tenant_key: props.spaces[0]?.value ?? '' })
30
+ if (props.invoice) { candidates.value = [props.invoice]; return }
31
+ try {
32
+ candidates.value = await billing.openInvoices({ client_id: props.clientId })
33
+ form.invoice_id = candidates.value[0]?.id ?? ''
34
+ } catch {
35
+ candidates.value = []
36
+ }
37
+ })
38
+
39
+ const targets = computed(() => props.invoice ? CREDIT_NOTE_TARGETS.filter(t => t.value === 'invoice') : CREDIT_NOTE_TARGETS)
40
+ const hint = computed(() => CREDIT_NOTE_TARGETS.find(t => t.value === form.target)?.hint)
41
+
42
+ async function submit() {
43
+ const { payload, error } = creditNotePayload(form, props.clientId)
44
+ if (error) { toast.error(error); return }
45
+ try {
46
+ const note = await billing.createCreditNote.mutateAsync(payload)
47
+ open.value = false
48
+ toast.success(`Nota de crédito ${note?.display_number ?? ''} creada.`)
49
+ emit('created', note)
50
+ } catch (e: any) {
51
+ toast.error(errorMessage(e, 'No se pudo crear la nota de crédito.'))
52
+ }
53
+ }
54
+
55
+ const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
56
+ </script>
57
+
58
+ <template>
59
+ <Modal v-model="open" title="Nota de crédito" size="md" show-footer>
60
+ <div class="space-y-3 text-sm">
61
+ <label class="block space-y-1"><span class="font-medium">Se aplica a</span>
62
+ <select v-model="form.target" :class="inputClass"><option v-for="t in targets" :key="t.value" :value="t.value">{{ t.label }}</option></select>
63
+ <span class="text-xs text-muted-foreground">{{ hint }}</span>
64
+ </label>
65
+ <label v-if="form.target === 'invoice'" class="block space-y-1"><span class="font-medium">Factura</span>
66
+ <select v-model="form.invoice_id" :class="inputClass" :disabled="!!invoice">
67
+ <option v-if="!candidates.length" value="">No hay facturas abiertas</option>
68
+ <option v-for="i in candidates" :key="i.id" :value="i.id">{{ i.display_number }} · saldo {{ formatMoney(i.balance, i.currency) }}</option>
69
+ </select>
70
+ </label>
71
+ <label v-if="form.target === 'next_period'" class="block space-y-1"><span class="font-medium">Espacio</span>
72
+ <select v-model="form.tenant_key" :class="inputClass"><option v-for="s in spaces" :key="s.value" :value="s.value">{{ s.label }}</option></select>
73
+ </label>
74
+ <label class="block space-y-1"><span class="font-medium">Monto ($)</span><input v-model="form.amount" inputmode="numeric" :class="inputClass" /></label>
75
+ <label class="block space-y-1"><span class="font-medium">Motivo</span><input v-model="form.reason" :class="inputClass" maxlength="250" /></label>
76
+ </div>
77
+ <template #footer>
78
+ <App.Button text="Cancelar" size="sm" @click="open = false" />
79
+ <App.Button text="Crear nota de crédito" severity="primary" size="sm" :loading="billing.createCreditNote.isPending.value" @click="submit" />
80
+ </template>
81
+ </Modal>
82
+ </template>
@@ -0,0 +1,394 @@
1
+ <script setup lang="ts">
2
+ import { IconFileInvoice, IconSend, IconDownload, IconCash, IconCheck, IconBan, IconRepeat, IconReceiptRefund, IconPercentage } from '@tabler/icons-vue'
3
+ import {
4
+ formatMoney, invoiceStatus, periodLabel, formatDate, formatDateTime, eventLabel, paymentMethodLabel, parseMoney, errorMessage,
5
+ reissuePayload, BILLING_FIELDS, INVOICE_STATUS_OPTIONS, type Invoice, type CorrectionLine,
6
+ } from '../../composables/useBilling/internal/billing'
7
+
8
+ /*
9
+ * Billing.Invoices — platform invoices: filters, detail (statements and lines per space, bitácora,
10
+ * payments), Emitir (folio optional, email to the billing contact), Reenviar, PDF and Registrar pago
11
+ * (transfer registered by hand; the remainder stays as client credit). Collections: Anular (reason), Refacturar
12
+ * (void + replacement with corrected billing data and correction lines; payments move over), Nota de crédito
13
+ * and Condonar interés por mora; the detail shows credit notes, late fee ranges and the void/reissue trail.
14
+ * Backend: \Innertia\Billing\Routes::platform() + platformWrite().
15
+ *
16
+ * <Billing.Invoices :clients="[{ value: id, label: name }]" />
17
+ * <Billing.Invoices :client-id="client.id" /> (inside a client detail)
18
+ * <Billing.Invoices space-key="rancagua" /> (inside a space detail)
19
+ */
20
+ const props = withDefaults(defineProps<{
21
+ endpoint?: string
22
+ clientId?: string | null
23
+ spaceKey?: string | null
24
+ clients?: { value: string; label: string }[]
25
+ canEdit?: boolean
26
+ }>(), { endpoint: 'platform/billing', clientId: null, spaceKey: null, clients: () => [], canEdit: true })
27
+
28
+ const toast = useToast()
29
+ const billing = useBillingPlatform({ base: props.endpoint })
30
+ const savePdf = useBillingPdf()
31
+
32
+ const filters = reactive({ status: '', client_id: props.clientId ?? '', tenant_key: props.spaceKey ?? '', page: 1 })
33
+ const filterRef = computed(() => ({ ...filters }))
34
+ const query = billing.invoices(filterRef)
35
+ const rows = computed<Invoice[]>(() => (query.data.value as any)?.data ?? [])
36
+ const meta = computed(() => (query.data.value as any)?.meta ?? { total: 0, page: 1, last_page: 1 })
37
+ watch(() => [filters.status, filters.client_id], () => { filters.page = 1 })
38
+
39
+ // ── Detail ────────────────────────────────────────────────────────────────
40
+ const detail = ref<Invoice | null>(null)
41
+ const loadingDetail = ref(false)
42
+ async function openDetail(i: Invoice) {
43
+ detail.value = i
44
+ loadingDetail.value = true
45
+ try {
46
+ detail.value = await billing.invoice(i.id)
47
+ } catch {
48
+ toast.error('No se pudo cargar la factura.')
49
+ } finally {
50
+ loadingDetail.value = false
51
+ }
52
+ }
53
+ const showDetail = computed({ get: () => detail.value !== null, set: (v) => { if (!v) detail.value = null } })
54
+
55
+ // ── Issue ─────────────────────────────────────────────────────────────────
56
+ const issueForm = reactive({ open: false, invoice: null as Invoice | null, folio: '', send: true })
57
+ function openIssue(i: Invoice) {
58
+ Object.assign(issueForm, { open: true, invoice: i, folio: i.folio ?? '', send: true })
59
+ }
60
+ async function submitIssue() {
61
+ if (!issueForm.invoice) return
62
+ try {
63
+ const res = await billing.issue.mutateAsync({ id: issueForm.invoice.id, body: { folio: issueForm.folio || null, send: issueForm.send } })
64
+ issueForm.open = false
65
+ if (detail.value?.id === res.id) detail.value = res
66
+ toast.success(`Factura ${res.display_number} emitida${issueForm.send ? ' y enviada' : ''}.`)
67
+ } catch (e: any) {
68
+ toast.error(errorMessage(e, 'No se pudo emitir la factura.'))
69
+ }
70
+ }
71
+
72
+ async function resend(i: Invoice) {
73
+ try {
74
+ const res = await billing.resend.mutateAsync(i.id)
75
+ res?.sent ? toast.success('Factura reenviada.') : toast.error('El cliente no tiene correo de facturación.')
76
+ } catch (e: any) {
77
+ toast.error(errorMessage(e, 'No se pudo reenviar la factura.'))
78
+ }
79
+ }
80
+
81
+ async function pdf(i: Invoice) {
82
+ try {
83
+ await savePdf(`${billing.base}/invoices/${i.id}/pdf`, `factura-${i.display_number ?? i.id}.pdf`)
84
+ } catch {
85
+ toast.error('No se pudo descargar el PDF.')
86
+ }
87
+ }
88
+
89
+ // ── Payment ───────────────────────────────────────────────────────────────
90
+ const payForm = reactive({ open: false, invoice: null as Invoice | null, amount: '', reference: '', received_at: '', method: 'transfer' })
91
+ function openPay(i: Invoice) {
92
+ Object.assign(payForm, { open: true, invoice: i, amount: String(i.balance), reference: '', received_at: new Date().toISOString().slice(0, 10), method: 'transfer' })
93
+ }
94
+ async function submitPay() {
95
+ const i = payForm.invoice
96
+ const amount = parseMoney(payForm.amount)
97
+ if (!i || !amount || Number.isNaN(amount) || amount <= 0) { toast.error('Ingresa un monto válido.'); return }
98
+ try {
99
+ await billing.registerPayment.mutateAsync({
100
+ client_id: i.client_id, amount, method: payForm.method, reference: payForm.reference || null,
101
+ received_at: payForm.received_at || null, invoice_id: i.id,
102
+ })
103
+ payForm.open = false
104
+ if (detail.value?.id === i.id) await openDetail(i)
105
+ toast.success(amount > i.balance ? 'Pago registrado. El excedente quedó como saldo a favor.' : 'Pago registrado.')
106
+ } catch (e: any) {
107
+ toast.error(errorMessage(e, 'No se pudo registrar el pago.'))
108
+ }
109
+ }
110
+
111
+ // ── Collections: void, reissue, credit note, late fee waiver ─────────────
112
+ const { prompt } = useModal()
113
+ async function reloadDetail(i: Invoice) {
114
+ if (detail.value?.id === i.id) await openDetail(i)
115
+ }
116
+ async function voidInvoice(i: Invoice) {
117
+ const reason = await prompt({
118
+ title: `Anular factura ${i.display_number}`,
119
+ message: 'La factura queda anulada (no se borra). Lo pagado pasa a saldo a favor del cliente. Para corregirla usa Refacturar.',
120
+ required: true, confirmText: 'Anular',
121
+ })
122
+ if (!reason) return
123
+ try {
124
+ detail.value = await billing.voidInvoice.mutateAsync({ id: i.id, reason })
125
+ toast.success('Factura anulada.')
126
+ } catch (e: any) {
127
+ toast.error(errorMessage(e, 'No se pudo anular la factura.'))
128
+ }
129
+ }
130
+
131
+ const reissueForm = reactive({
132
+ open: false, invoice: null as Invoice | null, reason: '', billing_data: {} as Record<string, string>, original: {} as Record<string, string | null>,
133
+ lines: [] as CorrectionLine[], due_at: '', send: true,
134
+ })
135
+ function openReissue(i: Invoice) {
136
+ const data = Object.fromEntries(BILLING_FIELDS.map(f => [f.key, (i.billing_data?.[f.key] ?? '') as string]))
137
+ Object.assign(reissueForm, { open: true, invoice: i, reason: '', billing_data: { ...data }, original: { ...data }, lines: [], due_at: '', send: true })
138
+ }
139
+ async function submitReissue() {
140
+ const i = reissueForm.invoice
141
+ if (!i) return
142
+ const { payload, error } = reissuePayload(reissueForm)
143
+ if (error) { toast.error(error); return }
144
+ try {
145
+ const res = await billing.reissue.mutateAsync({ id: i.id, body: payload! })
146
+ reissueForm.open = false
147
+ detail.value = res
148
+ toast.success(`Factura ${i.display_number} anulada y reemplazada por ${res.display_number}.`)
149
+ } catch (e: any) {
150
+ toast.error(errorMessage(e, 'No se pudo refacturar.'))
151
+ }
152
+ }
153
+
154
+ async function waive(i: Invoice) {
155
+ const reason = await prompt({ title: 'Condonar interés por mora', message: `Factura ${i.display_number}: deja de generar interés y se devuelve el ya cobrado.`, required: true, confirmText: 'Condonar' })
156
+ if (!reason) return
157
+ try {
158
+ const res = await billing.waiveLateFees.mutateAsync({ id: i.id, reason })
159
+ toast.success(`Interés condonado: ${formatMoney(res.removed + res.credited)}.`)
160
+ await reloadDetail(i)
161
+ } catch (e: any) {
162
+ toast.error(errorMessage(e, 'No se pudo condonar el interés.'))
163
+ }
164
+ }
165
+
166
+ const creditNote = reactive({ open: false, invoice: null as Invoice | null })
167
+ const isIssued = (i: Invoice) => ['issued', 'overdue', 'paid'].includes(i.status)
168
+ const hasLateFees = (i: Invoice) => (i.late_fees ?? []).some(f => !f.waived_at) || i.status === 'overdue'
169
+
170
+ const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
171
+ const isOpen = (i: Invoice) => i.status === 'issued' || i.status === 'overdue'
172
+ </script>
173
+
174
+ <template>
175
+ <div class="space-y-4">
176
+ <div class="flex flex-wrap items-end gap-3">
177
+ <label class="space-y-1">
178
+ <span class="text-xs text-muted-foreground">Estado</span>
179
+ <select v-model="filters.status" :class="inputClass">
180
+ <option value="">Todos</option>
181
+ <option v-for="o in INVOICE_STATUS_OPTIONS" :key="o.value" :value="o.value">{{ o.label }}</option>
182
+ </select>
183
+ </label>
184
+ <label v-if="!clientId && clients.length" class="space-y-1">
185
+ <span class="text-xs text-muted-foreground">Cliente</span>
186
+ <select v-model="filters.client_id" :class="inputClass">
187
+ <option value="">Todos</option>
188
+ <option v-for="c in clients" :key="c.value" :value="c.value">{{ c.label }}</option>
189
+ </select>
190
+ </label>
191
+ <span class="flex-1" />
192
+ <span class="text-xs text-muted-foreground">{{ meta.total }} facturas</span>
193
+ </div>
194
+
195
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
196
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
197
+ <div v-else-if="query.isError.value" class="p-8 text-center text-sm text-muted-foreground">
198
+ No se pudieron cargar las facturas.
199
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
200
+ </div>
201
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">
202
+ <IconFileInvoice class="size-6 mx-auto mb-2" :stroke-width="1.5" />
203
+ No hay facturas. Se generan en borrador al cerrar cada período.
204
+ </div>
205
+ <table v-else class="w-full text-sm">
206
+ <thead class="text-xs uppercase text-muted-foreground">
207
+ <tr class="border-b border-card-line">
208
+ <th class="text-left font-medium px-4 py-2">Factura</th>
209
+ <th class="text-left font-medium px-4 py-2">Cliente / espacio</th>
210
+ <th class="text-left font-medium px-4 py-2">Período</th>
211
+ <th class="text-right font-medium px-4 py-2">Total</th>
212
+ <th class="text-right font-medium px-4 py-2">Saldo</th>
213
+ <th class="text-left font-medium px-4 py-2">Vence</th>
214
+ <th class="px-4 py-2" />
215
+ </tr>
216
+ </thead>
217
+ <tbody class="divide-y divide-card-line">
218
+ <tr v-for="i in rows" :key="i.id" class="hover:bg-muted/40">
219
+ <td class="px-4 py-2">
220
+ <button type="button" class="font-medium text-foreground hover:underline" @click="openDetail(i)">{{ i.display_number ?? 'Borrador' }}</button>
221
+ <App.Tag :text="invoiceStatus(i.status).label" :severity="invoiceStatus(i.status).severity" size="xs" class="ml-2" />
222
+ <p v-if="i.folio" class="text-xs text-muted-foreground">Folio {{ i.folio }}</p>
223
+ </td>
224
+ <td class="px-4 py-2">
225
+ <p class="text-foreground">{{ i.client_name }}</p>
226
+ <p class="text-xs text-muted-foreground">{{ i.consolidated ? 'Consolidada' : i.tenant_name }}</p>
227
+ </td>
228
+ <td class="px-4 py-2 text-muted-foreground">{{ periodLabel(i.period_start, i.period_end) }}</td>
229
+ <td class="px-4 py-2 text-right">{{ formatMoney(i.total, i.currency) }}</td>
230
+ <td class="px-4 py-2 text-right" :class="i.status === 'overdue' ? 'text-danger font-medium' : ''">{{ formatMoney(i.balance, i.currency) }}</td>
231
+ <td class="px-4 py-2 text-muted-foreground">{{ formatDateTime(i.due_at) }}</td>
232
+ <td class="px-4 py-2">
233
+ <div class="flex justify-end gap-1">
234
+ <App.Button v-if="canEdit && i.status === 'draft'" text="Emitir" size="xs" severity="primary" :icon="IconCheck" @click="openIssue(i)" />
235
+ <App.Button v-if="canEdit && isOpen(i)" text="Registrar pago" size="xs" :icon="IconCash" @click="openPay(i)" />
236
+ <App.Button text="PDF" size="xs" outline :icon="IconDownload" @click="pdf(i)" />
237
+ </div>
238
+ </td>
239
+ </tr>
240
+ </tbody>
241
+ </table>
242
+ </div>
243
+
244
+ <div v-if="meta.last_page > 1" class="flex items-center justify-end gap-2 text-sm">
245
+ <App.Button text="Anterior" size="xs" :disabled="filters.page <= 1" @click="filters.page--" />
246
+ <span class="text-muted-foreground">Página {{ meta.page }} de {{ meta.last_page }}</span>
247
+ <App.Button text="Siguiente" size="xs" :disabled="filters.page >= meta.last_page" @click="filters.page++" />
248
+ </div>
249
+
250
+ <!-- Detail -->
251
+ <Modal v-model="showDetail" :title="detail ? `Factura ${detail.display_number ?? '(borrador)'}` : ''" size="3xl" show-footer>
252
+ <div v-if="detail" class="space-y-4 text-sm">
253
+ <div class="flex flex-wrap gap-2 items-center">
254
+ <App.Tag :text="invoiceStatus(detail.status).label" :severity="invoiceStatus(detail.status).severity" size="xs" />
255
+ <span class="text-muted-foreground">{{ detail.client_name }} · {{ detail.consolidated ? 'Factura consolidada' : detail.tenant_name }} · {{ paymentMethodLabel(detail.payment_method) }}</span>
256
+ </div>
257
+ <div class="grid gap-2 sm:grid-cols-4">
258
+ <div><p class="text-xs text-muted-foreground">Subtotal</p><p>{{ formatMoney(detail.subtotal, detail.currency) }}</p></div>
259
+ <div><p class="text-xs text-muted-foreground">IVA</p><p>{{ formatMoney(detail.tax, detail.currency) }}</p></div>
260
+ <div><p class="text-xs text-muted-foreground">Total</p><p class="font-medium">{{ formatMoney(detail.total, detail.currency) }}</p></div>
261
+ <div><p class="text-xs text-muted-foreground">Saldo</p><p class="font-medium">{{ formatMoney(detail.balance, detail.currency) }}</p></div>
262
+ </div>
263
+ <p v-if="detail.payment_link" class="text-xs">Enlace de pago: <a :href="detail.payment_link" target="_blank" rel="noopener" class="text-primary hover:underline break-all">{{ detail.payment_link }}</a></p>
264
+
265
+ <p v-if="detail.status === 'void'" class="text-xs text-danger">Anulada {{ formatDateTime(detail.voided_at) }}<template v-if="detail.void_reason"> · {{ detail.void_reason }}</template></p>
266
+ <p v-if="detail.replaces_invoice_id" class="text-xs text-muted-foreground">Reemplaza a una factura anulada (refacturación).</p>
267
+ <p v-if="detail.late_fees_waived_at" class="text-xs text-muted-foreground">Interés por mora condonado {{ formatDateTime(detail.late_fees_waived_at) }}.</p>
268
+
269
+ <div v-if="loadingDetail" class="text-muted-foreground">Cargando detalle…</div>
270
+ <template v-else>
271
+ <div v-for="s in detail.statements ?? []" :key="s.id" class="border border-card-line rounded-control">
272
+ <p class="px-3 py-2 bg-muted/40 text-xs font-medium">{{ s.tenant_name ?? s.tenant_id }} · {{ periodLabel(s.period_start, s.period_end) }}</p>
273
+ <table class="w-full">
274
+ <tbody class="divide-y divide-card-line">
275
+ <tr v-for="(l, idx) in s.lines" :key="idx">
276
+ <td class="px-3 py-1.5">{{ l.description }}</td>
277
+ <td class="px-3 py-1.5 text-right text-muted-foreground">{{ l.quantity }}</td>
278
+ <td class="px-3 py-1.5 text-right text-muted-foreground">{{ l.unit_price ? formatMoney(l.unit_price, detail.currency) : '' }}</td>
279
+ <td class="px-3 py-1.5 text-right">{{ formatMoney(l.amount, detail.currency) }}</td>
280
+ </tr>
281
+ </tbody>
282
+ </table>
283
+ </div>
284
+
285
+ <div v-if="detail.credit_notes?.length">
286
+ <p class="text-xs font-medium text-muted-foreground mb-1">Notas de crédito</p>
287
+ <ul class="space-y-1 text-xs">
288
+ <li v-for="n in detail.credit_notes" :key="n.id">{{ n.display_number }} · {{ formatMoney(n.amount ?? 0, detail.currency) }} · {{ n.reason }}</li>
289
+ </ul>
290
+ </div>
291
+ <div v-if="detail.late_fees?.length">
292
+ <p class="text-xs font-medium text-muted-foreground mb-1">Interés por mora generado</p>
293
+ <ul class="space-y-1 text-xs">
294
+ <li v-for="(f, idx) in detail.late_fees" :key="idx" :class="f.waived_at ? 'line-through text-muted-foreground' : ''">
295
+ {{ formatDate(f.from) }} al {{ formatDate(f.to) }} · {{ f.days }} días sobre {{ formatMoney(f.base, detail.currency) }} · {{ formatMoney(f.amount, detail.currency) }}
296
+ </li>
297
+ </ul>
298
+ </div>
299
+
300
+ <div v-if="detail.events?.length">
301
+ <p class="text-xs font-medium text-muted-foreground mb-1">Bitácora</p>
302
+ <ul class="space-y-1">
303
+ <li v-for="(e, idx) in detail.events" :key="idx" class="text-xs text-muted-foreground">
304
+ {{ formatDateTime(e.created_at) }} · {{ eventLabel(e.event) }}<template v-if="e.data?.amount"> · {{ formatMoney(e.data.amount, detail.currency) }}</template><template v-if="e.data?.reason"> · {{ e.data.reason }}</template>
305
+ <template v-if="e.event === 'reissued' && e.data?.totals"> · total {{ formatMoney(e.data.totals.before.total, detail.currency) }} → {{ formatMoney(e.data.totals.after.total, detail.currency) }}</template>
306
+ <template v-if="e.event === 'reissued' && e.data?.billing_data && Object.keys(e.data.billing_data).length"> · cambió {{ Object.keys(e.data.billing_data).join(', ') }}</template>
307
+ </li>
308
+ </ul>
309
+ </div>
310
+ </template>
311
+ </div>
312
+ <template #footer>
313
+ <template v-if="detail">
314
+ <App.Button v-if="canEdit && detail.status === 'draft'" text="Emitir" size="sm" severity="primary" :icon="IconCheck" @click="openIssue(detail)" />
315
+ <App.Button v-if="canEdit && detail.status !== 'draft' && detail.status !== 'void'" text="Reenviar" size="sm" :icon="IconSend" :loading="billing.resend.isPending.value" @click="resend(detail)" />
316
+ <App.Button v-if="canEdit && isOpen(detail)" text="Registrar pago" size="sm" :icon="IconCash" @click="openPay(detail)" />
317
+ <App.Button v-if="canEdit && isOpen(detail)" text="Nota de crédito" size="sm" :icon="IconReceiptRefund" @click="creditNote.invoice = detail; creditNote.open = true" />
318
+ <App.Button v-if="canEdit && isIssued(detail) && hasLateFees(detail) && !detail.late_fees_waived_at" text="Condonar interés" size="sm" :icon="IconPercentage" :loading="billing.waiveLateFees.isPending.value" @click="waive(detail)" />
319
+ <App.Button v-if="canEdit && isIssued(detail)" text="Refacturar" size="sm" :icon="IconRepeat" @click="openReissue(detail)" />
320
+ <App.Button v-if="canEdit && isIssued(detail)" text="Anular" size="sm" outline :icon="IconBan" :loading="billing.voidInvoice.isPending.value" @click="voidInvoice(detail)" />
321
+ <App.Button text="PDF" size="sm" outline :icon="IconDownload" @click="pdf(detail)" />
322
+ </template>
323
+ <App.Button text="Cerrar" size="sm" @click="detail = null" />
324
+ </template>
325
+ </Modal>
326
+
327
+ <!-- Issue -->
328
+ <Modal v-model="issueForm.open" title="Emitir factura" size="md" show-footer>
329
+ <div v-if="issueForm.invoice" class="space-y-3 text-sm">
330
+ <p>Se asigna el número correlativo, vence según el plazo del cliente y se envía al correo de facturación con el PDF adjunto. Total {{ formatMoney(issueForm.invoice.total, issueForm.invoice.currency) }}.</p>
331
+ <label class="block space-y-1"><span class="font-medium">Folio SII (opcional)</span><input v-model="issueForm.folio" :class="inputClass" maxlength="40" /></label>
332
+ <label class="flex items-center gap-2"><input v-model="issueForm.send" type="checkbox" class="rounded" /> Enviar por correo y avisar a los administradores del espacio</label>
333
+ </div>
334
+ <template #footer>
335
+ <App.Button text="Cancelar" size="sm" @click="issueForm.open = false" />
336
+ <App.Button text="Emitir" severity="primary" size="sm" :loading="billing.issue.isPending.value" @click="submitIssue" />
337
+ </template>
338
+ </Modal>
339
+
340
+ <!-- Reissue -->
341
+ <Modal v-model="reissueForm.open" :title="reissueForm.invoice ? `Refacturar ${reissueForm.invoice.display_number}` : ''" size="2xl" show-footer>
342
+ <div v-if="reissueForm.invoice" class="space-y-3 text-sm">
343
+ <p class="text-muted-foreground">La factura se anula y se emite otra con número nuevo. Los pagos aplicados pasan a la nueva y todo queda en la bitácora.</p>
344
+ <label class="block space-y-1"><span class="font-medium">Motivo (obligatorio)</span><input v-model="reissueForm.reason" :class="inputClass" maxlength="250" /></label>
345
+ <p class="font-medium">Datos de facturación</p>
346
+ <div class="grid gap-3 sm:grid-cols-2">
347
+ <label v-for="f in BILLING_FIELDS" :key="f.key" class="block space-y-1"><span class="text-xs text-muted-foreground">{{ f.label }}</span>
348
+ <input v-model="reissueForm.billing_data[f.key]" :class="inputClass" maxlength="250" />
349
+ </label>
350
+ </div>
351
+ <div class="space-y-2">
352
+ <div class="flex items-center"><p class="font-medium flex-1">Correcciones (monto neto, negativo para rebajar)</p>
353
+ <App.Button text="Agregar línea" size="xs" @click="reissueForm.lines.push({ description: '', amount: '' })" />
354
+ </div>
355
+ <div v-for="(l, idx) in reissueForm.lines" :key="idx" class="flex gap-2">
356
+ <input v-model="l.description" :class="inputClass" placeholder="Descripción" maxlength="200" />
357
+ <input v-model="l.amount" :class="inputClass" class="max-w-40" inputmode="numeric" placeholder="-10000" />
358
+ <App.Button text="Quitar" size="xs" outline @click="reissueForm.lines.splice(idx, 1)" />
359
+ </div>
360
+ </div>
361
+ <div class="grid gap-3 sm:grid-cols-2">
362
+ <label class="block space-y-1"><span class="font-medium">Nuevo vencimiento (opcional)</span><input v-model="reissueForm.due_at" type="date" :class="inputClass" />
363
+ <span class="text-xs text-muted-foreground">Vacío = mantiene el vencimiento original.</span>
364
+ </label>
365
+ <label class="flex items-center gap-2 self-center"><input v-model="reissueForm.send" type="checkbox" class="rounded" /> Enviar la nueva factura por correo</label>
366
+ </div>
367
+ </div>
368
+ <template #footer>
369
+ <App.Button text="Cancelar" size="sm" @click="reissueForm.open = false" />
370
+ <App.Button text="Anular y reemitir" severity="primary" size="sm" :loading="billing.reissue.isPending.value" @click="submitReissue" />
371
+ </template>
372
+ </Modal>
373
+
374
+ <Billing.CreditNoteForm v-if="creditNote.invoice" v-model="creditNote.open" :endpoint="endpoint" :client-id="creditNote.invoice.client_id" :invoice="creditNote.invoice"
375
+ @created="detail && openDetail(detail)" />
376
+
377
+ <!-- Payment -->
378
+ <Modal v-model="payForm.open" title="Registrar pago" size="md" show-footer>
379
+ <div v-if="payForm.invoice" class="space-y-3 text-sm">
380
+ <p class="text-muted-foreground">Factura {{ payForm.invoice.display_number }} · saldo {{ formatMoney(payForm.invoice.balance, payForm.invoice.currency) }}</p>
381
+ <label class="block space-y-1"><span class="font-medium">Monto ($)</span><input v-model="payForm.amount" inputmode="numeric" :class="inputClass" /></label>
382
+ <label class="block space-y-1"><span class="font-medium">Medio</span>
383
+ <select v-model="payForm.method" :class="inputClass"><option value="transfer">Transferencia</option><option value="manual">Otro (manual)</option></select>
384
+ </label>
385
+ <label class="block space-y-1"><span class="font-medium">Fecha de recepción</span><input v-model="payForm.received_at" type="date" :class="inputClass" /></label>
386
+ <label class="block space-y-1"><span class="font-medium">Referencia</span><input v-model="payForm.reference" :class="inputClass" maxlength="120" placeholder="N° de operación" /></label>
387
+ </div>
388
+ <template #footer>
389
+ <App.Button text="Cancelar" size="sm" @click="payForm.open = false" />
390
+ <App.Button text="Registrar" severity="primary" size="sm" :loading="billing.registerPayment.isPending.value" @click="submitPay" />
391
+ </template>
392
+ </Modal>
393
+ </div>
394
+ </template>