@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,130 @@
1
+ <script setup lang="ts">
2
+ import { IconDownload, IconCreditCard, IconFileInvoice } from '@tabler/icons-vue'
3
+ import {
4
+ formatMoney, subscriptionStatus, invoiceStatus, periodLabel, formatDate, formatDateTime, paymentMethodLabel, paymentChannelLabel,
5
+ bannerFor, type Invoice,
6
+ } from '../../composables/useBilling/internal/billing'
7
+
8
+ /*
9
+ * Billing.Overview — "Facturación" of the backoffice (permission billing.view), read-only: plan and
10
+ * status, consumption of the current period vs included with the estimate, invoices (PDF, due date,
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).
13
+ * Testing spaces only show the "Espacio de pruebas" strip.
14
+ * Backend: \Innertia\Billing\Routes::backoffice() → GET {endpoint}/overview|invoices|payments.
15
+ *
16
+ * <Billing.Overview />
17
+ */
18
+ const props = withDefaults(defineProps<{ endpoint?: string; showAccount?: boolean }>(), { endpoint: 'billing', showAccount: true })
19
+
20
+ const toast = useToast()
21
+ const { base, overview, invoices, payments } = useBillingSpace({ base: props.endpoint })
22
+ const savePdf = useBillingPdf()
23
+ const data = computed<any>(() => overview.data.value)
24
+ const list = computed<Invoice[]>(() => (invoices.data.value as Invoice[] | undefined) ?? [])
25
+ const paid = computed<any[]>(() => (payments.data.value as any[] | undefined) ?? [])
26
+ const banner = computed(() => bannerFor(data.value?.subscription?.status))
27
+
28
+ async function pdf(i: Invoice) {
29
+ try {
30
+ await savePdf(`${base}/invoices/${i.id}/pdf`, `factura-${i.display_number ?? i.id}.pdf`)
31
+ } catch {
32
+ toast.error('No se pudo descargar el PDF.')
33
+ }
34
+ }
35
+ </script>
36
+
37
+ <template>
38
+ <div class="space-y-4">
39
+ <div v-if="overview.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
40
+ <div v-else-if="overview.isError.value || !data" class="p-8 text-center text-sm text-muted-foreground">
41
+ No se pudo cargar la facturación.
42
+ <button type="button" class="text-primary hover:underline" @click="overview.refetch()">Reintentar</button>
43
+ </div>
44
+
45
+ <div v-else-if="data.testing" class="rounded-card border border-info/40 bg-info/5 p-4 text-sm text-foreground">
46
+ Espacio de pruebas: no tiene facturación.
47
+ </div>
48
+
49
+ <template v-else>
50
+ <div v-if="banner" class="rounded-card border p-4 text-sm" :class="banner.severity === 'danger' ? 'border-danger/40 bg-danger/5' : 'border-warning/40 bg-warning/5'">
51
+ <p class="font-medium" :class="banner.severity === 'danger' ? 'text-danger' : 'text-warning'">{{ banner.title }}</p>
52
+ <p class="text-foreground">{{ banner.message }}</p>
53
+ </div>
54
+
55
+ <div v-if="!data.subscription" class="bg-card border border-card-line rounded-card p-4 text-sm text-muted-foreground">
56
+ Este espacio aún no tiene un plan asignado.
57
+ </div>
58
+
59
+ <template v-else>
60
+ <div class="grid gap-3 sm:grid-cols-3">
61
+ <App.StatCard label="Plan" :value="data.subscription.plan?.name ?? '—'" :hint="`${subscriptionStatus(data.subscription.status).label} · ${paymentMethodLabel(data.subscription.payment_method)}`" />
62
+ <App.StatCard label="Total estimado del período" :value="formatMoney(data.estimate?.total ?? 0, data.estimate?.currency)" :hint="`${periodLabel(data.subscription.current_period_start, data.subscription.current_period_end)} · IVA incluido`" />
63
+ <App.StatCard label="Saldo pendiente" :value="formatMoney(data.balance?.open ?? 0)" :value-class="(data.balance?.overdue ?? 0) > 0 ? 'text-danger' : 'text-foreground'"
64
+ :hint="(data.balance?.overdue ?? 0) > 0 ? `${formatMoney(data.balance.overdue)} vencido` : (data.balance?.next_due_at ? `Próximo vencimiento ${formatDateTime(data.balance.next_due_at)}` : 'Al día')" />
65
+ </div>
66
+
67
+ <p v-if="data.subscription.status === 'trialing' && data.subscription.trial_ends_at" class="text-sm text-info">
68
+ Período de prueba hasta el {{ formatDate(data.subscription.trial_ends_at) }}: no se cobra.
69
+ </p>
70
+ <p v-if="data.subscription.pending_plan" class="text-sm text-muted-foreground">Desde el próximo período: plan {{ data.subscription.pending_plan.name }}.</p>
71
+
72
+ <div class="bg-card border border-card-line rounded-card p-4 space-y-3">
73
+ <p class="text-sm font-medium text-foreground">Consumo del período</p>
74
+ <p v-if="data.seats" class="text-sm text-muted-foreground">
75
+ Usuarios: {{ data.seats.counted }} de {{ data.seats.included }} incluidos<template v-if="data.seats.seat_price && data.seats.counted > data.seats.included"> · adicionales {{ formatMoney(data.estimate.seats) }}</template>
76
+ </p>
77
+ <Billing.UsageTable :usage="data.usage ?? []" :currency="data.estimate?.currency" />
78
+ </div>
79
+ </template>
80
+
81
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
82
+ <p class="text-sm font-medium text-foreground px-4 pt-3">Facturas</p>
83
+ <div v-if="invoices.isPending.value" class="p-6 text-center text-sm text-muted-foreground">Cargando…</div>
84
+ <div v-else-if="!list.length" class="p-6 text-center text-sm text-muted-foreground">
85
+ <IconFileInvoice class="size-6 mx-auto mb-2" :stroke-width="1.5" />
86
+ Aún no hay facturas.
87
+ </div>
88
+ <table v-else class="w-full text-sm">
89
+ <tbody class="divide-y divide-card-line">
90
+ <tr v-for="i in list" :key="i.id">
91
+ <td class="px-4 py-2">
92
+ <p class="font-medium text-foreground">{{ i.display_number }} <App.Tag :text="invoiceStatus(i.status).label" :severity="invoiceStatus(i.status).severity" size="xs" class="ml-1" /></p>
93
+ <p class="text-xs text-muted-foreground">{{ periodLabel(i.period_start, i.period_end) }}<template v-if="i.consolidated"> · factura conjunta del cliente</template></p>
94
+ </td>
95
+ <td class="px-4 py-2 text-right">
96
+ <p>{{ formatMoney(i.total, i.currency) }}</p>
97
+ <p v-if="i.consolidated" class="text-xs text-muted-foreground">Este espacio: {{ formatMoney(i.space_part ?? 0, i.currency) }}</p>
98
+ </td>
99
+ <td class="px-4 py-2 text-muted-foreground">
100
+ <template v-if="i.status === 'paid'">Pagada {{ formatDateTime(i.paid_at) }}</template>
101
+ <template v-else>Vence {{ formatDateTime(i.due_at) }} · saldo {{ formatMoney(i.balance, i.currency) }}</template>
102
+ </td>
103
+ <td class="px-4 py-2">
104
+ <div class="flex justify-end gap-1">
105
+ <App.Button v-if="i.payment_link" text="Pagar" size="xs" severity="primary" :icon="IconCreditCard" type="link" :link="i.payment_link" />
106
+ <App.Button text="PDF" size="xs" outline :icon="IconDownload" @click="pdf(i)" />
107
+ </div>
108
+ </td>
109
+ </tr>
110
+ </tbody>
111
+ </table>
112
+ </div>
113
+
114
+ <div v-if="paid.length" class="bg-card border border-card-line rounded-card">
115
+ <p class="text-sm font-medium text-foreground px-4 pt-3">Pagos</p>
116
+ <ul class="divide-y divide-card-line">
117
+ <li v-for="p in paid" :key="p.id" class="flex items-center gap-3 px-4 py-2 text-sm">
118
+ <span class="flex-1">{{ formatDateTime(p.received_at) }} · {{ paymentChannelLabel(p.method) }}<template v-if="p.reference"> · {{ p.reference }}</template></span>
119
+ <span class="font-medium">{{ formatMoney(p.amount) }}</span>
120
+ </li>
121
+ </ul>
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>
128
+ </template>
129
+ </div>
130
+ </template>
@@ -0,0 +1,146 @@
1
+ <script setup lang="ts">
2
+ import { IconPlus, IconPencil, IconTrash, IconReceipt } from '@tabler/icons-vue'
3
+ import {
4
+ formatMoney, intervalLabel, emptyPlan, planPayload, errorMessage, type Plan, type MeterDefinition,
5
+ } from '../../composables/useBilling/internal/billing'
6
+
7
+ /*
8
+ * Billing.Plans — plans and prices (platform): base price, included seats + seat price, trial,
9
+ * VAT and metered consumption (included + unit price; AI at real cost + markup %).
10
+ * Prices in pesos (integers). Changes rule from the next period close.
11
+ * Backend: \Innertia\Billing\Routes::platform() + platformWrite().
12
+ *
13
+ * <Billing.Plans endpoint="platform/billing" :can-edit="isOwner" />
14
+ */
15
+ const props = withDefaults(defineProps<{ endpoint?: string; canEdit?: boolean }>(), { endpoint: 'platform/billing', canEdit: true })
16
+
17
+ const toast = useToast()
18
+ const { plans, meters, savePlan } = useBillingPlatform({ base: props.endpoint })
19
+ const list = computed<Plan[]>(() => (plans.data.value as Plan[] | undefined) ?? [])
20
+ const catalog = computed<MeterDefinition[]>(() => (meters.data.value as MeterDefinition[] | undefined) ?? [])
21
+ const meterDef = (key: string) => catalog.value.find(m => m.key === key)
22
+
23
+ const show = ref(false)
24
+ const editing = ref<Plan | null>(null)
25
+ const form = reactive<Omit<Plan, 'id'>>(emptyPlan())
26
+
27
+ function open(plan: Plan | null) {
28
+ editing.value = plan
29
+ Object.assign(form, plan ? JSON.parse(JSON.stringify({ ...plan, description: plan.description ?? '', product: plan.product ?? '' })) : emptyPlan())
30
+ show.value = true
31
+ }
32
+
33
+ function addMeter() {
34
+ const used = new Set(form.meters.map(m => m.meter))
35
+ const next = catalog.value.find(m => !used.has(m.key))
36
+ form.meters.push({ meter: next?.key ?? '', included_quantity: 0, unit_price: 0, markup_percent: next?.valued_by_cost ? 20 : null })
37
+ }
38
+
39
+ async function submit() {
40
+ if (!form.name.trim() || !form.key.trim()) { toast.error('Nombre y clave son obligatorios.'); return }
41
+ try {
42
+ await savePlan.mutateAsync({ id: editing.value?.id, body: planPayload(form, catalog.value) })
43
+ show.value = false
44
+ toast.success(editing.value ? 'Plan actualizado.' : 'Plan creado.')
45
+ } catch (e: any) {
46
+ toast.error(errorMessage(e, 'No se pudo guardar el plan.'))
47
+ }
48
+ }
49
+
50
+ 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'
51
+ </script>
52
+
53
+ <template>
54
+ <div class="space-y-4">
55
+ <div class="flex flex-wrap items-center gap-3">
56
+ <p class="flex-1 text-sm text-muted-foreground">
57
+ Cada espacio de producción se cobra con un plan: precio base, usuarios adicionales y consumo medido. Los montos van en pesos; los cambios rigen desde el próximo cierre.
58
+ </p>
59
+ <App.Button v-if="canEdit" text="Nuevo plan" severity="primary" size="sm" :icon="IconPlus" @click="open(null)" />
60
+ </div>
61
+
62
+ <div class="bg-card border border-card-line rounded-card overflow-hidden">
63
+ <div v-if="plans.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
64
+ <div v-else-if="plans.isError.value" class="p-8 text-center text-sm text-muted-foreground">
65
+ No se pudieron cargar los planes.
66
+ <button type="button" class="text-primary hover:underline" @click="plans.refetch()">Reintentar</button>
67
+ </div>
68
+ <div v-else-if="!list.length" class="p-8 text-center text-sm text-muted-foreground">
69
+ <IconReceipt class="size-6 mx-auto mb-2" :stroke-width="1.5" />
70
+ Aún no hay planes.
71
+ </div>
72
+ <ul v-else class="divide-y divide-card-line">
73
+ <li v-for="p in list" :key="p.id" class="flex flex-wrap items-start gap-3 px-5 py-3">
74
+ <div class="flex-1 min-w-0">
75
+ <p class="text-sm font-medium text-foreground flex items-center gap-2">
76
+ {{ p.name }} <span class="text-xs font-mono text-muted-foreground">{{ p.key }}</span>
77
+ <App.Tag v-if="!p.active" text="Inactivo" size="xs" />
78
+ </p>
79
+ <p class="text-xs text-muted-foreground">
80
+ {{ formatMoney(p.base_price, p.currency) }} {{ intervalLabel(p.interval) }} + IVA {{ p.tax_rate }} %
81
+ · {{ p.included_seats }} usuarios incluidos<template v-if="p.seat_price">, adicional {{ formatMoney(p.seat_price, p.currency) }}</template>
82
+ <template v-if="p.trial_days"> · {{ p.trial_days }} días de prueba</template>
83
+ </p>
84
+ <p v-if="p.meters.length" class="text-xs text-muted-foreground">
85
+ <template v-for="(m, i) in p.meters" :key="m.meter">
86
+ {{ i ? ' · ' : '' }}{{ m.label ?? m.meter }}:
87
+ <template v-if="m.valued_by_cost">costo + {{ m.markup_percent ?? 0 }} %</template>
88
+ <template v-else>{{ m.included_quantity }} incluidos, {{ formatMoney(m.unit_price, p.currency) }} c/u</template>
89
+ </template>
90
+ </p>
91
+ </div>
92
+ <App.Button v-if="canEdit" text="Editar" size="xs" :icon="IconPencil" @click="open(p)" />
93
+ </li>
94
+ </ul>
95
+ </div>
96
+
97
+ <Modal v-model="show" :title="editing ? 'Editar plan' : 'Nuevo plan'" size="2xl" show-footer>
98
+ <form class="space-y-4" @submit.prevent="submit">
99
+ <div class="grid gap-3 sm:grid-cols-2">
100
+ <label class="block space-y-1"><span class="text-sm font-medium">Nombre</span><input v-model="form.name" :class="inputClass" maxlength="120" /></label>
101
+ <label class="block space-y-1"><span class="text-sm font-medium">Clave</span><input v-model="form.key" :class="inputClass" maxlength="60" placeholder="pro" /></label>
102
+ <label class="block space-y-1 sm:col-span-2"><span class="text-sm font-medium">Descripción</span><input v-model="form.description" :class="inputClass" maxlength="250" /></label>
103
+ <label class="block space-y-1"><span class="text-sm font-medium">Periodicidad</span>
104
+ <select v-model="form.interval" :class="inputClass"><option value="monthly">Mensual</option><option value="annual">Anual</option></select>
105
+ </label>
106
+ <label class="block space-y-1"><span class="text-sm font-medium">Precio base ($)</span><input v-model.number="form.base_price" type="number" min="0" step="1" :class="inputClass" /></label>
107
+ <label class="block space-y-1"><span class="text-sm font-medium">Usuarios incluidos</span><input v-model.number="form.included_seats" type="number" min="0" :class="inputClass" /></label>
108
+ <label class="block space-y-1"><span class="text-sm font-medium">Precio por usuario adicional ($)</span><input v-model.number="form.seat_price" type="number" min="0" :class="inputClass" /></label>
109
+ <label class="block space-y-1"><span class="text-sm font-medium">Días de prueba</span><input v-model.number="form.trial_days" type="number" min="0" max="365" :class="inputClass" /></label>
110
+ <label class="block space-y-1"><span class="text-sm font-medium">IVA (%)</span><input v-model.number="form.tax_rate" type="number" min="0" max="100" step="0.01" :class="inputClass" /></label>
111
+ <label class="flex items-center gap-2 text-sm sm:col-span-2"><input v-model="form.active" type="checkbox" class="rounded" /> Plan activo (disponible para nuevas suscripciones)</label>
112
+ </div>
113
+
114
+ <div class="space-y-2">
115
+ <div class="flex items-center justify-between">
116
+ <span class="text-sm font-medium">Consumo medido</span>
117
+ <App.Button text="Agregar medidor" size="xs" :icon="IconPlus" :disabled="form.meters.length >= catalog.length" @click="addMeter" />
118
+ </div>
119
+ <p v-if="!form.meters.length" class="text-xs text-muted-foreground">Sin consumo medido: solo se cobra base y usuarios.</p>
120
+ <div v-for="(m, i) in form.meters" :key="i" class="grid gap-2 sm:grid-cols-[1fr_8rem_8rem_auto] items-end border border-card-line rounded-control p-2">
121
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Medidor</span>
122
+ <select v-model="m.meter" :class="inputClass">
123
+ <option v-for="d in catalog" :key="d.key" :value="d.key">{{ d.label }}</option>
124
+ </select>
125
+ </label>
126
+ <template v-if="meterDef(m.meter)?.valued_by_cost">
127
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Margen (%)</span><input v-model.number="m.markup_percent" type="number" min="0" :class="inputClass" /></label>
128
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Incluido ($)</span><input v-model.number="m.included_quantity" type="number" min="0" :class="inputClass" /></label>
129
+ </template>
130
+ <template v-else>
131
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Incluido ({{ meterDef(m.meter)?.unit ?? 'unidad' }})</span><input v-model.number="m.included_quantity" type="number" min="0" step="any" :class="inputClass" /></label>
132
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Precio unitario ($)</span><input v-model.number="m.unit_price" type="number" min="0" :class="inputClass" /></label>
133
+ </template>
134
+ <button type="button" class="p-2 text-muted-foreground hover:text-danger" aria-label="Quitar medidor" @click="form.meters.splice(i, 1)">
135
+ <IconTrash class="size-4" />
136
+ </button>
137
+ </div>
138
+ </div>
139
+ </form>
140
+ <template #footer>
141
+ <App.Button text="Cancelar" size="sm" @click="show = false" />
142
+ <App.Button text="Guardar" severity="primary" size="sm" :loading="savePlan.isPending.value" @click="submit" />
143
+ </template>
144
+ </Modal>
145
+ </div>
146
+ </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>