示例#1
0
            public static void get_order_detail(SortedList <int, order> orders)
            {
                order         o         = null;
                SqlCommand    cmd       = new SqlCommand("select OrderNum, OrderDate, ProductID, Volume, Price from OrderDetails order by OrderNum, ProductId", DB.cnn());
                SqlDataReader rdr       = cmd.ExecuteReader();
                int           order_num = -1;

                while (rdr.Read())
                {
                    order_detail od = new order_detail();
                    od.order_num  = (int)rdr.GetValue(0);
                    od.order_date = (DateTime)rdr.GetValue(1);
                    od.product_id = (int)rdr.GetValue(2);
                    od.volume     = (int)rdr.GetValue(3);
                    od.price      = (Double)rdr.GetValue(4);
                    if (od.order_num != order_num)
                    {
                        orders.TryGetValue(od.order_num, out o);
                        order_num = od.order_num;
                    }
                    if (o != null)
                    {
                        o.details.Add(od);
                        o.OnDetailChanged();
                    }
                }
                rdr.Close();
            }
示例#2
0
        public order_detail Createorder_detail(Int32?orderID = null, Int32?productID = null, Decimal?unitPrice = null, Int16?quantity = null, Double?discount = null)
        {
            order_detail value = CreateObject <order_detail>();

            if (orderID != null)
            {
                value.OrderID = orderID.Value;
            }
            if (productID != null)
            {
                value.ProductID = productID.Value;
            }
            if (unitPrice != null)
            {
                value.UnitPrice = unitPrice.Value;
            }
            if (quantity != null)
            {
                value.Quantity = quantity.Value;
            }
            if (discount != null)
            {
                value.Discount = discount.Value;
            }
            return(value);
        }
示例#3
0
 /// <summary>
 /// 从商品信息生成订单的构造函数
 /// </summary>
 /// <param name="uid"></param>
 /// <param name="infos"></param>
 public Order(string uid, MerchandiseInfoCashier[] infos)
 {
     orderList = new List <order_detail>(infos.Length);
     foreach (MerchandiseInfoCashier info in infos)
     {
         string m_id          = info.id;
         bool   found_same_id = false;
         foreach (order_detail detail in orderList)
         {
             if (m_id == detail.id)
             {
                 detail.num   += 1;
                 found_same_id = true;
                 break;
             }
         }
         if (found_same_id == false)
         {
             order_detail detail = new order_detail();
             detail.id  = m_id;
             detail.num = 1;
             orderList.Add(detail);
         }
     }
     order_method = "1";
     user_id      = uid;
     shop_id      = shop_identify;
 }
        // POST: odata/OrderDetails
        public async Task <IHttpActionResult> Post(order_detail order_detail)
        {
            if (!ModelState.IsValid)
            {
                _log.Error("OrderDetailsController:Put - Model was Invalid");
                return(BadRequest(ModelState));
            }

            db.order_detail.Add(order_detail);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (order_detailExists(order_detail.order_detail_id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(Created(order_detail));
        }
示例#5
0
        public ActionResult DeleteConfirmed(int id)
        {
            order_detail order_detail = db.order_detail.Find(id);

            db.order_detail.Remove(order_detail);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#6
0
            public static void delete_order_details(order_detail od)
            {
                SqlCommand   cmd = new SqlCommand("delete from OrderDetails where OrderNum=@OrderNum", DB.cnn());
                SqlParameter p   = new SqlParameter("@OrderNum", od.order_num); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);

                //cmd.Prepare();
                cmd.ExecuteNonQuery();
            }
示例#7
0
 public order_detail(order_detail od)
 {
     this.order_num  = od.order_num;
     this.order_date = od.order_date;
     this.product_id = od.product_id;
     this.price      = od.price;
     this.volume     = od.volume;
 }
示例#8
0
        public ActionResult CreateOrder()
        {
            int uID = (Int32)(Session["id"]);
            int oID = 0;

            using (OrderSystemEntities2 db = new OrderSystemEntities2())

            {
                user            u            = db.users.Where(x => x.id == uID).FirstOrDefault();
                List <CartItem> items        = (List <CartItem>)Session["cart"];
                DateTime        date         = items[0].Date;
                int             service_time = items[0].ServiceTime;
                float           total_price  = (float)items.Sum(x => x.Product.price * x.Quantity);
                if (total_price > u.balance)
                {
                    ViewBag.BalanceError = 1;
                    return(RedirectToAction("CheckOut", "CreateOrder"));
                }
                else
                {
                    order order = new order()
                    {
                        userID       = (Int32)(Session["id"]),
                        create_time  = DateTime.Now,
                        take_date    = date,
                        take_time    = service_time,
                        is_cancle    = false,
                        total_price  = total_price,
                        reviewed     = false,
                        receive_code = RandReceiveCode()
                    };
                    db.orders.Add(order);
                    db.SaveChanges();
                    int orderID = order.id;
                    oID = orderID;
                    foreach (CartItem item in items)
                    {
                        order_detail order_Detail = new order_detail()
                        {
                            orderID     = orderID,
                            productID   = item.Product.id,
                            quantity    = item.Quantity,
                            price       = item.Product.price,
                            total_price = item.Quantity * item.Product.price
                        };
                        db.order_detail.Add(order_Detail);
                    }
                    db.SaveChanges();
                    AddOrderToTransaction(order);
                    ViewBag.BalanceError = 0;

                    SendActivationEmail(u, order);

                    Session.Remove("cart");
                }
            }
            return(RedirectToAction("Index", "OrderDetail", new { oID = oID }));
        }
        // PUT: odata/OrderDetails(5)
        public async Task <IHttpActionResult> Put([FromODataUri] int key, Delta <order_detail> patch)
        {
            //var re = Request;
            //var headers = re.Headers;
            //var id = "";
            //if (headers.Contains("id"))
            //{
            //    id = headers.GetValues("id").First();
            //}
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(patch);

            _log.Info($"Model Object: {json}");
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                _log.Error("OrderDetailsController:Put - Model was Invalid");
                _log.Info($"Model Object: {json}");
                return(BadRequest(ModelState));
            }

            order_detail order_detail = await db.order_detail.FindAsync(key);

            if (order_detail == null)
            {
                return(NotFound());
            }

            patch.Put(order_detail);


            // Check to see if the we need to update the task status to completed.
            //order_task order_task =
            //    db.order_task.FirstOrDefault(p => p.order_id == order_detail.order_id && p.task_code == "order");

            //order_task.is_complete = "Y";
            //order_task.completed_by = id;
            //order_task.completed_date = DateTime.Now;
            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                if (!order_detailExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    _log.Error("An Error Occurred in OrderDetailsController:Put", ex);
                    throw;
                }
            }

            return(Updated(order_detail));
        }
示例#10
0
 public ActionResult Edit([Bind(Include = "order_detail_id,order_id,productname,quiantity,build_time,total_price,productid,buy_id")] order_detail order_detail)
 {
     if (ModelState.IsValid)
     {
         db.Entry(order_detail).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.order_id = new SelectList(db.orders, "order_id", "buy_Name", order_detail.order_id);
     return(View(order_detail));
 }
示例#11
0
        public ActionResult AddOrder(string rname, string rphone, string raddress, string remark)
        {
            var time = DateTime.Now;
            //string sqlFormattedDate = time.ToString("yyyy-MM-dd HH:mm:ss.fff");
            order_form order = new order_form();



            order.order_date         = time;
            order.member_account     = appClass.Account;
            order.remittance_account = "0000-0000-0000";
            order.payment_method     = "匯款";
            order.shipping_status    = "已接收訂單";
            order.recipient_name     = rname;
            order.recipient_phone    = rphone;
            order.recipient_address  = raddress;
            order.remark             = remark;
            db.order_form.Add(order);
            try { db.SaveChanges(); }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                throw ex;
            }

            order_detail orderDetail = new order_detail();
            var          cartlist    = db.shopping_cart.Where(m => m.member_account == appClass.Account).ToList();

            foreach (var item in cartlist)
            {
                orderDetail.order_id         = order.order_id;
                orderDetail.product_quantity = item.product_quantity;
                orderDetail.product_no       = item.product_no;
                db.order_detail.Add(orderDetail);
                try { db.SaveChanges(); }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    throw ex;
                }
            }
            var clearCart = db.shopping_cart.Where(m => m.member_account == appClass.Account).ToList();

            foreach (var item in clearCart)
            {
                var deleteItem = db.shopping_cart.Where(m => m.member_account == appClass.Account).FirstOrDefault();
                db.shopping_cart.Remove(deleteItem);
                db.SaveChanges();
            }



            return(RedirectToAction("OrderList"));

            //return View();
        }
示例#12
0
            public static void update_order_detail(order_detail od)
            {
                SqlCommand   cmd = new SqlCommand("update OrderDetails set OrderDate=@OrderDate, ProductID=@ProductID, Volume=@Volume, Price=@Price where OrderNum=@OrderNum", DB.cnn());
                SqlParameter p   = new SqlParameter("@OrderDate", od.order_date); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);

                p = new SqlParameter("@ProductID", od.product_id); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
                p = new SqlParameter("@Volume", od.volume); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
                p = new SqlParameter("@Price", od.price); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
                p = new SqlParameter("@OrderNum", od.order_num); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
                //cmd.Prepare();
                cmd.ExecuteNonQuery();
            }
示例#13
0
 public ActionResult Edit([Bind(Include = "order_detail_id,order_id,game_id,amount")] order_detail order_detail)
 {
     if (ModelState.IsValid)
     {
         db.Entry(order_detail).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.game_id  = new SelectList(db.games, "game_id", "title", order_detail.game_id);
     ViewBag.order_id = new SelectList(db.orders, "order_id", "order_id", order_detail.order_id);
     return(View(order_detail));
 }
 public bool Insert(order_detail orderDetail)
 {
     try
     {
         db.order_detail.Add(orderDetail);
         db.SaveChanges();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        // DELETE: odata/OrderDetails(5)
        public async Task <IHttpActionResult> Delete([FromODataUri] int key)
        {
            order_detail order_detail = await db.order_detail.FindAsync(key);

            if (order_detail == null)
            {
                return(NotFound());
            }

            db.order_detail.Remove(order_detail);
            await db.SaveChangesAsync();

            return(StatusCode(HttpStatusCode.NoContent));
        }
示例#16
0
        // GET: order_detail/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            order_detail order_detail = db.order_detail.Find(id);

            if (order_detail == null)
            {
                return(HttpNotFound());
            }
            return(View(order_detail));
        }
示例#17
0
        public ActionResult pack(int?order_detail_id, int?product_id, int quintity)
        {
            farmarEntities1 db = new farmarEntities1();
            product         c  = db.products.Where(a => a.productid == product_id).Select(b => b).SingleOrDefault();

            c.unitstock      -= quintity;
            c.sale           += quintity;
            db.Entry(c).State = EntityState.Modified;
            db.SaveChanges();
            order_detail o = db.order_detail.Where(a => a.order_detail_id == order_detail_id).Select(b => b).SingleOrDefault();

            o.status = "成功出貨";
            db.SaveChanges();
            return(RedirectToAction("Index", "Home", null));
        }
示例#18
0
        // GET: order_detail/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            order_detail order_detail = db.order_detail.Find(id);

            if (order_detail == null)
            {
                return(HttpNotFound());
            }
            ViewBag.order_id = new SelectList(db.orders, "order_id", "buy_Name", order_detail.order_id);

            return(View(order_detail));
        }
示例#19
0
 public static void add_order_detail(order_detail od)
 {
     try
     {
         SqlCommand   cmd = new SqlCommand("insert into OrderDetails values (@OrderNum,@OrderDate,@ProductID,@Volume,@Price)", DB.cnn());
         SqlParameter p   = new SqlParameter("@OrderNum", od.order_num); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
         p = new SqlParameter("@OrderDate", od.order_date); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
         p = new SqlParameter("@ProductID", od.product_id); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
         p = new SqlParameter("@Volume", od.volume); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
         p = new SqlParameter("@Price", od.price); p.Direction = ParameterDirection.Input; cmd.Parameters.Add(p);
         //cmd.Prepare();
         cmd.ExecuteNonQuery();
     }
     catch (Exception e) {
         Console.WriteLine(e.Message);
         MessageBox.Show(e.Message);
     }
 }
示例#20
0
    public void checkoutCart(string user_id, book_order book_order)
    {
        db.book_order.Add(book_order);
        db.SaveChanges();
        int         order_id = book_order.auto_id;
        List <Cart> listCart = db.Carts.Where(c => c.user_id == user_id).ToList <Cart>();

        for (int i = 0; i < listCart.Count; i++)
        {
            order_detail detail = new order_detail();
            detail.order_id = order_id;
            detail.book_id  = listCart[i].book_id;
            db.order_detail.Add(detail);
            db.SaveChanges();

            listCart[i].status = false;
            updateCart(listCart[i]);
        }
    }
        public async Task <IHttpActionResult> Patch([FromODataUri] int key, Delta <order_detail> patch)
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(patch);

            _log.Info($"Model Object: {json}");

            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            order_detail order_detail = await db.order_detail.FindAsync(key);

            if (order_detail == null)
            {
                return(NotFound());
            }

            patch.Patch(order_detail);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!order_detailExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(order_detail));
        }
        private List<order_detail> GetOrderDetail(int ServiceProviderId)
        {
            List<order_detail> ReturnList = new List<order_detail>();
            foreach (OrderDetail od in SyncClient.GetOrderDetail(GetFromDate, DateTimeNow, ServiceProviderId))
            {
                order_detail tmp = QueryOrderDetail(od.Id);
                Boolean NewValue = false;
                if (tmp == null)
                {
                    tmp = new order_detail();
                    NewValue = true;
                }
                tmp.address_1 = od.Address1;
                tmp.address_2 = od.Address2;
                tmp.city = od.City;
                tmp.company = od.Company;
                tmp.country_id = od.CountryId;
                tmp.createdAt = System.DateTime.Parse(od.CreateDat);
                tmp.Id = od.Id;
                tmp.phone_1 = od.Phone1;
                tmp.phone_2 = od.Phone2;
                tmp.tax_number = od.Taxnumber;
                tmp.zip = od.Zip;
                tmp.first_name = od.Firstname;
                tmp.last_name = od.Lastname;
                tmp.order_id = od.OrderId;
                tmp.zone_id = od.ZoneId;

                if (NewValue)
                {
                    dbContext.Set<order_detail>().Add(tmp);
                }
                dbContext.SaveChanges();
                ReturnList.Add(tmp);
            }
            return ReturnList;
        }
示例#23
0
        public async Task <IActionResult> NewOrder(order_detail od)
        {
            var customer = new SelectList(await _context.customer.ToListAsync(), "customer_id", "firstname", od.order_List.customer_id);
            var product  = new SelectList(await _context.product.ToListAsync(), "product_id", "product_name", od.product_id);

            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    order_list ol = new order_list();
                    ol.order_id    = od.order_id;
                    ol.customer_id = od.order_List.customer_id;
                    ol.status      = od.order_List.status;
                    ol.order_date  = System.DateTime.Now;
                    _context.Add(ol);
                    await _context.SaveChangesAsync();

                    _context.Add(od);
                    await _context.SaveChangesAsync();

                    tran.Commit();
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                }

                tran.Dispose();
            }

            ViewData["customer"] = customer;
            ViewData["product"]  = product;


            return(View());
        }
        public ActionResult Order(string name, string email, string phone, string address, string province, string district)
        {
            var objOrder = new order();

            objOrder.order_name     = name;
            objOrder.order_email    = email;
            objOrder.order_phone    = phone;
            objOrder.order_address  = address;
            objOrder.order_province = province;
            objOrder.order_district = district;
            // objOrder.order_ward = ward;
            objOrder.order_date = DateTime.Now;

            // Get user infor
            try
            {
                var orderId = new OrderADO().Insert(objOrder);
                var cart    = (List <CartModel>)Session[SessionConst.CART_SESSION];

                var     orderDetailADO = new OrderDetailADO();
                decimal total          = 0;

                var orderDetail = new order_detail();
                foreach (var item in cart)
                {
                    orderDetail.product_id = item.Product.product_id;
                    orderDetail.order_id   = orderId;
                    orderDetail.price      = item.Product.price;
                    orderDetail.quantity   = item.Quantity;
                    orderDetailADO.Insert(orderDetail);
                    total += (item.Product.price.GetValueOrDefault(0) * item.Quantity);
                }
                var productInfo = new product();
                foreach (var item in cart)
                {
                    productInfo.prod_code    = item.Product.prod_code;
                    productInfo.product_name = item.Product.product_name;
                    productInfo.quantity     = item.Product.quantity;
                    productInfo.price        = item.Product.price;
                }

                string content = System.IO.File.ReadAllText(Server.MapPath("~/Contents/EmailTemplate/neworder.html"));
                content = content.Replace("{{CustomerName}}", name);
                content = content.Replace("{{CustomerPhone}}", phone);
                content = content.Replace("{{CustomerEmail}}", email);
                content = content.Replace("{{CustomerAddress}}", address);
                content = content.Replace("{{CustomerProvince}}", province);
                content = content.Replace("{{CustomerDistrict}}", district);
                //  content = content.Replace("{{CustomerWard}}", ward);
                content = content.Replace("{{CustomerProdCode}}", productInfo.prod_code);
                content = content.Replace("{{CustomerProdName}}", productInfo.product_name);
                content = content.Replace("{{CustomerQuantity}}", productInfo.quantity.ToString());
                content = content.Replace("{{CustomerPrice}}", productInfo.price.ToString());
                content = content.Replace("{{CustomerTotal}}", total.ToString("N0"));

                var toEmailAddress = ConfigurationManager.AppSettings["ToEmailAddress"].ToString();
                new MailHelper().SendMail(email, "FashionShop - Xác nhận đơn hàng", content);     // Send Email to Customer
                new MailHelper().SendMail(toEmailAddress, "FashionShop - Đơn hàng mới", content); // Send Email to Admin
            }
            catch (Exception)
            {
                return(Redirect("/dat-hang-khong-thanh-cong"));
            }
            Session[SessionConst.CART_SESSION] = null;
            return(Redirect("/dat-hang-thanh-cong"));
        }
示例#25
0
 /// <summary>
 /// Deprecated Method for adding a new object to the order_details EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToorder_details(order_detail order_detail)
 {
     base.AddObject("order_details", order_detail);
 }
        private void SaveLogInterface(POSAirPortClassesDataContext _posDB, OrderHeader order, order_session new_session_order)
        {
            // order_header db save
            var new_order_header = new order_header();

            new_order_header.session_id    = new_session_order.id;
            new_order_header.order_type    = order.Flight.Terminal;
            new_order_header.member_id     = order.NewOrder.MemberID;
            new_order_header.full_name     = order.Billing.FirstName + " " + order.Billing.LastName;
            new_order_header.passport_no   = order.Billing.PassportNo;
            new_order_header.country       = order.Billing.CountryCode;
            new_order_header.airport_code  = order.Flight.AirportCode;
            new_order_header.terminal_code = order.Flight.Terminal;
            new_order_header.airline_code  = order.Flight.AirlineCode;
            new_order_header.flight_code   = order.Flight.FlightCode;
            new_order_header.flight_no     = order.Flight.FlightCode;
            //new_order_header.flight_
            new_order_header.reference_1 = "";
            new_order_header.reference_2 = "";
            new_order_header.reference_3 = "";
            new_order_header.remark      = "";
            new_order_header.create_date = DateTime.Now;
            _omDB.order_headers.InsertOnSubmit(new_order_header);
            _omDB.SubmitChanges();

            // db save new order_detail and order_discount
            foreach (var item in order.Items.Select((value, index) => new { Value = value, Index = index }))
            {
                order_detail new_item = new order_detail();
                new_item.header_id       = new_order_header.id;
                new_item.line_no         = item.Index + 1;
                new_item.sub_order_type  = "I";
                new_item.article_code    = item.Value.MaterialCode;
                new_item.quantity        = item.Value.Quantity;
                new_item.selling_price   = item.Value.SellingPrice;
                new_item.total_amt       = item.Value.Amount;
                new_item.dis_rate        = item.Value.DiscountRate;
                new_item.dis_amt         = item.Value.Discount;
                new_item.dis_pro_code    = item.Value.PromoCode;
                new_item.sp_dis_amt      = item.Value.SPDiscount;
                new_item.sp_dis_rate     = item.Value.SPDiscountRate;
                new_item.sp_dis_pro_code = item.Value.SPPromoCode;
                new_item.net_amt         = item.Value.TotalNet;
                new_item.reference_1     = "";
                new_item.reference_2     = "";
                new_item.reference_3     = "";

                _omDB.order_details.InsertOnSubmit(new_item);
                _omDB.SubmitChanges();
            }
            // new df_payment_onl
            var master_paymath = _posDB.df_paymeths.ToList();

            foreach (var payment in order.Payments.Select((value, index) => new { Value = value, Index = index }))
            {
                decimal amt_curr = 0;
                var     paymath  = master_paymath.FirstOrDefault(x => x.method_code.Trim() == payment.Value.Code.Trim());
                if (paymath != null)
                {
                    if (paymath.check_voucher || paymath.is_cashcard)
                    {
                        amt_curr = 0;
                    }
                    else
                    {
                        amt_curr = payment.Value.Amount * 1;
                    }
                }

                order_payment new_payment = new order_payment();
                new_payment.header_id          = new_order_header.id;
                new_payment.payment_type       = payment.Value.Code;
                new_payment.paymemt_agent      = "";
                new_payment.paymemt_session_id = "";
                new_payment.paymemt_ref_no     = "";
                new_payment.payment_code       = payment.Value.Code;
                new_payment.paymemt_amt        = payment.Value.Amount;
                new_payment.paymemt_datetime   = DateTime.Now;
                _omDB.order_payments.InsertOnSubmit(new_payment);
                _omDB.SubmitChanges();
            }
        }
示例#27
0
        public static bool CartPayment(cvmOrder model)
        {
            OrderNo = CreateNewOrderNo(model);
            using (dbcon db = new dbcon())
            {
                var datas = db.carts
                            .Where(m => m.mno == UserAccount.UserNo)
                            .ToList();
                if (datas != null)
                {
                    //將同會員購買的所有品項加總 為什麼不用CartTotal??
                    int int_amount = datas.Sum(m => m.amount).GetValueOrDefault();
                    //加上稅金
                    decimal dec_tax = 0;
                    if (int_amount > 0)
                    {
                        dec_tax = Math.Round((decimal)(int_amount * 5 / 100), 0);
                    }
                    int int_total = int_amount + (int)dec_tax;
                    var data      = db.order.Where(m => m.order_no == OrderNo).FirstOrDefault();
                    if (data != null)
                    {
                        data.amounts = int_amount;
                        data.taxs    = (int)dec_tax;
                        data.totals  = int_total;
                    }

                    foreach (var item in datas)
                    {
                        var stock_date_list = item.ptype_spec.Trim().Split(' ').ToList();
                        stock_date_list.RemoveAt(stock_date_list.Count - 1);
                        foreach (var d in stock_date_list)
                        {
                            DateTime date     = Convert.ToDateTime(d);
                            var      hasStock = db.product_typedetail_everydaystock.Count(e => e.ptype_no == item.ptype_no && e.stock_date == date && e.stock >= item.ptype_qty) > 0;
                            if (!hasStock)
                            {
                                return(false);
                            }
                        }
                        order_detail detail = new order_detail();
                        detail.order_no      = OrderNo;
                        detail.pno           = item.pno;
                        detail.pname         = item.pname;
                        detail.ptype_no      = item.ptype_no;
                        detail.ptype_name    = item.ptype_name;
                        detail.vendor_no     = Shop.GetVendorNoByProduct(item.pno);
                        detail.category_name = Shop.GetCategoryName(item.pno);
                        detail.ptype_spec    = item.ptype_spec;
                        detail.qty           = item.ptype_qty;
                        detail.price         = item.ptype_price;
                        detail.amount        = item.amount;
                        detail.remark        = "";
                        db.order_detail.Add(detail);

                        db.carts.Remove(item);
                    }
                    db.SaveChanges();
                }
            }
            return(true);
        }
示例#28
0
        public ActionResult ProcessOrder(FormCollection frc)
        {
            List <Cart> lsCart   = (List <Cart>)Session[strCart];
            List <Cart> temp     = (List <Cart>)Session["Cart"];
            customer    customer = new customer()
            {
                name          = frc["cusName"],
                surname       = frc["cusSurname"],
                Email         = frc["cusMail"],
                PhoneNumber   = frc["cusPhone"],
                address_line1 = frc["cusAddress1"],
                address_line2 = frc["cusAddress2"],
                postal_code   = frc["cusPostal"]
            };

            string          aspnetuserID = User.Identity.GetUserId();
            decimal         total        = 0;
            List <customer> custList     = db.customers.Where(x => x.AspNetUsers_id == aspnetuserID).ToList();
            var             customerID   = db.customers.Where(x => x.AspNetUsers_id == aspnetuserID);

            if (custList.Count() > 0)
            {
                int cust = custList.First().customer_id;
                foreach (Cart cart in lsCart)
                {
                    total += cart.Quantity * cart.Product.price;
                }
                order order = new order()
                {
                    customer_id   = cust,
                    price         = total,
                    date          = DateTime.Now,
                    order_type_id = 3
                };
                db.orders.Add(order);
                db.SaveChanges();
            }
            else if (custList.Count() == 0 && Request.IsAuthenticated)
            {
                return(RedirectToAction("../Account/User_details"));
            }
            else
            {
                db.customers.Add(customer);
                db.SaveChanges();
                List <customer> lsCust = db.customers.ToList();
                int             idCust = lsCust.Last().customer_id;

                foreach (Cart cart in lsCart)
                {
                    total += cart.Quantity * cart.Product.price;
                }
                order order = new order()
                {
                    customer_id   = idCust,
                    price         = total,
                    date          = DateTime.Now,
                    order_type_id = 3
                };
                db.orders.Add(order);
                db.SaveChanges();
            }

            List <order> lsOrder = db.orders.ToList();
            int          idOrder = lsOrder.Last().order_id;

            foreach (Cart cart in lsCart)
            {
                order_detail order_detail = new order_detail()
                {
                    order_id = idOrder,
                    game_id  = cart.Product.game_id,
                    amount   = cart.Quantity
                };
                db.order_detail.Add(order_detail);
                db.SaveChanges();
            }

            Session.Remove(strCart);
            return(View("OrderSuccess"));
        }