示例#1
0
 public static void SetValue(this CustomFieldRef field, object value)
 {
     if (field is StringCustomFieldRef)
     {
         ((StringCustomFieldRef)field).SetValue(value);
     }
     else if (field is DoubleCustomFieldRef)
     {
         ((DoubleCustomFieldRef)field).SetValue(value);
     }
     else if (field is MultiSelectCustomFieldRef)
     {
         ((MultiSelectCustomFieldRef)field).SetValue(value);
     }
     else if (field is SelectCustomFieldRef)
     {
         ((SelectCustomFieldRef)field).SetValue(value);
     }
     else if (field is DateCustomFieldRef)
     {
         ((DateCustomFieldRef)field).SetValue(value);
     }
     else if (field is BooleanCustomFieldRef)
     {
         ((BooleanCustomFieldRef)field).SetValue(value);
     }
     else if (field is LongCustomFieldRef)
     {
         ((LongCustomFieldRef)field).SetValue(value);
     }
     else if (field != null)
     {
         throw new NotSupportedException(field.GetType().Name + " is not supported.");
     }
 }
        /// <summary>
        /// Sets the value of the specified custom field.
        /// </summary>
        /// <param name="fieldId">The field id.</param>
        /// <param name="value">The value.</param>
        /// <param name="fieldBuilder">The builder function.</param>
        private CustomFieldRef SetValue <T>(string fieldId, T value, Func <CustomFieldRef> fieldBuilder)
        {
            CustomFieldRef retVal = null;

            if (value != null)
            {
                retVal           = fieldBuilder();
                _parent[fieldId] = retVal;
            }
            else if (_parent.ContainsKey(fieldId))
            {
                retVal = _parent[fieldId];
                _parent.Remove(fieldId);
            }
            return(retVal);
        }
        private CustomFieldRef[] CreateCustomFieldList(M2Order magentoOrder)
        {
            StringCustomFieldRef customer_email = new StringCustomFieldRef()
            {
                scriptId = "custbody111",
                value    = magentoOrder.customer_email
            };

            StringCustomFieldRef receiving_phone = new StringCustomFieldRef()
            {
                scriptId = "custbody46",
                value    = (magentoOrder.extension_attributes.shipping_assignments[0].shipping.address.telephone == null) ? "" : magentoOrder.extension_attributes.shipping_assignments[0].shipping.address.telephone
            };

            StringCustomFieldRef totalWeight = new StringCustomFieldRef()
            {
                scriptId = "custbody63",
                value    = magentoOrder.weight.ToString()
            };

            CustomFieldRef[] customFieldList;

            if (magentoOrder.customer_group_id == 3)
            {
                StringCustomFieldRef amazon_id = new StringCustomFieldRef()
                {
                    scriptId = "custbody_celigo_amz_orderid",
                    value    = magentoOrder.increment_id
                };

                customFieldList = new CustomFieldRef[] { receiving_phone, amazon_id, customer_email, totalWeight };
            }
            else
            {
                customFieldList = new CustomFieldRef[] { receiving_phone, customer_email, totalWeight };
            }

            return(customFieldList);
        }
示例#4
0
        public com.netsuite.webservices.AssemblyItem[] GenerateNetSuitelst(List <Item> Lst_Items)
        {
            Price[]   pricelst   = new Price[1];
            Pricing[] Pricinglst = new Pricing[1];
            com.netsuite.webservices.AssemblyItem[] ItemArr = new com.netsuite.webservices.AssemblyItem[Lst_Items.Count];
            try
            {
                for (int i = 0; i < Lst_Items.Count; i++)
                {
                    Item    Obj        = Lst_Items[i];
                    Setting objSetting = new GenericeDAO <Setting>().GetWhere("Subsidiary_Netsuite_Id=" + Obj.Subsidiary_Id).FirstOrDefault();
                    com.netsuite.webservices.AssemblyItem NewItemObject = new com.netsuite.webservices.AssemblyItem();
                    Categories.CategoriesAccounts         objCatAccount = new Categories.CategoriesAccounts();

                    // if (Obj.Netsuite_Id <= 0)
                    //{
                    NewItemObject.itemId      = Obj.UPC_Code;
                    NewItemObject.displayName = Obj.Display_Name_En;
                    //}


                    NewItemObject.trackLandedCost          = true;
                    NewItemObject.trackLandedCostSpecified = true;

                    if (Obj.Category_Id > 0)
                    {
                        RecordRef classref = new RecordRef();
                        classref.internalId  = Obj.Category_Id.ToString();
                        classref.type        = RecordType.classification;
                        NewItemObject.@class = classref;

                        objCatAccount = new GenericeDAO <Categories.CategoriesAccounts>().GetWhere("Netsuite_Id=" + Obj.Category_Id).FirstOrDefault();
                    }

                    #region Custom fields

                    Obj.Storage_Unit = string.IsNullOrEmpty(Obj.Storage_Unit) ? "" : Obj.Storage_Unit;

                    CustomFieldRef[] custFieldList = new CustomFieldRef[] {
                        new StringCustomFieldRef {
                            value    = !string.IsNullOrEmpty(Obj.Name_Ar)? Obj.Name_Ar.ToString():"",
                            scriptId = "custitem_da_item_name_ar"
                        }
                        ,
                        new StringCustomFieldRef {
                            value    = Obj.UPC_Code.ToString(),
                            scriptId = "custitem1"
                        }
                    };
                    NewItemObject.customFieldList = custFieldList;
                    #endregion
                    if (Obj.Netsuite_Id > 0)
                    {
                        NewItemObject.internalId = Obj.Netsuite_Id.ToString();
                    }

                    #region pricing

                    NewItemObject.pricingMatrix = Helper.GeneratePricingMatrix(objSetting, Obj.Price);
                    #endregion
                    #region AssemblyComponent

                    List <ItemCompnent> itemCompnentslst = new GenericeDAO <ItemCompnent>().GetWhere("ItemFoodics_Id ='" + Obj.Foodics_Id + "'");
                    if (itemCompnentslst.Count > 0)
                    {
                        ItemMember[]   ItemMemberlst = new ItemMember[itemCompnentslst.Count];
                        ItemMemberList memberlst     = new ItemMemberList();
                        for (int x = 0; x < itemCompnentslst.Count; x++)
                        {
                            ItemMember   obj        = new ItemMember();
                            ItemCompnent itmcompobj = itemCompnentslst[x];
                            RecordRef    Itemref    = new RecordRef();
                            Itemref.internalId = itmcompobj.ComponentId.ToString();
                            Itemref.type       = RecordType.inventoryItem;

                            obj.item = Itemref;

                            obj.quantity          = itmcompobj.Quantity == 0 ? 1 : itmcompobj.Quantity;
                            obj.quantitySpecified = true;
                            ItemMemberlst[x]      = obj;
                        }
                        memberlst.itemMember                = ItemMemberlst;
                        NewItemObject.memberList            = memberlst;
                        NewItemObject.memberList.replaceAll = true;
                    }



                    #endregion
                    #region Items Account
                    RecordRef IncomAccountref = new RecordRef();
                    IncomAccountref.type        = RecordType.account;
                    NewItemObject.incomeAccount = IncomAccountref;
                    if (objCatAccount.income_account > 0)
                    {
                        IncomAccountref.internalId = objCatAccount.income_account.ToString();
                    }
                    else if (objSetting.IncomeAccount_Netsuite_Id > 0)
                    {
                        IncomAccountref.internalId = objSetting.IncomeAccount_Netsuite_Id.ToString();
                    }

                    RecordRef cogsAccountref = new RecordRef();
                    cogsAccountref.type       = RecordType.account;
                    NewItemObject.cogsAccount = cogsAccountref;
                    if (objCatAccount.cogs_account > 0)
                    {
                        cogsAccountref.internalId = objCatAccount.cogs_account.ToString();
                    }
                    else if (objSetting.CogsAccount_Netsuite_Id > 0)
                    {
                        cogsAccountref.internalId = objSetting.CogsAccount_Netsuite_Id.ToString();
                    }

                    RecordRef assetAccountref = new RecordRef();
                    assetAccountref.type       = RecordType.account;
                    NewItemObject.assetAccount = assetAccountref;
                    if (objCatAccount.asset_account > 0)
                    {
                        assetAccountref.internalId = objCatAccount.asset_account.ToString();
                    }
                    else if (objSetting.AssetAccount_Netsuite_Id > 0)
                    {
                        assetAccountref.internalId = objSetting.AssetAccount_Netsuite_Id.ToString();
                    }

                    RecordRef intercoIncomeref = new RecordRef();
                    intercoIncomeref.type = RecordType.account;
                    NewItemObject.intercoIncomeAccount = intercoIncomeref;
                    if (objCatAccount.income_intercompany_account > 0)
                    {
                        intercoIncomeref.internalId = objCatAccount.income_intercompany_account.ToString();
                    }
                    else if (objSetting.IntercoIncomeAccount_Netsuite_Id > 0)
                    {
                        intercoIncomeref.internalId = objSetting.IntercoIncomeAccount_Netsuite_Id.ToString();
                    }

                    RecordRef intercoCogsAccount = new RecordRef();
                    intercoCogsAccount.type          = RecordType.account;
                    NewItemObject.intercoCogsAccount = intercoCogsAccount;
                    if (objCatAccount.inter_cogs_account > 0)
                    {
                        intercoCogsAccount.internalId = objCatAccount.inter_cogs_account.ToString();
                    }
                    else if (objSetting.IntercoCogsAccount_Netsuite_Id > 0)
                    {
                        intercoCogsAccount.internalId = objSetting.IntercoCogsAccount_Netsuite_Id.ToString();
                    }

                    RecordRef gainLossAccount = new RecordRef();
                    gainLossAccount.type          = RecordType.account;
                    NewItemObject.gainLossAccount = gainLossAccount;
                    if (objCatAccount.gainloss_account > 0)
                    {
                        gainLossAccount.internalId = objCatAccount.gainloss_account.ToString();
                    }
                    else if (objSetting.GainLossAccount_Netsuite_Id > 0)
                    {
                        gainLossAccount.internalId = objSetting.GainLossAccount_Netsuite_Id.ToString();
                    }


                    if (objCatAccount.cust_qty_variance_account > 0)
                    {
                        RecordRef refgAccount = new RecordRef();
                        refgAccount.type                  = RecordType.account;
                        refgAccount.internalId            = objCatAccount.cust_qty_variance_account.ToString();
                        NewItemObject.billQtyVarianceAcct = refgAccount;
                    }

                    if (objCatAccount.cust_ex_rate_account > 0)
                    {
                        RecordRef refgAccount = new RecordRef();
                        refgAccount.type       = RecordType.account;
                        refgAccount.internalId = objCatAccount.cust_ex_rate_account.ToString();
                        NewItemObject.billExchRateVarianceAcct = refgAccount;
                    }
                    if (objCatAccount.price_variance_account > 0)
                    {
                        RecordRef refgAccount = new RecordRef();
                        refgAccount.type       = RecordType.account;
                        refgAccount.internalId = objCatAccount.price_variance_account.ToString();
                        NewItemObject.billPriceVarianceAcct = refgAccount;
                    }

                    #endregion
                    RecordRef Tax_Schedule = new RecordRef();
                    Tax_Schedule.internalId   = objSetting.TaxSchedule_Netsuite_Id.ToString();
                    Tax_Schedule.type         = RecordType.salesTaxItem;
                    NewItemObject.taxSchedule = Tax_Schedule;
                    RecordRef[] subsidiarylst = new RecordRef[1];
                    RecordRef   subsidiary    = new RecordRef();
                    subsidiary.internalId        = Obj.Subsidiary_Id.ToString();
                    subsidiary.type              = RecordType.subsidiary;
                    subsidiarylst[0]             = subsidiary;
                    NewItemObject.subsidiaryList = subsidiarylst;

                    if (Obj.InActive)
                    {
                        NewItemObject.isInactive          = true;
                        NewItemObject.isInactiveSpecified = true;
                    }

                    ItemArr[i] = NewItemObject;
                }
            }
            catch (Exception ex)
            {
                LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
            }
            return(ItemArr);
        }
 private ListOrRecordRef getSelectCustomField(CustomFieldRef[] theCFList, string theCFinternalID)
 {
     ListOrRecordRef theCFValue = null;
     if (theCFList != null)
     {
         for (int cf = 0; cf < theCFList.Length; cf++)
         {
             CustomFieldRef theCF = theCFList[cf];
             if (theCF.ToString().EndsWith("SelectCustomFieldRef"))
             {
                 SelectCustomFieldRef theStrCF = (SelectCustomFieldRef)theCF;
                 if (theStrCF.internalId == theCFinternalID) theCFValue = theStrCF.value;
             }
         }
     }
     return theCFValue;
 }
 private DateTime getDateTimeCustomField(CustomFieldRef[] theCFList, string theCFinternalID)
 {
     DateTime theCFValue = System.DateTime.Now;
     if (theCFList != null)
     {
         for (int cf = 0; cf < theCFList.Length; cf++)
         {
             CustomFieldRef theCF = theCFList[cf];
             if (theCF.ToString().EndsWith("DateCustomFieldRef"))
             {
                 DateCustomFieldRef theStrCF = (DateCustomFieldRef)theCF;
                 if (theStrCF.internalId == theCFinternalID) theCFValue = theStrCF.value;
             }
         }
     }
     return theCFValue;
 }
 private double getDoubleCustomField(CustomFieldRef[] theCFList, string theCFinternalID)
 {
     double theCFValue = 0.00;
     if (theCFList != null)
     {
         for (int cf = 0; cf < theCFList.Length; cf++)
         {
             CustomFieldRef theCF = theCFList[cf];
             if (theCF.ToString().EndsWith("DoubleCustomFieldRef"))
             {
                 DoubleCustomFieldRef theStrCF = (DoubleCustomFieldRef)theCF;
                 if (theStrCF.internalId == theCFinternalID) theCFValue = theStrCF.value;
             }
         }
     }
     return theCFValue;
 }
 private int getLongCustomField(CustomFieldRef[] theCFList, string theCFinternalID)
 {
     long theCFValue = 0;
     if (theCFList != null)
     {
         for (int cf = 0; cf < theCFList.Length; cf++)
         {
             CustomFieldRef theCF = theCFList[cf];
             if (theCF.ToString().EndsWith("LongCustomFieldRef"))
             {
                 LongCustomFieldRef theStrCF = (LongCustomFieldRef)theCF;
                 if (theStrCF.internalId == theCFinternalID) theCFValue = theStrCF.value;
             }
         }
     }
     return Convert.ToInt32(theCFValue);
 }
 private bool getBooleanCustomField(CustomFieldRef[] theCFList, string theCFinternalID)
 {
     bool theCFValue = false;
     if (theCFList != null)
     {
         for (int cf = 0; cf < theCFList.Length; cf++)
         {
             CustomFieldRef theCF = theCFList[cf];
             if (theCF.ToString().EndsWith("BooleanCustomFieldRef"))
             {
                 BooleanCustomFieldRef theStrCF = (BooleanCustomFieldRef)theCF;
                 if (theStrCF.internalId == theCFinternalID) theCFValue = theStrCF.value;
             }
         }
     }
     return theCFValue;
 }
        private WriteResponseList CreateCreditMemo(List <Foodics.NetSuite.Shared.Model.Invoice> returnList)
        {
            //Define Array of credit Memo Then Loop
            CreditMemo[]     memoList = new CreditMemo[returnList.Count];
            CreditMemoItem[] memoitemarr;
            CreditMemoItem   invoiceItemObject;

            //add return id + return netsuite id to credit memo table, credit memo netsuite id
            #region Add Credit Memoes to CreditMemo Array

            for (int i = 0; i < returnList.Count; i++)
            {
                Foodics.NetSuite.Shared.Model.Invoice invoiceReturn   = returnList[i];
                Foodics.NetSuite.Shared.Model.Invoice invoiceoriginal = new GenericeDAO <Foodics.NetSuite.Shared.Model.Invoice>().GetWhere(" Foodics_Id = '" + invoiceReturn.Original_Foodics_Id + "'").FirstOrDefault();
                if (invoiceoriginal != null && invoiceoriginal.Netsuite_Id > 0)
                {
                    Setting objSetting = new GenericeDAO <Setting>().GetWhere("Subsidiary_Netsuite_Id=" + invoiceReturn.Subsidiary_Id).FirstOrDefault();
                    StringCustomFieldRef FoodicsRef, FoodicsNumb, orderDiscount;
                    CustomFieldRef[]     customFieldRefArray;
                    CreditMemo           memo = new CreditMemo();
                    // Return
                    RecordRef returnRef = new RecordRef();
                    returnRef.internalId = invoiceoriginal.Netsuite_Id.ToString();
                    returnRef.type       = RecordType.invoice;
                    memo.createdFrom     = returnRef;


                    //Customer

                    RecordRef entity = new RecordRef();
                    entity.internalId = invoiceReturn.Customer_Netsuite_Id > 0 ? invoiceReturn.Customer_Netsuite_Id.ToString() : objSetting.Customer_Netsuite_Id.ToString();
                    entity.type       = RecordType.customer;
                    memo.entity       = entity;

                    //currency
                    RecordRef currency = new RecordRef();
                    currency.internalId = objSetting.Currency_Netsuite_Id.ToString();
                    currency.type       = RecordType.currency;
                    memo.currency       = currency;

                    //date
                    memo.tranDateSpecified = true;
                    memo.tranDate          = TimeZoneInfo.ConvertTimeToUtc(invoiceReturn.Date, TimeZoneInfo.Local);

                    //exchange rate
                    memo.exchangeRate = invoiceReturn.Exchange_Rate;

                    //subsidary
                    RecordRef subsid = new RecordRef();
                    subsid.internalId = invoiceReturn.Subsidiary_Id.ToString();
                    subsid.type       = RecordType.subsidiary;
                    memo.subsidiary   = subsid;


                    #region Item List
                    List <Foodics.NetSuite.Shared.Model.InvoiceItem> itemLst = new GenericeDAO <Foodics.NetSuite.Shared.Model.InvoiceItem>().GetWhere(" ProductStatus =6 and Invoice_Id =" + invoiceReturn.Id + " and isnull(Item_Id,0) >0 ");
                    int DiscountItems = itemLst.Where(x => x.Line_Discount_Amount > 0).Count();
                    //Define Invoice Items List
                    int totalItems = itemLst.Count + DiscountItems;
                    memoitemarr = new CreditMemoItem[totalItems];
                    if (itemLst.Count > 0)
                    {
                        CreditMemoItemList crdtmemoitmlst = new CreditMemoItemList();

                        try
                        {
                            int arr = 0;
                            for (int k = 0; k < totalItems; k++)
                            {
                                Foodics.NetSuite.Shared.Model.InvoiceItem itemDetails = itemLst[arr];
                                invoiceItemObject = CreateCreditItem(objSetting, itemDetails);
                                memoitemarr[k]    = invoiceItemObject;
                                if (itemDetails.Line_Discount_Amount > 0)
                                {
                                    float Discount = itemDetails.Line_Discount_Amount;
                                    k++;
                                    Foodics.NetSuite.Shared.Model.InvoiceItem OtherCharge = new Foodics.NetSuite.Shared.Model.InvoiceItem();
                                    OtherCharge.Item_Id   = objSetting.OtherChargeItem_Netsuite_Id;
                                    OtherCharge.Amount    = Discount * -1;
                                    OtherCharge.Quantity  = 1;
                                    OtherCharge.Item_Type = "OtherChargeResaleItem";
                                    invoiceItemObject     = CreateCreditItem(objSetting, OtherCharge);
                                    memoitemarr[k]        = invoiceItemObject;
                                }
                                arr++;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
                        }


                        crdtmemoitmlst.item = memoitemarr;
                        memo.itemList       = crdtmemoitmlst;
                    }

                    #endregion

                    #region Discount
                    if (invoiceReturn.Total_Discount > 0)
                    {
                        RecordRef discountitem = new RecordRef();
                        discountitem.type = RecordType.discountItem;
                        memo.discountItem = discountitem;

                        memo.discountRate = (Math.Round((invoiceReturn.Total_Discount / 1.15), 3) * -1).ToString();
                        if (invoiceReturn.Discount_Id > 0)
                        {
                            discountitem.internalId = invoiceReturn.Discount_Id.ToString();
                        }
                        else
                        {
                            discountitem.internalId = objSetting.DiscountItem_Netsuite_Id.ToString();
                        }
                    }
                    else
                    {
                        memo.discountRate = "0";
                    }
                    if (invoiceReturn.Accounting_Discount_Item != 0)
                    {
                        RecordRef discItem = new RecordRef();
                        discItem.internalId = invoiceReturn.Accounting_Discount_Item.ToString();
                        discItem.type       = RecordType.discountItem;
                        memo.discountItem   = discItem;
                    }
                    #region Custom Attributes
                    orderDiscount          = new StringCustomFieldRef();
                    orderDiscount.scriptId = "custbody_da_invoice_discount";
                    orderDiscount.value    = invoiceReturn.Total_Discount.ToString();


                    FoodicsRef          = new StringCustomFieldRef();
                    FoodicsRef.scriptId = "custbody_da_foodics_reference";
                    FoodicsRef.value    = invoiceReturn.BarCode.ToString();

                    FoodicsNumb          = new StringCustomFieldRef();
                    FoodicsNumb.scriptId = "custbody_da_foodics_number";
                    FoodicsNumb.value    = invoiceReturn.Number.ToString();

                    customFieldRefArray    = new CustomFieldRef[3];
                    customFieldRefArray[0] = orderDiscount;
                    customFieldRefArray[1] = FoodicsRef;
                    customFieldRefArray[2] = FoodicsNumb;

                    memo.customFieldList = customFieldRefArray;
                    #endregion

                    #endregion


                    memoList[i] = memo;
                }
            }

            //Post Memos to Netsuite
            WriteResponseList memoWR = Service(true).addList(memoList);
            bool receiptresult       = memoWR.status.isSuccess;

            if (receiptresult)
            {
                UpdatedInvoice(returnList, memoWR);
            }
            #endregion
            return(memoWR);
        }
示例#11
0
        public override Int64 Set(string parametersArr)
        {
            List <Foodics.NetSuite.Shared.Model.PaymentMethodEntity> lstitemsAll = new CustomDAO().SelectCustomerPayment(4);
            int Exe_length = 200;
            int lstend     = Exe_length;

            if (lstitemsAll.Count > 0)
            {
                for (int Index = 0; Index < lstitemsAll.Count; Index += Exe_length)
                {
                    if (Index + Exe_length >= lstitemsAll.Count)
                    {
                        lstend = lstitemsAll.Count - Index;
                    }
                    List <Foodics.NetSuite.Shared.Model.PaymentMethodEntity> invoiceMethodLst = lstitemsAll.GetRange(Index, lstend);
                    try
                    {
                        if (invoiceMethodLst.Count > 0)
                        {
                            List <Record> cps      = new List <Record>();
                            bool          is_valid = false;
                            try
                            {
                                for (int f = 0; f < invoiceMethodLst.Count; f++)
                                {
                                    PaymentMethodEntity payobj = invoiceMethodLst[f];
                                    Foodics.NetSuite.Shared.Model.Invoice invoiceobj = new GenericeDAO <Foodics.NetSuite.Shared.Model.Invoice>().GetWhere(" Foodics_Id = '" + payobj.Foodics_Id + "'").FirstOrDefault();
                                    Setting objSetting = new GenericeDAO <Setting>().GetWhere("Subsidiary_Netsuite_Id=" + invoiceobj.Subsidiary_Id).FirstOrDefault();
                                    #region Accept Payment
                                    CustomerPaymentApplyList    AplyList    = new CustomerPaymentApplyList();
                                    CustomerPaymentCreditList   CreditList  = new CustomerPaymentCreditList();
                                    CustomerPaymentDepositList  DepositList = new CustomerPaymentDepositList();
                                    List <CustomerPaymentApply> payApplylst = new List <CustomerPaymentApply>();
                                    CustomerPaymentApply        payApply;
                                    CustomerPayment             cp = new CustomerPayment();
                                    cp.autoApply = false;
                                    is_valid     = false;
                                    #region Payment Properties
                                    //customer
                                    RecordRef customer = new RecordRef();
                                    customer.internalId = invoiceobj.Customer_Netsuite_Id > 0 ? invoiceobj.Customer_Netsuite_Id.ToString() : objSetting.Customer_Netsuite_Id.ToString();
                                    customer.type       = RecordType.customer;
                                    cp.customer         = customer;

                                    //currency
                                    RecordRef currency = new RecordRef();
                                    currency.internalId = objSetting.Currency_Netsuite_Id.ToString();//payobj.Currency_Id.ToString();
                                    currency.type       = RecordType.currency;
                                    cp.currency         = currency;
                                    StringCustomFieldRef FoodicsRef, FoodicsNumb;

                                    // memo
                                    cp.memo = payobj.Notes;

                                    //tranDate
                                    cp.tranDate          = TimeZoneInfo.ConvertTimeToUtc(payobj.Business_Date, TimeZoneInfo.Local);
                                    cp.tranDateSpecified = true;

                                    //cp.subsidiary
                                    RecordRef subsidiary = new RecordRef();
                                    subsidiary.internalId = objSetting.Subsidiary_Netsuite_Id.ToString(); //payobj.Subsidiary_Id.ToString();
                                    subsidiary.type       = RecordType.subsidiary;
                                    cp.subsidiary         = subsidiary;

                                    //cp.location
                                    RecordRef location = new RecordRef();
                                    location.internalId = invoiceobj.Location_Id.ToString();//objSetting.Location_Netsuite_Id.ToString();//payobj.Location_Id.ToString();
                                    location.type       = RecordType.location;
                                    cp.location         = location;

                                    // payment amount
                                    cp.payment          = payobj.Amount;
                                    cp.paymentSpecified = true;



                                    #region Payment Custom Attributes

                                    DoubleCustomFieldRef payPercent = new DoubleCustomFieldRef();
                                    payPercent.scriptId = "custbody_da_payment_method_percentage";
                                    payPercent.value    = payobj.Payment_Method_Percentage;

                                    DoubleCustomFieldRef PayPercentAmount = new DoubleCustomFieldRef();
                                    PayPercentAmount.scriptId = "custbody_da_payment_method_amount";
                                    PayPercentAmount.value    = (payobj.Payment_Method_Percentage * payobj.Amount) / 100;

                                    LongCustomFieldRef trans_id = new LongCustomFieldRef();
                                    trans_id.scriptId = "custbody_da_transaction_id";
                                    trans_id.value    = invoiceobj.Netsuite_Id;

                                    FoodicsRef          = new StringCustomFieldRef();
                                    FoodicsRef.scriptId = "custbody_da_foodics_reference";
                                    FoodicsRef.value    = invoiceobj.BarCode.ToString();

                                    FoodicsNumb          = new StringCustomFieldRef();
                                    FoodicsNumb.scriptId = "custbody_da_foodics_number";
                                    FoodicsNumb.value    = invoiceobj.Number.ToString();

                                    CustomFieldRef[] customFieldRefArray = new CustomFieldRef[5];
                                    customFieldRefArray[0] = trans_id;
                                    customFieldRefArray[1] = payPercent;
                                    customFieldRefArray[2] = PayPercentAmount;
                                    customFieldRefArray[3] = FoodicsRef;
                                    customFieldRefArray[4] = FoodicsNumb;

                                    cp.customFieldList = customFieldRefArray;
                                    #endregion

                                    #region Apply Invoice
                                    // Invoice
                                    payApply                 = new CustomerPaymentApply();
                                    payApply.apply           = true;
                                    payApply.docSpecified    = true;
                                    payApply.amountSpecified = true;
                                    payApply.currency        = currency.internalId;
                                    payApply.type            = "Invoice";
                                    payApply.doc             = invoiceobj.Netsuite_Id;
                                    payApply.total           = payobj.Amount;
                                    payApply.amount          = payobj.Amount;
                                    payApply.applyDate       = payobj.Business_Date;

                                    payApplylst.Add(payApply);
                                    #endregion

                                    #region Invoice Custom Attributes



                                    #endregion

                                    // payment method
                                    if (payobj.Payment_Method_Id > 0)
                                    {
                                        is_valid = true;

                                        //payment method
                                        RecordRef payment_method = new RecordRef();
                                        payment_method.internalId = payobj.Payment_Method_Id.ToString();
                                        payment_method.type       = RecordType.customerPayment;
                                        cp.paymentMethod          = payment_method;
                                        cp.authCode = payobj.Ref.Length > 30 ? payobj.Ref.Substring(0, 30) : payobj.Ref;


                                        // amount
                                        cp.payment          = payobj.Amount;
                                        cp.paymentSpecified = true;
                                    }

                                    AplyList.apply = payApplylst.ToArray();
                                    cp.applyList   = AplyList;

                                    #endregion

                                    if (is_valid)
                                    {
                                        cps.Add(cp);
                                    }
                                    #endregion
                                }
                            }
                            catch (Exception ex)
                            {
                                LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
                            }
                            if (cps.Count > 0)
                            {
                                WriteResponseList wr = Service(true).addList(cps.ToArray());
                                bool result          = wr.status.isSuccess;

                                UpdatedLst(invoiceMethodLst, wr);

                                // return result;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
                    }
                }
            }
            return(0);
        }
        public override Int64 Set(string parametersArr)
        {
            try
            {
                //Set Values of Netsuite Customer ID
                //  LogDAO.Integration_Exception(LogIntegrationType.Info, TaskRunType.POST, "InvoiceTask", "Start");

                //new GenericeDAO<Foodics.NetSuite.Shared.Model.Invoice.Integrate>().GetAndUpdateCustomerIDandCreditMemo();
                //get recentrly added invoices after creating the return
                List <Foodics.NetSuite.Shared.Model.Invoice> invoiceLst = new GenericeDAO <Foodics.NetSuite.Shared.Model.Invoice>().GetWhere(" Netsuite_Id IS NULL or Netsuite_Id =0");
                Setting objSetting = new GenericeDAO <Setting>().GetAll().FirstOrDefault();
                // = new NetsuiteDAO().SelectInvoicesForIntegration();
                //  LogDAO.Integration_Exception(LogIntegrationType.Info, TaskRunType.POST, "InvoiceTask", "Count: " + invoiceLst.Count.ToString());
                bool result = true;
                if (invoiceLst.Count > 0)
                {
                    #region variables
                    Invoice[] InvoiceArr = new Invoice[invoiceLst.Count];

                    List <Foodics.NetSuite.Shared.Model.InvoiceItem> itemLst;
                    List <Foodics.NetSuite.Shared.Model.GiftCertificate.Integrate> giftCertificateLst;
                    //List<Foodics.NetSuite.Shared.Model.ItemLotSerial.Sales> lotSerialLst;

                    Foodics.NetSuite.Shared.Model.Invoice     invoice_info;
                    Foodics.NetSuite.Shared.Model.InvoiceItem itemDetails;

                    GiftCertRedemption[] giftRedeem;
                    InvoiceItem[]        invoiceItems;

                    DateTime                invoice_date;
                    Invoice                 invoiceObject;
                    InvoiceItem             invoiceItemObject;
                    InvoiceItemList         items;
                    InventoryAssignmentList InventoryAssignmentlst;
                    InventoryAssignment[]   assignList;
                    InventoryAssignment     assign;
                    InventoryDetail         invDetails;

                    GiftCertRedemptionList redemptionLst;

                    DateCustomFieldRef   trans_time;
                    ListOrRecordRef      emirate_region, custSelectValue, custSelectCashier;
                    SelectCustomFieldRef emirate_ref = null, terminal, cashier;
                    RecordRef            authCodeRef, taxCode, item, unit, price, itmSerial, discItem,
                                         subsid, currency, entity, location, classification, department;
                    DoubleCustomFieldRef line_total, line_discount_amount, balance, paid, lineDiscount;
                    StringCustomFieldRef trans_no, pos_id, orderDiscount;

                    CustomFieldRef[] customFieldRefArr, customFieldRefArray;

                    int item_custom_cols = 2;
                    #endregion

                    for (int i = 0; i < invoiceLst.Count; i++)
                    {
                        try
                        {
                            invoice_info = invoiceLst[i];
                            //Netsuite invoice type
                            invoiceObject = new Invoice();

                            //get invoice items
                            itemLst = new GenericeDAO <Foodics.NetSuite.Shared.Model.InvoiceItem>().GetWhere("Invoice_Id =" + invoice_info.Id);//new NetsuiteDAO().SelectInvoicItems(invoice_info.Id);

                            //get invoice gift certificates
                            #region gift certificate redemption
                            //try
                            //{
                            //    giftCertificateLst = new NetsuiteDAO().SelectEntityGiftCertificates(invoice_info.Id, 1);
                            //    if (giftCertificateLst.Count > 0)
                            //    {
                            //        redemptionLst = new GiftCertRedemptionList();
                            //        giftRedeem = new GiftCertRedemption[giftCertificateLst.Count];
                            //        for (int r = 0; r < giftCertificateLst.Count; r++)
                            //        {
                            //            GiftCertRedemption gift = new GiftCertRedemption();
                            //            authCodeRef = new RecordRef();
                            //            authCodeRef.internalId = giftCertificateLst[r].Netsuite_Id.ToString();
                            //            authCodeRef.type = RecordType.giftCertificate;
                            //            gift.authCode = authCodeRef;
                            //            gift.authCodeAppliedSpecified = true;
                            //            gift.authCodeApplied = Convert.ToDouble(giftCertificateLst[r].Amount);
                            //            giftRedeem[r] = gift;
                            //        }

                            //        redemptionLst.giftCertRedemption = giftRedeem;
                            //        invoiceObject.giftCertRedemptionList = redemptionLst;
                            //    }
                            //}
                            //catch (Exception ex)
                            //{
                            //    //LogDAO.Integration_Exception(LogIntegrationType.Error, TaskRunType.POST, "InvoiceTask", "Error adding GiftCertificates: " + ex.Message + " Invoice id = " + invoiceLst[i].Id.ToString());
                            //}
                            #endregion

                            #region invoice items

                            //Define Invoice Items List
                            invoiceItems = new InvoiceItem[itemLst.Count];
                            try
                            {
                                item_custom_cols = 2;
                                for (int k = 0; k < itemLst.Count; k++)
                                {
                                    itemDetails       = itemLst[k];
                                    invoiceItemObject = new InvoiceItem();

                                    // TAX
                                    //invoiceItemObject.taxRate1Specified = true;
                                    //invoiceItemObject.taxRate1 = itemDetails.Tax_Rate;
                                    //invoiceItemObject.taxAmount = itemDetails.Tax_Amt;

                                    // tax code
                                    taxCode                   = new RecordRef();
                                    taxCode.internalId        = objSetting.TaxCode_Netsuite_Id.ToString(); //"15";//itemDetails.Tax_Code.ToString();
                                    taxCode.type              = RecordType.taxAcct;
                                    invoiceItemObject.taxCode = taxCode;

                                    // item
                                    item            = new RecordRef();
                                    item.internalId = itemDetails.Item_Id.ToString();
                                    item.type       = (RecordType)Enum.Parse(typeof(RecordType), itemDetails.Item_Type, true);
                                    //item.type = (RecordType)Enum.Parse(typeof(RecordType), "InventoryItem", true);
                                    invoiceItemObject.item = item;

                                    if (Utility.ConvertToInt(itemDetails.Units) > 0)
                                    {
                                        unit                    = new RecordRef();
                                        unit.internalId         = itemDetails.Units.ToString();
                                        unit.type               = RecordType.unitsType;
                                        invoiceItemObject.units = unit;
                                    }

                                    // price level
                                    #region price level
                                    price      = new RecordRef();
                                    price.type = RecordType.priceLevel;

                                    if (itemDetails.Amount > 0)
                                    {
                                        //if (itemDetails.Customer_Price_Level > 0)
                                        //{
                                        //    // customer price level
                                        //    price.internalId = itemDetails.Customer_Price_Level.ToString();
                                        //    invoiceItemObject.price = price;
                                        //}
                                        //else if (itemDetails.Price_Level_Id > 0)
                                        //{
                                        //    // default price level
                                        //    price.internalId = itemDetails.Price_Level_Id.ToString();
                                        //    invoiceItemObject.price = price;
                                        //}
                                        //else
                                        //{
                                        // amount
                                        invoiceItemObject.amountSpecified = true;
                                        invoiceItemObject.amount          = itemDetails.Amount;
                                        //}
                                    }

                                    #endregion

                                    // invoiceItemObject.costEstimateType = (ItemCostEstimateType)itemDetails.Cost_Estimate_Type;


                                    //if (itemDetails.Item_Type == "GiftCertificateItem")
                                    //{
                                    //    #region sell gift certificate
                                    //    try
                                    //    {
                                    //        invoiceItemObject.giftCertNumber = itemDetails.Gift_Code;
                                    //        invoiceItemObject.giftCertFrom = itemDetails.Sender;
                                    //        invoiceItemObject.giftCertMessage = itemDetails.Gift_Message;
                                    //        invoiceItemObject.giftCertRecipientName = itemDetails.Recipient_Name;
                                    //        invoiceItemObject.giftCertRecipientEmail = itemDetails.Recipient_Email;
                                    //    }
                                    //    catch { }
                                    //    #endregion
                                    //}
                                    //else
                                    //{
                                    // quantity
                                    invoiceItemObject.quantitySpecified = true;
                                    invoiceItemObject.quantity          = itemDetails.Quantity;

                                    #region serials/Lot
                                    //if (Utility.ItemTypeSerialized.Contains(itemDetails.Item_Type))
                                    //{
                                    //    lotSerialLst = new NetsuiteDAO().SelectInvoiceLotSerials(itemDetails.Id);
                                    //    InventoryAssignmentlst = new InventoryAssignmentList();
                                    //    assignList = new InventoryAssignment[lotSerialLst.Count];

                                    //    for (int z = 0; z < lotSerialLst.Count; z++)
                                    //    {
                                    //        assign = new InventoryAssignment();

                                    //        itmSerial = new RecordRef();
                                    //        itmSerial.internalId = lotSerialLst[z].Netsuite_Id.ToString();
                                    //        itmSerial.type = RecordType.lotNumberedInventoryItem;
                                    //        itmSerial.typeSpecified = true;

                                    //        if (Utility.ItemTypeLot.Contains(itemDetails.Item_Type))
                                    //        {
                                    //            assign.quantitySpecified = true;
                                    //            assign.quantity = lotSerialLst[z].Quantity;
                                    //        }
                                    //        assign.issueInventoryNumber = itmSerial;

                                    //        assignList[z] = assign;
                                    //    }

                                    //    InventoryAssignmentlst.inventoryAssignment = assignList;
                                    //    invDetails = new InventoryDetail();
                                    //    invDetails.inventoryAssignmentList = InventoryAssignmentlst;

                                    //    invoiceItemObject.inventoryDetail = invDetails;
                                    //}

                                    #endregion
                                    //  }

                                    #region custom fields

                                    try
                                    {
                                        #region line-item discount

                                        //line_total = new DoubleCustomFieldRef();
                                        //line_total.scriptId = "custcol_da_pos_line_item_total";
                                        //line_total.value = Math.Round(itemDetails.Total_Line_Amount, 3);

                                        //line_discount_amount = new DoubleCustomFieldRef();
                                        //line_discount_amount.scriptId = "custcol_da_pos_line_item_discount";
                                        //line_discount_amount.value = Math.Round(itemDetails.Line_Discount_Amount, 3);

                                        // line-item amount
                                        invoiceItemObject.amount = (itemDetails.Quantity * itemDetails.Amount);

                                        #endregion

                                        #region Transaction Region (Emirate)
                                        //item_custom_cols = 2;
                                        //if (invoice_info.Transaction_Region > 0)
                                        //{
                                        //    item_custom_cols = 3;
                                        //    emirate_region = new ListOrRecordRef();
                                        //    emirate_region.internalId = invoice_info.Transaction_Region.ToString();

                                        //    emirate_ref = new SelectCustomFieldRef();
                                        //    emirate_ref.scriptId = "custcol_emirate";
                                        //    emirate_ref.value = emirate_region;
                                        //}
                                        #endregion

                                        //customFieldRefArr = new CustomFieldRef[item_custom_cols];
                                        //customFieldRefArr[0] = line_total;
                                        //customFieldRefArr[1] = line_discount_amount;

                                        //if (item_custom_cols == 3)
                                        //    customFieldRefArr[2] = emirate_ref;

                                        //invoiceItemObject.customFieldList = customFieldRefArr;
                                    }
                                    catch (Exception ex)
                                    {
                                        //  LogDAO.Integration_Exception(LogIntegrationType.Error, TaskRunType.POST, "InvoiceTask", "Error adding customField: " + ex.Message + " Invoice id = " + invoiceLst[i].Id.ToString());
                                    }
                                    #endregion

                                    invoiceItems[k] = invoiceItemObject;
                                }
                            }
                            catch (Exception ex)
                            {
                                //  LogDAO.Integration_Exception(LogIntegrationType.Error, TaskRunType.POST, "InvoiceTask", "Error adding invoice: " + ex.Message + " Invoice id = " + invoiceLst[i].Id.ToString());
                            }
                            //Assign invoive items
                            items                  = new InvoiceItemList();
                            items.item             = invoiceItems;
                            invoiceObject.itemList = items;

                            //GiftCertRedemption
                            #endregion

                            #region Invoice Values

                            #region Standard Attributes
                            invoice_date = TimeZoneInfo.ConvertTimeToUtc(invoice_info.Date, TimeZoneInfo.Local);

                            invoiceObject.tranDateSpecified = true;
                            invoiceObject.dueDateSpecified  = true;
                            invoiceObject.tranDate          = invoice_date;
                            invoiceObject.dueDate           = invoice_date;
                            invoiceObject.exchangeRate      = invoice_info.Exchange_Rate;

                            invoiceObject.memo = invoice_info.Notes;

                            if (invoice_info.Subsidiary_Id > 0)
                            {
                                subsid                   = new RecordRef();
                                subsid.internalId        = objSetting.Subsidiary_Netsuite_Id.ToString();
                                subsid.type              = RecordType.subsidiary;
                                invoiceObject.subsidiary = subsid;
                            }

                            //RecordRef customForm = new RecordRef();
                            //customForm.internalId = "92";
                            //invoiceObject.customForm = customForm;

                            currency               = new RecordRef();
                            currency.internalId    = objSetting.Currency_Netsuite_Id.ToString();
                            currency.type          = RecordType.currency;
                            invoiceObject.currency = currency;

                            entity = new RecordRef();

                            entity.internalId    = invoice_info.Customer_Netsuite_Id > 0? invoice_info.Customer_Netsuite_Id.ToString(): objSetting.Customer_Netsuite_Id.ToString();
                            entity.type          = RecordType.customer;
                            invoiceObject.entity = entity;

                            location               = new RecordRef();
                            location.internalId    = invoice_info.Location_Id.ToString(); //objSetting.Location_Netsuite_Id.ToString();
                            location.type          = RecordType.location;
                            invoiceObject.location = location;

                            // department
                            //if (invoice_info.Department_Id > 0)
                            //{
                            //    department = new RecordRef();
                            //    department.internalId = invoice_info.Department_Id.ToString();
                            //    department.type = RecordType.department;
                            //    invoiceObject.department = department;
                            //}

                            //// class
                            //if (invoice_info.Class_Id > 0)
                            //{
                            //    classification = new RecordRef();
                            //    classification.internalId = invoice_info.Class_Id.ToString();
                            //    classification.type = RecordType.classification;
                            //    invoiceObject.@class = classification;
                            //}
                            // sales rep
                            if (invoice_info.Sales_Rep_Id > 0)
                            {
                                RecordRef sales_rep = new RecordRef();
                                sales_rep.internalId   = invoice_info.Sales_Rep_Id.ToString();
                                sales_rep.type         = RecordType.employee;
                                invoiceObject.salesRep = sales_rep;
                            }
                            #endregion

                            #region Invoice Custom Attributes

                            trans_no          = new StringCustomFieldRef();
                            trans_no.scriptId = "custbody_da_pos_trans_no";
                            trans_no.value    = invoice_info.BarCode.ToString();

                            pos_id          = new StringCustomFieldRef();
                            pos_id.scriptId = "custbody_da_pos_id";
                            pos_id.value    = invoice_info.Id.ToString();

                            custSelectValue = new ListOrRecordRef();

                            terminal = new SelectCustomFieldRef();
                            custSelectValue.internalId = invoice_info.Terminal_Id.ToString();
                            terminal.scriptId          = "custbody_da_terminal";
                            terminal.value             = custSelectValue;

                            custSelectCashier = new ListOrRecordRef();

                            cashier = new SelectCustomFieldRef();
                            custSelectCashier.internalId = invoice_info.Cashier.ToString();
                            cashier.scriptId             = "custbody_da_cashier";
                            cashier.value = custSelectCashier;

                            balance          = new DoubleCustomFieldRef();
                            balance.scriptId = "custbody_da_balance";
                            balance.value    = Math.Round(invoice_info.Balance, 3);


                            paid          = new DoubleCustomFieldRef();
                            paid.scriptId = "custbody_da_paid";
                            paid.value    = Math.Round(invoice_info.Paid, 3);

                            trans_time          = new DateCustomFieldRef();
                            trans_time.scriptId = "custbody_da_pos_trans_time";
                            trans_time.value    = invoice_date;

                            #region Discount

                            invoiceObject.discountRate = (Math.Round(invoice_info.Total_Discount, 3) * -1).ToString();

                            lineDiscount          = new DoubleCustomFieldRef();
                            lineDiscount.scriptId = "custbody_da_pos_line_item_discount";
                            lineDiscount.value    = Math.Round(invoice_info.Line_Discount_Amount, 3) * -1;


                            orderDiscount          = new StringCustomFieldRef();
                            orderDiscount.scriptId = "custbody_da_pos_order_discount";
                            orderDiscount.value    = (Math.Round(invoice_info.Invoice_Discount_Rate, 3) * -1).ToString();
                            if (invoice_info.Invoice_Discount_Type == 1)
                            {
                                orderDiscount.value = (Math.Round(invoice_info.Invoice_Discount_Rate, 3) * -1).ToString() + "%";
                            }

                            if (invoice_info.Accounting_Discount_Item != 0)
                            {
                                discItem                   = new RecordRef();
                                discItem.internalId        = invoice_info.Accounting_Discount_Item.ToString();
                                discItem.type              = RecordType.discountItem;
                                invoiceObject.discountItem = discItem;
                            }
                            #endregion

                            int length = 7;
                            if (invoice_info.Terminal_Id > 0)
                            {
                                length = 8;
                            }

                            customFieldRefArray    = new CustomFieldRef[length];
                            customFieldRefArray[0] = cashier;
                            customFieldRefArray[1] = balance;
                            customFieldRefArray[2] = paid;
                            customFieldRefArray[3] = trans_time;
                            customFieldRefArray[4] = trans_no;
                            customFieldRefArray[5] = lineDiscount;
                            customFieldRefArray[6] = orderDiscount;

                            if (invoice_info.Terminal_Id > 0)
                            {
                                customFieldRefArray[7] = terminal;
                            }

                            invoiceObject.customFieldList = customFieldRefArray;
                            #endregion

                            InvoiceArr[i] = invoiceObject;
                            #endregion
                        }
                        catch (Exception ex)
                        {
                            invoiceLst.RemoveAt(i);
                            //  LogDAO.Integration_Exception(LogIntegrationType.Error, TaskRunType.POST, "InvoiceTask", "Error adding invoice: " + ex.Message + " Invoice id = " + invoiceLst[i].Id.ToString());
                        }
                    }
                    // Send invoice list to netsuite
                    WriteResponseList wr = Service(true).addList(InvoiceArr);
                    result = wr.status.isSuccess;

                    // LogDAO.Integration_Exception(LogIntegrationType.Info, TaskRunType.POST, "InvoiceTask", "Status: " + result);
                    if (result)
                    {
                        //Update database with returned Netsuite ids
                        UpdatedInvoice(invoiceLst, wr);
                    }
                }

                // post customerPayment to netsuite
                //  bool postPayments = PostCustomerPayment();
            }
            catch (Exception ex)
            {
                //  LogDAO.Integration_Exception(LogIntegrationType.Error, TaskRunType.POST, "InvoiceTask Error", "Error " + ex.Message);
            }

            // release the the object
            //new ScheduleTaskDAO().Processing(taskType, TaskRunType.POST, false);

            return(0);
        }
        public com.netsuite.webservices.InventoryItem[] GenerateNetSuitelst(List <Item> Lst_ItemsAll)
        {
            com.netsuite.webservices.InventoryItem[] ItemArr = new com.netsuite.webservices.InventoryItem[Lst_ItemsAll.Count];
            try
            {
                for (int i = 0; i < Lst_ItemsAll.Count; i++)
                {
                    RecordRef[] subsidiarylst = new RecordRef[1];
                    Item        Obj           = Lst_ItemsAll[i];
                    Setting     objSetting    = new GenericeDAO <Setting>().GetWhere("Subsidiary_Netsuite_Id=" + Obj.Subsidiary_Id).FirstOrDefault();
                    Categories.CategoriesAccounts          objCatAccount = new Categories.CategoriesAccounts();
                    com.netsuite.webservices.InventoryItem NewItemObject = new com.netsuite.webservices.InventoryItem();
                    //check if new or can be updated
                    if (Obj.Netsuite_Id > 0)
                    {
                        NewItemObject.internalId = Obj.Netsuite_Id.ToString();
                    }

                    NewItemObject.itemId           = Obj.UPC_Code;
                    NewItemObject.displayName      = Obj.Display_Name_En;
                    NewItemObject.salesDescription = Obj.Display_Name_En;

                    NewItemObject.trackLandedCost          = true;
                    NewItemObject.trackLandedCostSpecified = true;
                    if (Obj.Price > 0)
                    {
                        NewItemObject.pricingMatrix = Helper.GeneratePricingMatrix(objSetting, Obj.Price);
                    }
                    if (Obj.Category_Id > 0)
                    {
                        objCatAccount = new GenericeDAO <Categories.CategoriesAccounts>().GetWhere("Netsuite_Id=" + Obj.Category_Id).FirstOrDefault();
                        RecordRef classref = new RecordRef();
                        classref.internalId  = Obj.Category_Id.ToString();
                        classref.type        = RecordType.classification;
                        NewItemObject.@class = classref;
                    }
                    CustomFieldRef[] custFieldList = new CustomFieldRef[] {
                        new StringCustomFieldRef {
                            value    = Obj.Name_Ar != null? Obj.Name_Ar:"",
                            scriptId = "custitem_da_item_name_ar"
                        }
                        ,
                        new StringCustomFieldRef {
                            value    = Obj.UPC_Code.ToString(),
                            scriptId = "custitem1"
                        }
                        ,
                        new StringCustomFieldRef {
                            value    = Obj.storage_to_ingredient_factor != null? Obj.storage_to_ingredient_factor:"",
                            scriptId = "custitem_da_item_ingredient"
                        }
                    };
                    NewItemObject.customFieldList = custFieldList;
                    UnitsOfMeasure objunit = new UnitsOfMeasure();
                    if (!string.IsNullOrEmpty(Obj.Ingredient_Unit))
                    {
                        List <UnitsOfMeasure> unitlst = new GenericeDAO <UnitsOfMeasure>().GetWhere("Name ='" + Obj.Ingredient_Unit + "' and abbreviation ='" + Obj.Storage_Unit + "' and conversionRate ='" + Obj.storage_to_ingredient_factor + "'");
                        if (unitlst.Count > 0)
                        {
                            objunit = unitlst[0];
                        }
                        else
                        {
                            unitlst = new GenericeDAO <UnitsOfMeasure>().GetWhere("Name ='" + Obj.Ingredient_Unit + "' and abbreviation ='" + Obj.Storage_Unit + "'");
                            if (unitlst.Count > 0)
                            {
                                objunit = unitlst[0];
                            }
                        }
                    }
                    else if (!string.IsNullOrEmpty(Obj.Storage_Unit))
                    {
                        List <UnitsOfMeasure> unitlst = new GenericeDAO <UnitsOfMeasure>().GetWhere("unitName ='" + Obj.Storage_Unit + "' and abbreviation ='" + Obj.Storage_Unit + "' and conversionRate ='" + Obj.storage_to_ingredient_factor + "'");
                        if (unitlst.Count > 0)
                        {
                            objunit = unitlst[0];
                        }
                    }

                    if (objunit != null && objunit.Id > 0)
                    {
                        RecordRef unitsTyperef = new RecordRef();
                        unitsTyperef.internalId = objunit.unit_id.ToString();
                        unitsTyperef.type       = RecordType.unitsType;
                        NewItemObject.unitsType = unitsTyperef;

                        if (objunit.details_id > 0)
                        {
                            RecordRef unitsTyperefother = new RecordRef();
                            unitsTyperefother.internalId = objunit.details_id.ToString();
                            NewItemObject.saleUnit       = unitsTyperefother;
                            NewItemObject.stockUnit      = unitsTyperefother;
                            NewItemObject.purchaseUnit   = unitsTyperefother;
                        }
                    }


                    #region Items Account
                    RecordRef IncomAccountref = new RecordRef();
                    IncomAccountref.type = RecordType.account;
                    if (objCatAccount.income_account > 0)
                    {
                        IncomAccountref.internalId = objCatAccount.income_account.ToString();
                    }
                    else if (objSetting.IncomeAccount_Netsuite_Id > 0)
                    {
                        IncomAccountref.internalId = objSetting.IncomeAccount_Netsuite_Id.ToString();
                    }
                    if (!string.IsNullOrEmpty(IncomAccountref.internalId))
                    {
                        NewItemObject.incomeAccount = IncomAccountref;
                    }


                    RecordRef cogsAccountref = new RecordRef();
                    cogsAccountref.type = RecordType.account;
                    if (objCatAccount.cogs_account > 0)
                    {
                        cogsAccountref.internalId = objCatAccount.cogs_account.ToString();
                    }
                    else if (objSetting.CogsAccount_Netsuite_Id > 0)
                    {
                        cogsAccountref.internalId = objSetting.CogsAccount_Netsuite_Id.ToString();
                    }
                    if (!string.IsNullOrEmpty(cogsAccountref.internalId))
                    {
                        NewItemObject.cogsAccount = cogsAccountref;
                    }

                    RecordRef assetAccountref = new RecordRef();
                    assetAccountref.type = RecordType.account;
                    if (objCatAccount.asset_account > 0)
                    {
                        assetAccountref.internalId = objCatAccount.asset_account.ToString();
                    }
                    else if (objSetting.AssetAccount_Netsuite_Id > 0)
                    {
                        assetAccountref.internalId = objSetting.AssetAccount_Netsuite_Id.ToString();
                    }
                    if (!string.IsNullOrEmpty(assetAccountref.internalId))
                    {
                        NewItemObject.assetAccount = assetAccountref;
                    }


                    RecordRef intercoIncomeref = new RecordRef();
                    intercoIncomeref.type = RecordType.account;
                    if (objCatAccount.income_intercompany_account > 0)
                    {
                        intercoIncomeref.internalId = objCatAccount.income_intercompany_account.ToString();
                    }
                    else if (objSetting.IntercoIncomeAccount_Netsuite_Id > 0)
                    {
                        intercoIncomeref.internalId = objSetting.IntercoIncomeAccount_Netsuite_Id.ToString();
                    }

                    if (!string.IsNullOrEmpty(intercoIncomeref.internalId))
                    {
                        NewItemObject.intercoIncomeAccount = intercoIncomeref;
                    }

                    RecordRef intercoCogsAccount = new RecordRef();
                    intercoCogsAccount.type = RecordType.account;
                    if (objCatAccount.inter_cogs_account > 0)
                    {
                        intercoCogsAccount.internalId = objCatAccount.inter_cogs_account.ToString();
                    }
                    else if (objSetting.IntercoCogsAccount_Netsuite_Id > 0)
                    {
                        intercoCogsAccount.internalId = objSetting.IntercoCogsAccount_Netsuite_Id.ToString();
                    }

                    if (!string.IsNullOrEmpty(intercoCogsAccount.internalId))
                    {
                        NewItemObject.intercoCogsAccount = intercoCogsAccount;
                    }

                    RecordRef gainLossAccount = new RecordRef();
                    gainLossAccount.type = RecordType.account;
                    if (objCatAccount.gainloss_account > 0)
                    {
                        gainLossAccount.internalId = objCatAccount.gainloss_account.ToString();
                    }
                    else if (objSetting.GainLossAccount_Netsuite_Id > 0)
                    {
                        gainLossAccount.internalId = objSetting.GainLossAccount_Netsuite_Id.ToString();
                    }
                    if (!string.IsNullOrEmpty(gainLossAccount.internalId))
                    {
                        NewItemObject.gainLossAccount = gainLossAccount;
                    }

                    if (objCatAccount.cust_qty_variance_account > 0)
                    {
                        RecordRef refgAccount = new RecordRef();
                        refgAccount.type                  = RecordType.account;
                        refgAccount.internalId            = objCatAccount.cust_qty_variance_account.ToString();
                        NewItemObject.billQtyVarianceAcct = refgAccount;
                    }

                    if (objCatAccount.cust_ex_rate_account > 0)
                    {
                        RecordRef refgAccount = new RecordRef();
                        refgAccount.type       = RecordType.account;
                        refgAccount.internalId = objCatAccount.cust_ex_rate_account.ToString();
                        NewItemObject.billExchRateVarianceAcct = refgAccount;
                    }
                    if (objCatAccount.price_variance_account > 0)
                    {
                        RecordRef refgAccount = new RecordRef();
                        refgAccount.type       = RecordType.account;
                        refgAccount.internalId = objCatAccount.price_variance_account.ToString();
                        NewItemObject.billPriceVarianceAcct = refgAccount;
                    }

                    #endregion
                    RecordRef Tax_Schedule = new RecordRef();
                    Tax_Schedule.internalId   = objSetting.TaxSchedule_Netsuite_Id.ToString();
                    Tax_Schedule.type         = RecordType.salesTaxItem;
                    NewItemObject.taxSchedule = Tax_Schedule;

                    RecordRef subsidiary = new RecordRef();
                    subsidiary.internalId        = objSetting.Subsidiary_Netsuite_Id.ToString();
                    subsidiary.type              = RecordType.subsidiary;
                    subsidiarylst[0]             = subsidiary;
                    NewItemObject.subsidiaryList = subsidiarylst;


                    NewItemObject.isInactive          = Obj.InActive;
                    NewItemObject.isInactiveSpecified = true;

                    ItemArr[i] = NewItemObject;
                }
            }
            catch (Exception ex)
            {
                LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
            }
            return(ItemArr);
        }
        private InvoiceItem CreateInvoiceItem(Setting objSetting, Foodics.NetSuite.Shared.Model.InvoiceItem itemDetails)
        {
            RecordRef   taxCode, item, unit, price;
            InvoiceItem invoiceItemObject = new InvoiceItem();

            taxCode = new RecordRef();
            float taxRate = 1 + (objSetting.TaxRate / 100);

            if (objSetting.TaxAlwaysAppliedInItems)
            {
                taxCode.internalId     = objSetting.TaxCode_Netsuite_Id.ToString();
                invoiceItemObject.rate = Convert.ToString(itemDetails.Amount / taxRate);
            }
            else
            {
                //if (itemDetails.FoodicsTax > 0 && itemDetails.Item_Type != nameof(Item_Type.OtherChargeSaleItem))
                //if (itemDetails.FoodicsTax > 0 || itemDetails.Item_Type == nameof(Item_Type.OtherChargeSaleItem))
                //{
                taxCode.internalId = objSetting.TaxCode_Netsuite_Id.ToString();
                if (objSetting.ItemTaxInclusive)//= tax inclusive in item price
                {
                    invoiceItemObject.rate = Convert.ToString(itemDetails.Amount / taxRate);
                }
                else
                {
                    invoiceItemObject.rate = Convert.ToString(itemDetails.Amount);
                }
                //}
                //else
                //{
                //    taxCode.internalId = objSetting.TaxCode_Free_Netsuite_Id.ToString();
                //    invoiceItemObject.rate = Convert.ToString(itemDetails.Amount);
                //}
            }
            taxCode.type = RecordType.taxAcct;
            if (int.Parse(taxCode.internalId) > 0)
            {
                invoiceItemObject.taxCode = taxCode;
            }
            // item
            item                   = new RecordRef();
            item.internalId        = itemDetails.Item_Id.ToString();
            item.type              = (RecordType)Enum.Parse(typeof(RecordType), itemDetails.Item_Type, true);
            invoiceItemObject.item = item;
            if (Utility.ConvertToInt(itemDetails.Units) > 0)
            {
                unit                    = new RecordRef();
                unit.internalId         = itemDetails.Units.ToString();
                unit.type               = RecordType.unitsType;
                invoiceItemObject.units = unit;
            }
            // price level
            #region price level
            price                   = new RecordRef();
            price.type              = RecordType.priceLevel;
            price.internalId        = "-1";
            invoiceItemObject.price = price;
            #endregion
            invoiceItemObject.quantitySpecified = true;
            invoiceItemObject.quantity          = itemDetails.Quantity;
            if (!string.IsNullOrEmpty(itemDetails.Combo_Name))
            {
                StringCustomFieldRef ComboRef = new StringCustomFieldRef();
                ComboRef.scriptId = "custcol_da_foodics_combos";
                ComboRef.value    = itemDetails.Combo_Name.ToString() + " - " + itemDetails.ComboSize_Name.ToString();

                CustomFieldRef[] customFieldRefArray = new CustomFieldRef[1];
                customFieldRefArray[0]            = ComboRef;
                invoiceItemObject.customFieldList = customFieldRefArray;
            }
            return(invoiceItemObject);
        }
        public override Int64 Set(string parametersArr)
        {
            try
            {
                bool result = true;
                new CustomDAO().InvoiceRelatedUpdate();
                new CustomDAO().SetItemClass();
                #region Check Correct Invoices

                /*
                 * SELECT      *
                 * FROM            Invoice
                 * WHERE
                 * --(Location_Id = 201) and
                 * Order_Status=4
                 * and Net_Payable + Total_Discount != (select sum( Quantity  * amount) - sum(Line_Discount_Amount) from InvoiceItem where InvoiceItem.Invoice_Id =Invoice.Id and ISNULL(Item_Id,0)>0 and ProductStatus=3 )
                 *
                 * SELECT      *
                 * FROM            Invoice
                 * WHERE
                 *
                 * Order_Status=5
                 * and Net_Payable + Total_Discount != (select sum( Quantity  * amount) - sum(Line_Discount_Amount) from InvoiceItem where InvoiceItem.Invoice_Id =Invoice.Id and ISNULL(Item_Id,0)>0 and ProductStatus=6 )
                 * select * from InvoiceItem where isnull([Item_Id], 0)=0
                 *
                 * Declare @id nvarchar(50)
                 * set @id='007f91e2-a8ad-4dab-a20a-70c90e8db6ce'
                 *              select * from Invoice
                 *              where Foodics_Id =@id
                 *              select Net_Payable,Net_Payable-((Net_Payable*15)/100) from Invoice
                 *              where Foodics_Id =@id
                 *              select * from InvoiceItem
                 *              where Foodics_Id =@id
                 */
                #endregion
                List <Foodics.NetSuite.Shared.Model.Invoice> lstitemsAll = new CustomDAO().SelectInvoice(4);
                int Exe_length = 200;
                int lstend     = Exe_length;
                if (lstitemsAll.Count > 0)
                {
                    for (int Index = 0; Index < lstitemsAll.Count; Index += Exe_length)
                    {
                        if (Index + Exe_length >= lstitemsAll.Count)
                        {
                            lstend = lstitemsAll.Count - Index;
                        }
                        List <Foodics.NetSuite.Shared.Model.Invoice> invoiceLst = lstitemsAll.GetRange(Index, lstend);

                        if (invoiceLst.Count > 0)
                        {
                            #region variables
                            Invoice[] InvoiceArr = new Invoice[invoiceLst.Count];



                            Foodics.NetSuite.Shared.Model.Invoice     invoice_info;
                            Foodics.NetSuite.Shared.Model.InvoiceItem itemDetails;


                            DateTime        invoice_date;
                            Invoice         invoiceObject;
                            InvoiceItem     invoiceItemObject;
                            InvoiceItemList items;

                            RecordRef            subsid, currency, entity, location;
                            StringCustomFieldRef FoodicsRef, FoodicsNumb, CreatedBy, Source, orderDiscount;
                            CustomFieldRef[]     customFieldRefArray;
                            #endregion
                            for (int i = 0; i < invoiceLst.Count; i++)
                            {
                                try
                                {
                                    List <Foodics.NetSuite.Shared.Model.InvoiceItem> itemLst = new List <Foodics.NetSuite.Shared.Model.InvoiceItem>();
                                    List <InvoiceItem> invoiceItems = new List <InvoiceItem>();
                                    invoice_info = invoiceLst[i];
                                    Setting objSetting = new GenericeDAO <Setting>().GetWhere("Subsidiary_Netsuite_Id=" + invoice_info.Subsidiary_Id).FirstOrDefault();
                                    invoiceObject = new Invoice();
                                    #region invoice items
                                    itemLst = new GenericeDAO <Foodics.NetSuite.Shared.Model.InvoiceItem>().GetWhere(" ProductStatus =3 and Invoice_Id =" + invoice_info.Id + " and isnull(Item_Id,0) >0 ");
                                    try
                                    {
                                        for (int k = 0; k < itemLst.Count; k++)
                                        {
                                            itemDetails       = itemLst[k];
                                            invoiceItemObject = CreateInvoiceItem(objSetting, itemDetails);
                                            invoiceItems.Add(invoiceItemObject);
                                            if (itemDetails.Line_Discount_Amount > 0)
                                            {
                                                float Discount = itemDetails.Line_Discount_Amount;
                                                Foodics.NetSuite.Shared.Model.InvoiceItem OtherCharge = new Foodics.NetSuite.Shared.Model.InvoiceItem();
                                                OtherCharge.Item_Id   = objSetting.OtherChargeItem_Netsuite_Id;
                                                OtherCharge.Amount    = Discount * -1;
                                                OtherCharge.Quantity  = 1;
                                                OtherCharge.Item_Type = nameof(Item_Type.OtherChargeSaleItem);
                                                invoiceItemObject     = CreateInvoiceItem(objSetting, OtherCharge);
                                                invoiceItems.Add(invoiceItemObject);
                                            }
                                        }
                                        //if (invoice_info.Total_Discount > 0)
                                        //{
                                        //    float Discount = invoice_info.Total_Discount;
                                        //    Foodics.NetSuite.Shared.Model.InvoiceItem discountItem = new Foodics.NetSuite.Shared.Model.InvoiceItem();
                                        //    if (invoice_info.Discount_Id > 0)
                                        //        discountItem.Item_Id = invoice_info.Discount_Id;
                                        //    else
                                        //        discountItem.Item_Id = objSetting.DiscountItem_Netsuite_Id;

                                        //    discountItem.Amount = Discount * -1;
                                        //    //discountItem.Quantity = 1;
                                        //    discountItem.Item_Type = nameof(Item_Type.DiscountItem);
                                        //    invoiceItemObject = CreateInvoiceItem(objSetting, discountItem);
                                        //    invoiceItems.Add(invoiceItemObject);
                                        //}
                                    }
                                    catch (Exception ex)
                                    {
                                        LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
                                    }
                                    //Assign invoive items
                                    items                  = new InvoiceItemList();
                                    items.item             = invoiceItems.ToArray();
                                    invoiceObject.itemList = items;

                                    //GiftCertRedemption
                                    #endregion


                                    #region Standard Attributes
                                    invoice_date = TimeZoneInfo.ConvertTimeToUtc(invoice_info.Date, TimeZoneInfo.Local);

                                    //invoiceObject.externalId = invoice_info.BarCode;
                                    invoiceObject.tranDateSpecified = true;
                                    invoiceObject.dueDateSpecified  = true;
                                    invoiceObject.tranDate          = invoice_date;
                                    invoiceObject.dueDate           = invoice_date;
                                    invoiceObject.exchangeRate      = invoice_info.Exchange_Rate;


                                    //invoiceObject.memo = invoice_info.Notes;
                                    if (invoice_info.Subsidiary_Id > 0)
                                    {
                                        subsid                   = new RecordRef();
                                        subsid.internalId        = objSetting.Subsidiary_Netsuite_Id.ToString();
                                        subsid.type              = RecordType.subsidiary;
                                        invoiceObject.subsidiary = subsid;
                                    }
                                    currency               = new RecordRef();
                                    currency.internalId    = objSetting.Currency_Netsuite_Id.ToString();
                                    currency.type          = RecordType.currency;
                                    invoiceObject.currency = currency;
                                    entity               = new RecordRef();
                                    entity.internalId    = invoice_info.Customer_Netsuite_Id > 0 ? invoice_info.Customer_Netsuite_Id.ToString() : objSetting.Customer_Netsuite_Id.ToString();
                                    entity.type          = RecordType.customer;
                                    invoiceObject.entity = entity;

                                    location               = new RecordRef();
                                    location.internalId    = invoice_info.Location_Id.ToString(); //objSetting.Location_Netsuite_Id.ToString();
                                    location.type          = RecordType.location;
                                    invoiceObject.location = location;

                                    if (invoice_info.Sales_Rep_Id > 0)
                                    {
                                        RecordRef sales_rep = new RecordRef();
                                        sales_rep.internalId   = invoice_info.Sales_Rep_Id.ToString();
                                        sales_rep.type         = RecordType.employee;
                                        invoiceObject.salesRep = sales_rep;
                                    }
                                    #endregion

                                    #region Discount
                                    if (invoice_info.Total_Discount > 0)
                                    {
                                        RecordRef discountitem = new RecordRef();
                                        discountitem.type          = RecordType.discountItem;
                                        invoiceObject.discountItem = discountitem;
                                        float taxRate = 1 + (objSetting.TaxRate / 100);
                                        if (objSetting.TaxAlwaysAppliedInItems)
                                        {
                                            invoiceObject.discountRate = (Math.Round((invoice_info.Total_Discount / taxRate), 3) * -1).ToString();
                                        }
                                        else
                                        {
                                            //if (objSetting.ItemTaxInclusive)
                                            //    invoiceObject.discountRate = (Math.Round((invoice_info.Total_Discount / taxRate), 3) * -1).ToString();
                                            //else
                                            invoiceObject.discountRate = (Math.Round(invoice_info.Total_Discount, 3) * -1).ToString();
                                        }

                                        if (invoice_info.Discount_Id > 0)
                                        {
                                            discountitem.internalId = invoice_info.Discount_Id.ToString();
                                        }
                                        else
                                        {
                                            discountitem.internalId = objSetting.DiscountItem_Netsuite_Id.ToString();
                                        }
                                    }
                                    else
                                    {
                                        invoiceObject.discountRate = "0";
                                    }
                                    orderDiscount          = new StringCustomFieldRef();
                                    orderDiscount.scriptId = "custbody_da_invoice_discount";
                                    orderDiscount.value    = invoice_info.Total_Discount.ToString();

                                    //if (invoice_info.Accounting_Discount_Item != 0)
                                    //{
                                    //    RecordRef discItem = new RecordRef();
                                    //    discItem.internalId = invoice_info.Accounting_Discount_Item.ToString();
                                    //    discItem.type = RecordType.discountItem;
                                    //    invoiceObject.discountItem = discItem;
                                    //}
                                    #endregion

                                    //RecordRef Approval = new RecordRef();
                                    //Approval.internalId = "2";
                                    ////Approval.type = RecordType.;
                                    //invoiceObject.approvalStatus = Approval;

                                    #region Invoice Custom Attributes
                                    FoodicsRef          = new StringCustomFieldRef();
                                    FoodicsRef.scriptId = "custbody_da_foodics_reference";
                                    FoodicsRef.value    = invoice_info.BarCode.ToString();

                                    FoodicsNumb          = new StringCustomFieldRef();
                                    FoodicsNumb.scriptId = "custbody_da_foodics_number";
                                    FoodicsNumb.value    = invoice_info.Number.ToString();

                                    CreatedBy          = new StringCustomFieldRef();
                                    CreatedBy.scriptId = "custbody_da_foodics_createdby";
                                    CreatedBy.value    = invoice_info.CreatedBy != null?invoice_info.CreatedBy.ToString() : "";

                                    Source          = new StringCustomFieldRef();
                                    Source.scriptId = "custbody_da_foodics_source";
                                    Source.value    = invoice_info.Source.ToString();

                                    customFieldRefArray    = new CustomFieldRef[5];
                                    customFieldRefArray[0] = orderDiscount;
                                    customFieldRefArray[1] = FoodicsRef;
                                    customFieldRefArray[2] = FoodicsNumb;
                                    customFieldRefArray[3] = CreatedBy;
                                    customFieldRefArray[4] = Source;

                                    invoiceObject.customFieldList = customFieldRefArray;
                                    #endregion
                                    InvoiceArr[i] = invoiceObject;
                                }
                                catch (Exception ex)
                                {
                                    //invoiceLst.RemoveAt(i);
                                    LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
                                }
                            }
                            // Send invoice list to netsuite
                            WriteResponseList wr = Service(true).addList(InvoiceArr);
                            result = wr.status.isSuccess;
                            if (result)
                            {
                                //Update database with returned Netsuite ids
                                UpdatedInvoice(invoiceLst, wr);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
            }



            return(0);
        }
        private static object GetValue(string strId, CustomFieldRef[] arrFields)
        {
            object objValue = null;

            foreach (CustomFieldRef objField in arrFields)
            {
                if (objField is BooleanCustomFieldRef)
                {
                    BooleanCustomFieldRef objCustomFieldRef = (BooleanCustomFieldRef)objField;
                    if (objCustomFieldRef.internalId.Equals(strId))
                    {
                        objValue = objCustomFieldRef.value;
                        break;
                    }
                }
                else if (objField is StringCustomFieldRef)
                {
                    StringCustomFieldRef objCustomFieldRef = (StringCustomFieldRef)objField;
                    if (objCustomFieldRef.internalId.Equals(strId))
                    {
                        objValue = objCustomFieldRef.value;
                        break;
                    }
                }
                else if (objField is SelectCustomFieldRef)
                {
                    SelectCustomFieldRef objCustomFieldRef = (SelectCustomFieldRef)objField;
                    if (objCustomFieldRef.internalId.Equals(strId))
                    {
                        if (objCustomFieldRef.value.name != null)
                        {
                            objValue = objCustomFieldRef.value.name;
                        }
                        else
                        {
                            objValue = objCustomFieldRef.value.internalId;
                        }
                        break;
                    }
                }
                else if (objField is MultiSelectCustomFieldRef)
                {
                    MultiSelectCustomFieldRef objCustomFieldRef = (MultiSelectCustomFieldRef)objField;
                    if (objCustomFieldRef.internalId.Equals(strId))
                    {
                        objValue = objCustomFieldRef.value[0].internalId;
                        break;
                    }
                }
                else if (objField is DateCustomFieldRef)
                {
                    DateCustomFieldRef objCustomFieldRef = (DateCustomFieldRef)objField;
                    if (objCustomFieldRef.internalId.Equals(strId))
                    {
                        objValue = objCustomFieldRef.value;
                        break;
                    }
                }
                else if (objField is DoubleCustomFieldRef)
                {
                    DoubleCustomFieldRef objCustomFieldRef = (DoubleCustomFieldRef)objField;
                    if (objCustomFieldRef.internalId.Equals(strId))
                    {
                        objValue = objCustomFieldRef.value;
                        break;
                    }
                }
                else if (objField is LongCustomFieldRef)
                {
                    LongCustomFieldRef objCustomFieldRef = (LongCustomFieldRef)objField;
                    if (objCustomFieldRef.internalId.Equals(strId))
                    {
                        objValue = objCustomFieldRef.value;
                        break;
                    }
                }
            }
            return objValue;
        }
        //protected List<Model.ItemSubsidiary> subsidiaryListLocal = new List<Model.ItemSubsidiary>();
        //protected List<Model.Item> itemWithImages = new List<Model.Item>();
        //protected List<Model.ItemOptionListValue> ItemOptionList = new List<Model.ItemOptionListValue>();
        public override Int64 Set(string parametersArr)
        {
            List <Item> Lst_Items  = new GenericeDAO <Item>().GetWhere(" (Netsuite_Id IS NULL or Netsuite_Id =0) and Item_Type=" + (int)Item_Type.GiftCertificate);
            Setting     objSetting = new GenericeDAO <Setting>().GetAll().FirstOrDefault();

            if (objSetting == null)
            {
                return(0);
            }
            if (Lst_Items.Count <= 0)
            {
                return(0);
            }



            RecordRef[] subsidiarylst = new RecordRef[1];
            Price[]     pricelst      = new Price[1];
            Pricing[]   Pricinglst    = new Pricing[1];
            // AssemblyComponentList assemplyList = new AssemblyComponentList();
            ItemMemberList memberlst = new ItemMemberList();

            ItemMember[] ItemMemberlst = new ItemMember[1];
            com.netsuite.webservices.GiftCertificateItem[] ItemArr = new com.netsuite.webservices.GiftCertificateItem[Lst_Items.Count];
            for (int i = 0; i < Lst_Items.Count; i++)
            //for (int i = 0; i < 1; i++)
            {
                Item Obj = Lst_Items[i];

                com.netsuite.webservices.GiftCertificateItem NewItemObject = new com.netsuite.webservices.GiftCertificateItem();
                NewItemObject.displayName = Obj.Display_Name_En;
                NewItemObject.itemId      = Obj.UPC_Code;

                #region Custom fields

                if (!string.IsNullOrEmpty(Obj.Storage_Unit))
                {
                    CustomFieldRef[] custFieldList = new CustomFieldRef[] {
                        new StringCustomFieldRef {
                            value    = Obj.Storage_Unit.ToString(),
                            scriptId = "custitem_da_it_uom"
                        },
                    };
                    NewItemObject.customFieldList = custFieldList;
                }

                #endregion


                //obj.


                #region AssemblyComponent
                // AssemblyComponent obj = new AssemblyComponent();
                //obj.



                //ItemMember obj = new ItemMember();

                //RecordRef Itemref = new RecordRef();
                //Itemref.internalId = "612";//objSetting.Subsidiary_Netsuite_Id.ToString();
                //Itemref.type = RecordType.inventoryItem;

                //obj.item = Itemref;
                //obj.quantity = 1;



                //ItemMemberlst[0] = obj;


                //memberlst.itemMember = ItemMemberlst;
                //NewItemObject.memberList = memberlst;

                //NewItemObject.item
                ////NewItemObject.component
                #endregion
                RecordRef Tax_Schedule = new RecordRef();
                Tax_Schedule.internalId   = objSetting.TaxSchedule_Netsuite_Id.ToString();
                Tax_Schedule.type         = RecordType.salesTaxItem;
                NewItemObject.taxSchedule = Tax_Schedule;

                RecordRef subsidiary = new RecordRef();
                subsidiary.internalId        = objSetting.Subsidiary_Netsuite_Id.ToString();
                subsidiary.type              = RecordType.subsidiary;
                subsidiarylst[0]             = subsidiary;
                NewItemObject.subsidiaryList = subsidiarylst;


                RecordRef Liability = new RecordRef();
                Liability.internalId           = objSetting.LiabilityAccount_Netsuite_Id.ToString();
                Liability.type                 = RecordType.subsidiary;
                NewItemObject.liabilityAccount = Liability;


                if (Obj.InActive)
                {
                    NewItemObject.isInactive          = true;
                    NewItemObject.isInactiveSpecified = true;
                }

                ItemArr[i] = NewItemObject;
            }
            // Send order list to netsuite
            WriteResponseList wr = Service(true).addList(ItemArr);
            bool result          = wr.status.isSuccess;
            if (result)
            {
                //Update database with returned Netsuite ids
                UpdatedLst(Lst_Items, wr);
            }
            return(0);
        }
        public com.netsuite.webservices.ServiceSaleItem[] GenerateNetSuitelst(List <Item> Lst_ItemsAll)
        {
            com.netsuite.webservices.ServiceSaleItem[] ItemArr = new com.netsuite.webservices.ServiceSaleItem[Lst_ItemsAll.Count];
            try
            {
                for (int i = 0; i < Lst_ItemsAll.Count; i++)
                {
                    RecordRef[] subsidiarylst = new RecordRef[1];
                    Item        Obj           = Lst_ItemsAll[i];
                    Setting     objSetting    = new GenericeDAO <Setting>().GetWhere("Subsidiary_Netsuite_Id=" + Obj.Subsidiary_Id).FirstOrDefault();
                    Categories.CategoriesAccounts            objCatAccount = new Categories.CategoriesAccounts();
                    com.netsuite.webservices.ServiceSaleItem NewItemObject = new com.netsuite.webservices.ServiceSaleItem();
                    if (Obj.Netsuite_Id <= 0)
                    {
                        NewItemObject.displayName = Obj.Display_Name_En;
                        //NewItemObject.itemId = Obj.UPC_Code;
                        NewItemObject.itemId           = Obj.Display_Name_En;
                        NewItemObject.salesDescription = Obj.Display_Name_En;
                    }
                    //check if new or can be updated
                    if (Obj.Netsuite_Id > 0)
                    {
                        NewItemObject.internalId = Obj.Netsuite_Id.ToString();
                    }

                    NewItemObject.pricingMatrix = Helper.GeneratePricingMatrix(objSetting, Obj.Price);


                    CustomFieldRef[] custFieldList = new CustomFieldRef[] {
                        new StringCustomFieldRef {
                            value    = Obj.Name_Ar != null? Obj.Name_Ar:"",
                            scriptId = "custitem_da_item_name_ar"
                        }
                    };
                    NewItemObject.customFieldList = custFieldList;


                    #region Items Account
                    RecordRef IncomAccountref = new RecordRef();
                    IncomAccountref.type        = RecordType.account;
                    NewItemObject.incomeAccount = IncomAccountref;

                    IncomAccountref.internalId = objSetting.IncomeAccount_Netsuite_Id.ToString();



                    #endregion
                    RecordRef Tax_Schedule = new RecordRef();
                    Tax_Schedule.internalId   = objSetting.TaxSchedule_Netsuite_Id.ToString();
                    Tax_Schedule.type         = RecordType.salesTaxItem;
                    NewItemObject.taxSchedule = Tax_Schedule;

                    RecordRef subsidiary = new RecordRef();
                    subsidiary.internalId        = objSetting.Subsidiary_Netsuite_Id.ToString();
                    subsidiary.type              = RecordType.subsidiary;
                    subsidiarylst[0]             = subsidiary;
                    NewItemObject.subsidiaryList = subsidiarylst;


                    NewItemObject.isInactive          = Obj.InActive;
                    NewItemObject.isInactiveSpecified = true;

                    ItemArr[i] = NewItemObject;
                }
            }
            catch (Exception ex)
            {
                LogDAO.Integration_Exception(LogIntegrationType.Error, this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name, "Error " + ex.Message);
            }
            return(ItemArr);
        }
        /*
            Creates the new Lead/Customer record in NetSuite.  Must be called first because we'll need the resulting Customer ID
            to place in the new Contact record, and both ids to run the 'attach' operation.  These are NetSuite's rules, sadly.
        */
        public void createCustomer()
        {
            Customer customer = new Customer();

            // Populate information provided by the user
            customer.companyName = _companyName;
            customer.email = _email;
            customer.phone = _phone;

            // Set as Lead - New
            RecordRef status = new RecordRef();
            status.internalId = "6"; // LEAD - New
            customer.entityStatus = status;

            /*
                Custom Fields require creating a reference record based on the type of field, and then we
                add each reference object to an array that gets passed into the XML renderer that NetSuite
                provides for us.

                Industry, IP address and Source are custom fields we've created.  Industry is a drop down list, which
                means our reference object must contain a reference to which drop down entry the new lead selected.
                This seems a bit overboard but lists can be multi-selects as well.  IP Address and source are just simple
                text fields, so nothing fancy is required, they're just a simple name/value pair.
            */

            System.Collections.ArrayList customFields = new System.Collections.ArrayList();

            if (_industry != "") {
                SelectCustomFieldRef custIndustry = new SelectCustomFieldRef();
                custIndustry.internalId = "custentity_customerindustry";
                ListOrRecordRef custIndustryList = new ListOrRecordRef();
                custIndustryList.internalId = _industry;
                custIndustry.value = custIndustryList;
                customFields.Add(custIndustry);
            }

            if (_ip != "") {
                StringCustomFieldRef ip = new StringCustomFieldRef();
                ip.internalId = "custentity_fnaipaddress";
                ip.value = _ip;
                customFields.Add(ip);
            }

            if (_source != "") {
                StringCustomFieldRef source = new StringCustomFieldRef();
                source.internalId = "custentity_custfnasource";
                source.value = _source;
                customFields.Add(source);
            }

            CustomFieldRef[] customFieldRefs = new CustomFieldRef[customFields.Count];
            IEnumerator ienum = customFields.GetEnumerator();
            for (int i = 0; ienum.MoveNext(); i++) {
                customFieldRefs[i] = (CustomFieldRef)ienum.Current;
            }
            customer.customFieldList = customFieldRefs;

            /*
                Now with our customer record created, we're going to add it to our XML renderer and pass it on NetSuite.
                NetSuite will be returning a response in XML so we're going to grab that so we can get the id of the newly
                created record in NetSuite.
            */
            WriteResponse response = _service.add(customer);
            _customerStatus = response.status;
            if (this.getCustomerStatus() == "") {
                _customerID = ((RecordRef)response.baseRef).internalId;
                _entityName = ((RecordRef)response.baseRef).name;
            }
        }
 // ============ Custom Field general purpose access functions for all types ==========
 private string getStringCustomField(CustomFieldRef[] theCFList, string theCFinternalID)
 {
     string theCFValue = "";
     if (theCFList != null)
     {
         for (int cf = 0; cf < theCFList.Length; cf++)
         {
             CustomFieldRef theCF = theCFList[cf];
             if (theCF.ToString().EndsWith("StringCustomFieldRef"))
             {
                 StringCustomFieldRef theStrCF = (StringCustomFieldRef)theCF;
                 if (theStrCF.internalId == theCFinternalID) theCFValue = theStrCF.value;
             }
         }
     }
     return theCFValue;
 }