public void Create_NullOrder_DoesNotThrow() { var factory = new ConnectionStringFactory(this._configuration); var repo = new OrdersRepository(factory, this._marketRepository, this._orderBrokerRepository, this._logger); Assert.DoesNotThrowAsync(() => repo.Create(null)); }
public Order Create(Order newOrder) { int id = _repo.Create(newOrder); newOrder.Id = id; return(newOrder); }
public void CreateOrder(string CustomerId, CreateOrderView model) { //產生orderId string Id = ordersRepository.GetNewId(); var split = Id.Split('E'); string numner = (Convert.ToInt32(split[1]) + 1).ToString(); while (numner.Length < 3) { numner = "0" + numner; } var newOrder = new Orders() { OrderID = "DE" + numner, CustomerID = CustomerId, OrderDate = DateTime.Now, ShippedDate = null, PaymentMethodID = model.PaymentMethodID, DeliveryMethodID = model.DeliveryMethodID, Status = 0 }; //新增訂單 ordersRepository.Create(newOrder); //新增訂單明細 CreateOrderDetail(newOrder.OrderID, CustomerId); }
public IActionResult CreateOrder(Orders order) { if (ModelState.IsValid) { repo.Create(order); return(RedirectToAction("ViewOrders")); } return(View("CreateOrder")); }
public async Task Create() { var factory = new ConnectionStringFactory(this._configuration); var repo = new OrdersRepository(factory, this._marketRepository, this._orderBrokerRepository, this._logger); var frame = this.Frame(); await repo.Create(frame); Assert.IsTrue(true); }
public HttpResponseMessage AddOrder(OrdersDto order) { var repo = new OrdersRepository(); var result = repo.Create(order); if (result) { return(Request.CreateResponse(HttpStatusCode.Created)); } return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Could not create order, try again later...")); }
public async Task Get() { var factory = new ConnectionStringFactory(this._configuration); var brokerRepository = new OrderBrokerRepository(factory, NullLogger <OrderBrokerRepository> .Instance); var repo = new OrdersRepository(factory, this._marketRepository, brokerRepository, this._logger); var row1 = this.Frame(); var row2 = this.Frame(); var start = row1.MostRecentDateEvent().Date; var end = row2.MostRecentDateEvent().AddDays(1).Date; await repo.Create(row1); await repo.Create(row2); var result = await repo.Get(start, end, this._opCtx); Assert.IsTrue(true); }
internal Order AddOrder(Order orderData) { orderData.Id = Guid.NewGuid().ToString(); orderData.OrderIn = DateTime.Now; _repo.Create(orderData); orderData.Food.ForEach(item => { _repo.CreateOrderItem(orderData.Id, item.Id); }); return(orderData); }
public void Create_OrderNoBrokerInsert_DoesNotThrow() { var factory = new ConnectionStringFactory(this._configuration); var repo = new OrdersRepository(factory, this._marketRepository, this._orderBrokerRepository, this._logger); var frame = this.Frame(); frame.OrderBroker = null; Assert.DoesNotThrowAsync(() => repo.Create(frame)); A.CallTo(() => this._orderBrokerRepository.InsertOrUpdateBrokerAsync(A <IOrderBroker> .Ignored)) .MustNotHaveHappened(); }
public async Task CreateOrder(Order order) { try { await _repository.Create(order); } catch (Exception e) { throw new ApplicationException(e.Message); } finally { await _repository.Save(); } }
public void CreateNewOrder() { //Arrange OrdersRepository ordersRepository = new OrdersRepository(); var ordersCount = ordersRepository.GetAll().Count(); DateTime deliveryTime = DateTime.Now.AddDays(5); decimal freight = 26.75m; Order order = new Order("BONAP", 6, deliveryTime, 3, freight, "Ernst Handel", "Kirchgasse 6", "Graz", null, "8010", "Austria"); //Act ordersRepository.Create(order); //Assert Assert.AreEqual(ordersCount + 1, ordersRepository.GetAll().Count()); }
public void SetNewOrderInProgress() { //Arrange OrdersRepository ordersRepository = new OrdersRepository(); DateTime deliveryTime = DateTime.Now.AddDays(5); decimal freight = 26.75m; Order order = new Order("BONAP", 6, deliveryTime, 3, freight, "Ernst Handel", "Kirchgasse 6", "Graz", null, "8010", "Austria"); //Act int orderID = ordersRepository.Create(order).OrderID; ordersRepository.SetInProgress(order); order = ordersRepository.Get(orderID); //Assert Assert.IsNotNull(order.OrderDate); }
public void UpdateNewOrder() { //Arrange string newPostalCode = "1488"; //Act OrdersRepository ordersRepository = new OrdersRepository(); DateTime deliveryTime = DateTime.Now.AddDays(5); decimal freight = 26.75m; Order order = new Order("BONAP", 6, deliveryTime, 3, freight, "Ernst Handel", "Kirchgasse 6", "Graz", null, "8010", "Austria"); int orderID = ordersRepository.Create(order).OrderID; order.ShipPostalCode = newPostalCode; ordersRepository.Update(order); order = ordersRepository.Get(orderID); //Assert Assert.AreEqual(newPostalCode, order.ShipPostalCode); }
public void OrdersRepositoryTests_Create() { //測試rollback SqlConnection connection = new SqlConnection(SqlConnect.str); OrdersRepository repository = new OrdersRepository(); connection.Open(); var transaction = connection.BeginTransaction(); int temp1 = repository.GetAll().Count(); try { var model = new Orders { Order_Date = DateTime.Parse("2018-05-12 00:00:00.000"), Account = "Osborn", Pay = "超商取貨", Transport = "物流", Order_Check = 1, Total = 680, TranMoney = 0 }; repository.Create(connection, model, transaction); transaction.Commit(); } catch (Exception) { try { transaction.Rollback(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } var temp2 = repository.GetAll().Count(); Assert.IsTrue(temp1 < temp2); }
public JsonResult Order(string name, string phone, string address, string memberID, decimal totalPrice) { if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(phone) || string.IsNullOrWhiteSpace(address)) { return(Json("填空區不可有空白")); } else { if (Regex.Match(name, @"[\u3000-\u9FA5\x20]{2,4}").Success) { if (Regex.Match(phone, @"(\(?\d{3,4}\)?)?[\s-]?\d{7,8}[\s-]?\d{0,4}").Success) { ShoppingCartRepository shoppingCartRepository = new ShoppingCartRepository(); OrdersRepository ordersRepository = new OrdersRepository(); EmployeesRepository employeesRepository = new EmployeesRepository(); ProductFormatRepository productFormatRepository = new ProductFormatRepository(); OrderDetailsRepository orderDetailsRepository = new OrderDetailsRepository(); ProductRepository productRepository = new ProductRepository(); var employees = employeesRepository.GetAll(); var randomNumber = new Random().Next(0, employees.Count()); Orders orders = new Orders() { EmployeeID = employees.ElementAt(randomNumber).EmployeeID, MemberID = memberID, ShipName = name, ShipAddress = address, ShipPhone = phone, OrderDate = DateTime.Now, Status = "未送貨", TotalPrice = totalPrice }; ordersRepository.Create(orders); Procedure.Procedure procedure = new Procedure.Procedure(); var orderTempID = procedure.FindOrderID(memberID); var shoppingCart = shoppingCartRepository.FindByMemberID(memberID); Stack <OrderDetails> orderData = new Stack <OrderDetails>(); orderData.Clear(); foreach (var item in shoppingCart) { if (productFormatRepository.FindById(item.ProductFormatID).StockQuantity - item.Quantity >= 0) { OrderDetails orderDetails = new OrderDetails() { OrderID = orderTempID.OrderID, ProductFormatID = item.ProductFormatID, Quantity = item.Quantity, UnitPrice = productRepository.FindById(item.ProductID).UnitPrice }; orderData.Push(orderDetails); } else { var productFormatTemp = productFormatRepository.FindById(item.ProductFormatID); var productTemp = productRepository.FindById(productFormatTemp.ProductID); return(Json("產品:" + productTemp.ProductName + Environment.NewLine + "顏色:" + productFormatTemp.Color + Environment.NewLine + "尺寸:" + productFormatTemp.Size + Environment.NewLine + "剩餘數量:" + productFormatTemp.StockQuantity + Environment.NewLine + "請重新下訂!")); } } foreach (var orderItem in orderData) { orderDetailsRepository.Create(orderItem); } shoppingCartRepository.DeleteByMemberId(memberID); return(Json("下訂成功")); } else { return(Json("電話格式有誤")); } } else { return(Json("姓名不符合格式")); } } }
public async Task Create_OrderMultipleInsert_DoesNotThrow() { var factory = new ConnectionStringFactory(this._configuration); var marketRepository = new ReddeerMarketRepository( factory, new CfiInstrumentTypeMapper(), new NullLogger <ReddeerMarketRepository>()); var repo = new OrdersRepository(factory, marketRepository, this._orderBrokerRepository, this._logger); var securityIdentifiers1 = new InstrumentIdentifiers( null, null, null, "6657789", "6657789", null, null, null, null, null, "STAN1", null); var security1 = new FinancialInstrument( InstrumentTypes.Equity, securityIdentifiers1, "Standard Chartered", "CFI", "USD", "Standard Chartered Bank"); var securityIdentifiers2 = new InstrumentIdentifiers( null, null, null, "B00KT68", "B00KT68", null, null, null, null, null, "STAN1", null); var security2 = new FinancialInstrument( InstrumentTypes.Equity, securityIdentifiers2, "Standard Chartered", "CFI", "USD", "Standard Chartered Bank"); var securityIdentifiers3 = new InstrumentIdentifiers( null, null, null, "B00KT68", "B00KT68", null, null, null, null, null, "STAN1", null); var security3 = new FinancialInstrument( InstrumentTypes.Equity, securityIdentifiers3, "Standard Chartered", "CFI", "USD", "Standard Chartered Bank"); var exch = new Market(null, "NA", "NA", MarketTypes.STOCKEXCHANGE); var order1 = this.OrderMultiple(security1, exch); var order2 = this.OrderMultiple(security2, exch); var order3 = this.OrderMultiple(security3, exch); var order4 = this.OrderMultiple(security1, exch); await repo.Create(order1); await repo.Create(order2); await repo.Create(order3); await repo.Create(order4); var result1 = await repo.Get(order1.PlacedDate.Value, order3.PlacedDate.Value, this._opCtx); Assert.AreEqual(result1.Count, 3); }
public ActionResult Create(CreateOrderModel model) { /// Validating user input if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission); if (!ModelState.IsValid) return Error(Loc.Dic.error_invalid_form); if (String.IsNullOrEmpty(model.ItemsString)) return Error(Loc.Dic.error_invalid_form); List<Orders_OrderToItem> ItemsList = ItemsFromString(model.ItemsString, 0); if (ItemsList == null || ItemsList.Count == 0) return Error(Loc.Dic.error_invalid_form); if (model.IsFutureOrder && !Authorized(RoleType.FutureOrderWriter)) return Error(Loc.Dic.Error_NoPermission); if (model.Allocations == null || model.Allocations.Where(x => x.IsActive).Count() == 0) return Error(Loc.Dic.error_invalid_form); model.Allocations = model.Allocations.Where(x => x.IsActive).ToList(); decimal totalOrderPrice = (decimal.Floor(ItemsList.Sum(x => x.SingleItemPrice * x.Quantity) * 1000) / 1000); decimal totalAllocation = (decimal.Floor(model.Allocations.Sum(x => x.Amount) * 1000) / 1000); if (totalOrderPrice != totalAllocation) return Error(Loc.Dic.error_order_insufficient_allocation); // Initializing needed temporary variables bool allowExeeding = true; List<Orders_OrderToAllocation> AllocationsToCreate = new List<Orders_OrderToAllocation>(); // Setting order properties model.Order.UserId = CurrentUser.UserId; model.Order.Price = totalOrderPrice; model.Order.IsFutureOrder = model.IsFutureOrder; using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId)) using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId)) using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId)) { Budget currentBudget = budgetsRep.GetList().SingleOrDefault(x => x.IsActive); if (currentBudget == null) return Error(Loc.Dic.error_database_error); model.Order.BudgetId = currentBudget.Id; int[] orderAllocationsIds = model.Allocations.Select(x => x.AllocationId).Distinct().ToArray(); var allocationsData = allocationsRep.GetAllocationsData(orderAllocationsIds, StatusType.Pending); bool IsValidAllocations = (allocationsData.Count == orderAllocationsIds.Length) && model.Allocations.All(x => (x.MonthId == null || (x.MonthId >= 1 && x.MonthId <= 12)) && x.Amount > 0); if (!IsValidAllocations) return Error(Loc.Dic.error_invalid_form); if (model.IsFutureOrder) { foreach (var allocationData in allocationsData) { List<OrderAllocation> allocationMonths = model.Allocations.Where(x => x.AllocationId == allocationData.AllocationId).ToList(); foreach (var month in allocationMonths) { if (month.MonthId == DateTime.Now.Month) { OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId); var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month); if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation); AllocationsToCreate.AddRange(newAllocations); } else { var monthData = allocationData.Months.SingleOrDefault(x => x.MonthId == month.MonthId); if (!allowExeeding && month.Amount > monthData.RemainingAmount) return Error(Loc.Dic.error_order_insufficient_allocation); Orders_OrderToAllocation newAllocation = new Orders_OrderToAllocation() { AllocationId = allocationData.AllocationId, MonthId = month.MonthId.Value, Amount = month.Amount, OrderId = 0 }; AllocationsToCreate.Add(newAllocation); } } } } else { foreach (var allocationData in allocationsData) { OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId); var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month); if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation); AllocationsToCreate.AddRange(newAllocations); } } if (!CurrentUser.OrdersApprovalRouteId.HasValue) { model.Order.NextOrderApproverId = null; model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice; } else { Users_ApprovalRoutes orderRoute = routesRep.GetEntity(CurrentUser.OrdersApprovalRouteId.Value, "Users_ApprovalStep"); Users_ApprovalStep firstStep = orderRoute.Users_ApprovalStep.OrderBy(x => x.StepNumber).FirstOrDefault(); if (firstStep != null) { model.Order.ApprovalRouteId = orderRoute.Id; model.Order.ApprovalRouteStep = firstStep.StepNumber; model.Order.NextOrderApproverId = firstStep.UserId; model.Order.StatusId = (int)StatusType.Pending; } else { model.Order.ApprovalRouteStep = null; model.Order.NextOrderApproverId = null; model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice; } } } using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) using (OrderToItemRepository orderToItemRep = new OrderToItemRepository()) using (OrderToAllocationRepository orderAllocationsRep = new OrderToAllocationRepository()) { bool creationError = false; if (!ordersRep.Create(model.Order)) return Error(Loc.Dic.error_orders_create_error); model.Order = ordersRep.GetEntity(model.Order.Id, "User", "User1"); foreach (Orders_OrderToItem item in ItemsList) { item.OrderId = model.Order.Id; if (!orderToItemRep.Create(item)) { creationError = true; break; } } foreach (var allocation in AllocationsToCreate) { allocation.OrderId = model.Order.Id; if (!orderAllocationsRep.Create(allocation)) { creationError = true; break; } } if (creationError) { ordersRep.Delete(model.Order.Id); return Error(Loc.Dic.error_orders_create_error); } } using (OrdersHistoryRepository ordersHistoryRepository = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, model.Order.Id)) { Orders_History orderHis = new Orders_History(); ordersHistoryRepository.Create(orderHis, (int)HistoryActions.Created, model.NotesForApprover); } if (model.Order.NextOrderApproverId.HasValue) { SendNotifications.OrderPendingApproval(model.Order, Url); } return RedirectToAction("MyOrders"); }
public void CreateOrder(Order order) { ordersRepository.Create(order); }
public string CreateOrder(string Account, string Pay, string Transport, decimal TranMoney) { var cart_R = RepositoryContainer.GetInstance <ShoppingCartRepository>(); var orders_R = new OrdersRepository(); var order_Details_R = new Order_DetailsRepository(); var stock_R = new StockRepository(); var products_R = new ProductsRepository(); var now_time = DateTime.Now; SqlConnection connection = new SqlConnection(SqlConnect.str); connection.Open(); var transaction = connection.BeginTransaction(); try { orders_R.Create(connection, new Orders { Account = Account, Order_Check = 0, Order_Date = now_time, Pay = Pay, TranMoney = TranMoney, Transport = Transport, }, transaction); string errorMessage = ""; var order = orders_R.GetLatestByAccount(connection, Account, transaction); var items = cart_R.GetByAccount(connection, Account, transaction); decimal totalmoney = 0; foreach (var item in items) { if (stock_R.CheckInventory(item.Product_ID, item.size, item.Color, item.Quantity) == false) { errorMessage += "產品 :" + products_R.GetByProduct_ID(item.Product_ID).Product_Name + " 庫存不足\n"; } else { totalmoney += item.Quantity * products_R.GetByProduct_ID(item.Product_ID).UnitPrice; order_Details_R.Create(connection, new Order_Details() { Order_ID = order.Order_ID, Product_ID = item.Product_ID, Quantity = (short)item.Quantity, size = item.size, Price = item.Quantity * products_R.GetByProduct_ID(item.Product_ID).UnitPrice, Color = item.Color }, transaction); stock_R.Update(connection, new Stock() { Product_ID = item.Product_ID, Size = item.size, Quantity = stock_R.GetByPK(item.Product_ID, item.size, item.Color).Quantity - item.Quantity, Color = item.Color }, transaction); } } if (errorMessage.Length <= 1) { cart_R.DeleteByAccount(Account); orders_R.Update(order.Order_ID, totalmoney + TranMoney, connection, transaction); transaction.Commit(); connection.Close(); return("新訂單"); } else { throw new Exception(errorMessage); } } catch (Exception ex) { Console.WriteLine(ex.Message); transaction.Rollback(); return(ex.Message); } }
public ActionResult Shopping5() { List <Shopping> shopping; User user; ShipData ship; JavaScriptSerializer JSONSerializer = new JavaScriptSerializer(); if (Request.Cookies["shoppingcar"] != null && Request.Cookies["user"] != null && Request.Cookies["ShipData"] != null) { string json = HttpUtility.UrlDecode(Request.Cookies["shoppingcar"].Value); shopping = JSONSerializer.Deserialize <List <Shopping> >(json); string json1 = HttpUtility.UrlDecode(Request.Cookies["user"].Value); user = JSONSerializer.Deserialize <User>(json1); string json2 = HttpUtility.UrlDecode(Request.Cookies["ShipData"].Value); ship = JSONSerializer.Deserialize <ShipData>(json2); SqlConnection connection = new SqlConnection("data source=.; database=Commerce; integrated security=true"); connection.Open(); using (var transaction = connection.BeginTransaction()) { try { var order = new Orders() { MemberID = user.UserID, EmployeeID = 1, OrderDate = DateTime.Now, Discount = 1, ReceiptedDate = null, ShipName = ship.ShipName, ShipPhone = ship.ShipPhone, ShipAddress = ship.ShipAddress, ShippedDate = null, Status = "未出貨" }; var orderrepository = new OrdersRepository(); orderrepository.Create(order, connection, transaction); var memberrepository = new MemberRepository(); var memberorder = memberrepository.GetBuyerOrder(user.UserID, connection, transaction); var lastordeer = memberorder.First(); var orderdetailrepository = new OrderDetailsRepository(); foreach (var item in shopping) { OrderDetails od = new OrderDetails() { OrderID = lastordeer.OrderID, ProductFormatID = item.ProductFormatID, Quantity = item.Quantity, UnitPrice = item.UnitPrice }; orderdetailrepository.Create(od, connection, transaction); } transaction.Commit(); return(RedirectToAction("Shopping6", "Shopping")); } catch (Exception) { transaction.Rollback(); return(RedirectToAction("", "Shopping")); } } } else { return(RedirectToAction("", "Shopping")); } //做order跟orderdetail }