Subversion Repositories SmartDukaan

Rev

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

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