@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,87 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { IconDownload } from '@tabler/icons-vue'
|
|
3
|
+
import { REPORTS, reportCell, isNumericColumn, yearToDate } from '../../composables/useBilling/internal/billing'
|
|
4
|
+
|
|
5
|
+
/*
|
|
6
|
+
* Billing.Reports — collection reports: invoiced revenue (by month/client/plan/product), receivables,
|
|
7
|
+
* debt aging (0–30, 31–60, 61–90, 90+), collections (by month/method/client), MRR and consumption by
|
|
8
|
+
* space, with date range and .xlsx export.
|
|
9
|
+
* Backend: GET {endpoint}/reports/{report}(/export)?from=&to=&group_by=.
|
|
10
|
+
*
|
|
11
|
+
* <Billing.Reports />
|
|
12
|
+
*/
|
|
13
|
+
const props = withDefaults(defineProps<{ endpoint?: string; initial?: string }>(), { endpoint: 'platform/billing', initial: 'revenue' })
|
|
14
|
+
|
|
15
|
+
const toast = useToast()
|
|
16
|
+
const billing = useBillingPlatform({ base: props.endpoint })
|
|
17
|
+
const download = useBillingDownload()
|
|
18
|
+
const active = ref(props.initial)
|
|
19
|
+
const def = computed(() => REPORTS.find(r => r.key === active.value) ?? REPORTS[0])
|
|
20
|
+
const range = reactive({ ...yearToDate(), group_by: '' })
|
|
21
|
+
watch(active, () => { range.group_by = def.value.groups[0]?.value ?? '' }, { immediate: true })
|
|
22
|
+
const params = computed(() => def.value.dated ? { from: range.from, to: range.to, group_by: range.group_by } : { group_by: range.group_by })
|
|
23
|
+
const query = billing.report(active, params)
|
|
24
|
+
const data = computed<any>(() => query.data.value)
|
|
25
|
+
const columns = computed<[string, string][]>(() => Object.entries(data.value?.columns ?? {}))
|
|
26
|
+
|
|
27
|
+
async function exportXlsx() {
|
|
28
|
+
try {
|
|
29
|
+
await download(`${billing.base}/reports/${active.value}/export`, `${active.value}.xlsx`, params.value)
|
|
30
|
+
} catch {
|
|
31
|
+
toast.error('No se pudo descargar el reporte.')
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const inputClass = 'h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
|
|
36
|
+
</script>
|
|
37
|
+
|
|
38
|
+
<template>
|
|
39
|
+
<div class="space-y-4">
|
|
40
|
+
<div class="flex flex-wrap gap-2 text-sm">
|
|
41
|
+
<button v-for="r in REPORTS" :key="r.key" type="button" class="px-3 py-1.5 rounded-control border"
|
|
42
|
+
:class="active === r.key ? 'border-primary bg-primary/10 text-primary' : 'border-card-line text-muted-foreground hover:text-foreground'" @click="active = r.key">
|
|
43
|
+
{{ r.label }}
|
|
44
|
+
</button>
|
|
45
|
+
</div>
|
|
46
|
+
|
|
47
|
+
<div class="flex flex-wrap items-end gap-3 text-sm">
|
|
48
|
+
<template v-if="def.dated">
|
|
49
|
+
<label class="space-y-1"><span class="block text-xs text-muted-foreground">Desde</span><input v-model="range.from" type="date" :class="inputClass" /></label>
|
|
50
|
+
<label class="space-y-1"><span class="block text-xs text-muted-foreground">Hasta</span><input v-model="range.to" type="date" :class="inputClass" /></label>
|
|
51
|
+
</template>
|
|
52
|
+
<label v-if="def.groups.length" class="space-y-1"><span class="block text-xs text-muted-foreground">Agrupar por</span>
|
|
53
|
+
<select v-model="range.group_by" :class="inputClass"><option v-for="g in def.groups" :key="g.value" :value="g.value">{{ g.label }}</option></select>
|
|
54
|
+
</label>
|
|
55
|
+
<span class="flex-1" />
|
|
56
|
+
<App.Button text="Excel" size="sm" outline :icon="IconDownload" @click="exportXlsx" />
|
|
57
|
+
</div>
|
|
58
|
+
|
|
59
|
+
<div class="bg-card border border-card-line rounded-card overflow-x-auto">
|
|
60
|
+
<div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
|
|
61
|
+
<div v-else-if="query.isError.value || !data" class="p-8 text-center text-sm text-muted-foreground">
|
|
62
|
+
No se pudo cargar el reporte.
|
|
63
|
+
<button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
|
|
64
|
+
</div>
|
|
65
|
+
<div v-else-if="!data.rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin datos para el período.</div>
|
|
66
|
+
<table v-else class="w-full text-sm">
|
|
67
|
+
<thead class="text-xs uppercase text-muted-foreground">
|
|
68
|
+
<tr class="border-b border-card-line">
|
|
69
|
+
<th v-for="[key, label] in columns" :key="key" class="font-medium px-4 py-2" :class="isNumericColumn(key) ? 'text-right' : 'text-left'">{{ label }}</th>
|
|
70
|
+
</tr>
|
|
71
|
+
</thead>
|
|
72
|
+
<tbody class="divide-y divide-card-line">
|
|
73
|
+
<tr v-for="(row, idx) in data.rows" :key="idx">
|
|
74
|
+
<td v-for="[key] in columns" :key="key" class="px-4 py-2" :class="isNumericColumn(key) ? 'text-right whitespace-nowrap' : ''">{{ reportCell(key, row[key]) }}</td>
|
|
75
|
+
</tr>
|
|
76
|
+
</tbody>
|
|
77
|
+
<tfoot v-if="Object.keys(data.totals ?? {}).length" class="border-t border-card-line font-medium">
|
|
78
|
+
<tr>
|
|
79
|
+
<td v-for="([key], i) in columns" :key="key" class="px-4 py-2" :class="isNumericColumn(key) ? 'text-right whitespace-nowrap' : ''">
|
|
80
|
+
{{ i === 0 ? 'Total' : (key in data.totals ? reportCell(key, data.totals[key]) : '') }}
|
|
81
|
+
</td>
|
|
82
|
+
</tr>
|
|
83
|
+
</tfoot>
|
|
84
|
+
</table>
|
|
85
|
+
</div>
|
|
86
|
+
</div>
|
|
87
|
+
</template>
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { errorMessage, parseReminderDays } from '../../composables/useBilling/internal/billing'
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Billing.Settings — platform billing settings (owner): USD→CLP rate used to value AI cost, transfer
|
|
6
|
+
* instructions shown in the invoice email/PDF and the issuer block of the PDF; plus manual runs of
|
|
7
|
+
* the daily close, dunning and payment reminders (they also run on the scheduler, America/Santiago).
|
|
8
|
+
* Reminders: days before the due date, the due day, every N days while overdue (max), escalation (copy to
|
|
9
|
+
* the collections email + critical notice) after N overdue reminders.
|
|
10
|
+
* Backend: GET|PUT {endpoint}/settings, POST {endpoint}/run/{close|dunning|reminders}.
|
|
11
|
+
*/
|
|
12
|
+
const props = withDefaults(defineProps<{ endpoint?: string; canRun?: boolean }>(), { endpoint: 'platform/billing', canRun: true })
|
|
13
|
+
|
|
14
|
+
const toast = useToast()
|
|
15
|
+
const { confirm } = useModal()
|
|
16
|
+
const { settings, saveSettings, run } = useBillingPlatform({ base: props.endpoint })
|
|
17
|
+
const form = reactive({
|
|
18
|
+
usd_clp_rate: '' as string | number, transfer_instructions: '', issuer_name: '', issuer_tax_id: '', issuer_address: '',
|
|
19
|
+
reminders_enabled: true, reminder_days_before: '3', reminder_on_due: true, reminder_overdue_every_days: 7 as number | string,
|
|
20
|
+
reminder_overdue_max: 6 as number | string, reminder_escalate_after: 2 as number | string, reminder_escalation_email: '',
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
watch(() => settings.data.value, (s: any) => {
|
|
24
|
+
if (s) {
|
|
25
|
+
Object.assign(form, {
|
|
26
|
+
usd_clp_rate: s.usd_clp_rate ?? '', transfer_instructions: s.transfer_instructions ?? '', issuer_name: s.issuer_name ?? '', issuer_tax_id: s.issuer_tax_id ?? '', issuer_address: s.issuer_address ?? '',
|
|
27
|
+
reminders_enabled: s.reminders_enabled ?? true, reminder_days_before: s.reminder_days_before ?? '', reminder_on_due: s.reminder_on_due ?? true,
|
|
28
|
+
reminder_overdue_every_days: s.reminder_overdue_every_days ?? 7, reminder_overdue_max: s.reminder_overdue_max ?? 6,
|
|
29
|
+
reminder_escalate_after: s.reminder_escalate_after ?? 2, reminder_escalation_email: s.reminder_escalation_email ?? '',
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
}, { immediate: true })
|
|
33
|
+
|
|
34
|
+
async function save() {
|
|
35
|
+
const days = parseReminderDays(form.reminder_days_before)
|
|
36
|
+
if (days === null) { toast.error('Días antes del vencimiento: números separados por coma (ej. 7, 3).'); return }
|
|
37
|
+
try {
|
|
38
|
+
await saveSettings.mutateAsync({
|
|
39
|
+
usd_clp_rate: form.usd_clp_rate === '' ? null : Number(form.usd_clp_rate),
|
|
40
|
+
transfer_instructions: form.transfer_instructions || null,
|
|
41
|
+
issuer_name: form.issuer_name || null, issuer_tax_id: form.issuer_tax_id || null, issuer_address: form.issuer_address || null,
|
|
42
|
+
reminders_enabled: form.reminders_enabled, reminder_days_before: days.join(',') || null, reminder_on_due: form.reminder_on_due,
|
|
43
|
+
reminder_overdue_every_days: Number(form.reminder_overdue_every_days) || 7, reminder_overdue_max: Number(form.reminder_overdue_max) || 0,
|
|
44
|
+
reminder_escalate_after: Number(form.reminder_escalate_after) || 0, reminder_escalation_email: form.reminder_escalation_email || null,
|
|
45
|
+
})
|
|
46
|
+
toast.success('Configuración guardada.')
|
|
47
|
+
} catch (e: any) {
|
|
48
|
+
toast.error(errorMessage(e, 'No se pudo guardar.'))
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const JOBS = {
|
|
53
|
+
close: ['Cerrar períodos ahora', 'Se cierran los períodos vencidos y se generan las facturas en borrador. Es idempotente: no duplica cobros.'],
|
|
54
|
+
dunning: ['Revisar mora ahora', 'Se marcan las facturas vencidas y se actualiza el estado de las suscripciones (mora, suspensión, reactivación).'],
|
|
55
|
+
reminders: ['Enviar recordatorios ahora', 'Se envían los recordatorios que correspondan hoy. Nunca repite uno ya enviado.'],
|
|
56
|
+
} as const
|
|
57
|
+
|
|
58
|
+
async function runJob(job: 'close' | 'dunning' | 'reminders') {
|
|
59
|
+
const ok = await confirm({
|
|
60
|
+
title: JOBS[job][0],
|
|
61
|
+
message: JOBS[job][1],
|
|
62
|
+
confirmText: 'Ejecutar',
|
|
63
|
+
})
|
|
64
|
+
if (!ok) return
|
|
65
|
+
try {
|
|
66
|
+
const res: any = await run.mutateAsync(job)
|
|
67
|
+
toast.success(job === 'close' ? `Cierre listo: ${res?.statements ?? 0} cobros nuevos.`
|
|
68
|
+
: job === 'dunning' ? `Mora revisada: ${res?.overdue ?? 0} facturas vencidas, ${res?.changed ?? 0} cambios.`
|
|
69
|
+
: `Recordatorios: ${res?.sent ?? 0} enviados (${res?.escalated ?? 0} escalados).`)
|
|
70
|
+
} catch (e: any) {
|
|
71
|
+
toast.error(errorMessage(e, 'No se pudo ejecutar.'))
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
|
|
76
|
+
</script>
|
|
77
|
+
|
|
78
|
+
<template>
|
|
79
|
+
<div class="space-y-4">
|
|
80
|
+
<form class="bg-card border border-card-line rounded-card p-4 grid gap-3 sm:grid-cols-2 text-sm" @submit.prevent="save">
|
|
81
|
+
<label class="block space-y-1"><span class="font-medium">Tipo de cambio USD → CLP</span>
|
|
82
|
+
<input v-model="form.usd_clp_rate" type="number" min="1" step="0.01" :class="inputClass" />
|
|
83
|
+
<span class="text-xs text-muted-foreground">Valoriza el costo de IA de cada uso desde ahora.</span>
|
|
84
|
+
</label>
|
|
85
|
+
<span />
|
|
86
|
+
<label class="block space-y-1"><span class="font-medium">Emisor (razón social)</span><input v-model="form.issuer_name" :class="inputClass" maxlength="150" /></label>
|
|
87
|
+
<label class="block space-y-1"><span class="font-medium">RUT del emisor</span><input v-model="form.issuer_tax_id" :class="inputClass" maxlength="20" /></label>
|
|
88
|
+
<label class="block space-y-1 sm:col-span-2"><span class="font-medium">Dirección del emisor</span><input v-model="form.issuer_address" :class="inputClass" maxlength="250" /></label>
|
|
89
|
+
<label class="block space-y-1 sm:col-span-2"><span class="font-medium">Datos para transferencia</span>
|
|
90
|
+
<textarea v-model="form.transfer_instructions" rows="3" maxlength="1000" class="w-full rounded-control border border-card-line bg-card text-sm text-foreground px-3 py-2" placeholder="Banco, tipo y número de cuenta, RUT, correo de aviso" />
|
|
91
|
+
</label>
|
|
92
|
+
<p class="sm:col-span-2 font-medium text-foreground pt-2">Recordatorios de pago</p>
|
|
93
|
+
<label class="sm:col-span-2 flex items-center gap-2"><input v-model="form.reminders_enabled" type="checkbox" class="rounded" /> Enviar recordatorios por correo (marca de la plataforma) y avisos a los administradores del espacio</label>
|
|
94
|
+
<label class="block space-y-1"><span class="font-medium">Días antes del vencimiento</span><input v-model="form.reminder_days_before" :class="inputClass" placeholder="7, 3" /></label>
|
|
95
|
+
<label class="flex items-center gap-2 self-end h-9"><input v-model="form.reminder_on_due" type="checkbox" class="rounded" /> El día que vence</label>
|
|
96
|
+
<label class="block space-y-1"><span class="font-medium">Vencida: cada cuántos días</span><input v-model="form.reminder_overdue_every_days" type="number" min="1" max="90" :class="inputClass" /></label>
|
|
97
|
+
<label class="block space-y-1"><span class="font-medium">Máximo de recordatorios de vencida</span><input v-model="form.reminder_overdue_max" type="number" min="0" max="50" :class="inputClass" /></label>
|
|
98
|
+
<label class="block space-y-1"><span class="font-medium">Escalar después de (recordatorios de vencida)</span><input v-model="form.reminder_escalate_after" type="number" min="0" max="50" :class="inputClass" /></label>
|
|
99
|
+
<label class="block space-y-1"><span class="font-medium">Correo de cobranza (copia al escalar)</span><input v-model="form.reminder_escalation_email" type="email" :class="inputClass" maxlength="150" /></label>
|
|
100
|
+
<div class="sm:col-span-2 flex justify-end">
|
|
101
|
+
<App.Button text="Guardar" severity="primary" size="sm" :loading="saveSettings.isPending.value" @click="save" />
|
|
102
|
+
</div>
|
|
103
|
+
</form>
|
|
104
|
+
|
|
105
|
+
<div v-if="canRun" class="bg-card border border-card-line rounded-card p-4 flex flex-wrap items-center gap-3 text-sm">
|
|
106
|
+
<p class="flex-1 text-muted-foreground">El cierre (00:30), la revisión de mora (08:00) y los recordatorios (09:00) corren solos cada día, hora de Chile.</p>
|
|
107
|
+
<App.Button text="Cerrar períodos" size="sm" :loading="run.isPending.value" @click="runJob('close')" />
|
|
108
|
+
<App.Button text="Revisar mora" size="sm" :loading="run.isPending.value" @click="runJob('dunning')" />
|
|
109
|
+
<App.Button text="Enviar recordatorios" size="sm" :loading="run.isPending.value" @click="runJob('reminders')" />
|
|
110
|
+
</div>
|
|
111
|
+
</div>
|
|
112
|
+
</template>
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { IconPlayerPause, IconPlayerPlay, IconX } from '@tabler/icons-vue'
|
|
3
|
+
import {
|
|
4
|
+
formatMoney, subscriptionStatus, periodLabel, formatDate, paymentMethodLabel, parseMoney, errorMessage,
|
|
5
|
+
PAYMENT_METHODS, type Plan, type Subscription, type Statement,
|
|
6
|
+
} from '../../composables/useBilling/internal/billing'
|
|
7
|
+
|
|
8
|
+
/*
|
|
9
|
+
* Billing.SpaceSubscription — subscription of one space (platform › client › space): start it
|
|
10
|
+
* (plan, payment method, trial, negotiated prices), change plan (rules from the next period),
|
|
11
|
+
* payment method, suspend / reactivate / cancel, consumption of the period with the estimate and
|
|
12
|
+
* the closed statements. Testing spaces show a notice: they are never billed.
|
|
13
|
+
* Backend: GET {endpoint}/spaces/{key} + writes of \Innertia\Billing\Routes::platformWrite().
|
|
14
|
+
*
|
|
15
|
+
* <Billing.SpaceSubscription space-key="rancagua" :can-edit="isOwner" />
|
|
16
|
+
*/
|
|
17
|
+
const props = withDefaults(defineProps<{ spaceKey: string; endpoint?: string; canEdit?: boolean }>(), { endpoint: 'platform/billing', canEdit: true })
|
|
18
|
+
|
|
19
|
+
const toast = useToast()
|
|
20
|
+
const { confirm } = useModal()
|
|
21
|
+
const billing = useBillingPlatform({ base: props.endpoint })
|
|
22
|
+
const key = computed(() => props.spaceKey)
|
|
23
|
+
const query = billing.space(key)
|
|
24
|
+
const data = computed<any>(() => query.data.value)
|
|
25
|
+
const sub = computed<Subscription | null>(() => data.value?.subscription ?? null)
|
|
26
|
+
const plans = computed<Plan[]>(() => ((billing.plans.data.value as Plan[] | undefined) ?? []).filter(p => p.active))
|
|
27
|
+
const statements = computed<Statement[]>(() => data.value?.statements ?? [])
|
|
28
|
+
|
|
29
|
+
// ── Start ─────────────────────────────────────────────────────────────────
|
|
30
|
+
const start = reactive({ open: false, plan_id: '', payment_method: 'invoice', trial_days: '' as string | number, starts_at: '', base_price: '', seat_price: '' })
|
|
31
|
+
function openStart() {
|
|
32
|
+
Object.assign(start, { open: true, plan_id: plans.value[0]?.id ?? '', payment_method: 'invoice', trial_days: '', starts_at: new Date().toISOString().slice(0, 10), base_price: '', seat_price: '' })
|
|
33
|
+
}
|
|
34
|
+
function overridesFrom(base: string, seat: string) {
|
|
35
|
+
const o: Record<string, number> = {}
|
|
36
|
+
const b = parseMoney(base); const s = parseMoney(seat)
|
|
37
|
+
if (b !== null && !Number.isNaN(b)) o.base_price = b
|
|
38
|
+
if (s !== null && !Number.isNaN(s)) o.seat_price = s
|
|
39
|
+
return o
|
|
40
|
+
}
|
|
41
|
+
async function submitStart() {
|
|
42
|
+
if (!start.plan_id) { toast.error('Elige un plan.'); return }
|
|
43
|
+
try {
|
|
44
|
+
await billing.startSubscription.mutateAsync({ key: props.spaceKey, body: {
|
|
45
|
+
plan_id: start.plan_id, payment_method: start.payment_method, starts_at: start.starts_at || null,
|
|
46
|
+
trial_days: start.trial_days === '' ? null : Number(start.trial_days), overrides: overridesFrom(start.base_price, start.seat_price),
|
|
47
|
+
} })
|
|
48
|
+
start.open = false
|
|
49
|
+
toast.success('Suscripción iniciada.')
|
|
50
|
+
} catch (e: any) {
|
|
51
|
+
toast.error(errorMessage(e, 'No se pudo iniciar la suscripción.'))
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ── Edit ──────────────────────────────────────────────────────────────────
|
|
56
|
+
const edit = reactive({ open: false, plan_id: '', payment_method: 'invoice', base_price: '', seat_price: '' })
|
|
57
|
+
function openEdit() {
|
|
58
|
+
const s = sub.value!
|
|
59
|
+
Object.assign(edit, {
|
|
60
|
+
open: true, plan_id: s.pending_plan?.id ?? s.plan?.id ?? '', payment_method: s.payment_method,
|
|
61
|
+
base_price: s.overrides?.base_price ?? '', seat_price: s.overrides?.seat_price ?? '',
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
async function submitEdit() {
|
|
65
|
+
const overrides = { ...(sub.value?.overrides ?? {}) }
|
|
66
|
+
delete overrides.base_price; delete overrides.seat_price
|
|
67
|
+
try {
|
|
68
|
+
await billing.updateSubscription.mutateAsync({ key: props.spaceKey, body: {
|
|
69
|
+
plan_id: edit.plan_id, payment_method: edit.payment_method,
|
|
70
|
+
overrides: { ...overrides, ...overridesFrom(String(edit.base_price), String(edit.seat_price)) },
|
|
71
|
+
} })
|
|
72
|
+
edit.open = false
|
|
73
|
+
toast.success('Suscripción actualizada.')
|
|
74
|
+
} catch (e: any) {
|
|
75
|
+
toast.error(errorMessage(e, 'No se pudo actualizar la suscripción.'))
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function act(action: 'suspend' | 'reactivate' | 'cancel') {
|
|
80
|
+
const texts = {
|
|
81
|
+
suspend: ['Suspender espacio', 'El espacio quedará en solo lectura hasta que lo reactives.', 'Suspender', 'warning'],
|
|
82
|
+
reactivate: ['Reactivar espacio', 'El espacio vuelve a operar. Si aún tiene facturas vencidas quedará "con deuda vencida".', 'Reactivar', 'primary'],
|
|
83
|
+
cancel: ['Cancelar suscripción', 'Se deja de cobrar al espacio desde ahora. Puedes iniciar otra suscripción después.', 'Cancelar suscripción', 'danger'],
|
|
84
|
+
}[action]
|
|
85
|
+
if (!(await confirm({ title: texts[0], message: texts[1], confirmText: texts[2], severity: texts[3] }))) return
|
|
86
|
+
try {
|
|
87
|
+
await billing.subscriptionAction.mutateAsync({ key: props.spaceKey, action })
|
|
88
|
+
toast.success('Listo.')
|
|
89
|
+
} catch (e: any) {
|
|
90
|
+
toast.error(errorMessage(e, 'No se pudo completar la acción.'))
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const inputClass = 'w-full h-9 rounded-control border border-card-line bg-card text-sm text-foreground px-3 focus:outline-hidden focus:ring-2 focus:ring-primary/30'
|
|
95
|
+
</script>
|
|
96
|
+
|
|
97
|
+
<template>
|
|
98
|
+
<div class="space-y-4">
|
|
99
|
+
<div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
|
|
100
|
+
<div v-else-if="query.isError.value || !data" class="p-8 text-center text-sm text-muted-foreground">
|
|
101
|
+
No se pudo cargar la facturación del espacio.
|
|
102
|
+
<button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
|
|
103
|
+
</div>
|
|
104
|
+
|
|
105
|
+
<div v-else-if="data.testing" class="rounded-card border border-info/40 bg-info/5 p-4 text-sm text-foreground">
|
|
106
|
+
Espacio de pruebas: no tiene suscripción y nunca se cobra.
|
|
107
|
+
</div>
|
|
108
|
+
|
|
109
|
+
<template v-else>
|
|
110
|
+
<div class="bg-card border border-card-line rounded-card p-4">
|
|
111
|
+
<div v-if="!sub" class="flex flex-wrap items-center gap-3">
|
|
112
|
+
<p class="flex-1 text-sm text-muted-foreground">El espacio no tiene suscripción: no se cobra ni se bloquea.</p>
|
|
113
|
+
<App.Button v-if="canEdit" text="Iniciar suscripción" severity="primary" size="sm" @click="openStart" />
|
|
114
|
+
</div>
|
|
115
|
+
<div v-else class="space-y-2">
|
|
116
|
+
<div class="flex flex-wrap items-center gap-2">
|
|
117
|
+
<p class="text-base font-medium text-foreground">{{ sub.plan?.name }}</p>
|
|
118
|
+
<App.Tag :text="subscriptionStatus(sub.status).label" :severity="subscriptionStatus(sub.status).severity" size="xs" />
|
|
119
|
+
<App.Tag v-if="sub.suspended_manually" text="Suspendido a mano" size="xs" />
|
|
120
|
+
<span class="flex-1" />
|
|
121
|
+
<template v-if="canEdit && sub.status !== 'canceled'">
|
|
122
|
+
<App.Button text="Editar" size="xs" @click="openEdit" />
|
|
123
|
+
<App.Button v-if="sub.status !== 'suspended'" text="Suspender" size="xs" :icon="IconPlayerPause" @click="act('suspend')" />
|
|
124
|
+
<App.Button v-else text="Reactivar" size="xs" :icon="IconPlayerPlay" @click="act('reactivate')" />
|
|
125
|
+
<App.Button text="Cancelar" size="xs" severity="danger" outline :icon="IconX" @click="act('cancel')" />
|
|
126
|
+
</template>
|
|
127
|
+
<App.Button v-if="canEdit && sub.status === 'canceled'" text="Nueva suscripción" size="xs" severity="primary" @click="openStart" />
|
|
128
|
+
</div>
|
|
129
|
+
<p class="text-sm text-muted-foreground">
|
|
130
|
+
Período {{ periodLabel(sub.current_period_start, sub.current_period_end) }} · {{ paymentMethodLabel(sub.payment_method) }}
|
|
131
|
+
<template v-if="sub.trial_ends_at && sub.status === 'trialing'"> · prueba hasta {{ formatDate(sub.trial_ends_at) }}</template>
|
|
132
|
+
</p>
|
|
133
|
+
<p v-if="sub.pending_plan" class="text-sm text-warning">Cambia a {{ sub.pending_plan.name }} desde el próximo período.</p>
|
|
134
|
+
<p v-if="sub.overrides?.base_price !== undefined || sub.overrides?.seat_price !== undefined" class="text-xs text-muted-foreground">
|
|
135
|
+
Precio negociado:
|
|
136
|
+
<template v-if="sub.overrides.base_price !== undefined">base {{ formatMoney(sub.overrides.base_price) }}</template>
|
|
137
|
+
<template v-if="sub.overrides.seat_price !== undefined"> · usuario adicional {{ formatMoney(sub.overrides.seat_price) }}</template>
|
|
138
|
+
</p>
|
|
139
|
+
</div>
|
|
140
|
+
</div>
|
|
141
|
+
|
|
142
|
+
<div v-if="sub && data.estimate" class="bg-card border border-card-line rounded-card p-4 space-y-3">
|
|
143
|
+
<div class="flex items-center justify-between">
|
|
144
|
+
<p class="text-sm font-medium text-foreground">Consumo del período (estimado)</p>
|
|
145
|
+
<p class="text-sm">Total estimado <span class="font-medium">{{ formatMoney(data.estimate.total, data.estimate.currency) }}</span> <span class="text-xs text-muted-foreground">IVA incl.</span></p>
|
|
146
|
+
</div>
|
|
147
|
+
<p class="text-xs text-muted-foreground">
|
|
148
|
+
Base {{ formatMoney(data.estimate.base) }} · Usuarios {{ data.seats?.counted }} de {{ data.seats?.included }} incluidos ({{ formatMoney(data.estimate.seats) }}) · Consumo {{ formatMoney(data.estimate.usage) }}
|
|
149
|
+
</p>
|
|
150
|
+
<Billing.UsageTable :usage="data.usage" :currency="data.estimate.currency" />
|
|
151
|
+
</div>
|
|
152
|
+
|
|
153
|
+
<div v-if="statements.length" class="bg-card border border-card-line rounded-card">
|
|
154
|
+
<p class="text-sm font-medium text-foreground px-4 pt-3">Cobros cerrados</p>
|
|
155
|
+
<ul class="divide-y divide-card-line">
|
|
156
|
+
<li v-for="s in statements" :key="s.id" class="flex items-center gap-3 px-4 py-2 text-sm">
|
|
157
|
+
<span class="flex-1">{{ periodLabel(s.period_start, s.period_end) }}</span>
|
|
158
|
+
<span class="text-xs text-muted-foreground">{{ s.invoice_id ? 'Facturado' : 'Sin factura (monto 0)' }}</span>
|
|
159
|
+
<span class="w-28 text-right font-medium">{{ formatMoney(s.total) }}</span>
|
|
160
|
+
</li>
|
|
161
|
+
</ul>
|
|
162
|
+
</div>
|
|
163
|
+
</template>
|
|
164
|
+
|
|
165
|
+
<Modal v-model="start.open" title="Iniciar suscripción" size="lg" show-footer>
|
|
166
|
+
<div class="grid gap-3 sm:grid-cols-2 text-sm">
|
|
167
|
+
<label class="block space-y-1 sm:col-span-2"><span class="font-medium">Plan</span>
|
|
168
|
+
<select v-model="start.plan_id" :class="inputClass"><option v-for="p in plans" :key="p.id" :value="p.id">{{ p.name }} · {{ formatMoney(p.base_price, p.currency) }}</option></select>
|
|
169
|
+
</label>
|
|
170
|
+
<label class="block space-y-1 sm:col-span-2"><span class="font-medium">Modo de pago</span>
|
|
171
|
+
<select v-model="start.payment_method" :class="inputClass"><option v-for="m in PAYMENT_METHODS" :key="m.value" :value="m.value">{{ m.label }}</option></select>
|
|
172
|
+
</label>
|
|
173
|
+
<label class="block space-y-1"><span class="font-medium">Inicio</span><input v-model="start.starts_at" type="date" :class="inputClass" /></label>
|
|
174
|
+
<label class="block space-y-1"><span class="font-medium">Días de prueba</span><input v-model="start.trial_days" type="number" min="0" placeholder="Los del plan" :class="inputClass" /></label>
|
|
175
|
+
<label class="block space-y-1"><span class="font-medium">Precio base negociado ($)</span><input v-model="start.base_price" inputmode="numeric" placeholder="El del plan" :class="inputClass" /></label>
|
|
176
|
+
<label class="block space-y-1"><span class="font-medium">Usuario adicional negociado ($)</span><input v-model="start.seat_price" inputmode="numeric" placeholder="El del plan" :class="inputClass" /></label>
|
|
177
|
+
</div>
|
|
178
|
+
<template #footer>
|
|
179
|
+
<App.Button text="Cancelar" size="sm" @click="start.open = false" />
|
|
180
|
+
<App.Button text="Iniciar" severity="primary" size="sm" :loading="billing.startSubscription.isPending.value" @click="submitStart" />
|
|
181
|
+
</template>
|
|
182
|
+
</Modal>
|
|
183
|
+
|
|
184
|
+
<Modal v-model="edit.open" title="Editar suscripción" size="lg" show-footer>
|
|
185
|
+
<div class="grid gap-3 sm:grid-cols-2 text-sm">
|
|
186
|
+
<label class="block space-y-1 sm:col-span-2"><span class="font-medium">Plan</span>
|
|
187
|
+
<select v-model="edit.plan_id" :class="inputClass"><option v-for="p in plans" :key="p.id" :value="p.id">{{ p.name }}</option></select>
|
|
188
|
+
<span class="text-xs text-muted-foreground">Un cambio de plan rige desde el próximo período, sin prorrateo.</span>
|
|
189
|
+
</label>
|
|
190
|
+
<label class="block space-y-1 sm:col-span-2"><span class="font-medium">Modo de pago</span>
|
|
191
|
+
<select v-model="edit.payment_method" :class="inputClass"><option v-for="m in PAYMENT_METHODS" :key="m.value" :value="m.value">{{ m.label }}</option></select>
|
|
192
|
+
</label>
|
|
193
|
+
<label class="block space-y-1"><span class="font-medium">Precio base negociado ($)</span><input v-model="edit.base_price" inputmode="numeric" placeholder="El del plan" :class="inputClass" /></label>
|
|
194
|
+
<label class="block space-y-1"><span class="font-medium">Usuario adicional negociado ($)</span><input v-model="edit.seat_price" inputmode="numeric" placeholder="El del plan" :class="inputClass" /></label>
|
|
195
|
+
</div>
|
|
196
|
+
<template #footer>
|
|
197
|
+
<App.Button text="Cancelar" size="sm" @click="edit.open = false" />
|
|
198
|
+
<App.Button text="Guardar" severity="primary" size="sm" :loading="billing.updateSubscription.isPending.value" @click="submitEdit" />
|
|
199
|
+
</template>
|
|
200
|
+
</Modal>
|
|
201
|
+
</div>
|
|
202
|
+
</template>
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { IconAlertTriangle } from '@tabler/icons-vue'
|
|
3
|
+
import { bannerFor } from '../../composables/useBilling/internal/billing'
|
|
4
|
+
|
|
5
|
+
/*
|
|
6
|
+
* Billing.StatusBanner — global backoffice banner when the space is past due or suspended
|
|
7
|
+
* (read-only). Pass `status` (e.g. from the X-Billing-Status header or your own store) or let it
|
|
8
|
+
* fetch GET {endpoint}/overview (only for users with billing.view).
|
|
9
|
+
*
|
|
10
|
+
* <Billing.StatusBanner billing-route="/backoffice/billing" />
|
|
11
|
+
*/
|
|
12
|
+
const props = withDefaults(defineProps<{ status?: string | null; endpoint?: string; billingRoute?: string; fetch?: boolean }>(), {
|
|
13
|
+
status: undefined, endpoint: 'billing', billingRoute: '/backoffice/billing', fetch: true,
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
const api = useApi()
|
|
17
|
+
const fetched = ref<string | null>(null)
|
|
18
|
+
onMounted(async () => {
|
|
19
|
+
if (props.status !== undefined || !props.fetch) return
|
|
20
|
+
try {
|
|
21
|
+
const res: any = await api.get(`${props.endpoint.replace(/^\/+|\/+$/g, '')}/overview`)
|
|
22
|
+
fetched.value = res?.subscription?.status ?? null
|
|
23
|
+
} catch { /* no permission or billing off: no banner */ }
|
|
24
|
+
})
|
|
25
|
+
const banner = computed(() => bannerFor(props.status !== undefined ? props.status : fetched.value))
|
|
26
|
+
</script>
|
|
27
|
+
|
|
28
|
+
<template>
|
|
29
|
+
<div v-if="banner" class="flex flex-wrap items-center gap-3 px-4 py-2 text-sm border-b"
|
|
30
|
+
:class="banner.severity === 'danger' ? 'bg-danger/10 border-danger/30 text-danger' : 'bg-warning/10 border-warning/30 text-warning'" role="alert">
|
|
31
|
+
<IconAlertTriangle class="size-4 shrink-0" />
|
|
32
|
+
<span class="font-medium">{{ banner.title }}.</span>
|
|
33
|
+
<span class="flex-1 text-foreground">{{ banner.message }}</span>
|
|
34
|
+
<NuxtLink :to="billingRoute" class="font-medium underline">Ver facturación</NuxtLink>
|
|
35
|
+
</div>
|
|
36
|
+
</template>
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
import { formatMoney, formatQuantity, usageProgress, type UsageEstimate } from '../../composables/useBilling/internal/billing'
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Billing.UsageTable — consumption of the current period per meter vs what the plan includes,
|
|
6
|
+
* with the estimated charge. Used by Billing.SpaceSubscription and Billing.Overview.
|
|
7
|
+
*/
|
|
8
|
+
withDefaults(defineProps<{ usage: UsageEstimate[]; currency?: string }>(), { currency: 'CLP' })
|
|
9
|
+
|
|
10
|
+
const barClass = (level: string) => level === 'over' ? 'bg-danger' : level === 'warning' ? 'bg-warning' : 'bg-primary'
|
|
11
|
+
</script>
|
|
12
|
+
|
|
13
|
+
<template>
|
|
14
|
+
<div>
|
|
15
|
+
<p v-if="!usage.length" class="text-sm text-muted-foreground">El plan no tiene consumo medido.</p>
|
|
16
|
+
<ul v-else class="divide-y divide-card-line">
|
|
17
|
+
<li v-for="u in usage" :key="u.meter.key" class="py-2 text-sm">
|
|
18
|
+
<div class="flex items-center gap-3">
|
|
19
|
+
<span class="flex-1 text-foreground">{{ u.meter.label }}</span>
|
|
20
|
+
<span class="text-muted-foreground">
|
|
21
|
+
<template v-if="u.meter.valued_by_cost">{{ formatMoney(u.cost, currency) }} de costo (+{{ u.markup_percent ?? 0 }} %)</template>
|
|
22
|
+
<template v-else>{{ formatQuantity(u.quantity, u.meter.unit) }}<template v-if="u.included_quantity"> de {{ formatQuantity(u.included_quantity, u.meter.unit) }} incluidos</template></template>
|
|
23
|
+
</span>
|
|
24
|
+
<span class="w-28 text-right font-medium">{{ formatMoney(u.estimated_amount, currency) }}</span>
|
|
25
|
+
</div>
|
|
26
|
+
<div v-if="usageProgress(u).percent !== null" class="mt-1 h-1.5 rounded-full bg-muted overflow-hidden">
|
|
27
|
+
<div class="h-full rounded-full" :class="barClass(usageProgress(u).level)" :style="{ width: `${Math.min(100, usageProgress(u).percent ?? 0)}%` }" />
|
|
28
|
+
</div>
|
|
29
|
+
</li>
|
|
30
|
+
</ul>
|
|
31
|
+
</div>
|
|
32
|
+
</template>
|
|
@@ -0,0 +1,29 @@
|
|
|
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 = [
|
|
8
|
+
'../Plans.vue', '../Invoices.vue', '../SpaceSubscription.vue', '../ClientTotals.vue', '../Settings.vue', '../Overview.vue', '../StatusBanner.vue', '../UsageTable.vue',
|
|
9
|
+
'../Adjustments.vue', '../CreditNoteForm.vue', '../ClientTerms.vue', '../AccountStatement.vue', '../ActivityLog.vue', '../Reconciliation.vue', '../Reports.vue',
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
describe('SFC de Billing compilan', () => {
|
|
13
|
+
for (const rel of COMPONENTS) {
|
|
14
|
+
it(rel, () => {
|
|
15
|
+
const filename = resolve(__dirname, rel)
|
|
16
|
+
const { descriptor, errors } = parse(readFileSync(filename, 'utf8'), { filename })
|
|
17
|
+
expect(errors).toEqual([])
|
|
18
|
+
|
|
19
|
+
const script = compileScript(descriptor, { id: rel })
|
|
20
|
+
const tpl = compileTemplate({
|
|
21
|
+
source: descriptor.template!.content,
|
|
22
|
+
filename,
|
|
23
|
+
id: rel,
|
|
24
|
+
compilerOptions: { bindingMetadata: script.bindings },
|
|
25
|
+
})
|
|
26
|
+
expect(tpl.errors).toEqual([])
|
|
27
|
+
})
|
|
28
|
+
}
|
|
29
|
+
})
|
|
@@ -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
|
+
})
|