hl-core 0.0.8 → 0.0.9-beta.2

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