Create a Cash Refund In Big Commerce from NetSuite through API

Solution

Below code shows creating a cash refund in Big Commerce if the related order exists in Big Commerce

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 * 
 * * The Nutty Company, Inc - USA-NS
 *
 * NUTC-49 : Cash Refund Sync (NetSuite-Big Commerce)
 *
 *
 **************************************************************************************
 ********
 *
 * Author: Jobin and Jismi IT Services
 *
 * Date Created : 18-May-2023
 *
 * Description : This is a user event script to Cash Refund sync from netsuite to big commerce
 *
 * REVISION HISTORY
 *
 * @version 1.0 NUTC-49 : 18-May-2023 : Created the initial build by JJ0131
 * **************************************************************************************
 * 
 */
define(['N/record', 'N/search', 'N/https', '../NUTC 40 Big Commerce Common Library/jj_big_commerce_common_library_nutc40.js'],
    /**
   * @param{record} record
   * @param{search} search
   * @param{https} https
   * @param{LibraryScript} bigComLibrary
   */
    (record, search, https, bigComLibrary) => {

        /**
   * @function afterSubmit
   * @param{Object} context
   */
        const afterSubmit = (scriptContext) => {
             if (scriptContext.type != "create") return;
            const refundRecord = scriptContext.newRecord;
            const refundRecId = refundRecord.id;
        
            try {
                const productAPI = bigComLibrary.BIG_COM_API_REQUESTS.FETCH_ITEMS_IN_ORDER;

                let items = [];
                let cashRefundBody = {};

                const cashSale = refundRecord.getValue({
                    fieldId: 'createdfrom'
                });
                const lineCount = refundRecord.getLineCount({
                    sublistId: 'item'
                });

                let cashSaleSearch = search.lookupFields({
                    type: 'cashsale',
                    id: cashSale,
                    columns: ['custbody_jj_big_commerce_order_id']
                });

                const bgComId = cashSaleSearch.custbody_jj_big_commerce_order_id;

                let refundAPI = '/v3/orders/' + bgComId + '/payment_actions/refund_quotes'
                const newProductAPI = productAPI.replace("{orderId}", bgComId)
                //getting products from Big commerce
                const getProducts = bigComLibrary.commonFunctions.sendGetAPIRequest(newProductAPI);
                let productList = JSON.parse(getProducts.body);

                for (let i = 0; i < lineCount; i++) {
                    let item = refundRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'item_display',
                        line: i
                    })
                    let products = [];
                    //creating a item object for creating refund qoutes
                    for (let j = 0; j < productList.length; j++) {
                        log.debug("item", productList[j].sku)
                        if (item == productList[j].sku) {
                            let itemProdObj = {};
                            let itemOrdrObj = {};
                            let itemId = productList[j].id;

                            let qty = Number(refundRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'quantity',
                                line: i
                            }))
                            let reason = refundRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_atlas_return_reason',
                                line: i
                            })
                            let amount = refundRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'amount',
                                line: i
                            })
                            itemProdObj.item_type = "PRODUCT";
                            itemProdObj.item_id = itemId;
                            itemProdObj.quantity = qty;
                            itemProdObj.requested_amount = amount;
                            itemProdObj.reason = reason;
                            items.push(itemProdObj);
                           /* itemOrdrObj.item_type = "ORDER";
                            itemOrdrObj.item_id = itemId;
                            itemOrdrObj.amount = amount;
                            itemOrdrObj.reason = reason;
                            items.push(itemOrdrObj);*/
                        }
                    }
                }

                cashRefundBody.items = items;
                //creating refund qoutes on big commerce
                let refundResponse = postAPI(refundAPI, cashRefundBody)
                log.debug("RefundResponse", refundResponse.body)
                if (refundResponse.code != 200) {
                    let refundErr = refundResponse.body;
                    //Error record creation
                    createErrRecord(refundErr,refundRecId)
                }
                if (refundResponse.code == 200) {
                    let refundBody = JSON.parse(refundResponse.body);
                    let paymentActions = refundBody.data.refund_methods[0];
                    log.debug("PaymentActions", paymentActions)

                    let createRefundAPI = '/v3/orders/' + bgComId + '/payment_actions/refunds'
                    cashRefundBody.payments = paymentActions;
                    log.debug("CashRefund", JSON.stringify(cashRefundBody));

                    //creating refund on Big commerce
                    let paymentResponse = postAPI(createRefundAPI, cashRefundBody)
                    log.debug("PayResponse", paymentResponse.body)

                    let refundBgComId = JSON.stringify(paymentResponse.body)
                    if (paymentResponse.code != 200) {
                        let refundErr = paymentResponse.body;
                        //Error Record creation
                        createErrRecord(refundErr,refundRecId)
                    }
                }

            }
            catch (e) {
                log.error("Error", e.message)

            }
        }

        function createErrRecord(refundErr,refundRecId)
        {
            let cusErrRecord = record.create({
                type: 'customrecord_jj_cr_csrfd_er_bgcom_nutc49',
            })
            cusErrRecord.setValue({
                fieldId: 'custrecord_jj_err_details_cshrefund',
                value: refundErr
            });
            cusErrRecord.setValue({
                fieldId: 'custrecord_jj_cash_refund_id',
                value: refundRecId
            });
            let errRecordId = cusErrRecord.save({ ignoreMandatoryFields: true });
            log.error("Error Record ID", errRecordId);
        }
        /**
         * @function postAPI
         * @param {String} customURL 
         * @param {String} body 
         */
        function postAPI(customURL, body) {
            try {
                let apiCredentials = bigComLibrary.commonFunctions.apiConfigFileSearch();
                let bigComURL = apiCredentials.urlPath + customURL;
                let response = https.post({
                    url: bigComURL,
                    headers: apiCredentials.headerObj,
                    body: JSON.stringify(body)
                });
                return response;
            } catch (e) {
                log.error("error in library module @ PostAPI", e);
                return false;
            }
        }

        return { afterSubmit }

    });

Related KBs of Big Commerce Integration: https://jobinandjismi.in/get-customers-from-big-commerce-through-api/
https://jobinandjismi.in/update-item-base-price-netsuite-to-big-commerce/

Leave a comment

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