public void Run() { using (var session = sessionFactory.OpenSession()) { long id; using (var tx = session.BeginTransaction()) { var order = new CustomerOrder {Comments = "No comment.", DatePlaced = DateTime.Now}; id = (long) session.Save(order); tx.Commit(); } var savedOrder = session.Get<CustomerOrder>(id); Console.WriteLine(); Console.WriteLine(savedOrder); } }
public async Task <CustomerOrder> CreateOrderItemsFromCart(string cart_id) { CustomerOrder order = new CustomerOrder(); try { CustomerCart cart = await unitOfWork.Carts.GetCartDetails(cart_id, true); using (var connection = this.GetOpenConnection()) { order.customer_id = cart.customer_id; order.order_total = cart.cart_total; order.total_payable = cart.total_payable; order.discount_amount = cart.cart_discount; var result = await connection.InsertAsync(order); if (cart.cartItems != null && cart.cartItems.Count > 0) { foreach (var item in cart.cartItems) { CustomerOrderItem orderitem = new CustomerOrderItem(); orderitem.rec_id = Guid.NewGuid().ToString().ToLower().Replace("-", ""); orderitem.order_id = order.rec_id; orderitem.qty = item.qty; orderitem.price = item.price; orderitem.total_payable = item.total_payable; orderitem.product_id = item.product_id; var Id = (int)await connection.InsertAsync(orderitem); order.orderItems.Add(orderitem); } } } } catch (Exception ex) { return(null); } return(order); }
public static CustomerOrderEntity ToDataModel(this CustomerOrder order) { if (order == null) { throw new ArgumentNullException("order"); } var retVal = new CustomerOrderEntity(); retVal.InjectFrom(order); retVal.Currency = order.Currency.ToString(); if (order.Addresses != null) { retVal.Addresses = new ObservableCollection <AddressEntity>(order.Addresses.Select(x => x.ToDataModel())); } if (order.Items != null) { retVal.Items = new ObservableCollection <LineItemEntity>(order.Items.Select(x => x.ToDataModel())); } if (order.Shipments != null) { retVal.Shipments = new ObservableCollection <ShipmentEntity>(order.Shipments.Select(x => x.ToDataModel(retVal))); } if (order.InPayments != null) { retVal.InPayments = new ObservableCollection <PaymentInEntity>(order.InPayments.Select(x => x.ToDataModel(retVal))); } if (order.Discount != null) { retVal.Discounts = new ObservableCollection <DiscountEntity>(new DiscountEntity[] { order.Discount.ToDataModel() }); } if (order.TaxDetails != null) { retVal.TaxDetails = new ObservableCollection <TaxDetailEntity>(); retVal.TaxDetails.AddRange(order.TaxDetails.Select(x => x.ToDataModel())); } return(retVal); }
private static OrderSummary CreateOrderSummary(CustomerOrder order) { // Retrieve all the menu items var menuItems = MenuItem.GetAll(); // Iterate through the list of ordered items to calculate // the total and compile a list of item summaries. var orderTotal = 0.0m; var itemSummaries = new List <OrderItemSummary>(); foreach (var orderItem in order.OrderItems) { var menuItem = menuItems.FirstOrDefault(x => x.MenuItemId == orderItem.MenuItemId); if (menuItem == null) { continue; } orderTotal += (menuItem.Price * orderItem.Quantity); itemSummaries.Add(new OrderItemSummary { Quantity = orderItem.Quantity, MenuItemId = orderItem.MenuItemId, MenuItemName = menuItem.Name }); } // Initialize and return the order summary var summary = new OrderSummary { OrderId = Guid.NewGuid(), StoreId = order.StoreId, CustomerName = order.CustomerName, LoyaltyId = order.LoyaltyId, OrderDate = DateTime.UtcNow, OrderItems = itemSummaries, OrderTotal = orderTotal }; return(summary); }
public async Task <bool> UpdateOrderAsync(CustomerOrder order) { await using var transaction = await _dbContext.Database.BeginTransactionAsync(); try { _dbContext.CustomerOrder.Update(order); await _dbContext.SaveChangesAsync(); await transaction.CommitAsync(); } catch { await transaction.RollbackAsync(); return(false); } return(true); }
//this method is need to be called when HTTP POST is done public IActionResult Checkout(CustomerOrder order) //order is created by using model binding { var items = _shoppingCart.GetShoppingCartItems(); _shoppingCart.ShoppingCartItems = items; if (_shoppingCart.ShoppingCartItems.Count == 0) { ModelState.AddModelError("", "Your cart is empty, add some items first"); } if (ModelState.IsValid) //check model state is valid property //IsValid Property is going to check the state of the odere model instance { _orderRepository.CreateOrder(order); _shoppingCart.ClearCart(); return(RedirectToAction("CheckoutComplete")); } return(View(order)); }
private bool MyChefContentMatchesExactly(CustomerOrder order, string[] items) { var orderItems = order.Items.Split('-').OrderBy(x => x).ToArray(); if (orderItems.Length != items.Length) { return(false); } var sortedItems = items.OrderBy(x => x).ToArray(); for (int i = 0; i < orderItems.Length; i++) { if (orderItems[i] != sortedItems[i]) { return(false); } } return(true); }
public bool CreateOrUpdateCustomerOrder(CustomerOrder customerOrder) { bool result = false; try { _daoManager.OpenConnection(); _customerOrderDao.CreateOrUpdateCustomerOrder(customerOrder); result = true; } catch (Exception exception) { result = false; LogHelper.GetInstance().Error(string.Format("[CreateOrUpdateCustomerOrder]参数:customerOrder_{0}", JsonConvert.SerializeObject(customerOrder)), exception); } finally { _daoManager.CloseConnection(); } return(result); }
private void WriteOrder(CustomerOrder Ordertransaction, LinkedList <CustomerOrderLineItem> OrderLineItem) { CustomerOrderLineItem[] s2 = OrderLineItem.ToArray <CustomerOrderLineItem>(); con = new SqlConnection(); cmd = new SqlCommand(); con.ConnectionString = Connection; con.Open(); cmd.Connection = con; //transaction cmd.CommandText = string.Format("insert into CustomerOrder ([BillNo.],PurchaseDate,Amount,CustomerId) values('{0}','{1}','{2}','{3}')", Ordertransaction.BillNo, Ordertransaction.PurchaseDate, Ordertransaction.TotalAmount, Ordertransaction.CustomerId); cmd.ExecuteNonQuery(); for (int i = 0; i < s2.Length; i++) {//transaction line item cmd.CommandText = string.Format("insert into CustomerOrderLineItem ([BillNo.],Quantity,[Product Id],[Product Name],Rate,Amount) values('{0}','{1}','{2}','{3}','{4}','{5}')", s2[i].BillNo, s2[i].Quantity, s2[i].ProductId, s2[i].ProductName, s2[i].Rate, s2[i].Amount); cmd.ExecuteNonQuery(); } con.Close(); }
//BUSA-1345: SS orders should start with S-series Requestor & Approver flow. public void GetOrderNumberPrefix(CustomerOrder customerOrder) { bool isSubscriptionOrder = false; foreach (var orderLine in customerOrder.OrderLines.ToList()) { if (orderLine.CustomProperties.Where(y => y.Name == "IsSubscriptionOpted").Count() > 0) { var value = orderLine.CustomProperties.Where(x => x.Name.EqualsIgnoreCase("IsSubscriptionOpted")).FirstOrDefault().Value; if (bool.Parse(value)) { isSubscriptionOrder = true; break; } } } if (isSubscriptionOrder) { customerOrder.OrderNumber = this.customSettings.SmartSupply_Prefix + customerOrder.OrderNumber.Substring(1); } }
/// <summary> /// /// </summary> /// <param name="email"></param> /// <returns></returns> public static IRestResponse SendSimpleMessage(string email) { var order = new CustomerOrder(); RestClient client = new RestClient(); client.BaseUrl = new Uri("https://api.mailgun.net/v3"); client.Authenticator = new HttpBasicAuthenticator("api", "key-f72d70c645350a58d4ce92d0df30c281"); RestRequest request = new RestRequest(); request.AddParameter("domain", "sandbox914ac94e81cc46408d1ecd8a6ca9d54d.mailgun.org", ParameterType.UrlSegment); request.Resource = "{domain}/messages"; request.AddParameter("from", "Shop Staff <*****@*****.**>"); request.AddParameter("to", email); request.AddParameter("subject", "Your Order has been placed"); request.AddParameter("text", "Thank you for placing an order with our shop, we have just begun processing your order. You will recieve a follow up email when your order is ready for collection"); request.Method = Method.POST; return(client.Execute(request)); }
public void Run() { using (var session = sessionFactory.OpenSession()) { long id; using (var tx = session.BeginTransaction()) { var order = new CustomerOrder { Comments = "No comment.", DatePlaced = DateTime.Now }; id = (long)session.Save(order); tx.Commit(); } var savedOrder = session.Get <CustomerOrder>(id); Console.WriteLine(); Console.WriteLine(savedOrder); } }
private void AddPromotionCode(IUnitOfWork unitOfWork, CustomerOrder customerOrder, OrderPromotionCode orderPromotionCode) { if (this.promotionEngine.ListContainsPromotionCode(customerOrder.OrderPromotionCodes.Select <OrderPromotionCode, string>((Func <OrderPromotionCode, string>)(o => o.Code)), orderPromotionCode.Code)) { return; } IRepository <OrderPromotionCode> repository = unitOfWork.GetRepository <OrderPromotionCode>(); foreach (OrderPromotionCode deleted in customerOrder.OrderPromotionCodes.ToList <OrderPromotionCode>()) { repository.Delete(deleted); } unitOfWork.Save(); orderPromotionCode.CustomerOrder = customerOrder; customerOrder.OrderPromotionCodes.Add(orderPromotionCode); repository.Insert(orderPromotionCode); customerOrder.RecalculatePromotions = true; customerOrder.ShippingCalculationNeededAsOf = DateTimeProvider.Current.Now; customerOrder.RecalculateTax = true; }
/// <summary> /// 根据客户订单号获取客户订单信息(对外打印标签接口) /// </summary> /// <param name="orderNumbers"></param> /// <returns></returns> public List <CustomerOrderInfo> PrintByCustomerOrderNumbers(List <string> orderNumbers, string customerCode) { int deleteStatus = CustomerOrder.StatusToValue(CustomerOrder.StatusEnum.Delete); var orderInfoList = _customerOrderInfoRepository.GetList(p => orderNumbers.Contains(p.CustomerOrderNumber) && p.CustomerCode == customerCode && p.Status != deleteStatus); orderInfoList.ForEach(p => { if (p.IsPrinted) { return; } p.IsPrinted = true; p.LastUpdatedBy = customerCode; p.LastUpdatedOn = DateTime.Now; _customerOrderInfoRepository.Modify(p); }); _customerOrderInfoRepository.UnitOfWork.Commit(); return(orderInfoList); }
public virtual CustomerOrder Create(CustomerOrder order) { EnsureThatAllOperationsHaveNumber(order); _eventPublisher.Publish(new OrderChangeEvent(EntryState.Added, order, order)); var pkMap = new PrimaryKeyResolvingMap(); var entity = order.ToDataModel(pkMap); using (var repository = _repositoryFactory()) { repository.Add(entity); CommitChanges(repository); pkMap.ResolvePrimaryKeys(); } _dynamicPropertyService.SaveDynamicPropertyValues(order); var retVal = GetById(entity.Id, CustomerOrderResponseGroup.Full); return(retVal); }
public virtual CustomerOrder Create(CustomerOrder order) { EnsureThatAllOperationsHaveNumber(order); _eventPublisher.Publish(new OrderChangeEvent(EntryState.Added, null, order)); var entity = order.ToDataModel(); using (var repository = _repositoryFactory()) { repository.Add(entity); CommitChanges(repository); } order.SetObjectId(entity.Id); _dynamicPropertyService.SaveDynamicPropertyValues(order); var retVal = GetById(entity.Id, CustomerOrderResponseGroup.Full); return(retVal); }
public ActionResult PostOrder(CustomerOrder customerOrder) { var orders = JsonConvert.DeserializeObject <List <Order> >(customerOrder.Items); try { foreach (var item in orders) { _stocksService.UpdateItemQuantity(Guid.Parse(item.Id), item.Quantity); } } catch (Exception ex) { return(new HttpStatusCodeResult(500, ex.Message)); } _currentUserService.UpdateBalance(customerOrder.TotalSum); var newBalance = _currentUserService.GetBalance(); return(Redirect(Request.UrlReferrer.ToString())); }
public async Task <CustomerOrder> GetById(int id) { CustomerOrder order = await( from o in GetOrderById(id) select new CustomerOrder { CustomerName = $"{o.Customer.LastName}, {o.Customer.FirstName}", OrderFulfilled = o.OrderFulfilled.HasValue ? o.OrderFulfilled.Value.ToShortDateString() : string.Empty, OrderPlaced = o.OrderPlaced.ToShortDateString(), OrderLineItems = (from po in o.ProductOrder select new OrderLineItem { ProductQuantity = po.Quantity, ProductName = po.Product.Name }).ToList() }) .TagWith <CustomerOrder>($"Get order with ID {id}") .FirstOrDefaultAsync(); return(order); }
public static CustomerOrder ToCoreModel(this CustomerOrderEntity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } var retVal = new CustomerOrder(); retVal.InjectFrom(entity); retVal.Currency = (CurrencyCodes)Enum.Parse(typeof(CurrencyCodes), entity.Currency); if (entity.Properties != null) { retVal.Properties = entity.Properties.Select(x => x.ToCoreModel()).ToList(); } if (entity.Discounts != null && entity.Discounts.Any()) { retVal.Discount = entity.Discounts.First().ToCoreModel(); } if (entity.Items != null) { retVal.Items = entity.Items.Select(x => x.ToCoreModel()).ToList(); } if (entity.Addresses != null) { retVal.Addresses = entity.Addresses.Select(x => x.ToCoreModel()).ToList(); } if (entity.Shipments != null) { retVal.Shipments = entity.Shipments.Select(x => x.ToCoreModel()).ToList(); } if (entity.InPayments != null) { retVal.InPayments = entity.InPayments.Select(x => x.ToCoreModel()).ToList(); } retVal.TaxDetails = entity.TaxDetails.Select(x => x.ToCoreModel()).ToList(); return(retVal); }
public ActionResult AddressAndPayment(FormCollection values) { var order = new CustomerOrder(); var UserId = User.Identity.GetUserId(); TryUpdateModel(order); order.CustomerUserName = User.Identity.Name; order.DateCreated = DateTime.Now; db.CustomerOrders.Add(order); db.SaveChanges(); var cart = ShoppingCart.GetCart(this.HttpContext); cart.CreateOrder(order); db.SaveChanges(); //we have received the total amount lets update it return(RedirectToAction("Complete", new { id = order.Id, email = order.Email })); }
public IActionResult PlaceOrder(long AddressID) { try { var identity = User.Identity as ClaimsIdentity; if (identity != null) { IEnumerable <Claim> claims = identity.Claims; long CustomerID = Convert.ToInt64(claims.Where(p => p.Type == "CustomerID").FirstOrDefault()?.Value); CustomerOrder Order = customerOrderBL.PlaceOrder(CustomerID, AddressID); if (Order != null) { return(Ok(new { success = true, Message = "order placed successfully", Order })); } } return(BadRequest(new { success = false, Message = "order place Unsuccessful" })); } catch (Exception exception) { return(BadRequest(new { success = false, exception.Message })); } }
public static GetTaxResult Execute(CustomerOrder order, out string summary) { summary = ""; TaxServiceWrapper taxSvcWrapper = new TaxServiceWrapper(); TaxSvc taxSvc = taxSvcWrapper.GetTaxSvcInstance(order.InProduction); PostTaxRequest postTaxRequest = new PostTaxRequest(); GetTaxRequest getTaxRequest = BuildGetTaxRequest(order); GetTaxResult getTaxResult = taxSvc.GetTax(getTaxRequest); if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success)) { foreach (Message message in getTaxResult.Messages) { summary = message.Summary; } } return(getTaxResult); }
public void ShouldPrintSalesReportCapturingAllValidSales() { var priceList = new PriceList(); var salesData = new SalesData(); var salesRegister = new SalesRegister(salesData, priceList); var mockNotifier = new Mock <EmailNotifier>(); var mockChecker = new Mock <BeverageQuantityChecker>(); var orderProcessor = new OrderProcessor(priceList, salesRegister, mockNotifier.Object, mockChecker.Object); var customerOrder = new CustomerOrder(Drink.OrangeJuice); var customerOrder1 = new CustomerOrder(Drink.Coffee, temputure: (int)DrinkTemputure.Hot); var customerOrder2 = new CustomerOrder(Drink.Chocolate, 2); var customerOrder3 = new CustomerOrder(Drink.Tea, 2); orderProcessor.HandleOrder(customerOrder, (decimal)0.60); orderProcessor.HandleOrder(customerOrder1, (decimal)0.60); orderProcessor.HandleOrder(customerOrder2, (decimal)0.20); orderProcessor.HandleOrder(customerOrder3, (decimal)0.60); var salesReporter = new SalesReporter(salesData); var result = salesReporter.GenerateReport(); Assert.Equal("Coffee: 1\nTea: 1\nHot Chocolate: 0\nOrange Juice: 1\n\nTotal Sales: $1.60", result); }
public async Task <ActionResult> GetOrder(int id) { try { CustomerOrder order = await dbContext.CustomerOrders.Where(co => co.Id == id) .Include(co => co.Customer) .Include(co => co.OrderItems) .ThenInclude(oi => oi.Product) .FirstOrDefaultAsync(); if (order == null) { return(NotFound($"Order with Id: {id} not found")); } return(Ok(new Response <CustomerOrderFullDto>(mapper.Map <CustomerOrderFullDto>(order)))); } catch { return(StatusCode(StatusCodes.Status500InternalServerError)); } }
public static CustomerOrder ToOrder(this CsvOrderLine orderLine, CustomerOrder order) { if (orderLine == null) { throw new ArgumentNullException(nameof(orderLine)); } if (order == null) { order = new CustomerOrder() { CustomerId = orderLine.CustomerId, Name = orderLine.Name, Country = orderLine.Country }; } order.OrderLines.Add(orderLine); order.Weight += orderLine.Weight; return(order); }
public List <CustomerOrder> GetCustomerOrderByDateAndId(string from, string to, int id) { string sql = "SELECT * FROM Sales WHERE SalesDate BETWEEN '" + from + "' AND '" + to + "' AND CustomerId=" + id; this.dataAccess = new DataAccess(); SqlDataReader reader = this.dataAccess.GetData(sql); List <CustomerOrder> customerOrders = new List <CustomerOrder>(); while (reader.Read()) { CustomerOrder customerOrder = new CustomerOrder(); customerOrder.OrderId = (int)reader["OrderId"]; customerOrder.ProductName = reader["ProductName"].ToString(); customerOrder.ProductId = (int)reader["ProductId"]; customerOrder.SalesDate = reader["SalesDate"].ToString(); customerOrder.Quantity = (int)reader["Quantity"]; customerOrder.UnitPrice = Convert.ToDouble(reader["UnitPrice"]); customerOrder.TotalPrice = Convert.ToDouble(reader["TotalPrice"]); customerOrders.Add(customerOrder); } return(customerOrders); }
private PayRequest CreatePaypalRequest(CustomerOrder order, PaymentIn payment, string url) { var receivers = new List <Receiver>(); receivers.Add(new Receiver { amount = payment.Sum, email = "*****@*****.**", invoiceId = payment.Id }); PayRequest retVal = new PayRequest { requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" }, currencyCode = order.Currency.ToString(), receiverList = new ReceiverList(receivers), actionType = "PAY", cancelUrl = string.Format("{0}/{1}?cancel=true&orderId={2}", url, PaypalPaymentRedirectRelativePath, order.Id) + "&paykey=${paykey}", returnUrl = string.Format("{0}/{1}?cancel=false&orderId={2}", url, PaypalPaymentRedirectRelativePath, order.Id) + "&paykey=${paykey}" }; return(retVal); }
protected override void EnsureThatAllOperationsHaveNumber(CustomerOrder order) { var store = StoreService.GetById(order.StoreId); foreach (var operation in order.GetFlatObjectsListWithInterface <Domain.Commerce.Model.IOperation>()) { if (operation.Number == null) { if (operation.OperationType == "CustomerOrder") { CustomerOrderSearchCriteria criteria = new CustomerOrderSearchCriteria() { Sort = "createdDate:desc", Take = 1, ResponseGroup = "default" }; var lastOrder = _orderSearchService.SearchCustomerOrders(criteria).Results.First(); if (lastOrder != null) { operation.Number = (Convert.ToInt32(lastOrder.Number) + 1).ToString(); } } else { var objectTypeName = operation.OperationType; // take uppercase chars to form operation type, or just take 2 first chars. (CustomerOrder => CO, PaymentIn => PI, Shipment => SH) var opType = string.Concat(objectTypeName.Select(c => char.IsUpper(c) ? c.ToString() : "")); if (opType.Length < 2) { opType = objectTypeName.Substring(0, 2).ToUpper(); } var numberTemplate = opType + "{0:yyMMdd}-{1:D5}"; if (store != null) { numberTemplate = store.Settings.GetSettingValue("Order." + objectTypeName + "NewNumberTemplate", numberTemplate); } operation.Number = UniqueNumberGenerator.GenerateNumber(numberTemplate); } } } }
public async Task <IActionResult> PostAsync([FromBody] CustomerOrder customerOrder) { TransactionResult result; if (customerOrder == null) { return(BadRequest(Constant.Exception_InvalidOrder)); } using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) // not need in this case, // I already managed in unit of work // but I always use it for guaranting transactional operations { result = await this._orderService.SaveOrderAsync(customerOrder.OrderID, customerOrder.OrderItems); if (result.IsSuccessful) { scope.Complete(); return(StatusCode(201, string.Format(Constant.RequiredBinWidth, result.Content))); // Created } } return(BadRequest(result.ExceptionContentResult)); }
public override bool Validate(RuleClause ruleClause, object argument) { CustomerOrder customerOrder = argument as CustomerOrder; if (customerOrder == null) { throw new ArgumentException("argument must be of type CustomerOrder"); } Guid categoryId = this.TryParseGuid("SimpleValue", ruleClause.SimpleValue); bool isBasePrice = ruleClause.CriteriaValue.EqualsIgnoreCase("BasePrice"); var is_PromotionBasePrice = customerOrder.OrderLines.Where <OrderLine>((Func <OrderLine, bool>)(o => { ICollection <Category> categories = o.Product.Categories; int count = 0; foreach (Category category in categories) { if (categoryId == category.Id) { count++; } } if (count == 0) { return(false); } if (o.Product.IsQuoteRequired) { return(ruleClause.RuleManager.Name != "Promotion"); } return(true); })).Where(o => o.UnitNetPrice == o.UnitListPrice); if (is_PromotionBasePrice.Count() > 0 && isBasePrice) { return(true); } return(false); }
public static void DisplayOrders() { List <Customer> customers = new List <Customer>(); CustomerOrder customerOrder = new CustomerOrder(); CustomerOrderRepository customerOrderRepository = new CustomerOrderRepository(); customers = customerOrderRepository.LoadAllCustomers(); foreach (var cust in customers) { customerOrder.orders = customerOrderRepository.LoadAllOrders(cust.CustomerId); Console.WriteLine("***************************************************"); Console.WriteLine("Customer Name : " + cust.Name); Console.WriteLine("Orders: "); foreach (var order in customerOrder.orders) { Console.WriteLine("\tOrder ID: " + order.OrderId); Console.WriteLine("\tOrder Amount:" + order.Amount); } } }
public void OnOrderNotification(CustomerOrder order) { MessageBox.Show("Order Id = " + order.CustomerOrderId + " " + "Table Id = " + order.TableId + " " + "Status = " + ((OrderStatus)order.Status).ToString(), "Order Status"); }
public OrderPlacedEvent(CustomerOrder order, ShoppingCart cart) { Cart = cart; Order = order; }