In some cases, the client applies Bills to Journals via the Bill Payment page. In such cases, we check the apply box for the relevant bills and journals such that the body amount shows 0. This can be done via UI but not csv.We can done this through scripting.
Here we consider one bill can be applied to one journal and csv file is uploaded in the file cabinet.
/**
* @NApiVersion 2.1
* @NScriptType MapReduceScript
*/
define([‘N/file’, ‘N/record’, ‘N/format’, ‘N/runtime’, ‘N/email’],
/**
* @param{record} record
* @param{search} search
*/
(file, record, format, runtime, email) => {
/**
* Defines the function that is executed at the beginning of the map/reduce process and generates the input data.
* @param {Object} inputContext
* @param {boolean} inputContext.isRestarted – Indicates whether the current invocation of this function is the first
* invocation (if true, the current invocation is not the first invocation and this function has been restarted)
* @param {Object} inputContext.ObjectRef – Object that references the input data
* @typedef {Object} ObjectRef
* @property {string|number} ObjectRef.id – Internal ID of the record instance that contains the input data
* @property {string} ObjectRef.type – Type of the record instance that contains the input data
* @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process
* @since 2015.2
*/
const getInputData = (inputContext) => {
try {
log.debug(“In get input data”)
let csvFile = file.load({
id: 12833
});
let fileContents = csvFile.getContents();
let lines = fileContents.split(/r?n/);
log.debug(“Lines ****”, lines);
// Remove the header line
lines.shift();
let data = lines.map(line => {
let fields = line.split(‘,’);
if (fields.length >= 9) { // Check if fields array has enough elements
return {
externalId: fields[0].trim(),
date: fields[1].trim(),
vendorId: fields[2].trim(),
subsidiary: fields[3].trim(),
account: fields[4].trim(),
currency: fields[5].trim(),
exchgrate: fields[6].trim(),
billIds: fields[7].trim(),
journalIds: fields[8].trim(),
};
}
else {
// Handle the case where the line does not have enough fields
log.error(`Invalid line format: ${line}`);
return null; // or handle differently as per your requirement
}
}).filter(obj => obj !== null); // Remove null objects
log.debug(“Data”, data);
return data;
} catch (e) {
log.error(“error@getinput data”, e);
}
}
/**
* Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically
* when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided
* context.
* @param {Object} mapContext – Data collection containing the key-value pairs to process in the map stage. This parameter
* is provided automatically based on the results of the getInputData stage.
* @param {Iterator} mapContext.errors – Serialized errors that were thrown during previous attempts to execute the map
* function on the current key-value pair
* @param {number} mapContext.executionNo – Number of times the map function has been executed on the current key-value
* pair
* @param {boolean} mapContext.isRestarted – Indicates whether the current invocation of this function is the first
* invocation (if true, the current invocation is not the first invocation and this function has been restarted)
* @param {string} mapContext.key – Key to be processed during the map stage
* @param {string} mapContext.value – Value to be processed during the map stage
* @since 2015.2
*/
const map = (mapContext) => {
let extId;
try {
let line = mapContext.value;
const inputData = JSON.parse(line);
const { externalId, date, vendorId, subsidiary, account, currency, exchgrate, billIds, journalIds } = inputData;
extId = externalId;
let vendorID = vendorId;
let sub = subsidiary;
let venAccount = account;
let venCurrency = currency;
let billId = billIds;
let journalId = journalIds;
let exRate = exchgrate;
let recdate = format.parse({
value: date,
type: format.Type.DATE,
});
let dateFormat = runtime.getCurrentUser().getPreference({
name: ‘DATEFORMAT’
});
let formattedDate = ”
formattedDate = format.format({
value: recdate,
type: format.Type.DATE,
format: dateFormat
});
log.debug(“ext id***”, extId);
let payRec = record.create({
type: record.Type.VENDOR_PAYMENT,
isDynamic: true
});
payRec.setValue({
fieldId: ‘entity’,
value: vendorID
});
payRec.setValue({
fieldId: “externalid”,
value: extId
});
payRec.setValue({
fieldId: “trandate”,
value: recdate
});
payRec.setValue({
fieldId: “subsidiary”,
value: sub
});
payRec.setValue({
fieldId: “currency”,
value: venCurrency
});
// payRec.setValue({
// fieldId: “account”,
// value: venAccount
// });
// payRec.setValue({
// fieldId : “exchangerate”,
// value : Number(exRate)
// });
let lineCount = payRec.getLineCount({ sublistId: ‘apply’ });
log.debug(“Line count : “, lineCount)
if (lineCount === 0) {
log.error(‘No line items found for apply sublist.’);
return;
}
for (let i = 0; i < lineCount; i++) {
payRec.selectLine({
sublistId: ‘apply’,
line: i
});
let type = payRec.getCurrentSublistValue({
sublistId: ‘apply’,
fieldId: ‘type’
});
let intId = payRec.getCurrentSublistValue({
sublistId: ‘apply’,
fieldId: ‘internalid’
});
if (type === “Journal” && intId === journalIds) {
log.debug(“Inside the journal if loop”);
payRec.setCurrentSublistValue({
sublistId: ‘apply’,
fieldId: ‘apply’,
value: true,
});
}
if (type === “Bill” && intId === billIds) {
payRec.setCurrentSublistValue({
sublistId: ‘apply’,
fieldId: ‘apply’,
value: true,
});
}
payRec.commitLine({
sublistId: “apply”
});
}
let payId = payRec.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
log.debug(“Record has been created****”, payId);
}
catch (e) {
log.error(“error@map data”, e);
sendErrorEmail(extId);
}
}
/**
* Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered
* automatically when the associated map stage is complete. This function is applied to each group in the provided context.
* @param {Object} reduceContext – Data collection containing the groups to process in the reduce stage. This parameter is
* provided automatically based on the results of the map stage.
* @param {Iterator} reduceContext.errors – Serialized errors that were thrown during previous attempts to execute the
* reduce function on the current group
* @param {number} reduceContext.executionNo – Number of times the reduce function has been executed on the current group
* @param {boolean} reduceContext.isRestarted – Indicates whether the current invocation of this function is the first
* invocation (if true, the current invocation is not the first invocation and this function has been restarted)
* @param {string} reduceContext.key – Key to be processed during the reduce stage
* @param {List<String>} reduceContext.values – All values associated with a unique key that was passed to the reduce stage
* for processing
* @since 2015.2
*/
const reduce = (reduceContext) => {
}
/**
* Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered
* automatically when the associated reduce stage is complete. This function is applied to the entire result set.
* @param {Object} summaryContext – Statistics about the execution of a map/reduce script
* @param {number} summaryContext.concurrency – Maximum concurrency number when executing parallel tasks for the map/reduce
* script
* @param {Date} summaryContext.dateCreated – The date and time when the map/reduce script began running
* @param {boolean} summaryContext.isRestarted – Indicates whether the current invocation of this function is the first
* invocation (if true, the current invocation is not the first invocation and this function has been restarted)
* @param {Iterator} summaryContext.output – Serialized keys and values that were saved as output during the reduce stage
* @param {number} summaryContext.seconds – Total seconds elapsed when running the map/reduce script
* @param {number} summaryContext.usage – Total number of governance usage units consumed when running the map/reduce
* script
* @param {number} summaryContext.yields – Total number of yields when running the map/reduce script
* @param {Object} summaryContext.inputSummary – Statistics about the input stage
* @param {Object} summaryContext.mapSummary – Statistics about the map stage
* @param {Object} summaryContext.reduceSummary – Statistics about the reduce stage
* @since 2015.2
*/
const summarize = (summaryContext) => {
}
function sendErrorEmail (externalId)
{
try {
// Prepare email content
const emailSubject = ‘Error occurred during creation of vendor bill payment record’;
const emailBody = `An error occurred during the creation of the vendor bill payment record for External ID: ${externalId}.`;
// Send email to script owner
email.send({
author: 7,
recipients: 7,
subject: emailSubject,
body: emailBody
});
log.debug(‘Error email sent successfully.’);
} catch (error) {
log.error(‘Error sending error email:’, error);
}
}
return { getInputData, map, reduce, summarize }
});