@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.
- package/components/Billing/AccountStatement.vue +121 -0
- package/components/Billing/ActivityLog.vue +44 -0
- package/components/Billing/Adjustments.vue +169 -0
- package/components/Billing/ClientTerms.vue +70 -0
- package/components/Billing/CreditNoteForm.vue +82 -0
- package/components/Billing/Invoices.vue +128 -5
- package/components/Billing/Overview.vue +7 -1
- package/components/Billing/Reconciliation.vue +309 -0
- package/components/Billing/Reports.vue +87 -0
- package/components/Billing/Settings.vue +45 -12
- package/components/Billing/__tests__/sfc-compile.test.ts +4 -1
- package/composables/useAiUsage/internal/aiUsage.ts +1 -0
- package/composables/useBilling/index.ts +113 -3
- package/composables/useBilling/internal/__tests__/collections.test.ts +120 -0
- package/composables/useBilling/internal/billing.ts +323 -0
- package/docs/billing.md +42 -7
- package/package.json +1 -1
|
@@ -82,6 +82,14 @@ export interface Invoice {
|
|
|
82
82
|
due_at: string | null
|
|
83
83
|
paid_at: string | null
|
|
84
84
|
sent_at: string | null
|
|
85
|
+
voided_at?: string | null
|
|
86
|
+
void_reason?: string | null
|
|
87
|
+
replaces_invoice_id?: string | null
|
|
88
|
+
replaced_by_invoice_id?: string | null
|
|
89
|
+
late_fees_waived_at?: string | null
|
|
90
|
+
billing_data?: Record<string, string | null> | null
|
|
91
|
+
late_fees?: LateFee[]
|
|
92
|
+
credit_notes?: Adjustment[]
|
|
85
93
|
space_part?: number
|
|
86
94
|
statements?: Statement[]
|
|
87
95
|
events?: { event: string; user_id: string | null; data: any; created_at: string }[]
|
|
@@ -210,6 +218,8 @@ export function eventLabel(event: string): string {
|
|
|
210
218
|
created: 'Creada', statement_added: 'Cobro agregado', issued: 'Emitida', sent: 'Enviada por correo',
|
|
211
219
|
payment_applied: 'Pago aplicado', credit: 'Saldo a favor aplicado', overdue: 'Vencida',
|
|
212
220
|
payment_link_created: 'Enlace de pago creado', voided: 'Anulada', reissued: 'Refacturada',
|
|
221
|
+
credit_note: 'Nota de crédito', late_fee_waived: 'Interés condonado', reminder_sent: 'Recordatorio enviado',
|
|
222
|
+
payment_released: 'Pago liberado (saldo a favor)', payment_reversed: 'Pago revertido',
|
|
213
223
|
} as Record<string, string>)[event] ?? event
|
|
214
224
|
}
|
|
215
225
|
|
|
@@ -262,3 +272,316 @@ export function planPayload(form: Omit<Plan, 'id'>, catalog: MeterDefinition[]):
|
|
|
262
272
|
export function errorMessage(e: any, fallback: string): string {
|
|
263
273
|
return e?.data?.message ?? (e?.data?.errors ? (Object.values(e.data.errors).flat()[0] as string) : null) ?? fallback
|
|
264
274
|
}
|
|
275
|
+
|
|
276
|
+
// ── Collections (stage 3) ────────────────────────────────────────────────────
|
|
277
|
+
|
|
278
|
+
export type AdjustmentType = 'discount' | 'surcharge' | 'one_off' | 'credit'
|
|
279
|
+
export type CreditNoteTarget = 'invoice' | 'balance' | 'next_period'
|
|
280
|
+
|
|
281
|
+
export interface Adjustment {
|
|
282
|
+
id: string
|
|
283
|
+
number: number | null
|
|
284
|
+
display_number: string | null
|
|
285
|
+
credit_note: boolean
|
|
286
|
+
tenant_id: string | null
|
|
287
|
+
client_id: string | null
|
|
288
|
+
scope: 'space' | 'client'
|
|
289
|
+
type: AdjustmentType
|
|
290
|
+
amount: number | null
|
|
291
|
+
percent: number | null
|
|
292
|
+
recurring: boolean
|
|
293
|
+
starts_at: string | null
|
|
294
|
+
ends_at: string | null
|
|
295
|
+
reason: string
|
|
296
|
+
target: CreditNoteTarget | null
|
|
297
|
+
invoice_id: string | null
|
|
298
|
+
created_by: string | null
|
|
299
|
+
created_at: string | null
|
|
300
|
+
canceled_at: string | null
|
|
301
|
+
cancel_reason: string | null
|
|
302
|
+
status: 'pending' | 'applied' | 'canceled'
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export interface LateFee { tenant_id: string; from: string; to: string; days: number; base: number; rate: number; amount: number; waived_at: string | null; waive_reason: string | null }
|
|
306
|
+
|
|
307
|
+
export const ADJUSTMENT_TYPES: { value: AdjustmentType; label: string }[] = [
|
|
308
|
+
{ value: 'discount', label: 'Descuento' },
|
|
309
|
+
{ value: 'surcharge', label: 'Recargo' },
|
|
310
|
+
{ value: 'one_off', label: 'Cargo único' },
|
|
311
|
+
{ value: 'credit', label: 'Crédito' },
|
|
312
|
+
]
|
|
313
|
+
|
|
314
|
+
export const CREDIT_NOTE_TARGETS: { value: CreditNoteTarget; label: string; hint: string }[] = [
|
|
315
|
+
{ value: 'invoice', label: 'A una factura abierta', hint: 'Monto con IVA. Baja el saldo de la factura; lo que sobre queda a favor del cliente.' },
|
|
316
|
+
{ value: 'balance', label: 'Saldo a favor del cliente', hint: 'Monto con IVA. Se descuenta de la próxima factura que se emita.' },
|
|
317
|
+
{ value: 'next_period', label: 'Próximo cobro del espacio', hint: 'Monto neto (antes de IVA). Entra como línea en el próximo cierre.' },
|
|
318
|
+
]
|
|
319
|
+
|
|
320
|
+
export function adjustmentTypeLabel(type: string): string {
|
|
321
|
+
return ADJUSTMENT_TYPES.find(t => t.value === type)?.label ?? type
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** "- $ 10.000" / "+ 15 %" with the sign of the type (discounts and credits reduce). */
|
|
325
|
+
export function adjustmentValue(a: Pick<Adjustment, 'type' | 'amount' | 'percent'>): string {
|
|
326
|
+
const sign = a.type === 'discount' || a.type === 'credit' ? '-' : '+'
|
|
327
|
+
if (a.percent !== null && a.percent !== undefined) return `${sign} ${Number(a.percent).toLocaleString('es-CL')} %`
|
|
328
|
+
return `${sign} ${formatMoney(a.amount ?? 0)}`
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function adjustmentStatus(status: string): { label: string; severity: Severity } {
|
|
332
|
+
return ({
|
|
333
|
+
pending: { label: 'Pendiente', severity: 'info' },
|
|
334
|
+
applied: { label: 'Aplicado', severity: 'success' },
|
|
335
|
+
canceled: { label: 'Anulado', severity: 'secondary' },
|
|
336
|
+
} as Record<string, { label: string; severity: Severity }>)[status] ?? { label: status, severity: 'secondary' }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export interface AdjustmentForm {
|
|
340
|
+
scope: 'space' | 'client'
|
|
341
|
+
tenant_key: string
|
|
342
|
+
type: AdjustmentType
|
|
343
|
+
mode: 'amount' | 'percent'
|
|
344
|
+
value: string | number
|
|
345
|
+
recurring: boolean
|
|
346
|
+
starts_at: string
|
|
347
|
+
ends_at: string
|
|
348
|
+
reason: string
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Adjustment form → payload, or the first error (client scope: percent discounts/surcharges only). */
|
|
352
|
+
export function adjustmentPayload(form: AdjustmentForm, clientId: string | null): { payload?: Record<string, any>; error?: string } {
|
|
353
|
+
if (!form.reason.trim()) return { error: 'El motivo es obligatorio.' }
|
|
354
|
+
if (form.scope === 'client') {
|
|
355
|
+
if (!clientId) return { error: 'Falta el cliente.' }
|
|
356
|
+
if (form.mode !== 'percent' || !['discount', 'surcharge'].includes(form.type)) return { error: 'A nivel de cliente solo se admiten descuentos o recargos porcentuales.' }
|
|
357
|
+
} else if (!form.tenant_key) {
|
|
358
|
+
return { error: 'Elige el espacio.' }
|
|
359
|
+
}
|
|
360
|
+
const n = form.mode === 'percent' ? Number(String(form.value).replace(',', '.')) : parseMoney(form.value)
|
|
361
|
+
if (n === null || Number.isNaN(n) || n <= 0 || (form.mode === 'percent' && n > 100)) return { error: form.mode === 'percent' ? 'Ingresa un porcentaje entre 0 y 100.' : 'Ingresa un monto válido.' }
|
|
362
|
+
if (form.starts_at && form.ends_at && form.ends_at < form.starts_at) return { error: 'La vigencia termina antes de empezar.' }
|
|
363
|
+
const once = form.type === 'one_off' || form.type === 'credit'
|
|
364
|
+
return {
|
|
365
|
+
payload: {
|
|
366
|
+
...(form.scope === 'client' ? { client_id: clientId } : { tenant_key: form.tenant_key }),
|
|
367
|
+
type: form.type,
|
|
368
|
+
[form.mode]: form.mode === 'percent' ? n : Math.round(n),
|
|
369
|
+
recurring: once ? false : !!form.recurring,
|
|
370
|
+
starts_at: form.starts_at || null,
|
|
371
|
+
ends_at: once ? null : (form.ends_at || null),
|
|
372
|
+
reason: form.reason.trim(),
|
|
373
|
+
},
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export interface CreditNoteForm { target: CreditNoteTarget; amount: string | number; reason: string; invoice_id: string; tenant_key: string }
|
|
378
|
+
|
|
379
|
+
export function creditNotePayload(form: CreditNoteForm, clientId: string): { payload?: Record<string, any>; error?: string } {
|
|
380
|
+
const amount = parseMoney(form.amount)
|
|
381
|
+
if (!amount || Number.isNaN(amount) || amount <= 0) return { error: 'Ingresa un monto válido.' }
|
|
382
|
+
if (!form.reason.trim()) return { error: 'El motivo es obligatorio.' }
|
|
383
|
+
if (form.target === 'invoice' && !form.invoice_id) return { error: 'Elige la factura.' }
|
|
384
|
+
if (form.target === 'next_period' && !form.tenant_key) return { error: 'Elige el espacio.' }
|
|
385
|
+
return {
|
|
386
|
+
payload: {
|
|
387
|
+
client_id: clientId, amount, reason: form.reason.trim(), target: form.target,
|
|
388
|
+
invoice_id: form.target === 'invoice' ? form.invoice_id : null,
|
|
389
|
+
tenant_key: form.target === 'next_period' ? form.tenant_key : null,
|
|
390
|
+
},
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export interface CorrectionLine { description: string; amount: string | number; tenant_key?: string }
|
|
395
|
+
|
|
396
|
+
/** Reissue form → payload: only changed billing fields, correction lines with a non-zero signed amount. */
|
|
397
|
+
export function reissuePayload(form: { reason: string; billing_data: Record<string, string>; original: Record<string, string | null>; lines: CorrectionLine[]; due_at: string; send: boolean }):
|
|
398
|
+
{ payload?: Record<string, any>; error?: string } {
|
|
399
|
+
if (!form.reason.trim()) return { error: 'El motivo es obligatorio.' }
|
|
400
|
+
const billing: Record<string, string> = {}
|
|
401
|
+
for (const [k, v] of Object.entries(form.billing_data)) {
|
|
402
|
+
if ((v ?? '') !== (form.original[k] ?? '')) billing[k] = v
|
|
403
|
+
}
|
|
404
|
+
const lines = []
|
|
405
|
+
for (const l of form.lines) {
|
|
406
|
+
if (!l.description?.trim() && (l.amount === '' || l.amount === null || l.amount === undefined)) continue
|
|
407
|
+
const raw = String(l.amount ?? '').trim()
|
|
408
|
+
const negative = raw.startsWith('-')
|
|
409
|
+
const n = parseMoney(raw.replace(/^-/, ''))
|
|
410
|
+
if (!l.description?.trim() || n === null || Number.isNaN(n) || n === 0) return { error: 'Cada corrección necesita descripción y un monto distinto de cero.' }
|
|
411
|
+
lines.push({ description: l.description.trim(), amount: negative ? -n : n, tenant_key: l.tenant_key || null })
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
payload: {
|
|
415
|
+
reason: form.reason.trim(),
|
|
416
|
+
billing_data: Object.keys(billing).length ? billing : null,
|
|
417
|
+
lines,
|
|
418
|
+
due_at: form.due_at || null,
|
|
419
|
+
send: form.send,
|
|
420
|
+
},
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export const BILLING_FIELDS: { key: string; label: string }[] = [
|
|
425
|
+
{ key: 'legal_name', label: 'Razón social' },
|
|
426
|
+
{ key: 'tax_id', label: 'RUT' },
|
|
427
|
+
{ key: 'business_activity', label: 'Giro' },
|
|
428
|
+
{ key: 'address', label: 'Dirección' },
|
|
429
|
+
{ key: 'billing_email', label: 'Correo de facturación' },
|
|
430
|
+
]
|
|
431
|
+
|
|
432
|
+
// ── Reconciliation ───────────────────────────────────────────────────────────
|
|
433
|
+
|
|
434
|
+
export type TransactionStatus = 'unmatched' | 'suggested' | 'matched' | 'ignored'
|
|
435
|
+
|
|
436
|
+
export interface Suggestion { client_id: string; client_name: string; invoice_ids: string[]; invoices: string[]; amount: number; score: number; reasons: string[] }
|
|
437
|
+
|
|
438
|
+
export interface BankTransaction {
|
|
439
|
+
id: string
|
|
440
|
+
import_id: string
|
|
441
|
+
posted_at: string
|
|
442
|
+
amount: number
|
|
443
|
+
description: string | null
|
|
444
|
+
reference: string | null
|
|
445
|
+
tax_id: string | null
|
|
446
|
+
counterpart_name: string | null
|
|
447
|
+
status: TransactionStatus
|
|
448
|
+
score: number | null
|
|
449
|
+
suggestions: Suggestion[]
|
|
450
|
+
client_id: string | null
|
|
451
|
+
client_name: string | null
|
|
452
|
+
payment_id: string | null
|
|
453
|
+
matched_by: string | null
|
|
454
|
+
matched_at: string | null
|
|
455
|
+
ignore_reason: string | null
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export const BANK_FIELDS: { key: string; label: string; hint?: string }[] = [
|
|
459
|
+
{ key: 'date', label: 'Fecha', hint: 'obligatoria' },
|
|
460
|
+
{ key: 'credit', label: 'Abonos', hint: 'o "Monto"' },
|
|
461
|
+
{ key: 'debit', label: 'Cargos', hint: 'opcional' },
|
|
462
|
+
{ key: 'amount', label: 'Monto (con signo)', hint: 'si no hay abonos/cargos' },
|
|
463
|
+
{ key: 'description', label: 'Descripción / glosa' },
|
|
464
|
+
{ key: 'reference', label: 'N° de documento / referencia' },
|
|
465
|
+
{ key: 'tax_id', label: 'RUT de origen' },
|
|
466
|
+
{ key: 'name', label: 'Nombre de origen' },
|
|
467
|
+
]
|
|
468
|
+
|
|
469
|
+
/** null when the mapping can be imported; otherwise the problem. */
|
|
470
|
+
export function mappingError(mapping: Record<string, string | null | undefined>): string | null {
|
|
471
|
+
if (!mapping.date) return 'Elige la columna de fecha.'
|
|
472
|
+
if (!mapping.credit && !mapping.amount) return 'Elige la columna de abonos o la de monto.'
|
|
473
|
+
const used = Object.values(mapping).filter(Boolean)
|
|
474
|
+
if (new Set(used).size !== used.length) return 'Una columna está asignada a dos campos.'
|
|
475
|
+
return null
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export function transactionStatus(status: string): { label: string; severity: Severity } {
|
|
479
|
+
return ({
|
|
480
|
+
unmatched: { label: 'Sin emparejar', severity: 'warning' },
|
|
481
|
+
suggested: { label: 'Con sugerencia', severity: 'info' },
|
|
482
|
+
matched: { label: 'Conciliado', severity: 'success' },
|
|
483
|
+
ignored: { label: 'Descartado', severity: 'secondary' },
|
|
484
|
+
} as Record<string, { label: string; severity: Severity }>)[status] ?? { label: status, severity: 'secondary' }
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export function importStatus(status: string): { label: string; severity: Severity } {
|
|
488
|
+
return ({
|
|
489
|
+
pending: { label: 'En cola', severity: 'secondary' },
|
|
490
|
+
processing: { label: 'Procesando', severity: 'info' },
|
|
491
|
+
done: { label: 'Lista', severity: 'success' },
|
|
492
|
+
failed: { label: 'Con error', severity: 'danger' },
|
|
493
|
+
} as Record<string, { label: string; severity: Severity }>)[status] ?? { label: status, severity: 'secondary' }
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
export function matchReasonLabel(reason: string): string {
|
|
497
|
+
return ({
|
|
498
|
+
tax_id: 'RUT', tax_id_in_text: 'RUT en la glosa', reference: 'N° de factura', name: 'Nombre',
|
|
499
|
+
amount_exact: 'Monto exacto', amount_sum: 'Suma de facturas', amount_total: 'Total de la factura', partial: 'Pago parcial',
|
|
500
|
+
} as Record<string, string>)[reason] ?? reason
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
export function scoreSeverity(score: number | null | undefined): Severity {
|
|
504
|
+
if (!score) return 'secondary'
|
|
505
|
+
return score >= 85 ? 'success' : score >= 60 ? 'info' : 'warning'
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** How a movement would be applied to the chosen invoices, in order; what is left becomes client credit. */
|
|
509
|
+
export function allocationPreview(amount: number, invoices: { id: string; balance: number }[], selected: string[]):
|
|
510
|
+
{ rows: { id: string; applied: number; remaining: number }[]; credit: number } {
|
|
511
|
+
let left = Math.max(0, Math.round(amount))
|
|
512
|
+
const rows = []
|
|
513
|
+
for (const id of selected) {
|
|
514
|
+
const inv = invoices.find(i => i.id === id)
|
|
515
|
+
if (!inv) continue
|
|
516
|
+
const applied = Math.min(left, inv.balance)
|
|
517
|
+
left -= applied
|
|
518
|
+
rows.push({ id, applied, remaining: inv.balance - applied })
|
|
519
|
+
}
|
|
520
|
+
return { rows, credit: left }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// ── Account statement, reports, reminders ─────────────────────────────────
|
|
524
|
+
|
|
525
|
+
export const AGING_BUCKETS: { key: string; label: string }[] = [
|
|
526
|
+
{ key: 'current', label: 'Por vencer' },
|
|
527
|
+
{ key: 'd0_30', label: '0–30 días' },
|
|
528
|
+
{ key: 'd31_60', label: '31–60 días' },
|
|
529
|
+
{ key: 'd61_90', label: '61–90 días' },
|
|
530
|
+
{ key: 'd90_plus', label: 'Más de 90 días' },
|
|
531
|
+
]
|
|
532
|
+
|
|
533
|
+
export function movementLabel(type: string): string {
|
|
534
|
+
return ({ invoice: 'Factura', payment: 'Pago', credit_note: 'Nota de crédito', void: 'Anulación' } as Record<string, string>)[type] ?? type
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export const REPORTS: { key: string; label: string; dated: boolean; groups: { value: string; label: string }[] }[] = [
|
|
538
|
+
{ key: 'revenue', label: 'Ingresos', dated: true, groups: [{ value: 'month', label: 'Mes' }, { value: 'client', label: 'Cliente' }, { value: 'plan', label: 'Plan' }, { value: 'product', label: 'Producto' }] },
|
|
539
|
+
{ key: 'receivables', label: 'Cuentas por cobrar', dated: false, groups: [] },
|
|
540
|
+
{ key: 'aging', label: 'Antigüedad de deuda', dated: false, groups: [] },
|
|
541
|
+
{ key: 'collections', label: 'Recaudación', dated: true, groups: [{ value: 'month', label: 'Mes' }, { value: 'method', label: 'Medio de pago' }, { value: 'client', label: 'Cliente' }] },
|
|
542
|
+
{ key: 'mrr', label: 'MRR', dated: false, groups: [{ value: 'client', label: 'Cliente' }, { value: 'plan', label: 'Plan' }, { value: 'product', label: 'Producto' }] },
|
|
543
|
+
{ key: 'usage', label: 'Consumo', dated: true, groups: [] },
|
|
544
|
+
]
|
|
545
|
+
|
|
546
|
+
const MONEY_COLUMNS = new Set(['subtotal', 'tax', 'total', 'balance', 'amount', 'credit', 'mrr', 'cost', 'current', 'd0_30', 'd31_60', 'd61_90', 'd90_plus'])
|
|
547
|
+
|
|
548
|
+
/** Cell text of a report: money columns as pesos, numbers with es-CL separators. */
|
|
549
|
+
export function reportCell(column: string, value: any): string {
|
|
550
|
+
if (value === null || value === undefined || value === '') return '—'
|
|
551
|
+
if (MONEY_COLUMNS.has(column) && typeof value === 'number') return formatMoney(value)
|
|
552
|
+
if (typeof value === 'number') return value.toLocaleString('es-CL', { maximumFractionDigits: 4 })
|
|
553
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(String(value))) return formatDate(String(value))
|
|
554
|
+
return String(value)
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
export function isNumericColumn(column: string): boolean {
|
|
558
|
+
return MONEY_COLUMNS.has(column) || ['invoices', 'payments', 'spaces', 'quantity', 'records', 'days_overdue'].includes(column)
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** "7, 3" → [7, 3] (descending, unique, 1–60); null when invalid. */
|
|
562
|
+
export function parseReminderDays(raw: string | null | undefined): number[] | null {
|
|
563
|
+
const text = String(raw ?? '').trim()
|
|
564
|
+
if (!text) return []
|
|
565
|
+
if (!/^\d{1,2}(\s*,\s*\d{1,2})*$/.test(text)) return null
|
|
566
|
+
const days = [...new Set(text.split(',').map(d => Number(d.trim())))].filter(d => d > 0 && d <= 60)
|
|
567
|
+
return days.sort((a, b) => b - a)
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** Default date range: from the first day of the current year to today (YYYY-MM-DD, local). */
|
|
571
|
+
export function yearToDate(now = new Date()): { from: string; to: string } {
|
|
572
|
+
const pad = (n: number) => String(n).padStart(2, '0')
|
|
573
|
+
return { from: `${now.getFullYear()}-01-01`, to: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}` }
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export function activityLabel(subject: string, action: string): string {
|
|
577
|
+
const subjects: Record<string, string> = {
|
|
578
|
+
adjustment: 'Ajuste', credit_note: 'Nota de crédito', invoice: 'Factura', terms: 'Condiciones de cobranza',
|
|
579
|
+
bank_import: 'Cartola', bank_transaction: 'Movimiento bancario', late_fee: 'Interés por mora', credit: 'Saldo a favor',
|
|
580
|
+
}
|
|
581
|
+
const actions: Record<string, string> = {
|
|
582
|
+
created: 'creado', canceled: 'anulado', voided: 'anulada', reissued: 'refacturada', updated: 'actualizadas',
|
|
583
|
+
processed: 'importada', matched: 'conciliado a mano', auto_matched: 'conciliado automáticamente', unmatched: 'desconciliado',
|
|
584
|
+
ignored: 'descartado', restored: 'restaurado', waived: 'condonado', applied: 'aplicado',
|
|
585
|
+
}
|
|
586
|
+
return `${subjects[subject] ?? subject} ${actions[action] ?? action}`
|
|
587
|
+
}
|
package/docs/billing.md
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
# Facturación (Billing) — componentes
|
|
2
2
|
|
|
3
3
|
Front de `Innertia\Billing` (innertia-laravel): planes, suscripción por espacio, consumo medido,
|
|
4
|
-
cierre mensual, facturas (por espacio o consolidadas por cliente), pagos, mora y suspensión
|
|
4
|
+
cierre mensual, facturas (por espacio o consolidadas por cliente), pagos, mora y suspensión, y la
|
|
5
|
+
cobranza (etapa 3): ajustes y notas de crédito, interés por mora, refacturación con bitácora,
|
|
6
|
+
conciliación de cartolas, saldo a favor, estado de cuenta, recordatorios y reportes.
|
|
5
7
|
La lógica vive en el backend; estos componentes solo muestran y llaman a sus endpoints.
|
|
6
8
|
|
|
7
9
|
Montos: enteros en pesos (CLP sin decimales). Fechas de período: fechas locales de Chile
|
|
@@ -33,6 +35,13 @@ Activar el feature en el backend: ver `docs/billing.md` de innertia-laravel.
|
|
|
33
35
|
| `/platform/billing/settings` | `<Billing.Settings />` (solo owner) | `canRun` |
|
|
34
36
|
| Detalle del espacio (pestaña Suscripción) | `<Billing.SpaceSubscription :space-key="key" :can-edit="isOwner" />` | `spaceKey` (obligatoria) |
|
|
35
37
|
| Detalle del cliente (pestaña Facturas) | `<Billing.Invoices :client-id="client.id" />` | |
|
|
38
|
+
| Detalle del cliente (pestaña Ajustes) | `<Billing.Adjustments :client-id="client.id" :spaces="[{ value: key, label: name }]" />` | `spaceKey` (en el detalle del espacio), `canEdit` |
|
|
39
|
+
| Detalle del cliente (pestaña Estado de cuenta) | `<Billing.AccountStatement :client-id="client.id" />` | `spaceKey`, `canEdit` |
|
|
40
|
+
| Detalle del cliente (pestaña Cobranza) | `<Billing.ClientTerms :client-id="client.id" />` | `canEdit` |
|
|
41
|
+
| Detalle del cliente (pestaña Bitácora) | `<Billing.ActivityLog :client-id="client.id" :users="{ id: nombre }" />` | |
|
|
42
|
+
| `/platform/billing/reconciliation` | `<Billing.Reconciliation :can-edit="isOwner" />` | `canEdit` |
|
|
43
|
+
| `/platform/billing/reports` | `<Billing.Reports />` | `initial` (revenue, receivables, aging, collections, mrr, usage) |
|
|
44
|
+
| Cualquier lugar | `<Billing.CreditNoteForm v-model="open" :client-id="id" :invoice="factura?" :spaces="…" @created="…" />` | modal |
|
|
36
45
|
|
|
37
46
|
- **Invoices**: filtros por estado y cliente, detalle con los cobros por espacio y sus líneas, bitácora,
|
|
38
47
|
**Emitir** (folio SII opcional, envío por correo con el PDF), **Reenviar**, **PDF** y **Registrar pago**
|
|
@@ -41,8 +50,27 @@ Activar el feature en el backend: ver `docs/billing.md` de innertia-laravel.
|
|
|
41
50
|
prueba, precio base y por usuario negociados), editar (el cambio de plan rige desde el próximo período),
|
|
42
51
|
suspender, reactivar y cancelar; consumo del período con total estimado y los cobros cerrados.
|
|
43
52
|
Los espacios de pruebas muestran un aviso (nunca se cobran).
|
|
44
|
-
- **
|
|
45
|
-
|
|
53
|
+
- **Invoices** (cobranza): en el detalle, **Anular** (motivo; lo pagado queda a favor), **Refacturar**
|
|
54
|
+
(anula y emite otra: corrige datos de facturación, agrega líneas de corrección netas con signo, nuevo
|
|
55
|
+
vencimiento opcional; los pagos pasan a la nueva), **Nota de crédito** y **Condonar interés**. Muestra
|
|
56
|
+
notas de crédito, tramos de interés por mora y la bitácora con motivo y diferencias.
|
|
57
|
+
- **Settings**: tipo de cambio USD→CLP (valoriza la IA), datos para transferencia y emisor del PDF,
|
|
58
|
+
recordatorios de pago (días antes, día del vencimiento, cada N días vencida, máximo, escalamiento con
|
|
59
|
+
correo de cobranza); botones para ejecutar a mano el cierre, la mora y los recordatorios.
|
|
60
|
+
- **Adjustments**: descuentos, recargos, cargos únicos y créditos por espacio (monto neto o %; recurrentes
|
|
61
|
+
con vigencia o de una vez) o del cliente completo (solo %); motivo obligatorio; anular pendientes;
|
|
62
|
+
notas de crédito (botón que abre `CreditNoteForm`).
|
|
63
|
+
- **CreditNoteForm**: destino factura abierta (con IVA), saldo a favor o próximo cobro del espacio (neto).
|
|
64
|
+
- **ClientTerms**: interés por mora (%, base mensual o diaria, tope, exención) y recordatorios del cliente.
|
|
65
|
+
- **AccountStatement**: cargos, abonos y saldo corrido con rango de fechas (saldo inicial), saldo a favor
|
|
66
|
+
(botón **Aplicar saldo a favor**), antigüedad de la deuda (por vencer, 0–30, 31–60, 61–90, +90) y Excel.
|
|
67
|
+
- **Reconciliation**: **Importar cartola** (CSV o XLSX; vista previa, fila de encabezados y mapeo de
|
|
68
|
+
columnas sugerido o el último usado), la importación corre en cola y concilia sola lo claro; la tabla
|
|
69
|
+
muestra sugerencias con puntaje y razones (**Aplicar**), **Emparejar** a mano (cliente + facturas en
|
|
70
|
+
orden, con vista de lo que se aplica y el saldo a favor que queda), **Deshacer**, **Descartar**/**Restaurar**
|
|
71
|
+
y **Revisar de nuevo**. Importar la misma cartola no duplica.
|
|
72
|
+
- **Reports**: ingresos, cuentas por cobrar, antigüedad, recaudación, MRR y consumo; rango, agrupación y Excel.
|
|
73
|
+
- **ActivityLog**: bitácora de cobranza del cliente (quién, qué, motivo, monto).
|
|
46
74
|
|
|
47
75
|
## 3. Backoffice
|
|
48
76
|
|
|
@@ -56,8 +84,9 @@ Activar el feature en el backend: ver `docs/billing.md` de innertia-laravel.
|
|
|
56
84
|
|
|
57
85
|
- **Overview**: plan y estado, total estimado del período, saldo pendiente y vencido, consumo por
|
|
58
86
|
medidor frente a lo incluido (barra de progreso), facturas con PDF y botón **Pagar** cuando hay enlace,
|
|
59
|
-
la parte del espacio en facturas consolidadas, y
|
|
60
|
-
"
|
|
87
|
+
la parte del espacio en facturas consolidadas, pagos y el **estado de cuenta** del espacio
|
|
88
|
+
(`<Billing.AccountStatement mode="space" />`, se apaga con `:show-account="false"`). Espacio de
|
|
89
|
+
pruebas: solo la franja "Espacio de pruebas".
|
|
61
90
|
- **StatusBanner**: se muestra con `past_due` ("Tienes facturas vencidas") o `suspended` ("Espacio en
|
|
62
91
|
solo lectura"). Pásale `status` (por ejemplo desde el header `X-Billing-Status` que pone el
|
|
63
92
|
middleware `billing.enforce`) o deja que consulte `billing/overview` (requiere `billing.view`; si
|
|
@@ -68,8 +97,14 @@ Activar el feature en el backend: ver `docs/billing.md` de innertia-laravel.
|
|
|
68
97
|
|
|
69
98
|
- `useBillingPlatform({ base })` → `plans`, `meters`, `savePlan`, `invoices(filtersRef)`, `invoice(id)`,
|
|
70
99
|
`issue`, `resend`, `registerPayment`, `space(keyRef)`, `startSubscription`, `updateSubscription`,
|
|
71
|
-
`subscriptionAction`, `clientTotals`, `settings`, `saveSettings`, `run
|
|
72
|
-
|
|
100
|
+
`subscriptionAction`, `clientTotals`, `settings`, `saveSettings`, `run` (`close|dunning|reminders`) y de
|
|
101
|
+
cobranza `adjustments(filtersRef)`, `createAdjustment`, `cancelAdjustment`, `createCreditNote`,
|
|
102
|
+
`terms(clientIdRef)`, `saveTerms`, `applyCredit`, `account(clientIdRef, paramsRef)`, `activity(filtersRef)`,
|
|
103
|
+
`voidInvoice`, `reissue`, `waiveLateFees`, `preview(file, headerRow?)`, `importStatement`, `imports`
|
|
104
|
+
(se refresca solo mientras hay importaciones en curso), `transactions(filtersRef)`, `openInvoices(params)`,
|
|
105
|
+
`match`, `unmatch`, `ignore`, `restore`, `rematch`, `report(nameRef, paramsRef)`.
|
|
106
|
+
- `useBillingSpace({ base })` → `overview`, `invoices`, `payments`, `account(paramsRef)` (backoffice).
|
|
73
107
|
- `useBillingPdf()` → `(path, filename) => Promise` descarga un PDF con la sesión.
|
|
108
|
+
- `useBillingDownload()` → `(path, filename, params?) => Promise` descarga un Excel (reportes, estado de cuenta).
|
|
74
109
|
- Helpers puros (formato de pesos, estados, períodos, progreso de consumo) en
|
|
75
110
|
`composables/useBilling/internal/billing.ts`.
|