Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

const openESignRequest = async (cmrId) => { try { const otherData = await…

  1. User

    const openESignRequest = async (cmrId) => { try { const otherData = await getCMRDetailsById(cmrId); console.log(otherData); const pdfFile = await getCMRPdfById(cmrId); console.log(pdfFile) EMGRSignUtils.sendESignDocuments('CMR', cmrId, otherData); } catch (error) { emgrToast.error("Error opening e-sign request:", error); } };

    const getCMRDetailsById = async (cmrId) => {
    	let url = AppContext.restUrl + 'CMR/getCMRDetailById';
    	$(".gridloading").show();
    
    	try {
    		const response = await $.ajax({
    			url: url,
    			type: 'POST',
    			data: { "data": Base64.encode(JSON.stringify({ "cmrId": cmrId })) },
    		});
    		let otherData = {};
    		let recipientList = [];
    		//Create Recipient List
    		if(response.approverlist && response.approverlist.length > 0) {
    			response.approverlist.forEach((element) => {
    				if(element.uemail !== '') {
    					recipientList.push({
    						"userType" : "Client",
    						"role" : "",
    						"recipientName": element.contactname,
    						"recipientEmail": element.uemail,
    						"recipientType": element.reviewerfrom === 'portalUser' ? "Portal User" : "Client User",
    						"recipientId": element.contactid,
    						"clientName": response.clientname || '',
    						"clientId": response.clientid
    					});
    				}
    			});
    		}
    
    		//Create Task Associate Entity
    		let associateList = [];
    		if(response.tasklist && response.tasklist.length > 0) {
    			response.tasklist.forEach((element) => {
    				associateList.push({
    					"entityType": "Task",
    					"entityId": element.id
    				})
    			});
    		}
    		//Create Case Associate Entity
    		if(response.caselist && response.caselist.length > 0) {
    			response.caselist.forEach((element) => {
    				associateList.push({
    					"entityType": "Case",
    					"entityId": element.ticketid
    				})
    			});
    		}
    		//Create IR Associate Entity
    		if(response.irlist && response.irlist.length > 0) {
    			response.irlist.forEach((element) => {
    				associateList.push({
    					"entityType": "IR",
    					"entityId": element.irid
    				})
    			});
    		}
    
    		otherData['associateEntity'] = associateList;
    		otherData['recipientDetails'] = recipientList
    		return otherData;
    	} catch (error) {
    		emgrToast.error("Error while retrieving data!!", 5000);
    	} finally {
    		$(".gridloading").hide();
    	}
    };
    
    const getCMRPdfById = async (cmrId) => {
    	let requestObject = {"cmrId": cmrId}
    	let url = AppContext.restUrl + 'CMR/getCMRPdfById?data=' + btoa(JSON.stringify(requestObject));
    	$(".gridloading").show();
    
    	try {
    		const response = await $.ajax({
    			url: url,
    			type: 'GET',
    			xhrFields: {
    				responseType: 'blob'
    			},
    			contentType: false,
    			processData: false,
    		});
    		return URL.createObjectURL(response);
    	} catch (error) {
    		emgrToast.error("Error while retrieving pdf file!!", 5000);
    	} finally {
    		$(".gridloading").hide();
    	}
    }
    

    please refactor code

  2. Assistant

    Certainly! Refactoring code can help improve readability, maintainability, and overall performance. Below is a refactored version of your provided code. I've condensed some duplicated logic, improved error messages, and enhanced overall structure:

    const openESignRequest = async (cmrId) => {
        try {
            const otherData = await getCMRDetailsById(cmrId);
            const pdfFile = await getCMRPdfById(cmrId);
            
            console.log(otherData, pdfFile);
            EMGRSignUtils.sendESignDocuments('CMR', cmrId, otherData);
        } catch (error) {
            emgrToast.error(`Error opening e-sign request: ${error.message}`);
        }
    };
    
    const getCMRDetailsById = async (cmrId) => {
        const url = `${AppContext.restUrl}CMR/getCMRDetailById`;
        $(".gridloading").show();
    
        try {
            const response = await $.ajax({
                url,
                type: 'POST',
                data: { "data": Base64.encode(JSON.stringify({ "cmrId": cmrId })) },
            });
    
            const otherData = {
                associateEntity: [],
                recipientDetails: createRecipientList(response.approverlist),
            };
    
            // Collect associate entities (Tasks, Cases, IRs)
            otherData.associateEntity = [
                ...createAssociateEntities(response.tasklist, "Task"),
                ...createAssociateEntities(response.caselist, "Case"),
                ...createAssociateEntities(response.irlist, "IR"),
            ];
    
            return otherData;
        } catch (error) {
            emgrToast.error("Error while retrieving data: " + error.message, 5000);
        } finally {
            $(".gridloading").hide();
        }
    };
    
    const createRecipientList = (approverList) => {
        return approverList?.filter(element => element.uemail)
            .map(element => ({
                userType: "Client",
                role: "",
                recipientName: element.contactname,
                recipientEmail: element.uemail,
                recipientType: element.reviewerfrom === 'portalUser' ? "Portal User" : "Client User",
                recipientId: element.contactid,
                clientName: element.clientname || '',
                clientId: element.clientid,
            })) || [];
    };
    
    const createAssociateEntities = (items, entityType) => {
        return items?.map(element => ({
            entityType,
            entityId: element.id || element.ticketid || element.irid,
        })) || [];
    };
    
    const getCMRPdfById = async (cmrId) => {
        const url = `${AppContext.restUrl}CMR/getCMRPdfById?data=${btoa(JSON.stringify({ cmrId }))}`;
        $(".gridloading").show();
    
        try {
            const response = await $.ajax({
                url,
                type: 'GET',
                xhrFields: { responseType: 'blob' },
                contentType: false,
                processData: false,
            });
            return URL.createObjectURL(response);
        } catch (error) {
            emgrToast.error("Error while retrieving pdf file: " + error.message, 5000);
        } finally {
            $(".gridloading").hide();
        }
    };
    

    Changes Made:

    1. Error Messaging: Improved the error messages to provide more context.
    2. Helper Functions: Created createRecipientList and createAssociateEntities to modularize the recipient and associate entity creation logic.
    3. Destructured and Improved Logic: Used optional chaining (?.) and simplified the filtering and mapping processes.
    4. Better Concatenation of Associate Entities: Combined the creation of associate entities into one concise array initialization.

    This refactored version should still maintain the same functionality while being more maintainable and easier to read.