/// <summary>
        /// If exist return existing pi
        /// </summary>
        /// <param name="PartCode"></param>
        /// <param name="PartType"></param>
        /// <param name="DealerCode"></param>
        /// <returns></returns>
        public static PartInfo AddPartToDealer(string PartCode, string PartType, string DealerCode)
        {
            //using (var db = new PartDataContext())
            //{

            var db = new PartDataContext(); // must create another data context
            var pi = db.PartInfos.SingleOrDefault(p => p.DealerCode == DealerCode && p.PartCode == PartCode && p.PartType == PartType);
            if (pi != null) return pi;

            // cancel check dealer, assume dealer is valid
            //Dealer dl = DealerDAO.GetDealerByCode(DealerCode);
            //if (dl == null) return null;

            pi = new PartInfo
            {
                DealerCode = DealerCode,
                PartCode = PartCode,
                PartType = PartType
            };

            // cancel check part code, assume part code is valid
            //if (!PartDAO.IsPartCodeValid(PartCode, "P", DealerCode)) return null;

            db.PartInfos.InsertOnSubmit(pi);
            db.SubmitChanges();
            //            db.Dispose();
            return pi;
        }
        public static Accessory CreateNew(string code, string ename, string vname, string dealerCode, string type, long catId)
        {
            Accessory acs = null;
            if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(dealerCode) || (catId <= 0)) throw new InvalidOperationException("Wrong paramaters");

            if (!AccessoryDAO.IsAccessoryExist(code, dealerCode))
            {
                acs = new Accessory
                {
                    AccessoryCode = code,
                    EnglishName = ename,
                    VietnamName = vname,
                    DealerCode = dealerCode,
                    AccessoryTypeCode = type,
                };
                PartInfo pi = new PartInfo
                {
                    Accessory = acs,
                    DealerCode = dealerCode,
                    PartType = "A",
                    PartCode = acs.AccessoryCode,
                    CategoryId = catId,
                };

                DC.PartInfos.InsertOnSubmit(pi);
                DC.SubmitChanges();
            }
            return acs;
        }
    protected void LoadPartInfo(long partInfoId)
    {
        EditingPart = PartInfoDAO.GetPartInfo(partInfoId);
        Favorite fSale = PartDAO.GetFavorite(EditingPart.PartCode, EditingPart.PartType, EditingPart.DealerCode, "S");
        Favorite fOrder = PartDAO.GetFavorite(EditingPart.PartCode, EditingPart.PartType, EditingPart.DealerCode, "O");

        if (fSale != null)
        {
            ddlSaleRank.BindingSelectedValue = fSale.Rank.ToString();
            ddlSaleRank.DataBind();
        }
        if (fOrder != null)
        {
            ddlOrderRank.BindingSelectedValue = fOrder.Rank.ToString();
            ddlOrderRank.DataBind();
        }

        if (EditingPart != null)
        {
            tbEnName.Text = EditingPart.Accessory.EnglishName;
            tbVnName.Text = EditingPart.Accessory.VietnamName;
            tbPartCode.Text = EditingPart.PartCode;
            tbPrice.Text = EditingPart.Price.ToString();
            ddlCategory.BindingSelectedValue = EditingPart.CategoryId.ToString();
            ddlAccType.BindingSelectedValue = EditingPart.Accessory.AccessoryTypeCode;
            ddlCategory.DataBind();
            ddlAccType.DataBind();

            odsPartSafeties.SelectParameters["partInfoId"].DefaultValue = PartInfoId.ToString();
            odsPartSafeties.SelectParameters["dealerCode"].DefaultValue = UserHelper.DealerCode;
            gvSafeties.DataSourceID = odsPartSafeties.ID;
            gvSafeties.DataBind();
        }
    }
 public static PartInfo AddPartToDealer(long? catId, string dealerCode, string partCode, string type, int? price)
 {
     PartInfo pi = null;
     if (!PartExist(partCode, dealerCode))
     {
         pi = new PartInfo() { CategoryId = catId, DealerCode = dealerCode, PartCode = partCode, PartType = type, Price = price };
         PartDC.PartInfos.InsertOnSubmit(pi);
         PartDC.SubmitChanges();
     }
     return pi;
 }
    protected void bSave_Click(object sender, EventArgs e)
    {
        int price;
        int.TryParse(tbPrice.Text, out price);
        string partCode = tbPartCode.Text.Trim().ToUpper();

        if (PartDAO.IsPartCodeValidGlobal(partCode))//(VDMS.Data.TipTop.Part.IsPartExist(partCode, "ALL"))
        {
            AddErrorMsg(lbExistInTipTop.Text);
            return;
        }

        try
        {
            EditingPart = PartInfoDAO.SaveOrUpdate((string.IsNullOrEmpty(ddlCategory.SelectedValue)) ? null : (long?)long.Parse(ddlCategory.SelectedValue), UserHelper.DealerCode, partCode, PartType.Accessory, price);
            var acs = AccessoryDAO.SaveOrUpdate(partCode, UserHelper.DealerCode, tbEnName.Text.Trim(), tbVnName.Text.Trim(), ddlAccType.SelectedValue);

            if (EditingPart.Accessory == null)
            {
                EditingPart.AccessoryId = acs.AccessoryId;
            }

            // check Favorite
            var fSale = PartDAO.GetFavorite(partCode, EditingPart.PartType, UserHelper.DealerCode, "S");
            var fOrder = PartDAO.GetFavorite(partCode, EditingPart.PartType, UserHelper.DealerCode, "O");
            ProcessFavorite(fSale, ddlSaleRank.SelectedIndex > 0, "S", EditingPart.PartCode, EditingPart.PartType, ddlSaleRank.SelectedValue);
            ProcessFavorite(fOrder, ddlOrderRank.SelectedIndex > 0, "O", EditingPart.PartCode, EditingPart.PartType, ddlOrderRank.SelectedValue);

            // save safety stock
            ProcessSafety(EditingPart.PartInfoId);

            PartInfoDAO.SaveChanged();

            Session["SaveAccessory"] = "ok";
            string url = Request.Url.ToString();
            Response.Redirect(url.Remove(url.IndexOf('?')) + "?id=" + EditingPart.PartInfoId.ToString());
        }
        catch (Exception ex) { AddErrorMsg(ex.Message); }
    }
        public static TransactionHistory CreateTransaction(PartInfo partInfo, string dealerCode, long actWarehouse, long? toWarehouse, DateTime transDate, string transCode, int cost, int qty, string comment, string invNo, long? vendorId)
        {
            //var db = new PartDataContext(); // must create another data context
            var db = DCFactory.GetDataContext<PartDataContext>();
            var trans = new TransactionHistory
            {
                ActualCost = cost,
                CreatedBy = UserHelper.Username,
                CreatedDate = DateTime.Now,
                DealerCode = dealerCode,
                InvoiceNumber = invNo,
                PartInfoId = partInfo.PartInfoId,
                Quantity = qty,
                TransactionCode = transCode,
                TransactionComment = comment,
                TransactionDate = transDate,
                SecondaryWarehouseId = toWarehouse,
                VendorId = vendorId,
                WarehouseId = actWarehouse,
            };

            db.TransactionHistories.InsertOnSubmit(trans);
            return trans;
        }
 private void detach_PartInfos(PartInfo entity)
 {
     this.SendPropertyChanging();
     entity.Category = null;
 }
 private void attach_PartInfos(PartInfo entity)
 {
     this.SendPropertyChanging();
     entity.Category = this;
 }
        public static PartSafety CreatePartSafety(PartInfo pInfo, long warehouseId, int quantity, int safeQty)
        {
            //Warehouse wh = PartDC.ActiveWarehouses.SingleOrDefault(w => w.WarehouseId == warehouseId);
            //if (wh == null) return null;

            //PartInfo pi = PartDC.PartInfos.SingleOrDefault(p => p.PartCode == partCode && p.DealerCode == wh.DealerCode);
            //if (pi == null) return null;

            var db = DCFactory.GetDataContext<PartDataContext>();
            PartSafety ps = null;
            if (pInfo.PartInfoId != 0) ps = db.PartSafeties.SingleOrDefault(p => p.PartInfoId == pInfo.PartInfoId);
            if (ps != null)
                ps.CurrentStock += quantity;
            else
            {
                ps = new PartSafety
                {
                    CurrentStock = quantity,
                    SafetyQuantity = safeQty,
                    WarehouseId = warehouseId
                };
                db.PartSafeties.InsertOnSubmit(ps);
            }
            return ps;
        }
 public static PartInfo CreatePartInfo(string partCode, string dealerCode, string partType)
 {
     var db = DCFactory.GetDataContext<PartDataContext>();
     var pi = db.PartInfos.SingleOrDefault(p => p.DealerCode == dealerCode && p.PartCode == partCode && p.PartType == partType);
     if (pi != null) return pi;
     pi = new PartInfo
     {
         DealerCode = dealerCode,
         PartCode = partCode,
         PartType = partType
     };
     db.PartInfos.InsertOnSubmit(pi);
     return pi;
 }
        /// <summary>
        /// Inc Current Stock n Create "part safety" if needed
        /// </summary>
        /// <param name="pi"></param>
        /// <param name="Quantity"></param>
        /// <param name="warehouseId"></param>
        public static void IncCurrentStock(PartInfo pi, int Quantity, long warehouseId)
        {
            var ps = PartInfoDAO.GetPartSafety(pi.PartInfoId, warehouseId);
            if (ps == null)
            {
                var db = new PartDataContext(); // must create another data context
                ps = new PartSafety
                {
                    WarehouseId = warehouseId,
                    PartInfoId = pi.PartInfoId,
                    CurrentStock = 0,
                    SafetyQuantity = 0
                };
                db.PartSafeties.InsertOnSubmit(ps);
                db.SubmitChanges();
                //db.Dispose();

            }

            ps = PartInfoDAO.GetPartSafety(pi.PartInfoId, warehouseId);
            if (ps != null)
            {
                ps.CurrentStock += Quantity;
                if (ps.CurrentStock < 0)
                {
                    throw new Exception(string.Format("On hand quantity of \"{0}\" will be negative!", pi.PartCode));
                }
            }
            else throw new Exception(string.Format("Cannot create safatyStock to inc current stock for {0}!", pi.PartCode));
        }
 private void detach_PartInfos(PartInfo entity)
 {
     this.SendPropertyChanging("PartInfos");
     entity.Accessory = null;
 }
 private void attach_PartInfos(PartInfo entity)
 {
     this.SendPropertyChanging("PartInfos");
     entity.Dealer = this;
 }