Standard Invoice XML creation

 xmlStandardInvFile: function (invoiceId) {
                let customRecId = '';
                try {


                    // Load the invoice record
                    const invObjRecord = record.load({
                        type: record.Type.INVOICE,
                        id: invoiceId,
                        isDynamic: true
                    });


                    // Extract general invoice details
                    const currentTime = new Date().toISOString().split('.')[0];
                    const invoiceNumber = invObjRecord.getValue({ fieldId: 'tranid' });
                    const invoiceDate = invObjRecord.getValue({ fieldId: 'trandate' }).toISOString().split('T')[0];
                    const shipDate = invObjRecord.getValue({ fieldId: 'shipdate' }).toISOString().split('.')[0];
                    const priceBeforeGST = invObjRecord.getValue({ fieldId: 'subtotal' }) || 0;
                    const gstPrice = invObjRecord.getValue({ fieldId: 'taxtotal' }) || 0;
                    const totalPrice = invObjRecord.getValue({ fieldId: 'total' }) || 0;
                    // Get the value of 'otherrefnum' field
                    let orderNum = invObjRecord.getValue({ fieldId: 'otherrefnum' });
                    let salesOrderId = invObjRecord.getValue({ fieldId: 'createdfrom' });
                    let islandId = invObjRecord.getValue({ fieldId: 'custbodyast_custerr' });
                    log.debug("salesOrderId", salesOrderId);
                    let salesOrderTotal = '';
                    let salesOrderDoc = '';
                    if (salesOrderId) {
                        let fieldLookUp = search.lookupFields({
                            type: search.Type.SALES_ORDER,
                            id: salesOrderId,
                            columns: ['total', 'tranid']
                        });
                        salesOrderTotal = fieldLookUp.total;
                        salesOrderDoc = fieldLookUp.tranid;
                        log.debug("salesOrderTotal", salesOrderTotal);
                        log.debug("salesOrderDoc", salesOrderDoc);
                    }



                    // Check if OrderNum is a valid number
                    orderNum = isNaN(Number(orderNum)) ? 0 : Number(orderNum);
                    // Customer and address details
                    const customerName = invObjRecord.getText({ fieldId: 'entity' });
                    const customerRecId = invObjRecord.getValue({ fieldId: 'entity' });
                    log.debug("customerRecId", customerRecId);
                    let foodStuffId = search.lookupFields({
                        type: search.Type.CUSTOMER,
                        id: customerRecId,
                        columns: ['custentitystore_id']
                    });
                    log.debug("foodStuffId", foodStuffId.custentitystore_id);
                    const streetAddress1 = invObjRecord.getValue({ fieldId: 'shipaddress' }) || '';
                    const postalAddress = invObjRecord.getValue({ fieldId: 'billaddress' }) || '';
                    log.debug("streetAddress1", streetAddress1);
                    log.debug("postalAddress", postalAddress);


                    const storeOwnerCode = foodStuffId.custentitystore_id; // This could come from a custom field or mapping logic.


                    let totalLinesInvoiced = 0;
                    let totalQtyOrdered = 0;
                    let totalQtyDelivered = 0;


                    //                     // Start building the XML


                    invConfirmationXml = `<INVOICES_150 partner="FOODSTUFFS" transaction="INVOICE" version="1.50" timestamp="${currentTime}" document_mode="Test">
<CUSTOMER>
<COMPANY>
<NAME>${customerName}</NAME>
<ORG_ID OrgType="EAN_Prefix">123</ORG_ID>
<STREET_ADDRESS>
<ADDRESS1>${streetAddress1.split('n')[0] || ''}</ADDRESS1>
<ADDRESS2>${streetAddress1.split('n')[1] || ''}</ADDRESS2>
<ADDRESS3>${streetAddress1.split('n')[2] || ''}</ADDRESS3>
<CITY>${streetAddress1.split('n')[3] || ''}</CITY>
<COUNTRY>${streetAddress1.split('n')[5] || ''}</COUNTRY>
</STREET_ADDRESS>
<POSTAL_ADDRESS>
<ADDRESS1>${postalAddress.split('n')[0] || ''}</ADDRESS1>
<ADDRESS2>${postalAddress.split('n')[1] || ''}</ADDRESS2>
<ADDRESS3>${postalAddress.split('n')[2] || ''}</ADDRESS3>
<CITY>${postalAddress.split('n')[3] || ''}</CITY>
<COUNTRY>${postalAddress.split('n')[5] || ''}</COUNTRY>
</POSTAL_ADDRESS>
<PHONE></PHONE>
<FAX></FAX>
</COMPANY>
<SUPPLIER_STORE_CODE></SUPPLIER_STORE_CODE>
<STORE_OWNER_CODE>${storeOwnerCode}</STORE_OWNER_CODE>
</CUSTOMER>
<SUPPLIER>
<COMPANY>
<NAME>Berica Limited</NAME>
<ORG_ID OrgType="EAN_Prefix">9004901</ORG_ID>
<STREET_ADDRESS>
<ADDRESS1>4 Liverpool Street</ADDRESS1>
<ADDRESS2></ADDRESS2>
<ADDRESS3></ADDRESS3>
<CITY>Riverlands</CITY>
<COUNTRY>New Zealand</COUNTRY>
</STREET_ADDRESS>
<POSTAL_ADDRESS>
<ADDRESS1>644</ADDRESS1>
<ADDRESS2></ADDRESS2>
<ADDRESS3></ADDRESS3>
<CITY>Riverlands</CITY>
<COUNTRY>New Zealand</COUNTRY>
</POSTAL_ADDRESS>
<PHONE></PHONE>
<FAX></FAX>
</COMPANY>
<SUPPLIER_INTERNAL_CODE ></SUPPLIER_INTERNAL_CODE>
<FOODSTUFFS_SUPPLIER_CODE></FOODSTUFFS_SUPPLIER_CODE>
<GST>
<GST_RATE>15.0</GST_RATE>
<GST_NUMBER>129459022</GST_NUMBER>
</GST>
</SUPPLIER>
<INVOICELIST>
<INVOICE>
<INVOICE_HEADER>
<INVOICE_CREDIT>Tax Invoice</INVOICE_CREDIT>
<INVOICE_NUM>${invoiceNumber}</INVOICE_NUM>
<INVOICE_DATE>${invoiceDate}</INVOICE_DATE>
<SUPPLIER_STORE_REFERENCE></SUPPLIER_STORE_REFERENCE>
<FOODSTUFFS_STORE_REFERENCE>617628</FOODSTUFFS_STORE_REFERENCE>
<ORDER_NUM>${orderNum}</ORDER_NUM>
<DISPATCH_DATE>${shipDate}</DISPATCH_DATE>
<PACKING_SLIP>${salesOrderDoc}</PACKING_SLIP>
<BUYER></BUYER>
<DELIVER_ADDRESS>
<ADDRESS1>${postalAddress.split('n')[0] || ''}</ADDRESS1>
<ADDRESS2>${postalAddress.split('n')[1] || ''}</ADDRESS2>
<ADDRESS3>${postalAddress.split('n')[2] || ''}</ADDRESS3>
<CITY>${postalAddress.split('n')[3] || ''}</CITY>
<POSTAL_CODE>${postalAddress.split('n')[4] || ''}</POSTAL_CODE>
<COUNTRY>${postalAddress.split('n')[5] || ''}</COUNTRY>
</DELIVER_ADDRESS>
<BILL_TO>
<COMPANY>
<NAME></NAME>
<ORG_ID OrgType="EAN_Prefix">123</ORG_ID>
<STREET_ADDRESS>
<ADDRESS1>${streetAddress1.split('n')[0] || ''}</ADDRESS1>
<ADDRESS2>${streetAddress1.split('n')[1] || ''}</ADDRESS2>
<ADDRESS3>${streetAddress1.split('n')[2] || ''}</ADDRESS3>
<CITY>${streetAddress1.split('n')[3] || ''}</CITY>
<POSTAL_CODE>${streetAddress1.split('n')[4] || ''}</POSTAL_CODE>
<COUNTRY>${streetAddress1.split('n')[5] || ''}</COUNTRY>
</STREET_ADDRESS>
<POSTAL_ADDRESS>
<ADDRESS1>FOODSTUFFS AUCKLAND LIMITED</ADDRESS1>
<ADDRESS2>${postalAddress.split('n')[1] || ''}</ADDRESS2>
<ADDRESS3>${postalAddress.split('n')[2] || ''}</ADDRESS3>
<CITY>${postalAddress.split('n')[3] || ''}</CITY>
<POSTAL_CODE>${postalAddress.split('n')[4] || ''}</POSTAL_CODE>
<COUNTRY>${postalAddress.split('n')[5] || ''}</COUNTRY>
</POSTAL_ADDRESS>
<PHONE></PHONE>
<FAX></FAX>
</COMPANY>
</BILL_TO>
<CURRENCY>NZD</CURRENCY>
<SPECIAL_INSTRUCTIONS></SPECIAL_INSTRUCTIONS>
<PRICE_BEFORE_GST>${priceBeforeGST.toFixed(2)}</PRICE_BEFORE_GST>
<TOTAL_GST>${gstPrice.toFixed(2)}</TOTAL_GST>
<TOTAL_PRICE>${totalPrice.toFixed(2)}</TOTAL_PRICE>
</INVOICE_HEADER>
<LINES>`
                    const LineCount = invObjRecord.getLineCount({ sublistId: 'item' });
                    for (let i = 0; i < LineCount; i++) {
                        const itemId = invObjRecord.getSublistValue({ sublistId: 'item', fieldId: 'item', line: i }) || '';
                        const productDesc = invObjRecord.getSublistValue({ sublistId: 'item', fieldId: 'description', line: i }) || '';
                        const quantity = invObjRecord.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: i }) || 0;
                        const rate = invObjRecord.getSublistValue({ sublistId: 'item', fieldId: 'rate', line: i }) || 0;
                        const amount = invObjRecord.getSublistValue({ sublistId: 'item', fieldId: 'amount', line: i }) || 0;
                        totalLinesInvoiced += 1;
                        totalQtyOrdered += quantity;
                        totalQtyDelivered += quantity; // Assuming qty delivered is same as ordered for simplicity
                        invConfirmationXml += `
                <INVOICE_LINE>
                <CUSTOMER_PRODUCT>5204313</CUSTOMER_PRODUCT>
<SUPPLIER_PRODUCT>9421026462350</SUPPLIER_PRODUCT>
                    <PRODUCT_DESC>${productDesc}</PRODUCT_DESC>
                    <QTY_ORDERED>${quantity}</QTY_ORDERED>
                    <UNIT_OF_MEASURE uomcode="Retail Unit">10</UNIT_OF_MEASURE>
                    <QTY_FOR_DELIVERY>${quantity}</QTY_FOR_DELIVERY>
                    <PRICING_DETAIL>
                    <PRICE>${rate.toFixed(2)}</PRICE>
                    <PRICE_UNIT_OF_MEASURE priceuomcode="Retail Unit">10</PRICE_UNIT_OF_MEASURE>
<DISCOUNT></DISCOUNT>
<DISCOUNT_LIST></DISCOUNT_LIST>
<BONUS_STOCK>false</BONUS_STOCK>
                    <LINE_PRICE>${amount.toFixed(2)}</LINE_PRICE>
                    </PRICING_DETAIL>
                </INVOICE_LINE>`;
                    }
                    // Closing XML tags
                    invConfirmationXml += `
            </LINES>
            <CONTROL>
                <LINES_INVOICED>${totalLinesInvoiced}</LINES_INVOICED>
                <TOTAL_QTY_ORDERED>${totalQtyOrdered}</TOTAL_QTY_ORDERED>
                <TOTAL_QTY_FOR_DELIVERY>${totalQtyDelivered}</TOTAL_QTY_FOR_DELIVERY>
            </CONTROL>
        </INVOICE>
    </INVOICELIST>
</INVOICES_150>`;
                    // Replace special characters
                    invConfirmationXml = invConfirmationXml.replace(/&/g, "&amp;");
                    // Save XML to custom record
                    const customRecord = record.create({
                        type: 'customrecord_ahnz67_jj_foodstuffexchange',
                        isDynamic: true
                    });
                    customRecord.setValue({ fieldId: 'custrecord_ahnz_79_invoice_inv_xml', value: invoiceId });
                    customRecord.setValue({ fieldId: 'custrecord_ahnz_79_jj_inv_xml_msg_reques', value: invConfirmationXml });
                    if (salesOrderId && (salesOrderTotal != totalPrice)) {
                        customRecord.setValue({
                            fieldId: 'custrecord_jj_partial_invoice_ahnz_86',
                            value: true
                        });
                    }
                    customRecId = customRecord.save({
                        enableSourcing: true,
                        ignoreMandatoryFields: true
                    });
                    log.debug("XML successfully saved for Invoice ID:", customRecId);
                    // Return the XML
                    return { invConfirmationXml, customRecId };
                } catch (err) {
                    log.error("Error generating standalone invoice XML", err);
                    if (customRecId) {
                        record.submitFields({
                            type: "customrecord_ahnz67_jj_foodstuffexchange",
                            id: customRecId,
                            values: {
                                custrecord_ahnz_78_jj_inv_error: err
                            },
                            options: { enableSourcing: true, ignoreMandatoryFields: true }
                        });
                    }
                    return false;
                }
            }

        }

Leave a comment

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