The function updateJsonFile has been implemented to update the promotional details of an item in a JSON file stored in the NetSuite File Cabinet. Below is a summary of the functionality:
- Loading the JSON File:
- The JSON file is loaded using
file.load()with the specific file ID (8381704). - The contents are parsed to extract the existing JSON data.
- Handling Non-Array JSON Content:
- If the content of the JSON file is not an array, it is converted to an array using
Object.values()to ensure compatibility.
- Finding the Item:
- The function iterates over the JSON array to locate the item using its
itemId.
- Updating the Item:
- If the item is found, its promotional details (
promotionapplied,promostartdate,promoenddate,promotionrate,promotiontype, andpromotionId) are updated with the values passed to the function.
- Saving the Updated JSON File:
- The updated JSON content is saved back to the File Cabinet, maintaining the same file name and folder.
function updateJsonFile(itemId, promoId, startDate, promoenddate, promotiontype, rate, isPromotionApplied) {
try {
// Load the JSON file
var jsonFile = file.load({
id: 8381704
});
var jsonContent = JSON.parse(jsonFile.getContents());
// Ensure jsonContent is an array
if (!Array.isArray(jsonContent)) {
jsonContent = Object.values(jsonContent); // Convert object to array if needed
}
var itemIndex = -1;
jsonContent.forEach(function (item, index) {
// Log each item
if (item.id === itemId && itemIndex === -1) {
itemIndex = index;
}
});
if (itemIndex !== -1) {
// Update item properties
log.error("jsonContent[itemIndex].itemid", jsonContent[itemIndex].itemid);
jsonContent[itemIndex].promotionapplied = isPromotionApplied;
jsonContent[itemIndex].promostartdate = startDate;
jsonContent[itemIndex].promoenddate = promoenddate;
jsonContent[itemIndex].promotionrate = rate;
jsonContent[itemIndex].promotiontype = promotiontype;
jsonContent[itemIndex].promotionId = promoId;
// Write the updated content back to the file
var updatedFile = file.create({
name: jsonFile.name,
fileType: file.Type.JSON,
contents: JSON.stringify(jsonContent, null, 2),
folder: jsonFile.folder // Maintain the same folder
});
updatedFile.save();
log.error('JSON Updated', 'Promotion details updated for item ID: ' + itemId);
} else {
log.error('Item Not Found', 'Item ID: ' + itemId + ' not found in JSON.');
}
} catch (error) {
log.error('Error Updating JSON File', error.message);
}
}