public ActionResult Order_detail(string ordernum, int Total)
        {
            TempData["Total"] = Total;
            var service     = new OrderDetailService();
            var OrderDetail = service.GetOrderDetail(ordernum.Trim());

            return(View(OrderDetail));
        }
 public OrderDetailFacadeService(
     OrderDetailService orderDetailService,
     OrderRefundDetailService orderRefundDetailService,
     WxPayService wxPayService)
 {
     _orderDetailService       = orderDetailService;
     _orderRefundDetailService = orderRefundDetailService;
     _wxPayService             = wxPayService;
 }
Example #3
0
 public StockApiController(ProductService prodSvc, ILogger logger, CategoryService categorySvc,
                           WasteService spoilSvc, AuditTrailService auditSvc, OrderDetailService ordDetSvc)
 {
     _logger    = logger;
     _prodSvc   = prodSvc;
     _spoilSvc  = spoilSvc;
     _ordDetSvc = ordDetSvc;
     _auditSvc  = auditSvc;
 }
Example #4
0
        public JsonResult Remove(int oid)
        {
            int count = OrderDetailService.Delete(oid);

            return(new JsonResult
            {
                Data = count > 0 ? true : false
            });
        }
Example #5
0
 public OrderTravelNoticeFacadeService(
     OrderTravelNoticeService orderTravelNoticeService,
     OrderDetailService orderDetailService,
     CtripGateway ctripGateway)
 {
     _orderTravelNoticeService = orderTravelNoticeService;
     _orderDetailService       = orderDetailService;
     _ctripGateway             = ctripGateway;
 }
 public UserController()
 {
     db                 = new KAIROS_SHOPEntities();
     accountService     = new AccountService(db);
     shoppingService    = new ShoppingCartService(db);
     orderService       = new OrderService(db);
     orderDetailService = new OrderDetailService(db);
     reviewService      = new ReviewService(db);
 }
        public JsonResult CheckOrder(int id)
        {
            var check = new OrderDetailService().CheckOrder(id);

            return(Json(new
            {
                status = check
            }));
        }
 public OrderDetailApiController(ICacheManager cacheManager, ProductService productSvc,
                                 IPosReportService orderSvc, OrderDetailService orderDetailSvc, ILogger logger)
 {
     _cacheManager   = cacheManager;
     _orderSvc       = orderSvc;
     _orderDetailSvc = orderDetailSvc;
     _productSvc     = productSvc;
     _logger         = logger;
 }
Example #9
0
 public OrderController(UserManager <IdentityUser> userManager, SignInManager <IdentityUser> signInManager, ShoppingBoxService shoppingBoxService, OrderService orderService, OrderDetailService orderDetailService, BookService bookService)
 {
     _userManager        = userManager;
     _signInManager      = signInManager;
     _shoppingBoxService = shoppingBoxService;
     _orderService       = orderService;
     _orderDetailService = orderDetailService;
     _bookService        = bookService;
 }
Example #10
0
 public ActionResult ViewOrderDetail(int id)
 {
     if (id > 0)
     {
         var model = new OrderDetailService().GetOrderDetail(id);
         return(View(model));
     }
     return(View());
 }
Example #11
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            SendOrderReportData ds = new SendOrderReportData();
            DataTable           SendOrderHeader = ds.Tables["SendOrderHeader"];
            DataTable           SendOrderDetail = ds.Tables["SendOrderDetail"];
            DataTable           SendOrderFooter = ds.Tables["SendOrderFooter"];

            var   cmd      = new OrderService();
            ORDER item     = cmd.Select(Convert.ToInt32(ViewState["orderId"]));
            var   cmdStore = new StoreService();

            item.STORE = cmdStore.Select(item.STORE_ID);
            var cmdOrderdetail = new OrderDetailService();

            item.ORDER_DETAIL = cmdOrderdetail.GetALLInclude(item.ORDER_ID);
            DataRow drSendOrderHeader = SendOrderHeader.NewRow();

            drSendOrderHeader["STORE_NAME"] = item.STORE.STORE_NAME;
            drSendOrderHeader["STORE_ADDR"] = item.STORE.STORE_ADDR1;
            drSendOrderHeader["STORE_TEL"]  = item.STORE.STORE_TEL1;
            if (item.STORE.STORE_TEL2 != "")
            {
                drSendOrderHeader["STORE_TEL"] += ("," + item.STORE.STORE_TEL2);
            }
            drSendOrderHeader["STORE_CODE"]  = item.STORE.STORE_CODE;
            drSendOrderHeader["ORDER_DATE"]  = item.ORDER_DATE.Value.ToShortDateString();
            drSendOrderHeader["SEND_DATE"]   = DateTime.Now.ToShortDateString();
            drSendOrderHeader["ZONE_NAME"]   = item.STORE.ZONE.ZONE_NAME;
            drSendOrderHeader["VEHICLE_REG"] = ddlVehicle.SelectedItem.Text;
            SendOrderHeader.Rows.Add(drSendOrderHeader);
            int     seq       = 1;
            decimal sumWeight = 0;

            foreach (ORDER_DETAIL od in item.ORDER_DETAIL)
            {
                DataRow drSendOrderDetail = SendOrderDetail.NewRow();
                drSendOrderDetail["SEQ"]        = seq.ToString();
                drSendOrderDetail["NAME"]       = od.PRODUCT.PRODUCT_NAME;
                drSendOrderDetail["QTY"]        = (od.PRODUCT_QTY - od.PRODUCT_SEND_QTY).ToString();
                drSendOrderDetail["PACKAGE"]    = od.PRODUCT.PRODUCT_PACKING_DESC;
                drSendOrderDetail["WEIGHT"]     = od.PRODUCT.PRODUCT_WEIGHT;
                drSendOrderDetail["SUM_WEIGHT"] = (od.PRODUCT.PRODUCT_WEIGHT * (od.PRODUCT_QTY - od.PRODUCT_SEND_QTY)).ToString();
                sumWeight += (od.PRODUCT.PRODUCT_WEIGHT * (od.PRODUCT_QTY - od.PRODUCT_SEND_QTY)).Value;
                SendOrderDetail.Rows.Add(drSendOrderDetail);
                seq++;
            }

            DataRow drSendOrderFooter = SendOrderFooter.NewRow();

            drSendOrderFooter["SUM_WEIGHT_TH"]     = ThaiBaht(sumWeight.ToString());
            drSendOrderFooter["SUM_WEIGHT_NUMBER"] = sumWeight.ToString();
            SendOrderFooter.Rows.Add(drSendOrderFooter);

            Session["SendOrderReportData"] = ds;
            Response.Redirect("../Reports/SendOrder.aspx");
        }
Example #12
0
 public OrderControllers(SetupRepository setupRepository, OrderDetailService orderDetailService, IMapper mapper, PaginatedMetaService paginatedMetaService, OrderService orderService, OrderRepository orderRepository, OrderDetailRepository orderDetailRepository)
 {
     _orderDetailRepository = orderDetailRepository;
     _orderRepository       = orderRepository;
     _orderService          = orderService;
     _paginatedMetaService  = paginatedMetaService;
     _mapper             = mapper;
     _orderDetailService = orderDetailService;
     _setupRepo          = setupRepository;
 }
Example #13
0
        /// <summary>
        /// 获取Plate-X券总金额
        /// </summary>
        /// <returns></returns>
        protected int GetNewOrderCount(int num)
        {
            UserInfo user = Session["user"] as UserInfo;

            if (user != null)
            {
                return(OrderDetailService.GetSaleOrder(user.id, num).Tables[0].Rows.Count);
            }
            return(0);
        }
Example #14
0
 public bool UpdateOrderDetail(OrderDetailData od)
 {
     return(OrderDetailService.Update(new Order_Detail()
     {
         ID = od.ID,
         book_ID = od.book_ID,
         order_ID = od.order_ID,
         quantity = od.quantity
     }));
 }
Example #15
0
        //MenuService _menuService;


        public HomeController()
        {
            _categoryService    = new CategoryService();
            _customerService    = new CustomerService();
            _productService     = new ProductService();
            _orderService       = new OrderService();
            _orderDetailService = new OrderDetailService();
            _sliderService      = new SliderService();
            //_menuService = new MenuService();
        }
Example #16
0
        public override void CalculateAndApplyUnitDiscount(DiscountCalculateItem discountCalculateItem)
        {
            decimal            unitDiscountAmount = discountCalculateItem.DiscountAmount / discountCalculateItem.TotalQuantity;
            List <OrderDetail> orderDetailList    = OrderDetailService.GetListByOrderIdCategoryId(discountCalculateItem.OrderId, discountCalculateItem.CategoryId);

            foreach (var orderDetail in orderDetailList)
            {
                orderDetail.TotalDiscountAmount = orderDetail.TotalDiscountAmount + unitDiscountAmount * orderDetail.Quantity;
                OrderDetailService.Update(orderDetail);
            }
        }
 public MessageFacadeService(
     OrderService orderService,
     OrderDetailService orderDetailService,
     SmsService smsService,
     AuthorizationService authorizationService)
 {
     _orderService         = orderService;
     _orderDetailService   = orderDetailService;
     _smsService           = smsService;
     _authorizationService = authorizationService;
 }
Example #18
0
        /// <summary>
        /// 清空一个用户的所有订单
        /// </summary>
        /// <param name="orderId"></param>
        public void EmptyOrdersByUserId(int userId)
        {
            var orders             = GetOrdersByUserId(userId);
            OrderDetailService ods = new OrderDetailService();

            foreach (var o in orders)
            {
                ods.DeleteByOrderId(o.Id);
            }
            os.EmptyOrdersByUserId(userId);
        }
Example #19
0
 //实例化
 public OrderController()
 {
     serviceOrder     = new OrderService(db);
     serviceDetail    = new OrderDetailService(db);
     serviceRoom      = new RoomService(db);
     serviceMoney     = new MoneyService(db);
     serviceFlow      = new FlowService(db);
     serviceDiscount  = new DiscountService(db);
     servicePay       = new PayService(db);
     UserTicketDetail = new UserTicketDetailService(db);
 }
Example #20
0
        /// <summary>
        /// 获取Action信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        protected string GetDoneInfo(object id, object status)
        {
            int           s  = Convert.ToInt32(status);
            StringBuilder sb = new StringBuilder();

            if (s == 0)
            {
                //sb.Append("<a href=\"doneOrder_" + id + ".html?action=delete\" class=\"del\">Delete订单</a><a href=\"payment_" + id + ".html\" class=\"dai\">去付款</a><a href=\"doneOrder_" + id + ".html?action=cancel\" class=\"cancle\">取消订单</a>");
                sb.Append("<a href=\"payment_" + id + ".html\" class=\"dai\">去付款</a><a  href=\"doneOrder_" + id + ".html?action=cancel\"  onclick=\"return confirm('确定要取消该订单吗!');\" class=\"cancle\">取消订单</a>");
            }
            else if (s == 2)
            {
                //sb.Append("<a href=\"doneOrder_" + id + ".html?action=delete\" class=\"del\">Delete订单</a><a href=\"payment_" + id + ".html\" class=\"dai\">去付款</a><a href=\"doneOrder_" + id + ".html?action=cancel\" class=\"cancle\">取消订单</a>");
                sb.Append("<a  href=\"doneOrder_" + id + ".html?action=recieve\"  onclick=\"return confirm('您确定收到货物了吗!');\" class=\"del\">确认收货</a>");
            }
            else if (s == 3)
            {
                //sb.Append("<a href=\"doneOrder_" + id + ".html?action=delete\" class=\"del\">Delete订单</a><a href=\"payment_" + id + ".html\" class=\"dai\">去付款</a><a href=\"doneOrder_" + id + ".html?action=cancel\" class=\"cancle\">取消订单</a>");
                DataSet ds = OrderDetailService.GetList("orderId = " + id);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int flag = 1;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (!CommentService.Exists(ds.Tables[0].Rows[i]["productId"], id))
                        {
                            flag = 0;
                            break;
                        }
                    }
                    if (flag == 0)
                    {
                        sb.Append("<a href=\"ordercomment_" + id + ".html\" class=\"del\">评论</a>");
                    }
                    else
                    {
                        //更新状态为4Order Delivered
                        OrderService.UpdateStatus(Convert.ToInt32(id), 4);
                    }
                }
                sb.Append("<a onclick=\"return confirm('确定要Delete该订单吗!');\" href=\"doneOrder_" + id + ".html?action=delete\" class=\"del\">Delete订单</a>");
            }
            else
            {
                sb.Append("<a onclick=\"return confirm('确定要Delete该订单吗!');\" href=\"doneOrder_" + id + ".html?action=delete\" class=\"del\">Delete订单</a>");
            }
            //if (s == 0)
            //{
            //    sb.Append("<a href=\"payment_" + id + ".html\" class=\"dai\">去付款</a><a href=\"doneOrder_" + id + ".aspx?action=cancel\" class=\"cancle\">取消订单</a>");
            //}
            return(sb.ToString());
        }
 public AdminController()
 {
     db                  = new KAIROS_SHOPEntities();
     watchService        = new WatchService(db);
     modificationService = new ModificationService(db);
     watchModelService   = new WatchModelService(db);
     movementService     = new MovementService(db);
     accountService      = new AccountService(db);
     roleService         = new RoleService(db);
     orderService        = new OrderService(db);
     orderStatusService  = new OrderStatusService(db);
     orderDetailService  = new OrderDetailService(db);
 }
Example #22
0
        public override DiscountCalculateItem CalculateAndApplyDiscount(Order order)
        {
            //step1: sepette her kategoride toplam kaç ürün var
            List <OrderDetail> orderDetailList = OrderDetailService.GetByOrderId(order.Id);
            var orderDetailSummaryList         = orderDetailList.GroupBy(p => p.CategoryId).Select(g => new
            {
                CategoryId = g.Key,
                Quantity   = g.Sum(t => t.Quantity)
            });

            //step2: her kategori için geçerli kampanyaları bul ve indirimi hesapla
            List <DiscountCalculateItem> discountCalculateItemList = new List <DiscountCalculateItem>();

            foreach (var item in orderDetailSummaryList)
            {
                List <Campaign> currentCampaignList = _campaignService.GetCurrentCampaignList(item.CategoryId, item.Quantity);
                if (currentCampaignList.Count != 0)
                {
                    foreach (var campaignItem in currentCampaignList)
                    {
                        DiscountCalculateItem discountCalculateItem = new DiscountCalculateItem();
                        discountCalculateItem.OrderId       = order.Id;
                        discountCalculateItem.CategoryId    = item.CategoryId;
                        discountCalculateItem.TotalQuantity = item.Quantity;
                        if (campaignItem.DiscountType == (int)DiscountType.RATE)
                        {
                            discountCalculateItem.DiscountAmount = (order.OriginalPrice * campaignItem.Rate) / 100;
                        }
                        else if (campaignItem.DiscountType == (int)DiscountType.AMOUNT)
                        {
                            discountCalculateItem.DiscountAmount = campaignItem.DiscountAmount;
                        }
                        discountCalculateItemList.Add(discountCalculateItem);
                    }
                }
                else
                {
                    return(null);
                }
            }

            //step3:Max indirim tutarlı olanı bul
            var maxDiscountCampaign = discountCalculateItemList.OrderByDescending(i => i.DiscountAmount).First();

            //indirimi order'a uygula
            order.TotalPrice          = order.TotalPrice - maxDiscountCampaign.DiscountAmount;
            order.TotalCampaignAmount = maxDiscountCampaign.DiscountAmount;
            OrderService.Update(order);

            return(maxDiscountCampaign);
        }
Example #23
0
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            OrderInfo order = OrderService.GetModel(orderId);

            if (order != null)
            {
                ViewState["orderDate"]    = order.addTime.ToString("yyyy-MM-dd HH:mm");
                Session["payOrder"]       = order;
                ViewState["orderId"]      = orderId;
                ViewState["orderTotal"]   = order.orderTotal.ToString("0.00");
                ViewState["productCount"] = OrderDetailService.GetProductCount(order.id);
                ViewState["orderNo"]      = order.orderNo;
            }
        }
Example #24
0
        /// <summary>
        /// 获取订单的状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        protected string GetDone(object orderId)
        {
            DataSet ds = OrderDetailService.GetList("orderId = " + orderId);

            if (ds.Tables[0].Rows.Count > 0)
            {
                int infoType = Convert.ToInt32(ds.Tables[0].Rows[0]["infoType"]);
                if (infoType == 0)
                {
                    return("<platex style=' padding:5px 10px; background-color:red; color:#ffffff;'>Order Placed</platex>");
                }
            }
            return("<platex style=' padding:5px 10px; background-color:green; color:#ffffff;'>Order Delivered</platex>");
        }
Example #25
0
        public string GetCommidityIdList(string OrderNo)
        {
            var commidityList = "";
            var orderDtlList  = OrderDetailService.GetByOrderNo(OrderNo);

            if (orderDtlList != null)
            {
                foreach (var item in orderDtlList)
                {
                    commidityList += item.commodityId + ",";
                }
            }
            return(commidityList);
        }
Example #26
0
        private void InitialDataPopup()
        {
            int orderId   = Convert.ToInt32(ViewState["orderId"]);
            var cmd       = new OrderDetailService();
            var cmdDetail = new DeliveryOrderDetailService();
            var cmdDO     = new DeliveryOrderService();

            DataSouceDetail = cmd.GetALLInclude().Where(x => x.ORDER_ID == orderId).ToList();

            foreach (var item in cmdDetail.GetALLInclude().Where(y => y.DELIVERY_ORDER.ORDER_ID == orderId))
            {
                DataSouceDetail.RemoveAll(x => x.PRODUCT_ID == item.PRODUCT_ID);
            }
            gridProductDetail.DataSource = DataSouceDetail;
            gridProductDetail.DataBind();
        }
Example #27
0
        private void InitialDataPopup()
        {
            int orderId = Convert.ToInt32(ViewState["orderId"]);
            var cmd = new OrderDetailService();
            var cmdDO = new DeliveryOrderService();
            DataSouceDetail = cmd.GetALLInclude().Where(x => x.ORDER_ID == orderId && x.PRODUCT_QTY != x.PRODUCT_SEND_QTY).ToList();
            gridProductDetail.DataSource = DataSouceDetail;
            gridProductDetail.DataBind();

            var cmdVehicle = new VehicleService();
            var list = cmdVehicle.GetALL();
            foreach (var item in list)
            {
                ddlVehicle.Items.Add(new ListItem(item.VEHICLE_REGNO, item.VEHICLE_ID.ToString()));
            }
        }
Example #28
0
        /// <summary>
        /// 控件行命令事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            UserInfo user = Session["user"] as UserInfo;

            if (user == null)
            {
                return;
            }
            if (e.CommandName.Equals("finish"))
            {
                int     id = Convert.ToInt32(e.CommandArgument);
                DataSet ds = OrderDetailService.GetList("orderId = " + id + " and productId in(select id from Product where useId = " + user.id + ")");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int infoType = Convert.ToInt32(ds.Tables[0].Rows[0]["infoType"]);
                    if (infoType == 0)
                    {
                        OrderDetailService.UpdateInfoTypeByOrderId(user.id, id, 1);      //只更新自己的商品状态
                        DataSet ds2 = OrderDetailService.GetList("orderId = " + id);     //循环遍历所有商品,查看是否都备货完毕,更新整个订单的状态。
                        if (ds2.Tables[0].Rows.Count > 0)
                        {
                            bool flag = true;
                            foreach (DataRow dr in ds2.Tables[0].Rows)
                            {
                                if (Convert.ToInt32(dr["infoType"]) == 0)
                                {
                                    flag = false;
                                }
                            }
                            if (flag)    //更新整个订单状态
                            {
                                OrderService.UpdateStatus(id, 1);
                                OrderDetailService.UpdateStatus(id, 1);
                            }
                        }
                    }
                    else
                    {
                        OrderDetailService.UpdateInfoTypeByOrderId(user.id, id, 0);   //只更新自己的商品状态
                        //更新整个订单状态
                        OrderService.UpdateStatus(id, 0);
                        OrderDetailService.UpdateStatus(id, 0);
                    }
                }
            }
            BindData();
        }
        // GET: OrderDetails
        public ActionResult OrderDetails()
        {
            var     service = new OrderDetailService();
            var     orders  = service.GetMemberOrders(1);
            decimal total   = 0;

            foreach (var item in orders)
            {
                var s = item.OrderId.ToString();
                total      += Convert.ToDecimal(item.UnitPrice * item.Quantity * (1 - item.Discount));
                ViewData[s] = service.GetOrdersOrderDetails(item.OrderId);
            }
            ViewBag.TotalAll = total;
            ViewBag.orders   = orders;

            return(View());
        }
Example #30
0
 public StopBuy(IConfiguration configuration, IBotFrameworkHttpAdapter adapter, ConcurrentDictionary <string, ConversationReference> conversationReferences, OrderService orderService, OrderDetailService orderDetailServices, CreateCardService createCardService, PayMentService payMentService)
 {
     _Adapter = adapter;
     _ConversationReferences = conversationReferences;
     _AppId               = configuration["MicrosoftAppId"];
     _OrderService        = orderService;
     _OrderDetailServices = orderDetailServices;
     _CreateCardService   = createCardService;
     _paymentService      = payMentService;
     // If the channel is the Emulator, and authentication is not in use,
     // the AppId will be null.  We generate a random AppId for this case only.
     // This is not required for production, since the AppId will have a value.
     if (string.IsNullOrEmpty(_AppId))
     {
         _AppId = Guid.NewGuid().ToString(); //if no AppId, use a random Guid
     }
 }
        private bool saveData()
        {
            calculateTotal();
            if (validator1.Validate() && ValidateData())
            {
                if (cbxCustomer.SelectedValue == null || cbxCustomer.SelectedIndex <= 0)
                {
                    MessageBox.Show("Bạn cần có một khách hàng cho phiếu này!");
                    return false;
                }
                DialogResult dialogResult = Preview();
                if (dialogResult == DialogResult.OK)
                {
                    XKNumber = PrintPreview.XKNumber;
                    BHNumber = PrintPreview.BHNumber;
                    double discount = 0;
                    Double.TryParse(txtDiscount.WorkingText, out discount);
                    DateTime createdDate = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();

                    double vat = 0;
                    Double.TryParse(txtVAT.WorkingText, out vat);
                    int userId = 0;
                    if (Global.CurrentUser != null)
                    {
                        userId = Global.CurrentUser.Id;
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                    if (order != null)//update
                    {
                        #region Update

                        order.CustId = (int)cbxCustomer.SelectedValue;
                        order.Discount = discount;
                        order.Note = txtNote.Text;
                        order.VAT = vat;
                        order.OrderCode = txtOrderCode.Text;
                        order.Reason = txtReason.Text;
                        order.WareHouse = txtWare.Text;
                        order.Total = totalWithTax;
                        order.UpdatedDate = createdDate;

                        #region Update Order Detail

                        string msg = "";
                        int error = 0, amount_change = 0;
                        ProductLog pl, newpl;
                        OrderDetail prd;

                        // Check old data

                        OrderDetailService orderDetailService = new OrderDetailService();
                        List<OrderDetail> deleted_details = old_orderDetails.Where(x => !orderDetails.Select(y => y.ProductId.ToString() + '_' +
                            y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                            x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                        List<OrderDetail> updated_details = old_orderDetails.Where(x => orderDetails.Select(y => y.ProductId.ToString() + '_' +
                            y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                            x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                        List<OrderDetail> new_details = orderDetails.Where(x => !old_orderDetails.Select(y => y.ProductId.ToString() + '_' +
                            y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                            x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                        foreach (OrderDetail item in updated_details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            prd = orderDetails.Where(x => x.ProductId == item.ProductId && x.AttributeId == item.AttributeId &&
                                x.UnitId == item.UnitId).FirstOrDefault();
                            amount_change = Convert.ToInt32(prd.NumberUnit - item.NumberUnit);
                            if (amount_change > 0 && pl.AfterNumber - amount_change < 0) // Tang nguyen lieu
                            {
                                if (error == 0)
                                {
                                    msg += "Những sản phẩm sau đã bị SỬA nhưng không đảm bảo dữ liệu trong kho:\n";
                                    error = 1;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + amount_change.ToString() + "\n";
                            }
                        }
                        foreach (OrderDetail item in new_details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            if (pl.AfterNumber - item.NumberUnit < 0)
                            {
                                if (error < 2)
                                {
                                    msg += "Những sản phẩm sau không đủ số lượng để tạo phiếu bán hàng:\n";
                                    error = 2;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " còn : " + pl.AfterNumber + "\n";
                            }
                        }

                        if (error > 0)
                        {
                            MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        foreach (OrderDetail item in deleted_details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            newpl = new ProductLog()
                            {
                                ProductId = item.ProductId,
                                AttributeId = item.AttributeId,
                                UnitId = item.UnitId,
                                BeforeNumber = pl.AfterNumber,
                                Amount = item.NumberUnit,
                                AfterNumber = pl.AfterNumber + item.NumberUnit,
                                RecordCode = order.OrderCode,
                                Status = BHConstant.ACTIVE_STATUS,
                                Direction = BHConstant.DIRECTION_IN,
                                UpdatedDate = createdDate
                            };
                            productLogService.AddProductLog(newpl);
                        }
                        foreach (OrderDetail od in orderDetails)
                        {
                            od.OrderId = order.Id;
                            if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                            {
                                totalCommission += od.Commission;
                                OrderDetail tmp_ode = old_orderDetails.Where(x => x.ProductId == od.ProductId &&
                                    x.AttributeId == od.AttributeId && x.UnitId == od.UnitId && x.OrderId == order.Id).FirstOrDefault();
                                if (tmp_ode != null)
                                {
                                    double amount = tmp_ode.NumberUnit - od.NumberUnit;
                                    bool ret = orderDetailService.UpdateOrderDetail(od);
                                    //Save in Production Log
                                    if (amount != 0)
                                    {
                                        pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                        newpl = new ProductLog()
                                        {
                                            ProductId = od.ProductId,
                                            AttributeId = od.AttributeId,
                                            UnitId = od.UnitId,
                                            BeforeNumber = pl.AfterNumber,
                                            Amount = Math.Abs(amount),
                                            AfterNumber = pl.AfterNumber + amount,
                                            RecordCode = order.OrderCode,
                                            Status = BHConstant.ACTIVE_STATUS,
                                            Direction = amount > 0 ? BHConstant.DIRECTION_IN : BHConstant.DIRECTION_OUT,
                                            UpdatedDate = createdDate
                                        };
                                        productLogService.AddProductLog(newpl);
                                    }
                                }
                                else
                                {
                                    bool ret = (od.Id != null && od.Id > 0) ? orderDetailService.UpdateOrderDetail(od) 
                                        : orderDetailService.AddOrderDetail(od);
                                    //Save in Production Log
                                    pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId = od.ProductId,
                                        AttributeId = od.AttributeId,
                                        UnitId = od.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount = od.NumberUnit,
                                        AfterNumber = pl.AfterNumber - od.NumberUnit,
                                        RecordCode = order.OrderCode,
                                        Status = BHConstant.ACTIVE_STATUS,
                                        Direction = BHConstant.DIRECTION_OUT,
                                        UpdatedDate = createdDate
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }
                        }

                        OrderService orderService = new OrderService();
                        bool result = orderService.UpdateOrder(order);

                        #endregion

                        #region KH & NV

                        CustomerLogService cls = new CustomerLogService();
                        CustomerLog newest = cls.GetCustomerLog(order.OrderCode);
                        if (newest != null)
                        {
                            newest.Amount = totalWithTax;
                            cls.UpdateCustomerLog(newest);
                        }

                        int salerId = (int)order.Customer.SalerId;
                        if (salerId > 0)
                        {
                            EmployeeLogService els = new EmployeeLogService();
                            EmployeeLog order_el = els.SelectEmployeeLogByWhere(x => x.RecordCode == order.OrderCode).FirstOrDefault();
                            if (order_el != null)
                            {
                                order_el.Amount = totalCommission;
                                els.UpdateEmployeeLog(order_el);
                            }
                        }

                        #endregion

                        if (result)
                        {
                            MessageBox.Show("Phiếu bán hàng đã được cập nhật thành công");
                            this.Close();
                            return true;
                        }
                        else
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        #endregion
                    }
                    else//add new
                    {
                        #region Create New

                        ProductLog pl, newpl;
                        string msg = "";
                        int error = 0;
                        foreach (OrderDetail item in orderDetails)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            if (pl.AfterNumber - item.NumberUnit < 0)
                            {
                                if (error == 0)
                                {
                                    msg += "Những sản phẩm sau không đủ số lượng để tạo phiếu bán hàng:\n";
                                    error = 1;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " còn : " + pl.AfterNumber + "\n";
                            }
                        }

                        if (error > 0)
                        {
                            MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        SeedService ss = new SeedService();
                        order = new Order
                        {
                            CustId = cbxCustomer.SelectedValue != null ? (int)cbxCustomer.SelectedValue : 0,
                            Discount = discount,
                            Note = txtNote.Text,
                            VAT = vat,
                            OrderCode = ss.AddSeedID(BHConstant.PREFIX_FOR_ORDER),
                            CreatedDate = createdDate,
                            UserId = userId,
                            Reason = txtReason.Text,
                            WareHouse = txtWare.Text,
                            Total = totalWithTax
                        };
                        OrderService orderService = new OrderService();
                        bool result = orderService.AddOrder(order);
                        long newOrderId = -1;
                        try
                        {
                            newOrderId = order.Id;// BaoHienRepository.GetMaxId<Order>();
                        }
                        catch
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        #region New Order Detail

                        OrderDetailService orderDetailService = new OrderDetailService();
                        foreach (OrderDetail od in orderDetails)
                        {
                            if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                            {
                                od.OrderId = (int)newOrderId;
                                bool ret = orderDetailService.AddOrderDetail(od);
                                totalCommission += od.Commission;

                                //Save in Production Log
                                pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                newpl = new ProductLog()
                                {
                                    ProductId = od.ProductId,
                                    AttributeId = od.AttributeId,
                                    UnitId = od.UnitId,
                                    BeforeNumber = pl.AfterNumber,
                                    Amount = od.NumberUnit,
                                    AfterNumber = pl.AfterNumber - od.NumberUnit,
                                    RecordCode = order.OrderCode,
                                    Status = BHConstant.ACTIVE_STATUS,
                                    Direction = BHConstant.DIRECTION_OUT,
                                    UpdatedDate = createdDate
                                };
                                productLogService.AddProductLog(newpl);
                            }
                        }

                        #endregion

                        #region KH & NV

                        CustomerLogService cls = new CustomerLogService();
                        CustomerLog cl = new CustomerLog
                        {
                            CustomerId = order.CustId,
                            RecordCode = order.OrderCode,
                            Amount = totalWithTax,
                            Direction = BHConstant.DIRECTION_OUT,
                            CreatedDate = createdDate
                        };
                        result = cls.AddCustomerLog(cl);

                        int salerId = (int)order.Customer.SalerId;
                        if (salerId > 0)
                        {
                            EmployeeLogService els = new EmployeeLogService();
                            EmployeeLog newel = new EmployeeLog
                            {
                                EmployeeId = salerId,
                                RecordCode = order.OrderCode,
                                Amount = totalCommission,
                                CreatedDate = createdDate
                            };
                            result = els.AddEmployeeLog(newel);
                        }

                        #endregion

                        if (result)
                        {
                            MessageBox.Show("Phiếu bán hàng đã được tạo thành công");
                            this.Close();
                            return true;
                        }
                        else
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        #endregion
                    }
                }
                return false;
            }
            else
            {
                MessageBox.Show("Vui lòng kiểm tra các thông tin cần thiết!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
 public void loadDataForEditOrder(int orderId)
 {
     if (!Global.isAdmin())
     {
         disableForm();
     }
     cbxCustomer.Enabled = false; // Don't allow change Customer
     isUpdating = true;
     OrderService orderService = new OrderService();
     order = orderService.GetOrder(orderId);
     old_order = order;
     if (order != null)
     {
         if (orderDetails == null)
         {
             OrderDetailService orderDetailService = new OrderDetailService();
             orderDetails = new BindingList<OrderDetail>(orderDetailService.SelectOrderDetailByWhere(o => o.OrderId == order.Id));
             old_orderDetails = new List<OrderDetail>();
             foreach (OrderDetail od in orderDetails)
             {
                 old_orderDetails.Add(new OrderDetail
                     {
                         AttributeId = od.AttributeId,
                         ProductId = od.ProductId,
                         UnitId = od.UnitId,
                         OrderId = od.OrderId,
                         NumberUnit = od.NumberUnit
                     });
             }
         }
     }            
 }
        private void DeleteOrder(DataGridViewCellEventArgs e)
        {
            DialogResult result = MessageBox.Show("Bạn muốn xóa đơn hàng này?", "Xoá đơn hàng", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                DataGridViewRow currentRow = dgwOrderList.Rows[e.RowIndex];

                OrderService orderService = new OrderService();
                int id = ObjectHelper.GetValueFromAnonymousType<int>(currentRow.DataBoundItem, "Id");
                Order order = orderService.GetOrder(id);
                DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();

                #region CustomerLog

                CustomerLogService cls = new CustomerLogService();
                CustomerLog cl = cls.GetCustomerLog(order.OrderCode);
                bool kq = true;
                if (cl != null)
                    kq = cls.DeleteCustomerLog(cl.Id);

                #endregion

                #region ProductLog

                ProductLogService productLogService = new ProductLogService();
                OrderDetailService orderDetailService = new OrderDetailService();
                List<OrderDetail> details = orderDetailService.SelectOrderDetailByWhere(x => x.OrderId == order.Id).ToList();
                ProductLog pl, newpl;
                foreach (OrderDetail item in details)
                {
                    pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                    newpl = new ProductLog()
                    {
                        ProductId = item.ProductId,
                        AttributeId = item.AttributeId,
                        UnitId = item.UnitId,
                        BeforeNumber = pl.AfterNumber,
                        Amount = item.NumberUnit,
                        AfterNumber = pl.AfterNumber + item.NumberUnit,
                        RecordCode = order.OrderCode,
                        Status = BHConstant.DEACTIVE_STATUS,
                        Direction = BHConstant.DIRECTION_IN,
                        UpdatedDate = systime
                    };
                    productLogService.AddProductLog(newpl);
                }
                productLogService.DeactiveProductLog(order.OrderCode);

                #endregion

                #region EmployeeLog

                int salerId = (int)order.Customer.SalerId;
                if (salerId > 0)
                {
                    EmployeeLogService els = new EmployeeLogService(); 
                    EmployeeLog order_el = els.SelectEmployeeLogByWhere(x => x.RecordCode == order.OrderCode).FirstOrDefault();
                    if(order_el != null)
                        els.DeleteEmployeeLog(order_el.Id);
                }

                #endregion

                if (!orderService.DeleteOrder(id) && kq)
                {
                    MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                loadOrderList();
            }
        }