PageSourceSearch

https://gradana.co.id/assets/js/controllers/signup.js

js gradana.co.id collected 2026-10-07 21:52:59 UTC 113,878 bytes, 3,002 lines download raw bytes

1"use strict";
2
3/* Controllers */
4
5angular.module("app").controller("SignupCtrl", SignupController);
6SignupController.$inject = [
7  "$scope",
8  "$sce",
9  "$rootScope",
10  "ServerService",
11  "SettingsService",
12  "$state",
13  "SweetAlert",
14  "$window",
15  "Upload",
16  "$location",
17  "$http",
18];
19
20function SignupController(
21  $scope,
22  $sce,
23  $rootScope,
24  ServerService,
25  SettingsService,
26  $state,
27  SweetAlert,
28  $window,
29  Upload,
30  $location,
31  $http
32) {
33  var vm = this;
34  let newRole = $state.params.role || "";
35  const TAG = "SignupController";
36  $state.params.role = newRole === "pendana" ? "lender" : newRole === "peminjam" ? "borrower" : $state.params.role;
37  if (newRole !== "pendana" && newRole !== "peminjam") {
38    $state.go("home");
39  }
40
41  let currentUser = {};
42  $scope.loading = false;
43  vm.globalSetting = {};
44  vm.selectedPropertyId;
45  vm.questionnaireIsComplete = false;
46  vm.data = {};
47  vm.purposeChosen = {}
48  vm.tenorList = [];
49  vm.imagesToBeUploaded = {};
50  vm.imagesToBeUploadedStatus = {};
51  vm.isLjk = false
52  $scope.isAgreed1 = false;
53  $scope.isAgreed2 = false;
54  vm.purposeChosen = {};
55  vm.questionnaire = {
56    graSewa: {},
57    graStrata: {
58      property: {},
59      buyer: {},
60      seller: {},
61    },
62    product: {
63      productType: "GraDP",
64    },
65    property: {},
66    propertyUnit: {},
67  };
68  vm.borrowerTypeChosen = {};
69  vm.propertyUnitPriceObject = {};
70  vm.currentPropertyUnitsPage = -1;
71  vm.isSubmitted = true;
72  vm.isInstitutional = false;
73  vm.isLoadingPropertyUnits = false;
74  vm.shouldLoadMorePropertyUnits = true;
75  vm.propertyUnits = [];
76  vm.industryBorrowerChosen = {};
77  vm.managerOwnerStatus = [];
78  vm.homeOwnershipStatusCodes = [
79    { value: 1, name: "Memiliki Rumah Sendiri" },
80    { value: 2, name: "Tidak Memiliki Rumah Sendiri" }
81  ];
82
83  //new register
84  vm.domicileFlag = "sesuai";
85
86  function loadLanguageContentDropdown(language) {
87    $http.get(`assets/i18n/data/${language}.json`).then(function (response) {
88      vm.language = language;
89      $scope.dropdown = response.data;
90
91      ServerService.getIndustries(currentUser, function (industries) {
92        vm.bidangPekerjaan = [];
93        vm.bidangUsaha = [];
94        vm.industriesBorrower = [];
95  
96        industries.forEach((industry, index) => {
97          vm.bidangPekerjaan.push({
98            ...industry,
99            name: $scope.dropdown['field-of-work'][`item-${index + 1}`]
100          });
101          vm.bidangUsaha.push({
102            ...industry,
103            name: $scope.dropdown['field-of-work'][`item-${index + 1}`]
104          });
105          vm.industriesBorrower.push({
106            ...industry,
107            name: $scope.dropdown['field-of-work'][`item-${index + 1}`]
108          });
109        });
110      });
111
112      vm.title = [
113        { value: "BPK", name: $scope.dropdown['title']['item-1'] },
114        { value: "IBU", name: $scope.dropdown['title']['item-2'] },
115        { value: "SDR", name: $scope.dropdown['title']['item-3'] },
116        { value: "SDRI", name: $scope.dropdown['title']['item-4'] },
117      ];
118
119      vm.religion = [
120        { value: "ISLAM", name: $scope.dropdown['religion']['item-1'] },
121        { value: "CATHOLIC", name: $scope.dropdown['religion']['item-2'] },
122        { value: "CHRISTIAN", name: $scope.dropdown['religion']['item-3'] },
123        { value: "BUDDHIST", name: $scope.dropdown['religion']['item-4'] },
124        { value: "HINDU", name: $scope.dropdown['religion']['item-5'] },
125        { value: "CONFUCIAN", name: $scope.dropdown['religion']['item-6'] },
126        { value: "OTHERS", name: $scope.dropdown['religion']['item-7'] },
127      ];
128
129      vm.lastEducation = [
130        { value: "sd", name: $scope.dropdown['educations']['item-1'] },
131        { value: "smp", name: $scope.dropdown['educations']['item-2'] },
132        { value: "sma", name: $scope.dropdown['educations']['item-3'] },
133        { value: "d1", name: $scope.dropdown['educations']['item-4'] },
134        { value: "d2", name: $scope.dropdown['educations']['item-5'] },
135        { value: "d3", name: $scope.dropdown['educations']['item-6'] },
136        { value: "d4", name: $scope.dropdown['educations']['item-7'] },
137        { value: "s1", name: $scope.dropdown['educations']['item-8'] },
138        { value: "s2", name: $scope.dropdown['educations']['item-9'] },
139        { value: "s3", name: $scope.dropdown['educations']['item-10'] },
140      ];
141
142      vm.open_account_reason = [
143        { value: "INVESTMENTS", name: $scope.dropdown['reasons']['item-1'] },
144        { value: "SAVINGS", name: $scope.dropdown['reasons']['item-2'] },
145        { value: "TRANSACTIONS", name: $scope.dropdown['reasons']['item-3'] },
146      ];
147
148
149      vm.job_codeLender = [
150        { value: "GOVERNMENT_EMPLOYEE", name: $scope.dropdown['occupations']['item-1'] },
151        { value: "PRIVATE_SECTOR_EMPLOYEE", name: $scope.dropdown['occupations']['item-2'] },
152        { value: "STATE_OWNED_ENTERPRISE_EMPLOYEE", name: $scope.dropdown['occupations']['item-3'] },
153        { value: "NATIONAL_MILITARY_OR_POLICE_OFFICER", name: $scope.dropdown['occupations']['item-4'] },
154        { value: "BUSINESS_OWNER", name: $scope.dropdown['occupations']['item-5'] },
155        { value: "TRADER", name: $scope.dropdown['occupations']['item-6'] },
156        { value: "FARMER_OR_FISHERMAN", name: $scope.dropdown['occupations']['item-7'] },
157        { value: "STUDENT", name: $scope.dropdown['occupations']['item-8'] },
158        { value: "HOUSEWIFE", name: $scope.dropdown['occupations']['item-9'] },
159        { value: "UNEMPLOYED", name: $scope.dropdown['occupations']['item-10'] },
160        { value: "EMPLOYEE", name: $scope.dropdown['occupations']['item-11'] },
161        { value: "ENTREPRENEUR", name: $scope.dropdown['occupations']['item-12'] },
162        { value: "STATE_OFFICIAL", name: $scope.dropdown['occupations']['item-13'] },
163        { value: "ACCOUNTANT", name: $scope.dropdown['occupations']['item-14'] },
164        { value: "LAWYER_OR_NOTARY", name: $scope.dropdown['occupations']['item-15'] },
165        { value: "PROFESSION", name: $scope.dropdown['occupations']['item-16'] },
166        { value: "RETIREE", name: $scope.dropdown['occupations']['item-17'] },
167        { value: "PRIVATE_LECTURER_OR_TEACHER", name: $scope.dropdown['occupations']['item-18'] },
168        { value: "PUBLIC_LECTURER_OR_TEACHER", name: $scope.dropdown['occupations']['item-19'] },
169        { value: "DOCTOR", name: $scope.dropdown['occupations']['item-20'] },
170        { value: "BNI_EMPLOYEE", name: $scope.dropdown['occupations']['item-21'] },
171        { value: "BNI_AFFILIATE_UNIT", name: $scope.dropdown['occupations']['item-22'] },
172        { value: "OTHERS", name: $scope.dropdown['occupations']['item-23'] },
173      ];
174
175      vm.pengalamanKerja = [
176        { value: "0", name: $scope.dropdown['work-experiences']['item-1'] },
177        { value: "1", name: $scope.dropdown['work-experiences']['item-2'] },
178        { value: "2", name: $scope.dropdown['work-experiences']['item-3'] },
179        { value: "3", name: $scope.dropdown['work-experiences']['item-4'] },
180        { value: "4", name: $scope.dropdown['work-experiences']['item-5'] },
181        { value: "5", name: $scope.dropdown['work-experiences']['item-6'] },
182        { value: "6", name: $scope.dropdown['work-experiences']['item-7'] },
183      ];
184
185      vm.referrals = [
186        { name: $scope.dropdown['references']['item-1'] },
187        { name: $scope.dropdown['references']['item-2'] },
188        { name: $scope.dropdown['references']['item-3'] },
189        { name: $scope.dropdown['references']['item-4'] },
190        { name: $scope.dropdown['references']['item-5'] },
191        { name: $scope.dropdown['references']['item-6'] },
192      ];
193
194      vm.industries = [
195        { name: $scope.dropdown['industries']['item-1'] },
196        { name: $scope.dropdown['industries']['item-2'] },
197        { name: $scope.dropdown['industries']['item-3'] },
198        { name: $scope.dropdown['industries']['item-4'] },
199        { name: $scope.dropdown['industries']['item-5'] },
200      ];
201
202      vm.gender = [
203        { value: "male", name: $scope.dropdown['genders']['item-1'] },
204        { value: "female", name: $scope.dropdown['genders']['item-2'] },
205      ];
206
207      vm.maritalStatus = [
208        { value: "lajang", name: $scope.dropdown['marital-status']['item-1'] },
209        { value: "menikah", name: $scope.dropdown['marital-status']['item-2'] },
210        { value: "cerai", name: $scope.dropdown['marital-status']['item-3'] },
211      ];
212
213      vm.source_of_fund = [
214        { value: "SALARY", name: $scope.dropdown['source-of-funds']['item-1'] },
215        { value: "BUSINESS", name: $scope.dropdown['source-of-funds']['item-2'] },
216        { value: "INVESTMENT", name: $scope.dropdown['source-of-funds']['item-3'] },
217        { value: "GRANTS", name: $scope.dropdown['source-of-funds']['item-4'] },
218      ];
219    }, function (error) {
220      console.error("Error loading language file:", error);
221    });
222  }
223
224  function loadLanguageContent(language) {
225    $http.get(`assets/i18n/signup/${language}.json`).then(function (response) {
226      $scope.textContent = response.data;
227    }, function (error) {
228      console.error("Error loading language file:", error);
229    });
230  }
231
232  $scope.currentLanguage = localStorage.getItem("language") || "id";
233  loadLanguageContentDropdown($scope.currentLanguage);
234  loadLanguageContent($scope.currentLanguage);
235
236  $scope.$watch(function () {
237    return localStorage.getItem("language");
238  }, function (newValue) {
239    if (newValue) {
240      $scope.currentLanguage = newValue;
241      loadLanguageContent(newValue);
242      loadLanguageContentDropdown(newValue);
243      console.log("Current Language changed to:", $scope.currentLanguage);
244    }
245  });
246
247  $scope.changeLanguage = function () {
248    $scope.currentLanguage = $scope.currentLanguage === 'id' ? 'en' : 'id';
249    loadLanguageContent($scope.currentLanguage);
250    localStorage.setItem("language", $scope.currentLanguage);
251  };
252
253  vm.securityQuestionChosen = "";
254  vm.industries = [
255    { name: "Bank Komersial" },
256    { name: "BPR" },
257    { name: "Asset Management" },
258    { name: "Multifinance" },
259    { name: "Other" },
260  ];
261  // console.log(industries, " industries")
262  vm.companyTypes = [];
263
264  vm.borrowerTypes = [
265    { value: "lajang", name: "Lajang" },
266    { value: "menikah", name: "Menikah" },
267    { value: "cerai", name: "Cerai" },
268  ];
269
270  vm.lastEducation = [
271    { value: "sd", name: "SD" },
272    { value: "smp", name: "SMP" },
273    { value: "sma", name: "SMA" },
274    { value: "d1", name: "D1" },
275    { value: "d2", name: "D2" },
276    { value: "d3", name: "D3" },
277    { value: "d4", name: "D4" },
278    { value: "s1", name: "S1" },
279    { value: "s2", name: "S2" },
280    { value: "s3", name: "S3" },
281  ];
282
283  vm.open_account_reason = [
284    { value: "INVESTMENTS", name: "Untuk tujuan pendanaan" },
285    { value: "SAVINGS", name: "Untuk tujuan tabungan" },
286    { value: "TRANSACTIONS", name: "Untuk tujuan transaksi" },
287  ];
288
289  vm.industriesBorrower = [{}];
290  vm.bidangPekerjaan = [{}];
291  vm.bidangUsaha = [{}];
292  vm.sectorEconomics = [{}];
293  $scope.isFieldOfBusiness = false
294
295  vm.job_codeBorrower = [
296    { value: "1", name: "PNS" },
297    { value: "2", name: "TNI/POLRI" },
298    { value: "3", name: "Karyawan BUMN" },
299    { value: "4", name: "Karyawan Swasta" },
300    { value: "5", name: "Wiraswasta" },
301    { value: "6", name: "Pelajar/Mahasiswa" },
302    { value: "7", name: "Lain-Lain" },
303    { value: "8", name: "Tidak Bekerja/Bukan Pelajar" },
304    { value: "9", name: "Badan Hukum" },
305    { value: "10", name: "Tidak Ada Data" },
306  ];
307
308  // console.log(title, " title")
309  vm.genders = [
310    { name: "Laki-laki", value: "male" },
311    { name: "Perempuan", value: "female" },
312  ];
313
314  vm.maritalStatus = [
315    { value: "lajang", name: "Lajang" },
316    { value: "menikah", name: "Menikah" },
317    { value: "cerai", name: "Cerai" },
318  ];
319
320  vm.lastEducation = [
321    { value: "sd", name: "SD" },
322    { value: "smp", name: "SMP" },
323    { value: "sma", name: "SMA" },
324    { value: "d1", name: "D1" },
325    { value: "d2", name: "D2" },
326    { value: "d3", name: "D3" },
327    { value: "d4", name: "D4" },
328    { value: "s1", name: "S1" },
329    { value: "s2", name: "S2" },
330    { value: "s3", name: "S3" },
331  ];
332
333  vm.title = [
334    { value: "BPK", name: "Bapak" },
335    { value: "IBU", name: "Ibu" },
336    { value: "SDR", name: "Saudara" },
337    { value: "SDRI", name: "Saudari" },
338  ];
339
340  vm.open_account_reason = [
341    { value: "INVESTMENTS", name: "Untuk tujuan pendanaan" },
342    { value: "SAVINGS", name: "Untuk tujuan tabungan" },
343    { value: "TRANSACTIONS", name: "Untuk tujuan transaksi" },
344  ];
345
346  vm.religion = [
347    { value: "ISLAM", name: "Islam" },
348    { value: "CATHOLIC", name: "Katolik" },
349    { value: "CHRISTIAN", name: "Kristen (Protestan)" },
350    { value: "BUDDHIST", name: "Buddha" },
351    { value: "HINDU", name: "Hindu" },
352    { value: "CONFUCIAN", name: "Konfusianisme / Konghucu" },
353    { value: "OTHERS", name: "Lainnya" },
354  ];
355
356  vm.source_of_fund = [
357    { value: "SALARY", name: "Gaji" },
358    { value: "BUSINESS", name: "Hasil bisnis" },
359    { value: "INVESTMENT", name: "Hasil pendanaan" },
360    { value: "GRANTS", name: "Hibah" },
361  ];
362
363  $window.async.parallel({
364    loadingOperation: function (callback) {
365      $scope.loading = true;
366      callback();
367    },
368    /**
369      * @function
370      * @name sectorEconomicsOperation
371      * @returns {Promise<Record<String, Array<Record<String, String>>>>} this get from asset data sector economics
372    */
373    sectorEconomicsOperation: function (callback) {
374      return new Promise((resolve) => {
375        ServerService.getSectorEconomics(currentUser, function (response) {
376          vm.sectorEconomics = response;
377          resolve();
378          callback()
379        });
380      });
381    },
382    /**
383 * @function
384 * @name industriesOperation
385 * @returns {Promise<Array<Record<String, String>>>} this gets data from asset industries
386 */
387    industriesOperation: function (callback) {
388      return new Promise((resolve, reject) => {
389        ServerService.getIndustries(currentUser, function (industries) {
390          $http.get(`assets/i18n/data/${vm.language}.json`).then(function (response) {
391            $scope.industriesData = response.data["field-of-work"];
392            vm.bidangPekerjaan = [];
393            vm.bidangUsaha = [];
394            vm.industriesBorrower = [];
395
396            industries.forEach((industry, index) => {
397              vm.bidangPekerjaan.push({
398                ...industry,
399                name: $scope.industriesData[`item-${index + 1}`]
400              });
401
402              vm.bidangUsaha.push({
403                ...industry,
404                name: $scope.industriesData[`item-${index + 1}`]
405              });
406
407              vm.industriesBorrower.push({
408                ...industry,
409                name: $scope.industriesData[`item-${index + 1}`]
410              });
411            });
412            resolve(vm.industriesBorrower);
413            if (callback) callback();
414          }).catch((error) => {
415            console.error("Error loading language file:", error);
416            reject(error);
417          });
418        });
419      });
420    },
421    /**
422        * @function
423        * @name companyTypesOperation:
424        * @returns {Promise<Array<Record<String, String>>>} this get from asset data companyTypes
425      */
426    companyTypesOperation: function (callback) {
427      return new Promise((resolve) => {
428        ServerService.getCompanyTypes(currentUser, function (response) {
429          vm.companyTypes = response;
430          vm.companyType = response;
431          $scope.typeOfBusiness = response
432          resolve();
433          callback()
434        });
435      });
436    },
437  }, function (err) {
438    if (err) {
439      if (typeof err == 'string' && err == 'no response') {
440        SweetAlert.swal($scope.textContent['swal']['error']['item-1']['title'], $scope.textContent['swal']['error']['item-1']['text'], 'error');
441        $scope.loading = false;
442      } else {
443        SweetAlert.swal(err.status, err.message, 'error');
444        $scope.loading = false;
445      }
446    }
447  })
448
449  $scope.goToRegisterGrakarya = () => {
450    $state.go("access.signup", { role: "peminjam", type: "Daftar-GraKarya" });
451  };
452
453  $scope.getSecurityQuestions = function () {
454    ServerService.GetSecurityQuestions(currentUser, function (response) {
455      if (!response) {
456        $scope.loading = false;
457        return SweetAlert.swal($scope.textContent['swal']['error']['item-1']['title'], $scope.textContent['swal']['error']['item-1']['text'], "error");
458      }
459
460      if (response.statusCode != 200) {
461        $scope.loading = false;
462        return SweetAlert.swal(response.status, response.message, "error");
463      }
464
465      if (response.data) {
466        vm.securityQuestions = response.data;
467      }
468
469      $scope.loading = false;
470    });
471  };
472  $scope.getSecurityQuestions();
473  //new register
474
475  // list of years
476  let dateBefore17 = moment().subtract(17, "years");
477  let dateBefore80 = moment().subtract(80, "years");
478  let startYear = dateBefore80.year();
479  let endYear = dateBefore17.year();
480  vm.yearList = [];
481  for (let i = startYear; i <= endYear; i++) {
482    vm.yearList.push({ name: i, value: i });
483  }
484  vm.yearList.reverse();
485
486  // list of months
487  vm.monthList = [];
488  for (let i = 1; i <= 12; i++) {
489    const month = i < 10 ? "0" + i : "" + i;
490    vm.monthList.push({ name: month, value: i });
491  }
492
493  // list of date
494  vm.dateList = [];
495  for (let i = 1; i <= 31; i++) {
496    const dd = i < 10 ? "0" + i : "" + i;
497    vm.dateList.push({ name: dd, value: i });
498  }
499
500  // list of graStrata tenor
501  vm.graStrataTenorList = [];
502  for (let i = 2; i <= 20; i++) {
503    vm.graStrataTenorList.push({ name: i + " tahun", value: i });
504  }
505
506  vm.locationAccessList = [
507    { name: "Mobil 1 arah", value: "mobil 1 arah" },
508    { name: "Mobil 2 arah", value: "mobil 2 arah" },
509  ];
510
511  vm.genders = [
512    { name: "Laki-laki", value: "male" },
513    { name: "Perempuan", value: "female" },
514  ];
515
516  vm.numberOfBorrowers = [{ name: "1 Peminjam" }, { name: "2 Peminjam" }, { name: "3 Peminjam" }, { name: ">3 Peminjam" }];
517  vm.numberOfInstallment = [{ name: "24 Bulan" }, { name: "36 Bulan" }];
518  vm.nationalities = [{ name: "WNI" }, { name: "WNA" }];
519  vm.workSinceChoices = [{ name: "< 1 tahun" }, { name: "=> 1 tahun" }];
520
521  vm.propertyUnitTypeList = [
522    { name: "Rumah", value: "rumah" },
523    { name: "Apartment", value: "apartment" },
524    { name: "Ruko", value: "ruko" },
525    { name: "Gudang", value: "gudang" },
526    { name: "Kantor", value: "kantor" },
527    { name: "Lainnya", value: "lainnya" },
528  ];
529
530  vm.grasewaTypeList = [
531    {
532      typeName: "Sewa",
533      name: "Pembiayaan Sewa Tahunan",
534    },
535    {
536      typeName: "Renovasi",
537      name: "Pembiayaan Renovasi",
538    },
539    {
540      typeName: "sewaRenov",
541      name: "Pembiayaan Sewa & Renovasi",
542    },
543  ];
544
545  vm.grasewaTypeSelected = vm.grasewaTypeList[0];
546  vm.borrowerType = [
547    { name: "Individual dengan Status Karyawan", value: "individual_karyawan" },
548    {
549      name: "Individual dengan Usaha Pribadi",
550      value: "individual_usaha_pribadi",
551    },
552    { name: "Perusahaan (PT/CV)", value: "perusahaan" },
553  ];
554  vm.companyType = [];
555  vm.company = { companyType: "", name: "" };
556  vm.tenor = [];
557  for (let index = 1; index <= 24; index++) {
558    vm.tenor.push({ name: "Cicilan " + index + " bulan", value: index });
559  }
560
561  vm.tempBank = {};
562
563  vm.baseImageURL = "https://gradana-prod.oss-ap-southeast-5.aliyuncs.com/";
564  var currentUrl = $location.absUrl();
565  var folder = "";
566  if (currentUrl.includes("gradana.co.id") == true || currentUrl.includes("gradana.com") == true) {
567    folder = "prod/";
568  } else {
569    folder = "dev/";
570  }
571  $scope.uploads3Image = function (file, key) {
572    if (file) {
573      var type = file.type.split("/");
574      if (type[0] == "image") {
575        vm.imagesToBeUploaded[key] = file;
576      } else {
577        SweetAlert.swal($scope.textContent['swal']['error']['item-2']['title'], $scope.textContent['swal']['error']['item-2']['text'], "error");
578      }
579    }
580  };
581
582  // ------------------------------------------------------------------------
583  // GET DATA MASTER GLOBAL SETTING
584  // ------------------------------------------------------------------------
585  ServerService.GetGlobalSettingAsync(currentUser)
586    .then((response) => {
587      if (!response) {
588        throw Error(`${TAG} - no response`);
589      }
590
591      if (response.status === "Success") {
592        vm.globalSetting = response.data;
593      }
594    })
595    .catch((err) => {
596      if (err) {
597        if (typeof err == "string" && err == "no response") {
598          SweetAlert.swal($scope.textContent['swal']['error']['item-1']['title'], $scope.textContent['swal']['error']['item-1']['text'], "error");
599          $scope.loading = false;
600        } else {
601          SweetAlert.swal(err.status, err.message, "error");
602          $scope.loading = false;
603        }
604      } else {
605        $scope.loading = false;
606      }
607    });
608
609  // ------------------------------------------------------------------------
610  // [END] GET DATA MASTER GLOBAL SETTING
611  // ------------------------------------------------------------------------
612
613  $scope.user = {};
614  $scope.user.jobInfo = {};
615  $scope.user.lenderType = "individual";
616  $scope.user.correspondenceKTP = "sesuai";
617  $scope.user.domicileKTP = "sesuai";
618  $scope.user.lenderPreference = {};
619  $scope.user.company = {};
620
621  //Infinite Scroll Magic
622  $scope.infiniteScroll = {};
623  $scope.infiniteScroll.currentItems = 0;
624
625  $scope.type = "";
626
627  vm.cities = [];
628  vm.provinces = [];
629  vm.kecamatans = [];
630  vm.citiesCompany = [];
631  vm.provincesCompany = [];
632  vm.kecamatansCompany = [];
633  vm.emailCompany = "";
634
635  if ($state.params.type) {
636    $scope.type = $state.params.type;
637  }
638
639  vm.loadNextPagePropertyUnits = function () {
640    if (!vm.isLoadingPropertyUnits && vm.shouldLoadMorePropertyUnits) {
641      vm.isLoadingPropertyUnits = true;
642
643      if (vm.currentPropertyUnitsPage == -1) {
644        vm.currentPropertyUnitsPage = 0;
645      } else {
646        vm.currentPropertyUnitsPage++;
647      }
648
649      let parameters = {
650        propertyId: vm.selectedPropertyId,
651        perPage: 20,
652        page: vm.currentPropertyUnitsPage,
653        status: "available",
654        // isActive: true
655      };
656
657      ServerService.GetPropertyUnitsByPropertyIdPaging(currentUser, parameters, function (response) {
658        vm.isLoadingPropertyUnits = false;
659
660        if (!response) {
661          $scope.loading = false;
662          return SweetAlert.swal(
663            $scope.textContent['swal']['error']['item-1']['title'],
664            $scope.textContent['swal']['error']['item-1']['text'],
665            "error"
666          );
667        }
668        if (response.status != "Success") {
669          $scope.loading = false;
670          return SweetAlert.swal(response.status, response.message, "error");
671        }
672        let olderPropertyUnits = vm.propertyUnits;
673        let newPropertyUnits = response.data.propertyUnits;
674        vm.propertyUnits = olderPropertyUnits.concat(newPropertyUnits);
675
676        // To prevent infinite-scroll calling this API after the last page
677        // have been loaded
678        if (vm.propertyUnits.length == response.data.propertyUnitsCount) {
679          vm.shouldLoadMorePropertyUnits = false;
680        }
681
682        $scope.infiniteScroll.currentItems += response.data.propertyUnits.length;
683        $scope.loading = false;
684      });
685    }
686    $scope.loading = false;
687  };
688
689  if ($state.params.role) {
690    $scope.user.role = $state.params.role;
691
692    ServerService.GetAllProvinces(currentUser, function (response) {
693      if (response && response.status === "Success") {
694        vm.provinces = response.data;
695        vm.provincesCompany = response.data;
696      }
697    });
698
699    if ($scope.user.role === "borrower") {
700      $scope.type = $state.params.type;
701      $scope.email = $state.params.email;
702      $scope.scoringId = $location.search().scoringID;
703      $scope.first = $location.search().first;
704      $scope.last = $location.search().last;
705      if ($scope.scoringId) {
706        $scope.user.email = $location.search().email;
707        $scope.user.scoringId = $scope.scoringId;
708        $scope.user.firstName = $scope.first;
709        $scope.user.lastName = $scope.last;
710        // console.log("createAccount scori$scope.user.lastNamengId",$scope.user.lastName);
711      }
712      $scope.scoringID = $state.params.scoringID;
713      if ($scope.type === "GraKarya" || $scope.type === "Daftar-GraKarya") {
714        vm.questionnaireIsComplete = false;
715      } else {
716        $scope.loading = true;
717        let query = {
718          isActive: "true",
719          sortBy: "orderNumber",
720        };
721        ServerService.GetProperties(currentUser, query, function (response) {
722          if (!response) {
723            $scope.loading = false;
724            return SweetAlert.swal(
725              $scope.textContent['swal']['error']['item-1']['title'],
726              $scope.textContent['swal']['error']['item-1']['text'],
727              "error"
728            );
729          }
730
731          if (response.status != "Success") {
732            $scope.loading = false;
733            return SweetAlert.swal(response.status, response.message, "error");
734          }
735          vm.properties = response.data;
736          $scope.loading = false;
737        });
738
739        $scope.loading = true;
740        var productQueryParameters = {
741          productTypeName: $scope.type,
742        };
743
744        ServerService.GetProducts(currentUser, productQueryParameters, function (response) {
745          if (!response) {
746            $scope.loading = false;
747            return SweetAlert.swal(
748              $scope.textContent['swal']['error']['item-1']['title'],
749              $scope.textContent['swal']['error']['item-1']['text'],
750              "error"
751            );
752          }
753
754          if (response.status != "Success") {
755            $scope.loading = false;
756            return SweetAlert.swal(response.status, response.message, "error");
757          }
758
759          if ($scope.type == "GraSewa") {
760            vm.products = response.data;
761            // temporary since there is still only one product for grasewa,so set default for cicilan 12 bulan
762            if (vm.products[0]) {
763              vm.questionnaire.product = {
764                productData: vm.products[0],
765                name: vm.products[0].name,
766                productType: vm.products[0].productType.name,
767                numberOfInstallment: vm.products[0].numberOfInstallment,
768              };
769            }
770          } else if ($scope.type == "GraDP") {
771            vm.tempProducts = response.data;
772          }
773          $scope.loading = false;
774        });
775      }
776    }
777  }
778
779  // vm.firstFormComplete = true;
780  // vm.secondFormComplete = true;
781  $scope.trustAsHtml = function (value) {
782    return $sce.trustAsHtml(value);
783  };
784
785  $scope.submitFirstForm = function () {
786    vm.firstFormComplete = true;
787  };
788
789  $scope.backToFirstForm = function () {
790    vm.firstFormComplete = false;
791  };
792
793  $scope.submitSecondForm = function () {
794    vm.firstFormComplete = true;
795    vm.secondFormComplete = true;
796  };
797
798  $scope.backToSecondForm = function () {
799    vm.secondFormComplete = false;
800  };
801
802  $scope.$watch("signup.questionnaire.property.propertyData", function (newValue) {
803    if (newValue && $scope.isObjectEmpty(newValue) === false) {
804      vm.products = [];
805
806      vm.tenorList = [];
807      for (let i = 0; i < newValue.dpShowOption.length; i++) {
808        vm.tenorList.push({
809          name: newValue.dpShowOption[i] + " bulan",
810          value: Number(newValue.dpShowOption[i]),
811        });
812      }
813    }
814  });
815
816  $scope.$watch("graKaryaForm.fieldOfBusiness", function (newValue, oldValue) {
817    if (newValue != oldValue) {
818      $scope.isFieldOfBusiness = true
819      vm.sectorEconomic = vm.sectorEconomics[newValue.value || "e72"]
820      vm.data.purpose = vm.purposeChosen.value;
821      $scope.graKaryaForm.purpose = vm.data.purpose
822    }
823  })
824
825  $scope.$watch("signup.domicileFlag", function (newValue, oldValue) {
826    if (newValue && newValue !== oldValue) {
827      if (newValue === "tidak") {
828        $scope.user.domicileAddress = "";
829      } else {
830        $scope.user.domicileAddress = $scope.user.address;
831      }
832    }
833  });
834
835  $scope.$watch("signup.amountText", function (newValue, oldValue) {
836    if (newValue != oldValue) {
837      if (newValue) {
838        var tempTextArray = newValue.split(",");
839        var tempText = tempTextArray.join("");
840
841        vm.questionnaire.amount = Number(tempText);
842      } else {
843        vm.questionnaire.amount = undefined;
844      }
845    }
846  });
847
848  $scope.propertyChange = function (property) {
849    vm.products = [];
850    vm.questionnaire.property = {
851      propertyData: property,
852      name: property.name,
853      imagesPath: property.imagesPath,
854      location: property.location,
855      address: property.address,
856      city: property.city,
857      province: property.province,
858      deposit: property.deposit,
859      adminFee: property.adminFee,
860      interestPct: property.interestPct,
861    };
862    if (property.developer) {
863      vm.questionnaire.property.developerName = property.developer.name;
864      vm.questionnaire.buffer = property.developer.buffer;
865    }
866    // vm.questionnaire.product = {}
867    vm.tenorList = [];
868    for (let i = 0; i < property.dpShowOption.length; i++) {
869      vm.tenorList.push({
870        name: property.dpShowOption[i] + " bulan",
871        value: Number(property.dpShowOption[i]),
872      });
873    }
874    vm.questionnaire.tenor = "";
875    // vm.tenorList = property.dpShowOption;
876  };
877
878  $scope.propertyClicked = function (index) {
879    for (var i = 0, len = vm.properties.length; i < len; i++) {
880      vm.properties[i].chosen = undefined;
881    }
882    delete vm.questionnaire.propertyUnit;
883    delete vm.questionnaire.product;
884    vm.products = [];
885    vm.properties[index].chosen = true;
886
887    vm.questionnaire.property.propertyData = vm.properties[index];
888    vm.questionnaire.property = {
889      propertyData: vm.properties[index],
890      name: vm.properties[index].name,
891      imagesPath: vm.properties[index].imagesPath,
892      // location: {
893      // 	coordinates: [Number],
894      // 	type: { type: String, default: "Point"}
895      // },
896      address: vm.properties[index].address,
897      city: vm.properties[index].city,
898      province: vm.properties[index].province,
899    };
900
901    if (vm.properties[index].developer) {
902      vm.questionnaire.property.developerName = vm.properties[index].developer.name;
903      vm.questionnaire.buffer = vm.properties[index].developer.buffer;
904    }
905
906    $scope.loading = true;
907
908    vm.propertyUnits = [];
909    vm.shouldLoadMorePropertyUnits = true;
910    vm.currentPropertyUnitsPage = -1;
911    $scope.infiniteScroll = {};
912    $scope.infiniteScroll.currentItems = 0;
913
914    vm.selectedPropertyId = vm.properties[index]._id;
915    vm.loadNextPagePropertyUnits();
916  };
917
918  $scope.propertyUnitChange = function (propertyUnit) {
919    vm.products = [];
920    vm.questionnaire.product = {};
921    for (var key in propertyUnit.priceList) {
922      for (var i = 0, len = vm.tempProducts.length; i < len; i++) {
923        if (vm.tempProducts[i].numberOfInstallment === Number(key)) {
924          vm.products.push(vm.tempProducts[i]);
925          break;
926        }
927      }
928    }
929  };
930
931  $scope.isObjectEmpty = function (card) {
932    return Object.keys(card).length === 0;
933  };
934
935  if ($scope.user.bidangPekerjaan) {
936    vm.bidangPekerjaanChosen = $scope.user.bidangPekerjaan
937      ? {
938        name: $scope.bidangPekerjaan.find((x) => x.value === $scope.user.bidangPekerjaan).name,
939        value: $scope.user.bidangPekerjaan,
940      }
941      : { name: "", value: "" };
942  }
943
944  if ($scope.user.industriesBorrower) {
945    vm.industryBorrowerChosen = $scope.user.industriesBorrower
946      ? {
947        name: $scope.industriesBorrower.find((x) => x.value === $scope.user.industriesBorrower).name,
948        value: $scope.user.industriesBorrower,
949      }
950      : { name: "", value: "" };
951  }
952
953  if ($scope.user.job_code) {
954    vm.job_codeChosen = $scope.user.job_code
955      ? {
956        name: $scope.job_code.find((x) => x.value === $scope.user.job_code).name,
957        value: $scope.user.job_code,
958      }
959      : { name: "", value: "" };
960  }
961  //-----------------------------------------------------------------------------------
962  // CREATE ACCOUNT
963  //-----------------------------------------------------------------------------------
964
965  $scope.createAccount = function () {
966    console.log("---------------------------------------------------------------");
967    console.log("## CREATE ACCOUNT ##");
968    console.log("---------------------------------------------------------------");
969
970    $scope.loading = true;
971    $scope.user.isTnCAgree = true;
972    // console.log("createAccount scoringId",$scope.scoringId);
973    $scope.user.scoringId = $scope.scoringId;
974    // console.log("createAccount $scope.user.scoringId",$scope.user.scoringId);
975
976    if (vm.bidangPekerjaanChosen) {
977      $scope.user.bidangPekerjaan = vm.bidangPekerjaanChosen.value;
978    }
979
980    if (vm.industryBorrowerChosen) {
981      $scope.user.company.industryBorrowerChosen = vm.industryBorrowerChosen.value;
982    }
983
984    if (vm.pengalamanKerjaChosen) {
985      $scope.user.pengalamanKerja = vm.pengalamanKerjaChosen.value;
986    }
987
988    if ($scope.type == "GraSewa") {
989      let { renovationAmount, rentAmount, totalAmount } = getGraSewaTotalAmount();
990      vm.questionnaire.graSewa.amount = totalAmount;
991      vm.questionnaire.graSewa.rentAmount = rentAmount;
992      vm.questionnaire.graSewa.renovationAmount = renovationAmount;
993      vm.questionnaire.graSewa.grasewaType = vm.grasewaTypeSelected;
994      vm.questionnaire.grasewaType = vm.grasewaTypeSelected;
995    }
996
997    if (vm.companyTypeChosen) {
998      if (vm.companyTypeChosen.name != "Other") {
999        $scope.user.jobInfo.companyType = vm.companyTypeChosen.name;
1000      } else {
1001        $scope.user.jobInfo.companyType = vm.companyTypeOther;
1002      }
1003    }
1004
1005    if (vm.industryChosen) {
1006      if (vm.industryChosen.name != "Other") {
1007        $scope.user.industry = vm.industryChosen.name;
1008      } else {
1009        $scope.user.industry = vm.industryOther;
1010      }
1011    }
1012
1013    if (vm.titleChosen) {
1014      $scope.user.title = vm.titleChosen.value;
1015    }
1016    if (vm.genderChosen) {
1017      $scope.user.gender = vm.genderChosen.value;
1018    }
1019    if (vm.maritalStatusChosen) {
1020      $scope.user.maritalStatus = vm.maritalStatusChosen.value;
1021    }
1022    if (vm.lastEducationChosen) {
1023      $scope.user.lastEducation = vm.lastEducationChosen.value;
1024    }
1025
1026    if (vm.religionChosen) {
1027      $scope.user.religion = vm.religionChosen.value;
1028    }
1029    if (vm.source_of_fundChosen) {
1030      $scope.user.source_of_fund = vm.source_of_fundChosen.value;
1031    }
1032    if (vm.open_account_reasonChosen) {
1033      $scope.user.open_account_reason = vm.open_account_reasonChosen.value;
1034      $scope.user.open_account_reason = vm.open_account_reasonChosen.value;
1035    }
1036
1037    if (vm.job_codeChosen) {
1038      $scope.user.job_code = vm.job_codeChosen.value;
1039    }
1040    if (vm.securityQuestionChosen) {
1041      $scope.user.securityQuestion = vm.securityQuestionChosen.item;
1042    }
1043
1044    if ($scope.user.correspondenceKTP === "tidak") {
1045      $scope.user.correspondenceKTP = false;
1046    }
1047
1048    if ($scope.user.domicileKTP === "tidak") {
1049      $scope.user.domicileKTP = false;
1050    }
1051
1052    if (vm.provinceChosen) {
1053      $scope.user.province = vm.provinceChosen.name;
1054    }
1055
1056    if (vm.cityChosen) {
1057      $scope.user.city = vm.cityChosen.name;
1058    }
1059
1060    if (vm.kecamatanChosen) {
1061      $scope.user.kecamatan = vm.kecamatanChosen.name;
1062    }
1063
1064    if (vm.kelurahanChosen) {
1065      $scope.user.kelurahan = vm.kelurahanChosen.name;
1066    }
1067
1068    if (vm.provinceCompanyChosen) {
1069      $scope.user.provinceCompany = vm.provinceCompanyChosen.name;
1070    }
1071
1072    if (vm.cityCompanyChosen) {
1073      $scope.user.cityCompany = vm.cityCompanyChosen.name;
1074    }
1075
1076    if (vm.kecamatanCompanyChosen) {
1077      $scope.user.kecamatanCompany = vm.kecamatanCompanyChosen.name;
1078    }
1079
1080    if (vm.kelurahanCompanyChosen) {
1081      $scope.user.kelurahanCompany = vm.kelurahanCompanyChosen.name;
1082    }
1083
1084    if (vm.borrowerTypeChosen) {
1085      $scope.user.borrowerType = vm.borrowerTypeChosen.value;
1086    }
1087
1088    if (vm.corespondenProvinceChosen) {
1089      $scope.user.corespondenProvinceChosen = vm.corespondenProvinceChosen.name;
1090    }
1091
1092    if (vm.corespondenCityChosen) {
1093      $scope.user.corespondenCityChosen = vm.corespondenCityChosen.name;
1094    }
1095
1096    if (vm.corespondenKecamatanChosen) {
1097      $scope.user.corespondenKecamatanChosen = vm.corespondenKecamatanChosen.name;
1098    }
1099
1100    if (vm.corespondenKelurahanChosen) {
1101      $scope.user.kelurahan = vm.corespondenKelurahanChosen.name;
1102    }
1103
1104    if ($scope.user.referralChosen && $scope.user.referralChosen.name == "Lainnya") {
1105      $scope.user.referal = $scope.user.referralOther;
1106    } else {
1107      if ($scope.user.referralChosen) {
1108        $scope.user.referal = $scope.user.referralChosen.name;
1109      }
1110    }
1111
1112    // Start to check user role as borrower/lender
1113    console.log("333");
1114    $scope.nameField = true;
1115    $scope.user.origin = "browser";
1116    if ($scope.user.role === "lender") {
1117      if ($scope.user.lenderType == "institutional") {
1118        $scope.user.isLjk = vm.isLjk
1119        if (vm.bidangUsahaChosen) {
1120          $scope.user.company.industry = vm.bidangUsahaChosen.value;
1121        }
1122        if (vm.sectorEconomic) {
1123          $scope.user.company.sectorEconomic = vm.sectorEconomic.value;
1124        }
1125        $scope.user.company.companyType = $scope.user.company.companyType.name;
1126        $scope.user.institutionName = $scope.user.company.companyType + ' ' + $scope.user.company.name
1127        if (vm.industryChosen) {
1128          $scope.user.industry = vm.industryChosen.name == 'Other' ? $scope.user.industryOther : vm.industryChosen.name;
1129        }
1130      } else {
1131        if (vm.sectorEconomic) {
1132          $scope.user.sectorEconomic = vm.sectorEconomic.value;
1133        }
1134        if (vm.bidangUsahaChosen) {
1135          $scope.user.bidangPekerjaan = vm.bidangUsahaChosen.value;
1136        }
1137      }
1138    } else if ($scope.user.role === "borrower") {
1139      vm.isInstitutional = false;
1140      if (vm.borrowerTypeChosen && vm.borrowerTypeChosen.value == "perusahaan") {
1141        vm.isInstitutional = true;
1142      }
1143    }
1144    // End to check user role as borrower/lender
1145
1146    // console.log('user role : ', $scope.user.role , ' ' , $scope.user.email , ' ' ,  ' ' ,  $scope.user.mobileNumber);
1147    if ($scope.user.role && $scope.user.email && $scope.user.password && $scope.user.mobileNumber) {
1148      console.log("444");
1149      vm.submitted = true;
1150      if ($scope.user.password != $scope.user.confirmPassword) {
1151        SweetAlert.swal($scope.textContent['swal']['error']['item-3']['title'], $scope.textContent['swal']['error']['item-3']['text'], "error");
1152        $scope.loading = false;
1153        console.log("bb");
1154      } else {
1155        if ($scope.user.role === "borrower") {
1156          $scope.user.questionnaire = vm.questionnaire;
1157        }
1158        // console.log('cc $scope.user',$scope.user);
1159        $scope.user.sectorEconomic = $scope.user.sectorEconomic ? $scope.user.sectorEconomic.value || vm.sectorEconomic.value : "009000"
1160        $scope.user.homeOwnershipStatusCode = $scope.user.homeOwnershipStatusCode ? $scope.user.homeOwnershipStatusCode.value : 1
1161        ServerService.Signup($scope.user, function (response) {
1162          if (!response) {
1163            $scope.loading = false;
1164            return SweetAlert.swal(response.status, response.message, "error");
1165          }
1166
1167          if (response.status != "Success") {
1168            $scope.loading = false;
1169            return SweetAlert.swal(response.status, response.message, "error");
1170          }
1171
1172          $("#skTermAndCondition").modal("hide");
1173          $("#skTermAndConditionLender").modal("hide");
1174          $("#verifiedLenderReminderModal").modal("hide");
1175          $(".in").remove();
1176          SettingsService.SetCredentials(response);
1177          currentUser = SettingsService.GetCredentials();
1178          var signedUpUser = response.data.user;
1179          // console.log("signedUpUser : ", signedUpUser);
1180          $scope.newUser = signedUpUser;
1181          $scope.user.email = signedUpUser.email; //replace the email with the lowercased email
1182
1183          var destinationEmails = [];
1184          destinationEmails.push(signedUpUser.email);
1185
1186          $window.async.waterfall(
1187            [
1188              function (done) {
1189                $window.async.mapValues(
1190                  vm.imagesToBeUploaded,
1191                  function (file, key, next) {
1192                    let params = {};
1193                    params.file = file;
1194                    params.path = folder + "user/" + $scope.newUser._id;
1195                    ServerService.UploadFile(currentUser, params, function (response) {
1196                      if (response && response.res && response.res.status == 200) {
1197                        if (key === "idImagePath") {
1198                          $scope.user.idImagePath = response.imagePath;
1199                          delete vm.imagesToBeUploaded[key];
1200                        } else if (key === "NPWPImagePathCompany") {
1201                          $scope.user.company.NPWPImagePath = response.imagePath;
1202                          delete vm.imagesToBeUploaded[key];
1203                        } else if (key === "NPWPImagePath") {
1204                          $scope.user.NPWPImagePath = response.imagePath;
1205                          delete vm.imagesToBeUploaded[key];
1206                        } else if (key === "RABImagePath") {
1207                          $scope.user.RABImagePath = response.imagePath;
1208                          delete vm.imagesToBeUploaded[key];
1209                        } else if (key === "siupCompanyImagePath") {
1210                          $scope.user.jobInfo.siupImagePath = response.imagePath;
1211                          delete vm.imagesToBeUploaded[key];
1212                        } else if (key === "tdpCompanyImagePath") {
1213                          $scope.user.jobInfo.tdpImagePath = response.imagePath;
1214                          delete vm.imagesToBeUploaded[key];
1215                        } else if (key === "NPWPCompanyImagePath") {
1216                          $scope.user.jobInfo.NPWPImagePath = response.imagePath;
1217                          delete vm.imagesToBeUploaded[key];
1218                        } else if (key === "SKMenteriImagePath") {
1219                          $scope.user.jobInfo.SKMenteriImagePath = response.imagePath;
1220                          delete vm.imagesToBeUploaded[key];
1221                        } else if (key === "suratDomisiliImagePath") {
1222                          $scope.user.jobInfo.suratDomisiliImagePath = response.imagePath;
1223                          delete vm.imagesToBeUploaded[key];
1224                        } else if (key === "establishmentDeedImagePath") {
1225                          $scope.user.jobInfo.establishmentDeedImagePath = response.imagePath;
1226                          delete vm.imagesToBeUploaded[key];
1227                        } else if (key === "latestEstablishmentDeedImagePath") {
1228                          $scope.user.jobInfo.latestEstablishmentDeedImagePath = response.imagePath;
1229                          delete vm.imagesToBeUploaded[key];
1230                        }
1231                        next();
1232                      } else {
1233                        $("#skTermAndCondition").modal("hide");
1234                        $("#skTermAndConditionLender").modal("hide");
1235                        $("#verifiedLenderReminderModal").modal("hide");
1236                        done("no response");
1237                      }
1238                    });
1239                  },
1240                  function (err) {
1241                    if (err) {
1242                      $("#skTermAndCondition").modal("hide");
1243                      $("#skTermAndConditionLender").modal("hide");
1244                      $("#verifiedLenderReminderModal").modal("hide");
1245                      done(err);
1246                    }
1247
1248                    $("#skTermAndCondition").modal("hide");
1249                    $("#skTermAndConditionLender").modal("hide");
1250                    $("#verifiedLenderReminderModal").modal("hide");
1251                    done();
1252                  }
1253                );
1254              },
1255              function (done) {
1256                $scope.user._id = $scope.newUser._id;
1257                $scope.user.name = {
1258                  first: $scope.user.firstName,
1259                  last: $scope.user.lastName,
1260                };
1261
1262                if ($scope.user.role === "lender") {
1263                  if (vm.numberOfInstallmentChosen) {
1264                    if (vm.numberOfInstallmentChosen.name == "24 Bulan") {
1265                      $scope.user.lenderPreference.numberOfInstallment = 24;
1266                    } else if (vm.numberOfInstallmentChosen.name == "36 Bulan") {
1267                      $scope.user.lenderPreference.numberOfInstallment = 36;
1268                    }
1269                  }
1270
1271                  if (vm.numberOfBorrowersChosen) {
1272                    $scope.user.lenderPreference.numberOfBorrowers = vm.numberOfBorrowersChosen.name;
1273                  }
1274
1275                  if (vm.companyTypeChosen) {
1276                    if (vm.companyTypeChosen.name == "Other") {
1277                      $scope.user.jobInfo.companyType = vm.companyTypeOther;
1278                    } else {
1279                      $scope.user.jobInfo.companyType = vm.companyTypeChosen.name;
1280                    }
1281                  }
1282                }
1283
1284                ServerService.UpdateUser(currentUser, $scope.user, function (response) {
1285                  if (response) {
1286                    if (response.status === "Success") {
1287                      $("#skTermAndCondition").modal("hide");
1288                      $("#skTermAndConditionLender").modal("hide");
1289                      $("#verifiedLenderReminderModal").modal("hide");
1290                      done();
1291                    } else {
1292                      $("#skTermAndCondition").modal("hide");
1293                      $("#skTermAndConditionLender").modal("hide");
1294                      $("#verifiedLenderReminderModal").modal("hide");
1295                      done(response);
1296                    }
1297                  } else {
1298                    $("#skTermAndCondition").modal("hide");
1299                    $("#skTermAndConditionLender").modal("hide");
1300                    $("#verifiedLenderReminderModal").modal("hide");
1301                    done("no response");
1302                  }
1303                });
1304              },
1305              //send verify email
1306              function (done) {
1307                var destinationEmails = [];
1308                destinationEmails.push($scope.newUser.email);
1309
1310                var emailData = {};
1311                emailData.email = $scope.newUser.email;
1312                emailData.role = $scope.newUser.role;
1313                emailData.name = $scope.newUser.name;
1314
1315                ServerService.SendAccountVerificationEmailV2(
1316                  currentUser,
1317                  emailData,
1318                  $scope.newUser._id,
1319                  function (response) {
1320                    if (!response) {
1321                      $("#skTermAndCondition").modal("hide");
1322                      $("#skTermAndConditionLender").modal("hide");
1323                      $("#verifiedLenderReminderModal").modal("hide");
1324                      return done("no response");
1325                    }
1326                    if (response.statusCode != 200) {
1327                      $("#skTermAndCondition").modal("hide");
1328                      $("#skTermAndConditionLender").modal("hide");
1329                      $("#verifiedLenderReminderModal").modal("hide");
1330                      return done(response);
1331                    }
1332                    $("#skTermAndCondition").modal("hide");
1333                    $("#skTermAndConditionLender").modal("hide");
1334                    $("#verifiedLenderReminderModal").modal("hide");
1335                    return done();
1336                  }
1337                );
1338              },
1339            ],
1340            function (err) {
1341              if (typeof err === "string") {
1342                if (err === "no response") {
1343                  SweetAlert.swal($scope.textContent['swal']['error']['item-1']['title'], $scope.textContent['swal']['error']['item-1']['text'], "error");
1344                  $scope.loading = false;
1345                }
1346              } else if (typeof err === "object") {
1347                SweetAlert.swal(err.error, err.message, "error");
1348                $scope.loading = false;
1349              }
1350
1351              if (!err) {
1352                ServerService.SubscribeNewsletter(signedUpUser, function (response) {
1353                  if (!response) {
1354                    $scope.loading = false;
1355                    return SweetAlert.swal(
1356                      $scope.textContent['swal']['error']['item-1']['title'],
1357                      $scope.textContent['swal']['error']['item-1']['text'],
1358                      "error"
1359                    );
1360                  }
1361
1362                  if (response.status === "Success") {
1363                    if (signedUpUser.role === "borrower") {
1364                      $state.go("applyLoan");
1365                      $scope.loading = false;
1366                    }
1367                    if (signedUpUser.role === "lender") {
1368                      let phoneNumber = $scope.newUser.mobileNumber.substring(0, 3);
1369                      if ($scope.newUser.mobileNumber[3] === "0") {
1370                        phoneNumber += $scope.newUser.mobileNumber.substring(4, $scope.newUser.mobileNumber.length);
1371                      } else phoneNumber = $scope.newUser.mobileNumber;
1372
1373                      ServerService.RequestVerifyPhoneNumberSignup(
1374                        currentUser,
1375                        phoneNumber,
1376                        $scope.newUser._id,
1377                        function (response) {
1378                          var data = {};
1379                          data.data = {
1380                            token: currentUser.token,
1381                            user: response.data,
1382                          };
1383                          SettingsService.SetCredentials(data);
1384
1385                          $("#skTermAndCondition").modal("hide");
1386                          $("#skTermAndConditionLender").modal("hide");
1387                          $("#verifiedLenderReminderModal").modal("hide");
1388                          $state.go("app.dashboard");
1389                          $("#skTermAndCondition").modal("hide");
1390                          $("#skTermAndConditionLender").modal("hide");
1391                          $("#verifiedLenderReminderModal").modal("hide");
1392                          $scope.loading = false;
1393                        }
1394                      );
1395                    }
1396                  } else {
1397                    if (signedUpUser.role === "lender") {
1398                      $("#skTermAndCondition").modal("hide");
1399                      $("#skTermAndConditionLender").modal("hide");
1400                      $("#verifiedLenderReminderModal").modal("hide");
1401                      $state.go("app.dashboard");
1402                    } else if (signedUpUser.role === "borrower") {
1403                      $("#skTermAndCondition").modal("hide");
1404                      $("#skTermAndConditionLender").modal("hide");
1405                      $("#verifiedLenderReminderModal").modal("hide");
1406                      $state.go("applyLoan");
1407                    }
1408                    $("#skTermAndCondition").modal("hide");
1409                    $("#skTermAndConditionLender").modal("hide");
1410                    $("#verifiedLenderReminderModal").modal("hide");
1411                    $scope.loading = false;
1412                  }
1413                });
1414              }
1415            }
1416          );
1417        });
1418      }
1419    } else {
1420      $("#skTermAndCondition").modal("hide");
1421      $("#skTermAndConditionLender").modal("hide");
1422      $("#verifiedLenderReminderModal").modal("hide");
1423      SweetAlert.swal($scope.textContent['swal']['error']['item-4']['title'], $scope.textContent['swal']['error']['item-4']['text'], "error");
1424      vm.submitted = false;
1425      $scope.loading = false;
1426    }
1427  };
1428
1429  //-----------------------------------------------------------------------------------
1430  // [END] CREATE ACCOUNT
1431  //-----------------------------------------------------------------------------------
1432
1433  vm.changeFormatNumber = function (number) {
1434    return accounting.formatNumber(number);
1435  };
1436
1437  // pre assesment loan
1438  function submitGrastrataQuestionnaireStep1() {
1439    let dateOfBirth = new Date(vm.questionnaire.dateOfBirth).getTime();
1440    let ageDifMs = Date.now() - dateOfBirth;
1441    let ageDate = new Date(ageDifMs);
1442    let age = Math.abs(ageDate.getUTCFullYear() - 1970);
1443    let monthlyIncome = vm.questionnaire.monthlyIncome;
1444    let passPctMax = vm.globalSetting.graStrataPassLoanPctMax;
1445    let amount = vm.questionnaire.graStrata.amount;
1446    let tenorInYears = vm.questionnaire.graStrata.rollingTenor;
1447    let { interestPctRolling, installmentAmountRolling, installmentAmountRollingRounded } =
1448      calculateGraStrataInstallmentAmount(amount, tenorInYears);
1449    let maxAmount = passPctMax * monthlyIncome;
1450
1451    // console.log("age", age);
1452    // console.log('amount',amount)
1453    // console.log('tenorInYears',tenorInYears)
1454    // console.log('installmentAmountRolling',installmentAmountRolling)
1455    // console.log('interestPctRolling',interestPctRolling)
1456    // console.log('maxAmount',maxAmount)
1457
1458    if (age + tenorInYears > 55) {
1459      vm.questionnaire.graStrata.interestPctRolling = interestPctRolling;
1460      vm.questionnaire.graStrata.installmentAmountRolling = installmentAmountRolling;
1461
1462      SweetAlert.swal($scope.textContent['swal']['error']['item-5']['title'], $scope.textContent['swal']['error']['item-5']['text'], "error");
1463      return false;
1464    }
1465    if (installmentAmountRolling <= maxAmount) {
1466      // pass to next process
1467      let message =
1468        "<div style='font-size: 18px'>" +
1469        `<span><strong>${$scope.textContent['swal']['success']['item-1']['text-1']}</strong></span><br>` +
1470        `<span> ${$scope.textContent['swal']['success']['item-1']['text-2']} </span><br><br>` +
1471        `<span style='color: red'><strong> ${$scope.textContent['swal']['success']['item-1']['text-3']} ` +
1472        accounting.formatNumber(installmentAmountRollingRounded) +
1473        " </strong></span><br><br>" +
1474        `<span> ${$scope.textContent['swal']['success']['item-1']['text-4']} </span><br>` +
1475        `<span> ${$scope.textContent['swal']['success']['item-1']['text-5']} </span>` +
1476        "</div>";
1477
1478      SweetAlert.swal({
1479        title: $scope.textContent['swal']['success']['item-1']['title'],
1480        text: message,
1481        html: true,
1482        icon: "success",
1483        confirmButtonText: $scope.textContent['swal']['success']['item-1']['button'],
1484      });
1485      vm.questionnaireIsCompleteStep1 = true;
1486      vm.questionnaireIsComplete = false;
1487      return true;
1488    } else {
1489      // failed
1490      vm.questionnaire.graStrata.interestPctRolling = interestPctRolling;
1491      vm.questionnaire.graStrata.installmentAmountRolling = installmentAmountRolling;
1492
1493      SweetAlert.swal($scope.textContent['swal']['error']['item-5']['title'], $scope.textContent['swal']['error']['item-5']['text'], "error");
1494      return false;
1495    }
1496  }
1497
1498  // sending email
1499  function submitGrastrataQuestionnaireStep2() {
1500    let destinationEmail = "";
1501    let currentUrl = $location.absUrl();
1502    if (currentUrl.includes("dev.gradana") === true || currentUrl.includes("137.59.126.204")) {
1503      destinationEmail = "[email protected]";
1504    } else if (
1505      currentUrl.includes("gradana.co.id") == true ||
1506      currentUrl.includes("gradana.com") == true ||
1507      currentUrl.includes("116.206.196.96")
1508    ) {
1509      destinationEmail = "[email protected]";
1510    } else {
1511      destinationEmail = "[email protected]";
1512    }
1513    let emailContent = {
1514      subjectEmail: "[Gradana] New Account Register Grastrata",
1515      destinationEmail: destinationEmail,
1516      message: "",
1517    };
1518
1519    emailContent.message =
1520      "" +
1521      "kewarganegaraan       : " +
1522      vm.questionnaire.nationality +
1523      "\n \n" +
1524      "lama bekerja          : " +
1525      vm.questionnaire.workSince +
1526      "\n \n" +
1527      "tgl lahir             : " +
1528      moment(vm.questionnaire.dateOfBirth).format("YYYY-MM-DD") +
1529      "\n \n" +
1530      "penghasilan per bulan : Rp " +
1531      accounting.formatNumber(vm.questionnaire.monthlyIncome) +
1532      "\n \n" +
1533      "pinjaman yg diajukan  : " +
1534      vm.questionnaire.graStrata.amount +
1535      "\n \n" +
1536      "tenor                 : " +
1537      vm.questionnaire.graStrata.rollingTenor +
1538      " tahun \n \n" +
1539      "PEMBELI \n \n" +
1540      "nama                  : " +
1541      vm.questionnaire.graStrata.buyer.name +
1542      "\n \n" +
1543      "no telepon            : " +
1544      vm.questionnaire.graStrata.buyer.phoneNo +
1545      "\n \n" +
1546      "email                 : " +
1547      vm.questionnaire.graStrata.buyer.email +
1548      "\n \n" +
1549      "PENJUAL \n \n" +
1550      "nama                  : " +
1551      vm.questionnaire.graStrata.seller.name +
1552      "\n \n" +
1553      "no telepon            : " +
1554      vm.questionnaire.graStrata.seller.phoneNo +
1555      "\n \n";
1556    if (vm.questionnaire.graStrata.seller.email) {
1557      emailContent.message =
1558        emailContent.message + "email                 : " + vm.questionnaire.graStrata.seller.email + "\n \n";
1559    }
1560    emailContent.message =
1561      emailContent.message +
1562      "PROPERTI \n \n" +
1563      "harga                 : " +
1564      vm.questionnaire.graStrata.property.price +
1565      "\n \n" +
1566      "alamat                : " +
1567      vm.questionnaire.graStrata.property.address +
1568      "\n \n" +
1569      "luas bangunan         : " +
1570      vm.questionnaire.graStrata.property.buildingSize +
1571      " m²" +
1572      "\n \n" +
1573      "luas tanah            : " +
1574      vm.questionnaire.graStrata.property.landSize +
1575      " m²" +
1576      "\n \n";
1577
1578    ServerService.NewSendEmailsBySendGrid(emailContent, function (response) {
1579      // pass to next process
1580      let message =
1581        "<div style='font-size: 18px'>" +
1582        `<span><strong>${$scope.textContent['swal']['success']['item-2']['text-1']}</strong></span><br>` +
1583        `<span><strong>${$scope.textContent['swal']['success']['item-2']['text-2']}</strong></span><br>` +
1584        "</div>";
1585
1586      SweetAlert.swal(
1587        {
1588          title: $scope.textContent['swal']['success']['item-2']['title'],
1589          text: message,
1590          html: true,
1591          icon: "success",
1592          confirmButtonColor: "#EF5936",
1593          confirmButtonText: $scope.textContent['swal']['success']['item-2']['button'],
1594        },
1595        function (isConfirm) {
1596          if (isConfirm) {
1597            vm.questionnaireIsCompleteStep2 = true;
1598            vm.questionnaireIsComplete = true;
1599            return;
1600          }
1601        }
1602      );
1603    });
1604  }
1605
1606  $scope.submitQuestionnaireStep2 = function () {
1607    if ($scope.type == "GraStrata") {
1608      return submitGrastrataQuestionnaireStep2();
1609    }
1610  };
1611
1612  $scope.submitQuestionnaire = function () {
1613    if ($scope.type == "GraStrata") {
1614      return submitGrastrataQuestionnaireStep1();
1615    }
1616
1617    function nationalityValidation() {
1618      var score = false;
1619
1620      if (vm.questionnaire.nationality === "WNI") {
1621        score = true;
1622      }
1623      return score;
1624    }
1625
1626    function dateOfBirthValidation() {
1627      var score = false;
1628      var dateOfBirthYear = new Date(vm.questionnaire.dateOfBirth).getFullYear();
1629      var currentYear = new Date().getFullYear();
1630
1631      if (currentYear - dateOfBirthYear <= 45) {
1632        score = true;
1633      }
1634      return score;
1635    }
1636
1637    function startDateValidation() {
1638      var score = false;
1639      var startDate = new Date(vm.questionnaire.startDate).getTime;
1640      var currentDate = new Date().getTime;
1641
1642      if (startDate >= currentDate) {
1643        score = true;
1644      }
1645
1646      return score;
1647    }
1648
1649    function workSinceValidation() {
1650      var score = false;
1651
1652      if (vm.questionnaire.workSince === "=> 1 tahun") {
1653        score = true;
1654      }
1655
1656      return score;
1657    }
1658
1659    function incomeValidation() {
1660      var score = false;
1661      let { installmentAmount } = calculateInstallmentAmount(vm.questionnaire.amount, vm.questionnaire.tenor);
1662      let monthlyInstallment;
1663      if ($scope.type == "GraDP") {
1664        monthlyInstallment = installmentAmount;
1665      } else {
1666        // console.log('====' , vm.questionnaire)
1667        monthlyInstallment =
1668          vm.questionnaire.propertyUnit.propertyUnitData.priceList[vm.questionnaire.product.productData.numberOfInstallment]
1669            .monthlyInstallment;
1670      }
1671      if (monthlyInstallment <= vm.questionnaire.monthlyIncome / 3) {
1672        score = true;
1673      }
1674      return score;
1675    }
1676
1677    if ($scope.type == "GraSewa") {
1678      if (startDateValidation()) {
1679        let { renovationAmount, rentAmount, totalAmount } = getGraSewaTotalAmount();
1680        let tenor = vm.selectedTenor.value;
1681        // let grasewaInterestPct = vm.globalSetting.grasewaInterestPct;
1682        // let borrowerPrice = totalAmount * grasewaInterestPct;
1683        // let installmentAmount = borrowerPrice / tenor;
1684        const installmentPct = (17.5 / 100 / 12) * tenor;
1685        let installmentAmount = (totalAmount + totalAmount * installmentPct) / tenor;
1686        installmentAmount = Math.round(installmentAmount / 1000) * 1000;
1687
1688        vm.questionnaire.graSewa.tenor = tenor;
1689        vm.questionnaire.borrowerType = vm.borrowerTypeChosen.value; //vm.selectedBorrowerType.value;
1690        vm.questionnaire.graSewa.amount = totalAmount;
1691        vm.questionnaire.graSewa.renovationAmount = renovationAmount;
1692        vm.questionnaire.graSewa.rentAmount = rentAmount;
1693        vm.questionnaire.graSewa.installmentAmount = installmentAmount;
1694        vm.questionnaire.graSewa.grasewaType = vm.grasewaTypeSelected;
1695        vm.questionnaire.graSewa.startingDate = vm.questionnaire.startDate;
1696
1697        SweetAlert.swal(
1698          $scope.textContent['swal']['success']['item-3']['title'],
1699          $scope.textContent['swal']['success']['item-3']['text-1'] +
1700          vm.changeFormatNumber(installmentAmount) +
1701          $scope.textContent['swal']['success']['item-3']['title-2'],
1702          "success"
1703        );
1704        vm.questionnaireIsComplete = true;
1705      } else {
1706        var message = $scope.textContent['swal']['error']['item-6']['text-1'];
1707        if (!dateOfBirthValidation()) {
1708          message = message + $scope.textContent['swal']['error']['item-6']['text-2'];
1709          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Usia calon peminjam tidak dapat melebihi 45 tahun', 'error');
1710        }
1711        SweetAlert.swal($scope.textContent['swal']['error']['item-6']['title'], message, "error");
1712      }
1713    } else if ($scope.type == "GraDP") {
1714      let message;
1715      let amount = vm.questionnaire.amount;
1716      let tenor = vm.questionnaire.tenor;
1717      let { interestPct, installmentAmount, deposit, adminFee, borrowerPrice } = calculateInstallmentAmount(amount, tenor);
1718      message =
1719        "<div style='font-size: 18px'>" +
1720        `<span><strong>${$scope.textContent['swal']['success']['item-4']['text-1']}</strong></span><br><br>` +
1721        `<span style='font-size: 14px'>${$scope.textContent['swal']['success']['item-4']['text-2']}</span><span style='font-size: 14px'>&nbsp` +
1722        vm.questionnaire.property.name +
1723        "</span><br>" +
1724        `<span style='font-size: 14px'>${$scope.textContent['swal']['success']['item-4']['text-3']}</span><span style='font-size: 14px'>&nbsp ${$scope.textContent['swal']['success']['item-4']['currency']} ` +
1725        accounting.formatNumber(amount) +
1726        "</span><br>" +
1727        `<span style='font-size: 14px'>${$scope.textContent['swal']['success']['item-4']['text-4']}</span><span style='font-size: 14px'>&nbsp` +
1728        tenor +
1729        ` ${$scope.textContent['swal']['success']['item-4']['text-5']}</span><br>` +
1730        `<span style='font-size: 14px'>${$scope.textContent['swal']['success']['item-4']['text-6']}</span><span style='font-size: 14px'>&nbsp ${$scope.textContent['swal']['success']['item-4']['currency']} ` +
1731        accounting.formatNumber(installmentAmount) +
1732        "</span><br>" +
1733        // + "<span style='font-size: 14px'>Biaya Deposit: </span><span style='font-size: 14px'>&nbsp Rp "+ accounting.formatNumber(deposit)+"</span><br>"
1734        `<span style='font-size: 14px'>${$scope.textContent['swal']['success']['item-4']['text-7']}</span><span style='font-size: 14px'>&nbsp ${$scope.textContent['swal']['success']['item-4']['currency']} ` +
1735        accounting.formatNumber(adminFee) +
1736        "</span><br><br>" +
1737        `<span style='font-size: 14px'> ${$scope.textContent['swal']['success']['item-4']['text-8']}
1737 </span><br>` +
1738        `<span style='font-size: 14px'> ${$scope.textContent['swal']['success']['item-4']['text-9']} </span>` +
1739        "</div>";
1740      if (nationalityValidation() && dateOfBirthValidation() && workSinceValidation() && incomeValidation()) {
1741        SweetAlert.swal({
1742          title: $scope.textContent['swal']['success']['item-4']['title'],
1743          text: message,
1744          html: true,
1745          icon: "success",
1746          confirmButtonText: $scope.textContent['swal']['success']['item-4']['button'],
1747        });
1748        vm.questionnaireIsComplete = true;
1749      } else {
1750        message = $scope.textContent['swal']['error']['item-7']['text-1'];
1751        if (!nationalityValidation()) {
1752          message = message + $scope.textContent['swal']['error']['item-7']['text-2'];
1753          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Kewarganegaraan harus Indonesia', 'error');
1754        }
1755        if (!dateOfBirthValidation()) {
1756          message = message + $scope.textContent['swal']['error']['item-7']['text-3'];
1757          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Usia calon peminjam tidak dapat melebihi 45 tahun', 'error');
1758        }
1759        if (!startDateValidation()) {
1760          message = message + $scope.textContent['swal']['error']['item-7']['text-4'];
1761        }
1762        if (!workSinceValidation()) {
1763          message = message + $scope.textContent['swal']['error']['item-7']['text-5'];
1764          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Lama bekerja minimum 1 tahun', 'error');
1765        }
1766        if (!incomeValidation()) {
1767          message = message + $scope.textContent['swal']['error']['item-7']['text-6'];
1768          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Cicilan maksimum ⅓ dari penghasilan bulanan.', 'error');
1769        }
1770        SweetAlert.swal($scope.textContent['swal']['error']['item-7']['title'], message, "error");
1771      }
1772    } else {
1773      if (nationalityValidation() && dateOfBirthValidation() && workSinceValidation() && incomeValidation()) {
1774        SweetAlert.swal($scope.textContent['swal']['success']['item-5']['title'], $scope.textContent['swal']['success']['item-5']['text'], "success");
1775        vm.questionnaireIsComplete = true;
1776      } else {
1777        var message = $scope.textContent['swal']['error']['item-8']['text-1'];
1778        if (!nationalityValidation()) {
1779          message = message + $scope.textContent['swal']['error']['item-8']['text-2'];
1780          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Kewarganegaraan harus Indonesia', 'error');
1781        }
1782        if (!dateOfBirthValidation()) {
1783          message = message + $scope.textContent['swal']['error']['item-8']['text-3'];
1784          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Usia calon peminjam tidak dapat melebihi 45 tahun', 'error');
1785        }
1786        if (!startDateValidation()) {
1787          message = message + $scope.textContent['swal']['error']['item-8']['text-4'];
1788        }
1789        if (!workSinceValidation()) {
1790          message = message + $scope.textContent['swal']['error']['item-8']['text-5'];
1791          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Lama bekerja minimum 1 tahun', 'error');
1792        }
1793        if (!incomeValidation()) {
1794          message = message + $scope.textContent['swal']['error']['item-8']['text-6'];
1795          // SweetAlert.swal('Gagal', 'Maaf, Anda belum memenuhi persyaratan untuk mengajukan pinjaman cicilan DP Gradana.  Cicilan maksimum ⅓ dari penghasilan bulanan.', 'error');
1796        }
1797        SweetAlert.swal($scope.textContent['swal']['error']['item-8']['title'], message, "error");
1798      }
1799    }
1800  };
1801
1802  $scope.backButton = function () {
1803    // console.log('test 5');
1804    $state.go("access.login");
1805  };
1806
1807  $scope.navigatePage = function (toPage) {
1808    if (toPage === "home") {
1809      // console.log('test 6');
1810      $state.go("home");
1811    }
1812  };
1813
1814  $scope.showWithdrawalModal = function () {
1815    $("#referralCodeModal").modal("show");
1816  };
1817
1818  $scope.submitReferralCode = function () {
1819    // store real referral code
1820    if (vm.referralCodeView) {
1821      ServerService.CheckReferralCodeAvailability(vm.referralCodeView, function (response) {
1822        if (!response) {
1823          $scope.loading = false;
1824          return SweetAlert.swal(
1825            $scope.textContent['swal']['error']['item-1']['title'],
1826            $scope.textContent['swal']['error']['item-1']['text'],
1827            "error"
1828          );
1829        }
1830        if (response.status != "Success") {
1831          $scope.loading = false;
1832          return SweetAlert.swal(response.status, response.message, "error");
1833        }
1834
1835        SweetAlert.swal(response.status, $scope.textContent['swal']['success']['item-6']['text'], "success");
1836
1837        // console.log('RESPONSE ', response)
1838        // console.log('RESPONSE ', vm)
1839        $("#referralCodeModal").modal("hide");
1840        // save referent, got from someone's referralCode
1841        $scope.user.referent = vm.referralCodeView
1842        console.log("$scope.user", $scope.user)
1843      });
1844    } else {
1845      $("#referralCodeModal").modal("hide");
1846    }
1847  };
1848
1849  vm.getTnc = function () {
1850    let queryParameters = {};
1851    const roleMapping = {
1852      lender: "Lender",
1853      borrower: "Borrower",
1854    };
1855    queryParameters.isActive = true;
1856
1857    if ($scope.user.role != "") {
1858      queryParameters.type = roleMapping[$scope.user.role];
1859    }
1860
1861    $scope.loading = true;
1862    ServerService.GetTermAndCondition(currentUser, queryParameters, function (response) {
1863      if (!response) {
1864        SweetAlert.swal($scope.textContent['swal']['error']['item-1']['title'], $scope.textContent['swal']['error']['item-1']['text'], "error");
1865        return ($scope.loading = false);
1866      }
1867
1868      if (!response.statusCode === 200) {
1869        SweetAlert.swal(response.status, response.message, "error");
1870        return ($scope.loading = false);
1871      }
1872
1873      if (!response.data) {
1874        return ($scope.loading = false);
1875      }
1876      vm.tnc = response.data;
1877      $scope.user.version = vm.tnc.version;
1878      $scope.graKaryaForm.version = vm.tnc.version;
1879      $scope.loading = false;
1880    });
1881  };
1882  vm.getTnc();
1883
1884  //---------------------------------------------------------------------------------------------------
1885  // WATCHER / EVENT LISTENER
1886  //---------------------------------------------------------------------------------------------------
1887  // signup.selectedBorrowerType
1888  $scope.$watch("signup.bidangPekerjaanChosen", function (newValue, oldValue) {
1889    if (newValue != oldValue) {
1890      $scope.loading = true;
1891      $scope.user.bidangPekerjaan = newValue.value;
1892      $scope.isFieldOfBusiness = true
1893      vm.sectorEconomic = vm.sectorEconomics[newValue.value || "e72"]
1894      vm.data.purpose = vm.purposeChosen.value;
1895      console.log("first", vm.bidangPekerjaanChosen);
1896      $scope.loading = false;
1897    }
1898  });
1899
1900  $scope.$watch("signup.industryBorrowerChosen", function (newValue, oldValue) {
1901    if (newValue != oldValue) {
1902      $scope.loading = true;
1903      $scope.user.company.industry = newValue.value;
1904      $scope.isFieldOfBusiness = true
1905      vm.sectorEconomic = vm.sectorEconomics[newValue.value || "e72"]
1906      vm.data.purpose = vm.purposeChosen.value;
1907      console.log("industryChosen", vm.industryBorrowerChosen);
1908      $scope.loading = false;
1909    }
1910  });
1911
1912  $scope.$watch("signup.bidangUsahaChosen", function (newValue, oldValue) {
1913    if (newValue != oldValue) {
1914      $scope.loading = true;
1915      $scope.isFieldOfBusiness = true
1916      vm.sectorEconomic = vm.sectorEconomics[newValue.value || "e72"]
1917      $scope.loading = false;
1918    }
1919  });
1920
1921  $scope.$watch("signup.borrowerTypeChosen", function (newValue, oldValue) {
1922    if (newValue) {
1923      $scope.loading = true;
1924      $scope.user.borrowerType = newValue.value;
1925      $scope.loading = false;
1926      if (newValue.value == "perusahaan") {
1927        vm.isInstitutional = true;
1928      } else {
1929        vm.isInstitutional = false;
1930      }
1931      console.log("borrowerTypeChosen", newValue.value);
1932    }
1933  });
1934
1935  $scope.$watch("user.correspondenceKTP", function (newValue) {
1936    if (newValue) {
1937      if (newValue === "sesuai") {
1938        vm.isMatchKTP = true;
1939      } else {
1940        vm.isMatchKTP = false;
1941      }
1942    }
1943  });
1944
1945  $scope.$watch("user.domicileKTP", function (newValue) {
1946    if (newValue) {
1947      if (newValue === "sesuai") {
1948        vm.isMatchKTP = true;
1949      } else {
1950        vm.isMatchKTP = false;
1951      }
1952    }
1953  });
1954
1955  $scope.$watch("user.lenderType", function (newValue) {
1956    if (newValue) {
1957      if (newValue == "institutional") {
1958        vm.isInstitutional = true;
1959      } else {
1960        vm.isInstitutional = false;
1961      }
1962    }
1963  });
1964
1965  $scope.$watch("signup.questionnaire.propertyUnitType", function (newValue) {
1966    if (newValue) {
1967      vm.data.propertyUnitType = newValue.name;
1968    }
1969  });
1970
1971  $scope.$watch("signup.questionnaire.propertyUnit.propertyUnitData", function (newValue) {
1972    if (newValue && $scope.isObjectEmpty(newValue) === false) {
1973      vm.questionnaire.propertyUnit.name = newValue.name;
1974      vm.questionnaire.propertyUnit.landSize = newValue.landSize;
1975      vm.questionnaire.propertyUnit.buildingSize = newValue.buildingSize;
1976      // vm.questionnaire.propertyUnit.price = newValue.price;
1977      vm.questionnaire.propertyUnit.utj = newValue.utj;
1978      vm.questionnaire.propertyUnit.priceList = newValue.priceList;
1979    }
1980  });
1981
1982  $scope.$watch("signup.questionnaire.product.productData", function (newValue) {
1983    if ($scope.type == "GraDP") {
1984      if (newValue && $scope.isObjectEmpty(newValue) === false) {
1985        vm.questionnaire.product.name = newValue.name;
1986        vm.questionnaire.product.productType = newValue.productType.name;
1987        vm.questionnaire.product.numberOfInstallment = newValue.numberOfInstallment;
1988      }
1989    } else if ($scope.type == "GraSewa") {
1990      if (newValue) {
1991        vm.questionnaire.product.name = newValue.name;
1992        vm.questionnaire.product.productType = newValue.productType.name;
1993        vm.questionnaire.product.numberOfInstallment = newValue.numberOfInstallment;
1994
1995        vm.rentFlexLenderPriceText = undefined; //reset price
1996        vm.propertyUnitPriceObject = {};
1997      }
1998    }
1999  });
2000
2001  $scope.$watchGroup(
2002    ["signup.questionnaire.propertyUnit.propertyUnitData", "signup.questionnaire.product.productData"],
2003    function (newValues, oldValues) {
2004      if (newValues[0] && newValues[1]) {
2005        if (newValues[0] !== oldValues[0] || newValues[1] !== oldValues[1]) {
2006          // vm.questionnaire.amount = newValues[0].priceList[newValues[1].numberOfInstallment].monthlyInstallment * newValues[1].numberOfInstallment;
2007          vm.questionnaire.amount = newValues[0].priceList[newValues[1].numberOfInstallment].price;
2008        }
2009      }
2010    }
2011  );
2012
2013  $scope.$watchGroup(
2014    [
2015      'signup.imagesToBeUploaded["idImagePath"]',
2016      "signup.idImagePath",
2017      'signup.imagesToBeUploaded["NPWPImagePath"]',
2018      "signup.NPWPImagePath",
2019      'signup.imagesToBeUploaded["siupCompanyImagePath"]',
2020      "signup.jobInfo.siupCompanyImagePath",
2021      'signup.imagesToBeUploaded["tdpCompanyImagePath"]',
2022      "signup.jobInfo.tdpCompanyImagePath",
2023      'signup.imagesToBeUploaded["NPWPCompanyImagePath"]',
2024      "signup.jobInfo.NPWPCompanyImagePath",
2025      'signup.imagesToBeUploaded["establishmentDeedImagePath"]',
2026      "signup.jobInfo.establishmentDeedImagePath",
2027      'signup.imagesToBeUploaded["latestEstablishmentDeedImagePath"]',
2028      "signup.jobInfo.latestEstablishmentDeedImagePath",
2029      'signup.imagesToBeUploaded["SKMenteriImagePath"]',
2030      "signup.jobInfo.SKMenteriImagePath",
2031      'signup.imagesToBeUploaded["suratDomisiliImagePath"]',
2032      "signup.jobInfo.suratDomisiliImagePath",
2033      "signup.RABImagePath",
2034      'signup.imagesToBeUploaded["NPWPImagePathCompany"]',
2035      "signup.NPWPImagePathCompany",
2036    ],
2037    function (newValues, oldValues) {
2038      if (newValues[0] !== oldValues[0] || newValues[1] !== oldValues[1]) {
2039        if (newValues[0] || newValues[1]) {
2040          vm.imagesToBeUploadedStatus["idImagePath"] = true;
2041        } else {
2042          vm.imagesToBeUploadedStatus["idImagePath"] = undefined;
2043        }
2044      }
2045
2046      if (newValues[2] !== oldValues[2] || newValues[3] !== oldValues[3]) {
2047        if (newValues[2] || newValues[3]) {
2048          vm.imagesToBeUploadedStatus["NPWPImagePath"] = true;
2049        } else {
2050          vm.imagesToBeUploadedStatus["NPWPImagePath"] = undefined;
2051        }
2052      }
2053
2054      if (newValues[4] !== oldValues[4] || newValues[5] !== oldValues[5]) {
2055        if (newValues[4] || newValues[5]) {
2056          vm.imagesToBeUploadedStatus["siupCompanyImagePath"] = true;
2057        } else {
2058          vm.imagesToBeUploadedStatus["siupCompanyImagePath"] = undefined;
2059        }
2060      }
2061
2062      if (newValues[6] !== oldValues[6] || newValues[7] !== oldValues[7]) {
2063        if (newValues[6] || newValues[7]) {
2064          vm.imagesToBeUploadedStatus["tdpCompanyImagePath"] = true;
2065        } else {
2066          vm.imagesToBeUploadedStatus["tdpCompanyImagePath"] = undefined;
2067        }
2068      }
2069
2070      if (newValues[8] !== oldValues[8] || newValues[9] !== oldValues[9]) {
2071        if (newValues[8] || newValues[9]) {
2072          vm.imagesToBeUploadedStatus["NPWPCompanyImagePath"] = true;
2073        } else {
2074          vm.imagesToBeUploadedStatus["NPWPCompanyImagePath"] = undefined;
2075        }
2076      }
2077
2078      if (newValues[10] !== oldValues[10] || newValues[11] !== oldValues[11]) {
2079        if (newValues[10] || newValues[11]) {
2080          vm.imagesToBeUploadedStatus["establishmentDeedImagePath"] = true;
2081        } else {
2082          vm.imagesToBeUploadedStatus["establishmentDeedImagePath"] = undefined;
2083        }
2084      }
2085
2086      if (newValues[12] !== oldValues[12] || newValues[13] !== oldValues[13]) {
2087        if (newValues[12] || newValues[13]) {
2088          vm.imagesToBeUploadedStatus["latestEstablishmentDeedImagePath"] = true;
2089        } else {
2090          vm.imagesToBeUploadedStatus["latestEstablishmentDeedImagePath"] = undefined;
2091        }
2092      }
2093
2094      if (newValues[14] !== oldValues[14] || newValues[15] !== oldValues[15]) {
2095        if (newValues[14] || newValues[15]) {
2096          vm.imagesToBeUploadedStatus["SKMenteriImagePath"] = true;
2097        } else {
2098          vm.imagesToBeUploadedStatus["SKMenteriImagePath"] = undefined;
2099        }
2100      }
2101
2102      if (newValues[16] !== oldValues[16] || newValues[17] !== oldValues[17]) {
2103        if (newValues[16] || newValues[17]) {
2104          vm.imagesToBeUploadedStatus["suratDomisiliImagePath"] = true;
2105        } else {
2106          vm.imagesToBeUploadedStatus["suratDomisiliImagePath"] = undefined;
2107        }
2108      }
2109
2110      if (newValues[17] !== oldValues[17] || newValues[18] !== oldValues[18]) {
2111        if (newValues[17] || newValues[18]) {
2112          vm.imagesToBeUploadedStatus["RABImagePath"] = true;
2113        } else {
2114          vm.imagesToBeUploadedStatus["RABImagePath"] = undefined;
2115        }
2116      }
2117
2118      if (newValues[18] !== oldValues[18] || newValues[19] !== oldValues[19]) {
2119        if (newValues[18] || newValues[19]) {
2120          vm.imagesToBeUploadedStatus["NPWPImagePathCompany"] = true;
2121        } else {
2122          vm.imagesToBeUploadedStatus["NPWPImagePathCompany"] = undefined;
2123        }
2124      }
2125    }
2126  );
2127
2128  $scope.$watch("signup.monthlyIncomeText", function (newValue) {
2129    if (newValue) {
2130      var tempTextArray = newValue.split(",");
2131      var tempText = tempTextArray.join("");
2132
2133      vm.questionnaire.monthlyIncome = Number(tempText);
2134    }
2135  });
2136
2137  $scope.$watch("signup.propertyPriceText", function (newValue) {
2138    if (newValue) {
2139      let tempTextArray = newValue.split(",");
2140      let tempText = tempTextArray.join("");
2141      vm.questionnaire.graStrata.property.price = Number(tempText);
2142    }
2143  });
2144
2145  $scope.$watch("signup.buildingSizeText", function (newValue) {
2146    if (newValue) {
2147      let tempTextArray = newValue.split(",");
2148      let tempText = tempTextArray.join("");
2149      vm.questionnaire.graStrata.property.buildingSize = Number(tempText);
2150    }
2151  });
2152
2153  $scope.$watch("signup.landSizeText", function (newValue) {
2154    if (newValue) {
2155      let tempTextArray = newValue.split(",");
2156      let tempText = tempTextArray.join("");
2157      vm.questionnaire.graStrata.property.landSize = Number(tempText);
2158    }
2159  });
2160
2161  $scope.$watch("signup.loanAmountText", function (newValue) {
2162    if (newValue) {
2163      let tempTextArray = newValue.split(",");
2164      let tempText = tempTextArray.join("");
2165      vm.questionnaire.graStrata.amount = Number(tempText);
2166    }
2167  });
2168
2169  $scope.$watch("signup.questionnaire.rollingTenorSelected", function (newValue) {
2170    if (newValue) {
2171      vm.questionnaire.graStrata.rollingTenor = newValue.value;
2172    }
2173  });
2174
2175  $scope.$watch("signup.questionnaire.locationAccessSelected", function (newValue) {
2176    if (newValue) {
2177      vm.questionnaire.graStrata.property.locationAccess = newValue.value;
2178    }
2179  });
2180
2181  $scope.$watch("signup.lenderPreferenceAmountText", function (newValue) {
2182    if (newValue) {
2183      var tempTextArray = newValue.split(",");
2184      var tempText = tempTextArray.join("");
2185
2186      if (!$scope.user.lenderPreference) {
2187        $scope.user.lenderPreference = {};
2188      }
2189      $scope.user.lenderPreference.amount = Number(tempText);
2190    }
2191  });
2192
2193  $scope.$watch("signup.provinceChosen", function (newValue, oldValue) {
2194    if (newValue) {
2195      $scope.loading = true;
2196
2197      ServerService.GetCitiesByProvince(currentUser, newValue.name, function (response) {
2198        if (response) {
2199          $scope.user.province = newValue.name;
2200          vm.cities = response.data;
2201          $scope.loading = false;
2202        } else {
2203          // console.log("err get city");
2204          $scope.loading = false;
2205        }
2206      });
2207    }
2208  });
2209
2210  $scope.$watch("signup.genderChosen", function (newValue, oldValue) {
2211    if (newValue) {
2212      $scope.loading = true;
2213      $scope.user.gender = newValue.value;
2214      $scope.loading = false;
2215    }
2216  });
2217
2218  $scope.$watch("signup.cityChosen", function (newValue, oldValue) {
2219    if (newValue != oldValue) {
2220      $scope.loading = true;
2221
2222      ServerService.GetKecamatanByCity(currentUser, newValue._id, function (response) {
2223        if (response) {
2224          $scope.user.city = newValue.name;
2225          vm.kecamatans = response.data;
2226          $scope.loading = false;
2227        } else {
2228          console.log("err get city");
2229          $scope.loading = false;
2230        }
2231      });
2232    }
2233  });
2234
2235  $scope.$watch("signup.kecamatanChosen", function (newValue, oldValue) {
2236    if (newValue != oldValue) {
2237      $scope.loading = true;
2238
2239      ServerService.GetKelurahanByKecamatan(currentUser, newValue._id, function (response) {
2240        if (response) {
2241          $scope.user.kecamatan = newValue.name;
2242          vm.kelurahans = response.data;
2243          $scope.loading = false;
2244        } else {
2245          // console.log("err get city");
2246          $scope.loading = false;
2247        }
2248      });
2249    }
2250  });
2251
2252  $scope.$watch("signup.kelurahanChosen", function (newValue, oldValue) {
2253    if (newValue) {
2254      $scope.loading = true;
2255
2256      ServerService.GetPostalCodeByKelurahan(currentUser, newValue._id, function (response) {
2257        if (response) {
2258          $scope.user.kelurahan = newValue.name;
2259          $scope.user.postalCode = response.data.postalCode;
2260          $scope.loading = false;
2261        } else {
2262          // console.log("err get city");
2263          $scope.loading = false;
2264        }
2265      });
2266    }
2267  });
2268
2269  $scope.$watch("signup.provinceCompanyChosen", function (newValue, oldValue) {
2270    if (newValue) {
2271      $scope.loading = true;
2272
2273      ServerService.GetCitiesByProvince(currentUser, newValue.name, function (response) {
2274        if (response) {
2275          $scope.user.company.province = newValue.name;
2276          vm.citiesCompany = response.data;
2277          $scope.loading = false;
2278        } else {
2279          // console.log("err get city");
2280          $scope.loading = false;
2281        }
2282      });
2283    }
2284  });
2285
2286  $scope.$watch("signup.cityCompanyChosen", function (newValue, oldValue) {
2287    if (newValue != oldValue) {
2288      $scope.loading = true;
2289
2290      ServerService.GetKecamatanByCity(currentUser, newValue._id, function (response) {
2291        if (response) {
2292          $scope.user.company.city = newValue.name;
2293          vm.kecamatansCompany = response.data;
2294          $scope.loading = false;
2295        } else {
2296          console.log("err get city");
2297          $scope.loading = false;
2298        }
2299      });
2300    }
2301  });
2302
2303  $scope.$watch("signup.kecamatanCompanyChosen", function (newValue, oldValue) {
2304    if (newValue != oldValue) {
2305      $scope.loading = true;
2306
2307      ServerService.GetKelurahanByKecamatan(currentUser, newValue._id, function (response) {
2308        if (response) {
2309          $scope.user.company.kecamatan = newValue.name;
2310          vm.kelurahansCompany = response.data;
2311          $scope.loading = false;
2312        } else {
2313          // console.log("err get city");
2314          $scope.loading = false;
2315        }
2316      });
2317    }
2318  });
2319
2320  $scope.$watch("signup.kelurahanCompanyChosen", function (newValue, oldValue) {
2321    if (newValue) {
2322      $scope.loading = true;
2323
2324      ServerService.GetPostalCodeByKelurahan(currentUser, newValue._id, function (response) {
2325        if (response) {
2326          $scope.user.company.kelurahan = newValue.name;
2327          $scope.user.company.postalCode = response.data.postalCode;
2328          $scope.loading = false;
2329        } else {
2330          // console.log("err get city");
2331          $scope.loading = false;
2332        }
2333      });
2334    }
2335  });
2336
2337  $scope.$watch("signup.corespondenProvinceChosen", function (newValue, oldValue) {
2338    if (newValue) {
2339      $scope.loading = true;
2340
2341      ServerService.GetCitiesByProvince(currentUser, newValue.name, function (response) {
2342        if (response) {
2343          $scope.user.corespondenProvinceChosen = newValue.name;
2344          vm.corespondenCities = response.data;
2345          $scope.loading = false;
2346        }
2347        $scope.loading = false;
2348      });
2349    }
2350  });
2351
2352  $scope.$watch("signup.corespondenCityChosen", function (newValue, oldValue) {
2353    if (newValue != oldValue) {
2354      $scope.loading = true;
2355
2356      ServerService.GetKecamatanByCity(currentUser, newValue._id, function (response) {
2357        if (response) {
2358          $scope.user.corespondenCityChosen = newValue.name;
2359          vm.corespondenKecamatans = response.data;
2360          $scope.loading = false;
2361        }
2362        $scope.loading = false;
2363      });
2364    }
2365  });
2366
2367  $scope.$watch("signup.corespondenKecamatanChosen", function (newValue, oldValue) {
2368    if (newValue != oldValue) {
2369      $scope.loading = true;
2370
2371      ServerService.GetKelurahanByKecamatan(currentUser, newValue._id, function (response) {
2372        if (response) {
2373          $scope.user.corespondenKecamatanChosen = newValue.name;
2374          vm.corespondenKelurahans = response.data;
2375          $scope.loading = false;
2376        }
2377        $scope.loading = false;
2378      });
2379    }
2380  });
2381
2382  $scope.$watch("signup.corespondenKelurahanChosen", function (newValue, oldValue) {
2383    if (newValue) {
2384      $scope.loading = true;
2385
2386      ServerService.GetPostalCodeByKelurahan(currentUser, newValue._id, function (response) {
2387        if (response) {
2388          $scope.user.corespondenKelurahanChosen = newValue.name;
2389          $scope.user.corespondenPostalCode = response.data.postalCode;
2390          $scope.loading = false;
2391        }
2392        $scope.loading = false;
2393      });
2394    }
2395  });
2396
2397  $scope.$watch("signup.selectedTenor", function (newValue) {
2398    if (newValue) {
2399      let tenor = newValue.value;
2400      if ($scope.type == "GraSewa") {
2401        vm.questionnaire.graSewa.tenor = tenor;
2402      }
2403    }
2404  });
2405
2406  $scope.$watch("signup.nationalitySelected", function (newValue) {
2407    if (newValue) {
2408      vm.questionnaire.nationality = newValue.name;
2409      // console.log('nationality',vm.questionnaire.nationality )
2410    }
2411  });
2412
2413  $scope.$watch("signup.workSinceSelected", function (newValue) {
2414    if (newValue) {
2415      vm.questionnaire.workSince = newValue.name;
2416    }
2417  });
2418
2419  $scope.$watch("signup.dobYearSelected", function (newValue) {
2420    if (newValue) {
2421      let dateOfBirth = stringToDate(vm.dobYearSelected, vm.dobMonthSelected, vm.dobDDSelected);
2422      if (dateOfBirth) {
2423        vm.questionnaire.dateOfBirth = dateOfBirth;
2424      }
2425    }
2426  });
2427
2428  $scope.$watch("signup.dobMonthSelected", function (newValue) {
2429    if (newValue) {
2430      let dateOfBirth = stringToDate(vm.dobYearSelected, vm.dobMonthSelected, vm.dobDDSelected);
2431      if (dateOfBirth) {
2432        vm.questionnaire.dateOfBirth = dateOfBirth;
2433      }
2434    }
2435  });
2436
2437  $scope.$watch("signup.dobDDSelected", function (newValue) {
2438    if (newValue) {
2439      let dateOfBirth = stringToDate(vm.dobYearSelected, vm.dobMonthSelected, vm.dobDDSelected);
2440      if (dateOfBirth) {
2441        vm.questionnaire.dateOfBirth = dateOfBirth;
2442      }
2443    }
2444  });
2445
2446  function stringToDate(year, month, dd) {
2447    if (year && month && dd) {
2448      return moment(year.name + "" + month.name + "" + dd.name, "YYYYMMDD");
2449    }
2450    return null;
2451  }
2452
2453  $scope.$watch("signup.rentAmountText", function (newValue) {
2454    if (newValue) {
2455      // console.log(newValue);
2456      let { totalAmount } = getGraSewaTotalAmount();
2457      vm.graSewaTotalAmount = totalAmount;
2458    }
2459  });
2460
2461  $scope.$watch("signup.renovationAmountText", function (newValue) {
2462    if (newValue) {
2463      // console.log(newValue);
2464      let { totalAmount } = getGraSewaTotalAmount();
2465      vm.graSewaTotalAmount = totalAmount;
2466    }
2467  });
2468
2469  // Grakarya
2470
2471  $scope.email = $location.search().email;
2472  $scope.scoringId = $location.search().scoringID;
2473  $scope.first = $location.search().first;
2474  $scope.last = $location.search().last;
2475  $scope.stepGraKarya = 1;
2476
2477  $scope.graKaryaForm = {
2478    companyName: $scope.first ? `${$scope.first} ${$scope.last}` : "",
2479    typeOfBusiness: "",
2480    fieldOfBusiness: "",
2481    emailPIC: $scope.email ? $scope.email : "",
2482    phoneNumberPIC: null,
2483    password: "",
2484    confirmPassword: "",
2485    nama_perwakilan_direksi: null,
2486    jabatan_perwakilan_direksi: "",
2487    email_perwakilan_direksi: "",
2488    nohp_perwakilan_direksi: null,
2489    scoringId: $scope.scoringId,
2490  };
2491
2492  $scope.validation = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$/;
2493
2494  $scope.nextStepGraKarya = () => {
2495    let allowToNext = true;
2496    if (
2497      $scope.graKaryaForm.password !== $scope.graKaryaForm.confirmPassword ||
2498      !$scope.validation.test($scope.graKaryaForm.password)
2499    ) {
2500      SweetAlert.swal($scope.textContent['swal']['warning']['item-1']['title'], $scope.textContent['swal']['warning']['item-1']['text'], "warning");
2501      allowToNext = false;
2502    }
2503
2504    if ($scope.nibFile && !$scope.files.nibImagePath) {
2505      SweetAlert.swal($scope.textContent['swal']['warning']['item-2']['title'], $scope.textContent['swal']['warning']['item-2']['text'], "warning");
2506      allowToNext = false;
2507      console.log("here 1");
2508    }
2509
2510    if (!$scope.nibFile) {
2511      if (!$scope.files.tdpImagePath || !$scope.files.siupImagePath) {
2512        SweetAlert.swal($scope.textContent['swal']['warning']['item-2']['title'], $scope.textContent['swal']['warning']['item-2']['text'], "warning");
2513        allowToNext = false;
2514        console.log("here 2");
2515      }
2516    }
2517
2518    if (!$scope.graKaryaForm.emailPIC) {
2519      SweetAlert.swal($scope.textContent['swal']['warning']['item-3']['title'], $scope.textContent['swal']['warning']['item-3']['text'], "warning");
2520      allowToNext = false;
2521    }
2522
2523    if (
2524      !$scope.files.NPWPImagePath ||
2525      !$scope.files.establishmentDeedImagePath ||
2526      !$scope.files.SKestablishmentImagePath ||
2527      !$scope.graKaryaForm.companyName ||
2528      !$scope.graKaryaForm.typeOfBusiness ||
2529      !$scope.graKaryaForm.fieldOfBusiness ||
2530      !$scope.graKaryaForm.phoneNumberPIC
2531    ) {
2532      SweetAlert.swal($scope.textContent['swal']['warning']['item-2']['title'], $scope.textContent['swal']['warning']['item-2']['text'], "warning");
2533      allowToNext = false;
2534    }
2535
2536    if (allowToNext) {
2537      window.scrollTo(0, 0);
2538      $scope.stepGraKarya = $scope.stepGraKarya + 1;
2539    }
2540  };
2541
2542  $scope.prevStepGraKarya = () => {
2543    window.scrollTo(0, 0);
2544    $scope.stepGraKarya = $scope.stepGraKarya - 1;
2545  };
2546
2547  $scope.files = {};
2548
2549  $scope.nibFile = true;
2550
2551  if ($state.params.scoringID) {
2552    ServerService.GetLoanByScoringId($state.params.scoringID)
2553      .then((res) => {
2554        if (res && res.data.status === "Success" && res.data.data) {
2555          // console.log(res.data,"<<< res");
2556          const data = res.data.data;
2557          $scope.graKaryaForm = {
2558            companyName: data.company.name,
2559            typeOfBusiness: { name: data.company.companyType },
2560            fieldOfBusiness: "",
2561            emailPIC: data.borrower.email,
2562            phoneNumberPIC: data.borrower.mobileNumber ? data.borrower.mobileNumber : data.borrower.phoneNumber,
2563            password: "",
2564            confirmPassword: "",
2565            nama_perwakilan_direksi: data.borrower.managements[0].name,
2566            jabatan_perwakilan_direksi: data.borrower.managements[0].jabatan_perwakilan_direksi,
2567            email_perwakilan_direksi: data.borrower.managements[0].email,
2568            nohp_perwakilan_direksi: data.borrower.managements[0].mobileNumber,
2569          };
2570
2571          if (data.borrower) {
2572            if (data.borrower.gender) $scope.graKaryaForm["gender"] = data.borrower.gender;
2573            if (data.borrower.dateOfBirth) $scope.graKaryaForm["dateOfBirth"] = data.borrower.dateOfBirth;
2574            if (data.borrower.placeOfBirth) $scope.graKaryaForm["placeOfBirth"] = data.borrower.placeOfBirth;
2575            if (data.borrower.address) $scope.graKaryaForm["address"] = data.borrower.address;
2576            if (data.borrower.province) $scope.graKaryaForm["province"] = data.borrower.province;
2577            if (data.borrower.city) $scope.graKaryaForm["city"] = data.borrower.city;
2578            if (data.borrower.kecamatan) $scope.graKaryaForm["kecamatan"] = data.borrower.kecamatan;
2579            if (data.borrower.kelurahan) $scope.graKaryaForm["kelurahan"] = data.borrower.kelurahan;
2580            if (data.borrower.postalCode) $scope.graKaryaForm["postalCode"] = data.borrower.postalCode;
2581            if (data.borrower.idNumber) $scope.graKaryaForm["idNumber"] = data.borrower.idNumber;
2582            if (data.borrower.NPWPNumber) $scope.graKaryaForm["NPWPNumber"] = data.borrower.NPWPNumber;
2583            if (data.borrower.SPKNumber) $scope.graKaryaForm["SPKNumber"] = data.borrower.SPKNumber;
2584            if (data.borrower.motherMaidenName) $scope.graKaryaForm["motherMaidenName"] = data.borrower.motherMaidenName;
2585            if (data.borrower.lastEducation) $scope.graKaryaForm["lastEducation"] = data.borrower.lastEducation;
2586            if (data.borrower.finances) $scope.graKaryaForm["finances"] = data.borrower.finances;
2587            if (data.borrower.managements) $scope.graKaryaForm["managements"] = data.borrower.managements;
2588          }
2589
2590          if (data.pefindo) {
2591            $scope.graKaryaForm["pefindo"] = data.pefindo;
2592          }
2593
2594          if (data.borrower && data.borrower.NPWPImagePath) {
2595            $scope.files["NPWPImagePath"] = {
2596              name: "Sudah diupload",
2597              path: data.borrower.NPWPImagePath,
2598            };
2599            $scope.graKaryaForm["NPWPImagePath"] = data.borrower.NPWPImagePath;
2600          }
2601
2602          if (data.borrower && data.borrower.jobInfo.nibImagePath) {
2603            $scope.files["nibImagePath"] = {
2604              name: "Sudah diupload",
2605              path: data.borrower.jobInfo.nibImagePath,
2606            };
2607            $scope.graKaryaForm["nibImagePath"] = data.borrower.jobInfo.nibImagePath;
2608
2609            $scope.nibFile = true;
2610          }
2611
2612          if (data.borrower && data.borrower.jobInfo.siupImagePath) {
2613            $scope.files["siupImagePath"] = {
2614              name: "Sudah diupload",
2615              path: data.borrower.jobInfo.siupImagePath,
2616            };
2617            $scope.graKaryaForm["siupImagePath"] = data.borrower.jobInfo.siupImagePath;
2618
2619            $scope.nibFile = false;
2620          }
2621
2622          if (data.borrower && data.borrower.jobInfo.tdpImagePath) {
2623            $scope.files["tdpImagePath"] = {
2624              name: "Sudah diupload",
2625              path: data.borrower.jobInfo.tdpImagePath,
2626            };
2627            $scope.graKaryaForm["tdpImagePath"] = data.borrower.jobInfo.tdpImagePath;
2628          }
2629
2630          if (data.borrower && data.borrower.jobInfo.deedOfIncorporationImagePath) {
2631            $scope.files["establishmentDeedImagePath"] = {
2632              name: "Sudah diupload",
2633              path: data.borrower.jobInfo.deedOfIncorporationImagePath,
2634            };
2635            $scope.graKaryaForm["deedOfIncorporationImagePath"] = data.borrower.jobInfo.deedOfIncorporationImagePath;
2636          }
2637
2638          if (data.SKestablishmentImagePath) {
2639            $scope.files["SKestablishmentImagePath"] = {
2640              name: "Sudah diupload",
2641              path: data.SKestablishmentImagePath,
2642            };
2643            $scope.graKaryaForm["SKestablishmentImagePath"] = data.SKestablishmentImagePath;
2644          }
2645
2646          if (data.borrower && data.borrower.company.managements[0].idImagePath) {
2647            $scope.files["idImagePath"] = {
2648              name: "Sudah diupload",
2649              path: data.borrower.company.managements[0].idImagePath,
2650            };
2651            $scope.graKaryaForm.managementsIdImagePath = data.borrower.company.managements[0].idImagePath;
2652          }
2653
2654          if (data.borrower && data.borrower.company.managements[0].NPWPImagePath) {
2655            $scope.files["managementNPWPImagePath"] = {
2656              name: "Sudah diupload",
2657              path: data.borrower.company.managements[0].NPWPImagePath,
2658            };
2659            $scope.graKaryaForm.managementsNPWPImagePath = data.borrower.company.managements[0].NPWPImagePath;
2660          }
2661        }
2662      })
2663      .catch((err) => console.log(err, "<<< message \n"));
2664  }
2665
2666  $scope.setnibFileCond = () => {
2667    $scope.nibFile = !$scope.nibFile;
2668  };
2669
2670  $scope.typeOfBusiness = [];
2671
2672  $scope.selectFile = ($files, type) => {
2673    $scope.files[type] = $files[0];
2674  };
2675
2676  $scope.submitGrakarya = async () => {
2677    $scope.loading = true;
2678    try {
2679      if ($scope.nibFile && !$scope.files.nibImagePath)
2680        throw {
2681          title: $scope.textContent['swal']['warning']['item-2']['title'],
2682          message: $scope.textContent['swal']['warning']['item-2']['text'],
2683          status: "warning",
2684        };
2685
2686      if (!$scope.nibFile && (!$scope.files.tdpImagePath || !$scope.files.siupImagePath))
2687        throw {
2688          title: $scope.textContent['swal']['warning']['item-2']['title'],
2689          message: $scope.textContent['swal']['warning']['item-2']['text'],
2690          status: "warning",
2691        };
2692
2693      if (
2694        !$scope.files.NPWPImagePath ||
2695        !$scope.files.establishmentDeedImagePath ||
2696        !$scope.files.SKestablishmentImagePath ||
2697        !$scope.files.idImagePath ||
2698        !$scope.files.managementNPWPImagePath ||
2699        !$scope.graKaryaForm.companyName ||
2700        !$scope.graKaryaForm.typeOfBusiness ||
2701        !$scope.graKaryaForm.fieldOfBusiness ||
2702        !$scope.graKaryaForm.emailPIC ||
2703        !$scope.graKaryaForm.phoneNumberPIC ||
2704        !$scope.graKaryaForm.nama_perwakilan_direksi ||
2705        !$scope.graKaryaForm.jabatan_perwakilan_direksi ||
2706        !$scope.graKaryaForm.email_perwakilan_direksi ||
2707        !$scope.graKaryaForm.nohp_perwakilan_direksi
2708      )
2709        // throw { message: $scope.textContent['swal']['warning']['item-2']['title'] };
2710        throw {
2711          title: $scope.textContent['swal']['warning']['item-2']['title'],
2712          message: $scope.textContent['swal']['warning']['item-2']['text'],
2713          status: "warning",
2714        };
2715
2716      $scope.loading = true;
2717      $scope.graKaryaForm.isTnCAgree = true;
2718      $scope.graKaryaForm.origin = "browser";
2719      $scope.graKaryaForm.typeOfBusiness = $scope.graKaryaForm.typeOfBusiness.name;
2720      $scope.graKaryaForm.fieldOfBusiness = $scope.graKaryaForm.fieldOfBusiness.value;
2721      $scope.graKaryaForm.sectorEconomic = $scope.graKaryaForm.sectorEconomic ? $scope.graKaryaForm.sectorEconomic.value : "009000"
2722      const register = await ServerService.SignUpGrakarya($scope.graKaryaForm);
2723      if (!register)
2724        throw {
2725          title: $scope.textContent['swal']['error']['item-1']['title'],
2726          message: $scope.textContent['swal']['error']['item-1']['text'],
2727          status: "error",
2728        };
2729
2730      if (register.data.status != "Success")
2731        throw {
2732          title: `Response server ${register.data.status}`,
2733          message: `Err message: ${register.data.message || "Gagal registrasi"}`,
2734          status: "error",
2735        };
2736
2737      if (register.data) {
2738        SettingsService.SetCredentials(register.data);
2739        let getCurrentUser = SettingsService.GetCredentials();
2740        let signedUpUser = register.data.data.user;
2741        $scope.newUser = signedUpUser;
2742        if (!$scope.newUser.company.managements[0]) {
2743          $scope.newUser.company.managements = [{}]
2744        }
2745        let getResponseUpload;
2746
2747        const uploadFileImage = await Object.keys($scope.files).map(async (key) => {
2748          const params = {
2749            file: $scope.files[key],
2750            path: folder + "user/" + $scope.newUser._id,
2751          };
2752          let responUpload;
2753          if ($scope.files[key].size) {
2754            responUpload = await ServerService.UploadFileV2(getCurrentUser, params);
2755          } else {
2756            if (key === "NPWPImagePath") {
2757              $scope.newUser.jobInfo.NPWPImagePath = $scope.files[key].path;
2758              $scope.newUser.company.NPWPImagePath = $scope.files[key].path;
2759            }
2760            if (key === "establishmentDeedImagePath") {
2761              $scope.newUser.company.deedOfIncorporationImagePath = $scope.files[key].path;
2762              $scope.newUser.jobInfo.deedOfIncorporationImagePath = $scope.files[key].path;
2763            }
2764            if (key === "SKestablishmentImagePath") {
2765              $scope.newUser.company.SKestablishmentImagePath = $scope.files[key].path;
2766              $scope.newUser.jobInfo.SKestablishmentImagePath = $scope.files[key].path;
2767            }
2768            if (key === "businessChangeDeedImagePath") {
2769              $scope.newUser.companyo.businessChangeDeedImagePath = $scope.files[key].path;
2770              $scope.newUser.jobInfo.businessChangeDeedImagePath = $scope.files[key].path;
2771            }
2772            if (key === "SKbusinessChangeDeedImagePath") {
2773              $scope.newUser.company.SKbusinessChangeDeedImagePath = $scope.files[key].path;
2774              $scope.newUser.jobInfo.SKbusinessChangeDeedImagePath = $scope.files[key].path;
2775            }
2776            if (key === "siupImagePath") {
2777              $scope.newUser.company.siupImagePath = $scope.files[key].path;
2778              $scope.newUser.jobInfo.siupImagePath = $scope.files[key].path;
2779            }
2780            if (key === "tdpImagePath") {
2781              $scope.newUser.company.tdpImagePath = $scope.files[key].path;
2782              $scope.newUser.jobInfo.tdpImagePath = $scope.files[key].path;
2783            }
2784            if (key === "idImagePath") {
2785              $scope.newUser.company.managements[0].idImagePath = $scope.files[key].path;
2786              $scope.newUser.idImagePath = $scope.files[key].path;
2787            }
2788            if (key === "managementNPWPImagePath") {
2789              $scope.newUser.company.managements[0].NPWPImagePath = $scope.files[key].path;
2790            }
2791            if (key === "nibImagePath") {
2792              $scope.newUser.company.nibImagePath = $scope.files[key].path;
2793              $scope.newUser.jobInfo.nibImagePath = $scope.files[key].path;
2794            }
2795            if (key === "RABImagePath") {
2796              $scope.newUser.RABImagePath = $scope.files[key].path;
2797              $scope.newUser.company.RABImagePath = $scope.files[key].path;
2798            }
2799          }
2800
2801          if (responUpload && responUpload.data.res && responUpload.data.res.status == 200) {
2802            if (key === "NPWPImagePath") {
2803              $scope.newUser.company.NPWPImagePath = responUpload.data.imagePath;
2804              $scope.newUser.jobInfo.NPWPImagePath = responUpload.data.imagePath;
2805            }
2806            if (key === "establishmentDeedImagePath") {
2807              $scope.newUser.company.establishmentDeedImagePath = responUpload.data.imagePath;
2808              $scope.newUser.jobInfo.deedOfIncorporationImagePath = responUpload.data.imagePath;
2809            }
2810            if (key === "SKestablishmentImagePath") {
2811              $scope.newUser.company.SKestablishmentImagePath = responUpload.data.imagePath;
2812              $scope.newUser.jobInfo.SKestablishmentImagePath = responUpload.data.imagePath;
2813            }
2814            if (key === "businessChangeDeedImagePath") {
2815              $scope.newUser.company.businessChangeDeedImagePath = responUpload.data.imagePath;
2816              $scope.newUser.jobInfo.businessChangeDeedImagePath = responUpload.data.imagePath;
2817            }
2818            if (key === "SKbusinessChangeDeedImagePath") {
2819              $scope.newUser.company.SKbusinessChangeDeedImagePath = responUpload.data.imagePath;
2820              $scope.newUser.jobInfo.SKbusinessChangeDeedImagePath = responUpload.data.imagePath;
2821            }
2822            if (key === "siupImagePath") {
2823              $scope.newUser.company.siupImagePath = responUpload.data.imagePath;
2824              $scope.newUser.jobInfo.siupImagePath = responUpload.data.imagePath;
2825            }
2826            if (key === "tdpImagePath") {
2827              $scope.newUser.company.tdpImagePath = responUpload.data.imagePath;
2828              $scope.newUser.jobInfo.tdpImagePath = responUpload.data.imagePath;
2829            }
2830            if (key === "idImagePath") {
2831              $scope.newUser.company.managements[0].idImagePath = responUpload.data.imagePath;
2832              $scope.newUser.idImagePath = responUpload.data.imagePath;
2833            }
2834            if (key === "managementNPWPImagePath") {
2835              $scope.newUser.company.managements[0].NPWPImagePath = responUpload.data.imagePath;
2836            }
2837            if (key === "nibImagePath") {
2838              $scope.newUser.company.nibImagePath = responUpload.data.imagePath;
2839              $scope.newUser.jobInfo.nibImagePath = responUpload.data.imagePath;
2840            }
2841            if (key === "RABImagePath") {
2842              $scope.newUser.RABImagePath = responUpload.data.imagePath;
2843              $scope.newUser.company.RABImagePath = responUpload.data.imagePath;
2844            }
2845          }
2846          getResponseUpload = responUpload;
2847        });
2848
2849        await Promise.all(uploadFileImage);
2850
2851        if (getResponseUpload.data && getResponseUpload.data.res.status != 200)
2852          throw {
2853            title: "Gagal upload file",
2854            message: `Response dari server: ${getResponseUpload.data.res.message || "Mohon di cek kembali data yang anda upload"
2855              }`,
2856            status: "error",
2857          };
2858
2859        const updateUser = await ServerService.UpdateUserV2(getCurrentUser, $scope.newUser);
2860
2861        if (updateUser.data && updateUser.data.status != "Success")
2862          throw {
2863            title: "Gagal update data",
2864            message: `Response dari server: ${getResponseUpload.data.res.message}`,
2865            status: "error",
2866          };
2867        let destinationEmails = [];
2868        destinationEmails.push($scope.newUser.email);
2869
2870        let emailData = {};
2871        emailData.email = $scope.newUser.email;
2872        emailData.role = $scope.newUser.role;
2873
2874        emailData.name = {
2875          first: $scope.graKaryaForm.typeOfBusiness,
2876          last: $scope.graKaryaForm.companyName,
2877        };
2878
2879        ServerService.SendAccountVerificationEmailV2(getCurrentUser, emailData, $scope.newUser._id, (res) => {
2880          if ((res, res.statusCode === 200)) {
2881            ServerService.SubscribeNewsletter(signedUpUser, (res) => {
2882              if (res && res.status != "Success")
2883                throw {
2884                  title: "Gagal mengirim verifikasi email",
2885                  message: `Response dari server: ${res.message || "Mohon periksa kembali data anda"}`,
2886                  status: "error",
2887                };
2888
2889              SweetAlert.swal($scope.textContent['swal']['success']['item-7']['title'], $scope.textContent['swal']['success']['item-7']['text'], "success");
2890              $state.go("applyLoan");
2891              $scope.loading = false;
2892            });
2893          } else
2894            throw {
2895              title: "Gagal mengirim verifikasi email",
2896              message: `Response dari server: ${res.message || "Mohon periksa kembali data anda"}`,
2897              status: "error",
2898            };
2899        });
2900      }
2901    } catch (error) {
2902      SweetAlert.swal(
2903        error.title || $scope.textContent['swal']['error']['item-1']['title'],
2904        error.message || $scope.textContent['swal']['error']['item-1']['text'],
2905        error.status || "error"
2906      );
2907      $scope.loading = false;
2908    }
2909  };
2910
2911  //---------------------------------------------------------------------------------------------------
2912  // [END] WATCHER / EVENT LISTENER
2913  //---------------------------------------------------------------------------------------------------
2914
2915  //---------------------------------------------------------------------------------------------------
2916  // [START] COLLECTION PRIVATE FUNCTION
2917  //---------------------------------------------------------------------------------------------------
2918
2919  // note :
2920  // use function functionName for private access, only can call by controller
2921  // use vm.functionName for public access in controller, for example invoke ctrlName.functionName
2922  // user $scope.functionName for public access in controller without prefix controller name direct call function, for example invoke functionName
2923
2924  // get amount total graSewa
2925  function getGraSewaTotalAmount() {
2926    let renovationAmount = 0;
2927    let rentAmount = 0;
2928    if (vm.grasewaTypeSelected.typeName == "Sewa") {
2929      let tempAnnualRentTextArray = vm.rentAmountText.split(",");
2930      rentAmount = Number(tempAnnualRentTextArray.join(""));
2931    } else if (vm.grasewaTypeSelected.typeName == "Renovasi") {
2932      let renovTextArray = vm.renovationAmountText.split(",");
2933      renovationAmount = Number(renovTextArray.join(""));
2934    } else if (vm.grasewaTypeSelected.typeName == "sewaRenov") {
2935      let tempAnnualRentTextArray = vm.rentAmountText.split(",");
2936      rentAmount = Number(tempAnnualRentTextArray.join(""));
2937
2938      let renovTextArray = vm.renovationAmountText.split(",");
2939      renovationAmount = Number(renovTextArray.join(""));
2940    }
2941    let totalAmount = rentAmount + renovationAmount;
2942    return { renovationAmount, rentAmount, totalAmount };
2943  }
2944
2945  // getInterestRolling By tenor in year
2946  function getInterestRollingByYear(tenorInYears) {
2947    let pct = 0.0962;
2948    if (tenorInYears >= 10) {
2949      pct = 0.0962;
2950    }
2951    if (tenorInYears >= 15) {
2952      pct = 0.1027;
2953    }
2954    if (tenorInYears >= 20) {
2955      pct = 0.1089;
2956    }
2957    return pct;
2958  }
2959
2960  // thousand rounding
2961  function thousandRounding(value) {
2962    return Math.ceil(value / 1000) * 1000;
2963  }
2964
2965  // questionnaire.graStrata:{
2966  //   amount : Number,
2967  //   rollingTenor : Number,
2968  //   interestPctRolling : Number,
2969  //   installmentAmount : Number
2970  // }
2971
2972  // calculate graStrata installment amount
2973  // vm.questionnaire.amount
2974  // vm.questionnaire.rollingTenor
2975  function calculateGraStrataInstallmentAmount(amount, tenorInYears) {
2976    let interestPctRolling = getInterestRollingByYear(tenorInYears);
2977    let tenorRollingInMonths = tenorInYears * 12; //in months
2978    let pctRollingBorrowerByTenor = 1 + interestPctRolling * tenorInYears;
2979    let installmentAmountRolling = (amount * pctRollingBorrowerByTenor) / tenorRollingInMonths;
2980    let installmentAmountRollingRounded = thousandRounding((amount * pctRollingBorrowerByTenor) / tenorRollingInMonths);
2981    return {
2982      interestPctRolling,
2983      installmentAmountRolling,
2984      installmentAmountRollingRounded,
2985    };
2986  }
2987
2988  function calculateInstallmentAmount(amount, tenor) {
2989    let installmentAmount = 0;
2990    let amountGraDP = amount;
2991    let interestPct = vm.questionnaire.property.interestPct || vm.globalSetting.graDPInterestPct;
2992    let borrowerPrice = thousandRounding(amountGraDP * ((tenor / 12) * interestPct + 1));
2993    installmentAmount = thousandRounding(borrowerPrice / tenor);
2994    let deposit = vm.questionnaire.property.deposit ? installmentAmount : 0;
2995    let adminFee = vm.questionnaire.property.adminFee || 500000;
2996    return { interestPct, installmentAmount, deposit, adminFee, borrowerPrice };
2997  }
2998
2999  //---------------------------------------------------------------------------------------------------
3000  // [END] COLLECTION PRIVATE FUNCTION
3001  //---------------------------------------------------------------------------------------------------
3002}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.