void IOrderHelper.AddOrder(OrderModel model) { var adress = model.Client.Name + " " + model.Client.Surname + ";" + model.Client.Street + ";" + model.Client.PostalCode + ";" + model.Client.City; var order = new orders { Id_Client = model.Client.Id, Id_Delivery = model.selectedDeliveryId, Id_Status = 1, ToPay = model.cart.ComputeTotalValue(), AdressToDelivery = adress, InsertTime = DateTime.Now, }; //dodanie nowego zamówienia => przejscie do wypełnienia szczegółów zamówienia var orderId = _ordersRepository.AddOrder(order); var orderDetails = new List<order_details>(); var arrayToList = model.cart.Lines.ToList(); for (int i = 0; i < arrayToList.Count - 1; i++) { orderDetails.Add(new order_details { Id_Order = orderId, Id_Item = arrayToList[i].Item.Id, Quantity = arrayToList[i].Quantity }); } _ordersRepository.AddOrderDetails(orderDetails); }
public async Task<ReplaceOneResult> UpdateOrder(Job job, OrderModel orderModel) { if (job.Order.Type != orderModel.Type) { throw new InvalidOperationException("Updating with a different ordermodel for this job"); } // FIXME: Finding a resolver here would help here dude switch (orderModel.Type) { case OrderTypes.Delivery: case OrderTypes.ClassifiedDelivery: { var orderCalculationService = new DefaultOrderCalculationService(); var serviceChargeCalculationService = new DefaultDeliveryServiceChargeCalculationService(); var orderProcessor = new DeliveryOrderProcessor( orderCalculationService, serviceChargeCalculationService); orderProcessor.ProcessOrder(orderModel); var jobUpdater = new DeliveryJobUpdater(job); jobUpdater.UpdateJob(orderModel); job = jobUpdater.Job; break; } } var result = await UpdateJob(job); return result; }
public async Task<IHttpActionResult> PostOrder(OrderModel model, OrderCreationOptions opt = OrderCreationOptions.CREATE) { if (model == null) return BadRequest("No freaking payload man!"); if (!ModelState.IsValid) return BadRequest(ModelState); var currentUserId = this.User.Identity.GetUserId(); if (!this.User.IsInRole(RoleNames.ROLE_ADMINISTRATOR) && !this.User.IsInRole(RoleNames.ROLE_BACKOFFICEADMIN)) { if (model.UserId != null && model.UserId != currentUserId) throw new InvalidOperationException(string.Format("Updating order/job id {0} is not authorized against user id {1}", model.UserId, this.User.Identity.GetUserId())); if (opt == OrderCreationOptions.CREATE_AND_CLAIM) throw new InvalidOperationException(string.Format("Claiming a job under user id {0} is not authorized", User.Identity.GetUserId())); } if (model.UserId == null) model.UserId = currentUserId; Job createdJob; switch (opt) { case OrderCreationOptions.CREATE: createdJob = await _repository.PostOrder(model); return Ok(createdJob); case OrderCreationOptions.CREATE_AND_CLAIM: createdJob = await _repository.PostOrder(model, currentUserId); return Ok(createdJob); default: throw new InvalidOperationException("Invalid OrderCreationOptions selected"); } }
protected void Page_Load(object sender, EventArgs e) { List<Cart> carts = (List<Cart>)Application["ShoppingCart"]; string clientName = Application["clientName"].ToString(); int clientId = Convert.ToInt32(Application["clientId"]); DateTime date = DateTime.Now; double totalAmount = Convert.ToDouble(Application["totalAmount"]); //Create new record in database OrderModel orderModel = new OrderModel(); Order order = new Order { ClientID = clientId, OrderDate = date, Status = "Waitting", TotalAmount = totalAmount, }; string id = orderModel.InsertOrder(order); //Fill page lblName.Text = clientName; lblDate.Text = date.ToString(); lblStatus.Text = "Waitting"; lblAmount.Text = "$ " + totalAmount.ToString(); lblNumber.Text = id; CartModel cartModel = new CartModel(); cartModel.MarkOrderAsPaid(carts); Application["ShoppingCart"] = null; }
public JobBuilder(OrderModel order, UserModel userModel, IHRIDService hridService, Vendor vendor = null) { job = new Job(order, hridService.NextId("Job")); job.User = userModel; job.Vendor = vendor; job.ProfitShareResult = vendor?.Strategy?.Calculate(order.OrderCart.TotalToPay.Value); }
public void VmShouldUseResourceNameNewEntity() { InitializeRepository(); var model = new OrderModel(); var viewModel = GetViewModel<OrderEditorViewModel>(); viewModel.InitializeEntity(model, true); Assert.AreEqual(viewModel.DisplayName, UiResources.OrderNewDisplayName); }
public void VmShouldUseResourceNameEditEntity() { InitializeRepository(); var model = new OrderModel(); var viewModel = GetViewModel<OrderEditorViewModel>(); viewModel.InitializeEntity(model, Enumerable.Empty<OrderProductModel>()); Assert.AreEqual(viewModel.DisplayName, UiResources.OrderEditDisplayName); }
public JobBuilder(OrderModel order, UserModel userModel, UserModel adminUserModel, IHRIDService hridService, Vendor vendor = null) : this(order, userModel, hridService, vendor) { if (adminUserModel == null) throw new ArgumentNullException(nameof(adminUserModel)); job.JobServedBy = adminUserModel; }
public EditOrder(OrderModel dataModel) { InitializeComponent(); listControl = new OrderDetailControl(dataModel.DetailModel); listControl.Dock = DockStyle.Top; this.listPanel.Controls.Add(listControl); this.dataModel = dataModel; }
public ActionResult ToOrder() { if (Manager.IsAuthentication) { OrderModel model = new OrderModel(); return View(model); } else return Redirect(Url.Action("Index", "Home")); }
public void VmShouldLoadProductsFromRepository() { var models = new[] { new ProductModel(), new ProductModel() }; InitializeRepository(models); var model = new OrderModel(); var viewModel = GetViewModel<OrderEditorViewModel>(); viewModel.InitializeEntity(model, true); Assert.IsTrue(viewModel.GridViewModel.OriginalItemsSource.All(wrapper => !wrapper.IsSelected)); Assert.IsTrue(viewModel.GridViewModel.OriginalItemsSource.Select(wrapper => wrapper.Model).SequenceEqual(models)); }
public ActionResult Destroy([DataSourceRequest]DataSourceRequest request, OrderModel viewModel) { var error = this.LoadModel<OrderModel, bool>(false).Delete(viewModel); if (error != null) { return this.Json(error); } return this.GridOperation(viewModel, request); }
public void VmShouldLoadProductsFromRepositoryAndRestoreSelection() { var models = new[] { new ProductModel(), new ProductModel { Id = Guid.NewGuid() } }; var links = new[] { new OrderProductModel { IdProduct = models[1].Id } }; InitializeRepository(models); var model = new OrderModel(); var viewModel = GetViewModel<OrderEditorViewModel>(); viewModel.InitializeEntity(model, links); Assert.IsTrue(viewModel.GridViewModel.OriginalItemsSource.Single(wrapper => wrapper.Model == models[1]).IsSelected); Assert.IsTrue(viewModel.GridViewModel.OriginalItemsSource.Select(wrapper => wrapper.Model).SequenceEqual(models)); }
public OrderDetailControl(OrderModel.OrderDetailModel dataModel) { InitializeComponent(); _controls = new Control[] { this.btnAddnewProduct, this.btnRemoveProducts, this.btnRemoveAll }; this.dataModel = dataModel; addForm = new AddItem(this.dataModel); }
public override bool UpdateOrder(OrderModel model) { using (SqlConnection cn = new SqlConnection(this.ConnectionString)) { SqlCommand cmd = new SqlCommand("proc_UPDATE_ORDER", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ID", SqlDbType.Int).Value = model.Id; cmd.Parameters.Add("@ID_USER", SqlDbType.Int).Value = model.IdUser; cmd.Parameters.Add("@Id_ORDER_DETAIL", SqlDbType.Int).Value = model.IdOrderDetail; cmd.Parameters.Add("@STATUS", SqlDbType.Int).Value = model.Status; cn.Open(); int re = ExecuteNonQuery(cmd); return (re == 1); } }
public void VmShouldNotBeValidNameNull() { InitializeRepository(new[] { new ProductModel() }); var model = new OrderModel { Number = "test", Id = Guid.NewGuid() }; var viewModel = GetViewModel<OrderEditorViewModel>(); viewModel.InitializeEntity(model, false); viewModel.GridViewModel.OriginalItemsSource[0].IsSelected = true; Assert.IsFalse(viewModel.IsValid); viewModel.Name = "test"; viewModel.ValidateAsync(() => editorViewModel => editorViewModel.Name); Assert.IsTrue(viewModel.IsValid); }
public void PlaceOrder(OrderModel order) { if (order.Quantity <= 0) throw new NotSupportedException(); using (var transaction = new TransactionScope(TransactionScopeOption.Required)) { CustomerBase customer; ProductBase prod; using (var mappers = new OrdersDataMapperContainer()) { prod = EnsureProductExistance(mappers.ProductMapper, order.ProductCode); customer = EnsureCustomerExistance(mappers.CustomerMapper, order.CustomerId); using (var orderService = new CustomerOrderReceiverServiceClient()) { orderService.HandleOrder(new CustomerOrderModel { CustomerId = order.CustomerId, ProductCode = order.ProductCode, Quantity = order.Quantity }); } try { using (var notification = new NotificationServiceClient()) { notification.SendEmail(customer.Email, "Your order was ."); } } catch { // if it fails ignore. } transaction.Complete(); } } }
public override OrderModel GetByIdOrder(int id) { using (SqlConnection cn = new SqlConnection(this.ConnectionString)) { SqlCommand cmd = new SqlCommand("proc_GET_ORDER_BY_ID", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ID", SqlDbType.Int).Value = id; cn.Open(); IDataReader reader = ExecuteReader(cmd, CommandBehavior.SingleRow); if (reader.Read()) { OrderModel model = new OrderModel { (int)reader["id"], (int)reader["IdUser"], (int)reader["IdOrderDetail"], (int)reader["STATUS"] }; } else return null; } }
OrderModel IOrderHelper.GetOrderModel(Cart cart, AccountModel client) { var delivery = _ordersRepository.DictOrdersDelivery; var selectListItemDelivery = new List<SelectListItem>(); var modelToReturn = new OrderModel(); foreach (var item in delivery) { selectListItemDelivery.Add(new SelectListItem { Text = item.Name + " - " + item.Price.ToString("c"), Value = item.Id.ToString() }); } modelToReturn.OrderDelivery = selectListItemDelivery; modelToReturn.cart = cart; modelToReturn.Client = client; modelToReturn.TotalPrice = cart.ComputeTotalValue(); return modelToReturn; }
public Task<bool> OrderAsync(string userId) { var task = Task.Run(async () => { List<OrderDetail> userOrders; if (RemoveFromUserFromCart(userId, out userOrders) == false) return false; var orderId = Guid.NewGuid().ToString(); var orderModel = new OrderModel { OrderId = orderId, UserId = userId, OrderDate = DateTime.Now }; var total = userOrders.Sum(p => p.Total); userOrders.ForEach(p => p.OrderId = orderId); var payTask = await _paymentService.Pay(total); if (string.IsNullOrEmpty(payTask) == true) { //return order to cart; //cancle order } var addOrderTask = await AddOrder(orderModel, userOrders); if (addOrderTask == true) { var locations = userOrders.Select(p => p.LocationId); foreach (var location in locations) { _locationsService.SetAsUnAvailable(location); } return true; } return false; }); return task; }
public SingleResult <OrderPreViewResultDto> CustomerOrderPreview_UI(OrderModel order) { try { var orerProductList = new List <CustomerOrderProduct>(); var time = DateTime.Now.Ticks; order.ProductList.ForEach(c => { var product = _repository.Product.FindByCondition(x => x.Id == c.ProductId).First(); var ofer = _repository.ProductOffer.FindByCondition(x => x.ProductId == c.ProductId && x.FromDate <= time && time <= x.ToDate && x.DaDate == null && x.Ddate == null).Include(c => c.Offer).FirstOrDefault(); var packingType = _repository.ProductPackingType.FindByCondition(x => x.Id == c.PackingTypeId) .FirstOrDefault(); var statusId = _repository.Status.GetSatusId("CustomerOrderProduct", 2); var orderproduct = new CustomerOrderProduct { OrderCount = c.Count, ProductId = c.ProductId, ProductCode = product.Coding, ProductName = product.Name, ProductPrice = product.Price, ProductOfferId = ofer?.Id, ProductOfferCode = ofer?.Offer.OfferCode, ProductOfferPrice = (long?)(ofer != null ? (ofer.Value / 100 * product.Price) : 0), ProductOfferValue = ofer?.Value, PackingTypeId = c.PackingTypeId, PackingWeight = packingType == null ? 0 : packingType.Weight, PackingPrice = packingType == null ? 0 : packingType.Price, SellerId = product.SellerId, Weight = c.Count * product.Weight, FinalWeight = (c.Count * product.Weight) + (c.Count * (packingType == null ? 0 : packingType.Weight)), FinalStatusId = statusId }; orerProductList.Add(orderproduct); }); var offer = _repository.Offer.FindByCondition(c => c.Id == order.OfferId).FirstOrDefault(); var paking = _repository.PackingType.FindByCondition(c => c.Id == order.PaymentTypeId).FirstOrDefault(); var customerOrder = new OrderPreViewResultDto(); customerOrder.OrderPrice = orerProductList.Sum(c => (c.ProductPrice + c.PackingPrice - c.ProductOfferPrice) * c.OrderCount); if (offer != null) { if (offer.Value == 0 || offer.Value == null) { customerOrder.OfferPrice = offer.MaximumPrice > customerOrder.OrderPrice ? customerOrder.OrderPrice : offer.MaximumPrice; customerOrder.OfferValue = null; } else { customerOrder.OfferPrice = (long?)(customerOrder.OrderPrice * (offer.Value / 100)); customerOrder.OfferValue = (int?)offer.Value.Value; } } else { customerOrder.OfferPrice = 0; customerOrder.OfferValue = null; } customerOrder.FinalWeight = orerProductList.Sum(x => x.FinalWeight); customerOrder.OrderWeight = customerOrder.FinalWeight; customerOrder.PaymentTypeId = order.PaymentTypeId; customerOrder.PostServicePrice = 0; customerOrder.ProductList = orerProductList; var toCityId = _repository.CustomerAddress.FindByCondition(c => c.Id == order.CustomerAddressId).Include(c => c.City).Select(c => c.City.PostCode).FirstOrDefault(); var postType = _repository.PostType.FindByCondition(c => c.Id == order.PostTypeId).FirstOrDefault(); var payType = _repository.PaymentType.FindByCondition(c => c.Id == order.PaymentTypeId) .FirstOrDefault(); if (postType.IsFree.Value) { customerOrder.PostServicePrice = 0; } else { var post = new PostServiceProvider(); var postpriceparam = new PostGetDeliveryPriceParam { Price = (int)customerOrder.OrderPrice.Value, Weight = (int)customerOrder.FinalWeight.Value, ServiceType = postType?.Rkey ?? 2,// (int)customerOrder.PostTypeId, ToCityId = (int)toCityId, PayType = (int)(payType?.Rkey ?? 88) }; var postresult = post.GetDeliveryPrice(postpriceparam).Result; if (postresult.ErrorCode != 0) { throw new BusinessException(XError.IncomingSerivceErrors.PostSeerivcError()); } customerOrder.PostServicePrice = (postresult.PostDeliveryPrice + postresult.VatTax) / 10; } customerOrder.FinalPrice = customerOrder.OrderPrice - customerOrder.OfferPrice + customerOrder.PostServicePrice; var finalres = SingleResult <OrderPreViewResultDto> .GetSuccessfulResult(customerOrder); _logger.LogData(MethodBase.GetCurrentMethod(), finalres, null, order); return(finalres); } catch (Exception e) { _logger.LogError(e, MethodBase.GetCurrentMethod(), order); return(SingleResult <OrderPreViewResultDto> .GetFailResult(e.Message)); } }
private void Construct( Context context, List <SelectedSite> siteList, bool includeRecordPermission, bool includeColumnPermission) { var recordIdList = new List <long>(); if ((siteList != null) && (siteList.Count > 0)) { foreach (SelectedSite site in siteList) { var siteModel = new SiteModel( context: context, siteId: site.SiteId); var packageSiteModel = new PackageSiteModel(new SiteModel( context: context, siteId: site.SiteId)); if (packageSiteModel.ReferenceType == "Wikis") { var wikiId = Repository.ExecuteScalar_long( context: context, statements: Rds.SelectWikis( top: 1, column: Rds.WikisColumn().WikiId(), where : Rds.WikisWhere().SiteId(siteModel.SiteId))); var wikiModel = new WikiModel( context: context, ss: siteModel.SiteSettings, wikiId: wikiId); packageSiteModel.WikiId = wikiId; packageSiteModel.Body = wikiModel.Body; } if (includeColumnPermission == false) { packageSiteModel.SiteSettings.CreateColumnAccessControls?.Clear(); packageSiteModel.SiteSettings.ReadColumnAccessControls?.Clear(); packageSiteModel.SiteSettings.UpdateColumnAccessControls?.Clear(); } Sites.Add(packageSiteModel); string order = null; if (siteModel.ReferenceType == "Sites") { var orderModel = new OrderModel( context: context, ss: siteModel.SiteSettings, referenceId: siteModel.SiteId, referenceType: "Sites"); order = orderModel.SavedData; } HeaderInfo.Add( siteId: site.SiteId, referenceType: packageSiteModel.ReferenceType, includeData: site.IncludeData, order: order, siteTitle: packageSiteModel.Title); recordIdList.Clear(); if (site.IncludeData == true) { switch (packageSiteModel.ReferenceType) { case "Issues": case "Results": var ss = siteModel.SiteSettings; ss.SetPermissions( context: context, referenceId: ss.SiteId); var export = new Export(ss.DefaultExportColumns(context: context)); export.Header = true; export.Type = Export.Types.Json; export.Columns.ForEach(o => o.SiteId = ss.SiteId); var gridData = Utilities.GetGridData( context: context, ss: ss, export: export); if (gridData.TotalCount > 0) { Data.Add(gridData.GetJsonExport( context: context, ss: ss, export: export)); foreach (DataRow dr in gridData.DataRows) { recordIdList.Add(dr[0].ToLong()); } } break; } } if (includeRecordPermission == true) { var packagePermissionModel = new PackagePermissionModel( context: context, siteModel: siteModel, recordIdList: recordIdList); Permissions.Add(packagePermissionModel); } } } }
private static void AssignData(OrderModel item) { if (item.InternalOrderStatus == Enumerations.OrderExecutionStatus.RstopExist.ToString()) { if (new[] { "A", "U" }.Any(x => x == item.OrderAction)) { ReturnedStopLossOrderModel objReturnedOrderModel = new ReturnedStopLossOrderModel(); objReturnedOrderModel.BuySell = item.BuySellIndicator; objReturnedOrderModel.SCode = item.ScripCode; var Segment = CommonFunctions.GetSegmentID(objReturnedOrderModel.SCode); int DecimalPoint = CommonFunctions.GetDecimal(Convert.ToInt32(objReturnedOrderModel.SCode), "BSE", Segment); objReturnedOrderModel.ScripID = item.Symbol; objReturnedOrderModel.TotalQty = item.PendingQuantity; objReturnedOrderModel.RevQty = item.RevealQty; objReturnedOrderModel.ClientType = item.ClientType; objReturnedOrderModel.LimitRate = (item.Price / Math.Pow(10, DecimalPoint)).ToString(); if (Segment == Enumerations.Segment.Currency.ToString()) { objReturnedOrderModel.LimitRateString = string.Format("{0}.{1}", objReturnedOrderModel.LimitRate, "0000"); } else { objReturnedOrderModel.LimitRateString = string.Format("{0}.{1}", objReturnedOrderModel.LimitRate, "00"); } objReturnedOrderModel.TriggertRate = (item.TriggerPrice / Math.Pow(10, DecimalPoint)).ToString(); if (Segment == Enumerations.Segment.Currency.ToString()) { objReturnedOrderModel.TriggertRateString = string.Format("{0}.{1}", objReturnedOrderModel.TriggertRate, "0000"); } else { objReturnedOrderModel.TriggertRateString = string.Format("{0}.{1}", objReturnedOrderModel.TriggertRate, "00"); } objReturnedOrderModel.ClientID = item.ClientId; objReturnedOrderModel.Time = Convert.ToDateTime(item.Time); objReturnedOrderModel.OrdID = item.OrderId + item.OrderType; objReturnedOrderModel.ClientType = item.ClientType; objReturnedOrderModel.OrderKey = string.Format("{0}_{1}", item.ScripCode, item.OrderId); objReturnedOrderModel.SegmentId = item.SegmentFlag; if (ReturnedStopLossOrderCollection != null && ReturnedStopLossOrderCollection.Count > 0) { if (ReturnedStopLossOrderCollection.Any(x => x.OrderKey == item.OrderKey)) { int index = ReturnedStopLossOrderCollection.IndexOf(ReturnedStopLossOrderCollection.Where(x => x.OrderKey == item.OrderKey).FirstOrDefault()); ReturnedStopLossOrderCollection[index] = objReturnedOrderModel; } else { ReturnedStopLossOrderCollection.Add(objReturnedOrderModel); } } else { ReturnedStopLossOrderCollection?.Add(objReturnedOrderModel); } } else if (item.OrderAction == "D") { if (ReturnedStopLossOrderCollection != null && ReturnedStopLossOrderCollection.Count > 0) { if (ReturnedStopLossOrderCollection.Any(x => x.OrderKey == item.OrderKey)) { int index = ReturnedStopLossOrderCollection.IndexOf(ReturnedStopLossOrderCollection.Where(x => x.OrderKey == item.OrderKey).FirstOrDefault()); if (index != -1) { ReturnedStopLossOrderCollection.RemoveAt(index); } } } } } else { if (ReturnedStopLossOrderCollection != null && ReturnedStopLossOrderCollection.Count > 0) { if (ReturnedStopLossOrderCollection.Any(x => x.OrderKey == item.OrderKey)) { int index = ReturnedStopLossOrderCollection.IndexOf(ReturnedStopLossOrderCollection.Where(x => x.OrderKey == item.OrderKey).FirstOrDefault()); if (index != -1) { ReturnedStopLossOrderCollection.RemoveAt(index); } } } } //ReturnedStopLossOrderCollection.Add(objReturnedOrderModel); }
public OrderController(ILogger <OrderController> logger, IMailer mailer) { _logger = logger; _orderModel = new OrderModel(mailer); _mailer = mailer; }
public OrderForm(CreditCardPaymentForm creditCardPaymentFormData, OrderPresentationModel orderPresentationModelData, OrderModel orderModelData, Model modelData) { InitializeComponent(); // [Automatically generated by Windows Form Designer] _creditCardPaymentForm = creditCardPaymentFormData; _orderPresentationModel = orderPresentationModelData; _orderModel = orderModelData; _model = modelData; _products = _model.Products; InitializeProductTabPageItemsContainers(); // UI _creditCardPaymentForm.FormClosed += CloseCreditCardPaymentForm; _cartDataGridView.CellPainting += CartDataGridViewCellPainting; _cartDataGridView.CellContentClick += CartDataGridViewCellContentClick; _leftArrowButton.Click += (sender, events) => GoToPreviousPage(); _rightArrowButton.Click += (sender, events) => GoToNextPage(); _addButton.Click += ClickAddButton; _orderButton.Click += ClickOrderButton; _productTabControl.SelectedIndexChanged += (sender, events) => SelectProductTabPage(_productTabControl.SelectedIndex); InitializeProductTabPages(); // Initial UI States SelectProductTabPage(AppDefinition.MOTHER_BOARD_INDEX); RefreshControls(); }
// POST api/products public void Post([FromBody] OrderModel model) { _repository.Add(model); }
public override void OnLoad(HttpContext context) { base.OnLoad(context); requestBody = new RequestBody(); requestBody.accessToken = context.Request["accessToken"]; requestBody.oid = context.Request["oid"]; requestBody.uid = context.Request["uid"]; if (requestBody.accessToken == null || requestBody.accessToken.Trim().Length == 0 || requestBody.oid.Length == 0 || requestBody.uid.Length == 0) { SystemResponse.Output(SystemResponse.TYPE_NULLPARAMETER, out statusCode, out responseJson); } else { List <int> values = JsonConvert.DeserializeObject <List <int> >(requestBody.uid); //验证用户 TokenHelper token = new TokenHelper(); UserTokenModel userTokenModel = token.getUserToken(requestBody.accessToken); if (userTokenModel == null) { SystemResponse.Output(SystemResponse.TYPE_EXPIRE, out statusCode, out responseJson); } else { //获取订单表数据 ModelAdo <OrderModel> modelAdoOrder = new ModelAdo <OrderModel>(); OrderModel orderModel = modelAdoOrder.GetModel("(id=?id AND ostatus=?ostatus) or (id=?id AND ostatus=?ostatus1) ", "", new MySqlParameter("?id", requestBody.oid), new MySqlParameter("?ostatus", 2), new MySqlParameter("?ostatus1", 1)); if (orderModel != null) { ModelAdo <OrderUserModel> modelAdo = new ModelAdo <OrderUserModel>(); int existCount = modelAdo.GetRecordCount("oid=?oid", new MySqlParameter("?oid", requestBody.oid)); if (existCount >= 1) { int delCount = modelAdo.ExecuteSql("DELETE FROM ct_order_user WHERE oid=?oid", new MySqlParameter("?oid", requestBody.oid)); if (delCount >= 1) { StringBuilder sbValues = new StringBuilder(); sbValues.Append(" INSERT INTO ct_order_user(oid,uid,status,remark) VALUES "); for (int i = 0; i < values.Count; i++) { sbValues.Append("(" + requestBody.oid + "," + values[i] + ",1,'派送中的订单'),"); } sbValues.Remove(sbValues.Length - 1, 1).Append(";"); int inCount = modelAdo.ExecuteSql(sbValues.ToString()); if (inCount >= 1) { if (orderModel != null) { orderModel.ostatus = 2; modelAdoOrder.Update(orderModel); } SystemResponse.Output(SystemResponse.TYPE_OK, out statusCode, out responseJson); } else { SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson); } } else { SystemResponse.Output(SystemResponse.TYPE_ERROR, out statusCode, out responseJson); } } else { StringBuilder sbValues = new StringBuilder(); sbValues.Append(" INSERT INTO ct_order_user(oid,uid,status) VALUES "); for (int i = 0; i < values.Count; i++) { sbValues.Append("(" + requestBody.oid + "," + values[i] + ",1),"); } sbValues.Remove(sbValues.Length - 1, 1).Append(";"); int inCount = modelAdo.ExecuteSql(sbValues.ToString()); if (inCount >= 1) { SystemResponse.Output(SystemResponse.TYPE_OK, out statusCode, out responseJson); } else { SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson); } } } else { SystemResponse.Output(SystemResponse.TYPE_NULL, out statusCode, out responseJson); } } } }
private void button_modify_Click(object sender, EventArgs e) //修改订单 { Form_modifyOrder modifyOrderForm = new Form_modifyOrder(); DialogResult dialogResult = modifyOrderForm.ShowDialog(); if (dialogResult == DialogResult.OK) { for (int i = 0; i < dataGridView1.Rows.Count; i++) { if (dataGridView1.Rows[i].Cells[4].Value == null) { dataGridView1.Rows[i].Cells[4].Value = false; continue; } if ((bool)dataGridView1.Rows[i].Cells[4].Value == true) { int num = (int)dataGridView1.Rows[i].Cells[0].Value; using (var db = new OrderModel()) { var order = db.Orders.Include("OrderDetails").First(p => p.orderNumber == num); //在数据库中找到一个订单num对应的订单 if (order != null) { order.guest = modifyOrderForm.modifyOrder.guest; order.orderAddress = modifyOrderForm.modifyOrder.orderAddress; var orderdetails = db.OrderDetails.Where(p => p.Order.orderNumber == order.orderNumber); foreach (OrderDetails orderDetails1 in orderdetails) { db.OrderDetails.Remove(orderDetails1); } db.SaveChanges(); //order.orderDetails.Clear(); int cou = 1; foreach (var good in modifyOrderForm.goods) //遍历字典,将所有商品及数量添加到订单中 { OrderDetails orderDetails = new OrderDetails(good.Key, good.Value); orderDetails.OrderId = order.orderNumber; orderDetails.Order = order; orderDetails.OrderDetailsId = int.Parse(order.orderTime.Day + "" + cou++); order.orderDetails.Add(orderDetails); } order.reCalculatePrice(); db.SaveChanges(); } } //bindingSource1.List.Insert(i, modifyOrderForm.modifyOrder); } } using (var db = new OrderModel()) { bindingSource1.DataSource = db.Orders.ToList <Order>(); } button_delete.Enabled = false; button_delete.Visible = false; button_modify.Enabled = false; button_modify.Visible = false; dataGridView1.Columns[4].Visible = false; } }
// GET: Admin/Order public ActionResult Index() { if (Session["UserID"] != null && Session["UserType"].ToString().ToLower() == "admin") { List <DAL.User> users = uRepo.GetCurrent(); List <DAL.Order> orders = oRepo.GetCurrent(); List <DAL.Meal> meals = mRepo.GetCurrent(); List <DAL.OrderProduct> orderProducts = opRepo.GetCurrent(); List <OrderModel> orderModels = new List <OrderModel>(); foreach (DAL.Order o in orders) { OrderModel om = new OrderModel(); if (o.Date != null) { om.Date = (DateTime)o.Date; } else { om.Date = new DateTime(); } om.EstimatedTime = o.EstimatedTime; om.ID = o.ID; om.QRCodePath = o.QRCodePath; om.TotalPrice = o.TotalPrice; om.Voucher = null; UserModel um = new UserModel(); if (o.UserID != null) { var usr = uRepo.GetByID((int)o.UserID); if (usr.DOB != null) { um.DOB = (DateTime)usr.DOB; } else { um.DOB = new DateTime(); } um.ID = usr.ID; um.Mail = usr.Mail; um.Name = usr.Name; um.NrOrders = usr.NrOrders; um.Type = usr.Type; } om.User = um; om.EstimatedTime = o.EstimatedTime; List <MealModel> mm = new List <MealModel>(); foreach (DAL.OrderProduct op in orderProducts) { if (op.OrderID == o.ID) { MealModel mealmodel = new MealModel(); Meal meal = mRepo.GetByID((int)op.MealID); mealmodel.ID = meal.ID; mealmodel.Name = meal.Name; if (op.Quantity == null) { mealmodel.Quantity = 0; } else { mealmodel.Quantity = (int)op.Quantity; } mm.Add(mealmodel); } } om.Meals = mm; orderModels.Add(om); } return(View(orderModels.ToPagedList(1, 1000))); } return(RedirectToAction("Login", "Home", new { area = "" })); }
public List <OrderModel> GetOrderList(string LicensePlateNo) { List <OrderModel> orderList = new List <OrderModel>(); DataTable dt = PDAL.GetOrderTable(6, LicensePlateNo, null); if (dt != null && dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { OrderModel orderModel = new OrderModel(); orderModel.LicensePlateNo = dt.Rows[i]["LicensePlateNo"].ToString(); orderModel.InDate = Convert.ToDateTime(dt.Rows[i]["InDate"]); orderModel.State = Convert.ToInt32(dt.Rows[i]["State"]); orderModel.OrderNo = dt.Rows[i]["OrderNo"].ToString(); int LicensePlateType = Convert.ToInt32(dt.Rows[i]["LicensePlateType"]); int ChargeType = Convert.ToInt32(dt.Rows[i]["ChargeType"]); string ChargeTypeDes = String.Empty; //string PictureAddr = dt.Rows[i]["PictureAddr"].ToString(); //string PictureName = dt.Rows[i]["PictureName"].ToString(); //orderModel.picPath = PictureAddr + @"\" + PictureName; string color = ""; switch (LicensePlateType) { case 1: color = "蓝色"; break; case 2: color = "黄色"; break; case 3: color = "黑色"; break; case 4: color = "白绿色"; break; case 5: color = "黄绿色"; break; case 6: color = "绿色"; break; case 7: color = "白色"; break; default: color = "未识别"; //8是不在识别的颜色中 break; } switch (ChargeType) { case 10: ChargeTypeDes = "收费车辆"; break; case 20: ChargeTypeDes = "白名单车辆"; break; case 30: ChargeTypeDes = "包月车辆"; break; } orderModel.CarColor = color; orderModel.StateDes = dt.Rows[i]["StateDes"].ToString(); orderModel.ChargeTypeDes = ChargeTypeDes; orderList.Add(orderModel); } } return(orderList); }
public void EndOrder(OrderModel order) { _waiterConnectionProvider.EndOrder(order.OrderId, false, string.Empty); UpdateAfterEndOrder(order.OrderId); }
public IActionResult Submit(OrderModel model) { return(View("Index")); }
public Result <List <BooksReportModel> > GetBookReport(PageModel page = null, OrderModel order = null) { throw new NotImplementedException(); }
public void A_user_can_submit_the_Dropship_Order_modal_window_when_the_FiOS_subscriber_has_a_correctly_formed_WTN() { // will run as uitestuser (via code in TestInitialize method) // Given a known user // and a known FiOS subscriber with a correctly formed WTN const string subscriberIdValue = "370100037230"; // Field IT const string wtnValue = "4252525179"; // and the rest of the "Dropship Order" Modal window has been filled out correctly const string orderTypeValue = "dropship"; // this is set in the OrderEquipmentDropship_Partial and is "dropship" for dropship orders var equipmentCatalogValue = FiOSCatalogId; const string qty_14Value = "1"; // means EquipmentTypeId of 14, and a quantity of 1 (that EquipmentTypeId must exist in the EquipmentTypes table in SIMPL database) var commentsValue = string.Format("Integration Test, Dropship Equipment Order, FiOS subscriber, generated on {0} at {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); var fields = new FormCollection { new NameValueCollection { { "SubscriberId", subscriberIdValue }, { "OrderType", orderTypeValue }, { "EquipmentCatalog", equipmentCatalogValue }, { "qty_14", qty_14Value }, { "comments", commentsValue }, { "WTN", wtnValue } } }; var myOrderModel = new OrderModel(); // Right now this is hardcoded, this might fail if the text is changed in the database var myFirstExpectedLineItem = new LineItem { Category = "Misc", Description = "Zyxel Wireless USB Adapter", EquipTypeId = 14, Fulfilled = false, ItemNumber = 11059789, Model = "ZYXEL USB", Quantity = 1 }; myOrderModel.LineItems.Add(myFirstExpectedLineItem); var actualExceptionMessage = string.Empty; var subscriber = CurrentSubscriber.GetInstance(); CurrentSubscriber.SetInstance(subscriberIdValue); var expectedShipAddress = new ShipAddress { Address1 = CleanOrderField(subscriber.Address), Address2 = CleanOrderField(subscriber.Address2), Name = CleanOrderField(subscriber.Name), City = CleanOrderField(subscriber.City), Zip = CleanOrderField(subscriber.Zip), Email = CleanOrderField(subscriber.Email), State = CleanOrderField(subscriber.State), UserEntered = false, WTN = wtnValue, Cbr = null }; const string expectedProduct01SKU = "G-220V3"; const string expectedProduct01Qty = "1"; var expectedProduct02SKU = string.Empty; var expectedProduct02Qty = string.Empty; ActionResult resultSubmitDropship = null; try { //1st Act // when submitting the data resultSubmitDropship = EquipmentOrderControllerForTests.SubmitDropship(fields); } catch(Exception ex) { actualExceptionMessage = ex.Message; } Assert_that_SubmitDropship_returned_the_expected_values_for_a_regular_dropship_order(actualExceptionMessage, resultSubmitDropship, wtnValue, commentsValue, equipmentCatalogValue, myOrderModel, expectedShipAddress, expectedProduct01SKU, expectedProduct01Qty, expectedProduct02SKU, expectedProduct02Qty); }
public void A_user_can_submit_the_Return_Mailer_Dropship_Order_page_when_the_user_has_entered_a_correctly_formed_WTN() { // will run as uitestuser (via code in TestInitialize method) // The InventoryMenuSendReturnMailerItemEnabled key needs to be set to true for the user to // see the ReturnMailer_Partial / ReturnMailerDropship_Partial views (as those views // are returned by the ReturnMailerDropship action method only when that key is true) // The phone number for a former subscriber from the previous // company (e.g. AT&T or Verizon) that needs a return // mailer sent to them const string wtnValue = "1234567890"; const string altAddressValue = "true"; // Indicates that an alternate address was provided const string address1Value = "Any Street"; const string address2Value = "Any Apartment"; const string customerNameValue = "testName"; const string cityValue = "Any City"; const string zipCodeValue = "12345"; const string emailValue = "*****@*****.**"; const string stateValue = "WA"; const string cbrValue = "2345623456"; const string orderTypeValue = "dropship"; // this is set in the ReturnMailerDropship_Partial var equipmentCatalogValue = UVerseCatalogId; // should be 60 in our development environment const string qty_88Value = "1"; // means EquipmentTypeId of 88, and a quantity of 1 (that EquipmentTypeId must exist in the EquipmentTypes table in SIMPL database) var commentsValue = string.Format("Integration Test, Dropship via SendReturnMailer menu item, generated on {0} at {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); var fields = new FormCollection { new NameValueCollection { { "WTN", wtnValue }, { "altAddress", altAddressValue }, { "address1", address1Value }, { "address2", address2Value }, { "customer_name", customerNameValue }, { "city", cityValue }, { "zipCode", zipCodeValue }, { "email", emailValue }, { "state", stateValue }, { "cbr", cbrValue }, { "OrderType", orderTypeValue }, { "EquipmentCatalog", equipmentCatalogValue }, { "qty_88", qty_88Value }, { "comments", commentsValue } } }; var myOrderModel = new OrderModel(); // Right now this is hardcoded, this might fail if the text is changed in the database var myFirstExpectedLineItem = new LineItem { Category = "Returnmailer", Description = "Return Mailer - UCON Modem/RG", EquipTypeId = 88, Fulfilled = false, ItemNumber = 1001, Model = "FTRTVBHRDISC", Quantity = 1 }; var mySecondExpectedLineItem = new LineItem { Category = "Misc", Description = "Frontier TV Combo Letter", EquipTypeId = 91, Fulfilled = false, ItemNumber = 1004, Model = "FTR TV COMBO LETTER", Quantity = 1 }; myOrderModel.LineItems.Add(myFirstExpectedLineItem); myOrderModel.LineItems.Add(mySecondExpectedLineItem); const string expectedProduct01SKU = "FTRTVBHRDISC"; const string expectedProduct01Qty = "1"; const string expectedProduct02SKU = "FTRTVCOMBOLTR"; const string expectedProduct02Qty = "1"; var expectedShipAddress = new ShipAddress { Address1 = address1Value, Address2 = address2Value, Name = customerNameValue, City = cityValue, Zip = zipCodeValue, Email = emailValue, State = stateValue, UserEntered = true, WTN = wtnValue, Cbr = cbrValue }; var actualExceptionMessage = string.Empty; ActionResult resultSubmitDropship = null; try { //1st Act // when submitting the data resultSubmitDropship = EquipmentOrderControllerForTests.SubmitDropship(fields); } catch (Exception ex) { actualExceptionMessage = ex.Message; } Assert_that_SubmitDropship_returned_the_expected_values_for_a_dropship_order_submitted_via_SendReturnMailers(actualExceptionMessage, resultSubmitDropship, wtnValue, commentsValue, customerNameValue, emailValue, equipmentCatalogValue, myOrderModel, expectedShipAddress, expectedProduct01SKU, expectedProduct01Qty, expectedProduct02SKU, expectedProduct02Qty); }
public void A_UVerse_Dropship_Order_modal_window_order_with_six_mailers_will_return_the_correct_number_of_one_and_four_pack_mailers() { // will run as UITestUser (via code in TestInitialize method) //Arrange //If this subscriber is no longer available change subscriberIdValue and wtnValue to another CT subscriber //Given a known user and a known UVerse (Connecticut) subscriber with a correctly formed WTN const string subscriberIdValue = "490002311813"; const string wtnValue = "8600360923"; // and the rest of the "Dropship Order" Modal window has been filled out correctly const string orderTypeValue = "dropship"; // this is set in the OrderEquipmentDropship_Partial and is "dropship" for dropship orders var equipmentCatalogValue = UVerseCatalogId; const string qty_89Value = "6"; // means EquipmentTypeId of 89 and a quantity of 6 (that EquipmentTypeId must exist in the EquipmentTypes table in SIMPL database) var commentsValue = string.Format("Integration Test, Dropship Equipment Order, UVerse Subscriber, generated on {0} at {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); //Collect information to create an order var fields = new FormCollection { new NameValueCollection { { "SubscriberId", subscriberIdValue }, { "OrderType", orderTypeValue }, { "EquipmentCatalog", equipmentCatalogValue }, { "qty_89", qty_89Value //Indicates the number of items to be returned. //This total will be split between one and four pack mailers }, { "comments", commentsValue }, { "WTN", wtnValue } } }; const int singlePackEquipmentTypeId = 89; const int fourPackEquipmentTypeId = 90; const int comboLetterEquipmentTypeId = 91; try { //Get the expected information that should be in the returned order information string[] lineItemInformation = GetExpectedMailerInformation(singlePackEquipmentTypeId); var myFirstExpectedLineItem = new LineItem { Category = lineItemInformation[0], Description = lineItemInformation[1], EquipTypeId = singlePackEquipmentTypeId, Fulfilled = false, ItemNumber = Int32.Parse(lineItemInformation[2]), Model = lineItemInformation[3], Quantity = 2 }; var myOrderModel = new OrderModel(); lineItemInformation = GetExpectedMailerInformation(comboLetterEquipmentTypeId); var mySecondExpectedLineItem = new LineItem { Category = lineItemInformation[0], Description = lineItemInformation[1], EquipTypeId = comboLetterEquipmentTypeId, Fulfilled = false, ItemNumber = Int32.Parse(lineItemInformation[2]), Model = lineItemInformation[3], Quantity = 1 }; lineItemInformation = GetExpectedMailerInformation(fourPackEquipmentTypeId); var myThirdExpectedLineItem = new LineItem { Category = lineItemInformation[0], Description = lineItemInformation[1], EquipTypeId = fourPackEquipmentTypeId, Fulfilled = false, ItemNumber = Int32.Parse(lineItemInformation[2]), Model = lineItemInformation[3], Quantity = 1 }; myOrderModel.LineItems = new List<LineItem> { myFirstExpectedLineItem, mySecondExpectedLineItem, myThirdExpectedLineItem }; //Act CurrentSubscriber.SetInstance(subscriberIdValue); ActionResult resultSubmitDropship = null; //Process the order resultSubmitDropship = EquipmentOrderControllerForTests.SubmitDropship(fields); //Assert Assert_that_SubmitDropship_returned_the_expected_Line_Item_values_for_a_regular_dropship_order( resultSubmitDropship, myOrderModel); } catch (Exception ex) { Assert.Fail("Error: " + ex.Message + " " + ex.InnerException.ToString()); } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string action = HYRequest.GetQueryString("action"); UserModel userInfo = this.LoginUser; OrderModel myorder = OrderFactory.GetCartOrder(userInfo.uid); if (action == "addtocart") //添加到购物车 { #region ==addtocart== int pid = HYRequest.GetFormInt("pid", 0); int buycount = HYRequest.GetFormInt("buycount", 0); int itemflag = HYRequest.GetFormInt("itemflag", 0); OrderModel myof = myorder; if (myof == null) { myof = new OrderModel(); myof.orderno = Utils.GenerateOutTradeNo(this.LoginUser.uid); myof.uid = userInfo.uid; myof.customername = userInfo.fullname; myof.tel = userInfo.tel; myof.address = userInfo.address; } ProductModel p = ProductFactory.Get(pid); OrderProduct op = new OrderProduct(); op.count = buycount; op.productinfo = p; op.price = p.price; //判断是否有属性 if (itemflag > 0) { int tmpflag = 1; foreach (KeyValuePair <string, decimal> kvp in p.itempricelist) { if (itemflag == tmpflag) { op.item = kvp.Key; op.price = kvp.Value; break; } tmpflag++; } } CheckIsAdd(myof.productlist, op); if (myorder == null) { OrderFactory.Add(myof); } else { OrderFactory.Update(myof); } string json = "{\"shopcount\":" + myof.productlist.Count + ",\"error\":0}"; Response.Write(json); Response.Flush(); Response.End(); return; #endregion } else if (action == "addtofav") //添加到收藏夹 { #region ==addtofav== int pid = HYRequest.GetFormInt("pid", 0); bool isfav = FavoriteFactory.IsFavorite(this.LoginUser.uid, pid); if (!isfav) { FavoriteModel fm = new FavoriteModel(); fm.product = ProductFactory.Get(pid); fm.uid = this.LoginUser.uid; fm.productid = pid; FavoriteFactory.Add(fm); } string json = "{\"favtip\":\"已收藏\",\"error\":0}"; Response.Write(json); Response.Flush(); Response.End(); return; #endregion } else if (action == "delfav") //删除收藏夹 { int fid = HYRequest.GetFormInt("fid", 0); FavoriteFactory.Delete(fid); } } }
private void Assert_that_SubmitDropship_returned_the_expected_values_for_a_dropship_order_submitted_via_SendReturnMailers(string actualExceptionMessage, ActionResult resultSubmitDropship, string wtnValue, string commentsValue, string customerNameValue, string emailValue, string equipmentCatalogValue, OrderModel myOrderModel, ShipAddress expectedShipAddress, string expectedProduct01SKU, string expectedProduct01Qty, string expectedProduct02SKU, string expectedProduct02Qty) { //1st Assert Assert.IsNotNull(resultSubmitDropship, "SubmitDropship method returned null"); if (resultSubmitDropship is ContentResult) { var content = ((ContentResult)resultSubmitDropship).Content; Assert.Fail("The return was expected to be a PartialViewResult; instead it was a ContentResult. This normally means there was an exception. Here is the content {0}", content); } Assert.IsTrue(resultSubmitDropship is PartialViewResult, "The return from the SubmitDropship action method was not a PartialViewResult"); //2nd Act var resultSubmitDropshipAsViewResult = resultSubmitDropship as PartialViewResult; //2nd Assert Assert.IsTrue(resultSubmitDropshipAsViewResult.Model is OrderModel, "The model from the SubmitDropship action method was not a OrderModel"); //3rd Act var resultOrderModel = resultSubmitDropshipAsViewResult.Model as OrderModel; var resultLineItems = resultOrderModel.LineItems; //3rd Assert Assert.IsNotNull(resultLineItems, "The LineItems list from the OrderModel is null"); Assert.AreEqual(myOrderModel.LineItems.Count, resultLineItems.Count, "The LineItems count is not the expected value"); var index = 0; foreach (var individualLineItem in resultLineItems) { //4th Assert Assert.AreEqual(myOrderModel.LineItems[index].Category.Trim().ToUpper(), individualLineItem.Category.Trim().ToUpper(), "The LineItem Category for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Description.Trim().ToUpper(), individualLineItem.Description.Trim().ToUpper(), "The LineItem Description for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].EquipTypeId, individualLineItem.EquipTypeId, "The LineItem EquipTypeId for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Fulfilled, individualLineItem.Fulfilled, "The LineItem Fulfilled for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].ItemNumber, individualLineItem.ItemNumber, "The LineItem ItemNumber for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Model.Trim().ToUpper(), individualLineItem.Model.Trim().ToUpper(), "The LineItem Model for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Quantity, individualLineItem.Quantity, "The LineItem Quantity for index of {0} is not the expected value", index); index++; } //5th Act var resultOrder = resultOrderModel.Order; //5th Assert Assert.IsNotNull(resultOrder, "The Order object is null"); Assert.AreNotEqual(0, resultOrder.OrderId, "The OrderId value is 0"); Assert.AreNotEqual(0, resultOrder.MasterOrderId, "The MasterOrderId value is 0"); Assert.IsNotNull(resultOrder.ShipAddress, "The ShipAddress is null (this is really the Id, not the object)"); Assert.IsNotNull(resultOrder.ShipAddress1, "The Ship1Address1 is null (this is the object"); //6th Act var resultShipAddress1 = resultOrder.ShipAddress1; //6th Assert // Here I can actually test the address information as this isn't a live subscriber and the address information here should match the inputs Assert.AreEqual(expectedShipAddress.Address1.Trim().ToUpper(), resultShipAddress1.Address1.Trim().ToUpper(), "Address1 is not the expected value"); Assert.AreEqual(expectedShipAddress.Address2.Trim().ToUpper(), resultShipAddress1.Address2.Trim().ToUpper(), "Address2 is not the expected value"); Assert.AreEqual(expectedShipAddress.Cbr, resultShipAddress1.Cbr, "CBR is not the expected value"); Assert.AreEqual(expectedShipAddress.City.Trim().ToUpper(), resultShipAddress1.City.Trim().ToUpper(), "City is not the expected value"); Assert.AreEqual(expectedShipAddress.Email.Trim().ToUpper(), resultShipAddress1.Email.Trim().ToUpper(), "Email is not the expected value"); Assert.AreEqual(expectedShipAddress.State.Trim().ToUpper(), resultShipAddress1.State.Trim().ToUpper(), "State is not the expected value"); Assert.IsNotNull(resultShipAddress1.UserEntered, "UserEntered is null"); Assert.AreEqual(expectedShipAddress.UserEntered, resultShipAddress1.UserEntered, "UserEntered is not the expected value"); Assert.AreEqual(expectedShipAddress.Zip.Trim().ToUpper(), resultShipAddress1.Zip.Trim().ToUpper(), "Zip is not the expected value"); using (var db = DBContextFactory.CreateContext()) { //7th Act var comments = db.Comments.FirstOrDefault(x => x.CommentText == commentsValue); //7th Assert Assert.IsNotNull(comments, "Comments is null"); Assert.AreNotEqual(0, comments.CommentId, "CommentId is not valid value"); Assert.AreEqual(resultOrder.MasterOrderId, comments.CommentOrderId, "CommentOrdeId is not the expected value"); //8th Act var itxOrders = db.ItxOrders.FirstOrDefault(x => x.OrderId == resultOrder.OrderId); //8th Assert Assert.IsNotNull(itxOrders, "ItxOrders is null"); Assert.AreNotEqual(0, itxOrders.ItxOrderId, "ItxOrderId is not valid value"); // OrderId was already checked with the FirstOrDefault Assert.IsNull(itxOrders.SentToItx, "SentToItx is not null. itxOrders.SentToItx: " + itxOrders.SentToItx); Assert.IsNull(itxOrders.SentDateTime, "SentDateTime is not null. itxOrders.SentDateTime: " + itxOrders.SentDateTime); Assert.IsNotNull(itxOrders.GenerationDateTime, "GenerationDateTime is null"); Assert.AreEqual(1, itxOrders.ProductCatalogTypeId, "ProductCatalogTypeId is not the expected value"); // For orders placed in our test system for AT&T / CT, they are converted from a equipment catalog value of 69 to 60 (ItxOrderHelper.cs, SubmitOrder method) var environment = ConfigurationManager.AppSettings["Environment"]; Assert.IsNotNull(environment, "Environment appSetting key is missing"); var localEquipmentCatalogValue = Convert.ToInt32(equipmentCatalogValue); var convertedEquipmentCatalogValue = (environment.ToUpper() != "PROD" && localEquipmentCatalogValue == Int32.Parse(UVerseCatalogId)) ? 60 : localEquipmentCatalogValue; Assert.AreEqual(convertedEquipmentCatalogValue, itxOrders.ProductCatalogID, "ProductCatalogID is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.OrderNumber, "OrderNumber is not the expected value"); Assert.AreEqual(1, itxOrders.OrderStatusID, "OrderStatusID is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.ReturnInfo, "ReturnInfo is not the expected value"); Assert.AreEqual(wtnValue, itxOrders.CustomerPhoneNumber.Trim(), "CustomerPhoneNumber is not the expected value"); // Here I can actually test the actual FirstName, LastName, and email address values as this isn't a live subscriber and the information here should match the inputs // Note: since customerNameValue only has one word in it, all the data will be in the first name Assert.AreEqual(customerNameValue, itxOrders.CustomerFirstName, "CustomerFirstName is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.CustomerLastName, "CustomerLastName is not the expected value"); Assert.AreEqual(emailValue, itxOrders.CustomerEmail, "CustomerEmail is not the expected value"); // Note: since customerNameValue only has one word in it, all the data will be in the first name Assert.AreEqual(customerNameValue, itxOrders.ShipName1, "ShipName1 is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.ShipName2, "ShipName2 is not the expected value"); Assert.AreEqual(expectedShipAddress.Address1, itxOrders.ShipAddress1, "ShipAddress1 is not the expected value"); Assert.AreEqual(expectedShipAddress.Address2, itxOrders.ShipAddress2, "ShipAddress2 is not the expected value"); Assert.AreEqual(expectedShipAddress.City, itxOrders.ShipCity, "ShipCity is not the expected value"); Assert.AreEqual(expectedShipAddress.State, itxOrders.ShipState, "ShipState is not the expected value"); Assert.AreEqual(expectedShipAddress.Zip, itxOrders.ShipZip, "ShipZip is not the expected value"); // Ship instructions for orders placed in test will have specific text in it Assert.AreEqual("TEST: DO NOT SHIP", itxOrders.ShipInstructions.Trim().ToUpper(), "ShipInstructions is not the expected value"); // Billing information should all be empty Assert.AreEqual(string.Empty, itxOrders.BillName, "BillName is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillAddress1, "BillAddress1 is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillAddress2, "BillAddress2 is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillCity, "BillCity is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillState, "BillState is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillZip, "BillZip is not the expected value"); // Only the first and second Product SKU columns should be filled in with a quantity of 1 // all of the other fields will be empty strings Assert.AreEqual(expectedProduct01SKU, itxOrders.Product01SKU.Trim().ToUpper(), "Product01SKU is not the expected value"); Assert.AreEqual(expectedProduct01Qty, itxOrders.Product01Qty, "Product01Qty is not the expected value"); Assert.AreEqual(expectedProduct02SKU, itxOrders.Product02SKU.Trim().ToUpper(), "Product02SKU is not the expected value"); Assert.AreEqual(expectedProduct02Qty, itxOrders.Product02Qty, "Product02Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product03SKU, "Product03SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product03Qty, "Product03Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product04SKU, "Product04SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product04Qty, "Product04Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product05SKU, "Product05SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product05Qty, "Product05Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product06SKU, "Product06SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product06Qty, "Product06Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product07SKU, "Product07SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product07Qty, "Product07Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product08SKU, "Product08SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product08Qty, "Product08Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product09SKU, "Product09SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product09Qty, "Product09Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product10SKU, "Product10SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product10Qty, "Product10Qty is not the expected value"); } }
private Payment PaymentProcess(OrderModel model) { Options options = new Options(); options.ApiKey = "sandbox-yMXJfymlYYtA31sTwpZsJnU8OBXESAsK"; options.SecretKey = "sandbox-8nBmH73vHSGbuNKmF9CkpG9RTJUIjfNZ"; options.BaseUrl = "https://sandbox-api.iyzipay.com"; CreatePaymentRequest request = new CreatePaymentRequest(); request.Locale = Locale.TR.ToString(); request.ConversationId = Guid.NewGuid().ToString(); request.Price = model.CartModel.TotalPrice().ToString().Split(",")[0];; request.PaidPrice = model.CartModel.TotalPrice().ToString().Split(",")[0];; request.Currency = Currency.TRY.ToString(); request.Installment = 1; request.BasketId = model.CartModel.CartId.ToString(); request.PaymentChannel = PaymentChannel.WEB.ToString(); request.PaymentGroup = PaymentGroup.PRODUCT.ToString(); PaymentCard paymentCard = new PaymentCard(); paymentCard.CardHolderName = model.CardName; paymentCard.CardNumber = model.CardNumber; paymentCard.ExpireMonth = model.ExpirationMonth; paymentCard.ExpireYear = model.ExpirationYear; paymentCard.Cvc = model.Cvv; paymentCard.RegisterCard = 0; request.PaymentCard = paymentCard; //paymentCard.CardHolderName = "John Doe"; //paymentCard.CardNumber = "5528790000000008"; //paymentCard.ExpireMonth = "12"; //paymentCard.ExpireYear = "2030"; //paymentCard.Cvc = "123"; Buyer buyer = new Buyer(); buyer.Id = "BY789"; buyer.Name = "John"; buyer.Surname = "Doe"; buyer.GsmNumber = "+905350000000"; buyer.Email = "*****@*****.**"; buyer.IdentityNumber = "74300864791"; buyer.LastLoginDate = "2015-10-05 12:43:35"; buyer.RegistrationDate = "2013-04-21 15:12:09"; buyer.RegistrationAddress = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; buyer.Ip = "85.34.78.112"; buyer.City = "Istanbul"; buyer.Country = "Turkey"; buyer.ZipCode = "34732"; request.Buyer = buyer; Address shippingAddress = new Address(); shippingAddress.ContactName = "Jane Doe"; shippingAddress.City = "Istanbul"; shippingAddress.Country = "Turkey"; shippingAddress.Description = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; shippingAddress.ZipCode = "34742"; request.ShippingAddress = shippingAddress; Address billingAddress = new Address(); billingAddress.ContactName = "Jane Doe"; billingAddress.City = "Istanbul"; billingAddress.Country = "Turkey"; billingAddress.Description = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; billingAddress.ZipCode = "34742"; request.BillingAddress = billingAddress; List <BasketItem> basketItems = new List <BasketItem>(); BasketItem basketItem; foreach (var item in model.CartModel.CardItems) { basketItem = new BasketItem(); basketItem.Id = item.ProductId.ToString(); basketItem.Name = item.Name; basketItem.Category1 = "Phone"; basketItem.ItemType = BasketItemType.PHYSICAL.ToString(); basketItem.Price = (item.Price * item.Quantity).ToString().Split(",")[0]; basketItems.Add(basketItem); } request.BasketItems = basketItems; return(Payment.Create(request, options)); }
private void Assert_that_SubmitFieldOrder_returned_the_expected_values_for_a_field_order(ActionResult resultSubmitFieldOrder, string commentsValue, string equipmentCatalogValue, OrderModel myOrderModel) { //1st Assert Assert.IsNotNull(resultSubmitFieldOrder, "SubmitFieldOrder method returned null"); if (resultSubmitFieldOrder is JsonResult) { var data = ((JsonResult)resultSubmitFieldOrder).Data; var errorMessage = ErrorMessageFromJsonResult(data); Assert.Fail("The return was expected to be a PartialViewResult; instead it was a JsonResult. This normally means there was an exception. Here is the error message: '{0}'", errorMessage); } Assert.IsTrue(resultSubmitFieldOrder is PartialViewResult, "The return from the SubmitFieldOrder action method was not a PartialViewResult"); //2nd Act var resultSubmitFieldOrderAsViewResult = resultSubmitFieldOrder as PartialViewResult; //2nd Assert Assert.IsTrue(resultSubmitFieldOrderAsViewResult.Model is OrderModel, "The model from the SubmitFieldOrder action method was not a OrderModel"); //3rd Act var resultOrderModel = resultSubmitFieldOrderAsViewResult.Model as OrderModel; var resultLineItems = resultOrderModel.LineItems; //3rd Assert Assert.IsNotNull(resultLineItems, "The LineItems list from the OrderModel is null"); Assert.AreEqual(myOrderModel.LineItems.Count, resultLineItems.Count, "The LineItems count is not the expected value"); var index = 0; foreach (var individualLineItem in resultLineItems) { //4th Assert Assert.AreEqual(myOrderModel.LineItems[index].Category.Trim().ToUpper(), individualLineItem.Category.Trim().ToUpper(), "The LineItem Category for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Description.Trim().ToUpper(), individualLineItem.Description.Trim().ToUpper(), "The LineItem Description for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].EquipTypeId, individualLineItem.EquipTypeId, "The LineItem EquipTypeId for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Fulfilled, individualLineItem.Fulfilled, "The LineItem Fulfilled for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].ItemNumber, individualLineItem.ItemNumber, "The LineItem ItemNumber for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Model.Trim().ToUpper(), individualLineItem.Model.Trim().ToUpper(), "The LineItem Model for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Quantity, individualLineItem.Quantity, "The LineItem Quantity for index of {0} is not the expected value", index); index++; } //5th Act var resultOrder = resultOrderModel.Order; //5th Assert Assert.IsNotNull(resultOrder, "The Order object is null"); Assert.AreNotEqual(0, resultOrder.OrderId, "The OrderId value is 0"); Assert.AreNotEqual(0, resultOrder.MasterOrderId, "The MasterOrderId value is 0"); // The Field Orders do not have a shipping address, so both ShipAddress and ShipAddress1 should be null Assert.IsNull(resultOrder.ShipAddress, "The ShipAddress is not null (this is really the Id, not the object). resultOrder.ShipAddress: " + resultOrder.ShipAddress); Assert.IsNull(resultOrder.ShipAddress1, "The Ship1Address1 is not null (this is the object). resultOrder.ShipAddress1: " + resultOrder.ShipAddress1); ; // Field orders shouldn't have a record in the ItxOrders table, so this is a negative check using (var db = DBContextFactory.CreateContext()) { //6th Act var comments = db.Comments.FirstOrDefault(x => x.CommentText == commentsValue); //6th Assert Assert.IsNotNull(comments, "Comments is null"); Assert.AreNotEqual(0, comments.CommentId, "CommentId is not valid value"); Assert.AreEqual(resultOrder.MasterOrderId, comments.CommentOrderId, "CommentOrdeId is not the expected value"); //7th Act var itxOrders = db.ItxOrders.FirstOrDefault(x => x.OrderId == resultOrder.OrderId); //7th Assert Assert.IsNull(itxOrders, "ItxOrders is not null"); } }
public async Task <JsonResult> CreateOrder_Output(OrderModel model) { var Messaging = new RenderMessaging(); try { if (User == null || User.BranchesId <= 0 || User.ChannelId <= 0) { Messaging.isError = true; Messaging.messaging = "Phiên đăng nhập đã hết hạn."; return(Json(Messaging, JsonRequestBehavior.AllowGet)); } model.Id_From = User.BranchesId; if (model.Id_To <= 0) { Messaging.isError = true; Messaging.messaging = "Vui lòng chọn Kho bạn xuất đến."; return(Json(Messaging, JsonRequestBehavior.AllowGet)); } var Braches = _context.soft_Branches.Where(o => o.BranchesId == model.Id_To || o.BranchesId == User.BranchesId).ToList(); var BrachesTo = Braches.FirstOrDefault(o => o.BranchesId == model.Id_To); if (model.Id_To == User.BranchesId || BrachesTo == null) { Messaging.isError = true; Messaging.messaging = "Kho xuất không hơp lệ"; return(Json(Messaging, JsonRequestBehavior.AllowGet)); } if (model.Detail.Count <= 0) { Messaging.isError = true; Messaging.messaging = "Vui lòng chọn sản phẩm xuất."; return(Json(Messaging, JsonRequestBehavior.AllowGet)); } foreach (var item in model.Detail) { var product = _context.shop_sanpham.Find(item.ProductId); if (product == null) { Messaging.isError = true; Messaging.messaging = "Sản phẩm không tồn tại, vui lòng thử lại."; return(Json(Messaging, JsonRequestBehavior.AllowGet)); } var productstock = _context.soft_Branches_Product_Stock.FirstOrDefault(o => o.BranchesId == User.BranchesId && o.ProductId == item.ProductId); if (productstock != null) { if (productstock.Stock_Total < item.Total) { Messaging.isError = true; Messaging.messaging = "Số lượng sản phẩm " + product.tensp + " không đủ để xuất, vui lòng thử lại."; return(Json(Messaging, JsonRequestBehavior.AllowGet)); } } else { Messaging.isError = true; Messaging.messaging = "Số lượng sản phẩm " + product.tensp + " không đủ để xuất, vui lòng thử lại."; return(Json(Messaging, JsonRequestBehavior.AllowGet)); } } var objOrder = Mapper.Map <soft_Order>(model); objOrder.Code = "PX" + DateTime.Now.ToString("dd/MM/yy").Replace("/", "") + "-" + BrachesTo.Code; objOrder.Status = (int)StatusOrder_Output.Process; objOrder.DateCreate = DateTime.Now; objOrder.EmployeeCreate = User.UserId; objOrder.TypeOrder = (int)TypeOrder.Output; _crud.Add <soft_Order>(objOrder); _crud.SaveChanges(); objOrder.Code = "PX" + DateTime.Now.ToString("dd/MM/yy").Replace("/", "") + "-" + BrachesTo.Code + "-" + objOrder.Id; if (model.OrderFromId.HasValue) { var orderFromBranches = _unitOW.OrderBranchesRepository.FindBy(o => o.Id == model.OrderFromId.Value && o.TypeOrder == (int)TypeOrder.OrderBranches).FirstOrDefault(); if (orderFromBranches != null) { orderFromBranches.Status = (int)StatusOrder_Branches.Exported; _unitOW.OrderBranchesRepository.Update(orderFromBranches, o => o.Status); await _unitOW.SaveChanges(); } } _unitOW.NotificationRepository.Add(new soft_Notification { Contents = "Đơn hàng xuất " + objOrder.Code + " từ kho " + Braches.FirstOrDefault(o => o.BranchesId == User.BranchesId).BranchesName + " đến kho " + BrachesTo.BranchesName + " cần được xử lý", Branch = model.Id_To, DateCreate = DateTime.Now, Type = (int)TypeNotification.OrderOut, Href = "/Order_Input/RenderView" }); await _unitOW.SaveChanges(); Messaging.messaging = "Đã tạo phiếu xuất hàng."; } catch { Messaging.isError = true; Messaging.messaging = "Tạo phiếu xuất không thành công!"; } return(Json(Messaging, JsonRequestBehavior.AllowGet)); }
public async Task GetAccountsAsync(Action <object> update) { // Skip if subscription active if (_fxcmSocket.AccountsUpdate != default && update != default) { return; } Log.Trace("{0}: GetAccountsAsync", GetType().Name); string json = await GetAsync(_getModel).ConfigureAwait(false); JObject jo = JObject.Parse(json); JToken jResponse = jo["response"]; bool executed = (bool)jResponse["executed"]; if (!executed) { string error = jResponse["error"].ToString(); throw new ApplicationException(error); } // Properties JArray jProperties = JArray.FromObject(jo["properties"]); foreach (JToken jProperty in jProperties) { ReadProperty(jProperty); } // Accounts var accounts = new List <AccountModel>(); JArray jAccounts = JArray.FromObject(jo["accounts"]); foreach (JToken jAccount in jAccounts) { AccountModel account = ToAccount(jAccount); if (account == null) { continue; } accounts.Add(account); } // Orders JArray jOrders = JArray.FromObject(jo["orders"]); foreach (JToken jOrder in jOrders) { // Find account string accountId = jOrder["accountId"].ToString(); AccountModel account = accounts.Find(m => m.Id.Equals(accountId)); if (account == default) { continue; } OrderModel order = ToOrder(jOrder); if (order == default) { continue; } account.Orders.Add(order); } // Open positions JArray jPositions = JArray.FromObject(jo["open_positions"]); foreach (JToken jPosition in jPositions) { // Find account string accountId = jPosition["accountId"].ToString(); AccountModel account = accounts.Find(m => m.Id.Equals(accountId)); if (account == default) { continue; } PositionModel position = ToPosition(jPosition); if (position == null) { continue; } account.Positions.Add(position); } update(accounts); _fxcmSocket.AccountsUpdate = update; }
private Payment PaymentProcess(OrderModel model) { Options options = new Options(); options.ApiKey = "sandbox-DUnDbJBwWO7mM3aOhQztq9blAQiDfmJ1"; options.SecretKey = "sandbox-tL0LazZd7Us7HP9XtsFhxAn7gSw13YKN"; options.BaseUrl = "https://sandbox-api.iyzipay.com"; CreatePaymentRequest request = new CreatePaymentRequest(); request.Locale = Locale.TR.ToString(); request.ConversationId = Guid.NewGuid().ToString(); request.Price = model.CartModel.TotalPrice().ToString().Split(",")[0];; request.PaidPrice = model.CartModel.TotalPrice().ToString().Split(",")[0];; request.Currency = Currency.TRY.ToString(); request.Installment = 1; request.BasketId = model.CartModel.CartId.ToString(); request.PaymentChannel = PaymentChannel.WEB.ToString(); request.PaymentGroup = PaymentGroup.PRODUCT.ToString(); PaymentCard paymentCard = new PaymentCard(); paymentCard.CardHolderName = model.CardName; paymentCard.CardNumber = model.CardNumber; paymentCard.ExpireMonth = model.ExpirationMonth; paymentCard.ExpireYear = model.ExpirationYear; paymentCard.Cvc = model.Cvv; paymentCard.RegisterCard = 0; request.PaymentCard = paymentCard; var kBuyer = _buyerService.GetById(_usersAndBuyersService.GetByUserId(_userManager.GetUserId(User)).BuyerId); Buyer buyer = new Buyer(); buyer.Id = model.BuyerId.ToString(); buyer.Name = model.FirstName; buyer.Surname = model.LastName; buyer.GsmNumber = model.Phone; buyer.Email = model.Email; buyer.IdentityNumber = "11111111111"; buyer.LastLoginDate = kBuyer.LastLoginDate; buyer.RegistrationDate = kBuyer.RegistrationDate; buyer.RegistrationAddress = kBuyer.Adress; buyer.Ip = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(); buyer.City = model.City; buyer.Country = "Turkey"; buyer.ZipCode = model.ZipCode; request.Buyer = buyer; Address shippingAddress = new Address(); shippingAddress.ContactName = model.FirstName + " " + model.LastName; shippingAddress.City = model.City; shippingAddress.Country = "Turkey"; shippingAddress.Description = model.Address; shippingAddress.ZipCode = model.ZipCode; request.ShippingAddress = shippingAddress; Address billingAddress = new Address(); billingAddress.ContactName = model.FirstName + " " + model.LastName; billingAddress.City = model.City; billingAddress.Country = "Turkey"; billingAddress.Description = model.Address; billingAddress.ZipCode = model.ZipCode; request.BillingAddress = billingAddress; List <BasketItem> basketItems = new List <BasketItem>(); BasketItem basketItem; foreach (var item in model.CartModel.CartItems) { basketItem = new BasketItem(); basketItem.Id = item.ProductId.ToString(); basketItem.Name = item.Name; basketItem.Category1 = "Koleksiyonluk"; basketItem.ItemType = BasketItemType.PHYSICAL.ToString(); basketItem.Price = (item.Quantity * item.Price).ToString().Split(",")[0]; basketItems.Add(basketItem); } request.BasketItems = basketItems; return(Payment.Create(request, options)); }
public ActionResult OrderSumPost() { OrderForm orderForm = (OrderForm)Session["order"]; CartModel cart = (CartModel)Session["cart"]; OrderModel order = new OrderModel(); order.Firstname = orderForm.Firstname; order.Lastname = orderForm.Lastname; order.Locality = orderForm.Locality; order.Street = orderForm.Street; order.Zipcode = orderForm.Zipcode; order.Phone = orderForm.Phone; order.Shipment = orderForm.Shipment; order.Date = DateTime.Now; order.Description = orderForm.Description; order.orderDetails = new Collection <OrderDetailModel>(); UserDetails ud = null; if (orderForm.Remember == true) { try { string query = "SELECT * FROM UserDetails WHERE Email = @email"; ud = db.UserDetails.SqlQuery(query, new SqlParameter("@email", User.Identity.GetUserName())).First(); ud.Firstname = orderForm.Firstname; ud.Lastname = orderForm.Lastname; ud.Locality = orderForm.Locality; ud.Street = orderForm.Street; ud.Zipcode = orderForm.Zipcode; ud.Phone = orderForm.Phone; db.Entry(ud).State = EntityState.Modified; db.SaveChanges(); } catch (Exception e) { ud = new UserDetails(); ud.Firstname = orderForm.Firstname; ud.Lastname = orderForm.Lastname; ud.Locality = orderForm.Locality; ud.Street = orderForm.Street; ud.Zipcode = orderForm.Zipcode; ud.Phone = orderForm.Phone; ud.Email = User.Identity.GetUserName(); db.UserDetails.Add(ud); db.SaveChanges(); } } else { try { string query = "SELECT * FROM UserDetails WHERE Email = @email"; ud = db.UserDetails.SqlQuery(query, new SqlParameter("@email", User.Identity.GetUserName())).First(); } catch (Exception e) { ud = new UserDetails(); ud.Firstname = orderForm.Firstname; ud.Lastname = orderForm.Lastname; ud.Locality = orderForm.Locality; ud.Street = orderForm.Street; ud.Zipcode = orderForm.Zipcode; ud.Phone = orderForm.Phone; ud.Email = User.Identity.GetUserName(); db.UserDetails.Add(ud); db.SaveChanges(); } } foreach (var item in cart.products) { ProductModel p = item.Key; int q = item.Value; if (p.Quantity >= q) { p.Quantity -= q; db.Entry(p).State = EntityState.Modified; } else { Session["order"] = null; Session["cart"] = null; return(RedirectToAction("OrderResultUnsuccessful")); } OrderDetailModel od = new OrderDetailModel(); od.product = p; od.Quantity = q; db.OrderDetail.Add(od); order.orderDetails.Add(od); } order.user = ud; db.Order.Add(order); db.SaveChanges(); Session["order"] = null; Session["cart"] = null; return(RedirectToAction("OrderResult")); }
public SingleResult <InsertOrderResultDto> InsertCustomerOrder_UI(OrderModel order) { try { var userId = ClaimPrincipalFactory.GetUserId(User); var time = DateTime.Now.Ticks; var cc = _repository.Customer.FindByCondition(c => c.UserId == userId).FirstOrDefault(); var customerId = cc.Id; var today = DateTime.Now.AddDays(-1).Ticks; var orerProductList = new List <CustomerOrderProduct>(); var orderNo = customerId.ToString() + DateTimeFunc.TimeTickToShamsi(DateTime.Now.Ticks).Replace("/", "") + (_repository.CustomerOrder.FindByCondition(c => c.CustomerId == customerId && today > c.Cdate) .Count() + 1).ToString().PadLeft(3, '0'); order.ProductList.ForEach(c => { var product = _repository.Product.FindByCondition(x => x.Id == c.ProductId).First(); var ofer = _repository.ProductOffer.FindByCondition(x => x.ProductId == c.ProductId && x.FromDate <= time && time <= x.ToDate && x.DaDate == null && x.Ddate == null).Include(c => c.Offer).FirstOrDefault(); var packingType = _repository.ProductPackingType.FindByCondition(x => x.Id == c.PackingTypeId) .FirstOrDefault(); var statusId = _repository.Status.GetSatusId("CustomerOrderProduct", 2); var orderproduct = new CustomerOrderProduct { OrderCount = c.Count, ProductId = c.ProductId, Cdate = DateTime.Now.Ticks, CuserId = userId, OrderType = 1, ProductCode = product.Coding, ProductIncreasePrice = null, ProductName = product.Name, ProductPrice = product.Price, ProductOfferId = ofer?.Id, ProductOfferCode = ofer?.Offer.OfferCode, ProductOfferPrice = (long?)(ofer != null ? (ofer.Value / 100 * product.Price) : 0), ProductOfferValue = ofer?.Value, PackingTypeId = packingType?.PackinggTypeId, PackingWeight = packingType == null ? 0 : packingType.Weight, PackingPrice = packingType == null ? 0 : packingType.Price, SellerId = product.SellerId, Weight = c.Count * product.Weight, FinalWeight = (c.Count * product.Weight) + (c.Count * (packingType == null ? 0 : packingType.Weight)), FinalStatusId = statusId }; orerProductList.Add(orderproduct); }); var offer = _repository.Offer.FindByCondition(c => c.Id == order.OfferId).FirstOrDefault(); var paking = _repository.PackingType.FindByCondition(c => c.Id == order.PaymentTypeId).FirstOrDefault(); var customerOrder = new CustomerOrder { Cdate = DateTime.Now.Ticks, CuserId = userId, CustomerAddressId = order.CustomerAddressId, CustomerDescription = order.CustomerDescription, CustomerId = customerId, FinalStatusId = _repository.Status.GetSatusId("CustomerOrder", 1), OfferId = order.OfferId, OrderPrice = orerProductList.Sum(x => ((x.PackingPrice + x.ProductPrice - x.ProductOfferPrice) * x.OrderCount)) }; if (offer != null) { if (offer.Value == 0 || offer.Value == null) { customerOrder.OfferPrice = offer.MaximumPrice > customerOrder.OrderPrice ? customerOrder.OrderPrice : offer.MaximumPrice; customerOrder.OfferValue = null; } else { customerOrder.OfferPrice = (long?)(customerOrder.OrderPrice * (offer.Value / 100)); customerOrder.OfferValue = (int?)offer.Value.Value; } } else { customerOrder.OfferPrice = 0; customerOrder.OfferValue = null; } customerOrder.OrderDate = DateTime.Now.Ticks; customerOrder.FinalWeight = orerProductList.Sum(x => x.FinalWeight); customerOrder.OrderNo = Convert.ToInt64(orderNo); customerOrder.OrderProduceTime = 0; customerOrder.OrderType = 1; customerOrder.OrderWeight = customerOrder.FinalWeight; customerOrder.PackingPrice = 0; customerOrder.PackingWeight = 0; customerOrder.PaymentTypeId = order.PaymentTypeId; customerOrder.PostServicePrice = 0; customerOrder.PostTypeId = order.PostTypeId; //customerOrder.TaxPrice = (long?)((customerOrder.OrderPrice - customerOrder.OfferPrice) * 0.09); //customerOrder.TaxValue = 9; customerOrder.TaxPrice = 0; customerOrder.TaxValue = 9; customerOrder.CustomerOrderProduct = orerProductList; var toCityId = _repository.CustomerAddress.FindByCondition(c => c.Id == order.CustomerAddressId).Include(c => c.City).Select(c => c.City.PostCode).FirstOrDefault(); var postType = _repository.PostType.FindByCondition(c => c.Id == order.PostTypeId).FirstOrDefault(); var payType = _repository.PaymentType.FindByCondition(c => c.Id == order.PaymentTypeId) .FirstOrDefault(); if (postType.IsFree.Value) { customerOrder.PostServicePrice = 0; } else { var post = new PostServiceProvider(); var postpriceparam = new PostGetDeliveryPriceParam { Price = (int)customerOrder.OrderPrice.Value, Weight = (int)customerOrder.FinalWeight.Value, ServiceType = postType?.Rkey ?? 2,// (int)customerOrder.PostTypeId, ToCityId = (int)toCityId, PayType = (int)(payType?.Rkey ?? 88) }; var postresult = post.GetDeliveryPrice(postpriceparam).Result; if (postresult.ErrorCode != 0) { throw new BusinessException(XError.IncomingSerivceErrors.PostSeerivcError()); } customerOrder.PostServicePrice = (postresult.PostDeliveryPrice + postresult.VatTax) / 10; } customerOrder.FinalPrice = customerOrder.OrderPrice - customerOrder.OfferPrice + customerOrder.TaxPrice + customerOrder.PostServicePrice; _repository.CustomerOrder.Create(customerOrder); if (customerOrder.FinalPrice > 0) { var request = new ZarinPallRequest { // amount = (int)((customerOrder.FinalPrice.Value + customerOrder.PostServicePrice) * 10), amount = (int)((customerOrder.FinalPrice.Value) * 10), description = "order NO: " + customerOrder.OrderNo, metadata = new ZarinPalRequestMetaData { mobile = "0" + cc.Mobile.ToString(), email = cc.Email } }; var zarinPal = new ZarinPal(); var res = zarinPal.Request(request); var customerOrderPayment = new CustomerOrderPayment { OrderNo = customerOrder.OrderNo.ToString(), TraceNo = res.authority, TransactionPrice = customerOrder.FinalPrice, TransactionDate = DateTime.Now.Ticks, Cdate = DateTime.Now.Ticks, CuserId = userId, PaymentPrice = customerOrder.FinalPrice, FinalStatusId = 26 }; customerOrder.CustomerOrderPayment.Add(customerOrderPayment); _repository.Save(); var result = new InsertOrderResultDto { OrderNo = customerOrder.OrderNo, CustomerOrderId = customerOrder.Id, BankUrl = "https://www.zarinpal.com/pg/StartPay/" + res.authority, RedirectToBank = true, PostPrice = customerOrder.PostServicePrice }; var finalres = SingleResult <InsertOrderResultDto> .GetSuccessfulResult(result); _logger.LogData(MethodBase.GetCurrentMethod(), finalres, null, order); return(finalres); } else { var customerOrderPayment = new CustomerOrderPayment { OrderNo = customerOrder.OrderNo.ToString(), TraceNo = "پرداخت رایگان", TransactionPrice = customerOrder.FinalPrice, TransactionDate = DateTime.Now.Ticks, Cdate = DateTime.Now.Ticks, CuserId = userId, PaymentPrice = customerOrder.FinalPrice, FinalStatusId = 24 }; customerOrder.CustomerOrderPayment.Add(customerOrderPayment); var sendSms = new SendSMS(); sendSms.SendSuccessOrderPayment(cc.Mobile.Value, customerOrderPayment.OrderNo, customerOrderPayment.PaymentPrice.Value); var sendEmail = new SendEmail(); var email = cc.Email; sendEmail.SendSuccessOrderPayment(email, customerOrderPayment.OrderNo, customerOrderPayment.PaymentPrice.Value); var productist = _repository.CustomerOrderProduct.FindByCondition(c => c.CustomerOrderId == customerOrder.Id).Select(c => c.Product).ToList(); productist.ForEach(c => { c.Count = c.Count--; _repository.Product.Update(c); }); var sellerList = _repository.CustomerOrderProduct.FindByCondition(c => c.CustomerOrderId == customerOrder.Id).Select(c => c.Seller.Mobile).ToList(); sellerList.ForEach(c => { if (c == null) { return; } var sendSms = new SendSMS(); sendSms.SendOrderSmsForSeller(c.Value); }); _repository.Save(); var result = new InsertOrderResultDto { OrderNo = customerOrder.OrderNo, CustomerOrderId = customerOrder.Id, BankUrl = "", RedirectToBank = false, PostPrice = customerOrder.PostServicePrice }; var finalres = SingleResult <InsertOrderResultDto> .GetSuccessfulResult(result); _logger.LogData(MethodBase.GetCurrentMethod(), finalres, null, order); return(finalres); } } catch (Exception e) { _logger.LogError(e, MethodBase.GetCurrentMethod(), order); return(SingleResult <InsertOrderResultDto> .GetFailResult(e.Message)); } }
private bool CanRemoveOrder(OrderModel obj) { return(obj != null || (GridViewModel != null && GridViewModel.SelectedItem != null)); }
public async Task SendStatusChangeNotification(OrderModel order, OrderStatus oldStatus, OrderStatus newStatus) { if (oldStatus == newStatus) { return; } switch (newStatus) { case OrderStatus.NotAssigned: //No entra nunca break; case OrderStatus.PreAssigned: //Entra por SendAmbassadorChangedNotification break; case OrderStatus.Pending: var mailMessage = new MailMessage { From = _fromEmail, Subject = $"[Atomic Limbs] Aceptaste el pedido (#{order.Id})", To = order.OrderAmbassador.Email, Body = CompiledTemplateEngine.Render("Mails.OrderAcceptedToAmbassador", order), }; if (order.OrderAmbassador.HasAlternativeEmail()) { mailMessage.Cc = order.OrderAmbassador.AlternativeEmail; } await AzureQueue.EnqueueAsync(mailMessage); mailMessage = new MailMessage { From = _fromEmail, Subject = $"[Atomic Limbs] Pedido aceptado por embajador (#{order.Id})", To = order.OrderRequestor.Email, Body = CompiledTemplateEngine.Render("Mails.OrderAcceptedToRequestor", order), }; if (order.OrderRequestor.HasAlternativeEmail()) { mailMessage.Cc = order.OrderRequestor.AlternativeEmail; } await AzureQueue.EnqueueAsync(mailMessage); break; case OrderStatus.Ready: mailMessage = new MailMessage { From = _fromEmail, Subject = $"[Atomic Limbs] Coordinar envío (#{order.Id})", To = _adminEmails, Body = CompiledTemplateEngine.Render("Mails.OrderReadyToAdmin", order), }; await AzureQueue.EnqueueAsync(mailMessage); mailMessage = new MailMessage { From = _fromEmail, Subject = $"[Atomic Limbs] Coordinar envío (#{order.Id})", To = order.OrderAmbassador.Email, Body = CompiledTemplateEngine.Render("Mails.OrderReadyToAmbassador", order), }; if (order.OrderAmbassador.HasAlternativeEmail()) { mailMessage.Cc = order.OrderAmbassador.AlternativeEmail; } await AzureQueue.EnqueueAsync(mailMessage); mailMessage = new MailMessage { From = _fromEmail, Subject = $"[Atomic Limbs] Pedido listo (#{order.Id})", To = order.OrderRequestor.Email, Body = CompiledTemplateEngine.Render("Mails.OrderReadyToRequestor", order), }; if (order.OrderRequestor.HasAlternativeEmail()) { mailMessage.Cc = order.OrderRequestor.AlternativeEmail; } await AzureQueue.EnqueueAsync(mailMessage); break; case OrderStatus.Delivered: //Entra por SendDeliveryInformationNotification break; case OrderStatus.ArrangeDelivery: //No action break; } }
public async Task <int> DeleteOrderAsync(OrderModel model) { return(await DataService.DeleteOrderAsync(model.OrderID)); }
private Payment PaymentProcess(OrderModel model) { Options options = new Options(); options.ApiKey = "sandbox-8fHUIOWiWLhvysuCiMhclEobkOsZHS9H"; options.SecretKey = "sandbox-nAZl4hck9hn4mEA9oTAog5bfGIFcSxZi"; options.BaseUrl = "https://sandbox-api.iyzipay.com"; CreatePaymentRequest request = new CreatePaymentRequest(); request.Locale = Locale.TR.ToString(); request.ConversationId = Guid.NewGuid().ToString(); //Guid benzersiz bir değer üretir request.Price = model.CardModel.TotolPrice().ToString().Split(",")[0];; request.PaidPrice = model.CardModel.TotolPrice().ToString().Split(",")[0];; request.Currency = Currency.TRY.ToString(); request.Installment = 1; request.BasketId = model.CardModel.CardId.ToString(); request.PaymentChannel = PaymentChannel.WEB.ToString(); request.PaymentGroup = PaymentGroup.PRODUCT.ToString(); PaymentCard paymentCard = new PaymentCard(); paymentCard.CardHolderName = model.CardName; paymentCard.CardNumber = model.CardNumber; paymentCard.ExpireMonth = model.ExpirationMonth; //.ToString() paymentCard.ExpireYear = model.ExpirationYear; //.ToString() paymentCard.Cvc = model.Cvv; paymentCard.RegisterCard = 0; request.PaymentCard = paymentCard; //paymentCard.CardHolderName = "John Doe"; //paymentCard.CardNumber = "5528790000000008"; //paymentCard.ExpireMonth = "12"; //paymentCard.ExpireYear = "2030"; //paymentCard.Cvc = "123"; //paymentCard.RegisterCard = 0; Buyer buyer = new Buyer(); buyer.Id = "BY789"; buyer.Name = "John"; buyer.Surname = "Doe"; buyer.GsmNumber = "+905350000000"; buyer.Email = "*****@*****.**"; buyer.IdentityNumber = "74300864791"; buyer.LastLoginDate = "2015-10-05 12:43:35"; buyer.RegistrationDate = "2013-04-21 15:12:09"; buyer.RegistrationAddress = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; buyer.Ip = "85.34.78.112"; buyer.City = "Istanbul"; buyer.Country = "Turkey"; buyer.ZipCode = "34732"; request.Buyer = buyer; Address shippingAddress = new Address(); shippingAddress.ContactName = "Jane Doe"; shippingAddress.City = "Istanbul"; shippingAddress.Country = "Turkey"; shippingAddress.Description = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; shippingAddress.ZipCode = "34742"; request.ShippingAddress = shippingAddress; Address billingAddress = new Address(); billingAddress.ContactName = "Jane Doe"; billingAddress.City = "Istanbul"; billingAddress.Country = "Turkey"; billingAddress.Description = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; billingAddress.ZipCode = "34742"; request.BillingAddress = billingAddress; List <BasketItem> basketItems = new List <BasketItem>(); BasketItem basketItem; foreach (var item in model.CardModel.CardItems) { basketItem = new BasketItem(); basketItem.Id = item.ProductId.ToString(); basketItem.Name = item.Name; basketItem.Category1 = "Phone"; basketItem.Category2 = "Accessories"; basketItem.ItemType = BasketItemType.PHYSICAL.ToString(); basketItem.Price = item.Price.ToString().Split(",")[0]; //split metodu virgülle ayırma işlemi yapar basketItems.Add(basketItem); } request.BasketItems = basketItems; return(Payment.Create(request, options)); }
public async Task <ActionResult <Dto.Invoice> > Order([FromBody] OrderModel model) { var orderInfo = mapper.Map <Dto.CreateOrder> (model); return(this.ToActionResult(await this.service.Order(orderInfo), logger)); }
public void A_user_can_submit_the_Dropship_Order_modal_window_when_the_UVerse_subscriber_has_a_correctly_formed_WTN() { // will run as uitestuser (via code in TestInitialize method) // Given a known user // and a known UVerse (Connecticut) subscriber with a correctly formed WTN const string subscriberIdValue = "490003615254"; // Using well-known Middletown, CT "test" subscriber (from list attached to email by Andrew T. on 11/12/2014) const string wtnValue = "8608523792"; // and the rest of the "Dropship Order" Modal window has been filled out correctly const string orderTypeValue = "dropship"; // this is set in the OrderEquipmentDropship_Partial and is "dropship" for dropship orders var equipmentCatalogValue = UVerseCatalogId; const string qty_83Value = "1"; // means EquipmentTypeId of 83, and a quantity of 1 (that EquipmentTypeId must exist in the EquipmentTypes table in SIMPL database) var commentsValue = string.Format("Integration Test, Dropship Equipment Order, UVerse Subscriber, generated on {0} at {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); var fields = new FormCollection { new NameValueCollection { { "SubscriberId", subscriberIdValue }, { "OrderType", orderTypeValue }, { "EquipmentCatalog", equipmentCatalogValue }, { "qty_83", qty_83Value }, { "comments", commentsValue }, { "WTN", wtnValue } } }; var myOrderModel = new OrderModel(); // Right now this is hardcoded, this might fail if the text is changed in the database var myFirstExpectedLineItem = new LineItem { Category = "Modem", Description = "RG - VAP2500 Wireless Access Point", EquipTypeId = 83, Fulfilled = false, ItemNumber = 2500, Model = "VAP2500", Quantity = 1 }; var mySecondExpectedLineItem = new LineItem { Category = "Misc", Description = "Frontier TV Combo Letter", EquipTypeId = 91, Fulfilled = false, ItemNumber = 1004, Model = "FTR TV COMBO LETTER", Quantity = 1 }; myOrderModel.LineItems.Add(myFirstExpectedLineItem); myOrderModel.LineItems.Add(mySecondExpectedLineItem); const string expectedProduct01SKU = "VAP2500KIT"; const string expectedProduct01Qty = "1"; const string expectedProduct02SKU = "FTRTVCOMBOLTR"; const string expectedProduct02Qty = "1"; var actualExceptionMessage = string.Empty; var subscriber = CurrentSubscriber.GetInstance(); CurrentSubscriber.SetInstance(subscriberIdValue); var expectedShipAddress = new ShipAddress { Address1 = CleanOrderField(subscriber.Address), Address2 = CleanOrderField(subscriber.Address2), Name = CleanOrderField(subscriber.Name), City = CleanOrderField(subscriber.City), Zip = CleanOrderField(subscriber.Zip), Email = CleanOrderField(subscriber.Email), State = CleanOrderField(subscriber.State), UserEntered = false, WTN = wtnValue, Cbr = null }; ActionResult resultSubmitDropship = null; try { //1st Act // when submitting the data resultSubmitDropship = EquipmentOrderControllerForTests.SubmitDropship(fields); } catch (Exception ex) { actualExceptionMessage = ex.Message; } // Note: for UVerse orders, the development database has the value as 60 instead of 69, so passing "60" instead of the equipmentCatalogValue Assert_that_SubmitDropship_returned_the_expected_values_for_a_regular_dropship_order(actualExceptionMessage, resultSubmitDropship, wtnValue, commentsValue, "60", myOrderModel, expectedShipAddress, expectedProduct01SKU, expectedProduct01Qty, expectedProduct02SKU, expectedProduct02Qty); }
public async Task <ActionResult> Order(OrderModel model, Payment payment) { bool fire = false; var transaction = db.Database.BeginTransaction(IsolationLevel.Serializable); try { if (model != null && payment != null) { var account = await db.Database.SqlQuery <Account>("select * from account where email=@p0", User.Identity.Name).SingleOrDefaultAsync(); model.FirstName = account.FirstName; model.LastName = account.LastName; model.Email = account.Email; model.OrderDate = DateTime.Now; await db.Database.ExecuteSqlCommandAsync("insert into [order] (firstname, lastname, address, city, country, province, postcode, phone, total, orderdate, email) values(@p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10)", model.FirstName, model.LastName, model.Address, model.City, model.Country, model.Province, model.PostCode, model.Phone, model.Total, model.OrderDate, model.Email ); var found = await db.Database.SqlQuery <Order>("select * from [order] where email=@p0 and orderdate=@p1 and total = @p2", model.Email, model.OrderDate, model.Total).SingleOrDefaultAsync(); //Deducting items quantity from stock var details = await db.Database.SqlQuery <OrderDetail>("select * from orderdetail").ToListAsync(); //var details = await details.Convert(db); foreach (var de in details) { var item = await db.Database.SqlQuery <Item>("select * from item where id = @p0", de.ItemId).SingleOrDefaultAsync(); var leftQuantity = item.Quantity - de.Quantity; if (leftQuantity == 0) { await db.Database.ExecuteSqlCommandAsync("update item set quantity = @p0, availability = @p1 where id=@p2", leftQuantity, false, de.ItemId); } else if (leftQuantity > 0) { await db.Database.ExecuteSqlCommandAsync("update item set quantity=@p0, availability=@p1 where id=@p2", leftQuantity, true, de.ItemId); } else { fire = true; transaction.Rollback(); return(RedirectToAction("response", new { msgType = "error", msg = "Sorry, Looks like we are out of items", title = "Out Of Stock" })); //Quantity not available msg } } if (!fire) { await db.Database.ExecuteSqlCommandAsync("insert into payment (cardNumber,amount,paytype,email,paydate,orderid) values(@p0,@p1,@p2,@p3,@p4,@p5)", payment.CardNumber, model.Total, payment.PayType, model.Email, DateTime.Now, found.OrderId); transaction.Commit(); return(RedirectToAction("response", new { msgType = "success", msg = "Soon Your items will be at your home, Enjoy Shopping further", title = "Thank You For Your Order" }));; // successfull view Thankyou page } } } catch { transaction.Rollback(); } return(RedirectToAction("response", new { msgType = "error", msg = "Sorry, Some Problem occurr", title = "Technical Problem" })); // failure either something doesn't exist }
public void A_user_submit_the_Field_Replenishment_Order_page_and_the_WTN_field_is_not_required() { // will run as uitestuser (via code in TestInitialize method) const string orderTypeValue = "fieldOrder"; // this is set in the OrderEquipmentDropship_Partial and is "fieldOrder" for field orders var equipmentCatalogValue = FiOSCatalogId; const string qty_14Value = "1"; // means EquipmentTypeId of 14, and a quantity of 1 (that EquipmentTypeId must exist in the EquipmentTypes table in SIMPL database) var commentsValue = string.Format("Integration Test, Field Order, generated on {0} at {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); var fields = new FormCollection { new NameValueCollection { { "OrderType", orderTypeValue }, { "EquipmentCatalog", equipmentCatalogValue }, { "qty_14", qty_14Value }, { "comments", commentsValue } } }; var myOrderModel = new OrderModel(); // Right now this is hardcoded, this might fail if the text is changed in the database var myFirstExpectedLineItem = new LineItem { Category = "Misc", Description = "Zyxel Wireless USB Adapter", EquipTypeId = 14, Fulfilled = false, ItemNumber = 11059789, Model = "ZYXEL USB", Quantity = 1 }; myOrderModel.LineItems.Add(myFirstExpectedLineItem); //1st Act var resultSubmitFieldOrder = EquipmentOrderControllerForTests.SubmitFieldOrder(fields); Assert_that_SubmitFieldOrder_returned_the_expected_values_for_a_field_order(resultSubmitFieldOrder, commentsValue, equipmentCatalogValue, myOrderModel); }
private Payment PaymentProccess(OrderModel model) { Options options = new Options(); options.ApiKey = "sandbox-3aMgaT0kOANKoe3OiFt49YtSKNPfgNoa"; options.SecretKey = "sandbox-687wRAIsY4mquOsdfZ75bR2LxXHU7lsn"; options.BaseUrl = "https://sandbox-api.iyzipay.com"; CreatePaymentRequest request = new CreatePaymentRequest(); request.Locale = Locale.TR.ToString(); request.ConversationId = new Random().Next(111111111, 999999999).ToString(); request.Price = model.CartModel.TotalPrice().ToString(); request.PaidPrice = model.CartModel.TotalPrice().ToString(); request.Currency = Currency.TRY.ToString(); request.Installment = 1; request.BasketId = "B67832"; request.PaymentChannel = PaymentChannel.WEB.ToString(); request.PaymentGroup = PaymentGroup.PRODUCT.ToString(); PaymentCard paymentCard = new PaymentCard(); paymentCard.CardHolderName = model.CardName; paymentCard.CardNumber = model.CardNumber; paymentCard.ExpireMonth = model.ExpirationMonth; paymentCard.ExpireYear = model.ExpirationYear; paymentCard.Cvc = model.Cvc; paymentCard.RegisterCard = 0; request.PaymentCard = paymentCard; // paymentCard.CardNumber = "5528790000000008"; // paymentCard.ExpireMonth = "12"; // paymentCard.ExpireYear = "2030"; // paymentCard.Cvc = "123"; Buyer buyer = new Buyer(); buyer.Id = "BY789"; buyer.Name = model.FirstName; buyer.Surname = model.LastName; buyer.GsmNumber = "+905350000000"; buyer.Email = "*****@*****.**"; buyer.IdentityNumber = "74300864791"; buyer.LastLoginDate = "2015-10-05 12:43:35"; buyer.RegistrationDate = "2013-04-21 15:12:09"; buyer.RegistrationAddress = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; buyer.Ip = "85.34.78.112"; buyer.City = "Istanbul"; buyer.Country = "Turkey"; buyer.ZipCode = "34732"; request.Buyer = buyer; Address shippingAddress = new Address(); shippingAddress.ContactName = "Hasan Tunç"; shippingAddress.City = "Istanbul"; shippingAddress.Country = "Turkey"; shippingAddress.Description = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; shippingAddress.ZipCode = "34742"; request.ShippingAddress = shippingAddress; Address billingAddress = new Address(); billingAddress.ContactName = "Hüseyin Tunç"; billingAddress.City = "Istanbul"; billingAddress.Country = "Turkey"; billingAddress.Description = "Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1"; billingAddress.ZipCode = "34742"; request.BillingAddress = billingAddress; List <BasketItem> basketItems = new List <BasketItem>(); BasketItem basketItem; foreach (var item in model.CartModel.CartItems) { basketItem = new BasketItem(); basketItem.Id = item.ProductId.ToString(); basketItem.Name = item.Name; basketItem.Category1 = "Telefon"; basketItem.Price = item.Price.ToString(); basketItem.ItemType = BasketItemType.PHYSICAL.ToString(); basketItems.Add(basketItem); } request.BasketItems = basketItems; return(Payment.Create(request, options)); }
private void Assert_that_SubmitDropship_returned_the_expected_Line_Item_values_for_a_regular_dropship_order(ActionResult resultSubmitDropship, OrderModel myOrderModel) { //1st Assert //The result is a partialViewResult // then the "Order Successfully Created" modal window is shown if (resultSubmitDropship is ContentResult) { var content = ((ContentResult)resultSubmitDropship).Content; Assert.Fail("The return was expected to be a PartialViewResult; instead it was a ContentResult. This normally means there was an exception. Here is the content {0}", content); } Assert.IsTrue(resultSubmitDropship is PartialViewResult, "The return from the SubmitDropship action method was not a PartialViewResult"); //2nd Act //Start drilling down the result record from SubmitDropship //Cast the result to be a PartialViewResult var resultSubmitDropshipAsViewResult = resultSubmitDropship as PartialViewResult; //2nd Assert //Verify the result Model is an OrderModel type // and the records in the database match the expected values // Note: the OrderModel has data that is retrieved from the database Assert.IsTrue(resultSubmitDropshipAsViewResult.Model is OrderModel, "The model from the SubmitDropship action method was not a OrderModel"); //3rd Act //Get the LineItems from the SubmitDropship return .OrderModel.LineItems var resultOrderModel = resultSubmitDropshipAsViewResult.Model as OrderModel; var resultLineItems = resultOrderModel.LineItems; //3rd Assert Assert.IsNotNull(resultLineItems, "The LineItems list from the OrderModel is null"); Assert.AreEqual(myOrderModel.LineItems.Count, resultLineItems.Count, "The LineItems count is not the expected value"); var index = 0; foreach (var individualLineItem in resultLineItems) { //4th Assert Assert.AreEqual(myOrderModel.LineItems[index].Category.Trim().ToUpper(), individualLineItem.Category.Trim().ToUpper(), "The LineItem Category for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Description.Trim().ToUpper(), individualLineItem.Description.Trim().ToUpper(), "The LineItem Description for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].EquipTypeId, individualLineItem.EquipTypeId, "The LineItem EquipTypeId for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Fulfilled, individualLineItem.Fulfilled, "The LineItem Fulfilled for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].ItemNumber, individualLineItem.ItemNumber, "The LineItem ItemNumber for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Model.Trim().ToUpper(), individualLineItem.Model.Trim().ToUpper(), "The LineItem Model for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Quantity, individualLineItem.Quantity, "The LineItem Quantity for index of {0} is not the expected value", index); index++; } }
//添加订单 // POST: api/Order public OrderModel Post([FromBody] OrderModel m) { return(dal.AddOrder(m.PId, m.OrderNo)); }
private void Assert_that_SubmitDropship_returned_the_expected_values_for_a_regular_dropship_order(string actualExceptionMessage, ActionResult resultSubmitDropship, string wtnValue, string commentsValue, string equipmentCatalogValue, OrderModel myOrderModel, ShipAddress expectedShipAddress, string expectedProduct01SKU, string expectedProduct01Qty, string expectedProduct02SKU, string expectedProduct02Qty) { //1st Assert //The result is a partialViewResult // then the "Order Successfully Created" modal window is shown if (resultSubmitDropship is ContentResult) { var content = ((ContentResult)resultSubmitDropship).Content; Assert.Fail("The return was expected to be a PartialViewResult; instead it was a ContentResult. This normally means there was an exception. Here is the content {0}", content); } Assert.IsTrue(resultSubmitDropship is PartialViewResult, "The return from the SubmitDropship action method was not a PartialViewResult"); //2nd Act //Start drilling down the result record from SubmitDropship //Cast the result to be a PartialViewResult var resultSubmitDropshipAsViewResult = resultSubmitDropship as PartialViewResult; //2nd Assert //Verify the result Model is an OrderModel type // and the records in the database match the expected values // Note: the OrderModel has data that is retrieved from the database Assert.IsTrue(resultSubmitDropshipAsViewResult.Model is OrderModel, "The model from the SubmitDropship action method was not a OrderModel"); //3rd Act //Get the LineItems from the SubmitDropship return .OrderModel.LineItems var resultOrderModel = resultSubmitDropshipAsViewResult.Model as OrderModel; var resultLineItems = resultOrderModel.LineItems; //3rd Assert Assert.IsNotNull(resultLineItems, "The LineItems list from the OrderModel is null"); Assert.AreEqual(myOrderModel.LineItems.Count, resultLineItems.Count, "The LineItems count is not the expected value"); var index = 0; foreach (var individualLineItem in resultLineItems) { //4th Assert Assert.AreEqual(myOrderModel.LineItems[index].Category.Trim().ToUpper(), individualLineItem.Category.Trim().ToUpper(), "The LineItem Category for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Description.Trim().ToUpper(), individualLineItem.Description.Trim().ToUpper(), "The LineItem Description for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].EquipTypeId, individualLineItem.EquipTypeId, "The LineItem EquipTypeId for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Fulfilled, individualLineItem.Fulfilled, "The LineItem Fulfilled for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].ItemNumber, individualLineItem.ItemNumber, "The LineItem ItemNumber for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Model.Trim().ToUpper(), individualLineItem.Model.Trim().ToUpper(), "The LineItem Model for index of {0} is not the expected value", index); Assert.AreEqual(myOrderModel.LineItems[index].Quantity, individualLineItem.Quantity, "The LineItem Quantity for index of {0} is not the expected value", index); index++; } //5th Act var resultOrder = resultOrderModel.Order; //5th Assert Assert.IsNotNull(resultOrder, "The Order object is null"); Assert.AreNotEqual(0, resultOrder.OrderId, "The OrderId value is 0"); Assert.AreNotEqual(0, resultOrder.MasterOrderId, "The MasterOrderId value is 0"); Assert.IsNotNull(resultOrder.ShipAddress, "The ShipAddress is null (this is really the Id, not the object)"); Assert.IsNotNull(resultOrder.ShipAddress1, "The Ship1Address1 is null (this is the object"); //6th Act var resultShipAddress1 = resultOrder.ShipAddress1; //6th Assert Assert.AreEqual(expectedShipAddress.Address1.Trim().ToUpper(), resultShipAddress1.Address1.Trim().ToUpper(), "Address1 is not the expected value"); Assert.AreEqual(expectedShipAddress.Address2.Trim().ToUpper(), resultShipAddress1.Address2.Trim().ToUpper(), "Address2 is not the expected value"); Assert.AreEqual(expectedShipAddress.Cbr, resultShipAddress1.Cbr, "CBR is not the expected value"); Assert.AreEqual(expectedShipAddress.City.Trim().ToUpper(), resultShipAddress1.City.Trim().ToUpper(), "City is not the expected value"); Assert.AreEqual(expectedShipAddress.Email.Trim().ToUpper(), resultShipAddress1.Email.Trim().ToUpper(), "Email is not the expected value"); Assert.AreEqual(expectedShipAddress.State.Trim().ToUpper(), resultShipAddress1.State.Trim().ToUpper(), "State is not the expected value"); Assert.IsNotNull(resultShipAddress1.UserEntered, "UserEntered is null"); Assert.AreEqual(expectedShipAddress.UserEntered, resultShipAddress1.UserEntered, "UserEntered is not the expected value"); Assert.AreEqual(expectedShipAddress.Zip.Trim().ToUpper(), resultShipAddress1.Zip.Trim().ToUpper(), "Zip is not the expected value"); // We can test the WTN as that is being set at the beginning of the test Assert.AreEqual(wtnValue, resultShipAddress1.WTN, "WTN is not the expected value"); using (var db = DBContextFactory.CreateContext()) { //7th Act var comments = db.Comments.FirstOrDefault(x => x.CommentText == commentsValue); //7th Assert Assert.IsNotNull(comments, "Comments is null"); Assert.AreNotEqual(0, comments.CommentId, "CommentId is not valid value"); Assert.AreEqual(resultOrder.MasterOrderId, comments.CommentOrderId, "CommentOrdeId is not the expected value"); //8th Act var itxOrders = db.ItxOrders.FirstOrDefault(x => x.OrderId == resultOrder.OrderId); //8th Assert Assert.IsNotNull(itxOrders, "ItxOrders is null"); Assert.AreNotEqual(0, itxOrders.ItxOrderId, "ItxOrderId is not valid value"); // OrderId was already checked with the FirstOrDefault Assert.IsNull(itxOrders.SentToItx, "SentToItx is not null"); Assert.IsNull(itxOrders.SentDateTime, "SentDateTime is not null"); Assert.IsNotNull(itxOrders.GenerationDateTime, "GenerationDateTime is null"); Assert.AreEqual(1, itxOrders.ProductCatalogTypeId, "ProductCatalogTypeId is not the expected value"); Assert.AreEqual(Convert.ToInt32(equipmentCatalogValue), itxOrders.ProductCatalogID, "ProductCatalogID is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.OrderNumber, "OrderNumber is not the expected value"); Assert.AreEqual(1, itxOrders.OrderStatusID, "OrderStatusID is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.ReturnInfo, "ReturnInfo is not the expected value"); Assert.AreEqual(wtnValue, itxOrders.CustomerPhoneNumber, "CustomerPhoneNumber is not the expected value"); // Note: Not testing the actual FirstName, LastName, and email address values as this is a live subscriber and the data in Triad could change // Therefore, just testing the values to make sure that everything is not null or whitespace (except for lastname as that can be string.empty) Assert.IsFalse(string.IsNullOrWhiteSpace(itxOrders.CustomerFirstName.Trim()), "CustomerFirstName is null or whitespace"); Assert.IsNotNull(itxOrders.CustomerLastName, "CustomerLastName is null"); Assert.IsFalse(string.IsNullOrWhiteSpace(itxOrders.CustomerEmail.Trim()), "CustomerEmail is null or whitespace"); // Therefore, just testing the address values to make sure that everything is not null or whitespace (except for shipname2 as that can be string.empty) Assert.IsFalse(string.IsNullOrWhiteSpace(itxOrders.ShipName1.Trim()), "ShipName1 is null or whitespace"); Assert.IsNotNull(itxOrders.ShipName2, "ShipName2 is null"); Assert.AreEqual(expectedShipAddress.Address1, itxOrders.ShipAddress1, "ShipAddress1 is not the expected value"); Assert.AreEqual(expectedShipAddress.Address2, itxOrders.ShipAddress2, "ShipAddress2 is not the expected value"); Assert.AreEqual(expectedShipAddress.City, itxOrders.ShipCity, "ShipCity is not the expected value"); Assert.AreEqual(expectedShipAddress.State, itxOrders.ShipState, "ShipState is not the expected value"); Assert.AreEqual(expectedShipAddress.Zip, itxOrders.ShipZip, "ShipZip is not the expected value"); // Ship instructions for orders placed in test will have specific text in it Assert.AreEqual("TEST: DO NOT SHIP", itxOrders.ShipInstructions.Trim().ToUpper(), "ShipInstructions is not the expected value"); // Billing information should all be empty Assert.AreEqual(string.Empty, itxOrders.BillName, "BillName is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillAddress1, "BillAddress1 is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillAddress2, "BillAddress2 is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillCity, "BillCity is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillState, "BillState is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.BillZip, "BillZip is not the expected value"); // Only the first Product SKU column will be guaranteed to be filled in with a quantity of 1 // one some orders, the second item may be filled // all of the other fields will be empty strings Assert.AreEqual(expectedProduct01SKU, itxOrders.Product01SKU.Trim(), "Product01SKU is not the expected value"); Assert.AreEqual(expectedProduct01Qty, itxOrders.Product01Qty, "Product01Qty is not the expected value"); Assert.AreEqual(expectedProduct02SKU, itxOrders.Product02SKU, "Product02SKU is not the expected value"); Assert.AreEqual(expectedProduct02Qty, itxOrders.Product02Qty, "Product02Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product03SKU, "Product03SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product03Qty, "Product03Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product04SKU, "Product04SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product04Qty, "Product04Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product05SKU, "Product05SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product05Qty, "Product05Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product06SKU, "Product06SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product06Qty, "Product06Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product07SKU, "Product07SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product07Qty, "Product07Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product08SKU, "Product08SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product08Qty, "Product08Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product09SKU, "Product09SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product09Qty, "Product09Qty is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product10SKU, "Product10SKU is not the expected value"); Assert.AreEqual(string.Empty, itxOrders.Product10Qty, "Product10Qty is not the expected value"); } }
public static IQueryable <TDb> OrderBy2 <TDb>(this IQueryable <TDb> source, OrderModel model) { var x = Expression.Parameter(source.ElementType, "x"); System.Linq.Expressions.LambdaExpression selector = null; if ((model?.ByDistance ?? false)) { var parseMethod = typeof(double).GetMethod("Parse", new[] { typeof(string) }); var dbParameterXstr = Expression.PropertyOrField(x, "Latitude"); var dbParameterX = Expression.Call(parseMethod, dbParameterXstr); var dbParameterYstr = Expression.PropertyOrField(x, "Longitude"); var dbParameterY = Expression.Call(parseMethod, dbParameterYstr); var xParameterLocal = Expression.Constant(model.X); var yParameterLocal = Expression.Constant(model.Y); var cosMethod = typeof(Math).GetMethod("Cos", new[] { typeof(double) }); var sinMethod = typeof(Math).GetMethod("Sin", new[] { typeof(double) }); var acosMethod = typeof(Math).GetMethod("Acos", new[] { typeof(double) }); Expression Sin(Expression target) { return(Expression.Call(sinMethod, target)); } Expression Cos(Expression target) { return(Expression.Call(cosMethod, target)); } Expression Acos(Expression target) { return(Expression.Call(acosMethod, target)); } var baseRadEx = Expression.Multiply(Expression.Constant(Math.PI), Expression.Divide(xParameterLocal, Expression.Constant(180.0))); var targetRadEx = Expression.Multiply(Expression.Constant(Math.PI), Expression.Divide(dbParameterX, Expression.Constant(180.0))); var thetaEx = Expression.Subtract(yParameterLocal, dbParameterY); var thetaRadEx = Expression.Multiply(Expression.Constant(Math.PI), Expression.Divide(thetaEx, Expression.Constant(180.0))); var distEx = Add(Mult(Sin(baseRadEx), Sin(thetaRadEx)), Mult(Cos(thetaRadEx), Mult(Cos(baseRadEx), Cos(targetRadEx)))); var dist2Ex = Acos(distEx); var dist3Ex = Div(Mult(dist2Ex, Expression.Constant(180.0)), Expression.Constant(Math.PI)); var distance = Mult(dist3Ex, Expression.Constant(111.18957696)); selector = Expression.Lambda( distance, x); } else { selector = Expression.Lambda(Expression.PropertyOrField(x, model.PropertyName), x); } return (source.Provider.CreateQuery <TDb>( Expression.Call(typeof(Queryable), model.IsDes ? "OrderByDescending" : "OrderBy", new Type[] { source.ElementType, selector.Body.Type }, source.Expression, selector ))); }
public void A_dropship_return_mailer_order_for_three_TiVo_Mini_devices_will_have_1_line_item_which_has_quantity_3_for_the_return_mailer() { // will run as uitestuser (via code in TestInitialize method) // Given a known subscriber with TiVo service const string subscriberIdValue = "130000259078"; // Alice Buffkin, North Myrtle Beach SC - FiOS data and TiVo service const string wtnValue = "8641330868"; // and the rest of the "Dropship Order" Modal window has been filled out correctly const string orderTypeValue = "dropship"; // this is set in the OrderEquipmentDropship_Partial and is "dropship" for dropship orders var equipmentCatalogValue = TiVoReturnMailerCatalogId; const string qty_104Value = "3"; // means EquipmentTypeId of 104, and a quantity of 3 (that EquipmentTypeId must exist in the EquipmentTypes table in SIMPL database) var commentsValue = string.Format("Integration Test, Dropship Return Mailer Order, TiVo return mailer for 3 TiVo Minis, generated on {0} at {1}", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString()); var fields = new FormCollection { new NameValueCollection { { "SubscriberId", subscriberIdValue }, { "OrderType", orderTypeValue }, { "EquipmentCatalog", equipmentCatalogValue }, { "qty_104", qty_104Value }, { "comments", commentsValue }, { "WTN", wtnValue } } }; var myOrderModel = new OrderModel(); // Right now this is hardcoded, this might fail if the text is changed in the database // TiVo (OTA) - right now there will not be any 4-packs var myFirstExpectedLineItem = new LineItem { Category = "Returnmailer", Description = "Return Mailer - TiVo Mini", EquipTypeId = 104, Fulfilled = false, ItemNumber = 5004, Model = "RTTVMINI1PK", Quantity = 3 }; myOrderModel.LineItems.Add(myFirstExpectedLineItem); const string expectedProduct01SKU = "FRDMTVMINISTRMRTNKIT"; const string expectedProduct01Qty = "3"; var expectedProduct02SKU = string.Empty; var expectedProduct02Qty = string.Empty; var actualExceptionMessage = string.Empty; var subscriber = CurrentSubscriber.GetInstance(); CurrentSubscriber.SetInstance(subscriberIdValue); var expectedShipAddress = new ShipAddress { Address1 = CleanOrderField(subscriber.Address), Address2 = CleanOrderField(subscriber.Address2), Name = CleanOrderField(subscriber.Name), City = CleanOrderField(subscriber.City), Zip = CleanOrderField(subscriber.Zip), Email = CleanOrderField(subscriber.Email), State = CleanOrderField(subscriber.State), UserEntered = false, WTN = wtnValue, Cbr = null }; ActionResult resultSubmitDropship = null; try { //1st Act // when submitting the data resultSubmitDropship = EquipmentOrderControllerForTests.SubmitDropship(fields); } catch (Exception ex) { actualExceptionMessage = ex.Message; } Assert_that_SubmitDropship_returned_the_expected_values_for_a_regular_dropship_order(actualExceptionMessage, resultSubmitDropship, wtnValue, commentsValue, equipmentCatalogValue, myOrderModel, expectedShipAddress, expectedProduct01SKU, expectedProduct01Qty, expectedProduct02SKU, expectedProduct02Qty); }
public static IQueryable <TDb> OrderBy3 <TDb>(this IQueryable <TDb> source, OrderModel model) { var x = Expression.Parameter(source.ElementType, "x"); System.Linq.Expressions.LambdaExpression selector = null; if ((model?.ByDistance ?? false)) { var parseMethod = typeof(double).GetMethod("Parse", new[] { typeof(string) }); var dbParameterXstr = Expression.PropertyOrField(x, "Latitude"); var dbParameterX = Expression.Call(parseMethod, dbParameterXstr); var dbParameterYstr = Expression.PropertyOrField(x, "Longitude"); var dbParameterY = Expression.Call(parseMethod, dbParameterYstr); var xParameterLocal = Expression.Constant(model.X); var yParameterLocal = Expression.Constant(model.Y); var sqrtMethod = typeof(Math).GetMethod("Sqrt", new[] { typeof(double) }); var cosMethod = typeof(Math).GetMethod("Cos", new[] { typeof(double) }); var asinMethod = typeof(Math).GetMethod("Asin", new[] { typeof(double) }); var pParameter = Expression.Constant(0.017453292519943295); var latSubst = Expression.Subtract(dbParameterX, xParameterLocal); var latSubstP = Expression.Multiply(latSubst, pParameter); var cosLatSubstP = Expression.Call(cosMethod, latSubstP); var cosLatSubstPdiv2 = Expression.Divide(cosLatSubstP, Expression.Constant(2.0)); var locLatP = Expression.Multiply(xParameterLocal, pParameter); var cosLocLatP = Expression.Call(cosMethod, locLatP); var dbLatP = Expression.Multiply(dbParameterX, pParameter); var cosDbLatP = Expression.Call(cosMethod, dbLatP); var longSubst = Expression.Subtract(dbParameterY, yParameterLocal); var longSubstP = Expression.Multiply(longSubst, pParameter); var cosLongSubstP = Expression.Call(cosMethod, longSubstP); var oneSubstCosLongSubstP = Expression.Subtract(Expression.Constant(1.0), cosLongSubstP); var oneSubstCosLongSubstPdiv2 = Expression.Divide(oneSubstCosLongSubstP, Expression.Constant(2.0)); var mult12 = Expression.Multiply(cosLocLatP, cosDbLatP); var mult123 = Expression.Multiply(mult12, oneSubstCosLongSubstPdiv2); var res = Expression.Subtract(Expression.Constant(0.5), cosLatSubstPdiv2); var res2 = Expression.Add(res, mult123); var sqrtRes = Expression.Call(sqrtMethod, res2); var asinSqrtRes = Expression.Call(asinMethod, sqrtRes); var distance = Expression.Multiply(Expression.Constant(12742.0), asinSqrtRes); selector = Expression.Lambda( distance, x); } else { selector = Expression.Lambda(Expression.PropertyOrField(x, model.PropertyName), x); } return (source.Provider.CreateQuery <TDb>( Expression.Call(typeof(Queryable), model.IsDes ? "OrderByDescending" : "OrderBy", new Type[] { source.ElementType, selector.Body.Type }, source.Expression, selector ))); }