Beispiel #1
0
        public static void Detail2Cart(String so, String cart_id, String erp_id, String user_id, String currency, String org_id)
        {
            SqlProvider.dbExecuteNoQuery("MY", String.Format("delete from ORDER_MASTER where ORDER_ID = '{0}'", so));
            SqlProvider.dbExecuteNoQuery("MY", String.Format("delete from ORDER_DETAIL where ORDER_ID = '{0}'", so));
            SqlProvider.dbExecuteNoQuery("MY", String.Format("delete from ORDER_PARTNERS where ORDER_ID = '{0}'", so));
            SqlProvider.dbExecuteNoQuery("MY", String.Format("delete from order_Master_ExtensionV2 where ORDER_ID = '{0}'", so));

            // SO_Header to CartMaster
            CARTMASTERV2 CartMaster = new CARTMASTERV2();

            CartMaster.CartID          = cart_id;
            CartMaster.ErpID           = erp_id;
            CartMaster.CreatedDate     = DateTime.Now;
            CartMaster.Currency        = currency;
            CartMaster.CreatedBy       = user_id;
            CartMaster.LastUpdatedDate = DateTime.Now;
            CartMaster.LastUpdatedBy   = user_id;
            MyAdvantechContext.Current.CARTMASTERV2.Add(CartMaster);

            // SO_Detail to CartDetail
            List <SO_DETAIL> sd = new CPDBDAL().GetSoDetail(so); // get a list from SO_Detail table

            // Simulate Product List to get the correct list price
            Order _order = new Order();

            GetPriceForCheckPoint(ref _order, so, currency, org_id);

            if (_order != null)
            {
                List <Product> pr = _order.LineItems;
                foreach (SO_DETAIL d in sd)
                {
                    cart_DETAIL_V2 CartDetail = new cart_DETAIL_V2();

                    CartDetail.Cart_Id      = cart_id;
                    CartDetail.Line_No      = int.Parse(d.LINE_NO);
                    CartDetail.Part_No      = Advantech.Myadvantech.DataAccess.SAPDAL.RemovePrecedingZeros(d.MATERIAL);
                    CartDetail.Qty          = int.Parse(d.QTY);
                    CartDetail.CustMaterial = d.CUST_MATERIAL;
                    CartDetail.Ew_Flag      = 0;
                    CartDetail.SatisfyFlag  = 0;
                    CartDetail.QUOTE_ID     = "";

                    // higherlevel value validate, if is null then set it as 0 to avoid further error
                    if (d.HIGHER_LEVEL == null)
                    {
                        CartDetail.higherLevel = 0;
                    }
                    else
                    {
                        CartDetail.higherLevel = int.Parse(d.HIGHER_LEVEL);
                    }

                    // item type validate, set it's type, req_date, due_date
                    CartDetail.otype    = 0;
                    CartDetail.req_date = DateTime.Now.AddDays(2);
                    if (CartDetail.Line_No < 100)
                    {
                        CartDetail.otype = (int)QuoteItemType.Part;
                    }
                    else if (CartDetail.Line_No % 100 == 0 && CartDetail.higherLevel == 0)
                    {
                        CartDetail.otype    = (int)QuoteItemType.BtosParent;
                        CartDetail.req_date = getCompNextWorkDate(CartDetail.req_date.Value, org_id, getBTOWorkingDate(org_id));
                    }
                    else if (CartDetail.Line_No % 100 > 0 && CartDetail.Line_No > 100)
                    {
                        CartDetail.otype    = (int)QuoteItemType.BtosPart;
                        CartDetail.req_date = getCompNextWorkDate(CartDetail.req_date.Value, org_id, getBTOWorkingDate(org_id));
                    }
                    CartDetail.due_date = CartDetail.req_date;

                    //Ryan 20160421 Revise Delivery Plant Logic, *Must behind partno & otype processing.
                    CartDetail.Delivery_Plant = PartBusinessLogic.GetDeliveryPlant(erp_id, org_id, CartDetail.Part_No, (QuoteItemType)Enum.Parse(typeof(QuoteItemType), CartDetail.otype.ToString()));

                    // set price according to it's item type
                    if (CartDetail.otype == (int)QuoteItemType.BtosParent)
                    {
                        CartDetail.List_Price = 0;
                        CartDetail.Unit_Price = 0;
                        CartDetail.Itp        = 0;
                    }
                    else
                    {
                        // Get the list price only if CartDetail's Part_NO is equal to _Order's Part_NO
                        Decimal list_price = 0, unit_price = 0;
                        if ((from p in pr where p.PartNumber == CartDetail.Part_No select p.ListPrice).Any())
                        {
                            list_price = (from p in pr where p.PartNumber == CartDetail.Part_No select p.ListPrice).FirstOrDefault();
                        }
                        if ((from p in pr where p.PartNumber == CartDetail.Part_No select p.UnitPrice).Any())
                        {
                            unit_price = (from p in pr where p.PartNumber == CartDetail.Part_No select p.UnitPrice).FirstOrDefault();
                        }

                        CartDetail.List_Price = list_price;
                        CartDetail.Unit_Price = unit_price;
                        CartDetail.Itp        = 0;
                    }
                    MyAdvantechContext.Current.cart_DETAIL_V2.Add(CartDetail);
                }
                MyAdvantechContext.Current.SaveChanges();
            }
        }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="SystemPartNo"></param>
        /// <returns></returns>
        public static void ExpandSchneiderSystemPartToCart(String SystemPartNo, String cart_id, String user_id, String erp_id, String org_id)
        {
            String _plant = "TWH1"; string _Currency = "USD";

            //1. Expanding BOM
            DataTable dt = Advantech.Myadvantech.DataAccess.SAPDAL.ExpandSystemPartToBOM(SystemPartNo, 1);

            //1.5 Get deliveryplant from SAP_Product_Org. Ryan 20160316
            dt.Columns.Add("DELIVERYPLANT", typeof(String));
            List <String> list_partno = new List <String>();

            foreach (DataRow d in dt.Rows)
            {
                list_partno.Add("'" + d["Idnrk"].ToString() + "'");
            }
            String    sql_in   = string.Join(",", list_partno);
            String    sql_str  = "select PART_NO,ORG_ID,DELIVERYPLANT from SAP_PRODUCT_ORG where ORG_ID = 'TW01' AND PART_NO IN (" + sql_in + ")";
            DataTable dt_plant = SqlProvider.dbGetDataTable("MY", sql_str);

            foreach (DataRow d in dt.Rows)
            {
                DataRow[] rows = dt_plant.Select("PART_NO='" + d["Idnrk"].ToString() + "'");
                if (rows.Count() > 0)
                {
                    d["DELIVERYPLANT"] = dt_plant.Select("PART_NO='" + d["Idnrk"].ToString() + "'")[0][2];
                }
                else
                {
                    d["DELIVERYPLANT"] = _plant;
                }
            }


            //2. Get system part's unit price by order simulation
            Order _order = new Order();

            _order.Currency    = _Currency;
            _order.OrgID       = org_id;
            _order.DistChannel = "10";
            _order.Division    = "00";

            int i = 0;

            foreach (DataRow d in dt.Rows)
            {
                _order.AddLooseItem(Advantech.Myadvantech.DataAccess.SAPDAL.RemovePrecedingZeros(d["Idnrk"].ToString()), 1);
                _order.LineItems[i].PlantID = d["DELIVERYPLANT"].ToString();
                i++;
            }
            _order.SetOrderPartnet(new OrderPartner(erp_id, org_id, OrderPartnerType.SoldTo));
            _order.SetOrderPartnet(new OrderPartner(erp_id, org_id, OrderPartnerType.ShipTo));
            _order.SetOrderPartnet(new OrderPartner(erp_id, org_id, OrderPartnerType.BillTo));

            String _errMsg = String.Empty;

            Advantech.Myadvantech.DataAccess.SAPDAL.SimulateOrder(ref _order, ref _errMsg);
            List <Product> pr = _order.LineItems;

            //3.
            //_UnitPrice = 1000;
            //var totalcost = dt.AsEnumerable().Sum(x => x.Field<decimal>("Stprs"));

            //CARTMASTERV2 CartMaster = new CARTMASTERV2();
            //CartMaster.CartID = cart_id;
            //CartMaster.ErpID = erp_id;
            //CartMaster.CreatedDate = DateTime.Now;
            //CartMaster.Currency = _Currency;
            //CartMaster.CreatedBy = user_id;
            //CartMaster.LastUpdatedDate = DateTime.Now;
            //CartMaster.LastUpdatedBy = user_id;
            //MyAdvantechContext.Current.CARTMASTERV2.Add(CartMaster);

            // Get Bto_Parent Line_No
            List <cart_DETAIL_V2> cd = new MyAdvantechDAL().GetCartDetailV2ByCartID(cart_id);
            int Bto_LineNo           = 0;

            do
            {
                Bto_LineNo += 100;
            } while ((from d in cd where d.Cart_Id == cart_id && d.Line_No == Bto_LineNo select d).Any());

            // Set Bto_Parent
            cart_DETAIL_V2 CartDetail = new cart_DETAIL_V2();

            CartDetail.Cart_Id        = cart_id;
            CartDetail.Line_No        = Bto_LineNo;
            CartDetail.Part_No        = "PTRADE-BTO";
            CartDetail.Description    = SystemPartNo;
            CartDetail.Qty            = 1;
            CartDetail.CustMaterial   = "";
            CartDetail.Ew_Flag        = 0;
            CartDetail.SatisfyFlag    = 0;
            CartDetail.QUOTE_ID       = "";
            CartDetail.Delivery_Plant = _plant;
            CartDetail.higherLevel    = 0;
            CartDetail.otype          = (int)QuoteItemType.BtosParent;
            CartDetail.List_Price     = 0;
            CartDetail.Unit_Price     = 0;
            CartDetail.Itp            = 0;
            CartDetail.Description    = SystemPartNo;

            CartDetail.req_date = DateTime.Now.AddDays(1);
            String   LandStr = SAPDAL.SAPDAL.GetCalendarIDbyOrg(org_id.Substring(0, 1));
            DateTime reqdate = CartDetail.req_date.Value;

            SAPDAL.SAPDAL.Get_Next_WorkingDate_ByCode(ref reqdate, WebConfigurationManager.AppSettings["TWBTOSWorkingDay"].ToString(), LandStr);
            CartDetail.req_date = reqdate;
            CartDetail.due_date = reqdate;

            MyAdvantechContext.Current.cart_DETAIL_V2.Add(CartDetail);

            // Set Bto_Part
            Bto_LineNo++;
            foreach (DataRow d in dt.Rows)
            {
                CartDetail = new cart_DETAIL_V2();

                CartDetail.Cart_Id        = cart_id;
                CartDetail.Line_No        = Bto_LineNo;
                CartDetail.Part_No        = Advantech.Myadvantech.DataAccess.SAPDAL.RemovePrecedingZeros(d["Idnrk"].ToString());
                CartDetail.Description    = d["Ojtxp"].ToString();
                CartDetail.Qty            = Convert.ToInt32(d["Menge"]);
                CartDetail.CustMaterial   = "";
                CartDetail.Ew_Flag        = 0;
                CartDetail.SatisfyFlag    = 0;
                CartDetail.QUOTE_ID       = "";
                CartDetail.Delivery_Plant = d["DELIVERYPLANT"].ToString();
                CartDetail.higherLevel    = 100;
                CartDetail.otype          = (int)QuoteItemType.Part;

                // Get req_date
                CartDetail.req_date = DateTime.Now.AddDays(1);
                LandStr             = SAPDAL.SAPDAL.GetCalendarIDbyOrg(org_id.Substring(0, 1));
                reqdate             = CartDetail.req_date.Value;
                SAPDAL.SAPDAL.Get_Next_WorkingDate_ByCode(ref reqdate, "0", LandStr);
                CartDetail.req_date = reqdate;
                CartDetail.due_date = reqdate;

                // Set list price
                Decimal list_price = 0, unit_price = 0;
                if ((from p in pr where p.PartNumber == CartDetail.Part_No select p.ListPrice).Any())
                {
                    list_price = (from p in pr where p.PartNumber == CartDetail.Part_No select p.ListPrice).FirstOrDefault();
                }
                if ((from p in pr where p.PartNumber == CartDetail.Part_No select p.UnitPrice).Any())
                {
                    unit_price = (from p in pr where p.PartNumber == CartDetail.Part_No select p.UnitPrice).FirstOrDefault();
                }
                CartDetail.List_Price = list_price;
                CartDetail.Unit_Price = unit_price;
                CartDetail.Itp        = 0;
                Bto_LineNo++;
                MyAdvantechContext.Current.cart_DETAIL_V2.Add(CartDetail);
            }
            MyAdvantechContext.Current.SaveChanges();

            //With BOMTable.Columns
            //    .Remove("Mandt")
            //    '.Remove("Alprf") : .Remove("Alpgr") : .Remove("Ewahr")
            //    .Item("Alprf").ColumnName = "Alt. Item Rank Order" : .Item("Alpgr").ColumnName = "Alt. Item Grp." : .Item("Ewahr").ColumnName = "Usage Prob (%)"
            //    .Item("Matnr").ColumnName = "Parent Item" : .Item("Bstmi").ColumnName = "MoQ" : .Item("Ojtxb").ColumnName = "Parent Desc."
            //    .Item("Idnrk").ColumnName = "Child Item" : .Item("Ojtxp").ColumnName = "Child Desc." : .Item("Stprs").ColumnName = "Cost"
            //    .Item("Stprs_Usd").ColumnName = "USD Cost" : .Item("Werks").ColumnName = "Plant" : .Item("Waers").ColumnName = "Currency"
            //    .Item("Stufe").ColumnName = "Level" : .Item("Menge").ColumnName = "Component Qty." : .Item("Peinh").ColumnName = "Price Unit"
            //    .Item("Peinh_Usd").ColumnName = "USD Price Unit" : .Add("MPN") : .Add("Manufacture Name")
            //End With
        }
        public static UpdateDBResult Configurator2Cart(String SelectedItems, String ERPID, String CartID, String Currency, String Org_ID, bool isPrj = false)
        {
            UpdateDBResult         updateresult = new UpdateDBResult();
            List <ConfiguredItems> items        = new List <ConfiguredItems>();

            try
            {
                // Remove all items in current cart for ACN
                if (Org_ID.StartsWith("CN"))
                {
                    CartDetailHelper.RemoveCartDetailByID(CartID);
                }

                List <ConfiguredItems> toAdditems = Newtonsoft.Json.JsonConvert.DeserializeObject <List <ConfiguredItems> >(SelectedItems);

                if (toAdditems == null || toAdditems.Count == 0)
                {
                    updateresult.IsUpdated     = false;
                    updateresult.ServerMessage = "No item was selected.";
                    return(updateresult);
                }

                // Split pipeline items
                foreach (ConfiguredItems c in toAdditems)
                {
                    if (c.name.Contains("|"))
                    {
                        //List<String> pipelineitems = c.name.Split('|').ToList();
                        //while (pipelineitems.Count > 0)
                        //{
                        //    ConfiguredItems newitem = new ConfiguredItems();
                        //    newitem.name = pipelineitems.First();
                        //    newitem.desc = c.desc;
                        //    newitem.qty = c.qty;
                        //    pipelineitems.RemoveAt(0);
                        //    toAdditems.Add(newitem);
                        //}
                        foreach (var i in c.name.Split('|').ToList())
                        {
                            SAP_PRODUCT sp = MyAdvantechDAL.GetSAPProduct(i);

                            ConfiguredItems newitem = new ConfiguredItems();
                            newitem.name        = i;
                            newitem.desc        = (sp != null && !String.IsNullOrEmpty(sp.PRODUCT_DESC)) ? sp.PRODUCT_DESC : c.desc;
                            newitem.qty         = c.qty;
                            newitem.isLooseItem = c.isLooseItem;
                            items.Add(newitem);
                        }
                    }
                    else
                    {
                        items.Add(c);
                    }
                }
                //if (toAdditems.Count > 0)
                //{
                //    items.RemoveAll(d => d.name.Contains("|"));
                //    items.AddRange(toAdditems);
                //}

                //ICC 2017/4/7 Add product compatibility check. To make sure all items are not incompatible.
                List <PRODUCT_COMPATIBILITY> pcList = MyAdvantechDAL.GetProductCompatibility(Compatibility.Incompatible);
                foreach (ConfiguredItems c in items)
                {
                    List <ConfiguredItems> copy = new List <ConfiguredItems>(items);
                    copy.Remove(c);
                    Tuple <bool, string> result = CheckCompatibility(c.name, copy.Select(p => p.name).ToList(), pcList);
                    if (result.Item1 == true)
                    {
                        updateresult.IsUpdated     = false;
                        updateresult.ServerMessage = string.Format("This part - {0} is {1} with {2}.", c.name, Compatibility.Incompatible.ToString().ToLower(), result.Item2);
                        return(updateresult);
                    }
                }

                //111
                //var _result = "'" + String.Join("','", items) + "'";
            }
            catch (Exception ex)
            {
                updateresult.IsUpdated     = false;
                updateresult.ServerMessage = ex.ToString();
                return(updateresult);
            }

            int NextHigherLevel    = 100;
            var objNextHigherLevel = SqlProvider.dbExecuteScalar("MY", "select max(line_no) from cart_DETAIL_V2 where cart_id = '" + CartID + "' and (otype = 0 or otype = 1)");

            if (objNextHigherLevel != null && !String.IsNullOrEmpty(objNextHigherLevel.ToString()))
            {
                NextHigherLevel = (Convert.ToInt32(objNextHigherLevel.ToString()) / 100 + 1) * 100;
            }
            int NextLooseItemLineNo    = 1;
            var objNextLooseItemLineNo = SqlProvider.dbExecuteScalar("MY", "select max(line_no) from cart_DETAIL_V2 where cart_id = '" + CartID + "' and otype = 0 ");

            if (objNextLooseItemLineNo != null && !String.IsNullOrEmpty(objNextLooseItemLineNo.ToString()))
            {
                NextLooseItemLineNo = Convert.ToInt32(objNextLooseItemLineNo.ToString()) + 1;
            }

            if (items.Count > 0)
            {
                try
                {
                    // For ACN, need to split BOTS root name with "/", ex: IPC-510-BTO/P4
                    items.Where(c => c.name.Contains("-BTO/")).ToList().ForEach(c => c.name = c.name.Split(new string[] { "/" }, StringSplitOptions.None)[0]);

                    // Simulate Product List to get price
                    Order _order = new Order();
                    _order.Currency    = Currency;
                    _order.OrgID       = Org_ID;
                    _order.DistChannel = "10";
                    _order.Division    = "00";
                    if (Org_ID.StartsWith("CN"))
                    {
                        if (System.Configuration.ConfigurationManager.AppSettings["ACNTaxRate"] != null)
                        {
                            _order.Tax = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["ACNTaxRate"]);
                        }
                        else
                        {
                            _order.Tax = (Decimal)0.16;
                        }
                    }

                    foreach (ConfiguredItems c in items)
                    {
                        //Frank 20171222, if part's material is BTO then identify it as BTOS parent item
                        SAP_PRODUCT sap_p = MyAdvantechDAL.GetSAPProduct(c.name);

                        if (Org_ID.Equals("EU80") && c.isLooseItem)
                        {
                            _order.AddLooseItem(c.name, SAPDAL.GetPlantByOrg(Org_ID), NextLooseItemLineNo, c.qty);
                            NextLooseItemLineNo++;
                        }
                        else if (sap_p != null && (sap_p.MATERIAL_GROUP.Equals("BTOS", StringComparison.InvariantCultureIgnoreCase) || c.name.EndsWith("-BTO", StringComparison.OrdinalIgnoreCase)))
                        {
                            _order.AddBTOSParentItem(c.name, SAPDAL.GetPlantByOrg(Org_ID), NextHigherLevel, c.qty);
                        }
                        else
                        {
                            _order.AddBTOSChildItem(c.name, NextHigherLevel, SAPDAL.GetPlantByOrg(Org_ID), c.qty);
                        }
                    }
                    _order.SetOrderPartnet(new OrderPartner(ERPID, Org_ID, OrderPartnerType.SoldTo));
                    _order.SetOrderPartnet(new OrderPartner(ERPID, Org_ID, OrderPartnerType.ShipTo));
                    _order.SetOrderPartnet(new OrderPartner(ERPID, Org_ID, OrderPartnerType.BillTo));

                    String _errMsg = String.Empty;
                    Advantech.Myadvantech.DataAccess.SAPDAL.SimulateOrder(ref _order, ref _errMsg);
                    // End order simulation


                    if (_order != null && String.IsNullOrEmpty(_errMsg))
                    {
                        foreach (Product p in _order.LineItems)
                        {
                            cart_DETAIL_V2 CartDetail = new cart_DETAIL_V2();
                            CartDetail.Cart_Id = CartID;

                            if (p.LineItemType == LineItemType.LooseItem)
                            {
                                CartDetail.Line_No     = p.LineNumber;
                                CartDetail.higherLevel = 0;
                            }
                            else if (p.LineItemType == LineItemType.BTOSParent)
                            {
                                CartDetail.Line_No     = NextHigherLevel;
                                CartDetail.higherLevel = 0;
                            }
                            else
                            {
                                CartDetail.Line_No     = p.LineNumber;
                                CartDetail.higherLevel = NextHigherLevel;
                            }

                            CartDetail.Part_No     = p.PartNumber;
                            CartDetail.Description = items.Where(i => i.name == p.PartNumber).FirstOrDefault().desc;
                            CartDetail.Qty         = p.Quantity;
                            CartDetail.Ew_Flag     = 0;
                            CartDetail.SatisfyFlag = 0;
                            CartDetail.QUOTE_ID    = "";
                            CartDetail.Category    = items.Where(i => i.name == p.PartNumber).FirstOrDefault().category;

                            //For ACN project, set customer material value = original customer part No.
                            if (isPrj == true && p.LineItemType == LineItemType.BTOSParent && !string.IsNullOrEmpty(CartDetail.Category) && CartDetail.Category.ToUpper().StartsWith("CM-"))
                            {
                                CartDetail.CustMaterial = CartDetail.Category;
                            }
                            else
                            {
                                CartDetail.CustMaterial = "";
                            }

                            CartDetail.otype    = 0;
                            CartDetail.req_date = DateTime.Now.AddDays(2);
                            if (CartDetail.Line_No < 100)
                            {
                                CartDetail.otype = (int)QuoteItemType.Part;
                            }
                            else if (CartDetail.Line_No % 100 == 0 && CartDetail.higherLevel == 0)
                            {
                                CartDetail.otype = (int)QuoteItemType.BtosParent;
                            }
                            else if (CartDetail.Line_No % 100 > 0 && CartDetail.Line_No > 100)
                            {
                                CartDetail.otype = (int)QuoteItemType.BtosPart;
                            }
                            CartDetail.due_date = CartDetail.req_date;

                            CartDetail.Delivery_Plant = GetDeliveryPlant(ERPID, Org_ID, CartDetail.Part_No, (QuoteItemType)Enum.Parse(typeof(QuoteItemType), CartDetail.otype.ToString()));

                            // set price according to it's item type
                            if (CartDetail.otype == (int)QuoteItemType.BtosParent)
                            {
                                CartDetail.List_Price = 0;
                                CartDetail.Unit_Price = 0;
                                CartDetail.Itp        = 0;
                            }
                            else
                            {
                                CartDetail.List_Price = p.ListPrice;
                                CartDetail.Unit_Price = p.UnitPrice;
                                CartDetail.Itp        = 0;
                            }

                            // Get product info from sap_product table
                            DataTable sapproduct_dt = SqlProvider.dbGetDataTable("MY", "select * from sap_product where part_no = '" + p.PartNumber + "'");
                            if (sapproduct_dt != null && sapproduct_dt.Rows.Count > 0)
                            {
                                CartDetail.Model_No = sapproduct_dt.Rows[0]["Model_No"].ToString();
                            }


                            MyAdvantechContext.Current.cart_DETAIL_V2.Add(CartDetail);
                        }
                        MyAdvantechContext.Current.SaveChanges();
                        updateresult.IsUpdated = true;
                    }
                    else
                    {
                        updateresult.IsUpdated     = false;
                        updateresult.ServerMessage = _errMsg;
                    }
                }
                catch (Exception ex)
                {
                    updateresult.IsUpdated     = false;
                    updateresult.ServerMessage = ex.ToString();
                }
            }
            else
            {
                updateresult.IsUpdated = false;
            }

            return(updateresult);
        }
        public static UpdateDBResult ConfiguratorSRP2Cart(String SelectedItems, String ERPID, String CartID, String Currency, String Org_ID, String LanguagePack)
        {
            UpdateDBResult         updateresult = new UpdateDBResult();
            List <ConfiguredItems> items        = new List <ConfiguredItems>();

            try
            {
                //Convert items
                items = Newtonsoft.Json.JsonConvert.DeserializeObject <List <ConfiguredItems> >(SelectedItems);
                //Convert language pack
                if (!string.IsNullOrEmpty(LanguagePack))
                {
                    LanguagePack = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(LanguagePack);
                }
            }
            catch (Exception ex)
            {
                updateresult.IsUpdated     = false;
                updateresult.ServerMessage = ex.ToString();
                return(updateresult);
            }

            try
            {
                Order _order = new Order();
                _order.Currency    = Currency;
                _order.OrgID       = Org_ID;
                _order.DistChannel = "10";
                _order.Division    = "00";
                if (Org_ID.StartsWith("CN"))
                {
                    var org = System.Configuration.ConfigurationManager.AppSettings["ACNTaxRate"] ?? "cn";
                    if (System.Configuration.ConfigurationManager.AppSettings["ACNTaxRate"] != null)
                    {
                        _order.Tax = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["ACNTaxRate"]);
                    }
                    else
                    {
                        _order.Tax = (Decimal)0.16;
                    }
                }


                foreach (ConfiguredItems c in items)
                {
                    _order.AddLooseItem(c.name, c.qty);
                }

                _order.SetOrderPartnet(new OrderPartner(ERPID, Org_ID, OrderPartnerType.SoldTo));
                _order.SetOrderPartnet(new OrderPartner(ERPID, Org_ID, OrderPartnerType.ShipTo));
                _order.SetOrderPartnet(new OrderPartner(ERPID, Org_ID, OrderPartnerType.BillTo));
                String _errMsg = String.Empty;
                Advantech.Myadvantech.DataAccess.SAPDAL.SimulateOrder(ref _order, ref _errMsg);

                if (_order != null && String.IsNullOrEmpty(_errMsg))
                {
                    //Get current max cart line no.
                    int    line_no = 0;
                    object max     = SqlProvider.dbExecuteScalar("MY", string.Format("select ISNULL(max(line_no), 0) from CART_DETAIL_V2 where cart_id='{0}' and otype=0 ", CartID));
                    if (max != null)
                    {
                        int.TryParse(max.ToString(), out line_no);
                    }
                    line_no = line_no + 1;

                    //Get SRP part in list
                    var srpItem = _order.LineItems.Where(p => p.PartNumber.ToUpper().StartsWith("SRP-")).FirstOrDefault();
                    if (srpItem == null)
                    {
                        updateresult.IsUpdated     = false;
                        updateresult.ServerMessage = "No SRP- item in list";
                        return(updateresult);
                    }

                    _order.LineItems.Remove(srpItem);
                    srpItem.LineNumber = line_no;
                    int srpLevel = line_no;
                    _order.LineItems.Insert(0, srpItem);

                    if (!string.IsNullOrEmpty(LanguagePack))
                    {
                        SqlProvider.dbExecuteNoQuery("MY", string.Format("DELETE FROM SRP_ORDER_LANGUAGE WHERE Cart_ID = '{0}' AND Line_No = {1}; INSERT INTO SRP_ORDER_LANGUAGE VALUES ('{0}', '{2}', {1}, 'SRP OS {3}');", CartID, srpLevel, srpItem.PartNumber, LanguagePack));
                    }

                    foreach (Product p in _order.LineItems)
                    {
                        cart_DETAIL_V2 CartDetail = new cart_DETAIL_V2();
                        CartDetail.Cart_Id = CartID;

                        CartDetail.Line_No     = line_no;
                        CartDetail.higherLevel = 0;

                        if (!p.PartNumber.ToUpper().StartsWith("SRP-"))
                        {
                            CartDetail.higherLevel = srpLevel;
                        }

                        CartDetail.Part_No      = p.PartNumber;
                        CartDetail.Description  = items.Where(i => i.name == p.PartNumber).FirstOrDefault().desc;
                        CartDetail.Qty          = p.Quantity;
                        CartDetail.CustMaterial = "";
                        CartDetail.Ew_Flag      = 0;
                        CartDetail.SatisfyFlag  = 0;
                        CartDetail.QUOTE_ID     = "";

                        CartDetail.otype    = 0;
                        CartDetail.req_date = DateTime.Now.AddDays(2);
                        if (CartDetail.Line_No < 100)
                        {
                            CartDetail.otype = (int)QuoteItemType.Part;
                        }
                        else if (CartDetail.Line_No % 100 == 0 && CartDetail.higherLevel == 0)
                        {
                            CartDetail.otype = (int)QuoteItemType.BtosParent;
                        }
                        else if (CartDetail.Line_No % 100 > 0 && CartDetail.Line_No > 100)
                        {
                            CartDetail.otype = (int)QuoteItemType.BtosPart;
                        }
                        CartDetail.due_date = CartDetail.req_date;

                        CartDetail.Delivery_Plant = GetDeliveryPlant(ERPID, Org_ID, CartDetail.Part_No, (QuoteItemType)Enum.Parse(typeof(QuoteItemType), CartDetail.otype.ToString()));

                        // set price according to it's item type
                        if (CartDetail.otype == (int)QuoteItemType.BtosParent)
                        {
                            CartDetail.List_Price = 0;
                            CartDetail.Unit_Price = 0;
                            CartDetail.Itp        = 0;
                        }
                        else
                        {
                            CartDetail.List_Price = p.ListPrice;
                            CartDetail.Unit_Price = p.UnitPrice;
                            CartDetail.Itp        = 0;
                        }

                        // Get product info from sap_product table
                        DataTable sapproduct_dt = SqlProvider.dbGetDataTable("MY", "select * from sap_product where part_no = '" + p.PartNumber + "'");
                        if (sapproduct_dt != null && sapproduct_dt.Rows.Count > 0)
                        {
                            CartDetail.Model_No = sapproduct_dt.Rows[0]["Model_No"].ToString();
                        }


                        MyAdvantechContext.Current.cart_DETAIL_V2.Add(CartDetail);
                        line_no = line_no + 1;
                    }
                    MyAdvantechContext.Current.SaveChanges();
                    updateresult.IsUpdated = true;
                }
                else
                {
                    updateresult.IsUpdated     = false;
                    updateresult.ServerMessage = _errMsg;
                }
            }
            catch (Exception ex)
            {
                updateresult.IsUpdated     = false;
                updateresult.ServerMessage = ex.ToString();
            }
            return(updateresult);
        }
        public static UpdateResult Configurator2Cart(string cartId, int parentLineNo, string orgId)
        {
            UpdateResult           updateResult = new UpdateResult();
            List <ConfiguredItems> items        = new List <ConfiguredItems>();

            try
            {
                HubConfiguredResult hcr = MyAdvantechDAL.GetHubConfiguredResultsWithLineNo(cartId, parentLineNo);
                if (hcr != null)
                {
                    // Remove all items in current cart for ACN
                    if (orgId.StartsWith("CN"))
                    {
                        CartDetailHelper.RemoveCartDetailByID(cartId);
                    }

                    List <ConfiguredItems> toAdditems = Newtonsoft.Json.JsonConvert.DeserializeObject <List <ConfiguredItems> >(hcr.SelectedItems);

                    if (toAdditems == null || toAdditems.Count == 0)
                    {
                        updateResult.IsUpdated     = false;
                        updateResult.ServerMessage = "No item was selected.";
                        return(updateResult);
                    }

                    // Split pipeline items
                    foreach (ConfiguredItems c in toAdditems)
                    {
                        if (c.name.Contains("|"))
                        {
                            foreach (var i in c.name.Split('|').ToList())
                            {
                                SAP_PRODUCT sp = MyAdvantechDAL.GetSAPProduct(i);

                                ConfiguredItems newitem = new ConfiguredItems();
                                newitem.name = i;
                                newitem.desc = (sp != null && !String.IsNullOrEmpty(sp.PRODUCT_DESC)) ? sp.PRODUCT_DESC : c.desc;
                                newitem.qty  = c.qty;
                                //newitem.isLooseItem = c.isLooseItem;
                                items.Add(newitem);
                            }
                        }
                        else
                        {
                            items.Add(c);
                        }
                    }

                    // Get next higherlevel & next loose line no.
                    int NextHigherLevel    = hcr.ParentLineNo;
                    var objNextHigherLevel = SqlProvider.dbExecuteScalar("MY", "select max(line_no) from cart_DETAIL_V2 where cart_id = '" + cartId + "' and (otype = 0 or otype = 1)");
                    if (objNextHigherLevel != null && !String.IsNullOrEmpty(objNextHigherLevel.ToString()))
                    {
                        NextHigherLevel = (Convert.ToInt32(objNextHigherLevel.ToString()) / 100 + 1) * 100;
                    }
                    int NextLooseItemLineNo    = 1;
                    var objNextLooseItemLineNo = SqlProvider.dbExecuteScalar("MY", "select max(line_no) from cart_DETAIL_V2 where cart_id = '" + cartId + "' and otype = 0 ");
                    if (objNextLooseItemLineNo != null && !String.IsNullOrEmpty(objNextLooseItemLineNo.ToString()))
                    {
                        NextLooseItemLineNo = Convert.ToInt32(objNextLooseItemLineNo.ToString()) + 1;
                    }

                    if (items.Count > 0)
                    {
                        // For ACN, need to split BOTS root name with "/", ex: IPC-510-BTO/P4
                        items.Where(c => c.name.Contains("-BTO/")).ToList().ForEach(c => c.name = c.name.Split(new string[] { "/" }, StringSplitOptions.None)[0]);

                        // Simulate Product List to get price
                        Order _order = new Order();
                        _order.Currency    = hcr.Currency;
                        _order.OrgID       = orgId;
                        _order.DistChannel = "10";
                        _order.Division    = "00";
                        if (orgId.StartsWith("CN"))
                        {
                            if (System.Configuration.ConfigurationManager.AppSettings["ACNTaxRate"] != null)
                            {
                                _order.Tax = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["ACNTaxRate"]);
                            }
                            else
                            {
                                _order.Tax = (Decimal)0.16;
                            }
                        }

                        foreach (ConfiguredItems c in items)
                        {
                            //Frank 20171222, if part's material is BTO then identify it as BTOS parent item
                            SAP_PRODUCT sap_p = MyAdvantechDAL.GetSAPProduct(c.name);

                            if (orgId.Equals("EU80") && c.isLooseItem)
                            {
                                _order.AddLooseItem(c.name, SAPDAL.GetPlantByOrg(orgId), NextLooseItemLineNo, c.qty);
                                NextLooseItemLineNo++;
                            }
                            else if (sap_p != null && (sap_p.MATERIAL_GROUP.Equals("BTOS", StringComparison.InvariantCultureIgnoreCase) || c.name.EndsWith("-BTO", StringComparison.OrdinalIgnoreCase)))
                            {
                                _order.AddBTOSParentItem(c.name, SAPDAL.GetPlantByOrg(orgId), NextHigherLevel, c.qty);
                            }
                            else
                            {
                                _order.AddBTOSChildItem(c.name, NextHigherLevel, SAPDAL.GetPlantByOrg(orgId), c.qty);
                            }
                        }
                        _order.SetOrderPartnet(new OrderPartner(hcr.CompanyID, orgId, OrderPartnerType.SoldTo));
                        _order.SetOrderPartnet(new OrderPartner(hcr.CompanyID, orgId, OrderPartnerType.ShipTo));
                        _order.SetOrderPartnet(new OrderPartner(hcr.CompanyID, orgId, OrderPartnerType.BillTo));

                        String _errMsg = String.Empty;
                        Advantech.Myadvantech.DataAccess.SAPDAL.SimulateOrder(ref _order, ref _errMsg);
                        // End order simulation


                        if (_order != null && String.IsNullOrEmpty(_errMsg))
                        {
                            foreach (Product p in _order.LineItems)
                            {
                                cart_DETAIL_V2 CartDetail = new cart_DETAIL_V2();
                                CartDetail.Cart_Id = cartId;

                                if (p.LineItemType == LineItemType.LooseItem)
                                {
                                    CartDetail.Line_No     = p.LineNumber;
                                    CartDetail.higherLevel = 0;
                                }
                                else if (p.LineItemType == LineItemType.BTOSParent)
                                {
                                    CartDetail.Line_No     = NextHigherLevel;
                                    CartDetail.higherLevel = 0;
                                }
                                else
                                {
                                    CartDetail.Line_No     = p.LineNumber;
                                    CartDetail.higherLevel = NextHigherLevel;
                                }

                                CartDetail.Part_No      = p.PartNumber;
                                CartDetail.Description  = items.Where(i => i.name == p.PartNumber).FirstOrDefault().desc;
                                CartDetail.Qty          = p.Quantity;
                                CartDetail.Ew_Flag      = 0;
                                CartDetail.SatisfyFlag  = 0;
                                CartDetail.QUOTE_ID     = "";
                                CartDetail.Category     = items.Where(i => i.name == p.PartNumber).FirstOrDefault().category;
                                CartDetail.CustMaterial = "";

                                CartDetail.otype    = 0;
                                CartDetail.req_date = DateTime.Now.AddDays(2);
                                if (CartDetail.Line_No < 100)
                                {
                                    CartDetail.otype = (int)QuoteItemType.Part;
                                }
                                else if (CartDetail.Line_No % 100 == 0 && CartDetail.higherLevel == 0)
                                {
                                    CartDetail.otype = (int)QuoteItemType.BtosParent;
                                }
                                else if (CartDetail.Line_No % 100 > 0 && CartDetail.Line_No > 100)
                                {
                                    CartDetail.otype = (int)QuoteItemType.BtosPart;
                                }
                                CartDetail.due_date = CartDetail.req_date;

                                CartDetail.Delivery_Plant = SAPDAL.GetDeliveryPlant(hcr.CompanyID, orgId, CartDetail.Part_No, (QuoteItemType)Enum.Parse(typeof(QuoteItemType), CartDetail.otype.ToString()));

                                // set price according to it's item type
                                if (CartDetail.otype == (int)QuoteItemType.BtosParent)
                                {
                                    CartDetail.List_Price = 0;
                                    CartDetail.Unit_Price = 0;
                                    CartDetail.Itp        = 0;
                                }
                                else
                                {
                                    CartDetail.List_Price = p.ListPrice;
                                    CartDetail.Unit_Price = p.UnitPrice;
                                    CartDetail.Itp        = 0;
                                }

                                // Get product info from sap_product table
                                DataTable sapproduct_dt = SqlProvider.dbGetDataTable("MY", "select * from sap_product where part_no = '" + p.PartNumber + "'");
                                if (sapproduct_dt != null && sapproduct_dt.Rows.Count > 0)
                                {
                                    CartDetail.Model_No = sapproduct_dt.Rows[0]["Model_No"].ToString();
                                }


                                MyAdvantechContext.Current.cart_DETAIL_V2.Add(CartDetail);
                            }
                            MyAdvantechContext.Current.SaveChanges();
                            updateResult.IsUpdated = true;
                        }
                        else
                        {
                            updateResult.IsUpdated     = false;
                            updateResult.ServerMessage = _errMsg;
                        }
                    }
                }
                else
                {
                    updateResult.IsUpdated     = false;
                    updateResult.ServerMessage = "No matched record found.";
                }
            }
            catch (Exception ex)
            {
                updateResult.IsUpdated     = false;
                updateResult.ServerMessage = ex.ToString();
            }

            return(updateResult);
        }