@opencitylabs/formio-sdk 1.0.0 → 1.1.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 (2) hide show
  1. package/index.js +213 -330
  2. package/package.json +6 -4
package/index.js CHANGED
@@ -2,15 +2,15 @@
2
2
 
3
3
  const axios = require("axios");
4
4
  const get = require("lodash.get");
5
+ const { baseUrl } = require("./BaseUrl");
6
+ const { jwtDecode } = require("jwt-decode");
5
7
 
6
- class FormioHelper {
7
- constructor(options = {}) {
8
- this.options = options;
9
- this.httpClient = options.httpClient || axios;
10
- this.logger = options.logger || console;
8
+ class FormIoHelper {
9
+
10
+ constructor() {
11
11
  this.token = null;
12
12
  this.basePath = null;
13
- this.init();
13
+ this.init()
14
14
  }
15
15
 
16
16
  init() {
@@ -18,92 +18,20 @@ class FormioHelper {
18
18
  this.token = this.getCurrentToken();
19
19
  }
20
20
 
21
- logError(...args) {
22
- if (this.logger && typeof this.logger.error === "function") {
23
- this.logger.error(...args);
24
- }
25
- }
26
-
27
- logWarn(...args) {
28
- if (this.logger && typeof this.logger.warn === "function") {
29
- this.logger.warn(...args);
30
- }
31
- }
32
-
33
- getWindow() {
34
- return typeof window !== "undefined" ? window : null;
35
- }
36
-
37
- getDocument() {
38
- return typeof document !== "undefined" ? document : null;
39
- }
40
-
41
- getStorage() {
42
- if (this.options.storage) {
43
- return this.options.storage;
44
- }
45
-
46
- const win = this.getWindow();
47
- if (win && win.sessionStorage) {
48
- return win.sessionStorage;
49
- }
50
-
51
- return null;
52
- }
53
-
54
- resolveOption(optionName) {
55
- const optionValue = this.options[optionName];
56
- if (typeof optionValue === "function") {
57
- return optionValue();
58
- }
59
-
60
- return optionValue ?? null;
61
- }
62
-
63
21
  getCurrentLocale() {
64
- if (typeof this.options.getCurrentLocale === "function") {
65
- return this.options.getCurrentLocale();
66
- }
67
-
68
- const optionLocale = this.resolveOption("locale");
69
- if (optionLocale) {
70
- return optionLocale.toString();
71
- }
72
-
73
- const doc = this.getDocument();
74
- if (doc && doc.documentElement && doc.documentElement.lang) {
75
- return doc.documentElement.lang.toString();
76
- }
77
-
78
- return "it";
22
+ return document.documentElement.lang.toString();
79
23
  }
80
24
 
81
- getCurrentToken() {
25
+ async getCurrentToken() {
82
26
  if (this.token) {
83
27
  return this.token;
84
28
  }
85
29
 
86
- if (typeof this.options.getCurrentToken === "function") {
87
- return this.options.getCurrentToken();
88
- }
89
-
90
- const optionToken = this.resolveOption("token");
91
- if (typeof optionToken === "string") {
92
- return optionToken;
93
- }
94
-
95
- if (optionToken && typeof optionToken === "object") {
96
- return optionToken.value || null;
97
- }
98
-
99
- const storage = this.getStorage();
100
- if (!storage || typeof storage.getItem !== "function") {
101
- return null;
102
- }
103
-
104
- const rawToken = storage.getItem("auth-token");
30
+ const rawToken = sessionStorage.getItem("auth-token");
105
31
  if (!rawToken) {
106
- return null;
32
+ const response = await axios.get(this.basePath + '/api/session-auth')
33
+ sessionStorage.setItem("auth-token",response?.data?.token);
34
+ return response?.data?.token;
107
35
  }
108
36
 
109
37
  try {
@@ -111,121 +39,61 @@ class FormioHelper {
111
39
  if (typeof parsedToken === "string") {
112
40
  return parsedToken;
113
41
  }
114
-
115
- return parsedToken && parsedToken.value ? parsedToken.value : null;
42
+ return parsedToken?.value || null;
116
43
  } catch (error) {
117
44
  return rawToken;
118
45
  }
119
46
  }
120
47
 
121
- getBaseUrl() {
122
- if (typeof this.options.getBaseUrl === "function") {
123
- return this.options.getBaseUrl();
124
- }
125
-
126
- const optionBaseUrl = this.resolveOption("baseUrl");
127
- if (optionBaseUrl) {
128
- return optionBaseUrl;
129
- }
130
-
131
- const win = this.getWindow();
132
- if (win && win.BASE_URL) {
133
- return win.BASE_URL;
134
- }
135
-
136
- if (win && win.location && win.location.origin && win.location.pathname) {
137
- const explodedPath = win.location.pathname.split("/");
138
- return `${win.location.origin}/${explodedPath[1]}`;
139
- }
140
-
141
- return null;
142
- }
143
-
144
- getSiteUrl() {
145
- if (typeof this.options.getSiteUrl === "function") {
146
- return this.options.getSiteUrl();
147
- }
148
-
149
- const optionSiteUrl = this.resolveOption("siteUrl");
150
- if (optionSiteUrl) {
151
- return optionSiteUrl;
152
- }
153
-
154
- const win = this.getWindow();
155
- if (win && win.SITE_URL) {
156
- return win.SITE_URL;
157
- }
158
-
159
- return null;
160
- }
161
-
162
- buildApiUrl(endPoint = "") {
163
- const baseUrl = this.getBaseUrl();
164
- if (!baseUrl) {
165
- throw new Error("Missing baseUrl. Pass { baseUrl } to FormioHelper.");
166
- }
167
-
168
- const normalizedBaseUrl = baseUrl.replace(/\/$/, "");
169
- const normalizedEndpoint = endPoint.toString().replace(/^\/+/, "");
170
- return `${normalizedBaseUrl}/api/${normalizedEndpoint}`;
171
- }
172
-
173
48
  async getTenantInfo() {
174
- const response = await this.httpClient.get(this.buildApiUrl("tenants/info"), {
49
+ const response = await axios.get(this.basePath + '/api/tenants/info', {
175
50
  headers: {
176
- "x-locale": this.getCurrentLocale(),
51
+ "x-locale": this.getCurrentLocale()
177
52
  },
178
- });
53
+ });
54
+ return response.data
55
+ }
179
56
 
180
- return response.data;
57
+ getBaseUrl() {
58
+ return baseUrl() || window.BASE_URL;
181
59
  }
182
60
 
183
61
  async authenticatedCall(endPoint) {
184
- const token = this.getCurrentToken();
185
- if (!token) {
186
- return;
62
+ if(this.token){
63
+ const response = await axios.get(this.basePath + '/api/' + endPoint, {
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ "Authorization": "Bearer " + this.token
67
+ }
68
+ })
69
+ return response.data
187
70
  }
188
-
189
- const response = await this.httpClient.get(this.buildApiUrl(endPoint), {
190
- headers: {
191
- "Content-Type": "application/json",
192
- Authorization: `Bearer ${token}`,
193
- },
194
- });
195
-
196
- return response.data;
197
71
  }
198
72
 
199
- async authenticatedPOSTCall(endPoint, params) {
200
- const token = this.getCurrentToken();
201
- if (!token) {
202
- return;
203
- }
204
-
205
- const response = await this.httpClient.post(
206
- this.buildApiUrl(endPoint),
207
- JSON.stringify(params),
208
- {
73
+ async authenticatedPOSTCall(endPoint,params) {
74
+ if(this.token){
75
+ const response = await axios.post(this.basePath + '/api/' + endPoint, JSON.stringify(params),{
209
76
  headers: {
210
77
  "Content-Type": "application/json",
211
- Authorization: `Bearer ${token}`,
212
- },
213
- },
214
- );
215
-
216
- return response.data;
78
+ "Authorization": "Bearer " + this.token
79
+ }
80
+ })
81
+ return response.data
82
+ }
217
83
  }
218
84
 
219
- async authenticatedRequest(method, endPoint, params = {}) {
85
+ async authenticatedRequest(method, endPoint, params = {}) {
220
86
  const token = this.getCurrentToken();
221
87
  if (!token) {
222
88
  return;
223
89
  }
224
90
 
225
91
  try {
226
- const response = await this.httpClient({
92
+ const url = `${this.getBaseUrl()}/api/${endPoint}`;
93
+
94
+ const response = await axios({
227
95
  method,
228
- url: this.buildApiUrl(endPoint),
96
+ url,
229
97
  data: params,
230
98
  headers: {
231
99
  "Content-Type": "application/json",
@@ -235,122 +103,89 @@ class FormioHelper {
235
103
 
236
104
  return response.data;
237
105
  } catch (error) {
238
- this.logError(`Error on ${method.toUpperCase()} ${endPoint}:`, error);
106
+ console.error(`Error on ${method.toUpperCase()} ${endPoint}:`, error);
239
107
  throw error;
240
108
  }
241
109
  }
242
110
 
243
- async postGraphql(url, method = "post", payload) {
111
+ async getRemoteJson(url, method = 'get', headers = null) {
112
+ let config = {};
113
+ if (headers) {
114
+ config = {
115
+ headers: headers
116
+ }
117
+ }
118
+ const response = await axios({
119
+ method: method,
120
+ url: url,
121
+ params: config
122
+ });
123
+ return response.data
124
+ }
125
+
126
+ async postGraphql(url, method = 'post',payload) {
244
127
  const graphqlQuery = {
245
- operationName: "fetchList",
246
- query: `${payload}`,
247
- variables: {},
128
+ "operationName": "fetchList",
129
+ "query": `${payload}`,
130
+ "variables": {}
248
131
  };
249
-
250
- const response = await this.httpClient({
251
- url,
252
- method,
132
+ const response = await axios({
133
+ url: url,
134
+ method: 'post',
253
135
  headers: {
254
136
  "Content-Type": "application/json",
255
137
  },
256
- data: graphqlQuery,
257
- });
258
-
259
- return response.data;
260
- }
261
-
262
- async getRemoteJson(url, method = "get", headers = null) {
263
- const requestConfig = {
264
- method,
265
- url,
266
- };
267
-
268
- if (headers) {
269
- requestConfig.headers = headers;
138
+ data: graphqlQuery
270
139
  }
271
-
272
- const response = await this.httpClient(requestConfig);
273
- return response.data;
140
+ );
141
+ return response.data
274
142
  }
275
143
 
276
144
  async anonymousCall(endPoint) {
277
- const response = await this.httpClient.get(this.buildApiUrl(endPoint), {
145
+ const response = await axios.get(this.basePath + '/api/' + endPoint, {
278
146
  headers: {
279
- "Content-Type": "application/json",
280
- },
281
- });
282
-
283
- return response.data;
147
+ "Content-Type": "application/json"
148
+ }
149
+ })
150
+ return response.data
284
151
  }
285
152
 
286
153
  // See Doc {@link https://gitlab.com/opencity-labs/area-personale/core/-/wikis/Guida-alla-creazione-dei-moduli/Form.io-Sdk#esempio-recupero-dato-dai-meta}
287
- async getFieldMeta(getParams) {
288
- try {
289
- const result = await this.getTenantInfo();
290
- const rawMeta = Array.isArray(result && result.meta) ? result.meta[0] : null;
291
- if (!rawMeta) {
292
- return null;
293
- }
294
-
295
- const meta = JSON.parse(rawMeta);
296
- if (!meta) {
297
- return null;
298
- }
299
-
300
- if (getParams) {
301
- return get(meta, getParams, false);
154
+ getFieldMeta(getParams){
155
+ this.getTenantInfo().then(result => {
156
+ const meta = JSON.parse(result.meta[0]) || null
157
+ if(meta){
158
+ if(getParams){
159
+ return get(meta, getParams, false);
160
+ }else{
161
+ return meta
162
+ }
302
163
  }
303
-
304
- return meta;
305
- } catch (error) {
306
- this.logError("error getFieldMeta", error);
307
- return null;
308
- }
164
+ }).catch(e => {
165
+ console.error('error getFieldMeta',e)
166
+ })
309
167
  }
310
168
 
311
- readApplicationIdFromDom() {
312
- const doc = this.getDocument();
313
- if (!doc) {
314
- return null;
315
- }
316
169
 
317
- const formioElement = doc.querySelector("#formio");
318
- return formioElement && formioElement.dataset
319
- ? formioElement.dataset.applicationId || null
320
- : null;
321
- }
322
-
323
- async getFieldApplication(getParams, applicationId = null) {
324
- const resolvedApplicationId =
325
- applicationId ||
326
- this.resolveOption("applicationId") ||
327
- this.readApplicationIdFromDom();
170
+ getFieldApplication(getParams) {
328
171
 
329
- if (!resolvedApplicationId) {
330
- this.logWarn("No applicationId provided to getFieldApplication");
331
- return null;
332
- }
333
-
334
- try {
335
- const result = await this.authenticatedCall(
336
- `applications/${resolvedApplicationId}`,
337
- );
172
+ const formioElement = document.querySelector("#formio");
173
+ const applicationId = formioElement.dataset.applicationId;
338
174
 
175
+ return this.authenticatedCall('applications/' + applicationId).then(result => {
339
176
  if (result && getParams) {
340
- return get(result, getParams);
177
+ return get(result, getParams);
178
+ } else {
179
+ return result
341
180
  }
342
-
343
- return result;
344
- } catch (error) {
345
- this.logError("error getFieldApplication", error);
346
- return null;
347
- }
181
+ }).catch(e => {
182
+ console.error('error getFieldApplication', e)
183
+ })
348
184
  }
349
185
 
350
- addLimitParam(url, limit) {
351
- const origin = this.resolveOption("origin") || this.getWindow()?.location?.origin;
352
- const parsedUrl = origin ? new URL(url, origin) : new URL(url);
353
- parsedUrl.searchParams.set("limit", String(limit));
186
+ addLimitParam(url, limit) {
187
+ const parsedUrl = new URL(url, window.location.origin);
188
+ parsedUrl.searchParams.set("limit", limit);
354
189
  return parsedUrl.toString();
355
190
  }
356
191
 
@@ -360,19 +195,18 @@ class FormioHelper {
360
195
 
361
196
  try {
362
197
  while (nextUrl) {
363
- const response = await this.httpClient.get(nextUrl);
198
+ const response = await axios.get(nextUrl);
364
199
  const json = response.data;
365
-
366
- if (Array.isArray(json && json.items)) {
200
+ if (Array.isArray(json.items)) {
367
201
  allData.push(...json.items);
368
202
  }
369
203
 
370
- nextUrl = json && json.next ? json.next : null;
204
+ nextUrl = json?.next || null;
371
205
  }
372
206
 
373
207
  return allData;
374
208
  } catch (error) {
375
- this.logError(
209
+ console.error(
376
210
  "Errore durante il recupero delle disponibilita complete:",
377
211
  error,
378
212
  );
@@ -386,19 +220,19 @@ class FormioHelper {
386
220
 
387
221
  try {
388
222
  while (nextUrl) {
389
- const response = await this.httpClient.get(nextUrl);
223
+ const response = await axios.get(nextUrl);
390
224
  const json = response.data;
391
225
 
392
- if (Array.isArray(json && json.data)) {
226
+ if (Array.isArray(json.data)) {
393
227
  allData.push(...json.data);
394
228
  }
395
229
 
396
- nextUrl = json && json.next ? json.next : null;
230
+ nextUrl = json?.next || null;
397
231
  }
398
232
 
399
233
  return allData;
400
234
  } catch (error) {
401
- this.logError(
235
+ console.error(
402
236
  "Errore durante il recupero delle disponibilita complete:",
403
237
  error,
404
238
  );
@@ -408,14 +242,14 @@ class FormioHelper {
408
242
 
409
243
  async getBookingConfig(id = null) {
410
244
  try {
411
- let siteUrl = this.getSiteUrl();
245
+ let siteUrl = window.SITE_URL;
412
246
  if (!siteUrl) {
413
247
  const tenantInfo = await this.getTenantInfo();
414
- siteUrl = tenantInfo && tenantInfo.site_url ? tenantInfo.site_url : null;
248
+ siteUrl = tenantInfo?.site_url || null;
415
249
  }
416
250
 
417
251
  if (!siteUrl) {
418
- this.logWarn("Nessun site_url trovato, impossibile proseguire.");
252
+ console.warn("Nessun site_url trovato, impossibile proseguire.");
419
253
  return null;
420
254
  }
421
255
 
@@ -426,7 +260,7 @@ class FormioHelper {
426
260
  const response = await this.fetchBookingUrl(apiUrl);
427
261
  return response;
428
262
  } catch (error) {
429
- this.logError("Errore in getBookingConfig:", error);
263
+ console.error("Errore in getBookingConfig:", error);
430
264
  return null;
431
265
  }
432
266
  }
@@ -434,11 +268,8 @@ class FormioHelper {
434
268
  async getRatesLists(url, calendarId) {
435
269
  const tenant = await this.getTenantInfo();
436
270
 
437
- if (tenant && tenant.id) {
438
- return this.postGraphql(
439
- url,
440
- "POST",
441
- `query fetchList {
271
+ if(tenant.id){
272
+ return this.postGraphql(url,'POST', `query fetchList {
442
273
  rooms(filter: {id:{ _eq: "${calendarId}"},tenant:{id:{_eq:"${tenant.id}"}}}) {
443
274
  id
444
275
  title
@@ -455,37 +286,34 @@ class FormioHelper {
455
286
  hours_upper_limit
456
287
  }
457
288
  }
458
- }}`,
459
- )
460
- .then((result) => {
461
- return result;
462
- })
463
- .catch((error) => {
464
- this.logError("error getRatesLists", error);
465
- return null;
466
- });
289
+ }}`).then(result => {
290
+ return result
291
+ }).catch(e => {
292
+ console.error('error getRatesLists', e)
293
+ })
467
294
  }
468
295
 
469
- return null;
470
296
  }
471
297
 
472
298
  async editFormProperties(instance, edits) {
473
299
  if (!instance || typeof instance.getComponent !== "function") {
474
- this.logError("[editFormProperties] Invalid instance:", instance);
300
+ console.error("[editFormProperties] Invalid instance:", instance);
475
301
  return;
476
302
  }
477
303
 
478
304
  for (const [fullPath, changes] of Object.entries(edits)) {
479
305
  const pathParts = fullPath.split(".");
480
- const fieldKey = pathParts.pop();
306
+ const fieldKey = pathParts.pop(); // Last part is the actual field name
307
+
481
308
  let currentInstance = instance;
482
309
 
310
+ // Traverse nested subforms following the path
483
311
  for (const part of pathParts) {
484
312
  let comp;
485
313
  try {
486
314
  comp = currentInstance.getComponent(part);
487
- } catch (error) {
488
- this.logError("[editFormProperties:getComponent - nested]", part, error);
315
+ } catch (err) {
316
+ console.error("[editFormProperties:getComponent - nested]", part, err);
489
317
  comp = null;
490
318
  }
491
319
 
@@ -494,16 +322,18 @@ class FormioHelper {
494
322
  break;
495
323
  }
496
324
 
325
+ // Wait for subForm to load if needed
497
326
  if (!comp.subForm) {
498
327
  currentInstance = null;
499
328
  break;
500
329
  }
501
330
 
331
+ // If subForm is asynchronous, wait for it
502
332
  if (typeof comp.subForm.ready === "function") {
503
333
  try {
504
334
  await comp.subForm.ready;
505
- } catch (error) {
506
- this.logError("[editFormProperties] subForm.ready failed:", part, error);
335
+ } catch (err) {
336
+ console.error("[editFormProperties] subForm.ready failed:", part, err);
507
337
  currentInstance = null;
508
338
  break;
509
339
  }
@@ -516,11 +346,12 @@ class FormioHelper {
516
346
  continue;
517
347
  }
518
348
 
349
+ // Now edit the final field
519
350
  let comp;
520
351
  try {
521
352
  comp = currentInstance.getComponent(fieldKey);
522
- } catch (error) {
523
- this.logError("[editFormProperties:getComponent - field]", fieldKey, error);
353
+ } catch (err) {
354
+ console.error("[editFormProperties:getComponent - field]", fieldKey, err);
524
355
  continue;
525
356
  }
526
357
 
@@ -533,10 +364,8 @@ class FormioHelper {
533
364
  const parts = propPath.split(".");
534
365
  let target = comp.component;
535
366
 
536
- for (let i = 0; i < parts.length - 1; i += 1) {
537
- if (!target[parts[i]]) {
538
- target[parts[i]] = {};
539
- }
367
+ for (let i = 0; i < parts.length - 1; i++) {
368
+ if (!target[parts[i]]) target[parts[i]] = {};
540
369
  target = target[parts[i]];
541
370
  }
542
371
 
@@ -544,31 +373,26 @@ class FormioHelper {
544
373
  if (last === "hidden") {
545
374
  comp._hasCondition = newVal ? false : true;
546
375
  }
547
-
548
376
  if (target[last] !== newVal) {
549
377
  target[last] = newVal;
550
378
 
551
379
  if (typeof comp.redraw === "function") {
552
380
  try {
553
- comp.redraw();
554
- } catch (error) {
555
- this.logError("[editFormProperties:redraw]", fullPath, propPath, error);
381
+ comp.redraw();
382
+ } catch (err) {
383
+ console.error("[editFormProperties:redraw]", fullPath, propPath, err);
556
384
  }
557
385
  }
558
386
  }
559
- } catch (error) {
560
- this.logError(
561
- "[editFormProperties:property assignment]",
562
- fullPath,
563
- propPath,
564
- error,
565
- );
387
+ } catch (err) {
388
+ console.error("[editFormProperties:property assignment]", fullPath, propPath, err);
566
389
  }
567
390
  }
568
391
  }
569
392
  }
570
393
 
571
394
  checkResidences(data, residenceFields, requireAllResidences = false) {
395
+ // Guards
572
396
  if (!data) {
573
397
  throw new Error("[checkResidences] Data object is missing.");
574
398
  }
@@ -580,74 +404,82 @@ class FormioHelper {
580
404
  const tenantName = data.residence_tenant.toLowerCase();
581
405
  const residenceMatchFn = requireAllResidences ? "every" : "some";
582
406
 
583
- const isLocationInTenant = residenceFields[residenceMatchFn]((path) => {
407
+ // Check if any/all locality fields match the tenant name
408
+ const isLocationInTenant = residenceFields[residenceMatchFn](path => {
584
409
  const locality = (get(data, path, "") || "").toLowerCase().trim();
585
410
  return locality !== "" && tenantName.includes(locality);
586
411
  });
587
412
 
413
+ // Fields that represent country information
588
414
  const COUNTRY_FIELDS = ["address_country", "country"];
589
415
 
590
- const hasEmptyCountry = residenceFields.every((config) => {
416
+ // Check if all country fields are empty for each residence
417
+ const hasEmptyCountry = residenceFields.every(config => {
591
418
  const basePath = config.split(".").slice(0, -1).join(".");
592
- return COUNTRY_FIELDS.every((field) => {
419
+ return COUNTRY_FIELDS.every(field => {
593
420
  const value = get(data, `${basePath}.${field}`, "");
594
421
  return typeof value === "string" && value.trim() === "";
595
422
  });
596
423
  });
597
424
 
425
+ // Final visibility logic
598
426
  return isLocationInTenant ? false : !hasEmptyCountry;
599
427
  }
600
428
 
601
429
  syncApplicantToBeneficiary(data, instance, applicantRequester) {
430
+ // Guards
602
431
  if (!data) {
603
432
  throw new Error("[syncApplicantToBeneficiary] Data object is missing.");
604
433
  }
605
434
 
606
435
  if (!instance || typeof instance.getComponent !== "function") {
607
- this.logError("[syncApplicantToBeneficiary] Invalid instance:", instance);
436
+ console.error("[syncApplicantToBeneficiary] Invalid instance:", instance);
608
437
  return;
609
438
  }
610
439
 
440
+ // Inline hash calculation
611
441
  const jsonString = JSON.stringify(data.applicant);
612
442
  let hash = 0;
613
- for (let i = 0; i < jsonString.length; i += 1) {
443
+ for (let i = 0; i < jsonString.length; i++) {
614
444
  const char = jsonString.charCodeAt(i);
615
445
  hash = (hash << 5) - hash + char;
616
- hash &= hash;
446
+ hash = hash & hash; // Convert to 32-bit integer
617
447
  }
618
448
  hash = hash.toString(16);
619
449
 
620
450
  if (applicantRequester && hash !== data.applicant_hash) {
621
- const sub = Object.assign({}, instance.calculatedValue);
451
+
452
+ let sub = Object.assign({}, instance.calculatedValue);
622
453
 
623
454
  sub.data.given_name = data.applicant.data.completename.data.name;
624
455
  sub.data.family_name = data.applicant.data.completename.data.surname;
625
456
 
626
- if (data.applicant.data.Born && data.applicant.data.Born.data) {
457
+ if (data.applicant.data.Born?.data) {
627
458
  sub.data.birth_place = data.applicant.data.Born.data.place_of_birth;
628
459
  sub.data.birth_date = data.applicant.data.Born.data.natoAIl;
629
460
  }
630
461
 
631
- if (data.applicant.data.gender && data.applicant.data.gender.data) {
462
+ if (data.applicant.data.gender?.data) {
632
463
  sub.data.gender = data.applicant.data.gender.data.gender;
633
464
  }
634
465
 
635
- if (data.applicant.data.fiscal_code && data.applicant.data.fiscal_code.data) {
466
+ if (data.applicant.data.fiscal_code?.data) {
636
467
  sub.data.tax_id = data.applicant.data.fiscal_code.data.fiscal_code;
637
468
  }
638
469
 
639
- if (data.applicant.data.address && data.applicant.data.address.data) {
640
- if (!sub.data.address) {
641
- sub.data.address = { data: {} };
642
- }
470
+ if (data.applicant.data.address?.data) {
471
+ if (!sub.data.address) sub.data.address = { data: {} };
643
472
 
644
- sub.data.address.data.street_address = data.applicant.data.address.data.address;
473
+ sub.data.address.data.street_address =
474
+ data.applicant.data.address.data.address;
645
475
  sub.data.address.data.address_number =
646
476
  data.applicant.data.address.data.house_number;
647
477
  sub.data.address.data.address_locality =
648
478
  data.applicant.data.address.data.municipality;
649
- sub.data.address.data.postal_code = data.applicant.data.address.data.postal_code;
650
- sub.data.address.data.address_country = data.applicant.data.address.data.country;
479
+ sub.data.address.data.postal_code =
480
+ data.applicant.data.address.data.postal_code;
481
+ sub.data.address.data.address_country =
482
+ data.applicant.data.address.data.country;
651
483
  }
652
484
 
653
485
  sub.data.nationality = data.beneficiary.data.nationality;
@@ -655,11 +487,62 @@ class FormioHelper {
655
487
 
656
488
  instance.setValue(sub);
657
489
  data.applicant_hash = hash;
490
+
658
491
  } else if (!applicantRequester && data.applicant_hash !== "") {
659
492
  instance.setValue(instance.defaultValue);
660
493
  data.applicant_hash = "";
661
494
  }
662
495
  }
496
+
497
+ isOperator() {
498
+ try {
499
+ const rawSessionToken = window.sessionStorage.getItem('auth-token');
500
+ if (!rawSessionToken) {
501
+ return false;
502
+ }
503
+
504
+ const parsedSessionToken = JSON.parse(rawSessionToken);
505
+ const token = parsedSessionToken?.value || null;
506
+ if (!token) {
507
+ return false;
508
+ }
509
+
510
+ const decodedToken = jwtDecode(token);
511
+ const roles = Array.isArray(decodedToken?.roles) ? decodedToken.roles : [];
512
+
513
+ return roles.some(role => ['ROLE_OPERATORE', 'ROLE_MANAGER'].includes(role));
514
+ } catch (e) {
515
+ console.error('[FormIoHelper:isOperator]', e)
516
+ return false;
517
+ }
518
+ }
519
+
520
+ isUser() {
521
+ try {
522
+ const rawSessionToken = window.sessionStorage.getItem('auth-token');
523
+ if (!rawSessionToken) {
524
+ return false;
525
+ }
526
+
527
+ const parsedSessionToken = JSON.parse(rawSessionToken);
528
+ const token = parsedSessionToken?.value || null;
529
+ if (!token) {
530
+ return false;
531
+ }
532
+
533
+ const decodedToken = jwtDecode(token);
534
+ const roles = Array.isArray(decodedToken?.roles) ? decodedToken.roles : [];
535
+ const isOperatorOrManager = roles.some(role =>
536
+ ['ROLE_OPERATORE', 'ROLE_MANAGER'].includes(role)
537
+ );
538
+
539
+ return roles.length > 0 && !isOperatorOrManager;
540
+ } catch (e) {
541
+ console.error('[FormIoHelper:isUser]', e)
542
+ return false;
543
+ }
544
+ }
545
+
663
546
  }
664
547
 
665
548
  function createFormioHelper(options = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opencitylabs/formio-sdk",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Node/browser SDK helper for Form.io APIs",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -22,7 +22,9 @@
22
22
  "author": "OpencityLabs",
23
23
  "license": "ISC",
24
24
  "dependencies": {
25
- "axios": "^1.13.5",
26
- "lodash.get": "^4.4.2"
25
+ "axios": "^1.13.6",
26
+ "jwt-decode": "^4.0.0",
27
+ "lodash.get": "^4.4.2",
28
+ "sweetalert2": "^11.26.21"
27
29
  }
28
- }
30
+ }