Best way with a user event script to add Item A to...
# ask-stanley-ai
s
Best way with a user event script to add Item A to a sales order where the amount of Item A should be calculated by multiplying all line item amounts by a custom percentage field on the item record, and summing it all up
c
AI generated answer (using internal Slack threads):
To add Item A to a sales order with a user event script, where the amount of Item A is calculated by multiplying all line item amounts by a custom percentage field on the item record, and summing it all up, you can follow these steps: 1. Create a User Event script that triggers on the 'After Submit' event of the Sales Order record. 2. In the script, load the submitted Sales Order record and iterate over each line item. 3. For each line item, load the corresponding Item record and retrieve the custom percentage field. 4. Multiply the line item amount by the custom percentage and keep a running total of these calculated amounts. 5. After iterating over all line items, add a new line to the Sales Order for Item A, setting the amount to the calculated total. Here is a sample code snippet based on the conversations provided:
Copy code
javascript
function afterSubmit(context) {
    if (context.type !== context.UserEventType.CREATE && context.type !== context.UserEventType.EDIT) {
        return;
    }

    var salesOrder = context.newRecord;
    var total = 0;

    var itemCount = salesOrder.getLineCount({sublistId: 'item'});
    for (var i = 0; i < itemCount; i++) {
        var itemId = salesOrder.getSublistValue({sublistId: 'item', fieldId: 'item', line: i});
        var itemAmount = salesOrder.getSublistValue({sublistId: 'item', fieldId: 'amount', line: i});

        var itemRecord = record.load({type: 'inventoryitem', id: itemId});
        var customPercentage = itemRecord.getValue({fieldId: 'custitem_custom_percentage'});

        total += itemAmount * customPercentage;
    }

    salesOrder.selectNewLine({sublistId: 'item'});
    salesOrder.setCurrentSublistValue({sublistId: 'item', fieldId: 'item', value: 'Item A'});
    salesOrder.setCurrentSublistValue({sublistId: 'item', fieldId: 'amount', value: total});
    salesOrder.commitLine({sublistId: 'item'});
    
    record.submitFields({type: 'salesorder', id: salesOrder.id, values: {item: salesOrder}});
}
****** Disclaimer: This response was generated by an artificial intelligence assistant based on previous conversations from multiple Slack channels, and may contain inaccuracies or mistakes. ******
Slack thread 1: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.834043384
Slack thread 2: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.831859708
Slack thread 3: here (available only if the original thread was posted in the last 90 days)
Similarity score: 0.830379367
Please provide your feedback on this answer.