@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,587 @@
1
+ /**
2
+ * Pure helpers for the billing screens (no Nuxt/Vue: testable in node).
3
+ * Backend: innertia-laravel \Innertia\Billing\Routes (platform + backoffice).
4
+ * Money arrives as integers in the currency minor unit (CLP = pesos, no decimals).
5
+ */
6
+
7
+ export type Severity = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info'
8
+ export type InvoiceStatus = 'draft' | 'issued' | 'paid' | 'overdue' | 'void'
9
+ export type SubscriptionStatus = 'trialing' | 'active' | 'past_due' | 'suspended' | 'canceled'
10
+
11
+ export interface PlanMeter {
12
+ meter: string
13
+ label?: string
14
+ unit?: string | null
15
+ valued_by_cost?: boolean
16
+ included_quantity: number
17
+ unit_price: number
18
+ markup_percent: number | null
19
+ }
20
+
21
+ export interface Plan {
22
+ id: string
23
+ key: string
24
+ name: string
25
+ description?: string | null
26
+ product?: string | null
27
+ currency: string
28
+ interval: 'monthly' | 'annual'
29
+ base_price: number
30
+ included_seats: number
31
+ seat_price: number
32
+ trial_days: number
33
+ tax_rate: number
34
+ limits?: Record<string, any>
35
+ active: boolean
36
+ meters: PlanMeter[]
37
+ }
38
+
39
+ export interface MeterDefinition { key: string; label: string; unit: string; aggregation: 'sum' | 'max'; valued_by_cost: boolean; description?: string }
40
+
41
+ export interface Subscription {
42
+ id: string
43
+ tenant_id: string
44
+ status: SubscriptionStatus
45
+ status_label: string
46
+ plan: { id: string; key: string; name: string } | null
47
+ pending_plan: { id: string; key: string; name: string } | null
48
+ payment_method: 'automatic' | 'invoice'
49
+ overrides: Record<string, any>
50
+ started_at: string | null
51
+ trial_ends_at: string | null
52
+ current_period_start: string
53
+ current_period_end: string
54
+ suspended_manually: boolean
55
+ }
56
+
57
+ export interface StatementLine { kind: string; description: string; meter: string | null; quantity: number; unit_price: number; amount: number; meta?: any }
58
+ export interface Statement { id: string; tenant_id: string; tenant_name?: string | null; invoice_id: string | null; period_start: string; period_end: string; subtotal: number; tax: number; total: number; lines: StatementLine[] }
59
+
60
+ export interface Invoice {
61
+ id: string
62
+ number: number | null
63
+ display_number: string | null
64
+ client_id: string
65
+ client_name?: string | null
66
+ tenant_id: string | null
67
+ tenant_name?: string | null
68
+ consolidated: boolean
69
+ period_start: string
70
+ period_end: string
71
+ currency: string
72
+ subtotal: number
73
+ tax: number
74
+ total: number
75
+ balance: number
76
+ status: InvoiceStatus
77
+ status_label: string
78
+ payment_method: 'automatic' | 'invoice'
79
+ payment_link: string | null
80
+ folio: string | null
81
+ issued_at: string | null
82
+ due_at: string | null
83
+ paid_at: string | null
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[]
93
+ space_part?: number
94
+ statements?: Statement[]
95
+ events?: { event: string; user_id: string | null; data: any; created_at: string }[]
96
+ allocations?: { payment_id: string; amount: number; created_at: string }[]
97
+ }
98
+
99
+ export interface UsageEstimate {
100
+ meter: { key: string; label: string; unit: string; valued_by_cost: boolean }
101
+ quantity: number
102
+ cost: number
103
+ included_quantity: number
104
+ unit_price: number
105
+ markup_percent: number | null
106
+ estimated_amount: number
107
+ }
108
+
109
+ /** 152420 → "$ 152.420" (CLP); other currencies in cents → "USD 12,50". */
110
+ export function formatMoney(amount: number | null | undefined, currency = 'CLP'): string {
111
+ if (amount === null || amount === undefined) return '—'
112
+ const sign = amount < 0 ? '-' : ''
113
+ const abs = Math.abs(Math.round(amount))
114
+ if (currency === 'CLP') return `${sign}$ ${abs.toLocaleString('es-CL')}`
115
+ return `${sign}${currency} ${(abs / 100).toLocaleString('es-CL', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
116
+ }
117
+
118
+ /** Parses a typed CLP amount ("$ 1.500" / "1500") into integer pesos; null when empty, NaN when invalid. */
119
+ export function parseMoney(raw: string | number | null | undefined): number | null {
120
+ if (raw === null || raw === undefined || String(raw).trim() === '') return null
121
+ const digits = String(raw).replace(/[$\s.]/g, '').replace(',', '.')
122
+ const n = Number(digits)
123
+ return Number.isFinite(n) ? Math.round(n) : Number.NaN
124
+ }
125
+
126
+ const INVOICE_STATUS: Record<InvoiceStatus, { label: string; severity: Severity }> = {
127
+ draft: { label: 'Borrador', severity: 'secondary' },
128
+ issued: { label: 'Emitida', severity: 'info' },
129
+ paid: { label: 'Pagada', severity: 'success' },
130
+ overdue: { label: 'Vencida', severity: 'danger' },
131
+ void: { label: 'Anulada', severity: 'secondary' },
132
+ }
133
+
134
+ const SUBSCRIPTION_STATUS: Record<SubscriptionStatus, { label: string; severity: Severity }> = {
135
+ trialing: { label: 'En prueba', severity: 'info' },
136
+ active: { label: 'Al día', severity: 'success' },
137
+ past_due: { label: 'Con deuda vencida', severity: 'warning' },
138
+ suspended: { label: 'Suspendido', severity: 'danger' },
139
+ canceled: { label: 'Cancelada', severity: 'secondary' },
140
+ }
141
+
142
+ export function invoiceStatus(status: string): { label: string; severity: Severity } {
143
+ return INVOICE_STATUS[status as InvoiceStatus] ?? { label: status, severity: 'secondary' }
144
+ }
145
+
146
+ export function subscriptionStatus(status: string | null | undefined): { label: string; severity: Severity } {
147
+ if (!status) return { label: 'Sin suscripción', severity: 'secondary' }
148
+ return SUBSCRIPTION_STATUS[status as SubscriptionStatus] ?? { label: status, severity: 'secondary' }
149
+ }
150
+
151
+ export const INVOICE_STATUS_OPTIONS = (Object.keys(INVOICE_STATUS) as InvoiceStatus[]).map(value => ({ value, label: INVOICE_STATUS[value].label }))
152
+
153
+ export const PAYMENT_METHODS = [
154
+ { value: 'invoice', label: 'Factura (pago por transferencia)' },
155
+ { value: 'automatic', label: 'Automático (enlace de pago)' },
156
+ ] as const
157
+
158
+ export function paymentMethodLabel(method: string | null | undefined): string {
159
+ return method === 'automatic' ? 'Enlace de pago' : method === 'invoice' ? 'Transferencia' : (method ?? '—')
160
+ }
161
+
162
+ export function paymentChannelLabel(method: string): string {
163
+ return ({ transfer: 'Transferencia', link: 'Pago en línea', manual: 'Manual', credit: 'Saldo a favor' } as Record<string, string>)[method] ?? method
164
+ }
165
+
166
+ export function intervalLabel(interval: string): string {
167
+ return interval === 'annual' ? 'anual' : 'mensual'
168
+ }
169
+
170
+ /** 'YYYY-MM-DD' → 'DD-MM-YYYY' without time zone shifts. */
171
+ export function formatDate(date: string | null | undefined): string {
172
+ if (!date) return '—'
173
+ const [y, m, d] = date.slice(0, 10).split('-')
174
+ return d && m && y ? `${d}-${m}-${y}` : date
175
+ }
176
+
177
+ export function periodLabel(start: string | null | undefined, end: string | null | undefined): string {
178
+ if (!start || !end) return '—'
179
+ return `${formatDate(start)} al ${formatDate(end)}`
180
+ }
181
+
182
+ /** ISO timestamp → 'DD-MM-YYYY' in the given time zone (default America/Santiago). */
183
+ export function formatDateTime(iso: string | null | undefined, timeZone = 'America/Santiago'): string {
184
+ if (!iso) return '—'
185
+ const d = new Date(iso)
186
+ if (Number.isNaN(d.getTime())) return iso
187
+ const parts = new Intl.DateTimeFormat('es-CL', { timeZone, day: '2-digit', month: '2-digit', year: 'numeric' }).formatToParts(d)
188
+ const get = (t: string) => parts.find(p => p.type === t)?.value ?? ''
189
+ return `${get('day')}-${get('month')}-${get('year')}`
190
+ }
191
+
192
+ /** Consumption vs included: percent used (null when nothing included) and level. */
193
+ export function usageProgress(u: Pick<UsageEstimate, 'quantity' | 'cost' | 'included_quantity' | 'markup_percent'> & { meter: { valued_by_cost: boolean } }):
194
+ { percent: number | null; level: 'ok' | 'warning' | 'over'; over: boolean } {
195
+ const used = u.meter.valued_by_cost ? u.cost * (1 + (u.markup_percent ?? 0) / 100) : u.quantity
196
+ const included = Number(u.included_quantity ?? 0)
197
+ if (included <= 0) return { percent: null, level: used > 0 ? 'over' : 'ok', over: used > 0 }
198
+ const percent = Math.round((used / included) * 100)
199
+ return { percent, level: percent > 100 ? 'over' : percent >= 80 ? 'warning' : 'ok', over: percent > 100 }
200
+ }
201
+
202
+ /** "150 mensajes" style quantity (units from the meter catalog, AI cost in USD). */
203
+ export function formatQuantity(quantity: number, unit?: string | null): string {
204
+ if (unit === 'USD') return `US$ ${quantity.toLocaleString('es-CL', { maximumFractionDigits: 2 })}`
205
+ const n = quantity.toLocaleString('es-CL', { maximumFractionDigits: 2 })
206
+ if (!unit) return n
207
+ return `${n} ${quantity === 1 ? unit : pluralize(unit)}`
208
+ }
209
+
210
+ function pluralize(unit: string): string {
211
+ if (/[aeiouáéíóú]$/i.test(unit)) return `${unit}s`
212
+ if (/^[A-Z]+$/.test(unit)) return unit
213
+ return `${unit}es`
214
+ }
215
+
216
+ export function eventLabel(event: string): string {
217
+ return ({
218
+ created: 'Creada', statement_added: 'Cobro agregado', issued: 'Emitida', sent: 'Enviada por correo',
219
+ payment_applied: 'Pago aplicado', credit: 'Saldo a favor aplicado', overdue: 'Vencida',
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',
223
+ } as Record<string, string>)[event] ?? event
224
+ }
225
+
226
+ /** Banner of the backoffice for a subscription status (null = nothing to show). */
227
+ export function bannerFor(status: string | null | undefined): { severity: 'warning' | 'danger'; title: string; message: string } | null {
228
+ if (status === 'past_due') {
229
+ return { severity: 'warning', title: 'Tienes facturas vencidas', message: 'Regulariza el pago para evitar la suspensión del espacio.' }
230
+ }
231
+ if (status === 'suspended') {
232
+ return { severity: 'danger', title: 'Espacio en solo lectura', message: 'El espacio está suspendido por facturas vencidas. Puedes consultar y pagar desde Facturación.' }
233
+ }
234
+ return null
235
+ }
236
+
237
+ /** Empty plan form. */
238
+ export function emptyPlan(): Omit<Plan, 'id'> {
239
+ return {
240
+ key: '', name: '', description: '', product: '', currency: 'CLP', interval: 'monthly', base_price: 0,
241
+ included_seats: 0, seat_price: 0, trial_days: 0, tax_rate: 19, limits: {}, active: true, meters: [],
242
+ }
243
+ }
244
+
245
+ /** Plan form → API payload (meters cleaned: valued-by-cost meters send markup, others unit price). */
246
+ export function planPayload(form: Omit<Plan, 'id'>, catalog: MeterDefinition[]): Record<string, any> {
247
+ const byKey = new Map(catalog.map(m => [m.key, m]))
248
+ return {
249
+ key: form.key.trim(),
250
+ name: form.name.trim(),
251
+ description: form.description || null,
252
+ product: form.product || null,
253
+ interval: form.interval,
254
+ base_price: Math.max(0, Math.round(Number(form.base_price) || 0)),
255
+ included_seats: Math.max(0, Math.round(Number(form.included_seats) || 0)),
256
+ seat_price: Math.max(0, Math.round(Number(form.seat_price) || 0)),
257
+ trial_days: Math.max(0, Math.round(Number(form.trial_days) || 0)),
258
+ tax_rate: Number(form.tax_rate) || 0,
259
+ active: !!form.active,
260
+ meters: form.meters.filter(m => m.meter).map((m) => {
261
+ const def = byKey.get(m.meter)
262
+ return {
263
+ meter: m.meter,
264
+ included_quantity: Math.max(0, Number(m.included_quantity) || 0),
265
+ unit_price: def?.valued_by_cost ? 0 : Math.max(0, Math.round(Number(m.unit_price) || 0)),
266
+ markup_percent: def?.valued_by_cost ? (m.markup_percent === null || m.markup_percent === undefined ? null : Number(m.markup_percent)) : null,
267
+ }
268
+ }),
269
+ }
270
+ }
271
+
272
+ export function errorMessage(e: any, fallback: string): string {
273
+ return e?.data?.message ?? (e?.data?.errors ? (Object.values(e.data.errors).flat()[0] as string) : null) ?? fallback
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
+ }
@@ -0,0 +1,38 @@
1
+ # Consumo de IA — componentes
2
+
3
+ Front del costeo de IA de `Innertia\Ai` (innertia-laravel): precios por modelo en USD y consumo
4
+ agregado por función, día y espacio. Cada uso se valoriza al registrarse con el precio vigente del
5
+ modelo (no es retroactivo); los usos de modelos sin precio se cuentan como "sin precio".
6
+
7
+ ## 1. Backend que hay que montar (en el producto)
8
+
9
+ ```php
10
+ // Grupo platform (prefijo 'platform')
11
+ \Innertia\Ai\Routes::platform(); // GET ai/models/prices, GET ai/usage/report
12
+ Route::middleware('platform.owner')->group(fn () => \Innertia\Ai\Routes::platformWrite()); // PUT ai/models/{id}/prices
13
+
14
+ // Grupo backoffice (espacio activo)
15
+ \Innertia\Ai\Routes::tenant(); // GET ai/usage/summary
16
+ ```
17
+
18
+ ## 2. Componentes
19
+
20
+ | Dónde | Componente | Props |
21
+ |---|---|---|
22
+ | `/platform/ai` (pestaña Precios) | `<Ai.ModelPrices :can-edit="isOwner" />` | `endpoint` (default `platform/ai`), `canEdit` |
23
+ | `/platform/ai` (pestaña Consumo) | `<Ai.UsageReport />` | `endpoint`, `tenantId` (filtra un espacio) |
24
+ | Backoffice › Sistema › IA › Consumo | `<Ai.UsageSummary :budget="presupuestoUsd" />` | `endpoint` (default `ai`), `budget` (USD/mes, opcional) |
25
+
26
+ - **ModelPrices**: precios editables en línea: entrada y salida por 1M de tokens, audio por minuto
27
+ y voz (TTS) por 1M de caracteres. Vacío = sin precio.
28
+ - **UsageReport / UsageSummary**: selector de mes, costo estimado, usos y unidades, barras por día,
29
+ consumo por función (resumen de llamadas, transcripción, copiloto en vivo, asistente, TTS, agente de
30
+ voz, importación de PDF…), días de mayor consumo, por espacio (solo platform) y exportación CSV.
31
+ Con `budget`, aviso al 80 % y al 100 % del presupuesto mensual.
32
+
33
+ ## 3. Composables
34
+
35
+ - `useAiModelPrices({ base })` → `list`, `update`.
36
+ - `useAiUsage(monthRef, { base, scope: 'platform' | 'tenant', tenantId })` → query del resumen.
37
+ - Helpers puros (etiquetas de funciones, formato USD, navegación de meses, presupuesto) en
38
+ `composables/useAiUsage/internal/aiUsage.ts`.