@asteby/metacore-runtime-react 53.2.0 → 53.4.0

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 (49) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/dynamic-columns.d.ts.map +1 -1
  3. package/dist/dynamic-columns.js +26 -4
  4. package/dist/index.d.ts +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/license/index.d.ts +3 -1
  8. package/dist/license/index.d.ts.map +1 -1
  9. package/dist/license/index.js +3 -1
  10. package/dist/license/license-expiry-banner.d.ts +8 -1
  11. package/dist/license/license-expiry-banner.d.ts.map +1 -1
  12. package/dist/license/license-expiry-banner.js +96 -54
  13. package/dist/license/license-gate.d.ts +14 -4
  14. package/dist/license/license-gate.d.ts.map +1 -1
  15. package/dist/license/license-gate.js +75 -63
  16. package/dist/license/license-status-badge.d.ts.map +1 -1
  17. package/dist/license/license-status-badge.js +8 -9
  18. package/dist/license/messages.d.ts +29 -0
  19. package/dist/license/messages.d.ts.map +1 -0
  20. package/dist/license/messages.js +159 -0
  21. package/dist/license/types.d.ts +30 -7
  22. package/dist/license/types.d.ts.map +1 -1
  23. package/dist/license/types.js +20 -6
  24. package/dist/license/use-license-t.d.ts +11 -0
  25. package/dist/license/use-license-t.d.ts.map +1 -0
  26. package/dist/license/use-license-t.js +18 -0
  27. package/dist/license/view.d.ts +40 -0
  28. package/dist/license/view.d.ts.map +1 -0
  29. package/dist/license/view.js +62 -0
  30. package/dist/relative-date.d.ts +37 -0
  31. package/dist/relative-date.d.ts.map +1 -0
  32. package/dist/relative-date.js +110 -0
  33. package/dist/types.d.ts +1 -1
  34. package/dist/types.d.ts.map +1 -1
  35. package/package.json +1 -1
  36. package/src/__tests__/license-states.test.tsx +381 -0
  37. package/src/__tests__/relative-date-brand-avatar.test.tsx +154 -0
  38. package/src/dynamic-columns.tsx +48 -6
  39. package/src/index.ts +13 -0
  40. package/src/license/index.ts +19 -0
  41. package/src/license/license-expiry-banner.tsx +155 -94
  42. package/src/license/license-gate.tsx +210 -147
  43. package/src/license/license-status-badge.tsx +8 -10
  44. package/src/license/messages.ts +185 -0
  45. package/src/license/types.ts +38 -6
  46. package/src/license/use-license-t.ts +23 -0
  47. package/src/license/view.ts +93 -0
  48. package/src/relative-date.tsx +142 -0
  49. package/src/types.ts +2 -0
@@ -0,0 +1,381 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // Estados de licencia, de punta a punta en el SDK (genérico: sin marca ni vertical):
4
+ // vigente, por vencer, en gracia, vencida (solo lectura con exportación),
5
+ // desactivada, hub caído (opera con lease), sin licencia, clonada.
6
+ // Cada estado se prueba con su texto EXACTO en español y en inglés, con el
7
+ // contacto del vendedor cuando la licencia lo trae, y el modal con encabezado y
8
+ // pie fijos (solo el cuerpo se desplaza).
9
+ import { afterEach, describe, expect, it, vi } from 'vitest'
10
+ import { cleanup, render, screen, fireEvent, waitFor, within } from '@testing-library/react'
11
+
12
+ let LANG = 'es'
13
+ vi.mock('react-i18next', () => ({
14
+ useTranslation: () => ({
15
+ i18n: { language: LANG },
16
+ t: (k: string, opts?: Record<string, unknown>) => {
17
+ let s = (opts?.defaultValue as string) ?? k
18
+ for (const [key, v] of Object.entries(opts ?? {})) {
19
+ if (key === 'defaultValue') continue
20
+ s = s.replace(new RegExp(`{{\\s*${key}\\s*}}`, 'g'), String(v))
21
+ }
22
+ return s
23
+ },
24
+ }),
25
+ }))
26
+
27
+ afterEach(() => {
28
+ cleanup()
29
+ localStorage.clear()
30
+ LANG = 'es'
31
+ })
32
+
33
+ import {
34
+ LicenseGate,
35
+ LicenseExpiryBanner,
36
+ LicenseStatusBadge,
37
+ LICENSE_MESSAGES,
38
+ registerLicenseMessages,
39
+ deriveLicenseView,
40
+ isLicenseBlocking,
41
+ isLicenseReadOnly,
42
+ type LicenseState,
43
+ } from '../license'
44
+
45
+ function make(p: Partial<LicenseState>): LicenseState {
46
+ return {
47
+ enforced: true,
48
+ configured: true,
49
+ valid: false,
50
+ status: 'missing',
51
+ entitlements: [],
52
+ wildcard: false,
53
+ stale: false,
54
+ in_grace: false,
55
+ days_remaining: 0,
56
+ ...p,
57
+ }
58
+ }
59
+
60
+ const SELLER = { name: 'Distribuidora Norte', email: 'ventas@norte.mx', phone: '+52 55 0000 0000' }
61
+ const CHILD = <div>contenido protegido</div>
62
+ const noop = () => Promise.resolve()
63
+
64
+ describe('deriveLicenseView: una sola verdad para cada estado', () => {
65
+ it('sin enforcement o sin estado no hay vista', () => {
66
+ expect(deriveLicenseView(undefined)).toBeUndefined()
67
+ expect(deriveLicenseView(make({ enforced: false, status: 'expired' }))).toBeUndefined()
68
+ })
69
+
70
+ const cases: Array<[string, Partial<LicenseState>, Record<string, unknown>]> = [
71
+ ['vigente', { status: 'valid', valid: true, days_remaining: 200 }, { condition: 'valid', blocking: false, readOnly: false }],
72
+ ['por vencer', { status: 'valid', valid: true, days_remaining: 9 }, { condition: 'expiring', blocking: false, readOnly: false }],
73
+ ['en gracia', { status: 'grace', in_grace: true, days_remaining: 4 }, { condition: 'grace', blocking: false, readOnly: false }],
74
+ ['vencida, política clásica', { status: 'expired' }, { condition: 'expired', blocking: true, readOnly: false }],
75
+ ['vencida, solo lectura', { status: 'expired', on_expiry: 'read_only' }, { condition: 'expired', blocking: false, readOnly: true }],
76
+ ['desactivada, sin plazo', { status: 'revoked' }, { condition: 'revoked', blocking: true, readOnly: false }],
77
+ ['desactivada, con plazo de aviso', { status: 'revoked', in_grace: true }, { condition: 'revoked', blocking: false, readOnly: true }],
78
+ ['hub caído con lease', { status: 'stale', stale: true, valid: true }, { condition: 'hub_unreachable', blocking: false, ownerOnly: true }],
79
+ ['sin licencia', { status: 'missing' }, { condition: 'missing', blocking: true }],
80
+ ['no válida', { status: 'invalid' }, { condition: 'invalid', blocking: true }],
81
+ ]
82
+ it.each(cases)('%s', (_n, partial, expected) => {
83
+ expect(deriveLicenseView(make(partial))).toMatchObject(expected)
84
+ })
85
+
86
+ it('clonada se suma a cualquier estado y no bloquea', () => {
87
+ const v = deriveLicenseView(make({ status: 'valid', valid: true, days_remaining: 100, notices: ['clone_suspected'] }))
88
+ expect(v).toMatchObject({ condition: 'valid', cloned: true, blocking: false })
89
+ })
90
+
91
+ it('los helpers siguen al estado: solo lectura nunca bloquea; revocada sin plazo sí', () => {
92
+ expect(isLicenseBlocking(make({ status: 'expired', on_expiry: 'read_only' }))).toBe(false)
93
+ expect(isLicenseReadOnly(make({ status: 'expired', on_expiry: 'read_only' }))).toBe(true)
94
+ expect(isLicenseBlocking(make({ status: 'revoked' }))).toBe(true)
95
+ expect(isLicenseReadOnly(make({ status: 'valid', valid: true, on_expiry: 'read_only' }))).toBe(false)
96
+ })
97
+ })
98
+
99
+ describe('banner: texto exacto por estado (es)', () => {
100
+ const txt = (s: Partial<LicenseState>, props: Record<string, unknown> = {}) => {
101
+ const { container } = render(<LicenseExpiryBanner state={make(s)} {...props} />)
102
+ return Array.from(container.querySelectorAll('[role="alert"]')).map((n) => n.textContent ?? '')
103
+ }
104
+
105
+ it('por vencer', () => {
106
+ expect(txt({ status: 'valid', valid: true, days_remaining: 7 })[0]).toContain('Tu licencia vence en 7 días.')
107
+ })
108
+ it('por vencer mañana y hoy', () => {
109
+ expect(txt({ status: 'valid', valid: true, days_remaining: 1 })[0]).toContain('Tu licencia vence mañana.')
110
+ cleanup()
111
+ expect(txt({ status: 'valid', valid: true, days_remaining: 0 })[0]).toContain('Tu licencia vence hoy.')
112
+ })
113
+ it('vigente no muestra nada', () => {
114
+ expect(txt({ status: 'valid', valid: true, days_remaining: 120 })).toEqual([])
115
+ })
116
+ it('en gracia con fecha', () => {
117
+ expect(txt({ status: 'grace', in_grace: true, days_remaining: 5, expires_at: '2026-10-01T00:00:00Z' })[0]).toContain(
118
+ 'Tu licencia venció el 1 de octubre de 2026. Tienes 5 días para renovarla antes de que se bloqueen los cambios.',
119
+ )
120
+ })
121
+ it('vencida en solo lectura, con exportación y contacto del vendedor', () => {
122
+ const onExport = vi.fn()
123
+ const [m] = txt(
124
+ { status: 'expired', on_expiry: 'read_only', expires_at: '2026-10-01T00:00:00Z', seller: SELLER },
125
+ { onExport },
126
+ )
127
+ expect(m).toContain(
128
+ 'Tu licencia venció el 1 de octubre de 2026. Tu información sigue disponible para consultar y exportar; renueva para volver a registrar cambios.',
129
+ )
130
+ expect(m).toContain('Contacto: Distribuidora Norte · ventas@norte.mx · +52 55 0000 0000')
131
+ fireEvent.click(screen.getByText('Exportar mis datos'))
132
+ expect(onExport).toHaveBeenCalled()
133
+ // En solo lectura el aviso es fijo.
134
+ expect(screen.queryByTitle('Descartar')).toBeNull()
135
+ })
136
+ it('el botón de exportar solo aparece en solo lectura', () => {
137
+ txt({ status: 'grace', in_grace: true, days_remaining: 3 }, { onExport: () => {} })
138
+ expect(screen.queryByText('Exportar mis datos')).toBeNull()
139
+ })
140
+ it('desactivada con plazo nombra al vendedor', () => {
141
+ const [m] = txt({ status: 'revoked', in_grace: true, grace_until: '2026-10-23T00:00:00Z', seller: SELLER })
142
+ expect(m).toContain(
143
+ 'Distribuidora Norte desactivó esta licencia. Tu información sigue disponible para consultar y exportar hasta el 23 de octubre de 2026.',
144
+ )
145
+ })
146
+ it('desactivada sin vendedor dice "Tu proveedor"', () => {
147
+ const [m] = txt({ status: 'revoked', in_grace: true })
148
+ expect(m).toContain('Tu proveedor desactivó esta licencia. Tu información sigue disponible para consultar y exportar.')
149
+ })
150
+ it('hub caído: el dueño lo ve; los demás usuarios no', () => {
151
+ const stale = { status: 'stale', stale: true, valid: true, last_checked_at: '2026-10-10T08:00:00Z' } as const
152
+ expect(txt(stale, { isOwner: true })[0]).toContain('No pudimos contactar al servidor de licencias desde el 10 de octubre de 2026. Seguimos funcionando.')
153
+ cleanup()
154
+ expect(txt(stale, { isOwner: false })).toEqual([])
155
+ cleanup()
156
+ // Sin informar el rol, tampoco se muestra (default seguro).
157
+ expect(txt(stale)).toEqual([])
158
+ })
159
+ it('clonada: solo el dueño, con el nombre del vendedor', () => {
160
+ const s = { status: 'valid', valid: true, days_remaining: 300, notices: ['clone_suspected'], seller: SELLER } as const
161
+ expect(txt(s, { isOwner: true })[0]).toContain('Detectamos esta licencia activa en otro servidor. Si no fue a propósito, avisa a Distribuidora Norte.')
162
+ cleanup()
163
+ expect(txt(s, { isOwner: false })).toEqual([])
164
+ cleanup()
165
+ expect(txt({ ...s, seller: undefined }, { isOwner: true })[0]).toContain('avisa a tu proveedor.')
166
+ })
167
+ it('clonada y por vencer se muestran juntas', () => {
168
+ const rows = txt({ status: 'valid', valid: true, days_remaining: 5, notices: ['clone_suspected'] }, { isOwner: true })
169
+ expect(rows).toHaveLength(2)
170
+ })
171
+ it('descartar un aviso menor no oculta la fila de clonado, que no se descarta', () => {
172
+ const st = { status: 'valid', valid: true, days_remaining: 5, notices: ['clone_suspected'] } as const
173
+ const { container } = render(<LicenseExpiryBanner state={make(st)} isOwner />)
174
+ fireEvent.click(screen.getByTitle('Descartar')) // solo hay un botón: el de la fila principal
175
+ const rows = Array.from(container.querySelectorAll('[role="alert"]')).map((n) => n.textContent ?? '')
176
+ expect(rows).toHaveLength(1)
177
+ expect(rows[0]).toContain('otro servidor')
178
+ expect(screen.queryByTitle('Descartar')).toBeNull()
179
+ })
180
+ })
181
+
182
+ describe('banner: inglés', () => {
183
+ it('textos exactos en inglés', () => {
184
+ LANG = 'en-US'
185
+ const { container } = render(
186
+ <LicenseExpiryBanner
187
+ state={make({ status: 'expired', on_expiry: 'read_only', expires_at: '2026-10-01T00:00:00Z', seller: SELLER })}
188
+ onExport={() => {}}
189
+ />,
190
+ )
191
+ const m = container.textContent ?? ''
192
+ expect(m).toContain('Your license expired on October 1, 2026. Your data is still available to view and export; renew to record changes again.')
193
+ expect(m).toContain('Contact: Distribuidora Norte · ventas@norte.mx · +52 55 0000 0000')
194
+ expect(screen.getByText('Export my data')).toBeTruthy()
195
+ cleanup()
196
+ const g = render(<LicenseExpiryBanner state={make({ status: 'grace', in_grace: true, days_remaining: 5, expires_at: '2026-10-01T00:00:00Z' })} />)
197
+ expect(g.container.textContent).toContain('Your license expired on October 1, 2026. You have 5 days to renew it before changes are blocked.')
198
+ })
199
+ })
200
+
201
+ describe('gate: modal con encabezado y pie fijos', () => {
202
+ it('vencida con solo lectura abre la app, no el modal', () => {
203
+ render(
204
+ <LicenseGate state={make({ status: 'expired', on_expiry: 'read_only' })} onActivate={noop} onExport={() => {}}>
205
+ {CHILD}
206
+ </LicenseGate>,
207
+ )
208
+ expect(screen.queryByRole('dialog')).toBeNull()
209
+ expect(screen.getByText('contenido protegido')).toBeTruthy()
210
+ expect(screen.getByText('Exportar mis datos')).toBeTruthy()
211
+ })
212
+
213
+ it('vencida sin solo lectura (instancias sin enlace de activación) sigue bloqueando como antes', () => {
214
+ render(
215
+ <LicenseGate state={make({ status: 'expired' })} onActivate={noop}>
216
+ {CHILD}
217
+ </LicenseGate>,
218
+ )
219
+ expect(screen.getByRole('dialog')).toBeTruthy()
220
+ expect(screen.getByText('Tu licencia venció')).toBeTruthy()
221
+ })
222
+
223
+ it('desactivada sin plazo: modal con título, texto y contacto del vendedor', () => {
224
+ render(
225
+ <LicenseGate state={make({ status: 'revoked', seller: SELLER })} onActivate={noop}>
226
+ {CHILD}
227
+ </LicenseGate>,
228
+ )
229
+ const dlg = screen.getByRole('dialog')
230
+ expect(within(dlg).getByText('Licencia desactivada')).toBeTruthy()
231
+ expect(within(dlg).getByText('Distribuidora Norte desactivó la licencia de esta instancia.')).toBeTruthy()
232
+ expect(dlg.querySelector('[data-license-part="seller"]')?.textContent).toContain('ventas@norte.mx')
233
+ })
234
+
235
+ it('sin licencia: textos en inglés', () => {
236
+ LANG = 'en'
237
+ render(
238
+ <LicenseGate state={make({ status: 'missing' })} onActivate={noop}>
239
+ {CHILD}
240
+ </LicenseGate>,
241
+ )
242
+ expect(screen.getByText('Activate your license')).toBeTruthy()
243
+ expect(screen.getByText("This instance doesn't have an active license yet.")).toBeTruthy()
244
+ expect(screen.getByText('Activate license')).toBeTruthy()
245
+ })
246
+
247
+ it('encabezado y pie fijos; solo el cuerpo se desplaza; el botón activa el formulario', async () => {
248
+ const onActivate = vi.fn().mockResolvedValue(undefined)
249
+ render(
250
+ <LicenseGate state={make({ status: 'missing' })} onActivate={onActivate}>
251
+ {CHILD}
252
+ </LicenseGate>,
253
+ )
254
+ const dlg = screen.getByRole('dialog')
255
+ const header = dlg.querySelector('[data-license-part="header"]') as HTMLElement
256
+ const body = dlg.querySelector('[data-license-part="body"]') as HTMLElement
257
+ const footer = dlg.querySelector('[data-license-part="footer"]') as HTMLElement
258
+ expect(header && body && footer).toBeTruthy()
259
+ expect(header.className).toContain('shrink-0')
260
+ expect(footer.className).toContain('shrink-0')
261
+ expect(body.className).toContain('overflow-y-auto')
262
+ expect(body.className).toContain('min-h-0')
263
+ // El contenedor limita su alto: sin eso el cuerpo no podría desplazarse.
264
+ expect(header.parentElement!.className).toContain('max-h-[')
265
+ expect(header.parentElement!.className).toContain('flex-col')
266
+ // El botón vive en el pie (fuera del cuerpo que se desplaza) y envía el formulario.
267
+ const btn = within(footer).getByText('Activar licencia').closest('button')!
268
+ expect(body.contains(btn)).toBe(false)
269
+ expect(btn.getAttribute('form')).toBe('license-gate-form')
270
+ fireEvent.change(screen.getByLabelText('Clave o token de licencia'), { target: { value: ' lic_x ' } })
271
+ fireEvent.click(btn)
272
+ await waitFor(() => expect(onActivate).toHaveBeenCalledWith('lic_x'))
273
+ })
274
+
275
+ it('con enlaces de activación cambia la etiqueta del campo', () => {
276
+ render(
277
+ <LicenseGate state={make({ status: 'missing' })} onActivate={noop} acceptsActivationLink>
278
+ {CHILD}
279
+ </LicenseGate>,
280
+ )
281
+ expect(screen.getByLabelText('Enlace, código o clave de licencia')).toBeTruthy()
282
+ })
283
+
284
+ it('un error con código del hub muestra el texto localizado de ese caso', async () => {
285
+ const err = Object.assign(new Error('license rejected: 409'), { code: 'activation_used' })
286
+ render(
287
+ <LicenseGate state={make({ status: 'missing' })} onActivate={vi.fn().mockRejectedValue(err)} acceptsActivationLink>
288
+ {CHILD}
289
+ </LicenseGate>,
290
+ )
291
+ fireEvent.change(screen.getByLabelText('Enlace, código o clave de licencia'), { target: { value: 'acs_x' } })
292
+ fireEvent.click(screen.getByText('Activar licencia'))
293
+ await waitFor(() =>
294
+ expect(screen.getByText('Este enlace ya se usó en otro servidor. Pide uno nuevo a tu proveedor.')).toBeTruthy(),
295
+ )
296
+ })
297
+
298
+ it('un error sin código muestra el mensaje del backend', async () => {
299
+ render(
300
+ <LicenseGate state={make({ status: 'missing' })} onActivate={vi.fn().mockRejectedValue(new Error('boom'))}>
301
+ {CHILD}
302
+ </LicenseGate>,
303
+ )
304
+ fireEvent.change(screen.getByLabelText('Clave o token de licencia'), { target: { value: 'x' } })
305
+ fireEvent.click(screen.getByText('Activar licencia'))
306
+ await waitFor(() => expect(screen.getByText('boom')).toBeTruthy())
307
+ })
308
+
309
+ it('vencida con exportación ofrece el botón en el pie del modal', () => {
310
+ const onExport = vi.fn()
311
+ render(
312
+ <LicenseGate state={make({ status: 'expired' })} onActivate={noop} onExport={onExport}>
313
+ {CHILD}
314
+ </LicenseGate>,
315
+ )
316
+ const footer = screen.getByRole('dialog').querySelector('[data-license-part="footer"]') as HTMLElement
317
+ fireEvent.click(within(footer).getByText('Exportar mis datos'))
318
+ expect(onExport).toHaveBeenCalled()
319
+ })
320
+
321
+ it('hub caído no estorba a un usuario que no es el dueño', () => {
322
+ render(
323
+ <LicenseGate state={make({ status: 'stale', stale: true, valid: true })} onActivate={noop} isOwner={false}>
324
+ {CHILD}
325
+ </LicenseGate>,
326
+ )
327
+ expect(screen.queryByRole('alert')).toBeNull()
328
+ expect(screen.queryByRole('dialog')).toBeNull()
329
+ })
330
+ })
331
+
332
+ describe('copy: sin eco de instrucciones', () => {
333
+ const ECHO = /\b(pega|pegar|pegue|ingresa|introduce|paste|enter your|type your)\b/i
334
+
335
+ it('ningún texto de estado (título, descripción, aviso) manda a pegar o escribir algo', () => {
336
+ const stateKeys = (m: Record<string, string>) =>
337
+ Object.entries(m).filter(([k]) => /\.(description|title)|_description|_title|banner\./.test(k) && !/placeholder|label|activate/.test(k))
338
+ for (const lang of ['es', 'en'] as const) {
339
+ for (const [k, v] of stateKeys(LICENSE_MESSAGES[lang])) {
340
+ expect(v, `${lang} ${k}`).not.toMatch(ECHO)
341
+ if (/description|banner\./.test(k)) expect(v, `${lang} ${k}`).not.toContain('lic_')
342
+ }
343
+ }
344
+ })
345
+
346
+ it('es y en tienen exactamente las mismas claves', () => {
347
+ expect(Object.keys(LICENSE_MESSAGES.en).sort()).toEqual(Object.keys(LICENSE_MESSAGES.es).sort())
348
+ })
349
+
350
+ it('cada texto con variable usa las mismas variables en es y en en', () => {
351
+ const vars = (s: string) => (s.match(/{{\s*\w+\s*}}/g) ?? []).map((x) => x.replace(/\s/g, '')).sort()
352
+ for (const k of Object.keys(LICENSE_MESSAGES.es)) {
353
+ expect(vars(LICENSE_MESSAGES.en[k]), k).toEqual(vars(LICENSE_MESSAGES.es[k]))
354
+ }
355
+ })
356
+ })
357
+
358
+ describe('insignia y registro i18n', () => {
359
+ it('la insignia de desactivada existe en es y en', () => {
360
+ render(<LicenseStatusBadge status="revoked" />)
361
+ expect(screen.getByText('Desactivada')).toBeTruthy()
362
+ cleanup()
363
+ LANG = 'en'
364
+ render(<LicenseStatusBadge status="revoked" />)
365
+ expect(screen.getByText('Deactivated')).toBeTruthy()
366
+ })
367
+
368
+ it('registerLicenseMessages siembra es/en sin pisar lo que el host ya definió', () => {
369
+ const calls: Array<[string, string, Record<string, unknown>, boolean | undefined, boolean | undefined]> = []
370
+ registerLicenseMessages({
371
+ addResourceBundle: (lng, ns, res, deep, overwrite) => {
372
+ calls.push([lng, ns, res as Record<string, unknown>, deep, overwrite])
373
+ },
374
+ })
375
+ expect(calls.map((c) => c[0]).sort()).toEqual(['en', 'es'])
376
+ for (const c of calls) expect(c[4]).toBe(false) // overwrite=false: el host manda
377
+ const es = calls.find((c) => c[0] === 'es')![2] as { license: { gate: { title: string } } }
378
+ expect(es.license.gate.title).toBe('Activa tu licencia')
379
+ expect(() => registerLicenseMessages(undefined)).not.toThrow()
380
+ })
381
+ })
@@ -0,0 +1,154 @@
1
+ // @vitest-environment happy-dom
2
+ //
3
+ // `display: relative_date` ("hace X" + tono por frescura) y avatar de marca
4
+ // (`image_field`, `color_field`, `subtitle_field`, `shape`).
5
+ import { afterEach, describe, expect, it } from 'vitest'
6
+ import { cleanup, render } from '@testing-library/react'
7
+ import { makeDefaultGetDynamicColumns, resolveAvatarSrc } from '../dynamic-columns'
8
+ import {
9
+ brandAvatarColors,
10
+ contrastRatio,
11
+ freshnessTone,
12
+ parseDurationMs,
13
+ parseHexColor,
14
+ } from '../relative-date'
15
+ import type { TableMetadata } from '../types'
16
+
17
+ afterEach(cleanup)
18
+
19
+ function renderCell(col: Record<string, unknown>, row: Record<string, unknown>, timeZone?: string) {
20
+ const meta = {
21
+ title: 't',
22
+ endpoint: '/x',
23
+ columns: [{ label: 'C', ...col }],
24
+ actions: [],
25
+ perPageOptions: [10],
26
+ defaultPerPage: 10,
27
+ searchPlaceholder: '',
28
+ enableCRUDActions: false,
29
+ hasActions: false,
30
+ } as unknown as TableMetadata
31
+ const cols = makeDefaultGetDynamicColumns({ getImageUrl: (p: string) => p })(meta, undefined, undefined, 'es', undefined, timeZone)
32
+ const key = col.key as string
33
+ const c = cols.find((x) => (x as { accessorKey?: string }).accessorKey === key || x.id === key)
34
+ if (!c || typeof c.cell !== 'function') throw new Error('columna no encontrada')
35
+ const node = (c.cell as (ctx: unknown) => React.ReactNode)({
36
+ row: { original: row },
37
+ getValue: () => row[key],
38
+ })
39
+ return render(<>{node}</>).container
40
+ }
41
+
42
+ const ago = (ms: number) => new Date(Date.now() - ms).toISOString()
43
+ const rel = (cfg?: Record<string, unknown>) => ({
44
+ key: 'last_seen_at',
45
+ type: 'timestamp',
46
+ cellStyle: 'relative_date',
47
+ styleConfig: cfg,
48
+ })
49
+
50
+ describe('parseDurationMs / freshnessTone', () => {
51
+ it('parsea s/m/h/d y rechaza basura', () => {
52
+ expect(parseDurationMs('30s')).toBe(30_000)
53
+ expect(parseDurationMs('15m')).toBe(900_000)
54
+ expect(parseDurationMs('6h')).toBe(21_600_000)
55
+ expect(parseDurationMs('7d')).toBe(604_800_000)
56
+ expect(parseDurationMs('abc')).toBeUndefined()
57
+ expect(parseDurationMs(undefined)).toBeUndefined()
58
+ })
59
+ it('sin umbrales: neutro', () => {
60
+ expect(freshnessTone(10_000)).toBeUndefined()
61
+ })
62
+ it('fresh_within y stale_after', () => {
63
+ const f = 15 * 60_000
64
+ const s = 60 * 60_000
65
+ expect(freshnessTone(60_000, f, s)).toBe('fresh')
66
+ expect(freshnessTone(30 * 60_000, f, s)).toBe('warn')
67
+ expect(freshnessTone(2 * 60 * 60_000, f, s)).toBe('stale')
68
+ })
69
+ it('un solo umbral', () => {
70
+ expect(freshnessTone(1000, 5000, undefined)).toBe('fresh')
71
+ expect(freshnessTone(9000, 5000, undefined)).toBe('stale')
72
+ expect(freshnessTone(1000, undefined, 5000)).toBe('warn')
73
+ expect(freshnessTone(9000, undefined, 5000)).toBe('stale')
74
+ })
75
+ })
76
+
77
+ describe('celda relative_date', () => {
78
+ it('sin umbrales: texto «hace» sin punto de tono', () => {
79
+ const el = renderCell(rel(), { last_seen_at: ago(3 * 60_000) })
80
+ expect(el.textContent).toMatch(/3 min|3 minutes/i)
81
+ expect(el.querySelector('[data-tone]')).toBeNull()
82
+ })
83
+ it('tono fresh / warn / stale', () => {
84
+ const cfg = { fresh_within: '15m', stale_after: '1h' }
85
+ expect(renderCell(rel(cfg), { last_seen_at: ago(60_000) }).querySelector('[data-tone]')?.getAttribute('data-tone')).toBe('fresh')
86
+ expect(renderCell(rel(cfg), { last_seen_at: ago(30 * 60_000) }).querySelector('[data-tone]')?.getAttribute('data-tone')).toBe('warn')
87
+ expect(renderCell(rel(cfg), { last_seen_at: ago(3 * 3600_000) }).querySelector('[data-tone]')?.getAttribute('data-tone')).toBe('stale')
88
+ })
89
+ it('valor vacío o inválido: guion', () => {
90
+ expect(renderCell(rel(), { last_seen_at: null }).textContent).toBe('-')
91
+ expect(renderCell(rel(), { last_seen_at: '' }).textContent).toBe('-')
92
+ expect(renderCell(rel(), { last_seen_at: 'nope' }).textContent).toBe('-')
93
+ })
94
+ it('tooltip con fecha absoluta en la zona de la org', () => {
95
+ const iso = '2026-01-15T18:30:00Z'
96
+ const el = renderCell(rel(), { last_seen_at: iso }, 'America/Mexico_City')
97
+ const title = el.querySelector('[title]')?.getAttribute('title') ?? ''
98
+ expect(title).toMatch(/12:30/)
99
+ expect(title).toMatch(/CST|GMT-6/)
100
+ })
101
+ })
102
+
103
+ describe('avatar de marca', () => {
104
+ const avatar = (cfg: Record<string, unknown>) => ({
105
+ key: 'brand_name',
106
+ type: 'text',
107
+ cellStyle: 'avatar',
108
+ styleConfig: cfg,
109
+ })
110
+ it('color_field: iniciales sobre el color de la fila con contraste AA', () => {
111
+ const el = renderCell(avatar({ color_field: 'brand_color' }), { brand_name: 'Acme Corp', brand_color: '#1d4ed8' })
112
+ const fb = Array.from(el.querySelectorAll('span')).find((s) => s.textContent === 'AC' && s.className.includes('text-[10px]')) as HTMLElement
113
+ expect(fb).toBeTruthy()
114
+ expect(fb.style.backgroundColor).toBe('rgb(29, 78, 216)')
115
+ expect(fb.style.color).toBe('#ffffff')
116
+ })
117
+ it('color claro usa tinta oscura', () => {
118
+ const c = brandAvatarColors('#fde68a')!
119
+ expect(c.color).toBe('#020617')
120
+ expect(c.ratio).toBeGreaterThanOrEqual(4.5)
121
+ })
122
+ it('AA para una muestra de colores', () => {
123
+ for (const h of ['#ef4444', '#10b981', '#6366f1', '#000000', '#ffffff', '#f59e0b', '#0ea5e9']) {
124
+ const c = brandAvatarColors(h)!
125
+ expect(c.ratio, h).toBeGreaterThanOrEqual(4.5)
126
+ }
127
+ expect(contrastRatio([0, 0, 0], [255, 255, 255])).toBeCloseTo(21, 0)
128
+ })
129
+ it('hex inválido o ausente: comportamiento previo (sin estilo inline)', () => {
130
+ expect(parseHexColor('rojo')).toBeUndefined()
131
+ const el = renderCell(avatar({ color_field: 'brand_color' }), { brand_name: 'Acme Corp', brand_color: 'rojo' })
132
+ const fb = Array.from(el.querySelectorAll('span')).find((s) => s.textContent === 'AC' && s.className.includes('text-[10px]')) as HTMLElement
133
+ expect(fb.getAttribute('style') ?? '').toBe('')
134
+ expect(fb.className).toContain('bg-primary/5')
135
+ })
136
+ it('sin config: intacto', () => {
137
+ const el = renderCell({ key: 'name', type: 'avatar' }, { name: 'Ana Perez' })
138
+ const fb = Array.from(el.querySelectorAll('span')).find((s) => s.textContent === 'AP' && s.className.includes('text-[10px]')) as HTMLElement
139
+ expect(fb.className).toContain('rounded-lg')
140
+ expect(fb.getAttribute('style') ?? '').toBe('')
141
+ })
142
+ it('shape circle y subtitle_field', () => {
143
+ const el = renderCell(avatar({ shape: 'circle', subtitle_field: 'customer' }), { brand_name: 'Acme', customer: 'Cliente SA' })
144
+ expect(el.textContent).toContain('Cliente SA')
145
+ expect(el.innerHTML).toContain('rounded-full')
146
+ })
147
+ it('image_field resuelve la URL del logo con la regla de base_path', () => {
148
+ const col = { key: 'brand_name', label: 'B', type: 'avatar', styleConfig: { image_field: 'brand_logo_url' } } as never
149
+ expect(resolveAvatarSrc(col, { brand_logo_url: 'https://cdn.x/l.svg' }, 'Acme')).toBe('https://cdn.x/l.svg')
150
+ expect(resolveAvatarSrc(col, { brand_logo_url: 'l.png' }, 'Acme', 'https://api.x')).toBe('https://api.xl.png')
151
+ // sin imagen en la fila: cae al valor de la columna (previo)
152
+ expect(resolveAvatarSrc(col, {}, 'https://cdn.x/v.png')).toBe('https://cdn.x/v.png')
153
+ })
154
+ })
@@ -38,6 +38,7 @@ import {
38
38
  relationChipStyles,
39
39
  } from '@asteby/metacore-ui/lib'
40
40
  import { Progress } from './dialogs/_primitives'
41
+ import { RelativeDateCell, brandAvatarColors } from './relative-date'
41
42
  import { useSystemActor } from './org-runtime-context'
42
43
  import { AuthorshipCell, hasSpecialAuthorship } from './provenance'
43
44
  import { humanizeToken, resolveColumnOptions, translateMetadataLabel } from './dynamic-columns-helpers'
@@ -673,7 +674,13 @@ export const resolveAvatarSrc = (
673
674
  apiBaseUrl = '',
674
675
  ): string | undefined => {
675
676
  let raw: string | undefined
676
- if (col.key.includes('.')) {
677
+ // Explicit per-row logo column (`display_config.image_field`) wins.
678
+ const imageField = styleCfg(col, 'image_field', 'imageField')
679
+ if (imageField) {
680
+ const fromField = getNestedValue(row, String(imageField))
681
+ if (fromField !== undefined && fromField !== null && fromField !== '') raw = String(fromField)
682
+ }
683
+ if (!raw && col.key.includes('.')) {
677
684
  const parentPath = col.key.split('.').slice(0, -1).join('.')
678
685
  const sibling =
679
686
  getNestedValue(row, `${parentPath}.avatar`) ||
@@ -857,15 +864,25 @@ const AvatarCell: React.FC<{
857
864
  desc?: string
858
865
  avatarSrc?: string
859
866
  getImageUrl: (path: string) => string
860
- }> = ({ name, desc, avatarSrc, getImageUrl }) => (
867
+ /** `display_config.shape`: rounded (default, logos) | circle (people). */
868
+ shape?: 'rounded' | 'circle'
869
+ /** Per-row brand colour (hex) for the initials fallback. */
870
+ color?: string
871
+ }> = ({ name, desc, avatarSrc, getImageUrl, shape, color }) => {
872
+ const radius = shape === 'circle' ? 'rounded-full' : 'rounded-lg'
873
+ const brand = brandAvatarColors(color)
874
+ return (
861
875
  <div className="flex items-center gap-3 min-w-0">
862
- <Avatar className="h-8 w-8 rounded-lg ring-1 ring-border/50">
876
+ <Avatar className={`h-8 w-8 ${radius} ring-1 ring-border/50`}>
863
877
  <AvatarImage
864
878
  src={avatarSrc ? getImageUrl(avatarSrc) : ''}
865
879
  alt={name}
866
880
  className="object-cover"
867
881
  />
868
- <AvatarFallback className="text-[10px] font-bold bg-primary/5 text-primary rounded-lg">
882
+ <AvatarFallback
883
+ className={`text-[10px] font-bold ${radius} ${brand ? '' : 'bg-primary/5 text-primary'}`}
884
+ style={brand ? { backgroundColor: brand.background, color: brand.color } : undefined}
885
+ >
869
886
  {getInitials(name)}
870
887
  </AvatarFallback>
871
888
  </Avatar>
@@ -880,7 +897,8 @@ const AvatarCell: React.FC<{
880
897
  )}
881
898
  </div>
882
899
  </div>
883
- )
900
+ )
901
+ }
884
902
 
885
903
  /**
886
904
  * Avatar cell for the system actor: the OrgRuntimeProvider `systemActor`
@@ -1249,7 +1267,17 @@ export function makeDefaultGetDynamicColumns(
1249
1267
  const name =
1250
1268
  resolvedName ||
1251
1269
  resolveMissingActorLabel(renderAs, col.key, namePath, t)
1252
- const desc = getNestedValue(row.original, col.description || '')
1270
+ const subtitleField = styleCfg(col, 'subtitle_field', 'subtitleField')
1271
+ const desc = getNestedValue(
1272
+ row.original,
1273
+ subtitleField ? String(subtitleField) : col.description || '',
1274
+ )
1275
+ const colorField = styleCfg(col, 'color_field', 'colorField')
1276
+ const brandColor = colorField
1277
+ ? getNestedValue(row.original, String(colorField))
1278
+ : undefined
1279
+ const avatarShape =
1280
+ styleCfg(col, 'shape') === 'circle' ? 'circle' : 'rounded'
1253
1281
 
1254
1282
  // Provenance (kernel `provenance`): a person with
1255
1283
  // the agent, the agent alone, or the system /
@@ -1279,6 +1307,20 @@ export function makeDefaultGetDynamicColumns(
1279
1307
  desc={desc ? String(desc) : undefined}
1280
1308
  avatarSrc={avatarSrc}
1281
1309
  getImageUrl={getImageUrl}
1310
+ shape={avatarShape}
1311
+ color={brandColor ? String(brandColor) : undefined}
1312
+ />
1313
+ )
1314
+ }
1315
+
1316
+ case 'relative_date': {
1317
+ const fmt = formatDateCell(value, 'datetime', dateLocale, timeZone)
1318
+ return (
1319
+ <RelativeDateCell
1320
+ value={value}
1321
+ locale={dateLocale}
1322
+ config={col.styleConfig}
1323
+ absolute={fmt ? fmt.title ?? fmt.display : undefined}
1282
1324
  />
1283
1325
  )
1284
1326
  }
package/src/index.ts CHANGED
@@ -11,14 +11,27 @@ export {
11
11
  LicenseStatusBadge,
12
12
  isLicenseOperable,
13
13
  isLicenseBlocking,
14
+ isLicenseReadOnly,
14
15
  isPresetEntitled,
15
16
  isTrialExpired,
17
+ deriveLicenseView,
18
+ isLicenseCloned,
19
+ sellerContactLine,
20
+ CLONE_NOTICE,
21
+ LICENSE_MESSAGES,
22
+ registerLicenseMessages,
16
23
  type LicenseGateProps,
17
24
  type LicenseExpiryBannerProps,
18
25
  type LicenseStatusBadgeProps,
19
26
  type LicenseState,
20
27
  type LicenseStatus,
28
+ type LicenseSeller,
29
+ type LicenseOnExpiry,
21
30
  type LicenseBranding,
31
+ type LicenseView,
32
+ type LicenseCondition,
33
+ type LicenseSeverity,
34
+ type LicenseLang,
22
35
  } from './license'
23
36
  export * from './options-context'
24
37
  export {