@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,26 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { readFileSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+ import { parse, compileScript, compileTemplate } from 'vue/compiler-sfc'
5
+
6
+ // Billing components compile (script + template) without errors.
7
+ const COMPONENTS = ['../Plans.vue', '../Invoices.vue', '../SpaceSubscription.vue', '../ClientTotals.vue', '../Settings.vue', '../Overview.vue', '../StatusBanner.vue', '../UsageTable.vue']
8
+
9
+ describe('SFC de Billing compilan', () => {
10
+ for (const rel of COMPONENTS) {
11
+ it(rel, () => {
12
+ const filename = resolve(__dirname, rel)
13
+ const { descriptor, errors } = parse(readFileSync(filename, 'utf8'), { filename })
14
+ expect(errors).toEqual([])
15
+
16
+ const script = compileScript(descriptor, { id: rel })
17
+ const tpl = compileTemplate({
18
+ source: descriptor.template!.content,
19
+ filename,
20
+ id: rel,
21
+ compilerOptions: { bindingMetadata: script.bindings },
22
+ })
23
+ expect(tpl.errors).toEqual([])
24
+ })
25
+ }
26
+ })
@@ -0,0 +1,48 @@
1
+ import { computed, type Ref } from 'vue'
2
+ import type { AiModelPrice, PriceField, UsageSummary } from './internal/aiUsage'
3
+
4
+ const clean = (base: string | undefined, fallback: string) => String(base || fallback).replace(/^\/+|\/+$/g, '')
5
+
6
+ /**
7
+ * AI model prices (platform). innertia-laravel \Innertia\Ai\Routes::platform() + platformWrite():
8
+ * GET {base}/models/prices · PUT {base}/models/{id}/prices
9
+ */
10
+ export function useAiModelPrices(options: { base?: string } = {}) {
11
+ const base = clean(options.base, 'platform/ai')
12
+ const api = useApi()
13
+ const queryClient = useQueryClient()
14
+ const key = computed(() => ['ai', base, 'model-prices'])
15
+
16
+ const list = useQuery({
17
+ queryKey: key,
18
+ queryFn: () => api.get(`${base}/models/prices`),
19
+ select: (res: any) => (res?.data ?? []) as AiModelPrice[],
20
+ })
21
+
22
+ const update = useMutation({
23
+ mutationFn: ({ id, prices }: { id: string; prices: Record<PriceField, number | null> }) =>
24
+ api.put(`${base}/models/${id}/prices`, prices),
25
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: key.value }),
26
+ })
27
+
28
+ return { list, update }
29
+ }
30
+
31
+ /**
32
+ * Aggregated AI usage of a month.
33
+ * scope 'platform' → GET {base}/usage/report?month=&tenant_id= (with by_tenant)
34
+ * scope 'tenant' → GET {base}/usage/summary?month= (active space)
35
+ */
36
+ export function useAiUsage(month: Ref<string>, options: { base?: string; scope?: 'platform' | 'tenant'; tenantId?: Ref<string | null> } = {}) {
37
+ const scope = options.scope ?? 'platform'
38
+ const base = clean(options.base, scope === 'platform' ? 'platform/ai' : 'ai')
39
+ const api = useApi()
40
+ const path = scope === 'platform' ? 'usage/report' : 'usage/summary'
41
+
42
+ return useQuery({
43
+ queryKey: computed(() => ['ai', base, path, month.value, options.tenantId?.value ?? null]),
44
+ queryFn: () => api.get(`${base}/${path}`, {
45
+ params: { month: month.value, ...(options.tenantId?.value ? { tenant_id: options.tenantId.value } : {}) },
46
+ }) as Promise<UsageSummary>,
47
+ })
48
+ }
@@ -0,0 +1,50 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ featureLabel, formatUsd, compactNumber, unitsLabel, shiftMonth, monthLabel, monthKey, barHeights, budgetState, parsePrice,
4
+ } from '../aiUsage'
5
+
6
+ describe('aiUsage helpers', () => {
7
+ it('labels features, falling back to a readable key', () => {
8
+ expect(featureLabel('call_summary')).toBe('Resumen de llamadas')
9
+ expect(featureLabel('live_copilot')).toBe('Copiloto en vivo')
10
+ expect(featureLabel('custom_thing')).toBe('Custom thing')
11
+ expect(featureLabel(null)).toBe('Sin clasificar')
12
+ })
13
+
14
+ it('formats USD with adaptive precision', () => {
15
+ expect(formatUsd(0.0042)).toBe('US$ 0,0042')
16
+ expect(formatUsd(12.5)).toBe('US$ 12,50')
17
+ expect(formatUsd(null)).toBe('—')
18
+ })
19
+
20
+ it('compacts numbers and summarizes units', () => {
21
+ expect(compactNumber(1_250_000)).toBe('1,3 M')
22
+ expect(compactNumber(15_300)).toBe('15,3 mil')
23
+ expect(compactNumber(950)).toBe('950')
24
+ expect(unitsLabel({ input_tokens: 1000, output_tokens: 500, audio_seconds: 90, tts_chars: 0 })).toBe('1.500 tokens · 1,5 min de audio')
25
+ expect(unitsLabel({})).toBe('—')
26
+ })
27
+
28
+ it('navigates months', () => {
29
+ expect(shiftMonth('2026-01', -1)).toBe('2025-12')
30
+ expect(shiftMonth('2026-11', 2)).toBe('2027-01')
31
+ expect(monthLabel('2026-11')).toBe('Noviembre 2026')
32
+ expect(monthKey(new Date(2026, 2, 15))).toBe('2026-03')
33
+ })
34
+
35
+ it('scales bars and computes budget levels', () => {
36
+ expect(barHeights([0, 5, 10])).toEqual([0, 50, 100])
37
+ expect(barHeights([0, 0])).toEqual([0, 0])
38
+ expect(budgetState(79, 100)).toEqual({ percent: 79, level: 'ok' })
39
+ expect(budgetState(80, 100)?.level).toBe('warning')
40
+ expect(budgetState(130, 100)?.level).toBe('over')
41
+ expect(budgetState(10, null)).toBeNull()
42
+ })
43
+
44
+ it('parses price inputs', () => {
45
+ expect(parsePrice('')).toBeNull()
46
+ expect(parsePrice('1,5')).toBe(1.5)
47
+ expect(parsePrice('-1')).toBeUndefined()
48
+ expect(parsePrice('abc')).toBeUndefined()
49
+ })
50
+ })
@@ -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
+ })