@innertia-solutions/innertia-nuxt 0.1.91 → 0.1.92

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.
@@ -0,0 +1,264 @@
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
+ space_part?: number
86
+ statements?: Statement[]
87
+ events?: { event: string; user_id: string | null; data: any; created_at: string }[]
88
+ allocations?: { payment_id: string; amount: number; created_at: string }[]
89
+ }
90
+
91
+ export interface UsageEstimate {
92
+ meter: { key: string; label: string; unit: string; valued_by_cost: boolean }
93
+ quantity: number
94
+ cost: number
95
+ included_quantity: number
96
+ unit_price: number
97
+ markup_percent: number | null
98
+ estimated_amount: number
99
+ }
100
+
101
+ /** 152420 → "$ 152.420" (CLP); other currencies in cents → "USD 12,50". */
102
+ export function formatMoney(amount: number | null | undefined, currency = 'CLP'): string {
103
+ if (amount === null || amount === undefined) return '—'
104
+ const sign = amount < 0 ? '-' : ''
105
+ const abs = Math.abs(Math.round(amount))
106
+ if (currency === 'CLP') return `${sign}$ ${abs.toLocaleString('es-CL')}`
107
+ return `${sign}${currency} ${(abs / 100).toLocaleString('es-CL', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
108
+ }
109
+
110
+ /** Parses a typed CLP amount ("$ 1.500" / "1500") into integer pesos; null when empty, NaN when invalid. */
111
+ export function parseMoney(raw: string | number | null | undefined): number | null {
112
+ if (raw === null || raw === undefined || String(raw).trim() === '') return null
113
+ const digits = String(raw).replace(/[$\s.]/g, '').replace(',', '.')
114
+ const n = Number(digits)
115
+ return Number.isFinite(n) ? Math.round(n) : Number.NaN
116
+ }
117
+
118
+ const INVOICE_STATUS: Record<InvoiceStatus, { label: string; severity: Severity }> = {
119
+ draft: { label: 'Borrador', severity: 'secondary' },
120
+ issued: { label: 'Emitida', severity: 'info' },
121
+ paid: { label: 'Pagada', severity: 'success' },
122
+ overdue: { label: 'Vencida', severity: 'danger' },
123
+ void: { label: 'Anulada', severity: 'secondary' },
124
+ }
125
+
126
+ const SUBSCRIPTION_STATUS: Record<SubscriptionStatus, { label: string; severity: Severity }> = {
127
+ trialing: { label: 'En prueba', severity: 'info' },
128
+ active: { label: 'Al día', severity: 'success' },
129
+ past_due: { label: 'Con deuda vencida', severity: 'warning' },
130
+ suspended: { label: 'Suspendido', severity: 'danger' },
131
+ canceled: { label: 'Cancelada', severity: 'secondary' },
132
+ }
133
+
134
+ export function invoiceStatus(status: string): { label: string; severity: Severity } {
135
+ return INVOICE_STATUS[status as InvoiceStatus] ?? { label: status, severity: 'secondary' }
136
+ }
137
+
138
+ export function subscriptionStatus(status: string | null | undefined): { label: string; severity: Severity } {
139
+ if (!status) return { label: 'Sin suscripción', severity: 'secondary' }
140
+ return SUBSCRIPTION_STATUS[status as SubscriptionStatus] ?? { label: status, severity: 'secondary' }
141
+ }
142
+
143
+ export const INVOICE_STATUS_OPTIONS = (Object.keys(INVOICE_STATUS) as InvoiceStatus[]).map(value => ({ value, label: INVOICE_STATUS[value].label }))
144
+
145
+ export const PAYMENT_METHODS = [
146
+ { value: 'invoice', label: 'Factura (pago por transferencia)' },
147
+ { value: 'automatic', label: 'Automático (enlace de pago)' },
148
+ ] as const
149
+
150
+ export function paymentMethodLabel(method: string | null | undefined): string {
151
+ return method === 'automatic' ? 'Enlace de pago' : method === 'invoice' ? 'Transferencia' : (method ?? '—')
152
+ }
153
+
154
+ export function paymentChannelLabel(method: string): string {
155
+ return ({ transfer: 'Transferencia', link: 'Pago en línea', manual: 'Manual', credit: 'Saldo a favor' } as Record<string, string>)[method] ?? method
156
+ }
157
+
158
+ export function intervalLabel(interval: string): string {
159
+ return interval === 'annual' ? 'anual' : 'mensual'
160
+ }
161
+
162
+ /** 'YYYY-MM-DD' → 'DD-MM-YYYY' without time zone shifts. */
163
+ export function formatDate(date: string | null | undefined): string {
164
+ if (!date) return '—'
165
+ const [y, m, d] = date.slice(0, 10).split('-')
166
+ return d && m && y ? `${d}-${m}-${y}` : date
167
+ }
168
+
169
+ export function periodLabel(start: string | null | undefined, end: string | null | undefined): string {
170
+ if (!start || !end) return '—'
171
+ return `${formatDate(start)} al ${formatDate(end)}`
172
+ }
173
+
174
+ /** ISO timestamp → 'DD-MM-YYYY' in the given time zone (default America/Santiago). */
175
+ export function formatDateTime(iso: string | null | undefined, timeZone = 'America/Santiago'): string {
176
+ if (!iso) return '—'
177
+ const d = new Date(iso)
178
+ if (Number.isNaN(d.getTime())) return iso
179
+ const parts = new Intl.DateTimeFormat('es-CL', { timeZone, day: '2-digit', month: '2-digit', year: 'numeric' }).formatToParts(d)
180
+ const get = (t: string) => parts.find(p => p.type === t)?.value ?? ''
181
+ return `${get('day')}-${get('month')}-${get('year')}`
182
+ }
183
+
184
+ /** Consumption vs included: percent used (null when nothing included) and level. */
185
+ export function usageProgress(u: Pick<UsageEstimate, 'quantity' | 'cost' | 'included_quantity' | 'markup_percent'> & { meter: { valued_by_cost: boolean } }):
186
+ { percent: number | null; level: 'ok' | 'warning' | 'over'; over: boolean } {
187
+ const used = u.meter.valued_by_cost ? u.cost * (1 + (u.markup_percent ?? 0) / 100) : u.quantity
188
+ const included = Number(u.included_quantity ?? 0)
189
+ if (included <= 0) return { percent: null, level: used > 0 ? 'over' : 'ok', over: used > 0 }
190
+ const percent = Math.round((used / included) * 100)
191
+ return { percent, level: percent > 100 ? 'over' : percent >= 80 ? 'warning' : 'ok', over: percent > 100 }
192
+ }
193
+
194
+ /** "150 mensajes" style quantity (units from the meter catalog, AI cost in USD). */
195
+ export function formatQuantity(quantity: number, unit?: string | null): string {
196
+ if (unit === 'USD') return `US$ ${quantity.toLocaleString('es-CL', { maximumFractionDigits: 2 })}`
197
+ const n = quantity.toLocaleString('es-CL', { maximumFractionDigits: 2 })
198
+ if (!unit) return n
199
+ return `${n} ${quantity === 1 ? unit : pluralize(unit)}`
200
+ }
201
+
202
+ function pluralize(unit: string): string {
203
+ if (/[aeiouáéíóú]$/i.test(unit)) return `${unit}s`
204
+ if (/^[A-Z]+$/.test(unit)) return unit
205
+ return `${unit}es`
206
+ }
207
+
208
+ export function eventLabel(event: string): string {
209
+ return ({
210
+ created: 'Creada', statement_added: 'Cobro agregado', issued: 'Emitida', sent: 'Enviada por correo',
211
+ payment_applied: 'Pago aplicado', credit: 'Saldo a favor aplicado', overdue: 'Vencida',
212
+ payment_link_created: 'Enlace de pago creado', voided: 'Anulada', reissued: 'Refacturada',
213
+ } as Record<string, string>)[event] ?? event
214
+ }
215
+
216
+ /** Banner of the backoffice for a subscription status (null = nothing to show). */
217
+ export function bannerFor(status: string | null | undefined): { severity: 'warning' | 'danger'; title: string; message: string } | null {
218
+ if (status === 'past_due') {
219
+ return { severity: 'warning', title: 'Tienes facturas vencidas', message: 'Regulariza el pago para evitar la suspensión del espacio.' }
220
+ }
221
+ if (status === 'suspended') {
222
+ return { severity: 'danger', title: 'Espacio en solo lectura', message: 'El espacio está suspendido por facturas vencidas. Puedes consultar y pagar desde Facturación.' }
223
+ }
224
+ return null
225
+ }
226
+
227
+ /** Empty plan form. */
228
+ export function emptyPlan(): Omit<Plan, 'id'> {
229
+ return {
230
+ key: '', name: '', description: '', product: '', currency: 'CLP', interval: 'monthly', base_price: 0,
231
+ included_seats: 0, seat_price: 0, trial_days: 0, tax_rate: 19, limits: {}, active: true, meters: [],
232
+ }
233
+ }
234
+
235
+ /** Plan form → API payload (meters cleaned: valued-by-cost meters send markup, others unit price). */
236
+ export function planPayload(form: Omit<Plan, 'id'>, catalog: MeterDefinition[]): Record<string, any> {
237
+ const byKey = new Map(catalog.map(m => [m.key, m]))
238
+ return {
239
+ key: form.key.trim(),
240
+ name: form.name.trim(),
241
+ description: form.description || null,
242
+ product: form.product || null,
243
+ interval: form.interval,
244
+ base_price: Math.max(0, Math.round(Number(form.base_price) || 0)),
245
+ included_seats: Math.max(0, Math.round(Number(form.included_seats) || 0)),
246
+ seat_price: Math.max(0, Math.round(Number(form.seat_price) || 0)),
247
+ trial_days: Math.max(0, Math.round(Number(form.trial_days) || 0)),
248
+ tax_rate: Number(form.tax_rate) || 0,
249
+ active: !!form.active,
250
+ meters: form.meters.filter(m => m.meter).map((m) => {
251
+ const def = byKey.get(m.meter)
252
+ return {
253
+ meter: m.meter,
254
+ included_quantity: Math.max(0, Number(m.included_quantity) || 0),
255
+ unit_price: def?.valued_by_cost ? 0 : Math.max(0, Math.round(Number(m.unit_price) || 0)),
256
+ markup_percent: def?.valued_by_cost ? (m.markup_percent === null || m.markup_percent === undefined ? null : Number(m.markup_percent)) : null,
257
+ }
258
+ }),
259
+ }
260
+ }
261
+
262
+ export function errorMessage(e: any, fallback: string): string {
263
+ return e?.data?.message ?? (e?.data?.errors ? (Object.values(e.data.errors).flat()[0] as string) : null) ?? fallback
264
+ }
@@ -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`.
@@ -0,0 +1,75 @@
1
+ # Facturación (Billing) — componentes
2
+
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.
5
+ La lógica vive en el backend; estos componentes solo muestran y llaman a sus endpoints.
6
+
7
+ Montos: enteros en pesos (CLP sin decimales). Fechas de período: fechas locales de Chile
8
+ (`YYYY-MM-DD`, ambos extremos incluidos).
9
+
10
+ ## 1. Backend que hay que montar (en el producto)
11
+
12
+ ```php
13
+ // Grupo platform (prefijo 'platform')
14
+ \Innertia\Billing\Routes::platform(); // lectura (owner y staff)
15
+ Route::middleware('platform.owner')->group(fn () => \Innertia\Billing\Routes::platformWrite());
16
+
17
+ // Grupo backoffice (espacio activo), solo lectura
18
+ Route::middleware('permission:billing.view')->group(fn () => \Innertia\Billing\Routes::backoffice());
19
+
20
+ // Escrituras del backoffice en solo lectura cuando el espacio está suspendido
21
+ Route::middleware('billing.enforce')->group(/* rutas del backoffice */);
22
+ ```
23
+
24
+ Activar el feature en el backend: ver `docs/billing.md` de innertia-laravel.
25
+
26
+ ## 2. Platform
27
+
28
+ | Página sugerida | Componente | Props |
29
+ |---|---|---|
30
+ | `/platform/billing` (resumen) | `<Billing.ClientTotals @select-space="…" @select-client="…" />` | `endpoint` (default `platform/billing`) |
31
+ | `/platform/billing/invoices` | `<Billing.Invoices :clients="opciones" />` | `clientId`, `spaceKey`, `clients`, `canEdit` |
32
+ | `/platform/billing/plans` | `<Billing.Plans :can-edit="isOwner" />` | `canEdit` |
33
+ | `/platform/billing/settings` | `<Billing.Settings />` (solo owner) | `canRun` |
34
+ | Detalle del espacio (pestaña Suscripción) | `<Billing.SpaceSubscription :space-key="key" :can-edit="isOwner" />` | `spaceKey` (obligatoria) |
35
+ | Detalle del cliente (pestaña Facturas) | `<Billing.Invoices :client-id="client.id" />` | |
36
+
37
+ - **Invoices**: filtros por estado y cliente, detalle con los cobros por espacio y sus líneas, bitácora,
38
+ **Emitir** (folio SII opcional, envío por correo con el PDF), **Reenviar**, **PDF** y **Registrar pago**
39
+ (transferencia; el excedente queda como saldo a favor del cliente).
40
+ - **SpaceSubscription**: iniciar suscripción (plan, modo de pago `invoice`/`automatic`, inicio, días de
41
+ prueba, precio base y por usuario negociados), editar (el cambio de plan rige desde el próximo período),
42
+ suspender, reactivar y cancelar; consumo del período con total estimado y los cobros cerrados.
43
+ Los espacios de pruebas muestran un aviso (nunca se cobran).
44
+ - **Settings**: tipo de cambio USD→CLP (valoriza la IA), datos para transferencia y emisor del PDF;
45
+ botones para ejecutar a mano el cierre y la revisión de mora (también corren solos cada día).
46
+
47
+ ## 3. Backoffice
48
+
49
+ ```vue
50
+ <!-- pages/backoffice/billing.vue (permiso billing.view; solo espacios de producción) -->
51
+ <Billing.Overview />
52
+
53
+ <!-- layout del backoffice: franja global de mora / solo lectura -->
54
+ <Billing.StatusBanner billing-route="/backoffice/billing" />
55
+ ```
56
+
57
+ - **Overview**: plan y estado, total estimado del período, saldo pendiente y vencido, consumo por
58
+ 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 pagos. Espacio de pruebas: solo la franja
60
+ "Espacio de pruebas".
61
+ - **StatusBanner**: se muestra con `past_due` ("Tienes facturas vencidas") o `suspended` ("Espacio en
62
+ solo lectura"). Pásale `status` (por ejemplo desde el header `X-Billing-Status` que pone el
63
+ middleware `billing.enforce`) o deja que consulte `billing/overview` (requiere `billing.view`; si
64
+ falla no muestra nada). `:fetch="false"` evita la consulta.
65
+ - Una escritura con el espacio suspendido responde **402** `{code: 'subscription_suspended'}`.
66
+
67
+ ## 4. Composables
68
+
69
+ - `useBillingPlatform({ base })` → `plans`, `meters`, `savePlan`, `invoices(filtersRef)`, `invoice(id)`,
70
+ `issue`, `resend`, `registerPayment`, `space(keyRef)`, `startSubscription`, `updateSubscription`,
71
+ `subscriptionAction`, `clientTotals`, `settings`, `saveSettings`, `run`.
72
+ - `useBillingSpace({ base })` → `overview`, `invoices`, `payments` (backoffice).
73
+ - `useBillingPdf()` → `(path, filename) => Promise` descarga un PDF con la sesión.
74
+ - Helpers puros (formato de pesos, estados, períodos, progreso de consumo) en
75
+ `composables/useBilling/internal/billing.ts`.
package/nuxt.config.ts CHANGED
@@ -29,7 +29,7 @@ export default defineNuxtConfig({
29
29
  { path: './components', pathPrefix: true, prefix: '' },
30
30
  ],
31
31
  imports: {
32
- dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys', 'composables/useDriveBrowser', 'composables/useFileImports', 'composables/useFileVersions', 'composables/useNotificationPreferences', 'composables/useIntegrations'],
32
+ dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys', 'composables/useDriveBrowser', 'composables/useFileImports', 'composables/useFileVersions', 'composables/useNotificationPreferences', 'composables/useIntegrations', 'composables/useAiUsage', 'composables/useBilling'],
33
33
  presets: [
34
34
  {
35
35
  from: '@tanstack/vue-query',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@innertia-solutions/innertia-nuxt",
3
- "version": "0.1.91",
3
+ "version": "0.1.92",
4
4
  "description": "Innertia Solutions — Nuxt layer unificada: core, auth, multitenancy, theme y app contexts",
5
5
  "keywords": [
6
6
  "nuxt",