@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
@@ -0,0 +1,458 @@
1
+ <script setup lang="ts">
2
+ import { IconWebhook, IconPlus, IconRefresh, IconTrash, IconSend, IconAlertTriangle, IconBook, IconPlayerPause, IconPlayerPlay, IconPencil } from '@tabler/icons-vue'
3
+ import {
4
+ webhookState, deliveryStatus, httpSeverity, groupEvents, toggleFamily, toggleEvent, familyState, isEventSelected,
5
+ groupScopes, toggleValue, validateWebhookUrl, relativeTime, formatDateTime, appendPage, prettyJson,
6
+ type Webhook, type WebhookEvent, type WebhookLog,
7
+ } from '../../composables/useIntegrations/internal/integrations'
8
+
9
+ /*
10
+ * Integrations.Webhooks — outbound webhooks of the active space: list, create/edit (https URL,
11
+ * events with `family.*` wildcards, optional site, sensitive-data scopes), secret shown ONCE,
12
+ * delivery log with resend, test event, secret rotation (24 h double signature), pause/enable, delete.
13
+ * Backend: \Innertia\PublicApi\Routes::manage() (GET|POST webhooks, …).
14
+ *
15
+ * <Integrations.Webhooks :organizations="sites" developers-url="/developers" />
16
+ */
17
+ const props = withDefaults(defineProps<{
18
+ endpoint?: string
19
+ organizations?: { value: string | number; label: string }[]
20
+ canManage?: boolean
21
+ developersUrl?: string
22
+ }>(), { endpoint: 'integrations', organizations: () => [], canManage: true, developersUrl: '' })
23
+
24
+ const toast = useToast()
25
+ const { confirm } = useModal()
26
+ const wh = useWebhooks({ base: props.endpoint })
27
+ const keysApi = useApiKeys({ base: props.endpoint })
28
+
29
+ const hooks = computed<Webhook[]>(() => (wh.list.data.value as Webhook[] | undefined) ?? [])
30
+ const catalog = computed<WebhookEvent[]>(() => (wh.events.data.value as WebhookEvent[] | undefined) ?? [])
31
+ const eventGroups = computed(() => groupEvents(catalog.value))
32
+ // Sensitive-data scopes the subscription may receive (e.g. people:pii, recordings:read): only those
33
+ // that some event declares.
34
+ const sensitiveScopes = computed(() => {
35
+ const declared = new Set(catalog.value.map(e => e.scope).filter(Boolean) as string[])
36
+ const all = ((keysApi.scopes.data.value as any[]) ?? []).filter(s => declared.has(s.key))
37
+ const known = new Set(all.map(s => s.key))
38
+ for (const s of declared) if (!known.has(s)) all.push({ key: s })
39
+ return groupScopes(all)
40
+ })
41
+ const orgLabel = (id: any) => props.organizations.find(o => String(o.value) === String(id))?.label ?? id
42
+
43
+ const errorMessage = (e: any, fallback: string) =>
44
+ e?.data?.message ?? (e?.data?.errors ? Object.values(e.data.errors).flat()[0] : null) ?? fallback
45
+
46
+ // ── Create / edit ───────────────────────────────────────────────────────────
47
+ const showForm = ref(false)
48
+ const editing = ref<Webhook | null>(null)
49
+ const form = reactive({ url: '', description: '', events: [] as string[], organization_id: '' as string | number, scopes: [] as string[] })
50
+ const urlError = computed(() => (form.url ? validateWebhookUrl(form.url) : null))
51
+ const canSubmit = computed(() => !validateWebhookUrl(form.url) && form.events.length > 0)
52
+ const saving = computed(() => wh.create.isPending.value || wh.update.isPending.value)
53
+
54
+ function openCreate() {
55
+ editing.value = null
56
+ Object.assign(form, { url: '', description: '', events: [], organization_id: '', scopes: [] })
57
+ showForm.value = true
58
+ }
59
+
60
+ function openEdit(w: Webhook) {
61
+ editing.value = w
62
+ Object.assign(form, {
63
+ url: w.url, description: w.description ?? '', events: [...w.events],
64
+ organization_id: w.organization_id ?? '', scopes: [...(w.scopes ?? [])],
65
+ })
66
+ showForm.value = true
67
+ }
68
+
69
+ async function submitForm() {
70
+ if (!canSubmit.value) return
71
+ const body = {
72
+ url: form.url.trim(),
73
+ description: form.description.trim() || null,
74
+ events: form.events,
75
+ organization_id: form.organization_id === '' ? null : form.organization_id,
76
+ scopes: form.scopes,
77
+ }
78
+ try {
79
+ if (editing.value) {
80
+ const res = await wh.update.mutateAsync({ id: editing.value.id, ...body })
81
+ if (detail.value?.id === editing.value.id) detail.value = res.data
82
+ showForm.value = false
83
+ toast.success('Webhook actualizado.')
84
+ } else {
85
+ const res = await wh.create.mutateAsync({ ...body, active: true })
86
+ showForm.value = false
87
+ secret.value = { value: res.secret, title: 'Webhook creado' }
88
+ }
89
+ } catch (e: any) {
90
+ toast.error(errorMessage(e, 'No se pudo guardar el webhook.'))
91
+ }
92
+ }
93
+
94
+ // ── Secret shown once ───────────────────────────────────────────────────────
95
+ const secret = ref<{ value: string; title: string; note?: string } | null>(null)
96
+ const showSecret = computed({ get: () => secret.value !== null, set: (v) => { if (!v) secret.value = null } })
97
+
98
+ // ── Actions ─────────────────────────────────────────────────────────────────
99
+ async function setActive(w: Webhook, active: boolean) {
100
+ try {
101
+ const res = await wh.update.mutateAsync({ id: w.id, active })
102
+ if (detail.value?.id === w.id) detail.value = res.data
103
+ toast.success(active ? 'Webhook activado.' : 'Webhook pausado.')
104
+ } catch (e: any) {
105
+ toast.error(errorMessage(e, 'No se pudo actualizar el webhook.'))
106
+ }
107
+ }
108
+
109
+ async function doRotate(w: Webhook) {
110
+ const ok = await confirm({
111
+ severity: 'warning',
112
+ title: 'Rotar secreto',
113
+ message: 'Se generará un secreto nuevo. Durante 24 horas cada entrega irá firmada con el secreto nuevo y con el anterior, para que alcances a actualizar tu receptor.',
114
+ confirmText: 'Rotar',
115
+ })
116
+ if (!ok) return
117
+ try {
118
+ const res = await wh.rotateSecret.mutateAsync(w.id)
119
+ if (detail.value?.id === w.id) detail.value = res.data
120
+ secret.value = {
121
+ value: res.secret, title: 'Nuevo secreto',
122
+ note: res.data?.previous_secret_expires_at ? `El secreto anterior se deja de usar ${relativeTime(res.data.previous_secret_expires_at)}.` : undefined,
123
+ }
124
+ } catch (e: any) {
125
+ toast.error(errorMessage(e, 'No se pudo rotar el secreto.'))
126
+ }
127
+ }
128
+
129
+ async function doDelete(w: Webhook) {
130
+ const ok = await confirm({
131
+ severity: 'danger',
132
+ title: 'Eliminar webhook',
133
+ message: `Se dejarán de enviar eventos a ${w.url}. Esta acción no se puede deshacer.`,
134
+ confirmText: 'Eliminar',
135
+ })
136
+ if (!ok) return
137
+ try {
138
+ await wh.remove.mutateAsync(w.id)
139
+ if (detail.value?.id === w.id) detail.value = null
140
+ toast.success('Webhook eliminado.')
141
+ } catch (e: any) {
142
+ toast.error(errorMessage(e, 'No se pudo eliminar el webhook.'))
143
+ }
144
+ }
145
+
146
+ async function doTest(w: Webhook) {
147
+ try {
148
+ await wh.test.mutateAsync(w.id)
149
+ toast.success('Evento de prueba encolado.')
150
+ if (detail.value?.id === w.id) setTimeout(reloadLogs, 1500)
151
+ } catch (e: any) {
152
+ toast.error(errorMessage(e, 'No se pudo enviar el evento de prueba.'))
153
+ }
154
+ }
155
+
156
+ // ── Detail + delivery log ───────────────────────────────────────────────────
157
+ const detail = ref<Webhook | null>(null)
158
+ const showDetail = computed({ get: () => detail.value !== null, set: (v) => { if (!v) detail.value = null } })
159
+ const logs = reactive({ items: [] as WebhookLog[], cursor: null as string | null, status: '', loading: false, loaded: false })
160
+ const openLog = ref<(WebhookLog & { payload?: any; request_headers?: any; response_body?: string | null }) | null>(null)
161
+
162
+ async function openDetail(w: Webhook) {
163
+ detail.value = w
164
+ openLog.value = null
165
+ await reloadLogs()
166
+ }
167
+
168
+ async function reloadLogs() {
169
+ Object.assign(logs, { items: [], cursor: null, loaded: false })
170
+ await loadMore()
171
+ }
172
+
173
+ async function loadMore() {
174
+ if (!detail.value || logs.loading) return
175
+ logs.loading = true
176
+ try {
177
+ const res = await wh.logs(detail.value.id, { cursor: logs.cursor, status: logs.status || undefined })
178
+ logs.items = appendPage(logs.items, res?.data ?? [])
179
+ logs.cursor = res?.meta?.next_cursor ?? null
180
+ } catch {
181
+ toast.error('No se pudo cargar el registro de entregas.')
182
+ } finally {
183
+ logs.loading = false
184
+ logs.loaded = true
185
+ }
186
+ }
187
+
188
+ async function toggleLog(l: WebhookLog) {
189
+ if (openLog.value?.id === l.id) { openLog.value = null; return }
190
+ try {
191
+ const res = await wh.log(detail.value!.id, l.id)
192
+ openLog.value = res?.data ?? null
193
+ } catch {
194
+ toast.error('No se pudo cargar la entrega.')
195
+ }
196
+ }
197
+
198
+ async function doResend(l: WebhookLog) {
199
+ try {
200
+ await wh.resend.mutateAsync({ id: detail.value!.id, logId: l.id })
201
+ toast.success('Reenvío encolado.')
202
+ setTimeout(reloadLogs, 1500)
203
+ } catch (e: any) {
204
+ toast.error(errorMessage(e, 'No se pudo reenviar la entrega.'))
205
+ }
206
+ }
207
+
208
+ 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'
209
+ const checkClass = 'size-4 rounded border-card-line text-primary focus:ring-primary/30'
210
+ </script>
211
+
212
+ <template>
213
+ <div class="space-y-4">
214
+ <div class="flex flex-wrap items-center gap-3">
215
+ <p class="flex-1 text-sm text-muted-foreground">
216
+ Los webhooks avisan a tus sistemas cuando ocurre algo (POST JSON firmado con <em>Standard Webhooks</em>). Reintentamos durante ~24 horas antes de desactivar.
217
+ </p>
218
+ <a v-if="developersUrl" :href="developersUrl" target="_blank" rel="noopener" class="inline-flex items-center gap-1 text-sm text-primary hover:underline">
219
+ <IconBook class="size-4" :stroke-width="1.75" /> Documentación de la API
220
+ </a>
221
+ <App.Button v-if="canManage" text="Nuevo webhook" severity="primary" size="sm" :icon="IconPlus" @click="openCreate" />
222
+ </div>
223
+
224
+ <div class="bg-card border border-card-line rounded-card overflow-hidden">
225
+ <div v-if="wh.list.isPending.value" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
226
+ <div v-else-if="wh.list.isError.value" class="p-8 text-center text-sm text-muted-foreground">
227
+ No se pudieron cargar los webhooks.
228
+ <button type="button" class="text-primary hover:underline" @click="wh.list.refetch()">Reintentar</button>
229
+ </div>
230
+ <div v-else-if="!hooks.length" class="p-8 text-center text-sm text-muted-foreground">
231
+ <IconWebhook class="size-6 mx-auto mb-2 text-muted-foreground" :stroke-width="1.5" />
232
+ Aún no hay webhooks.
233
+ </div>
234
+ <ul v-else class="divide-y divide-card-line">
235
+ <li v-for="w in hooks" :key="w.id" class="flex flex-wrap items-center gap-3 px-5 py-3">
236
+ <button type="button" class="flex-1 min-w-0 text-left" @click="openDetail(w)">
237
+ <p class="text-sm font-medium text-foreground flex items-center gap-2 min-w-0">
238
+ <span class="truncate font-mono">{{ w.url }}</span>
239
+ <App.Tag :text="webhookState(w).label" :severity="webhookState(w).severity" size="xs" />
240
+ </p>
241
+ <p class="text-xs text-muted-foreground truncate">
242
+ <template v-if="w.description">{{ w.description }} · </template>
243
+ {{ w.events.join(', ') }}
244
+ <template v-if="w.organization_id"> · Sede {{ orgLabel(w.organization_id) }}</template>
245
+ </p>
246
+ <p v-if="w.disabled_at && w.disabled_reason" class="text-xs text-destructive">{{ w.disabled_reason }}</p>
247
+ </button>
248
+ <div v-if="canManage" class="flex gap-2">
249
+ <App.Button text="Probar" size="xs" :icon="IconSend" :disabled="!w.active" @click="doTest(w)" />
250
+ <App.Button v-if="w.active" text="Pausar" size="xs" :icon="IconPlayerPause" @click="setActive(w, false)" />
251
+ <App.Button v-else text="Activar" size="xs" :icon="IconPlayerPlay" @click="setActive(w, true)" />
252
+ </div>
253
+ </li>
254
+ </ul>
255
+ </div>
256
+
257
+ <!-- Create / edit -->
258
+ <Modal v-model="showForm" :title="editing ? 'Editar webhook' : 'Nuevo webhook'" size="2xl" show-footer>
259
+ <form class="space-y-4" @submit.prevent="submitForm">
260
+ <label class="block space-y-1">
261
+ <span class="text-sm font-medium text-foreground">URL del receptor</span>
262
+ <input v-model="form.url" type="url" placeholder="https://tu-sistema.cl/webhooks/innertia" :class="inputClass" />
263
+ <span v-if="urlError" class="text-xs text-destructive">{{ urlError }}</span>
264
+ <span v-else class="text-xs text-muted-foreground">Debe ser https y públicamente accesible.</span>
265
+ </label>
266
+
267
+ <label class="block space-y-1">
268
+ <span class="text-sm font-medium text-foreground">Descripción</span>
269
+ <input v-model="form.description" type="text" maxlength="255" placeholder="Opcional" :class="inputClass" />
270
+ </label>
271
+
272
+ <label v-if="organizations.length" class="block space-y-1">
273
+ <span class="text-sm font-medium text-foreground">Sede</span>
274
+ <select v-model="form.organization_id" :class="inputClass">
275
+ <option value="">Todas las sedes</option>
276
+ <option v-for="o in organizations" :key="o.value" :value="o.value">{{ o.label }}</option>
277
+ </select>
278
+ </label>
279
+
280
+ <div class="space-y-2">
281
+ <span class="text-sm font-medium text-foreground">Eventos</span>
282
+ <div v-if="wh.events.isPending.value" class="text-sm text-muted-foreground">Cargando eventos…</div>
283
+ <div v-else-if="!eventGroups.length" class="text-sm text-muted-foreground">No hay eventos disponibles.</div>
284
+ <div v-else class="border border-card-line rounded-card divide-y divide-card-line">
285
+ <div v-for="g in eventGroups" :key="g.family" class="px-4 py-2">
286
+ <label class="flex items-center gap-2 py-1">
287
+ <input
288
+ type="checkbox" :class="checkClass"
289
+ :checked="familyState(form.events, g.family, catalog) === 'all'"
290
+ :indeterminate="familyState(form.events, g.family, catalog) === 'some'"
291
+ @change="form.events = toggleFamily(form.events, g.family, ($event.target as HTMLInputElement).checked)"
292
+ />
293
+ <code class="text-xs font-mono font-semibold text-foreground">{{ g.family }}.*</code>
294
+ <span class="text-xs text-muted-foreground">todos</span>
295
+ </label>
296
+ <label v-for="e in g.items" :key="e.key" class="flex items-start gap-2 py-1 pl-6">
297
+ <input
298
+ type="checkbox" :class="[checkClass, 'mt-0.5']"
299
+ :checked="isEventSelected(form.events, e.key)"
300
+ @change="form.events = toggleEvent(form.events, e.key, ($event.target as HTMLInputElement).checked, catalog)"
301
+ />
302
+ <span class="text-sm">
303
+ <code class="text-xs font-mono text-foreground">{{ e.key }}</code>
304
+ <span v-if="e.scope" class="ml-1 text-[11px] text-muted-foreground">(requiere {{ e.scope }})</span>
305
+ <span v-if="e.description" class="block text-xs text-muted-foreground">{{ e.description }}</span>
306
+ </span>
307
+ </label>
308
+ </div>
309
+ </div>
310
+ </div>
311
+
312
+ <div v-if="sensitiveScopes.length" class="space-y-2">
313
+ <span class="text-sm font-medium text-foreground">Datos sensibles</span>
314
+ <p class="text-xs text-muted-foreground">Sin estos permisos los eventos se envían con los datos sensibles omitidos o enmascarados.</p>
315
+ <div class="border border-card-line rounded-card px-4 py-2">
316
+ <template v-for="g in sensitiveScopes" :key="g.group">
317
+ <label v-for="s in g.items" :key="s.key" class="flex items-start gap-2 py-1">
318
+ <input
319
+ type="checkbox" :class="[checkClass, 'mt-0.5']"
320
+ :checked="form.scopes.includes(s.key)"
321
+ @change="form.scopes = toggleValue(form.scopes, s.key, ($event.target as HTMLInputElement).checked)"
322
+ />
323
+ <span class="text-sm">
324
+ <code class="text-xs font-mono text-foreground">{{ s.key }}</code>
325
+ <span v-if="s.description" class="block text-xs text-muted-foreground">{{ s.description }}</span>
326
+ </span>
327
+ </label>
328
+ </template>
329
+ </div>
330
+ </div>
331
+ </form>
332
+ <template #footer>
333
+ <div class="flex justify-end gap-2">
334
+ <App.Button text="Cancelar" size="sm" @click="showForm = false" />
335
+ <App.Button :text="editing ? 'Guardar' : 'Crear webhook'" severity="primary" size="sm" :disabled="!canSubmit" :loading="saving" @click="submitForm" />
336
+ </div>
337
+ </template>
338
+ </Modal>
339
+
340
+ <!-- Secret (once) -->
341
+ <Modal v-model="showSecret" :title="secret?.title ?? ''" size="lg" show-footer :backdrop-dismiss="false">
342
+ <div v-if="secret" class="space-y-3">
343
+ <div class="flex items-start gap-2 rounded-card border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100">
344
+ <IconAlertTriangle class="size-5 shrink-0 text-amber-500" :stroke-width="1.75" />
345
+ <span>Copia el secreto de firma ahora: <strong>no se volverá a mostrar</strong>.</span>
346
+ </div>
347
+ <div class="flex items-center gap-2 rounded-control border border-card-line bg-muted/30 px-3 py-2">
348
+ <code class="flex-1 break-all text-sm font-mono text-foreground">{{ secret.value }}</code>
349
+ <CopyButton :value="secret.value" />
350
+ </div>
351
+ <p v-if="secret.note" class="text-xs text-muted-foreground">{{ secret.note }}</p>
352
+ <p class="text-xs text-muted-foreground">
353
+ Verifica cada entrega con los headers <code class="font-mono">webhook-id</code>, <code class="font-mono">webhook-timestamp</code> y
354
+ <code class="font-mono">webhook-signature</code> (HMAC-SHA256 de <code class="font-mono">id.timestamp.body</code>).
355
+ </p>
356
+ </div>
357
+ <template #footer>
358
+ <div class="flex justify-end">
359
+ <App.Button text="Ya lo copié" severity="primary" size="sm" @click="secret = null" />
360
+ </div>
361
+ </template>
362
+ </Modal>
363
+
364
+ <!-- Detail -->
365
+ <Modal v-model="showDetail" title="Webhook" size="4xl" variant="drawer-right">
366
+ <div v-if="detail" class="space-y-5">
367
+ <div class="space-y-1">
368
+ <p class="font-mono text-sm text-foreground break-all">{{ detail.url }}</p>
369
+ <p v-if="detail.description" class="text-sm text-muted-foreground">{{ detail.description }}</p>
370
+ <App.Tag :text="webhookState(detail).label" :severity="webhookState(detail).severity" size="xs" />
371
+ </div>
372
+
373
+ <div v-if="detail.disabled_at" class="rounded-card border border-destructive/40 bg-destructive/5 p-3 text-sm text-foreground">
374
+ Desactivado {{ relativeTime(detail.disabled_at) }}<template v-if="detail.disabled_reason">: {{ detail.disabled_reason }}</template>.
375
+ Corrige el receptor y vuelve a activarlo.
376
+ </div>
377
+
378
+ <dl class="grid grid-cols-2 gap-3 text-sm">
379
+ <div class="col-span-2">
380
+ <dt class="text-xs text-muted-foreground mb-1">Eventos</dt>
381
+ <dd class="flex flex-wrap gap-1"><code v-for="e in detail.events" :key="e" class="text-xs font-mono rounded bg-muted px-1.5 py-0.5">{{ e }}</code></dd>
382
+ </div>
383
+ <div v-if="detail.organization_id"><dt class="text-xs text-muted-foreground">Sede</dt><dd>{{ orgLabel(detail.organization_id) }}</dd></div>
384
+ <div v-if="detail.scopes?.length"><dt class="text-xs text-muted-foreground">Datos sensibles</dt><dd class="font-mono text-xs">{{ detail.scopes.join(', ') }}</dd></div>
385
+ <div><dt class="text-xs text-muted-foreground">Secreto</dt><dd class="font-mono text-xs">{{ detail.secret_hint || '—' }}</dd></div>
386
+ <div v-if="detail.previous_secret_expires_at"><dt class="text-xs text-muted-foreground">Secreto anterior</dt><dd>Vigente hasta {{ formatDateTime(detail.previous_secret_expires_at) }}</dd></div>
387
+ <div><dt class="text-xs text-muted-foreground">Última entrega OK</dt><dd>{{ formatDateTime(detail.last_success_at) }}</dd></div>
388
+ <div><dt class="text-xs text-muted-foreground">Última falla</dt><dd>{{ formatDateTime(detail.last_failure_at) }}</dd></div>
389
+ </dl>
390
+
391
+ <p v-if="detail.legacy" class="text-xs text-muted-foreground">
392
+ Webhook antiguo: se entrega con el formato heredado. Rota el secreto para pasar al formato Standard Webhooks.
393
+ </p>
394
+
395
+ <div v-if="canManage" class="flex flex-wrap gap-2">
396
+ <App.Button text="Editar" size="xs" :icon="IconPencil" @click="openEdit(detail)" />
397
+ <App.Button text="Enviar evento de prueba" size="xs" :icon="IconSend" :disabled="!detail.active" :loading="wh.test.isPending.value" @click="doTest(detail)" />
398
+ <App.Button text="Rotar secreto" size="xs" :icon="IconRefresh" @click="doRotate(detail)" />
399
+ <App.Button v-if="detail.active" text="Pausar" size="xs" :icon="IconPlayerPause" @click="setActive(detail, false)" />
400
+ <App.Button v-else text="Activar" size="xs" :icon="IconPlayerPlay" @click="setActive(detail, true)" />
401
+ <App.Button text="Eliminar" size="xs" severity="danger" outline :icon="IconTrash" @click="doDelete(detail)" />
402
+ </div>
403
+
404
+ <div>
405
+ <div class="flex items-center gap-2 mb-2">
406
+ <p class="flex-1 text-sm font-semibold text-foreground">Entregas (30 días)</p>
407
+ <select v-model="logs.status" class="h-8 rounded-control border border-card-line bg-card text-xs px-2" @change="reloadLogs">
408
+ <option value="">Todas</option>
409
+ <option value="delivered">Entregadas</option>
410
+ <option value="retrying">Reintentando</option>
411
+ <option value="failed">Fallidas</option>
412
+ <option value="pending">Pendientes</option>
413
+ </select>
414
+ </div>
415
+ <div class="border border-card-line rounded-card overflow-hidden">
416
+ <div v-if="logs.loaded && !logs.items.length" class="p-6 text-center text-sm text-muted-foreground">Sin entregas registradas.</div>
417
+ <ul v-else class="divide-y divide-card-line">
418
+ <li v-for="l in logs.items" :key="l.id" class="text-sm">
419
+ <div class="flex flex-wrap items-center gap-2 px-3 py-2">
420
+ <button type="button" class="flex-1 min-w-0 text-left flex flex-wrap items-center gap-2" @click="toggleLog(l)">
421
+ <App.Tag :text="deliveryStatus(l.status).label" :severity="deliveryStatus(l.status).severity" size="xs" />
422
+ <code class="text-xs font-mono">{{ l.event_key }}</code>
423
+ <App.Tag v-if="l.is_test" text="Prueba" size="xs" />
424
+ <App.Tag v-if="l.response_status" :text="`HTTP ${l.response_status}`" :severity="httpSeverity(l.response_status)" size="xs" />
425
+ <span class="text-xs text-muted-foreground">{{ formatDateTime(l.created_at) }} · intento {{ l.attempts ?? 1 }}<template v-if="l.duration_ms != null"> · {{ l.duration_ms }} ms</template></span>
426
+ <span v-if="l.status === 'retrying' && l.next_retry_at" class="text-xs text-muted-foreground">· próximo {{ relativeTime(l.next_retry_at) }}</span>
427
+ </button>
428
+ <App.Button v-if="canManage && l.status !== 'pending'" text="Reenviar" size="xs" :icon="IconRefresh" @click="doResend(l)" />
429
+ </div>
430
+ <p v-if="l.error && openLog?.id !== l.id" class="px-3 pb-2 text-xs text-destructive break-all">{{ l.error }}</p>
431
+ <div v-if="openLog?.id === l.id" class="px-3 pb-3 space-y-2">
432
+ <p v-if="openLog.message_id" class="text-xs text-muted-foreground">webhook-id: <code class="font-mono">{{ openLog.message_id }}</code></p>
433
+ <p v-if="openLog.error" class="text-xs text-destructive break-all">{{ openLog.error }}</p>
434
+ <div v-if="openLog.request_headers">
435
+ <p class="text-xs font-medium text-muted-foreground">Headers enviados</p>
436
+ <pre class="text-xs bg-muted/40 rounded p-2 overflow-auto max-h-40">{{ prettyJson(openLog.request_headers) }}</pre>
437
+ </div>
438
+ <div>
439
+ <p class="text-xs font-medium text-muted-foreground">Payload</p>
440
+ <pre class="text-xs bg-muted/40 rounded p-2 overflow-auto max-h-64">{{ prettyJson(openLog.payload) }}</pre>
441
+ </div>
442
+ <div v-if="openLog.response_body">
443
+ <p class="text-xs font-medium text-muted-foreground">Respuesta (truncada a 64 KB)</p>
444
+ <pre class="text-xs bg-muted/40 rounded p-2 overflow-auto max-h-40">{{ prettyJson(openLog.response_body) }}</pre>
445
+ </div>
446
+ </div>
447
+ </li>
448
+ </ul>
449
+ </div>
450
+ <div class="mt-2 flex justify-center">
451
+ <App.Button v-if="logs.cursor" text="Cargar más" size="xs" :loading="logs.loading" @click="loadMore" />
452
+ <span v-else-if="logs.loading" class="text-xs text-muted-foreground">Cargando…</span>
453
+ </div>
454
+ </div>
455
+ </div>
456
+ </Modal>
457
+ </div>
458
+ </template>
@@ -0,0 +1,31 @@
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
+ // Integrations components (API keys, webhooks, API reference) compile (script + template) without errors.
7
+ const COMPONENTS = ['../ApiKeys.vue', '../Webhooks.vue', '../Developers.vue']
8
+
9
+ describe('SFC de integraciones 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
+
27
+ it('Developers pins the Scalar CDN build', () => {
28
+ const src = readFileSync(resolve(__dirname, '../Developers.vue'), 'utf8')
29
+ expect(src).toContain('https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.76.4/dist/browser/standalone.js')
30
+ })
31
+ })
@@ -0,0 +1,48 @@
1
+ import { computed, type Ref } from 'vue'
2
+ import type { AiModelPrice, PriceField, UsageSummary } from './internal/aiUsage'
3
+
4
+ const clean = (base: string | undefined, fallback: string) => String(base || fallback).replace(/^\/+|\/+$/g, '')
5
+
6
+ /**
7
+ * AI model prices (platform). innertia-laravel \Innertia\Ai\Routes::platform() + platformWrite():
8
+ * GET {base}/models/prices · PUT {base}/models/{id}/prices
9
+ */
10
+ export function useAiModelPrices(options: { base?: string } = {}) {
11
+ const base = clean(options.base, 'platform/ai')
12
+ const api = useApi()
13
+ const queryClient = useQueryClient()
14
+ const key = computed(() => ['ai', base, 'model-prices'])
15
+
16
+ const list = useQuery({
17
+ queryKey: key,
18
+ queryFn: () => api.get(`${base}/models/prices`),
19
+ select: (res: any) => (res?.data ?? []) as AiModelPrice[],
20
+ })
21
+
22
+ const update = useMutation({
23
+ mutationFn: ({ id, prices }: { id: string; prices: Record<PriceField, number | null> }) =>
24
+ api.put(`${base}/models/${id}/prices`, prices),
25
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: key.value }),
26
+ })
27
+
28
+ return { list, update }
29
+ }
30
+
31
+ /**
32
+ * Aggregated AI usage of a month.
33
+ * scope 'platform' → GET {base}/usage/report?month=&tenant_id= (with by_tenant)
34
+ * scope 'tenant' → GET {base}/usage/summary?month= (active space)
35
+ */
36
+ export function useAiUsage(month: Ref<string>, options: { base?: string; scope?: 'platform' | 'tenant'; tenantId?: Ref<string | null> } = {}) {
37
+ const scope = options.scope ?? 'platform'
38
+ const base = clean(options.base, scope === 'platform' ? 'platform/ai' : 'ai')
39
+ const api = useApi()
40
+ const path = scope === 'platform' ? 'usage/report' : 'usage/summary'
41
+
42
+ return useQuery({
43
+ queryKey: computed(() => ['ai', base, path, month.value, options.tenantId?.value ?? null]),
44
+ queryFn: () => api.get(`${base}/${path}`, {
45
+ params: { month: month.value, ...(options.tenantId?.value ? { tenant_id: options.tenantId.value } : {}) },
46
+ }) as Promise<UsageSummary>,
47
+ })
48
+ }
@@ -0,0 +1,50 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ featureLabel, formatUsd, compactNumber, unitsLabel, shiftMonth, monthLabel, monthKey, barHeights, budgetState, parsePrice,
4
+ } from '../aiUsage'
5
+
6
+ describe('aiUsage helpers', () => {
7
+ it('labels features, falling back to a readable key', () => {
8
+ expect(featureLabel('call_summary')).toBe('Resumen de llamadas')
9
+ expect(featureLabel('live_copilot')).toBe('Copiloto en vivo')
10
+ expect(featureLabel('custom_thing')).toBe('Custom thing')
11
+ expect(featureLabel(null)).toBe('Sin clasificar')
12
+ })
13
+
14
+ it('formats USD with adaptive precision', () => {
15
+ expect(formatUsd(0.0042)).toBe('US$ 0,0042')
16
+ expect(formatUsd(12.5)).toBe('US$ 12,50')
17
+ expect(formatUsd(null)).toBe('—')
18
+ })
19
+
20
+ it('compacts numbers and summarizes units', () => {
21
+ expect(compactNumber(1_250_000)).toBe('1,3 M')
22
+ expect(compactNumber(15_300)).toBe('15,3 mil')
23
+ expect(compactNumber(950)).toBe('950')
24
+ expect(unitsLabel({ input_tokens: 1000, output_tokens: 500, audio_seconds: 90, tts_chars: 0 })).toBe('1.500 tokens · 1,5 min de audio')
25
+ expect(unitsLabel({})).toBe('—')
26
+ })
27
+
28
+ it('navigates months', () => {
29
+ expect(shiftMonth('2026-01', -1)).toBe('2025-12')
30
+ expect(shiftMonth('2026-11', 2)).toBe('2027-01')
31
+ expect(monthLabel('2026-11')).toBe('Noviembre 2026')
32
+ expect(monthKey(new Date(2026, 2, 15))).toBe('2026-03')
33
+ })
34
+
35
+ it('scales bars and computes budget levels', () => {
36
+ expect(barHeights([0, 5, 10])).toEqual([0, 50, 100])
37
+ expect(barHeights([0, 0])).toEqual([0, 0])
38
+ expect(budgetState(79, 100)).toEqual({ percent: 79, level: 'ok' })
39
+ expect(budgetState(80, 100)?.level).toBe('warning')
40
+ expect(budgetState(130, 100)?.level).toBe('over')
41
+ expect(budgetState(10, null)).toBeNull()
42
+ })
43
+
44
+ it('parses price inputs', () => {
45
+ expect(parsePrice('')).toBeNull()
46
+ expect(parsePrice('1,5')).toBe(1.5)
47
+ expect(parsePrice('-1')).toBeUndefined()
48
+ expect(parsePrice('abc')).toBeUndefined()
49
+ })
50
+ })