Patch Cable Configurator Extension for PDP

Overview

The Patch Cable Configurator is a SuiteCommerce Advanced (SCA) extension that allows users to request a customized patch cable from an existing product page by submitting additional configuration options via a form. The extension is seamlessly integrated into the PDP and provides a backend service for handling requests.

Key Features

  • Adds a custom form to the PDP to capture patch cable-specific information.
  • Provides a server-side service using SuiteScript 2.0 for data handling.
  • Stores or forwards the request for processing (e.g., email, custom record).
  • Fully isolated JavaScript module architecture.
  • Custom styling through SCSS for seamless UI integration.

File Structure & Components

1. manifest.json

Defines the extension’s metadata, required modules, and entry points.

2. Configuration/PatchCableConfigurater.json

Manages the module’s configuration options (if needed via SCA backend config UI).

JavaScript Modules

JJ.PatchCableConfigurater.PatchCableConfigurater.js

  • This is the frontend controller.
  • Initializes the patch cable view module on the PDP page.
  • Uses ProductDetails.Full.View composite view injection.

PatchCableConfigurater.View.js

  • Contains the view logic and event handlers.
  • Renders the form from the template.
  • Listens for user input and submits the form data.

JJ.PatchCableConfigurater.PatchCableConfigurater.SS2Model.js

  • Provides the client-side model to interact with the Suitelet service.
  • Uses Utils.getAbsoluteUrl to call the backend Service.ss.

SuiteScript 2.0 Backend

PatchCableConfigurater.Service.ss

  • Exposes a Suitelet endpoint to receive the form submission.
  • Handles the logic to store, validate, or route the request.
  • May include functionality such as:
  • Sending email to admins.
  • Creating a custom record.
  • Logging for audits.

Template & Styling

jj_patchcableconfigurater_patchcableconfigurater.tpl

  • Handlebars template for rendering the input form on the PDP.
  • Includes fields such as length, connector type, color, notes, etc.

_patchcableconfigurater-patchcableconfigurater.scss

  • SCSS file for styling the form to match your website’s theme.

Integration Details

PDP Injection Point:

The extension uses the ProductDetails.Full.View to inject the configurator form. This is usually done via:

javascript

Copy

Edit
ProductDetailsFullView.addChildView('PatchCableConfigurator', function() {
    return new PatchCableConfiguraterView({ model: this.model });
});

Service Call:

Form data is sent to the backend via a POST request using SuiteScript 2.0 Model like this:

javascript

Copy

Edit
Model.save({
  length: this.$('#cable_length').val(),
  connectorType: this.$('#connector_type').val(),
  notes: this.$('#notes').val()
});

✅ Use Cases

  • Customers needing custom cable specifications for server rooms, audio systems, etc.
  • Businesses offering value-added configuration services before ordering.

🚧 Deployment Notes

  • Ensure the extension is deployed and activated via Extension Manager.
  • Confirm services are published (under SSP Application).
  • Test across various PDPs to ensure compatibility with different item types.

✅ Final Notes

This extension enhances the PDP experience by giving customers control over customization without leaving the product page. It’s particularly useful for B2B and electronics-focused SuiteCommerce implementations.

{
    "type": "object",
    "subtab":
    {
        "id": "patchCable_subtab",
        "title": "Patch Cable Configuration",
        "description": "Patch Cable Configuration section",
        "group": "extensions",
        "docRef": ""
    },
    "properties": { 
        "PatchCableConfigurater.formtitle": {
            "group": "extensions",
            "subtab": "patchCable_subtab",
            "type": "string",
            "title": "Configurater_Form_Title",
            "description": "Configuration form title",
            "default": "Custom Patch Cable Configurator"
        },
        "PatchCableConfigurater.senderEmail": {
            "group": "extensions",
            "subtab": "patchCable_subtab",
            "type": "string",
            "title": "EmailSender_EmployeeId",
            "description": "employee ID of the person who send the email",
            "default": "27393"
        },
        "PatchCableConfigurater.RecieverEmail": {
            "group": "extensions",
            "subtab": "patchCable_subtab",
            "type": "string",
            "title": "EmailId_Of_Receiver",
            "description": "email ID of the person who receive the email",
            "default": "orders@cleerline.com"
        },
        "PatchCableConfigurater.items": {
            "group": "extensions",
            "subtab": "patchCable_subtab",
            "type": "string",
            "title": "Item internal id",
            "description": "Add the internal IDs of the items, separated by commas, for which you want to remove the stagger option."
        }
    }
}


define(
    'JJ.PatchCableConfigurater.PatchCableConfigurater'
    , [
        'JJ.PatchCableConfigurater.PatchCableConfigurater.View',
        'ProductDetails.Full.View'
    ]
    , function (
        PatchCableConfiguraterView,
        ProductDetailsFullView
    ) {
        'use strict';


        return {
            mountToApp: function mountToApp(container) {
                var pdp = container.getComponent('PDP');
                ProductDetailsFullView.addChildViews({
                    'BuildPatchCable': function wrapperFunction() {
                        return new PatchCableConfiguraterView({
                            container: container
                        });
                    }
                });
                _.extend(ProductDetailsFullView.prototype, {
                    initialize: _.wrap(ProductDetailsFullView.prototype.initialize, function (fn) {
                        fn.apply(this, _.toArray(arguments).slice(1));
                        /* To Add childView in ProductDetailsFullView */
                        this.on('beforeCompositeViewRender', function beforeCompositeViewRender() {
                            this.$el.find('.product-details-full-actions-container[data-view="ItemActions"]').after('<div class="BuildPatchCable" data-view="BuildPatchCable"></div>');
                        });


                        /* To render the BuildPatchCable view when the matrix option changes on PDP page */
                        var self = this;
                        pdp.on('afterOptionSelection', function () {
                            if(!!self.getChildViewInstance('BuildPatchCable')){
                            self.getChildViewInstance('BuildPatchCable').render();
                            }
                        })
                    })
                });
            }
        };
    });


// @module JJ.PatchCableConfigurater.PatchCableConfigurater
define('JJ.PatchCableConfigurater.PatchCableConfigurater.View'
    , [
        'jj_patchcableconfigurater_patchcableconfigurater.tpl'
        , 'JJ.PatchCableConfigurater.PatchCableConfigurater.SS2Model'
        , 'Backbone'
        , 'Profile.Model'
    ]
    , function (
        jj_patchcableconfigurater_patchcableconfigurater_tpl


        , PatchCableConfiguraterSS2Model
        , Backbone
        , ProfileModel
    ) {
        'use strict';


        // @class JJ.PatchCableConfigurater.PatchCableConfigurater.View @extends Backbone.View
        return Backbone.View.extend({


            template: jj_patchcableconfigurater_patchcableconfigurater_tpl


            , initialize: function (options) {
                var self = this;
                self.container = options.container;
                this.showPatchForm = false;
            }


            , events: {
                'click [data-action="configuraterForm"]': 'showForm',
                'click [data-action="close-modal"]': 'closeForm',
                'click [data-action="formSubmission"]': 'formSumit',
                'change [data-action="addLength"]': 'addLength',
                'change [data-action="selectConnector"]': 'connectorUpdate',
            }
            , showForm: function () {
                var self = this;
                this.showPatchForm = !this.showPatchForm; // Toggle the state
                this.patchModel = new PatchCableConfiguraterSS2Model({ id: null });
                this.patchModel.fetch().done(function (result) {
                    self.inputFormDetails = result;
                    var mode = self.currentITemInPDP.custitemfibertype_facet ? self.currentITemInPDP.custitemfibertype_facet : null;
                    if (mode === null) {
                        mode = self.currentITemInPDP.custitem38 ? self.currentITemInPDP.custitem38 : null;
                    }
                    self.mode = mode;
                    //To obtain connectionOption
                    var matchedGroup = self.mode!=null?self.inputFormDetails.connection.find(connector => (connector.group).toUpperCase() === (self.mode).toUpperCase()):null;
                    const combinedOptions = self.inputFormDetails.connection
                        .filter(connector => ['Singlemode', 'Multimode'].includes(connector.group))
                        .flatMap(connector => connector.options);
                    self.connectorOptions = matchedGroup ? matchedGroup.options : combinedOptions;
                    //To obtain strandOption
                    var strangGroupIdOfItem = self.currentITemInPDP.custitemstrandcount_facet ? self.currentITemInPDP.custitemstrandcount_facet : null;
                    if (strangGroupIdOfItem) {
                        var i = 0;
                        var strandsGroup = self.inputFormDetails.strands.find(strand => strand.group === "unique strands");
                        strandsGroup = strandsGroup.options.filter(strand => {
                            if (Number(strand.strandsGroup) === Number(strangGroupIdOfItem)) {
                                return strand.connectorCounts;
                            }
                        });
                        self.strandsOptions = strandsGroup[i].connectorCounts;
                    } else {
                        var allConnectorCounts = self.inputFormDetails.strands.find(strand => strand.group === "All Strands");
                        allConnectorCounts = allConnectorCounts.options.flatMap(strand => strand.connectorCount
                        );
                        var uniqueConnectorCounts = [...new Set(allConnectorCounts)];
                        self.strandsOptions = uniqueConnectorCounts;
                    }
                    //To obtain furcationOption
                    var furcationGrupOption = self.currentITemInPDP.custitemfurcationtubinggroup ? self.currentITemInPDP.custitemfurcationtubinggroup : null;
                    var furcation = [];
                    if (furcationGrupOption) {
                        var furcationOption = self.inputFormDetails.furcation.find(f => f.group === "All furcation");
                        if (furcationOption) {
                            var furcationGRpArr = furcationOption.options.filter(f => Number(f.internalId) === Number(furcationGrupOption));
                            if (furcationGRpArr.length > 0) {
                                var furcationGRp = furcationGRpArr[0].furcationGroup; // Ensure it exists before accessing
                                var furcationList = furcationOption.options.filter(f => f.furcationGroup === furcationGRp);
                                furcationList.forEach(f => {
                                    furcation.push(f.furcationName); // Correctly pushing to furcation array
                                });
                                self.furcationOption = furcation; // Assign the array instead of accessing a single property
                            }
                        }
                    } else {
                        var uniqueFurcation = self.inputFormDetails.furcation.find(f => f.group === "unique Furcation");
                        self.furcationOption = uniqueFurcation ? uniqueFurcation.options : [];
                    }
                    //To obtain pullEyeOption
                    var pullEyeDetails = self.inputFormDetails.pullEye;
                    self.pullEyeDetails = pullEyeDetails;
                    self.pullEyeOption = ["Yes", "No"];
                    //To obtain offsetOption
                    var offfsetDetails = self.inputFormDetails.offset;
                    self.offfsetDetails = offfsetDetails;
                    var offsetOption = [];
                    const restrictedItemIdsString = SC.CONFIGURATION.PatchCableConfigurater.items || '';
                    const itemIds = (restrictedItemIdsString.match(/d+/g) || []).map(Number);
                    const matching = itemIds.includes(self.itemArray.internalid);
                    if (matching) {
                        offfsetDetails.forEach(offset => {
                            if (offset.offsetName === "Standard") {
                                offsetOption.push(offset.offsetName);
                            }
                        });
                    } else {
                        offfsetDetails.forEach(offset => {
                            offsetOption.push(offset.offsetName);
                        });
                    }
                    self.offsetOption = offsetOption;
                    self.render();
                });
                this.render();
            }
            , connectorUpdate: function (event) {
                const sideBConnector = document.getElementById("side B Connector");
                const sideBFields = [
                    document.getElementById("side B #Connectors"),
                    document.getElementById("side B Tubing"),
                    document.getElementById("Side B Connector Offset"),
                    document.getElementById("sideB#Connectors"),
                    document.getElementById("sideBTubing"),
                    document.getElementById("sideBOffset")
                ];
                if (sideBConnector.value === "NC") {
                    sideBFields.forEach(field => {
                        field.disabled = true;
                        field.style.opacity = "0.5";
                        field.value = "None"
                    });
                } else {
                    sideBFields.forEach(field => {
                        field.disabled = false;
                        field.style.opacity = "1";
                    });
                }
            },
            addLength: function (event) {
                event.preventDefault();
                const form = document.getElementById('patchCableForm');
                const requiredFields = form.querySelectorAll("#patchCableForm input[id='Cable Length']");
                var lengthInFeet;
                requiredFields.forEach((field) => {
                    if (field.value.trim() != "") {
                        lengthInFeet = field.value.trim();
                    }
                });
                var lengthInMeter = lengthInFeet ? (lengthInFeet / 3.281).toFixed(4) : null;
                document.getElementById("cableLengthMeters").value = lengthInMeter;
            }
            , closeForm: function () {
                this.showPatchForm = false;
                this.render();
            }
            , formSumit: function (event) {
                try {
                    event.preventDefault();
                    const form = document.getElementById('patchCableForm');
                    let isValid = true;
                    let firstInvalidField = null;
                    var requiredFields = Array.from(form.querySelectorAll(
                        "#patchCableForm select, #patchCableForm input[type='number']"
                    ));
                    const sideBConnector = document.getElementById("side B Connector");
                    if (sideBConnector.value === "NC") {
                        // Fields to remove
                        const fieldsToRemove = ["side B #Connectors", "side B Tubing", "Side B Connector Offset"];
                        requiredFields = requiredFields.filter(field => !fieldsToRemove.includes(field.id));
                    }
                    requiredFields.forEach((field) => {
                        if (field.value.trim() === "") {
                            isValid = false;
                            if (!firstInvalidField) {
                                firstInvalidField = field;
                            }
                            if (!field.nextElementSibling) {
                                const errorMessage = document.createElement("div");
                                errorMessage.className = "error-message";
                                errorMessage.textContent = field.id + " field is required.";
                                field.parentNode.appendChild(errorMessage);
                            } else if (!field.nextElementSibling.classList.contains("error-message") && !field.nextElementSibling.classList.contains("lengthMeter")) {
                                const errorMessage = document.createElement("div");
                                errorMessage.className = "error-message";
                                errorMessage.textContent = field.id + " field is required.";
                                field.parentNode.appendChild(errorMessage);
                            }
                        } else {
                            // Remove existing validation message
                            if (field.nextElementSibling && field.nextElementSibling.classList.contains("error-message")) {
                                field.nextElementSibling.remove();
                            }
                        }
                    });
                    if (isValid === false) {
                        firstInvalidField.focus();
                    }
                    // Submit the form if all fields are valid
                    if (isValid === true) {
                        var strandHashIdOfItem = this.currentITemInPDP.custitemstrandcount_facet ? this.currentITemInPDP.custitemstrandcount_facet : 0;
                        var baseCable = this.currentITemInPDP ? this.currentITemInPDP.itemid : null;
                        var baseCableId = this.currentITemInPDP ? this.currentITemInPDP.internalid : null;
                        var selectsideAConnector, selectsideAHashConnectors, selectsideATubing, selectsideBConnector, selectsideBHashConnectors, selectsideBTubing, selectedCableLength, selectsideAPullEye, selectsideBPullEye, sideAOffset, sideBOffset;
                        requiredFields.forEach((field) => {
                            if (field.name === "sideAConnector") {
                                selectsideAConnector = field.value.trim();
                            } else if (field.name === "sideA#Connectors") {
                                selectsideAHashConnectors = field.value.trim();
                            } else if (field.name === "sideATubing") {
                                selectsideATubing = field.value.trim();
                            } else if (field.name === "sideAPullEye") {
                                selectsideAPullEye = field.value.trim();
                            } else if (field.name === "sideAOffset") {
                                sideAOffset = field.value.trim();
                            } else if (field.name === "sideBConnector") {
                                selectsideBConnector = field.value.trim();
                            } else if (field.name === "sideB#Connectors") {
                                selectsideBHashConnectors = field.value.trim();
                            } else if (field.name === "sideBTubing") {
                                selectsideBTubing = field.value.trim();
                            } else if (field.name === "sideBPullEye") {
                                selectsideBPullEye = field.value.trim();
                            } else if (field.name === "sideBOffset") {
                                sideBOffset = field.value.trim();
                            } else if (field.name === "cableLengthFeet") {
                                selectedCableLength = field.value.trim();
                            }
                        });
                        var notes = form.querySelector("#notes").value || '';
                        var itemComponent_7 = "CTG-MFG OVERHEAD";
                        var itemComponent_8 = "CTG-PATCH-FANOUT";
                        if (selectsideBConnector.toUpperCase() === "NC") {
                            selectsideBHashConnectors = "None";
                            selectsideBTubing = "None";
                            sideBOffset = "None";
                            itemComponent_7 = "NO-MFG OVERHEAD";
                            itemComponent_8 = "NO-PATCH-FANOUT";
                        }
                        var sideAPullEye = !!selectsideAPullEye && selectsideAPullEye === "Yes" ? "Y" : "N";
                        var sideBPullEye = !!selectsideBPullEye && selectsideBPullEye === "Yes" ? "Y" : "N";
                        var sideATubing = !!selectsideATubing && selectsideATubing != "None" ? selectsideATubing.charAt(0) : 'X';
                        var sideBTubing = !!selectsideBTubing && selectsideBTubing != "None" ? selectsideBTubing.charAt(0) : 'X';
                        var mode = this.currentITemInPDP.custitemfibertype_facet ? this.currentITemInPDP.custitemfibertype_facet : null;
                        var fiberTypeFacet = mode;
                        if (mode === null) {
                            mode = this.currentITemInPDP.custitem38 ? this.currentITemInPDP.custitem38 : null;
                        }
                        var cableconstruction_facet = this.currentITemInPDP.custitemcableconstruction_facet ? this.currentITemInPDP.custitemcableconstruction_facet : null;
                        var cableConstruct;
                        if (cableconstruction_facet != null) {
                            cableConstruct = cableconstruction_facet.split(' ').map(word => word.charAt(0).toUpperCase()).join('');
                        } else {
                            cableConstruct = null;
                        }
                        // Create a success message element
                        var responseMessage = document.createElement("div");
                        responseMessage.id = "responseMessage";
                        responseMessage.textContent = "Submitting...";
                        const existingMessage = document.getElementById("responseMessage");
                        if (!existingMessage) {
                            document.getElementById("patchCableForm").parentElement.appendChild(responseMessage);
                        }
                        // Optionally clear the form fields (if needed)
                        document.getElementById("patchCableForm").style.display = "none";
                        var i = 0;
                        var baseFurcatioOption = this.currentITemInPDP.custitemfurcationtubinggroup ? this.currentITemInPDP.custitemfurcationtubinggroup : null;
                        if (!!baseFurcatioOption) {
                            var furcationDetail = this.inputFormDetails.furcation.find(furcation => furcation.group === "All furcation").options;
                            furcationDetail = furcationDetail.filter(furcation => Number(furcation.internalId) === baseFurcatioOption);
                            baseFurcatioOption = furcationDetail[i].furcationGroup;
                        } else {
                            baseFurcatioOption = null;
                        }
                        var baseConnectorOption = this.currentITemInPDP.custitemstrandcount_facet ? this.currentITemInPDP.custitemstrandcount_facet : 0;
                        var matchedGroup = this.inputFormDetails.connection.find(connector => connector.group === "All Options");
                        matchedGroup = matchedGroup.options;
                        var connectorMatch = matchedGroup.filter(connector => (connector.optionName).toUpperCase() === selectsideAConnector.toUpperCase());
                        var componentItem2;
                        if (selectsideATubing === "None") {
                            componentItem2 = connectorMatch[i].optionItem;
                            componentItem2 = connectorMatch.find(connector => (connector.ftOption).toUpperCase() === "3MM").optionItem;
                        } else {
                            componentItem2 = connectorMatch.find(connector => (connector.ftOption).toUpperCase() === selectsideATubing.toUpperCase()).optionItem;
                        }
                        var componentItem2Qty = selectsideAConnector.toUpperCase() === "NC" ? 1 : selectsideAHashConnectors;
                        connectorMatch = matchedGroup.filter(connector => (connector.optionName).toUpperCase() === selectsideBConnector.toUpperCase());
                        var componentItem6;
                        if (selectsideBTubing === "None") {
                            componentItem6 = connectorMatch.find(connector => (connector.ftOption).toUpperCase() === "3MM").optionItem;
                        } else {
                            componentItem6 = connectorMatch.find(connector => (connector.ftOption).toUpperCase() === selectsideBTubing.toUpperCase()).optionItem;
                        };
                        var componentItem6Qty = selectsideBConnector.toUpperCase() === "NC" ? 1 : selectsideBHashConnectors;
                        var furcationMatch = this.inputFormDetails.furcation.find(furcation => furcation.group === "All furcation");
                        furcationMatch = furcationMatch.options;
                        var componentItem5 = furcationMatch.find(furcation => (furcation.furcationName).toUpperCase() === selectsideATubing.toUpperCase()).furcationItem;
                        var componentItem5Qty = selectsideATubing.toUpperCase() === "NONE" ? 1 : componentItem2Qty;
                        var componentItem9 = furcationMatch.find(furcation => (furcation.furcationName).toUpperCase() === selectsideBTubing.toUpperCase()).furcationItem;
                        var componentItem9Qty = selectsideBTubing.toUpperCase() === "NONE" ? 1 : componentItem6Qty;
                        var baseConA = matchedGroup.find(connector => (connector.optionName).toUpperCase() === selectsideAConnector.toUpperCase()).optionLegend;
                        var baseConB = matchedGroup.find(connector => (connector.optionName).toUpperCase() === selectsideBConnector.toUpperCase()).optionLegend;
                        var basePolishA = matchedGroup.find(connector => (connector.optionName).toUpperCase() === selectsideAConnector.toUpperCase()).polishLegend;
                        var basePolishB = matchedGroup.find(connector => (connector.optionName).toUpperCase() === selectsideBConnector.toUpperCase()).polishLegend;
                        var baseJacket = this.currentITemInPDP.custitemjackettype_facet ? this.currentITemInPDP.custitemjackettype_facet : null;
                        if (!!baseJacket) {
                            baseJacket = baseJacket.charAt(0);
                        } else {
                            baseJacket = this.currentITemInPDP.custitemjacketlegend ? this.currentITemInPDP.custitemjacketlegend : null;
                        }
                        var eyeGroup = this.inputFormDetails.pullEye;
                        var componentItem10, componentItem10Qty, componentItem11, componentItem11Qty;
                        var i = 0;
                        if (selectsideAPullEye.toUpperCase() === "YES") {
                            if (cableconstruction_facet === "Duplex" || cableconstruction_facet === "Simplex") {
                                var selectedeyeGroup = eyeGroup.filter(pullEye => (pullEye.pullEyeName).toUpperCase() === "SIMPLEX/DUPLEX");
                                componentItem10 = selectedeyeGroup[0].pullEyeItem;
                                componentItem10Qty = 1;
                            } else {
                                var selectedeyeGroup = eyeGroup.filter(pullEye => (pullEye.pullEyeName).toUpperCase() === "OTHER");
                                componentItem10 = selectedeyeGroup[0].pullEyeItem;
                                componentItem10Qty = 1;
                            }
                        } else {
                            var selectedeyeGroup = eyeGroup.filter(pullEye => (pullEye.pullEyeName).toUpperCase() === "NONE");
                            componentItem10 = selectedeyeGroup[0].pullEyeItem;
                            componentItem10Qty = 1;
                        }
                        if (selectsideBPullEye.toUpperCase() === "YES") {
                            if (cableconstruction_facet === "Duplex" || cableconstruction_facet === "Simplex") {
                                var selectedeyeGroup = eyeGroup.filter(pullEye => (pullEye.pullEyeName).toUpperCase() === "SIMPLEX/DUPLEX");
                                componentItem11 = selectedeyeGroup[0].pullEyeItem;
                                componentItem11Qty = 1;
                            } else {
                                var selectedeyeGroup = eyeGroup.filter(pullEye => (pullEye.pullEyeName).toUpperCase() === "OTHER");
                                componentItem11 = selectedeyeGroup[0].pullEyeItem;
                                componentItem11Qty = 1;
                            }
                        } else {
                            var selectedeyeGroup = eyeGroup.filter(pullEye => (pullEye.pullEyeName).toUpperCase() === "NONE");
                            componentItem11 = selectedeyeGroup[0].pullEyeItem;
                            componentItem11Qty = 1;
                        }
                        var offset = this.inputFormDetails.offset;
                        var basePullEyeA = offset.find(offset => (offset.offsetName).toUpperCase() === sideAOffset.toUpperCase()).offsetLegend;
                        if (sideBOffset.toUpperCase() != "NONE") {
                            var basePullEyeB = offset.find(offset => (offset.offsetName).toUpperCase() === sideBOffset.toUpperCase()).offsetLegend;
                        } else {
                            var basePullEyeB = "X";
                        }
                        var baseFiberGrade = this.currentITemInPDP.custitem39 ? this.currentITemInPDP.custitem39 : null;
                        if (baseFiberGrade === null) {
                            baseFiberGrade = this.currentITemInPDP.custitem16 ? this.currentITemInPDP.custitem16 : null;
                        }
                        var classL5 = this.currentITemInPDP.custitem37 ? this.currentITemInPDP.custitem37 : null;
                        var classofBase = this.currentITemInPDP.class ? this.currentITemInPDP.class : null;
                        var senderEmpId = SC.CONFIGURATION.PatchCableConfigurater.senderEmail;
                        var RecieverEmail = SC.CONFIGURATION.PatchCableConfigurater.RecieverEmail;
                        var profileModel = ProfileModel.ProfileModel ? ProfileModel.ProfileModel.getInstance() : ProfileModel.getInstance();
                        var requestedCustomerId = profileModel.get('internalid');
                        var customerId = profileModel.get('name')
                        customerId = customerId.split(" ")[0];
                        var customerEmail = profileModel.get('email') ? profileModel.get('email') : null;
                        var allDetails = {
                            baseCable: baseCable,
                            baseCableId: baseCableId,
                            mode: mode,
                            selectsideAConnector: selectsideAConnector,
                            baseFurcatioOption: baseFurcatioOption,
                            selectsideAHashConnectors: selectsideAHashConnectors,
                            selectsideATubing: selectsideATubing,
                            selectsideAPullEye: selectsideAPullEye,
                            sideAOffset: sideAOffset,
                            selectsideBConnector: selectsideBConnector,
                            selectsideBHashConnectors: selectsideBHashConnectors,
                            selectsideBTubing: selectsideBTubing,
                            selectsideBPullEye: selectsideBPullEye,
                            sideBOffset: sideBOffset,
                            selectedCableLength: selectedCableLength,
                            notes: notes,
                            baseConnectorOption: baseConnectorOption,
                            baseConA: baseConA,
                            baseConB: baseConB,
                            baseJacket: baseJacket,
                            basePolishA: basePolishA,
                            basePolishB: basePolishB,
                            basePullEyeA: basePullEyeA,
                            basePullEyeB: basePullEyeB,
                            sideAPullEye: sideAPullEye,
                            sideBPullEye: sideBPullEye,
                            sideATubing: sideATubing,
                            sideBTubing: sideBTubing,
                            FiberGrade: baseFiberGrade,
                            componentItem2: componentItem2,
                            componentItem2Qty: componentItem2Qty,
                            componentItem3: "CTG-MFG OVERHEAD",
                            componentItem3Qty: componentItem2Qty,
                            componentItem4: "CTG-PATCH-FANOUT",
                            componentItem4Qty: componentItem2Qty,
                            componentItem5: componentItem5,
                            componentItem5Qty: componentItem5Qty,
                            componentItem6: componentItem6,
                            componentItem6Qty: componentItem6Qty,
                            componentItem7: itemComponent_7,
                            componentItem7Qty: componentItem6Qty,
                            componentItem8: itemComponent_8,
                            componentItem8Qty: componentItem6Qty,
                            componentItem9: componentItem9,
                            componentItem9Qty: componentItem9Qty,
                            componentItem10: componentItem10,
                            componentItem10Qty: componentItem10Qty,
                            componentItem11: componentItem11,
                            componentItem11Qty: componentItem11Qty,
                            classL5: classL5,
                            classofBase: classofBase,
                            senderEmpId: senderEmpId,
                            RecieverEmail: RecieverEmail,
                            requestedCustomerId: requestedCustomerId,
                            customerId: customerId,
                            customerEmail: customerEmail,
                            fiberTypeFacet: fiberTypeFacet,
                            cableconstruction_facet: cableconstruction_facet,
                            strandHashIdOfItem: strandHashIdOfItem,
                            cableConstruct: cableConstruct
                        }
                        this.allDetails = allDetails;
                        this.cableModel = new PatchCableConfiguraterSS2Model({ id: JSON.stringify(allDetails) });
                        this.cableModel.fetch().done(function (result) {
                            console.log("result*****", result);
                            if (result === "fail") {
                                // Create a success message element
                                var errorMessage = document.createElement("div");
                                errorMessage.id = "errorMessage";
                                errorMessage.textContent = "Issue occured in the submission of Custom Patch Cable request recheck the input details entered or try after some time"
                                const existingMessage = document.getElementById("errorMessage");
                                if (!existingMessage) {
                                    document.getElementById("responseMessage") ? document.getElementById("responseMessage").style.display = "none" : null;
                                    document.getElementById("patchCableForm").parentElement.appendChild(errorMessage);
                                }
                                // Optionally clear the form fields (if needed)
                                document.getElementById("patchCableForm").style.display = "none";
                            } else {
                                // Create a success message element
                                var successMessage = document.createElement("div");
                                successMessage.id = "successMessage";
                                successMessage.innerHTML = `Thank you, your custom patch cable configuration request has been submitted successfully. 
You will receive an email containing the details of the cable you configured.  
Our team will review your configuration and reach out within the next business day to verify your configuration and place the order.  
If you have any questions, please reach out to <a href="mailto:orders@cleerline.com">orders@cleerline.com</a>.`;
                                const existingMessage = document.getElementById("successMessage");
                                if (!existingMessage) {
                                    document.getElementById("responseMessage") ? document.getElementById("responseMessage").style.display = "none" : null;
                                    document.getElementById("patchCableForm").parentElement.appendChild(successMessage);
                                }
                                // Optionally clear the form fields (if needed)
                                document.getElementById("patchCableForm").style.display = "none";
                            }
                        });
                    }
                } catch (error) {
                    console.log("error", error);
                    // Create a success message element
                    var errorMessage = document.createElement("div");
                    errorMessage.id = "errorMessage";
                    errorMessage.textContent = "Issue occurred during the submission of the Custom Patch Cable request. Please recheck the input details or try again later."
                    const existingMessage = document.getElementById("errorMessage");
                    if (!existingMessage) {
                        document.getElementById("responseMessage") ? document.getElementById("responseMessage").style.display = "none" : null;
                        document.getElementById("patchCableForm").parentElement.appendChild(errorMessage);
                    }
                    // Optionally clear the form fields (if needed)
                    document.getElementById("patchCableForm").style.display = "none";
                }
            }
            //@method getContext @return JJ.PatchCableConfigurater.PatchCableConfigurater.View.Context
            , getContext: function getContext() {
                //@class JJ.PatchCableConfigurater.PatchCableConfigurater.View.Context
                var self = this;
                var Container = this.container;
                var pdp = Container.getComponent('PDP');
                self.itemArray = pdp.getItemInfo().item;
                self.subitem = null;
                var formattedConnectorOptions, filteredOptions;
                // Create a new array where 'NC' is replaced for display purposes
                if (!!self.connectorOptions) {
                    if (self.connectorOptions.includes("LC-OS2") && self.connectorOptions.includes("LC-OS2APC")) {
                        var lcIndex = self.connectorOptions.indexOf("LC-OS2");
                        var apcIndex = self.connectorOptions.indexOf("LC-OS2APC");
                        if (lcIndex > apcIndex) {
                            var lcOption = self.connectorOptions.splice(lcIndex, 1)[0];
                            self.connectorOptions.splice(apcIndex, 0, lcOption);
                        }
                    }
                    const seen = new Set();
                    formattedConnectorOptions = self.connectorOptions.map(option =>
                        option === 'NC' ? { value: 'NC', display: 'No Connectors Option' } : { value: option, display: option }
                    ).filter(opt => {
                        if (seen.has(opt.value)) return false;
                        seen.add(opt.value);
                        return true;
                    });
                    filteredOptions = self.connectorOptions.filter(option => option !== 'NC');
                }
                if (pdp.getSelectedMatrixChilds().length == 1) {
                    self.subitem = pdp.getSelectedMatrixChilds()[0];
                }
                var showBuildPatchButton;
                if (self.subitem != null) {
                    showBuildPatchButton = self.subitem.custitemenablecustompatchcable;
                    self.currentITemInPDP = self.subitem;
                } else {
                    showBuildPatchButton = self.itemArray.custitemenablecustompatchcable
                    self.currentITemInPDP = self.itemArray;
                }
                var selectedItemId = this.currentITemInPDP ? this.currentITemInPDP.itemid : null;
                var formTitle = SC.CONFIGURATION.PatchCableConfigurater.formtitle;
                self.strandsOptions = Array.isArray(self.strandsOptions) ? self.strandsOptions.sort((a, b) => Number(a) - Number(b)) : self.strandsOptions;
                return {
                    showBuildPatchButton: showBuildPatchButton,
                    showPatchForm: this.showPatchForm,
                    formTitle: formTitle,
                    selectedItemId: selectedItemId,
                    connectorOptionssideB: formattedConnectorOptions,
                    connectorOptionssideA: filteredOptions,
                    strandsOptions: self.strandsOptions,
                    furcationOption: self.furcationOption,
                    pullEyeOption: self.pullEyeOption,
                    offsetOption: self.offsetOption
                };
            }
        });
    });

/**
* @NApiVersion 2.x
* @NModuleScope Public
*/
define(['N/search', 'N/file', 'N/email', 'N/log', 'N/runtime'], function (search, file, email, log, runtime) {
    "use strict";
    return {
        service: function (ctx) {
            var connection = [];
            var strands = [];
            var furcation = [];
            var pullEye = [];
            var offset = [];
            var parameter = ctx.request.parameters ? (ctx.request.parameters.internalid) : null;
            try {
                var customrecordconnectoroptionsSearchObj = search.create({
                    type: "customrecordconnectoroptions",
                    filters:
                        [
                            ["isinactive", "is", "F"]
                        ],
                    columns:
                        [
                            search.createColumn({ name: "custrecordconnectoroptionname", label: "Connector Option Name" }),
                            search.createColumn({ name: "custrecordconnectoroptiongroup", label: "Connector Option Group" }),
                            search.createColumn({ name: "custrecordconnectoroptionsitem", label: "Connector Option Item" }),
                            search.createColumn({ name: "custrecordconnectoroptionlegend", label: "Connector Option Legend" }),
                            search.createColumn({ name: "custrecordpolishlegend", label: "Polish Legend" }),
                            search.createColumn({ name: "custrecordftoption", label: "FT Option" }),
                            search.createColumn({ name: "internalid", label: "Internal ID" })
                        ]
                });
                var singleModeOptions = [];
                var multiModeOptions = [];
                var connectAllOptions = [];
                customrecordconnectoroptionsSearchObj.run().each(function (result) {
                    const optionGroup = result.getValue({ name: "custrecordconnectoroptiongroup" });
                    const optionName = result.getValue({ name: "custrecordconnectoroptionname" });
                    const ftOption = result.getValue({ name: "custrecordftoption" });
                    const allFields = {
                        optionName: optionName,
                        optionGroup: optionGroup,
                        optionItem: result.getText({ name: "custrecordconnectoroptionsitem" }),
                        optionItemId: result.getValue({ name: "custrecordconnectoroptionsitem" }),
                        optionLegend: result.getValue({ name: "custrecordconnectoroptionlegend" }),
                        polishLegend: result.getValue({ name: "custrecordpolishlegend" }),
                        ftOption: result.getValue({ name: "custrecordftoption" }),
                        internalId: result.getValue({ name: "internalid" })
                    };
                    connectAllOptions.push(allFields);
                    if (optionGroup === 'Singlemode' && singleModeOptions.indexOf(optionName) === -1) {
                        singleModeOptions.push(optionName);
                    } else if (optionGroup === 'Multimode' && multiModeOptions.indexOf(optionName) === -1) {
                        multiModeOptions.push(optionName);
                    }
                    return true;
                });
                connection = [
                    { group: "Singlemode", options: singleModeOptions },
                    { group: "Multimode", options: multiModeOptions },
                    { group: "All Options", options: connectAllOptions }
                ];
            } catch (error) {
                log.error('Error in fetch of connector option', error);
            }
            try {
                var customrecordstrandsoptionsSearchObj = search.create({
                    type: "customrecordstrandsoptions",
                    filters:
                        [
                            ["isinactive", "is", "F"]
                        ],
                    columns:
                        [
                            search.createColumn({ name: "internalid", label: "Internal ID" }),
                            search.createColumn({ name: "custrecordconnectorcount", label: "Connector Count" }),
                            search.createColumn({ name: "custrecordstrandsgroup", label: "Strands Group" })
                        ]
                });
                var allStrandsGroup = [];
                var uniqueStrand = [];
                customrecordstrandsoptionsSearchObj.run().each(function (result) {
                    var strandsGroup = result.getValue({ name: "custrecordstrandsgroup" });
                    var connectorCount = result.getValue({ name: "custrecordconnectorcount" });
                    allStrandsGroup.push({
                        internalId: result.getValue({ name: "internalid" }),
                        strandsGroup: strandsGroup,
                        connectorCount: connectorCount
                    });
                    if (!uniqueStrand[strandsGroup]) {
                        uniqueStrand[strandsGroup] = [];
                    }
                    if (uniqueStrand[strandsGroup].indexOf(connectorCount) === -1) {
                        uniqueStrand[strandsGroup].push(connectorCount);
                    }
                    return true;
                });
                var uniqueGroupsArray = [];
                for (var group in uniqueStrand) {
                    if (uniqueStrand.hasOwnProperty(group)) {
                        uniqueGroupsArray.push({
                            strandsGroup: group,
                            connectorCounts: uniqueStrand[group]
                        });
                    }
                }
                strands = [
                    { group: "All Strands", options: allStrandsGroup },
                    { group: "unique strands", options: uniqueGroupsArray },
                ];
            } catch (error) {
                log.error('Error in fetch of strand option', error);
            }
            try {
                var customrecordfurcationtubingoptionsSearchObj = search.create({
                    type: "customrecordfurcationtubingoptions",
                    filters:
                        [
                            ["isinactive", "is", "F"]
                        ],
                    columns:
                        [
                            search.createColumn({ name: "internalid", label: "Internal ID" }),
                            search.createColumn({ name: "custrecordname", label: "Furcation Tubing Name" }),
                            search.createColumn({ name: "custrecordfurcationtubingitem", label: "Furcation Tubing Item" }),
                            search.createColumn({ name: "custrecordgroup", label: "Furcation Tubing Group" })
                        ]
                });
                var furcationOptions = [];
                var uniqueFurcation = [];
                customrecordfurcationtubingoptionsSearchObj.run().each(function (result) {
                    var furcationName = result.getValue({ name: "custrecordname" });
                    furcationOptions.push({
                        internalId: result.getValue({ name: "internalid" }),
                        furcationGroup: result.getValue({ name: "custrecordgroup" }),
                        furcationName: furcationName,
                        furcationItemID: result.getValue({ name: "custrecordfurcationtubingitem" }),
                        furcationItem: result.getText({ name: "custrecordfurcationtubingitem" })
                    });
                    uniqueFurcation.push(furcationName);
                    var tempArray = [];
                    for (var i = 0; i < uniqueFurcation.length; i++) {
                        var furcationName = uniqueFurcation[i];
                        if (tempArray.indexOf(furcationName) === -1) {
                            tempArray.push(furcationName);
                        }
                    }
                    uniqueFurcation = tempArray;
                    return true;
                });
                furcation = [
                    { group: "All furcation", options: furcationOptions },
                    { group: "unique Furcation", options: uniqueFurcation },
                ];
            } catch (error) {
                log.error('Error in fetch of furcation option', error);
            }
            try {
                var customrecordpulleyeoptionsSearchObj = search.create({
                    type: "customrecordpulleyeoptions",
                    filters:
                        [
                            ["isinactive", "is", "F"]
                        ],
                    columns:
                        [
                            search.createColumn({ name: "internalid", label: "Internal ID" }),
                            search.createColumn({ name: "custrecordpulleyename", label: "Pull Eye Name" }),
                            search.createColumn({ name: "custrecordpulleyeitem", label: "Pull Eye Item" })
                        ]
                });
                var pullEyeRecord = [];
                customrecordpulleyeoptionsSearchObj.run().each(function (result) {
                    var pullEyeName = result.getValue({ name: "custrecordpulleyename" });
                    pullEyeRecord.push({
                        internalId: result.getValue({ name: "internalid" }),
                        pullEyeName: pullEyeName,
                        pullEyeItemID: result.getValue({ name: "custrecordpulleyeitem" }),
                        pullEyeItem: result.getText({ name: "custrecordpulleyeitem" }),
                    });
                    return true;
                });
                pullEye = pullEyeRecord;
            } catch (error) {
                log.error('Error in fetch of pulleye option', error);
            }
            try {
                var customrecordoffsetlistSearchObj = search.create({
                    type: "customrecordoffsetlist",
                    filters:
                        [
                            ["isinactive", "is", "F"]
                        ],
                    columns:
                        [
                            search.createColumn({ name: "custrecordoffestname", label: "Name" }),
                            search.createColumn({ name: "custrecordoffsetlegend", label: "Legend" })
                        ]
                });
                var offsetRecord = [];
                customrecordoffsetlistSearchObj.run().each(function (result) {
                    offsetRecord.push({
                        offsetName: result.getValue({ name: "custrecordoffestname" }),
                        offsetLegend: result.getValue({ name: "custrecordoffsetlegend" }),
                    });
                    return true;
                });
                offset = offsetRecord;
            } catch (error) {
                log.error('Error in fetch of pulleye option', error);
            }
            if (parameter == null) {
                ctx.response.write(JSON.stringify({
                    connection: connection,
                    strands: strands,
                    furcation: furcation,
                    pullEye: pullEye,
                    offset: offset
                }));
            } else {
                var success;
                try {
                    var formfieldValues = JSON.parse(parameter);
                    var comHashItem1, comHashItem1Name;
                    var x = formfieldValues.baseCable;
                    var self = this;
                    var endsWithB = x.length >= 2 && x[x.length - 2] === '-' && x[x.length - 1] === 'B';
                    if (endsWithB) {
                        comHashItem1 = formfieldValues.baseCable;
                    } else {
                        comHashItem1 = formfieldValues.baseCable + "-B";
                    }
                    var baseFiberPart, baseItemPart, baseColor, baseBrandFacet, comHashItem1ID;
                    var comHashItem1priceLevels = {}, comHashItem2priceLevels = {}, comHashItem6priceLevels = {};
                    var comHashItem3priceLevels, comHashItem7priceLevels, comHashItem4priceLevels, comHashItem8priceLevels;
                    var comHashItem5priceLevels, comHashItem9priceLevels, comHashItem10priceLevels, comHashItem11priceLevels;
                    var basePrice, distributorPrice, InternationalPrice;
                    var itemSearchObj = search.create({
                        type: "item",
                        filters:
                            [
                                ["isinactive", "is", "F"],
                                "AND",
                                ["name", "is", comHashItem1],
                                "AND",
                                ["pricing.minimumquantity", "equalto", "0"],
                                "AND",
                                ["pricing.pricelevel", "noneof", "18"]
                            ],
                        columns:
                            [
                                search.createColumn({ name: "internalid", label: "Internal ID" }),
                                search.createColumn({ name: "custitemfiberlegend", label: "Fiber Legend" }),
                                search.createColumn({ name: "custitemitemlegend", label: "Item Legend" }),
                                search.createColumn({ name: "custitemcolorlegend", label: "Color Legend" }),
                                search.createColumn({ name: "custitembrand_facet", label: "Brand Facet" }),
                                search.createColumn({ name: "itemid", label: "Name" }),
                                search.createColumn({
                                    name: "pricelevel",
                                    join: "pricing",
                                    label: "Price Level"
                                }),
                                search.createColumn({
                                    name: "unitprice",
                                    join: "pricing",
                                    label: "Unit Price"
                                })
                            ]
                    });
                    itemSearchObj.run().each(function (result) {
                        if (!baseFiberPart) {
                            baseFiberPart = result.getValue({ name: "custitemfiberlegend" });
                            baseItemPart = result.getValue({ name: "custitemitemlegend" });
                            comHashItem1ID = result.getValue({ name: "internalid" });
                            baseColor = result.getValue({ name: "custitemcolorlegend" });
                            baseBrandFacet = result.getText({ name: "custitembrand_facet" });
                            comHashItem1Name = result.getValue({ name: "itemid" });
                        }
                        // Get price level and unit price
                        var priceLevel = result.getText({ name: "pricelevel", join: "pricing" });
                        var unitPrice = parseFloat(result.getValue({ name: "unitprice", join: "pricing" })) || 0;
                        if (priceLevel) {
                            priceLevel = priceLevel === "Base Price" ? "BasePrice" : priceLevel;
                            comHashItem1priceLevels[priceLevel] = unitPrice.toFixed(4);
                        }
                        return true;
                    });
                    var componentItem1Qty = Math.round(formfieldValues.selectedCableLength) + 2;
                    var ConnectionType2, ConnectionType6;
                    var comitem2SearchObj = search.create({
                        type: "item",
                        filters:
                            [
                                ["isinactive", "is", "F"],
                                "AND",
                                ["name", "is", formfieldValues.componentItem2],
                                "AND",
                                ["pricing.minimumquantity", "equalto", "0"],
                                "AND",
                                ["pricing.pricelevel", "noneof", "18"]
                            ],
                        columns:
                            [
                                search.createColumn({ name: "internalid", label: "Internal ID" }),
                                search.createColumn({ name: "custitemconnectiontype_facet", label: "Connection Type" }),
                                search.createColumn({
                                    name: "pricelevel",
                                    join: "pricing",
                                    label: "Price Level"
                                }),
                                search.createColumn({
                                    name: "unitprice",
                                    join: "pricing",
                                    label: "Unit Price"
                                })
                            ]
                    });
                    comitem2SearchObj.run().each(function (result) {
                        if (!ConnectionType2) {
                            ConnectionType2 = result.getText({ name: "custitemconnectiontype_facet" });
                        }
                        var priceLevel = result.getText({ name: "pricelevel", join: "pricing" });
                        priceLevel = priceLevel === "Base Price" ? "BasePrice" : priceLevel;
                        var unitPrice = parseFloat(result.getValue({ name: "unitprice", join: "pricing" })) || 0;
                        if (priceLevel) {
                            comHashItem2priceLevels[priceLevel] = unitPrice.toFixed(4);
                        }
                        return true;
                    });
                    var comitem6SearchObj = search.create({
                        type: "item",
                        filters:
                            [
                                ["isinactive", "is", "F"],
                                "AND",
                                ["name", "is", formfieldValues.componentItem6],
                                "AND",
                                ["pricing.minimumquantity", "equalto", "0"],
                                "AND",
                                ["pricing.pricelevel", "noneof", "18"]
                            ],
                        columns:
                            [
                                search.createColumn({ name: "internalid", label: "Internal ID" }),
                                search.createColumn({ name: "custitemconnectiontype_facet", label: "Connection Type" }),
                                search.createColumn({
                                    name: "pricelevel",
                                    join: "pricing",
                                    label: "Price Level"
                                }),
                                search.createColumn({
                                    name: "unitprice",
                                    join: "pricing",
                                    label: "Unit Price"
                                })
                            ]
                    });
                    comitem6SearchObj.run().each(function (result) {
                        if (!ConnectionType6) {
                            ConnectionType6 = result.getText({ name: "custitemconnectiontype_facet" });
                            ConnectionType6 = ConnectionType6 ? ConnectionType6 : "Undefined";
                        }
                        var priceLevel = result.getText({ name: "pricelevel", join: "pricing" });
                        priceLevel = priceLevel === "Base Price" ? "BasePrice" : priceLevel;
                        var unitPrice = parseFloat(result.getValue({ name: "unitprice", join: "pricing" })) || 0;
                        if (priceLevel) {
                            comHashItem6priceLevels[priceLevel] = unitPrice.toFixed(4);
                        }
                        return true;
                    });
                    comHashItem3priceLevels = self.priceCalc(formfieldValues.componentItem3);
                    comHashItem7priceLevels = comHashItem3priceLevels;
                    comHashItem4priceLevels = self.priceCalc(formfieldValues.componentItem4);
                    comHashItem8priceLevels = comHashItem4priceLevels;
                    comHashItem5priceLevels = self.priceCalc(formfieldValues.componentItem5);
                    comHashItem9priceLevels = self.priceCalc(formfieldValues.componentItem9);
                    comHashItem10priceLevels = self.priceCalc(formfieldValues.componentItem10);
                    comHashItem11priceLevels = self.priceCalc(formfieldValues.componentItem11);
                    const itemPriceLevels = [
                        comHashItem1priceLevels, comHashItem2priceLevels, comHashItem3priceLevels,
                        comHashItem4priceLevels, comHashItem5priceLevels, comHashItem6priceLevels,
                        comHashItem7priceLevels, comHashItem8priceLevels, comHashItem9priceLevels,
                        comHashItem10priceLevels, comHashItem11priceLevels
                    ];
                    log.error('itemPriceLevels', JSON.stringify(itemPriceLevels));
                    const itemQuantities = [
                        componentItem1Qty,
                        formfieldValues.componentItem2Qty,
                        formfieldValues.componentItem3Qty,
                        formfieldValues.componentItem4Qty,
                        formfieldValues.componentItem5Qty,
                        formfieldValues.componentItem6Qty,
                        formfieldValues.componentItem7Qty,
                        formfieldValues.componentItem8Qty,
                        formfieldValues.componentItem9Qty,
                        formfieldValues.componentItem10Qty,
                        formfieldValues.componentItem11Qty
                    ];
                    log.error('itemQuantities', JSON.stringify(itemQuantities));
                    var basePrice = 0;
                    var distributorPrice = 0;
                    var InternationalPrice = 0;
                    for (var i = 0; i < itemPriceLevels.length; i++) {
                        var priceLevel = itemPriceLevels[i];
                        var qty = Number(itemQuantities[i]) || 0;
                        var baseComponent = 0;
                        var distributorComponent  = 0;
                        var internationalComponent =0;
                        baseComponent = (Number(priceLevel.BasePrice) || 0) * qty;
                        log.error('baseComponent'+i, baseComponent);
                        distributorComponent = (Number(priceLevel.Distributor) || 0) * qty;
                        internationalComponent = (Number(priceLevel.International) || 0) * qty;
                        basePrice += baseComponent;
                        distributorPrice += distributorComponent;
                        InternationalPrice += internationalComponent;
                    }
                    formfieldValues.basePrice = basePrice.toFixed(2);
                    formfieldValues.distributorPrice = distributorPrice.toFixed(2);
                    formfieldValues.InternationalPrice = InternationalPrice.toFixed(2);
                    formfieldValues.MSRPPrice = (2 * basePrice).toFixed(2);


                    if (baseBrandFacet === "Cleerline SSF™") {
                        baseBrandFacet = "SSF"
                    } else if (baseBrandFacet === "Cleerline TSB™" || baseBrandFacet === "Cleerline BendSafe®") {
                        baseBrandFacet = "BSF"
                    }
                    var x = "standard";
                    var result = x.charAt(0).toUpperCase();
                    var lengthInMeter = Math.round(formfieldValues.selectedCableLength / 3.281);
                    var namePart1, description;
                    formfieldValues.basePullEyeB = formfieldValues.basePullEyeB === "None" ? "X" : formfieldValues.basePullEyeB;
                    if (formfieldValues.selectsideBConnector === "NC") {
                        namePart1 = baseItemPart + "-" + formfieldValues.selectsideAHashConnectors + formfieldValues.selectsideAConnector + "-" + "0NC-XX";
                    } else {
                        namePart1 = baseItemPart + "-" + formfieldValues.selectsideAHashConnectors + formfieldValues.selectsideAConnector + "-" + formfieldValues.selectsideBHashConnectors + formfieldValues.selectsideBConnector;
                    }
                    var namePart2 = lengthInMeter + "m-" + formfieldValues.baseJacket + formfieldValues.basePolishA + formfieldValues.basePolishB + formfieldValues.sideATubing + formfieldValues.sideBTubing + formfieldValues.basePullEyeA + formfieldValues.basePullEyeB + formfieldValues.sideAPullEye + formfieldValues.sideBPullEye + baseBrandFacet;
                    var requestedITem = namePart1 + "-" + namePart2;
                    if (formfieldValues.selectsideBConnector != "NC") {
                        description = "Custom Patch Cable-" + formfieldValues.baseCable + "-" + formfieldValues.selectsideAHashConnectors + "x" + formfieldValues.selectsideAConnector + "-" + formfieldValues.sideATubing + "-" + formfieldValues.selectsideBHashConnectors + "x" + formfieldValues.selectsideBConnector + "-" + formfieldValues.sideBTubing + "-PullEyeA=" + formfieldValues.selectsideAPullEye + "-" + formfieldValues.sideAOffset + "-" + "PullEyeB=" + formfieldValues.selectsideBPullEye + "-" + formfieldValues.sideBOffset + "-" + lengthInMeter + "m/" + formfieldValues.selectedCableLength + "ft";
                    } else {
                        description = "Custom Patch Cable-" + formfieldValues.baseCable + "-" + formfieldValues.selectsideAHashConnectors + "x" + formfieldValues.selectsideAConnector + "-" + formfieldValues.sideATubing + "-" + "0xNC" + "-" + formfieldValues.sideBTubing + "-PullEyeA=" + formfieldValues.selectsideAPullEye + "-" + formfieldValues.sideAOffset + "-" + "PullEyeB=" + formfieldValues.selectsideBPullEye + "-" + formfieldValues.sideBOffset + "-" + lengthInMeter + "m/" + formfieldValues.selectedCableLength + "ft";
                    }
                    var strandCount = formfieldValues.baseConnectorOption;
                    formfieldValues.baseFiberPart = baseFiberPart;
                    formfieldValues.baseColor = baseColor;
                    formfieldValues.baseBrandFacet = baseBrandFacet;
                    formfieldValues.requestedITem = requestedITem;
                    formfieldValues.description = description;
                    formfieldValues.strandCount = strandCount;
                    formfieldValues.Foot = Math.round(formfieldValues.selectedCableLength);
                    formfieldValues.componentItem1 = comHashItem1Name;
                    formfieldValues.componentItem1Qty = componentItem1Qty;
                    formfieldValues.classL6 = formfieldValues.mode;
                    formfieldValues.classtierTwo = "Custom Assemblies";
                    if (formfieldValues.selectsideAConnector != formfieldValues.selectsideBConnector) {
                        formfieldValues.ConnectionTypeFacet = ConnectionType2 + "-" + ConnectionType6;
                    } else {
                        formfieldValues.ConnectionTypeFacet = ConnectionType2
                    }
                    formfieldValues.class = "Cleerline FG : Cables : Fiber Patch Cables : Custom Assemblies : " + formfieldValues.classL5 + " : " + formfieldValues.classL6 + " : " + formfieldValues.ConnectionTypeFacet;
                   
                    formfieldValues.usebins = true;
                    formfieldValues.custitemdiscoitem = true;
                    log.error('formfieldValues', JSON.stringify(formfieldValues));
                    // Define CSV headers
                    const headers = [
                        'Item Name',
                        'Description',
                        'Strand Count',
                        'Class',
                        'Components Item #1',
                        'Components Item #1 Qty',
                        'Components Item #2',
                        'Components Item #2 Qty',
                        'Components Item #3',
                        'Components Item #3 Qty',
                        'Components Item #4',
                        'Components Item #4 Qty',
                        'Components Item #5',
                        'Components Item #5 Qty',
                        'Components Item #6',
                        'Components Item #6 Qty',
                        'Components Item #7',
                        'Components Item #7 Qty',
                        'Components Item #8',
                        'Components Item #8 Qty',
                        'Components Item #9',
                        'Components Item #9 Qty',
                        'Components Item #10',
                        'Components Item #10 Qty',
                        'Components Item #11',
                        'Components Item #11 Qty',
                        'Price Level Base Price',
                        'Price Level Distributor',
                        'Price Level International',
                        'Price Level MSRP',
                        'Class L5',
                        'Class L6',
                        'Class Tier Two',
                        'Fiber Type Facet',
                        'Connection Type Facet',
                        'Cable Construction Facet',
                        'Fiber Grade Facet',
                        'Use Bins',
                        'Disco Item'
                    ];
                    const rows = [
                        [
                            formfieldValues.requestedITem || '',
                            formfieldValues.description || '',
                            formfieldValues.strandCount || '',
                            formfieldValues.class || '',
                            formfieldValues.componentItem1 || '',
                            formfieldValues.componentItem1Qty || '',
                            formfieldValues.componentItem2 || '',
                            formfieldValues.componentItem2Qty || '',
                            formfieldValues.componentItem3 || '',
                            formfieldValues.componentItem3Qty || '',
                            formfieldValues.componentItem4 || '',
                            formfieldValues.componentItem4Qty || '',
                            formfieldValues.componentItem5 || '',
                            formfieldValues.componentItem5Qty || '',
                            formfieldValues.componentItem6 || '',
                            formfieldValues.componentItem6Qty || '',
                            formfieldValues.componentItem7 || '',
                            formfieldValues.componentItem7Qty || '',
                            formfieldValues.componentItem8 || '',
                            formfieldValues.componentItem8Qty || '',
                            formfieldValues.componentItem9 || '',
                            formfieldValues.componentItem9Qty || '',
                            formfieldValues.componentItem10 || '',
                            formfieldValues.componentItem10Qty || '',
                            formfieldValues.componentItem11 || '',
                            formfieldValues.componentItem11Qty || '',
                            formfieldValues.basePrice || '',
                            formfieldValues.distributorPrice || '',
                            formfieldValues.InternationalPrice || '',
                            formfieldValues.MSRPPrice || '',
                            formfieldValues.classL5 || '',
                            formfieldValues.classL6 || '',
                            formfieldValues.classtierTwo || '',
                            formfieldValues.fiberTypeFacet || '',
                            formfieldValues.ConnectionTypeFacet || '',
                            formfieldValues.cableconstruction_facet || '',
                            formfieldValues.FiberGrade || '',
                            formfieldValues.usebins || '',
                            formfieldValues.custitemdiscoitem || ''
                        ],
                    ];
                    // Create CSV content
                    var csvContent = headers.join(',') + 'n'; // Add headers
                    rows.forEach(function (row) {
                        csvContent += row.join(',') + 'n'; // Add each row
                    });
                    const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14);
                    var fileName = formfieldValues.requestedITem + "-" + "Custid-" + formfieldValues.customerId + "-" + timestamp;
                    // Create CSV file
                    const csvFile = file.create({
                        name: fileName,
                        fileType: file.Type.CSV,
                        contents: csvContent,
                        folder: 1465256,
                        isOnline: true
                    });


                    // Save CSV file to the file cabinet
                    const fileId = csvFile.save();
                    log.error('File Saved', 'File ID: ' + fileId);


                    // Load the saved file for email attachment
                    const savedFile = file.load({
                        id: fileId,
                    });
                    var repEmail;
                    var customerSearchObj = search.create({
                        type: "customer",
                        filters:
                            [
                                ["internalid", "anyof", formfieldValues.requestedCustomerId]
                            ],
                        columns:
                            [
                                search.createColumn({ name: "salesrep", label: "Sales Rep" }),
                                search.createColumn({
                                    name: "email",
                                    join: "salesRep",
                                    label: "Email"
                                })
                            ]
                    });
                    customerSearchObj.run().each(function (result) {
                        repEmail = result.getValue({ name: "email", join: "salesRep" });
                        return true;
                    });


                    log.error('File repEmail11', repEmail);
                    // Define recipient email
                    var sendList;
                    var recipientEmail = formfieldValues.RecieverEmail ? formfieldValues.RecieverEmail : "orders@cleerline.com";
                    sendList = [recipientEmail];
                    var custEmail = formfieldValues.customerEmail;
                    if (custEmail != null) {
                        sendList.push(custEmail);
                    }
                    if (repEmail != null) {
                        sendList.push(repEmail);
                    }
                    // Get sender email from the current user
                    const senderEmail = Number(formfieldValues.senderEmpId);
                    var body = "Thank you for submitting your Cleerline custom patch cable configuration request. Typical lead time for shipment is 7 to 10 business days, depending on cable type and quantity. If your order requires additional processing time, a Cleerline team member will contact you. <b>Please note that all custom patch cables are non-returnable and non-refundable, and orders cannot be modified once production has begun.</b>" + "<br><br>";
                    body += "Below are the details of your configuration: " + "<br><br>";
                    body += "<b> Selected Cable:</b> " + formfieldValues.baseCable + "<br>";
                    body += "n" + "<b>Side A Connector:</b> " + formfieldValues.selectsideAConnector + "<br>";
                    body += "<b>Side A # of Connectors:</b> " + formfieldValues.selectsideAHashConnectors + "<br>";
                    body += "<b>Side A Furcation Tubing:</b> " + formfieldValues.selectsideATubing + "<br>";
                    body += "<b>Side A Connector Offset:</b> " + formfieldValues.sideAOffset + "<br>";
                    body += "<b>Side A Pull Eye:</b> " + formfieldValues.selectsideAPullEye + "<br><br>";
                    body += "<b>Side B Connector:</b> " + formfieldValues.selectsideBConnector + "<br>";
                    body += "<b>Side B # of Connectors:</b> " + formfieldValues.selectsideBHashConnectors + "<br>";
                    body += "<b>Side B Furcation Tubing: </b>" + formfieldValues.selectsideBTubing + "<br>";
                    body += "<b>Side B Connector Offset: </b>" + formfieldValues.sideBOffset + "<br>";
                    body += "<b>Side B Pull Eye:</b> " + formfieldValues.selectsideBPullEye + "<br><br>";
                    body += "<b>Cable Length (ft):</b> " + formfieldValues.selectedCableLength + "<br>";
                    body += "<b>Cable Length (Meter): </b>" + lengthInMeter + "<br><br>";
                    if (formfieldValues.notes && formfieldValues.notes.trim() !== "") {
                        body += "<b>Notes:</b> " + formfieldValues.notes + "<br><br>";
                    }
                    body += "Here is the item name for your cable: <b>" + formfieldValues.requestedITem + "</b><br><br>";
                    body += "Our customer service team will send you a quote for this cable configuration.<br><br>";
                    body += "Thank you,<br><br>";
                    body += "The Cleerline Team<br>";
                    // Send email with the CSV attachment
                    email.send({
                        author: senderEmail,
                        recipients: sendList,
                        subject: 'Cleerline Custom Patch Cable Configuration',
                        body: body
                    });
                    success = { result: "success", value: requestedITem };
                } catch (error) {
                    success = "fail";
                    log.error('Error in CSV field Calculation', error);
                }
                ctx.response.write(JSON.stringify(success));
            }
        },
        priceCalc: function (itemName) {
            var priceLevels = {};
            var itemSearch = search.create({
                type: "item",
                filters: [
                    ["isinactive", "is", "F"],
                    "AND", ["name", "is", itemName],
                    "AND", ["pricing.minimumquantity", "equalto", "0"],
                    "AND", ["pricing.pricelevel", "noneof", "18"]
                ],
                columns: [
                    search.createColumn({ name: "internalid" }),
                    search.createColumn({ name: "pricelevel", join: "pricing" }),
                    search.createColumn({ name: "unitprice", join: "pricing" })
                ]
            });
            itemSearch.run().each(function (res) {
                var level = res.getText({ name: "pricelevel", join: "pricing" });
                if (!level) return true;
                level = level === "Base Price" ? "BasePrice" : level;
                var price = parseFloat(res.getValue({ name: "unitprice", join: "pricing" })) || 0;
                priceLevels[level] = price.toFixed(4);
                return true;
            });
            return priceLevels;
        }


    };
});


Leave a comment

Your email address will not be published. Required fields are marked *