PageSourceSearch

https://havells.com/static/version1790868634/frontend/Custom/defau…/js/validate-serial-number.js

js havells.com collected 2026-10-02 10:08:52 UTC 26,663 bytes, 612 lines download raw bytes

1require([
2    "jquery",
3    "mage/url",
4    "Magento_Ui/js/modal/confirm",
5    "Magento_Ui/js/modal/alert",
6    "mage/translate",
7    "jquery/ui",
8], function ($, urlBuilder, confirmation, alert, $t) {
9    $(window).on("load", function () {
10        const urlParams = new URLSearchParams(window.location.search);
11        if (urlParams.has("serial_number")) {
12            const serialNumber = urlParams.get("serial_number");
13            if (serialNumber) {
14                $("#serialnumber").val(serialNumber);
15                $(".verify-serial").click();
16            } else {
17                $("#error-inputDate").text(
18                    "Serial number is missing from the query parameters"
19                );
20            }
21            return;
22        }
23
24        const queryParams = window.location.search.substring(1);
25        if (queryParams && queryParams.length > 0) {
26            const serialNumber = queryParams;
27            $("#serialnumber").val(serialNumber);
28            $(".verify-serial").click();
29        }
30    });
31
32    $(document).ready(function () {
33        function getDeviceType() {
34            const userAgent = navigator.userAgent.toLowerCase();
35            if (
36                userAgent.includes("iphone") ||
37                userAgent.includes("ipod") ||
38                userAgent.includes("android") ||
39                userAgent.includes("blackberry") ||
40                userAgent.includes("windows phone")
41            ) {
42                return "mobile";
43            }
44            if (window.innerWidth <= 768) {
45                return "mobile";
46            }
47            return "desktop";
48        }
49
50        $(".product-register").hide();
51        $(".is-register").hide();
52        var today = new Date();
53        var formattedToday = today.toISOString().split("T")[0];
54        // Set the max attribute of the date input to today's date
55        document.getElementById("inputDate").setAttribute("max", formattedToday);
56
57        sendAjaxRequest("/registerproduct/api/checkislogin", function (response) {
58            if (response.success) {
59                var previousPageUrl = sessionStorage.getItem("previousPageUrl");
60                if (previousPageUrl) {
61                    var productDetails = sessionStorage.getItem("productDetails");
62                    if (productDetails) {
63                        productDetails = JSON.parse(productDetails);
64                        //Append register validate product data
65                        appendValidateProduct(productDetails);
66
67                        $(".registerwarrantydiv").remove();
68                        $("#vaidate-serial-number").remove();
69                        $(".product-register").show();
70
71                        $(".validate-heading h2").text(
72                            "You're Just a Click Away to Complete Registration"
73                        );
74                        $(".validate-heading h4").remove();
75
76                        $(".is-register").show();
77                        $(".is-non-register").hide();
78
79                        sessionStorage.removeItem("previousPageUrl");
80                        sessionStorage.removeItem("productDetails");
81                    }
82                }
83            }
84        });
85
86        function appendValidateProduct(response) {
87            var productResultHtml = `
88				<div class="row my-5">
89					<div class="col-md-4 col-sm-5 col-img">
90						<div class="overflow-hidden shadow rounded p-4 h-100 d-flex align-items-center">
91							<img class="rounded" src="${response.ProductImage}" alt="Product Image">
92						</div>
93					</div>
94					<div class="col-md-8 col-sm-7 mt-sm-0 mt-3">
95						<div class="rounded p-4 shadow d-flex flex-column h-100 text-sm-start text-center">
96							<div class="d-flex flex-sm-row flex-column gap-3 align-items-center justify-content-between">
97								<div class="register-product-detail">
98									<h2>Product Details</h2>
99									<h3 class="title mb-2 text-size-xl">${response.ModelName}</h3>
100									<p class="sub-title m-0 text-size-lg">${response.CategoryName}</p>
101									<p class="sku text-muted mb-4">${response.ModelCode}</p>
102									<input type="hidden" id="modelId" value="${response.ModelId}" >
103									<input type="hidden" id="serialNo" value="${response.SerialNumber}" >
104									<input type="hidden" id="categoryId" value="${response.CategoryId}" >
105									<input type="hidden" id="subCategoryId" value="${response.SubCategoryId}" >
106									${response.ManualURL
107                    ? '<div><a href="' +
108                    response.ManualURL +
109                    '" target="_blank" class="link-arrow-blue">Access User Manual</a></div>'
110                    : ""
111                }
112									<div class="mt-3"><a href="/new-service-request" target="_blank" class="link-arrow-blue register-raise-request" id="prod-new-service-request">Raise service request</a></div>
113								</div>
114								<div class="register-product-status text-center">
115									<img src="/media/wysiwyg/product-register/genuine-batch.png" alt="Genuine Product">
116									<h4>Genuine Product</h4>
117								</div>
118							</div>
119						</div>
120					</div>
121				</div>
122				<div class="mt-4 text-center registerwarrantydiv">
123					<a href="" class="btn btn-dark btn-lg text-white register-for-warranty register-for-warranty">Register for Warranty</a>
124				</div>
125			`;
126            $("#productResult").html(productResultHtml);
127        }
128
129        function appendAlreadyValidateProduct(response) {
130
131            // Get serial number from input field
132            var enteredSerialNumber = $("#serialnumber").val();
133            var alraedyproductResultHtml = `
134			 <div class="row justify-content-center my-5">
135				  <div class="col-lg-5 col-md-8">
136						<div class="rounded p-4 shadow d-flex flex-column h-100 text-sm-start text-center">
137							<div class="d-flex flex-sm-row flex-column gap-3 align-items-center justify-content-center">
138								<div class="register-product-detail">
139									<div><a href="/new-service-request" target="_blank" class="link-arrow-blue register-raise-request" id="prod-new-service-request">Raise service request</a></div>
140								<input type="hidden" id="isAlreadyRegistered" value="1">
141								<!-- Use entered serial number -->
142                               <input type="hidden" id="serialNo" value="${enteredSerialNumber}">
143								</div>
144								
145							</div>
146						</div>
147					</div>
148				</div>
149			`;
150
151            $("#productResult").html(alraedyproductResultHtml);
152            $("#isAlreadyRegistered").val('1');
153        }
154
155        $(document).on('click', '#prod-new-service-request', function (event) {
156            event.preventDefault();
157            const deviceType = getDeviceType();
158            const serialNumber = $("#serialNo").val();
159            const categoryId = $("#categoryId").val();
160            const subCategoryId = $("#subCategoryId").val();
161            const isAlreadyRegistered = $("#isAlreadyRegistered").val(); // Example flag
162
163            if (deviceType === 'mobile') {
164
165                // Already Registered Product
166
167                if (isAlreadyRegistered === '1') {
168                    //console.log('Already Registered Redirect');
169                    window.location.href =
170                        'https://wa.me/919711773333?text=Please%20sen
170d%20the%20message%20to%20initiate%20chat%0AWebQRIssue:' +
171                        serialNumber +
172                        ';' +
173                        '*' +
174                        ';' +
175                        '*';
176                }
177                else if (serialNumber && serialNumber.trim() !== '') {
178
179                    let waUrl =
180                        'https://wa.me/919711773333?text=Please%20send%20the%20message%20to%20initiate%20chat%0AWebQRIssue:' +
181                        serialNumber +
182                        ';' +
183                        subCategoryId +
184                        ';' +
185                        categoryId;
186
187                    window.location.href = waUrl;
188
189                } else {
190
191                    window.location.href =
192                        'https://wa.me/919711773333?text=Service%20Request';
193                }
194
195                return;
196            }
197            sendAjaxRequest('/registerproduct/api/checkislogin', function (response) {
198                if (response.success) {
199                    window.location.href = '/new-service-request';
200                } else {
201                    window.location.href = window.new_service_request;
202                }
203            });
204        });
205
206        $(".verify-serial").on("click", function () {
207            displayError("", "error-inputSerial");
208            $("#productResult").html("");
209
210            var serialNumber = $("#serialnumber").val();
211            if (serialNumber) {
212                $(this).prop("disabled", true).text($t("Verifying..."));
213
214                // Send the AJAX request
215                $.ajax({
216                    url: urlBuilder.build("register/validate/serialno"),
217                    type: "POST",
218                    data: {
219                        serial_number: serialNumber,
220                    },
221                    success: function (response) {
222                        $("#verifySerial")
223                            .prop("disabled", false)
224                            .text($t("Verify"));
225
226                        if (response.success) {
227
228                            displayError("", "error-inputSerial");
229                            $("#alreadyproductResult").html("");
230
231                            var productDetails = {
232                                ProductImage: response.result.ProductImage,
233                                ModelName: response.result.ModelName,
234                                CategoryName: response.result.CategoryName,
235                                ModelCode: response.result.ModelCode,
236                                ModelId: response.result.ModelId,
237                                SerialNumber: serialNumber,
238                                AssetLink: response.result.AssetLink
239                            };
240
241                            sessionStorage.setItem(
242                                "productDetails",
243                                JSON.stringify(productDetails)
244                            );
245
246                            appendValidateProduct(response.result);
247
248                        } else {
249
250                            if (
251                                response.message &&
252                                (
253                                    response.message.toLowerCase().includes("already exist") ||
254                                    response.message.toLowerCase().includes("already registered")
255                                )
256                            ) {
257
258                                $("#productResult").html("");
259                                displayError("", "error-inputSerial");
260
261                                appendAlreadyValidateProduct(response);
262
263                            } else {
264
265                                $("#alreadyproductResult").html("");
266                                displayError(
267                                    response.message,
268                                    "error-inputSerial"
269                                );
270                            }
271                        }
272                    },
273
274
275
276
277                    error: function () {
278                        $("#verifySerial").prop("disabled", false).text($t("Verify"));
279                        displayError(error, "error-inputSerial");
280                    },
281                });
282            } else {
283                $("#verifySerial").prop("disabled", false).text($t("Verify"));
284                displayError(
285                    "Please enter a valid serial number.",
286                    "error-inputSerial"
287                );
288            }
289        });
290
291        function displayError(message, errorFieldId) {
292            $("#" + errorFieldId).text(message);
293        }
294
295        $("#serialnumber").on("keyup", function () {
296            displayError("", "error-inputSerial");
297        });
298
299        // For file input (attachInvoiceFile)
300        $("#attachInvoiceFile").on("change", function () {
301            var fileInput = $(this)[0].files;
302            if (fileInput.length > 0) {
303                displayError("", "error-attachInvoiceFile"); // Clear the error message for file input if file is selected
304            }
305        });
306
307        // For date input (inputDate)
308        $("#inputDate").on("change", function () {
309            var inputValue = $(this).val().trim();
310            if (inputValue !== "") {
311                displayError("", "error-inputDate");
312            }
313        });
314
315        function redirectToLogin() {
316            var loginUrl = urlBuilder.build("customer/account/login");
317            var validateSerialUrl = urlBuilder.build("engagement-product");
318            var redirectUrl =
319                loginUrl + "?callback_url=" + encodeURIComponent(validateSerialUrl);
320            window.location.href = redirectUrl;
321        }
322
323        function sendAjaxRequest(url, successCallback, errorCallback) {
324            $.ajax({
325                url: url,
326                type: "POST",
327                dataType: "json",
328                success: successCallback,
329                error:
330                    errorCallback ||
331                    function (xhr, status, error) {
332                        console.error("AJAX Request Failed:", status, error);
333                    },
334            });
335        }
336
337        $(document).on("click", ".register-for-warranty", function (e) {
338            e.preventDefault();
339            var isLogin = false;
340            const deviceType = getDeviceType();
341            var serialNumber = $("#serialNo").val();
342            sendAjaxRequest("/registerproduct/api/checkislogin", function (response) {
343                if (!response.success) {
344                    if (deviceType == "mobile") {
345                        window.location.href =
346                            "https://wa.me/9711773333?text=Serial Number: " + serialNumber;
347                        return;
348                    } else {
349                        sessionStorage.setItem("previousPageUrl", window.register_url);
350                        window.location.href = window.register_url;
351                        return;
352                    }
353                } else {
354                    isLogin = true;
355                    if (deviceType == "mobile") {
356                        window.location.href =
357                            "https://wa.me/9711773333?text=Serial Number: " + serialNumber;
358                        return;
359                    }
360                }
361                if (isLogin) {
362                    var modelId = $("#modelId").val();
363                    if (modelId) {
364                        $(".registerwarrantydiv").remove();
365                        $("#vaidate-serial-number").remove();
366                        $(".product-register").show();
367
368                        $(".validate-heading h2").text(
369                            "You're Just a Click Away to Complete Registration"
370                        );
371                        $(".validate-heading h4").remove();
372
373                        $(".is-register").show();
374                        $(".is-non-register").hide();
375                    } else {
376                        displayError("Product details not found.", "error-inputSerial");
377                    }
378                }
379            });
380        });
381
382        $("#form-registerproduct").on("submit", function (event) {
383            event.preventDefault();
384            $("#apierrormsg").text("");
385            if ($("#modelId").val()) {
386                var formParam = {
387                    inputDate: $("#inputDate").val(),
388                    attachInvoiceFile: $("#attachInvoiceFile").val(),
389                };
390
391                var isValid = true;
392                for (var field in formParam) {
393                    if (formParam[field].trim() == "") {
394                        if (field === "attachInvoiceFile") {
395                            displayError("Please upload an image.", "error-" + field);
396                        } else {
397                            displayError(
398                                "Please select the " + getFieldLabel(field) + " field.",
399                                "error-" + field
400                            );
401                        }
402                        isValid = false;
403                    }
404                }
405
406                var imageVal = $("#attachInvoiceFile").val();
407                if (isValid && imageVal !== "") {
408                    $("body").trigger("processStart");
409                    var imageInput = document.getElementById("attachInvoiceFile");
410                    var file = imageInput.files[0];
411                    if (file) {
412                        var formData = new FormData();
413                        formData.append("image", file);
414                        var input = document.getElementById("attachInvoiceFile");
415                        $.ajax({
416                            url: "/registerproduct/api/uploadImage",
417                            type: "POST",
418                            data: formData,
419                            contentType: false,
420                            processData: false,
421                            success: function (response) {
422                                if (response.success) {
423                                    const fileInput =
424                                        document.getElementById("attachInvoiceFile");
425                                    const file = fileInput.files[0];
426                                    if (file) {
427                                        const maxFileSize = 5 * 1024 * 1024; // 5MB in bytes
428                                        if (file.size > maxFileSize) {
429                                            $("#error-attachInvoiceFile")
430                                                .text(
431                                                    "File size exceeds 5MB. Please upload a smaller file."
432                                                )
433                                                .css("color", "red");
434                                            return;
435                                        }
436
437                                        var reader = new FileReader();
438                                        reader.onload = function (e) {
439                                            var base64String = e.target.result.split(",")[1];
440                                            document
441                                                .getElementById("fileData")
442                                                .setAttribute("base-code", base64String);
443                                            var base64Code = document
444                                                .getElementById("fileData")
445                                                .getAttribute("base-code");
446                                            var fileName = file.name;
447
448                                            var fileExtension = fileName.substring(
449                                                fileName.lastIndexOf(".") + 1
450                                            );
451                                            formParam.fileType = fileExtension;
452                                            formParam.base64Code = base64Code;
453                                            formParam.fileName = fileName;
454
455                                            formParam.serialNumber = $("#serialNo").val();
456                                            formParam.modelGuid = $("#modelId").val();
457
458                                            performAjaxCall(formParam);
459                                        };
460
461                                        reader.readAsDataURL(file);
462                                    }
463                                    $("#error-attachInvoiceFile")
464                                        .text("Image uploaded successfully.")
465                                        .css("color", "green");
466                                } else {
467                                    $("body").trigger("processStop");
468                                    $("#error-attachInvoiceFile")
469                                        .text("Error: " + response.message)
470                                        .css("color", "red");
471                                }
472                            },
473                            error: function () {
474                                $("body").trigger("processStop");
475                                $("#error-attachInvoiceFile")
476                                    .text("An error occurred while uploading the image.")
477                                    .css("color", "red");
478                            },
479                        });
480                    }
481                }
482            }
483        });
484
485        function getFieldLabel(fieldName) {
486            var fieldLabels = {
487                inputDate: "Invoice Date",
488                attachInvoiceFile: "Invoice File",
489            };
490
491            return fieldLabels[fieldName] || fieldName;
492        }
493
494        function performAjaxCall(formParam) {
495            $.ajax({
496                type: "POST",
497                url: "/register/product/productregister",
498                data: formParam,
499                dataType: "json",
500                success: function (response) {
501                    if (response.success) {
502                        $(".registerproductamc").prop("disabled", true);
503                        //$('body').trigger('processStop');
504                        var urlParams = new URLSearchParams(window.location.search);
505                        var callbackUrl = urlParams.get("callback_url");
506                        checkCallbackAndSignup(callbackUrl);
507                    } else {
508                        $("#apierrormsg").text(response.message);
509                        $("body").trigger("processStop");
510                    }
511                },
512
513                error: function (xhr, status, errorThrown) {
514                    console.error("XHR:", xhr);
515                    console.error("Status:", status);
516                    console.error("Error Thrown:", errorThrown);
517                    $("body").trigger("processStop");
518                },
519            });
520        }
521
522        var btnTxt;
523        function confirmationPopup(btnTxt, callbackUrl) {
524            var buttons = [];
525
526            if (btnTxt === "Enroll in Loyalty Program") {
527                buttons.push({
528                    text: $.mage.__(btnTxt),
529                    class: "btn btn-primary",
530                    click: function () {
531                        this.closeModal();
532                        if (callbackUrl && callbackUrl.includes("loyalty-signup")) {
533                            window.location.href = callbackUrl;
534                        } else {
535                            window.location.href = "/loyalty-signup";
536                        }
537                    },
538                });
539            }
540
541            // Always add the 'Add More Products' button
542            buttons.push({
543                text: $.mage.__("Add More Products"),
544                class: "btn btn-primary",
545                click: function () {
546                    this.closeModal();
547                    window.location.href = "/engagement-product";
548                },
549            });
550
551            // Open the confirmation popup with the buttons array
552            confirmation({
553                content: `
554					<img src="/media/wysiwyg/product-register/success-img.png" alt="Successfully">
555					<div class="p-5 text-size-xxl fw-bold text-center">
556						Your Product has been Registered <br><span class="text-success text-size-xxxl">Successfully.</span>
557					</div>
558				`,
559                modalClass: "custom-popup",
560                responsive: true,
561                clickableOverlay: false,
562                buttons: buttons,
563            });
564
565            $(document).on("click", ".action-close", function () {
566                location.reload();
567            });
568        }
569
570        function checkCallbackAndSignup(callbackUrl) {
571            /* if (callbackUrl && callbackUrl.includes('loyalty-signup')) {
572                      $.ajax({
573                          url: '/registerproduct/loyalty/loyaltysignup',
574                          type: 'POST',
575                          dataType: 'json',
576                          success: function(response) {					
577                              if (response.success && response.response === 'Y') {
578                                  confirmationPopup ('Enroll in Loyalty Program', callbackUrl)
579                                  window.location.href = callbackUrl;
580                              } else {
581                                  confirmationPopup ('Register Another Product', callbackUrl)
582                              } 
583                          },
584                          error: function(xhr, status, errorThrown) {
585                              console.error('AJAX call error:', status, errorThrown);
586                          }
587                      });
588                  } else {
589                      confirmationPopup ('Register Another Product', callbackUrl)
590                  } */
591
592            $.ajax({
593                url: "/registerproduct/loyalty/loyaltysignup",
594                type: "POST",
595                dataType: "json",
596                success: function (response) {
597                    $("body").trigger("processStop");
598                    if (response.success && response.response === "Y") {
599                        confirmationPopup("Enroll in Loyalty Program", callbackUrl);
600                        //window.location.href = callbackUrl;
601                    } else {
602                        confirmationPopup("", callbackUrl);
603                    }
604                },
605                error: function (xhr, status, errorThrown) {
606                    console.error("AJAX call error:", status, errorThrown);
607                    $("body").trigger("processStop");
608                },
609            });
610        }
611    });
612});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.