@innertia-solutions/innertia-nuxt 0.1.90 → 0.1.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/components/Ai/ModelPrices.vue +105 -0
  3. package/components/Ai/UsageReport.vue +127 -0
  4. package/components/Ai/UsageSummary.vue +13 -0
  5. package/components/Ai/__tests__/sfc-compile.test.ts +26 -0
  6. package/components/Billing/ClientTotals.vue +65 -0
  7. package/components/Billing/Invoices.vue +271 -0
  8. package/components/Billing/Overview.vue +124 -0
  9. package/components/Billing/Plans.vue +146 -0
  10. package/components/Billing/Settings.vue +79 -0
  11. package/components/Billing/SpaceSubscription.vue +202 -0
  12. package/components/Billing/StatusBanner.vue +36 -0
  13. package/components/Billing/UsageTable.vue +32 -0
  14. package/components/Billing/__tests__/sfc-compile.test.ts +26 -0
  15. package/components/Integrations/ApiKeys.vue +297 -0
  16. package/components/Integrations/Developers.vue +60 -0
  17. package/components/Integrations/Webhooks.vue +458 -0
  18. package/components/Integrations/__tests__/sfc-compile.test.ts +31 -0
  19. package/composables/useAiUsage/index.ts +48 -0
  20. package/composables/useAiUsage/internal/__tests__/aiUsage.test.ts +50 -0
  21. package/composables/useAiUsage/internal/aiUsage.ts +140 -0
  22. package/composables/useBilling/index.ts +147 -0
  23. package/composables/useBilling/internal/__tests__/billing.test.ts +78 -0
  24. package/composables/useBilling/internal/billing.ts +264 -0
  25. package/composables/useIntegrations/index.ts +136 -0
  26. package/composables/useIntegrations/internal/__tests__/integrations.test.ts +112 -0
  27. package/composables/useIntegrations/internal/integrations.ts +276 -0
  28. package/docs/ai-usage.md +38 -0
  29. package/docs/billing.md +75 -0
  30. package/docs/webhooks-api.md +88 -0
  31. package/nuxt.config.ts +1 -1
  32. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -6,6 +6,8 @@ All notable changes to `@innertia-solutions/innertia-nuxt` are documented here.
6
6
 
7
7
  ### Added
8
8
 
9
+ - Facturación de la plataforma (`Innertia\Billing`) y consumo de IA: `Billing.Plans`, `Billing.Invoices`, `Billing.SpaceSubscription`, `Billing.ClientTotals`, `Billing.Settings` (platform), `Billing.Overview`, `Billing.StatusBanner` y `Billing.UsageTable` (backoffice); `Ai.ModelPrices`, `Ai.UsageReport` y `Ai.UsageSummary`; composables `useBillingPlatform()`, `useBillingSpace()`, `useBillingPdf()`, `useAiModelPrices()` y `useAiUsage()`. Ver `docs/billing.md` y `docs/ai-usage.md`.
10
+
9
11
  - Correos y notificaciones con marca (opt-in): `Notifications.Preferences` + `useNotificationPreferences()`, `Platform.Emails` (filtros por tipo, espacio y estado; motivo de los fallidos), `Platform.MailSettings` (versión pulida: validación por campo, cambios sin guardar, confirmar borrar key, prueba con vista previa), `Mail.BrandingPreview` y `Mail.BrandingSettings` (marca del espacio). Campanita e historial en platform con la prop `endpoint` (`useNotifications({ base })`, `useNotificationHistory({ base })`). Middleware `platform-owner` y `06.force-password.global` (apagado hasta `appConfig.innertia.forcePassword.enabled`). Ver `docs/correos-notificaciones.md`.
10
12
 
11
13
  - Passkeys (WebAuthn): composable `usePasskeys()`, componentes `Auth.PasskeyButton` (login tenant y `/platform`, con autocompletado), `Auth.PasskeyInvite`, `Auth.PasskeyManager` y `Auth.UserPasskeys`, y rutas BFF `/_auth/passkey/login` y `/_auth/platform/passkey/login` que sellan la sesión solo si hay token. Se activa y desactiva desde `/platform` con `Auth.PasskeySettings` (sin variables de entorno). Ver `docs/passkeys.md`.
@@ -0,0 +1,105 @@
1
+ <script setup lang="ts">
2
+ import { IconCurrencyDollar, IconDeviceFloppy } from '@tabler/icons-vue'
3
+ import { PRICE_FIELDS, parsePrice, formatUsd, type AiModelPrice, type PriceField } from '../../composables/useAiUsage/internal/aiUsage'
4
+
5
+ /*
6
+ * Ai.ModelPrices — USD prices per model (input/output per 1M tokens, audio per minute, TTS per 1M chars).
7
+ * The cost of every AI usage is computed with the price in force when it is recorded (not retroactive).
8
+ * Backend: \Innertia\Ai\Routes::platform() + platformWrite() (owner).
9
+ *
10
+ * <Ai.ModelPrices endpoint="platform/ai" :can-edit="isOwner" />
11
+ */
12
+ const props = withDefaults(defineProps<{ endpoint?: string; canEdit?: boolean }>(), { endpoint: 'platform/ai', canEdit: true })
13
+
14
+ const toast = useToast()
15
+ const { list, update } = useAiModelPrices({ base: props.endpoint })
16
+ const models = computed<AiModelPrice[]>(() => (list.data.value as AiModelPrice[] | undefined) ?? [])
17
+
18
+ const drafts = reactive<Record<string, Record<PriceField, string>>>({})
19
+ const saving = ref<string | null>(null)
20
+
21
+ function draftOf(m: AiModelPrice) {
22
+ if (!drafts[m.id]) {
23
+ drafts[m.id] = Object.fromEntries(PRICE_FIELDS.map(f => [f.key, m.prices[f.key] === null || m.prices[f.key] === undefined ? '' : String(m.prices[f.key])])) as Record<PriceField, string>
24
+ }
25
+ return drafts[m.id]
26
+ }
27
+
28
+ function dirty(m: AiModelPrice) {
29
+ const d = draftOf(m)
30
+ return PRICE_FIELDS.some(f => parsePrice(d[f.key]) !== (m.prices[f.key] ?? null))
31
+ }
32
+
33
+ async function save(m: AiModelPrice) {
34
+ const d = draftOf(m)
35
+ const prices = {} as Record<PriceField, number | null>
36
+ for (const f of PRICE_FIELDS) {
37
+ const v = parsePrice(d[f.key])
38
+ if (v === undefined) { toast.error(`Precio inválido en ${f.label}.`); return }
39
+ prices[f.key] = v
40
+ }
41
+ saving.value = m.id
42
+ try {
43
+ await update.mutateAsync({ id: m.id, prices })
44
+ delete drafts[m.id]
45
+ toast.success(`Precios de ${m.name} guardados. Rigen para el consumo desde ahora.`)
46
+ } catch (e: any) {
47
+ toast.error(e?.data?.message ?? 'No se pudieron guardar los precios.')
48
+ } finally {
49
+ saving.value = null
50
+ }
51
+ }
52
+
53
+ const inputClass = 'w-24 h-8 rounded-control border border-card-line bg-card text-sm text-foreground px-2 text-right focus:outline-hidden focus:ring-2 focus:ring-primary/30 disabled:opacity-60'
54
+ </script>
55
+
56
+ <template>
57
+ <div class="space-y-3">
58
+ <p class="text-sm text-muted-foreground">
59
+ Precios en dólares de cada modelo. El costo de cada uso de IA se calcula al registrarlo con el precio vigente; un modelo sin precio queda como "sin valorizar".
60
+ </p>
61
+
62
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
63
+ <div v-if="list.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
64
+ <div v-else-if="list.isError.value" class="p-8 text-center text-sm text-muted-foreground">
65
+ No se pudieron cargar los modelos.
66
+ <button type="button" class="text-primary hover:underline" @click="list.refetch()">Reintentar</button>
67
+ </div>
68
+ <div v-else-if="!models.length" class="p-8 text-center text-sm text-muted-foreground">
69
+ <IconCurrencyDollar class="size-6 mx-auto mb-2" :stroke-width="1.5" />
70
+ No hay modelos configurados.
71
+ </div>
72
+ <table v-else class="w-full text-sm">
73
+ <thead class="text-xs uppercase text-muted-foreground">
74
+ <tr class="border-b border-card-line">
75
+ <th class="text-left font-medium px-4 py-2">Modelo</th>
76
+ <th v-for="f in PRICE_FIELDS" :key="f.key" class="text-right font-medium px-2 py-2" :title="f.hint">
77
+ {{ f.label }}<span class="block normal-case font-normal">{{ f.hint }}</span>
78
+ </th>
79
+ <th class="px-4 py-2" />
80
+ </tr>
81
+ </thead>
82
+ <tbody class="divide-y divide-card-line">
83
+ <tr v-for="m in models" :key="m.id">
84
+ <td class="px-4 py-2">
85
+ <p class="font-medium text-foreground flex items-center gap-2">
86
+ {{ m.name }}
87
+ <App.Tag v-if="!m.priced" text="Sin precio" severity="warning" size="xs" />
88
+ <App.Tag v-if="!m.active" text="Inactivo" size="xs" />
89
+ </p>
90
+ <p class="text-xs text-muted-foreground font-mono">{{ m.provider?.name ?? '—' }} · {{ m.key }}</p>
91
+ </td>
92
+ <td v-for="f in PRICE_FIELDS" :key="f.key" class="px-2 py-2 text-right">
93
+ <input v-if="canEdit" v-model="draftOf(m)[f.key]" type="text" inputmode="decimal" placeholder="—" :class="inputClass" :aria-label="`${f.label} ${m.name}`" />
94
+ <span v-else class="text-foreground">{{ m.prices[f.key] === null ? '—' : formatUsd(m.prices[f.key]) }}</span>
95
+ </td>
96
+ <td class="px-4 py-2 text-right">
97
+ <App.Button v-if="canEdit" text="Guardar" size="xs" severity="primary" :icon="IconDeviceFloppy"
98
+ :disabled="!dirty(m)" :loading="saving === m.id" @click="save(m)" />
99
+ </td>
100
+ </tr>
101
+ </tbody>
102
+ </table>
103
+ </div>
104
+ </div>
105
+ </template>
@@ -0,0 +1,127 @@
1
+ <script setup lang="ts">
2
+ import { IconChevronLeft, IconChevronRight } from '@tabler/icons-vue'
3
+ import {
4
+ featureLabel, formatUsd, unitsLabel, monthKey, shiftMonth, monthLabel, barHeights, budgetState, compactNumber, type UsageSummary,
5
+ } from '../../composables/useAiUsage/internal/aiUsage'
6
+
7
+ /*
8
+ * Ai.UsageReport — AI consumption of a month: totals, by feature, daily bars, top days and (platform)
9
+ * by space. Cost in USD estimated with the model prices in force when each usage was recorded.
10
+ *
11
+ * <Ai.UsageReport /> platform: GET platform/ai/usage/report
12
+ * <Ai.UsageReport scope="tenant" endpoint="ai" :budget="50" /> backoffice: GET ai/usage/summary
13
+ */
14
+ const props = withDefaults(defineProps<{
15
+ endpoint?: string
16
+ scope?: 'platform' | 'tenant'
17
+ tenantId?: string | null
18
+ budget?: number | null
19
+ }>(), { scope: 'platform', tenantId: null, budget: null })
20
+
21
+ const month = ref(monthKey())
22
+ const tenant = computed(() => props.tenantId ?? null)
23
+ const query = useAiUsage(month, { base: props.endpoint, scope: props.scope, tenantId: tenant })
24
+ const data = computed(() => query.data.value as UsageSummary | undefined)
25
+
26
+ const daily = computed(() => data.value?.daily ?? [])
27
+ const heights = computed(() => barHeights(daily.value.map(d => d.cost_usd)))
28
+ const topDays = computed(() => [...daily.value].filter(d => d.events > 0).sort((a, b) => b.cost_usd - a.cost_usd).slice(0, 5))
29
+ const budget = computed(() => budgetState(data.value?.totals.cost_usd ?? 0, props.budget))
30
+ const isCurrent = computed(() => month.value >= monthKey())
31
+
32
+ function exportCsv() {
33
+ if (!data.value) return
34
+ const rows = [['fecha', 'eventos', 'costo_usd', 'tokens_entrada', 'tokens_salida', 'audio_segundos', 'caracteres_tts']]
35
+ for (const d of daily.value) rows.push([d.date, String(d.events), String(d.cost_usd), String(d.input_tokens), String(d.output_tokens), String(d.audio_seconds), String(d.tts_chars)])
36
+ const blob = new Blob([rows.map(r => r.join(',')).join('\n')], { type: 'text/csv;charset=utf-8' })
37
+ const url = URL.createObjectURL(blob)
38
+ const a = document.createElement('a')
39
+ a.href = url
40
+ a.download = `consumo-ia-${month.value}.csv`
41
+ a.click()
42
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
43
+ }
44
+ </script>
45
+
46
+ <template>
47
+ <div class="space-y-4">
48
+ <div class="flex flex-wrap items-center gap-2">
49
+ <button type="button" class="p-1.5 rounded-control hover:bg-muted" aria-label="Mes anterior" @click="month = shiftMonth(month, -1)">
50
+ <IconChevronLeft class="size-4" />
51
+ </button>
52
+ <span class="text-sm font-medium text-foreground min-w-36 text-center">{{ monthLabel(month) }}</span>
53
+ <button type="button" class="p-1.5 rounded-control hover:bg-muted disabled:opacity-40" aria-label="Mes siguiente" :disabled="isCurrent" @click="month = shiftMonth(month, 1)">
54
+ <IconChevronRight class="size-4" />
55
+ </button>
56
+ <span class="flex-1" />
57
+ <App.Button text="Exportar CSV" size="xs" :disabled="!data" @click="exportCsv" />
58
+ </div>
59
+
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 consumo.
63
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
64
+ </div>
65
+ <template v-else>
66
+ <div class="grid gap-3 sm:grid-cols-3">
67
+ <App.StatCard label="Costo estimado" :value="formatUsd(data.totals.cost_usd)" :hint="data.totals.unpriced_events ? `${data.totals.unpriced_events} usos sin precio` : ''" />
68
+ <App.StatCard label="Usos" :value="compactNumber(data.totals.events)" />
69
+ <App.StatCard label="Unidades" :value="unitsLabel(data.totals)" />
70
+ </div>
71
+
72
+ <div v-if="budget" class="rounded-card border p-3 text-sm"
73
+ :class="budget.level === 'over' ? 'border-danger/40 bg-danger/5 text-danger' : budget.level === 'warning' ? 'border-warning/40 bg-warning/5 text-warning' : 'border-card-line bg-card text-foreground'">
74
+ Presupuesto mensual: {{ budget.percent }} % usado ({{ formatUsd(data.totals.cost_usd) }} de {{ formatUsd(budget ? props.budget : 0) }}).
75
+ </div>
76
+
77
+ <div class="bg-card border border-card-line rounded-card p-4">
78
+ <p class="text-sm font-medium text-foreground mb-3">Costo por día</p>
79
+ <div class="flex items-end gap-0.5 h-32">
80
+ <div v-for="(d, i) in daily" :key="d.date" class="flex-1 bg-primary/70 rounded-t-sm min-h-px" :style="{ height: `${heights[i]}%` }"
81
+ :title="`${d.date}: ${formatUsd(d.cost_usd)} · ${d.events} usos`" />
82
+ </div>
83
+ <div class="flex justify-between text-xs text-muted-foreground mt-1">
84
+ <span>{{ daily[0]?.date }}</span><span>{{ daily[daily.length - 1]?.date }}</span>
85
+ </div>
86
+ </div>
87
+
88
+ <div class="grid gap-4 lg:grid-cols-2">
89
+ <div class="bg-card border border-card-line rounded-card">
90
+ <p class="text-sm font-medium text-foreground px-4 pt-3">Por función</p>
91
+ <p v-if="!data.by_feature.length" class="px-4 py-6 text-sm text-muted-foreground">Sin consumo en el mes.</p>
92
+ <ul v-else class="divide-y divide-card-line">
93
+ <li v-for="f in data.by_feature" :key="f.feature ?? 'none'" class="flex items-center gap-3 px-4 py-2 text-sm">
94
+ <span class="flex-1 text-foreground">{{ featureLabel(f.feature) }}</span>
95
+ <span class="text-xs text-muted-foreground">{{ unitsLabel(f) }}</span>
96
+ <span class="w-28 text-right font-medium">{{ formatUsd(f.cost_usd) }}</span>
97
+ </li>
98
+ </ul>
99
+ </div>
100
+
101
+ <div class="bg-card border border-card-line rounded-card">
102
+ <p class="text-sm font-medium text-foreground px-4 pt-3">Días de mayor consumo</p>
103
+ <p v-if="!topDays.length" class="px-4 py-6 text-sm text-muted-foreground">Sin consumo en el mes.</p>
104
+ <ul v-else class="divide-y divide-card-line">
105
+ <li v-for="d in topDays" :key="d.date" class="flex items-center gap-3 px-4 py-2 text-sm">
106
+ <span class="flex-1 text-foreground">{{ d.date }}</span>
107
+ <span class="text-xs text-muted-foreground">{{ d.events }} usos</span>
108
+ <span class="w-28 text-right font-medium">{{ formatUsd(d.cost_usd) }}</span>
109
+ </li>
110
+ </ul>
111
+ </div>
112
+ </div>
113
+
114
+ <div v-if="scope === 'platform' && data.by_tenant" class="bg-card border border-card-line rounded-card">
115
+ <p class="text-sm font-medium text-foreground px-4 pt-3">Por espacio</p>
116
+ <p v-if="!data.by_tenant.length" class="px-4 py-6 text-sm text-muted-foreground">Sin consumo en el mes.</p>
117
+ <ul v-else class="divide-y divide-card-line">
118
+ <li v-for="t in data.by_tenant" :key="t.tenant_id ?? 'none'" class="flex items-center gap-3 px-4 py-2 text-sm">
119
+ <span class="flex-1 text-foreground">{{ t.tenant_name ?? (t.tenant_id ? `Espacio ${t.tenant_id}` : 'Sin espacio (plataforma)') }}</span>
120
+ <span class="text-xs text-muted-foreground">{{ unitsLabel(t) }}</span>
121
+ <span class="w-28 text-right font-medium">{{ formatUsd(t.cost_usd) }}</span>
122
+ </li>
123
+ </ul>
124
+ </div>
125
+ </template>
126
+ </div>
127
+ </template>
@@ -0,0 +1,13 @@
1
+ <script setup lang="ts">
2
+ /*
3
+ * Ai.UsageSummary — AI consumption of the active space (backoffice), with an optional monthly budget
4
+ * in USD (warning at 80 % and 100 %). Backend: \Innertia\Ai\Routes::tenant() → GET ai/usage/summary.
5
+ *
6
+ * <Ai.UsageSummary endpoint="ai" :budget="settings.ai_budget_usd" />
7
+ */
8
+ withDefaults(defineProps<{ endpoint?: string; budget?: number | null }>(), { endpoint: 'ai', budget: null })
9
+ </script>
10
+
11
+ <template>
12
+ <Ai.UsageReport scope="tenant" :endpoint="endpoint" :budget="budget" />
13
+ </template>
@@ -0,0 +1,26 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { readFileSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+ import { parse, compileScript, compileTemplate } from 'vue/compiler-sfc'
5
+
6
+ // Ai components compile (script + template) without errors.
7
+ const COMPONENTS = ['../ModelPrices.vue', '../UsageReport.vue', '../UsageSummary.vue']
8
+
9
+ describe('SFC de Ai compilan', () => {
10
+ for (const rel of COMPONENTS) {
11
+ it(rel, () => {
12
+ const filename = resolve(__dirname, rel)
13
+ const { descriptor, errors } = parse(readFileSync(filename, 'utf8'), { filename })
14
+ expect(errors).toEqual([])
15
+
16
+ const script = compileScript(descriptor, { id: rel })
17
+ const tpl = compileTemplate({
18
+ source: descriptor.template!.content,
19
+ filename,
20
+ id: rel,
21
+ compilerOptions: { bindingMetadata: script.bindings },
22
+ })
23
+ expect(tpl.errors).toEqual([])
24
+ })
25
+ }
26
+ })
@@ -0,0 +1,65 @@
1
+ <script setup lang="ts">
2
+ import { formatMoney, subscriptionStatus } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.ClientTotals — per client: MRR (monthly base of billable subscriptions), open balance,
6
+ * overdue and drafts, with its spaces (Prod/Pruebas badge, subscription status, plan).
7
+ * Backend: GET {endpoint}/clients/totals. Emits `select-client` / `select-space` for navigation.
8
+ *
9
+ * <Billing.ClientTotals @select-space="key => navigateTo(`/platform/spaces/${key}`)" />
10
+ */
11
+ const props = withDefaults(defineProps<{ endpoint?: string }>(), { endpoint: 'platform/billing' })
12
+ const emit = defineEmits<{ 'select-client': [id: string]; 'select-space': [key: string] }>()
13
+
14
+ const { clientTotals } = useBillingPlatform({ base: props.endpoint })
15
+ const data = computed<any>(() => clientTotals.data.value)
16
+ const filter = ref<'all' | 'balance' | 'overdue'>('all')
17
+ const rows = computed<any[]>(() => (data.value?.data ?? []).filter((c: any) =>
18
+ filter.value === 'all' ? true : filter.value === 'overdue' ? c.overdue > 0 : c.balance > 0))
19
+ </script>
20
+
21
+ <template>
22
+ <div class="space-y-4">
23
+ <div v-if="data" class="grid gap-3 sm:grid-cols-3">
24
+ <App.StatCard label="MRR" :value="formatMoney(data.totals.mrr)" hint="Base mensual de las suscripciones vigentes" />
25
+ <App.StatCard label="Por cobrar" :value="formatMoney(data.totals.balance)" />
26
+ <App.StatCard label="Vencido" :value="formatMoney(data.totals.overdue)" :value-class="data.totals.overdue > 0 ? 'text-danger' : 'text-foreground'" />
27
+ </div>
28
+
29
+ <div class="flex gap-2 text-sm">
30
+ <button v-for="f in [['all', 'Todos'], ['balance', 'Con saldo'], ['overdue', 'Con mora']]" :key="f[0]" type="button"
31
+ class="px-3 py-1 rounded-control border" :class="filter === f[0] ? 'border-primary text-primary' : 'border-card-line text-muted-foreground'"
32
+ @click="filter = f[0] as any">{{ f[1] }}</button>
33
+ </div>
34
+
35
+ <div class="bg-card border border-card-line rounded-card overflow-hidden">
36
+ <div v-if="clientTotals.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
37
+ <div v-else-if="clientTotals.isError.value" class="p-8 text-center text-sm text-muted-foreground">
38
+ No se pudieron cargar los totales.
39
+ <button type="button" class="text-primary hover:underline" @click="clientTotals.refetch()">Reintentar</button>
40
+ </div>
41
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin clientes para este filtro.</div>
42
+ <ul v-else class="divide-y divide-card-line">
43
+ <li v-for="c in rows" :key="c.client_id" class="px-5 py-3 space-y-2">
44
+ <div class="flex flex-wrap items-center gap-3 text-sm">
45
+ <button type="button" class="flex-1 text-left font-medium text-foreground hover:underline" @click="emit('select-client', c.client_id)">
46
+ {{ c.name }} <span class="text-xs font-normal text-muted-foreground">{{ c.invoicing_mode === 'per_space' ? 'Factura por espacio' : 'Factura consolidada' }}</span>
47
+ </button>
48
+ <span class="text-muted-foreground">MRR {{ formatMoney(c.mrr) }}</span>
49
+ <span>Saldo {{ formatMoney(c.balance) }}</span>
50
+ <span :class="c.overdue > 0 ? 'text-danger font-medium' : 'text-muted-foreground'">Vencido {{ formatMoney(c.overdue) }}</span>
51
+ <App.Tag v-if="c.drafts" :text="`${c.drafts} borrador${c.drafts > 1 ? 'es' : ''}`" severity="info" size="xs" />
52
+ </div>
53
+ <div class="flex flex-wrap gap-2">
54
+ <button v-for="s in c.spaces" :key="s.key" type="button" class="flex items-center gap-1.5 rounded-control border border-card-line px-2 py-1 text-xs hover:bg-muted/50" @click="emit('select-space', s.key)">
55
+ <span class="text-foreground">{{ s.name }}</span>
56
+ <App.Tag :text="s.environment === 'testing' ? 'Pruebas' : 'Prod'" :severity="s.environment === 'testing' ? 'secondary' : 'primary'" size="xs" />
57
+ <App.Tag v-if="s.environment !== 'testing'" :text="s.subscription ? `${s.subscription.plan ?? ''} · ${subscriptionStatus(s.subscription.status).label}` : 'Sin suscripción'"
58
+ :severity="subscriptionStatus(s.subscription?.status).severity" size="xs" />
59
+ </button>
60
+ </div>
61
+ </li>
62
+ </ul>
63
+ </div>
64
+ </div>
65
+ </template>
@@ -0,0 +1,271 @@
1
+ <script setup lang="ts">
2
+ import { IconFileInvoice, IconSend, IconDownload, IconCash, IconCheck } from '@tabler/icons-vue'
3
+ import {
4
+ formatMoney, invoiceStatus, periodLabel, formatDateTime, eventLabel, paymentMethodLabel, parseMoney, errorMessage,
5
+ INVOICE_STATUS_OPTIONS, type Invoice,
6
+ } from '../../composables/useBilling/internal/billing'
7
+
8
+ /*
9
+ * Billing.Invoices — platform invoices: filters, detail (statements and lines per space, bitácora,
10
+ * payments), Emitir (folio optional, email to the billing contact), Reenviar, PDF and Registrar pago
11
+ * (transfer registered by hand; the remainder stays as client credit).
12
+ * Backend: \Innertia\Billing\Routes::platform() + platformWrite().
13
+ *
14
+ * <Billing.Invoices :clients="[{ value: id, label: name }]" />
15
+ * <Billing.Invoices :client-id="client.id" /> (inside a client detail)
16
+ * <Billing.Invoices space-key="rancagua" /> (inside a space detail)
17
+ */
18
+ const props = withDefaults(defineProps<{
19
+ endpoint?: string
20
+ clientId?: string | null
21
+ spaceKey?: string | null
22
+ clients?: { value: string; label: string }[]
23
+ canEdit?: boolean
24
+ }>(), { endpoint: 'platform/billing', clientId: null, spaceKey: null, clients: () => [], canEdit: true })
25
+
26
+ const toast = useToast()
27
+ const billing = useBillingPlatform({ base: props.endpoint })
28
+ const savePdf = useBillingPdf()
29
+
30
+ const filters = reactive({ status: '', client_id: props.clientId ?? '', tenant_key: props.spaceKey ?? '', page: 1 })
31
+ const filterRef = computed(() => ({ ...filters }))
32
+ const query = billing.invoices(filterRef)
33
+ const rows = computed<Invoice[]>(() => (query.data.value as any)?.data ?? [])
34
+ const meta = computed(() => (query.data.value as any)?.meta ?? { total: 0, page: 1, last_page: 1 })
35
+ watch(() => [filters.status, filters.client_id], () => { filters.page = 1 })
36
+
37
+ // ── Detail ────────────────────────────────────────────────────────────────
38
+ const detail = ref<Invoice | null>(null)
39
+ const loadingDetail = ref(false)
40
+ async function openDetail(i: Invoice) {
41
+ detail.value = i
42
+ loadingDetail.value = true
43
+ try {
44
+ detail.value = await billing.invoice(i.id)
45
+ } catch {
46
+ toast.error('No se pudo cargar la factura.')
47
+ } finally {
48
+ loadingDetail.value = false
49
+ }
50
+ }
51
+ const showDetail = computed({ get: () => detail.value !== null, set: (v) => { if (!v) detail.value = null } })
52
+
53
+ // ── Issue ─────────────────────────────────────────────────────────────────
54
+ const issueForm = reactive({ open: false, invoice: null as Invoice | null, folio: '', send: true })
55
+ function openIssue(i: Invoice) {
56
+ Object.assign(issueForm, { open: true, invoice: i, folio: i.folio ?? '', send: true })
57
+ }
58
+ async function submitIssue() {
59
+ if (!issueForm.invoice) return
60
+ try {
61
+ const res = await billing.issue.mutateAsync({ id: issueForm.invoice.id, body: { folio: issueForm.folio || null, send: issueForm.send } })
62
+ issueForm.open = false
63
+ if (detail.value?.id === res.id) detail.value = res
64
+ toast.success(`Factura ${res.display_number} emitida${issueForm.send ? ' y enviada' : ''}.`)
65
+ } catch (e: any) {
66
+ toast.error(errorMessage(e, 'No se pudo emitir la factura.'))
67
+ }
68
+ }
69
+
70
+ async function resend(i: Invoice) {
71
+ try {
72
+ const res = await billing.resend.mutateAsync(i.id)
73
+ res?.sent ? toast.success('Factura reenviada.') : toast.error('El cliente no tiene correo de facturación.')
74
+ } catch (e: any) {
75
+ toast.error(errorMessage(e, 'No se pudo reenviar la factura.'))
76
+ }
77
+ }
78
+
79
+ async function pdf(i: Invoice) {
80
+ try {
81
+ await savePdf(`${billing.base}/invoices/${i.id}/pdf`, `factura-${i.display_number ?? i.id}.pdf`)
82
+ } catch {
83
+ toast.error('No se pudo descargar el PDF.')
84
+ }
85
+ }
86
+
87
+ // ── Payment ───────────────────────────────────────────────────────────────
88
+ const payForm = reactive({ open: false, invoice: null as Invoice | null, amount: '', reference: '', received_at: '', method: 'transfer' })
89
+ function openPay(i: Invoice) {
90
+ Object.assign(payForm, { open: true, invoice: i, amount: String(i.balance), reference: '', received_at: new Date().toISOString().slice(0, 10), method: 'transfer' })
91
+ }
92
+ async function submitPay() {
93
+ const i = payForm.invoice
94
+ const amount = parseMoney(payForm.amount)
95
+ if (!i || !amount || Number.isNaN(amount) || amount <= 0) { toast.error('Ingresa un monto válido.'); return }
96
+ try {
97
+ await billing.registerPayment.mutateAsync({
98
+ client_id: i.client_id, amount, method: payForm.method, reference: payForm.reference || null,
99
+ received_at: payForm.received_at || null, invoice_id: i.id,
100
+ })
101
+ payForm.open = false
102
+ if (detail.value?.id === i.id) await openDetail(i)
103
+ toast.success(amount > i.balance ? 'Pago registrado. El excedente quedó como saldo a favor.' : 'Pago registrado.')
104
+ } catch (e: any) {
105
+ toast.error(errorMessage(e, 'No se pudo registrar el pago.'))
106
+ }
107
+ }
108
+
109
+ 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'
110
+ const isOpen = (i: Invoice) => i.status === 'issued' || i.status === 'overdue'
111
+ </script>
112
+
113
+ <template>
114
+ <div class="space-y-4">
115
+ <div class="flex flex-wrap items-end gap-3">
116
+ <label class="space-y-1">
117
+ <span class="text-xs text-muted-foreground">Estado</span>
118
+ <select v-model="filters.status" :class="inputClass">
119
+ <option value="">Todos</option>
120
+ <option v-for="o in INVOICE_STATUS_OPTIONS" :key="o.value" :value="o.value">{{ o.label }}</option>
121
+ </select>
122
+ </label>
123
+ <label v-if="!clientId && clients.length" class="space-y-1">
124
+ <span class="text-xs text-muted-foreground">Cliente</span>
125
+ <select v-model="filters.client_id" :class="inputClass">
126
+ <option value="">Todos</option>
127
+ <option v-for="c in clients" :key="c.value" :value="c.value">{{ c.label }}</option>
128
+ </select>
129
+ </label>
130
+ <span class="flex-1" />
131
+ <span class="text-xs text-muted-foreground">{{ meta.total }} facturas</span>
132
+ </div>
133
+
134
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
135
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
136
+ <div v-else-if="query.isError.value" class="p-8 text-center text-sm text-muted-foreground">
137
+ No se pudieron cargar las facturas.
138
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
139
+ </div>
140
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">
141
+ <IconFileInvoice class="size-6 mx-auto mb-2" :stroke-width="1.5" />
142
+ No hay facturas. Se generan en borrador al cerrar cada período.
143
+ </div>
144
+ <table v-else class="w-full text-sm">
145
+ <thead class="text-xs uppercase text-muted-foreground">
146
+ <tr class="border-b border-card-line">
147
+ <th class="text-left font-medium px-4 py-2">Factura</th>
148
+ <th class="text-left font-medium px-4 py-2">Cliente / espacio</th>
149
+ <th class="text-left font-medium px-4 py-2">Período</th>
150
+ <th class="text-right font-medium px-4 py-2">Total</th>
151
+ <th class="text-right font-medium px-4 py-2">Saldo</th>
152
+ <th class="text-left font-medium px-4 py-2">Vence</th>
153
+ <th class="px-4 py-2" />
154
+ </tr>
155
+ </thead>
156
+ <tbody class="divide-y divide-card-line">
157
+ <tr v-for="i in rows" :key="i.id" class="hover:bg-muted/40">
158
+ <td class="px-4 py-2">
159
+ <button type="button" class="font-medium text-foreground hover:underline" @click="openDetail(i)">{{ i.display_number ?? 'Borrador' }}</button>
160
+ <App.Tag :text="invoiceStatus(i.status).label" :severity="invoiceStatus(i.status).severity" size="xs" class="ml-2" />
161
+ <p v-if="i.folio" class="text-xs text-muted-foreground">Folio {{ i.folio }}</p>
162
+ </td>
163
+ <td class="px-4 py-2">
164
+ <p class="text-foreground">{{ i.client_name }}</p>
165
+ <p class="text-xs text-muted-foreground">{{ i.consolidated ? 'Consolidada' : i.tenant_name }}</p>
166
+ </td>
167
+ <td class="px-4 py-2 text-muted-foreground">{{ periodLabel(i.period_start, i.period_end) }}</td>
168
+ <td class="px-4 py-2 text-right">{{ formatMoney(i.total, i.currency) }}</td>
169
+ <td class="px-4 py-2 text-right" :class="i.status === 'overdue' ? 'text-danger font-medium' : ''">{{ formatMoney(i.balance, i.currency) }}</td>
170
+ <td class="px-4 py-2 text-muted-foreground">{{ formatDateTime(i.due_at) }}</td>
171
+ <td class="px-4 py-2">
172
+ <div class="flex justify-end gap-1">
173
+ <App.Button v-if="canEdit && i.status === 'draft'" text="Emitir" size="xs" severity="primary" :icon="IconCheck" @click="openIssue(i)" />
174
+ <App.Button v-if="canEdit && isOpen(i)" text="Registrar pago" size="xs" :icon="IconCash" @click="openPay(i)" />
175
+ <App.Button text="PDF" size="xs" outline :icon="IconDownload" @click="pdf(i)" />
176
+ </div>
177
+ </td>
178
+ </tr>
179
+ </tbody>
180
+ </table>
181
+ </div>
182
+
183
+ <div v-if="meta.last_page > 1" class="flex items-center justify-end gap-2 text-sm">
184
+ <App.Button text="Anterior" size="xs" :disabled="filters.page <= 1" @click="filters.page--" />
185
+ <span class="text-muted-foreground">Página {{ meta.page }} de {{ meta.last_page }}</span>
186
+ <App.Button text="Siguiente" size="xs" :disabled="filters.page >= meta.last_page" @click="filters.page++" />
187
+ </div>
188
+
189
+ <!-- Detail -->
190
+ <Modal v-model="showDetail" :title="detail ? `Factura ${detail.display_number ?? '(borrador)'}` : ''" size="3xl" show-footer>
191
+ <div v-if="detail" class="space-y-4 text-sm">
192
+ <div class="flex flex-wrap gap-2 items-center">
193
+ <App.Tag :text="invoiceStatus(detail.status).label" :severity="invoiceStatus(detail.status).severity" size="xs" />
194
+ <span class="text-muted-foreground">{{ detail.client_name }} · {{ detail.consolidated ? 'Factura consolidada' : detail.tenant_name }} · {{ paymentMethodLabel(detail.payment_method) }}</span>
195
+ </div>
196
+ <div class="grid gap-2 sm:grid-cols-4">
197
+ <div><p class="text-xs text-muted-foreground">Subtotal</p><p>{{ formatMoney(detail.subtotal, detail.currency) }}</p></div>
198
+ <div><p class="text-xs text-muted-foreground">IVA</p><p>{{ formatMoney(detail.tax, detail.currency) }}</p></div>
199
+ <div><p class="text-xs text-muted-foreground">Total</p><p class="font-medium">{{ formatMoney(detail.total, detail.currency) }}</p></div>
200
+ <div><p class="text-xs text-muted-foreground">Saldo</p><p class="font-medium">{{ formatMoney(detail.balance, detail.currency) }}</p></div>
201
+ </div>
202
+ <p v-if="detail.payment_link" class="text-xs">Enlace de pago: <a :href="detail.payment_link" target="_blank" rel="noopener" class="text-primary hover:underline break-all">{{ detail.payment_link }}</a></p>
203
+
204
+ <div v-if="loadingDetail" class="text-muted-foreground">Cargando detalle…</div>
205
+ <template v-else>
206
+ <div v-for="s in detail.statements ?? []" :key="s.id" class="border border-card-line rounded-control">
207
+ <p class="px-3 py-2 bg-muted/40 text-xs font-medium">{{ s.tenant_name ?? s.tenant_id }} · {{ periodLabel(s.period_start, s.period_end) }}</p>
208
+ <table class="w-full">
209
+ <tbody class="divide-y divide-card-line">
210
+ <tr v-for="(l, idx) in s.lines" :key="idx">
211
+ <td class="px-3 py-1.5">{{ l.description }}</td>
212
+ <td class="px-3 py-1.5 text-right text-muted-foreground">{{ l.quantity }}</td>
213
+ <td class="px-3 py-1.5 text-right text-muted-foreground">{{ l.unit_price ? formatMoney(l.unit_price, detail.currency) : '' }}</td>
214
+ <td class="px-3 py-1.5 text-right">{{ formatMoney(l.amount, detail.currency) }}</td>
215
+ </tr>
216
+ </tbody>
217
+ </table>
218
+ </div>
219
+
220
+ <div v-if="detail.events?.length">
221
+ <p class="text-xs font-medium text-muted-foreground mb-1">Bitácora</p>
222
+ <ul class="space-y-1">
223
+ <li v-for="(e, idx) in detail.events" :key="idx" class="text-xs text-muted-foreground">
224
+ {{ formatDateTime(e.created_at) }} · {{ eventLabel(e.event) }}<template v-if="e.data?.amount"> · {{ formatMoney(e.data.amount, detail.currency) }}</template>
225
+ </li>
226
+ </ul>
227
+ </div>
228
+ </template>
229
+ </div>
230
+ <template #footer>
231
+ <template v-if="detail">
232
+ <App.Button v-if="canEdit && detail.status === 'draft'" text="Emitir" size="sm" severity="primary" :icon="IconCheck" @click="openIssue(detail)" />
233
+ <App.Button v-if="canEdit && detail.status !== 'draft' && detail.status !== 'void'" text="Reenviar" size="sm" :icon="IconSend" :loading="billing.resend.isPending.value" @click="resend(detail)" />
234
+ <App.Button v-if="canEdit && isOpen(detail)" text="Registrar pago" size="sm" :icon="IconCash" @click="openPay(detail)" />
235
+ <App.Button text="PDF" size="sm" outline :icon="IconDownload" @click="pdf(detail)" />
236
+ </template>
237
+ <App.Button text="Cerrar" size="sm" @click="detail = null" />
238
+ </template>
239
+ </Modal>
240
+
241
+ <!-- Issue -->
242
+ <Modal v-model="issueForm.open" title="Emitir factura" size="md" show-footer>
243
+ <div v-if="issueForm.invoice" class="space-y-3 text-sm">
244
+ <p>Se asigna el número correlativo, vence según el plazo del cliente y se envía al correo de facturación con el PDF adjunto. Total {{ formatMoney(issueForm.invoice.total, issueForm.invoice.currency) }}.</p>
245
+ <label class="block space-y-1"><span class="font-medium">Folio SII (opcional)</span><input v-model="issueForm.folio" :class="inputClass" maxlength="40" /></label>
246
+ <label class="flex items-center gap-2"><input v-model="issueForm.send" type="checkbox" class="rounded" /> Enviar por correo y avisar a los administradores del espacio</label>
247
+ </div>
248
+ <template #footer>
249
+ <App.Button text="Cancelar" size="sm" @click="issueForm.open = false" />
250
+ <App.Button text="Emitir" severity="primary" size="sm" :loading="billing.issue.isPending.value" @click="submitIssue" />
251
+ </template>
252
+ </Modal>
253
+
254
+ <!-- Payment -->
255
+ <Modal v-model="payForm.open" title="Registrar pago" size="md" show-footer>
256
+ <div v-if="payForm.invoice" class="space-y-3 text-sm">
257
+ <p class="text-muted-foreground">Factura {{ payForm.invoice.display_number }} · saldo {{ formatMoney(payForm.invoice.balance, payForm.invoice.currency) }}</p>
258
+ <label class="block space-y-1"><span class="font-medium">Monto ($)</span><input v-model="payForm.amount" inputmode="numeric" :class="inputClass" /></label>
259
+ <label class="block space-y-1"><span class="font-medium">Medio</span>
260
+ <select v-model="payForm.method" :class="inputClass"><option value="transfer">Transferencia</option><option value="manual">Otro (manual)</option></select>
261
+ </label>
262
+ <label class="block space-y-1"><span class="font-medium">Fecha de recepción</span><input v-model="payForm.received_at" type="date" :class="inputClass" /></label>
263
+ <label class="block space-y-1"><span class="font-medium">Referencia</span><input v-model="payForm.reference" :class="inputClass" maxlength="120" placeholder="N° de operación" /></label>
264
+ </div>
265
+ <template #footer>
266
+ <App.Button text="Cancelar" size="sm" @click="payForm.open = false" />
267
+ <App.Button text="Registrar" severity="primary" size="sm" :loading="billing.registerPayment.isPending.value" @click="submitPay" />
268
+ </template>
269
+ </Modal>
270
+ </div>
271
+ </template>