@innertia-solutions/innertia-nuxt 0.1.90 → 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.
- package/CHANGELOG.md +2 -0
- package/components/Ai/ModelPrices.vue +105 -0
- package/components/Ai/UsageReport.vue +127 -0
- package/components/Ai/UsageSummary.vue +13 -0
- package/components/Ai/__tests__/sfc-compile.test.ts +26 -0
- package/components/Billing/ClientTotals.vue +65 -0
- package/components/Billing/Invoices.vue +271 -0
- package/components/Billing/Overview.vue +124 -0
- package/components/Billing/Plans.vue +146 -0
- package/components/Billing/Settings.vue +79 -0
- package/components/Billing/SpaceSubscription.vue +202 -0
- package/components/Billing/StatusBanner.vue +36 -0
- package/components/Billing/UsageTable.vue +32 -0
- package/components/Billing/__tests__/sfc-compile.test.ts +26 -0
- package/components/Integrations/ApiKeys.vue +297 -0
- package/components/Integrations/Developers.vue +60 -0
- package/components/Integrations/Webhooks.vue +458 -0
- package/components/Integrations/__tests__/sfc-compile.test.ts +31 -0
- package/composables/useAiUsage/index.ts +48 -0
- package/composables/useAiUsage/internal/__tests__/aiUsage.test.ts +50 -0
- package/composables/useAiUsage/internal/aiUsage.ts +140 -0
- package/composables/useBilling/index.ts +147 -0
- package/composables/useBilling/internal/__tests__/billing.test.ts +78 -0
- package/composables/useBilling/internal/billing.ts +264 -0
- package/composables/useIntegrations/index.ts +136 -0
- package/composables/useIntegrations/internal/__tests__/integrations.test.ts +112 -0
- package/composables/useIntegrations/internal/integrations.ts +276 -0
- package/docs/ai-usage.md +38 -0
- package/docs/billing.md +75 -0
- package/docs/webhooks-api.md +88 -0
- package/nuxt.config.ts +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for the AI pricing/usage screens (no Nuxt/Vue: testable in node).
|
|
3
|
+
* Backend: innertia-laravel \Innertia\Ai\Routes (platform: ai/models/prices, ai/usage/report;
|
|
4
|
+
* backoffice: ai/usage/summary).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export type PriceField = 'price_input_per_mtok' | 'price_output_per_mtok' | 'price_per_audio_minute' | 'price_per_mchar_tts'
|
|
8
|
+
|
|
9
|
+
export const PRICE_FIELDS: { key: PriceField; label: string; hint: string }[] = [
|
|
10
|
+
{ key: 'price_input_per_mtok', label: 'Entrada', hint: 'USD por 1M tokens' },
|
|
11
|
+
{ key: 'price_output_per_mtok', label: 'Salida', hint: 'USD por 1M tokens' },
|
|
12
|
+
{ key: 'price_per_audio_minute', label: 'Audio', hint: 'USD por minuto' },
|
|
13
|
+
{ key: 'price_per_mchar_tts', label: 'Voz (TTS)', hint: 'USD por 1M caracteres' },
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
export interface AiModelPrice {
|
|
17
|
+
id: string
|
|
18
|
+
key: string
|
|
19
|
+
name: string
|
|
20
|
+
active: boolean
|
|
21
|
+
capabilities: string[]
|
|
22
|
+
provider: { id: string; key: string; name: string } | null
|
|
23
|
+
prices: Record<PriceField, number | null>
|
|
24
|
+
priced: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface UsageTotals {
|
|
28
|
+
events: number
|
|
29
|
+
cost_usd: number
|
|
30
|
+
input_tokens: number
|
|
31
|
+
output_tokens: number
|
|
32
|
+
audio_seconds: number
|
|
33
|
+
tts_chars: number
|
|
34
|
+
unpriced_events: number
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface UsageSummary {
|
|
38
|
+
from: string
|
|
39
|
+
to: string
|
|
40
|
+
timezone: string
|
|
41
|
+
tenant_id?: string | null
|
|
42
|
+
totals: UsageTotals
|
|
43
|
+
by_feature: (UsageTotals & { feature: string | null })[]
|
|
44
|
+
by_model: (UsageTotals & { model: string | null })[]
|
|
45
|
+
daily: (UsageTotals & { date: string })[]
|
|
46
|
+
by_tenant?: (UsageTotals & { tenant_id: string | null; tenant_key?: string | null; tenant_name?: string | null })[]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const FEATURE_LABELS: Record<string, string> = {
|
|
50
|
+
call_summary: 'Resumen de llamadas',
|
|
51
|
+
transcription: 'Transcripción',
|
|
52
|
+
live_copilot: 'Copiloto en vivo',
|
|
53
|
+
assistant: 'Asistente',
|
|
54
|
+
tts: 'Voz (TTS)',
|
|
55
|
+
voice_agent: 'Agente de voz',
|
|
56
|
+
import_pdf: 'Importación de PDF',
|
|
57
|
+
chat: 'Chat',
|
|
58
|
+
embedding: 'Embeddings',
|
|
59
|
+
vision: 'Visión',
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function featureLabel(key: string | null | undefined): string {
|
|
63
|
+
if (!key) return 'Sin clasificar'
|
|
64
|
+
return FEATURE_LABELS[key] ?? key.replace(/[_.-]+/g, ' ').replace(/^./, c => c.toUpperCase())
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** USD with adaptive precision: small amounts keep 4 decimals ($0.0042), larger ones 2. */
|
|
68
|
+
export function formatUsd(value: number | null | undefined): string {
|
|
69
|
+
if (value === null || value === undefined || Number.isNaN(Number(value))) return '—'
|
|
70
|
+
const v = Number(value)
|
|
71
|
+
const digits = v !== 0 && Math.abs(v) < 1 ? 4 : 2
|
|
72
|
+
return 'US$ ' + v.toLocaleString('es-CL', { minimumFractionDigits: digits, maximumFractionDigits: digits })
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 1234567 → "1,2 M"; 15300 → "15,3 mil"; 950 → "950". */
|
|
76
|
+
export function compactNumber(value: number | null | undefined): string {
|
|
77
|
+
const v = Number(value ?? 0)
|
|
78
|
+
const abs = Math.abs(v)
|
|
79
|
+
const fmt = (n: number) => n.toLocaleString('es-CL', { maximumFractionDigits: 1 })
|
|
80
|
+
if (abs >= 1_000_000) return `${fmt(v / 1_000_000)} M`
|
|
81
|
+
if (abs >= 10_000) return `${fmt(v / 1_000)} mil`
|
|
82
|
+
return Math.round(v).toLocaleString('es-CL')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Human summary of the units of a row: "1,2 M tokens · 3 min de audio · 4,5 mil caracteres". */
|
|
86
|
+
export function unitsLabel(t: Partial<UsageTotals>): string {
|
|
87
|
+
const parts: string[] = []
|
|
88
|
+
const tokens = (t.input_tokens ?? 0) + (t.output_tokens ?? 0)
|
|
89
|
+
if (tokens > 0) parts.push(`${compactNumber(tokens)} tokens`)
|
|
90
|
+
if ((t.audio_seconds ?? 0) > 0) parts.push(`${formatMinutes(t.audio_seconds!)} de audio`)
|
|
91
|
+
if ((t.tts_chars ?? 0) > 0) parts.push(`${compactNumber(t.tts_chars)} caracteres`)
|
|
92
|
+
return parts.join(' · ') || '—'
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function formatMinutes(seconds: number): string {
|
|
96
|
+
const min = seconds / 60
|
|
97
|
+
return `${min.toLocaleString('es-CL', { maximumFractionDigits: min < 10 ? 1 : 0 })} min`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 'YYYY-MM' of a date (local). */
|
|
101
|
+
export function monthKey(date: Date = new Date()): string {
|
|
102
|
+
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Shift a 'YYYY-MM' month by n months. */
|
|
106
|
+
export function shiftMonth(month: string, n: number): string {
|
|
107
|
+
const [y, m] = month.split('-').map(Number)
|
|
108
|
+
const d = new Date(y, m - 1 + n, 1)
|
|
109
|
+
return monthKey(d)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const MONTHS = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']
|
|
113
|
+
|
|
114
|
+
export function monthLabel(month: string): string {
|
|
115
|
+
const [y, m] = month.split('-').map(Number)
|
|
116
|
+
const name = MONTHS[(m - 1) % 12] ?? month
|
|
117
|
+
return `${name.charAt(0).toUpperCase()}${name.slice(1)} ${y}`
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Bar heights (0-100) for a daily series, relative to its max. */
|
|
121
|
+
export function barHeights(values: number[]): number[] {
|
|
122
|
+
const max = Math.max(0, ...values)
|
|
123
|
+
return values.map(v => (max > 0 ? Math.round((v / max) * 100) : 0))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Budget usage: percent and level (ok < 80 ≤ warning < 100 ≤ over). */
|
|
127
|
+
export function budgetState(cost: number, budget: number | null | undefined): { percent: number; level: 'ok' | 'warning' | 'over' } | null {
|
|
128
|
+
if (!budget || budget <= 0) return null
|
|
129
|
+
const percent = Math.round((cost / budget) * 100)
|
|
130
|
+
return { percent, level: percent >= 100 ? 'over' : percent >= 80 ? 'warning' : 'ok' }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Normalizes a price input ("" → null, "1,5" → 1.5). Returns undefined when invalid. */
|
|
134
|
+
export function parsePrice(raw: string | number | null | undefined): number | null | undefined {
|
|
135
|
+
if (raw === null || raw === undefined) return null
|
|
136
|
+
const s = String(raw).trim().replace(',', '.')
|
|
137
|
+
if (s === '') return null
|
|
138
|
+
const n = Number(s)
|
|
139
|
+
return Number.isFinite(n) && n >= 0 ? n : undefined
|
|
140
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { computed, type Ref } from 'vue'
|
|
2
|
+
import type { Invoice, MeterDefinition, Plan } from './internal/billing'
|
|
3
|
+
|
|
4
|
+
const clean = (base: string | undefined, fallback: string) => String(base || fallback).replace(/^\/+|\/+$/g, '')
|
|
5
|
+
|
|
6
|
+
/** Opens a PDF endpoint as a download (blob with auth headers). */
|
|
7
|
+
export function useBillingPdf() {
|
|
8
|
+
const { download } = useDownload()
|
|
9
|
+
return async (path: string, filename: string) => {
|
|
10
|
+
const { blob } = await download(path)
|
|
11
|
+
const url = URL.createObjectURL(blob)
|
|
12
|
+
const a = document.createElement('a')
|
|
13
|
+
a.href = url
|
|
14
|
+
a.download = filename
|
|
15
|
+
document.body.appendChild(a)
|
|
16
|
+
a.click()
|
|
17
|
+
a.remove()
|
|
18
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Platform billing (innertia-laravel \Innertia\Billing\Routes::platform() + platformWrite()).
|
|
24
|
+
* `base`: prefix where the product mounted them (default 'platform/billing').
|
|
25
|
+
*/
|
|
26
|
+
export function useBillingPlatform(options: { base?: string } = {}) {
|
|
27
|
+
const base = clean(options.base, 'platform/billing')
|
|
28
|
+
const api = useApi()
|
|
29
|
+
const queryClient = useQueryClient()
|
|
30
|
+
const invalidate = () => queryClient.invalidateQueries({ queryKey: ['billing', base] })
|
|
31
|
+
|
|
32
|
+
const plans = useQuery({
|
|
33
|
+
queryKey: ['billing', base, 'plans'],
|
|
34
|
+
queryFn: () => api.get(`${base}/plans`),
|
|
35
|
+
select: (res: any) => (res?.data ?? []) as Plan[],
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
const meters = useQuery({
|
|
39
|
+
queryKey: ['billing', base, 'meters'],
|
|
40
|
+
queryFn: () => api.get(`${base}/meters`),
|
|
41
|
+
select: (res: any) => (res?.data ?? []) as MeterDefinition[],
|
|
42
|
+
staleTime: 5 * 60_000,
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
const savePlan = useMutation({
|
|
46
|
+
mutationFn: ({ id, body }: { id?: string; body: Record<string, any> }) =>
|
|
47
|
+
id ? api.patch(`${base}/plans/${id}`, body) : api.post(`${base}/plans`, body),
|
|
48
|
+
onSuccess: invalidate,
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
function invoices(filters: Ref<Record<string, any>>) {
|
|
52
|
+
return useQuery({
|
|
53
|
+
queryKey: computed(() => ['billing', base, 'invoices', { ...filters.value }]),
|
|
54
|
+
queryFn: () => api.get(`${base}/invoices`, { params: Object.fromEntries(Object.entries(filters.value).filter(([, v]) => v !== '' && v !== null && v !== undefined)) }),
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const invoice = (id: string) => api.get(`${base}/invoices/${id}`) as Promise<Invoice>
|
|
59
|
+
|
|
60
|
+
const issue = useMutation({
|
|
61
|
+
mutationFn: ({ id, body }: { id: string; body: { folio?: string | null; pdf_file_id?: string | null; send?: boolean } }) =>
|
|
62
|
+
api.post(`${base}/invoices/${id}/issue`, body) as Promise<Invoice>,
|
|
63
|
+
onSuccess: invalidate,
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
const resend = useMutation({
|
|
67
|
+
mutationFn: (id: string) => api.post(`${base}/invoices/${id}/resend`, {}) as Promise<{ sent: boolean }>,
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
const registerPayment = useMutation({
|
|
71
|
+
mutationFn: (body: { client_id: string; amount: number; method?: string; reference?: string | null; received_at?: string | null; invoice_id?: string | null }) =>
|
|
72
|
+
api.post(`${base}/payments`, body),
|
|
73
|
+
onSuccess: invalidate,
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
function space(key: Ref<string>) {
|
|
77
|
+
return useQuery({
|
|
78
|
+
queryKey: computed(() => ['billing', base, 'space', key.value]),
|
|
79
|
+
queryFn: () => api.get(`${base}/spaces/${encodeURIComponent(key.value)}`),
|
|
80
|
+
enabled: computed(() => !!key.value),
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const startSubscription = useMutation({
|
|
85
|
+
mutationFn: ({ key, body }: { key: string; body: Record<string, any> }) => api.post(`${base}/spaces/${encodeURIComponent(key)}/subscription`, body),
|
|
86
|
+
onSuccess: invalidate,
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
const updateSubscription = useMutation({
|
|
90
|
+
mutationFn: ({ key, body }: { key: string; body: Record<string, any> }) => api.patch(`${base}/spaces/${encodeURIComponent(key)}/subscription`, body),
|
|
91
|
+
onSuccess: invalidate,
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
const subscriptionAction = useMutation({
|
|
95
|
+
mutationFn: ({ key, action }: { key: string; action: 'suspend' | 'reactivate' | 'cancel' }) =>
|
|
96
|
+
api.post(`${base}/spaces/${encodeURIComponent(key)}/subscription/${action}`, {}),
|
|
97
|
+
onSuccess: invalidate,
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
const clientTotals = useQuery({
|
|
101
|
+
queryKey: ['billing', base, 'clients-totals'],
|
|
102
|
+
queryFn: () => api.get(`${base}/clients/totals`),
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
const settings = useQuery({
|
|
106
|
+
queryKey: ['billing', base, 'settings'],
|
|
107
|
+
queryFn: () => api.get(`${base}/settings`),
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
const saveSettings = useMutation({
|
|
111
|
+
mutationFn: (body: Record<string, any>) => api.put(`${base}/settings`, body),
|
|
112
|
+
onSuccess: invalidate,
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
const run = useMutation({
|
|
116
|
+
mutationFn: (job: 'close' | 'dunning') => api.post(`${base}/run/${job}`, {}),
|
|
117
|
+
onSuccess: invalidate,
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
base, plans, meters, savePlan, invoices, invoice, issue, resend, registerPayment, space,
|
|
122
|
+
startSubscription, updateSubscription, subscriptionAction, clientTotals, settings, saveSettings, run,
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Backoffice billing of the active space, read-only (innertia-laravel \Innertia\Billing\Routes::backoffice()).
|
|
128
|
+
* `base`: default 'billing'.
|
|
129
|
+
*/
|
|
130
|
+
export function useBillingSpace(options: { base?: string } = {}) {
|
|
131
|
+
const base = clean(options.base, 'billing')
|
|
132
|
+
const api = useApi()
|
|
133
|
+
|
|
134
|
+
const overview = useQuery({ queryKey: ['billing-space', base, 'overview'], queryFn: () => api.get(`${base}/overview`) })
|
|
135
|
+
const invoices = useQuery({
|
|
136
|
+
queryKey: ['billing-space', base, 'invoices'],
|
|
137
|
+
queryFn: () => api.get(`${base}/invoices`),
|
|
138
|
+
select: (res: any) => (res?.data ?? []) as Invoice[],
|
|
139
|
+
})
|
|
140
|
+
const payments = useQuery({
|
|
141
|
+
queryKey: ['billing-space', base, 'payments'],
|
|
142
|
+
queryFn: () => api.get(`${base}/payments`),
|
|
143
|
+
select: (res: any) => (res?.data ?? []) as any[],
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
return { base, overview, invoices, payments }
|
|
147
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
formatMoney, parseMoney, invoiceStatus, subscriptionStatus, paymentMethodLabel, periodLabel, formatDate,
|
|
4
|
+
usageProgress, formatQuantity, bannerFor, planPayload, emptyPlan, formatDateTime, eventLabel, errorMessage,
|
|
5
|
+
} from '../billing'
|
|
6
|
+
|
|
7
|
+
describe('billing helpers', () => {
|
|
8
|
+
it('formats and parses CLP pesos', () => {
|
|
9
|
+
expect(formatMoney(152420)).toBe('$ 152.420')
|
|
10
|
+
expect(formatMoney(-11454)).toBe('-$ 11.454')
|
|
11
|
+
expect(formatMoney(1250, 'USD')).toBe('USD 12,50')
|
|
12
|
+
expect(formatMoney(null)).toBe('—')
|
|
13
|
+
expect(parseMoney('$ 1.500')).toBe(1500)
|
|
14
|
+
expect(parseMoney('')).toBeNull()
|
|
15
|
+
expect(Number.isNaN(parseMoney('abc'))).toBe(true)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('labels statuses with severity', () => {
|
|
19
|
+
expect(invoiceStatus('overdue')).toEqual({ label: 'Vencida', severity: 'danger' })
|
|
20
|
+
expect(invoiceStatus('paid').severity).toBe('success')
|
|
21
|
+
expect(subscriptionStatus('past_due').label).toBe('Con deuda vencida')
|
|
22
|
+
expect(subscriptionStatus(null).label).toBe('Sin suscripción')
|
|
23
|
+
expect(paymentMethodLabel('automatic')).toBe('Enlace de pago')
|
|
24
|
+
expect(eventLabel('issued')).toBe('Emitida')
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('formats local dates and periods without time zone shifts', () => {
|
|
28
|
+
expect(formatDate('2026-11-01')).toBe('01-11-2026')
|
|
29
|
+
expect(periodLabel('2026-11-01', '2026-11-30')).toBe('01-11-2026 al 30-11-2026')
|
|
30
|
+
expect(formatDateTime('2026-12-01T02:00:00Z')).toBe('30-11-2026') // Santiago UTC-3
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('computes consumption vs included', () => {
|
|
34
|
+
const meter = { valued_by_cost: false }
|
|
35
|
+
expect(usageProgress({ meter, quantity: 80, cost: 0, included_quantity: 100, markup_percent: null })).toEqual({ percent: 80, level: 'warning', over: false })
|
|
36
|
+
expect(usageProgress({ meter, quantity: 150, cost: 0, included_quantity: 100, markup_percent: null }).over).toBe(true)
|
|
37
|
+
expect(usageProgress({ meter, quantity: 5, cost: 0, included_quantity: 0, markup_percent: null })).toEqual({ percent: null, level: 'over', over: true })
|
|
38
|
+
expect(usageProgress({ meter: { valued_by_cost: true }, quantity: 4, cost: 1000, included_quantity: 2400, markup_percent: 20 }).percent).toBe(50)
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('formats quantities with units', () => {
|
|
42
|
+
expect(formatQuantity(150, 'mensaje')).toBe('150 mensajes')
|
|
43
|
+
expect(formatQuantity(1, 'minuto')).toBe('1 minuto')
|
|
44
|
+
expect(formatQuantity(12.5, 'GB')).toBe('12,5 GB')
|
|
45
|
+
expect(formatQuantity(3, 'usuario')).toBe('3 usuarios')
|
|
46
|
+
expect(formatQuantity(4.2, 'USD')).toBe('US$ 4,2')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('maps the subscription status to a banner', () => {
|
|
50
|
+
expect(bannerFor('active')).toBeNull()
|
|
51
|
+
expect(bannerFor('past_due')?.severity).toBe('warning')
|
|
52
|
+
expect(bannerFor('suspended')?.title).toBe('Espacio en solo lectura')
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('builds the plan payload', () => {
|
|
56
|
+
const form = { ...emptyPlan(), key: ' pro ', name: 'Pro', base_price: 99999.6 as any, meters: [
|
|
57
|
+
{ meter: 'ai.cost', included_quantity: 1000, unit_price: 50, markup_percent: 20 },
|
|
58
|
+
{ meter: 'sms.messages', included_quantity: 10, unit_price: 12, markup_percent: 5 },
|
|
59
|
+
{ meter: '', included_quantity: 0, unit_price: 0, markup_percent: null },
|
|
60
|
+
] }
|
|
61
|
+
const catalog = [
|
|
62
|
+
{ key: 'ai.cost', label: 'IA', unit: 'USD', aggregation: 'sum' as const, valued_by_cost: true },
|
|
63
|
+
{ key: 'sms.messages', label: 'SMS', unit: 'mensaje', aggregation: 'sum' as const, valued_by_cost: false },
|
|
64
|
+
]
|
|
65
|
+
const p = planPayload(form, catalog)
|
|
66
|
+
expect(p.key).toBe('pro')
|
|
67
|
+
expect(p.base_price).toBe(100000)
|
|
68
|
+
expect(p.meters).toEqual([
|
|
69
|
+
{ meter: 'ai.cost', included_quantity: 1000, unit_price: 0, markup_percent: 20 },
|
|
70
|
+
{ meter: 'sms.messages', included_quantity: 10, unit_price: 12, markup_percent: null },
|
|
71
|
+
])
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('extracts API error messages', () => {
|
|
75
|
+
expect(errorMessage({ data: { errors: { key: ['Ya existe'] } } }, 'x')).toBe('Ya existe')
|
|
76
|
+
expect(errorMessage({}, 'Falló')).toBe('Falló')
|
|
77
|
+
})
|
|
78
|
+
})
|
|
@@ -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
|
+
}
|