Untitled

mail@pastecode.io avatar
unknown
plain_text
4 months ago
15 kB
5
Indexable
import { LightningElement, api, track, wire } from 'lwc';
import { getFocusedTabInfo, refreshTab } from 'lightning/platformWorkspaceApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import calloutToHeroku from "@salesforce/apex/ComXHerokuCalloutUtil.calloutToHeroku";
import flatpick from '@salesforce/resourceUrl/flatpick';
import { loadStyle, loadScript } from "lightning/platformResourceLoader";

import Chartering_in_Product_Approval_Form__OBJ from "@salesforce/schema/Chartering_in_Product_Approval_Form__c";
import { getObjectInfo, getPicklistValues } from "lightning/uiObjectInfoApi";
import Cargo_FIELD from "@salesforce/schema/Cargo_detail__c.Cargo__c";
import Quantity_FIELD from "@salesforce/schema/Cargo_detail__c.Quantity__c";
import Unit_FIELD from "@salesforce/schema/Cargo_detail__c.Unit__c";

var flatpickdp = {};

export default class CharteringInProductApprovalFormDetail extends LightningElement {
    recordTypeId;
    @api recordId;
    @api approvalId; // Added approvalId for cargo-related actions
    @track showCharteringInDetail = true;
    @track showBSSDetails = true;
    @track showReasonCharteringInDetails = true;
    @track showCommentFromTraderDetails = true;
    @track isUpdate = false;
    @track combinedVesselLaycan;
    @track reasonForCharteringIn;
    @track commentFromTrader;
    @track bssItems = [];
    @track bssValue;
    @track bssLoadPorts = [];
    @track bssDischargePorts = [];
    @track charteringInList;
    @track cargoOtherUnit = false;
    @track isLoad = true;
    @track showCargoTab = true; // Updated
    @track showDetail = true; // New
    @track cargoDetails = []; // New

    @track cargoOptions = []; // New
    @track quantityOptions = []; // New
    @track unitOptions = []; // New

    field_padding = 'horizontal-small';
    datepickerInitialized = false;
    @track firstTimeOpenVesselLaycanDate = true;
    @track vesselLaycanDate;
    @track vesselLaycanDateStart = '';
    @track vesselLaycanDateEnd = '';

    @wire(getObjectInfo, { objectApiName: Chartering_in_Product_Approval_Form__OBJ })
    charteringInProductApprovallInfo({ error, data }) {
        if (data) {
            this.recordTypeId = data.defaultRecordTypeId;
        } else if (error) {
            this.recordTypeId = undefined;
        }
    }

    @wire(getPicklistValues, {
        recordTypeId: "$recordTypeId",
        fieldApiName: Cargo_FIELD
    })
    cargoPicklist({ error, data }) {
        if (data) {
            this.cargoOptions = data.values;
        } else if (error) {
            this.cargoOptions = [];
        }
    }

    @wire(getPicklistValues, {
        recordTypeId: "$recordTypeId",
        fieldApiName: Quantity_FIELD
    })
    quantityPicklist({ error, data }) {
        if (data) {
            this.quantityOptions = data.values;
        } else if (error) {
            this.quantityOptions = [];
        }
    }

    @wire(getPicklistValues, {
        recordTypeId: "$recordTypeId",
        fieldApiName: Unit_FIELD
    })
    unitPicklist({ error, data }) {
        if (data) {
            this.unitOptions = data.values;
        } else if (error) {
            this.unitOptions = [];
        }
    }

    connectedCallback() {
        this.fetchCharteringInList();
        //this.cargoDetails = [{ id: 1, Name: ' ', Quantity__c: ' ', Tolerance__c: 0, Unit__c: ' ' }, ...this.cargoDetails];
        this.cargoDetails = [{ id: 1, Name:this.cargoDetails[1], Quantity__c: ' ', Tolerance__c: 0, Unit__c: ' ' }, ...this.cargoDetails];
        if (this.datepickerInitialized){
            this.isLoad = false;
            return;
        } 
        this.datepickerInitialized = true;

        Promise.all([
            loadScript(this, flatpick + '/flatpickr.js'),
            loadStyle(this, flatpick + '/flatpickr.min.css')
        ]).then(() => {
            this.isLoad = false;
            // console.log('loadScript and loadStyle Success');
        }).catch(error => {
            this.isLoad = false;
            console.log({ message: 'Error onloading', error });
        });
    }

    // Fetching chartering in list
    async fetchCharteringInList() {
        try {
            const body = { recordId: this.recordId };
            const result = await calloutToHeroku({ http_method: "GET", endpoint_path: "/chartering-in-product", req_body: JSON.stringify(body) });
            const s_result = JSON.parse(result);
            this.charteringInList = s_result.detail[0];

            this.isLoad = false;
            this.bssValue = this.charteringInList.BSS__c;
            this.bssItems = this.charteringInList.BSS__c;
            this.generateBSSPorts(this.bssValue);

            this.cargoDetails = this.charteringInList.Cargo_detail__r.records.map((cargo, index) => ({
                id: index + 1, // Added id based on index
                Cargo__c: cargo.Cargo__c,
                Quantity__c: cargo.Quantity__c ? cargo.Quantity__c : '',
                Tolerance__c: cargo.Tolerance__c ? cargo.Tolerance__c : '',
                Unit__c: cargo.Unit__c ? cargo.Unit__c : ''
            }));
            //this.cargoDetails = [{ id: 1, Name:this.cargoDetails[1], Quantity__c: ' ', Tolerance__c: 0, Unit__c: ' ' }, ...this.cargoDetails];
        } catch (error) {
            console.error(error);
        }
    }

    // Handle adding new cargo
    handleAddCargo() {
        const newCargo = {
            id: this.cargoDetails.length + 1,
            name: '',
            quantity: '',
            tolerance: 0,
            unit: '',
            customUnit: '' // Added custom unit field
        };
        this.cargoDetails.push(newCargo);
    }

    // Handle deleting the last cargo
    handleDeleteCargo() {
        if (this.cargoDetails.length > 0) {
            this.cargoDetails.pop();
        }
    }

    // Handle unit field changes
    handleChangeUnit(event) {
        const cargoId = event.target.dataset.id;
        const cargo = this.cargoDetails.find(cargo => cargo.id === cargoId);
        cargo.unit = event.detail.value;
        // Update customUnit based on selected unit
        if (cargo.unit === 'OTHER') {
            this.cargoOtherUnit = '';
        }
    }

    // Handle generic value changes
    handleChangeValue(event) {
        const cargoId = event.target.dataset.id;
        const cargo = this.cargoDetails.find(cargo => cargo.id === cargoId);
        const field = event.target.dataset.targetId;
        cargo[field] = event.detail.value;
    }

    // Handle custom unit changes
    handleChangeCustomUnit(event) {
        const cargoId = event.target.dataset.id;
        const cargo = this.cargoDetails.find(cargo => cargo.id === cargoId);
        cargo.customUnit = event.detail.value;
    }

    handleShowDatePickVesselLaycan() {
        if (this.firstTimeOpenVesselLaycanDate) {
            this.datepickFocus();
            this.firstTimeOpenVesselLaycanDate = false;
        }

        const inputElement = this.template.querySelector('[data-id="flatpickr"]');
        if (inputElement) {
            inputElement.click();
        }
    }

    datepickFocus() {
        if (this.firstTimeOpenVesselLaycanDate) {
            this.firstTimeOpenVesselLaycanDate = false;
        }

        const dpDiv = this.template.querySelector('[data-id="flatpickr"]');
        flatpickdp = flatpickr(dpDiv, {
            inline: false,
            minDate: "today",
            mode: "range",
            onChange: function (selectedDates, dateStr, instance) {

                // console.log('Start : ', selectedDates);
                console.log('onChange: selectedDates: ', selectedDates);
                console.log('onChange: dateStr: ', dateStr);
                // console.log('onChange: instance: ', instance);
            },

            onOpen: [
                function (selectedDates, dateStr, instance) {
                    // console.log('onOpen: selectedDates: ', selectedDates);
                    // console.log('onOpen: dateStr: ', dateStr);
                },
            ],

            onClose: function (selectedDates, dateStr, instance) {
                // console.log('onClose: selectedDates: ', selectedDates);
                // console.log('onClose: dateStr: ', dateStr);
            }
        });

        if (dpDiv.value && dpDiv.value !== undefined) {
            const dates = dpDiv.value.split(' to ');
            if (dates.length === 2) {
                if (dates[0] !== undefined && dates[1] !== undefined) {
                    this.vesselLaycanDateStart = dates[0];
                    this.vesselLaycanDateEnd = dates[1];
                    
                    if (this.vesselLaycanDateStart === undefined || this.vesselLaycanDateEnd === undefined) {
                        this.vesselLaycanDateStart = null;
                        this.vesselLaycanDateEnd = null;
                        this.vesselLaycanDate = null;
                    } else {
                        this.vesselLaycanDate = this.vesselLaycanDateStart.toString() + ' to ' + this.vesselLaycanDateEnd.toString();
                    }
                    
                    this.template.querySelector("lightning-input-field[data-field=Vessel_Laycan_Start__c]").value = this.vesselLaycanDateStart;
                    this.template.querySelector("lightning-input-field[data-field=Vessel_Laycan_End__c]").value = this.vesselLaycanDateEnd;
                }
            }
        }
    }

    handleVesselLaycanDateChange() {
        if (this.vesselLaycanDateStart === undefined || this.vesselLaycanDateEnd === undefined) {
            this.vesselLaycanDate = this.vesselLaycanDateStart + ' to ' + this.vesselLaycanDateEnd;
            this.template.querySelector("lightning-input-field[data-field=Vessel_Laycan_Start__c]").value = this.vesselLaycanDateStart;
            this.template.querySelector("lightning-input-field[data-field=Vessel_Laycan_End__c]").value = this.vesselLaycanDateEnd;
        }
    }

    clearDatePickValueEs() {
        this.vesselLaycanDate = '';
    }
    handleInputChange(event) {
        if (event.target.fieldName === 'BSS__c') {
            this.bssValue = event.target.value;
            console.log('this.bssValue = ', this.bssValue);
            this.generateBSSPorts(this.bssValue);
        }
    }
    
    generateBSSPorts(bssValue) {
        const [loadPortCount, dischargePortCount] = bssValue.split(':').map(Number);
    
        // Clear existing ports
        this.bssLoadPorts = [];
        this.bssDischargePorts = [];
        this.bssCombinedPorts = [];
    
        // Populate Load Ports
        for (let i = 0; i < loadPortCount; i++) {
            this.bssLoadPorts.push({
                portFieldName: `Load_Port_${i + 1}`,
                value: '',
                key: i
            });
        }
    
        // Populate Discharge Ports
        for (let i = 0; i < dischargePortCount; i++) {
            this.bssDischargePorts.push({
                portFieldName: `Discharge_Port_${i + 1}`,
                value: '',
                key: i
            });
        }
    
        // Combine load and discharge ports into one array for rendering
        const maxLength = Math.max(loadPortCount, dischargePortCount);
        for (let i = 0; i < maxLength; i++) {
            this.bssCombinedPorts.push({
                key: i,
                loadPort: this.bssLoadPorts[i] || { portFieldName: '', value: '', key: i },
                dischargePort: this.bssDischargePorts[i] || { portFieldName: '', value: '', key: i }
            });
        }
    }
    
    handlePortPairLoadPortChange(event) {
        const key = event.target.dataset.id;
        const value = event.detail.value;

        console.log('handlePortPairLoadPortChange_key : ', key);
        console.log('handlePortPairLoadPortChange_value : ', value);
    }

    handlePortPairDischargePortChange(event) {
        const key = event.target.dataset.id;
        const value = event.detail.value;

        console.log('handlePortPairDischargePortChange_key : ', key);
        console.log('handlePortPairDischargePortChange_value : ', value);
    }

    // Handle port change
    handlePortChange(event) {
        const fieldKey = event.target.dataset.index;
        const newValue = event.target.value;

        // Update the relevant port value in the bssCombinedPorts array
        this.bssCombinedPorts = this.bssCombinedPorts.map((portPair) => {
            if (portPair.loadPort.key === fieldKey) {
                // Update load port value
                return {
                    ...portPair,
                    loadPort: { ...portPair.loadPort, value: newValue }
                };
            } else if (portPair.dischargePort.key === fieldKey) {
                // Update discharge port value
                return {
                    ...portPair,
                    dischargePort: { ...portPair.dischargePort, value: newValue }
                };
            }
            return portPair;
        });
    }

    submitForm() {
        const btnAccount = this.template.querySelector(".hidden-account");
        if (btnAccount) {
            btnAccount.click();
        }
    }

    handleSubmit(event) {
        const fields = event.detail.fields;
        event.preventDefault();
        this.template.querySelector('lightning-record-edit-form').submit(fields);
    }

    handleSuccess() {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: 'Chartering In Product Approval Form updated successfully.',
                variant: 'success'
            })
        );

        this.combinedVesselLaycan = '';
        this.reasonForCharteringIn = '';
        this.commentFromTrader = '';
        this.bssItems = [];
        this.isUpdate = false;
        this.refreshTab();
    }

    async refreshTab() {
        if (!this.isConsoleNavigation) {
            return;
        }
        const { tabId } = await getFocusedTabInfo();
        await refreshTab(tabId, {
            includeAllSubtabs: true
        });
    }


    
    handleUpdateDetail(){
        this.isUpdate = true;
    }


    handleError(event) {
        console.log(JSON.parse(JSON.stringify(event.detail)));
    }

    handleCancelClick() {
        this.isUpdate = false;
        this.refreshTab();
    }


    handleShowCharteringInDetailClick(){
        this.showCharteringInDetail = !this.showCharteringInDetail;
    }

    handleShowCargoDetailClick(){
        this.showCargoTab = !this.showCargoTab;
    }

    handleShowBSSDetailClick(){
        this.showBSSDetails = !this.showBSSDetails;
    }

    handleShowReasonCharteringInDetailClick(){
        this.showReasonCharteringInDetails = !this.showReasonCharteringInDetails;
    }


}
Leave a Comment