@innertia-solutions/innertia-nuxt 0.1.88 → 0.1.90

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.
@@ -0,0 +1,213 @@
1
+ <script setup lang="ts">
2
+ import { IconMail, IconSend } from '@tabler/icons-vue'
3
+ import { HEX_COLOR } from '../../composables/internal/mailBranding'
4
+
5
+ /*
6
+ * Platform.MailSettings — configuración de correo de la plataforma (solo owner).
7
+ * Backend: \Innertia\Mail\Routes::platform('') → GET|PUT mail-settings, DELETE mail-settings/resend-key,
8
+ * POST mail-settings/test. Página sugerida:
9
+ *
10
+ * definePageMeta({ layout: 'platform', middleware: ['platform-owner'] })
11
+ * <Platform.MailSettings>
12
+ * <template #logo-picker="{ set }"><MiSelector @picked="set" /></template> // opcional
13
+ * </Platform.MailSettings>
14
+ *
15
+ * Validación por campo (local + 422), aviso de cambios sin guardar, confirmación al borrar la
16
+ * key de Resend, correo de prueba con la configuración guardada y vista previa (en vivo y del
17
+ * correo realmente enviado).
18
+ */
19
+ const props = withDefaults(defineProps<{ endpoint?: string }>(), { endpoint: 'platform/mail-settings' })
20
+
21
+ const api = useApi()
22
+ const toast = useToast()
23
+ const { confirm } = useModal()
24
+ const queryClient = useQueryClient()
25
+ const base = props.endpoint.replace(/^\/+|\/+$/g, '')
26
+ const queryKey = ['platform', 'mail-settings', base]
27
+
28
+ const { data, isPending } = useQuery({ queryKey, queryFn: () => api.get(base) })
29
+
30
+ const form = reactive({ mailer: 'smtp', from_name: '', from_address: '', logo_url: '', brand_color: '#6366f1' })
31
+ const resendKeyInput = ref('')
32
+ const resendKeySet = ref(false)
33
+
34
+ const BASE_MAILERS = [
35
+ { value: 'smtp', label: 'Mailpit / SMTP (desarrollo)' },
36
+ { value: 'resend', label: 'Resend (producción)' },
37
+ ]
38
+ const MAILERS = computed(() => ((data.value as any)?.mailer === 'log' || form.mailer === 'log')
39
+ ? [...BASE_MAILERS, { value: 'log', label: 'Registro (solo pruebas)' }]
40
+ : BASE_MAILERS)
41
+
42
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
43
+ const HTTP_URL = /^https?:\/\//i
44
+ const FIELDS = ['from_name', 'from_address', 'logo_url', 'brand_color'] as const
45
+ const errors = reactive<Record<string, string | null>>(Object.fromEntries(FIELDS.map(f => [f, null])))
46
+ FIELDS.forEach(f => watch(() => form[f], () => { errors[f] = null }))
47
+
48
+ const savedSnapshot = ref('')
49
+ const snapshot = () => JSON.stringify({ ...form })
50
+ const isDirty = computed(() => snapshot() !== savedSnapshot.value || !!resendKeyInput.value.trim())
51
+
52
+ watch(data, (v: any) => {
53
+ if (!v) return
54
+ form.mailer = v.mailer ?? 'smtp'
55
+ form.from_name = v.from_name ?? ''
56
+ form.from_address = v.from_address ?? ''
57
+ form.logo_url = v.logo_url ?? ''
58
+ form.brand_color = v.brand_color ?? '#6366f1'
59
+ resendKeySet.value = !!v.resend_api_key_set
60
+ resendKeyInput.value = ''
61
+ savedSnapshot.value = snapshot()
62
+ }, { immediate: true })
63
+
64
+ const preview = computed(() => ({ name: form.from_name || 'Plataforma', logo_url: form.logo_url, color: form.brand_color }))
65
+
66
+ const saving = ref(false)
67
+ async function save() {
68
+ FIELDS.forEach((f) => { errors[f] = null })
69
+ if (form.from_address && !EMAIL.test(form.from_address.trim())) errors.from_address = 'Ingresa un correo válido, por ejemplo no-reply@tudominio.cl.'
70
+ if (form.logo_url && !HTTP_URL.test(form.logo_url.trim())) errors.logo_url = 'La URL del logo debe comenzar con http:// o https://.'
71
+ if (form.brand_color && !HEX_COLOR.test(form.brand_color.trim())) errors.brand_color = 'El color de marca debe ser un hexadecimal como #6366f1 o #fff.'
72
+ if (FIELDS.some(f => errors[f])) return
73
+ saving.value = true
74
+ try {
75
+ const payload: Record<string, any> = { ...form }
76
+ if (resendKeyInput.value.trim()) payload.resend_api_key = resendKeyInput.value.trim()
77
+ const res = await api.put(base, payload)
78
+ queryClient.setQueryData(queryKey, res)
79
+ savedSnapshot.value = snapshot()
80
+ resendKeyInput.value = ''
81
+ toast.success('Configuración de correo guardada.')
82
+ } catch (e: any) {
83
+ const fieldErrors = e?.data?.errors ?? {}
84
+ FIELDS.forEach((f) => { errors[f] = fieldErrors[f]?.[0] ?? null })
85
+ if (!FIELDS.some(f => errors[f])) toast.error(e?.data?.message ?? 'No se pudo guardar.')
86
+ } finally {
87
+ saving.value = false
88
+ }
89
+ }
90
+
91
+ async function clearResendKey() {
92
+ if (!await confirm({ severity: 'danger', title: 'Eliminar API key de Resend', message: 'Se borrará la API key guardada. Si Resend es el proveedor activo, los correos dejarán de enviarse hasta que configures una nueva.', confirmText: 'Eliminar' })) return
93
+ try {
94
+ const res = await api.delete(`${base}/resend-key`)
95
+ queryClient.setQueryData(queryKey, res)
96
+ toast.success('API key de Resend eliminada.')
97
+ } catch (e: any) {
98
+ toast.error(e?.data?.message ?? 'No se pudo eliminar.')
99
+ }
100
+ }
101
+
102
+ const testEmail = ref('')
103
+ const testEmailError = ref<string | null>(null)
104
+ const sentHtml = ref<string | null>(null)
105
+ watch(testEmail, () => { testEmailError.value = null })
106
+ const testing = ref(false)
107
+ async function sendTest() {
108
+ if (testing.value) return
109
+ if (isDirty.value) { toast.error('Guarda los cambios antes de probar: la prueba usa la configuración guardada.'); return }
110
+ if (!testEmail.value) { testEmailError.value = 'Ingresa un correo de destino.'; return }
111
+ if (!EMAIL.test(testEmail.value.trim())) { testEmailError.value = 'Ingresa un correo válido.'; return }
112
+ testing.value = true
113
+ try {
114
+ const res: any = await api.post(`${base}/test`, { email: testEmail.value.trim() })
115
+ sentHtml.value = res?.html ?? null
116
+ toast.success(`Correo de prueba enviado a ${testEmail.value}.`)
117
+ } catch (e: any) {
118
+ testEmailError.value = e?.data?.errors?.email?.[0] ?? null
119
+ if (!testEmailError.value) toast.error(e?.data?.message ?? 'No se pudo enviar la prueba.')
120
+ } finally {
121
+ testing.value = false
122
+ }
123
+ }
124
+
125
+ onBeforeRouteLeave(() => {
126
+ if (isDirty.value && import.meta.client) return window.confirm('Tienes cambios sin guardar. ¿Salir igual?')
127
+ })
128
+ </script>
129
+
130
+ <template>
131
+ <div class="max-w-4xl mx-auto space-y-5">
132
+ <div class="flex items-center gap-3">
133
+ <div class="size-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center shrink-0">
134
+ <IconMail class="size-5" :stroke-width="1.5" />
135
+ </div>
136
+ <div class="flex-1 min-w-0">
137
+ <h1 class="text-lg font-semibold text-foreground">Configuración de correo</h1>
138
+ <p class="text-sm text-muted-foreground">Proveedor, remitente y marca de los correos que envía la plataforma.</p>
139
+ </div>
140
+ <span v-if="isDirty" class="text-xs text-amber-600 dark:text-amber-400">Cambios sin guardar</span>
141
+ <App.Button v-if="!isPending" text="Guardar" severity="primary" size="sm" :disabled="!isDirty" :loading="saving" @click="save" />
142
+ </div>
143
+
144
+ <div v-if="isPending" class="p-8 text-center text-sm text-muted-foreground">Cargando…</div>
145
+
146
+ <div v-else class="grid lg:grid-cols-[1fr_320px] gap-5 items-start">
147
+ <div class="space-y-5">
148
+ <div class="bg-card border border-card-line rounded-card p-5 space-y-4">
149
+ <p class="text-sm font-semibold text-foreground">Proveedor de envío</p>
150
+ <Forms.Select v-model="form.mailer" label="Proveedor" :clearable="false" :options="MAILERS" />
151
+
152
+ <div v-if="form.mailer === 'resend'" class="space-y-1.5">
153
+ <label class="block text-sm font-medium text-foreground">API key de Resend</label>
154
+ <div class="flex items-center gap-3">
155
+ <input
156
+ v-model="resendKeyInput"
157
+ type="password"
158
+ autocomplete="off"
159
+ :placeholder="resendKeySet ? '•••••••••• (guardada)' : 're_xxxxxxxxxxxx'"
160
+ class="flex-1 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"
161
+ />
162
+ <button v-if="resendKeySet" type="button" class="text-xs text-red-500 hover:underline shrink-0" @click="clearResendKey">Eliminar</button>
163
+ </div>
164
+ <p class="text-xs text-muted-foreground">
165
+ Se guarda encriptada. Déjala en blanco para conservar la actual.
166
+ <span v-if="resendKeySet" class="text-emerald-600 dark:text-emerald-400">Hay una key configurada.</span>
167
+ <span v-else class="text-amber-600 dark:text-amber-400">Aún no hay key configurada.</span>
168
+ </p>
169
+ <p class="text-xs text-muted-foreground">El dominio del remitente debe estar verificado en Resend.</p>
170
+ </div>
171
+ </div>
172
+
173
+ <div class="bg-card border border-card-line rounded-card p-5 space-y-4">
174
+ <p class="text-sm font-semibold text-foreground">Remitente y marca</p>
175
+ <div class="grid sm:grid-cols-2 gap-4">
176
+ <Forms.Input v-model="form.from_name" maxlength="120" label="Nombre del remitente" placeholder="Mi plataforma" :error="errors.from_name" />
177
+ <Forms.Input v-model="form.from_address" label="Correo del remitente" type="email" placeholder="no-reply@tudominio.cl" :error="errors.from_address" />
178
+ </div>
179
+ <div class="space-y-2">
180
+ <Forms.Input v-model="form.logo_url" label="URL del logo (correos)" placeholder="https://…/logo.png" :error="errors.logo_url" />
181
+ <slot name="logo-picker" :set="(url: string) => (form.logo_url = url)" />
182
+ </div>
183
+ <div>
184
+ <label class="block text-sm font-medium text-foreground mb-1">Color de marca</label>
185
+ <div class="flex items-start gap-3">
186
+ <input v-model="form.brand_color" type="color" class="h-9 w-14 rounded-control border border-card-line bg-transparent p-1 cursor-pointer" />
187
+ <Forms.Input v-model="form.brand_color" class="w-40" placeholder="#6366f1" :error="errors.brand_color" />
188
+ </div>
189
+ </div>
190
+ </div>
191
+
192
+ <div class="bg-card border border-card-line rounded-card p-5 space-y-3">
193
+ <div class="flex items-center gap-2">
194
+ <IconSend class="size-4 text-muted-foreground" />
195
+ <p class="text-sm font-medium text-foreground">Enviar correo de prueba</p>
196
+ </div>
197
+ <p class="text-xs text-muted-foreground">Envía un correo de ejemplo con la configuración guardada.</p>
198
+ <div class="flex items-end gap-2">
199
+ <Forms.Input v-model="testEmail" label="Correo de destino" type="email" placeholder="tu@correo.com" :error="testEmailError" class="flex-1 min-w-0" @keydown.enter.prevent="sendTest" />
200
+ <App.Button text="Enviar prueba" :icon="IconSend" severity="secondary" size="sm" :loading="testing" :disabled="isDirty" @click="sendTest" />
201
+ </div>
202
+ <p v-if="isDirty" class="text-xs text-amber-600 dark:text-amber-400">Guarda los cambios antes de probar: la prueba usa la configuración guardada.</p>
203
+ <iframe v-if="sentHtml" :srcdoc="sentHtml" title="Correo de prueba enviado" sandbox="" class="w-full h-96 rounded-card border border-card-line bg-white" />
204
+ </div>
205
+ </div>
206
+
207
+ <div class="space-y-2 lg:sticky lg:top-4">
208
+ <p class="text-sm font-medium text-foreground">Vista previa</p>
209
+ <Mail.BrandingPreview :platform="preview" title="¡La configuración de correo funciona!" body="Así se verán los correos de cuenta (invitación, recuperación, códigos)." action="Botón de ejemplo" />
210
+ </div>
211
+ </div>
212
+ </div>
213
+ </template>
@@ -0,0 +1,32 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
2
+
3
+ const calls: string[] = []
4
+ const api = {
5
+ get: vi.fn(async (url: string) => { calls.push(`GET ${url}`); return { data: [], unread: 0 } }),
6
+ patch: vi.fn(async (url: string) => { calls.push(`PATCH ${url}`) }),
7
+ delete: vi.fn(async (url: string) => { calls.push(`DELETE ${url}`) }),
8
+ }
9
+ const store = { setNotifications: vi.fn(), markRead: vi.fn(), markAllRead: vi.fn(), remove: vi.fn() }
10
+ vi.stubGlobal('useApi', () => api)
11
+ vi.stubGlobal('useNotificationsStore', () => store)
12
+
13
+ const { useNotifications } = await import('../useNotifications.js')
14
+
15
+ describe('useNotifications (campanita)', () => {
16
+ beforeEach(() => { calls.length = 0 })
17
+
18
+ it('por defecto habla con notifications (backoffice)', async () => {
19
+ const n = useNotifications()
20
+ await n.fetchNotifications({ all: 1 })
21
+ await n.markAsRead('a')
22
+ expect(calls).toEqual(['GET notifications', 'PATCH notifications/a/read'])
23
+ })
24
+
25
+ it('en platform usa el endpoint configurado', async () => {
26
+ const n = useNotifications({ base: '/platform/notifications/' })
27
+ await n.fetchNotifications()
28
+ await n.markAllAsRead()
29
+ await n.remove('b')
30
+ expect(calls).toEqual(['GET platform/notifications', 'PATCH platform/notifications/read-all', 'DELETE platform/notifications/b'])
31
+ })
32
+ })
@@ -0,0 +1,37 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { resolveForcePasswordRedirect } from '../forcePassword'
3
+
4
+ const pending = { force_password_change: true }
5
+ const on = { enabled: true }
6
+
7
+ describe('force-password', () => {
8
+ it('apagado por defecto: nunca redirige', () => {
9
+ expect(resolveForcePasswordRedirect('/backoffice', pending, undefined)).toBeNull()
10
+ expect(resolveForcePasswordRedirect('/backoffice', pending, { enabled: false })).toBeNull()
11
+ })
12
+
13
+ it('con cambio pendiente lleva a la página de cambio del área', () => {
14
+ expect(resolveForcePasswordRedirect('/backoffice/users', pending, on)).toBe('/backoffice/auth/change-password')
15
+ })
16
+
17
+ it('deja pasar las rutas de auth y la propia página de cambio', () => {
18
+ expect(resolveForcePasswordRedirect('/backoffice/auth/change-password', pending, on)).toBeNull()
19
+ expect(resolveForcePasswordRedirect('/backoffice/auth/login', pending, on)).toBeNull()
20
+ })
21
+
22
+ it('sin cambio pendiente o fuera del área no hace nada', () => {
23
+ expect(resolveForcePasswordRedirect('/backoffice', { force_password_change: false }, on)).toBeNull()
24
+ expect(resolveForcePasswordRedirect('/portal', pending, on)).toBeNull()
25
+ expect(resolveForcePasswordRedirect('/backoffice-x', pending, on)).toBeNull()
26
+ })
27
+
28
+ it('rutas configurables por área, el prefijo más largo gana', () => {
29
+ const cfg = { enabled: true, routes: { '/backoffice': '/backoffice/auth/change-password', '/technician': '/technician/password' }, allow: ['/technician/password', '/backoffice/auth/'] }
30
+ expect(resolveForcePasswordRedirect('/technician/agenda', pending, cfg)).toBe('/technician/password')
31
+ expect(resolveForcePasswordRedirect('/technician/password', pending, cfg)).toBeNull()
32
+ })
33
+
34
+ it('/platform lo maneja su propio middleware', () => {
35
+ expect(resolveForcePasswordRedirect('/platform/users', { ...pending, is_platform_admin: true }, { enabled: true, routes: { '/platform': '/x' } })).toBeNull()
36
+ })
37
+ })
@@ -0,0 +1,35 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { resolveBrandingPreview, validateBranding } from '../mailBranding'
3
+
4
+ const platform = { name: 'pomely', logo_url: 'https://cdn.test/pomely.png', color: '#112233' }
5
+
6
+ describe('vista previa de marca', () => {
7
+ it('sin marca del espacio usa la de plataforma (sin "vía")', () => {
8
+ expect(resolveBrandingPreview({}, platform)).toEqual({
9
+ name: 'pomely', logo_url: 'https://cdn.test/pomely.png', color: '#112233', footer_address: null, footer_phone: null, via: null,
10
+ })
11
+ })
12
+
13
+ it('marca propia con respaldo campo a campo y pie "vía"', () => {
14
+ const r = resolveBrandingPreview({ display_name: 'CESFAM Rancagua', footer_phone: '+56 72 123' }, platform)
15
+ expect(r.name).toBe('CESFAM Rancagua')
16
+ expect(r.logo_url).toBeNull() // marca propia sin logo: el nombre en texto, no el logo de plataforma
17
+ expect(r.color).toBe('#112233')
18
+ expect(r.footer_phone).toBe('+56 72 123')
19
+ expect(r.via).toBe('pomely')
20
+ })
21
+
22
+ it('ignora color o URL inválidos', () => {
23
+ const r = resolveBrandingPreview({ color: 'rojo', logo_url: 'ftp://x' }, platform)
24
+ expect(r.color).toBe('#112233')
25
+ expect(r.logo_url).toBe('https://cdn.test/pomely.png')
26
+ })
27
+
28
+ it('valida los campos', () => {
29
+ expect(validateBranding({ color: '#zzz', logo_url: 'logo.png' })).toMatchObject({
30
+ color: 'El color debe ser un hexadecimal como #6366f1 o #fff.',
31
+ logo_url: 'La URL del logo debe comenzar con http:// o https://.',
32
+ })
33
+ expect(validateBranding({ color: '#fff', logo_url: 'https://x.cl/l.png' })).toMatchObject({ color: null, logo_url: null })
34
+ })
35
+ })
@@ -0,0 +1,39 @@
1
+ // Cambio de contraseña forzado (force_password_change) para backoffice y otras áreas.
2
+ // Lógica pura del middleware 06.force-password.global (la usan también los tests).
3
+ //
4
+ // appConfig.innertia.forcePassword = {
5
+ // enabled: true,
6
+ // routes: { '/backoffice': '/backoffice/auth/change-password' }, // prefijo → página de cambio
7
+ // allow: ['/backoffice/auth/'], // prefijos que siempre pasan
8
+ // }
9
+ // /platform ya lo cubre 05.platform-password.global (identidad de plataforma).
10
+
11
+ export interface ForcePasswordConfig {
12
+ enabled?: boolean
13
+ routes?: Record<string, string>
14
+ allow?: string[]
15
+ }
16
+
17
+ export const FORCE_PASSWORD_DEFAULT_ROUTES: Record<string, string> = {
18
+ '/backoffice': '/backoffice/auth/change-password',
19
+ }
20
+
21
+ /** Ruta a la que hay que redirigir, o null si se deja pasar. */
22
+ export function resolveForcePasswordRedirect(path: string, user: any, config?: ForcePasswordConfig | null): string | null {
23
+ if (!config?.enabled || user?.force_password_change !== true) return null
24
+ if (user?.is_platform_admin && path.startsWith('/platform')) return null
25
+
26
+ const routes = config.routes && Object.keys(config.routes).length ? config.routes : FORCE_PASSWORD_DEFAULT_ROUTES
27
+ const allow = config.allow ?? Object.keys(routes).map(prefix => `${prefix.replace(/\/+$/, '')}/auth/`)
28
+
29
+ if (allow.some(prefix => path.startsWith(prefix))) return null
30
+
31
+ // El prefijo más largo gana (p. ej. /backoffice/admin antes que /backoffice).
32
+ const match = Object.keys(routes)
33
+ .sort((a, b) => b.length - a.length)
34
+ .find(prefix => path === prefix || path.startsWith(prefix.endsWith('/') ? prefix : `${prefix}/`))
35
+
36
+ if (!match) return null
37
+ const target = routes[match]
38
+ return path === target ? null : target
39
+ }
@@ -0,0 +1,62 @@
1
+ // Vista previa de la marca de correos (espejo de \Innertia\Mail\Branding::for()):
2
+ // marca del espacio con respaldo campo a campo en la de plataforma y "vía" cuando hay marca propia.
3
+
4
+ export interface BrandingFields {
5
+ display_name?: string | null
6
+ logo_url?: string | null
7
+ color?: string | null
8
+ footer_address?: string | null
9
+ footer_phone?: string | null
10
+ }
11
+
12
+ export interface ResolvedBranding {
13
+ name: string
14
+ logo_url: string | null
15
+ color: string
16
+ footer_address: string | null
17
+ footer_phone: string | null
18
+ via: string | null
19
+ }
20
+
21
+ export const DEFAULT_BRAND_COLOR = '#6366f1'
22
+ export const HEX_COLOR = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
23
+ const HTTP_URL = /^https?:\/\//i
24
+
25
+ const clean = (v?: string | null) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : null)
26
+
27
+ export function resolveBrandingPreview(tenant: BrandingFields | null | undefined, platform: Partial<ResolvedBranding> | null | undefined): ResolvedBranding {
28
+ const p: ResolvedBranding = {
29
+ name: clean(platform?.name) ?? 'App',
30
+ logo_url: clean(platform?.logo_url),
31
+ color: clean(platform?.color) ?? DEFAULT_BRAND_COLOR,
32
+ footer_address: null,
33
+ footer_phone: null,
34
+ via: null,
35
+ }
36
+
37
+ const name = clean(tenant?.display_name)
38
+ const logoRaw = clean(tenant?.logo_url)
39
+ const logo = logoRaw && HTTP_URL.test(logoRaw) ? logoRaw : null
40
+ const color = clean(tenant?.color)
41
+ const own = name !== null || logo !== null
42
+
43
+ return {
44
+ name: name ?? p.name,
45
+ logo_url: logo ?? (own ? null : p.logo_url),
46
+ color: color && HEX_COLOR.test(color) ? color : p.color,
47
+ footer_address: clean(tenant?.footer_address),
48
+ footer_phone: clean(tenant?.footer_phone),
49
+ via: own && name !== p.name ? p.name : null,
50
+ }
51
+ }
52
+
53
+ /** Errores de validación local de los campos de marca (null = válido). */
54
+ export function validateBranding(fields: BrandingFields): Record<string, string | null> {
55
+ const logo = clean(fields.logo_url)
56
+ const color = clean(fields.color)
57
+ return {
58
+ logo_url: logo && !HTTP_URL.test(logo) ? 'La URL del logo debe comenzar con http:// o https://.' : null,
59
+ color: color && !HEX_COLOR.test(color) ? 'El color debe ser un hexadecimal como #6366f1 o #fff.' : null,
60
+ display_name: (fields.display_name ?? '').length > 120 ? 'Máximo 120 caracteres.' : null,
61
+ }
62
+ }
@@ -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('notifications', { params: historyParams(toValue(opts)) }),
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(`notifications/${id}/read`),
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('notifications/read-all'),
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(`notifications/${id}`),
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('notifications'),
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('notifications', { params })
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(`notifications/${id}/read`)
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('notifications/read-all')
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(`notifications/${id}`)
37
+ await api.delete(`${base}/${id}`)
33
38
  store.remove(id)
34
39
  }
35
40