hl-core 0.0.7 → 0.0.8-beta.10

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 (70) hide show
  1. package/.prettierrc +2 -1
  2. package/api/index.ts +562 -0
  3. package/api/interceptors.ts +38 -0
  4. package/components/Button/Btn.vue +57 -0
  5. package/components/Button/BtnIcon.vue +47 -0
  6. package/components/Button/ScrollButtons.vue +6 -0
  7. package/components/Button/SortArrow.vue +21 -0
  8. package/components/Complex/Content.vue +5 -0
  9. package/components/Complex/ContentBlock.vue +5 -0
  10. package/components/Complex/Page.vue +43 -0
  11. package/components/Dialog/Dialog.vue +76 -0
  12. package/components/Dialog/FamilyDialog.vue +39 -0
  13. package/components/Form/FormBlock.vue +139 -0
  14. package/components/Form/FormSection.vue +18 -0
  15. package/components/Form/FormTextSection.vue +20 -0
  16. package/components/Form/FormToggle.vue +52 -0
  17. package/components/Form/ManagerAttachment.vue +196 -0
  18. package/components/Form/ProductConditionsBlock.vue +72 -0
  19. package/components/Input/Datepicker.vue +41 -0
  20. package/components/Input/EmptyFormField.vue +5 -0
  21. package/components/Input/FileInput.vue +71 -0
  22. package/components/Input/FormInput.vue +183 -0
  23. package/components/Input/PanelInput.vue +133 -0
  24. package/components/Input/RoundedInput.vue +143 -0
  25. package/components/Layout/Drawer.vue +45 -0
  26. package/components/Layout/Header.vue +48 -0
  27. package/components/Layout/Loader.vue +35 -0
  28. package/components/Layout/SettingsPanel.vue +48 -0
  29. package/components/List/ListEmpty.vue +22 -0
  30. package/components/Menu/MenuNav.vue +108 -0
  31. package/components/Menu/MenuNavItem.vue +37 -0
  32. package/components/Pages/Anketa.vue +341 -0
  33. package/components/Pages/Auth.vue +91 -0
  34. package/components/Pages/Documents.vue +108 -0
  35. package/components/Pages/MemberForm.vue +1229 -0
  36. package/components/Pages/ProductAgreement.vue +18 -0
  37. package/components/Pages/ProductConditions.vue +659 -0
  38. package/components/Panel/PanelHandler.vue +233 -0
  39. package/components/Panel/PanelItem.vue +5 -0
  40. package/components/Panel/PanelSelectItem.vue +20 -0
  41. package/components/Transitions/FadeTransition.vue +5 -0
  42. package/components/Transitions/SlideTransition.vue +5 -0
  43. package/composables/axios.ts +11 -0
  44. package/composables/classes.ts +1179 -0
  45. package/composables/constants.ts +71 -0
  46. package/composables/index.ts +168 -2
  47. package/composables/styles.ts +48 -8
  48. package/configs/i18n.ts +19 -0
  49. package/layouts/clear.vue +3 -0
  50. package/layouts/default.vue +75 -0
  51. package/layouts/full.vue +6 -0
  52. package/locales/en.json +403 -0
  53. package/locales/kz.json +403 -0
  54. package/locales/ru.json +403 -0
  55. package/nuxt.config.ts +39 -5
  56. package/package.json +28 -10
  57. package/pages/500.vue +85 -0
  58. package/plugins/helperFunctionsPlugins.ts +19 -2
  59. package/plugins/storePlugin.ts +5 -7
  60. package/plugins/vuetifyPlugin.ts +15 -0
  61. package/store/data.store.js +2291 -8
  62. package/store/form.store.ts +8 -0
  63. package/store/member.store.ts +381 -0
  64. package/store/rules.js +52 -39
  65. package/tailwind.config.js +10 -0
  66. package/types/index.ts +317 -0
  67. package/app.vue +0 -3
  68. package/components/Button/GreenBtn.vue +0 -33
  69. package/store/app.store.js +0 -12
  70. package/store/messages.ts +0 -310
@@ -1,28 +1,2311 @@
1
1
  import { defineStore } from 'pinia';
2
- import { t } from './messages';
3
2
  import { rules } from './rules';
3
+ import { i18n } from '@/configs/i18n';
4
4
  import { Toast, Types, Positions, ToastOptions } from './toast';
5
+ import { isValidGUID, yearEnding, jwtDecode, ErrorHandler, getKeyWithPattern, getNumber, getAgeByBirthDate } from '../composables';
6
+ import { DataStoreClass, Contragent } from '../composables/classes';
7
+ import { ApiClass } from '@/api';
8
+ import { useFormStore } from './form.store';
5
9
 
6
10
  export const useDataStore = defineStore('data', {
7
11
  state: () => ({
8
- t: t,
12
+ ...new DataStoreClass(),
13
+ t: i18n.t,
9
14
  rules: rules,
10
15
  toast: Toast,
11
16
  toastTypes: Types,
12
17
  toastPositions: Positions,
18
+ isValidGUID: isValidGUID,
19
+ router: useRouter(),
20
+ formStore: useFormStore(),
21
+ contragent: useContragentStore(),
22
+ api: new ApiClass(),
23
+ yearEnding: year => yearEnding(year, constants.yearTitles, constants.yearCases),
24
+ currentDate: () => new Date(Date.now() - new Date().getTimezoneOffset() * 60 * 1000).toISOString().slice(0, -1),
13
25
  showToaster: (type, msg, timeout) =>
14
26
  Toast.useToast()(msg, {
15
27
  ...ToastOptions,
16
28
  type: Types[type.toUpperCase()],
17
- timeout:
18
- typeof timeout === ('number' || 'boolean')
19
- ? timeout
20
- : ToastOptions.timeout,
29
+ timeout: type === 'error' ? 6000 : typeof timeout === 'number' ? timeout : ToastOptions.timeout,
21
30
  }),
22
31
  }),
32
+ getters: {
33
+ isEFO: state => state.product === 'efo',
34
+ isAML: state => state.product === 'aml',
35
+ isBaiterek: state => state.product === 'baiterek',
36
+ isBolashak: state => state.product === 'bolashak',
37
+ isMycar: state => state.product === 'mycar',
38
+ isLifetrip: state => state.product === 'lifetrip',
39
+ isLiferenta: state => state.product === 'liferenta',
40
+ isPension: state => state.product === 'pension',
41
+ isGons: state => state.product === 'gons',
42
+ isKazyna: state => state.product === 'halykkazyna',
43
+ isComplianceWindow: state => state.product === 'compliance',
44
+ isEveryFormDisabled: state => Object.values(state.formStore.isDisabled).every(i => i === true),
45
+ },
23
46
  actions: {
24
- async loginUser(...data) {
25
- console.log(...data);
47
+ isIframe() {
48
+ try {
49
+ return window.self !== window.top;
50
+ } catch (err) {
51
+ return true;
52
+ }
53
+ },
54
+ sendToParent(action, value) {
55
+ window.parent.postMessage({ action: action, value: value }, '*');
56
+ },
57
+ getChildIframe() {
58
+ return document.getElementById('product-iframe');
59
+ },
60
+ sendToChild(action, value) {
61
+ const childFrame = this.getChildIframe();
62
+ if (childFrame && childFrame.contentWindow && childFrame.contentWindow.postMessage) {
63
+ childFrame.contentWindow.postMessage({ action: action, value: value }, '*');
64
+ }
65
+ },
66
+ copyToClipboard(text) {
67
+ if (typeof text === 'string' || typeof text === 'number') {
68
+ if (this.isEFO || this.isAML) {
69
+ navigator.clipboard.writeText(text);
70
+ } else {
71
+ this.sendToParent(constants.postActions.clipboard, text);
72
+ }
73
+ this.showToaster('success', this.t('toaster.copied'));
74
+ } else {
75
+ this.showToaster('error', this.t('toaster.noUrl'));
76
+ }
77
+ },
78
+ getFilesByIIN(iin) {
79
+ return iin ? this.formStore.signedDocumentList.filter(file => file.iin === iin && file.fileTypeName === 'Удостоверение личности') : null;
80
+ },
81
+ async getNewAccessToken() {
82
+ try {
83
+ const data = {
84
+ accessToken: localStorage.getItem('accessToken'),
85
+ refreshToken: localStorage.getItem('refreshToken'),
86
+ };
87
+ const response = await this.api.getNewAccessToken(data);
88
+ this.accessToken = response.accessToken;
89
+ this.refreshToken = response.refreshToken;
90
+ localStorage.setItem('accessToken', this.accessToken);
91
+ localStorage.setItem('refreshToken', this.refreshToken);
92
+ } catch (err) {
93
+ console.error(err);
94
+ }
95
+ },
96
+ async loginUser(login, password, numAttempt) {
97
+ try {
98
+ const token = localStorage.getItem('accessToken') || null;
99
+ if (token && isValidToken(token)) {
100
+ this.accessToken = token;
101
+ this.getUserRoles();
102
+ } else {
103
+ const response = await this.api.loginUser({
104
+ login: login,
105
+ password: password,
106
+ numAttempt: numAttempt,
107
+ });
108
+
109
+ this.accessToken = response.accessToken;
110
+ this.refreshToken = response.refreshToken;
111
+ this.getUserRoles();
112
+ }
113
+ if (this.controls.onAuth) {
114
+ const hasPermission =
115
+ this.isInitiator() ||
116
+ this.isUnderwriter() ||
117
+ this.isAdmin() ||
118
+ this.isCompliance() ||
119
+ this.isAnalyst() ||
120
+ this.isUpk() ||
121
+ this.isFinCenter() ||
122
+ this.isSupervisor() ||
123
+ this.isSupport();
124
+ if (hasPermission) {
125
+ localStorage.setItem('accessToken', this.accessToken);
126
+ localStorage.setItem('refreshToken', this.refreshToken);
127
+ } else {
128
+ this.showToaster('error', this.t('toaster.noProductPermission'), 5000);
129
+ this.accessToken = null;
130
+ this.refreshToken = null;
131
+ }
132
+ } else {
133
+ localStorage.setItem('accessToken', this.accessToken);
134
+ localStorage.setItem('refreshToken', this.refreshToken);
135
+ }
136
+ } catch (err) {
137
+ ErrorHandler(err);
138
+ }
139
+ },
140
+ getUserRoles() {
141
+ if (this.accessToken && this.user.roles.length === 0) {
142
+ const decoded = jwtDecode(this.accessToken);
143
+ this.user.id = decoded.sub;
144
+ this.user.fullName = `${decoded.lastName} ${decoded.firstName} ${decoded.middleName ? decoded.middleName : ''}`;
145
+ const key = getKeyWithPattern(decoded, 'role');
146
+ if (key) {
147
+ const roles = decoded[key];
148
+ if (typeof roles === constants.types.string) {
149
+ this.user.roles.push(roles);
150
+ } else if (typeof roles === constants.types.array) {
151
+ this.user.roles = roles;
152
+ }
153
+ }
154
+ }
155
+ },
156
+ isRole(whichRole) {
157
+ if (this.user.roles.length === 0) {
158
+ this.getUserRoles();
159
+ }
160
+ const isRole = this.user.roles.find(i => i === whichRole);
161
+ return !!isRole;
162
+ },
163
+ isInitiator() {
164
+ return this.isManager() || this.isAgent() || this.isAgentMycar() || this.isManagerHalykBank() || this.isServiceManager();
165
+ },
166
+ isManager() {
167
+ return this.isRole(constants.roles.manager);
168
+ },
169
+ isCompliance() {
170
+ return this.isRole(constants.roles.compliance);
171
+ },
172
+ isAdmin() {
173
+ return this.isRole(constants.roles.admin);
174
+ },
175
+ isAgent() {
176
+ return this.isRole(constants.roles.agent);
177
+ },
178
+ isManagerHalykBank() {
179
+ return this.isRole(constants.roles.managerHalykBank);
180
+ },
181
+ isServiceManager() {
182
+ return this.isRole(constants.roles.serviceManager);
183
+ },
184
+ isUnderwriter() {
185
+ return this.isRole(constants.roles.underwriter);
186
+ },
187
+ isAgentMycar() {
188
+ return this.isRole(constants.roles.agentMycar);
189
+ },
190
+ isAnalyst() {
191
+ return this.isRole(constants.roles.analyst);
192
+ },
193
+ isUpk() {
194
+ return this.isRole(constants.roles.upk);
195
+ },
196
+ isDrn() {
197
+ return this.isRole(constants.roles.drn);
198
+ },
199
+ isSupport() {
200
+ return this.isRole(constants.roles.support);
201
+ },
202
+ isFinCenter() {
203
+ return this.isRole(constants.roles.finCenter);
204
+ },
205
+ isSupervisor() {
206
+ return this.isRole(constants.roles.supervisor);
207
+ },
208
+ isProcessEditable(statusCode) {
209
+ return !!constants.editableStatuses.find(status => status === statusCode);
210
+ },
211
+ isTask() {
212
+ return this.formStore.applicationData.processInstanceId !== 0 && this.formStore.applicationData.isTask;
213
+ },
214
+ async resetSelected(route) {
215
+ this.settings.open = false;
216
+ this.panel.open = false;
217
+ this.panelAction = null;
218
+ this.menu.selectedItem = new MenuItem();
219
+ if (route && route.name) {
220
+ await this.router.replace({ name: route.name });
221
+ }
222
+ },
223
+ async logoutUser() {
224
+ this.isLoading = true;
225
+ try {
226
+ const whichProduct = this.product;
227
+ const token = localStorage.getItem('accessToken') || null;
228
+ if (token) {
229
+ this.$reset();
230
+ this.formStore.$reset();
231
+ localStorage.clear();
232
+
233
+ if (whichProduct === 'efo') {
234
+ await this.router.push({ name: 'Auth' });
235
+ } else {
236
+ this.sendToParent(constants.postActions.toAuth, null);
237
+ }
238
+ }
239
+ } catch (err) {
240
+ console.log(err);
241
+ }
242
+ this.isLoading = false;
243
+ },
244
+ async getFile(file, mode = 'view', fileType = 'pdf') {
245
+ try {
246
+ this.isLoading = true;
247
+ await this.api.getFile(file.id).then(response => {
248
+ if (!['pdf', 'docx'].includes(fileType)) {
249
+ const blob = new Blob([response], { type: `image/${fileType}` });
250
+ const url = window.URL.createObjectURL(blob);
251
+ const link = document.createElement('a');
252
+ link.href = url;
253
+ if (mode === 'view') {
254
+ setTimeout(() => {
255
+ window.open(url, '_blank', `width=${screen.width},height=${screen.height},top=70`);
256
+ });
257
+ } else {
258
+ link.setAttribute('download', file.fileName);
259
+ document.body.appendChild(link);
260
+ link.click();
261
+ }
262
+ } else {
263
+ const blob = new Blob([response], {
264
+ type: `application/${fileType}`,
265
+ });
266
+ const url = window.URL.createObjectURL(blob);
267
+ const link = document.createElement('a');
268
+ link.href = url;
269
+ if (mode === 'view') {
270
+ setTimeout(() => {
271
+ window.open(url, '_blank', `right=100`);
272
+ });
273
+ } else {
274
+ link.setAttribute('download', file.fileName);
275
+ document.body.appendChild(link);
276
+ link.click();
277
+ }
278
+ }
279
+ });
280
+ } catch (err) {
281
+ ErrorHandler(err);
282
+ } finally {
283
+ this.isLoading = false;
284
+ }
285
+ },
286
+ async deleteFile(data) {
287
+ try {
288
+ await this.api.deleteFile(data);
289
+ this.showToaster('success', this.t('toaster.fileWasDeleted'), 3000);
290
+ } catch (err) {
291
+ this.showToaster('error', err.response.data, 2000);
292
+ }
293
+ },
294
+ async uploadFiles(data, load = false) {
295
+ try {
296
+ if (load) {
297
+ this.isLoading = true;
298
+ }
299
+ await this.api.uploadFiles(data);
300
+ return true;
301
+ } catch (err) {
302
+ return ErrorHandler(err);
303
+ } finally {
304
+ if (load) {
305
+ this.isLoading = false;
306
+ }
307
+ }
308
+ },
309
+ async getContragent(member, load = true) {
310
+ if (load) {
311
+ this.isLoading = true;
312
+ }
313
+ try {
314
+ let response;
315
+ let queryData = {
316
+ firstName: '',
317
+ lastName: '',
318
+ middleName: '',
319
+ };
320
+ queryData.iin = member.iin.replace(/-/g, '');
321
+ response = await this.api.getContragent(queryData);
322
+ if (response.totalItems > 0) {
323
+ if (response.totalItems.length === 1) {
324
+ await this.serializeContragentData(member, response.items[0]);
325
+ } else {
326
+ const sortedByRegistrationDate = response.items.sort((left, right) => new Date(right.registrationDate) - new Date(left.registrationDate));
327
+ await this.serializeContragentData(member, sortedByRegistrationDate[0]);
328
+ }
329
+ member.gotFromInsis = true;
330
+ } else {
331
+ this.userNotFound = true;
332
+ }
333
+ } catch (err) {
334
+ console.log(err);
335
+ }
336
+ if (load) {
337
+ this.isLoading = false;
338
+ }
339
+ },
340
+ async getContragentById(id, whichForm, onlyGet = true, whichIndex = null) {
341
+ if (onlyGet) {
342
+ this.isLoading = true;
343
+ }
344
+ try {
345
+ const member = whichIndex === null ? this.formStore[whichForm] : this.formStore[whichForm][whichIndex];
346
+ if (this.isMycar && this.isAgentMycar() && whichForm === this.formStore.beneficiaryFormKey) {
347
+ await this.serializeContragentData(member, this.formStore.applicationData.beneficiaryApp[0]);
348
+ this.isLoading = false;
349
+ return;
350
+ }
351
+ const response = await this.api.getContragentById(id);
352
+ if (response.totalItems > 0) {
353
+ await this.serializeContragentData(member, response.items[0]);
354
+ } else {
355
+ this.isLoading = false;
356
+ return false;
357
+ }
358
+ } catch (err) {
359
+ console.log(err);
360
+ }
361
+ if (onlyGet) {
362
+ this.isLoading = false;
363
+ }
364
+ },
365
+ async serializeContragentData(member, contragent) {
366
+ const [{ value: data }, { value: contacts }, { value: documents }, { value: address }] = await Promise.allSettled([
367
+ this.api.getContrAgentData(contragent.id),
368
+ this.api.getContrAgentContacts(contragent.id),
369
+ this.api.getContrAgentDocuments(contragent.id),
370
+ this.api.getContrAgentAddress(contragent.id),
371
+ ]);
372
+ member.response = {
373
+ contragent: contragent,
374
+ };
375
+ if (data && data.length) {
376
+ member.response.questionnaires = data;
377
+ }
378
+ if (contacts && contacts.length) {
379
+ member.response.contacts = contacts;
380
+ }
381
+ if (documents && documents.length) {
382
+ member.response.documents = documents;
383
+ }
384
+ if (address && address.length) {
385
+ member.response.addresses = address;
386
+ }
387
+ this.parseContragent(member, {
388
+ personalData: contragent,
389
+ documents: documents,
390
+ contacts: contacts,
391
+ data: data,
392
+ address: address,
393
+ });
394
+ },
395
+ async searchContragent(iin) {
396
+ this.isLoading = true;
397
+ try {
398
+ let queryData = {
399
+ iin: iin.replace(/-/g, ''),
400
+ firstName: '',
401
+ lastName: '',
402
+ middleName: '',
403
+ };
404
+ const response = await this.api.getContragent(queryData);
405
+ if (response.totalItems > 0) {
406
+ this.contragentList = response.items;
407
+ } else {
408
+ this.contragentList = [];
409
+ }
410
+ } catch (err) {
411
+ console.log(err);
412
+ this.contragentList = [];
413
+ }
414
+ this.isLoading = false;
415
+ },
416
+ parseContragent(member, user) {
417
+ // Save User Personal Data
418
+ member.verifyType = user.personalData.verifyType;
419
+ member.verifyDate = user.personalData.verifyDate;
420
+ member.iin = reformatIin(user.personalData.iin);
421
+ member.age = user.personalData.age;
422
+ const country = this.countries.find(i => i.nameRu?.match(new RegExp(user.personalData.birthPlace, 'i')));
423
+ member.birthPlace = country && Object.keys(country).length ? country : new Value();
424
+ member.gender = this.gender.find(i => i.nameRu === user.personalData.genderName);
425
+ member.gender.id = user.personalData.gender;
426
+ member.birthDate = reformatDate(user.personalData.birthDate);
427
+ member.genderName = user.personalData.genderName;
428
+ member.lastName = user.personalData.lastName;
429
+ member.longName = user.personalData.longName;
430
+ member.middleName = user.personalData.middleName ? user.personalData.middleName : '';
431
+ member.firstName = user.personalData.firstName;
432
+ member.id = user.personalData.id;
433
+ member.type = user.personalData.type;
434
+ member.registrationDate = user.personalData.registrationDate;
435
+ // Save User Documents Data
436
+ if ('documents' in user && user.documents.length) {
437
+ const documentType = this.documentTypes.find(i => i.ids === user.documents[0].type);
438
+ const documentIssuer = this.documentIssuers.find(i => i.nameRu === user.documents[0].issuerNameRu);
439
+ member.documentType = documentType ? documentType : new Value();
440
+ member.documentNumber = user.documents[0].number;
441
+ member.documentIssuers = documentIssuer ? documentIssuer : new Value();
442
+ member.documentDate = reformatDate(user.documents[0].issueDate);
443
+ member.documentExpire = reformatDate(user.documents[0].expireDate);
444
+ }
445
+ // Document detail (residency, economy code, etc..)
446
+ if ('data' in user && user.data.length) {
447
+ user.data.forEach(dataObject => {
448
+ this.searchFromList(member, dataObject);
449
+ });
450
+ }
451
+ if ('address' in user && user.address.length) {
452
+ const country = this.countries.find(i => i.nameRu?.match(new RegExp(user.address[0].countryName, 'i')));
453
+ const province = this.states.find(i => i.ids === user.address[0].stateCode);
454
+ const localityType = this.localityTypes.find(i => i.nameRu === user.address[0].cityTypeName);
455
+ const city = this.cities.find(i => !!user.address[0].cityName && i.nameRu === user.address[0].cityName.replace('г.', ''));
456
+ const region = this.regions.find(i => !!user.address[0].regionCode && i.ids == user.address[0].regionCode);
457
+ member.registrationCountry = country ? country : new Value();
458
+ member.registrationStreet = user.address[0].streetName;
459
+ member.registrationCity = city ? city : new Value();
460
+ member.registrationNumberApartment = user.address[0].apartmentNumber;
461
+ member.registrationNumberHouse = user.address[0].blockNumber;
462
+ member.registrationProvince = province ? province : new Value();
463
+ member.registrationRegionType = localityType ? localityType : new Value();
464
+ member.registrationRegion = region ? region : new Value();
465
+ member.registrationQuarter = user.address[0].kvartal;
466
+ member.registrationMicroDistrict = user.address[0].microRaion;
467
+ }
468
+ if ('contacts' in user && user.contacts.length) {
469
+ user.contacts.forEach(contact => {
470
+ if (contact.type === 'EMAIL' && contact.value) {
471
+ member.email = contact.value;
472
+ }
473
+ if (contact.type === 'MOBILE' && contact.value) {
474
+ let phoneNumber = contact.value.substring(1);
475
+ member.phoneNumber = `+7 (${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3, 6)} ${phoneNumber.slice(6, 8)} ${phoneNumber.slice(8)}`;
476
+ }
477
+ if (contact.type === 'HOME' && contact.value) {
478
+ let homePhone = contact.value.substring(1);
479
+ member.homePhone = `+7 (${homePhone.slice(0, 3)}) ${homePhone.slice(3, 6)} ${homePhone.slice(6, 8)} ${homePhone.slice(8)}`;
480
+ }
481
+ });
482
+ }
483
+ },
484
+ async alreadyInInsis(iin, firstName, lastName, middleName) {
485
+ try {
486
+ const queryData = {
487
+ iin: iin.replaceAll('-', ''),
488
+ firstName: !!firstName ? firstName : '',
489
+ lastName: !!lastName ? lastName : '',
490
+ middleName: !!middleName ? middleName : '',
491
+ };
492
+ const contragent = await this.api.getContragent(queryData);
493
+ if (contragent.totalItems > 0) {
494
+ if (contragent.totalItems.length === 1) {
495
+ return contragent.items[0].id;
496
+ } else {
497
+ const sortedByRegistrationDate = contragent.items.sort((left, right) => new Date(right.registrationDate) - new Date(left.registrationDate));
498
+ return sortedByRegistrationDate[0].id;
499
+ }
500
+ } else {
501
+ return false;
502
+ }
503
+ } catch (err) {
504
+ console.log(err);
505
+ return false;
506
+ }
507
+ },
508
+ async saveContragent(user, whichForm, whichIndex, onlySaveAction = true) {
509
+ this.isLoading = !onlySaveAction;
510
+ const hasInsisId = await this.alreadyInInsis(user.iin, user.firstName, user.lastName, user.middleName);
511
+ if (hasInsisId !== false) {
512
+ user.id = hasInsisId;
513
+ const [{ value: data }, { value: contacts }, { value: documents }, { value: address }] = await Promise.allSettled([
514
+ this.api.getContrAgentData(user.id),
515
+ this.api.getContrAgentContacts(user.id),
516
+ this.api.getContrAgentDocuments(user.id),
517
+ this.api.getContrAgentAddress(user.id),
518
+ ]);
519
+ user.response = {};
520
+ if (data && data.length) {
521
+ user.response.questionnaires = data;
522
+ }
523
+ if (contacts && contacts.length) {
524
+ user.response.contacts = contacts;
525
+ }
526
+ if (documents && documents.length) {
527
+ user.response.documents = documents;
528
+ }
529
+ if (address && address.length) {
530
+ user.response.addresses = address;
531
+ }
532
+ }
533
+ try {
534
+ // ! SaveContragent -> Contragent
535
+ let contragentData = {
536
+ id: user.id,
537
+ type: user.type,
538
+ iin: user.iin.replace(/-/g, ''),
539
+ longName: user.longName !== null ? user.longName : user.lastName + user.firstName + user.middleName ? user.middleName : '',
540
+ lastName: user.lastName,
541
+ firstName: user.firstName,
542
+ middleName: user.middleName ? user.middleName : '',
543
+ birthDate: user.getDateByKey('birthDate'),
544
+ gender: user.gender.id,
545
+ genderName: user.genderName ? user.genderName : user.gender.nameRu,
546
+ birthPlace: user.birthPlace.nameRu,
547
+ age: user.age,
548
+ registrationDate: user.registrationDate,
549
+ verifyType: user.verifyType,
550
+ verifyDate: user.verifyDate,
551
+ };
552
+ // ! SaveContragent -> Questionnaires
553
+ let questionnaires = (({ economySectorCode, countryOfCitizenship, countryOfTaxResidency, signOfResidency }) => ({
554
+ economySectorCode,
555
+ countryOfCitizenship,
556
+ countryOfTaxResidency,
557
+ signOfResidency,
558
+ }))(user);
559
+ let questionariesData = Object.values(questionnaires).map(question => {
560
+ let questName = '';
561
+ let questionId = parseInt(question.ids).toString();
562
+ if (questionId === '500003') {
563
+ questName = 'Код сектора экономики';
564
+ } else if (questionId === '500011') {
565
+ questName = 'Признак резидентства';
566
+ } else if (questionId === '500012') {
567
+ questName = 'Страна гражданства';
568
+ } else if (questionId === '500014') {
569
+ questName = 'Страна налогового резиденства';
570
+ }
571
+ return {
572
+ id: 'response' in user && 'questionnaires' in user.response ? user.response.questionnaires?.find(i => i.questId == questionId).id : question.id,
573
+ contragentId: user.id,
574
+ questAnswer: question.ids,
575
+ questId: questionId,
576
+ questAnswerName: question.nameRu,
577
+ questName: questName,
578
+ };
579
+ });
580
+ if (user.countryOfTaxResidency.ids !== '500014.3') {
581
+ user.addTaxResidency = new Value();
582
+ }
583
+ const addTaxResidency = 'response' in user && 'questionnaires' in user.response && user.response.questionnaires.find(i => i.questId === '507777');
584
+ if (user.addTaxResidency.nameRu !== null) {
585
+ questionariesData.push({
586
+ id: addTaxResidency ? addTaxResidency.id : 0,
587
+ contragentId: user.id,
588
+ questAnswer: user.addTaxResidency.ids,
589
+ questAnswerName: user.addTaxResidency.nameRu,
590
+ questName: 'Указать если налоговое резиденство выбрано другое',
591
+ questId: '507777',
592
+ });
593
+ } else {
594
+ if (addTaxResidency && addTaxResidency.questAnswer !== null) {
595
+ questionariesData.push({
596
+ id: addTaxResidency.id,
597
+ contragentId: user.id,
598
+ questAnswer: null,
599
+ questAnswerName: null,
600
+ questName: 'Указать если налоговое резиденство выбрано другое',
601
+ questId: '507777',
602
+ });
603
+ }
604
+ }
605
+
606
+ // ! SaveContragent -> Contacts
607
+ let contactsData = [];
608
+ if (user.phoneNumber !== '' && user.phoneNumber !== null) {
609
+ contactsData.push({
610
+ contragentId: user.id,
611
+ id: 'response' in user && 'contacts' in user.response ? user.response.contacts.find(i => i.type === 'MOBILE').id : 0,
612
+ newValue: '',
613
+ note: '',
614
+ primaryFlag: 'Y',
615
+ type: 'MOBILE',
616
+ typeName: 'Сотовый телефон',
617
+ value: formatPhone(user.phoneNumber),
618
+ verifyType: user.otpTokenId ? 'BMG' : 'response' in user && 'contacts' in user.response ? user.response.contacts.find(i => i.type === 'MOBILE').verifyType : null,
619
+ verifyDate: user.otpTokenId
620
+ ? this.currentDate()
621
+ : 'response' in user && 'contacts' in user.response
622
+ ? user.response.contacts.find(i => i.type === 'MOBILE').verifyDate
623
+ : null,
624
+ });
625
+ }
626
+ if (user.email !== '' && user.email !== null) {
627
+ contactsData.push({
628
+ contragentId: user.id,
629
+ id: 'response' in user && 'contacts' in user.response ? user.response.contacts.find(i => i.type === 'EMAIL').id : 0,
630
+ newValue: '',
631
+ note: '',
632
+ primaryFlag: 'N',
633
+ type: 'EMAIL',
634
+ typeName: 'E-Mail',
635
+ value: user.email ? user.email : 'response' in user && 'contacts' in user.response ? user.response.contacts.find(i => i.type === 'EMAIL').value : '',
636
+ });
637
+ }
638
+ if (user.homePhone !== '' && user.homePhone !== null) {
639
+ contactsData.push({
640
+ contragentId: user.id,
641
+ id: 'response' in user && 'contacts' in user.response ? user.response.contacts.find(i => i.type === 'HOME').id : 0,
642
+ newValue: '',
643
+ note: '',
644
+ primaryFlag: 'N',
645
+ type: 'HOME',
646
+ typeName: 'Домашний телефон',
647
+ value: user.homePhone
648
+ ? formatPhone(user.homePhone)
649
+ : 'response' in user && 'contacts' in user.response
650
+ ? user.response.contacts.find(i => i.type === 'HOME').value
651
+ : '',
652
+ });
653
+ }
654
+
655
+ // ! SaveContragent -> Documents
656
+ let documentsData = [];
657
+ documentsData.push({
658
+ contragentId: user.id,
659
+ id: 'response' in user && 'documents' in user.response ? user.response.documents[0].id : 0,
660
+ description: null,
661
+ expireDate: user.getDateByKey('documentExpire'),
662
+ issueDate: user.getDateByKey('documentDate'),
663
+ issuerId: Number(user.documentIssuers.ids),
664
+ issuerName: user.documentIssuers.nameKz,
665
+ issuerNameRu: user.documentIssuers.nameRu,
666
+ note: null,
667
+ number: user.documentNumber,
668
+ type: user.documentType.ids,
669
+ typeName: user.documentType.nameRu,
670
+ serial: null,
671
+ verifyType: user.verifyType,
672
+ verifyDate: user.verifyDate,
673
+ });
674
+
675
+ const checkForNull = value => (value ? value : '');
676
+
677
+ // ! SaveContragent -> Addresses
678
+ let addressData = [];
679
+ addressData.push({
680
+ id: 'response' in user && 'addresses' in user.response ? user.response.addresses[0].id : 0,
681
+ contragentId: user.id,
682
+ countryCode: user.birthPlace.ids,
683
+ countryName: user.birthPlace.nameRu,
684
+ stateCode: user.registrationProvince.ids,
685
+ stateName: user.registrationProvince.nameRu,
686
+ cityCode: user.registrationCity.code,
687
+ cityName: user.registrationCity.nameRu,
688
+ regionCode: user.registrationRegion.ids,
689
+ regionName: user.registrationRegion.nameRu,
690
+ streetName: user.registrationStreet,
691
+ kvartal: user.registrationQuarter,
692
+ microRaion: user.registrationMicroDistrict,
693
+ cityTypeId: Number(user.registrationRegionType.ids) > 0 ? Number(user.registrationRegionType.ids) : null,
694
+ cityTypeName: user.registrationRegionType.nameRu,
695
+ blockNumber: user.registrationNumberHouse,
696
+ apartmentNumber: user.registrationNumberApartment,
697
+ address: `${checkForNull(user.birthPlace.nameRu)}, ${checkForNull(user.registrationRegionType.nameRu)} ${checkForNull(user.registrationCity.nameRu)}, ул. ${checkForNull(
698
+ user.registrationStreet,
699
+ )}, д. ${checkForNull(user.registrationNumberHouse)} кв. ${checkForNull(user.registrationNumberApartment)}`,
700
+
701
+ type: 'H',
702
+ });
703
+
704
+ const data = {
705
+ contragent: contragentData,
706
+ questionaries: questionariesData,
707
+ contacts: contactsData,
708
+ documents: documentsData,
709
+ addresses: addressData,
710
+ };
711
+
712
+ const personId = await this.api.saveContragent(data);
713
+ if (personId) {
714
+ await this.getContragentById(personId, whichForm, false, whichIndex);
715
+ user.otpTokenId = null;
716
+ }
717
+ } catch (err) {
718
+ this.isLoading = false;
719
+ return ErrorHandler(err);
720
+ }
721
+ if (onlySaveAction) {
722
+ this.isLoading = false;
723
+ }
724
+ return true;
725
+ },
726
+ async saveMember(member, whichMember, memberFromApplicaiton) {
727
+ let data = {};
728
+ try {
729
+ data = {
730
+ processInstanceId: this.formStore.applicationData.processInstanceId,
731
+ insisId: member.id,
732
+ iin: member.iin.replace(/-/g, ''),
733
+ longName: member.longName,
734
+ isIpdl: member.signOfIPDL.nameRu == 'Да' ? true : false,
735
+ isTerror: member.isTerror,
736
+ isIpdlCompliance: null,
737
+ isTerrorCompliance: null,
738
+ };
739
+ data.id = memberFromApplicaiton && memberFromApplicaiton.id ? memberFromApplicaiton.id : null;
740
+ if (whichMember === 'Client') {
741
+ data.isInsured = this.formStore.isPolicyholderInsured;
742
+ data.isActOwnBehalf = this.formStore.isActOwnBehalf;
743
+ data.profession = member.job;
744
+ data.position = member.jobPosition;
745
+ data.jobName = member.jobPlace;
746
+ data.familyStatusId = member.familyStatus.id;
747
+ }
748
+ if (whichMember === 'Spokesman') {
749
+ if (!!memberFromApplicaiton && memberFromApplicaiton.iin !== data.iin) {
750
+ delete data.id;
751
+ await this.api.deleteMember('Spokesman', this.formStore.applicationData.processInstanceId);
752
+ }
753
+ data.migrationCard = member.migrationCard;
754
+ const migrationCardIssueDate = formatDate(member.migrationCardIssueDate);
755
+ if (migrationCardIssueDate) data.migrationCardIssueDate = migrationCardIssueDate.toISOString();
756
+ const migrationCardExpireDate = formatDate(member.migrationCardExpireDate);
757
+ if (migrationCardExpireDate) data.migrationCardExpireDate = migrationCardExpireDate.toISOString();
758
+ data.confirmDocType = member.confirmDocType;
759
+ data.confirmDocNumber = member.confirmDocNumber;
760
+ const confirmDocIssueDate = formatDate(member.confirmDocIssueDate);
761
+ if (confirmDocIssueDate) data.confirmDocIssueDate = confirmDocIssueDate.toISOString();
762
+ const confirmDocExpireDate = formatDate(member.confirmDocExpireDate);
763
+ if (confirmDocExpireDate) data.confirmDocExpireDate = confirmDocExpireDate.toISOString();
764
+ data.clientLongName = this.formStore.applicationData.clientApp.longName;
765
+ data.notaryLongName = member.notaryLongName;
766
+ data.notaryLicenseNumber = member.notaryLicenseNumber;
767
+ const notaryLicenseDate = formatDate(member.notaryLicenseDate);
768
+ if (notaryLicenseDate) data.notaryLicenseDate = notaryLicenseDate.toISOString();
769
+ data.notaryLicenseIssuer = member.notaryLicenseIssuer;
770
+ data.jurLongName = member.jurLongName;
771
+ data.fullNameRod = member.fullNameRod;
772
+ data.confirmDocTypeKz = member.confirmDocTypeKz;
773
+ data.confirmDocTypeRod = member.confirmDocTypeRod;
774
+ data.isNotary = member.isNotary;
775
+ }
776
+ if (whichMember === 'Insured') {
777
+ if (
778
+ this.formStore.applicationData &&
779
+ this.formStore.applicationData.insuredApp &&
780
+ this.formStore.applicationData.insuredApp.length &&
781
+ this.formStore.applicationData.insuredApp.every(i => i.iin !== data.iin) &&
782
+ data.id !== null
783
+ ) {
784
+ await this.api.deleteMember('Insured', data.id);
785
+ delete data.id;
786
+ }
787
+ data.isDisability = this.formStore.isPolicyholderInsured ? false : member.isDisability.nameRu == 'Да';
788
+ data.disabilityGroupId = data.isDisability ? member.disabilityGroupId.id : null;
789
+ data.profession = member.job;
790
+ data.position = member.jobPosition;
791
+ data.jobName = member.jobPlace;
792
+ data.familyStatusId = member.familyStatus.id;
793
+ data.relationId = member.relationDegree.ids;
794
+ data.relationName = member.relationDegree.nameRu;
795
+ }
796
+ if (whichMember === 'Beneficiary') {
797
+ if (
798
+ this.formStore.applicationData &&
799
+ this.formStore.applicationData.beneficiaryApp &&
800
+ this.formStore.applicationData.beneficiaryApp.length &&
801
+ this.formStore.applicationData.beneficiaryApp.every(i => i.iin !== data.iin) &&
802
+ data.id !== null
803
+ ) {
804
+ await this.api.deleteMember('Beneficiary', data.id);
805
+ delete data.id;
806
+ }
807
+ data.familyStatusId = member.familyStatus.id == 0 ? null : member.familyStatus.id;
808
+ data.percentage = Number(member.percentageOfPayoutAmount);
809
+ data.relationId = member.relationDegree.ids;
810
+ data.relationName = member.relationDegree.nameRu;
811
+ }
812
+ if (whichMember === 'BeneficialOwner') {
813
+ if (data.id === 0) {
814
+ data.id = null;
815
+ }
816
+ if (
817
+ this.formStore.applicationData &&
818
+ this.formStore.applicationData.beneficialOwnerApp &&
819
+ this.formStore.applicationData.beneficialOwnerApp.length &&
820
+ this.formStore.applicationData.beneficialOwnerApp.every(i => i.iin !== data.iin) &&
821
+ data.id !== null
822
+ ) {
823
+ await this.api.deleteMember('BeneficialOwner', data.id);
824
+ delete data.id;
825
+ }
826
+ data.familyStatusId = member.familyStatus.id;
827
+ }
828
+ await this.api.setMember(whichMember, data);
829
+ return true;
830
+ } catch (err) {
831
+ return ErrorHandler(err, err.response?.data?.errors && Object.values(err.response?.data?.errors).join(' -> '));
832
+ }
833
+ },
834
+ searchFromList(member, searchIt) {
835
+ const getQuestionariesData = () => {
836
+ switch (searchIt.questId) {
837
+ case '500003':
838
+ return [this.economySectorCode, 'economySectorCode'];
839
+ case '500011':
840
+ return [this.residents, 'signOfResidency'];
841
+ case '500012':
842
+ return [this.citizenshipCountries, 'countryOfCitizenship'];
843
+ case '500014':
844
+ return [this.taxCountries, 'countryOfTaxResidency'];
845
+ case '507777':
846
+ return [this.addTaxCountries, 'addTaxResidency'];
847
+ case '500147':
848
+ return [[]];
849
+ case '500148':
850
+ return [[]];
851
+ }
852
+ };
853
+
854
+ const [searchFrom, whichField] = getQuestionariesData();
855
+ if (searchFrom && searchFrom.length) {
856
+ const result = searchFrom.find(i => i.ids === searchIt.questAnswer);
857
+ member[whichField] = result ? result : new Value();
858
+ }
859
+ },
860
+ async setSurvey(data) {
861
+ try {
862
+ this.isLoading = true;
863
+ const anketaToken = await this.api.setSurvey(data);
864
+ this.showToaster('success', this.t('toaster.successSaved'), 2000);
865
+ return anketaToken;
866
+ } catch (error) {
867
+ return ErrorHandler(err);
868
+ } finally {
869
+ this.isLoading = false;
870
+ }
871
+ },
872
+ async getFromApi(whichField, whichRequest, parameter, reset = false) {
873
+ const storageValue = JSON.parse(localStorage.getItem(whichField) || 'null');
874
+ const currentHour = new Date().getHours();
875
+ const currentMinutePart = Math.ceil((new Date().getMinutes() + 1) / 15);
876
+
877
+ const getDataCondition = () => {
878
+ if (!storageValue) return true;
879
+ const hasHourKey = 'hour' in storageValue;
880
+ const hasMiniteKey = 'minute' in storageValue;
881
+ const hasModeKey = 'mode' in storageValue;
882
+ const hasValueKey = 'value' in storageValue;
883
+ if (storageValue && (hasHourKey === false || hasMiniteKey === false || hasModeKey === false || hasValueKey === false)) return true;
884
+ if (
885
+ storageValue &&
886
+ (storageValue.hour !== currentHour || storageValue.minute !== currentMinutePart || storageValue.mode !== import.meta.env.MODE || storageValue.value.length === 0)
887
+ )
888
+ return true;
889
+ };
890
+ if (!!getDataCondition() || reset === true) {
891
+ this[whichField] = [];
892
+ try {
893
+ const response = await this.api[whichRequest](parameter);
894
+ if (response) {
895
+ localStorage.setItem(
896
+ whichField,
897
+ JSON.stringify({
898
+ value: response,
899
+ hour: currentHour,
900
+ minute: currentMinutePart,
901
+ mode: import.meta.env.MODE,
902
+ }),
903
+ );
904
+ this[whichField] = response;
905
+ }
906
+ } catch (err) {
907
+ console.log(err);
908
+ }
909
+ } else {
910
+ this[whichField] = storageValue.value;
911
+ }
912
+
913
+ return this[whichField];
914
+ },
915
+ async getCountries() {
916
+ return await this.getFromApi('countries', 'getCountries');
917
+ },
918
+ async getCitizenshipCountries() {
919
+ return await this.getFromApi('citizenshipCountries', 'getCitizenshipCountries');
920
+ },
921
+ async getTaxCountries() {
922
+ return await this.getFromApi('taxCountries', 'getTaxCountries');
923
+ },
924
+ async getAdditionalTaxCountries() {
925
+ return await this.getFromApi('addTaxCountries', 'getAdditionalTaxCountries');
926
+ },
927
+ async getStates(key, member) {
928
+ await this.getFromApi('states', 'getStates');
929
+ if (key && member[key] && member[key].ids !== null) {
930
+ return this.states.filter(i => i.code === member[key].ids);
931
+ }
932
+ return this.states;
933
+ },
934
+ async getRegions(key, member) {
935
+ await this.getFromApi('regions', 'getRegions');
936
+ if (key && member[key] && member[key].ids !== null) {
937
+ return this.regions.filter(i => i.code === member[key].ids);
938
+ }
939
+ if (member.registrationProvince.ids !== null) {
940
+ return this.regions.filter(i => i.code === member.registrationProvince.ids);
941
+ } else {
942
+ return this.regions;
943
+ }
944
+ },
945
+ async getCities(key, member) {
946
+ await this.getFromApi('cities', 'getCities');
947
+ if (key && member[key] && member[key].ids !== null) {
948
+ return this.cities.filter(i => i.code === member[key].ids);
949
+ }
950
+ if (member.registrationProvince.ids !== null) {
951
+ return this.cities.filter(i => i.code === member.registrationProvince.ids);
952
+ } else {
953
+ return this.cities;
954
+ }
955
+ },
956
+ async getLocalityTypes() {
957
+ return await this.getFromApi('localityTypes', 'getLocalityTypes');
958
+ },
959
+ async getDocumentTypes() {
960
+ const document_list = await this.getFromApi('documentTypes', 'getDocumentTypes');
961
+ await this.getDicFileTypeList();
962
+ return document_list.filter(doc => {
963
+ for (const dic of this.dicFileTypeList) {
964
+ if (doc.nameRu === dic.nameRu) {
965
+ return doc;
966
+ }
967
+ }
968
+ });
969
+ },
970
+ async getDicFileTypeList() {
971
+ return await this.getFromApi('dicFileTypeList', 'getDicFileTypeList');
972
+ },
973
+ async getDocumentIssuers() {
974
+ return await this.getFromApi('documentIssuers', 'getDocumentIssuers');
975
+ },
976
+ async getResidents() {
977
+ return await this.getFromApi('residents', 'getResidents');
978
+ },
979
+ async getSectorCodeList() {
980
+ await this.getFromApi('economySectorCode', 'getSectorCode');
981
+ return this.economySectorCode;
982
+ },
983
+ async getFamilyStatuses() {
984
+ return await this.getFromApi('familyStatuses', 'getFamilyStatuses');
985
+ },
986
+ async getRelationTypes() {
987
+ // TODO Remove this & add filtering in openPanel method
988
+ await this.getFromApi('relations', 'getRelationTypes');
989
+ const filteredRelations = this.relations.filter(i => Number(i.ids) >= 6 && Number(i.ids) <= 15);
990
+ const otherRelations = this.relations.filter(i => Number(i.ids) < 6 || Number(i.ids) > 15);
991
+ return [...filteredRelations, ...otherRelations];
992
+ },
993
+ async getProcessIndexRate() {
994
+ const response = await this.getFromApi('processIndexRate', 'getProcessIndexRate', this.processCode);
995
+ return response ? response : [];
996
+ },
997
+ async getProcessCoverTypeSum(type) {
998
+ return await this.getFromApi('processCoverTypeSum', 'getProcessCoverTypeSum', type);
999
+ },
1000
+ async getProcessPaymentPeriod() {
1001
+ return await this.getFromApi('processPaymentPeriod', 'getProcessPaymentPeriod', this.processCode);
1002
+ },
1003
+ async getQuestionRefs(id) {
1004
+ return await this.getFromApi('questionRefs', 'getQuestionRefs', id, true);
1005
+ },
1006
+ async getProcessTariff() {
1007
+ return await this.getFromApi('processTariff', 'getProcessTariff');
1008
+ },
1009
+ async getCurrencies() {
1010
+ try {
1011
+ const currencies = await this.api.getCurrencies();
1012
+ this.currencies = currencies;
1013
+ return currencies;
1014
+ } catch (err) {
1015
+ console.log(err);
1016
+ }
1017
+ },
1018
+ async getAdditionalInsuranceTermsAnswers(questionId) {
1019
+ try {
1020
+ const answers = await this.api.getAdditionalInsuranceTermsAnswers(this.processCode, questionId);
1021
+ return answers;
1022
+ } catch (err) {
1023
+ console.log(err);
1024
+ }
1025
+ },
1026
+ async getQuestionList(surveyType, processInstanceId, insuredId, baseField, secondaryField) {
1027
+ if (!this.formStore[baseField] || (this.formStore[baseField] && !this.formStore[baseField].length)) {
1028
+ try {
1029
+ const [{ value: baseQuestions }, { value: secondaryQuestions }] = await Promise.allSettled([
1030
+ this.api.getQuestionList(surveyType, processInstanceId, insuredId),
1031
+ this.api.getQuestionListSecond(`${surveyType}second`, processInstanceId, insuredId),
1032
+ ]);
1033
+ this.formStore[baseField] = baseQuestions;
1034
+ this.formStore[secondaryField] = secondaryQuestions;
1035
+ } catch (err) {
1036
+ console.log(err);
1037
+ }
1038
+ }
1039
+ return this.formStore[baseField];
1040
+ },
1041
+ getNumberWithSpaces(n) {
1042
+ return n === null ? null : Number((typeof n === 'string' ? n : n.toFixed().toString()).replace(/[^0-9]+/g, '')).toLocaleString('ru');
1043
+ },
1044
+ async getTaskList(search = '', groupCode = 'Work', onlyGet = false, needToReturn = false, key = 'dateCreated', processInstanceId = null, byOneProcess = null) {
1045
+ if (onlyGet === false) {
1046
+ this.isLoading = true;
1047
+ }
1048
+ try {
1049
+ const column = this.isColumnAsc[key] === null ? 'dateCreated' : key;
1050
+ const direction = this.isColumnAsc[key] === null ? 'desc' : this.isColumnAsc[key] === true ? 'asc' : 'desc';
1051
+ const query = {
1052
+ pageIndex: processInstanceId === null ? this.historyPageIndex - 1 : 0,
1053
+ pageSize: this.historyPageSize,
1054
+ search: search ? search.replace(/-/g, '') : '',
1055
+ column: column,
1056
+ direction: direction,
1057
+ groupCode: groupCode,
1058
+ processCodes: Object.values(constants.products),
1059
+ };
1060
+ if (byOneProcess !== null) {
1061
+ delete query.processCodes;
1062
+ query.processCode = byOneProcess;
1063
+ }
1064
+ const taskList = await this.api.getTaskList(processInstanceId === null ? query : { ...query, processInstanceId: processInstanceId });
1065
+ if (needToReturn) {
1066
+ this.isLoading = false;
1067
+ return taskList.items;
1068
+ } else {
1069
+ this.taskList = taskList.items;
1070
+ this.historyTotalItems = taskList.totalItems;
1071
+ }
1072
+ } catch (err) {
1073
+ this.showToaster('error', err?.response?.data, 2000);
1074
+ console.log(err);
1075
+ } finally {
1076
+ this.isLoading = false;
1077
+ }
1078
+ if (onlyGet === false) {
1079
+ this.isLoading = false;
1080
+ }
1081
+ },
1082
+ async getProcessHistoryList(id) {
1083
+ try {
1084
+ const processHistory = await this.api.getProcessHistory(id);
1085
+ if (processHistory.length > 0) {
1086
+ return processHistory;
1087
+ } else {
1088
+ return [];
1089
+ }
1090
+ } catch (err) {
1091
+ console.log(err);
1092
+ }
1093
+ },
1094
+ async getProcessHistory(id) {
1095
+ this.isLoading = true;
1096
+ try {
1097
+ const processHistory = await this.api.getProcessHistory(id);
1098
+ if (processHistory.length > 0) {
1099
+ this.processHistory = processHistory.reverse();
1100
+ } else {
1101
+ this.processHistory = [];
1102
+ }
1103
+ } catch (err) {
1104
+ console.log(err);
1105
+ }
1106
+ this.isLoading = false;
1107
+ },
1108
+ findObject(from, key, searchKey) {
1109
+ const found = this[from].find(i => i[key] == searchKey);
1110
+ return found || new Value();
1111
+ },
1112
+ async getAllFormsData() {
1113
+ await Promise.allSettled([
1114
+ this.getCountries(),
1115
+ this.getCitizenshipCountries(),
1116
+ this.getTaxCountries(),
1117
+ this.getAdditionalTaxCountries(),
1118
+ this.getStates(),
1119
+ this.getRegions(),
1120
+ this.getCities(),
1121
+ this.getLocalityTypes(),
1122
+ this.getDocumentTypes(),
1123
+ this.getDocumentIssuers(),
1124
+ this.getResidents(),
1125
+ this.getSectorCodeList(),
1126
+ this.getFamilyStatuses(),
1127
+ this.getRelationTypes(),
1128
+ this.getProcessIndexRate(),
1129
+ this.getProcessTariff(),
1130
+ this.getProcessPaymentPeriod(),
1131
+ this.getDicFileTypeList(),
1132
+ this.getDictionaryItems('RegionPolicy'),
1133
+ this.getDictionaryItems('SaleChanellPolicy'),
1134
+ ]);
1135
+ },
1136
+ async getUserGroups() {
1137
+ try {
1138
+ this.isLoading = true;
1139
+ this.userGroups = await this.api.getUserGroups();
1140
+ } catch (err) {
1141
+ console.log(err);
1142
+ } finally {
1143
+ this.isLoading = false;
1144
+ }
1145
+ },
1146
+ async getProcessList() {
1147
+ this.isLoading = true;
1148
+ try {
1149
+ const processList = await this.api.getProcessList();
1150
+ if (this.processList === null) {
1151
+ this.processList = processList;
1152
+ }
1153
+ } catch (err) {
1154
+ console.log(err);
1155
+ }
1156
+ this.isLoading = false;
1157
+ },
1158
+ sortTaskList(key) {
1159
+ if (this.taskList.length !== 0) {
1160
+ if (key in this.isColumnAsc) {
1161
+ if (this.isColumnAsc[key] === true) {
1162
+ this.isColumnAsc = { ...InitialColumns() };
1163
+ this.isColumnAsc[key] = false;
1164
+ return;
1165
+ }
1166
+ if (this.isColumnAsc[key] === false) {
1167
+ this.isColumnAsc = { ...InitialColumns() };
1168
+ this.isColumnAsc[key] = null;
1169
+ return;
1170
+ }
1171
+ if (this.isColumnAsc[key] === null) {
1172
+ this.isColumnAsc = { ...InitialColumns() };
1173
+ this.isColumnAsc[key] = true;
1174
+ return;
1175
+ }
1176
+ }
1177
+ }
1178
+ },
1179
+ async searchAgentByName(name) {
1180
+ try {
1181
+ this.AgentData = await this.api.searchAgentByName(name);
1182
+ if (!this.AgentData.length) {
1183
+ this.showToaster('error', this.t('toaster.notFound'), 1500);
1184
+ }
1185
+ } catch (err) {
1186
+ console.log(err);
1187
+ }
1188
+ },
1189
+ async setINSISWorkData() {
1190
+ const data = {
1191
+ id: this.formStore.applicationData.insisWorkDataApp.id,
1192
+ processInstanceId: this.formStore.applicationData.processInstanceId,
1193
+ agentId: this.formStore.AgentData.agentId,
1194
+ agentName: this.formStore.AgentData.fullName,
1195
+ salesChannel: this.formStore.applicationData.insisWorkDataApp.salesChannel,
1196
+ salesChannelName: this.formStore.applicationData.insisWorkDataApp.salesChannelName,
1197
+ insrType: this.formStore.applicationData.insisWorkDataApp.insrType,
1198
+ saleChanellPolicy: this.formStore.SaleChanellPolicy.ids,
1199
+ saleChanellPolicyName: this.formStore.SaleChanellPolicy.nameRu,
1200
+ regionPolicy: this.formStore.RegionPolicy.ids,
1201
+ regionPolicyName: this.formStore.RegionPolicy.nameRu,
1202
+ managerPolicy: this.formStore.ManagerPolicy.ids,
1203
+ managerPolicyName: this.formStore.ManagerPolicy.nameRu,
1204
+ insuranceProgramType: this.formStore.applicationData.insisWorkDataApp.insuranceProgramType,
1205
+ };
1206
+ try {
1207
+ this.isLoading = true;
1208
+ await this.api.setINSISWorkData(data);
1209
+ } catch (err) {
1210
+ console.log(err);
1211
+ } finally {
1212
+ this.isLoading = false;
1213
+ }
1214
+ },
1215
+ async getDictionaryItems(dictName) {
1216
+ return await this.getFromApi(dictName, 'getDictionaryItems', dictName);
1217
+ },
1218
+ async filterManagerByRegion(filterName) {
1219
+ try {
1220
+ this.ManagerPolicy = await this.api.filterManagerByRegion('ManagerPolicy', filterName);
1221
+ } catch (err) {
1222
+ console.log(err);
1223
+ }
1224
+ },
1225
+ async getUnderwritingCouncilData(id) {
1226
+ try {
1227
+ const response = await this.api.getUnderwritingCouncilData(id);
1228
+ this.formStore.affilationResolution.id = response.underwritingCouncilAppDto.id;
1229
+ this.formStore.affilationResolution.date = response.underwritingCouncilAppDto.date ? reformatDate(response.underwritingCouncilAppDto.date) : null;
1230
+ this.formStore.affilationResolution.number = response.underwritingCouncilAppDto.number ? response.underwritingCouncilAppDto.number : null;
1231
+ } catch (err) {
1232
+ console.log(err);
1233
+ }
1234
+ },
1235
+ async setConfirmation() {
1236
+ const data = {
1237
+ id: this.formStore.affilationResolution.id,
1238
+ processInstanceId: this.formStore.affilationResolution.processInstanceId,
1239
+ number: this.formStore.affilationResolution.number,
1240
+ date: formatDate(this.formStore.affilationResolution.date)?.toISOString(),
1241
+ };
1242
+ try {
1243
+ this.isLoading = true;
1244
+ await this.api.setConfirmation(data);
1245
+ this.showToaster('success', this.t('toaster.successSaved'));
1246
+ return true;
1247
+ } catch (err) {
1248
+ this.showToaster('error', this.t('toaster.error'));
1249
+ return false;
1250
+ } finally {
1251
+ this.isLoading = false;
1252
+ }
1253
+ },
1254
+ async sendUnderwritingCouncilTask(data) {
1255
+ try {
1256
+ this.isLoading = true;
1257
+ await this.api.sendUnderwritingCouncilTask(data);
1258
+ this.showToaster('success', this.t('toaster.successOperation'), 5000);
1259
+ return true;
1260
+ } catch (err) {
1261
+ console.log(err);
1262
+ this.showToaster('error', this.t('toaster.error'), 5000);
1263
+ return false;
1264
+ } finally {
1265
+ this.isLoading = false;
1266
+ }
1267
+ },
1268
+ async definedAnswers(filter, whichSurvey, value = null, index = null) {
1269
+ if (!this.formStore.definedAnswersId[whichSurvey].hasOwnProperty(filter)) {
1270
+ this.formStore.definedAnswersId[whichSurvey][filter] = await this.api.definedAnswers(filter);
1271
+ }
1272
+ if (value !== null && this.formStore.definedAnswersId[whichSurvey][filter].length) {
1273
+ const answer = this.formStore.definedAnswersId[whichSurvey][filter].find(answer => answer.nameRu === value);
1274
+ this.formStore[whichSurvey].body[index].first.answerId = answer.ids;
1275
+ }
1276
+ return this.formStore.definedAnswersId[whichSurvey];
1277
+ },
1278
+ async getPaymentTable(id) {
1279
+ try {
1280
+ const paymentResultTable = await this.api.calculatePremuim(id);
1281
+ if (paymentResultTable.length > 0) {
1282
+ this.paymentResultTable = paymentResultTable;
1283
+ } else {
1284
+ this.paymentResultTable = [];
1285
+ }
1286
+ } catch (err) {
1287
+ console.log(err);
1288
+ }
1289
+ },
1290
+ async getDefaultCalculationData(showLoader = false) {
1291
+ this.isLoading = showLoader;
1292
+ try {
1293
+ const calculationData = await this.api.getDefaultCalculationData();
1294
+ return calculationData;
1295
+ } catch (err) {
1296
+ ErrorHandler(err);
1297
+ } finally {
1298
+ this.isLoading = false;
1299
+ }
1300
+ },
1301
+ async calculateWithoutApplication(showLoader = false) {
1302
+ this.isLoading = showLoader;
1303
+ try {
1304
+ const calculationData = {
1305
+ signDate: formatDate(this.formStore.productConditionsForm.signDate)?.toISOString(),
1306
+ birthDate: formatDate(this.formStore.productConditionsForm.birthDate)?.toISOString(),
1307
+ gender: this.formStore.productConditionsForm.gender.id,
1308
+ amount: getNumber(this.formStore.productConditionsForm.requestedSumInsured),
1309
+ premium: getNumber(this.formStore.productConditionsForm.insurancePremiumPerMonth),
1310
+ coverPeriod: this.formStore.productConditionsForm.coverPeriod,
1311
+ payPeriod: this.formStore.productConditionsForm.coverPeriod,
1312
+ indexRateId: this.formStore.productConditionsForm.processIndexRate?.id
1313
+ ? this.formStore.productConditionsForm.processIndexRate.id
1314
+ : this.processIndexRate.find(i => i.code === '0')?.id,
1315
+ paymentPeriodId: this.formStore.productConditionsForm.paymentPeriod.id,
1316
+ addCovers: this.formStore.additionalInsuranceTermsWithout,
1317
+ };
1318
+ if (this.isKazyna) {
1319
+ calculationData.premiumInCurrency = getNumber(this.formStore.productConditionsForm.insurancePremiumPerMonthInDollar);
1320
+ calculationData.amountInCurrency = getNumber(this.formStore.productConditionsForm.requestedSumInsuredInDollar);
1321
+ }
1322
+ const calculationResponse = await this.api.calculateWithoutApplication(calculationData);
1323
+ this.formStore.productConditionsForm.requestedSumInsured = this.getNumberWithSpaces(calculationResponse.amount);
1324
+ this.formStore.productConditionsForm.insurancePremiumPerMonth = this.getNumberWithSpaces(calculationResponse.premium);
1325
+ this.formStore.additionalInsuranceTermsWithout = calculationResponse.addCovers;
1326
+ if (this.isKazyna) {
1327
+ this.formStore.productConditionsForm.requestedSumInsuredInDollar = this.getNumberWithSpaces(calculationResponse.amountInCurrency);
1328
+ this.formStore.productConditionsForm.insurancePremiumPerMonthInDollar = this.getNumberWithSpaces(calculationResponse.premiumInCurrency);
1329
+ }
1330
+ this.showToaster('success', this.t('toaster.calculated'), 1000);
1331
+ } catch (err) {
1332
+ ErrorHandler(err);
1333
+ } finally {
1334
+ this.isLoading = false;
1335
+ return !!this.formStore.productConditionsForm.requestedSumInsured && !!this.formStore.productConditionsForm.insurancePremiumPerMonth;
1336
+ }
1337
+ },
1338
+ async calculate(taskId) {
1339
+ this.isLoading = true;
1340
+ try {
1341
+ let form1 = {
1342
+ baiterekApp: null,
1343
+ policyAppDto: {
1344
+ id: this.formStore.applicationData.policyAppDto.id,
1345
+ processInstanceId: this.formStore.applicationData.policyAppDto.processInstanceId,
1346
+ policyId: null,
1347
+ policyNumber: null,
1348
+ contractDate: this.currentDate(),
1349
+ amount: this.formStore.productConditionsForm.requestedSumInsured != null ? Number(this.formStore.productConditionsForm.requestedSumInsured.replace(/\s/g, '')) : null,
1350
+ premium:
1351
+ this.formStore.productConditionsForm.insurancePremiumPerMonth != null
1352
+ ? Number(this.formStore.productConditionsForm.insurancePremiumPerMonth.replace(/\s/g, ''))
1353
+ : null,
1354
+ isSpokesman: this.formStore.hasRepresentative,
1355
+ coverPeriod: this.formStore.productConditionsForm.coverPeriod,
1356
+ payPeriod: this.formStore.productConditionsForm.coverPeriod,
1357
+ annualIncome: this.formStore.productConditionsForm.annualIncome ? Number(this.formStore.productConditionsForm.annualIncome.replace(/\s/g, '')) : null,
1358
+ indexRateId: this.formStore.productConditionsForm.processIndexRate?.id
1359
+ ? this.formStore.productConditionsForm.processIndexRate.id
1360
+ : this.processIndexRate.find(i => i.code === '0')?.id,
1361
+ paymentPeriodId: this.formStore.productConditionsForm.paymentPeriod.id,
1362
+ lifeMultiply: formatProcents(this.formStore.productConditionsForm.lifeMultiply),
1363
+ lifeAdditive: formatProcents(this.formStore.productConditionsForm.lifeAdditive),
1364
+ adbMultiply: formatProcents(this.formStore.productConditionsForm.adbMultiply),
1365
+ adbAdditive: formatProcents(this.formStore.productConditionsForm.adbAdditive),
1366
+ disabilityMultiply: formatProcents(this.formStore.productConditionsForm.disabilityMultiply),
1367
+ disabilityAdditive: formatProcents(this.formStore.productConditionsForm.adbAdditive),
1368
+ riskGroup: this.formStore.productConditionsForm.riskGroup?.id ? this.formStore.productConditionsForm.riskGroup.id : 1,
1369
+ },
1370
+ addCoversDto: this.formStore.additionalInsuranceTerms,
1371
+ };
1372
+ if (this.isKazyna) {
1373
+ form1.policyAppDto.premiumInCurrency = getNumber(this.formStore.productConditionsForm.insurancePremiumPerMonthInDollar);
1374
+ form1.policyAppDto.amountInCurrency = getNumber(this.formStore.productConditionsForm.requestedSumInsuredInDollar);
1375
+ }
1376
+ try {
1377
+ let id = this.formStore.applicationData.processInstanceId;
1378
+
1379
+ await this.api.setApplication(form1);
1380
+ let result;
1381
+ try {
1382
+ result = await this.api.getCalculation(id);
1383
+ } catch (err) {
1384
+ ErrorHandler(err);
1385
+ }
1386
+
1387
+ const applicationData = await this.api.getApplicationData(taskId);
1388
+ this.formStore.applicationData = applicationData;
1389
+ this.formStore.additionalInsuranceTerms = this.formStore.applicationData.addCoverDto;
1390
+ if (this.isKazyna) {
1391
+ this.formStore.productConditionsForm.requestedSumInsuredInDollar = this.getNumberWithSpaces(result / this.currencies.usd);
1392
+ }
1393
+ if (this.formStore.productConditionsForm.insurancePremiumPerMonth != null) {
1394
+ this.formStore.productConditionsForm.requestedSumInsured = this.getNumberWithSpaces(result);
1395
+ } else {
1396
+ this.formStore.productConditionsForm.insurancePremiumPerMonth = this.getNumberWithSpaces(result);
1397
+ }
1398
+ this.showToaster('success', this.t('toaster.calculated'), 1000);
1399
+ } catch (err) {
1400
+ ErrorHandler(err);
1401
+ }
1402
+ } catch (err) {
1403
+ ErrorHandler(err);
1404
+ }
1405
+ this.isLoading = false;
1406
+ },
1407
+ async startApplication(member) {
1408
+ try {
1409
+ const data = {
1410
+ clientId: member.id,
1411
+ iin: member.iin.replace(/-/g, ''),
1412
+ longName: member.longName,
1413
+ processCode: this.processCode,
1414
+ policyId: 0,
1415
+ };
1416
+ const response = await this.api.startApplication(data);
1417
+ this.sendToParent(constants.postActions.applicationCreated, response.processInstanceId);
1418
+ return response.processInstanceId;
1419
+ } catch (err) {
1420
+ return ErrorHandler(err);
1421
+ }
1422
+ },
1423
+ async getApplicationData(taskId, onlyGet = true, setMembersField = true, fetchMembers = true, setProductConditions = true) {
1424
+ if (onlyGet) {
1425
+ this.isLoading = true;
1426
+ }
1427
+ try {
1428
+ const applicationData = await this.api.getApplicationData(taskId);
1429
+ if (this.processCode !== applicationData.processCode) {
1430
+ this.isLoading = false;
1431
+ this.sendToParent(constants.postActions.toHomePage, this.t('toaster.noSuchProduct'));
1432
+ return;
1433
+ }
1434
+ this.formStore.applicationData = applicationData;
1435
+ this.formStore.additionalInsuranceTerms = applicationData.addCoverDto;
1436
+
1437
+ this.formStore.canBeClaimed = await this.api.isClaimTask(taskId);
1438
+ this.formStore.applicationTaskId = taskId;
1439
+ this.formStore.RegionPolicy.nameRu = applicationData.insisWorkDataApp.regionPolicyName;
1440
+ this.formStore.RegionPolicy.ids = applicationData.insisWorkDataApp.regionPolicy;
1441
+ this.formStore.ManagerPolicy.nameRu = applicationData.insisWorkDataApp.managerPolicyName;
1442
+ this.formStore.ManagerPolicy.ids = applicationData.insisWorkDataApp.managerPolicy;
1443
+ this.formStore.SaleChanellPolicy.nameRu = applicationData.insisWorkDataApp.saleChanellPolicyName;
1444
+ this.formStore.SaleChanellPolicy.ids = applicationData.insisWorkDataApp.saleChanellPolicy;
1445
+
1446
+ this.formStore.AgentData.fullName = applicationData.insisWorkDataApp.agentName;
1447
+ this.formStore.AgentData.agentId = applicationData.insisWorkDataApp.agentId;
1448
+
1449
+ const clientData = applicationData.clientApp;
1450
+ const insuredData = applicationData.insuredApp;
1451
+ const spokesmanData = applicationData.spokesmanApp;
1452
+ const beneficiaryData = applicationData.beneficiaryApp;
1453
+ const beneficialOwnerData = applicationData.beneficialOwnerApp;
1454
+
1455
+ this.formStore.isPolicyholderInsured = clientData.isInsured;
1456
+ this.formStore.isActOwnBehalf = clientData.isActOwnBehalf;
1457
+ this.formStore.hasRepresentative = !!applicationData.spokesmanApp;
1458
+
1459
+ const beneficiaryPolicyholderIndex = beneficiaryData.findIndex(i => i.insisId === clientData.insisId);
1460
+ this.formStore.isPolicyholderBeneficiary = beneficiaryPolicyholderIndex !== -1;
1461
+
1462
+ if (fetchMembers) {
1463
+ let allMembers = [
1464
+ {
1465
+ ...clientData,
1466
+ key: this.formStore.policyholderFormKey,
1467
+ index: null,
1468
+ },
1469
+ ];
1470
+
1471
+ if (spokesmanData) {
1472
+ allMembers.push({
1473
+ ...spokesmanData,
1474
+ key: this.formStore.policyholdersRepresentativeFormKey,
1475
+ index: null,
1476
+ });
1477
+ }
1478
+
1479
+ if (insuredData && insuredData.length) {
1480
+ insuredData.forEach((member, index) => {
1481
+ const inStore = this.formStore.insuredForm.find(each => each.id == member.insisId);
1482
+ if (!inStore) {
1483
+ member.key = this.formStore.insuredFormKey;
1484
+ member.index = index;
1485
+ allMembers.push(member);
1486
+ if (this.formStore.insuredForm.length - 1 < index) {
1487
+ this.formStore.insuredForm.push(new InsuredForm());
1488
+ }
1489
+ }
1490
+ });
1491
+ }
1492
+ if (beneficiaryData && beneficiaryData.length) {
1493
+ beneficiaryData.forEach((member, index) => {
1494
+ const inStore = this.formStore.beneficiaryForm.find(each => each.id == member.insisId);
1495
+ if (!inStore) {
1496
+ member.key = this.formStore.beneficiaryFormKey;
1497
+ member.index = index;
1498
+ allMembers.push(member);
1499
+ if (this.formStore.beneficiaryForm.length - 1 < index) {
1500
+ this.formStore.beneficiaryForm.push(new BeneficiaryForm());
1501
+ }
1502
+ }
1503
+ });
1504
+ }
1505
+ if (beneficialOwnerData && beneficialOwnerData.length) {
1506
+ beneficialOwnerData.forEach((member, index) => {
1507
+ const inStore = this.formStore.beneficialOwnerForm.find(each => each.id == member.insisId);
1508
+ if (!inStore) {
1509
+ member.key = this.formStore.beneficialOwnerFormKey;
1510
+ member.index = index;
1511
+ allMembers.push(member);
1512
+ if (this.formStore.beneficialOwnerForm.length - 1 < index) {
1513
+ this.formStore.beneficialOwnerForm.push(new BeneficialOwnerForm());
1514
+ }
1515
+ }
1516
+ });
1517
+ }
1518
+
1519
+ await Promise.allSettled(
1520
+ allMembers.map(async member => {
1521
+ await this.getContragentById(member.insisId, member.key, false, member.index);
1522
+ }),
1523
+ );
1524
+ }
1525
+
1526
+ if (setMembersField) {
1527
+ this.setMembersField(this.formStore.policyholderFormKey, 'clientApp');
1528
+ if (insuredData && insuredData.length) {
1529
+ insuredData.forEach((each, index) => {
1530
+ const relationDegree = this.relations.find(i => i.ids == each.relationId);
1531
+ this.formStore.insuredForm[index].relationDegree = relationDegree ? relationDegree : new Value();
1532
+ this.setMembersFieldIndex(this.formStore.insuredFormKey, 'insuredApp', index);
1533
+ });
1534
+ }
1535
+
1536
+ if (beneficiaryData && beneficiaryData.length) {
1537
+ beneficiaryData.forEach((each, index) => {
1538
+ this.setMembersFieldIndex(this.formStore.beneficiaryFormKey, 'beneficiaryApp', index);
1539
+ const relationDegree = this.relations.find(i => i.ids == each.relationId);
1540
+ this.formStore.beneficiaryForm[index].relationDegree = relationDegree ? relationDegree : new Value();
1541
+ this.formStore.beneficiaryForm[index].percentageOfPayoutAmount = each.percentage;
1542
+ });
1543
+ }
1544
+
1545
+ if (beneficialOwnerData && beneficialOwnerData.length) {
1546
+ beneficialOwnerData.forEach((each, index) => {
1547
+ this.setMembersFieldIndex(this.formStore.beneficialOwnerFormKey, 'beneficialOwnerApp', index);
1548
+ });
1549
+ }
1550
+
1551
+ if (!!spokesmanData) {
1552
+ this.formStore.policyholdersRepresentativeForm.signOfIPDL = spokesmanData.isIpdl ? this.ipdl[1] : this.ipdl[2];
1553
+ this.formStore.policyholdersRepresentativeForm.migrationCard = spokesmanData.migrationCard;
1554
+ this.formStore.policyholdersRepresentativeForm.migrationCardIssueDate = reformatDate(spokesmanData.migrationCardIssueDate);
1555
+ this.formStore.policyholdersRepresentativeForm.migrationCardExpireDate = reformatDate(spokesmanData.migrationCardExpireDate);
1556
+ this.formStore.policyholdersRepresentativeForm.confirmDocType = spokesmanData.confirmDocType;
1557
+ this.formStore.policyholdersRepresentativeForm.confirmDocNumber = spokesmanData.confirmDocNumber;
1558
+ this.formStore.policyholdersRepresentativeForm.confirmDocIssueDate = reformatDate(spokesmanData.confirmDocIssueDate);
1559
+ this.formStore.policyholdersRepresentativeForm.confirmDocExpireDate = reformatDate(spokesmanData.confirmDocExpireDate);
1560
+ this.formStore.policyholdersRepresentativeForm.notaryLongName = spokesmanData.notaryLongName;
1561
+ this.formStore.policyholdersRepresentativeForm.notaryLicenseNumber = spokesmanData.notaryLicenseNumber;
1562
+ this.formStore.policyholdersRepresentativeForm.notaryLicenseDate = reformatDate(spokesmanData.notaryLicenseDate);
1563
+ this.formStore.policyholdersRepresentativeForm.notaryLicenseIssuer = spokesmanData.notaryLicenseIssuer;
1564
+ this.formStore.policyholdersRepresentativeForm.jurLongName = spokesmanData.jurLongName;
1565
+ this.formStore.policyholdersRepresentativeForm.fullNameRod = spokesmanData.fullNameRod;
1566
+ this.formStore.policyholdersRepresentativeForm.confirmDocTypeKz = spokesmanData.confirmDocTypeKz;
1567
+ this.formStore.policyholdersRepresentativeForm.confirmDocTypeRod = spokesmanData.confirmDocTypeRod;
1568
+ this.formStore.policyholdersRepresentativeForm.isNotary = spokesmanData.isNotary;
1569
+ }
1570
+ }
1571
+ if (setProductConditions) {
1572
+ this.formStore.productConditionsForm.coverPeriod = applicationData.policyAppDto.coverPeriod;
1573
+ this.formStore.productConditionsForm.payPeriod = applicationData.policyAppDto.payPeriod;
1574
+ // this.formStore.productConditionsForm.annualIncome = applicationData.policyAppDto.annualIncome?.toString();
1575
+ this.formStore.productConditionsForm.lifeMultiply = parseProcents(applicationData.policyAppDto.lifeMultiply);
1576
+ this.formStore.productConditionsForm.lifeAdditive = parseProcents(applicationData.policyAppDto.lifeAdditive);
1577
+ this.formStore.productConditionsForm.adbMultiply = parseProcents(applicationData.policyAppDto.adbMultiply);
1578
+ this.formStore.productConditionsForm.adbAdditive = parseProcents(applicationData.policyAppDto.adbAdditive);
1579
+ this.formStore.productConditionsForm.disabilityMultiply = parseProcents(applicationData.policyAppDto.disabilityMultiply);
1580
+ this.formStore.productConditionsForm.disabilityAdditive = parseProcents(applicationData.policyAppDto.disabilityAdditive);
1581
+
1582
+ let processIndexRate = this.processIndexRate.find(item => item.id == applicationData.policyAppDto.indexRateId);
1583
+ this.formStore.productConditionsForm.processIndexRate = processIndexRate ? processIndexRate : this.processIndexRate.find(item => item.code === '0');
1584
+
1585
+ let paymentPeriod = this.processPaymentPeriod.find(item => item.id == applicationData.policyAppDto.paymentPeriodId);
1586
+ this.formStore.productConditionsForm.paymentPeriod = paymentPeriod ? paymentPeriod : new Value();
1587
+
1588
+ this.formStore.productConditionsForm.requestedSumInsured = this.getNumberWithSpaces(
1589
+ applicationData.policyAppDto.amount === null ? null : applicationData.policyAppDto.amount,
1590
+ );
1591
+ this.formStore.productConditionsForm.insurancePremiumPerMonth = this.getNumberWithSpaces(
1592
+ applicationData.policyAppDto.premium === null ? null : applicationData.policyAppDto.premium,
1593
+ );
1594
+ if (this.isKazyna) {
1595
+ this.formStore.productConditionsForm.requestedSumInsuredInDollar = this.getNumberWithSpaces(applicationData.policyAppDto.amountInCurrency);
1596
+ this.formStore.productConditionsForm.insurancePremiumPerMonthInDollar = this.getNumberWithSpaces(applicationData.policyAppDto.premiumInCurrency);
1597
+ }
1598
+ let riskGroup = this.riskGroup.find(item => {
1599
+ if (applicationData.policyAppDto.riskGroup == 0) {
1600
+ return true;
1601
+ }
1602
+ return item.id == applicationData.policyAppDto.riskGroup;
1603
+ });
1604
+ this.formStore.productConditionsForm.riskGroup = riskGroup ? riskGroup : this.riskGroup.find(item => item.id == 1);
1605
+ }
1606
+ } catch (err) {
1607
+ console.log(err);
1608
+ if ('response' in err) {
1609
+ this.sendToParent(constants.postActions.toHomePage, err.response.data);
1610
+ this.isLoading = false;
1611
+ return false;
1612
+ }
1613
+ }
1614
+ if (onlyGet) {
1615
+ this.isLoading = false;
1616
+ }
1617
+ },
1618
+ async setApplication() {
1619
+ try {
1620
+ await this.api.setApplication(this.formStore.applicationData);
1621
+ } catch (err) {
1622
+ console.log(err);
1623
+ }
1624
+ },
1625
+ async deleteTask(taskId) {
1626
+ this.isLoading = true;
1627
+ try {
1628
+ const data = {
1629
+ taskId: taskId,
1630
+ decision: 'rejectclient',
1631
+ comment: 'Клиент отказался',
1632
+ };
1633
+ await this.api.sendTask(data);
1634
+ this.showToaster('success', this.t('toaster.applicationDeleted'), 2000);
1635
+ } catch (err) {
1636
+ this.isLoading = false;
1637
+ return ErrorHandler(err);
1638
+ }
1639
+ this.isLoading = false;
1640
+ },
1641
+ async sendTask(taskId, decision, comment = null) {
1642
+ this.isLoading = true;
1643
+ try {
1644
+ const data = {
1645
+ taskId: taskId,
1646
+ decision: decision,
1647
+ };
1648
+ await this.api.sendTask(comment === null ? data : { ...data, comment: comment });
1649
+ this.showToaster('success', this.t('toaster.successOperation'), 3000);
1650
+ this.isLoading = false;
1651
+ return true;
1652
+ } catch (err) {
1653
+ this.isLoading = false;
1654
+ return ErrorHandler(err);
1655
+ }
1656
+ },
1657
+ async handleTask(action, taskId, comment) {
1658
+ if (action && Object.keys(constants.actions).includes(action)) {
1659
+ this.isButtonsLoading = true;
1660
+ switch (action) {
1661
+ case constants.actions.claim: {
1662
+ try {
1663
+ this.isLoading = true;
1664
+ await this.api.claimTask(this.formStore.applicationTaskId);
1665
+ await this.getApplicationData(taskId, false, false, false);
1666
+ this.showToaster('success', this.t('toaster.successOperation'), 3000);
1667
+ } catch (err) {
1668
+ ErrorHandler(err);
1669
+ }
1670
+ break;
1671
+ }
1672
+ case constants.actions.reject:
1673
+ case constants.actions.return:
1674
+ case constants.actions.rejectclient:
1675
+ case constants.actions.accept: {
1676
+ try {
1677
+ const sended = await this.sendTask(taskId, action, comment);
1678
+ if (!sended) return;
1679
+ this.formStore.$reset();
1680
+ if (this.isEFO || this.isAML) {
1681
+ await this.router.push({ name: 'Insurance-Product' });
1682
+ } else {
1683
+ this.sendToParent(constants.postActions.toHomePage, this.t('toaster.successOperation') + 'SUCCESS');
1684
+ }
1685
+ } catch (err) {
1686
+ ErrorHandler(err);
1687
+ }
1688
+ break;
1689
+ }
1690
+ }
1691
+ this.isButtonsLoading = false;
1692
+ } else {
1693
+ console.error('No handleTask action');
1694
+ }
1695
+ },
1696
+ async getInvoiceData(processInstanceId) {
1697
+ try {
1698
+ const response = await this.api.getInvoiceData(processInstanceId);
1699
+ if (response) {
1700
+ return response;
1701
+ } else {
1702
+ return false;
1703
+ }
1704
+ } catch (err) {
1705
+ return false;
1706
+ }
1707
+ },
1708
+ async createInvoice() {
1709
+ try {
1710
+ const created = await this.api.createInvoice(this.formStore.applicationData.processInstanceId, this.formStore.applicationData.policyAppDto.premium);
1711
+ return !!created;
1712
+ } catch (err) {
1713
+ this.isLoading = false;
1714
+ }
1715
+ },
1716
+ async sendToEpay() {
1717
+ try {
1718
+ const response = await this.api.sendToEpay(this.formStore.applicationData.processInstanceId);
1719
+ if (response) {
1720
+ return response;
1721
+ }
1722
+ } catch (err) {
1723
+ console.log(err);
1724
+ }
1725
+ },
1726
+ setMembersField(whichForm, whichMember) {
1727
+ this.formStore[whichForm].familyStatus = this.findObject('familyStatuses', 'id', this.formStore.applicationData[whichMember].familyStatusId);
1728
+ this.formStore[whichForm].signOfIPDL = this.findObject(
1729
+ 'ipdl',
1730
+ 'nameRu',
1731
+ this.formStore.applicationData[whichMember].isIpdl === null ? null : this.formStore.applicationData[whichMember].isIpdl == true ? 'Да' : 'Нет',
1732
+ );
1733
+ if (!!this.formStore.applicationData[whichMember].profession) this.formStore[whichForm].job = this.formStore.applicationData[whichMember].profession;
1734
+ if (!!this.formStore.applicationData[whichMember].position) this.formStore[whichForm].jobPosition = this.formStore.applicationData[whichMember].position;
1735
+ if (!!this.formStore.applicationData[whichMember].jobName) this.formStore[whichForm].jobPlace = this.formStore.applicationData[whichMember].jobName;
1736
+ },
1737
+ setMembersFieldIndex(whichForm, whichMember, index) {
1738
+ if ('familyStatus' in this.formStore[whichForm][index]) {
1739
+ this.formStore[whichForm][index].familyStatus = this.findObject('familyStatuses', 'id', this.formStore.applicationData[whichMember][index].familyStatusId);
1740
+ }
1741
+ if ('signOfIPDL' in this.formStore[whichForm][index]) {
1742
+ this.formStore[whichForm][index].signOfIPDL = this.findObject(
1743
+ 'ipdl',
1744
+ 'nameRu',
1745
+ this.formStore.applicationData[whichMember][index].isIpdl === null ? null : this.formStore.applicationData[whichMember][index].isIpdl == true ? 'Да' : 'Нет',
1746
+ );
1747
+ }
1748
+ if ('job' in this.formStore[whichForm][index] && !!this.formStore.applicationData[whichMember][index].profession) {
1749
+ this.formStore[whichForm][index].job = this.formStore.applicationData[whichMember][index].profession;
1750
+ }
1751
+ if ('jobPosition' in this.formStore[whichForm][index] && !!this.formStore.applicationData[whichMember][index].position) {
1752
+ this.formStore[whichForm][index].jobPosition = this.formStore.applicationData[whichMember][index].position;
1753
+ }
1754
+ if ('jobPlace' in this.formStore[whichForm][index] && !!this.formStore.applicationData[whichMember][index].jobName) {
1755
+ this.formStore[whichForm][index].jobPlace = this.formStore.applicationData[whichMember][index].jobName;
1756
+ }
1757
+ },
1758
+ findObject(from, key, searchKey) {
1759
+ const found = this[from].find(i => i[key] == searchKey);
1760
+ return found || new Value();
1761
+ },
1762
+ async signDocument() {
1763
+ try {
1764
+ if (this.formStore.signUrls.length) {
1765
+ return this.formStore.signUrls;
1766
+ }
1767
+ const data = [
1768
+ { processInstanceId: this.formStore.applicationData.processInstanceId, name: 'Agreement', format: 'pdf' },
1769
+ { processInstanceId: this.formStore.applicationData.processInstanceId, name: 'Statement', format: 'pdf' },
1770
+ ];
1771
+ const result = await this.api.signDocument(data);
1772
+ this.formStore.signUrls = result;
1773
+ return this.formStore.signUrls;
1774
+ } catch (err) {
1775
+ ErrorHandler(err);
1776
+ }
1777
+ },
1778
+ async sendSMS(type, phoneNumber, text) {
1779
+ if (!type || !phoneNumber || !text) return;
1780
+ const smsData = {
1781
+ iin: this.formStore.applicationData.clientApp.iin,
1782
+ phoneNumber: formatPhone(phoneNumber),
1783
+ processInstanceId: this.formStore.applicationData.processInstanceId,
1784
+ text: text,
1785
+ type: type,
1786
+ };
1787
+ try {
1788
+ this.isLoading = true;
1789
+ await this.api.sendSms(smsData);
1790
+ this.showToaster('success', this.t('toaster.smsSendSuccessfully'), 3000);
1791
+ } catch (err) {
1792
+ ErrorHandler(err);
1793
+ } finally {
1794
+ this.isLoading = false;
1795
+ }
1796
+ },
1797
+ sanitize(text) {
1798
+ if (text) {
1799
+ return text
1800
+ .replace(/\r?\n|\r/g, '')
1801
+ .replace(/\\/g, '')
1802
+ .replace(/"/g, '');
1803
+ }
1804
+ },
1805
+ async getSignedDocList(processInstanceId) {
1806
+ if (processInstanceId !== 0) {
1807
+ try {
1808
+ this.formStore.signedDocumentList = await this.api.getSignedDocList({
1809
+ processInstanceId: processInstanceId,
1810
+ });
1811
+ } catch (err) {
1812
+ console.log(err);
1813
+ }
1814
+ }
1815
+ },
1816
+ setFormsDisabled(isDisabled) {
1817
+ Object.keys(this.formStore.isDisabled).forEach(key => {
1818
+ this.formStore.isDisabled[key] = !!isDisabled;
1819
+ });
1820
+ },
1821
+ async reCalculate(processInstanceId, recalculationData, taskId, whichSum) {
1822
+ this.isLoading = true;
1823
+ try {
1824
+ const data = {
1825
+ processInstanceId: processInstanceId,
1826
+ ...recalculationData,
1827
+ };
1828
+ const recalculatedValue = await this.api.reCalculate(data);
1829
+ if (!!recalculatedValue) {
1830
+ await this.getApplicationData(taskId, false, false, false);
1831
+ this.showToaster(
1832
+ 'success',
1833
+ `${this.t('toaster.successRecalculation')}. ${whichSum == 'insurancePremiumPerMonth' ? 'Страховая премия' : 'Страховая сумма'}: ${this.getNumberWithSpaces(
1834
+ recalculatedValue,
1835
+ )}₸`,
1836
+ 4000,
1837
+ );
1838
+ }
1839
+ } catch (err) {
1840
+ ErrorHandler(err);
1841
+ }
1842
+ this.isLoading = false;
1843
+ },
1844
+ async getValidateClientESBD(data) {
1845
+ try {
1846
+ return await this.api.getValidateClientESBD(data);
1847
+ } catch (err) {
1848
+ this.isLoading = false;
1849
+ return ErrorHandler(err);
1850
+ }
1851
+ },
1852
+ validateMultipleMembers(localKey, applicationKey, text) {
1853
+ if (this.formStore[localKey].length === this.formStore.applicationData[applicationKey].length) {
1854
+ if (this.formStore[localKey].length !== 0 && this.formStore.applicationData[applicationKey].length !== 0) {
1855
+ const localMembers = [...this.formStore[localKey]].sort((a, b) => a.id - b.id);
1856
+ const applicationMembers = [...this.formStore.applicationData[applicationKey]].sort((a, b) => a.insisId - b.insisId);
1857
+ if (localMembers.every((each, index) => applicationMembers[index].insisId === each.id && applicationMembers[index].iin === each.iin.replace(/-/g, '')) === false) {
1858
+ this.showToaster('error', this.t('toaster.notSavedMember', { text: text }), 3000);
1859
+ return false;
1860
+ }
1861
+ if (localKey === this.formStore.beneficiaryFormKey) {
1862
+ const sumOfPercentage = localMembers.reduce((sum, member) => {
1863
+ return sum + Number(member.percentageOfPayoutAmount);
1864
+ }, 0);
1865
+ if (sumOfPercentage !== 100) {
1866
+ this.showToaster('error', this.t('toaster.errorSumOrPercentage'), 3000);
1867
+ return false;
1868
+ }
1869
+ }
1870
+ }
1871
+ } else {
1872
+ if (this.formStore[localKey].some(i => i.iin !== null)) {
1873
+ this.showToaster('error', this.t('toaster.notSavedMember', { text: text }), 3000);
1874
+ return false;
1875
+ }
1876
+ if (this.formStore.applicationData[applicationKey].length !== 0) {
1877
+ this.showToaster('error', this.t('toaster.notSavedMember', { text: text }), 3000);
1878
+ return false;
1879
+ } else {
1880
+ if (this.formStore[localKey][0].iin !== null) {
1881
+ this.showToaster('error', this.t('toaster.notSavedMember', { text: text }), 3000);
1882
+ return false;
1883
+ }
1884
+ }
1885
+ }
1886
+ return true;
1887
+ },
1888
+ async validateAllMembers(taskId, localCheck = false) {
1889
+ if (taskId === '0') {
1890
+ this.showToaster('error', this.t('toaster.needToRunStatement'), 2000);
1891
+ return false;
1892
+ }
1893
+ if (this.formStore.policyholderForm.id !== this.formStore.applicationData.clientApp.insisId) {
1894
+ this.showToaster('error', this.t('toaster.notSavedMember', { text: 'страхователя' }), 3000);
1895
+ return false;
1896
+ }
1897
+ if (!this.isGons) {
1898
+ if (this.validateMultipleMembers(this.formStore.insuredFormKey, 'insuredApp', 'застрахованных') === false) {
1899
+ return false;
1900
+ }
1901
+ }
1902
+ if (this.validateMultipleMembers(this.formStore.beneficiaryFormKey, 'beneficiaryApp', 'выгодоприобретателей') === false) {
1903
+ return false;
1904
+ }
1905
+ if (!this.isGons) {
1906
+ if (this.formStore.isActOwnBehalf === false) {
1907
+ if (this.validateMultipleMembers(this.formStore.beneficialOwnerFormKey, 'beneficialOwnerApp', 'бенефициарных собственников') === false) {
1908
+ return false;
1909
+ }
1910
+ }
1911
+ }
1912
+ if (!this.isGons) {
1913
+ if (this.formStore.hasRepresentative) {
1914
+ if (this.formStore.applicationData.spokesmanApp && this.formStore.policyholdersRepresentativeForm.id !== this.formStore.applicationData.spokesmanApp.insisId) {
1915
+ this.showToaster(
1916
+ 'error',
1917
+ this.t('toaster.notSavedMember', {
1918
+ text: 'представителя страхователя',
1919
+ }),
1920
+ 3000,
1921
+ );
1922
+ return false;
1923
+ }
1924
+ }
1925
+ }
1926
+ if (this.controls.hasAttachment) {
1927
+ const areValid = this.formStore.SaleChanellPolicy.nameRu && this.formStore.RegionPolicy.nameRu && this.formStore.ManagerPolicy.nameRu && this.formStore.AgentData.fullName;
1928
+ if (areValid) {
1929
+ await this.setINSISWorkData();
1930
+ } else {
1931
+ this.isLoading = false;
1932
+ this.showToaster('error', this.t('toaster.attachManagerError'), 3000);
1933
+ return false;
1934
+ }
1935
+ }
1936
+ if (localCheck === false) {
1937
+ try {
1938
+ if (!this.isGons) {
1939
+ if (this.formStore.isActOwnBehalf === true && this.formStore.applicationData.beneficialOwnerApp.length !== 0) {
1940
+ await Promise.allSettled(
1941
+ this.formStore.applicationData.beneficialOwnerApp.map(async member => {
1942
+ await this.api.deleteMember('BeneficialOwner', member.id);
1943
+ }),
1944
+ );
1945
+ }
1946
+ }
1947
+ await this.getApplicationData(taskId, false);
1948
+ } catch (err) {
1949
+ console.log(err);
1950
+ this.showToaster('error', err, 5000);
1951
+ return false;
1952
+ }
1953
+ }
1954
+
1955
+ return true;
1956
+ },
1957
+ validateAnketa(whichSurvey) {
1958
+ const list = this.formStore[whichSurvey].body;
1959
+ if (!list || (list && list.length === 0)) return false;
1960
+ let notAnswered = 0;
1961
+ for (let x = 0; x < list.length; x++) {
1962
+ if ((list[x].first.definedAnswers === 'N' && !list[x].first.answerText) || (list[x].first.definedAnswers === 'Y' && !list[x].first.answerName)) {
1963
+ notAnswered = notAnswered + 1;
1964
+ }
1965
+ }
1966
+ return notAnswered === 0;
1967
+ },
1968
+ async validateAllForms(taskId) {
1969
+ this.isLoading = true;
1970
+ const areMembersValid = await this.validateAllMembers(taskId);
1971
+ if (areMembersValid) {
1972
+ if (!!this.formStore.productConditionsForm.insurancePremiumPerMonth && !!this.formStore.productConditionsForm.requestedSumInsured) {
1973
+ const hasCritical = this.formStore.additionalInsuranceTerms?.find(cover => cover.coverTypeName === 'Критическое заболевание Застрахованного');
1974
+ if (hasCritical && hasCritical.coverSumName !== 'не включено') {
1975
+ await Promise.allSettled([
1976
+ this.getQuestionList(
1977
+ 'health',
1978
+ this.formStore.applicationData.processInstanceId,
1979
+ this.formStore.applicationData.insuredApp[0].id,
1980
+ 'surveyByHealthBase',
1981
+ 'surveyByHealthSecond',
1982
+ ),
1983
+ this.getQuestionList(
1984
+ 'critical',
1985
+ this.formStore.applicationData.processInstanceId,
1986
+ this.formStore.applicationData.insuredApp[0].id,
1987
+ 'surveyByCriticalBase',
1988
+ 'surveyByCriticalSecond',
1989
+ ),
1990
+ ]);
1991
+ await Promise.allSettled([
1992
+ ...this.formStore.surveyByHealthBase.body.map(async question => {
1993
+ await this.definedAnswers(question.first.id, 'surveyByHealthBase');
1994
+ }),
1995
+ ...this.formStore.surveyByCriticalBase.body.map(async question => {
1996
+ await this.definedAnswers(question.first.id, 'surveyByCriticalBase');
1997
+ }),
1998
+ ]);
1999
+ } else {
2000
+ await Promise.allSettled([
2001
+ this.getQuestionList(
2002
+ 'health',
2003
+ this.formStore.applicationData.processInstanceId,
2004
+ this.formStore.applicationData.insuredApp[0].id,
2005
+ 'surveyByHealthBase',
2006
+ 'surveyByHealthSecond',
2007
+ ),
2008
+ ]);
2009
+ await Promise.allSettled(
2010
+ this.formStore.surveyByHealthBase.body.map(async question => {
2011
+ await this.definedAnswers(question.first.id, 'surveyByHealthBase');
2012
+ }),
2013
+ );
2014
+ }
2015
+
2016
+ if (this.validateAnketa('surveyByHealthBase')) {
2017
+ let hasCriticalAndItsValid = null;
2018
+ if (hasCritical && hasCritical.coverSumName !== 'не включено') {
2019
+ if (this.validateAnketa('surveyByCriticalBase')) {
2020
+ hasCriticalAndItsValid = true;
2021
+ } else {
2022
+ hasCriticalAndItsValid = false;
2023
+ this.showToaster('error', this.t('toaster.emptyCriticalAnketa'), 3000);
2024
+ }
2025
+ } else {
2026
+ hasCriticalAndItsValid = null;
2027
+ }
2028
+ if (hasCriticalAndItsValid === true || hasCriticalAndItsValid === null) {
2029
+ this.isLoading = false;
2030
+ return true;
2031
+ }
2032
+ } else {
2033
+ this.showToaster('error', this.t('toaster.emptyHealthAnketa'), 3000);
2034
+ }
2035
+ } else {
2036
+ this.showToaster('error', this.t('toaster.emptyProductConditions'), 3000);
2037
+ }
2038
+ return false;
2039
+ }
2040
+ this.isLoading = false;
2041
+ return false;
2042
+ },
2043
+ async getFamilyInfo(iin, phoneNumber) {
2044
+ this.isLoading = true;
2045
+ try {
2046
+ const familyResponse = await this.api.getFamilyInfo({ iin: iin.replace(/-/g, ''), phoneNumber: formatPhone(phoneNumber) });
2047
+ if (familyResponse.status === 'soap:Server') {
2048
+ this.showToaster('error', `${familyResponse.statusName}. Отправьте запрос через некоторое время`, 5000);
2049
+ this.isLoading = false;
2050
+ return;
2051
+ }
2052
+ if (familyResponse.status === 'PENDING') {
2053
+ this.showToaster('success', this.t('toaster.waitForClient'), 5000);
2054
+ this.isLoading = false;
2055
+ return;
2056
+ }
2057
+ if (constants.gbdErrors.find(i => i === familyResponse.status)) {
2058
+ if (familyResponse.status === 'TIMEOUT') {
2059
+ this.showToaster('success', `${familyResponse.statusName}. Отправьте запрос еще раз`, 5000);
2060
+ } else {
2061
+ this.showToaster('error', familyResponse.statusName, 5000);
2062
+ }
2063
+ this.isLoading = false;
2064
+ return;
2065
+ }
2066
+ if (familyResponse.infoList && familyResponse.infoList.birthInfos && familyResponse.infoList.birthInfos.length) {
2067
+ const filteredBirthInfos = familyResponse.infoList.birthInfos.filter(member => {
2068
+ const filterAge = (() => {
2069
+ if (this.isBolashak) return 15;
2070
+ })();
2071
+ const baseCondition = !!member.childBirthDate && typeof member.childLifeStatus === 'number' && member.childLifeStatus === 0;
2072
+ return typeof filterAge === 'number' ? baseCondition && getAgeByBirthDate(member.childBirthDate) <= filterAge : baseCondition;
2073
+ });
2074
+ if (filteredBirthInfos && filteredBirthInfos.length) {
2075
+ this.formStore.birthInfos = filteredBirthInfos;
2076
+ this.showToaster('success', this.t('toaster.pickFamilyMember'), 3000);
2077
+ } else {
2078
+ this.formStore.birthInfos = [];
2079
+ this.showToaster('error', this.t('toaster.notFound'), 3000);
2080
+ }
2081
+ } else {
2082
+ this.formStore.birthInfos = [];
2083
+ this.showToaster('error', this.t('toaster.notFound'), 3000);
2084
+ }
2085
+ } catch (err) {
2086
+ ErrorHandler(err);
2087
+ } finally {
2088
+ this.isLoading = false;
2089
+ }
2090
+ },
2091
+ async getContragentFromGBDFL(member) {
2092
+ this.isLoading = true;
2093
+ try {
2094
+ const data = {
2095
+ iin: member.iin.replace(/-/g, ''),
2096
+ phoneNumber: formatPhone(member.phoneNumber),
2097
+ };
2098
+ const gbdResponse = await this.api.getContragentFromGBDFL(data);
2099
+ if (gbdResponse.status === 'soap:Server') {
2100
+ this.showToaster('error', `${gbdResponse.statusName}. Отправьте запрос через некоторое время`, 5000);
2101
+ this.isLoading = false;
2102
+ return;
2103
+ }
2104
+ if (gbdResponse.status === 'PENDING') {
2105
+ this.showToaster('success', this.t('toaster.waitForClient'), 5000);
2106
+ this.isLoading = false;
2107
+ return;
2108
+ }
2109
+ if (constants.gbdErrors.find(i => i === gbdResponse.status)) {
2110
+ if (gbdResponse.status === 'TIMEOUT') {
2111
+ this.showToaster('success', `${gbdResponse.statusName}. Отправьте запрос еще раз`, 5000);
2112
+ } else {
2113
+ this.showToaster('success', gbdResponse.statusName, 5000);
2114
+ }
2115
+ this.isLoading = false;
2116
+ return;
2117
+ }
2118
+ const { person } = parseXML(gbdResponse.content, true, 'person');
2119
+ const { responseInfo } = parseXML(gbdResponse.content, true, 'responseInfo');
2120
+ if (member.gosPersonData !== null && member.gosPersonData.iin !== iin.replace(/-/g, '')) {
2121
+ member.resetMember(false);
2122
+ }
2123
+ member.gosPersonData = person;
2124
+ await this.getContragent(member, false);
2125
+ member.verifyDate = responseInfo.responseDate;
2126
+ member.verifyType = 'GBDFL';
2127
+ await this.saveInStoreUserGBDFL(person, member);
2128
+ } catch (err) {
2129
+ ErrorHandler(err);
2130
+ }
2131
+ this.isLoading = false;
2132
+ },
2133
+ async saveInStoreUserGBDFL(person, member) {
2134
+ member.firstName = person.name;
2135
+ member.lastName = person.surname;
2136
+ member.middleName = person.patronymic ? person.patronymic : '';
2137
+ member.longName = `${person.surname} ${person.name} ${person.patronymic ? person.patronymic : ''}`;
2138
+ member.birthDate = reformatDate(person.birthDate);
2139
+ member.genderName = person.gender.nameRu;
2140
+
2141
+ const gender = this.gender.find(i => i.id == person.gender.code);
2142
+ if (gender) member.gender = gender;
2143
+
2144
+ const birthPlace = this.countries.find(i => i.nameRu.match(new RegExp(person.birthPlace.country.nameRu, 'i')));
2145
+ if (birthPlace) member.birthPlace = birthPlace;
2146
+
2147
+ const countryOfCitizenship = this.citizenshipCountries.find(i => i.nameRu.match(new RegExp(person.citizenship.nameRu, 'i')));
2148
+ if (countryOfCitizenship) member.countryOfCitizenship = countryOfCitizenship;
2149
+
2150
+ const regCountry = this.countries.find(i => i.nameRu.match(new RegExp(person.regAddress.country.nameRu, 'i')));
2151
+ if (regCountry) member.registrationCountry = regCountry;
2152
+
2153
+ const regProvince = this.states.find(i => i.nameRu.match(new RegExp(person.regAddress.district.nameRu, 'i')));
2154
+ if (regProvince) member.registrationProvince = regProvince;
2155
+
2156
+ if ('city' in person.regAddress && !!person.regAddress.city) {
2157
+ if (person.regAddress.city.includes(', ')) {
2158
+ const personCities = person.regAddress.city.split(', ');
2159
+ for (let i = 0; i < personCities.length; ++i) {
2160
+ const possibleCity = this.cities.find(i => i.nameRu.includes(personCities[i]));
2161
+ if (possibleCity) {
2162
+ member.registrationCity = possibleCity;
2163
+ break;
2164
+ }
2165
+ }
2166
+ if (member.registrationCity.nameRu === null) {
2167
+ for (let i = 0; i < personCities.length; ++i) {
2168
+ const possibleRegion = this.regions.find(i => i.nameRu.includes(personCities[i]));
2169
+ if (possibleRegion) {
2170
+ member.registrationRegion = possibleRegion;
2171
+ break;
2172
+ }
2173
+ }
2174
+ }
2175
+ } else {
2176
+ const regCity = this.cities.find(i => i.nameRu.match(new RegExp(person.regAddress.city, 'i')));
2177
+ if (regCity) member.registrationCity = regCity;
2178
+
2179
+ if (member.registrationCity.nameRu === null) {
2180
+ const regRegion = this.regions.find(i => i.nameRu.match(new RegExp(person.regAddress.city), 'i'));
2181
+ if (regRegion) member.registrationRegion = regRegion;
2182
+ }
2183
+ }
2184
+ }
2185
+
2186
+ if (member.registrationCity.nameRu === null && member.registrationRegion.nameRu === null) {
2187
+ const regCity = this.cities.find(
2188
+ i => i.nameRu.match(new RegExp(person.regAddress.region.nameRu, 'i')) || i.nameRu.match(new RegExp(person.regAddress.district.nameRu, 'i')),
2189
+ );
2190
+ if (regCity) {
2191
+ member.registrationCity = regCity;
2192
+ const regType = this.localityTypes.find(i => i.nameRu === 'город');
2193
+ if (regType) member.registrationRegionType = regType;
2194
+ } else {
2195
+ const regRegion = this.regions.find(
2196
+ i => i.nameRu.match(new RegExp(person.regAddress.region.nameRu), 'i') || i.nameRu.match(new RegExp(person.regAddress.district.nameRu, 'i')),
2197
+ );
2198
+ if (regRegion) {
2199
+ member.registrationRegion = regRegion;
2200
+ const regType = this.localityTypes.find(i => (i.nameRu === i.nameRu) === 'село' || i.nameRu === 'поселок');
2201
+ if (regType) member.registrationRegionType = regType;
2202
+ }
2203
+ }
2204
+ }
2205
+
2206
+ if (person.regAddress.street.includes(', ')) {
2207
+ const personAddress = person.regAddress.street.split(', ');
2208
+ const microDistrict = personAddress.find(i => i.match(new RegExp('микрорайон', 'i')));
2209
+ const quarter = personAddress.find(i => i.match(new RegExp('квартал', 'i')));
2210
+ const street = personAddress.find(i => i.match(new RegExp('улица', 'i')));
2211
+ if (microDistrict) member.registrationMicroDistrict = microDistrict;
2212
+ if (quarter) member.registrationQuarter = quarter;
2213
+ if (street) member.registrationStreet = street;
2214
+ } else {
2215
+ if (person.regAddress.street) member.registrationStreet = person.regAddress.street;
2216
+ }
2217
+ if (person.regAddress.building) member.registrationNumberHouse = person.regAddress.building;
2218
+ if (person.regAddress.flat) member.registrationNumberApartment = person.regAddress.flat;
2219
+
2220
+ // TODO Доработать логику и для остальных
2221
+ if ('length' in person.documents.document) {
2222
+ const validDocument = person.documents.document.find(i => new Date(i.endDate) > new Date(Date.now()) && i.status.code === '00' && i.type.code === '002');
2223
+ if (validDocument) {
2224
+ const documentType = this.documentTypes.find(i => i.ids === '1UDL');
2225
+ if (documentType) member.documentType = documentType;
2226
+
2227
+ member.documentNumber = validDocument.number;
2228
+ member.documentExpire = reformatDate(validDocument.endDate);
2229
+ member.documentDate = reformatDate(validDocument.beginDate);
2230
+ member.documentNumber = validDocument.number;
2231
+
2232
+ const documentIssuer = this.documentIssuers.find(i => i.nameRu.match(new RegExp('МВД РК', 'i')));
2233
+ if (documentIssuer) member.documentIssuers = documentIssuer;
2234
+ }
2235
+ } else {
2236
+ const documentType =
2237
+ person.documents.document.type.nameRu === 'УДОСТОВЕРЕНИЕ РК'
2238
+ ? this.documentTypes.find(i => i.ids === '1UDL')
2239
+ : this.documentTypes.find(i => i.nameRu.match(new RegExp(person.documents.document.type.nameRu, 'i')))
2240
+ ? this.documentTypes.find(i => i.nameRu.match(new RegExp(person.documents.document.type.nameRu, 'i')))
2241
+ : new Value();
2242
+ if (documentType) member.documentType = documentType;
2243
+
2244
+ const documentNumber = person.documents.document.number;
2245
+ if (documentNumber) member.documentNumber = documentNumber;
2246
+
2247
+ const documentDate = person.documents.document.beginDate;
2248
+ if (documentDate) member.documentDate = reformatDate(documentDate);
2249
+
2250
+ const documentExpire = person.documents.document.endDate;
2251
+ if (documentExpire) member.documentExpire = reformatDate(documentExpire);
2252
+
2253
+ // TODO уточнить
2254
+ const documentIssuer = this.documentIssuers.find(i => i.nameRu.match(new RegExp('МВД РК', 'i')));
2255
+ if (documentIssuer) member.documentIssuers = documentIssuer;
2256
+ }
2257
+ const economySectorCode = this.economySectorCode.find(i => i.ids === '500003.9');
2258
+ if (economySectorCode) member.economySectorCode = economySectorCode;
2259
+ },
2260
+ hasJobSection(whichForm) {
2261
+ switch (whichForm) {
2262
+ case this.formStore.beneficiaryFormKey:
2263
+ case this.formStore.beneficialOwnerFormKey:
2264
+ case this.formStore.policyholdersRepresentativeFormKey:
2265
+ return false;
2266
+ default:
2267
+ return true;
2268
+ }
2269
+ },
2270
+ hasBirthSection(whichForm) {
2271
+ if (this.isGons) return false;
2272
+ switch (whichForm) {
2273
+ case this.formStore.beneficiaryFormKey:
2274
+ return false;
2275
+ default:
2276
+ return true;
2277
+ }
2278
+ },
2279
+ hasPlaceSection(whichForm) {
2280
+ switch (whichForm) {
2281
+ default:
2282
+ return true;
2283
+ }
2284
+ },
2285
+ hasDocumentSection(whichForm) {
2286
+ switch (whichForm) {
2287
+ default:
2288
+ return true;
2289
+ }
2290
+ },
2291
+ hasContactSection(whichForm) {
2292
+ if (this.isGons) return false;
2293
+ switch (whichForm) {
2294
+ default:
2295
+ return true;
2296
+ }
26
2297
  },
27
2298
  },
28
2299
  });
2300
+
2301
+ export const useContragentStore = defineStore('contragent', {
2302
+ state: () => ({
2303
+ ...new Contragent(),
2304
+ formatDate: new Contragent().formatDate,
2305
+ getDateByKey: new Contragent().getDateByKey,
2306
+ getBirthDate: new Contragent().getBirthDate,
2307
+ getDocumentExpireDate: new Contragent().getDocumentExpireDate,
2308
+ getDocumentDate: new Contragent().getDocumentDate,
2309
+ getAgeByBirthDate: new Contragent().getAgeByBirthDate,
2310
+ }),
2311
+ });