public async Task <IActionResult> Edit(int id, [Bind("DeliveryDetailId,DeliveryId,ProductId,Quantity")] DeliveryDetail deliveryDetail)
        {
            if (id != deliveryDetail.DeliveryDetailId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(deliveryDetail);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DeliveryDetailExists(deliveryDetail.DeliveryDetailId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["DeliveryId"] = new SelectList(_context.Delivery, "DeliveryId", "DeliveryId", deliveryDetail.DeliveryId);
            ViewData["ProductId"]  = new SelectList(_context.Set <Product>(), "ProductId", "ProductId", deliveryDetail.ProductId);
            return(View(deliveryDetail));
        }
Exemple #2
0
 public bool Update(DeliveryDetail obj)
 {
     try
     {
         var temp = db.DeliveryDetails.SingleOrDefault(dis => dis.ID == obj.ID);
         if (temp != null)
         {
             if (!string.IsNullOrEmpty(obj.Name))
             {
                 temp.Name = obj.Name;
             }
             if (!string.IsNullOrEmpty(obj.PhoneNumber))
             {
                 temp.PhoneNumber = obj.PhoneNumber;
             }
             if (!string.IsNullOrEmpty(obj.Adress))
             {
                 temp.Adress = obj.Adress;
             }
             db.SaveChanges();
         }
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemple #3
0
        public BaseResponse <DeliveryDetail> Update(DeliveryDetail obj)
        {
            bool result = new DeliveryDAO().Update(obj);
            var  status = result ? StatusResponse.Success : StatusResponse.Fail;
            BaseResponse <DeliveryDetail> response = new BaseResponse <DeliveryDetail>(status, "", null);

            return(response);
        }
        public ActionResult DeleteConfirmed(int id)
        {
            DeliveryDetail deliveryDetail = db.DeliveryDetails.Find(id);

            db.DeliveryDetails.Remove(deliveryDetail);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemple #5
0
        public ActionResult ReceiveGRN(DeliveryViewModel deliveryViewModel)
        {
            if (ModelState.IsValid)
            {
                int transportOrderId = 0;

                var dispatch = _dispatchService.Get(t => t.DispatchID == deliveryViewModel.DispatchID, null,
                                                    "DispatchDetails,DispatchAllocation").FirstOrDefault();


                var delivery = new Delivery();
                delivery.DeliveryBy           = deliveryViewModel.DeliveryBy;
                delivery.DeliveryDate         = deliveryViewModel.DeliveryDate;
                delivery.DispatchID           = deliveryViewModel.DispatchID;
                delivery.DeliveryID           = deliveryViewModel.DeliveryID;
                delivery.DocumentReceivedBy   = deliveryViewModel.DocumentReceivedBy;
                delivery.DocumentReceivedDate = deliveryViewModel.DocumentReceivedDate;
                delivery.DonorID         = deliveryViewModel.DonorID;
                delivery.DriverName      = deliveryViewModel.DriverName;
                delivery.FDPID           = deliveryViewModel.FDPID;
                delivery.HubID           = deliveryViewModel.HubID;
                delivery.InvoiceNo       = deliveryViewModel.InvoiceNo;
                delivery.PlateNoPrimary  = deliveryViewModel.PlateNoPrimary;
                delivery.PlateNoTrailler = deliveryViewModel.PlateNoTrailler;
                delivery.ReceivedBy      = deliveryViewModel.ReceivedBy;
                delivery.ReceivedDate    = deliveryViewModel.ReceivedDate;
                delivery.ReceivingNumber = deliveryViewModel.ReceivingNumber;
                delivery.RequisitionNo   = deliveryViewModel.RequisitionNo;
                delivery.TransporterID   = deliveryViewModel.TransporterID;
                delivery.WayBillNo       = deliveryViewModel.WayBillNo;
                if (dispatch != null)
                {
                    foreach (var dispatchDetail in dispatch.DispatchDetails)
                    {
                        var deliveryDetail = new DeliveryDetail();
                        deliveryDetail.DeliveryID       = delivery.DeliveryID;
                        deliveryDetail.DeliveryDetailID = Guid.NewGuid();
                        deliveryDetail.CommodityID      = dispatchDetail.CommodityID;
                        deliveryDetail.ReceivedQuantity = 0;
                        deliveryDetail.SentQuantity     = dispatchDetail.RequestedQuantityInMT;
                        deliveryDetail.UnitID           = dispatchDetail.UnitID;
                        delivery.DeliveryDetails.Add(deliveryDetail);
                    }


                    _deliveryService.AddDelivery(delivery);

                    var dispatchAllocation = dispatch.DispatchAllocation;
                    if (dispatchAllocation != null)
                    {
                        transportOrderId = dispatchAllocation.TransportOrderID.HasValue ? dispatchAllocation.TransportOrderID.Value : 0;
                    }
                }
                return(RedirectToAction("EditGRN", "Delivery", new { Area = "Logistics", id = delivery.DeliveryID }));
            }

            return(View(deliveryViewModel));
        }
Exemple #6
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            DeliveryDetail deliveryDetail = await db.DeliveryDetails.FindAsync(id);

            db.DeliveryDetails.Remove(deliveryDetail);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Exemple #7
0
        public void ApprovePurchaseOrder(Employee employee, int poNumber, string approve)
        {
            PurchaseOrder purchaseOrder = db.PurchaseOrders.Find(poNumber);

            purchaseOrder.OrderStatus     = approve;
            purchaseOrder.AuthorizedDate  = DateTime.Today;
            purchaseOrder.AuthorizedBy    = employee.EmployeeId;
            db.Entry(purchaseOrder).State = EntityState.Modified;
            db.SaveChanges();
            if (approve == "Approved")
            {
                Delivery delivery = new Delivery();
                delivery.PurchaseOrderId = poNumber;
                db.Deliveries.Add(delivery);
                db.SaveChanges();

                var lastCreatedDeliveryId = db.Deliveries
                                            .OrderByDescending(x => x.PurchaseOrderId == purchaseOrder.PurchaseOrderId)
                                            .FirstOrDefault().DeliveryId;
                foreach (var item in purchaseOrder.PurchaseDetails)
                {
                    DeliveryDetail deliveryDetail = new DeliveryDetail();
                    deliveryDetail.DeliveryId = lastCreatedDeliveryId;
                    deliveryDetail.ItemNo     = item.ItemNo;
                    db.DeliveryDetails.Add(deliveryDetail);
                    db.SaveChanges();
                }
                try //email to notify approval
                {
                    string emailBody = "Your purchase order dated " + purchaseOrder.OrderDate.Value.Date.ToString("dd/MM/yyyy") + " for supplier " + purchaseOrder.Supplier.SupplierName + " has been approved.";
                    uSvc.SendEmail(new List <string>(new string[] { purchaseOrder.Employee1.Email }), "Purchase Order Approved", emailBody);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
            else if (approve == "Rejected")
            {
                foreach (var item in purchaseOrder.PurchaseDetails)
                {
                    Inventory tempInv = db.Inventories.Find(item.ItemNo);
                    tempInv.HoldQuantity   -= item.Quantity;
                    db.Entry(tempInv).State = EntityState.Modified;
                    db.SaveChanges();
                    try //email to notify rejection
                    {
                        string emailBody = "Your purchase order dated " + purchaseOrder.OrderDate.Value.Date.ToString("dd/MM/yyyy") + " for supplier " + purchaseOrder.Supplier.SupplierName + " has been rejected.";
                        uSvc.SendEmail(new List <string>(new string[] { purchaseOrder.Employee1.Email }), "Purchase Order Rejected", emailBody);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }
            }
        }
Exemple #8
0
        public List <DeliveryDetail> GetDeliveryDetailsByDeliveryId(int id)
        {
            DeliveryDetail dd = new DeliveryDetail();

            var q = (from x in db.DeliveryDetails
                     where x.DeliveryDetailid == id
                     select x).ToList();

            return(q);
        }
 public bool DeleteDeliveryDetail(DeliveryDetail deliveryDetail)
 {
     if (deliveryDetail == null)
     {
         return(false);
     }
     _unitOfWork.DeliveryDetailRepository.Delete(deliveryDetail);
     _unitOfWork.Save();
     return(true);
 }
 public ActionResult Edit([Bind(Include = "ID,OrderID,DeliveryDate,DeliveryArea")] DeliveryDetail deliveryDetail)
 {
     if (ModelState.IsValid)
     {
         db.Entry(deliveryDetail).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.ID = new SelectList(db.Orders, "ID", "FirstName", deliveryDetail.ID);
     return(View(deliveryDetail));
 }
Exemple #11
0
        public static DeliveryDetail ConvertString2DeliveryInfos(string result)
        {
            dynamic data = JObject.Parse(result);
            JsonDtoMapper <DeliveryDetail> map = new JsonDtoMapper <DeliveryDetail>();
            DeliveryDetail deliveryInfos       = new DeliveryDetail();

            if (data.result == "success")
            {
                deliveryInfos = map.ToDto(data.reply.delivery_detail);
            }
            return(deliveryInfos);
        }
Exemple #12
0
        /// <summary>
        /// Creates the order and associated details, print, delivery quote.
        /// </summary>
        /// <param name="createOrderViewModel">The new order in view model form</param>
        /// <returns>The created order</returns>
        private Order ProcessOrder(CreateOrderViewModel createOrderViewModel)
        {
            Order order = new Order
            {
                FirstName    = createOrderViewModel.FirstName,
                LastName     = createOrderViewModel.LastName,
                EmailAddress = createOrderViewModel.EmailAddress,
                PhoneNumber  = createOrderViewModel.PhoneNumber,
                Quantity     = createOrderViewModel.Quantity
            };

            this.db.Orders.Add(order);
            this.db.SaveChanges();

            DeliveryDetail deliveryDetail = new DeliveryDetail
            {
                OrderID      = order.ID,
                DeliveryArea = createOrderViewModel.DeliveryArea,
                DeliveryDate = createOrderViewModel.DeliveryDate
            };

            this.db.DeliveryDetails.Add(deliveryDetail);

            PrintDetail printDetail = new PrintDetail
            {
                OrderID     = order.ID,
                NeedsPrint  = createOrderViewModel.NeedsPrint,
                PrintFormat = createOrderViewModel.PrintFormat,
                PrintSize   = createOrderViewModel.PrintSize
            };

            this.db.PrintDetails.Add(printDetail);
            if (createOrderViewModel.Attachment != null)
            {
                string pathToSave = Server.MapPath(Config.objectDataPath) + "\\Order\\" + order.ID.ToString() + "\\";
                IO.CreateFolder(pathToSave);
                createOrderViewModel.Attachment.SaveAs(pathToSave + Path.GetFileName(createOrderViewModel.Attachment.FileName));
            }


            Quote quote = new Quote
            {
                OrderID  = order.ID,
                Cost     = createOrderViewModel.Cost,
                IsMetro  = createOrderViewModel.IsMetro,
                Quantity = createOrderViewModel.Quantity
            };

            this.db.Quotes.Add(quote);
            this.db.SaveChanges();

            return(order);
        }
 public ActionResult Edit([Bind(Include = "ID,IDDevice,IDDelivery,Quantity,DateExpires")] DeliveryDetail deliveryDetail)
 {
     if (ModelState.IsValid)
     {
         db.Entry(deliveryDetail).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.IDDelivery = new SelectList(db.ProductCategories, "ID", "DeliveryToUser", deliveryDetail.IDDelivery);
     ViewBag.IDDevice   = new SelectList(db.Devices, "ID", "Name", deliveryDetail.IDDevice);
     return(View(deliveryDetail));
 }
        public async Task <IActionResult> Create([Bind("DeliveryDetailId,DeliveryId,ProductId,Quantity")] DeliveryDetail deliveryDetail)
        {
            if (ModelState.IsValid)
            {
                _context.Add(deliveryDetail);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["DeliveryId"] = new SelectList(_context.Delivery, "DeliveryId", "DeliveryId", deliveryDetail.DeliveryId);
            ViewData["ProductId"]  = new SelectList(_context.Set <Product>(), "ProductId", "ProductId", deliveryDetail.ProductId);
            return(View(deliveryDetail));
        }
Exemple #15
0
 public DeliveryDetail Create(DeliveryDetail obj)
 {
     try
     {
         var delivery = db.DeliveryDetails.Add(obj);
         db.SaveChanges();
         return(delivery);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Exemple #16
0
        public async Task <ActionResult> Edit([Bind(Include = "ID,IDDevice,IDDelivery,Quantity,DateExpires,CreatedBy,CreatedDate,UpdatedDate,Note,UpdatedBy")] DeliveryDetail deliveryDetail)
        {
            if (ModelState.IsValid)
            {
                db.Entry(deliveryDetail).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            ViewBag.IDDelivery = new SelectList(db.Deliveries, "ID", "UsernameFromDelivery", deliveryDetail.IDDelivery);
            ViewBag.IDDevice   = new SelectList(db.Devices, "ID", "Name", deliveryDetail.IDDevice);
            return(View(deliveryDetail));
        }
Exemple #17
0
        // GET: Admin/DeliveryDetails/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeliveryDetail deliveryDetail = await db.DeliveryDetails.FindAsync(id);

            if (deliveryDetail == null)
            {
                return(HttpNotFound());
            }
            return(View(deliveryDetail));
        }
        // GET: Admin/DeliveryDetail/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeliveryDetail deliveryDetail = db.DeliveryDetails.Find(id);

            if (deliveryDetail == null)
            {
                return(HttpNotFound());
            }
            return(View(deliveryDetail));
        }
Exemple #19
0
        public BaseResponse <DeliveryDetail> Create(DeliveryDetail obj)
        {
            var result = new DeliveryDAO().Create(obj);
            var list   = new List <DeliveryDetail>();

            if (result != null)
            {
                list.Add(result);
            }
            var status = result != null ? StatusResponse.Success : StatusResponse.Fail;
            BaseResponse <DeliveryDetail> response = new BaseResponse <DeliveryDetail>(status, "", list);

            return(response);
        }
Exemple #20
0
        public async Task <ActionResult> Create([Bind(Include = "ID,IDDevice,IDDelivery,Quantity,DateExpires")] DeliveryDetail deliveryDetail)
        {
            if (ModelState.IsValid)
            {
                db.DeliveryDetails.Add(deliveryDetail);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            ViewBag.IDDelivery = new SelectList(db.ProductCategories, "ID", "DeliveryToUser", deliveryDetail.IDDelivery);
            ViewBag.IDDevice   = new SelectList(db.Devices, "ID", "Name", deliveryDetail.IDDevice);
            return(View(deliveryDetail));
        }
        // GET: DeliveryDetails/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeliveryDetail deliveryDetail = db.DeliveryDetails.Find(id);

            if (deliveryDetail == null)
            {
                return(HttpNotFound());
            }
            ViewBag.ID = new SelectList(db.Orders, "ID", "FirstName", deliveryDetail.ID);
            return(View(deliveryDetail));
        }
        // GET: Admin/DeliveryDetail/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeliveryDetail deliveryDetail = db.DeliveryDetails.Find(id);

            if (deliveryDetail == null)
            {
                return(HttpNotFound());
            }
            ViewBag.IDDelivery = new SelectList(db.ProductCategories, "ID", "DeliveryToUser", deliveryDetail.IDDelivery);
            ViewBag.IDDevice   = new SelectList(db.Devices, "ID", "Name", deliveryDetail.IDDevice);
            return(View(deliveryDetail));
        }
Exemple #23
0
        // GET: Admin/DeliveryDetails/Edit/5
        public async Task <ActionResult> Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            DeliveryDetail deliveryDetail = await db.DeliveryDetails.FindAsync(id);

            if (deliveryDetail == null)
            {
                return(HttpNotFound());
            }
            ViewBag.IDDelivery = new SelectList(db.Deliveries, "ID", "UsernameFromDelivery", deliveryDetail.IDDelivery);
            ViewBag.IDDevice   = new SelectList(db.Devices, "ID", "Name", deliveryDetail.IDDevice);
            return(View(deliveryDetail));
        }
Exemple #24
0
        public SaleVM Add(SaleVM entity)
        {
            try
            {
                var sale = _mapper.Map <Sale>(entity);
                _unitOfWork.SetTrackAll();
                IList <DeliveryDetail> deliveriesBoxes = new List <DeliveryDetail>();

                foreach (var saleProduct in sale.SalesProducts)
                {
                    if (entity.HasDelivery)
                    {
                        var boxes = _unitOfWork.RepositoryCustom <IBoxRepository>().GetBoxesParentsByOrderIDWithProductItems(sale.OrderID);

                        foreach (var box in boxes)
                        {
                            DeliveryDetail deliveryDetail = DeliveryDetail.FactoryCreate(sale.ClientID, saleProduct.ProductID, sale.OrderID, saleProduct.Quantity);

                            deliveryDetail.MakeDeliveryBox(box);
                            deliveriesBoxes.Add(deliveryDetail);
                        }

                        _unitOfWork.Repository <Box>().UpdateRange(boxes);
                    }

                    saleProduct.CalcTotalValue();
                }

                sale.CalculatePayment();
                _unitOfWork.Repository <DeliveryDetail>().AddRange(deliveriesBoxes);
                _unitOfWork.Repository <Sale>().Add(sale);
                _unitOfWork.CommitSync();

                return(entity);
            }
            catch (CustomException exc)
            {
                _unitOfWork.Rollback();
                throw exc;
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback();
                throw CustomException.Create <SaleApplicationService>("Unexpected error fetching add sale", nameof(this.Add), ex);
            }
        }
 public IActionResult Create(string orderdetailid, string deliveryid, string address, string note, string price, string datestart, string dateend)
 {
     try
     {
         DeliveryDetail deliverydetail = new DeliveryDetail()
         {
             OrderDetailId = orderdetailid, DeliveryId = deliveryid, Address = address, Note = note, Price = float.Parse(price), DateStart = DateTime.Parse(datestart), DateEnd = DateTime.Parse(dateend)
         };
         _context.DeliveryDetails.Add(deliverydetail);
         _context.SaveChanges();
         return(Json(new { success = true, message = "khởi tạo thành công chi tiết vận chuyển" }));
     }
     catch (Exception ex)
     {
         return(Json(new { success = false, message = ex.Message }));
     }
 }
 public void savecodedetails([FromBody] DeliveryDetail objdeliverdetail)
 {
     try
     {
         string code     = objdeliverdetail.QRCode;
         var    Codedata = InsuranceContext.QRCodes.Single(where : $"Qrcode=" + code);
         if (Codedata != null)
         {
             Codedata.ReadBy    = objdeliverdetail.ReadBy;
             Codedata.Deliverto = objdeliverdetail.DeliverTo;
             // Codedata.Comment = objdeliverdetail.Comment;
             InsuranceContext.QRCodes.Update(Codedata);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        private void SaveOrders(Delivery delivery)
        {
            var biz = new DeliveryDetailBiz();

            biz.RemoveItemsByDeliveryId(delivery.Id);

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                var item = row.DataBoundItem as SearchOrder;

                var detail = new DeliveryDetail();
                detail.DeliveryId = delivery.Id;
                detail.OrderId    = item.Id;
                if (item.DeliveryTime.HasValue)
                {
                    detail.Time = item.DeliveryTime.Value;
                }
                detail.Index = row.Index;

                biz.SaveItem(detail);
            }
        }
        public ActionResult Edit(DeliveryDetail obj)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var c = new List <CylinderMaster>();
                    var objCylinderlist = db.CustomerCylinderDetails.Where(a => a.cust_id == obj.cust_id).ToList();
                    foreach (var t in objCylinderlist)
                    {
                        CylinderMaster temp = db.CylinderMasters.Where(a => a.cylinderType == t.cylinderType).FirstOrDefault();
                        c.Add(temp);
                    }
                    obj.cylinders = c;
                    obj.users     = repo.GetAllUsers();
                    obj.customers = repo.GetAllCustomers();
                    var tempTotal = Convert.ToDecimal(TempData["TotalAmount"].ToString());
                    if (tempTotal != obj.totalAmount)
                    {
                        var gst   = Convert.ToDecimal(System.Configuration.ConfigurationManager.AppSettings["gst"]);
                        var total = Convert.ToDecimal(obj.totalAmount) / gst;
                        var diff  = Convert.ToDecimal(obj.totalAmount) - total;
                        obj.cgst = diff / 2;
                        obj.sgst = diff / 2;
                    }
                    repo.Update(obj);
                    ViewBag.SuccessMsg = "Record Updated Successfully";
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = "Sorry Some Problem Occured";
            }
            var DeliveryDetaillist = repo.GetAllDeliveryDetails();

            return(View("Listing", DeliveryDetaillist));
        }
Exemple #29
0
        public void ReceiveDelivery(Employee employee, int deliveryId, string deliveryRefNo, string dateDelivered, int[] deliveryDetailId, string[] itemNo, int[] quantity, string[] remarks)
        {
            for (int i = 0; i < deliveryDetailId.Count(); i++)
            {
                DeliveryDetail deliveryDetail = db.DeliveryDetails.Find(deliveryDetailId[i]);
                deliveryDetail.Quantity        = quantity[i];
                deliveryDetail.Remarks         = remarks[i];
                db.Entry(deliveryDetail).State = EntityState.Modified;
                db.SaveChanges();

                Inventory inventory = db.Inventories.Find(deliveryDetail.ItemNo);
                inventory.Quantity       += quantity[i];
                inventory.HoldQuantity   -= quantity[i];
                db.Entry(inventory).State = EntityState.Modified;
                db.SaveChanges();
            }
            Delivery delivery = db.Deliveries.Find(deliveryId);

            delivery.DeliveredDate   = DateTime.Today;
            delivery.DeliveryOrderNo = deliveryRefNo;
            delivery.ReceivedBy      = employee.EmployeeId;
            db.Entry(delivery).State = EntityState.Modified;
            db.SaveChanges();
        }
        /// <summary>
        /// 新增交付记录
        /// </summary>
        /// <param name="dto">新增交付数据对象</param>
        public void Add(DeliveryAddDTO dto)
        {
            using (DbConnection conn = DbHelper.CreateConnection())
            {
                DbTransaction trans = null;
                try
                {
                    conn.Open();
                    trans = conn.BeginTransaction();
                    if (trans == null)
                    {
                        throw new ArgumentNullException("DbTransaction");
                    }

                    #region Delivery and Cost

                    Delivery entity = new Delivery();
                    entity.Create(dto.Date, dto.ExpressCompany, dto.ExpressBill, dto.IncludeOrder, dto.Summary, dto.Remark, dto.Costs, dto.Creator);
                    this.deliveryRepository.Insert(trans, entity);
                    foreach (Cost cost in entity.Costs)
                    {
                        this.costRepository.Insert(trans, cost);
                    }

                    #endregion

                    Dictionary <string, Sale>   sales = new Dictionary <string, Sale>();
                    Dictionary <string, string> items = new Dictionary <string, string>();
                    foreach (DeliveryDetailAddDTO detail in dto.DeliveryDetails)
                    {
                        #region Purchase
                        Purchase purchase = this.purchaseRepository.Select(trans, detail.PurchaseId);
                        if (purchase == null || purchase.Category != detail.ItemCategory || purchase.Item != detail.Item)
                        {
                            throw new EasySoftException(string.Format("关联的采购单不存在或项目不正确。采购单ID:{0}, 采购项:{1}", purchase.Id, detail.ItemName));
                        }

                        if (purchase.Inventory < detail.DeliveryQuantity)
                        {
                            throw new EasySoftException(string.Format("库存不足。采购单ID:{0}, 采购项:{1}", purchase.Id, detail.ItemName));
                        }

                        purchase.Delivery(detail.DeliveryQuantity, dto.Creator);
                        this.purchaseRepository.Update(trans, purchase);
                        #endregion

                        #region DeliveryDetail
                        DeliveryDetail detailEntity = new DeliveryDetail();
                        detailEntity.Create(entity.Id, purchase.Id, detail.ItemCategory, detail.DeliveryQuantity, detail.PackQuantity, detail.PackUnit, dto.Creator);
                        this.deliveryDetailRepository.Insert(trans, detailEntity);
                        #endregion
                    }

                    #region SaleOrder
                    if (dto.IncludeOrder == Constant.COMMON_Y)
                    {
                        foreach (SaleOrderExpressDTO order in dto.SaleOrders)
                        {
                            SaleOrder orderEntity = this.saleOrderRepository.Select(trans, order.Id);
                            if (orderEntity == null || orderEntity.NeedExpress == Constant.COMMON_N || orderEntity.Item != order.Item || orderEntity.Quantity != order.Quantity || orderEntity.Status != SaleOrderStatus.Ordered)
                            {
                                throw new EasySoftException(string.Format("关联的订单不存在或状态不正确,订单信息Id:{0}, 订单项:{1}", order.Id, order.ItemName));
                            }
                            orderEntity.SentExpress(orderEntity.Id, dto.Creator);
                            this.saleOrderRepository.Update(trans, orderEntity);
                        }
                    }
                    #endregion

                    #region Sale
                    foreach (SaleAddDTO sale in dto.Sales)
                    {
                        Sale saleEntity = new Sale();
                        saleEntity.Create(entity.Id, sale.Item, sale.Quantity, sale.Unit, dto.Creator);
                        this.saleRepository.Insert(trans, saleEntity);
                    }
                    #endregion

                    trans.Commit();
                }
                catch
                {
                    if (trans != null)
                    {
                        trans.Rollback();
                    }
                    throw;
                }
            }
        }
        private void SaveOrders(Delivery delivery)
        {
            var biz = new DeliveryDetailBiz();
            biz.RemoveItemsByDeliveryId(delivery.Id);

            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                var item = row.DataBoundItem as SearchOrder;

                var detail = new DeliveryDetail();
                detail.DeliveryId = delivery.Id;
                detail.OrderId = item.Id;
                if (item.DeliveryTime.HasValue)
                {
                    detail.Time = item.DeliveryTime.Value;
                }
                detail.Index = row.Index;

                biz.SaveItem(detail);
            }
        }