Subversion Repositories SmartDukaan

Rev

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