public static String GetDeliveryPlant(String company_id, String org_id, String part_no, QuoteItemType type)
 {
     if (!String.IsNullOrEmpty(org_id))
     {
         if (org_id.Equals("TW01", StringComparison.OrdinalIgnoreCase))
         {
             if (type == QuoteItemType.BtosParent || type == QuoteItemType.BtosPart)
             {
                 return("TWH1");
             }
             else
             {
                 String    str = String.Format("select top 1 DELIVERYPLANT from SAP_PRODUCT_ORG where ORG_ID='TW01' and PART_NO = '{0}'", part_no);
                 DataTable dt  = DataAccess.SqlProvider.dbGetDataTable("MY", str);
                 if (dt.Rows.Count > 0)
                 {
                     return(dt.Rows[0][0].ToString());
                 }
                 else
                 {
                     return("TWH1");
                 }
             }
         }
         else
         {
             return(SAPDAL.GetPlantByOrg(org_id));
         }
     }
     else
     {
         return("TWH1");
     }
 }
        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 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);
        }