Created
May 21, 2021 18:22
-
-
Save charlie-s/8df64f0287e037d86e93fcc4e1451463 to your computer and use it in GitHub Desktop.
NetSuite - Create Purchase Orders for out of stock qtys on Sales Order creation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
*@NApiVersion 2.1 | |
*@NModuleScope Public | |
*@NScriptType UserEventScript | |
*/ | |
define(['N/record'], function (record) { | |
return { | |
afterSubmit: function (context) { | |
const order = context.newRecord | |
const numLines = order.getLineCount({ sublistId: 'item' }) | |
const purchaseOrders = new Map() | |
// Build array of Purchase Orders to create. | |
for (let i = 0; i < numLines; i++) { | |
const vendorId = order.getSublistValue({ sublistId: 'item', fieldId: 'custcol_preferred_vendor', line: i }) | |
// Find existing entry or create a new empty entry. | |
if (!purchaseOrders.get(vendorId)) { | |
purchaseOrders.set(vendorId, { items: [] }) | |
} | |
// Calculate the qty needed to purchase. | |
const qty = order.getSublistValue({ sublistId: 'item', fieldId: 'quantity', line: i }) | |
const qtyBackOrdered = order.getSublistValue({ sublistId: 'item', fieldId: 'quantitybackordered', line: i }) | |
const qtyOnHand = order.getSublistValue({ sublistId: 'item', fieldId: 'quantityonhand', line: i }) | |
const qtyToPurchase = qty - Math.max((qtyOnHand || 0) - (qtyBackOrdered || 0), 0) | |
if (qtyToPurchase > 0) { | |
purchaseOrders.get(vendorId).items.push({ | |
itemId: order.getSublistValue({ sublistId: 'item', fieldId: 'item', line: i }), | |
qty: qtyToPurchase | |
}) | |
} | |
} | |
// Create the Purchase Orders. | |
for (const [vendorId, entry] of purchaseOrders) { | |
// Ensure that a qty is needed before creating the PO. | |
if (!entry.items.reduce((acc, item) => acc + item.qty, 0)) continue | |
const purchaseOrder = record.create({ type: record.Type.PURCHASE_ORDER }) | |
purchaseOrder.setValue({ fieldId: 'entity', value: vendorId }) | |
purchaseOrder.setValue({ fieldId: 'custbody_sales_order', value: order.id }) | |
entry.items.forEach((item, i) => { | |
purchaseOrder.setSublistValue({ | |
sublistId: 'item', | |
fieldId: 'item', | |
line: i, | |
value: item.itemId | |
}) | |
purchaseOrder.setSublistValue({ | |
sublistId: 'item', | |
fieldId: 'quantity', | |
line: i, | |
value: item.qty | |
}) | |
}) | |
purchaseOrder.save() | |
} | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment