Ejemplo n.º 1
0
        public static void DoOpenW(string wCode, string dCode, VehicleDataContext dc)
        {
            var ilck = InventoryHelper.GetInventoryLock(dCode, wCode);
            if (ilck == null)
            {
                throw new Exception("This warehouse never closed before!");
            }
            else
            {
                if (!CanOpenW(wCode, dCode, (int)ilck.Year, (int)ilck.Month)) throw new Exception("May try to open months before 'first month' or parent component has not been opened!");
                // change locked month to new Closed month
                if (ilck.Month == 1) { ilck.Month = 12; ilck.Year--; }
                else ilck.Month--;
            }

            dc.SubmitChanges();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Do close inventory
        /// </summary>
        /// <param name="code"></param>
        /// <param name="dealerCode"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <param name="dc"></param>
        public static void DoInventory(string code, string dealerCode, int month, int year, VehicleDataContext dc)
        {
            //var dc = DCFactory.GetDataContext<VehicleDataContext>();
            int nextM = month + 1, nextY = year;
            int prevM = month - 1, prevY = year;

            if (nextM == 13) { nextM = 1; nextY++; }
            if (prevM == 0) { prevM = 12; prevY--; }

            var prevInv = dc.SaleInventories.Where(i => i.Year == prevY && i.Month == prevM && i.BranchCode == code && i.DealerCode == dealerCode).ToList();

            // delete all current data
            dc.SaleInventories.DeleteAllOnSubmit(dc.SaleInventories.Where(iv => iv.BranchCode == code && iv.DealerCode == dealerCode && iv.Year == year && iv.Month == month).ToList());

            // get all actions happend in closing month(group by item code)
            var invs = dc.SaleInventoryDays.Where(id => id.ActionDay >= DataFormat.DateToCompareNumber(1, month, year)
                    && id.ActionDay < DataFormat.DateToCompareNumber(1, nextM, nextY)
                    && id.BranchCode == code && id.DealerCode == dealerCode)
                    .GroupBy(id => id.ItemCode, (key, g) => new
                    {
                        Itemcode = key,
                        Quantity = (int)g.Sum(i => i.Quantity),
                    })
                .ToList();
            // all items already exist in sale_inventory and has transactions
            var udInvs = from pi in prevInv
                         join id in invs on pi.ItemCode equals id.Itemcode
                         select new SaleInventory
                         {
                             ItemCode = pi.ItemCode,
                             BranchCode = code,
                             DealerCode = dealerCode,
                             Month = month,
                             Year = year,
                             Quantity = id.Quantity + pi.Quantity,
                         };
            // new items has beem imported in closing month
            var nwInvs = invs.Where(i => prevInv.Where(p => p.ItemCode == i.Itemcode).Count() == 0).Select(i => new SaleInventory
            {
                ItemCode = i.Itemcode,
                BranchCode = code,
                DealerCode = dealerCode,
                Month = month,
                Year = year,
                Quantity = i.Quantity,
            });

            // all items already exist in sale_inventory and has no transactions
            var mvInvs = prevInv.Where(i => invs.Where(c => c.Itemcode == i.ItemCode).Count() == 0).Select(i => new SaleInventory
            {
                ItemCode = i.ItemCode,
                BranchCode = code,
                DealerCode = dealerCode,
                Month = month,
                Year = year,
                Quantity = i.Quantity,
            });

            // insert all to sale_inventory
            if (udInvs.Count() > 0)
                dc.SaleInventories.InsertAllOnSubmit(udInvs.Distinct());
            if (nwInvs.Count() > 0)
                dc.SaleInventories.InsertAllOnSubmit(nwInvs);
            if (mvInvs.Count() > 0)
                dc.SaleInventories.InsertAllOnSubmit(mvInvs);
            dc.SubmitChanges();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// DoInventory calulate follow dataiteminstance
        /// </summary>
        public static void DoInventory2(string code,string dealerCode, int month, int year,VehicleDataContext dc)
        {
            int nextM = month + 1, nextY = year;
            int prevM = month - 1, prevY = year;

            if (nextM == 13) { nextM = 1; nextY++; }
            if (prevM == 0) { prevM = 12; prevY--; }
            dc.SaleInventories.DeleteAllOnSubmit(dc.SaleInventories.Where(iv => iv.BranchCode == code && iv.DealerCode == dealerCode && iv.Year == year && iv.Month == month).ToList());
            var t = GetIOReportData(dealerCode,code, string.Empty, string.Empty,new DateTime(year, month, 1).ToShortDateString(), new DateTime(nextY, nextM, 1).AddTicks(-1).ToShortDateString());
            var result = from i in t
                         select new SaleInventory
                         {
                             ItemCode = i.ItemCode,
                             BranchCode = code,
                             DealerCode = dealerCode,
                             Month = month,
                             Year = year,
                             Quantity = i.Begin +  i.In + i.Out
                         };
            if (result.Count() > 0)
                dc.SaleInventories.InsertAllOnSubmit(result);
            dc.SubmitChanges();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Close warehouse vehicle inventory at specified month.
        /// </summary>
        /// <param name="code"></param>
        /// <param name="dealerCode"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <param name="dc"></param>
        public static void DoCloseW(string code, string dealerCode, int month, int year, VehicleDataContext dc)
        {
            if ((year > DateTime.Now.Year) //|| (year < 2000)
                 || ((year == DateTime.Now.Year) && (month > DateTime.Now.Month))
                 || (month > 12) || (month < 1)
               )
            {
                throw new Exception("Invalid closing month!");
            }

            // check for valid warehouse
            var wh = VDMS.II.BasicData.WarehouseDAO.GetWarehouse(code, dealerCode, VDMS.II.Entity.WarehouseType.Vehicle);
            if (wh == null) throw new Exception("Invalid closing warehouse!");

            // get lock record for current closed month
            var ilck = dc.SaleInventoryLocks.SingleOrDefault(i => i.DealerCode == GetWLockCode(dealerCode, code) && i.IsLocked == 1);
            if (ilck == null)// never closed before
            {
                if (year < 2007) throw new Exception("Invalid closing month at first time!");
                // lock month valid to first inventory action?
                SaleInventory frstIv = dc.SaleInventories.Where(i => i.BranchCode == code && i.DealerCode == dealerCode).OrderBy(i => i.Year).OrderBy(i => i.Month).FirstOrDefault();
                if (frstIv != null)
                {
                    DateTime fDt = new DateTime(frstIv.Year, frstIv.Month, 1);
                    DateTime cDt = new DateTime(year, month, 1);
                    if (fDt.AddMonths(1) < cDt)
                        throw new Exception("At first time, closing month cannot be greater than the first month that changing inventory action happen!");
                }
                ilck = new SaleInventoryLock
                {
                    DealerCode = GetWLockCode(wh.DealerCode, wh.Code),
                    Month = month,
                    Year = year,
                    IsLocked = 1
                };
                dc.SaleInventoryLocks.InsertOnSubmit(ilck);
            }
            else
            {
                // change locked month to new Closed month
                if (ilck.Month == 12) { ilck.Month = 1; ilck.Year++; }
                else ilck.Month++;
                if ((ilck.Year > DateTime.Now.Year) || ((ilck.Year == DateTime.Now.Year) && (ilck.Month > DateTime.Now.Month))) throw new Exception("Invalid closing month!");
            }

            dc.SubmitChanges();

            // summarization
            InventoryHelper.DoInventory2(code, dealerCode, (int)ilck.Month, (int)ilck.Year, dc);

            // gen excel file
            //new VDMS.II.Report.PartMonthlyReport(wId.ToString(), wh.DealerCode, ilck.Month, ilck.Year).DoReport();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Close dealer vehicle inventory at specified month.
        /// </summary>
        /// <param name="dealerCode"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <param name="dc"></param>
        public static void DoCloseD(string dealerCode, int month, int year, VehicleDataContext dc)
        {
            if ((year > DateTime.Now.Year) //|| (year < 2000)
                 || ((year == DateTime.Now.Year) && (month > DateTime.Now.Month))
                 || (month > 12) || (month < 1)
               )
            {
                throw new Exception("Invalid closing month!");
            }

            // check Dealer exist
            var d = DealerDAO.GetDealerByCode(dealerCode);
            if (d == null) throw new Exception("Invalid closing dealer!");

            // check all warehouse and sub dealer are closed
            if (!InventoryHelper.CanCloseDealer(dealerCode, year, month, dc))
                throw new Exception(string.Format("Cannot close {0}! All sub components must be closed before.", dealerCode));

            // get lock record for current closed month
            var ilck = dc.SaleInventoryLocks.SingleOrDefault(i => i.DealerCode == dealerCode && i.IsLocked == 0);
            if (ilck == null)   // never closed before
            {
                if (year < 2007) throw new Exception("Invalid closing month at first time!");
                // create new lock record
                ilck = new SaleInventoryLock
                {
                    IsLocked = 0,
                    DealerCode = d.DealerCode,
                    Month = month,
                    Year = year
                };
                dc.SaleInventoryLocks.InsertOnSubmit(ilck);
            }
            else // update locked record to new closing month
            {
                if (ilck.Month == 12) { ilck.Month = 1; ilck.Year++; }
                else ilck.Month++;
                if ((ilck.Year > DateTime.Now.Year) || ((ilck.Year == DateTime.Now.Year) && (ilck.Month > DateTime.Now.Month))) throw new Exception("Invalid closing month!");
            }

            dc.SubmitChanges();
        }
Ejemplo n.º 6
0
        public static bool SaveUpdate(string branchcode, string issueNumber, string shipnumber, string areacode, DateTime baseImportDate, string dealercode)
        {
            string exception, itemCode, engineNumber, itemType, color, orderNumber, shipTo;
            Collection<ImportErrorCode> errorCode = new Collection<ImportErrorCode>();
            Int32 status;
            bool hasVoucher;
            ImportItemStatus IisStatus;
            ItemInstance IInst = null;
            ItemStatus hisItemStatus;
            DateTime madeDate, impDate, itemImpDate;
            VDMS.I.Entity.ShippingDetail SD;
            long Price;

            Item item = null;
            long shipID;

            using (var db = new VehicleDataContext())
            {
                System.Data.Common.DbTransaction transaction;
                db.Connection.Open();
                transaction = db.Connection.BeginTransaction();
                db.Transaction = transaction;
                try
                {
                    impDate = CalculateInitImportDate(baseImportDate);
                    if (impDate < baseImportDate)
                    {
                        AddError(ImportErrorCode.ImportDateLessThanBaseDate, errorCode);
                        return false;
                    }
                    var tt = TipTop_ShippingDetail(issueNumber);
                    foreach (var m in tt)
                    {
                        exception = m.Exception;
                        status = 1;
                        hasVoucher = IsOrderConfirmed(m.TipTopOrderNumber);
                        itemCode = m.ItemCode;
                        engineNumber = m.EngineNumber;
                        itemType = m.Model;
                        if (m.Status == (int)ImportItemStatus.Imported || m.Status == (int)ImportItemStatus.AdmitTemporarily)
                        {
                            continue;
                        }

                        if (ItemInstanceHelper.EngineNumberExist(engineNumber))
                        {
                            LogError("IssueNumber: " + issueNumber + ", branchcode: " + branchcode + ", DealerCode:" + dealercode + ", Shipdate:" + baseImportDate + ", EngineNumber in dataItemInstance:" + engineNumber);//Log
                            continue;
                            //throw new Exception( engineNumber +  " avaliable in ItemInstance");
                            //return false;
                        }
                        if (isExsitDataItemInstance(engineNumber))
                            return false;

                        color = m.ColorCode + " (" + m.ColorName + ")";
                        orderNumber = m.TipTopOrderNumber;
                        DateTime.TryParse(m.OutStockDate.ToString(),
                                          Thread.CurrentThread.CurrentCulture,
                                          DateTimeStyles.AllowWhiteSpaces, out madeDate);
                        long.TryParse(m.Price.ToString(), out Price);

                        // custom imported date for item
                        string impDateString = CalculateInitImportDate(baseImportDate).ToShortDateString();
                        if (string.IsNullOrEmpty(impDateString)) impDateString = DateTime.Now.ToShortDateString();

                        if (
                            !DateTime.TryParse(impDateString, Thread.CurrentThread.CurrentCulture,
                                               DateTimeStyles.AllowWhiteSpaces, out itemImpDate))
                        {
                            AddError(ImportErrorCode.InvalidImportDate, errorCode);
                        }

                        if (itemImpDate < baseImportDate) AddError(ImportErrorCode.ImportDateLessThanBaseDate, errorCode);
                        if (itemImpDate > DateTime.Now) AddError(ImportErrorCode.ImportDateTooLate, errorCode);
                        if (InventoryHelper.IsInventoryLock(itemImpDate, dealercode, branchcode))
                            AddError(ImportErrorCode.ImportDateLocked, errorCode);
                        if (errorCode.Count > 0)
                        {
                            return false;
                        }

                        //branchCode = ((Label)row.FindControl("lblBranchCode")).Text;

                        // day du cac thu roi thi khong chap nhan exception
                        if ((hasVoucher) && (status == 1)) exception = string.Empty;

                        IInst = null;
                        // get n' check item in table DATA_ITEM
                        item = CommonDAO.GetItemByCode(db, itemCode);
                        if (item == null)
                        {
                            AddError(ImportErrorCode.ItemNotExist, errorCode);
                            return false;
                        }

                    }
                    shipTo = branchcode;

                    // save Shipping header
                    VDMS.I.Entity.ShippingHeader SH = CommonDAO.SaveOrUpdateShippingHeader(db, areacode, shipnumber,
                                                                                           shipTo,
                                                                                           impDate, dealercode,
                                                                                           (tt.Count +
                                                                                            tt.Count),
                                                                                           dealercode);
                    db.SubmitChanges();

                    if (SH == null)
                    {
                        return false;
                    }
                    shipID = db.ShippingHeaders.SingleOrDefault(p => p.ShippingNumber == shipnumber).ShippingId;

                    #region save shipping

                    foreach (var m in tt)
                    {
                        exception = m.Exception;
                        status = 1;
                        hasVoucher = IsOrderConfirmed(m.TipTopOrderNumber);
                        itemCode = m.ItemCode;
                        engineNumber = m.EngineNumber;
                        itemType = m.Model;

                        color = m.ColorCode + " (" + m.ColorName + ")";
                        orderNumber = m.TipTopOrderNumber;
                        DateTime.TryParse(m.OutStockDate.ToString(),
                                          Thread.CurrentThread.CurrentCulture,
                                          DateTimeStyles.AllowWhiteSpaces, out madeDate);
                        long.TryParse(m.Price.ToString(), out Price);

                        if (m.Status == (int)ImportItemStatus.Imported || m.Status == (int)ImportItemStatus.AdmitTemporarily)
                        {
                            continue;
                        }

                        if (ItemInstanceHelper.EngineNumberExist(engineNumber))
                        {
                            LogError("IssueNumber: " + issueNumber + ", branchcode: " + branchcode + ", DealerCode:" + dealercode + ", Shipdate:" + baseImportDate + ", EngineNumber in dataItemInstance:" + engineNumber);//Log
                            continue;
                            //throw new Exception( engineNumber +  " avaliable in ItemInstance");
                            //return false;
                        }

                        // custom imported date for item
                        string impDateString = impDate.ToShortDateString();
                        if (
                            !DateTime.TryParse(impDateString, Thread.CurrentThread.CurrentCulture,
                                               DateTimeStyles.AllowWhiteSpaces, out itemImpDate))
                        {
                            AddError(ImportErrorCode.InvalidImportDate, errorCode);
                        }

                        if (itemImpDate < baseImportDate) AddError(ImportErrorCode.ImportDateLessThanBaseDate, errorCode);
                        if (itemImpDate > DateTime.Now) AddError(ImportErrorCode.ImportDateTooLate, errorCode);
                        if (InventoryHelper.IsInventoryLock(itemImpDate, dealercode, branchcode))
                            AddError(ImportErrorCode.ImportDateLocked, errorCode);
                        if (errorCode.Count > 0)
                        {
                            return false;
                        }

                        if ((hasVoucher) && (status == 1)) exception = string.Empty;
                        item = CommonDAO.GetItemByCode(db, itemCode);
                        if (status > 0) // nhap xe hoac tam nhap => save iteminstance n' transHistory
                        {
                            // clear instance for old shipping info
                            //foreach (var sd in CommonDAO.GetShippingDetails(db, engineNumber))
                            //{
                            //    sd.ProductInstanceId = null;
                            //}
                            // save ItemInstance of shipping
                            switch (status)
                            {
                                case 0:
                                    IisStatus = ImportItemStatus.NotArrived;
                                    break;
                                case 1:
                                    IisStatus = ImportItemStatus.Imported;
                                    break;
                                case 2:
                                    IisStatus = ImportItemStatus.AdmitTemporarily;
                                    break;
                                default:
                                    IisStatus = ImportItemStatus.NotArrived;
                                    break;
                            }
                            //db.SubmitChanges();
                            IInst = CommonDAO.SaveOrUpdateItemInstance(db, dealercode, branchcode,
                                                                       engineNumber,
                                                                       shipnumber, orderNumber, itemType, item,
                                                                       itemImpDate,
                                                                       color, (int)IisStatus, madeDate,
                                                                       DealerHelper.GetDatabaseCode(dealercode));
                            db.SubmitChanges();

                            if (IInst == null)
                            {
                                return false;
                            }

                            // save transaction history. <actualCost> is temporary equal to "zero"
                            switch (status)
                            {
                                case 0:
                                    hisItemStatus = ItemStatus.Lacked;
                                    break;
                                case 1:
                                    hisItemStatus = ItemStatus.Imported;
                                    break;
                                case 2:
                                    hisItemStatus = ItemStatus.AdmitTemporarily;
                                    break;
                                default:
                                    hisItemStatus = ItemStatus.AdmitTemporarily;
                                    break;
                            }
                            var t = CommonDAO.SaveTransHist(db, IInst, itemImpDate, hisItemStatus, Price,
                                                            dealercode, branchcode);

                            // save to Inventory of Day
                            var ttt = InventoryHelper.SaveInventoryDay(db, itemCode, itemImpDate, 1, (int)IisStatus,
                                                                      dealercode, branchcode);

                        }

                        // save shipping detail info
                        SD = CommonDAO.SaveOrUpdateShippingDetail(db, shipID, item, engineNumber, status,
                                                                  hasVoucher,
                                                                  exception, IInst, itemType, color,
                                                                  dealercode,
                                                                  orderNumber);
                        //db.SubmitChanges();

                    }

                    #endregion

                    #region Update order delivered status
                    List<String> listOrderNumber = new List<string>();
                    foreach (var m in tt)
                    {
                        listOrderNumber.Add((m.TipTopOrderNumber));
                    }

                    List<VDMS.I.Entity.ShippingDetail> loh = db.ShippingDetails.Where(p => listOrderNumber.Contains(p.OrderNumber)).ToList();

                    foreach (var m in tt)
                    {
                        orderNumber = m.TipTopOrderNumber;
                        var list = db.OrderHeaders.FirstOrDefault(p => p.OrderNumber == orderNumber); //oDao.GetAll();)
                        //list.CanUndoAutoReceive = true;
                        if (list != null)
                        {
                            DataSet ds = InventoryDao.CheckOrderDetail(list.OrderHeaderId);
                            int Orderstatus = (int)DeliveredOrderStatus.DeliveredAll;
                            int Orderqty, OrderShipped;
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                item = CommonDAO.GetItemByCode(db, dr["itemcode"].ToString());
                                Orderqty = int.Parse(dr["orderqty"].ToString());

                                OrderShipped =
                                    loh.Count(
                                        p =>
                                        p.OrderNumber == orderNumber && p.ItemCode == item.ItemCode &&
                                        p.Status == (int)ItemStatus.Imported);

                                if ((Orderqty - OrderShipped) != 0)
                                {
                                    Orderstatus = (int)DeliveredOrderStatus.NotDeliveredAll;
                                }
                            }
                            list.DeliveredStatus = Orderstatus;
                            //  (Orderstatus.Equals((int)DeliveredOrderStatus.NotDeliveredAll)) ? (int)DeliveredOrderStatus.NotDeliveredAll : (int)DeliveredOrderStatus.DeliveredAll;
                        }
                    }
                    db.SubmitChanges();
                    transaction.Commit();
                    //trans.Complete();

                    #endregion

                    return true;
                }
                catch(Exception e)
                {
                    LogError("IssueNumber: " + issueNumber + ", branchcode: " + branchcode + ", DealerCode:" + dealercode + ", Shipdate:" + baseImportDate + ", System Error:" + e.Message );//Log
                    transaction.Rollback();
                    return false;
                }
                finally
                {
                    if (db.Connection != null)
                    {
                        db.Connection.Close();
                    }
                }
            }
        }
Ejemplo n.º 7
0
 public static void SysInit()
 {
     var dc = new VehicleDataContext();
     try
     {
         var l = dc.OrderHeaders.Where(h => h.OrderDetails.Count() == 0 && !string.IsNullOrEmpty(h.OrderNumber));
         var p = dc.SaleOrderPayments.Where(h => h.OrderHeader.OrderDetails.Count() == 0 && !string.IsNullOrEmpty(h.OrderHeader.OrderNumber));
         dc.SaleOrderPayments.DeleteAllOnSubmit(p);
         dc.OrderHeaders.DeleteAllOnSubmit(l);
         dc.SubmitChanges();
     }
     catch { }
     finally
     {
         dc.Dispose();
     }
 }
Ejemplo n.º 8
0
    private bool SaveShippingDetail()
    {
        string exception, shipNumber, itemCode, engineNumber, itemType, color, orderNumber, shipTo, branchCode;
        Int32 status;
        bool hasVoucher;
        ImportItemStatus IisStatus;
        ItemInstance IInst = null;
        ItemStatus hisItemStatus;
        DateTime madeDate, impDate, itemImpDate;
        VDMS.I.Entity.ShippingDetail SD;
        long Price;

        Item item = null;
        long shipID;

        using (var db = new VehicleDataContext())
        {
            //try
            //{
            System.Data.Common.DbTransaction transaction;
            db.Connection.Open();
            transaction = db.Connection.BeginTransaction();
            db.Transaction = transaction;
            try
            {
                if (
                   (!DateTime.TryParse(txtImportDate.Text, new CultureInfo(UserHelper.Language),
                                       DateTimeStyles.AllowWhiteSpaces, out impDate)) || (impDate > DateTime.Now))
                {
                    //impDate = DateTime.Now;
                    AddError(ImportErrorCode.InvalidImportDate);
                    return false;
                }

                DateTime baseImportDate = (DateTime)ViewState[VS_BaseShipDate];
                if (impDate < baseImportDate)
                {
                    AddError(ImportErrorCode.ImportDateLessThanBaseDate);
                    return false;
                }
                foreach (GridViewRow row in GridView3.Rows)
                {
                    if (row.Enabled) // skip error vehicle
                    {
                        exception = ((TextBox)row.FindControl("txtException")).Text.Trim();
                        Int32.TryParse(((RadioButtonList)row.FindControl("rblStatus")).SelectedValue, out status);
                        hasVoucher = ((CheckBox)row.FindControl("chbVoucherStatus")).Checked;
                        itemCode = ((Label)row.FindControl("lblItemCode")).Text.Trim();
                        engineNumber = ((Label)row.FindControl("lblEngineNumber")).Text;
                        itemType = ((Label)row.FindControl("lblItemType")).Text;
                        color = ((Label)row.FindControl("lblColor")).Text + " (" +
                                ((Label)row.FindControl("lblColorName")).Text + ")";
                        orderNumber = ((Label)row.FindControl("lblOrderNumber")).Text;
                        DateTime.TryParse(((Label)row.FindControl("lblMadeDate")).Text,
                                          Thread.CurrentThread.CurrentCulture,
                                          DateTimeStyles.AllowWhiteSpaces, out madeDate);
                        long.TryParse(((Label)row.FindControl("lblPrice")).Text, out Price);

                        // custom imported date for item
                        string impDateString = ((TextBox)row.FindControl("txtItemImportDate")).Text.Trim();
                        if (string.IsNullOrEmpty(impDateString)) impDateString = txtImportDate.Text;

                        if (
                            !DateTime.TryParse(impDateString, Thread.CurrentThread.CurrentCulture,
                                               DateTimeStyles.AllowWhiteSpaces, out itemImpDate))
                        {
                            AddError(ImportErrorCode.InvalidImportDate);
                        }

                        if (itemImpDate < baseImportDate) AddError(ImportErrorCode.ImportDateLessThanBaseDate);
                        if (itemImpDate > DateTime.Now) AddError(ImportErrorCode.ImportDateTooLate);
                        if (InventoryHelper.IsInventoryLock(itemImpDate, UserHelper.DealerCode, UserHelper.BranchCode))
                            AddError(ImportErrorCode.ImportDateLocked);
                        if (errorCode.Count > 0)
                        {
                            return false;
                        }

                        //branchCode = ((Label)row.FindControl("lblBranchCode")).Text;

                        // day du cac thu roi thi khong chap nhan exception
                        if ((hasVoucher) && (status == 1)) exception = string.Empty;

                        IInst = null;
                        // get n' check item in table DATA_ITEM
                        item = CommonDAO.GetItemByCode(db, itemCode);
                        if (item == null)
                        {
                            AddError(ImportErrorCode.ItemNotExist);
                            return false;
                        }
                    }
                }
                shipNumber = ViewState[VS_ShippingNumber].ToString();
                branchCode = ViewState[VS_BranchCode].ToString();
                shipTo = hdAddress.Value;

                // save Shipping header
                VDMS.I.Entity.ShippingHeader SH = CommonDAO.SaveOrUpdateShippingHeader(db, logedAreaCode, shipNumber,
                                                                                       shipTo,
                                                                                       impDate, UserHelper.DealerCode,
                                                                                       (GridView1.Rows.Count +
                                                                                        GridView3.Rows.Count),
                                                                                       UserHelper.Username);
                db.SubmitChanges();

                if (SH == null)
                {
                    return false;
                }
                shipID = db.ShippingHeaders.SingleOrDefault(p => p.ShippingNumber == shipNumber).ShippingId;

                #region save shipping

                foreach (GridViewRow row in GridView3.Rows)
                {
                    if (row.Enabled) // skip error vehicle
                    {
                        exception = ((TextBox)row.FindControl("txtException")).Text.Trim();
                        Int32.TryParse(((RadioButtonList)row.FindControl("rblStatus")).SelectedValue, out status);
                        hasVoucher = ((CheckBox)row.FindControl("chbVoucherStatus")).Checked;
                        itemCode = ((Label)row.FindControl("lblItemCode")).Text.Trim();
                        engineNumber = ((Label)row.FindControl("lblEngineNumber")).Text;
                        itemType = ((Label)row.FindControl("lblItemType")).Text;
                        color = ((Label)row.FindControl("lblColor")).Text + " (" +
                                ((Label)row.FindControl("lblColorName")).Text + ")";
                        orderNumber = ((Label)row.FindControl("lblOrderNumber")).Text;
                        DateTime.TryParse(((Label)row.FindControl("lblMadeDate")).Text,
                                          Thread.CurrentThread.CurrentCulture,
                                          DateTimeStyles.AllowWhiteSpaces, out madeDate);
                        long.TryParse(((Label)row.FindControl("lblPrice")).Text, out Price);

                        // custom imported date for item
                        string impDateString = ((TextBox)row.FindControl("txtItemImportDate")).Text.Trim();
                        if (string.IsNullOrEmpty(impDateString)) impDateString = txtImportDate.Text;

                        if (
                            !DateTime.TryParse(impDateString, Thread.CurrentThread.CurrentCulture,
                                               DateTimeStyles.AllowWhiteSpaces, out itemImpDate))
                        {
                            AddError(ImportErrorCode.InvalidImportDate);
                        }

                        if (itemImpDate < baseImportDate) AddError(ImportErrorCode.ImportDateLessThanBaseDate);
                        if (itemImpDate > DateTime.Now) AddError(ImportErrorCode.ImportDateTooLate);
                        if (errorCode.Count > 0)
                        {
                            return false;
                        }

                        //branchCode = ((Label)row.FindControl("lblBranchCode")).Text;

                        // day du cac thu roi thi khong chap nhan exception
                        if ((hasVoucher) && (status == 1)) exception = string.Empty;
                        item = CommonDAO.GetItemByCode(db, itemCode);

                        if (status > 0) // nhap xe hoac tam nhap => save iteminstance n' transHistory
                        {
                            // clear instance for old shipping info
                            //foreach (var sd in CommonDAO.GetShippingDetails(db, engineNumber))
                            //{
                            //    sd.ProductInstanceId = null;
                            //}
                            // save ItemInstance of shipping
                            switch (status)
                            {
                                case 0:
                                    IisStatus = ImportItemStatus.NotArrived;
                                    break;
                                case 1:
                                    IisStatus = ImportItemStatus.Imported;
                                    break;
                                case 2:
                                    IisStatus = ImportItemStatus.AdmitTemporarily;
                                    break;
                                default:
                                    IisStatus = ImportItemStatus.NotArrived;
                                    break;
                            }
                            IInst = CommonDAO.SaveOrUpdateItemInstance(db, UserHelper.DealerCode, branchCode,
                                                                       engineNumber,
                                                                       shipNumber, orderNumber, itemType, item,
                                                                       itemImpDate,
                                                                       color, (int)IisStatus, madeDate,
                                                                       UserHelper.DatabaseCode);
                            db.SubmitChanges();

                            if (IInst == null)
                            {
                                return false;
                            }

                            // save transaction history. <actualCost> is temporary equal to "zero"
                            switch (status)
                            {
                                case 0:
                                    hisItemStatus = ItemStatus.Lacked;
                                    break;
                                case 1:
                                    hisItemStatus = ItemStatus.Imported;
                                    break;
                                case 2:
                                    hisItemStatus = ItemStatus.AdmitTemporarily;
                                    break;
                                default:
                                    hisItemStatus = ItemStatus.AdmitTemporarily;
                                    break;
                            }
                            var t = CommonDAO.SaveTransHist(db, IInst, itemImpDate, hisItemStatus, Price,
                                                            UserHelper.DealerCode, UserHelper.BranchCode);

                            // save to Inventory of Day
                            var tt = InventoryHelper.SaveInventoryDay(db, itemCode, itemImpDate, 1, (int)IisStatus,
                                                                      UserHelper.DealerCode, branchCode);

                        }

                        // save shipping detail info
                        SD = CommonDAO.SaveOrUpdateShippingDetail(db, shipID, item, engineNumber, status,
                                                                  hasVoucher,
                                                                  exception, IInst, itemType, color,
                                                                  UserHelper.DealerCode,
                                                                  orderNumber);
                        //db.SubmitChanges();
                    }
                }

                #endregion
                #region Update order delivered status
                List<String> listOrderNumber = new List<string>();
                foreach (GridViewRow row in GridView3.Rows)
                {
                    listOrderNumber.Add(((Label)row.FindControl("lblOrderNumber")).Text);
                }

                List<VDMS.I.Entity.ShippingDetail> loh = db.ShippingDetails.Where(p => listOrderNumber.Contains(p.OrderNumber)).ToList();

                foreach (GridViewRow row in GridView3.Rows)
                {
                    orderNumber = ((Label)row.FindControl("lblOrderNumber")).Text;
                    /* tntung
                     * 14/01/2008
                     * Update order delivered status
                     */
                    //IDao<Orderheader, long> oDao = DaoFactory.GetDao<Orderheader, long>();
                    //oDao.SetCriteria(new ICriterion[] {Expression.Eq("Ordernumber", orderNumber)});
                    var list = db.OrderHeaders.FirstOrDefault(p => p.OrderNumber == orderNumber); //oDao.GetAll();)

                    if (list != null)
                    {
                        DataSet ds = InventoryDao.CheckOrderDetail(list.OrderHeaderId);
                        int Orderstatus = (int)DeliveredOrderStatus.DeliveredAll;
                        int Orderqty, OrderShipped;
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            item = CommonDAO.GetItemByCode(db, dr["itemcode"].ToString());
                            Orderqty = int.Parse(dr["orderqty"].ToString());

                            OrderShipped =
                                loh.Count(
                                    p =>
                                    p.OrderNumber == orderNumber && p.ItemCode == item.ItemCode &&
                                    p.Status == (int)ItemStatus.Imported);

                            if ((Orderqty - OrderShipped) != 0)
                            {
                                Orderstatus = (int)DeliveredOrderStatus.NotDeliveredAll;
                            }
                        }
                        list.DeliveredStatus = Orderstatus;
                        //  (Orderstatus.Equals((int)DeliveredOrderStatus.NotDeliveredAll)) ? (int)DeliveredOrderStatus.NotDeliveredAll : (int)DeliveredOrderStatus.DeliveredAll;
                    }
                }
                db.SubmitChanges();
                transaction.Commit();
                //trans.Complete();
                #endregion

            }
            catch
            {
                transaction.Rollback();
                return false;
            }
            finally
            {
                if (db.Connection != null)
                {
                    db.Connection.Close();
                }
            }

            //}
            //catch (Exception e)
            //{
            //    MessageBox.Show(e.Message);
            //    return false;
            //}

        } // transaction
        return true;
    }