Commercial Invoice PDF template

Jira Code: FHI-16,FHI-17,FHI-18

Designed the commercial invoice PDF template for Fully EU subsidiary. Need to update the currency and date format according to the EU standard. The commercial invoice takes print outs from item fulfilment using display commercial invoice button.

Template

<?xml version="1.0"?><!DOCTYPE pdf PUBLIC "-//big.faceless.org//report" "report-1.1.dtd"><pdf><head><#if .locale == "ru_RU"> <link name="verdana" type="font" subtype="opentype" src="${nsfont.verdana}" src-bold="${nsfont.verdana_bold}" bytes="2" /></#if> <macrolist> <macro id="nlheader"> <table class="header" style="width: 100%;"><tr> <td align="center"><span class="title">COMMERCIAL INVOICE</span></td></tr><tr> <td rowspan="3"><p style="font-size:9pt">Fully Europe BVBA<br/>Nieuwewandeling 62/10<br/>9000 Gent<br/>Belgium<br/> BTW nr / VAT number: BE 0635.808.769</p><br/> </td> </tr></table> </macro> <macro id="nlfooter"> <table class="footer" style="width: 100%;"><tr> <td align="right"><pagenumber/> of <totalpages/></td> </tr></table> </macro> </macrolist> <style type="text/css">table, p { <#if .locale == "zh_CN"> font-family: stsong, sans-serif; <#elseif .locale == "zh_TW"> font-family: msung, sans-serif; <#elseif .locale == "ja_JP"> font-family: heiseimin, sans-serif; <#elseif .locale == "ko_KR"> font-family: hygothic, sans-serif; <#elseif .locale == "ru_RU"> font-family: verdana; <#else> font-family: sans-serif; </#if> font-size: 9pt; table-layout: fixed; } th { font-weight: bold; font-size: 8pt; vertical-align: middle; padding: 5px 6px 3px; background-color: #e3e3e3; color: #333333; } td { padding: 4px 6px; } b { font-weight: bold; color: #333333; } table.header td { padding: 0px; font-size: 10pt; } table.footer td { padding: 0px; font-size: 8pt; }
table.bordertable td { border-style: solid; border-width: thin; border-color: #A9A9A9; } table.itemtable th { padding-bottom: 10px; padding-top: 10px; border-style: solid; border-width: thin; border-color: #A9A9A9;
} table.body td { padding-top: 2px; } table.total { page-break-inside: avoid; } tr.totalrow { background-color: #e3e3e3; line-height: 200%; } td.totalboxtop { font-size: 12pt; background-color: #e3e3e3; } td.addressheader { font-size: 8pt; padding-top: 6px; padding-bottom: 2px; } td.address { padding-top: 0px; } td.totalboxmid { font-size: 28pt; padding-top: 20px; background-color: #e3e3e3; } td.totalboxbot { background-color: #e3e3e3; font-weight: bold; } span.title { font-size: 14pt; font-weight: bold; } span.number { font-size: 16pt; } span.itemname { font-weight: bold; line-height: 150%; } hr { width: 100%; color: #d3d3d3; background-color: #d3d3d3; height: 1px; }</style>
<script>var w=window;if(w.performance||w.mozPerformance||w.msPerformance||w.webkitPerformance){var d=document;AKSB=w.AKSB||{},AKSB.q=AKSB.q||[],AKSB.mark=AKSB.mark||function(e,_){AKSB.q.push(["mark",e,_||(new Date).getTime()])},AKSB.measure=AKSB.measure||function(e,_,t){AKSB.q.push(["measure",e,_,t||(new Date).getTime()])},AKSB.done=AKSB.done||function(e){AKSB.q.push(["done",e])},AKSB.mark("firstbyte",(new Date).getTime()),AKSB.prof={custid:"501074",ustr:"",originlat:"0",clientrtt:"67",ghostip:"23.61.195.183",ipv6:false,pct:"10",clientip:"65.46.163.54",requestid:"b89299a",region:"17497",protocol:"h2",blver:13,akM:"x",akN:"ae",akTT:"O",akTX:"1",akTI:"b89299a",ai:"329458",ra:"false",pmgn:"",pmgi:"",pmp:"",qc:""},function(e){var _=d.createElement("script");_.async="async",_.src=e;var t=d.getElementsByTagName("script"),t=t[t.length-1];t.parentNode.insertBefore(_,t)}(("https:"===d.location.protocol?"https:":"http:")+"//ds-aksb-a.akamaihd.net/aksb.min.js")}</script> <script>var w=window;if(w.performance||w.mozPerformance||w.msPerformance||w.webkitPerformance){var d=document;AKSB=w.AKSB||{},AKSB.q=AKSB.q||[],AKSB.mark=AKSB.mark||function(e,_){AKSB.q.push(["mark",e,_||(new Date).getTime()])},AKSB.measure=AKSB.measure||function(e,_,t){AKSB.q.push(["measure",e,_,t||(new Date).getTime()])},AKSB.done=AKSB.done||function(e){AKSB.q.push(["done",e])},AKSB.mark("firstbyte",(new Date).getTime()),AKSB.prof={custid:"501074",ustr:"",originlat:"0",clientrtt:"89",ghostip:"23.61.195.183",ipv6:false,pct:"10",clientip:"65.46.163.54",requestid:"2fb450d",region:"17497",protocol:"h2",blver:13,akM:"x",akN:"ae",akTT:"O",akTX:"1",akTI:"2fb450d",ai:"329458",ra:"false",pmgn:"",pmgi:"",pmp:"",qc:""},function(e){var _=d.createElement("script");_.async="async",_.src=e;var t=d.getElementsByTagName("script"),t=t[t.length-1];t.parentNode.insertBefore(_,t)}(("https:"===d.location.protocol?"https:":"http:")+"//ds-aksb-a.akamaihd.net/aksb.min.js")}</script> <script>var w=window;if(w.performance||w.mozPerformance||w.msPerformance||w.webkitPerformance){var d=document;AKSB=w.AKSB||{},AKSB.q=AKSB.q||[],AKSB.mark=AKSB.mark||function(e,_){AKSB.q.push(["mark",e,_||(new Date).getTime()])},AKSB.measure=AKSB.measure||function(e,_,t){AKSB.q.push(["measure",e,_,t||(new Date).getTime()])},AKSB.done=AKSB.done||function(e){AKSB.q.push(["done",e])},AKSB.mark("firstbyte",(new Date).getTime()),AKSB.prof={custid:"501074",ustr:"",originlat:"0",clientrtt:"70",ghostip:"23.61.195.183",ipv6:false,pct:"10",clientip:"65.46.163.54",requestid:"338ea2f",region:"17497",protocol:"h2",blver:13,akM:"x",akN:"ae",akTT:"O",akTX:"1",akTI:"338ea2f",ai:"329458",ra:"false",pmgn:"",pmgi:"",pmp:"",qc:""},function(e){var _=d.createElement("script");_.async="async",_.src=e;var t=d.getElementsByTagName("script"),t=t[t.length-1];t.parentNode.insertBefore(_,t)}(("https:"===d.location.protocol?"https:":"http:")+"//ds-aksb-a.akamaihd.net/aksb.min.js")}</script> </head><body header="nlheader" header-height="14%" footer="nlfooter" footer-height="20pt" padding="0.5in 0.5in 0.5in 0.5in" size="Letter"> <#list results as result><#if result_index == 0> <table class="bordertable" style="width: 100%; margin-top: 10px;"><tr> <td colspan="3"><b>Billing Address</b></td> <td colspan="3"><b>Shipping Address</b></td> </tr> <tr> <td colspan="3" rowspan="2">${result.createdFrom.billaddress}</td> <td colspan="3" rowspan="2">${result.createdFrom.shipaddress}</td> </tr>    </table></#if></#list> <#list results as result><#if result_index == 0><table class="body" style="width: 100%; margin-top: 10px;"> <tr> <td>Fully Invoice Number: </td><td>inv_cs_id</td> <td>Invoice Date: </td><td>inv_cs_date </td> </tr> <tr> <td>Fully SO Number: </td><td><#if result.createdFrom.tranid?has_content>${result.createdFrom.tranid} <#else>N/A</#if></td> <td>Customer PO Number: </td><td><#if result.createdFrom.otherrefnum?has_content>${result.createdFrom.otherrefnum}<#else>N/A</#if></td> </tr> <tr> <td>Incoterms: </td><td><#if result.custbody_css_incoterms?has_content>${result.custbody_css_incoterms}<#else>N/A</#if></td> </tr></table></#if></#list> <#assign totalWeight = 0/><#assign totalValue = 0.00/> <#if results?has_content><table class="itemtable bordertable" style="width: 100%; margin-top: 10px;"><!-- start items --> <#list results as result><#if result_index == 0><thead> <tr> <th align="center" colspan="6"><p align="center">SKU</p></th> <th align="left" colspan="5"><p align="center">Product Description</p></th> <th align="left" colspan="5"><p align="center">Harmonized Code</p></th> <th align="left" colspan="4"><p align="center">Country of Origin</p></th> <th align="right" colspan="4"><p align="center">Quantity (pieces) </p></th> <th align="right" colspan="4"><p align="center">Unit Weight (lbs) </p></th> <th align="right" colspan="4"><p align="center">Unit Value<#if result.currency ="Euro">(€)<#elseif result.currency ="British Pound" >(£)<#else> </#if></p></th> <th align="right" colspan="3"><p align="center">Total Weight (lbs) </p></th> <th align="right" colspan="4"><p align="center">Total Value<#if result.currency ="Euro">(€)<#elseif result.currency ="British Pound" >(£)<#else> </#if> </p></th> </tr></thead> </#if><tr> <td align="center" colspan="6"><p align="center">${result.item.itemid}</p></td> <td align="left" colspan="5"><p align="center">${result.item.salesdescription}</p></td> <td align="left" colspan="5"><p align="center">${result.item.manufacturertariff}</p></td> <td align="left" colspan="4"><p align="center">${result.item.countryofmanufacture}</p></td> <td align="right" colspan="4"><p align="center">${result.quantity}</p></td> <td align="right" colspan="4"><p align="center">${result.item.weight}</p></td> <td align="right" colspan="4"><p align="center"><#if result.currency ="Euro">€<#elseif result.currency ="British Pound" >£<#else> </#if>${result.formulacurrency?string["0.##"]}</p></td> <td align="right" colspan="3"><p align="center">${result.formulanumeric}</p></td> <td align="right" colspan="4"><p align="center"><#if result.currency ="Euro">€<#elseif result.currency ="British Pound" >£<#else> </#if>${result.appliedToTransaction.amount?string["0.##"]}</p></td></tr> <#assign totalWeight = totalWeight + result.formulanumeric/> <#assign totalValue = totalValue + result.appliedToTransaction.amount/> </#list><!-- end items --></table></#if><#if results?has_content><#list results as result><#if result_index==0><table style="width: 100%;"> <tr> <td colspan="1"> </td> <td colspan="1"> <table class="total bordertable" style="width: 100%; margin-top: 10px;"><tr> <td align="left" colspan="4"><b>Total Weight of Goods (lbs) </b></td> <td align="right" colspan="3">${totalWeight}</td> </tr> <tr> <td colspan="4"><b>Total Value of Goods <#if result.currency ="Euro">(€)<#elseif result.currency ="British Pound" >(£)<#else> </#if></b></td> <td align="right" colspan="3"><#if result.currency ="Euro">€<#elseif result.currency ="British Pound" >£<#else></#if> ${totalValue?string["0.##"]}</td> </tr> </table> </td> </tr> </table></#if></#list></#if> <br/> <#if results?has_content><#list results as result><#if result_index==0><table style="width: 100%;"> <tr> <td align="left"> <p align="left">${result.memo} </p> </td> </tr></table> </#if></#list></#if></body></pdf>

Suitelet

 /**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */

define(['N/record', 'N/render', 'N/search', 'N/runtime', 'N/format'], function (record, render, search, runtime, format) {

    function onRequest(params) {

        var request = params.request;
        var response = params.response;

        var templateId = runtime.getCurrentScript().getParameter({ name: 'custscript_ns_commercial_inv_template' });//Fully NA 
        var templateId2 = runtime.getCurrentScript().getParameter({ name: 'custscript_jj_fhi_16_fully_eu_commercial' });//Fully Europe Template 

        if (request.method === 'GET') { // GET

            var ifId = request.parameters.ifId; // Item Fulfillment Internal ID
            var soId = request.parameters.soId; // Sales Order Internal ID
            var soRecord = record.load({
                type: record.Type.SALES_ORDER,
                id: soId,
                isDynamic: true,
            });
            var subsidiary = soRecord.getValue({
                fieldId: 'subsidiary'
            });
            log.debug('subsidiary', subsidiary);

            if (subsidiary == '3') {

                templateId = templateId2; //set this on script parameter for Fully Europe 


            }

            var ifRecord = record.load({ type: record.Type.ITEM_FULFILLMENT, id: ifId }); // Load IF Record

            // Get Line Item Internal ID from IF
            var itemArray = [];
            for (var i = 0; i < ifRecord.getLineCount({ sublistId: 'item' }); i++) {
                var itemId = ifRecord.getSublistValue({ sublistId: 'item', fieldId: 'item', line: i });
                if (itemArray.indexOf(itemId) === -1) {
                    itemArray.push(itemId);
                }
            }

            var ifItemSearchObj = search.load({ id: 'customsearch_script_commercial_invoice' }); // Load IF Search

            // Push item fulfillment ID and item ID's from IF
            ifItemSearchObj.filters.push(search.createFilter({ name: 'internalid', operator: search.Operator.ANYOF, values: ifId }));
            ifItemSearchObj.filters.push(search.createFilter({ name: 'item', operator: search.Operator.ANYOF, values: itemArray }));

            var ifItemResults = ifItemSearchObj.run().getRange({ start: 0, end: 999 });

            for (var i = 0; i < ifItemResults.length; i++) {
                log.debug('individual', ifItemResults[i]);
            }

            // Run invoice search to find the invoice associated with the item fulfillment
            var invoiceSearchResult = search.create({
                type: search.Type.TRANSACTION,
                filters: [
                    search.createFilter({
                        name: 'type',
                        operator: search.Operator.ANYOF,
                        values: ['CustInvc', 'CashSale']
                    }),
                    search.createFilter({
                        name: 'createdfrom',
                        operator: search.Operator.IS,
                        values: soId
                    }),
                    search.createFilter({
                        name: 'mainline',
                        operator: search.Operator.IS,
                        values: 'T'
                    })
                ],
                columns: [
                    search.createColumn({
                        name: 'internalid'
                    }),
                    search.createColumn({
                        name: 'type'
                    }),
                    search.createColumn({
                        name: 'tranid'
                    }),
                    search.createColumn({
                        name: 'trandate'
                    })
                ]
            }).run().getRange({ start: 0, end: 999 });

            if (ifItemResults.length !== 0) {
                var trackingNumbers = ifItemResults[0].getValue({ name: 'trackingnumbers' });
                trackingNumbers = trackingNumbers.replace(/<BR>/g, ',<br />');
            }

            // Render the PDF by setting the template, attaching the invoice record, and the write the file to the response
            var templateRender = render.create();
            templateRender.setTemplateById({ id: templateId });
            templateRender.addSearchResults({
                templateName: 'results',
                searchResult: ifItemResults
            });
            
            if (invoiceSearchResult.length !== 0) {
                var trandate = invoiceSearchResult[0].getValue({ name: 'trandate' });
               
            }else{

                var trandate = "N/A"
            }


//convert date based on the subsidiary
            if (subsidiary == '3') {


                if (invoiceSearchResult.length !== 0) {
                    var trandate = invoiceSearchResult[0].getValue({ name: 'trandate' });
                    log.debug("trandate", trandate);
                    trandate = convertformat(trandate);
                }else{

                    var trandate = "N/A"
                }


            }



            var templateXML = templateRender.templateContent;
            if (trackingNumbers !== '') {
                templateXML = templateXML.replace('tracking_numbers', trackingNumbers);
            } else { templateXML = templateXML.replace('tracking_numbers', 'N/A'); }

            if (invoiceSearchResult.length !== 0) {
                templateXML = templateXML.replace('inv_cs_id', invoiceSearchResult[0].getValue({ name: 'tranid' }));
                templateXML = templateXML.replace('inv_cs_date', trandate);
            } else {
                templateXML = templateXML.replace('inv_cs_id', 'N/A');
                templateXML = templateXML.replace('inv_cs_date', 'N/A');
            }

            templateRender.templateContent = templateXML;
            var commercialInvoicePDF = templateRender.renderAsPdf();
            commercialInvoicePDF.name = 'Commercial Invoice ' + ifRecord.getValue({ fieldId: 'tranid' }) + '.pdf';


            response.writeFile(commercialInvoicePDF, true);

        }
    }

    return {
        onRequest: onRequest
    }

    //function for converting the date format in to DD/MM/YYYY
    function convertformat(trandate) {


        var d = new Date(trandate);
        var dd = d.getDate();
        var mm = d.getMonth() + 1
        var yy = d.getFullYear();

        var datestring = dd + '/' + mm + '/' + yy

        return datestring

    }

}); 

User Event

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 */

define(['N/record'], function (record) {

    function beforeLoad(context) {
        var form = context.form;
        form.clientScriptModulePath = '/SuiteScripts/DSG/ed_CS_IF_PDFButton.js';
        form.addButton({
            id: 'custpage_pdf_button',
            label: 'Display Commercial Invoice',
            functionName: 'generatePDF();'
        });
    }

    return {beforeLoad: beforeLoad}

});

Client Script

 /**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 */

define(['N/currentRecord', 'N/search', 'N/url'], function (currentRecord, search, url) {

    function pageInit() {}

    function generatePDF() {

        var IFRecord = currentRecord.get();
        var SOId = IFRecord.getValue({fieldId: 'createdfrom'});

        window.open(url.resolveScript({
            scriptId: 'customscript_ns_sl_gen_pdf',
            deploymentId: 'customdeploy_ns_sl_gen_pdf',
            params: {
                ifId: IFRecord.id,
                soId: SOId
            }
        }));

    }

    return {
        pageInit: pageInit,
        generatePDF: generatePDF
    }

});

 

Leave a comment

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