@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,124 @@
1
+ <script setup lang="ts">
2
+ import { IconDownload, IconCreditCard, IconFileInvoice } from '@tabler/icons-vue'
3
+ import {
4
+ formatMoney, subscriptionStatus, invoiceStatus, periodLabel, formatDate, formatDateTime, paymentMethodLabel, paymentChannelLabel,
5
+ bannerFor, type Invoice,
6
+ } from '../../composables/useBilling/internal/billing'
7
+
8
+ /*
9
+ * Billing.Overview — "Facturación" of the backoffice (permission billing.view), read-only: plan and
10
+ * status, consumption of the current period vs included with the estimate, invoices (PDF, due date,
11
+ * "Pagar" when there is a payment link; in consolidated invoices, this space's part) and payments.
12
+ * Testing spaces only show the "Espacio de pruebas" strip.
13
+ * Backend: \Innertia\Billing\Routes::backoffice() → GET {endpoint}/overview|invoices|payments.
14
+ *
15
+ * <Billing.Overview />
16
+ */
17
+ const props = withDefaults(defineProps<{ endpoint?: string }>(), { endpoint: 'billing' })
18
+
19
+ const toast = useToast()
20
+ const { base, overview, invoices, payments } = useBillingSpace({ base: props.endpoint })
21
+ const savePdf = useBillingPdf()
22
+ const data = computed<any>(() => overview.data.value)
23
+ const list = computed<Invoice[]>(() => (invoices.data.value as Invoice[] | undefined) ?? [])
24
+ const paid = computed<any[]>(() => (payments.data.value as any[] | undefined) ?? [])
25
+ const banner = computed(() => bannerFor(data.value?.subscription?.status))
26
+
27
+ async function pdf(i: Invoice) {
28
+ try {
29
+ await savePdf(`${base}/invoices/${i.id}/pdf`, `factura-${i.display_number ?? i.id}.pdf`)
30
+ } catch {
31
+ toast.error('No se pudo descargar el PDF.')
32
+ }
33
+ }
34
+ </script>
35
+
36
+ <template>
37
+ <div class="space-y-4">
38
+ <div v-if="overview.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
39
+ <div v-else-if="overview.isError.value || !data" class="p-8 text-center text-sm text-muted-foreground">
40
+ No se pudo cargar la facturación.
41
+ <button type="button" class="text-primary hover:underline" @click="overview.refetch()">Reintentar</button>
42
+ </div>
43
+
44
+ <div v-else-if="data.testing" class="rounded-card border border-info/40 bg-info/5 p-4 text-sm text-foreground">
45
+ Espacio de pruebas: no tiene facturación.
46
+ </div>
47
+
48
+ <template v-else>
49
+ <div v-if="banner" class="rounded-card border p-4 text-sm" :class="banner.severity === 'danger' ? 'border-danger/40 bg-danger/5' : 'border-warning/40 bg-warning/5'">
50
+ <p class="font-medium" :class="banner.severity === 'danger' ? 'text-danger' : 'text-warning'">{{ banner.title }}</p>
51
+ <p class="text-foreground">{{ banner.message }}</p>
52
+ </div>
53
+
54
+ <div v-if="!data.subscription" class="bg-card border border-card-line rounded-card p-4 text-sm text-muted-foreground">
55
+ Este espacio aún no tiene un plan asignado.
56
+ </div>
57
+
58
+ <template v-else>
59
+ <div class="grid gap-3 sm:grid-cols-3">
60
+ <App.StatCard label="Plan" :value="data.subscription.plan?.name ?? '—'" :hint="`${subscriptionStatus(data.subscription.status).label} · ${paymentMethodLabel(data.subscription.payment_method)}`" />
61
+ <App.StatCard label="Total estimado del período" :value="formatMoney(data.estimate?.total ?? 0, data.estimate?.currency)" :hint="`${periodLabel(data.subscription.current_period_start, data.subscription.current_period_end)} · IVA incluido`" />
62
+ <App.StatCard label="Saldo pendiente" :value="formatMoney(data.balance?.open ?? 0)" :value-class="(data.balance?.overdue ?? 0) > 0 ? 'text-danger' : 'text-foreground'"
63
+ :hint="(data.balance?.overdue ?? 0) > 0 ? `${formatMoney(data.balance.overdue)} vencido` : (data.balance?.next_due_at ? `Próximo vencimiento ${formatDateTime(data.balance.next_due_at)}` : 'Al día')" />
64
+ </div>
65
+
66
+ <p v-if="data.subscription.status === 'trialing' && data.subscription.trial_ends_at" class="text-sm text-info">
67
+ Período de prueba hasta el {{ formatDate(data.subscription.trial_ends_at) }}: no se cobra.
68
+ </p>
69
+ <p v-if="data.subscription.pending_plan" class="text-sm text-muted-foreground">Desde el próximo período: plan {{ data.subscription.pending_plan.name }}.</p>
70
+
71
+ <div class="bg-card border border-card-line rounded-card p-4 space-y-3">
72
+ <p class="text-sm font-medium text-foreground">Consumo del período</p>
73
+ <p v-if="data.seats" class="text-sm text-muted-foreground">
74
+ Usuarios: {{ data.seats.counted }} de {{ data.seats.included }} incluidos<template v-if="data.seats.seat_price && data.seats.counted > data.seats.included"> · adicionales {{ formatMoney(data.estimate.seats) }}</template>
75
+ </p>
76
+ <Billing.UsageTable :usage="data.usage ?? []" :currency="data.estimate?.currency" />
77
+ </div>
78
+ </template>
79
+
80
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
81
+ <p class="text-sm font-medium text-foreground px-4 pt-3">Facturas</p>
82
+ <div v-if="invoices.isPending.value" class="p-6 text-center text-sm text-muted-foreground">Cargando…</div>
83
+ <div v-else-if="!list.length" class="p-6 text-center text-sm text-muted-foreground">
84
+ <IconFileInvoice class="size-6 mx-auto mb-2" :stroke-width="1.5" />
85
+ Aún no hay facturas.
86
+ </div>
87
+ <table v-else class="w-full text-sm">
88
+ <tbody class="divide-y divide-card-line">
89
+ <tr v-for="i in list" :key="i.id">
90
+ <td class="px-4 py-2">
91
+ <p class="font-medium text-foreground">{{ i.display_number }} <App.Tag :text="invoiceStatus(i.status).label" :severity="invoiceStatus(i.status).severity" size="xs" class="ml-1" /></p>
92
+ <p class="text-xs text-muted-foreground">{{ periodLabel(i.period_start, i.period_end) }}<template v-if="i.consolidated"> · factura conjunta del cliente</template></p>
93
+ </td>
94
+ <td class="px-4 py-2 text-right">
95
+ <p>{{ formatMoney(i.total, i.currency) }}</p>
96
+ <p v-if="i.consolidated" class="text-xs text-muted-foreground">Este espacio: {{ formatMoney(i.space_part ?? 0, i.currency) }}</p>
97
+ </td>
98
+ <td class="px-4 py-2 text-muted-foreground">
99
+ <template v-if="i.status === 'paid'">Pagada {{ formatDateTime(i.paid_at) }}</template>
100
+ <template v-else>Vence {{ formatDateTime(i.due_at) }} · saldo {{ formatMoney(i.balance, i.currency) }}</template>
101
+ </td>
102
+ <td class="px-4 py-2">
103
+ <div class="flex justify-end gap-1">
104
+ <App.Button v-if="i.payment_link" text="Pagar" size="xs" severity="primary" :icon="IconCreditCard" type="link" :link="i.payment_link" />
105
+ <App.Button text="PDF" size="xs" outline :icon="IconDownload" @click="pdf(i)" />
106
+ </div>
107
+ </td>
108
+ </tr>
109
+ </tbody>
110
+ </table>
111
+ </div>
112
+
113
+ <div v-if="paid.length" class="bg-card border border-card-line rounded-card">
114
+ <p class="text-sm font-medium text-foreground px-4 pt-3">Pagos</p>
115
+ <ul class="divide-y divide-card-line">
116
+ <li v-for="p in paid" :key="p.id" class="flex items-center gap-3 px-4 py-2 text-sm">
117
+ <span class="flex-1">{{ formatDateTime(p.received_at) }} · {{ paymentChannelLabel(p.method) }}<template v-if="p.reference"> · {{ p.reference }}</template></span>
118
+ <span class="font-medium">{{ formatMoney(p.amount) }}</span>
119
+ </li>
120
+ </ul>
121
+ </div>
122
+ </template>
123
+ </div>
124
+ </template>
@@ -0,0 +1,146 @@
1
+ <script setup lang="ts">
2
+ import { IconPlus, IconPencil, IconTrash, IconReceipt } from '@tabler/icons-vue'
3
+ import {
4
+ formatMoney, intervalLabel, emptyPlan, planPayload, errorMessage, type Plan, type MeterDefinition,
5
+ } from '../../composables/useBilling/internal/billing'
6
+
7
+ /*
8
+ * Billing.Plans — plans and prices (platform): base price, included seats + seat price, trial,
9
+ * VAT and metered consumption (included + unit price; AI at real cost + markup %).
10
+ * Prices in pesos (integers). Changes rule from the next period close.
11
+ * Backend: \Innertia\Billing\Routes::platform() + platformWrite().
12
+ *
13
+ * <Billing.Plans endpoint="platform/billing" :can-edit="isOwner" />
14
+ */
15
+ const props = withDefaults(defineProps<{ endpoint?: string; canEdit?: boolean }>(), { endpoint: 'platform/billing', canEdit: true })
16
+
17
+ const toast = useToast()
18
+ const { plans, meters, savePlan } = useBillingPlatform({ base: props.endpoint })
19
+ const list = computed<Plan[]>(() => (plans.data.value as Plan[] | undefined) ?? [])
20
+ const catalog = computed<MeterDefinition[]>(() => (meters.data.value as MeterDefinition[] | undefined) ?? [])
21
+ const meterDef = (key: string) => catalog.value.find(m => m.key === key)
22
+
23
+ const show = ref(false)
24
+ const editing = ref<Plan | null>(null)
25
+ const form = reactive<Omit<Plan, 'id'>>(emptyPlan())
26
+
27
+ function open(plan: Plan | null) {
28
+ editing.value = plan
29
+ Object.assign(form, plan ? JSON.parse(JSON.stringify({ ...plan, description: plan.description ?? '', product: plan.product ?? '' })) : emptyPlan())
30
+ show.value = true
31
+ }
32
+
33
+ function addMeter() {
34
+ const used = new Set(form.meters.map(m => m.meter))
35
+ const next = catalog.value.find(m => !used.has(m.key))
36
+ form.meters.push({ meter: next?.key ?? '', included_quantity: 0, unit_price: 0, markup_percent: next?.valued_by_cost ? 20 : null })
37
+ }
38
+
39
+ async function submit() {
40
+ if (!form.name.trim() || !form.key.trim()) { toast.error('Nombre y clave son obligatorios.'); return }
41
+ try {
42
+ await savePlan.mutateAsync({ id: editing.value?.id, body: planPayload(form, catalog.value) })
43
+ show.value = false
44
+ toast.success(editing.value ? 'Plan actualizado.' : 'Plan creado.')
45
+ } catch (e: any) {
46
+ toast.error(errorMessage(e, 'No se pudo guardar el plan.'))
47
+ }
48
+ }
49
+
50
+ 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'
51
+ </script>
52
+
53
+ <template>
54
+ <div class="space-y-4">
55
+ <div class="flex flex-wrap items-center gap-3">
56
+ <p class="flex-1 text-sm text-muted-foreground">
57
+ Cada espacio de producción se cobra con un plan: precio base, usuarios adicionales y consumo medido. Los montos van en pesos; los cambios rigen desde el próximo cierre.
58
+ </p>
59
+ <App.Button v-if="canEdit" text="Nuevo plan" severity="primary" size="sm" :icon="IconPlus" @click="open(null)" />
60
+ </div>
61
+
62
+ <div class="bg-card border border-card-line rounded-card overflow-hidden">
63
+ <div v-if="plans.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
64
+ <div v-else-if="plans.isError.value" class="p-8 text-center text-sm text-muted-foreground">
65
+ No se pudieron cargar los planes.
66
+ <button type="button" class="text-primary hover:underline" @click="plans.refetch()">Reintentar</button>
67
+ </div>
68
+ <div v-else-if="!list.length" class="p-8 text-center text-sm text-muted-foreground">
69
+ <IconReceipt class="size-6 mx-auto mb-2" :stroke-width="1.5" />
70
+ Aún no hay planes.
71
+ </div>
72
+ <ul v-else class="divide-y divide-card-line">
73
+ <li v-for="p in list" :key="p.id" class="flex flex-wrap items-start gap-3 px-5 py-3">
74
+ <div class="flex-1 min-w-0">
75
+ <p class="text-sm font-medium text-foreground flex items-center gap-2">
76
+ {{ p.name }} <span class="text-xs font-mono text-muted-foreground">{{ p.key }}</span>
77
+ <App.Tag v-if="!p.active" text="Inactivo" size="xs" />
78
+ </p>
79
+ <p class="text-xs text-muted-foreground">
80
+ {{ formatMoney(p.base_price, p.currency) }} {{ intervalLabel(p.interval) }} + IVA {{ p.tax_rate }} %
81
+ · {{ p.included_seats }} usuarios incluidos<template v-if="p.seat_price">, adicional {{ formatMoney(p.seat_price, p.currency) }}</template>
82
+ <template v-if="p.trial_days"> · {{ p.trial_days }} días de prueba</template>
83
+ </p>
84
+ <p v-if="p.meters.length" class="text-xs text-muted-foreground">
85
+ <template v-for="(m, i) in p.meters" :key="m.meter">
86
+ {{ i ? ' · ' : '' }}{{ m.label ?? m.meter }}:
87
+ <template v-if="m.valued_by_cost">costo + {{ m.markup_percent ?? 0 }} %</template>
88
+ <template v-else>{{ m.included_quantity }} incluidos, {{ formatMoney(m.unit_price, p.currency) }} c/u</template>
89
+ </template>
90
+ </p>
91
+ </div>
92
+ <App.Button v-if="canEdit" text="Editar" size="xs" :icon="IconPencil" @click="open(p)" />
93
+ </li>
94
+ </ul>
95
+ </div>
96
+
97
+ <Modal v-model="show" :title="editing ? 'Editar plan' : 'Nuevo plan'" size="2xl" show-footer>
98
+ <form class="space-y-4" @submit.prevent="submit">
99
+ <div class="grid gap-3 sm:grid-cols-2">
100
+ <label class="block space-y-1"><span class="text-sm font-medium">Nombre</span><input v-model="form.name" :class="inputClass" maxlength="120" /></label>
101
+ <label class="block space-y-1"><span class="text-sm font-medium">Clave</span><input v-model="form.key" :class="inputClass" maxlength="60" placeholder="pro" /></label>
102
+ <label class="block space-y-1 sm:col-span-2"><span class="text-sm font-medium">Descripción</span><input v-model="form.description" :class="inputClass" maxlength="250" /></label>
103
+ <label class="block space-y-1"><span class="text-sm font-medium">Periodicidad</span>
104
+ <select v-model="form.interval" :class="inputClass"><option value="monthly">Mensual</option><option value="annual">Anual</option></select>
105
+ </label>
106
+ <label class="block space-y-1"><span class="text-sm font-medium">Precio base ($)</span><input v-model.number="form.base_price" type="number" min="0" step="1" :class="inputClass" /></label>
107
+ <label class="block space-y-1"><span class="text-sm font-medium">Usuarios incluidos</span><input v-model.number="form.included_seats" type="number" min="0" :class="inputClass" /></label>
108
+ <label class="block space-y-1"><span class="text-sm font-medium">Precio por usuario adicional ($)</span><input v-model.number="form.seat_price" type="number" min="0" :class="inputClass" /></label>
109
+ <label class="block space-y-1"><span class="text-sm font-medium">Días de prueba</span><input v-model.number="form.trial_days" type="number" min="0" max="365" :class="inputClass" /></label>
110
+ <label class="block space-y-1"><span class="text-sm font-medium">IVA (%)</span><input v-model.number="form.tax_rate" type="number" min="0" max="100" step="0.01" :class="inputClass" /></label>
111
+ <label class="flex items-center gap-2 text-sm sm:col-span-2"><input v-model="form.active" type="checkbox" class="rounded" /> Plan activo (disponible para nuevas suscripciones)</label>
112
+ </div>
113
+
114
+ <div class="space-y-2">
115
+ <div class="flex items-center justify-between">
116
+ <span class="text-sm font-medium">Consumo medido</span>
117
+ <App.Button text="Agregar medidor" size="xs" :icon="IconPlus" :disabled="form.meters.length >= catalog.length" @click="addMeter" />
118
+ </div>
119
+ <p v-if="!form.meters.length" class="text-xs text-muted-foreground">Sin consumo medido: solo se cobra base y usuarios.</p>
120
+ <div v-for="(m, i) in form.meters" :key="i" class="grid gap-2 sm:grid-cols-[1fr_8rem_8rem_auto] items-end border border-card-line rounded-control p-2">
121
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Medidor</span>
122
+ <select v-model="m.meter" :class="inputClass">
123
+ <option v-for="d in catalog" :key="d.key" :value="d.key">{{ d.label }}</option>
124
+ </select>
125
+ </label>
126
+ <template v-if="meterDef(m.meter)?.valued_by_cost">
127
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Margen (%)</span><input v-model.number="m.markup_percent" type="number" min="0" :class="inputClass" /></label>
128
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Incluido ($)</span><input v-model.number="m.included_quantity" type="number" min="0" :class="inputClass" /></label>
129
+ </template>
130
+ <template v-else>
131
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Incluido ({{ meterDef(m.meter)?.unit ?? 'unidad' }})</span><input v-model.number="m.included_quantity" type="number" min="0" step="any" :class="inputClass" /></label>
132
+ <label class="block space-y-1"><span class="text-xs text-muted-foreground">Precio unitario ($)</span><input v-model.number="m.unit_price" type="number" min="0" :class="inputClass" /></label>
133
+ </template>
134
+ <button type="button" class="p-2 text-muted-foreground hover:text-danger" aria-label="Quitar medidor" @click="form.meters.splice(i, 1)">
135
+ <IconTrash class="size-4" />
136
+ </button>
137
+ </div>
138
+ </div>
139
+ </form>
140
+ <template #footer>
141
+ <App.Button text="Cancelar" size="sm" @click="show = false" />
142
+ <App.Button text="Guardar" severity="primary" size="sm" :loading="savePlan.isPending.value" @click="submit" />
143
+ </template>
144
+ </Modal>
145
+ </div>
146
+ </template>
@@ -0,0 +1,79 @@
1
+ <script setup lang="ts">
2
+ import { errorMessage } 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 and dunning (they also run on the scheduler, America/Santiago).
8
+ * Backend: GET|PUT {endpoint}/settings, POST {endpoint}/run/{close|dunning}.
9
+ */
10
+ const props = withDefaults(defineProps<{ endpoint?: string; canRun?: boolean }>(), { endpoint: 'platform/billing', canRun: true })
11
+
12
+ const toast = useToast()
13
+ const { confirm } = useModal()
14
+ const { settings, saveSettings, run } = useBillingPlatform({ base: props.endpoint })
15
+ const form = reactive({ usd_clp_rate: '' as string | number, transfer_instructions: '', issuer_name: '', issuer_tax_id: '', issuer_address: '' })
16
+
17
+ watch(() => settings.data.value, (s: any) => {
18
+ if (s) Object.assign(form, { 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 ?? '' })
19
+ }, { immediate: true })
20
+
21
+ async function save() {
22
+ try {
23
+ await saveSettings.mutateAsync({
24
+ usd_clp_rate: form.usd_clp_rate === '' ? null : Number(form.usd_clp_rate),
25
+ transfer_instructions: form.transfer_instructions || null,
26
+ issuer_name: form.issuer_name || null, issuer_tax_id: form.issuer_tax_id || null, issuer_address: form.issuer_address || null,
27
+ })
28
+ toast.success('Configuración guardada.')
29
+ } catch (e: any) {
30
+ toast.error(errorMessage(e, 'No se pudo guardar.'))
31
+ }
32
+ }
33
+
34
+ async function runJob(job: 'close' | 'dunning') {
35
+ const ok = await confirm({
36
+ title: job === 'close' ? 'Cerrar períodos ahora' : 'Revisar mora ahora',
37
+ message: job === 'close'
38
+ ? 'Se cierran los períodos vencidos y se generan las facturas en borrador. Es idempotente: no duplica cobros.'
39
+ : 'Se marcan las facturas vencidas y se actualiza el estado de las suscripciones (mora, suspensión, reactivación).',
40
+ confirmText: 'Ejecutar',
41
+ })
42
+ if (!ok) return
43
+ try {
44
+ const res: any = await run.mutateAsync(job)
45
+ toast.success(job === 'close' ? `Cierre listo: ${res?.statements ?? 0} cobros nuevos.` : `Mora revisada: ${res?.overdue ?? 0} facturas vencidas, ${res?.changed ?? 0} cambios.`)
46
+ } catch (e: any) {
47
+ toast.error(errorMessage(e, 'No se pudo ejecutar.'))
48
+ }
49
+ }
50
+
51
+ 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'
52
+ </script>
53
+
54
+ <template>
55
+ <div class="space-y-4">
56
+ <form class="bg-card border border-card-line rounded-card p-4 grid gap-3 sm:grid-cols-2 text-sm" @submit.prevent="save">
57
+ <label class="block space-y-1"><span class="font-medium">Tipo de cambio USD → CLP</span>
58
+ <input v-model="form.usd_clp_rate" type="number" min="1" step="0.01" :class="inputClass" />
59
+ <span class="text-xs text-muted-foreground">Valoriza el costo de IA de cada uso desde ahora.</span>
60
+ </label>
61
+ <span />
62
+ <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>
63
+ <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>
64
+ <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>
65
+ <label class="block space-y-1 sm:col-span-2"><span class="font-medium">Datos para transferencia</span>
66
+ <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" />
67
+ </label>
68
+ <div class="sm:col-span-2 flex justify-end">
69
+ <App.Button text="Guardar" severity="primary" size="sm" :loading="saveSettings.isPending.value" @click="save" />
70
+ </div>
71
+ </form>
72
+
73
+ <div v-if="canRun" class="bg-card border border-card-line rounded-card p-4 flex flex-wrap items-center gap-3 text-sm">
74
+ <p class="flex-1 text-muted-foreground">El cierre (00:30) y la revisión de mora (08:00) corren solos cada día, hora de Chile.</p>
75
+ <App.Button text="Cerrar períodos" size="sm" :loading="run.isPending.value" @click="runJob('close')" />
76
+ <App.Button text="Revisar mora" size="sm" :loading="run.isPending.value" @click="runJob('dunning')" />
77
+ </div>
78
+ </div>
79
+ </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>