-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapping.ts
More file actions
611 lines (574 loc) · 25.8 KB
/
Copy pathmapping.ts
File metadata and controls
611 lines (574 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/**
* Mapping Airtable case → Mercurio 143-field POST payload (form EX-32).
*
* Aquest mòdul és COMPARTIT entre el test harness i (futur) el Worker endpoint
* `/mercurio/payload`. Mantenir pure function sense dependències de Worker o
* Node-only modules.
*
* Conveni: les claus de `record.fields` són els NOMS d'Airtable (post-rename
* dels camps `(Mercurio)` al nom net). Si encara tens els suffixos, passa
* `record.fields["Tipus via (Mercurio)"]` etc. — el mapper accepta les dues.
*/
export interface AirtableCase {
id: string;
fields: Record<string, any>;
}
export interface PresentadorConfig {
/** Nom complet, ja en majúscules format Mercurio (cognoms + nom) */
nombre: string;
/** NIE/DNI del voluntari que presenta */
nie: string;
/** Tipus de doc, normalment 'NF' (NIE) o 'NV' (DNI) */
tipoDoc: 'NF' | 'NV' | 'PA';
/** Mòbil de contacte de l'entitat */
mobil: string;
/** Email genèric de l'entitat */
email: string;
}
/**
* Map "Via legal" (Airtable singleSelect) → Mercurio form & codes.
*
* Mercurio té DOS formularis paral·lels:
* • EX-31 = "...por razón de arraigo": cobreix DA 20ª (Sol·licitant Protecció
* Internacional) i variants (fills menors, familiars del Sol·licitant PI,
* pròrrogues...). 6 supuestos.
* • EX-32 = "...por circunstancias excepcionales": cobreix DA 21ª (Arraigo
* Laboral / Familiar / Vulnerabilitat) i variants (fills menors, familiars
* DA 21ª, pròrrogues). 8 supuestos.
*
* Codis confirmats per inspecció DOM dels 2 forms (2026-04-26).
*/
const FORM_DES = {
EX31: 'Solicitud de autorización de residencia por circunstancias excepcionales por razón de arraigo',
EX32: 'Solicitud de autorización de residencia por circunstancias excepcionales',
} as const;
const VIA_LEGAL_MAP: Record<string, {
formulario: 'EX31' | 'EX32';
viaAccesoNew: string;
tipoPermisoNew: string;
idOpcionAutorizacion: string;
codOpcionAutorizacion: string;
_confidence: 'confirmed' | 'estimated' | 'unknown';
}> = {
// ─── EX-32: DA 21ª (Reforma Llei estrangeria 2026) ─────────────
'DA 21ª – Laboral': {
formulario: 'EX32',
viaAccesoNew: 'ARL', tipoPermisoNew: 'D21',
idOpcionAutorizacion: '292', codOpcionAutorizacion: 'EX-32-1-01',
_confidence: 'confirmed', // HAR Marta + DOM EX-32
},
'DA 21ª – Familiar': {
// "Permanecer en España junto con su unidad familiar" (radio DOM EX-32)
formulario: 'EX32',
viaAccesoNew: 'AUF', tipoPermisoNew: 'D21',
idOpcionAutorizacion: '293', codOpcionAutorizacion: 'EX-32-1-02',
_confidence: 'confirmed', // DOM EX-32
},
'DA 21ª – Vulnerabilitat': {
formulario: 'EX32',
viaAccesoNew: 'ASV', tipoPermisoNew: 'D21',
idOpcionAutorizacion: '294', codOpcionAutorizacion: 'EX-32-1-03',
_confidence: 'confirmed', // DOM EX-32
},
// ─── EX-31: DA 20ª (Sol·licitant Protecció Internacional) ──────
'DA 20ª – Sol·licitant PI': {
// "Solicitante de Protección Internacional con solicitud presentada
// antes del 01 de enero de 2026" (radio DOM EX-31)
formulario: 'EX31',
// viaAccesoNew/tipoPermisoNew: estimats (HTML EX-31 no porta atribut viaSup
// visible — s'omplen via JS al click). Cal confirmar al primer submit real.
viaAccesoNew: 'PRI', tipoPermisoNew: 'D20',
idOpcionAutorizacion: '284', codOpcionAutorizacion: 'EX-31-1-01',
_confidence: 'estimated',
},
'DA 20ª – Familiar de Sol·licitant PI': {
// "Familiar de Solicitante de Protección Internacional" (radio DOM EX-31)
formulario: 'EX31',
viaAccesoNew: 'PRI', tipoPermisoNew: 'D20',
idOpcionAutorizacion: '287', codOpcionAutorizacion: 'EX-31-1-04',
_confidence: 'estimated',
},
};
/**
* Supuesto "Hijo menor (no) nacido en España" per a sol·licitants menors d'edat.
*
* Mercurio el tracta com un supuesto propi DINS de cada formulari — NO canvia
* el form (EX31/EX32), que el marca la via legal de la família. Quan el cas és
* menor, aquest supuesto sobreescriu el que dictaria "Via legal".
*
* Codis confirmats per inspecció DOM (2026-05-16): menorsmercuri31.html
* (EX-31-1-02/03) i menorsmercuri32.html (EX-32-1-04/05).
*
* viaAccesoNew/tipoPermisoNew: a EX-32 l'atribut `viasup`/`permisosup` del radio
* coincideix amb el valor real (confirmat: ARL/AUF/ASV a les vies adultes). A
* EX-31 `viasup` NO coincideix (EX-31-1-01 porta viasup=SPI però el valor real
* és PRI), així que els d'EX-31 són una estimació — confirmar al primer submit.
*/
const MENOR_SUPUESTO: Record<'EX31' | 'EX32', Record<'nacido' | 'noNacido', {
viaAccesoNew: string;
tipoPermisoNew: string;
idOpcionAutorizacion: string;
codOpcionAutorizacion: string;
}>> = {
EX31: {
nacido: { viaAccesoNew: 'HNP', tipoPermisoNew: 'RMH', idOpcionAutorizacion: '285', codOpcionAutorizacion: 'EX-31-1-02' },
noNacido: { viaAccesoNew: 'NNP', tipoPermisoNew: 'RMH', idOpcionAutorizacion: '286', codOpcionAutorizacion: 'EX-31-1-03' },
},
EX32: {
nacido: { viaAccesoNew: 'HNA', tipoPermisoNew: 'RMH', idOpcionAutorizacion: '295', codOpcionAutorizacion: 'EX-32-1-04' },
noNacido: { viaAccesoNew: 'NNA', tipoPermisoNew: 'RMH', idOpcionAutorizacion: '296', codOpcionAutorizacion: 'EX-32-1-05' },
},
};
export { FORM_DES };
/** Sexe Airtable "H (home)" → Mercurio code (codis confirmats del select del form):
* 0 = HOMBRE, 1 = MUJER, X = INDEFINIDO */
function mapSexo(s: string | undefined): string {
if (!s) return '';
if (s.startsWith('H')) return '0';
if (s.startsWith('M')) return '1';
if (s.startsWith('X')) return 'X';
return '';
}
/** Estat civil Airtable "Casat/da (C)" → Mercurio "C"
* "Separat/da (Sp)" → "P" (Sp is the Catalan abbrev; Mercurio uses P=Separado) */
function mapEstadoCivil(s: string | undefined): string {
if (!s) return '';
const m = s.match(/\(([A-Z][a-z]?)\)/);
if (!m) return '';
const raw = m[1];
const normalize: Record<string, string> = { 'Sp': 'P' };
return normalize[raw] ?? raw;
}
/** Extreu codi entre parèntesis: "COLOMBIA (212)" → "212" */
function extractCode(s: any): string {
if (typeof s !== 'string' || !s) return '';
const m = s.match(/\(([A-Z0-9]+)\)\s*$/);
return m ? m[1] : '';
}
/** Extreu codi de Tipus via Airtable "CALLE (ED)" → "ED" */
function mapTipoVia(s: string | undefined): string {
return extractCode(s);
}
/**
* Normalitza Pis al catàleg Mercurio (extPiso).
*
* Mercurio NO accepta '1', '2'... — el catàleg usa codis prefixats:
* P01..P40 (pisos numerals), A01..A10 (àtics), S01..S05 (sòtans),
* ALT, ENT, PBJ, PBE, PBI, PRL, SSO, SOT, ' ' (NINGUNO).
*
* Acceptem entrada flexible del voluntari:
* '2' / '02' / '2º' / '2ª' / 'P02' → 'P02'
* 'BJ' / 'PBJ' → 'PBJ'
* 'AT' / 'AT01' → 'A01'
* 'ENT' / 'ALT' / 'PRL' (pass-through si ja és vàlid)
*/
function normalitzaPis(s: string | undefined): string {
const v = String(s ?? '').trim();
if (!v) return '';
// Numeral pur (1, 2, ..., 40) o amb 0 al davant ('05') o ordinal ('2º', '2ª')
const numMatch = v.match(/^0*([1-9]\d?)[ºª°]?$/);
if (numMatch) {
const n = parseInt(numMatch[1], 10);
if (n >= 1 && n <= 40) return 'P' + String(n).padStart(2, '0');
}
// Ja és el codi del catàleg (P01, A01, S01, ALT, ENT, PBJ, PRL, etc.)
if (/^[A-Z]{1,3}\d{0,2}$/.test(v.toUpperCase())) return v.toUpperCase();
// Sinònims comuns
const upper = v.toUpperCase();
const aliases: Record<string, string> = {
'BJ': 'PBJ', 'BAJO': 'PBJ', 'BAJOS': 'PBJ',
'AT': 'ALT', 'ATICO': 'ALT',
'PR': 'PRL', 'PRINCIPAL': 'PRL',
'EN': 'ENT', 'ENTRESUELO': 'ENT',
'SS': 'SSO', 'SO': 'SOT', 'SOTANO': 'SOT',
};
return aliases[upper] ?? v; // si no reconeixem, deixem al userscript que reporti invalid_option
}
/** Normalitza mòbil: treu tot el no-dígit i el prefix de país (+34 / 0034).
* Mercurio espera el número espanyol de 9 dígits sense indicatiu. */
function normalitzaTelefon(raw: string | undefined): string {
let d = String(raw ?? '').replace(/\D/g, '');
if (d.length === 13 && d.startsWith('0034')) d = d.slice(4);
else if (d.length === 11 && d.startsWith('34')) d = d.slice(2);
return d;
}
/** ISO date "1986-08-15" → "15/08/1986" */
function isoToEs(iso: string | undefined): string {
if (!iso) return '';
const m = iso.match(/^(\d{4})-(\d{2})-(\d{2})/);
return m ? `${m[3]}/${m[2]}/${m[1]}` : '';
}
/** Typos coneguts de domini → domini correcte. Només alta confiança:
* proveïdors massius on un humà no podria tenir legítimament aquest domini. */
const EMAIL_DOMAIN_FIXES: Record<string, string> = {
// gmail.com
'gmai.com': 'gmail.com', 'gmial.com': 'gmail.com', 'gmaill.com': 'gmail.com',
'gmal.com': 'gmail.com', 'gmali.com': 'gmail.com', 'gmaul.com': 'gmail.com',
'gmsil.com': 'gmail.com', 'gnail.com': 'gmail.com', 'gamil.com': 'gmail.com',
'gmail.con': 'gmail.com', 'gmail.cm': 'gmail.com', 'gmail.co': 'gmail.com',
'gmail.cim': 'gmail.com', 'gmail.cpm': 'gmail.com', 'gmail.om': 'gmail.com',
// hotmail.com / hotmail.es
'hotmial.com': 'hotmail.com', 'hotmai.com': 'hotmail.com', 'hotmal.com': 'hotmail.com',
'hotmaill.com': 'hotmail.com', 'hotnail.com': 'hotmail.com', 'hottmail.com': 'hotmail.com',
'hotmail.con': 'hotmail.com', 'hotmail.cm': 'hotmail.com', 'hotmail.co': 'hotmail.com',
'hotmial.es': 'hotmail.es', 'hotmai.es': 'hotmail.es', 'hotmal.es': 'hotmail.es',
// yahoo.com / yahoo.es
'yaho.com': 'yahoo.com', 'yahho.com': 'yahoo.com', 'yahooo.com': 'yahoo.com',
'yhoo.com': 'yahoo.com', 'yahoo.con': 'yahoo.com',
'yaho.es': 'yahoo.es', 'yahooo.es': 'yahoo.es',
// outlook.com / outlook.es
'outlok.com': 'outlook.com', 'outloook.com': 'outlook.com', 'outloo.com': 'outlook.com',
'outlook.con': 'outlook.com', 'outlook.cm': 'outlook.com',
'outlok.es': 'outlook.es',
// icloud.com
'iclod.com': 'icloud.com', 'iclould.com': 'icloud.com', 'icloud.con': 'icloud.com',
// live.com
'live.con': 'live.com', 'livee.com': 'live.com',
};
/** Normalitza email: trim, lowercase, corregeix typos coneguts del domini.
* La part local (abans de @) NO es toca — qualsevol "correcció" seria endevinar.
* Si no hi ha @ o no hi ha domini, retorna el valor trimat/lowercase tal qual. */
function normalizeEmail(raw: string): string {
const s = raw.trim().toLowerCase();
if (!s) return '';
const at = s.lastIndexOf('@');
if (at <= 0 || at === s.length - 1) return s;
const local = s.slice(0, at);
const domain = s.slice(at + 1);
const fixed = EMAIL_DOMAIN_FIXES[domain] ?? domain;
return `${local}@${fixed}`;
}
/** Get field, preferint la versió sufixada "X (Mercurio)" si existeix.
* Cas Nacionalitat / País naixement / Tipus via: Airtable té DOS camps —
* l'antic (text "COLOMBIA") i el nou (codi "COLOMBIA (212)"). Volem el nou.
* Per als camps que no tenen sufix, troba el plain igualment. */
function f(rec: AirtableCase, name: string): any {
return rec.fields[`${name} (Mercurio)`] ?? rec.fields[name] ?? '';
}
/** First non-empty Airtable string value: nacionalitat or other singleSelect.
* Handles "MARRUECOS (348)" pattern.
* Trim agressiu — espais accidentals al final (p.ex. "2 " a Pis) trenquen
* el `<select>.options.find(o => o.value === value)` del userscript. Vist
* amb cas RR-014 Miryan: Pis="2 " → invalid_option a Mercurio. */
function fStr(rec: AirtableCase, name: string): string {
const v = f(rec, name);
return typeof v === 'string' ? v.trim() : '';
}
/**
* Construeix el payload de 143 camps a partir d'un cas Airtable.
*
* @param rec Cas Airtable principal (sol·licitant)
* @param presentador Configuració del presentador (entitat + voluntari)
* @param refRec Cas referent: dependents (DA 21ª Familiar) i menors d'edat
* (el pare/mare/tutor que ha sol·licitat prèviament). Omitir
* si no aplica.
*/
export function airtableToMercurio(
rec: AirtableCase,
presentador: PresentadorConfig,
refRec?: AirtableCase
): Record<string, string> {
const viaLegal = fStr(rec, 'Via legal');
const viaCfg = VIA_LEGAL_MAP[viaLegal];
if (!viaCfg) {
throw new Error(
viaLegal
? `Via legal desconeguda: "${viaLegal}"`
: "El cas no té 'Via legal' definida a Airtable",
);
}
// Trim whitespace from name fields — Airtable inputs occasionally have trailing spaces.
const nom = fStr(rec, 'Nom').trim().toUpperCase();
const cog1 = fStr(rec, '1r cognom').trim().toUpperCase();
const cog2 = fStr(rec, '2n cognom').trim().toUpperCase();
const isDependent = !!refRec;
// Determine reagrupante data when dependent
const rea = isDependent && refRec ? buildReagrupante(refRec) : emptyReagrupante();
// Decla3 logic: marcat només si hi ha activitat laboral declarada
const activitatLaboral = fStr(rec, 'Activitat laboral descripció');
const tipusContracte = fStr(rec, 'Tipus de contracte');
const declaIntencio = activitatLaboral ||
tipusContracte === 'Oferta ferma' ||
tipusContracte === 'Declaració responsable';
const chkDecla3 = declaIntencio ? 'true' : undefined;
const formulario = viaCfg.formulario;
const isEX32 = formulario === 'EX32';
// ─── Menor d'edat ───────────────────────────────────────
// Si el sol·licitant és menor, el supuesto passa a "Hijo menor (no) nacido
// en España" del MATEIX formulari (el form el segueix marcant "Via legal").
// La distinció nacido/no-nacido surt del país de naixement (ESPAÑA = 109).
const isMenor = rec.fields["Menor d'edat"] === true;
const nacidoEnEspana = extractCode(fStr(rec, 'País naixement')) === '109';
const menorCfg = isMenor
? MENOR_SUPUESTO[formulario][nacidoEnEspana ? 'nacido' : 'noNacido']
: null;
const viaAccesoNew = menorCfg?.viaAccesoNew ?? viaCfg.viaAccesoNew;
const tipoPermisoNew = menorCfg?.tipoPermisoNew ?? viaCfg.tipoPermisoNew;
const idOpcionAutorizacion = menorCfg?.idOpcionAutorizacion ?? viaCfg.idOpcionAutorizacion;
const codOpcionAutorizacion = menorCfg?.codOpcionAutorizacion ?? viaCfg.codOpcionAutorizacion;
return {
// ─── Header / form metadata ────────────────────────────
tipoSolicitud: 'INI',
tipoSolicitudRI: 'E',
tipoFormulario: formulario,
tipoFormularioDes: FORM_DES[formulario],
provincia: '43',
tipoPermiso: '',
viaAcceso: '',
expedienteCaduca: '',
expedientePregrabado: '',
idExpediente: '',
fechaCaducidad: '',
fechaCaducidadExpCaduca: '',
viaAccesoOld: '',
viaAccesoNew,
tipoPermisoNew,
codigoMeyss: '',
tipoPermisoOld: '',
idGesDocum: '',
id: '',
idInicial: '',
idEmpresa: '',
situacionProcede: '',
idExtranjero: '',
extReferenciaExtranjeroPolicia: '',
idCatalogoOcupacionesEmpresa: '',
actividadEmpresaOTrabajoCuentaPropia: '',
domicilioEnExtranjero: '',
reagrupanteDocumentoExpNuevo: '',
filiacionFamiliar: '',
codParentesco: isDependent ? mapParentesco(fStr(rec, 'Parentiu amb referent')) : '',
dirParentescoFamDirecto: '',
descripcionDesplegable: '',
cod1: '',
acompante: '',
acompananteDocumento: '',
acompananteTitulo: '',
idOpcionAutorizacion,
codOpcionAutorizacion,
datosForAut: idOpcionAutorizacion,
// Camp dinàmic — només apareix al DOM si datosForAut=284 (DA 20ª PI).
// Es resol via Phase 1 del userscript (datosForAut + 400ms wait abans
// d'iterar la resta de camps). Per casos no-PI (DA 21ª*), Mercurio NO
// renderitza aquest input al DOM i el userscript reportaria 'not_found'
// — sorollós i confús al panell. Per això el spread condicional.
...(/Sol·licitant PI/.test(viaLegal)
? { expAsilo: fStr(rec, 'N.º expedient asil') }
: {}),
// ─── Decla checkboxes ───────────────────────────────────
chkDecla1: 'true',
_chkDecla1: 'on',
chkDecla2: 'true',
_chkDecla2: 'on',
// Bloc Decla3 (intenció d'activitat laboral) NO existeix al form EX-31
// (DA 20ª PI/asilo) — confirmat 2026-04-27 per inspecció DOM real
// (cas REDACTED). Tant chkDecla3 com descActividadDecla3 només es
// serveixen quan formulario === 'EX32' (DA 21ª arraigos).
// descActividadDecla3 va DESPRÉS de chkDecla3 a la insertion order
// perquè a EX-32 Mercurio renderitza l'input al change handler del
// checkbox; si el handler fos async, la Phase 2-bis del userscript
// fa retry a 300ms.
...(isEX32 && chkDecla3 ? { chkDecla3 } : {}),
_chkDecla3: 'on',
...(isEX32 ? { descActividadDecla3: activitatLaboral } : {}),
docsAutoriza: '',
docsDeniega: '',
_chkConsientoConsultaDocumentos: 'on',
// ─── Sol·licitant (ext*) ────────────────────────────────
extPasaporte: fStr(rec, 'Núm. passaport'),
extNie: fStr(rec, 'NIE'),
extApellido1: cog1,
extApellido2: cog2,
extNombre: nom,
extSexo: mapSexo(fStr(rec, 'Sexe')),
extFechaNacimiento: isoToEs(fStr(rec, 'Data de naixement')),
extEstadoCivil: mapEstadoCivil(fStr(rec, 'Estat civil')),
extLugarNacimiento: fStr(rec, 'Lloc de naixement').toUpperCase(),
// País naixement: si buit, default a Nacionalitat (assumir nascut al país
// d'origen — cas habitual 95%+). El voluntari pot sobreescriure manualment.
extCodigoPaisNacimiento: extractCode(fStr(rec, 'País naixement'))
|| extractCode(fStr(rec, 'Nacionalitat')),
extCodigoNacionalidad: extractCode(fStr(rec, 'Nacionalitat')),
extPadre: fStr(rec, 'Nom del pare'),
extMadre: fStr(rec, 'Nom de la mare'),
_chkIncapacidad: 'on',
extCatalogoNacional: '',
extTipoVia: mapTipoVia(fStr(rec, 'Tipus via')),
extDomicilio: fStr(rec, 'Nom carrer'),
extNumero: fStr(rec, 'Número') || (fStr(rec, 'Nom carrer') ? 'SN' : ''),
extPiso: normalitzaPis(fStr(rec, 'Pis')),
extLetra: fStr(rec, 'Lletra'),
extEscalera: fStr(rec, 'Escala'),
extBloque: fStr(rec, 'Bloc'),
extKilometro: fStr(rec, 'Km'),
extHectometro: fStr(rec, 'Hm'),
extCodigoProvincia: '43',
extCodigoMunicipio: extractCode(fStr(rec, 'Municipi Mercurio')),
// Localitat Mercurio: el catàleg usa codis de 6 dígits ('000000', '000600'…).
// Si el voluntari escriu text ('REUS') en lloc del codi, fallback al codi
// central del municipi ('000000') per evitar invalid_option a Mercurio.
extCodigoLocalidad: /^\d{6}$/.test(fStr(rec, 'Localitat Mercurio'))
? fStr(rec, 'Localitat Mercurio')
: '000000',
extCodigoPostal: fStr(rec, 'CP'),
extTelefono: '',
extTelefonoMovil: normalitzaTelefon(fStr(rec, 'Telèfon')),
extEmail: normalizeEmail(fStr(rec, 'Email')),
// Bloc "REPRESENTANTE LEGAL, EN SU CASO" — només s'omple per a menors,
// amb les dades del Referent familiar (pare/mare/tutor).
...(isMenor && refRec
? buildRepresentanteLegal(refRec, fStr(rec, 'Parentiu amb referent'))
: {
extNombreRepresentante: '',
extTipodocumentoRepresentante: 'NF',
extNieRepresentante: '',
extTituloRepresentante: '',
}),
extVinculoRepresentante: '',
// ─── Reagrupante (cas referent) ─────────────────────────
...rea,
// ─── Doc ────────────────────────────────────────────────
docInteresado: '',
docRepresentante: presentador.nie,
// ─── Presentador ────────────────────────────────────────
preNombrePresentador: presentador.nombre,
preTipodocumentoPresentador: presentador.tipoDoc,
preNiePresentador: presentador.nie,
preTipoViaPresentador: '',
preDomicilioPresentador: '',
preNumeroPresentador: 'SN',
prePisoPresentador: '',
preLetraPresentador: '',
preEscaleraPresentador: '',
preBloquePresentador: '',
preKilometroPresentador: '',
preHectometroPresentador: '',
preCodigoProvinciaPresentador: '',
preCodigoMunicipioPresentador: '',
preCodigoLocalidadPresentador: '',
preCodigoPostalPresentador: '',
preTelefonoPresentador: '',
preTelefonoMovilPresentador: presentador.mobil,
preEmailPresentador: presentador.email,
preNombreRepresentantePresentador: '',
preTipodocumentoRepresentantePresentador: '',
preNieRepresentantePresentador: '',
preTituloRepresentantePresentador: '',
// ─── Notificació ────────────────────────────────────────
notNombreNotificacion: presentador.nombre,
notTipodocumentoNotificacion: presentador.tipoDoc,
notNieNotificacion: presentador.nie,
notEmailNotificacion: presentador.email,
notTelefonoMovilNotificacion: presentador.mobil,
chkConsentimientoNotificacion: 'true',
_chkConsentimientoNotificacion: 'on',
};
}
function mapParentesco(p: string): string {
// catàleg parental Mercurio — codis hipotètics, cal validar
switch (p) {
case 'Cònjuge / parella registrada': return '02';
case 'Fill/a': return '03';
case 'Ascendent': return '01';
case 'Altre': return '07';
default: return '';
}
}
function buildReagrupante(refRec: AirtableCase): Record<string, string> {
const f = (n: string) => {
// Prefer (Mercurio) suffix — same priority com a la f() principal
const v = refRec.fields[`${n} (Mercurio)`] ?? refRec.fields[n] ?? '';
return typeof v === 'string' ? v : '';
};
return {
reaPasaporteReagrupante: f('Núm. passaport'),
reaNieReagrupante: f('NIE'),
reaApellido1Reagrupante: f('1r cognom').trim().toUpperCase(),
reaApellido2Reagrupante: f('2n cognom').trim().toUpperCase(),
reaNombreReagrupante: f('Nom').trim().toUpperCase(),
reaSexoReagrupante: mapSexo(f('Sexe')),
reaFechaNacimientoReagrupante: isoToEs(f('Data de naixement')),
reaEstadoCivilReagrupante: mapEstadoCivil(f('Estat civil')),
reaLugarNacimientoReagrupante: f('Lloc de naixement').toUpperCase(),
reaCodigoPaisNacimientoReagrupante: extractCode(f('País naixement')),
reaCodigoNacionalidadReagrupante: extractCode(f('Nacionalitat')),
reaPadreReagrupante: f('Nom del pare'),
reaMadreReagrupante: f('Nom de la mare'),
reaParentescoReagrupante: '',
reaTipoViaReagrupante: mapTipoVia(f('Tipus via')),
reaDomicilioReagrupante: f('Nom carrer'),
reaNumeroReagrupante: f('Número'),
reaPisoReagrupante: normalitzaPis(String(f('Pis'))),
reaLetraReagrupante: f('Lletra'),
reaEscaleraReagrupante: f('Escala'),
reaBloqueReagrupante: f('Bloc'),
reaKilometroReagrupante: f('Km'),
reaHectometroReagrupante: f('Hm'),
reaCodigoProvinciaReagrupante: '43',
reaCodigoMunicipioReagrupante: extractCode(f('Municipi Mercurio')),
// Mateix guard que extCodigoLocalidad: si el voluntari hi escriu text
// ('TARRAGONA') en lloc del codi de 6 dígits, fallback al codi central.
reaCodigoLocalidadReagrupante: /^\d{6}$/.test(f('Localitat Mercurio'))
? f('Localitat Mercurio')
: '000000',
reaCodigoPostalReagrupante: f('CP'),
};
}
/**
* Bloc "REPRESENTANTE LEGAL, EN SU CASO" — obligatori quan el sol·licitant és
* menor. El representant legal és el pare/mare/tutor, és a dir el cas enllaçat
* a "Referent familiar". El títol (PADRE/MADRE) es deriva del sexe del referent
* quan el parentiu és Fill/a; en qualsevol altre cas, TUTOR.
*/
function buildRepresentanteLegal(refRec: AirtableCase, parentiu: string): Record<string, string> {
const g = (n: string): string => {
const v = refRec.fields[`${n} (Mercurio)`] ?? refRec.fields[n] ?? '';
return typeof v === 'string' ? v.trim() : '';
};
const nie = g('NIE');
const pasaporte = g('Núm. passaport');
const sexe = g('Sexe');
let titulo = 'TUTOR';
if (parentiu === 'Fill/a') {
if (sexe.startsWith('M')) titulo = 'MADRE';
else if (sexe.startsWith('H')) titulo = 'PADRE';
}
const nombre = [g('1r cognom'), g('2n cognom'), g('Nom')]
.filter(Boolean).join(' ').toUpperCase();
return {
extNombreRepresentante: nombre,
// NF=DNI, TU=NIE, PA=Pasaporte. El referent normalment encara no té NIE.
extTipodocumentoRepresentante: nie ? 'TU' : 'PA',
extNieRepresentante: nie || pasaporte,
extTituloRepresentante: titulo,
};
}
function emptyReagrupante(): Record<string, string> {
return {
reaPasaporteReagrupante: '', reaNieReagrupante: '', reaApellido1Reagrupante: '',
reaApellido2Reagrupante: '', reaNombreReagrupante: '', reaSexoReagrupante: '',
reaFechaNacimientoReagrupante: '', reaEstadoCivilReagrupante: '',
reaLugarNacimientoReagrupante: '', reaCodigoPaisNacimientoReagrupante: '',
reaCodigoNacionalidadReagrupante: '', reaPadreReagrupante: '', reaMadreReagrupante: '',
reaParentescoReagrupante: '', reaTipoViaReagrupante: '', reaDomicilioReagrupante: '',
reaNumeroReagrupante: '', reaPisoReagrupante: '', reaLetraReagrupante: '',
reaEscaleraReagrupante: '', reaBloqueReagrupante: '', reaKilometroReagrupante: '',
reaHectometroReagrupante: '',
// Buit (no-dependent). Si fos 43, el userscript dispararia un canvi a la
// rea provincia que pot fer rebotar el getMunicipios global de Mercurio
// i resetejar el muni d'ext (bug observat 2026-04-26).
reaCodigoProvinciaReagrupante: '',
reaCodigoMunicipioReagrupante: '', reaCodigoLocalidadReagrupante: '',
reaCodigoPostalReagrupante: '',
};
}
/**
* Detecta quin form Mercurio (EX31 vs EX32) correspon a un cas Airtable.
* Retorna `null` si "Via legal" està buida o no és reconeguda — el caller
* ha de tractar aquest cas (mostrar avís al voluntari, no inventar form).
*/
export function getFormulario(rec: AirtableCase): 'EX31' | 'EX32' | null {
const viaLegal = fStr(rec, 'Via legal');
return VIA_LEGAL_MAP[viaLegal]?.formulario ?? null;
}
export { VIA_LEGAL_MAP };