Hi all, I am trying to do auto cash sale from item...
# suitescript
k
Hi all, I am trying to do auto cash sale from item fulfillment. Is there a way for me to transform Item fulfillment to Cash sale?
b
sales order to cash sale
k
Currently cash sale from sales order includes all item, but I only want to include the item from the item fulfillment record, how can I achieve that?
b
remove them yourself
k
gotcha, when I generate a cash sale from sales order, is there a way for me to get the line id of the item in the related sales order?
Copy code
const cashSale = record.transform({
                    fromType: record.Type.SALES_ORDER,
                    fromId: salesOrderId,
                    toType: record.Type.CASH_SALE,
                    isDynamic: true,
                });
b
orderline on the item fulfillment
in general this kind of logic is made more complicated by items that are present on one transaction and not the other
for example a kit with serialized component items will have components that dont exist on the sales order
in an example of the other direction, line level discounts are on sales orders but not fulfillments
k
that is fine we don't do kits and for discount we have in line level, but I am planning on splitting them evenly
my currently approach is User event script triggered from item fulfillment
Check related sales order and their line id using saved search and store the line id in an array.
Then if possible, transform sales order into cash sale and remove item that my line id array does not include.
but my blocker is how I can get the sales order Line Id for each of the line item in the newly created cash sale
@battk,I'll give orderline a shot.
Copy code
const cashSale = record.transform({
                    fromType: record.Type.SALES_ORDER,
                    fromId: salesOrderId,
                    toType: record.Type.CASH_SALE,
                    isDynamic: true,
                });

                const cashSaleLineCount = cashSale.getLineCount("item")
                const cashSaleLines = cashSale.getSublist({ sublistId: 'item' });
                log.debug('cashsale Line Amount'. cashSaleLines)
                for (let i = 0; i < cashSaleLineCount ; i ++){
                    const salesOrderItemId = cashSale.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'orderline',
                        line: i
                      });
                    
                     
                }
@battk i got it working, thank you!
Funny thing is, i was trying to remove lines from index 0 to infinite
but i found out that I need to remove line index from infinite to 0
b
removing at the beginning changes the line indexes
🙌 1
👍 1
k
@battk I got the auto cash sale working and i am splitting discount correctly into different cash sales. I stumble on an issue that still shows pending billing for the existing discount on the sales order. I'm thinking of storing the discount total in a custom field and remove all discount line item from sales order?
b
what does the code look like
k
@battk
Copy code
define(['N/record', 'N/log'], function (record, log) {
    function afterSubmit(context) {
        if ((context.type === context.UserEventType.CREATE && context.newRecord.getValue('shipstatus') == 'C') || (context.type === "ship")) {
            log.debug('Item fulfillment is created', context);
            const fulfillment = context.newRecord;
            try {
                // Load Fulfillment Record
                const fulfillmentId = fulfillment.getValue('id');
                const itemFulfillment = record.load({
                    type: record.Type.ITEM_FULFILLMENT,
                    id: fulfillmentId,
                    isDynamic: true,
                });
                const itemfulfillmentCount = itemFulfillment.getLineCount("item")

                //Load Sales Record
                const salesOrderId = itemFulfillment.getValue({
                    fieldId: "createdfrom",
                });
                const salesOrder = record.load({
                    type: record.Type.SALES_ORDER,
                    id: salesOrderId,
                    isDynamic: true
                })

                const ifDate = context.newRecord.getValue('trandate');
                //Get Discount Spread
                let totalSalesDiscount = 0;
                let totalGiftCardRedeem = 0;
                let totalNormalCost = 0;
                const salesOrderLineCount = salesOrder.getLineCount({
                    sublistId: 'item'
                });
                log.debug('sales total Line', salesOrderLineCount)

                for (let i = 0; i < salesOrderLineCount; i++) {
                    const rate = salesOrder.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'rate',
                        line: i
                    });
                    const itemid = salesOrder.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        line: i,
                    })
                    const quantity = salesOrder.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'quantity',
                        line: i
                    });
                    log.debug('Item', `Item id - ${itemid},  rate - ${rate} , quantity - ${quantity}`)


                    if (rate < 0 && itemid != '4665') {
                        totalSalesDiscount += rate * quantity;
                    } else if (rate < 0 && itemid == '4665') {
                        totalGiftCardRedeem += rate * quantity;
                    } else {
                        totalNormalCost += rate * quantity;
                    }

                }

                log.debug('Total Normal Amount without Discount : ' + salesOrderId, totalNormalCost)
                log.debug('Total Sales Discount for sales Order ID : ' + salesOrderId, totalSalesDiscount)
                log.debug('Total Gift Card Redeem for sales Order ID : ' + salesOrderId, totalGiftCardRedeem)
                log.debug('Sales Order Info', salesOrder)
                log.debug('IMPORTANT', `IMPORTANT --  Creating Cash Sale`)


                const keepArray = [];
                log.debug('Inside Item fulfillment', 'Item fulfillment IMPORT')
                for (let i = 0; i < itemfulfillmentCount ; i ++){
                       const salesOrderItemLineId = itemFulfillment.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'orderline',
                        line: i
                      });
                      log.debug('salesOrderItemLineId', salesOrderItemLineId)
                      keepArray.push(salesOrderItemLineId)
                }

                log.debug('Keep Array', keepArray)

                const cashSale = record.transform({
                    fromType: record.Type.SALES_ORDER,
                    fromId: salesOrderId,
                    toType: record.Type.CASH_SALE,
                    isDynamic: true
                });

            
                const removeList = [];
                //Add Remove List
                for (let i = 0; i < cashSale.getLineCount("item") ; i ++){
                    const salesOrderItemId = cashSale.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'orderline',
                        line: i
                      });
                      if (!keepArray.includes(salesOrderItemId)) {
                        removeList.push(i);
                      } 
                }
                
                log.debug('Removing List', removeList)

                for(let i of removeList.sort().reverse()){
                    log.debug('Begin Removed', i)
                    cashSale.removeLine({
                        sublistId: "item",
                        line: i,
                    });
                    log.debug('Removed', i)
                }



                //Start adding discount to cash sale

                let splitDiscountAmountTotal = 0;
                let splitGiftCardReddemAmountTotal = 0;
                if(totalSalesDiscount<0){
                    for (let i = 0; i < cashSale.getLineCount("item") ; i ++){
                        const rate = cashSale.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'rate',
                            line: i
                        });
                        const quantity = cashSale.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity',
                            line: i
                        });
                        const itemValue  = rate*quantity;
                        splitDiscountAmountTotal+= (totalSalesDiscount)* (itemValue / totalNormalCost);
                    }
                }

                if(totalGiftCardRedeem<0){
                    for (let i = 0; i < cashSale.getLineCount("item") ; i ++){
                        const rate = cashSale.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'rate',
                            line: i
                        });
                        const quantity = cashSale.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity',
                            line: i
                        });
                        const itemValue  = rate*quantity;
                        splitGiftCardReddemAmountTotal+= (totalGiftCardRedeem)* (itemValue / totalNormalCost);
                    }
                }

                log.debug('Split DiscountAmountTotal', splitDiscountAmountTotal)
                log.debug('Split Total GC Redeem', splitGiftCardReddemAmountTotal);

                if(splitDiscountAmountTotal<0){
                    log.debug('adding Discount Line Item')
                    cashSale.selectNewLine({
                                sublistId: 'item',
                    });
                      cashSale.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        value: 4665,
                      });
                      cashSale.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'quantity',
                        value: 1,
                      });
                      cashSale.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'rate',
                        value: splitDiscountAmountTotal,
                      });
                     
                      cashSale.commitLine({
                        sublistId: 'item',
                      });
                }

                if(splitGiftCardReddemAmountTotal<0){
                    log.debug('adding Gift Card Line Item')
                    cashSale.selectNewLine({
                        sublistId: 'item',
                      });
                      cashSale.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        value: 4717,
                      });
                      cashSale.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'quantity',
                        value: 1,
                      });
                      cashSale.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'rate',
                        value: splitGiftCardReddemAmountTotal,
                      });
                     
                      cashSale.commitLine({
                        sublistId: 'item',
                      });
                }




                cashSale.setValue('trandate', ifDate);
                cashSale.save();

            } catch (e) {
                log.error('Error Billing Item Fulfillment', e.message);
            }
        }
    }



    return {
        afterSubmit: afterSubmit,
    };
});
b
you added a new discount line, which has no relation to the discount on the sales order
k
is it possible to add relationship from a single line to single line of two seperate cash sale ?
b
you need to use the actual line that matches the sales order, which your code removes since the discount item is not present on the item fulfillment
k
gotcha, but if I use the actual line, can i use it again for another cash, because I'm splitting them
b
same behavior as the ui, you want to try it out in the ui first
k
I've tried it on ui where I billed the sales order and removed the item that is not fulfilled, then split the discount for the first item. Then when i click bill again for the remaining fulfilled items, the discount item is gone
It seems like on netsuite UI i can only bill line items once.
b
still doesnt sound right, what does your sales order look like
k
message has been deleted
b
your discounts arent actually discount items
k
Our team needed as a non inv item
both Redeem and Sales Discount
b
you now get to fake quantity
you also lose out on the actual accounting provided by discount items
and complicate taxes
k
I understand but thats how they wanted it. Our taxes are provided by our web store currently.
b
in the meantime, you need to set the quantity of your discounts to some fraction of 1, preferably the correct fraction
k
noted, i'll update the suitescript