Subversion Repositories SmartDukaan

Rev

Rev 36845 | 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');
33885 tejus.loha 234
    if (!paymentAttachment) missingFields.push('Payment screenshot ');
33577 tejus.loha 235
    if (missingFields.length > 0) {
236
        alert('The following fields are required: ' + missingFields.join(', '));
237
        return;
238
    }
239
    const loiFormData = {
240
        referId: referId,
34107 tejus.loha 241
        stateHead: stateHead,
242
        bdm: bdm,
33577 tejus.loha 243
        businessType: businessType,
33582 tejus.loha 244
        acquiredDate: acquiredDate,
33577 tejus.loha 245
        firstName: firstName,
246
        lastName: lastName,
247
        mobile: mobile,
248
        email: email,
249
        landline: landline,
250
        dob: dob,
251
        anniversaryDate: anniversaryDate,
252
        panNo: panNo,
253
        adharNo: adharNo,
254
        gstNo: gstNo,
255
        bankName: bankName,
256
        ifscCode: ifscCode,
257
        accountNo: accountNo,
258
        companyName: companyName,
259
        gstPin: gstPin,
260
        gstState: gstState,
261
        gstCity: gstCity,
262
        gstDistrict: gstDistrict,
263
        agreeWalletValue: agreeWalletValue,
264
        storeArea: storeArea,
265
        storePotential: storePotential,
35971 aman 266
        financeOptions: financeOptions,
33577 tejus.loha 267
        lessCommitReason: lessCommitReason,
268
        agreedBrandFees: agreedBrandFees,
269
        brandFeesCollected: brandFeesCollected,
270
        paymentMode: paymentMode,
271
        paymentReferenceNo: paymentReferenceNo,
33578 tejus.loha 272
        feeCollectingTimeStamp: feeCollectingDate,
33885 tejus.loha 273
        paymentAttachment: paymentAttachment,
33658 tejus.loha 274
        billingAddress: billingAddress,
275
        brandCommitment: brandCommitment
33577 tejus.loha 276
    };
33658 tejus.loha 277
 
33577 tejus.loha 278
    if (confirm("Are you sure to submit the form ?")) {
279
        doPostAjaxRequestWithJsonHandler(`${context}/submitLoiForm`, JSON.stringify(loiFormData), function (response) {
280
            console.log('responsee', response);
33507 tejus.loha 281
            if (response) {
282
                alert("Your LOI form Submitted successfully ");
283
                pendingLoiForm("main-content");
284
 
285
            } else {
286
                alert("Your LOI form not Submitted , try again ");
33845 tejus.loha 287
                doGetAjaxRequestHandler(`${context}/loiForm`,
33507 tejus.loha 288
                    function (response) {
289
                        $('#' + 'main-content').html(response);
290
                    });
291
            }
292
        });
293
    }
294
});
33578 tejus.loha 295
 
33658 tejus.loha 296
$(document).on('click', ".updateLoiForm", function () {
33507 tejus.loha 297
    let loiId = $(this).val();
33658 tejus.loha 298
    doGetAjaxRequestHandler(context + "/updateLoiForm?loiId=" + loiId,
33507 tejus.loha 299
        function (response) {
300
            $('#' + 'main-content').html(response);
301
        });
302
});
33879 tejus.loha 303
 
33710 tejus.loha 304
$(document).on('click', ".save_agree_brand_fee", function () {
305
    let loiId = $(this).val();
306
    var $tr = $(this).closest('tr');
307
    var agreedBrandFee = $tr.find('input[name="brandFee"]').val();
34085 tejus.loha 308
    var brandType = $tr.find('select[name="brandType"]').val();
33710 tejus.loha 309
    if (confirm("Are you sure to change Agreed brand fee")) {
34085 tejus.loha 310
        doPutAjaxRequestHandler(`${context}/updateAgreedBrandFee?loiId=${loiId}&brandFee=${agreedBrandFee}&storeType=${brandType}`, function (response) {
33710 tejus.loha 311
            pendingLoiForm("main-content");
312
        });
313
    } else {
314
        pendingLoiForm("main-content");
315
    }
316
});
33507 tejus.loha 317
 
33658 tejus.loha 318
$(document).on('click', ".updateLoiFormDataButton", function () {
319
    let loiId = $(this).data('loiid');
320
    const firstName = $('input[name="firstName"]').val();
321
    const lastName = $('input[name="lastName"]').val();
322
    const mobile = $('input[name="mobile"]').val();
323
    const email = $('input[name="email"]').val();
324
    const landline = $('input[name="landline"]').val();
325
    const dob = $('input[name="dob"]').val();
326
    const panNo = $('input[name="panNo"]').val();
327
    const adharNo = $('input[name="adharNo"]').val();
328
    let missingFields = [];
329
    if (!firstName) missingFields.push('First Name');
330
    if (!lastName) missingFields.push('Last Name');
331
    if (mobile.length < 10 || !mobile) {
332
        missingFields.push('Mobile number should be 10 digit');
333
    }
334
    if (!dob) missingFields.push('dob(Date of Birth)');
335
    if (!panNo) missingFields.push('Pan Number');
336
    if (!adharNo) missingFields.push('Aadhar Number');
337
    if (!email) missingFields.push('Email');
338
    if (missingFields.length > 0) {
339
        alert('The following fields are required: ' + missingFields.join(', '));
340
        return;
341
    }
342
    const loiFormData = {
343
        firstName: firstName,
344
        lastName: lastName,
345
        mobile: mobile,
346
        email: email,
347
        landline: landline,
348
        dob: dob,
349
        panNo: panNo,
350
        adharNo: adharNo
351
    };
352
    alert("you want update ..");
353
    doPostAjaxRequestWithJsonHandler(`${context}/updateLoiFormData?loiId=${loiId}`, JSON.stringify(loiFormData), function (response) {
33507 tejus.loha 354
        pendingLoiForm("main-content");
355
    });
356
 
357
});
358
 
359
$(document).on('click', ".pending-onboarding-form", function () {
33710 tejus.loha 360
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
33507 tejus.loha 361
        function (response) {
362
            $('#' + 'main-content').html(response);
363
        });
364
});
365
$(document).on('click', "#addBrandFeePayment", function () {
35971 aman 366
    var $btn = $(this);
367
    if ($btn.prop('disabled')) return false;
33507 tejus.loha 368
    let formData = objectifyForm($("form[name='brandFeeCollectionForm']").serializeArray());
35971 aman 369
    let loiId = $btn.val();
33507 tejus.loha 370
    for (var key in formData) {
371
        if (formData.hasOwnProperty(key) && formData[key].trim() === '') {
372
            alert("The (" + key + ") value is blank please fill this field !");
373
            return false;
374
        }
375
    }
376
    let jsonData = JSON.stringify(formData);
33658 tejus.loha 377
    if (confirm("Are you sure to add payment ?")) {
35971 aman 378
        $btn.prop('disabled', true);
33525 tejus.loha 379
        doPostAjaxRequestWithJsonHandler(`${context}/brandfeeCollection?loiId=` + loiId, jsonData, function (response) {
380
            if (response) {
381
                alert("Payment add successfully...");
35971 aman 382
                $('#brandFeeCollectionModel').modal('hide');
33525 tejus.loha 383
                pendingLoiForm("main-content");
384
            }
35971 aman 385
            $btn.prop('disabled', false);
33525 tejus.loha 386
        });
387
    } else {
33658 tejus.loha 388
        alert("Payment is not add.");
33525 tejus.loha 389
    }
33507 tejus.loha 390
});
391
 
392
$(document).on('click', ".generateLoi", function () {
393
    let loiId = $(this).val();
394
    doGetAjaxRequestHandler(context + "/generateLoi?loiId=" + loiId,
395
        function (response) {
396
            $('#' + 'main-content').html(response);
397
        });
398
});
399
 
34085 tejus.loha 400
// $(document).on('change', 'select[name="pageSize"]', function () {
401
//     let pageSize = $(this).val();
402
//     console.log("pageSize - ", pageSize);
403
//     doGetAjaxRequestHandler(`${context}/pendingLoiForm?pageSize=${pageSize}&pageNumber=${1}`,
404
//         function (response) {
405
//             $('#' + 'main-content').html(response);
406
//         });
407
// });
408
 
33845 tejus.loha 409
$(document).on('click', ".mk-approve-loi", function () {
410
    let loiId = $(this).val();
411
    let companyName = $(this).data('company');
412
    let flag = $(this).data('flag');
413
    if (flag === 1) {
414
        if (confirm(`Are you sure Approve Loi of  ${companyName} `)) {
415
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${true}`,
416
                function (response) {
417
                    alert("Loi Approved successfully");
418
                    pendingLoiForm("main-content");
419
                });
420
        }
421
    } else {
422
        if (confirm(`Are you sure to Reject "${companyName}" LOI`)) {
423
            doPutAjaxRequestHandler(`${context}/approve-reject-Loi?loiId=${loiId}&flag=${false}`,
424
                function (response) {
425
                    pendingLoiForm("main-content");
426
                });
427
        }
428
    }
429
});
430
 
35977 aman 431
var otpCountdownTimer = null;
432
 
433
function startResendCountdown(btn) {
434
    var remaining = 30;
435
    btn.prop('disabled', true).removeClass('btn-success').addClass('btn-warning');
436
    btn.text('Resend OTP (' + remaining + 's)');
437
    otpCountdownTimer = setInterval(function () {
438
        remaining--;
439
        if (remaining <= 0) {
440
            clearInterval(otpCountdownTimer);
441
            otpCountdownTimer = null;
442
            btn.text('Resend OTP').prop('disabled', false);
443
        } else {
444
            btn.text('Resend OTP (' + remaining + 's)');
445
        }
446
    }, 1000);
447
}
448
 
33507 tejus.loha 449
$(document).on('click', "#LOI_otp", function () {
35977 aman 450
    let btn = $(this);
451
    let loiId = btn.val();
452
    if (otpCountdownTimer) return;
453
    let isResend = btn.text().indexOf('Resend') >= 0;
454
    if (!isResend && !confirm("Are you sure to send OTP ?")) return;
455
    btn.prop('disabled', true).text('Sending...');
456
    doPostAjaxRequestHandler(`${context}/loiAcceptanceOtp?loiId=` + loiId,
457
        function (response) {
458
            $('#otp_status').show().text('OTP Sent Successfully!');
459
            startResendCountdown(btn);
460
        });
33507 tejus.loha 461
});
462
 
463
//confirmPayment
33525 tejus.loha 464
$(document).on('click', ".paymentConfirmBtn", function () {
465
    let approval = $(this).data('approval');
33507 tejus.loha 466
    let bfcId = $(this).val();
33525 tejus.loha 467
    let description = "All details are correct";
468
    if (confirm("Are you sure to confirm this payment ?")) {
469
        doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
470
            function (response) {
33845 tejus.loha 471
                alert("Payment is confirm successfully");
33525 tejus.loha 472
                pendingLoiForm("main-content");
473
            });
474
    }
475
});
476
 
477
$(document).on('click', ".paymentRejectBtn", function () {
33507 tejus.loha 478
    let approval = $(this).data('approval');
33525 tejus.loha 479
    let bfcId = $(this).val();
480
    let description;
481
    description = prompt("Reason for rejection..");
482
    if (description !== null) {
483
        if (confirm("Are you sure to Reject this payment ?")) {
484
            doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
485
                function (response) {
33845 tejus.loha 486
                    alert("Payment is rejected successfully");
33525 tejus.loha 487
                    pendingLoiForm("main-content");
488
                });
489
        }
490
    } else {
491
        alert("Please mention the reason as description and try again");
492
    }
33507 tejus.loha 493
});
34739 aman.kumar 494
$(document).on('click', ".deleteFeeCollection", function () {
495
    let bfcId = $(this).val();
496
    if (confirm("Are you sure you want to delete this payment entry?")) {
497
        doPutAjaxRequestHandler(
498
            `${context}/feePaymentDeletion?bfcId=${bfcId}`,
499
            function (response) {
500
                alert("Payment entry has been deleted successfully.");
501
                pendingLoiForm("main-content");
502
            }
503
        );
504
    }
505
});
506
 
33507 tejus.loha 507
$(document).on('click', ".upload-document-form", function () {
508
    let loiId = $(this).val();
33617 tejus.loha 509
    doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 510
        function (response) {
511
            $('#' + 'main-content').html(response);
512
        });
513
});
33885 tejus.loha 514
$(document).on('input', 'table#OnboardingDocumentTable input[type=file],table#mk_brand-fee-collection-details input[type=file]', function () {
515
    if (confirm('Confirm file upload ?')) {
516
        var fileSelector = $(this)[0];
517
        if (fileSelector != undefined
518
            && fileSelector.files[0] != undefined) {
519
            var file = this.files[0];
520
            let fileInput = $(this);
521
            uploadDocument(file, function (documentId) {
522
                fileInput.closest('td').find(".documentId").val(documentId);
523
            });
524
        }
525
    }
526
});
527
 
528
$(document).on('input', '#payment-sc-doc', function () {
529
    if (confirm('Confirm file upload ?')) {
530
        var file = this.files[0];
531
        uploadDocument(file, function (documentId) {
532
            $('#payment-sc-docId').val(documentId);
533
        });
534
    }
535
});
536
 
537
 
33507 tejus.loha 538
$(document).on('click', ".mk_docApproval", function () {
539
    let loiId = $(this).data('form_id');
540
    let docMasterId = $(this).data('doc_master_id');
541
    let flag = $(this).data('flag');
542
    doPutAjaxRequestHandler(`${context}/documentVerify?loiId=${loiId}&docMasterId=${docMasterId}&flag=${flag}`,
543
        function (response) {
544
            alert(response);
33617 tejus.loha 545
            doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 546
                function (response) {
547
                    $('#' + 'main-content').html(response);
548
                });
549
 
550
        });
551
});
552
$(document).on('click', "#uploadDocumentbtn1", function () {
553
    if (confirm("Are you sure to upload all documents ?")) {
554
        var loiId = $(this).val();
555
        var loiDocModels = [];
556
        $("#OnboardingDocumentTable > tbody > tr").each(function (rowIndex) {
557
            var marsterId = $(this).find(".masterId").val();
558
            var docId = $(this).find(".documentId").val();
559
            var docName = $(this).find(".documentName").val();
560
            var loiDocModel = {
561
                documentId: docId,
562
                documentName: docName,
563
                documentMasterId: marsterId
564
            };
565
            loiDocModels.push(loiDocModel);
566
        });
567
        var loiDocModelData = JSON.stringify(loiDocModels);
568
        doPostAjaxRequestWithJsonHandler(`${context}/uploadOnboardingDocument?loiId=${loiId}`, loiDocModelData, function (response) {
569
            pendingLoiForm("main-content");
570
        });
571
    } else {
572
        //Nothing to do
573
    }
574
 
575
 
576
});
577
 
578
$(document).on('click', ".CompletedLoiForm", function () {
33617 tejus.loha 579
    doGetAjaxRequestHandler(`${context}/completedLoiForms`,
33507 tejus.loha 580
        function (response) {
581
            $('#' + 'main-content').html(response);
582
        });
583
});
584
 
585
$(document).on('click', "#createNewOnboardingPanel", function () {
586
    let loiId = $(this).val();
33710 tejus.loha 587
    //let authId = $(this).closest('tr').find('.authId').val();
33507 tejus.loha 588
 
33710 tejus.loha 589
    if (true) {
590
 
591
        doPostAjaxRequestHandler(`${context}/createNewOnboardingPanel?loiId=${loiId}&authId=${0}`,
33507 tejus.loha 592
            function (response) {
593
                if (response) {
33710 tejus.loha 594
                    // doGetAjaxRequestHandler(`${context}/completedLoiForms`,
595
                    //     function (response) {
596
                    //         $('#' + 'main-content').html(response);
597
                    //     });
598
                    alert("it moved successfully ");
33507 tejus.loha 599
                } else {
600
                    //nothing
601
                }
602
 
603
            });
604
    } else {
605
        alert("Please choose RBM ");
606
    }
607
 
608
});
609
 
33617 tejus.loha 610
$(document).on('click', "#downloadAllLoiForm", function () {
611
    const from = $('input[name="from"]').val();
612
    const to = $('input[name="to"]').val();
613
    let missingFields = [];
614
    if (!from) missingFields.push('From date');
615
    if (!to) missingFields.push('To date');
616
    if (missingFields.length > 0) {
617
        alert('Please select : ' + missingFields.join(','));
618
        return;
619
    }
620
    window.location.href = `${context}/downloadLoiFromReport?from=${from}&to=${to}`;
621
});
33658 tejus.loha 622
$(document).on('click', ".brandFeePaymentEdit", function () {
623
    var bfcId = $(this).val();
34310 tejus.loha 624
 
33658 tejus.loha 625
    // Get the table row
626
    var $row = $(this).closest('tr');
627
    var feeCollectingTimeStamp = $row.find('input[name="feeCollectingTimeStamp"]').val();
628
    var collectedAmount = $row.find('input[name="collectedAmount"]').val();
629
    var paymentReferenceNo = $row.find('input[name="paymentReferenceNo"]').val();
630
    var paymentMode = $row.find('select[name="paymentMode"]').val();
33885 tejus.loha 631
    var documentId = $row.find('input[name="documentId"]').val();
632
 
33658 tejus.loha 633
    const Data = {
634
        id: bfcId,
635
        feeCollectingTimeStamp: feeCollectingTimeStamp,
636
        collectedAmount: collectedAmount,
637
        paymentReferenceNo: paymentReferenceNo,
34745 aman.kumar 638
        paymentAttachment: documentId,
33658 tejus.loha 639
        paymentMode: paymentMode
640
    };
641
    var jsonData = JSON.stringify(Data);
642
    if (confirm("Are you sure to update details")) {
643
        doPostAjaxRequestWithJsonHandler(`${context}/updatePayment`, jsonData,
644
            function (response) {
33845 tejus.loha 645
                if (response) {
646
                    alert("Updated payment details are save successfully ")
647
                    pendingLoiForm('main-content');
648
                } else {
649
                    alert("Updated payment details are not save ")
650
                    pendingLoiForm('main-content');
651
                }
33658 tejus.loha 652
            });
653
    } else {
654
        pendingLoiForm('main-content');
655
    }
33617 tejus.loha 656
 
33658 tejus.loha 657
 
658
});
33879 tejus.loha 659
/*function validateOTP() {
660
    while (true) {
661
        let otp = prompt("Enter received OTP here");
662
        if (otp === null) {
663
            alert('OTP entry was cancelled. Try again.');
664
            return null;
665
        }
666
        let regex = /^[0-9]{5}$/;
667
        if (regex.test(otp)) {
668
            console.log('otp-flag-', otp);
669
            return otp;  // Return valid OTP
670
        } else {
671
            alert('Please enter a valid 5-digit numeric OTP');
672
        }
673
    }
674
}*/
33658 tejus.loha 675
 
33879 tejus.loha 676
$(document).on('click', "#confirmSign", function () {
677
    let loiId = $(this).val();
678
    let otp = prompt("Enter received OTP here");
679
    let validateOtpUrl = `${context}/validateLoiOtp?loiId=${loiId}&provideOtp=${otp}`;
33658 tejus.loha 680
 
35038 aman 681
    if (otp !== undefined && otp !== null) {
33879 tejus.loha 682
        doPutAjaxRequestHandler(validateOtpUrl, function (response) {
35038 aman 683
            console.log('OTP validation response:', response);
684
 
685
            if (response && response.response && response.response.success) {
686
                const docHash = (response.response.documentHash || "");
687
                const ip = response.response.ipAddress || "";
688
                const createdAt = response.response.createdAt || new Date().toLocaleString();
689
                const watermarkText =
690
                    `OTP VERIFIED\n` +
691
                    `DOCUMENT HASH:\n ${docHash}\n` +
692
                    `IP ADDRESS: ${ip}\n` +
693
                    `CREATED ON: ${createdAt}`;
694
                const originalElement = document.getElementById('loiPDF_content');
695
                const clonedElement = originalElement.cloneNode(true);
696
                const existingStyles = clonedElement.querySelectorAll('style');
697
                existingStyles.forEach(style => style.remove());
698
                $(clonedElement).find('.pending-badge, .pending-indicator').remove();
699
                $(clonedElement).find('.signature-section').each(function () {
700
                    this.style.setProperty('position', 'relative', 'important');
701
                    this.style.setProperty('padding', '20px', 'important');
702
                });
703
 
704
                const signatureSections = clonedElement.querySelectorAll('.signature-section');
705
                signatureSections.forEach(section => {
706
                    const oldWatermarks = section.querySelectorAll('.watermark-overlay');
707
                    oldWatermarks.forEach(w => w.remove());
708
 
709
                    const watermarkDiv = document.createElement('div');
710
                    watermarkDiv.className = 'watermark-overlay';
711
                    watermarkDiv.textContent = watermarkText;
712
                    watermarkDiv.style.position = 'absolute';
713
                    watermarkDiv.style.fontSize = '7px';
714
                    watermarkDiv.style.top = '30px';
715
                    watermarkDiv.style.left = '1%';
716
                    watermarkDiv.style.color = 'rgb(4,97,225)';
717
                    watermarkDiv.style.fontWeight = 'bold';
718
                    watermarkDiv.style.fontFamily = 'Arial,sans-serif';
719
                    watermarkDiv.style.whiteSpace = 'pre-line';
720
                    watermarkDiv.style.textAlign = 'center';
721
                    watermarkDiv.style.pointerEvents = 'none';
722
                    watermarkDiv.style.width = '90%';
723
                    watermarkDiv.style.lineHeight = '1.7';
724
                    watermarkDiv.style.zIndex = '1';
725
                    watermarkDiv.style.userSelect = 'none';
726
 
727
                    section.style.position = 'relative';
728
                    section.appendChild(watermarkDiv);
729
                });
730
 
731
                const tempContainer = document.createElement('div');
732
                tempContainer.style.position = 'absolute';
733
                tempContainer.style.left = '-9999px';
734
                tempContainer.style.width = '800px';
735
                tempContainer.appendChild(clonedElement);
736
                document.body.appendChild(tempContainer);
737
 
33879 tejus.loha 738
                const opt = {
35038 aman 739
                    margin: [0.5, 0.5, 0.5, 0.5],
740
                    filename: `LOI_${loiId}_${new Date().getTime()}.pdf`,
741
                    image: {
742
                        type: 'jpeg',
743
                        quality: 0.98
744
                    },
745
                    html2canvas: {
746
                        scale: 1.2,
747
                        logging: false,
748
                        useCORS: true,
749
                        allowTaint: false,
750
                        backgroundColor: '#ffffff'
751
                    },
752
                    jsPDF: {
753
                        unit: 'in',
754
                        format: 'letter',
755
                        orientation: 'portrait'
756
                    }
33879 tejus.loha 757
                };
35038 aman 758
 
759
                html2pdf().from(clonedElement).set(opt).outputPdf("arraybuffer")
760
                    .then(function (pdf) {
761
                        document.body.removeChild(tempContainer);
762
 
763
                        const file = new Blob([pdf], {type: 'application/pdf'});
764
 
765
                        uploadDocument(file, function (documentId) {
766
                            IdempotencyKey = uuidv4();
767
                            if (documentId > 0) {
768
                                saveLoiDoc(loiId, documentId);
769
                                alert("Document signed and saved successfully!");
770
                            } else {
771
                                alert("Something went wrong, please try again to confirm OTP");
772
                            }
773
                        });
774
                    })
775
                    .catch(function (error) {
776
                        console.error('PDF generation failed:', error);
777
                        document.body.removeChild(tempContainer);
778
                        alert("PDF generation failed. Please try again.");
33879 tejus.loha 779
                    });
35038 aman 780
            } else {
781
                console.error('OTP validation failed:', response);
782
                alert("OTP validation failed: " + (response.response?.message || "Please try again."));
33879 tejus.loha 783
            }
35038 aman 784
        }, function (error) {
785
            console.error('AJAX request failed:', error);
786
            alert("Request failed. Please check your connection and try again.");
33879 tejus.loha 787
        });
788
    } else {
34310 tejus.loha 789
        return false;
33879 tejus.loha 790
    }
791
});
792
 
793
 
794
function saveLoiDoc(loiId, documentId) {
795
    let saveLoiDocUrl = `${context}/saveLoiDoc?loiId=` + loiId + `&loiDocId=` + documentId
796
    doPostAjaxRequestHandler(saveLoiDocUrl, function (response) {
797
        if (response) {
798
            alert("LOI has been signed successfully and sent to the registered email. Please check your email.");
799
            pendingLoiForm("main-content");
800
        } else {
801
            alert("Something went wrong , Please try again to generate Loi and Validate otp");
802
        }
803
    });
804
}
805
 
806
 
33507 tejus.loha 807
function pendingLoiForm(domId) {
33710 tejus.loha 808
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
33507 tejus.loha 809
        function (response) {
810
            $('#' + domId).html(response);
811
        });
812
}
34085 tejus.loha 813
 
814
/*
815
function createPagination(containerId, totalPages, currentPage = 1, onPageChange = null) {
816
    const $container = $('#' + containerId);
817
    $container.empty(); // Clear the container
818
 
819
    // Helper Function to Render Pagination
820
    function renderPagination(currentPage) {
821
        $container.empty();
822
 
823
        // Previous Button
824
        const $prevButton = $('<button>')
825
            .text('Previous')
826
            .click(() => handlePageChange(currentPage > 1 ? currentPage - 1 : totalPages)); // Loop to last page if on the first page
827
        $container.append($prevButton);
828
 
829
        // First Page
830
        const $firstPageButton = $('<button>')
831
            .text('1')
832
            .addClass(currentPage === 1 ? 'active' : '')
833
            .click(() => handlePageChange(1));
834
        $container.append($firstPageButton);
835
 
836
        // Ellipsis Before Current Pages
837
        if (currentPage > 3) {
838
            $container.append($('<span>').text('...'));
839
        }
840
 
841
        // Dynamic Pages Around Current Page
842
        for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
843
            const $pageButton = $('<button>')
844
                .text(i)
845
                .addClass(currentPage === i ? 'active' : '')
846
                .click(() => handlePageChange(i));
847
            $container.append($pageButton);
848
        }
849
 
850
        // Ellipsis Before Last Page
851
        if (currentPage < totalPages - 2) {
852
            $container.append($('<span>').text('...'));
853
        }
854
 
855
        // Last Page
856
        if (totalPages > 1) {
857
            const $lastPageButton = $('<button>')
858
                .text(totalPages)
859
                .addClass(currentPage === totalPages ? 'active' : '')
860
                .click(() => handlePageChange(totalPages));
861
            $container.append($lastPageButton);
862
        }
863
 
864
        // Next Button
865
        const $nextButton = $('<button>')
866
            .text('Next')
867
            .click(() => handlePageChange(currentPage < totalPages ? currentPage + 1 : 1)); // Loop to first page if on the last page
868
        $container.append($nextButton);
869
    }
870
 
871
    // Handle Page Change
872
    function handlePageChange(selectedPage) {
873
        if (onPageChange) {
874
            onPageChange(selectedPage); // Trigger the callback with the selected page
875
        }
876
        renderPagination(selectedPage); // Re-render pagination
877
    }
878
 
879
    // Initial Render
880
    renderPagination(currentPage);
881
}*/