Subversion Repositories SmartDukaan

Rev

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