@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,29 +1,47 @@
1
1
  <script setup lang="ts">
2
- import { errorMessage } from '../../composables/useBilling/internal/billing'
2
+ import { errorMessage, parseReminderDays } from '../../composables/useBilling/internal/billing'
3
3
 
4
4
  /*
5
5
  * Billing.Settings — platform billing settings (owner): USD→CLP rate used to value AI cost, transfer
6
6
  * instructions shown in the invoice email/PDF and the issuer block of the PDF; plus manual runs of
7
- * the daily close and dunning (they also run on the scheduler, America/Santiago).
8
- * Backend: GET|PUT {endpoint}/settings, POST {endpoint}/run/{close|dunning}.
7
+ * the daily close, dunning and payment reminders (they also run on the scheduler, America/Santiago).
8
+ * Reminders: days before the due date, the due day, every N days while overdue (max), escalation (copy to
9
+ * the collections email + critical notice) after N overdue reminders.
10
+ * Backend: GET|PUT {endpoint}/settings, POST {endpoint}/run/{close|dunning|reminders}.
9
11
  */
10
12
  const props = withDefaults(defineProps<{ endpoint?: string; canRun?: boolean }>(), { endpoint: 'platform/billing', canRun: true })
11
13
 
12
14
  const toast = useToast()
13
15
  const { confirm } = useModal()
14
16
  const { settings, saveSettings, run } = useBillingPlatform({ base: props.endpoint })
15
- const form = reactive({ usd_clp_rate: '' as string | number, transfer_instructions: '', issuer_name: '', issuer_tax_id: '', issuer_address: '' })
17
+ const form = reactive({
18
+ usd_clp_rate: '' as string | number, transfer_instructions: '', issuer_name: '', issuer_tax_id: '', issuer_address: '',
19
+ reminders_enabled: true, reminder_days_before: '3', reminder_on_due: true, reminder_overdue_every_days: 7 as number | string,
20
+ reminder_overdue_max: 6 as number | string, reminder_escalate_after: 2 as number | string, reminder_escalation_email: '',
21
+ })
16
22
 
17
23
  watch(() => settings.data.value, (s: any) => {
18
- if (s) Object.assign(form, { usd_clp_rate: s.usd_clp_rate ?? '', transfer_instructions: s.transfer_instructions ?? '', issuer_name: s.issuer_name ?? '', issuer_tax_id: s.issuer_tax_id ?? '', issuer_address: s.issuer_address ?? '' })
24
+ if (s) {
25
+ Object.assign(form, {
26
+ usd_clp_rate: s.usd_clp_rate ?? '', transfer_instructions: s.transfer_instructions ?? '', issuer_name: s.issuer_name ?? '', issuer_tax_id: s.issuer_tax_id ?? '', issuer_address: s.issuer_address ?? '',
27
+ reminders_enabled: s.reminders_enabled ?? true, reminder_days_before: s.reminder_days_before ?? '', reminder_on_due: s.reminder_on_due ?? true,
28
+ reminder_overdue_every_days: s.reminder_overdue_every_days ?? 7, reminder_overdue_max: s.reminder_overdue_max ?? 6,
29
+ reminder_escalate_after: s.reminder_escalate_after ?? 2, reminder_escalation_email: s.reminder_escalation_email ?? '',
30
+ })
31
+ }
19
32
  }, { immediate: true })
20
33
 
21
34
  async function save() {
35
+ const days = parseReminderDays(form.reminder_days_before)
36
+ if (days === null) { toast.error('Días antes del vencimiento: números separados por coma (ej. 7, 3).'); return }
22
37
  try {
23
38
  await saveSettings.mutateAsync({
24
39
  usd_clp_rate: form.usd_clp_rate === '' ? null : Number(form.usd_clp_rate),
25
40
  transfer_instructions: form.transfer_instructions || null,
26
41
  issuer_name: form.issuer_name || null, issuer_tax_id: form.issuer_tax_id || null, issuer_address: form.issuer_address || null,
42
+ reminders_enabled: form.reminders_enabled, reminder_days_before: days.join(',') || null, reminder_on_due: form.reminder_on_due,
43
+ reminder_overdue_every_days: Number(form.reminder_overdue_every_days) || 7, reminder_overdue_max: Number(form.reminder_overdue_max) || 0,
44
+ reminder_escalate_after: Number(form.reminder_escalate_after) || 0, reminder_escalation_email: form.reminder_escalation_email || null,
27
45
  })
28
46
  toast.success('Configuración guardada.')
29
47
  } catch (e: any) {
@@ -31,18 +49,24 @@ async function save() {
31
49
  }
32
50
  }
33
51
 
34
- async function runJob(job: 'close' | 'dunning') {
52
+ const JOBS = {
53
+ close: ['Cerrar períodos ahora', 'Se cierran los períodos vencidos y se generan las facturas en borrador. Es idempotente: no duplica cobros.'],
54
+ dunning: ['Revisar mora ahora', 'Se marcan las facturas vencidas y se actualiza el estado de las suscripciones (mora, suspensión, reactivación).'],
55
+ reminders: ['Enviar recordatorios ahora', 'Se envían los recordatorios que correspondan hoy. Nunca repite uno ya enviado.'],
56
+ } as const
57
+
58
+ async function runJob(job: 'close' | 'dunning' | 'reminders') {
35
59
  const ok = await confirm({
36
- title: job === 'close' ? 'Cerrar períodos ahora' : 'Revisar mora ahora',
37
- message: job === 'close'
38
- ? 'Se cierran los períodos vencidos y se generan las facturas en borrador. Es idempotente: no duplica cobros.'
39
- : 'Se marcan las facturas vencidas y se actualiza el estado de las suscripciones (mora, suspensión, reactivación).',
60
+ title: JOBS[job][0],
61
+ message: JOBS[job][1],
40
62
  confirmText: 'Ejecutar',
41
63
  })
42
64
  if (!ok) return
43
65
  try {
44
66
  const res: any = await run.mutateAsync(job)
45
- toast.success(job === 'close' ? `Cierre listo: ${res?.statements ?? 0} cobros nuevos.` : `Mora revisada: ${res?.overdue ?? 0} facturas vencidas, ${res?.changed ?? 0} cambios.`)
67
+ toast.success(job === 'close' ? `Cierre listo: ${res?.statements ?? 0} cobros nuevos.`
68
+ : job === 'dunning' ? `Mora revisada: ${res?.overdue ?? 0} facturas vencidas, ${res?.changed ?? 0} cambios.`
69
+ : `Recordatorios: ${res?.sent ?? 0} enviados (${res?.escalated ?? 0} escalados).`)
46
70
  } catch (e: any) {
47
71
  toast.error(errorMessage(e, 'No se pudo ejecutar.'))
48
72
  }
@@ -65,15 +89,24 @@ const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card t
65
89
  <label class="block space-y-1 sm:col-span-2"><span class="font-medium">Datos para transferencia</span>
66
90
  <textarea v-model="form.transfer_instructions" rows="3" maxlength="1000" class="w-full rounded-control border border-card-line bg-card text-sm text-foreground px-3 py-2" placeholder="Banco, tipo y número de cuenta, RUT, correo de aviso" />
67
91
  </label>
92
+ <p class="sm:col-span-2 font-medium text-foreground pt-2">Recordatorios de pago</p>
93
+ <label class="sm:col-span-2 flex items-center gap-2"><input v-model="form.reminders_enabled" type="checkbox" class="rounded" /> Enviar recordatorios por correo (marca de la plataforma) y avisos a los administradores del espacio</label>
94
+ <label class="block space-y-1"><span class="font-medium">Días antes del vencimiento</span><input v-model="form.reminder_days_before" :class="inputClass" placeholder="7, 3" /></label>
95
+ <label class="flex items-center gap-2 self-end h-9"><input v-model="form.reminder_on_due" type="checkbox" class="rounded" /> El día que vence</label>
96
+ <label class="block space-y-1"><span class="font-medium">Vencida: cada cuántos días</span><input v-model="form.reminder_overdue_every_days" type="number" min="1" max="90" :class="inputClass" /></label>
97
+ <label class="block space-y-1"><span class="font-medium">Máximo de recordatorios de vencida</span><input v-model="form.reminder_overdue_max" type="number" min="0" max="50" :class="inputClass" /></label>
98
+ <label class="block space-y-1"><span class="font-medium">Escalar después de (recordatorios de vencida)</span><input v-model="form.reminder_escalate_after" type="number" min="0" max="50" :class="inputClass" /></label>
99
+ <label class="block space-y-1"><span class="font-medium">Correo de cobranza (copia al escalar)</span><input v-model="form.reminder_escalation_email" type="email" :class="inputClass" maxlength="150" /></label>
68
100
  <div class="sm:col-span-2 flex justify-end">
69
101
  <App.Button text="Guardar" severity="primary" size="sm" :loading="saveSettings.isPending.value" @click="save" />
70
102
  </div>
71
103
  </form>
72
104
 
73
105
  <div v-if="canRun" class="bg-card border border-card-line rounded-card p-4 flex flex-wrap items-center gap-3 text-sm">
74
- <p class="flex-1 text-muted-foreground">El cierre (00:30) y la revisión de mora (08:00) corren solos cada día, hora de Chile.</p>
106
+ <p class="flex-1 text-muted-foreground">El cierre (00:30), la revisión de mora (08:00) y los recordatorios (09:00) corren solos cada día, hora de Chile.</p>
75
107
  <App.Button text="Cerrar períodos" size="sm" :loading="run.isPending.value" @click="runJob('close')" />
76
108
  <App.Button text="Revisar mora" size="sm" :loading="run.isPending.value" @click="runJob('dunning')" />
109
+ <App.Button text="Enviar recordatorios" size="sm" :loading="run.isPending.value" @click="runJob('reminders')" />
77
110
  </div>
78
111
  </div>
79
112
  </template>
@@ -4,7 +4,10 @@ import { resolve } from 'node:path'
4
4
  import { parse, compileScript, compileTemplate } from 'vue/compiler-sfc'
5
5
 
6
6
  // Billing components compile (script + template) without errors.
7
- const COMPONENTS = ['../Plans.vue', '../Invoices.vue', '../SpaceSubscription.vue', '../ClientTotals.vue', '../Settings.vue', '../Overview.vue', '../StatusBanner.vue', '../UsageTable.vue']
7
+ const COMPONENTS = [
8
+ '../Plans.vue', '../Invoices.vue', '../SpaceSubscription.vue', '../ClientTotals.vue', '../Settings.vue', '../Overview.vue', '../StatusBanner.vue', '../UsageTable.vue',
9
+ '../Adjustments.vue', '../CreditNoteForm.vue', '../ClientTerms.vue', '../AccountStatement.vue', '../ActivityLog.vue', '../Reconciliation.vue', '../Reports.vue',
10
+ ]
8
11
 
9
12
  describe('SFC de Billing compilan', () => {
10
13
  for (const rel of COMPONENTS) {
@@ -53,6 +53,7 @@ export const FEATURE_LABELS: Record<string, string> = {
53
53
  assistant: 'Asistente',
54
54
  tts: 'Voz (TTS)',
55
55
  voice_agent: 'Agente de voz',
56
+ flow_builder: 'Asistente de flujos',
56
57
  import_pdf: 'Importación de PDF',
57
58
  chat: 'Chat',
58
59
  embedding: 'Embeddings',
@@ -1,5 +1,5 @@
1
1
  import { computed, type Ref } from 'vue'
2
- import type { Invoice, MeterDefinition, Plan } from './internal/billing'
2
+ import type { Adjustment, BankTransaction, Invoice, MeterDefinition, Plan } from './internal/billing'
3
3
 
4
4
  const clean = (base: string | undefined, fallback: string) => String(base || fallback).replace(/^\/+|\/+$/g, '')
5
5
 
@@ -19,6 +19,24 @@ export function useBillingPdf() {
19
19
  }
20
20
  }
21
21
 
22
+ const compact = (o: Record<string, any>) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== '' && v !== null && v !== undefined))
23
+
24
+ /** Downloads a file endpoint (xlsx exports) with the session, optional query params. */
25
+ export function useBillingDownload() {
26
+ const { download } = useDownload()
27
+ return async (path: string, filename: string, params: Record<string, any> = {}) => {
28
+ const { blob } = await download(path, compact(params))
29
+ const url = URL.createObjectURL(blob)
30
+ const a = document.createElement('a')
31
+ a.href = url
32
+ a.download = filename
33
+ document.body.appendChild(a)
34
+ a.click()
35
+ a.remove()
36
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
37
+ }
38
+ }
39
+
22
40
  /**
23
41
  * Platform billing (innertia-laravel \Innertia\Billing\Routes::platform() + platformWrite()).
24
42
  * `base`: prefix where the product mounted them (default 'platform/billing').
@@ -113,13 +131,98 @@ export function useBillingPlatform(options: { base?: string } = {}) {
113
131
  })
114
132
 
115
133
  const run = useMutation({
116
- mutationFn: (job: 'close' | 'dunning') => api.post(`${base}/run/${job}`, {}),
134
+ mutationFn: (job: 'close' | 'dunning' | 'reminders') => api.post(`${base}/run/${job}`, {}),
117
135
  onSuccess: invalidate,
118
136
  })
119
137
 
138
+ // ── Collections (stage 3) ────────────────────────────────────────────────
139
+ const post = (path: string, body: Record<string, any> = {}) => api.post(`${base}/${path}`, body)
140
+ const mutation = <T = any>(fn: (vars: any) => Promise<T>) => useMutation({ mutationFn: fn, onSuccess: invalidate })
141
+
142
+ function adjustments(filters: Ref<Record<string, any>>) {
143
+ return useQuery({
144
+ queryKey: computed(() => ['billing', base, 'adjustments', { ...filters.value }]),
145
+ queryFn: () => api.get(`${base}/adjustments`, { params: compact(filters.value) }),
146
+ select: (res: any) => (res?.data ?? []) as Adjustment[],
147
+ })
148
+ }
149
+ const createAdjustment = mutation((body: Record<string, any>) => post('adjustments', body))
150
+ const cancelAdjustment = mutation(({ id, reason }: { id: string; reason: string }) => post(`adjustments/${id}/cancel`, { reason }))
151
+ const createCreditNote = mutation((body: Record<string, any>) => post('credit-notes', body) as Promise<Adjustment>)
152
+
153
+ function terms(clientId: Ref<string>) {
154
+ return useQuery({
155
+ queryKey: computed(() => ['billing', base, 'terms', clientId.value]),
156
+ queryFn: () => api.get(`${base}/clients/${clientId.value}/terms`),
157
+ enabled: computed(() => !!clientId.value),
158
+ })
159
+ }
160
+ const saveTerms = mutation(({ clientId, body }: { clientId: string; body: Record<string, any> }) => api.put(`${base}/clients/${clientId}/terms`, body))
161
+ const applyCredit = mutation(({ clientId, invoiceId }: { clientId: string; invoiceId?: string | null }) =>
162
+ post(`clients/${clientId}/apply-credit`, { invoice_id: invoiceId ?? null }) as Promise<{ applied: number; credit_available: number }>)
163
+
164
+ function account(clientId: Ref<string>, params: Ref<Record<string, any>>) {
165
+ return useQuery({
166
+ queryKey: computed(() => ['billing', base, 'account', clientId.value, { ...params.value }]),
167
+ queryFn: () => api.get(`${base}/clients/${clientId.value}/account`, { params: compact(params.value) }),
168
+ enabled: computed(() => !!clientId.value),
169
+ })
170
+ }
171
+
172
+ function activity(filters: Ref<Record<string, any>>) {
173
+ return useQuery({
174
+ queryKey: computed(() => ['billing', base, 'activity', { ...filters.value }]),
175
+ queryFn: () => api.get(`${base}/activity`, { params: compact(filters.value) }),
176
+ })
177
+ }
178
+
179
+ const voidInvoice = mutation(({ id, reason }: { id: string; reason: string }) => post(`invoices/${id}/void`, { reason }) as Promise<Invoice>)
180
+ const reissue = mutation(({ id, body }: { id: string; body: Record<string, any> }) => post(`invoices/${id}/reissue`, body) as Promise<Invoice>)
181
+ const waiveLateFees = mutation(({ id, reason }: { id: string; reason: string }) =>
182
+ post(`invoices/${id}/waive-late-fees`, { reason }) as Promise<{ removed: number; credited: number }>)
183
+
184
+ // Reconciliation
185
+ const { upload } = useFile()
186
+ const preview = (file: File, headerRow?: number | null) =>
187
+ upload(`${base}/reconciliation/preview`, file, { extraData: { header_row: headerRow ?? null } }) as Promise<any>
188
+ const importStatement = mutation(({ file, mapping, bank, headerRow }: { file: File; mapping: Record<string, string>; bank?: string | null; headerRow?: number | null }) =>
189
+ upload(`${base}/reconciliation/imports`, file, { extraData: { mapping: compact(mapping), bank: bank || null, header_row: headerRow ?? null } }) as Promise<any>)
190
+ const imports = useQuery({
191
+ queryKey: ['billing', base, 'bank-imports'],
192
+ queryFn: () => api.get(`${base}/reconciliation/imports`),
193
+ select: (res: any) => (res?.data ?? []) as any[],
194
+ // Poll while an import is queued or running.
195
+ refetchInterval: (query: any) => ((query.state.data?.data ?? []) as any[]).some(i => i.status === 'pending' || i.status === 'processing') ? 3000 : false,
196
+ })
197
+ function transactions(filters: Ref<Record<string, any>>) {
198
+ return useQuery({
199
+ queryKey: computed(() => ['billing', base, 'bank-transactions', { ...filters.value }]),
200
+ queryFn: () => api.get(`${base}/reconciliation/transactions`, { params: compact(filters.value) }),
201
+ })
202
+ }
203
+ const openInvoices = (params: { client_id?: string | null; q?: string | null }) =>
204
+ api.get(`${base}/reconciliation/open-invoices`, { params: compact(params) }).then((res: any) => (res?.data ?? []) as Invoice[])
205
+ const match = mutation(({ id, clientId, invoiceIds }: { id: string; clientId: string; invoiceIds: string[] }) =>
206
+ post(`reconciliation/transactions/${id}/match`, { client_id: clientId, invoice_ids: invoiceIds }) as Promise<BankTransaction>)
207
+ const unmatch = mutation(({ id, reason }: { id: string; reason: string }) => post(`reconciliation/transactions/${id}/unmatch`, { reason }))
208
+ const ignore = mutation(({ id, reason }: { id: string; reason?: string | null }) => post(`reconciliation/transactions/${id}/ignore`, { reason: reason ?? null }))
209
+ const restore = mutation((id: string) => post(`reconciliation/transactions/${id}/restore`))
210
+ const rematch = mutation((importId?: string | null) => post('reconciliation/rematch', { import_id: importId ?? null }) as Promise<{ matched: number; suggested: number; unmatched: number }>)
211
+
212
+ function report(name: Ref<string>, params: Ref<Record<string, any>>) {
213
+ return useQuery({
214
+ queryKey: computed(() => ['billing', base, 'report', name.value, { ...params.value }]),
215
+ queryFn: () => api.get(`${base}/reports/${name.value}`, { params: compact(params.value) }),
216
+ enabled: computed(() => !!name.value),
217
+ })
218
+ }
219
+
120
220
  return {
121
221
  base, plans, meters, savePlan, invoices, invoice, issue, resend, registerPayment, space,
122
222
  startSubscription, updateSubscription, subscriptionAction, clientTotals, settings, saveSettings, run,
223
+ adjustments, createAdjustment, cancelAdjustment, createCreditNote, terms, saveTerms, applyCredit, account, activity,
224
+ voidInvoice, reissue, waiveLateFees, preview, importStatement, imports, transactions, openInvoices, match, unmatch,
225
+ ignore, restore, rematch, report,
123
226
  }
124
227
  }
125
228
 
@@ -143,5 +246,12 @@ export function useBillingSpace(options: { base?: string } = {}) {
143
246
  select: (res: any) => (res?.data ?? []) as any[],
144
247
  })
145
248
 
146
- return { base, overview, invoices, payments }
249
+ function account(params: Ref<Record<string, any>>) {
250
+ return useQuery({
251
+ queryKey: computed(() => ['billing-space', base, 'account', { ...params.value }]),
252
+ queryFn: () => api.get(`${base}/account`, { params: compact(params.value) }),
253
+ })
254
+ }
255
+
256
+ return { base, overview, invoices, payments, account }
147
257
  }
@@ -0,0 +1,120 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ adjustmentPayload, adjustmentValue, adjustmentStatus, creditNotePayload, reissuePayload, mappingError, allocationPreview,
4
+ transactionStatus, matchReasonLabel, scoreSeverity, reportCell, isNumericColumn, parseReminderDays, yearToDate,
5
+ activityLabel, movementLabel, eventLabel, importStatus, type AdjustmentForm,
6
+ } from '../billing'
7
+
8
+ const adj = (over: Partial<AdjustmentForm> = {}): AdjustmentForm => ({
9
+ scope: 'space', tenant_key: 'rancagua', type: 'discount', mode: 'amount', value: '10.000', recurring: true,
10
+ starts_at: '2026-11-01', ends_at: '2026-12-31', reason: ' Lanzamiento ', ...over,
11
+ })
12
+
13
+ describe('cobranza: ajustes y notas de crédito', () => {
14
+ it('arma el payload de un ajuste por espacio y valida', () => {
15
+ expect(adjustmentPayload(adj(), 'c1').payload).toEqual({
16
+ tenant_key: 'rancagua', type: 'discount', amount: 10000, recurring: true, starts_at: '2026-11-01', ends_at: '2026-12-31', reason: 'Lanzamiento',
17
+ })
18
+ expect(adjustmentPayload(adj({ reason: '' }), 'c1').error).toBe('El motivo es obligatorio.')
19
+ expect(adjustmentPayload(adj({ value: '0' }), 'c1').error).toBe('Ingresa un monto válido.')
20
+ expect(adjustmentPayload(adj({ mode: 'percent', value: '120' }), 'c1').error).toContain('porcentaje')
21
+ expect(adjustmentPayload(adj({ ends_at: '2026-10-01' }), 'c1').error).toContain('vigencia')
22
+ // one-off: never recurring, no end
23
+ expect(adjustmentPayload(adj({ type: 'one_off' }), 'c1').payload).toMatchObject({ recurring: false, ends_at: null })
24
+ })
25
+
26
+ it('a nivel de cliente solo admite porcentajes de descuento o recargo', () => {
27
+ expect(adjustmentPayload(adj({ scope: 'client' }), 'c1').error).toContain('porcentuales')
28
+ expect(adjustmentPayload(adj({ scope: 'client', mode: 'percent', value: '10,5' }), 'c1').payload).toMatchObject({ client_id: 'c1', percent: 10.5 })
29
+ })
30
+
31
+ it('muestra valor y estado del ajuste', () => {
32
+ expect(adjustmentValue({ type: 'discount', amount: 10000, percent: null })).toBe('- $ 10.000')
33
+ expect(adjustmentValue({ type: 'surcharge', amount: null, percent: 15 })).toBe('+ 15 %')
34
+ expect(adjustmentStatus('applied')).toEqual({ label: 'Aplicado', severity: 'success' })
35
+ })
36
+
37
+ it('arma la nota de crédito según el destino', () => {
38
+ const base = { amount: '$ 19.000', reason: 'Caída', invoice_id: 'i1', tenant_key: 'rancagua' }
39
+ expect(creditNotePayload({ ...base, target: 'invoice' }, 'c1').payload).toEqual({ client_id: 'c1', amount: 19000, reason: 'Caída', target: 'invoice', invoice_id: 'i1', tenant_key: null })
40
+ expect(creditNotePayload({ ...base, target: 'next_period' }, 'c1').payload).toMatchObject({ invoice_id: null, tenant_key: 'rancagua' })
41
+ expect(creditNotePayload({ ...base, target: 'invoice', invoice_id: '' }, 'c1').error).toBe('Elige la factura.')
42
+ expect(creditNotePayload({ ...base, target: 'balance', amount: '' }, 'c1').error).toBe('Ingresa un monto válido.')
43
+ })
44
+ })
45
+
46
+ describe('cobranza: refacturación', () => {
47
+ it('envía solo los datos cambiados y líneas con signo', () => {
48
+ const { payload } = reissuePayload({
49
+ reason: ' RUT mal ', billing_data: { tax_id: '76.222.222-2', legal_name: 'X SpA' }, original: { tax_id: '76.111.111-1', legal_name: 'X SpA' },
50
+ lines: [{ description: 'Descuento', amount: '-10.000' }, { description: '', amount: '' }], due_at: '', send: false,
51
+ })
52
+ expect(payload).toEqual({
53
+ reason: 'RUT mal', billing_data: { tax_id: '76.222.222-2' }, lines: [{ description: 'Descuento', amount: -10000, tenant_key: null }], due_at: null, send: false,
54
+ })
55
+ })
56
+
57
+ it('exige motivo y líneas completas', () => {
58
+ const base = { billing_data: {}, original: {}, due_at: '', send: true }
59
+ expect(reissuePayload({ ...base, reason: '', lines: [] }).error).toBe('El motivo es obligatorio.')
60
+ expect(reissuePayload({ ...base, reason: 'x', lines: [{ description: 'a', amount: '0' }] }).error).toContain('distinto de cero')
61
+ expect(reissuePayload({ ...base, reason: 'x', lines: [] }).payload?.billing_data).toBeNull()
62
+ })
63
+
64
+ it('etiqueta los eventos nuevos de la bitácora', () => {
65
+ expect(eventLabel('credit_note')).toBe('Nota de crédito')
66
+ expect(eventLabel('late_fee_waived')).toBe('Interés condonado')
67
+ expect(eventLabel('reminder_sent')).toBe('Recordatorio enviado')
68
+ })
69
+ })
70
+
71
+ describe('cobranza: conciliación', () => {
72
+ it('valida el mapeo de columnas', () => {
73
+ expect(mappingError({})).toBe('Elige la columna de fecha.')
74
+ expect(mappingError({ date: 'Fecha' })).toContain('abonos')
75
+ expect(mappingError({ date: 'Fecha', credit: 'Fecha' })).toContain('dos campos')
76
+ expect(mappingError({ date: 'Fecha', amount: 'Monto', description: '' })).toBeNull()
77
+ })
78
+
79
+ it('previsualiza la aplicación: parcial, varias facturas y saldo a favor', () => {
80
+ const invoices = [{ id: 'a', balance: 119000 }, { id: 'b', balance: 119000 }]
81
+ expect(allocationPreview(200000, invoices, ['a', 'b'])).toEqual({
82
+ rows: [{ id: 'a', applied: 119000, remaining: 0 }, { id: 'b', applied: 81000, remaining: 38000 }], credit: 0,
83
+ })
84
+ expect(allocationPreview(200000, invoices, ['a']).credit).toBe(81000)
85
+ expect(allocationPreview(50000, invoices, ['b', 'a']).rows).toEqual([{ id: 'b', applied: 50000, remaining: 69000 }, { id: 'a', applied: 0, remaining: 119000 }])
86
+ })
87
+
88
+ it('etiqueta estados, razones y puntajes', () => {
89
+ expect(transactionStatus('suggested').label).toBe('Con sugerencia')
90
+ expect(importStatus('failed').severity).toBe('danger')
91
+ expect(matchReasonLabel('tax_id_in_text')).toBe('RUT en la glosa')
92
+ expect(scoreSeverity(90)).toBe('success')
93
+ expect(scoreSeverity(65)).toBe('info')
94
+ expect(scoreSeverity(40)).toBe('warning')
95
+ })
96
+ })
97
+
98
+ describe('cobranza: estado de cuenta, reportes y recordatorios', () => {
99
+ it('formatea celdas de reportes', () => {
100
+ expect(reportCell('total', 238000)).toBe('$ 238.000')
101
+ expect(reportCell('d31_60', 0)).toBe('$ 0')
102
+ expect(reportCell('invoices', 1200)).toBe('1.200')
103
+ expect(reportCell('due_at', '2026-12-31')).toBe('31-12-2026')
104
+ expect(reportCell('label', null)).toBe('—')
105
+ expect(isNumericColumn('balance')).toBe(true)
106
+ expect(isNumericColumn('client')).toBe(false)
107
+ })
108
+
109
+ it('lee los días de recordatorio', () => {
110
+ expect(parseReminderDays('3, 7,7')).toEqual([7, 3])
111
+ expect(parseReminderDays('')).toEqual([])
112
+ expect(parseReminderDays('7;3')).toBeNull()
113
+ })
114
+
115
+ it('rango del año y etiquetas', () => {
116
+ expect(yearToDate(new Date(2026, 10, 19))).toEqual({ from: '2026-01-01', to: '2026-11-19' })
117
+ expect(activityLabel('bank_transaction', 'auto_matched')).toBe('Movimiento bancario conciliado automáticamente')
118
+ expect(movementLabel('credit_note')).toBe('Nota de crédito')
119
+ })
120
+ })