我在 NetSuite 中开发了一个 Suitelet 脚本来生成 XML 文件,我想将其重组为三个部分:
处理生成 XML 的逻辑的自定义模块。 文件结构的 XML 模板。 与自定义模块交互并生成响应的 Suitelet 脚本。
这是我到目前为止所拥有的:
//Custom Module
var TEMPLATE_FILE_ID = "36530";
define(["N/file", "N/render", "N/record", "N/search", "SuiteScripts/pts_helper1"],
function (file, render, record, search, util) {
function generateXml() {
var invoiceId = 1057613;
var invoiceRecord = record.load({
type: 'invoice',
id: invoiceId
});
var xmlTemplateFile = file.load({
id: TEMPLATE_FILE_ID
});
const customData = {
invoiceId: invoiceId
};
// Additional logic to populate XML data
}
return {
generateXml: generateXml
}
});
//XML Template
<?xml version="1.0" encoding="ISO-8859-1"?>
<INVOICE_ID>${customData.invoiceId}</INVOICE_ID>
</xml>
//Suitelet Script
/**
*@NApiVersion 2.1
*@NScriptType Suitelet
*/
define(["SuiteScripts/mp_ptc_module"], function(customXML) {
function onRequest(context) {
try {
var recId = 1057613;
var xmlFile = customXML.generateXml(recId);
context.response.writeFile({ file: xmlFile, isInLine: true });
} catch (e) {
log.error("map:error", e);
}
}
return {
onRequest: onRequest
}
});
您可以转换为模块化格式,如下所示。将有 2 个模块,即 suitelet 模块和 XML 生成器。模板存储在文件中。
/**
* @NApiVersion 2.x
* @NModuleScope Public
*/
define(['N/file', 'N/render', 'N/record', 'N/search', 'SuiteScripts/pts_helper1'], function(file, render, record, search, util) {
const TEMPLATE_FILE_ID = "36530";
/**
* Generate XML for a given invoice ID
* @param {number} invoiceId - The ID of the invoice
* @returns {file.File} - The generated XML file
*/
function generateXml(invoiceId) {
var invoiceRecord = record.load({
type: 'invoice',
id: invoiceId
});
var xmlTemplateFile = file.load({
id: TEMPLATE_FILE_ID
});
const customData = {
invoiceId: invoiceId
};
// Render the XML template with custom data
var renderer = render.create();
renderer.templateContent = xmlTemplateFile.getContents();
renderer.addCustomDataSource({
format: render.DataSource.OBJECT,
alias: 'customData',
data: customData
});
var xmlContent = renderer.renderAsString();
var xmlFile = file.create({
name: 'invoice_' + invoiceId + '.xml',
fileType: file.Type.XMLDOC,
contents: xmlContent,
folder: -15 // Replace with your folder ID
});
return xmlFile;
}
return {
generateXml: generateXml
};
});
上面是XML生成器,下面是suitelet
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
define(['SuiteScripts/xmlGenerator'], function(xmlGenerator) {
function onRequest(context) {
try {
var recId = 1057613; // Replace with dynamic ID if needed
var xmlFile = xmlGenerator.generateXml(recId);
context.response.writeFile({ file: xmlFile, isInline: true });
} catch (e) {
log.error("map:error", e);
}
}
return {
onRequest: onRequest
};
});