hl-core 0.0.7-beta.0 → 0.0.7-beta.2

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.
@@ -2,14 +2,26 @@ import { defineStore } from 'pinia';
2
2
  import { t } from './messages';
3
3
  import { rules } from './rules';
4
4
  import { Toast, Types, Positions, ToastOptions } from './toast';
5
+ import { isValidGUID } from '../composables';
6
+ import { DataStoreClass, Contragent } from '../composables/classes';
7
+ import { ApiClass } from '@/api';
5
8
 
6
9
  export const useDataStore = defineStore('data', {
7
10
  state: () => ({
11
+ ...new DataStoreClass(),
8
12
  t: t,
9
13
  rules: rules,
10
14
  toast: Toast,
11
15
  toastTypes: Types,
12
16
  toastPositions: Positions,
17
+ isValidGUID: isValidGUID,
18
+ router: useRouter(),
19
+ contragent: useContragentStore(),
20
+ api: new ApiClass(),
21
+ currentDate: () =>
22
+ new Date(Date.now() - new Date().getTimezoneOffset() * 60 * 1000)
23
+ .toISOString()
24
+ .slice(0, -1),
13
25
  showToaster: (type, msg, timeout) =>
14
26
  Toast.useToast()(msg, {
15
27
  ...ToastOptions,
@@ -21,8 +33,1119 @@ export const useDataStore = defineStore('data', {
21
33
  }),
22
34
  }),
23
35
  actions: {
24
- async loginUser(...data) {
25
- console.log(...data);
36
+ async getNewAccessToken() {
37
+ try {
38
+ const data = {
39
+ accessToken: JSON.parse(localStorage.getItem('accessToken')),
40
+ refreshToken: JSON.parse(localStorage.getItem('refreshToken')),
41
+ };
42
+ const response = await this.api.getNewAccessToken(data);
43
+ this.accessToken = response.accessToken;
44
+ this.refreshToken = response.refreshToken;
45
+ localStorage.setItem('accessToken', JSON.stringify(this.accessToken));
46
+ localStorage.setItem('refreshToken', JSON.stringify(this.refreshToken));
47
+ } catch (err) {
48
+ console.error(err);
49
+ }
50
+ },
51
+ async getDictionaryItems(dictName) {
52
+ try {
53
+ this.isLoading = true;
54
+ if (!this[`${dictName}List`].length) {
55
+ this[`${dictName}List`] = await this.api.getDictionaryItems(dictName);
56
+ }
57
+ } catch (err) {
58
+ console.log(err);
59
+ } finally {
60
+ this.isLoading = false;
61
+ }
62
+ },
63
+ async loginUser(login, password, numAttempt) {
64
+ try {
65
+ const token = JSON.parse(localStorage.getItem('accessToken'));
66
+
67
+ if (token && isValidToken(token)) {
68
+ this.accessToken = token;
69
+ this.getUserRoles();
70
+ } else {
71
+ const response = await this.api.loginUser({
72
+ login: login,
73
+ password: password,
74
+ numAttempt: numAttempt,
75
+ });
76
+
77
+ this.accessToken = response.accessToken;
78
+ this.refreshToken = response.refreshToken;
79
+ this.getUserRoles();
80
+ }
81
+ if (
82
+ this.isManager() ||
83
+ this.isUnderwriter() ||
84
+ this.isAdmin() ||
85
+ this.isAgent() ||
86
+ this.isCompliance() ||
87
+ this.isAgentMycar() ||
88
+ this.isAnalyst() ||
89
+ this.isUpk()
90
+ ) {
91
+ localStorage.setItem('accessToken', JSON.stringify(this.accessToken));
92
+ localStorage.setItem(
93
+ 'refreshToken',
94
+ JSON.stringify(this.refreshToken),
95
+ );
96
+ } else {
97
+ this.showToaster(
98
+ 'error',
99
+ this.t('toaster.noProductPermission'),
100
+ 5000,
101
+ );
102
+ }
103
+ } catch (err) {
104
+ console.log(err);
105
+ if ('response' in err) {
106
+ this.showToaster('error', err.response.data, 3000);
107
+ }
108
+ }
109
+ },
110
+ getUserRoles() {
111
+ if (this.accessToken && this.user.roles.length === 0) {
112
+ const decoded = jwtDecode(this.accessToken);
113
+ this.user.id = decoded.sub;
114
+ this.user.fullName = `${decoded.lastName} ${decoded.firstName} ${
115
+ decoded.middleName ? decoded.middleName : ''
116
+ }`;
117
+ const key = getKeyWithPattern(decoded, 'role');
118
+ if (key) {
119
+ const roles = decoded[key];
120
+ if (typeof roles === constants.types.string) {
121
+ this.user.roles.push(roles);
122
+ } else if (typeof roles === constants.types.array) {
123
+ this.user.roles = roles;
124
+ }
125
+ }
126
+ }
127
+ },
128
+ isRole(whichRole) {
129
+ if (this.user.roles.length === 0) {
130
+ this.getUserRoles();
131
+ }
132
+ const isRole = this.user.roles.find(i => i === whichRole);
133
+ return !!isRole;
134
+ },
135
+ isInitiator() {
136
+ return (
137
+ this.isRole(constants.roles.manager) ||
138
+ this.isRole(constants.roles.agent) ||
139
+ this.isRole(constants.roles.agentMycar)
140
+ );
141
+ },
142
+ isManager() {
143
+ return this.isRole(constants.roles.manager);
144
+ },
145
+ isCompliance() {
146
+ return this.isRole(constants.roles.compliance);
147
+ },
148
+ isAdmin() {
149
+ return this.isRole(constants.roles.admin);
150
+ },
151
+ isAgent() {
152
+ return this.isRole(constants.roles.agent);
153
+ },
154
+ isUnderwriter() {
155
+ return this.isRole(constants.roles.underwriter);
156
+ },
157
+ isAgentMycar() {
158
+ return this.isRole(constants.roles.agentMycar);
159
+ },
160
+ isAnalyst() {
161
+ return this.isRole(constants.roles.analyst);
162
+ },
163
+ isUpk() {
164
+ return this.isRole(constants.roles.upk);
165
+ },
166
+ isProcessEditable(statusCode) {
167
+ return !!constants.editableStatuses.find(status => status === statusCode);
168
+ },
169
+ async logoutUser() {
170
+ this.isLoading = true;
171
+ try {
172
+ const token = JSON.parse(localStorage.getItem('accessToken'));
173
+ if (token) {
174
+ this.$reset();
175
+ localStorage.clear();
176
+ }
177
+ await this.router.push({ name: 'Auth' });
178
+ } catch (err) {
179
+ console.log(err);
180
+ }
181
+ this.isLoading = false;
182
+ },
183
+ async getFile(file, mode = 'view', fileType = 'pdf') {
184
+ try {
185
+ this.isLoading = true;
186
+ await this.api.getFile(file.id).then(response => {
187
+ if (!['pdf', 'docx'].includes(fileType)) {
188
+ const blob = new Blob([response], { type: `image/${fileType}` });
189
+ const url = window.URL.createObjectURL(blob);
190
+ window.open(
191
+ url,
192
+ '_blank',
193
+ `width=${screen.width},height=${screen.height},top=70`,
194
+ );
195
+ } else {
196
+ const blob = new Blob([response], {
197
+ type: `application/${fileType}`,
198
+ });
199
+ const url = window.URL.createObjectURL(blob);
200
+ const link = document.createElement('a');
201
+ link.href = url;
202
+ if (mode === 'view') {
203
+ setTimeout(() => {
204
+ window.open(url, '_blank', `right=100`);
205
+ });
206
+ } else {
207
+ link.setAttribute('download', file.fileName);
208
+ document.body.appendChild(link);
209
+ link.click();
210
+ }
211
+ }
212
+ });
213
+ } catch (err) {
214
+ this.showToaster('error', err.response.data, 5000);
215
+ } finally {
216
+ this.isLoading = false;
217
+ }
218
+ },
219
+ async getDicFileTypeList() {
220
+ try {
221
+ if (this.dicFileTypeList.length) {
222
+ return this.dicFileTypeList;
223
+ } else {
224
+ this.dicFileTypeList = await this.api.getDicFileTypeList();
225
+ return this.dicFileTypeList;
226
+ }
227
+ } catch (err) {
228
+ console.log(err.response.data);
229
+ }
230
+ },
231
+ async getContragentById(id, onlyGet = true) {
232
+ if (onlyGet) {
233
+ this.isLoading = true;
234
+ }
235
+ try {
236
+ const response = await this.api.getContragentById(id);
237
+ if (response.totalItems > 0) {
238
+ await this.serializeContragentData(response.items[0]);
239
+ } else {
240
+ this.isLoading = false;
241
+ return false;
242
+ }
243
+ } catch (err) {
244
+ console.log(err);
245
+ }
246
+ if (onlyGet) {
247
+ this.isLoading = false;
248
+ }
249
+ },
250
+ async serializeContragentData(contragent) {
251
+ const [
252
+ { value: data },
253
+ { value: contacts },
254
+ { value: documents },
255
+ { value: address },
256
+ ] = await Promise.allSettled([
257
+ this.api.getContrAgentData(contragent.id),
258
+ this.api.getContrAgentContacts(contragent.id),
259
+ this.api.getContrAgentDocuments(contragent.id),
260
+ this.api.getContrAgentAddress(contragent.id),
261
+ ]);
262
+ this.contragent.response = {
263
+ contragent: contragent,
264
+ };
265
+ if (data && data.length) {
266
+ this.contragent.response.questionnaires = data;
267
+ }
268
+ if (contacts && contacts.length) {
269
+ this.contragent.response.contacts = contacts;
270
+ }
271
+ if (documents && documents.length) {
272
+ this.contragent.response.documents = documents;
273
+ }
274
+ if (address && address.length) {
275
+ this.contragent.response.addresses = address;
276
+ }
277
+ this.parseContragent({
278
+ personalData: contragent,
279
+ documents: documents,
280
+ contacts: contacts,
281
+ data: data,
282
+ address: address,
283
+ });
284
+ },
285
+ async searchContragent(iin) {
286
+ this.isLoading = true;
287
+ try {
288
+ let queryData = {
289
+ iin: iin.replace(/-/g, ''),
290
+ firstName: '',
291
+ lastName: '',
292
+ middleName: '',
293
+ };
294
+ const response = await this.api.getContragent(queryData);
295
+ if (response.totalItems > 0) {
296
+ this.contragentList = response.items;
297
+ } else {
298
+ this.contragentList = [];
299
+ }
300
+ } catch (err) {
301
+ console.log(err);
302
+ this.contragentList = [];
303
+ }
304
+ this.isLoading = false;
305
+ },
306
+ parseContragent(user) {
307
+ this.contragent.verifyType = user.personalData.verifyType;
308
+ this.contragent.verifyDate = user.personalData.verifyDate;
309
+ this.contragent.iin = reformatIin(user.personalData.iin);
310
+ this.contragent.age = user.personalData.age;
311
+ const country = this.countries.find(i =>
312
+ i.nameRu?.match(new RegExp(user.personalData.birthPlace, 'i')),
313
+ );
314
+ this.contragent.birthPlace =
315
+ country && Object.keys(country).length ? country : new Value();
316
+ this.contragent.gender = this.gender.find(
317
+ i => i.nameRu === user.personalData.genderName,
318
+ );
319
+ this.contragent.gender.id = user.personalData.gender;
320
+ this.contragent.birthDate = reformatDate(user.personalData.birthDate);
321
+ this.contragent.genderName = user.personalData.genderName;
322
+ this.contragent.lastName = user.personalData.lastName;
323
+ this.contragent.longName = user.personalData.longName;
324
+ this.contragent.middleName = user.personalData.middleName
325
+ ? user.personalData.middleName
326
+ : '';
327
+ this.contragent.firstName = user.personalData.firstName;
328
+ this.contragent.id = user.personalData.id;
329
+ this.contragent.type = user.personalData.type;
330
+ this.contragent.registrationDate = user.personalData.registrationDate;
331
+
332
+ if ('documents' in user && user.documents.length) {
333
+ const documentType = this.documentTypes.find(
334
+ i => i.ids === user.documents[0].type,
335
+ );
336
+ const documentIssuer = this.documentIssuers.find(
337
+ i => i.nameRu === user.documents[0].issuerNameRu,
338
+ );
339
+ this.contragent.documentType = documentType
340
+ ? documentType
341
+ : new Value();
342
+ this.contragent.documentNumber = user.documents[0].number;
343
+ this.contragent.documentIssuers = documentIssuer
344
+ ? documentIssuer
345
+ : new Value();
346
+ this.contragent.documentDate = reformatDate(
347
+ user.documents[0].issueDate,
348
+ );
349
+ this.contragent.documentExpire = reformatDate(
350
+ user.documents[0].expireDate,
351
+ );
352
+ }
353
+
354
+ if ('data' in user && user.data.length) {
355
+ user.data.forEach(dataObject => {
356
+ this.searchFromList(
357
+ [
358
+ 'signOfResidency',
359
+ 'countryOfCitizenship',
360
+ 'countryOfTaxResidency',
361
+ 'economySectorCode',
362
+ ],
363
+ dataObject,
364
+ [
365
+ this.residents,
366
+ this.citizenshipCountries,
367
+ this.taxCountries,
368
+ this.economySectorCode,
369
+ ],
370
+ );
371
+ });
372
+ }
373
+
374
+ if ('address' in user && user.address.length) {
375
+ const country = this.countries.find(i =>
376
+ i.nameRu?.match(new RegExp(user.address.countryName, 'i')),
377
+ );
378
+ const province = this.states.find(
379
+ i => i.ids === user.address[0].stateCode,
380
+ );
381
+ const localityType = this.localityTypes.find(
382
+ i => i.nameRu === user.address[0].cityTypeName,
383
+ );
384
+ const city = this.cities.find(
385
+ i => i.nameRu === user.address[0].cityName.replace('г.', ''),
386
+ );
387
+ const region = this.regions.find(
388
+ i => i.ids == user.address[0].regionCode,
389
+ );
390
+ this.contragent.registrationCountry = country ? country : new Value();
391
+ this.contragent.registrationStreet = user.address[0].streetName;
392
+ this.contragent.registrationCity = city ? city : new Value();
393
+ this.contragent.registrationNumberApartment =
394
+ user.address[0].apartmentNumber;
395
+ this.contragent.registrationNumberHouse = user.address[0].blockNumber;
396
+ this.contragent.registrationProvince = province
397
+ ? province
398
+ : new Value();
399
+ this.contragent.registrationRegionType = localityType
400
+ ? localityType
401
+ : new Value();
402
+ this.contragent.registrationRegion = region ? region : new Value();
403
+ this.contragent.registrationQuarter = user.address[0].kvartal;
404
+ this.contragent.registrationMicroDistrict = user.address[0].microRaion;
405
+ }
406
+
407
+ if ('contacts' in user && user.contacts.length) {
408
+ user.contacts.forEach(contact => {
409
+ if (contact.type === 'EMAIL' && contact.value) {
410
+ this.contragent.email = contact.value;
411
+ }
412
+ if (contact.type === 'MOBILE' && contact.value) {
413
+ let phoneNumber = contact.value.substring(1);
414
+ this.contragent.phoneNumber = `+7 (${phoneNumber.slice(
415
+ 0,
416
+ 3,
417
+ )}) ${phoneNumber.slice(3, 6)} ${phoneNumber.slice(
418
+ 6,
419
+ 8,
420
+ )} ${phoneNumber.slice(8)}`;
421
+ }
422
+ if (contact.type === 'HOME' && contact.value) {
423
+ let homePhone = contact.value.substring(1);
424
+ this.contragent.homePhone = `+7 (${homePhone.slice(
425
+ 0,
426
+ 3,
427
+ )}) ${homePhone.slice(3, 6)} ${homePhone.slice(
428
+ 6,
429
+ 8,
430
+ )} ${homePhone.slice(8)}`;
431
+ }
432
+ });
433
+ }
434
+ },
435
+ async alreadyInInsis(iin, firstName, lastName, middleName) {
436
+ try {
437
+ const queryData = {
438
+ iin: iin.replaceAll('-', ''),
439
+ firstName: !!firstName ? firstName : '',
440
+ lastName: !!lastName ? lastName : '',
441
+ middleName: !!middleName ? middleName : '',
442
+ };
443
+ const contragent = await this.api.getContragent(queryData);
444
+ if (contragent.totalItems > 0) {
445
+ if (contragent.totalItems.length === 1) {
446
+ return contragent.items[0].id;
447
+ } else {
448
+ const sortedByRegistrationDate = contragent.items.sort(
449
+ (left, right) =>
450
+ new Date(right.registrationDate) -
451
+ new Date(left.registrationDate),
452
+ );
453
+ return sortedByRegistrationDate[0].id;
454
+ }
455
+ } else {
456
+ return false;
457
+ }
458
+ } catch (err) {
459
+ console.log(err);
460
+ return false;
461
+ }
462
+ },
463
+ async saveContragent(user, onlySaveAction = true) {
464
+ this.isLoading = true;
465
+ const hasInsisId = await this.alreadyInInsis(
466
+ this.contragent.iin,
467
+ this.contragent.firstName,
468
+ this.contragent.lastName,
469
+ this.contragent.middleName,
470
+ );
471
+ if (hasInsisId !== false) {
472
+ user.id = hasInsisId;
473
+ const [
474
+ { value: data },
475
+ { value: contacts },
476
+ { value: documents },
477
+ { value: address },
478
+ ] = await Promise.allSettled([
479
+ this.api.getContrAgentData(user.id),
480
+ this.api.getContrAgentContacts(user.id),
481
+ this.api.getContrAgentDocuments(user.id),
482
+ this.api.getContrAgentAddress(user.id),
483
+ ]);
484
+ this.contragent.response = {};
485
+ if (data && data.length) {
486
+ this.contragent.response.questionnaires = data;
487
+ }
488
+ if (contacts && contacts.length) {
489
+ this.contragent.response.contacts = contacts;
490
+ }
491
+ if (documents && documents.length) {
492
+ this.contragent.response.documents = documents;
493
+ }
494
+ if (address && address.length) {
495
+ this.contragent.response.addresses = address;
496
+ }
497
+ }
498
+
499
+ try {
500
+ // ! SaveContragent -> Contragent
501
+ let contragentData = {
502
+ id: user.id,
503
+ type: user.type,
504
+ iin: user.iin.replace(/-/g, ''),
505
+ longName:
506
+ user.longName !== null
507
+ ? user.longName
508
+ : user.lastName + user.firstName + user.middleName
509
+ ? user.middleName
510
+ : '',
511
+ lastName: user.lastName,
512
+ firstName: user.firstName,
513
+ middleName: user.middleName ? user.middleName : '',
514
+ birthDate: user.getDateByKey('birthDate'),
515
+ gender: user.gender.id,
516
+ genderName: user.genderName ? user.genderName : user.gender.nameRu,
517
+ birthPlace: user.birthPlace.nameRu,
518
+ age: user.age,
519
+ registrationDate: user.registrationDate,
520
+ verifyType: user.verifyType,
521
+ verifyDate: user.verifyDate,
522
+ };
523
+ // ! SaveContragent -> Questionnaires
524
+ let questionnaires = (({
525
+ economySectorCode,
526
+ countryOfCitizenship,
527
+ countryOfTaxResidency,
528
+ signOfResidency,
529
+ }) => ({
530
+ economySectorCode,
531
+ countryOfCitizenship,
532
+ countryOfTaxResidency,
533
+ signOfResidency,
534
+ }))(user);
535
+ let questionariesData = Object.values(questionnaires).map(question => {
536
+ let questName = '';
537
+ let questionId = parseInt(question.ids).toString();
538
+ if (questionId === '500003') {
539
+ questName = 'Код сектора экономики';
540
+ } else if (questionId === '500011') {
541
+ questName = 'Признак резидентства';
542
+ } else if (questionId === '500012') {
543
+ questName = 'Страна гражданства';
544
+ } else if (questionId === '500014') {
545
+ questName = 'Страна налогового резиденства';
546
+ }
547
+ return {
548
+ id:
549
+ 'response' in user && 'questionnaires' in user.response
550
+ ? user.response.questionnaires?.find(
551
+ i => i.questId == questionId,
552
+ ).id
553
+ : question.id,
554
+ contragentId: user.id,
555
+ questAnswer: question.ids,
556
+ questId: questionId,
557
+ questAnswerName: question.nameRu,
558
+ questName: questName,
559
+ };
560
+ });
561
+
562
+ // ! SaveContragent -> Contacts
563
+ let contactsData = [];
564
+ if (user.phoneNumber !== '' && user.phoneNumber !== null) {
565
+ contactsData.push({
566
+ contragentId: user.id,
567
+ id:
568
+ 'response' in user && 'contacts' in user.response
569
+ ? user.response.contacts.find(i => i.type === 'MOBILE').id
570
+ : 0,
571
+ newValue: '',
572
+ note: '',
573
+ primaryFlag: 'Y',
574
+ type: 'MOBILE',
575
+ typeName: 'Сотовый телефон',
576
+ value: formatPhone(user.phoneNumber),
577
+ verifyType: this.contragent.otpTokenId
578
+ ? 'BMG'
579
+ : 'response' in user && 'contacts' in user.response
580
+ ? user.response.contacts.find(i => i.type === 'MOBILE').verifyType
581
+ : null,
582
+ verifyDate: this.contragent.otpTokenId
583
+ ? this.currentDate()
584
+ : 'response' in user && 'contacts' in user.response
585
+ ? user.response.contacts.find(i => i.type === 'MOBILE').verifyDate
586
+ : null,
587
+ });
588
+ }
589
+ if (user.email !== '' && user.email !== null) {
590
+ contactsData.push({
591
+ contragentId: user.id,
592
+ id:
593
+ 'response' in user && 'contacts' in user.response
594
+ ? user.response.contacts.find(i => i.type === 'EMAIL').id
595
+ : 0,
596
+ newValue: '',
597
+ note: '',
598
+ primaryFlag: 'N',
599
+ type: 'EMAIL',
600
+ typeName: 'E-Mail',
601
+ value: user.email
602
+ ? user.email
603
+ : 'response' in user && 'contacts' in user.response
604
+ ? user.response.contacts.find(i => i.type === 'EMAIL').value
605
+ : '',
606
+ });
607
+ }
608
+ if (user.homePhone !== '' && user.homePhone !== null) {
609
+ contactsData.push({
610
+ contragentId: user.id,
611
+ id:
612
+ 'response' in user && 'contacts' in user.response
613
+ ? user.response.contacts.find(i => i.type === 'HOME').id
614
+ : 0,
615
+ newValue: '',
616
+ note: '',
617
+ primaryFlag: 'N',
618
+ type: 'HOME',
619
+ typeName: 'Домашний телефон',
620
+ value: user.homePhone
621
+ ? formatPhone(user.homePhone)
622
+ : 'response' in user && 'contacts' in user.response
623
+ ? user.response.contacts.find(i => i.type === 'HOME').value
624
+ : '',
625
+ });
626
+ }
627
+
628
+ // ! SaveContragent -> Documents
629
+ let documentsData = [];
630
+ documentsData.push({
631
+ contragentId: user.id,
632
+ id:
633
+ 'response' in user && 'documents' in user.response
634
+ ? user.response.documents[0].id
635
+ : 0,
636
+ description: null,
637
+ expireDate: user.getDateByKey('documentExpire'),
638
+ issueDate: user.getDateByKey('documentDate'),
639
+ issuerId: Number(user.documentIssuers.ids),
640
+ issuerName: user.documentIssuers.nameKz,
641
+ issuerNameRu: user.documentIssuers.nameRu,
642
+ note: null,
643
+ number: user.documentNumber,
644
+ type: user.documentType.ids,
645
+ typeName: user.documentType.nameRu,
646
+ serial: null,
647
+ verifyType: user.verifyType,
648
+ verifyDate: user.verifyDate,
649
+ });
650
+
651
+ // ! SaveContragent -> Addresses
652
+ let addressData = [];
653
+ addressData.push({
654
+ id:
655
+ 'response' in user && 'addresses' in user.response
656
+ ? user.response.addresses[0].id
657
+ : 0,
658
+ contragentId: user.id,
659
+ countryCode: user.birthPlace.ids,
660
+ countryName: user.birthPlace.nameRu,
661
+ stateCode: user.registrationProvince.ids,
662
+ stateName: user.registrationProvince.nameRu,
663
+ cityCode: user.registrationCity.code,
664
+ cityName: user.registrationCity.nameRu,
665
+ regionCode: user.registrationRegion.ids,
666
+ regionName: user.registrationRegion.nameRu,
667
+ streetName: user.registrationStreet,
668
+ kvartal: user.registrationQuarter,
669
+ microRaion: user.registrationMicroDistrict,
670
+ cityTypeId: Number(user.registrationRegionType.ids),
671
+ cityTypeName: user.registrationRegionType.nameRu,
672
+ blockNumber: user.registrationNumberHouse,
673
+ apartmentNumber: user.registrationNumberApartment,
674
+ address: `${user.birthPlace.nameRu}, ${user.registrationRegionType.nameRu} ${user.registrationCity.nameRu}, ул. ${user.registrationStreet}, д. ${user.registrationNumberHouse} кв. ${user.registrationNumberApartment}`,
675
+ type: 'H',
676
+ });
677
+
678
+ const data = {
679
+ contragent: contragentData,
680
+ questionaries: questionariesData,
681
+ contacts: contactsData,
682
+ documents: documentsData,
683
+ addresses: addressData,
684
+ };
685
+ try {
686
+ const personId = await this.api.saveContragent(data);
687
+ if (personId) {
688
+ await this.getContragentById(personId, false);
689
+ this.contragent.otpTokenId = null;
690
+ }
691
+ } catch (saveErr) {
692
+ console.log(saveErr);
693
+ if ('response' in saveErr) {
694
+ this.showToaster('error', saveErr.response.data, 5000);
695
+ this.isLoading = false;
696
+ return false;
697
+ }
698
+ }
699
+ } catch (err) {
700
+ console.log(err);
701
+ this.isLoading = false;
702
+ this.showToaster(
703
+ 'error',
704
+ this.t('toaster.error') + err?.response?.data,
705
+ 2000,
706
+ );
707
+ return false;
708
+ }
709
+ if (onlySaveAction) {
710
+ this.isLoading = false;
711
+ }
712
+ return true;
713
+ },
714
+ searchFromList(whichField, searchIt, list) {
715
+ for (let index = 0; index < whichField.length; index++) {
716
+ const searchFrom = list[index];
717
+ const documentQuestionnaire = searchFrom.filter(
718
+ i =>
719
+ i.nameRu === searchIt.questAnswerName ||
720
+ i.ids === searchIt.questAnswer,
721
+ );
722
+ if (documentQuestionnaire.length) {
723
+ this.contragent[whichField[index]] = documentQuestionnaire[0];
724
+ }
725
+ }
726
+ },
727
+ async getFromApi(whichField, whichRequest, parameter) {
728
+ if (this[whichField].length === 0) {
729
+ try {
730
+ const response = await api[whichRequest](parameter);
731
+ if (response) {
732
+ this[whichField] = response;
733
+ if (
734
+ this[whichField].length &&
735
+ this[whichField][this[whichField].length - 1].nameRu ==
736
+ 'невключено'
737
+ ) {
738
+ this[whichField].unshift(this[whichField].pop());
739
+ }
740
+ }
741
+ } catch (err) {
742
+ console.log(err);
743
+ }
744
+ }
745
+ return this[whichField];
746
+ },
747
+ async getCountries() {
748
+ return await this.getFromApi('countries', 'getCountries');
749
+ },
750
+ async getCitizenshipCountries() {
751
+ return await this.getFromApi(
752
+ 'citizenshipCountries',
753
+ 'getCitizenshipCountries',
754
+ );
755
+ },
756
+ async getTaxCountries() {
757
+ return await this.getFromApi('taxCountries', 'getTaxCountries');
758
+ },
759
+ async getStates(key) {
760
+ await this.getFromApi('states', 'getStates');
761
+ if (key && this.contragent[key] && this.contragent[key].ids !== null) {
762
+ return this.states.filter(i => i.code === this.contragent[key].ids);
763
+ }
764
+ return this.states;
765
+ },
766
+ async getRegions(key) {
767
+ await this.getFromApi('regions', 'getRegions');
768
+ if (key && this.contragent[key] && this.contragent[key].ids !== null) {
769
+ return this.regions.filter(i => i.code === this.contragent[key].ids);
770
+ }
771
+ let registrationProvince = this.contragent.registrationProvince;
772
+ if (registrationProvince.ids !== null) {
773
+ return this.regions.filter(i => i.code === registrationProvince.ids);
774
+ } else {
775
+ return this.regions;
776
+ }
777
+ },
778
+ async getCities(key) {
779
+ await this.getFromApi('cities', 'getCities');
780
+ if (key && this.contragent[key] && this.contragent[key].ids !== null) {
781
+ return this.cities.filter(i => i.code === this.contragent[key].ids);
782
+ }
783
+ let registrationProvince = this.contragent.registrationProvince;
784
+ if (registrationProvince.ids !== null) {
785
+ return this.cities.filter(i => i.code === registrationProvince.ids);
786
+ } else {
787
+ return this.cities;
788
+ }
789
+ },
790
+ async getLocalityTypes() {
791
+ return await this.getFromApi('localityTypes', 'getLocalityTypes');
792
+ },
793
+ async getDocumentTypes() {
794
+ const document_list = await this.getFromApi(
795
+ 'documentTypes',
796
+ 'getDocumentTypes',
797
+ );
798
+ await this.getDicFileTypeList();
799
+ return document_list.filter(doc => {
800
+ for (const dic of this.dicFileTypeList) {
801
+ if (doc.nameRu === dic.nameRu) {
802
+ return doc;
803
+ }
804
+ }
805
+ });
806
+ },
807
+ async getDocumentIssuers() {
808
+ return await this.getFromApi('documentIssuers', 'getDocumentIssuers');
809
+ },
810
+ async getResidents() {
811
+ return await this.getFromApi('residents', 'getResidents');
812
+ },
813
+ async getSectorCodeList() {
814
+ await this.getFromApi('economySectorCode', 'getSectorCode');
815
+ if (this.economySectorCode[1].ids != '500003.9') {
816
+ this.economySectorCode = this.economySectorCode.reverse();
817
+ }
818
+ return this.economySectorCode;
819
+ },
820
+ async getFamilyStatuses() {
821
+ return await this.getFromApi('familyStatuses', 'getFamilyStatuses');
822
+ },
823
+ async getRelationTypes() {
824
+ await this.getFromApi('relations', 'getRelationTypes');
825
+ const filteredRelations = this.relations.filter(
826
+ i => Number(i.ids) >= 6 && Number(i.ids) <= 15,
827
+ );
828
+ const otherRelations = this.relations.filter(
829
+ i => Number(i.ids) < 6 || Number(i.ids) > 15,
830
+ );
831
+ return [...filteredRelations, ...otherRelations];
832
+ },
833
+ async getProcessCoverTypeSum(type) {
834
+ return await this.getFromApi(
835
+ 'processCoverTypeSum',
836
+ 'getProcessCoverTypeSum',
837
+ type,
838
+ );
839
+ },
840
+ getNumberWithSpaces(n) {
841
+ return n === null
842
+ ? null
843
+ : Number(
844
+ (typeof n === 'string' ? n : n.toFixed().toString()).replace(
845
+ /[^0-9]+/g,
846
+ '',
847
+ ),
848
+ ).toLocaleString('ru');
849
+ },
850
+ async getTaskList(
851
+ search = '',
852
+ groupCode = 'Work',
853
+ onlyGet = false,
854
+ needToReturn = false,
855
+ key = 'dateCreated',
856
+ processInstanceId = null,
857
+ ) {
858
+ if (onlyGet === false) {
859
+ this.isLoading = true;
860
+ }
861
+ try {
862
+ const column = this.isColumnAsc[key] === null ? 'dateCreated' : key;
863
+ const direction =
864
+ this.isColumnAsc[key] === null
865
+ ? 'desc'
866
+ : this.isColumnAsc[key] === true
867
+ ? 'asc'
868
+ : 'desc';
869
+ const query = {
870
+ pageIndex: processInstanceId === null ? this.historyPageIndex - 1 : 0,
871
+ pageSize: this.historyPageSize,
872
+ search: search ? search.replace(/-/g, '') : '',
873
+ column: column,
874
+ direction: direction,
875
+ groupCode: groupCode,
876
+ processCodes: Object.values(constants.products),
877
+ };
878
+ const taskList = await this.api.getTaskList(
879
+ processInstanceId === null
880
+ ? query
881
+ : { ...query, processInstanceId: processInstanceId },
882
+ );
883
+ if (needToReturn) {
884
+ this.isLoading = false;
885
+ return taskList.items;
886
+ } else {
887
+ this.taskList = taskList.items;
888
+ this.historyTotalItems = taskList.totalItems;
889
+ }
890
+ } catch (err) {
891
+ this.showToaster('error', err?.response?.data, 2000);
892
+ console.log(err);
893
+ } finally {
894
+ this.isLoading = false;
895
+ }
896
+ if (onlyGet === false) {
897
+ this.isLoading = false;
898
+ }
899
+ },
900
+ async getProcessHistoryList(id) {
901
+ try {
902
+ const processHistory = await this.api.getProcessHistory(id);
903
+ if (processHistory.length > 0) {
904
+ return processHistory;
905
+ } else {
906
+ return [];
907
+ }
908
+ } catch (err) {
909
+ console.log(err);
910
+ }
911
+ },
912
+ async getProcessHistory(id) {
913
+ this.isLoading = true;
914
+ try {
915
+ const processHistory = await this.api.getProcessHistory(id);
916
+ if (processHistory.length > 0) {
917
+ this.processHistory = processHistory.reverse();
918
+ } else {
919
+ this.processHistory = [];
920
+ }
921
+ } catch (err) {
922
+ console.log(err);
923
+ }
924
+ this.isLoading = false;
925
+ },
926
+ findObject(from, key, searchKey) {
927
+ const found = this[from].find(i => i[key] == searchKey);
928
+ return found || new Value();
929
+ },
930
+ async getAllFormsData() {
931
+ await Promise.allSettled([
932
+ this.getCountries(),
933
+ this.getCitizenshipCountries(),
934
+ this.getTaxCountries(),
935
+ this.getStates(),
936
+ this.getRegions(),
937
+ this.getCities(),
938
+ this.getLocalityTypes(),
939
+ this.getDocumentTypes(),
940
+ this.getDocumentIssuers(),
941
+ this.getResidents(),
942
+ this.getSectorCodeList(),
943
+ this.getFamilyStatuses(),
944
+ this.getRelationTypes(),
945
+ ]);
946
+ },
947
+ async getUserGroups() {
948
+ try {
949
+ this.isLoading = true;
950
+ this.userGroups = await this.api.getUserGroups();
951
+ } catch (err) {
952
+ console.log(err);
953
+ } finally {
954
+ this.isLoading = false;
955
+ }
956
+ },
957
+ async getOtpStatus(iin, phone, processInstanceId = null) {
958
+ try {
959
+ const otpData = {
960
+ iin: iin.replace(/-/g, ''),
961
+ phoneNumber: formatPhone(phone),
962
+ type: 'AgreementOtp',
963
+ };
964
+ return await this.api.getOtpStatus(
965
+ processInstanceId !== null && processInstanceId != 0
966
+ ? {
967
+ ...otpData,
968
+ processInstanceId: processInstanceId,
969
+ }
970
+ : otpData,
971
+ );
972
+ } catch (err) {
973
+ console.log(err);
974
+ this.showToaster('error', err.response.data, 3000);
975
+ }
976
+ },
977
+ async sendOtp(iin, phone, processInstanceId = null, onInit = false) {
978
+ this.isLoading = true;
979
+ let otpStatus = false;
980
+ let otpResponse = {};
981
+ try {
982
+ if (iin && iin.length === 15 && phone && phone.length === 18) {
983
+ const status = await this.getOtpStatus(iin, phone, processInstanceId);
984
+ if (status === true) {
985
+ this.showToaster('success', this.t('toaster.hasSuccessOtp'), 3000);
986
+ otpStatus = true;
987
+ this.isLoading = false;
988
+ return { otpStatus, otpResponse };
989
+ } else if (status === false && onInit === false) {
990
+ const otpData = {
991
+ iin: iin.replace(/-/g, ''),
992
+ phoneNumber: formatPhone(phone),
993
+ type: 'AgreementOtp',
994
+ };
995
+ otpResponse = await this.api.sendOtp(
996
+ processInstanceId !== null && processInstanceId != 0
997
+ ? {
998
+ ...otpData,
999
+ processInstanceId: processInstanceId,
1000
+ }
1001
+ : otpData,
1002
+ );
1003
+ this.isLoading = false;
1004
+ if (!!otpResponse) {
1005
+ if (
1006
+ 'errMessage' in otpResponse &&
1007
+ otpResponse.errMessage !== null
1008
+ ) {
1009
+ this.showToaster('error', otpResponse.errMessage, 3000);
1010
+ return { otpStatus };
1011
+ }
1012
+ if ('result' in otpResponse && otpResponse.result === null) {
1013
+ if ('statusName' in otpResponse && !!otpResponse.statusName) {
1014
+ this.showToaster('error', otpResponse.statusName, 3000);
1015
+ return { otpStatus };
1016
+ }
1017
+ if ('status' in otpResponse && !!otpResponse.status) {
1018
+ this.showToaster('error', otpResponse.status, 3000);
1019
+ return { otpStatus };
1020
+ }
1021
+ }
1022
+ if ('tokenId' in otpResponse && otpResponse.tokenId) {
1023
+ this.contragent.otpTokenId = otpResponse.tokenId;
1024
+ this.showToaster('success', this.t('toaster.successOtp'), 3000);
1025
+ }
1026
+ } else {
1027
+ this.showToaster('error', this.t('toaster.undefinedError'), 3000);
1028
+ return { otpStatus };
1029
+ }
1030
+ }
1031
+ } else {
1032
+ if (onInit === false) {
1033
+ this.showToaster(
1034
+ 'error',
1035
+ this.t('toaster.errorFormField', {
1036
+ text: 'Номер телефона, ИИН',
1037
+ }),
1038
+ );
1039
+ this.isLoading = false;
1040
+ }
1041
+ }
1042
+ return { otpStatus, otpResponse };
1043
+ } catch (err) {
1044
+ this.isLoading = false;
1045
+ if ('response' in err) {
1046
+ if (
1047
+ 'statusName' in err.response.data &&
1048
+ !!err.response.data.statusName
1049
+ ) {
1050
+ this.showToaster(
1051
+ 'error',
1052
+ this.t('toaster.phoneNotFoundInBMG'),
1053
+ 3000,
1054
+ );
1055
+ return { otpStatus };
1056
+ }
1057
+ if ('status' in err.response.data && !!err.response.data.status) {
1058
+ this.showToaster('error', err.response.data.status, 3000);
1059
+ return { otpStatus };
1060
+ }
1061
+ }
1062
+ } finally {
1063
+ this.isLoading = false;
1064
+ }
1065
+ this.isLoading = false;
1066
+ return { otpStatus, otpResponse };
1067
+ },
1068
+ async checkOtp(otpToken, phone, code) {
1069
+ try {
1070
+ this.isLoading = true;
1071
+ const otpData = {
1072
+ tokenId: otpToken,
1073
+ phoneNumber: formatPhone(phone),
1074
+ code: code,
1075
+ };
1076
+ const otpResponse = await this.api.checkOtp(otpData);
1077
+ if (otpResponse !== null) {
1078
+ if ('errMessage' in otpResponse && otpResponse.errMessage !== null) {
1079
+ this.showToaster('error', otpResponse.errMessage, 3000);
1080
+ return false;
1081
+ }
1082
+ if ('status' in otpResponse && !!otpResponse.status) {
1083
+ // TODO Доработать и менять значение hasAgreement.value => true
1084
+ this.showToaster(
1085
+ otpResponse.status !== 2 ? 'error' : 'success',
1086
+ otpResponse.statusName,
1087
+ 3000,
1088
+ );
1089
+ if (otpResponse.status === 2) {
1090
+ return true;
1091
+ }
1092
+ }
1093
+ }
1094
+ return false;
1095
+ } catch (err) {
1096
+ console.log(err);
1097
+ if ('response' in err) {
1098
+ this.showToaster('error', err.response.data, 3000);
1099
+ }
1100
+ } finally {
1101
+ this.isLoading = false;
1102
+ }
1103
+ return null;
1104
+ },
1105
+ async getProcessList() {
1106
+ this.isLoading = true;
1107
+ try {
1108
+ const processList = await this.api.getProcessList();
1109
+ if (processList.length > 0) {
1110
+ this.processList = processList;
1111
+ }
1112
+ } catch (err) {
1113
+ console.log(err);
1114
+ }
1115
+ this.isLoading = false;
1116
+ },
1117
+ sortTaskList(key) {
1118
+ if (this.taskList.length !== 0) {
1119
+ if (key in this.isColumnAsc) {
1120
+ if (this.isColumnAsc[key] === true) {
1121
+ this.isColumnAsc = { ...InitialColumns() };
1122
+ this.isColumnAsc[key] = false;
1123
+ return;
1124
+ }
1125
+ if (this.isColumnAsc[key] === false) {
1126
+ this.isColumnAsc = { ...InitialColumns() };
1127
+ this.isColumnAsc[key] = null;
1128
+ return;
1129
+ }
1130
+ if (this.isColumnAsc[key] === null) {
1131
+ this.isColumnAsc = { ...InitialColumns() };
1132
+ this.isColumnAsc[key] = true;
1133
+ return;
1134
+ }
1135
+ }
1136
+ }
26
1137
  },
27
1138
  },
28
1139
  });
1140
+
1141
+ export const useContragentStore = defineStore('contragent', {
1142
+ state: () => ({
1143
+ ...new Contragent(),
1144
+ formatDate: new Contragent().formatDate,
1145
+ getDateByKey: new Contragent().getDateByKey,
1146
+ getBirthDate: new Contragent().getBirthDate,
1147
+ getDocumentExpireDate: new Contragent().getDocumentExpireDate,
1148
+ getDocumentDate: new Contragent().getDocumentDate,
1149
+ getAgeByBirthDate: new Contragent().getAgeByBirthDate,
1150
+ }),
1151
+ });