Subversion Repositories SmartDukaan

Rev

Rev 37523 | 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'.
36851 aman 29
$(document).on('blur', 'input[name="acquiredDate"]', function () {
36842 aman 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
 
36851 aman 37
// Browser-independent guard: if the entered Acquired Date is outside the last 7 days,
38
// reject it (clear the field) instead of waiting until form submit.
39
// IMPORTANT: validate on 'blur', NOT 'change'. When a user TYPES into a type="date"
40
// field, the year is entered one digit at a time, so the field momentarily holds
41
// complete-but-wrong dates (e.g. 0002-06-16 → 0020-... → 0202-... before 2026-...),
42
// each of which fires 'change'. Validating on 'change' would reject and clear those
43
// intermediate years, making manual entry impossible. 'blur' fires only once the
44
// user has finished editing the field.
45
$(document).on('blur', 'input[name="acquiredDate"]', function () {
36843 aman 46
    const picked = $(this).val();
47
    if (!picked) return;
36845 aman 48
    const acq = parseLocalYMD(picked);
36843 aman 49
    const today = new Date();
50
    today.setHours(0, 0, 0, 0);
51
    const minAllowed = new Date(today);
52
    minAllowed.setDate(today.getDate() - 7);
53
    if (acq > today || acq < minAllowed) {
54
        alert('Acquired date must be within the last 7 days (today or up to 7 days ago).');
55
        $(this).val('');
56
    }
57
});
36842 aman 58
 
36843 aman 59
 
33577 tejus.loha 60
$(document).on('change', "#maritalStatus", function () {
61
    let maritalStatus = $(this).val();
62
    if (maritalStatus == 1) {
63
        $(".loiAnniversaryDate").removeClass('hide-model');
64
        $(".loiAnniversaryDate").addClass('show-model');
65
    } else {
66
        $(".loiAnniversaryDate").removeClass('show-model');
67
        $(".loiAnniversaryDate").addClass('hide-model');
68
    }
69
 
70
});
71
 
33578 tejus.loha 72
 
33885 tejus.loha 73
$(document).on('click', ".mk_submit_loi_form", function () {
33577 tejus.loha 74
    // Gather input values
37523 ranu 75
    const onboardingType = $('input[name="loiOnboardingType"]:checked').val() || 'NEW';
76
    const oldStoreCode = $('#loiOldStoreCode').val() ? $('#loiOldStoreCode').val().trim() : '';
77
    const revivalReason = $('#loiRevivalReason').val() ? $('#loiRevivalReason').val().trim() : '';
33577 tejus.loha 78
    const referId = $('select[name="referId"]').val();
34107 tejus.loha 79
    const stateHead = $('select[name="stateHead"]').val();
80
    const bdm = $('select[name="bdm"]').val();
34310 tejus.loha 81
    let billingAddress = $('select[name="billingAddress"]').val();
82
    if(!billingAddress){
83
        const addrFieldData = {
84
            "bno": "",
85
            "bnm": "",
86
            "st": "",
87
            "locality": "",
88
            "loc": "",
89
            "dst": "",
90
            "pncd": "",
91
            "stcd": ""
92
        };
93
 
94
        // Dynamically create input fields
95
        let address = [];
96
        Object.keys(addrFieldData).forEach(function (field) {
97
             addrFieldData[field] = $('input[name="'+field+'"]').val();
98
        });
99
        billingAddress = JSON.stringify(addrFieldData);
100
 
101
    }
33582 tejus.loha 102
    const acquiredDate = $('input[name="acquiredDate"]').val();
33577 tejus.loha 103
    const firstName = $('input[name="firstName"]').val();
104
    const lastName = $('input[name="lastName"]').val();
105
    const mobile = $('input[name="mobile"]').val();
33780 tejus.loha 106
 
107
    // validate email pattern
108
    const emailValue = $('input[name="email"]').val();
109
    var email;
110
    if (emailValue.length > 0) {
111
        if (isValidEmail(emailValue)) {
112
            email = emailValue;
113
        } else {
114
            alert("Please check your Email Address");
115
            return;
116
        }
117
    }
33577 tejus.loha 118
    const landline = $('input[name="landline"]').val();
119
    const dob = $('input[name="dob"]').val();
33624 tejus.loha 120
    var today = new Date();
121
    var birthDate = new Date(dob);
122
    var age = today.getFullYear() - birthDate.getFullYear();
123
    var monthDiff = today.getMonth() - birthDate.getMonth();
124
 
125
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
126
        age--;
127
    }
33577 tejus.loha 128
    var maritalStatus = $('select[name="maritalStatus"]').val();
129
    const anniversaryDate = $('input[name="anniversaryDate"]').val();
130
    const panNo = $('input[name="panNo"]').val();
131
    const adharNo = $('input[name="adharNo"]').val();
132
    const gstNo = $('input[name="gstNo"]').val();
133
    const bankName = $('input[name="bankName"]').val();
134
    const ifscCode = $('input[name="ifscCode"]').val();
135
    const accountNo = $('input[name="accountNo"]').val();
136
    const businessType = $('select[name="businessType"]').val();
137
    const companyName = $('input[name="companyName"]').val();
138
    const gstPin = $('input[name="gstPin"]').val();
139
    const gstState = $('input[name="gstState"]').val();
140
    const gstCity = $('input[name="gstCity"]').val();
141
    const gstDistrict = $('input[name="gstDistrict"]').val();
142
    const agreeWalletValue = $('select[name="agreeWalletValue"]').val();
143
    const storeArea = $('input[name="storeArea"]').val();
144
    const storePotential = $('input[name="storePotential"]').val();
35971 aman 145
    let financeOptions = [];
146
    document.querySelectorAll(".finance-code-input").forEach(function (input) {
147
        var code = input.value.trim();
148
        if (code) {
149
            financeOptions.push({
150
                paymentOptionId: parseInt(input.getAttribute("data-payment-option-id")),
151
                financeCode: code
152
            });
153
        }
154
    });
33658 tejus.loha 155
    let brandCommitment = [];
156
    var brandCommitmentInputs = document.querySelectorAll(".brand-commitment");
35971 aman 157
    var hasInvalidQty = false;
33658 tejus.loha 158
    brandCommitmentInputs.forEach(function (input) {
159
        var commitmentValue = parseInt(input.value);
160
        if (!isNaN(commitmentValue)) {
35971 aman 161
            if (commitmentValue > 1000) {
162
                hasInvalidQty = true;
163
            }
33658 tejus.loha 164
            brandCommitment.push({
165
                brandName: input.getAttribute("name"),
166
                value: commitmentValue
167
            });
168
        }
169
    });
35971 aman 170
    if (hasInvalidQty) {
171
        alert("Quantity per brand cannot exceed 1000. Please enter valid quantities.");
172
        return;
173
    }
33658 tejus.loha 174
    let totalCommitment = brandCommitment.reduce((total, commitment) => total + commitment.value, 0);
35971 aman 175
    // Calculate estimated value: total qty × 20000 (average smartphone value)
176
    let estimatedValue = totalCommitment * 20000;
177
    let minCommit = estimatedValue >= (0.7 * storePotential);
178
    const lessCommitReason = $('textarea[name="lessCommitReason"]').val();
33577 tejus.loha 179
    const agreedBrandFees = $('select[name="agreedBrandFees"]').val();
33624 tejus.loha 180
    const values = agreedBrandFees.split(/[-]/); // Split the string
181
    const brandFee = parseFloat(values[1]);
33577 tejus.loha 182
    const brandFeesCollected = $('input[name="brandFeesCollected"]').val();
183
    const paymentMode = $('select[name="paymentMode"]').val();
184
    const paymentReferenceNo = $('input[name="paymentReferenceNo"]').val();
33578 tejus.loha 185
    const feeCollectingDate = $('input[name="feeCollectingDate"]').val();
33885 tejus.loha 186
    const paymentAttachment = $('input[name="paymentAttachment"]').val();
33577 tejus.loha 187
 
188
    let missingFields = [];
37523 ranu 189
    if (onboardingType !== 'NEW') {
190
        if (!revivalReason) {
191
            missingFields.push(onboardingType === 'ANY_OTHER' ? 'Reason (Any Other)' : 'Reason for Revival');
192
        }
193
        if (onboardingType === 'REVIVAL' && !oldStoreCode) {
194
            missingFields.push('Old Store Code (required for Revival)');
195
        }
196
    }
33577 tejus.loha 197
    if (!firstName) missingFields.push('First Name');
198
    if (!lastName) missingFields.push('Last Name');
199
    if (mobile.length < 10 || !mobile) {
200
        missingFields.push('Mobile number should be 10 digit');
201
    }
33658 tejus.loha 202
    if (!minCommit) {
33577 tejus.loha 203
        if (!lessCommitReason) missingFields.push('Less Commit Reason');
204
    }
205
    if (!maritalStatus) missingFields.push('Marital Status');
206
    if (maritalStatus == 1) {
207
        if (!anniversaryDate) missingFields.push('Anniversary Date');
208
    }
209
    if (!email) missingFields.push('Email');
34107 tejus.loha 210
    if (!referId) missingFields.push('Refer By');
211
    if (!bdm) missingFields.push('Bdm');
212
    if (!stateHead) missingFields.push('State head');
36842 aman 213
    if (!acquiredDate) {
214
        missingFields.push('Acquired date');
215
    } else {
216
        // Acquired date must fall within the last 7 days (not in the future, not older than 7 days back)
36845 aman 217
        const acq = parseLocalYMD(acquiredDate);
36842 aman 218
        const today = new Date();
219
        today.setHours(0, 0, 0, 0);
220
        const minAllowed = new Date(today);
221
        minAllowed.setDate(today.getDate() - 7);
222
        if (acq > today || acq < minAllowed) {
223
            missingFields.push('Acquired date must be within the last 7 days');
224
        }
225
    }
33577 tejus.loha 226
    if (!dob) missingFields.push('dob(Date of Birth)');
33624 tejus.loha 227
    if (age <= 18) missingFields.push('You must be at least 18 years old to Fill LOI FORM. ');
33577 tejus.loha 228
    if (!panNo) missingFields.push('Pan Number');
229
    if (!adharNo) missingFields.push('Aadhar Number');
230
    if (!gstNo) missingFields.push('GST Number');
231
    if (!bankName) missingFields.push('Bank Name');
232
    if (!ifscCode) missingFields.push('IFSC code');
233
    if (!accountNo) missingFields.push('Account Number');
234
    if (!businessType) missingFields.push('businessType');
235
    if (!companyName) missingFields.push('Company Name');
236
    if (!agreeWalletValue) missingFields.push('Agree Wallet Value');
237
    if (!storeArea) missingFields.push('storeArea');
238
    if (!storePotential) missingFields.push('Store Potential');
239
    if (!agreedBrandFees) missingFields.push('Agreed Brand Fees');
240
    if (!brandFeesCollected) missingFields.push('Brand Fees Collected');
33845 tejus.loha 241
    if (brandFeesCollected > brandFee) missingFields.push('The collected brand fee must not exceed the agreed brand fees.');
33577 tejus.loha 242
    if (!paymentMode) missingFields.push('Payment Mode');
243
    if (!paymentReferenceNo) missingFields.push('Payment Reference No');
33578 tejus.loha 244
    if (!feeCollectingDate) missingFields.push('Fee Collecting Date');
37458 aman 245
    if (!paymentAttachment) {
246
        var screenshotInput = $('#payment-sc-doc')[0];
247
        if (paymentScreenshotUploading) {
248
            missingFields.push('Payment screenshot (still uploading - wait for "Attached: ..." under the field)');
249
        } else if (screenshotInput && screenshotInput.files && screenshotInput.files.length > 0) {
250
            missingFields.push('Payment screenshot (the file was picked but the upload did not complete - select it again)');
251
        } else {
252
            missingFields.push('Payment screenshot');
253
        }
254
    }
33577 tejus.loha 255
    if (missingFields.length > 0) {
256
        alert('The following fields are required: ' + missingFields.join(', '));
257
        return;
258
    }
259
    const loiFormData = {
37523 ranu 260
        onboardingType: onboardingType,
261
        oldStoreCode: oldStoreCode,
262
        revivalReason: revivalReason,
33577 tejus.loha 263
        referId: referId,
34107 tejus.loha 264
        stateHead: stateHead,
265
        bdm: bdm,
33577 tejus.loha 266
        businessType: businessType,
33582 tejus.loha 267
        acquiredDate: acquiredDate,
33577 tejus.loha 268
        firstName: firstName,
269
        lastName: lastName,
270
        mobile: mobile,
271
        email: email,
272
        landline: landline,
273
        dob: dob,
274
        anniversaryDate: anniversaryDate,
275
        panNo: panNo,
276
        adharNo: adharNo,
277
        gstNo: gstNo,
278
        bankName: bankName,
279
        ifscCode: ifscCode,
280
        accountNo: accountNo,
281
        companyName: companyName,
282
        gstPin: gstPin,
283
        gstState: gstState,
284
        gstCity: gstCity,
285
        gstDistrict: gstDistrict,
286
        agreeWalletValue: agreeWalletValue,
287
        storeArea: storeArea,
288
        storePotential: storePotential,
35971 aman 289
        financeOptions: financeOptions,
33577 tejus.loha 290
        lessCommitReason: lessCommitReason,
291
        agreedBrandFees: agreedBrandFees,
292
        brandFeesCollected: brandFeesCollected,
293
        paymentMode: paymentMode,
294
        paymentReferenceNo: paymentReferenceNo,
33578 tejus.loha 295
        feeCollectingTimeStamp: feeCollectingDate,
33885 tejus.loha 296
        paymentAttachment: paymentAttachment,
33658 tejus.loha 297
        billingAddress: billingAddress,
298
        brandCommitment: brandCommitment
33577 tejus.loha 299
    };
33658 tejus.loha 300
 
33577 tejus.loha 301
    if (confirm("Are you sure to submit the form ?")) {
302
        doPostAjaxRequestWithJsonHandler(`${context}/submitLoiForm`, JSON.stringify(loiFormData), function (response) {
303
            console.log('responsee', response);
33507 tejus.loha 304
            if (response) {
305
                alert("Your LOI form Submitted successfully ");
306
                pendingLoiForm("main-content");
307
 
308
            } else {
309
                alert("Your LOI form not Submitted , try again ");
33845 tejus.loha 310
                doGetAjaxRequestHandler(`${context}/loiForm`,
33507 tejus.loha 311
                    function (response) {
312
                        $('#' + 'main-content').html(response);
313
                    });
314
            }
315
        });
316
    }
317
});
33578 tejus.loha 318
 
33658 tejus.loha 319
$(document).on('click', ".updateLoiForm", function () {
33507 tejus.loha 320
    let loiId = $(this).val();
33658 tejus.loha 321
    doGetAjaxRequestHandler(context + "/updateLoiForm?loiId=" + loiId,
33507 tejus.loha 322
        function (response) {
323
            $('#' + 'main-content').html(response);
324
        });
325
});
33879 tejus.loha 326
 
33710 tejus.loha 327
$(document).on('click', ".save_agree_brand_fee", function () {
328
    let loiId = $(this).val();
329
    var $tr = $(this).closest('tr');
330
    var agreedBrandFee = $tr.find('input[name="brandFee"]').val();
34085 tejus.loha 331
    var brandType = $tr.find('select[name="brandType"]').val();
33710 tejus.loha 332
    if (confirm("Are you sure to change Agreed brand fee")) {
34085 tejus.loha 333
        doPutAjaxRequestHandler(`${context}/updateAgreedBrandFee?loiId=${loiId}&brandFee=${agreedBrandFee}&storeType=${brandType}`, function (response) {
33710 tejus.loha 334
            pendingLoiForm("main-content");
335
        });
336
    } else {
337
        pendingLoiForm("main-content");
338
    }
339
});
33507 tejus.loha 340
 
33658 tejus.loha 341
$(document).on('click', ".updateLoiFormDataButton", function () {
342
    let loiId = $(this).data('loiid');
343
    const firstName = $('input[name="firstName"]').val();
344
    const lastName = $('input[name="lastName"]').val();
345
    const mobile = $('input[name="mobile"]').val();
346
    const email = $('input[name="email"]').val();
347
    const landline = $('input[name="landline"]').val();
348
    const dob = $('input[name="dob"]').val();
349
    const panNo = $('input[name="panNo"]').val();
350
    const adharNo = $('input[name="adharNo"]').val();
351
    let missingFields = [];
352
    if (!firstName) missingFields.push('First Name');
353
    if (!lastName) missingFields.push('Last Name');
354
    if (mobile.length < 10 || !mobile) {
355
        missingFields.push('Mobile number should be 10 digit');
356
    }
357
    if (!dob) missingFields.push('dob(Date of Birth)');
358
    if (!panNo) missingFields.push('Pan Number');
359
    if (!adharNo) missingFields.push('Aadhar Number');
360
    if (!email) missingFields.push('Email');
361
    if (missingFields.length > 0) {
362
        alert('The following fields are required: ' + missingFields.join(', '));
363
        return;
364
    }
365
    const loiFormData = {
366
        firstName: firstName,
367
        lastName: lastName,
368
        mobile: mobile,
369
        email: email,
370
        landline: landline,
371
        dob: dob,
372
        panNo: panNo,
373
        adharNo: adharNo
374
    };
375
    alert("you want update ..");
376
    doPostAjaxRequestWithJsonHandler(`${context}/updateLoiFormData?loiId=${loiId}`, JSON.stringify(loiFormData), function (response) {
33507 tejus.loha 377
        pendingLoiForm("main-content");
378
    });
379
 
380
});
381
 
382
$(document).on('click', ".pending-onboarding-form", function () {
33710 tejus.loha 383
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
33507 tejus.loha 384
        function (response) {
385
            $('#' + 'main-content').html(response);
386
        });
387
});
388
$(document).on('click', "#addBrandFeePayment", function () {
35971 aman 389
    var $btn = $(this);
390
    if ($btn.prop('disabled')) return false;
33507 tejus.loha 391
    let formData = objectifyForm($("form[name='brandFeeCollectionForm']").serializeArray());
35971 aman 392
    let loiId = $btn.val();
37458 aman 393
    // paymentAttachment is a hidden field filled by the screenshot upload, so name it
394
    // the way the operator sees it rather than echoing the raw form key.
395
    const brandFeeFieldLabels = {
396
        collectedAmount: 'Amount',
397
        paymentMode: 'Payment Mode',
398
        paymentReferenceNo: 'Reference No',
399
        paymentAttachment: 'Attachment (pick the screenshot again - the upload did not complete)',
400
        feeCollectingTimeStamp: 'Collecting Date'
401
    };
33507 tejus.loha 402
    for (var key in formData) {
403
        if (formData.hasOwnProperty(key) && formData[key].trim() === '') {
37458 aman 404
            alert("The (" + (brandFeeFieldLabels[key] || key) + ") value is blank please fill this field !");
33507 tejus.loha 405
            return false;
406
        }
407
    }
408
    let jsonData = JSON.stringify(formData);
33658 tejus.loha 409
    if (confirm("Are you sure to add payment ?")) {
35971 aman 410
        $btn.prop('disabled', true);
33525 tejus.loha 411
        doPostAjaxRequestWithJsonHandler(`${context}/brandfeeCollection?loiId=` + loiId, jsonData, function (response) {
412
            if (response) {
413
                alert("Payment add successfully...");
35971 aman 414
                $('#brandFeeCollectionModel').modal('hide');
33525 tejus.loha 415
                pendingLoiForm("main-content");
416
            }
35971 aman 417
            $btn.prop('disabled', false);
33525 tejus.loha 418
        });
419
    } else {
33658 tejus.loha 420
        alert("Payment is not add.");
33525 tejus.loha 421
    }
33507 tejus.loha 422
});
423
 
424
$(document).on('click', ".generateLoi", function () {
425
    let loiId = $(this).val();
426
    doGetAjaxRequestHandler(context + "/generateLoi?loiId=" + loiId,
427
        function (response) {
428
            $('#' + 'main-content').html(response);
429
        });
430
});
431
 
34085 tejus.loha 432
// $(document).on('change', 'select[name="pageSize"]', function () {
433
//     let pageSize = $(this).val();
434
//     console.log("pageSize - ", pageSize);
435
//     doGetAjaxRequestHandler(`${context}/pendingLoiForm?pageSize=${pageSize}&pageNumber=${1}`,
436
//         function (response) {
437
//             $('#' + 'main-content').html(response);
438
//         });
439
// });
440
 
33845 tejus.loha 441
$(document).on('click', ".mk-approve-loi", function () {
442
    let loiId = $(this).val();
443
    let companyName = $(this).data('company');
444
    let flag = $(this).data('flag');
445
    if (flag === 1) {
446
        if (confirm(`Are you sure Approve Loi of  ${companyName} `)) {
447
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${true}`,
448
                function (response) {
449
                    alert("Loi Approved successfully");
450
                    pendingLoiForm("main-content");
451
                });
452
        }
453
    } else {
454
        if (confirm(`Are you sure to Reject "${companyName}" LOI`)) {
455
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${false}`,
456
                function (response) {
457
                    pendingLoiForm("main-content");
458
                });
459
        }
460
    }
461
});
462
 
35977 aman 463
var otpCountdownTimer = null;
464
 
465
function startResendCountdown(btn) {
466
    var remaining = 30;
467
    btn.prop('disabled', true).removeClass('btn-success').addClass('btn-warning');
468
    btn.text('Resend OTP (' + remaining + 's)');
469
    otpCountdownTimer = setInterval(function () {
470
        remaining--;
471
        if (remaining <= 0) {
472
            clearInterval(otpCountdownTimer);
473
            otpCountdownTimer = null;
474
            btn.text('Resend OTP').prop('disabled', false);
475
        } else {
476
            btn.text('Resend OTP (' + remaining + 's)');
477
        }
478
    }, 1000);
479
}
480
 
37194 aman 481
function showOtpStatus(color, text) {
482
    $('#otp_status').show().css('color', color).text(text);
483
}
484
 
33507 tejus.loha 485
$(document).on('click', "#LOI_otp", function () {
35977 aman 486
    let btn = $(this);
487
    let loiId = btn.val();
488
    if (otpCountdownTimer) return;
489
    let isResend = btn.text().indexOf('Resend') >= 0;
490
    if (!isResend && !confirm("Are you sure to send OTP ?")) return;
37194 aman 491
    let previousText = btn.text();
35977 aman 492
    btn.prop('disabled', true).text('Sending...');
493
    doPostAjaxRequestHandler(`${context}/loiAcceptanceOtp?loiId=` + loiId,
494
        function (response) {
37194 aman 495
            let res = null;
496
            try {
497
                res = (typeof response === 'string' ? JSON.parse(response) : response);
498
            } catch (e) {
499
                res = null;
500
            }
501
            if (!res || typeof res.status === 'undefined') {
502
                showOtpStatus('red', 'Could not confirm the OTP was sent. Check with tech support before retrying.');
503
                btn.prop('disabled', false).text(previousText);
504
                return;
505
            }
506
            if (res.status && res.sent) {
507
                showOtpStatus('green', res.message || 'OTP sent.');
508
                startResendCountdown(btn);
509
            } else if (res.status) {
510
                // Accepted, but nothing was dispatched - the previous OTP is still valid (resend throttle).
511
                showOtpStatus('#c07000', 'No new OTP sent - ' + (res.message || 'the previous OTP is still valid.'));
512
                startResendCountdown(btn);
513
            } else {
514
                showOtpStatus('red', 'OTP NOT sent - ' + (res.message || 'unknown reason.'));
515
                btn.prop('disabled', false).text(previousText);
516
            }
517
        },
518
        function (xhr, msg) {
519
            showOtpStatus('red', 'OTP NOT sent - request failed (' + xhr.status + ').');
520
            btn.prop('disabled', false).text(previousText);
35977 aman 521
        });
33507 tejus.loha 522
});
523
 
524
//confirmPayment
33525 tejus.loha 525
$(document).on('click', ".paymentConfirmBtn", function () {
526
    let approval = $(this).data('approval');
33507 tejus.loha 527
    let bfcId = $(this).val();
33525 tejus.loha 528
    let description = "All details are correct";
529
    if (confirm("Are you sure to confirm this payment ?")) {
530
        doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
531
            function (response) {
33845 tejus.loha 532
                alert("Payment is confirm successfully");
33525 tejus.loha 533
                pendingLoiForm("main-content");
534
            });
535
    }
536
});
537
 
538
$(document).on('click', ".paymentRejectBtn", function () {
33507 tejus.loha 539
    let approval = $(this).data('approval');
33525 tejus.loha 540
    let bfcId = $(this).val();
541
    let description;
542
    description = prompt("Reason for rejection..");
543
    if (description !== null) {
544
        if (confirm("Are you sure to Reject this payment ?")) {
545
            doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
546
                function (response) {
33845 tejus.loha 547
                    alert("Payment is rejected successfully");
33525 tejus.loha 548
                    pendingLoiForm("main-content");
549
                });
550
        }
551
    } else {
552
        alert("Please mention the reason as description and try again");
553
    }
33507 tejus.loha 554
});
34739 aman.kumar 555
$(document).on('click', ".deleteFeeCollection", function () {
556
    let bfcId = $(this).val();
557
    if (confirm("Are you sure you want to delete this payment entry?")) {
558
        doPutAjaxRequestHandler(
559
            `${context}/feePaymentDeletion?bfcId=${bfcId}`,
560
            function (response) {
561
                alert("Payment entry has been deleted successfully.");
562
                pendingLoiForm("main-content");
563
            }
564
        );
565
    }
566
});
567
 
33507 tejus.loha 568
$(document).on('click', ".upload-document-form", function () {
569
    let loiId = $(this).val();
33617 tejus.loha 570
    doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 571
        function (response) {
572
            $('#' + 'main-content').html(response);
573
        });
574
});
37458 aman 575
// A file input keeps showing the chosen filename no matter what happens next, so the
576
// operator reads "attached" from the widget while the validator reads the hidden
577
// documentId that the upload was supposed to fill. Every path below keeps those two in
578
// step: if the id does not land, the file input is cleared so the form stops claiming a
579
// file is attached. (The old confirm() gate is gone - picking a file in the OS dialog is
580
// already an explicit action, and Chrome's "prevent additional dialogs" checkbox made
581
// confirm() silently return false, which skipped the upload with no trace.)
582
var paymentScreenshotUploading = false;
583
 
584
function setPaymentScreenshotStatus(text, cssClass) {
585
    $('#payment-sc-status').text(text).attr('class', 'help-block ' + (cssClass || ''));
586
}
587
 
588
$(document).on('change', 'table#OnboardingDocumentTable input[type=file],table#mk_brand-fee-collection-details input[type=file]', function () {
589
    var input = this;
590
    var fileInput = $(input);
591
    var file = input.files && input.files[0];
592
    fileInput.closest('td').find(".documentId").val('');
593
    if (!file) {
594
        return;
33885 tejus.loha 595
    }
37458 aman 596
    uploadDocument(file, function (documentId) {
597
        fileInput.closest('td').find(".documentId").val(documentId);
598
    }, function (message) {
599
        input.value = '';
600
        alert(message);
601
    });
33885 tejus.loha 602
});
603
 
37458 aman 604
$(document).on('change', '#payment-sc-doc', function () {
605
    var input = this;
606
    var file = input.files && input.files[0];
607
    // A fresh pick invalidates whatever was uploaded before it.
608
    $('#payment-sc-docId').val('');
609
    if (!file) {
610
        paymentScreenshotUploading = false;
611
        setPaymentScreenshotStatus('', '');
612
        return;
33885 tejus.loha 613
    }
37458 aman 614
    paymentScreenshotUploading = true;
615
    setPaymentScreenshotStatus('Uploading ' + file.name + ' ...', '');
616
    uploadDocument(file, function (documentId) {
617
        paymentScreenshotUploading = false;
618
        $('#payment-sc-docId').val(documentId);
619
        setPaymentScreenshotStatus('Attached: ' + file.name, 'text-success');
620
    }, function (message) {
621
        paymentScreenshotUploading = false;
622
        input.value = '';
623
        setPaymentScreenshotStatus('Not attached - please select the file again', 'text-danger');
624
        alert(message);
625
    });
33885 tejus.loha 626
});
627
 
628
 
33507 tejus.loha 629
$(document).on('click', ".mk_docApproval", function () {
630
    let loiId = $(this).data('form_id');
631
    let docMasterId = $(this).data('doc_master_id');
632
    let flag = $(this).data('flag');
633
    doPutAjaxRequestHandler(`${context}/documentVerify?loiId=${loiId}&docMasterId=${docMasterId}&flag=${flag}`,
634
        function (response) {
635
            alert(response);
33617 tejus.loha 636
            doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 637
                function (response) {
638
                    $('#' + 'main-content').html(response);
639
                });
640
 
641
        });
642
});
643
$(document).on('click', "#uploadDocumentbtn1", function () {
644
    if (confirm("Are you sure to upload all documents ?")) {
645
        var loiId = $(this).val();
646
        var loiDocModels = [];
647
        $("#OnboardingDocumentTable > tbody > tr").each(function (rowIndex) {
648
            var marsterId = $(this).find(".masterId").val();
649
            var docId = $(this).find(".documentId").val();
650
            var docName = $(this).find(".documentName").val();
651
            var loiDocModel = {
652
                documentId: docId,
653
                documentName: docName,
654
                documentMasterId: marsterId
655
            };
656
            loiDocModels.push(loiDocModel);
657
        });
658
        var loiDocModelData = JSON.stringify(loiDocModels);
659
        doPostAjaxRequestWithJsonHandler(`${context}/uploadOnboardingDocument?loiId=${loiId}`, loiDocModelData, function (response) {
660
            pendingLoiForm("main-content");
661
        });
662
    } else {
663
        //Nothing to do
664
    }
665
 
666
 
667
});
668
 
669
$(document).on('click', ".CompletedLoiForm", function () {
33617 tejus.loha 670
    doGetAjaxRequestHandler(`${context}/completedLoiForms`,
33507 tejus.loha 671
        function (response) {
672
            $('#' + 'main-content').html(response);
673
        });
674
});
675
 
676
$(document).on('click', "#createNewOnboardingPanel", function () {
677
    let loiId = $(this).val();
33710 tejus.loha 678
    //let authId = $(this).closest('tr').find('.authId').val();
33507 tejus.loha 679
 
33710 tejus.loha 680
    if (true) {
681
 
682
        doPostAjaxRequestHandler(`${context}/createNewOnboardingPanel?loiId=${loiId}&authId=${0}`,
33507 tejus.loha 683
            function (response) {
684
                if (response) {
33710 tejus.loha 685
                    // doGetAjaxRequestHandler(`${context}/completedLoiForms`,
686
                    //     function (response) {
687
                    //         $('#' + 'main-content').html(response);
688
                    //     });
689
                    alert("it moved successfully ");
33507 tejus.loha 690
                } else {
691
                    //nothing
692
                }
693
 
694
            });
695
    } else {
696
        alert("Please choose RBM ");
697
    }
698
 
699
});
700
 
33617 tejus.loha 701
$(document).on('click', "#downloadAllLoiForm", function () {
702
    const from = $('input[name="from"]').val();
703
    const to = $('input[name="to"]').val();
704
    let missingFields = [];
705
    if (!from) missingFields.push('From date');
706
    if (!to) missingFields.push('To date');
707
    if (missingFields.length > 0) {
708
        alert('Please select : ' + missingFields.join(','));
709
        return;
710
    }
711
    window.location.href = `${context}/downloadLoiFromReport?from=${from}&to=${to}`;
712
});
33658 tejus.loha 713
$(document).on('click', ".brandFeePaymentEdit", function () {
714
    var bfcId = $(this).val();
34310 tejus.loha 715
 
33658 tejus.loha 716
    // Get the table row
717
    var $row = $(this).closest('tr');
718
    var feeCollectingTimeStamp = $row.find('input[name="feeCollectingTimeStamp"]').val();
719
    var collectedAmount = $row.find('input[name="collectedAmount"]').val();
720
    var paymentReferenceNo = $row.find('input[name="paymentReferenceNo"]').val();
721
    var paymentMode = $row.find('select[name="paymentMode"]').val();
33885 tejus.loha 722
    var documentId = $row.find('input[name="documentId"]').val();
723
 
33658 tejus.loha 724
    const Data = {
725
        id: bfcId,
726
        feeCollectingTimeStamp: feeCollectingTimeStamp,
727
        collectedAmount: collectedAmount,
728
        paymentReferenceNo: paymentReferenceNo,
34745 aman.kumar 729
        paymentAttachment: documentId,
33658 tejus.loha 730
        paymentMode: paymentMode
731
    };
732
    var jsonData = JSON.stringify(Data);
733
    if (confirm("Are you sure to update details")) {
734
        doPostAjaxRequestWithJsonHandler(`${context}/updatePayment`, jsonData,
735
            function (response) {
33845 tejus.loha 736
                if (response) {
737
                    alert("Updated payment details are save successfully ")
738
                    pendingLoiForm('main-content');
739
                } else {
740
                    alert("Updated payment details are not save ")
741
                    pendingLoiForm('main-content');
742
                }
33658 tejus.loha 743
            });
744
    } else {
745
        pendingLoiForm('main-content');
746
    }
33617 tejus.loha 747
 
33658 tejus.loha 748
 
749
});
33879 tejus.loha 750
/*function validateOTP() {
751
    while (true) {
752
        let otp = prompt("Enter received OTP here");
753
        if (otp === null) {
754
            alert('OTP entry was cancelled. Try again.');
755
            return null;
756
        }
757
        let regex = /^[0-9]{5}$/;
758
        if (regex.test(otp)) {
759
            console.log('otp-flag-', otp);
760
            return otp;  // Return valid OTP
761
        } else {
762
            alert('Please enter a valid 5-digit numeric OTP');
763
        }
764
    }
765
}*/
33658 tejus.loha 766
 
33879 tejus.loha 767
$(document).on('click', "#confirmSign", function () {
37632 aman 768
    let btn = $(this);
769
    let loiId = btn.val();
770
    if (btn.prop('disabled')) return false;
33879 tejus.loha 771
    let otp = prompt("Enter received OTP here");
37632 aman 772
    if (otp === undefined || otp === null) {
773
        return false;
774
    }
775
    otp = otp.trim();
776
    if (!otp) {
777
        alert("Please enter the OTP received by the partner.");
778
        return false;
779
    }
780
    let validateOtpUrl = `${context}/validateLoiOtp?loiId=${loiId}&provideOtp=${encodeURIComponent(otp)}`;
33658 tejus.loha 781
 
37632 aman 782
    // Once the OTP is accepted the LOI is only half signed: the server has the OTP but not the
783
    // signed PDF, and the partner mail + onboarding only happen in /saveLoiDoc. Every failure from
784
    // here on must say that plainly - a silent failure here left LOIs stuck with no mail.
785
    function signNotSaved(reason) {
786
        btn.prop('disabled', false);
787
        alert("OTP was verified, but the signed LOI was NOT saved.\nReason: " + reason
788
            + "\n\nNothing has been emailed to the partner. Click Send OTP to get a new OTP, then Confirm Sign again."
789
            + " Keep this page open until you see the \"LOI has been signed successfully\" message.");
790
    }
791
 
792
    btn.prop('disabled', true);
793
    $.ajax({
794
        url: validateOtpUrl,
795
        type: 'PUT',
796
        cache: false,
797
        suppressGlobalError: true,
798
        success: function (response) {
35038 aman 799
            console.log('OTP validation response:', response);
800
 
801
            if (response && response.response && response.response.success) {
37632 aman 802
                // html2pdf comes from cdnjs; if that script was blocked, the old code threw a
803
                // ReferenceError right here and the operator saw nothing at all.
804
                if (typeof html2pdf !== 'function') {
805
                    signNotSaved("the PDF library did not load in this browser (check internet / try Chrome, then reload the page)");
806
                    return;
807
                }
808
                let tempContainer = null;
809
                try {
810
                    const docHash = (response.response.documentHash || "");
811
                    const ip = response.response.ipAddress || "";
812
                    const createdAt = response.response.createdAt || new Date().toLocaleString();
813
                    const watermarkText =
814
                        `OTP VERIFIED\n` +
815
                        `DOCUMENT HASH:\n ${docHash}\n` +
816
                        `IP ADDRESS: ${ip}\n` +
817
                        `CREATED ON: ${createdAt}`;
818
                    const originalElement = document.getElementById('loiPDF_content');
819
                    const clonedElement = originalElement.cloneNode(true);
820
                    const existingStyles = clonedElement.querySelectorAll('style');
821
                    existingStyles.forEach(style => style.remove());
822
                    $(clonedElement).find('.pending-badge, .pending-indicator').remove();
823
                    $(clonedElement).find('.signature-section').each(function () {
824
                        this.style.setProperty('position', 'relative', 'important');
825
                        this.style.setProperty('padding', '20px', 'important');
826
                    });
35038 aman 827
 
37632 aman 828
                    const signatureSections = clonedElement.querySelectorAll('.signature-section');
829
                    signatureSections.forEach(section => {
830
                        const oldWatermarks = section.querySelectorAll('.watermark-overlay');
831
                        oldWatermarks.forEach(w => w.remove());
35038 aman 832
 
37632 aman 833
                        const watermarkDiv = document.createElement('div');
834
                        watermarkDiv.className = 'watermark-overlay';
835
                        watermarkDiv.textContent = watermarkText;
836
                        watermarkDiv.style.position = 'absolute';
837
                        watermarkDiv.style.fontSize = '7px';
838
                        watermarkDiv.style.top = '30px';
839
                        watermarkDiv.style.left = '1%';
840
                        watermarkDiv.style.color = 'rgb(4,97,225)';
841
                        watermarkDiv.style.fontWeight = 'bold';
842
                        watermarkDiv.style.fontFamily = 'Arial,sans-serif';
843
                        watermarkDiv.style.whiteSpace = 'pre-line';
844
                        watermarkDiv.style.textAlign = 'center';
845
                        watermarkDiv.style.pointerEvents = 'none';
846
                        watermarkDiv.style.width = '90%';
847
                        watermarkDiv.style.lineHeight = '1.7';
848
                        watermarkDiv.style.zIndex = '1';
849
                        watermarkDiv.style.userSelect = 'none';
35038 aman 850
 
37632 aman 851
                        section.style.position = 'relative';
852
                        section.appendChild(watermarkDiv);
853
                    });
35038 aman 854
 
37632 aman 855
                    tempContainer = document.createElement('div');
856
                    tempContainer.style.position = 'absolute';
857
                    tempContainer.style.left = '-9999px';
858
                    tempContainer.style.width = '800px';
859
                    tempContainer.appendChild(clonedElement);
860
                    document.body.appendChild(tempContainer);
35038 aman 861
 
37632 aman 862
                    const opt = {
863
                        margin: [0.5, 0.5, 0.5, 0.5],
864
                        filename: `LOI_${loiId}_${new Date().getTime()}.pdf`,
865
                        image: {
866
                            type: 'jpeg',
867
                            quality: 0.98
868
                        },
869
                        html2canvas: {
870
                            scale: 1.2,
871
                            logging: false,
872
                            useCORS: true,
873
                            allowTaint: false,
874
                            backgroundColor: '#ffffff'
875
                        },
876
                        jsPDF: {
877
                            unit: 'in',
878
                            format: 'letter',
879
                            orientation: 'portrait'
880
                        }
881
                    };
35038 aman 882
 
37632 aman 883
                    html2pdf().from(clonedElement).set(opt).outputPdf("arraybuffer")
884
                        .then(function (pdf) {
885
                            document.body.removeChild(tempContainer);
35038 aman 886
 
37632 aman 887
                            const file = new File([pdf], `LOI_${loiId}_signed.pdf`, {type: 'application/pdf'});
35038 aman 888
 
37632 aman 889
                            uploadDocument(file, function (documentId) {
890
                                IdempotencyKey = uuidv4();
891
                                saveLoiDoc(loiId, documentId, signNotSaved);
892
                            }, function (message) {
893
                                signNotSaved("upload failed - " + message);
894
                            });
895
                        })
896
                        .catch(function (error) {
897
                            console.error('PDF generation failed:', error);
898
                            if (tempContainer && tempContainer.parentNode) {
899
                                tempContainer.parentNode.removeChild(tempContainer);
35038 aman 900
                            }
37632 aman 901
                            signNotSaved("the PDF could not be generated in this browser (" + (error && error.message ? error.message : error) + ")");
35038 aman 902
                        });
37632 aman 903
                } catch (error) {
904
                    console.error('Signed LOI build failed:', error);
905
                    if (tempContainer && tempContainer.parentNode) {
906
                        tempContainer.parentNode.removeChild(tempContainer);
907
                    }
908
                    signNotSaved("the signed PDF could not be prepared (" + (error && error.message ? error.message : error) + ")");
909
                }
35038 aman 910
            } else {
911
                console.error('OTP validation failed:', response);
37632 aman 912
                btn.prop('disabled', false);
913
                alert("OTP validation failed: " + (response && response.response && response.response.message ? response.response.message : "Please try again."));
33879 tejus.loha 914
            }
37632 aman 915
        },
916
        error: function (xhr) {
917
            btn.prop('disabled', false);
918
            alert("OTP not accepted: " + uploadErrorMessage(xhr));
919
        }
920
    });
33879 tejus.loha 921
});
922
 
923
 
37632 aman 924
function saveLoiDoc(loiId, documentId, onFailure) {
925
    let saveLoiDocUrl = `${context}/saveLoiDoc?loiId=` + loiId + `&loiDocId=` + documentId;
926
    $.ajax({
927
        url: saveLoiDocUrl,
928
        type: 'POST',
929
        cache: false,
930
        suppressGlobalError: true,
931
        success: function (response) {
932
            // The "response" view renders the bare boolean, so a failure arrives as the string "false".
933
            if (response === true || String(response).trim() === 'true') {
934
                alert("LOI has been signed successfully and sent to the registered email. Please check your email.");
935
                pendingLoiForm("main-content");
936
            } else {
937
                onFailure("the server did not accept the signed document");
938
            }
939
        },
940
        error: function (xhr) {
941
            onFailure("saving failed - " + uploadErrorMessage(xhr));
33879 tejus.loha 942
        }
943
    });
944
}
945
 
946
 
33507 tejus.loha 947
function pendingLoiForm(domId) {
33710 tejus.loha 948
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
33507 tejus.loha 949
        function (response) {
950
            $('#' + domId).html(response);
951
        });
952
}
34085 tejus.loha 953
 
954
/*
955
function createPagination(containerId, totalPages, currentPage = 1, onPageChange = null) {
956
    const $container = $('#' + containerId);
957
    $container.empty(); // Clear the container
958
 
959
    // Helper Function to Render Pagination
960
    function renderPagination(currentPage) {
961
        $container.empty();
962
 
963
        // Previous Button
964
        const $prevButton = $('<button>')
965
            .text('Previous')
966
            .click(() => handlePageChange(currentPage > 1 ? currentPage - 1 : totalPages)); // Loop to last page if on the first page
967
        $container.append($prevButton);
968
 
969
        // First Page
970
        const $firstPageButton = $('<button>')
971
            .text('1')
972
            .addClass(currentPage === 1 ? 'active' : '')
973
            .click(() => handlePageChange(1));
974
        $container.append($firstPageButton);
975
 
976
        // Ellipsis Before Current Pages
977
        if (currentPage > 3) {
978
            $container.append($('<span>').text('...'));
979
        }
980
 
981
        // Dynamic Pages Around Current Page
982
        for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
983
            const $pageButton = $('<button>')
984
                .text(i)
985
                .addClass(currentPage === i ? 'active' : '')
986
                .click(() => handlePageChange(i));
987
            $container.append($pageButton);
988
        }
989
 
990
        // Ellipsis Before Last Page
991
        if (currentPage < totalPages - 2) {
992
            $container.append($('<span>').text('...'));
993
        }
994
 
995
        // Last Page
996
        if (totalPages > 1) {
997
            const $lastPageButton = $('<button>')
998
                .text(totalPages)
999
                .addClass(currentPage === totalPages ? 'active' : '')
1000
                .click(() => handlePageChange(totalPages));
1001
            $container.append($lastPageButton);
1002
        }
1003
 
1004
        // Next Button
1005
        const $nextButton = $('<button>')
1006
            .text('Next')
1007
            .click(() => handlePageChange(currentPage < totalPages ? currentPage + 1 : 1)); // Loop to first page if on the last page
1008
        $container.append($nextButton);
1009
    }
1010
 
1011
    // Handle Page Change
1012
    function handlePageChange(selectedPage) {
1013
        if (onPageChange) {
1014
            onPageChange(selectedPage); // Trigger the callback with the selected page
1015
        }
1016
        renderPagination(selectedPage); // Re-render pagination
1017
    }
1018
 
1019
    // Initial Render
1020
    renderPagination(currentPage);
1021
}*/