@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.
- 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/AccountStatement.vue +121 -0
- package/components/Billing/ActivityLog.vue +44 -0
- package/components/Billing/Adjustments.vue +169 -0
- package/components/Billing/ClientTerms.vue +70 -0
- package/components/Billing/ClientTotals.vue +65 -0
- package/components/Billing/CreditNoteForm.vue +82 -0
- package/components/Billing/Invoices.vue +394 -0
- package/components/Billing/Overview.vue +130 -0
- package/components/Billing/Plans.vue +146 -0
- package/components/Billing/Reconciliation.vue +309 -0
- package/components/Billing/Reports.vue +87 -0
- package/components/Billing/Settings.vue +112 -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 +29 -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 +257 -0
- package/composables/useBilling/internal/__tests__/billing.test.ts +78 -0
- package/composables/useBilling/internal/__tests__/collections.test.ts +120 -0
- package/composables/useBilling/internal/billing.ts +587 -0
- package/docs/ai-usage.md +38 -0
- package/docs/billing.md +110 -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,257 @@
|
|
|
1
|
+
import { computed, type Ref } from 'vue'
|
|
2
|
+
import type { Adjustment, BankTransaction, 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
|
+
const compact = (o: Record<string, any>) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== '' && v !== null && v !== undefined))
|
|
23
|
+
|
|
24
|
+
/** Downloads a file endpoint (xlsx exports) with the session, optional query params. */
|
|
25
|
+
export function useBillingDownload() {
|
|
26
|
+
const { download } = useDownload()
|
|
27
|
+
return async (path: string, filename: string, params: Record<string, any> = {}) => {
|
|
28
|
+
const { blob } = await download(path, compact(params))
|
|
29
|
+
const url = URL.createObjectURL(blob)
|
|
30
|
+
const a = document.createElement('a')
|
|
31
|
+
a.href = url
|
|
32
|
+
a.download = filename
|
|
33
|
+
document.body.appendChild(a)
|
|
34
|
+
a.click()
|
|
35
|
+
a.remove()
|
|
36
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Platform billing (innertia-laravel \Innertia\Billing\Routes::platform() + platformWrite()).
|
|
42
|
+
* `base`: prefix where the product mounted them (default 'platform/billing').
|
|
43
|
+
*/
|
|
44
|
+
export function useBillingPlatform(options: { base?: string } = {}) {
|
|
45
|
+
const base = clean(options.base, 'platform/billing')
|
|
46
|
+
const api = useApi()
|
|
47
|
+
const queryClient = useQueryClient()
|
|
48
|
+
const invalidate = () => queryClient.invalidateQueries({ queryKey: ['billing', base] })
|
|
49
|
+
|
|
50
|
+
const plans = useQuery({
|
|
51
|
+
queryKey: ['billing', base, 'plans'],
|
|
52
|
+
queryFn: () => api.get(`${base}/plans`),
|
|
53
|
+
select: (res: any) => (res?.data ?? []) as Plan[],
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
const meters = useQuery({
|
|
57
|
+
queryKey: ['billing', base, 'meters'],
|
|
58
|
+
queryFn: () => api.get(`${base}/meters`),
|
|
59
|
+
select: (res: any) => (res?.data ?? []) as MeterDefinition[],
|
|
60
|
+
staleTime: 5 * 60_000,
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
const savePlan = useMutation({
|
|
64
|
+
mutationFn: ({ id, body }: { id?: string; body: Record<string, any> }) =>
|
|
65
|
+
id ? api.patch(`${base}/plans/${id}`, body) : api.post(`${base}/plans`, body),
|
|
66
|
+
onSuccess: invalidate,
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
function invoices(filters: Ref<Record<string, any>>) {
|
|
70
|
+
return useQuery({
|
|
71
|
+
queryKey: computed(() => ['billing', base, 'invoices', { ...filters.value }]),
|
|
72
|
+
queryFn: () => api.get(`${base}/invoices`, { params: Object.fromEntries(Object.entries(filters.value).filter(([, v]) => v !== '' && v !== null && v !== undefined)) }),
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const invoice = (id: string) => api.get(`${base}/invoices/${id}`) as Promise<Invoice>
|
|
77
|
+
|
|
78
|
+
const issue = useMutation({
|
|
79
|
+
mutationFn: ({ id, body }: { id: string; body: { folio?: string | null; pdf_file_id?: string | null; send?: boolean } }) =>
|
|
80
|
+
api.post(`${base}/invoices/${id}/issue`, body) as Promise<Invoice>,
|
|
81
|
+
onSuccess: invalidate,
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
const resend = useMutation({
|
|
85
|
+
mutationFn: (id: string) => api.post(`${base}/invoices/${id}/resend`, {}) as Promise<{ sent: boolean }>,
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
const registerPayment = useMutation({
|
|
89
|
+
mutationFn: (body: { client_id: string; amount: number; method?: string; reference?: string | null; received_at?: string | null; invoice_id?: string | null }) =>
|
|
90
|
+
api.post(`${base}/payments`, body),
|
|
91
|
+
onSuccess: invalidate,
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
function space(key: Ref<string>) {
|
|
95
|
+
return useQuery({
|
|
96
|
+
queryKey: computed(() => ['billing', base, 'space', key.value]),
|
|
97
|
+
queryFn: () => api.get(`${base}/spaces/${encodeURIComponent(key.value)}`),
|
|
98
|
+
enabled: computed(() => !!key.value),
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const startSubscription = useMutation({
|
|
103
|
+
mutationFn: ({ key, body }: { key: string; body: Record<string, any> }) => api.post(`${base}/spaces/${encodeURIComponent(key)}/subscription`, body),
|
|
104
|
+
onSuccess: invalidate,
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
const updateSubscription = useMutation({
|
|
108
|
+
mutationFn: ({ key, body }: { key: string; body: Record<string, any> }) => api.patch(`${base}/spaces/${encodeURIComponent(key)}/subscription`, body),
|
|
109
|
+
onSuccess: invalidate,
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
const subscriptionAction = useMutation({
|
|
113
|
+
mutationFn: ({ key, action }: { key: string; action: 'suspend' | 'reactivate' | 'cancel' }) =>
|
|
114
|
+
api.post(`${base}/spaces/${encodeURIComponent(key)}/subscription/${action}`, {}),
|
|
115
|
+
onSuccess: invalidate,
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
const clientTotals = useQuery({
|
|
119
|
+
queryKey: ['billing', base, 'clients-totals'],
|
|
120
|
+
queryFn: () => api.get(`${base}/clients/totals`),
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
const settings = useQuery({
|
|
124
|
+
queryKey: ['billing', base, 'settings'],
|
|
125
|
+
queryFn: () => api.get(`${base}/settings`),
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
const saveSettings = useMutation({
|
|
129
|
+
mutationFn: (body: Record<string, any>) => api.put(`${base}/settings`, body),
|
|
130
|
+
onSuccess: invalidate,
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
const run = useMutation({
|
|
134
|
+
mutationFn: (job: 'close' | 'dunning' | 'reminders') => api.post(`${base}/run/${job}`, {}),
|
|
135
|
+
onSuccess: invalidate,
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
// ── Collections (stage 3) ────────────────────────────────────────────────
|
|
139
|
+
const post = (path: string, body: Record<string, any> = {}) => api.post(`${base}/${path}`, body)
|
|
140
|
+
const mutation = <T = any>(fn: (vars: any) => Promise<T>) => useMutation({ mutationFn: fn, onSuccess: invalidate })
|
|
141
|
+
|
|
142
|
+
function adjustments(filters: Ref<Record<string, any>>) {
|
|
143
|
+
return useQuery({
|
|
144
|
+
queryKey: computed(() => ['billing', base, 'adjustments', { ...filters.value }]),
|
|
145
|
+
queryFn: () => api.get(`${base}/adjustments`, { params: compact(filters.value) }),
|
|
146
|
+
select: (res: any) => (res?.data ?? []) as Adjustment[],
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
const createAdjustment = mutation((body: Record<string, any>) => post('adjustments', body))
|
|
150
|
+
const cancelAdjustment = mutation(({ id, reason }: { id: string; reason: string }) => post(`adjustments/${id}/cancel`, { reason }))
|
|
151
|
+
const createCreditNote = mutation((body: Record<string, any>) => post('credit-notes', body) as Promise<Adjustment>)
|
|
152
|
+
|
|
153
|
+
function terms(clientId: Ref<string>) {
|
|
154
|
+
return useQuery({
|
|
155
|
+
queryKey: computed(() => ['billing', base, 'terms', clientId.value]),
|
|
156
|
+
queryFn: () => api.get(`${base}/clients/${clientId.value}/terms`),
|
|
157
|
+
enabled: computed(() => !!clientId.value),
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
const saveTerms = mutation(({ clientId, body }: { clientId: string; body: Record<string, any> }) => api.put(`${base}/clients/${clientId}/terms`, body))
|
|
161
|
+
const applyCredit = mutation(({ clientId, invoiceId }: { clientId: string; invoiceId?: string | null }) =>
|
|
162
|
+
post(`clients/${clientId}/apply-credit`, { invoice_id: invoiceId ?? null }) as Promise<{ applied: number; credit_available: number }>)
|
|
163
|
+
|
|
164
|
+
function account(clientId: Ref<string>, params: Ref<Record<string, any>>) {
|
|
165
|
+
return useQuery({
|
|
166
|
+
queryKey: computed(() => ['billing', base, 'account', clientId.value, { ...params.value }]),
|
|
167
|
+
queryFn: () => api.get(`${base}/clients/${clientId.value}/account`, { params: compact(params.value) }),
|
|
168
|
+
enabled: computed(() => !!clientId.value),
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function activity(filters: Ref<Record<string, any>>) {
|
|
173
|
+
return useQuery({
|
|
174
|
+
queryKey: computed(() => ['billing', base, 'activity', { ...filters.value }]),
|
|
175
|
+
queryFn: () => api.get(`${base}/activity`, { params: compact(filters.value) }),
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const voidInvoice = mutation(({ id, reason }: { id: string; reason: string }) => post(`invoices/${id}/void`, { reason }) as Promise<Invoice>)
|
|
180
|
+
const reissue = mutation(({ id, body }: { id: string; body: Record<string, any> }) => post(`invoices/${id}/reissue`, body) as Promise<Invoice>)
|
|
181
|
+
const waiveLateFees = mutation(({ id, reason }: { id: string; reason: string }) =>
|
|
182
|
+
post(`invoices/${id}/waive-late-fees`, { reason }) as Promise<{ removed: number; credited: number }>)
|
|
183
|
+
|
|
184
|
+
// Reconciliation
|
|
185
|
+
const { upload } = useFile()
|
|
186
|
+
const preview = (file: File, headerRow?: number | null) =>
|
|
187
|
+
upload(`${base}/reconciliation/preview`, file, { extraData: { header_row: headerRow ?? null } }) as Promise<any>
|
|
188
|
+
const importStatement = mutation(({ file, mapping, bank, headerRow }: { file: File; mapping: Record<string, string>; bank?: string | null; headerRow?: number | null }) =>
|
|
189
|
+
upload(`${base}/reconciliation/imports`, file, { extraData: { mapping: compact(mapping), bank: bank || null, header_row: headerRow ?? null } }) as Promise<any>)
|
|
190
|
+
const imports = useQuery({
|
|
191
|
+
queryKey: ['billing', base, 'bank-imports'],
|
|
192
|
+
queryFn: () => api.get(`${base}/reconciliation/imports`),
|
|
193
|
+
select: (res: any) => (res?.data ?? []) as any[],
|
|
194
|
+
// Poll while an import is queued or running.
|
|
195
|
+
refetchInterval: (query: any) => ((query.state.data?.data ?? []) as any[]).some(i => i.status === 'pending' || i.status === 'processing') ? 3000 : false,
|
|
196
|
+
})
|
|
197
|
+
function transactions(filters: Ref<Record<string, any>>) {
|
|
198
|
+
return useQuery({
|
|
199
|
+
queryKey: computed(() => ['billing', base, 'bank-transactions', { ...filters.value }]),
|
|
200
|
+
queryFn: () => api.get(`${base}/reconciliation/transactions`, { params: compact(filters.value) }),
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
const openInvoices = (params: { client_id?: string | null; q?: string | null }) =>
|
|
204
|
+
api.get(`${base}/reconciliation/open-invoices`, { params: compact(params) }).then((res: any) => (res?.data ?? []) as Invoice[])
|
|
205
|
+
const match = mutation(({ id, clientId, invoiceIds }: { id: string; clientId: string; invoiceIds: string[] }) =>
|
|
206
|
+
post(`reconciliation/transactions/${id}/match`, { client_id: clientId, invoice_ids: invoiceIds }) as Promise<BankTransaction>)
|
|
207
|
+
const unmatch = mutation(({ id, reason }: { id: string; reason: string }) => post(`reconciliation/transactions/${id}/unmatch`, { reason }))
|
|
208
|
+
const ignore = mutation(({ id, reason }: { id: string; reason?: string | null }) => post(`reconciliation/transactions/${id}/ignore`, { reason: reason ?? null }))
|
|
209
|
+
const restore = mutation((id: string) => post(`reconciliation/transactions/${id}/restore`))
|
|
210
|
+
const rematch = mutation((importId?: string | null) => post('reconciliation/rematch', { import_id: importId ?? null }) as Promise<{ matched: number; suggested: number; unmatched: number }>)
|
|
211
|
+
|
|
212
|
+
function report(name: Ref<string>, params: Ref<Record<string, any>>) {
|
|
213
|
+
return useQuery({
|
|
214
|
+
queryKey: computed(() => ['billing', base, 'report', name.value, { ...params.value }]),
|
|
215
|
+
queryFn: () => api.get(`${base}/reports/${name.value}`, { params: compact(params.value) }),
|
|
216
|
+
enabled: computed(() => !!name.value),
|
|
217
|
+
})
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
base, plans, meters, savePlan, invoices, invoice, issue, resend, registerPayment, space,
|
|
222
|
+
startSubscription, updateSubscription, subscriptionAction, clientTotals, settings, saveSettings, run,
|
|
223
|
+
adjustments, createAdjustment, cancelAdjustment, createCreditNote, terms, saveTerms, applyCredit, account, activity,
|
|
224
|
+
voidInvoice, reissue, waiveLateFees, preview, importStatement, imports, transactions, openInvoices, match, unmatch,
|
|
225
|
+
ignore, restore, rematch, report,
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Backoffice billing of the active space, read-only (innertia-laravel \Innertia\Billing\Routes::backoffice()).
|
|
231
|
+
* `base`: default 'billing'.
|
|
232
|
+
*/
|
|
233
|
+
export function useBillingSpace(options: { base?: string } = {}) {
|
|
234
|
+
const base = clean(options.base, 'billing')
|
|
235
|
+
const api = useApi()
|
|
236
|
+
|
|
237
|
+
const overview = useQuery({ queryKey: ['billing-space', base, 'overview'], queryFn: () => api.get(`${base}/overview`) })
|
|
238
|
+
const invoices = useQuery({
|
|
239
|
+
queryKey: ['billing-space', base, 'invoices'],
|
|
240
|
+
queryFn: () => api.get(`${base}/invoices`),
|
|
241
|
+
select: (res: any) => (res?.data ?? []) as Invoice[],
|
|
242
|
+
})
|
|
243
|
+
const payments = useQuery({
|
|
244
|
+
queryKey: ['billing-space', base, 'payments'],
|
|
245
|
+
queryFn: () => api.get(`${base}/payments`),
|
|
246
|
+
select: (res: any) => (res?.data ?? []) as any[],
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
function account(params: Ref<Record<string, any>>) {
|
|
250
|
+
return useQuery({
|
|
251
|
+
queryKey: computed(() => ['billing-space', base, 'account', { ...params.value }]),
|
|
252
|
+
queryFn: () => api.get(`${base}/account`, { params: compact(params.value) }),
|
|
253
|
+
})
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return { base, overview, invoices, payments, account }
|
|
257
|
+
}
|
|
@@ -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,120 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
adjustmentPayload, adjustmentValue, adjustmentStatus, creditNotePayload, reissuePayload, mappingError, allocationPreview,
|
|
4
|
+
transactionStatus, matchReasonLabel, scoreSeverity, reportCell, isNumericColumn, parseReminderDays, yearToDate,
|
|
5
|
+
activityLabel, movementLabel, eventLabel, importStatus, type AdjustmentForm,
|
|
6
|
+
} from '../billing'
|
|
7
|
+
|
|
8
|
+
const adj = (over: Partial<AdjustmentForm> = {}): AdjustmentForm => ({
|
|
9
|
+
scope: 'space', tenant_key: 'rancagua', type: 'discount', mode: 'amount', value: '10.000', recurring: true,
|
|
10
|
+
starts_at: '2026-11-01', ends_at: '2026-12-31', reason: ' Lanzamiento ', ...over,
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
describe('cobranza: ajustes y notas de crédito', () => {
|
|
14
|
+
it('arma el payload de un ajuste por espacio y valida', () => {
|
|
15
|
+
expect(adjustmentPayload(adj(), 'c1').payload).toEqual({
|
|
16
|
+
tenant_key: 'rancagua', type: 'discount', amount: 10000, recurring: true, starts_at: '2026-11-01', ends_at: '2026-12-31', reason: 'Lanzamiento',
|
|
17
|
+
})
|
|
18
|
+
expect(adjustmentPayload(adj({ reason: '' }), 'c1').error).toBe('El motivo es obligatorio.')
|
|
19
|
+
expect(adjustmentPayload(adj({ value: '0' }), 'c1').error).toBe('Ingresa un monto válido.')
|
|
20
|
+
expect(adjustmentPayload(adj({ mode: 'percent', value: '120' }), 'c1').error).toContain('porcentaje')
|
|
21
|
+
expect(adjustmentPayload(adj({ ends_at: '2026-10-01' }), 'c1').error).toContain('vigencia')
|
|
22
|
+
// one-off: never recurring, no end
|
|
23
|
+
expect(adjustmentPayload(adj({ type: 'one_off' }), 'c1').payload).toMatchObject({ recurring: false, ends_at: null })
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('a nivel de cliente solo admite porcentajes de descuento o recargo', () => {
|
|
27
|
+
expect(adjustmentPayload(adj({ scope: 'client' }), 'c1').error).toContain('porcentuales')
|
|
28
|
+
expect(adjustmentPayload(adj({ scope: 'client', mode: 'percent', value: '10,5' }), 'c1').payload).toMatchObject({ client_id: 'c1', percent: 10.5 })
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('muestra valor y estado del ajuste', () => {
|
|
32
|
+
expect(adjustmentValue({ type: 'discount', amount: 10000, percent: null })).toBe('- $ 10.000')
|
|
33
|
+
expect(adjustmentValue({ type: 'surcharge', amount: null, percent: 15 })).toBe('+ 15 %')
|
|
34
|
+
expect(adjustmentStatus('applied')).toEqual({ label: 'Aplicado', severity: 'success' })
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('arma la nota de crédito según el destino', () => {
|
|
38
|
+
const base = { amount: '$ 19.000', reason: 'Caída', invoice_id: 'i1', tenant_key: 'rancagua' }
|
|
39
|
+
expect(creditNotePayload({ ...base, target: 'invoice' }, 'c1').payload).toEqual({ client_id: 'c1', amount: 19000, reason: 'Caída', target: 'invoice', invoice_id: 'i1', tenant_key: null })
|
|
40
|
+
expect(creditNotePayload({ ...base, target: 'next_period' }, 'c1').payload).toMatchObject({ invoice_id: null, tenant_key: 'rancagua' })
|
|
41
|
+
expect(creditNotePayload({ ...base, target: 'invoice', invoice_id: '' }, 'c1').error).toBe('Elige la factura.')
|
|
42
|
+
expect(creditNotePayload({ ...base, target: 'balance', amount: '' }, 'c1').error).toBe('Ingresa un monto válido.')
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
describe('cobranza: refacturación', () => {
|
|
47
|
+
it('envía solo los datos cambiados y líneas con signo', () => {
|
|
48
|
+
const { payload } = reissuePayload({
|
|
49
|
+
reason: ' RUT mal ', billing_data: { tax_id: '76.222.222-2', legal_name: 'X SpA' }, original: { tax_id: '76.111.111-1', legal_name: 'X SpA' },
|
|
50
|
+
lines: [{ description: 'Descuento', amount: '-10.000' }, { description: '', amount: '' }], due_at: '', send: false,
|
|
51
|
+
})
|
|
52
|
+
expect(payload).toEqual({
|
|
53
|
+
reason: 'RUT mal', billing_data: { tax_id: '76.222.222-2' }, lines: [{ description: 'Descuento', amount: -10000, tenant_key: null }], due_at: null, send: false,
|
|
54
|
+
})
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('exige motivo y líneas completas', () => {
|
|
58
|
+
const base = { billing_data: {}, original: {}, due_at: '', send: true }
|
|
59
|
+
expect(reissuePayload({ ...base, reason: '', lines: [] }).error).toBe('El motivo es obligatorio.')
|
|
60
|
+
expect(reissuePayload({ ...base, reason: 'x', lines: [{ description: 'a', amount: '0' }] }).error).toContain('distinto de cero')
|
|
61
|
+
expect(reissuePayload({ ...base, reason: 'x', lines: [] }).payload?.billing_data).toBeNull()
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('etiqueta los eventos nuevos de la bitácora', () => {
|
|
65
|
+
expect(eventLabel('credit_note')).toBe('Nota de crédito')
|
|
66
|
+
expect(eventLabel('late_fee_waived')).toBe('Interés condonado')
|
|
67
|
+
expect(eventLabel('reminder_sent')).toBe('Recordatorio enviado')
|
|
68
|
+
})
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
describe('cobranza: conciliación', () => {
|
|
72
|
+
it('valida el mapeo de columnas', () => {
|
|
73
|
+
expect(mappingError({})).toBe('Elige la columna de fecha.')
|
|
74
|
+
expect(mappingError({ date: 'Fecha' })).toContain('abonos')
|
|
75
|
+
expect(mappingError({ date: 'Fecha', credit: 'Fecha' })).toContain('dos campos')
|
|
76
|
+
expect(mappingError({ date: 'Fecha', amount: 'Monto', description: '' })).toBeNull()
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('previsualiza la aplicación: parcial, varias facturas y saldo a favor', () => {
|
|
80
|
+
const invoices = [{ id: 'a', balance: 119000 }, { id: 'b', balance: 119000 }]
|
|
81
|
+
expect(allocationPreview(200000, invoices, ['a', 'b'])).toEqual({
|
|
82
|
+
rows: [{ id: 'a', applied: 119000, remaining: 0 }, { id: 'b', applied: 81000, remaining: 38000 }], credit: 0,
|
|
83
|
+
})
|
|
84
|
+
expect(allocationPreview(200000, invoices, ['a']).credit).toBe(81000)
|
|
85
|
+
expect(allocationPreview(50000, invoices, ['b', 'a']).rows).toEqual([{ id: 'b', applied: 50000, remaining: 69000 }, { id: 'a', applied: 0, remaining: 119000 }])
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('etiqueta estados, razones y puntajes', () => {
|
|
89
|
+
expect(transactionStatus('suggested').label).toBe('Con sugerencia')
|
|
90
|
+
expect(importStatus('failed').severity).toBe('danger')
|
|
91
|
+
expect(matchReasonLabel('tax_id_in_text')).toBe('RUT en la glosa')
|
|
92
|
+
expect(scoreSeverity(90)).toBe('success')
|
|
93
|
+
expect(scoreSeverity(65)).toBe('info')
|
|
94
|
+
expect(scoreSeverity(40)).toBe('warning')
|
|
95
|
+
})
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
describe('cobranza: estado de cuenta, reportes y recordatorios', () => {
|
|
99
|
+
it('formatea celdas de reportes', () => {
|
|
100
|
+
expect(reportCell('total', 238000)).toBe('$ 238.000')
|
|
101
|
+
expect(reportCell('d31_60', 0)).toBe('$ 0')
|
|
102
|
+
expect(reportCell('invoices', 1200)).toBe('1.200')
|
|
103
|
+
expect(reportCell('due_at', '2026-12-31')).toBe('31-12-2026')
|
|
104
|
+
expect(reportCell('label', null)).toBe('—')
|
|
105
|
+
expect(isNumericColumn('balance')).toBe(true)
|
|
106
|
+
expect(isNumericColumn('client')).toBe(false)
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
it('lee los días de recordatorio', () => {
|
|
110
|
+
expect(parseReminderDays('3, 7,7')).toEqual([7, 3])
|
|
111
|
+
expect(parseReminderDays('')).toEqual([])
|
|
112
|
+
expect(parseReminderDays('7;3')).toBeNull()
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it('rango del año y etiquetas', () => {
|
|
116
|
+
expect(yearToDate(new Date(2026, 10, 19))).toEqual({ from: '2026-01-01', to: '2026-11-19' })
|
|
117
|
+
expect(activityLabel('bank_transaction', 'auto_matched')).toBe('Movimiento bancario conciliado automáticamente')
|
|
118
|
+
expect(movementLabel('credit_note')).toBe('Nota de crédito')
|
|
119
|
+
})
|
|
120
|
+
})
|