@innertia-solutions/innertia-nuxt 0.1.92 → 0.1.94

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.
@@ -1,14 +1,16 @@
1
1
  <script setup lang="ts">
2
- import { IconFileInvoice, IconSend, IconDownload, IconCash, IconCheck } from '@tabler/icons-vue'
2
+ import { IconFileInvoice, IconSend, IconDownload, IconCash, IconCheck, IconBan, IconRepeat, IconReceiptRefund, IconPercentage } from '@tabler/icons-vue'
3
3
  import {
4
- formatMoney, invoiceStatus, periodLabel, formatDateTime, eventLabel, paymentMethodLabel, parseMoney, errorMessage,
5
- INVOICE_STATUS_OPTIONS, type Invoice,
4
+ formatMoney, invoiceStatus, periodLabel, formatDate, formatDateTime, eventLabel, paymentMethodLabel, parseMoney, errorMessage,
5
+ reissuePayload, BILLING_FIELDS, INVOICE_STATUS_OPTIONS, type Invoice, type CorrectionLine,
6
6
  } from '../../composables/useBilling/internal/billing'
7
7
 
8
8
  /*
9
9
  * Billing.Invoices — platform invoices: filters, detail (statements and lines per space, bitácora,
10
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).
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.
12
14
  * Backend: \Innertia\Billing\Routes::platform() + platformWrite().
13
15
  *
14
16
  * <Billing.Invoices :clients="[{ value: id, label: name }]" />
@@ -106,6 +108,65 @@ async function submitPay() {
106
108
  }
107
109
  }
108
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
+
109
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'
110
171
  const isOpen = (i: Invoice) => i.status === 'issued' || i.status === 'overdue'
111
172
  </script>
@@ -201,6 +262,10 @@ const isOpen = (i: Invoice) => i.status === 'issued' || i.status === 'overdue'
201
262
  </div>
202
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>
203
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
+
204
269
  <div v-if="loadingDetail" class="text-muted-foreground">Cargando detalle…</div>
205
270
  <template v-else>
206
271
  <div v-for="s in detail.statements ?? []" :key="s.id" class="border border-card-line rounded-control">
@@ -217,11 +282,28 @@ const isOpen = (i: Invoice) => i.status === 'issued' || i.status === 'overdue'
217
282
  </table>
218
283
  </div>
219
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
+
220
300
  <div v-if="detail.events?.length">
221
301
  <p class="text-xs font-medium text-muted-foreground mb-1">Bitácora</p>
222
302
  <ul class="space-y-1">
223
303
  <li v-for="(e, idx) in detail.events" :key="idx" class="text-xs text-muted-foreground">
224
- {{ formatDateTime(e.created_at) }} · {{ eventLabel(e.event) }}<template v-if="e.data?.amount"> · {{ formatMoney(e.data.amount, detail.currency) }}</template>
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>
225
307
  </li>
226
308
  </ul>
227
309
  </div>
@@ -232,6 +314,10 @@ const isOpen = (i: Invoice) => i.status === 'issued' || i.status === 'overdue'
232
314
  <App.Button v-if="canEdit && detail.status === 'draft'" text="Emitir" size="sm" severity="primary" :icon="IconCheck" @click="openIssue(detail)" />
233
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)" />
234
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)" />
235
321
  <App.Button text="PDF" size="sm" outline :icon="IconDownload" @click="pdf(detail)" />
236
322
  </template>
237
323
  <App.Button text="Cerrar" size="sm" @click="detail = null" />
@@ -251,6 +337,43 @@ const isOpen = (i: Invoice) => i.status === 'issued' || i.status === 'overdue'
251
337
  </template>
252
338
  </Modal>
253
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
+
254
377
  <!-- Payment -->
255
378
  <Modal v-model="payForm.open" title="Registrar pago" size="md" show-footer>
256
379
  <div v-if="payForm.invoice" class="space-y-3 text-sm">
@@ -9,12 +9,13 @@ import {
9
9
  * Billing.Overview — "Facturación" of the backoffice (permission billing.view), read-only: plan and
10
10
  * status, consumption of the current period vs included with the estimate, invoices (PDF, due date,
11
11
  * "Pagar" when there is a payment link; in consolidated invoices, this space's part) and payments.
12
+ * With `show-account` (default) it ends with the space's account statement (charges, credits, aging).
12
13
  * Testing spaces only show the "Espacio de pruebas" strip.
13
14
  * Backend: \Innertia\Billing\Routes::backoffice() → GET {endpoint}/overview|invoices|payments.
14
15
  *
15
16
  * <Billing.Overview />
16
17
  */
17
- const props = withDefaults(defineProps<{ endpoint?: string }>(), { endpoint: 'billing' })
18
+ const props = withDefaults(defineProps<{ endpoint?: string; showAccount?: boolean }>(), { endpoint: 'billing', showAccount: true })
18
19
 
19
20
  const toast = useToast()
20
21
  const { base, overview, invoices, payments } = useBillingSpace({ base: props.endpoint })
@@ -119,6 +120,11 @@ async function pdf(i: Invoice) {
119
120
  </li>
120
121
  </ul>
121
122
  </div>
123
+
124
+ <div v-if="showAccount && data.subscription" class="space-y-2">
125
+ <p class="text-sm font-medium text-foreground">Estado de cuenta</p>
126
+ <Billing.AccountStatement mode="space" :endpoint="endpoint" />
127
+ </div>
122
128
  </template>
123
129
  </div>
124
130
  </template>
@@ -0,0 +1,309 @@
1
+ <script setup lang="ts">
2
+ import { IconUpload, IconRefresh, IconCheck, IconX, IconArrowBackUp, IconLink } from '@tabler/icons-vue'
3
+ import {
4
+ BANK_FIELDS, mappingError, transactionStatus, importStatus, matchReasonLabel, scoreSeverity, allocationPreview,
5
+ formatMoney, formatDate, formatDateTime, errorMessage, type BankTransaction, type Invoice, type Suggestion,
6
+ } from '../../composables/useBilling/internal/billing'
7
+
8
+ /*
9
+ * Billing.Reconciliation — conciliación de pagos: import a bank statement (CSV/XLSX) choosing its columns
10
+ * (preview + suggested mapping), the import runs on the queue and applies the conclusive movements alone;
11
+ * the rest show suggestions (score and reasons) to apply with one click, or are matched by hand (client +
12
+ * open invoices in order: partial payments, several invoices, the rest as client credit). Matches can be
13
+ * undone; movements that are not payments are discarded. Importing the same statement never duplicates.
14
+ * Backend: {endpoint}/reconciliation/* (preview, imports, transactions, open-invoices, match, unmatch, ignore,
15
+ * restore, rematch).
16
+ *
17
+ * <Billing.Reconciliation :can-edit="isOwner" />
18
+ */
19
+ const props = withDefaults(defineProps<{ endpoint?: string; canEdit?: boolean }>(), { endpoint: 'platform/billing', canEdit: true })
20
+
21
+ const toast = useToast()
22
+ const { prompt } = useModal()
23
+ const billing = useBillingPlatform({ base: props.endpoint })
24
+
25
+ // ── Import wizard ────────────────────────────────────────────────────────
26
+ const wizard = reactive({
27
+ open: false, file: null as File | null, loading: false, headerRow: null as number | null,
28
+ headers: [] as string[], rows: [] as string[][], mapping: {} as Record<string, string>, bank: '',
29
+ })
30
+ function openWizard() {
31
+ Object.assign(wizard, { open: true, file: null, loading: false, headerRow: null, headers: [], rows: [], mapping: {}, bank: '' })
32
+ }
33
+ async function pick(event: Event) {
34
+ const file = (event.target as HTMLInputElement).files?.[0]
35
+ if (!file) return
36
+ wizard.file = file
37
+ await loadPreview()
38
+ }
39
+ async function loadPreview() {
40
+ if (!wizard.file) return
41
+ wizard.loading = true
42
+ try {
43
+ const res = await billing.preview(wizard.file, wizard.headerRow)
44
+ wizard.headerRow = res.header_row
45
+ wizard.headers = res.headers ?? []
46
+ wizard.rows = res.rows ?? []
47
+ const last = res.last_mapping ?? {}
48
+ const fits = Object.values(last).every((h: any) => wizard.headers.includes(h))
49
+ wizard.mapping = { ...(Object.keys(last).length && fits ? last : res.mapping) }
50
+ } catch (e: any) {
51
+ toast.error(errorMessage(e, 'No se pudo leer el archivo.'))
52
+ } finally {
53
+ wizard.loading = false
54
+ }
55
+ }
56
+ const wizardError = computed(() => wizard.file ? mappingError(wizard.mapping) : 'Elige el archivo de la cartola.')
57
+ async function submitImport() {
58
+ if (wizardError.value || !wizard.file) { toast.error(wizardError.value ?? ''); return }
59
+ try {
60
+ const res = await billing.importStatement.mutateAsync({ file: wizard.file, mapping: wizard.mapping, bank: wizard.bank, headerRow: wizard.headerRow })
61
+ wizard.open = false
62
+ toast.success(res?.duplicate ? 'Esta cartola ya estaba importada: no se duplicó nada.' : 'Cartola en proceso. Los movimientos claros se concilian solos.')
63
+ } catch (e: any) {
64
+ toast.error(errorMessage(e, 'No se pudo importar la cartola.'))
65
+ }
66
+ }
67
+
68
+ // ── Movements ────────────────────────────────────────────────────────────
69
+ const filters = reactive({ status: 'open', import_id: '', page: 1 })
70
+ const query = billing.transactions(computed(() => ({ ...filters })))
71
+ const rows = computed<BankTransaction[]>(() => (query.data.value as any)?.data ?? [])
72
+ const meta = computed(() => (query.data.value as any)?.meta ?? { total: 0, page: 1, last_page: 1 })
73
+ const summary = computed(() => (query.data.value as any)?.summary ?? { open: 0, open_amount: 0 })
74
+ const importsList = computed<any[]>(() => (billing.imports.data.value as any[] | undefined) ?? [])
75
+ watch(() => [filters.status, filters.import_id], () => { filters.page = 1 })
76
+ // Refresh the movements when a running import finishes.
77
+ watch(() => importsList.value.map(i => i.status).join(), () => query.refetch())
78
+
79
+ async function applySuggestion(t: BankTransaction, s: Suggestion) {
80
+ await doMatch(t, s.client_id, s.invoice_ids)
81
+ }
82
+ async function doMatch(t: BankTransaction, clientId: string, invoiceIds: string[]) {
83
+ try {
84
+ await billing.match.mutateAsync({ id: t.id, clientId, invoiceIds })
85
+ manual.open = false
86
+ toast.success('Movimiento conciliado.')
87
+ } catch (e: any) {
88
+ toast.error(errorMessage(e, 'No se pudo conciliar.'))
89
+ }
90
+ }
91
+ async function unmatch(t: BankTransaction) {
92
+ const reason = await prompt({ title: 'Deshacer conciliación', message: 'Se elimina el pago y las facturas vuelven a quedar pendientes. Indica el motivo.', required: true, confirmText: 'Deshacer' })
93
+ if (!reason) return
94
+ try {
95
+ await billing.unmatch.mutateAsync({ id: t.id, reason })
96
+ toast.success('Conciliación deshecha.')
97
+ } catch (e: any) {
98
+ toast.error(errorMessage(e, 'No se pudo deshacer.'))
99
+ }
100
+ }
101
+ async function ignore(t: BankTransaction) {
102
+ const reason = await prompt({ title: 'Descartar movimiento', message: 'Para abonos que no son pagos de clientes (intereses, traspasos).', placeholder: 'Motivo (opcional)', confirmText: 'Descartar' })
103
+ if (reason === null) return
104
+ try {
105
+ await billing.ignore.mutateAsync({ id: t.id, reason })
106
+ } catch (e: any) {
107
+ toast.error(errorMessage(e, 'No se pudo descartar.'))
108
+ }
109
+ }
110
+ async function restore(t: BankTransaction) {
111
+ try { await billing.restore.mutateAsync(t.id) } catch (e: any) { toast.error(errorMessage(e, 'No se pudo restaurar.')) }
112
+ }
113
+ async function rematch() {
114
+ try {
115
+ const res = await billing.rematch.mutateAsync(null)
116
+ toast.success(`Revisado: ${res.matched} conciliados, ${res.suggested} con sugerencia.`)
117
+ } catch (e: any) {
118
+ toast.error(errorMessage(e, 'No se pudo revisar.'))
119
+ }
120
+ }
121
+
122
+ // ── Manual match ─────────────────────────────────────────────────────────
123
+ const manual = reactive({ open: false, tx: null as BankTransaction | null, search: '', invoices: [] as Invoice[], selected: [] as string[], loading: false })
124
+ const manualClient = computed(() => {
125
+ const first = manual.invoices.find(i => i.id === manual.selected[0])
126
+ return first?.client_id ?? null
127
+ })
128
+ const preview = computed(() => manual.tx ? allocationPreview(manual.tx.amount, manual.invoices, manual.selected) : { rows: [], credit: 0 })
129
+ const appliedTo = (id: string): number | null => preview.value.rows.find(r => r.id === id)?.applied ?? null
130
+ async function openManual(t: BankTransaction) {
131
+ Object.assign(manual, { open: true, tx: t, search: t.suggestions[0]?.client_name ?? '', invoices: [], selected: [] })
132
+ await searchInvoices()
133
+ }
134
+ async function searchInvoices() {
135
+ manual.loading = true
136
+ try {
137
+ const suggested = manual.tx?.suggestions[0]
138
+ manual.invoices = await billing.openInvoices(manual.search ? { q: manual.search } : { client_id: suggested?.client_id ?? null })
139
+ } catch {
140
+ manual.invoices = []
141
+ } finally {
142
+ manual.loading = false
143
+ }
144
+ }
145
+ function toggle(i: Invoice) {
146
+ if (manual.selected.includes(i.id)) {
147
+ manual.selected = manual.selected.filter(id => id !== i.id)
148
+ } else if (!manualClient.value || i.client_id === manualClient.value) {
149
+ manual.selected = [...manual.selected, i.id]
150
+ } else {
151
+ toast.error('Un pago se aplica a facturas de un solo cliente.')
152
+ }
153
+ }
154
+ async function submitManual() {
155
+ if (!manual.tx || !manualClient.value) { toast.error('Elige al menos una factura.'); return }
156
+ await doMatch(manual.tx, manualClient.value, manual.selected)
157
+ }
158
+
159
+ const inputClass = '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'
160
+ </script>
161
+
162
+ <template>
163
+ <div class="space-y-4">
164
+ <div class="flex flex-wrap items-end gap-3 text-sm">
165
+ <label class="space-y-1"><span class="block text-xs text-muted-foreground">Movimientos</span>
166
+ <select v-model="filters.status" :class="inputClass">
167
+ <option value="open">Pendientes</option>
168
+ <option value="suggested">Con sugerencia</option>
169
+ <option value="unmatched">Sin emparejar</option>
170
+ <option value="matched">Conciliados</option>
171
+ <option value="ignored">Descartados</option>
172
+ <option value="">Todos</option>
173
+ </select>
174
+ </label>
175
+ <label class="space-y-1"><span class="block text-xs text-muted-foreground">Cartola</span>
176
+ <select v-model="filters.import_id" :class="inputClass">
177
+ <option value="">Todas</option>
178
+ <option v-for="i in importsList" :key="i.id" :value="i.id">{{ i.file_name }} · {{ formatDateTime(i.created_at) }}</option>
179
+ </select>
180
+ </label>
181
+ <span class="flex-1 text-xs text-muted-foreground">{{ summary.open }} pendientes · {{ formatMoney(summary.open_amount) }}</span>
182
+ <App.Button v-if="canEdit" text="Revisar de nuevo" size="sm" outline :icon="IconRefresh" :loading="billing.rematch.isPending.value" @click="rematch" />
183
+ <App.Button v-if="canEdit" text="Importar cartola" size="sm" severity="primary" :icon="IconUpload" @click="openWizard" />
184
+ </div>
185
+
186
+ <div v-if="importsList.some(i => i.status === 'pending' || i.status === 'processing' || i.status === 'failed')" class="space-y-1">
187
+ <p v-for="i in importsList.filter(x => x.status !== 'done').slice(0, 3)" :key="i.id" class="text-xs">
188
+ <App.Tag :text="importStatus(i.status).label" :severity="importStatus(i.status).severity" size="xs" /> {{ i.file_name }}
189
+ <span v-if="i.error" class="text-danger"> · {{ i.error }}</span>
190
+ </p>
191
+ </div>
192
+
193
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
194
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
195
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">No hay movimientos {{ filters.status === 'open' ? 'pendientes' : '' }}.</div>
196
+ <table v-else class="w-full text-sm">
197
+ <thead class="text-xs uppercase text-muted-foreground">
198
+ <tr class="border-b border-card-line">
199
+ <th class="text-left font-medium px-4 py-2">Fecha</th>
200
+ <th class="text-left font-medium px-4 py-2">Movimiento</th>
201
+ <th class="text-right font-medium px-4 py-2">Monto</th>
202
+ <th class="text-left font-medium px-4 py-2">Conciliación</th>
203
+ <th class="px-4 py-2" />
204
+ </tr>
205
+ </thead>
206
+ <tbody class="divide-y divide-card-line">
207
+ <tr v-for="t in rows" :key="t.id" class="align-top">
208
+ <td class="px-4 py-2 whitespace-nowrap text-muted-foreground">{{ formatDate(t.posted_at) }}</td>
209
+ <td class="px-4 py-2">
210
+ <p class="text-foreground">{{ t.description || '—' }}</p>
211
+ <p class="text-xs text-muted-foreground">{{ [t.reference, t.tax_id, t.counterpart_name].filter(Boolean).join(' · ') }}</p>
212
+ </td>
213
+ <td class="px-4 py-2 text-right font-medium whitespace-nowrap">{{ formatMoney(t.amount) }}</td>
214
+ <td class="px-4 py-2">
215
+ <App.Tag :text="transactionStatus(t.status).label" :severity="transactionStatus(t.status).severity" size="xs" />
216
+ <p v-if="t.status === 'matched'" class="text-xs text-muted-foreground mt-1">{{ t.client_name }} · {{ t.matched_by === 'auto' ? 'automática' : 'manual' }} · {{ formatDateTime(t.matched_at) }}</p>
217
+ <p v-if="t.status === 'ignored' && t.ignore_reason" class="text-xs text-muted-foreground mt-1">{{ t.ignore_reason }}</p>
218
+ <ul v-if="t.status === 'suggested'" class="mt-1 space-y-1">
219
+ <li v-for="(s, idx) in t.suggestions" :key="idx" class="flex flex-wrap items-center gap-1 text-xs">
220
+ <App.Tag :text="`${s.score}`" :severity="scoreSeverity(s.score)" size="xs" />
221
+ <span class="text-foreground">{{ s.client_name }}</span>
222
+ <span class="text-muted-foreground">{{ s.invoices.join(', ') }} · {{ s.reasons.map(matchReasonLabel).join(', ') }}</span>
223
+ <button v-if="canEdit" type="button" class="text-primary hover:underline" @click="applySuggestion(t, s)">Aplicar</button>
224
+ </li>
225
+ </ul>
226
+ </td>
227
+ <td class="px-4 py-2">
228
+ <div v-if="canEdit" class="flex justify-end gap-1">
229
+ <App.Button v-if="t.status === 'unmatched' || t.status === 'suggested'" text="Emparejar" size="xs" :icon="IconLink" @click="openManual(t)" />
230
+ <App.Button v-if="t.status === 'unmatched' || t.status === 'suggested'" text="Descartar" size="xs" outline :icon="IconX" @click="ignore(t)" />
231
+ <App.Button v-if="t.status === 'matched'" text="Deshacer" size="xs" outline :icon="IconArrowBackUp" @click="unmatch(t)" />
232
+ <App.Button v-if="t.status === 'ignored'" text="Restaurar" size="xs" outline @click="restore(t)" />
233
+ </div>
234
+ </td>
235
+ </tr>
236
+ </tbody>
237
+ </table>
238
+ </div>
239
+
240
+ <div v-if="meta.last_page > 1" class="flex items-center justify-end gap-2 text-sm">
241
+ <App.Button text="Anterior" size="xs" :disabled="filters.page <= 1" @click="filters.page--" />
242
+ <span class="text-muted-foreground">Página {{ meta.page }} de {{ meta.last_page }}</span>
243
+ <App.Button text="Siguiente" size="xs" :disabled="filters.page >= meta.last_page" @click="filters.page++" />
244
+ </div>
245
+
246
+ <!-- Import wizard -->
247
+ <Modal v-model="wizard.open" title="Importar cartola" size="3xl" show-footer>
248
+ <div class="space-y-4 text-sm">
249
+ <p class="text-muted-foreground">Exporta la cartola del banco en Excel (.xlsx) o CSV. Solo se toman los abonos; importar la misma cartola dos veces no duplica movimientos.</p>
250
+ <div class="flex flex-wrap items-end gap-3">
251
+ <label class="space-y-1"><span class="block font-medium">Archivo</span><input type="file" accept=".csv,.txt,.xlsx" class="text-sm" @change="pick" /></label>
252
+ <label class="space-y-1"><span class="block font-medium">Banco (opcional)</span><input v-model="wizard.bank" :class="inputClass" maxlength="80" /></label>
253
+ <label v-if="wizard.headers.length" class="space-y-1"><span class="block font-medium">Fila de encabezados</span>
254
+ <input v-model.number="wizard.headerRow" type="number" min="1" :class="inputClass" class="w-24" @change="loadPreview" />
255
+ </label>
256
+ </div>
257
+ <p v-if="wizard.loading" class="text-muted-foreground">Leyendo el archivo…</p>
258
+ <template v-else-if="wizard.headers.length">
259
+ <div class="grid gap-3 sm:grid-cols-2">
260
+ <label v-for="f in BANK_FIELDS" :key="f.key" class="block space-y-1">
261
+ <span class="font-medium">{{ f.label }} <span v-if="f.hint" class="text-xs text-muted-foreground font-normal">({{ f.hint }})</span></span>
262
+ <select v-model="wizard.mapping[f.key]" :class="inputClass" class="w-full">
263
+ <option value="">—</option>
264
+ <option v-for="h in wizard.headers" :key="h" :value="h">{{ h }}</option>
265
+ </select>
266
+ </label>
267
+ </div>
268
+ <div class="overflow-x-auto border border-card-line rounded-control">
269
+ <table class="w-full text-xs">
270
+ <thead><tr class="bg-muted/40"><th v-for="h in wizard.headers" :key="h" class="text-left px-2 py-1 font-medium">{{ h }}</th></tr></thead>
271
+ <tbody class="divide-y divide-card-line"><tr v-for="(r, idx) in wizard.rows" :key="idx"><td v-for="(c, j) in r.slice(0, wizard.headers.length)" :key="j" class="px-2 py-1 whitespace-nowrap">{{ c }}</td></tr></tbody>
272
+ </table>
273
+ </div>
274
+ <p v-if="wizardError" class="text-warning">{{ wizardError }}</p>
275
+ </template>
276
+ </div>
277
+ <template #footer>
278
+ <App.Button text="Cancelar" size="sm" @click="wizard.open = false" />
279
+ <App.Button text="Importar" severity="primary" size="sm" :disabled="!!wizardError" :loading="billing.importStatement.isPending.value" @click="submitImport" />
280
+ </template>
281
+ </Modal>
282
+
283
+ <!-- Manual match -->
284
+ <Modal v-model="manual.open" title="Emparejar movimiento" size="2xl" show-footer>
285
+ <div v-if="manual.tx" class="space-y-3 text-sm">
286
+ <p>{{ formatDate(manual.tx.posted_at) }} · <span class="font-medium">{{ formatMoney(manual.tx.amount) }}</span> · {{ manual.tx.description }}</p>
287
+ <form class="flex gap-2" @submit.prevent="searchInvoices">
288
+ <input v-model="manual.search" :class="inputClass" class="flex-1" placeholder="Cliente o RUT" />
289
+ <App.Button text="Buscar" size="sm" :loading="manual.loading" @click="searchInvoices" />
290
+ </form>
291
+ <p class="text-xs text-muted-foreground">Elige las facturas en el orden en que se pagan. Si el monto no alcanza, la última queda con pago parcial; si sobra, queda como saldo a favor del cliente.</p>
292
+ <div class="border border-card-line rounded-control divide-y divide-card-line max-h-72 overflow-y-auto">
293
+ <p v-if="!manual.invoices.length" class="p-4 text-center text-muted-foreground">Sin facturas abiertas.</p>
294
+ <label v-for="i in manual.invoices" :key="i.id" class="flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-muted/40">
295
+ <input type="checkbox" class="rounded" :checked="manual.selected.includes(i.id)" @change="toggle(i)" />
296
+ <span class="flex-1">{{ i.display_number }} · {{ i.client_name }}<span class="text-xs text-muted-foreground"> · vence {{ formatDateTime(i.due_at) }}</span></span>
297
+ <span>{{ formatMoney(i.balance, i.currency) }}</span>
298
+ <span v-if="appliedTo(i.id) !== null" class="text-xs text-success w-28 text-right">aplica {{ formatMoney(appliedTo(i.id)) }}</span>
299
+ </label>
300
+ </div>
301
+ <p v-if="manual.selected.length && preview.credit > 0" class="text-xs text-info">Quedan {{ formatMoney(preview.credit) }} como saldo a favor del cliente.</p>
302
+ </div>
303
+ <template #footer>
304
+ <App.Button text="Cancelar" size="sm" @click="manual.open = false" />
305
+ <App.Button text="Conciliar" severity="primary" size="sm" :icon="IconCheck" :disabled="!manual.selected.length" :loading="billing.match.isPending.value" @click="submitManual" />
306
+ </template>
307
+ </Modal>
308
+ </div>
309
+ </template>
@@ -0,0 +1,87 @@
1
+ <script setup lang="ts">
2
+ import { IconDownload } from '@tabler/icons-vue'
3
+ import { REPORTS, reportCell, isNumericColumn, yearToDate } from '../../composables/useBilling/internal/billing'
4
+
5
+ /*
6
+ * Billing.Reports — collection reports: invoiced revenue (by month/client/plan/product), receivables,
7
+ * debt aging (0–30, 31–60, 61–90, 90+), collections (by month/method/client), MRR and consumption by
8
+ * space, with date range and .xlsx export.
9
+ * Backend: GET {endpoint}/reports/{report}(/export)?from=&to=&group_by=.
10
+ *
11
+ * <Billing.Reports />
12
+ */
13
+ const props = withDefaults(defineProps<{ endpoint?: string; initial?: string }>(), { endpoint: 'platform/billing', initial: 'revenue' })
14
+
15
+ const toast = useToast()
16
+ const billing = useBillingPlatform({ base: props.endpoint })
17
+ const download = useBillingDownload()
18
+ const active = ref(props.initial)
19
+ const def = computed(() => REPORTS.find(r => r.key === active.value) ?? REPORTS[0])
20
+ const range = reactive({ ...yearToDate(), group_by: '' })
21
+ watch(active, () => { range.group_by = def.value.groups[0]?.value ?? '' }, { immediate: true })
22
+ const params = computed(() => def.value.dated ? { from: range.from, to: range.to, group_by: range.group_by } : { group_by: range.group_by })
23
+ const query = billing.report(active, params)
24
+ const data = computed<any>(() => query.data.value)
25
+ const columns = computed<[string, string][]>(() => Object.entries(data.value?.columns ?? {}))
26
+
27
+ async function exportXlsx() {
28
+ try {
29
+ await download(`${billing.base}/reports/${active.value}/export`, `${active.value}.xlsx`, params.value)
30
+ } catch {
31
+ toast.error('No se pudo descargar el reporte.')
32
+ }
33
+ }
34
+
35
+ const inputClass = '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'
36
+ </script>
37
+
38
+ <template>
39
+ <div class="space-y-4">
40
+ <div class="flex flex-wrap gap-2 text-sm">
41
+ <button v-for="r in REPORTS" :key="r.key" type="button" class="px-3 py-1.5 rounded-control border"
42
+ :class="active === r.key ? 'border-primary bg-primary/10 text-primary' : 'border-card-line text-muted-foreground hover:text-foreground'" @click="active = r.key">
43
+ {{ r.label }}
44
+ </button>
45
+ </div>
46
+
47
+ <div class="flex flex-wrap items-end gap-3 text-sm">
48
+ <template v-if="def.dated">
49
+ <label class="space-y-1"><span class="block text-xs text-muted-foreground">Desde</span><input v-model="range.from" type="date" :class="inputClass" /></label>
50
+ <label class="space-y-1"><span class="block text-xs text-muted-foreground">Hasta</span><input v-model="range.to" type="date" :class="inputClass" /></label>
51
+ </template>
52
+ <label v-if="def.groups.length" class="space-y-1"><span class="block text-xs text-muted-foreground">Agrupar por</span>
53
+ <select v-model="range.group_by" :class="inputClass"><option v-for="g in def.groups" :key="g.value" :value="g.value">{{ g.label }}</option></select>
54
+ </label>
55
+ <span class="flex-1" />
56
+ <App.Button text="Excel" size="sm" outline :icon="IconDownload" @click="exportXlsx" />
57
+ </div>
58
+
59
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
60
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
61
+ <div v-else-if="query.isError.value || !data" class="p-8 text-center text-sm text-muted-foreground">
62
+ No se pudo cargar el reporte.
63
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
64
+ </div>
65
+ <div v-else-if="!data.rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin datos para el período.</div>
66
+ <table v-else class="w-full text-sm">
67
+ <thead class="text-xs uppercase text-muted-foreground">
68
+ <tr class="border-b border-card-line">
69
+ <th v-for="[key, label] in columns" :key="key" class="font-medium px-4 py-2" :class="isNumericColumn(key) ? 'text-right' : 'text-left'">{{ label }}</th>
70
+ </tr>
71
+ </thead>
72
+ <tbody class="divide-y divide-card-line">
73
+ <tr v-for="(row, idx) in data.rows" :key="idx">
74
+ <td v-for="[key] in columns" :key="key" class="px-4 py-2" :class="isNumericColumn(key) ? 'text-right whitespace-nowrap' : ''">{{ reportCell(key, row[key]) }}</td>
75
+ </tr>
76
+ </tbody>
77
+ <tfoot v-if="Object.keys(data.totals ?? {}).length" class="border-t border-card-line font-medium">
78
+ <tr>
79
+ <td v-for="([key], i) in columns" :key="key" class="px-4 py-2" :class="isNumericColumn(key) ? 'text-right whitespace-nowrap' : ''">
80
+ {{ i === 0 ? 'Total' : (key in data.totals ? reportCell(key, data.totals[key]) : '') }}
81
+ </td>
82
+ </tr>
83
+ </tfoot>
84
+ </table>
85
+ </div>
86
+ </div>
87
+ </template>