Subversion Repositories SmartDukaan

Rev

Rev 36851 | Rev 37458 | 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');
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
 
37194 aman 449
function showOtpStatus(color, text) {
450
    $('#otp_status').show().css('color', color).text(text);
451
}
452
 
33507 tejus.loha 453
$(document).on('click', "#LOI_otp", function () {
35977 aman 454
    let btn = $(this);
455
    let loiId = btn.val();
456
    if (otpCountdownTimer) return;
457
    let isResend = btn.text().indexOf('Resend') >= 0;
458
    if (!isResend && !confirm("Are you sure to send OTP ?")) return;
37194 aman 459
    let previousText = btn.text();
35977 aman 460
    btn.prop('disabled', true).text('Sending...');
461
    doPostAjaxRequestHandler(`${context}/loiAcceptanceOtp?loiId=` + loiId,
462
        function (response) {
37194 aman 463
            let res = null;
464
            try {
465
                res = (typeof response === 'string' ? JSON.parse(response) : response);
466
            } catch (e) {
467
                res = null;
468
            }
469
            if (!res || typeof res.status === 'undefined') {
470
                showOtpStatus('red', 'Could not confirm the OTP was sent. Check with tech support before retrying.');
471
                btn.prop('disabled', false).text(previousText);
472
                return;
473
            }
474
            if (res.status && res.sent) {
475
                showOtpStatus('green', res.message || 'OTP sent.');
476
                startResendCountdown(btn);
477
            } else if (res.status) {
478
                // Accepted, but nothing was dispatched - the previous OTP is still valid (resend throttle).
479
                showOtpStatus('#c07000', 'No new OTP sent - ' + (res.message || 'the previous OTP is still valid.'));
480
                startResendCountdown(btn);
481
            } else {
482
                showOtpStatus('red', 'OTP NOT sent - ' + (res.message || 'unknown reason.'));
483
                btn.prop('disabled', false).text(previousText);
484
            }
485
        },
486
        function (xhr, msg) {
487
            showOtpStatus('red', 'OTP NOT sent - request failed (' + xhr.status + ').');
488
            btn.prop('disabled', false).text(previousText);
35977 aman 489
        });
33507 tejus.loha 490
});
491
 
492
//confirmPayment
33525 tejus.loha 493
$(document).on('click', ".paymentConfirmBtn", function () {
494
    let approval = $(this).data('approval');
33507 tejus.loha 495
    let bfcId = $(this).val();
33525 tejus.loha 496
    let description = "All details are correct";
497
    if (confirm("Are you sure to confirm this payment ?")) {
498
        doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
499
            function (response) {
33845 tejus.loha 500
                alert("Payment is confirm successfully");
33525 tejus.loha 501
                pendingLoiForm("main-content");
502
            });
503
    }
504
});
505
 
506
$(document).on('click', ".paymentRejectBtn", function () {
33507 tejus.loha 507
    let approval = $(this).data('approval');
33525 tejus.loha 508
    let bfcId = $(this).val();
509
    let description;
510
    description = prompt("Reason for rejection..");
511
    if (description !== null) {
512
        if (confirm("Are you sure to Reject this payment ?")) {
513
            doPutAjaxRequestHandler(`${context}/feePaymentApproval?bfcId=${bfcId}&feePaymentStatus=${approval}&description=${description}`,
514
                function (response) {
33845 tejus.loha 515
                    alert("Payment is rejected successfully");
33525 tejus.loha 516
                    pendingLoiForm("main-content");
517
                });
518
        }
519
    } else {
520
        alert("Please mention the reason as description and try again");
521
    }
33507 tejus.loha 522
});
34739 aman.kumar 523
$(document).on('click', ".deleteFeeCollection", function () {
524
    let bfcId = $(this).val();
525
    if (confirm("Are you sure you want to delete this payment entry?")) {
526
        doPutAjaxRequestHandler(
527
            `${context}/feePaymentDeletion?bfcId=${bfcId}`,
528
            function (response) {
529
                alert("Payment entry has been deleted successfully.");
530
                pendingLoiForm("main-content");
531
            }
532
        );
533
    }
534
});
535
 
33507 tejus.loha 536
$(document).on('click', ".upload-document-form", function () {
537
    let loiId = $(this).val();
33617 tejus.loha 538
    doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 539
        function (response) {
540
            $('#' + 'main-content').html(response);
541
        });
542
});
33885 tejus.loha 543
$(document).on('input', 'table#OnboardingDocumentTable input[type=file],table#mk_brand-fee-collection-details input[type=file]', function () {
544
    if (confirm('Confirm file upload ?')) {
545
        var fileSelector = $(this)[0];
546
        if (fileSelector != undefined
547
            && fileSelector.files[0] != undefined) {
548
            var file = this.files[0];
549
            let fileInput = $(this);
550
            uploadDocument(file, function (documentId) {
551
                fileInput.closest('td').find(".documentId").val(documentId);
552
            });
553
        }
554
    }
555
});
556
 
557
$(document).on('input', '#payment-sc-doc', function () {
558
    if (confirm('Confirm file upload ?')) {
559
        var file = this.files[0];
560
        uploadDocument(file, function (documentId) {
561
            $('#payment-sc-docId').val(documentId);
562
        });
563
    }
564
});
565
 
566
 
33507 tejus.loha 567
$(document).on('click', ".mk_docApproval", function () {
568
    let loiId = $(this).data('form_id');
569
    let docMasterId = $(this).data('doc_master_id');
570
    let flag = $(this).data('flag');
571
    doPutAjaxRequestHandler(`${context}/documentVerify?loiId=${loiId}&docMasterId=${docMasterId}&flag=${flag}`,
572
        function (response) {
573
            alert(response);
33617 tejus.loha 574
            doGetAjaxRequestHandler(`${context}/uploadDocumentForm?loiId=${loiId}`,
33507 tejus.loha 575
                function (response) {
576
                    $('#' + 'main-content').html(response);
577
                });
578
 
579
        });
580
});
581
$(document).on('click', "#uploadDocumentbtn1", function () {
582
    if (confirm("Are you sure to upload all documents ?")) {
583
        var loiId = $(this).val();
584
        var loiDocModels = [];
585
        $("#OnboardingDocumentTable > tbody > tr").each(function (rowIndex) {
586
            var marsterId = $(this).find(".masterId").val();
587
            var docId = $(this).find(".documentId").val();
588
            var docName = $(this).find(".documentName").val();
589
            var loiDocModel = {
590
                documentId: docId,
591
                documentName: docName,
592
                documentMasterId: marsterId
593
            };
594
            loiDocModels.push(loiDocModel);
595
        });
596
        var loiDocModelData = JSON.stringify(loiDocModels);
597
        doPostAjaxRequestWithJsonHandler(`${context}/uploadOnboardingDocument?loiId=${loiId}`, loiDocModelData, function (response) {
598
            pendingLoiForm("main-content");
599
        });
600
    } else {
601
        //Nothing to do
602
    }
603
 
604
 
605
});
606
 
607
$(document).on('click', ".CompletedLoiForm", function () {
33617 tejus.loha 608
    doGetAjaxRequestHandler(`${context}/completedLoiForms`,
33507 tejus.loha 609
        function (response) {
610
            $('#' + 'main-content').html(response);
611
        });
612
});
613
 
614
$(document).on('click', "#createNewOnboardingPanel", function () {
615
    let loiId = $(this).val();
33710 tejus.loha 616
    //let authId = $(this).closest('tr').find('.authId').val();
33507 tejus.loha 617
 
33710 tejus.loha 618
    if (true) {
619
 
620
        doPostAjaxRequestHandler(`${context}/createNewOnboardingPanel?loiId=${loiId}&authId=${0}`,
33507 tejus.loha 621
            function (response) {
622
                if (response) {
33710 tejus.loha 623
                    // doGetAjaxRequestHandler(`${context}/completedLoiForms`,
624
                    //     function (response) {
625
                    //         $('#' + 'main-content').html(response);
626
                    //     });
627
                    alert("it moved successfully ");
33507 tejus.loha 628
                } else {
629
                    //nothing
630
                }
631
 
632
            });
633
    } else {
634
        alert("Please choose RBM ");
635
    }
636
 
637
});
638
 
33617 tejus.loha 639
$(document).on('click', "#downloadAllLoiForm", function () {
640
    const from = $('input[name="from"]').val();
641
    const to = $('input[name="to"]').val();
642
    let missingFields = [];
643
    if (!from) missingFields.push('From date');
644
    if (!to) missingFields.push('To date');
645
    if (missingFields.length > 0) {
646
        alert('Please select : ' + missingFields.join(','));
647
        return;
648
    }
649
    window.location.href = `${context}/downloadLoiFromReport?from=${from}&to=${to}`;
650
});
33658 tejus.loha 651
$(document).on('click', ".brandFeePaymentEdit", function () {
652
    var bfcId = $(this).val();
34310 tejus.loha 653
 
33658 tejus.loha 654
    // Get the table row
655
    var $row = $(this).closest('tr');
656
    var feeCollectingTimeStamp = $row.find('input[name="feeCollectingTimeStamp"]').val();
657
    var collectedAmount = $row.find('input[name="collectedAmount"]').val();
658
    var paymentReferenceNo = $row.find('input[name="paymentReferenceNo"]').val();
659
    var paymentMode = $row.find('select[name="paymentMode"]').val();
33885 tejus.loha 660
    var documentId = $row.find('input[name="documentId"]').val();
661
 
33658 tejus.loha 662
    const Data = {
663
        id: bfcId,
664
        feeCollectingTimeStamp: feeCollectingTimeStamp,
665
        collectedAmount: collectedAmount,
666
        paymentReferenceNo: paymentReferenceNo,
34745 aman.kumar 667
        paymentAttachment: documentId,
33658 tejus.loha 668
        paymentMode: paymentMode
669
    };
670
    var jsonData = JSON.stringify(Data);
671
    if (confirm("Are you sure to update details")) {
672
        doPostAjaxRequestWithJsonHandler(`${context}/updatePayment`, jsonData,
673
            function (response) {
33845 tejus.loha 674
                if (response) {
675
                    alert("Updated payment details are save successfully ")
676
                    pendingLoiForm('main-content');
677
                } else {
678
                    alert("Updated payment details are not save ")
679
                    pendingLoiForm('main-content');
680
                }
33658 tejus.loha 681
            });
682
    } else {
683
        pendingLoiForm('main-content');
684
    }
33617 tejus.loha 685
 
33658 tejus.loha 686
 
687
});
33879 tejus.loha 688
/*function validateOTP() {
689
    while (true) {
690
        let otp = prompt("Enter received OTP here");
691
        if (otp === null) {
692
            alert('OTP entry was cancelled. Try again.');
693
            return null;
694
        }
695
        let regex = /^[0-9]{5}$/;
696
        if (regex.test(otp)) {
697
            console.log('otp-flag-', otp);
698
            return otp;  // Return valid OTP
699
        } else {
700
            alert('Please enter a valid 5-digit numeric OTP');
701
        }
702
    }
703
}*/
33658 tejus.loha 704
 
33879 tejus.loha 705
$(document).on('click', "#confirmSign", function () {
706
    let loiId = $(this).val();
707
    let otp = prompt("Enter received OTP here");
708
    let validateOtpUrl = `${context}/validateLoiOtp?loiId=${loiId}&provideOtp=${otp}`;
33658 tejus.loha 709
 
35038 aman 710
    if (otp !== undefined && otp !== null) {
33879 tejus.loha 711
        doPutAjaxRequestHandler(validateOtpUrl, function (response) {
35038 aman 712
            console.log('OTP validation response:', response);
713
 
714
            if (response && response.response && response.response.success) {
715
                const docHash = (response.response.documentHash || "");
716
                const ip = response.response.ipAddress || "";
717
                const createdAt = response.response.createdAt || new Date().toLocaleString();
718
                const watermarkText =
719
                    `OTP VERIFIED\n` +
720
                    `DOCUMENT HASH:\n ${docHash}\n` +
721
                    `IP ADDRESS: ${ip}\n` +
722
                    `CREATED ON: ${createdAt}`;
723
                const originalElement = document.getElementById('loiPDF_content');
724
                const clonedElement = originalElement.cloneNode(true);
725
                const existingStyles = clonedElement.querySelectorAll('style');
726
                existingStyles.forEach(style => style.remove());
727
                $(clonedElement).find('.pending-badge, .pending-indicator').remove();
728
                $(clonedElement).find('.signature-section').each(function () {
729
                    this.style.setProperty('position', 'relative', 'important');
730
                    this.style.setProperty('padding', '20px', 'important');
731
                });
732
 
733
                const signatureSections = clonedElement.querySelectorAll('.signature-section');
734
                signatureSections.forEach(section => {
735
                    const oldWatermarks = section.querySelectorAll('.watermark-overlay');
736
                    oldWatermarks.forEach(w => w.remove());
737
 
738
                    const watermarkDiv = document.createElement('div');
739
                    watermarkDiv.className = 'watermark-overlay';
740
                    watermarkDiv.textContent = watermarkText;
741
                    watermarkDiv.style.position = 'absolute';
742
                    watermarkDiv.style.fontSize = '7px';
743
                    watermarkDiv.style.top = '30px';
744
                    watermarkDiv.style.left = '1%';
745
                    watermarkDiv.style.color = 'rgb(4,97,225)';
746
                    watermarkDiv.style.fontWeight = 'bold';
747
                    watermarkDiv.style.fontFamily = 'Arial,sans-serif';
748
                    watermarkDiv.style.whiteSpace = 'pre-line';
749
                    watermarkDiv.style.textAlign = 'center';
750
                    watermarkDiv.style.pointerEvents = 'none';
751
                    watermarkDiv.style.width = '90%';
752
                    watermarkDiv.style.lineHeight = '1.7';
753
                    watermarkDiv.style.zIndex = '1';
754
                    watermarkDiv.style.userSelect = 'none';
755
 
756
                    section.style.position = 'relative';
757
                    section.appendChild(watermarkDiv);
758
                });
759
 
760
                const tempContainer = document.createElement('div');
761
                tempContainer.style.position = 'absolute';
762
                tempContainer.style.left = '-9999px';
763
                tempContainer.style.width = '800px';
764
                tempContainer.appendChild(clonedElement);
765
                document.body.appendChild(tempContainer);
766
 
33879 tejus.loha 767
                const opt = {
35038 aman 768
                    margin: [0.5, 0.5, 0.5, 0.5],
769
                    filename: `LOI_${loiId}_${new Date().getTime()}.pdf`,
770
                    image: {
771
                        type: 'jpeg',
772
                        quality: 0.98
773
                    },
774
                    html2canvas: {
775
                        scale: 1.2,
776
                        logging: false,
777
                        useCORS: true,
778
                        allowTaint: false,
779
                        backgroundColor: '#ffffff'
780
                    },
781
                    jsPDF: {
782
                        unit: 'in',
783
                        format: 'letter',
784
                        orientation: 'portrait'
785
                    }
33879 tejus.loha 786
                };
35038 aman 787
 
788
                html2pdf().from(clonedElement).set(opt).outputPdf("arraybuffer")
789
                    .then(function (pdf) {
790
                        document.body.removeChild(tempContainer);
791
 
792
                        const file = new Blob([pdf], {type: 'application/pdf'});
793
 
794
                        uploadDocument(file, function (documentId) {
795
                            IdempotencyKey = uuidv4();
796
                            if (documentId > 0) {
797
                                saveLoiDoc(loiId, documentId);
798
                                alert("Document signed and saved successfully!");
799
                            } else {
800
                                alert("Something went wrong, please try again to confirm OTP");
801
                            }
802
                        });
803
                    })
804
                    .catch(function (error) {
805
                        console.error('PDF generation failed:', error);
806
                        document.body.removeChild(tempContainer);
807
                        alert("PDF generation failed. Please try again.");
33879 tejus.loha 808
                    });
35038 aman 809
            } else {
810
                console.error('OTP validation failed:', response);
811
                alert("OTP validation failed: " + (response.response?.message || "Please try again."));
33879 tejus.loha 812
            }
35038 aman 813
        }, function (error) {
814
            console.error('AJAX request failed:', error);
815
            alert("Request failed. Please check your connection and try again.");
33879 tejus.loha 816
        });
817
    } else {
34310 tejus.loha 818
        return false;
33879 tejus.loha 819
    }
820
});
821
 
822
 
823
function saveLoiDoc(loiId, documentId) {
824
    let saveLoiDocUrl = `${context}/saveLoiDoc?loiId=` + loiId + `&loiDocId=` + documentId
825
    doPostAjaxRequestHandler(saveLoiDocUrl, function (response) {
826
        if (response) {
827
            alert("LOI has been signed successfully and sent to the registered email. Please check your email.");
828
            pendingLoiForm("main-content");
829
        } else {
830
            alert("Something went wrong , Please try again to generate Loi and Validate otp");
831
        }
832
    });
833
}
834
 
835
 
33507 tejus.loha 836
function pendingLoiForm(domId) {
33710 tejus.loha 837
    doGetAjaxRequestHandler(`${context}/pendingLoiForm`,
33507 tejus.loha 838
        function (response) {
839
            $('#' + domId).html(response);
840
        });
841
}
34085 tejus.loha 842
 
843
/*
844
function createPagination(containerId, totalPages, currentPage = 1, onPageChange = null) {
845
    const $container = $('#' + containerId);
846
    $container.empty(); // Clear the container
847
 
848
    // Helper Function to Render Pagination
849
    function renderPagination(currentPage) {
850
        $container.empty();
851
 
852
        // Previous Button
853
        const $prevButton = $('<button>')
854
            .text('Previous')
855
            .click(() => handlePageChange(currentPage > 1 ? currentPage - 1 : totalPages)); // Loop to last page if on the first page
856
        $container.append($prevButton);
857
 
858
        // First Page
859
        const $firstPageButton = $('<button>')
860
            .text('1')
861
            .addClass(currentPage === 1 ? 'active' : '')
862
            .click(() => handlePageChange(1));
863
        $container.append($firstPageButton);
864
 
865
        // Ellipsis Before Current Pages
866
        if (currentPage > 3) {
867
            $container.append($('<span>').text('...'));
868
        }
869
 
870
        // Dynamic Pages Around Current Page
871
        for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
872
            const $pageButton = $('<button>')
873
                .text(i)
874
                .addClass(currentPage === i ? 'active' : '')
875
                .click(() => handlePageChange(i));
876
            $container.append($pageButton);
877
        }
878
 
879
        // Ellipsis Before Last Page
880
        if (currentPage < totalPages - 2) {
881
            $container.append($('<span>').text('...'));
882
        }
883
 
884
        // Last Page
885
        if (totalPages > 1) {
886
            const $lastPageButton = $('<button>')
887
                .text(totalPages)
888
                .addClass(currentPage === totalPages ? 'active' : '')
889
                .click(() => handlePageChange(totalPages));
890
            $container.append($lastPageButton);
891
        }
892
 
893
        // Next Button
894
        const $nextButton = $('<button>')
895
            .text('Next')
896
            .click(() => handlePageChange(currentPage < totalPages ? currentPage + 1 : 1)); // Loop to first page if on the last page
897
        $container.append($nextButton);
898
    }
899
 
900
    // Handle Page Change
901
    function handlePageChange(selectedPage) {
902
        if (onPageChange) {
903
            onPageChange(selectedPage); // Trigger the callback with the selected page
904
        }
905
        renderPagination(selectedPage); // Re-render pagination
906
    }
907
 
908
    // Initial Render
909
    renderPagination(currentPage);
910
}*/