﻿/// <reference path="References\Explore\SuiteScript\SuiteScriptAPI.js" />
/**
* Company			Automation-X
* Copyright		    2008 Explore Consulting, LLC
* Name				Client_PurchaseOrder.js
* Type				NetSuite Client-Side SuiteScript
* Version			1.0.0.0
* Description		When a link/button is clicked this script will look up the specified line item
*                   on the purchase order and update the item record when necessary to reflect the
*                   current pricing information.
**/

function GetPricingGroupText(pricingGroupID)
{
    switch (pricingGroupID)
    {
        case '5':
            return '10% Margin Base Price';
        case '6':
            return '15% Margin Base Price';
        case '11':
            return '20% Margin Base Price';
        case '12':
            return '25% Margin Base Price';
        case '7':
            return '30% Margin Base Price';
        case '8':
            return '40% Margin Base Price';
        case '9':
            return '50% Margin Base Price';
        case '16':
            return '60% Margin Base Price';
        case '17':
            return '70% Margin Base Price';
        case '18':
            return '80% Margin Base Price';
        case '19':
            return '90% Margin Base Price';
        case '3':
            return 'APCO Salt Lake';
        case '10':
            return 'Devon Carthage';
        case '14':
            return 'ESSI';
        case '15':
            return 'ESSI';
        case '13':
            return 'ESSI';
        case '4':
            return 'Lewis Energy Group';
        case '2':
            return 'XTO Orangeville';
        case '1':
            return 'XTO Orangeville';
    }
}

function OnItemUpdateSelected()
{
    // Make sure that a line is selected that has an item on it
    var proceed = false;
    var selectedLineNumber = nlapiGetCurrentLineItemIndex('item');
    try
    {
        if (selectedLineNumber > 0)
        {
            if (nlapiGetCurrentLineItemValue('item', 'item') != null && nlapiGetCurrentLineItemValue('item', 'item') != '')
            {
                proceed = true;
            }
        }
    }
    catch (Error)
    {
    
    }

    if (proceed)
    {
        // Commit line item in case they hadn't done so already, then re-select it
        nlapiCommitLineItem('item');
        nlapiSelectLineItem('item', selectedLineNumber);
    
        ItemUpdate(selectedLineNumber);
    }
    else
    {
        alert('Please select a line item before pressing Update Item');
    }
}

function ItemUpdate(lineItemNumber)
{
    var vendor = nlapiGetFieldValue('entity');
    var itemRate = nlapiGetLineItemValue('item', 'rate', lineItemNumber);
    var itemInternalID = nlapiGetLineItemValue('item', 'item', lineItemNumber);
    var itemType = nlapiGetLineItemValue('item', 'itemtype', lineItemNumber);
    var preferredVendor = false;
    var itemRecord = null;
    var itemLookupType = '';
    switch (itemType)
    {
        case 'InvtPart':
            itemLookupType = 'inventoryitem';
            break;
        case 'NonInvtPart':
            itemLookupType = 'noninventoryitem';
            break;
        case 'Assembly':
            itemLookupType = 'assemblyitem';
            break;
        case 'Kit':
            itemLookupType = 'kititem';
            break;
        case 'Service':
            itemLookupType = 'serviceitem';
            break;
    }
    
    if (itemLookupType == '')
    {
        alert('The item update function is only designed to work for Inventory, Non-Inventory, Assembly, Kit, and Service item types.');
        return true;
    }
    else 
    {
        itemRecord = nlapiLoadRecord(itemLookupType, itemInternalID);
        if (itemRecord != null)
        {
            // Loop through itemVendor lines until the vendor on the Purchase Order matches the vendor in the list
            var vendorCount = itemRecord.getLineItemCount('itemvendor');
            for (var i = 1; i < (vendorCount + 1); i++)
            {
                if (itemRecord.getLineItemValue('itemvendor', 'vendor', i) == vendor)
                {
                    if (itemRecord.getLineItemValue('itemvendor', 'preferredvendor', i) == 'T')
                    {
                        preferredVendor = true;
                        break;
                    }
                    else
                    {
                        preferredVendor = false;
                        break;
                    }
                }
            }
            
            // Calculate the new Base Price
            var existingBasePrice = 0;
            var newBasePrice = 0;
            var pricingGroupID = itemRecord.getFieldValue('pricinggroup');
            var marginPercent = 0;
            if (pricingGroupID == null || pricingGroupID == '')
            {
                alert('Cannot update the selected item: no pricing group has been defined on the item record.');
                return true;
            }
            else
            {
                // Get pricing group name
                var pricingGroup = GetPricingGroupText(pricingGroupID);
                if (pricingGroup.indexOf('%') > -1)
                {
                    var percentValue = pricingGroup.substr(0, pricingGroup.indexOf('%'));
                    if (percentValue != null)
                    {
                        if (!isNaN(parseFloat(percentValue))) 
                        {
                            marginPercent = parseFloat(percentValue) / 100;
                            
                            newBasePrice = itemRate / (1 - marginPercent);
                            newBasePrice = Math.round(newBasePrice * 100) / 100; // round to hundredth
                        }
                        else
                        {
                            alert('Configured Pricing Group for the selected item does not begin with a numeric value followed by a percent sign.');
                            return true;
                        }
                    }
                }
                
                // Get existing Base Price
                for (var i = 1; i < (itemRecord.getLineItemCount('price') + 1); i++)
                {
                    if (itemRecord.getLineItemValue('price', 'pricelevel', i) == '1')
                    {
                        // This is the base price
                        existingBasePrice = itemRecord.getLineItemValue('price', 'price_1_', i);
                        break;
                    }
                }
                
                // Now update
                var updateCost = false;
                itemRecord.setFieldValue('purchaseprice', itemRate);
                if (preferredVendor)
                {
                    if (parseFloat(newBasePrice) > parseFloat(existingBasePrice))
                    {
                        updateCost = true;
                        itemRecord.setFieldValue('cost', newBasePrice);
                    }
                }
                
                if (updateCost)
                {
                    alert('Item Update summary:\nVendor Purchase Price: ' + itemRate + '\nPurchase Price: ' + newBasePrice);
                }
                else 
                {
                    alert('Item Update summary:\nVendor Purchase Price: ' + itemRate + '\nPurchase Price: (No change)');
                }
                
                try
                {
                    nlapiSubmitRecord(itemRecord, false, true);
                }
                catch (error)
                {
                    alert('Item failed to update: ' + error.message);
                }
            }
        }
        else 
        {
            alert('Selected item could not be loaded.');
            return true;
        }
    }
}
