@innertia-solutions/innertia-nuxt 0.1.89 → 0.1.91
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.
- package/CHANGELOG.md +2 -0
- package/app.config.ts +8 -0
- package/components/App/NotificationBell.vue +4 -1
- package/components/App/NotificationHistory.vue +4 -2
- package/components/Integrations/ApiKeys.vue +297 -0
- package/components/Integrations/Developers.vue +60 -0
- package/components/Integrations/Webhooks.vue +458 -0
- package/components/Integrations/__tests__/sfc-compile.test.ts +31 -0
- package/components/Mail/BrandingPreview.vue +60 -0
- package/components/Mail/BrandingSettings.vue +141 -0
- package/components/Notifications/Preferences.vue +98 -0
- package/components/Notifications/__tests__/sfc-compile.test.ts +34 -0
- package/components/Platform/Emails.vue +133 -0
- package/components/Platform/MailSettings.vue +213 -0
- package/composables/__tests__/useNotifications.test.ts +32 -0
- package/composables/internal/__tests__/forcePassword.test.ts +37 -0
- package/composables/internal/__tests__/mailBranding.test.ts +35 -0
- package/composables/internal/forcePassword.ts +39 -0
- package/composables/internal/mailBranding.ts +62 -0
- package/composables/useIntegrations/index.ts +136 -0
- package/composables/useIntegrations/internal/__tests__/integrations.test.ts +112 -0
- package/composables/useIntegrations/internal/integrations.ts +276 -0
- package/composables/useNotificationHistory/index.ts +8 -7
- package/composables/useNotificationPreferences/index.ts +28 -0
- package/composables/useNotificationPreferences/internal/__tests__/preferences.test.ts +39 -0
- package/composables/useNotificationPreferences/internal/preferences.ts +66 -0
- package/composables/useNotifications.js +10 -5
- package/docs/correos-notificaciones.md +101 -0
- package/docs/webhooks-api.md +88 -0
- package/middleware/06.force-password.global.ts +14 -0
- package/middleware/platform-owner.ts +12 -0
- package/nuxt.config.ts +1 -1
- package/package.json +1 -1
|
@@ -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
|
+
}
|
|
@@ -15,34 +15,35 @@ import { historyParams, type HistoryFilter } from './internal/format'
|
|
|
15
15
|
* también la campanita del producto (y viceversa) si comparte el QueryClient.
|
|
16
16
|
* Nombre propio (no useNotifications) para no chocar con composables de producto.
|
|
17
17
|
*/
|
|
18
|
-
export function useNotificationHistory() {
|
|
18
|
+
export function useNotificationHistory(options: { base?: string } = {}) {
|
|
19
|
+
const base = String(options.base || 'notifications').replace(/^\/+|\/+$/g, '')
|
|
19
20
|
const api = useApi()
|
|
20
21
|
const queryClient = useQueryClient()
|
|
21
22
|
const invalidate = () => queryClient.invalidateQueries({ queryKey: ['notifications'] })
|
|
22
23
|
|
|
23
24
|
const list = (opts: MaybeRefOrGetter<{ filter: HistoryFilter; page: number; perPage: number }>) => useQuery({
|
|
24
|
-
queryKey: computed(() => ['notifications', 'history', historyParams(toValue(opts))]),
|
|
25
|
-
queryFn: () => api.get(
|
|
25
|
+
queryKey: computed(() => ['notifications', 'history', base, historyParams(toValue(opts))]),
|
|
26
|
+
queryFn: () => api.get(base, { params: historyParams(toValue(opts)) }),
|
|
26
27
|
placeholderData: (prev: any) => prev,
|
|
27
28
|
})
|
|
28
29
|
|
|
29
30
|
const markRead = () => useMutation({
|
|
30
|
-
mutationFn: (id: string) => api.patch(
|
|
31
|
+
mutationFn: (id: string) => api.patch(`${base}/${id}/read`),
|
|
31
32
|
onSuccess: invalidate,
|
|
32
33
|
})
|
|
33
34
|
|
|
34
35
|
const markAllRead = () => useMutation({
|
|
35
|
-
mutationFn: () => api.patch(
|
|
36
|
+
mutationFn: () => api.patch(`${base}/read-all`),
|
|
36
37
|
onSuccess: invalidate,
|
|
37
38
|
})
|
|
38
39
|
|
|
39
40
|
const remove = () => useMutation({
|
|
40
|
-
mutationFn: (id: string) => api.delete(
|
|
41
|
+
mutationFn: (id: string) => api.delete(`${base}/${id}`),
|
|
41
42
|
onSuccess: invalidate,
|
|
42
43
|
})
|
|
43
44
|
|
|
44
45
|
const removeRead = () => useMutation({
|
|
45
|
-
mutationFn: () => api.delete(
|
|
46
|
+
mutationFn: () => api.delete(base),
|
|
46
47
|
onSuccess: invalidate,
|
|
47
48
|
})
|
|
48
49
|
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { computed } from 'vue'
|
|
2
|
+
import type { PreferenceChange } from './internal/preferences'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Preferencias de avisos del usuario (innertia-laravel \Innertia\Notifications\Routes::preferences()):
|
|
6
|
+
* GET me/notification-preferences → {data: NoticeTypePreference[]}
|
|
7
|
+
* PUT me/notification-preferences {preferences: [{type, channel, enabled}]}
|
|
8
|
+
*
|
|
9
|
+
* `base`: prefijo de la API (en /platform: 'platform/me/notification-preferences').
|
|
10
|
+
*/
|
|
11
|
+
export function useNotificationPreferences(options: { base?: string } = {}) {
|
|
12
|
+
const base = String(options.base || 'me/notification-preferences').replace(/^\/+|\/+$/g, '')
|
|
13
|
+
const api = useApi()
|
|
14
|
+
const queryClient = useQueryClient()
|
|
15
|
+
const queryKey = computed(() => ['notification-preferences', base])
|
|
16
|
+
|
|
17
|
+
const query = useQuery({
|
|
18
|
+
queryKey,
|
|
19
|
+
queryFn: () => api.get(base),
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const save = useMutation({
|
|
23
|
+
mutationFn: (changes: PreferenceChange[]) => api.put(base, { preferences: changes }),
|
|
24
|
+
onSuccess: (res: any) => queryClient.setQueryData(queryKey.value, res),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
return { query, save }
|
|
28
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { clonePreferences, diffPreferences, groupByCategory, togglePreference, type NoticeTypePreference } from '../preferences'
|
|
3
|
+
|
|
4
|
+
const state = (enabled: boolean, locked = false, available = true) => ({ enabled, locked, available })
|
|
5
|
+
const data: NoticeTypePreference[] = [
|
|
6
|
+
{ key: 'call.missed', label: 'Llamada perdida', critical: false, category: null, channels: ['bell'], preferences: { bell: state(true), mail: state(false) } },
|
|
7
|
+
{ key: 'account.password_changed', label: 'Contraseña cambiada', critical: true, category: 'account', channels: ['bell', 'mail'], preferences: { bell: state(true, true), mail: state(true, true) } },
|
|
8
|
+
]
|
|
9
|
+
|
|
10
|
+
describe('preferencias de avisos', () => {
|
|
11
|
+
it('cambia un canal sin mutar lo que vino del servidor', () => {
|
|
12
|
+
const items = clonePreferences(data)
|
|
13
|
+
const next = togglePreference(items, 'call.missed', 'mail', true)
|
|
14
|
+
expect(next[0].preferences.mail.enabled).toBe(true)
|
|
15
|
+
expect(data[0].preferences.mail.enabled).toBe(false)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('los críticos están bloqueados: no cambian ni se envían', () => {
|
|
19
|
+
const next = togglePreference(clonePreferences(data), 'account.password_changed', 'mail', false)
|
|
20
|
+
expect(next[1].preferences.mail.enabled).toBe(true)
|
|
21
|
+
expect(diffPreferences(data, next)).toEqual([])
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('diff devuelve solo lo cambiado', () => {
|
|
25
|
+
let items = togglePreference(clonePreferences(data), 'call.missed', 'bell', false)
|
|
26
|
+
items = togglePreference(items, 'call.missed', 'mail', true)
|
|
27
|
+
expect(diffPreferences(data, items)).toEqual([
|
|
28
|
+
{ type: 'call.missed', channel: 'bell', enabled: false },
|
|
29
|
+
{ type: 'call.missed', channel: 'mail', enabled: true },
|
|
30
|
+
])
|
|
31
|
+
expect(diffPreferences(data, togglePreference(items, 'call.missed', 'bell', true))).toEqual([
|
|
32
|
+
{ type: 'call.missed', channel: 'mail', enabled: true },
|
|
33
|
+
])
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('agrupa por categoría', () => {
|
|
37
|
+
expect(groupByCategory(data).map(g => g.label)).toEqual(['Avisos', 'Cuenta y seguridad'])
|
|
38
|
+
})
|
|
39
|
+
})
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Lógica pura de preferencias de avisos (espejo de \Innertia\Notifications\Preferences).
|
|
2
|
+
// Los tipos críticos llegan `locked` y nunca se envían al servidor (que igual los ignora).
|
|
3
|
+
|
|
4
|
+
export type Channel = 'bell' | 'mail'
|
|
5
|
+
export const CHANNELS: Channel[] = ['bell', 'mail']
|
|
6
|
+
|
|
7
|
+
export interface ChannelState { enabled: boolean; locked: boolean; available: boolean }
|
|
8
|
+
|
|
9
|
+
export interface NoticeTypePreference {
|
|
10
|
+
key: string
|
|
11
|
+
label: string
|
|
12
|
+
description?: string
|
|
13
|
+
critical: boolean
|
|
14
|
+
category?: string | null
|
|
15
|
+
channels: Channel[]
|
|
16
|
+
preferences: Record<Channel, ChannelState>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface PreferenceChange { type: string; channel: Channel; enabled: boolean }
|
|
20
|
+
|
|
21
|
+
export const CHANNEL_LABELS: Record<Channel, string> = { bell: 'Campanita', mail: 'Correo' }
|
|
22
|
+
|
|
23
|
+
/** Copia profunda editable (el formulario no muta lo que vino del servidor). */
|
|
24
|
+
export function clonePreferences(items: NoticeTypePreference[] | null | undefined): NoticeTypePreference[] {
|
|
25
|
+
return (items ?? []).map(t => ({
|
|
26
|
+
...t,
|
|
27
|
+
preferences: Object.fromEntries(CHANNELS.map(c => [c, { ...t.preferences[c] }])) as Record<Channel, ChannelState>,
|
|
28
|
+
}))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Cambia un canal; los bloqueados (críticos) no cambian. Devuelve una lista nueva. */
|
|
32
|
+
export function togglePreference(items: NoticeTypePreference[], key: string, channel: Channel, enabled: boolean): NoticeTypePreference[] {
|
|
33
|
+
return items.map((t) => {
|
|
34
|
+
if (t.key !== key) return t
|
|
35
|
+
const state = t.preferences[channel]
|
|
36
|
+
if (!state || state.locked || !state.available) return t
|
|
37
|
+
return { ...t, preferences: { ...t.preferences, [channel]: { ...state, enabled } } }
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Cambios respecto de lo guardado (solo canales no bloqueados). */
|
|
42
|
+
export function diffPreferences(original: NoticeTypePreference[], current: NoticeTypePreference[]): PreferenceChange[] {
|
|
43
|
+
const before = new Map(original.map(t => [t.key, t]))
|
|
44
|
+
const changes: PreferenceChange[] = []
|
|
45
|
+
for (const t of current) {
|
|
46
|
+
for (const channel of CHANNELS) {
|
|
47
|
+
const now = t.preferences[channel]
|
|
48
|
+
const prev = before.get(t.key)?.preferences[channel]
|
|
49
|
+
if (!now || now.locked || !now.available) continue
|
|
50
|
+
if (!prev || prev.enabled !== now.enabled) changes.push({ type: t.key, channel, enabled: now.enabled })
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return changes
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Agrupa por categoría (null → 'Generales'; 'account' → 'Cuenta'), conservando el orden. */
|
|
57
|
+
export function groupByCategory(items: NoticeTypePreference[]): { category: string; label: string; items: NoticeTypePreference[] }[] {
|
|
58
|
+
const labels: Record<string, string> = { account: 'Cuenta y seguridad' }
|
|
59
|
+
const groups = new Map<string, NoticeTypePreference[]>()
|
|
60
|
+
for (const t of items) {
|
|
61
|
+
const cat = t.category || 'general'
|
|
62
|
+
if (!groups.has(cat)) groups.set(cat, [])
|
|
63
|
+
groups.get(cat)!.push(t)
|
|
64
|
+
}
|
|
65
|
+
return [...groups.entries()].map(([category, list]) => ({ category, label: labels[category] ?? (category === 'general' ? 'Avisos' : category), items: list }))
|
|
66
|
+
}
|
|
@@ -7,29 +7,34 @@
|
|
|
7
7
|
* PATCH notifications/read-all
|
|
8
8
|
* DELETE notifications/{id}
|
|
9
9
|
* DELETE notifications (borra las leídas)
|
|
10
|
+
*
|
|
11
|
+
* `base` (opcional): prefijo de las rutas. En /platform la campanita usa
|
|
12
|
+
* `useNotifications({ base: 'platform/notifications' })` (el producto monta
|
|
13
|
+
* \Innertia\Notifications\Routes::register('notifications') dentro de su grupo platform).
|
|
10
14
|
*/
|
|
11
|
-
export function useNotifications() {
|
|
15
|
+
export function useNotifications(options = {}) {
|
|
12
16
|
const api = useApi()
|
|
13
17
|
const store = useNotificationsStore()
|
|
18
|
+
const base = String(options.base || 'notifications').replace(/^\/+|\/+$/g, '')
|
|
14
19
|
|
|
15
20
|
async function fetchNotifications(params = {}) {
|
|
16
|
-
const res = await api.get(
|
|
21
|
+
const res = await api.get(base, { params })
|
|
17
22
|
store.setNotifications(res?.data ?? [])
|
|
18
23
|
return res
|
|
19
24
|
}
|
|
20
25
|
|
|
21
26
|
async function markAsRead(id) {
|
|
22
|
-
await api.patch(
|
|
27
|
+
await api.patch(`${base}/${id}/read`)
|
|
23
28
|
store.markRead(id)
|
|
24
29
|
}
|
|
25
30
|
|
|
26
31
|
async function markAllAsRead() {
|
|
27
|
-
await api.patch(
|
|
32
|
+
await api.patch(`${base}/read-all`)
|
|
28
33
|
store.markAllRead()
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
async function remove(id) {
|
|
32
|
-
await api.delete(
|
|
37
|
+
await api.delete(`${base}/${id}`)
|
|
33
38
|
store.remove(id)
|
|
34
39
|
}
|
|
35
40
|
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Correos y notificaciones con marca
|
|
2
|
+
|
|
3
|
+
Front del motor de avisos y correos de innertia-laravel (`\Innertia\Notifications`, `\Innertia\Mail`).
|
|
4
|
+
Guía del backend: `docs/correos-notificaciones.md` de innertia-laravel (rutas, `NoticeTypes`, `Notifier`).
|
|
5
|
+
|
|
6
|
+
**Todo es opt-in:** ningún componente se monta solo y el middleware de cambio de clave forzado
|
|
7
|
+
no hace nada hasta activarlo. Los productos que tienen sus propias páginas siguen igual.
|
|
8
|
+
|
|
9
|
+
## Campanita en platform
|
|
10
|
+
|
|
11
|
+
El producto registra en su grupo platform `\Innertia\Notifications\Routes::register('notifications')`
|
|
12
|
+
(queda en `platform/notifications`) y monta la campanita en el layout de platform:
|
|
13
|
+
|
|
14
|
+
```vue
|
|
15
|
+
<App.NotificationBell endpoint="platform/notifications" all-route="/platform/notifications" />
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```vue
|
|
19
|
+
<!-- pages/platform/notifications.vue -->
|
|
20
|
+
<template><App.NotificationHistory endpoint="platform/notifications" /></template>
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`useNotifications({ base })` y `useNotificationHistory({ base })` aceptan el mismo prefijo
|
|
24
|
+
(default `notifications`, el backoffice no cambia).
|
|
25
|
+
|
|
26
|
+
## Preferencias (Mi cuenta › Notificaciones)
|
|
27
|
+
|
|
28
|
+
```vue
|
|
29
|
+
<Notifications.Preferences /> <!-- backoffice -->
|
|
30
|
+
<Notifications.Preferences endpoint="platform/me/notification-preferences" /> <!-- platform -->
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Lista los tipos registrados en `NoticeTypes` con un interruptor por canal (campanita/correo).
|
|
34
|
+
Los avisos críticos de cuenta se muestran con candado y deshabilitados (el servidor ignora
|
|
35
|
+
apagarlos). Solo envía lo cambiado. Composable: `useNotificationPreferences({ base })`.
|
|
36
|
+
|
|
37
|
+
## Registro de correos (/platform/emails)
|
|
38
|
+
|
|
39
|
+
```vue
|
|
40
|
+
<!-- pages/platform/emails/index.vue -->
|
|
41
|
+
<script setup>definePageMeta({ layout: 'platform', middleware: 'platform' })</script>
|
|
42
|
+
<template><Platform.Emails :tenants="tenantOptions" /></template>
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Filtros por destinatario/asunto, estado, tipo (de `emails/types`) y espacio (`tenants`, opcional).
|
|
46
|
+
Los fallidos se expanden para ver el motivo.
|
|
47
|
+
|
|
48
|
+
## Configuración de correo (/platform/settings/mail, solo owner)
|
|
49
|
+
|
|
50
|
+
```vue
|
|
51
|
+
<script setup>definePageMeta({ layout: 'platform', middleware: ['platform', 'platform-owner'] })</script>
|
|
52
|
+
<template>
|
|
53
|
+
<Platform.MailSettings>
|
|
54
|
+
<!-- opcional: selector de imagen del producto -->
|
|
55
|
+
<template #logo-picker="{ set }"><Platform.FileImagePicker @picked="set" /></template>
|
|
56
|
+
</Platform.MailSettings>
|
|
57
|
+
</template>
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Proveedor (Mailpit/SMTP, Resend), API key encriptada (confirmación al borrar), remitente, logo y
|
|
61
|
+
color con validación por campo, aviso de cambios sin guardar, correo de prueba con la
|
|
62
|
+
configuración guardada y vista previa en vivo + del correo enviado. El middleware
|
|
63
|
+
`platform-owner` de la capa redirige a `/platform` a quien no es owner (si el producto tiene uno
|
|
64
|
+
propio con ese nombre, gana el del producto).
|
|
65
|
+
|
|
66
|
+
## Marca del espacio (Sistema › Marca)
|
|
67
|
+
|
|
68
|
+
```vue
|
|
69
|
+
<script setup>definePageMeta({ middleware: ['auth'] })</script>
|
|
70
|
+
<template>
|
|
71
|
+
<Mail.BrandingSettings>
|
|
72
|
+
<template #logo-picker="{ set }"><MiSelectorDeDocumentos @picked="(f) => set({ logo_file_id: f.id })" /></template>
|
|
73
|
+
</Mail.BrandingSettings>
|
|
74
|
+
</template>
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Backend: `\Innertia\Mail\Routes::tenantBranding('settings/branding')` con el permiso del producto
|
|
78
|
+
(p. ej. `settings.manage`). Nombre visible, logo (URL pública o archivo de Documentos), color y pie
|
|
79
|
+
(dirección/teléfono), vista previa en vivo y "Enviarme un correo de prueba".
|
|
80
|
+
|
|
81
|
+
`<Mail.BrandingPreview :branding="campos" :platform="marcaPlataforma" />` sirve suelto: resuelve
|
|
82
|
+
igual que `Branding::for()` del backend (respaldo campo a campo y "Enviado vía …").
|
|
83
|
+
|
|
84
|
+
## Cambio de contraseña forzado
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// nuxt.config.ts del producto
|
|
88
|
+
appConfig: {
|
|
89
|
+
innertia: {
|
|
90
|
+
forcePassword: {
|
|
91
|
+
enabled: true,
|
|
92
|
+
routes: { '/backoffice': '/backoffice/auth/change-password' }, // prefijo → página de cambio
|
|
93
|
+
// allow: ['/backoffice/auth/'], // por defecto '<prefijo>/auth/'
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Con `user.force_password_change === true`, cualquier ruta del área lleva a su página de cambio.
|
|
100
|
+
`/platform` ya lo cubre `05.platform-password.global`. Si el producto tiene su propio
|
|
101
|
+
`force-password.global.ts`, bórralo al activar este.
|