Subversion Repositories SmartDukaan

Rev

Rev 35977 | Rev 36843 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33507 tejus.loha 1
$(document).on('click', ".onboarding-form1", function () {
33845 tejus.loha 2
    doGetAjaxRequestHandler(`${context}/loiForm`,
33507 tejus.loha 3
        function (response) {
4
            $('#' + 'main-content').html(response);
5
        });
6
});
7
 
33577 tejus.loha 8
 
36842 aman 9
// Format a Date as a local YYYY-MM-DD string (avoids UTC/IST day shift from toISOString)
10
function toLocalYMD(d) {
11
    const y = d.getFullYear();
12
    const m = String(d.getMonth() + 1).padStart(2, '0');
13
    const day = String(d.getDate()).padStart(2, '0');
14
    return `${y}-${m}-${day}`;
15
}
16
 
17
// Restrict the Acquired Date picker to the last 7 days (today and the 7 days before it).
18
// The form HTML is injected via AJAX, so set min/max lazily when the field is focused.
19
$(document).on('focus', 'input[name="acquiredDate"]', function () {
20
    const today = new Date();
21
    const minDate = new Date();
22
    minDate.setDate(today.getDate() - 7);
23
    $(this).attr('max', toLocalYMD(today));
24
    $(this).attr('min', toLocalYMD(minDate));
25
});
26
 
27
 
33577 tejus.loha 28
$(document).on('change', "#maritalStatus", function () {
29
    let maritalStatus = $(this).val();
30
    if (maritalStatus == 1) {
31
        $(".loiAnniversaryDate").removeClass('hide-model');
32
        $(".loiAnniversaryDate").addClass('show-model');
33
    } else {
34
        $(".loiAnniversaryDate").removeClass('show-model');
35
        $(".loiAnniversaryDate").addClass('hide-model');
36
    }
37
 
38
});
39
 
33578 tejus.loha 40
 
33885 tejus.loha 41
$(document).on('click', ".mk_submit_loi_form", function () {
33577 tejus.loha 42
    // Gather input values
43
    const referId = $('select[name="referId"]').val();
34107 tejus.loha 44
    const stateHead = $('select[name="stateHead"]').val();
45
    const bdm = $('select[name="bdm"]').val();
34310 tejus.loha 46
    let billingAddress = $('select[name="billingAddress"]').val();
47
    if(!billingAddress){
48
        const addrFieldData = {
49
            "bno": "",
50
            "bnm": "",
51
            "st": "",
52
            "locality": "",
53
            "loc": "",
54
            "dst": "",
55
            "pncd": "",
56
            "stcd": ""
57
        };
58
 
59
        // Dynamically create input fields
60
        let address = [];
61
        Object.keys(addrFieldData).forEach(function (field) {
62
             addrFieldData[field] = $('input[name="'+field+'"]').val();
63
        });
64
        billingAddress = JSON.stringify(addrFieldData);
65
 
66
    }
33582 tejus.loha 67
    const acquiredDate = $('input[name="acquiredDate"]').val();
33577 tejus.loha 68
    const firstName = $('input[name="firstName"]').val();
69
    const lastName = $('input[name="lastName"]').val();
70
    const mobile = $('input[name="mobile"]').val();
33780 tejus.loha 71
 
72
    // validate email pattern
73
    const emailValue = $('input[name="email"]').val();
74
    var email;
75
    if (emailValue.length > 0) {
76
        if (isValidEmail(emailValue)) {
77
            email = emailValue;
78
        } else {
79
            alert("Please check your Email Address");
80
            return;
81
        }
82
    }
33577 tejus.loha 83
    const landline = $('input[name="landline"]').val();
84
    const dob = $('input[name="dob"]').val();
33624 tejus.loha 85
    var today = new Date();
86
    var birthDate = new Date(dob);
87
    var age = today.getFullYear() - birthDate.getFullYear();
88
    var monthDiff = today.getMonth() - birthDate.getMonth();
89
 
90
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
91
        age--;
92
    }
33577 tejus.loha 93
    var maritalStatus = $('select[name="maritalStatus"]').val();
94
    const anniversaryDate = $('input[name="anniversaryDate"]').val();
95
    const panNo = $('input[name="panNo"]').val();
96
    const adharNo = $('input[name="adharNo"]').val();
97
    const gstNo = $('input[name="gstNo"]').val();
98
    const bankName = $('input[name="bankName"]').val();
99
    const ifscCode = $('input[name="ifscCode"]').val();
100
    const accountNo = $('input[name="accountNo"]').val();
101
    const businessType = $('select[name="businessType"]').val();
102
    const companyName = $('input[name="companyName"]').val();
103
    const gstPin = $('input[name="gstPin"]').val();
104
    const gstState = $('input[name="gstState"]').val();
105
    const gstCity = $('input[name="gstCity"]').val();
106
    const gstDistrict = $('input[name="gstDistrict"]').val();
107
    const agreeWalletValue = $('select[name="agreeWalletValue"]').val();
108
    const storeArea = $('input[name="storeArea"]').val();
109
    const storePotential = $('input[name="storePotential"]').val();
35971 aman 110
    let financeOptions = [];
111
    document.querySelectorAll(".finance-code-input").forEach(function (input) {
112
        var code = input.value.trim();
113
        if (code) {
114
            financeOptions.push({
115
                paymentOptionId: parseInt(input.getAttribute("data-payment-option-id")),
116
                financeCode: code
117
            });
118
        }
119
    });
33658 tejus.loha 120
    let brandCommitment = [];
121
    var brandCommitmentInputs = document.querySelectorAll(".brand-commitment");
35971 aman 122
    var hasInvalidQty = false;
33658 tejus.loha 123
    brandCommitmentInputs.forEach(function (input) {
124
        var commitmentValue = parseInt(input.value);
125
        if (!isNaN(commitmentValue)) {
35971 aman 126
            if (commitmentValue > 1000) {
127
                hasInvalidQty = true;
128
            }
33658 tejus.loha 129
            brandCommitment.push({
130
                brandName: input.getAttribute("name"),
131
                value: commitmentValue
132
            });
133
        }
134
    });
35971 aman 135
    if (hasInvalidQty) {
136
        alert("Quantity per brand cannot exceed 1000. Please enter valid quantities.");
137
        return;
138
    }
33658 tejus.loha 139
    let totalCommitment = brandCommitment.reduce((total, commitment) => total + commitment.value, 0);
35971 aman 140
    // Calculate estimated value: total qty × 20000 (average smartphone value)
141
    let estimatedValue = totalCommitment * 20000;
142
    let minCommit = estimatedValue >= (0.7 * storePotential);
143
    const lessCommitReason = $('textarea[name="lessCommitReason"]').val();
33577 tejus.loha 144
    const agreedBrandFees = $('select[name="agreedBrandFees"]').val();
33624 tejus.loha 145
    const values = agreedBrandFees.split(/[-]/); // Split the string
146
    const brandFee = parseFloat(values[1]);
33577 tejus.loha 147
    const brandFeesCollected = $('input[name="brandFeesCollected"]').val();
148
    const paymentMode = $('select[name="paymentMode"]').val();
149
    const paymentReferenceNo = $('input[name="paymentReferenceNo"]').val();
33578 tejus.loha 150
    const feeCollectingDate = $('input[name="feeCollectingDate"]').val();
33885 tejus.loha 151
    const paymentAttachment = $('input[name="paymentAttachment"]').val();
33577 tejus.loha 152
 
153
    let missingFields = [];
154
    if (!firstName) missingFields.push('First Name');
155
    if (!lastName) missingFields.push('Last Name');
156
    if (mobile.length < 10 || !mobile) {
157
        missingFields.push('Mobile number should be 10 digit');
158
    }
33658 tejus.loha 159
    if (!minCommit) {
33577 tejus.loha 160
        if (!lessCommitReason) missingFields.push('Less Commit Reason');
161
    }
162
    if (!maritalStatus) missingFields.push('Marital Status');
163
    if (maritalStatus == 1) {
164
        if (!anniversaryDate) missingFields.push('Anniversary Date');
165
    }
166
    if (!email) missingFields.push('Email');
34107 tejus.loha 167
    if (!referId) missingFields.push('Refer By');
168
    if (!bdm) missingFields.push('Bdm');
169
    if (!stateHead) missingFields.push('State head');
36842 aman 170
    if (!acquiredDate) {
171
        missingFields.push('Acquired date');
172
    } else {
173
        // Acquired date must fall within the last 7 days (not in the future, not older than 7 days back)
174
        const acq = new Date(acquiredDate);
175
        const today = new Date();
176
        today.setHours(0, 0, 0, 0);
177
        const minAllowed = new Date(today);
178
        minAllowed.setDate(today.getDate() - 7);
179
        if (acq > today || acq < minAllowed) {
180
            missingFields.push('Acquired date must be within the last 7 days');
181
        }
182
    }
33577 tejus.loha 183
    if (!dob) missingFields.push('dob(Date of Birth)');
33624 tejus.loha 184
    if (age <= 18) missingFields.push('You must be at least 18 years old to Fill LOI FORM. ');
33577 tejus.loha 185
    if (!panNo) missingFields.push('Pan Number');
186
    if (!adharNo) missingFields.push('Aadhar Number');
187
    if (!gstNo) missingFields.push('GST Number');
188
    if (!bankName) missingFields.push('Bank Name');
189
    if (!ifscCode) missingFields.push('IFSC code');
190
    if (!accountNo) missingFields.push('Account Number');
191
    if (!businessType) missingFields.push('businessType');
192
    if (!companyName) missingFields.push('Company Name');
193
    if (!agreeWalletValue) missingFields.push('Agree Wallet Value');
194
    if (!storeArea) missingFields.push('storeArea');
195
    if (!storePotential) missingFields.push('Store Potential');
196
    if (!agreedBrandFees) missingFields.push('Agreed Brand Fees');
197
    if (!brandFeesCollected) missingFields.push('Brand Fees Collected');
33845 tejus.loha 198
    if (brandFeesCollected > brandFee) missingFields.push('The collected brand fee must not exceed the agreed brand fees.');
33577 tejus.loha 199
    if (!paymentMode) missingFields.push('Payment Mode');
200
    if (!paymentReferenceNo) missingFields.push('Payment Reference No');
33578 tejus.loha 201
    if (!feeCollectingDate) missingFields.push('Fee Collecting Date');
33885 tejus.loha 202
    if (!paymentAttachment) missingFields.push('Payment screenshot ');
33577 tejus.loha 203
    if (missingFields.length > 0) {
204
        alert('The following fields are required: ' + missingFields.join(', '));
205
        return;
206
    }
207
    const loiFormData = {
208
        referId: referId,
34107 tejus.loha 209
        stateHead: stateHead,
210
        bdm: bdm,
33577 tejus.loha 211
        businessType: businessType,
33582 tejus.loha 212
        acquiredDate: acquiredDate,
33577 tejus.loha 213
        firstName: firstName,
214
        lastName: lastName,
215
        mobile: mobile,
216
        email: email,
217
        landline: landline,
218
        dob: dob,
219
        anniversaryDate: anniversaryDate,
220
        panNo: panNo,
221
        adharNo: adharNo,
222
        gstNo: gstNo,
223
        bankName: bankName,
224
        ifscCode: ifscCode,
225
        accountNo: accountNo,
226
        companyName: companyName,
227
        gstPin: gstPin,
228
        gstState: gstState,
229
        gstCity: gstCity,
230
        gstDistrict: gstDistrict,
231
        agreeWalletValue: agreeWalletValue,
232
        storeArea: storeArea,
233
        storePotential: storePotential,
35971 aman 234
        financeOptions: financeOptions,
33577 tejus.loha 235
        lessCommitReason: lessCommitReason,
236
        agreedBrandFees: agreedBrandFees,
237
        brandFeesCollected: brandFeesCollected,
238
        paymentMode: paymentMode,
239
        paymentReferenceNo: paymentReferenceNo,
33578 tejus.loha 240
        feeCollectingTimeStamp: feeCollectingDate,
33885 tejus.loha 241
        paymentAttachment: paymentAttachment,
33658 tejus.loha 242
        billingAddress: billingAddress,
243
        brandCommitment: brandCommitment
33577 tejus.loha 244
    };
33658 tejus.loha 245
 
33577 tejus.loha 246
    if (confirm("Are you sure to submit the form ?")) {
247
        doPostAjaxRequestWithJsonHandler(`${context}/submitLoiForm`, JSON.stringify(loiFormData), function (response) {
248
            console.log('responsee', response);
33507 tejus.loha 249
            if (response) {
250
                alert("Your LOI form Submitted successfully ");
251
                pendingLoiForm("main-content");
252
 
253
            } else {
254
                alert("Your LOI form not Submitted , try again ");
33845 tejus.loha 255
                doGetAjaxRequestHandler(`${context}/loiForm`,
33507 tejus.loha 256
                    function (response) {
257
                        $('#' + 'main-content').html(response);
258
                    });
259
            }
260
        });
261
    }
262
});
33578 tejus.loha 263
 
33658 tejus.loha 264
$(document).on('click', ".updateLoiForm", function () {
33507 tejus.loha 265
    let loiId = $(this).val();
33658 tejus.loha 266
    doGetAjaxRequestHandler(context + "/updateLoiForm?loiId=" + loiId,
33507 tejus.loha 267
        function (response) {
268
            $('#' + 'main-content').html(response);
269
        });
270
});
33879 tejus.loha 271
 
33710 tejus.loha 272
$(document).on('click', ".save_agree_brand_fee", function () {
273
    let loiId = $(this).val();
274
    var $tr = $(this).closest('tr');
275
    var agreedBrandFee = $tr.find('input[name="brandFee"]').val();
34085 tejus.loha 276
    var brandType = $tr.find('select[name="brandType"]').val();
33710 tejus.loha 277
    if (confirm("Are you sure to change Agreed brand fee")) {
34085 tejus.loha 278
        doPutAjaxRequestHandler(`${context}/updateAgreedBrandFee?loiId=${loiId}&brandFee=${agreedBrandFee}&storeType=${brandType}`, function (response) {
33710 tejus.loha 279
            pendingLoiForm("main-content");
280
        });
281
    } else {
282
        pendingLoiForm("main-content");
283
    }
284
});
33507 tejus.loha 285
 
33658 tejus.loha 286
$(document).on('click', ".updateLoiFormDataButton", function () {
287
    let loiId = $(this).data('loiid');
288
    const firstName = $('input[name="firstName"]').val();
289
    const lastName = $('input[name="lastName"]').val();
290
    const mobile = $('input[name="mobile"]').val();
291
    const email = $('input[name="email"]').val();
292
    const landline = $('input[name="landline"]').val();
293
    const dob = $('input[name="dob"]').val();
294
    const panNo = $('input[name="panNo"]').val();
295
    const adharNo = $('input[name="adharNo"]').val();
296
    let missingFields = [];
297
    if (!firstName) missingFields.push('First Name');
298
    if (!lastName) missingFields.push('Last Name');
299
    if (mobile.length < 10 || !mobile) {
300
        missingFields.push('Mobile number should be 10 digit');
301
    }
302
    if (!dob) missingFields.push('dob(Date of Birth)');
303
    if (!panNo) missingFields.push('Pan Number');
304
    if (!adharNo) missingFields.push('Aadhar Number');
305
    if (!email) missingFields.push('Email');
306
    if (missingFields.length > 0) {
307
        alert('The following fields are required: ' + missingFields.join(', '));
308
        return;
309
    }
310
    const loiFormData = {
311
        firstName: firstName,
312
        lastName: lastName,
313
        mobile: mobile,
314
        email: email,
315
        landline: landline,
316
        dob: dob,
317
        panNo: panNo,
318
        adharNo: adharNo
319
    };
320
    alert("you want update ..");
321
    doPostAjaxRequestWithJsonHandler(`${context}/updateLoiFormData?loiId=${loiId}`, JSON.stringify(loiFormData), function (response) {
33507 tejus.loha 322
        pendingLoiForm("main-content");
323
    });
324
 
325
});
326
 
327
$(document).on('click', ".pending-onboarding-form", function () {
33710 tejus.loha 328
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
33507 tejus.loha 329
        function (response) {
330
            $('#' + 'main-content').html(response);
331
        });
332
});
333
$(document).on('click', "#addBrandFeePayment", function () {
35971 aman 334
    var $btn = $(this);
335
    if ($btn.prop('disabled')) return false;
33507 tejus.loha 336
    let formData = objectifyForm($("form[name='brandFeeCollectionForm']").serializeArray());
35971 aman 337
    let loiId = $btn.val();
33507 tejus.loha 338
    for (var key in formData) {
339
        if (formData.hasOwnProperty(key) && formData[key].trim() === '') {
340
            alert("The (" + key + ") value is blank please fill this field !");
341
            return false;
342
        }
343
    }
344
    let jsonData = JSON.stringify(formData);
33658 tejus.loha 345
    if (confirm("Are you sure to add payment ?")) {
35971 aman 346
        $btn.prop('disabled', true);
33525 tejus.loha 347
        doPostAjaxRequestWithJsonHandler(`${context}/brandfeeCollection?loiId=` + loiId, jsonData, function (response) {
348
            if (response) {
349
                alert("Payment add successfully...");
35971 aman 350
                $('#brandFeeCollectionModel').modal('hide');
33525 tejus.loha 351
                pendingLoiForm("main-content");
352
            }
35971 aman 353
            $btn.prop('disabled', false);
33525 tejus.loha 354
        });
355
    } else {
33658 tejus.loha 356
        alert("Payment is not add.");
33525 tejus.loha 357
    }
33507 tejus.loha 358
});
359
 
360
$(document).on('click', ".generateLoi", function () {
361
    let loiId = $(this).val();
362
    doGetAjaxRequestHandler(context + "/generateLoi?loiId=" + loiId,
363
        function (response) {
364
            $('#' + 'main-content').html(response);
365
        });
366
});
367
 
34085 tejus.loha 368
// $(document).on('change', 'select[name="pageSize"]', function () {
369
//     let pageSize = $(this).val();
370
//     console.log("pageSize - ", pageSize);
371
//     doGetAjaxRequestHandler(`${context}/pendingLoiForm?pageSize=${pageSize}&pageNumber=${1}`,
372
//         function (response) {
373
//             $('#' + 'main-content').html(response);
374
//         });
375
// });
376
 
33845 tejus.loha 377
$(document).on('click', ".mk-approve-loi", function () {
378
    let loiId = $(this).val();
379
    let companyName = $(this).data('company');
380
    let flag = $(this).data('flag');
381
    if (flag === 1) {
382
        if (confirm(`Are you sure Approve Loi of  ${companyName} `)) {
383
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${true}`,
384
                function (response) {
385
                    alert("Loi Approved successfully");
386
                    pendingLoiForm("main-content");
387
                });
388
        }
389
    } else {
390
        if (confirm(`Are you sure to Reject "${companyName}" LOI`)) {
391
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${false}`,
392
                function (response) {
393
                    pendingLoiForm("main-content");
394
                });
395
        }
396
    }
397
});
398
 
35977 aman 399
var otpCountdownTimer = null;
400
 
401
function startResendCountdown(btn) {
402
    var remaining = 30;
403
    btn.prop('disabled', true).removeClass('btn-success').addClass('btn-warning');
404
    btn.text('Resend OTP (' + remaining + 's)');
405
    otpCountdownTimer = setInterval(function () {
406
        remaining--;
407
        if (remaining <= 0) {
408
            clearInterval(otpCountdownTimer);
409
            otpCountdownTimer = null;
410
            btn.text('Resend OTP').prop('disabled', false);
411
        } else {
412
            btn.text('Resend OTP (' + remaining + 's)');
413
        }
414
    }, 1000);
415
}
416
 
33507 tejus.loha 417
$(document).on('click', "#LOI_otp", function () {
35977 aman 418
    let btn = $(this);
419
    let loiId = btn.val();
420
    if (otpCountdownTimer) return;
421
    let isResend = btn.text().indexOf('Resend') >= 0;
422
    if (!isResend && !confirm("Are you sure to send OTP ?")) return;
423
    btn.prop('disabled', true).text('Sending...');
424
    doPostAjaxRequestHandler(`${context}/loiAcceptanceOtp?loiId=` + loiId,
425
        function (response) {
426
            $('#otp_status').show().text('OTP Sent Successfully!');
427
            startResendCountdown(btn);
428
        });
33507 tejus.loha 429
});
430
 
431
//confirmPayment
33525 tejus.loha 432
$(document).on('click', ".paymentConfirmBtn", function () {
433
    let approval = $(this).data('approval');
33507 tejus.loha 434
    let bfcId = $(this).val();
33525 tejus.loha 435
    let description = "All details are correct";
436
    if (confirm("Are you sure to confirm this payment ?")) {
437
        doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
438
            function (response) {
33845 tejus.loha 439
                alert("Payment is confirm successfully");
33525 tejus.loha 440
                pendingLoiForm("main-content");
441
            });
442
    }
443
});
444
 
445
$(document).on('click', ".paymentRejectBtn", function () {
33507 tejus.loha 446
    let approval = $(this).data('approval');
33525 tejus.loha 447
    let bfcId = $(this).val();
448
    let description;
449
    description = prompt("Reason for rejection..");
450
    if (description !== null) {
451
        if (confirm("Are you sure to Reject this payment ?")) {
452
            doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
453
                function (response) {
33845 tejus.loha 454
                    alert("Payment is rejected successfully");
33525 tejus.loha 455
                    pendingLoiForm("main-content");
456
                });
457
        }
458
    } else {
459
        alert("Please mention the reason as description and try again");
460
    }
33507 tejus.loha 461
});
34739 aman.kumar 462
$(document).on('click', ".deleteFeeCollection", function () {
463
    let bfcId = $(this).val();
464
    if (confirm("Are you sure you want to delete this payment entry?")) {
465
        doPutAjaxRequestHandler(
466
            `${context}/feePaymentDeletion?bfcId=${bfcId}`,
467
            function (response) {
468
                alert("Payment entry has been deleted successfully.");
469
                pendingLoiForm("main-content");
470
            }
471
        );
472
    }
473
});
474
 
33507 tejus.loha 475
$(document).on('click', ".upload-document-form", function () {
476
    let loiId = $(this).val();
33617 tejus.loha 477
    doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 478
        function (response) {
479
            $('#' + 'main-content').html(response);
480
        });
481
});
33885 tejus.loha 482
$(document).on('input', 'table#OnboardingDocumentTable input[type=file],table#mk_brand-fee-collection-details input[type=file]', function () {
483
    if (confirm('Confirm file upload ?')) {
484
        var fileSelector = $(this)[0];
485
        if (fileSelector != undefined
486
            && fileSelector.files[0] != undefined) {
487
            var file = this.files[0];
488
            let fileInput = $(this);
489
            uploadDocument(file, function (documentId) {
490
                fileInput.closest('td').find(".documentId").val(documentId);
491
            });
492
        }
493
    }
494
});
495
 
496
$(document).on('input', '#payment-sc-doc', function () {
497
    if (confirm('Confirm file upload ?')) {
498
        var file = this.files[0];
499
        uploadDocument(file, function (documentId) {
500
            $('#payment-sc-docId').val(documentId);
501
        });
502
    }
503
});
504
 
505
 
33507 tejus.loha 506
$(document).on('click', ".mk_docApproval", function () {
507
    let loiId = $(this).data('form_id');
508
    let docMasterId = $(this).data('doc_master_id');
509
    let flag = $(this).data('flag');
510
    doPutAjaxRequestHandler(`${context}/documentVerify?loiId=${loiId}&docMasterId=${docMasterId}&flag=${flag}`,
511
        function (response) {
512
            alert(response);
33617 tejus.loha 513
            doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 514
                function (response) {
515
                    $('#' + 'main-content').html(response);
516
                });
517
 
518
        });
519
});
520
$(document).on('click', "#uploadDocumentbtn1", function () {
521
    if (confirm("Are you sure to upload all documents ?")) {
522
        var loiId = $(this).val();
523
        var loiDocModels = [];
524
        $("#OnboardingDocumentTable > tbody > tr").each(function (rowIndex) {
525
            var marsterId = $(this).find(".masterId").val();
526
            var docId = $(this).find(".documentId").val();
527
            var docName = $(this).find(".documentName").val();
528
            var loiDocModel = {
529
                documentId: docId,
530
                documentName: docName,
531
                documentMasterId: marsterId
532
            };
533
            loiDocModels.push(loiDocModel);
534
        });
535
        var loiDocModelData = JSON.stringify(loiDocModels);
536
        doPostAjaxRequestWithJsonHandler(`${context}/uploadOnboardingDocument?loiId=${loiId}`, loiDocModelData, function (response) {
537
            pendingLoiForm("main-content");
538
        });
539
    } else {
540
        //Nothing to do
541
    }
542
 
543
 
544
});
545
 
546
$(document).on('click', ".CompletedLoiForm", function () {
33617 tejus.loha 547
    doGetAjaxRequestHandler(`${context}/completedLoiForms`,
33507 tejus.loha 548
        function (response) {
549
            $('#' + 'main-content').html(response);
550
        });
551
});
552
 
553
$(document).on('click', "#createNewOnboardingPanel", function () {
554
    let loiId = $(this).val();
33710 tejus.loha 555
    //let authId = $(this).closest('tr').find('.authId').val();
33507 tejus.loha 556
 
33710 tejus.loha 557
    if (true) {
558
 
559
        doPostAjaxRequestHandler(`${context}/createNewOnboardingPanel?loiId=${loiId}&authId=${0}`,
33507 tejus.loha 560
            function (response) {
561
                if (response) {
33710 tejus.loha 562
                    // doGetAjaxRequestHandler(`${context}/completedLoiForms`,
563
                    //     function (response) {
564
                    //         $('#' + 'main-content').html(response);
565
                    //     });
566
                    alert("it moved successfully ");
33507 tejus.loha 567
                } else {
568
                    //nothing
569
                }
570
 
571
            });
572
    } else {
573
        alert("Please choose RBM ");
574
    }
575
 
576
});
577
 
33617 tejus.loha 578
$(document).on('click', "#downloadAllLoiForm", function () {
579
    const from = $('input[name="from"]').val();
580
    const to = $('input[name="to"]').val();
581
    let missingFields = [];
582
    if (!from) missingFields.push('From date');
583
    if (!to) missingFields.push('To date');
584
    if (missingFields.length > 0) {
585
        alert('Please select : ' + missingFields.join(','));
586
        return;
587
    }
588
    window.location.href = `${context}/downloadLoiFromReport?from=${from}&to=${to}`;
589
});
33658 tejus.loha 590
$(document).on('click', ".brandFeePaymentEdit", function () {
591
    var bfcId = $(this).val();
34310 tejus.loha 592
 
33658 tejus.loha 593
    // Get the table row
594
    var $row = $(this).closest('tr');
595
    var feeCollectingTimeStamp = $row.find('input[name="feeCollectingTimeStamp"]').val();
596
    var collectedAmount = $row.find('input[name="collectedAmount"]').val();
597
    var paymentReferenceNo = $row.find('input[name="paymentReferenceNo"]').val();
598
    var paymentMode = $row.find('select[name="paymentMode"]').val();
33885 tejus.loha 599
    var documentId = $row.find('input[name="documentId"]').val();
600
 
33658 tejus.loha 601
    const Data = {
602
        id: bfcId,
603
        feeCollectingTimeStamp: feeCollectingTimeStamp,
604
        collectedAmount: collectedAmount,
605
        paymentReferenceNo: paymentReferenceNo,
34745 aman.kumar 606
        paymentAttachment: documentId,
33658 tejus.loha 607
        paymentMode: paymentMode
608
    };
609
    var jsonData = JSON.stringify(Data);
610
    if (confirm("Are you sure to update details")) {
611
        doPostAjaxRequestWithJsonHandler(`${context}/updatePayment`, jsonData,
612
            function (response) {
33845 tejus.loha 613
                if (response) {
614
                    alert("Updated payment details are save successfully ")
615
                    pendingLoiForm('main-content');
616
                } else {
617
                    alert("Updated payment details are not save ")
618
                    pendingLoiForm('main-content');
619
                }
33658 tejus.loha 620
            });
621
    } else {
622
        pendingLoiForm('main-content');
623
    }
33617 tejus.loha 624
 
33658 tejus.loha 625
 
626
});
33879 tejus.loha 627
/*function validateOTP() {
628
    while (true) {
629
        let otp = prompt("Enter received OTP here");
630
        if (otp === null) {
631
            alert('OTP entry was cancelled. Try again.');
632
            return null;
633
        }
634
        let regex = /^[0-9]{5}$/;
635
        if (regex.test(otp)) {
636
            console.log('otp-flag-', otp);
637
            return otp;  // Return valid OTP
638
        } else {
639
            alert('Please enter a valid 5-digit numeric OTP');
640
        }
641
    }
642
}*/
33658 tejus.loha 643
 
33879 tejus.loha 644
$(document).on('click', "#confirmSign", function () {
645
    let loiId = $(this).val();
646
    let otp = prompt("Enter received OTP here");
647
    let validateOtpUrl = `${context}/validateLoiOtp?loiId=${loiId}&provideOtp=${otp}`;
33658 tejus.loha 648
 
35038 aman 649
    if (otp !== undefined && otp !== null) {
33879 tejus.loha 650
        doPutAjaxRequestHandler(validateOtpUrl, function (response) {
35038 aman 651
            console.log('OTP validation response:', response);
652
 
653
            if (response && response.response && response.response.success) {
654
                const docHash = (response.response.documentHash || "");
655
                const ip = response.response.ipAddress || "";
656
                const createdAt = response.response.createdAt || new Date().toLocaleString();
657
                const watermarkText =
658
                    `OTP VERIFIED\n` +
659
                    `DOCUMENT HASH:\n ${docHash}\n` +
660
                    `IP ADDRESS: ${ip}\n` +
661
                    `CREATED ON: ${createdAt}`;
662
                const originalElement = document.getElementById('loiPDF_content');
663
                const clonedElement = originalElement.cloneNode(true);
664
                const existingStyles = clonedElement.querySelectorAll('style');
665
                existingStyles.forEach(style => style.remove());
666
                $(clonedElement).find('.pending-badge, .pending-indicator').remove();
667
                $(clonedElement).find('.signature-section').each(function () {
668
                    this.style.setProperty('position', 'relative', 'important');
669
                    this.style.setProperty('padding', '20px', 'important');
670
                });
671
 
672
                const signatureSections = clonedElement.querySelectorAll('.signature-section');
673
                signatureSections.forEach(section => {
674
                    const oldWatermarks = section.querySelectorAll('.watermark-overlay');
675
                    oldWatermarks.forEach(w => w.remove());
676
 
677
                    const watermarkDiv = document.createElement('div');
678
                    watermarkDiv.className = 'watermark-overlay';
679
                    watermarkDiv.textContent = watermarkText;
680
                    watermarkDiv.style.position = 'absolute';
681
                    watermarkDiv.style.fontSize = '7px';
682
                    watermarkDiv.style.top = '30px';
683
                    watermarkDiv.style.left = '1%';
684
                    watermarkDiv.style.color = 'rgb(4,97,225)';
685
                    watermarkDiv.style.fontWeight = 'bold';
686
                    watermarkDiv.style.fontFamily = 'Arial,sans-serif';
687
                    watermarkDiv.style.whiteSpace = 'pre-line';
688
                    watermarkDiv.style.textAlign = 'center';
689
                    watermarkDiv.style.pointerEvents = 'none';
690
                    watermarkDiv.style.width = '90%';
691
                    watermarkDiv.style.lineHeight = '1.7';
692
                    watermarkDiv.style.zIndex = '1';
693
                    watermarkDiv.style.userSelect = 'none';
694
 
695
                    section.style.position = 'relative';
696
                    section.appendChild(watermarkDiv);
697
                });
698
 
699
                const tempContainer = document.createElement('div');
700
                tempContainer.style.position = 'absolute';
701
                tempContainer.style.left = '-9999px';
702
                tempContainer.style.width = '800px';
703
                tempContainer.appendChild(clonedElement);
704
                document.body.appendChild(tempContainer);
705
 
33879 tejus.loha 706
                const opt = {
35038 aman 707
                    margin: [0.5, 0.5, 0.5, 0.5],
708
                    filename: `LOI_${loiId}_${new Date().getTime()}.pdf`,
709
                    image: {
710
                        type: 'jpeg',
711
                        quality: 0.98
712
                    },
713
                    html2canvas: {
714
                        scale: 1.2,
715
                        logging: false,
716
                        useCORS: true,
717
                        allowTaint: false,
718
                        backgroundColor: '#ffffff'
719
                    },
720
                    jsPDF: {
721
                        unit: 'in',
722
                        format: 'letter',
723
                        orientation: 'portrait'
724
                    }
33879 tejus.loha 725
                };
35038 aman 726
 
727
                html2pdf().from(clonedElement).set(opt).outputPdf("arraybuffer")
728
                    .then(function (pdf) {
729
                        document.body.removeChild(tempContainer);
730
 
731
                        const file = new Blob([pdf], {type: 'application/pdf'});
732
 
733
                        uploadDocument(file, function (documentId) {
734
                            IdempotencyKey = uuidv4();
735
                            if (documentId > 0) {
736
                                saveLoiDoc(loiId, documentId);
737
                                alert("Document signed and saved successfully!");
738
                            } else {
739
                                alert("Something went wrong, please try again to confirm OTP");
740
                            }
741
                        });
742
                    })
743
                    .catch(function (error) {
744
                        console.error('PDF generation failed:', error);
745
                        document.body.removeChild(tempContainer);
746
                        alert("PDF generation failed. Please try again.");
33879 tejus.loha 747
                    });
35038 aman 748
            } else {
749
                console.error('OTP validation failed:', response);
750
                alert("OTP validation failed: " + (response.response?.message || "Please try again."));
33879 tejus.loha 751
            }
35038 aman 752
        }, function (error) {
753
            console.error('AJAX request failed:', error);
754
            alert("Request failed. Please check your connection and try again.");
33879 tejus.loha 755
        });
756
    } else {
34310 tejus.loha 757
        return false;
33879 tejus.loha 758
    }
759
});
760
 
761
 
762
function saveLoiDoc(loiId, documentId) {
763
    let saveLoiDocUrl = `${context}/saveLoiDoc?loiId=` + loiId + `&loiDocId=` + documentId
764
    doPostAjaxRequestHandler(saveLoiDocUrl, function (response) {
765
        if (response) {
766
            alert("LOI has been signed successfully and sent to the registered email. Please check your email.");
767
            pendingLoiForm("main-content");
768
        } else {
769
            alert("Something went wrong , Please try again to generate Loi and Validate otp");
770
        }
771
    });
772
}
773
 
774
 
33507 tejus.loha 775
function pendingLoiForm(domId) {
33710 tejus.loha 776
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
33507 tejus.loha 777
        function (response) {
778
            $('#' + domId).html(response);
779
        });
780
}
34085 tejus.loha 781
 
782
/*
783
function createPagination(containerId, totalPages, currentPage = 1, onPageChange = null) {
784
    const $container = $('#' + containerId);
785
    $container.empty(); // Clear the container
786
 
787
    // Helper Function to Render Pagination
788
    function renderPagination(currentPage) {
789
        $container.empty();
790
 
791
        // Previous Button
792
        const $prevButton = $('<button>')
793
            .text('Previous')
794
            .click(() => handlePageChange(currentPage > 1 ? currentPage - 1 : totalPages)); // Loop to last page if on the first page
795
        $container.append($prevButton);
796
 
797
        // First Page
798
        const $firstPageButton = $('<button>')
799
            .text('1')
800
            .addClass(currentPage === 1 ? 'active' : '')
801
            .click(() => handlePageChange(1));
802
        $container.append($firstPageButton);
803
 
804
        // Ellipsis Before Current Pages
805
        if (currentPage > 3) {
806
            $container.append($('<span>').text('...'));
807
        }
808
 
809
        // Dynamic Pages Around Current Page
810
        for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
811
            const $pageButton = $('<button>')
812
                .text(i)
813
                .addClass(currentPage === i ? 'active' : '')
814
                .click(() => handlePageChange(i));
815
            $container.append($pageButton);
816
        }
817
 
818
        // Ellipsis Before Last Page
819
        if (currentPage < totalPages - 2) {
820
            $container.append($('<span>').text('...'));
821
        }
822
 
823
        // Last Page
824
        if (totalPages > 1) {
825
            const $lastPageButton = $('<button>')
826
                .text(totalPages)
827
                .addClass(currentPage === totalPages ? 'active' : '')
828
                .click(() => handlePageChange(totalPages));
829
            $container.append($lastPageButton);
830
        }
831
 
832
        // Next Button
833
        const $nextButton = $('<button>')
834
            .text('Next')
835
            .click(() => handlePageChange(currentPage < totalPages ? currentPage + 1 : 1)); // Loop to first page if on the last page
836
        $container.append($nextButton);
837
    }
838
 
839
    // Handle Page Change
840
    function handlePageChange(selectedPage) {
841
        if (onPageChange) {
842
            onPageChange(selectedPage); // Trigger the callback with the selected page
843
        }
844
        renderPagination(selectedPage); // Re-render pagination
845
    }
846
 
847
    // Initial Render
848
    renderPagination(currentPage);
849
}*/