@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,136 @@
1
+ import { computed } from 'vue'
2
+ import type { ApiKey, ApiScope, Webhook, WebhookEvent, WebhookLog } from './internal/integrations'
3
+
4
+ // Only the composables are exported: ./internal helpers are not auto-imported globally
5
+ // (avoids name clashes in products).
6
+
7
+ const clean = (base?: string) => String(base || 'integrations').replace(/^\/+|\/+$/g, '')
8
+
9
+ export interface CursorPage<T> { data: T[]; meta?: { next_cursor?: string | null; limit?: number } }
10
+
11
+ /**
12
+ * API keys of the active space (innertia-laravel \Innertia\PublicApi\Routes::manage()):
13
+ * GET api-keys · GET api-keys/scopes · POST api-keys → {data, secret} (shown once)
14
+ * POST api-keys/{id}/rotate → {data, secret, previous} · DELETE api-keys/{id}
15
+ * GET api-keys/{id}/requests?cursor&limit → {data, meta.next_cursor}
16
+ *
17
+ * `base`: API prefix where the product mounted the routes (default 'integrations').
18
+ */
19
+ export function useApiKeys(options: { base?: string } = {}) {
20
+ const base = clean(options.base)
21
+ const api = useApi()
22
+ const queryClient = useQueryClient()
23
+ const listKey = computed(() => ['integrations', base, 'api-keys'])
24
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: listKey.value })
25
+
26
+ const list = useQuery({
27
+ queryKey: listKey,
28
+ queryFn: () => api.get(`${base}/api-keys`),
29
+ select: (res: any) => (res?.data ?? []) as ApiKey[],
30
+ })
31
+
32
+ const scopes = useQuery({
33
+ queryKey: computed(() => ['integrations', base, 'api-key-scopes']),
34
+ queryFn: () => api.get(`${base}/api-keys/scopes`),
35
+ select: (res: any) => (res?.data ?? []) as ApiScope[],
36
+ staleTime: 5 * 60_000,
37
+ })
38
+
39
+ const create = useMutation({
40
+ mutationFn: (body: { name: string; scopes: string[]; organization_id?: string | number | null; expires_at?: string | null }) =>
41
+ api.post(`${base}/api-keys`, body) as Promise<{ data: ApiKey; secret: string }>,
42
+ onSuccess: invalidate,
43
+ })
44
+
45
+ const rotate = useMutation({
46
+ mutationFn: (id: string) =>
47
+ api.post(`${base}/api-keys/${id}/rotate`, {}) as Promise<{ data: ApiKey; secret: string; previous?: { id: string; expires_at: string | null } }>,
48
+ onSuccess: invalidate,
49
+ })
50
+
51
+ const revoke = useMutation({
52
+ mutationFn: (id: string) => api.delete(`${base}/api-keys/${id}`) as Promise<{ data: ApiKey }>,
53
+ onSuccess: invalidate,
54
+ })
55
+
56
+ /** Request log page of a key (cursor pagination). */
57
+ function requests(id: string, cursor?: string | null, limit = 25): Promise<CursorPage<any>> {
58
+ return api.get(`${base}/api-keys/${id}/requests`, { params: { limit, ...(cursor ? { cursor } : {}) } })
59
+ }
60
+
61
+ return { list, scopes, create, rotate, revoke, requests }
62
+ }
63
+
64
+ /**
65
+ * Outbound webhooks of the active space (innertia-laravel \Innertia\PublicApi\Routes::manage()):
66
+ * GET webhooks · GET webhooks/events · POST webhooks → {data, secret} · GET|PATCH|DELETE webhooks/{id}
67
+ * POST webhooks/{id}/rotate-secret → {data, secret} · POST webhooks/{id}/test
68
+ * GET webhooks/{id}/logs?cursor&limit&status · GET webhooks/{id}/logs/{log} · POST …/logs/{log}/resend
69
+ */
70
+ export function useWebhooks(options: { base?: string } = {}) {
71
+ const base = clean(options.base)
72
+ const api = useApi()
73
+ const queryClient = useQueryClient()
74
+ const listKey = computed(() => ['integrations', base, 'webhooks'])
75
+ const invalidate = () => queryClient.invalidateQueries({ queryKey: listKey.value })
76
+
77
+ const list = useQuery({
78
+ queryKey: listKey,
79
+ queryFn: () => api.get(`${base}/webhooks`),
80
+ select: (res: any) => (res?.data ?? []) as Webhook[],
81
+ })
82
+
83
+ const events = useQuery({
84
+ queryKey: computed(() => ['integrations', base, 'webhook-events']),
85
+ queryFn: () => api.get(`${base}/webhooks/events`),
86
+ select: (res: any) => (res?.data ?? []) as WebhookEvent[],
87
+ staleTime: 5 * 60_000,
88
+ })
89
+
90
+ type WebhookInput = { url?: string; events?: string[]; description?: string | null; organization_id?: string | number | null; scopes?: string[]; active?: boolean }
91
+
92
+ const create = useMutation({
93
+ mutationFn: (body: WebhookInput) => api.post(`${base}/webhooks`, body) as Promise<{ data: Webhook; secret: string }>,
94
+ onSuccess: invalidate,
95
+ })
96
+
97
+ const update = useMutation({
98
+ mutationFn: ({ id, ...body }: WebhookInput & { id: string | number }) =>
99
+ api.patch(`${base}/webhooks/${id}`, body) as Promise<{ data: Webhook }>,
100
+ onSuccess: invalidate,
101
+ })
102
+
103
+ const remove = useMutation({
104
+ mutationFn: (id: string | number) => api.delete(`${base}/webhooks/${id}`),
105
+ onSuccess: invalidate,
106
+ })
107
+
108
+ const rotateSecret = useMutation({
109
+ mutationFn: (id: string | number) => api.post(`${base}/webhooks/${id}/rotate-secret`, {}) as Promise<{ data: Webhook; secret: string }>,
110
+ onSuccess: invalidate,
111
+ })
112
+
113
+ const test = useMutation({
114
+ mutationFn: (id: string | number) => api.post(`${base}/webhooks/${id}/test`, {}) as Promise<{ data: WebhookLog }>,
115
+ })
116
+
117
+ const resend = useMutation({
118
+ mutationFn: ({ id, logId }: { id: string | number; logId: string | number }) =>
119
+ api.post(`${base}/webhooks/${id}/logs/${logId}/resend`, {}) as Promise<{ data: WebhookLog }>,
120
+ })
121
+
122
+ /** Delivery log page (cursor pagination, optional status filter). */
123
+ function logs(id: string | number, params: { cursor?: string | null; status?: string; limit?: number } = {}): Promise<CursorPage<WebhookLog>> {
124
+ const q: Record<string, any> = { limit: params.limit ?? 25 }
125
+ if (params.cursor) q.cursor = params.cursor
126
+ if (params.status) q.status = params.status
127
+ return api.get(`${base}/webhooks/${id}/logs`, { params: q })
128
+ }
129
+
130
+ /** One delivery with payload, request headers and (truncated) response body. */
131
+ function log(id: string | number, logId: string | number): Promise<{ data: WebhookLog }> {
132
+ return api.get(`${base}/webhooks/${id}/logs/${logId}`)
133
+ }
134
+
135
+ return { list, events, create, update, remove, rotateSecret, test, resend, logs, log }
136
+ }
@@ -0,0 +1,112 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ apiKeyStatus, deliveryStatus, webhookState, httpSeverity, scopeResource, groupScopes, toggleValue,
4
+ eventMatches, isEventSelected, groupEvents, toggleFamily, toggleEvent, familyState,
5
+ validateWebhookUrl, relativeTime, expiryLabel, expiryFromPreset, appendPage, prettyJson,
6
+ } from '../integrations'
7
+
8
+ const catalog = [
9
+ { key: 'call.ringing' }, { key: 'call.answered' }, { key: 'call.ended' },
10
+ { key: 'person.created' }, { key: 'person.updated' },
11
+ ]
12
+
13
+ describe('status labels', () => {
14
+ it('maps key and delivery statuses with fallback', () => {
15
+ expect(apiKeyStatus('active')).toEqual({ label: 'Activa', severity: 'success' })
16
+ expect(apiKeyStatus('revoked').severity).toBe('danger')
17
+ expect(apiKeyStatus('weird').label).toBe('weird')
18
+ expect(deliveryStatus('retrying').label).toBe('Reintentando')
19
+ expect(deliveryStatus(null).label).toBe('—')
20
+ })
21
+
22
+ it('derives the webhook state', () => {
23
+ expect(webhookState({ active: false, disabled_at: '2026-11-19T00:00:00Z' }).label).toBe('Desactivado por fallas')
24
+ expect(webhookState({ active: false }).label).toBe('Pausado')
25
+ expect(webhookState({ active: true, failing_since: 'x' }).severity).toBe('warning')
26
+ expect(webhookState({ active: true }).label).toBe('Activo')
27
+ })
28
+
29
+ it('colors http statuses', () => {
30
+ expect(httpSeverity(200)).toBe('success')
31
+ expect(httpSeverity(404)).toBe('warning')
32
+ expect(httpSeverity(503)).toBe('danger')
33
+ expect(httpSeverity(null)).toBe('secondary')
34
+ })
35
+ })
36
+
37
+ describe('scopes', () => {
38
+ it('groups by explicit group or resource', () => {
39
+ expect(scopeResource('calls:read')).toBe('calls')
40
+ const g = groupScopes([{ key: 'calls:read' }, { key: 'people:read' }, { key: 'calls:write' }, { key: 'people:pii', group: 'people' }])
41
+ expect(g.map(x => x.group)).toEqual(['calls', 'people'])
42
+ expect(g[0].items.map(i => i.key)).toEqual(['calls:read', 'calls:write'])
43
+ expect(g[1].items).toHaveLength(2)
44
+ })
45
+
46
+ it('toggles values without duplicates', () => {
47
+ expect(toggleValue(['a'], 'a', true)).toEqual(['a'])
48
+ expect(toggleValue(['a', 'b'], 'a', false)).toEqual(['b'])
49
+ })
50
+ })
51
+
52
+ describe('event selection with wildcards', () => {
53
+ it('matches patterns', () => {
54
+ expect(eventMatches('*', 'call.ended')).toBe(true)
55
+ expect(eventMatches('call.*', 'call.ended')).toBe(true)
56
+ expect(eventMatches('call.*', 'callback.x')).toBe(false)
57
+ expect(isEventSelected(['person.created'], 'person.updated')).toBe(false)
58
+ })
59
+
60
+ it('groups events by family', () => {
61
+ expect(groupEvents(catalog).map(g => [g.family, g.items.length])).toEqual([['call', 3], ['person', 2]])
62
+ })
63
+
64
+ it('toggles a family as wildcard', () => {
65
+ expect(toggleFamily(['call.ended', 'person.created'], 'call', true)).toEqual(['person.created', 'call.*'])
66
+ expect(toggleFamily(['call.*', 'person.created'], 'call', false)).toEqual(['person.created'])
67
+ })
68
+
69
+ it('expands a wildcard when one event is turned off', () => {
70
+ expect(toggleEvent(['call.*'], 'call.ringing', false, catalog)).toEqual(['call.answered', 'call.ended'])
71
+ expect(toggleEvent(['*'], 'person.updated', false, catalog).sort()).toEqual(['call.*', 'person.created'].sort())
72
+ expect(toggleEvent(['call.*'], 'call.ended', true, catalog)).toEqual(['call.*'])
73
+ expect(toggleEvent([], 'call.ended', true, catalog)).toEqual(['call.ended'])
74
+ })
75
+
76
+ it('reports family state', () => {
77
+ expect(familyState(['call.*'], 'call', catalog)).toBe('all')
78
+ expect(familyState(['call.ended'], 'call', catalog)).toBe('some')
79
+ expect(familyState(['person.created', 'person.updated'], 'person', catalog)).toBe('all')
80
+ expect(familyState([], 'person', catalog)).toBe('none')
81
+ })
82
+ })
83
+
84
+ describe('validation and dates', () => {
85
+ it('validates https webhook URLs', () => {
86
+ expect(validateWebhookUrl('')).toMatch(/Ingresa/)
87
+ expect(validateWebhookUrl('http://x.cl/hook')).toMatch(/https/)
88
+ expect(validateWebhookUrl('nope')).toMatch(/no es válida/)
89
+ expect(validateWebhookUrl('https://u:p@x.cl')).toMatch(/credenciales/)
90
+ expect(validateWebhookUrl('https://hooks.example.com/in')).toBeNull()
91
+ })
92
+
93
+ it('formats relative times and expiry', () => {
94
+ const now = new Date('2026-11-19T12:00:00Z')
95
+ expect(relativeTime('2026-11-19T11:55:00Z', now)).toBe('hace 5 min')
96
+ expect(relativeTime('2026-11-22T12:00:00Z', now)).toBe('en 3 días')
97
+ expect(relativeTime(null, now)).toBe('—')
98
+ expect(expiryLabel(null, now)).toBe('Sin vencimiento')
99
+ expect(expiryLabel('2026-11-20T12:00:00Z', now)).toBe('Vence en 1 día')
100
+ expect(expiryLabel('2026-11-18T12:00:00Z', now)).toBe('Venció hace 1 día')
101
+ expect(expiryFromPreset('30', now)).toBe('2026-12-19T12:00:00.000Z')
102
+ expect(expiryFromPreset('', now)).toBeNull()
103
+ })
104
+
105
+ it('appends cursor pages without duplicates and pretty-prints json', () => {
106
+ expect(appendPage([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }]).map(i => i.id)).toEqual([1, 2, 3])
107
+ expect(prettyJson('{"a":1}')).toBe('{\n "a": 1\n}')
108
+ expect(prettyJson({ a: 1 })).toBe('{\n "a": 1\n}')
109
+ expect(prettyJson('plain')).toBe('plain')
110
+ expect(prettyJson(null)).toBe('')
111
+ })
112
+ })
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Pure helpers for the Integrations screens (API keys + webhooks), no Nuxt/Vue: testable in node.
3
+ * Consumed by useApiKeys / useWebhooks and <Integrations.ApiKeys> / <Integrations.Webhooks>.
4
+ * Backend: innertia-laravel \Innertia\PublicApi\Routes::manage().
5
+ */
6
+
7
+ export type Severity = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info'
8
+
9
+ export type ApiKeyStatus = 'active' | 'expiring' | 'expired' | 'revoked'
10
+ export type DeliveryStatus = 'pending' | 'delivered' | 'failed' | 'retrying'
11
+
12
+ export interface ApiKey {
13
+ id: string
14
+ name: string
15
+ prefix: string
16
+ hint?: string | null
17
+ scopes: string[]
18
+ organization_id?: string | null
19
+ expires_at?: string | null
20
+ last_used_at?: string | null
21
+ last_used_ip?: string | null
22
+ created_by?: string | null
23
+ revoked_at?: string | null
24
+ rotated_to_id?: string | null
25
+ status: ApiKeyStatus
26
+ created_at?: string | null
27
+ }
28
+
29
+ export interface ApiScope { key: string; description?: string | null; group?: string | null }
30
+
31
+ export interface Webhook {
32
+ id: string | number
33
+ url: string
34
+ description?: string | null
35
+ events: string[]
36
+ active: boolean
37
+ organization_id?: string | null
38
+ scopes?: string[]
39
+ secret_hint?: string | null
40
+ previous_secret_expires_at?: string | null
41
+ disabled_at?: string | null
42
+ disabled_reason?: string | null
43
+ failing_since?: string | null
44
+ last_success_at?: string | null
45
+ last_failure_at?: string | null
46
+ legacy?: boolean
47
+ created_at?: string | null
48
+ }
49
+
50
+ export interface WebhookEvent { key: string; description?: string | null; version?: string | null; scope?: string | null; example?: any }
51
+
52
+ export interface WebhookLog {
53
+ id: string | number
54
+ message_id?: string | null
55
+ event_key: string
56
+ status: DeliveryStatus
57
+ attempts?: number
58
+ response_status?: number | null
59
+ duration_ms?: number | null
60
+ error?: string | null
61
+ is_test?: boolean
62
+ created_at?: string | null
63
+ delivered_at?: string | null
64
+ failed_at?: string | null
65
+ next_retry_at?: string | null
66
+ [key: string]: any
67
+ }
68
+
69
+ // ── Status labels ────────────────────────────────────────────────────────────
70
+
71
+ export const API_KEY_STATUS: Record<ApiKeyStatus, { label: string; severity: Severity }> = {
72
+ active: { label: 'Activa', severity: 'success' },
73
+ expiring: { label: 'Por vencer', severity: 'warning' },
74
+ expired: { label: 'Vencida', severity: 'secondary' },
75
+ revoked: { label: 'Revocada', severity: 'danger' },
76
+ }
77
+
78
+ export const DELIVERY_STATUS: Record<DeliveryStatus, { label: string; severity: Severity }> = {
79
+ pending: { label: 'Pendiente', severity: 'info' },
80
+ delivered: { label: 'Entregado', severity: 'success' },
81
+ retrying: { label: 'Reintentando', severity: 'warning' },
82
+ failed: { label: 'Fallido', severity: 'danger' },
83
+ }
84
+
85
+ export function apiKeyStatus(status: string | null | undefined) {
86
+ return API_KEY_STATUS[status as ApiKeyStatus] ?? { label: status || '—', severity: 'secondary' as Severity }
87
+ }
88
+
89
+ export function deliveryStatus(status: string | null | undefined) {
90
+ return DELIVERY_STATUS[status as DeliveryStatus] ?? { label: status || '—', severity: 'secondary' as Severity }
91
+ }
92
+
93
+ /** Webhook state: disabled by health check, paused by a user, or active. */
94
+ export function webhookState(w: Pick<Webhook, 'active' | 'disabled_at' | 'failing_since'>): { label: string; severity: Severity } {
95
+ if (w.disabled_at) return { label: 'Desactivado por fallas', severity: 'danger' }
96
+ if (!w.active) return { label: 'Pausado', severity: 'secondary' }
97
+ if (w.failing_since) return { label: 'Con fallas', severity: 'warning' }
98
+ return { label: 'Activo', severity: 'success' }
99
+ }
100
+
101
+ /** Severity for an HTTP status code shown in logs. */
102
+ export function httpSeverity(status: number | null | undefined): Severity {
103
+ if (!status) return 'secondary'
104
+ if (status < 300) return 'success'
105
+ if (status < 400) return 'info'
106
+ if (status === 429 || status < 500) return 'warning'
107
+ return 'danger'
108
+ }
109
+
110
+ // ── Scopes ───────────────────────────────────────────────────────────────────
111
+
112
+ /** Resource of a scope: `calls:read` → `calls`, `people:pii` → `people`. */
113
+ export function scopeResource(scope: string): string {
114
+ const i = scope.indexOf(':')
115
+ return i === -1 ? scope : scope.slice(0, i)
116
+ }
117
+
118
+ /** Groups scopes by `group` (or the resource of the key), keeping the server order. */
119
+ export function groupScopes(scopes: ApiScope[]): { group: string; items: ApiScope[] }[] {
120
+ const groups: { group: string; items: ApiScope[] }[] = []
121
+ for (const s of scopes) {
122
+ const g = s.group || scopeResource(s.key)
123
+ let entry = groups.find(x => x.group === g)
124
+ if (!entry) groups.push(entry = { group: g, items: [] })
125
+ entry.items.push(s)
126
+ }
127
+ return groups
128
+ }
129
+
130
+ export function toggleValue(list: string[], value: string, on: boolean): string[] {
131
+ const set = new Set(list)
132
+ on ? set.add(value) : set.delete(value)
133
+ return [...set]
134
+ }
135
+
136
+ // ── Events (wildcards) ───────────────────────────────────────────────────────
137
+
138
+ /** Family of an event key: `call.ended` → `call`. */
139
+ export function eventFamily(key: string): string {
140
+ const i = key.indexOf('.')
141
+ return i === -1 ? key : key.slice(0, i)
142
+ }
143
+
144
+ /** Does a subscription pattern (`*`, `call.*`, `call.ended`) match the event key? */
145
+ export function eventMatches(pattern: string, key: string): boolean {
146
+ if (pattern === '*') return true
147
+ if (pattern.endsWith('.*')) return key.startsWith(pattern.slice(0, -1))
148
+ return pattern === key
149
+ }
150
+
151
+ /** Is the event covered by the selection (directly or by a wildcard)? */
152
+ export function isEventSelected(selection: string[], key: string): boolean {
153
+ return selection.some(p => eventMatches(p, key))
154
+ }
155
+
156
+ export function groupEvents(events: WebhookEvent[]): { family: string; items: WebhookEvent[] }[] {
157
+ const groups: { family: string; items: WebhookEvent[] }[] = []
158
+ for (const e of events) {
159
+ const f = eventFamily(e.key)
160
+ let entry = groups.find(x => x.family === f)
161
+ if (!entry) groups.push(entry = { family: f, items: [] })
162
+ entry.items.push(e)
163
+ }
164
+ return groups
165
+ }
166
+
167
+ /**
168
+ * Toggles a whole family as `family.*`: on → replaces its individual events with the wildcard;
169
+ * off → removes the wildcard and every individual event of the family.
170
+ */
171
+ export function toggleFamily(selection: string[], family: string, on: boolean): string[] {
172
+ const rest = selection.filter(p => p !== `${family}.*` && eventFamily(p) !== family)
173
+ return on ? [...rest, `${family}.*`] : rest
174
+ }
175
+
176
+ /**
177
+ * Toggles one event. Turning one off while its family wildcard (or `*`) is selected expands the
178
+ * wildcard into the remaining events of the catalog.
179
+ */
180
+ export function toggleEvent(selection: string[], key: string, on: boolean, catalog: WebhookEvent[]): string[] {
181
+ if (on) return isEventSelected(selection, key) ? selection : [...selection, key]
182
+
183
+ const family = eventFamily(key)
184
+ let next = selection
185
+ if (next.includes('*')) {
186
+ next = [...next.filter(p => p !== '*'), ...[...new Set(catalog.map(e => eventFamily(e.key)))].map(f => `${f}.*`)]
187
+ }
188
+ if (next.includes(`${family}.*`)) {
189
+ const siblings = catalog.map(e => e.key).filter(k => eventFamily(k) === family && k !== key)
190
+ next = [...next.filter(p => p !== `${family}.*`), ...siblings]
191
+ }
192
+ return next.filter(p => p !== key)
193
+ }
194
+
195
+ export function familyState(selection: string[], family: string, catalog: WebhookEvent[]): 'all' | 'some' | 'none' {
196
+ if (selection.includes('*') || selection.includes(`${family}.*`)) return 'all'
197
+ const keys = catalog.map(e => e.key).filter(k => eventFamily(k) === family)
198
+ const n = keys.filter(k => selection.includes(k)).length
199
+ return n === 0 ? 'none' : n === keys.length ? 'all' : 'some'
200
+ }
201
+
202
+ // ── Validation ───────────────────────────────────────────────────────────────
203
+
204
+ /** Webhook URL: absolute https with a host (the server also blocks private addresses). */
205
+ export function validateWebhookUrl(url: string): string | null {
206
+ const v = (url || '').trim()
207
+ if (!v) return 'Ingresa la URL del receptor.'
208
+ let parsed: URL
209
+ try { parsed = new URL(v) } catch { return 'La URL no es válida.' }
210
+ if (parsed.protocol !== 'https:') return 'La URL debe usar https.'
211
+ if (!parsed.hostname) return 'La URL no es válida.'
212
+ if (parsed.username || parsed.password) return 'La URL no puede incluir credenciales.'
213
+ return null
214
+ }
215
+
216
+ // ── Dates ────────────────────────────────────────────────────────────────────
217
+
218
+ /** Relative Spanish label ("hace 5 min", "en 3 días"). */
219
+ export function relativeTime(iso: string | null | undefined, now: Date = new Date()): string {
220
+ if (!iso) return '—'
221
+ const d = new Date(iso)
222
+ if (isNaN(d.getTime())) return '—'
223
+ const diff = Math.round((d.getTime() - now.getTime()) / 1000)
224
+ const abs = Math.abs(diff)
225
+ const fmt = (n: number, unit: string) => (diff < 0 ? `hace ${n} ${unit}` : `en ${n} ${unit}`)
226
+ if (abs < 45) return diff < 0 ? 'recién' : 'en unos segundos'
227
+ if (abs < 3600) return fmt(Math.round(abs / 60), 'min')
228
+ if (abs < 86400) { const h = Math.round(abs / 3600); return fmt(h, h === 1 ? 'hora' : 'horas') }
229
+ const days = Math.round(abs / 86400)
230
+ if (days < 30) return fmt(days, days === 1 ? 'día' : 'días')
231
+ return d.toLocaleDateString('es-CL', { day: 'numeric', month: 'short', year: 'numeric' })
232
+ }
233
+
234
+ /** Expiry label for an API key. */
235
+ export function expiryLabel(expiresAt: string | null | undefined, now: Date = new Date()): string {
236
+ if (!expiresAt) return 'Sin vencimiento'
237
+ const d = new Date(expiresAt)
238
+ if (isNaN(d.getTime())) return 'Sin vencimiento'
239
+ return d.getTime() <= now.getTime() ? `Venció ${relativeTime(expiresAt, now)}` : `Vence ${relativeTime(expiresAt, now)}`
240
+ }
241
+
242
+ export function formatDateTime(iso: string | null | undefined): string {
243
+ if (!iso) return '—'
244
+ const d = new Date(iso)
245
+ if (isNaN(d.getTime())) return '—'
246
+ return d.toLocaleString('es-CL', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })
247
+ }
248
+
249
+ /** Expiry presets for the create form → ISO date (null = never). */
250
+ export const EXPIRY_PRESETS = [
251
+ { value: '', label: 'Sin vencimiento' },
252
+ { value: '30', label: '30 días' },
253
+ { value: '90', label: '90 días' },
254
+ { value: '365', label: '1 año' },
255
+ ]
256
+
257
+ export function expiryFromPreset(days: string, now: Date = new Date()): string | null {
258
+ const n = Number(days)
259
+ if (!days || !Number.isFinite(n) || n <= 0) return null
260
+ return new Date(now.getTime() + n * 86400000).toISOString()
261
+ }
262
+
263
+ /** Appends a cursor page to the accumulated list (dedup by id). */
264
+ export function appendPage<T extends { id: string | number }>(items: T[], page: T[]): T[] {
265
+ const seen = new Set(items.map(i => String(i.id)))
266
+ return [...items, ...page.filter(i => !seen.has(String(i.id)))]
267
+ }
268
+
269
+ /** Pretty JSON for payload/headers previews. */
270
+ export function prettyJson(value: unknown): string {
271
+ if (value === null || value === undefined || value === '') return ''
272
+ if (typeof value === 'string') {
273
+ try { return JSON.stringify(JSON.parse(value), null, 2) } catch { return value }
274
+ }
275
+ try { return JSON.stringify(value, null, 2) } catch { return String(value) }
276
+ }
@@ -0,0 +1,38 @@
1
+ # Consumo de IA — componentes
2
+
3
+ Front del costeo de IA de `Innertia\Ai` (innertia-laravel): precios por modelo en USD y consumo
4
+ agregado por función, día y espacio. Cada uso se valoriza al registrarse con el precio vigente del
5
+ modelo (no es retroactivo); los usos de modelos sin precio se cuentan como "sin precio".
6
+
7
+ ## 1. Backend que hay que montar (en el producto)
8
+
9
+ ```php
10
+ // Grupo platform (prefijo 'platform')
11
+ \Innertia\Ai\Routes::platform(); // GET ai/models/prices, GET ai/usage/report
12
+ Route::middleware('platform.owner')->group(fn () => \Innertia\Ai\Routes::platformWrite()); // PUT ai/models/{id}/prices
13
+
14
+ // Grupo backoffice (espacio activo)
15
+ \Innertia\Ai\Routes::tenant(); // GET ai/usage/summary
16
+ ```
17
+
18
+ ## 2. Componentes
19
+
20
+ | Dónde | Componente | Props |
21
+ |---|---|---|
22
+ | `/platform/ai` (pestaña Precios) | `<Ai.ModelPrices :can-edit="isOwner" />` | `endpoint` (default `platform/ai`), `canEdit` |
23
+ | `/platform/ai` (pestaña Consumo) | `<Ai.UsageReport />` | `endpoint`, `tenantId` (filtra un espacio) |
24
+ | Backoffice › Sistema › IA › Consumo | `<Ai.UsageSummary :budget="presupuestoUsd" />` | `endpoint` (default `ai`), `budget` (USD/mes, opcional) |
25
+
26
+ - **ModelPrices**: precios editables en línea: entrada y salida por 1M de tokens, audio por minuto
27
+ y voz (TTS) por 1M de caracteres. Vacío = sin precio.
28
+ - **UsageReport / UsageSummary**: selector de mes, costo estimado, usos y unidades, barras por día,
29
+ consumo por función (resumen de llamadas, transcripción, copiloto en vivo, asistente, TTS, agente de
30
+ voz, importación de PDF…), días de mayor consumo, por espacio (solo platform) y exportación CSV.
31
+ Con `budget`, aviso al 80 % y al 100 % del presupuesto mensual.
32
+
33
+ ## 3. Composables
34
+
35
+ - `useAiModelPrices({ base })` → `list`, `update`.
36
+ - `useAiUsage(monthRef, { base, scope: 'platform' | 'tenant', tenantId })` → query del resumen.
37
+ - Helpers puros (etiquetas de funciones, formato USD, navegación de meses, presupuesto) en
38
+ `composables/useAiUsage/internal/aiUsage.ts`.
@@ -0,0 +1,75 @@
1
+ # Facturación (Billing) — componentes
2
+
3
+ Front de `Innertia\Billing` (innertia-laravel): planes, suscripción por espacio, consumo medido,
4
+ cierre mensual, facturas (por espacio o consolidadas por cliente), pagos, mora y suspensión.
5
+ La lógica vive en el backend; estos componentes solo muestran y llaman a sus endpoints.
6
+
7
+ Montos: enteros en pesos (CLP sin decimales). Fechas de período: fechas locales de Chile
8
+ (`YYYY-MM-DD`, ambos extremos incluidos).
9
+
10
+ ## 1. Backend que hay que montar (en el producto)
11
+
12
+ ```php
13
+ // Grupo platform (prefijo 'platform')
14
+ \Innertia\Billing\Routes::platform(); // lectura (owner y staff)
15
+ Route::middleware('platform.owner')->group(fn () => \Innertia\Billing\Routes::platformWrite());
16
+
17
+ // Grupo backoffice (espacio activo), solo lectura
18
+ Route::middleware('permission:billing.view')->group(fn () => \Innertia\Billing\Routes::backoffice());
19
+
20
+ // Escrituras del backoffice en solo lectura cuando el espacio está suspendido
21
+ Route::middleware('billing.enforce')->group(/* rutas del backoffice */);
22
+ ```
23
+
24
+ Activar el feature en el backend: ver `docs/billing.md` de innertia-laravel.
25
+
26
+ ## 2. Platform
27
+
28
+ | Página sugerida | Componente | Props |
29
+ |---|---|---|
30
+ | `/platform/billing` (resumen) | `<Billing.ClientTotals @select-space="…" @select-client="…" />` | `endpoint` (default `platform/billing`) |
31
+ | `/platform/billing/invoices` | `<Billing.Invoices :clients="opciones" />` | `clientId`, `spaceKey`, `clients`, `canEdit` |
32
+ | `/platform/billing/plans` | `<Billing.Plans :can-edit="isOwner" />` | `canEdit` |
33
+ | `/platform/billing/settings` | `<Billing.Settings />` (solo owner) | `canRun` |
34
+ | Detalle del espacio (pestaña Suscripción) | `<Billing.SpaceSubscription :space-key="key" :can-edit="isOwner" />` | `spaceKey` (obligatoria) |
35
+ | Detalle del cliente (pestaña Facturas) | `<Billing.Invoices :client-id="client.id" />` | |
36
+
37
+ - **Invoices**: filtros por estado y cliente, detalle con los cobros por espacio y sus líneas, bitácora,
38
+ **Emitir** (folio SII opcional, envío por correo con el PDF), **Reenviar**, **PDF** y **Registrar pago**
39
+ (transferencia; el excedente queda como saldo a favor del cliente).
40
+ - **SpaceSubscription**: iniciar suscripción (plan, modo de pago `invoice`/`automatic`, inicio, días de
41
+ prueba, precio base y por usuario negociados), editar (el cambio de plan rige desde el próximo período),
42
+ suspender, reactivar y cancelar; consumo del período con total estimado y los cobros cerrados.
43
+ Los espacios de pruebas muestran un aviso (nunca se cobran).
44
+ - **Settings**: tipo de cambio USD→CLP (valoriza la IA), datos para transferencia y emisor del PDF;
45
+ botones para ejecutar a mano el cierre y la revisión de mora (también corren solos cada día).
46
+
47
+ ## 3. Backoffice
48
+
49
+ ```vue
50
+ <!-- pages/backoffice/billing.vue (permiso billing.view; solo espacios de producción) -->
51
+ <Billing.Overview />
52
+
53
+ <!-- layout del backoffice: franja global de mora / solo lectura -->
54
+ <Billing.StatusBanner billing-route="/backoffice/billing" />
55
+ ```
56
+
57
+ - **Overview**: plan y estado, total estimado del período, saldo pendiente y vencido, consumo por
58
+ medidor frente a lo incluido (barra de progreso), facturas con PDF y botón **Pagar** cuando hay enlace,
59
+ la parte del espacio en facturas consolidadas, y pagos. Espacio de pruebas: solo la franja
60
+ "Espacio de pruebas".
61
+ - **StatusBanner**: se muestra con `past_due` ("Tienes facturas vencidas") o `suspended` ("Espacio en
62
+ solo lectura"). Pásale `status` (por ejemplo desde el header `X-Billing-Status` que pone el
63
+ middleware `billing.enforce`) o deja que consulte `billing/overview` (requiere `billing.view`; si
64
+ falla no muestra nada). `:fetch="false"` evita la consulta.
65
+ - Una escritura con el espacio suspendido responde **402** `{code: 'subscription_suspended'}`.
66
+
67
+ ## 4. Composables
68
+
69
+ - `useBillingPlatform({ base })` → `plans`, `meters`, `savePlan`, `invoices(filtersRef)`, `invoice(id)`,
70
+ `issue`, `resend`, `registerPayment`, `space(keyRef)`, `startSubscription`, `updateSubscription`,
71
+ `subscriptionAction`, `clientTotals`, `settings`, `saveSettings`, `run`.
72
+ - `useBillingSpace({ base })` → `overview`, `invoices`, `payments` (backoffice).
73
+ - `useBillingPdf()` → `(path, filename) => Promise` descarga un PDF con la sesión.
74
+ - Helpers puros (formato de pesos, estados, períodos, progreso de consumo) en
75
+ `composables/useBilling/internal/billing.ts`.