REQUIREMENT
Need to implement a button within the invoice record. This button will only appear in the view mode of the record. Additionally, add two new body fields to both the standard and commercial invoice records.
Upon clicking this button, it will initiate the opening of a commercial invoice record in a new tab, specifically in edit mode. During this process, certain fields will be automatically filled in the commercial invoice.
SOLUTION
Userevent script.
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
define(['N/record', 'N/search'],
/**
* @param{record} record
* @param{search} search
*/
(record, search) => {
/**
* Defines the function definition that is executed before record is loaded.
* @param {Object} scriptContext
* @param {Record} scriptContext.newRecord - New record
* @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
* @param {Form} scriptContext.form - Current form
* @param {ServletRequest} scriptContext.request - HTTP request information sent from the browser for a client action only.
* @since 2015.2
*/
const beforeLoad = (scriptContext) => {
try {
let invoiceRec = scriptContext.newRecord;
let recordType = invoiceRec.type
if ((scriptContext.type === "view") && (recordType == 'invoice')) {
let invoiceId = invoiceRec.id
let deployDateCheck = checkDateCreated(invoiceId)
if (deployDateCheck) {
let comInvId = invoiceRec.getValue({
fieldId: 'custbody_jj_comm_invoice'
})
if (!checkForParameter(comInvId)) {
log.debug("scriptContext.type", scriptContext.type)
scriptContext.form.clientScriptModulePath = './jj_cs_logistic_iv_blurh7.js'
let currentForm = scriptContext.form
currentForm.addButton({
id: 'custpage_com_inv_btn',
label: 'Create Commercial Invoice',
functionName: 'createCommercialInv("' + invoiceId + '")'
});
}
}
}
catch (err) {
log.error("error@beforeLoad", err)
}
}
/**
* Defines the function definition that is executed after record is submitted.
* @param {Object} scriptContext
* @param {Record} scriptContext.newRecord - New record
* @param {Record} scriptContext.oldRecord - Old record
* @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
* @since 2015.2
*/
const afterSubmit = (scriptContext) => {
try {
let newRecord = scriptContext.newRecord
log.debug("nerRecord", newRecord)
let recordType = newRecord.type
if (recordType == 'customrecord_f3_commercial_invoice') {
let commInvRecordid = newRecord.id
let triggerType = scriptContext.type
if (triggerType == 'create') {
let invoicid = newRecord.getValue({
fieldId: 'custrecord_jj_related_invocie'
})
if (checkForParameter(invoicid)) {
if (checkIfCommercialRecordExist(invoicid)) {
record.submitFields({
type: 'invoice',
id: invoicid,
values: {
custbody_jj_comm_invoice: commInvRecordid
},
options: {
enableSourcing: false,
ignoreMandatoryFields: true
}
});
}
}
catch (err) {
log.error("error@afterSubmit", err)
}
}
/**
* Function to check if the commercial record value exist for an invoice record
* @param {*} invoiceId Internal Id of the invoice
* @returns true if no commercial invoice exists
*/
function checkIfCommercialRecordExist(invoiceId) {
try {
let invoiceSearchObj = search.create({
type: "invoice",
filters:
[
["type", "anyof", "CustInvc"],
"AND",
["internalid", "anyof", invoiceId]
],
columns:
[
search.createColumn({ name: "internalid", label: "Internal ID" }),
search.createColumn({ name: "custbody_jj_comm_invoice", label: "Related Commercial Invoice" })
]
});
let searchResultCount = invoiceSearchObj.runPaged().count;
var searchRes = invoiceSearchObj.run().getRange({
start: 0,
end: 1
});
if (checkForParameter(searchRes[0].getValue({ name: "custbody_jj_comm_invoice", label: "Related Commercial Invoice" }))) {
return false
}
else {
return true
}
}
catch (err) {
log.error("error@checkIfCommercialRecordExist", err)
}
}
function checkForParameter(parameter) {
if (parameter !== "" && parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== " " && parameter !== 'false' && parameter !== '- None -') {
return true;
}
}
/**
* Function to check if the invoice is created after the script is added to the account.
* @param {*} invId Internal ID of the invoice
* @returns result count if invocie is created after the specific date
*/
function checkDateCreated(invId) {
try {
let todayDate = new Date("10/10/2023")
let dateFilterValue = todayDate.getMonth() + 1 + '-' + todayDate.getDate() + '-' + todayDate.getFullYear()
log.debug("dateFilterValue", dateFilterValue)
let invoiceSearchObj = search.create({
type: "invoice",
filters:
[
["type", "anyof", "CustInvc"],
"AND",
["internalid", "anyof", invId],
"AND",
["mainline", "is", "T"],
"AND",
[
`formulanumeric: CASE WHEN (TO_CHAR(TO_DATE({datecreated}), 'MM-DD-YYYY')) >= (TO_CHAR(TO_DATE('${dateFilterValue}','MM-DD-YYYY'),'MM-DD-YYYY')) THEN 1 ELSE 0 END `,
"equalto",
"1"
],
],
columns:
[
search.createColumn({ name: "datecreated", label: "Date Created" })
]
});
let searchResultCount = invoiceSearchObj.runPaged().count;
log.debug("searchResultCount", searchResultCount)
if (searchResultCount > 0) {
return true
}
else {
return false
}
}
catch (err) {
log.error("error@checkDateCreated", err)
}
}
return { beforeLoad, afterSubmit }
});
Client script
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
* @NModuleScope SameAccount
*/
define(['N/record', 'N/search'],
/**
* @param{record} record
* @param{search} search
*/
function (record, search) {
/**
* Function to be executed after page is initialized.
*
* @param {Object} scriptContext
* @param {Record} scriptContext.currentRecord - Current form record
* @param {string} scriptContext.mode - The mode in which the record is being accessed (create, copy, or edit)
*
* @since 2015.2
*/
function pageInit(scriptContext) {
try {
var currentContext = scriptContext.mode
var currentRec = scriptContext.currentRecord
var recordType=currentRec.type
if(recordType == 'customrecord_f3_commercial_invoice'){
if(currentContext == 'copy'){
currentRec.setValue({ fieldId: "custrecord_f3_comm_inv_no", value: '' });
currentRec.setValue({ fieldId: "custrecord_f3_comm_inv_date", value: '' });
currentRec.setValue({ fieldId: "custrecord_bri_commercial_inv_project", value: '' });
currentRec.setValue({ fieldId: "custrecord_jj_related_invocie", value: '' });
}else if (currentContext === 'create') {
const urlParams = new URLSearchParams(window.location.search);
console.log("urlParams...", urlParams)
var invoiceId = urlParams.get('InvId');
if (checkForParameter(invoiceId)) {
var invoiceDetails = invoiceSearch(invoiceId)
if (Object.keys(invoiceDetails).length > 0) {
if (checkForParameter(invoiceDetails["tranId"])) {
console.log("setting inv")
currentRec.setValue({ fieldId: "custrecord_f3_comm_inv_no", value: invoiceDetails["tranId"] });
}
if (checkForParameter(invoiceDetails["date"])) {
currentRec.setText({ fieldId: "custrecord_f3_comm_inv_date", text: invoiceDetails["date"] });
}
if (checkForParameter(invoiceDetails["project"])) {
currentRec.setValue({ fieldId: "custrecord_bri_commercial_inv_project", value: invoiceDetails["project"] });
}
if (checkForParameter(invoiceId)) {
currentRec.setValue({ fieldId: "custrecord_jj_related_invocie", value: invoiceId });
}
}
if((recordType == 'invoice') && (currentContext== 'copy')){
currentRec.setValue({ fieldId: "custbody_jj_comm_invoice", value:'' });
}
}
catch (err) {
console.error("error@pageInit",err)
}
}
/**
* This fucntion is called when the button to create commercial invocie is clicked in invoice record
* @param {*} InvId Internal ID of the invoice record
* @returns true
*/
function createCommercialInv(InvId) {
try {
var newCommercialInvUrl = "https://....." //Custom function to get new standard Sales Order URL
var finalUrl = newCommercialInvUrl + '&InvId=' + InvId;
window.open(finalUrl, "_blank");
return true;
}
catch (err) {
log.error("error@createCommercialInv", err)
}
}
/**
* @description Check whether the given parameter argument has value on it or is it empty.
* @param {*} parameter parameter which contains/references some values
* @returns {Boolean} true if there exist a value, else false
*/
function checkForParameter(parameter) {
if (parameter !== "" && parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== " " && parameter !== 'false' && parameter !== '- None -') {
return true;
}
}
/**
* Function to run a invoice saved search with the given invoice internal id
* @param {*} invoiceId Internal Id of the invoice
* @returns tranDate, tranid and the project ID
*/
function invoiceSearch(invoiceId) {
try {
var invoiceSearchObj = search.create({
type: "invoice",
filters:
[
["type", "anyof", "CustInvc"],
"AND",
["internalid", "anyof", invoiceId],
"AND",
["mainline", "is", "T"]
],
columns:
[
search.createColumn({ name: "tranid", label: "Document Number" }),
search.createColumn({ name: "trandate", label: "Date" }),
search.createColumn({
name: "internalid",
join: "jobMain",
label: "Internal ID"
})
]
});
var searchRes = invoiceSearchObj.run().getRange({
start: 0,
end: 1
});
var invObj = {}
if (searchRes.length > 0) {
invObj.tranId = searchRes[0].getValue({ name: "tranid", label: "Document Number" })
invObj.date = searchRes[0].getValue({ name: "trandate", label: "Date" })
invObj.project = searchRes[0].getValue({
name: "internalid",
join: "jobMain",
label: "Internal ID"
})
}
console.log("invObj", invObj)
return invObj
}
catch (err) {
console.error("error@invoiceSearch", err)
}
}
return {
pageInit: pageInit,
createCommercialInv: createCommercialInv
};
});