@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.
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/AccountStatement.vue +121 -0
  7. package/components/Billing/ActivityLog.vue +44 -0
  8. package/components/Billing/Adjustments.vue +169 -0
  9. package/components/Billing/ClientTerms.vue +70 -0
  10. package/components/Billing/ClientTotals.vue +65 -0
  11. package/components/Billing/CreditNoteForm.vue +82 -0
  12. package/components/Billing/Invoices.vue +394 -0
  13. package/components/Billing/Overview.vue +130 -0
  14. package/components/Billing/Plans.vue +146 -0
  15. package/components/Billing/Reconciliation.vue +309 -0
  16. package/components/Billing/Reports.vue +87 -0
  17. package/components/Billing/Settings.vue +112 -0
  18. package/components/Billing/SpaceSubscription.vue +202 -0
  19. package/components/Billing/StatusBanner.vue +36 -0
  20. package/components/Billing/UsageTable.vue +32 -0
  21. package/components/Billing/__tests__/sfc-compile.test.ts +29 -0
  22. package/composables/useAiUsage/index.ts +48 -0
  23. package/composables/useAiUsage/internal/__tests__/aiUsage.test.ts +50 -0
  24. package/composables/useAiUsage/internal/aiUsage.ts +140 -0
  25. package/composables/useBilling/index.ts +257 -0
  26. package/composables/useBilling/internal/__tests__/billing.test.ts +78 -0
  27. package/composables/useBilling/internal/__tests__/collections.test.ts +120 -0
  28. package/composables/useBilling/internal/billing.ts +587 -0
  29. package/docs/ai-usage.md +38 -0
  30. package/docs/billing.md +110 -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,121 @@
1
+ <script setup lang="ts">
2
+ import { IconDownload, IconCoin } from '@tabler/icons-vue'
3
+ import { formatMoney, formatDate, movementLabel, AGING_BUCKETS, errorMessage } from '../../composables/useBilling/internal/billing'
4
+
5
+ /*
6
+ * Billing.AccountStatement — estado de cuenta: charges, credits and running balance (opening balance with
7
+ * "desde"), credit in favor, aging of the open debt (not due, 0–30, 31–60, 61–90, 90+) and open invoices.
8
+ * platform: <Billing.AccountStatement :client-id="client.id" /> (whole client; xlsx export,
9
+ * "Aplicar saldo a favor"; space-key narrows to one space)
10
+ * backoffice: <Billing.AccountStatement mode="space" /> (active space, read-only)
11
+ * Backend: GET {endpoint}/clients/{id}/account(/export) · POST …/apply-credit — backoffice GET {endpoint}/account.
12
+ */
13
+ const props = withDefaults(defineProps<{
14
+ endpoint?: string
15
+ mode?: 'client' | 'space'
16
+ clientId?: string | null
17
+ spaceKey?: string | null
18
+ canEdit?: boolean
19
+ }>(), { endpoint: undefined, mode: 'client', clientId: null, spaceKey: null, canEdit: true })
20
+
21
+ const toast = useToast()
22
+ const range = reactive({ from: '', to: '' })
23
+ const params = computed(() => ({ from: range.from, to: range.to, tenant_key: props.spaceKey }))
24
+ const isSpace = props.mode === 'space'
25
+ const platform = isSpace ? null : useBillingPlatform({ base: props.endpoint ?? 'platform/billing' })
26
+ const space = isSpace ? useBillingSpace({ base: props.endpoint ?? 'billing' }) : null
27
+ const query = isSpace
28
+ ? space!.account(computed(() => ({ from: range.from, to: range.to })))
29
+ : platform!.account(computed(() => props.clientId ?? ''), params)
30
+ const data = computed<any>(() => query.data.value)
31
+ const download = useBillingDownload()
32
+
33
+ async function exportXlsx() {
34
+ if (!platform || !props.clientId) return
35
+ try {
36
+ await download(`${platform.base}/clients/${props.clientId}/account/export`, `estado-de-cuenta.xlsx`, params.value)
37
+ } catch {
38
+ toast.error('No se pudo descargar el estado de cuenta.')
39
+ }
40
+ }
41
+
42
+ async function applyCredit() {
43
+ if (!platform || !props.clientId) return
44
+ try {
45
+ const res = await platform.applyCredit.mutateAsync({ clientId: props.clientId })
46
+ toast.success(res.applied > 0 ? `Saldo a favor aplicado: ${formatMoney(res.applied)}.` : 'No hay facturas abiertas para aplicar el saldo.')
47
+ query.refetch()
48
+ } catch (e: any) {
49
+ toast.error(errorMessage(e, 'No se pudo aplicar el saldo a favor.'))
50
+ }
51
+ }
52
+
53
+ 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'
54
+ </script>
55
+
56
+ <template>
57
+ <div class="space-y-4">
58
+ <div class="flex flex-wrap items-end gap-3 text-sm">
59
+ <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>
60
+ <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>
61
+ <span class="flex-1" />
62
+ <App.Button v-if="!isSpace && canEdit && (data?.credit_available ?? 0) > 0" text="Aplicar saldo a favor" size="sm" :icon="IconCoin" :loading="platform?.applyCredit.isPending.value" @click="applyCredit" />
63
+ <App.Button v-if="!isSpace" text="Excel" size="sm" outline :icon="IconDownload" @click="exportXlsx" />
64
+ </div>
65
+
66
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
67
+ <div v-else-if="query.isError.value || !data" class="p-8 text-center text-sm text-muted-foreground">
68
+ No se pudo cargar el estado de cuenta.
69
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
70
+ </div>
71
+ <div v-else-if="data.testing" class="rounded-card border border-info/40 bg-info/5 p-4 text-sm">Espacio de pruebas: no tiene facturación.</div>
72
+
73
+ <template v-else>
74
+ <div class="grid gap-3 sm:grid-cols-3">
75
+ <App.StatCard label="Saldo" :value="formatMoney(data.closing_balance, data.currency)" :value-class="data.closing_balance > 0 ? 'text-foreground' : 'text-success'"
76
+ :hint="data.closing_balance < 0 ? 'A favor del cliente' : 'Cargos menos abonos'" />
77
+ <App.StatCard label="Deuda abierta" :value="formatMoney(data.open_balance, data.currency)" :value-class="data.aging.total - data.aging.current > 0 ? 'text-danger' : 'text-foreground'"
78
+ :hint="`${formatMoney(data.aging.total - data.aging.current, data.currency)} vencido`" />
79
+ <App.StatCard v-if="data.credit_available !== null" label="Saldo a favor disponible" :value="formatMoney(data.credit_available, data.currency)" hint="Se aplica a la próxima factura emitida" />
80
+ </div>
81
+
82
+ <div class="bg-card border border-card-line rounded-card p-4">
83
+ <p class="text-sm font-medium text-foreground mb-2">Antigüedad de la deuda</p>
84
+ <div class="grid gap-2 grid-cols-2 sm:grid-cols-5 text-sm">
85
+ <div v-for="b in AGING_BUCKETS" :key="b.key">
86
+ <p class="text-xs text-muted-foreground">{{ b.label }}</p>
87
+ <p :class="b.key !== 'current' && data.aging[b.key] > 0 ? 'text-danger font-medium' : ''">{{ formatMoney(data.aging[b.key], data.currency) }}</p>
88
+ </div>
89
+ </div>
90
+ </div>
91
+
92
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
93
+ <table class="w-full text-sm">
94
+ <thead class="text-xs uppercase text-muted-foreground">
95
+ <tr class="border-b border-card-line">
96
+ <th class="text-left font-medium px-4 py-2">Fecha</th>
97
+ <th class="text-left font-medium px-4 py-2">Detalle</th>
98
+ <th class="text-right font-medium px-4 py-2">Cargo</th>
99
+ <th class="text-right font-medium px-4 py-2">Abono</th>
100
+ <th class="text-right font-medium px-4 py-2">Saldo</th>
101
+ </tr>
102
+ </thead>
103
+ <tbody class="divide-y divide-card-line">
104
+ <tr v-if="range.from" class="text-muted-foreground">
105
+ <td class="px-4 py-2">{{ formatDate(range.from) }}</td><td class="px-4 py-2">Saldo inicial</td><td /><td />
106
+ <td class="px-4 py-2 text-right">{{ formatMoney(data.opening_balance, data.currency) }}</td>
107
+ </tr>
108
+ <tr v-if="!data.movements.length"><td colspan="5" class="p-6 text-center text-muted-foreground">Sin movimientos en el rango.</td></tr>
109
+ <tr v-for="(m, idx) in data.movements" :key="idx">
110
+ <td class="px-4 py-2 whitespace-nowrap text-muted-foreground">{{ formatDate(m.date) }}</td>
111
+ <td class="px-4 py-2"><span class="text-xs text-muted-foreground mr-1">{{ movementLabel(m.type) }}</span>{{ m.description }}</td>
112
+ <td class="px-4 py-2 text-right">{{ m.charge ? formatMoney(m.charge, data.currency) : '' }}</td>
113
+ <td class="px-4 py-2 text-right text-success">{{ m.credit ? formatMoney(m.credit, data.currency) : '' }}</td>
114
+ <td class="px-4 py-2 text-right font-medium">{{ formatMoney(m.balance, data.currency) }}</td>
115
+ </tr>
116
+ </tbody>
117
+ </table>
118
+ </div>
119
+ </template>
120
+ </div>
121
+ </template>
@@ -0,0 +1,44 @@
1
+ <script setup lang="ts">
2
+ import { formatDateTime, activityLabel, formatMoney } from '../../composables/useBilling/internal/billing'
3
+
4
+ /*
5
+ * Billing.ActivityLog — collections audit log of a client (who did what: adjustments, credit notes,
6
+ * voids and reissues, terms, reconciliations, waivers), newest first.
7
+ * Backend: GET {endpoint}/activity?client_id=.
8
+ *
9
+ * <Billing.ActivityLog :client-id="client.id" :users="{ [id]: name }" />
10
+ */
11
+ const props = withDefaults(defineProps<{ endpoint?: string; clientId?: string | null; users?: Record<string, string> }>(), { endpoint: 'platform/billing', clientId: null, users: () => ({}) })
12
+
13
+ const billing = useBillingPlatform({ base: props.endpoint })
14
+ const page = ref(1)
15
+ const query = billing.activity(computed(() => ({ client_id: props.clientId, page: page.value })))
16
+ const rows = computed<any[]>(() => (query.data.value as any)?.data ?? [])
17
+ const meta = computed(() => (query.data.value as any)?.meta ?? { page: 1, last_page: 1 })
18
+
19
+ function detail(a: any): string {
20
+ const d = a.data ?? {}
21
+ const parts = [d.number, d.invoice, d.reason]
22
+ if (typeof d.amount === 'number') parts.push(formatMoney(d.amount))
23
+ return parts.filter(Boolean).join(' · ')
24
+ }
25
+ const who = (a: any) => !a.user_id ? 'Sistema' : (props.users[a.user_id] ?? `Usuario ${a.user_id}`)
26
+ </script>
27
+
28
+ <template>
29
+ <div class="bg-card border border-card-line rounded-card">
30
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
31
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin actividad de cobranza.</div>
32
+ <ul v-else class="divide-y divide-card-line text-sm">
33
+ <li v-for="a in rows" :key="a.id" class="px-4 py-2">
34
+ <p class="text-foreground">{{ activityLabel(a.subject_type, a.action) }}<span v-if="detail(a)" class="text-muted-foreground"> · {{ detail(a) }}</span></p>
35
+ <p class="text-xs text-muted-foreground">{{ formatDateTime(a.created_at) }} · {{ who(a) }}</p>
36
+ </li>
37
+ </ul>
38
+ <div v-if="meta.last_page > 1" class="flex items-center justify-end gap-2 p-3 text-sm">
39
+ <App.Button text="Anterior" size="xs" :disabled="page <= 1" @click="page--" />
40
+ <span class="text-muted-foreground">Página {{ meta.page }} de {{ meta.last_page }}</span>
41
+ <App.Button text="Siguiente" size="xs" :disabled="page >= meta.last_page" @click="page++" />
42
+ </div>
43
+ </div>
44
+ </template>
@@ -0,0 +1,169 @@
1
+ <script setup lang="ts">
2
+ import { IconPlus, IconReceiptRefund, IconX } from '@tabler/icons-vue'
3
+ import {
4
+ ADJUSTMENT_TYPES, adjustmentTypeLabel, adjustmentValue, adjustmentStatus, adjustmentPayload, formatDate, formatDateTime,
5
+ errorMessage, type Adjustment, type AdjustmentForm,
6
+ } from '../../composables/useBilling/internal/billing'
7
+
8
+ /*
9
+ * Billing.Adjustments — discounts, surcharges, one-off charges and credits of a client's spaces (or of the
10
+ * whole client: percent discounts/surcharges applied to every space), plus its credit notes. Every
11
+ * adjustment carries reason and author; pending ones can be canceled. They enter the next closes.
12
+ * Backend: GET|POST {endpoint}/adjustments, POST {endpoint}/adjustments/{id}/cancel, POST {endpoint}/credit-notes.
13
+ *
14
+ * <Billing.Adjustments :client-id="client.id" :spaces="[{ value: 'rancagua', label: 'Rancagua' }]" />
15
+ * <Billing.Adjustments :client-id="client.id" space-key="rancagua" /> (inside a space detail)
16
+ */
17
+ const props = withDefaults(defineProps<{
18
+ endpoint?: string
19
+ clientId: string
20
+ spaceKey?: string | null
21
+ spaces?: { value: string; label: string }[]
22
+ canEdit?: boolean
23
+ }>(), { endpoint: 'platform/billing', spaceKey: null, spaces: () => [], canEdit: true })
24
+
25
+ const toast = useToast()
26
+ const { prompt } = useModal()
27
+ const billing = useBillingPlatform({ base: props.endpoint })
28
+
29
+ const status = ref<'' | 'pending' | 'applied' | 'canceled'>('')
30
+ const filters = computed(() => ({ client_id: props.spaceKey ? null : props.clientId, tenant_key: props.spaceKey, status: status.value }))
31
+ const query = billing.adjustments(filters)
32
+ const rows = computed<Adjustment[]>(() => (query.data.value as Adjustment[] | undefined) ?? [])
33
+ const spaceName = (a: Adjustment) => a.scope === 'client' ? 'Todo el cliente' : (props.spaces.find(s => s.value === a.tenant_id)?.label ?? props.spaceKey ?? 'Espacio')
34
+
35
+ const empty = (): AdjustmentForm => ({
36
+ scope: 'space', tenant_key: props.spaceKey ?? props.spaces[0]?.value ?? '', type: 'discount', mode: 'amount', value: '',
37
+ recurring: false, starts_at: '', ends_at: '', reason: '',
38
+ })
39
+ const form = reactive({ open: false, data: empty() })
40
+ const once = computed(() => form.data.type === 'one_off' || form.data.type === 'credit')
41
+
42
+ async function submit() {
43
+ const { payload, error } = adjustmentPayload(form.data, props.clientId)
44
+ if (error) { toast.error(error); return }
45
+ try {
46
+ await billing.createAdjustment.mutateAsync(payload)
47
+ form.open = false
48
+ toast.success('Ajuste creado. Se aplica en el próximo cierre.')
49
+ } catch (e: any) {
50
+ toast.error(errorMessage(e, 'No se pudo crear el ajuste.'))
51
+ }
52
+ }
53
+
54
+ async function cancel(a: Adjustment) {
55
+ const reason = await prompt({ title: 'Anular ajuste', message: `${adjustmentTypeLabel(a.type)} "${a.reason}". Indica el motivo.`, required: true, confirmText: 'Anular' })
56
+ if (!reason) return
57
+ try {
58
+ await billing.cancelAdjustment.mutateAsync({ id: a.id, reason })
59
+ toast.success('Ajuste anulado.')
60
+ } catch (e: any) {
61
+ toast.error(errorMessage(e, 'No se pudo anular.'))
62
+ }
63
+ }
64
+
65
+ const creditNoteOpen = ref(false)
66
+ 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'
67
+ </script>
68
+
69
+ <template>
70
+ <div class="space-y-4">
71
+ <div class="flex flex-wrap items-end gap-3">
72
+ <label class="space-y-1">
73
+ <span class="text-xs text-muted-foreground">Estado</span>
74
+ <select v-model="status" :class="inputClass">
75
+ <option value="">Todos</option>
76
+ <option value="pending">Pendientes</option>
77
+ <option value="applied">Aplicados</option>
78
+ <option value="canceled">Anulados</option>
79
+ </select>
80
+ </label>
81
+ <span class="flex-1" />
82
+ <App.Button v-if="canEdit" text="Nota de crédito" size="sm" :icon="IconReceiptRefund" @click="creditNoteOpen = true" />
83
+ <App.Button v-if="canEdit" text="Nuevo ajuste" size="sm" severity="primary" :icon="IconPlus" @click="form.data = empty(); form.open = true" />
84
+ </div>
85
+
86
+ <div class="bg-card border border-card-line rounded-card overflow-x-auto">
87
+ <div v-if="query.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
88
+ <div v-else-if="query.isError.value" class="p-8 text-center text-sm text-muted-foreground">
89
+ No se pudieron cargar los ajustes.
90
+ <button type="button" class="text-primary hover:underline" @click="query.refetch()">Reintentar</button>
91
+ </div>
92
+ <div v-else-if="!rows.length" class="p-8 text-center text-sm text-muted-foreground">Sin ajustes ni notas de crédito.</div>
93
+ <table v-else class="w-full text-sm">
94
+ <thead class="text-xs uppercase text-muted-foreground">
95
+ <tr class="border-b border-card-line">
96
+ <th class="text-left font-medium px-4 py-2">Ajuste</th>
97
+ <th class="text-left font-medium px-4 py-2">Alcance</th>
98
+ <th class="text-right font-medium px-4 py-2">Valor</th>
99
+ <th class="text-left font-medium px-4 py-2">Vigencia</th>
100
+ <th class="text-left font-medium px-4 py-2">Motivo</th>
101
+ <th class="px-4 py-2" />
102
+ </tr>
103
+ </thead>
104
+ <tbody class="divide-y divide-card-line">
105
+ <tr v-for="a in rows" :key="a.id">
106
+ <td class="px-4 py-2">
107
+ <p class="font-medium text-foreground">{{ a.credit_note ? `Nota de crédito ${a.display_number}` : adjustmentTypeLabel(a.type) }}</p>
108
+ <App.Tag :text="adjustmentStatus(a.status).label" :severity="adjustmentStatus(a.status).severity" size="xs" />
109
+ </td>
110
+ <td class="px-4 py-2 text-muted-foreground">{{ spaceName(a) }}</td>
111
+ <td class="px-4 py-2 text-right whitespace-nowrap">{{ adjustmentValue(a) }}</td>
112
+ <td class="px-4 py-2 text-muted-foreground">
113
+ <template v-if="a.credit_note">{{ a.target === 'invoice' ? 'A factura' : a.target === 'balance' ? 'Saldo a favor' : 'Próximo cobro' }}</template>
114
+ <template v-else-if="a.recurring">Recurrente {{ a.starts_at ? `desde ${formatDate(a.starts_at)}` : '' }} {{ a.ends_at ? `hasta ${formatDate(a.ends_at)}` : '(sin término)' }}</template>
115
+ <template v-else>Una vez</template>
116
+ </td>
117
+ <td class="px-4 py-2">
118
+ <p>{{ a.reason }}</p>
119
+ <p class="text-xs text-muted-foreground">{{ formatDateTime(a.created_at) }}<template v-if="a.cancel_reason"> · anulado: {{ a.cancel_reason }}</template></p>
120
+ </td>
121
+ <td class="px-4 py-2 text-right">
122
+ <App.Button v-if="canEdit && a.status === 'pending'" text="Anular" size="xs" outline :icon="IconX" @click="cancel(a)" />
123
+ </td>
124
+ </tr>
125
+ </tbody>
126
+ </table>
127
+ </div>
128
+
129
+ <Modal v-model="form.open" title="Nuevo ajuste" size="md" show-footer>
130
+ <div class="space-y-3 text-sm">
131
+ <div v-if="!spaceKey" class="flex gap-4">
132
+ <label class="flex items-center gap-2"><input v-model="form.data.scope" type="radio" value="space" /> Un espacio</label>
133
+ <label class="flex items-center gap-2"><input v-model="form.data.scope" type="radio" value="client" /> Todo el cliente (porcentaje)</label>
134
+ </div>
135
+ <label v-if="form.data.scope === 'space' && !spaceKey" class="block space-y-1"><span class="font-medium">Espacio</span>
136
+ <select v-model="form.data.tenant_key" :class="inputClass"><option v-for="s in spaces" :key="s.value" :value="s.value">{{ s.label }}</option></select>
137
+ </label>
138
+ <div class="grid grid-cols-2 gap-3">
139
+ <label class="block space-y-1"><span class="font-medium">Tipo</span>
140
+ <select v-model="form.data.type" :class="inputClass">
141
+ <option v-for="t in ADJUSTMENT_TYPES" :key="t.value" :value="t.value" :disabled="form.data.scope === 'client' && !['discount', 'surcharge'].includes(t.value)">{{ t.label }}</option>
142
+ </select>
143
+ </label>
144
+ <label class="block space-y-1"><span class="font-medium">Cálculo</span>
145
+ <select v-model="form.data.mode" :class="inputClass">
146
+ <option value="amount" :disabled="form.data.scope === 'client'">Monto neto ($)</option>
147
+ <option value="percent">Porcentaje (%)</option>
148
+ </select>
149
+ </label>
150
+ </div>
151
+ <label class="block space-y-1"><span class="font-medium">{{ form.data.mode === 'percent' ? 'Porcentaje' : 'Monto (antes de IVA)' }}</span>
152
+ <input v-model="form.data.value" inputmode="decimal" :class="inputClass" />
153
+ </label>
154
+ <label v-if="!once" class="flex items-center gap-2"><input v-model="form.data.recurring" type="checkbox" class="rounded" /> Recurrente (se aplica en cada cierre dentro de la vigencia)</label>
155
+ <div class="grid grid-cols-2 gap-3">
156
+ <label class="block space-y-1"><span class="font-medium">Desde</span><input v-model="form.data.starts_at" type="date" :class="inputClass" /></label>
157
+ <label v-if="!once" class="block space-y-1"><span class="font-medium">Hasta</span><input v-model="form.data.ends_at" type="date" :class="inputClass" /></label>
158
+ </div>
159
+ <label class="block space-y-1"><span class="font-medium">Motivo</span><input v-model="form.data.reason" :class="inputClass" maxlength="250" placeholder="Aparece como línea del cobro" /></label>
160
+ </div>
161
+ <template #footer>
162
+ <App.Button text="Cancelar" size="sm" @click="form.open = false" />
163
+ <App.Button text="Crear ajuste" severity="primary" size="sm" :loading="billing.createAdjustment.isPending.value" @click="submit" />
164
+ </template>
165
+ </Modal>
166
+
167
+ <Billing.CreditNoteForm v-model="creditNoteOpen" :endpoint="endpoint" :client-id="clientId" :spaces="spaceKey ? [{ value: spaceKey, label: spaceKey }] : spaces" />
168
+ </div>
169
+ </template>