public CustomerContact CreateCustomer(string email, string password, string phone, OrderAddress billingAddress, OrderAddress shippingAddress, bool hasPassword, Action<MembershipCreateStatus> userCreationFailed) { MembershipCreateStatus createStatus; var user = Membership.CreateUser(email, password, email, null, null, true, out createStatus); switch (createStatus) { case MembershipCreateStatus.Success: SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.EveryoneRole); SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.RegisteredRole); var customer = CustomerContext.Current.GetContactForUser(user); customer.FirstName = billingAddress.FirstName; customer.LastName = billingAddress.LastName; customer.FullName = string.Format("{0} {1}", customer.FirstName, customer.LastName); customer.SetPhoneNumber(phone); customer.SetHasPassword(hasPassword); var customerBillingAddress = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId); OrderAddress.CopyOrderAddressToCustomerAddress(billingAddress, customerBillingAddress); customer.AddContactAddress(customerBillingAddress); customer.SaveChanges(); customer.PreferredBillingAddressId = customerBillingAddress.AddressId; customerBillingAddress.Name = string.Format("{0}, {1} {2}", customerBillingAddress.Line1, customerBillingAddress.PostalCode, customerBillingAddress.City); CheckCountryCode(customerBillingAddress); BusinessManager.Update(customerBillingAddress); customer.SaveChanges(); var customerShippingAddress = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId); OrderAddress.CopyOrderAddressToCustomerAddress(shippingAddress, customerShippingAddress); customer.AddContactAddress(customerShippingAddress); customer.SaveChanges(); customer.PreferredShippingAddressId = customerShippingAddress.AddressId; customerShippingAddress.Name = string.Format("{0}, {1} {2}", customerShippingAddress.Line1, customerShippingAddress.PostalCode, customerShippingAddress.City); CheckCountryCode(customerShippingAddress); BusinessManager.Update(customerShippingAddress); customer.SaveChanges(); return customer; default: userCreationFailed(createStatus); break; } return null; }
public void Populate(OrderAddress orderAddress) { FirstName = orderAddress.FirstName; LastName = orderAddress.LastName; Line1 = orderAddress.Line1; Line2 = orderAddress.Line2; Line3 = string.Empty; PostCode = orderAddress.PostalCode; City = orderAddress.City; State = orderAddress.State; Country = orderAddress.CountryName; CountryCode = orderAddress.CountryCode; Mobile = orderAddress.DaytimePhoneNumber; Email = orderAddress.Email; Phone = string.Empty; }
public void MapOrderAddressToModel(Address address, OrderAddress orderAddress) { address.Line1 = orderAddress.Line1; address.Line2 = orderAddress.Line2; address.City = orderAddress.City; address.CountryName = orderAddress.CountryName; address.CountryCode = orderAddress.CountryCode; address.Email = orderAddress.Email; address.FirstName = orderAddress.FirstName; address.LastName = orderAddress.LastName; address.PostalCode = orderAddress.PostalCode; address.SaveAddress = false; address.Region = orderAddress.RegionName ?? orderAddress.State; address.Modified = orderAddress.Modified; address.Name = orderAddress.Name; address.DaytimePhoneNumber = orderAddress.DaytimePhoneNumber; }
public void MapModelToOrderAddress(Address address, OrderAddress orderAddress) { orderAddress.City = address.City; orderAddress.CountryCode = address.CountryCode; orderAddress.CountryName = GetAllCountries().Where(x => x.Code == address.CountryCode).Select(x => x.Name).FirstOrDefault(); orderAddress.FirstName = address.FirstName; orderAddress.LastName = address.LastName; orderAddress.Line1 = address.Line1; orderAddress.Line2 = address.Line2; orderAddress.DaytimePhoneNumber = address.DaytimePhoneNumber; orderAddress.PostalCode = address.PostalCode; orderAddress.RegionName = address.Region; // Commerce Manager expects State to be set for addresses in order management. Set it to be same as // RegionName to avoid issues. orderAddress.State = address.Region; orderAddress.Email = address.Email; }
/// <summary> /// Translates the specified source party. /// </summary> /// <param name="sourceParty">The source party.</param> /// <param name="destinationAddress">The destination address.</param> protected virtual void TranslateCommerceParty([NotNull] ConnectOrderModels.CommerceParty sourceParty, [NotNull] OrderAddress destinationAddress) { Assert.ArgumentNotNullOrEmpty(sourceParty.Name, "sourceParty.Name"); destinationAddress.City = sourceParty.City; destinationAddress.CountryName = sourceParty.Country; destinationAddress.DaytimePhoneNumber = sourceParty.PhoneNumber; destinationAddress.Email = sourceParty.Email; destinationAddress.FirstName = sourceParty.FirstName; destinationAddress.LastName = sourceParty.LastName; destinationAddress.Line1 = sourceParty.Address1; destinationAddress.Line2 = sourceParty.Address2; destinationAddress.PostalCode = sourceParty.ZipPostalCode; destinationAddress.State = sourceParty.State; destinationAddress.CountryCode = sourceParty.CountryCode; destinationAddress.EveningPhoneNumber = sourceParty.EveningPhoneNumber; destinationAddress.FaxNumber = sourceParty.FaxNumber; destinationAddress.Name = sourceParty.Name; destinationAddress.Organization = sourceParty.Company; destinationAddress.RegionCode = sourceParty.RegionCode; destinationAddress.RegionName = sourceParty.RegionName; this.TranslateCommercePartyCustomProperties(sourceParty, destinationAddress); }
/// <summary> /// Binds the billing address. /// </summary> private void BindBillingAddress() { CustomerProfile ci = ProfileContext.Current.Profile; if (ci == null || ci.Account == null || ci.Account.Addresses == null || ci.Account.Addresses.Count == 0) { tblAddresses.Visible = false; OrderAddress address = CartHelper.FindAddressByName(CartHelper.OrderForm.BillingAddressId); if (address != null) { AddressNewModule1.AddressInfo = address; } else { if (CartHelper.Cart.OrderAddresses.Count > 0) { AddressNewModule1.AddressInfo = CartHelper.Cart.OrderAddresses[0]; } } rbBillingNewAddress.Checked = true; return; } //bool bSearch = CurrentOrderInfo.BillingAddress!=null; //bool bFound = false; AddressesList.Items.Clear(); if (ci.Account.Addresses.Count > 0) { AddressesList.DataSource = ci.Account.Addresses; AddressesList.DataBind(); AddressViewModule.AddressInfo = StoreHelper.ConvertToOrderAddress(ci.Account.Addresses[0]); AddressViewModule.DataBind(); CommonHelper.SelectListItem(AddressesList, Profile.PreferredBillingAddress); if (!rbBillingNewAddress.Checked) { rbBillingAddress.Checked = true; } } else { } /* * foreach (AddressInfo info in ci.Addresses) * { * string strAddress = MakeAddressString(info); * AddressesList.Items.Add(new ListItem(strAddress, info.AddressId)); * if(bSearch && (info.AddressId == CurrentOrderInfo.BillingAddress.AddressId)) * bFound = true; * } * */ /* * if (!bFound) * { * if (CurrentOrderInfo.BillingAddress != null) * { * AddressNewModule1.AddressInfo = CurrentOrderInfo.BillingAddress; * } * else * { * // bind shipping address * if (CurrentOrderInfo.Shipments != null && CurrentOrderInfo.Shipments.Length > 0 && CurrentOrderInfo.Shipments[0].Details.DeliveryAddress != null) * { * // need to set AddressId to 0 to avoid replacing corresponding address' fields if new address' fields will be changed * AddressInfo ai = CurrentOrderInfo.Shipments[0].Details.DeliveryAddress; * ai.AddressId = "0"; * AddressNewModule1.AddressInfo = ai; * } * } * * rbBillingNewAddress.Checked = true; * * // Bind view address * if (ci != null && ci.Addresses != null && ci.Addresses.Length != 0) * { * AddressViewModule.AddressInfo = ci.Addresses[0]; * AddressViewModule.DataBind(); * } * } * else * { * if (BillingAddress != null && !String.IsNullOrEmpty(BillingAddress.AddressId)) * { * CommonHelper.SelectListItem(AddressesList, BillingAddress.AddressId); * AddressViewModule.AddressInfo = BillingAddress; * AddressViewModule.DataBind(); * } * else * { * CommonHelper.SelectListItem(AddressesList, AddressesList.Items[0].Value); * AddressViewModule.AddressInfo = ci.Addresses[0]; * AddressViewModule.DataBind(); * } * rbBillingAddress.Checked = true; * } * */ }
protected CustomerContact CreateCustomer(string email, string password, string phone, OrderAddress billingAddress, OrderAddress shippingAddress, bool hasPassword, Action <MembershipCreateStatus> userCreationFailed) { return(_customerFactory.CreateCustomer(email, password, phone, billingAddress, shippingAddress, hasPassword, userCreationFailed)); }
/// <summary> /// Translates the custom properties. /// </summary> /// <param name="sourceParty">The source party.</param> /// <param name="destinationAddress">The destination address.</param> protected virtual void TranslateEmailPartyCustomProperties([NotNull] EmailParty sourceParty, [NotNull] OrderAddress destinationAddress) { destinationAddress[CommerceServerStorefrontConstants.KnowWeaklyTypesProperties.PartyType] = 2; }
public async Task <Order> OrderCreate(int userId, OrderCreateBaseParam param, string adminNote = null) { if (param == null) { throw new Exception("参数异常"); } if (param.Items == null || param.Items.Count <= 0) { throw new Exception("购买商品不存在或已下架"); } if (param.Items.Any(c => c.Quantity <= 0)) { throw new Exception("购买商品数量必须>0"); } param.Items = param.Items.GroupBy(c => c.ProductId).Select(c => new OrderCreateBaseItemParam() { ProductId = c.Key, Quantity = c.Sum(x => x.Quantity) }).ToList(); var customerId = param.CustomerId; var payEndTimeForMin = await _appSettingService.Get <int>(OrderKeys.OrderAutoCanceledTimeForMinute); var productIds = param.Items.Select(c => c.ProductId).Distinct(); var products = await _productRepository.Query() .Where(c => productIds.Contains(c.Id) && c.IsPublished && c.IsAllowToOrder) .Include(c => c.ThumbnailImage) .ToListAsync(); if (products == null || products.Count <= 0) { throw new Exception("购买商品不存在或已下架"); } var stocks = await _stockRepository.Query().Where(c => productIds.Contains(c.ProductId)).ToListAsync(); var order = new Order() { OrderStatus = OrderStatus.PendingPayment, // 默认创建订单,待付款 CreatedById = userId, UpdatedById = userId, CustomerId = customerId, AdminNote = adminNote, OrderNote = param.OrderNote, ShippingMethod = param.ShippingMethod, PaymentType = param.PaymentType, ShippingFeeAmount = param.ShippingFeeAmount, DiscountAmount = param.DiscountAmount, PaymentEndOn = DateTime.Now.AddMinutes(payEndTimeForMin) }; var orderShipping = await UserAddressToOrderAddress(param.ShippingUserAddressId, customerId, AddressType.Shipping, order); OrderAddress orderBilling = null; if (param.BillingUserAddressId.HasValue && param.BillingUserAddressId.Value > 0) { orderBilling = await this.UserAddressToOrderAddress(param.BillingUserAddressId.Value, customerId, AddressType.Billing, order); } var addStockHistories = new List <StockHistory>(); foreach (var item in param.Items) { var product = products.FirstOrDefault(c => c.Id == item.ProductId); if (product == null) { continue; } OrderStockDoWorker(stocks, addStockHistories, product, userId, -item.Quantity, order, "创建订单"); var orderItem = new OrderItem() { Order = order, Product = product, ItemWeight = 0, ItemAmount = item.Quantity * product.Price, Quantity = item.Quantity, ProductPrice = product.Price, DiscountAmount = 0, CreatedById = userId, UpdatedById = userId, ProductName = product.Name, ProductMediaUrl = product.ThumbnailImage?.Url }; order.OrderItems.Add(orderItem); } order.SubTotal = order.OrderItems.Sum(c => c.Quantity * c.ProductPrice); order.SubTotalWithDiscount = order.OrderItems.Sum(c => c.DiscountAmount); order.OrderTotal = order.OrderItems.Sum(c => c.Product.Price * c.Quantity) + order.ShippingFeeAmount - order.SubTotalWithDiscount - order.DiscountAmount; _orderRepository.Add(order); // Unable to save changes because a circular dependency was detected in the data to be saved // https://github.com/aspnet/EntityFrameworkCore/issues/11888 // https://docs.microsoft.com/zh-cn/ef/core/saving/transactions // https://stackoverflow.com/questions/40073149/entity-framework-circular-dependency-for-last-entity using (var transaction = _orderRepository.BeginTransaction()) { await _orderRepository.SaveChangesAsync(); order.ShippingAddress = orderShipping; order.BillingAddress = orderBilling; await _orderRepository.SaveChangesAsync(); var orderCreated = new OrderCreated { OrderId = order.Id, Order = order, UserId = order.CreatedById, Note = order.OrderNote }; await _mediator.Publish(orderCreated); await _stockRepository.SaveChangesAsync(); if (addStockHistories.Count > 0) { _stockHistoryRepository.AddRange(addStockHistories); await _stockHistoryRepository.SaveChangesAsync(); } // 订单取消任务 如果n分钟内用户支付或主动取消订单时,则自动取消此任务 var min = await _appSettingService.Get <int>(OrderKeys.OrderAutoCanceledTimeForMinute); await _jobService.Schedule(() => Cancel(order.Id, (int)UserWithId.System, "超时自动取消"), TimeSpan.FromMinutes(min)); transaction.Commit(); } //TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted } //using (var ts = new TransactionScope()) //{ // ts.Complete(); //} return(order); }
/// <summary> /// Processes the payment. /// </summary> /// <param name="payment">The payment.</param> /// <param name="message">The message.</param> /// <returns></returns> public override bool ProcessPayment(Payment payment, ref string message) { string erroneousConfigurationMessage = "Authorize.NET payment gateway is not configured correctly. {0} is not set."; // cast the object first CreditCardPayment info = (CreditCardPayment)payment; if (info == null) { message = "Payment information is not specified."; throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } // Check if the gateway is configured correctly string processUrl = String.Empty; string user = String.Empty; string password = String.Empty; string recurringMethod = String.Empty; string cancelStatus = String.Empty; #region Getting parameters from the db // get user name if (!Settings.ContainsKey(_UserParameterName) || String.IsNullOrEmpty(Settings[_UserParameterName])) { message = String.Format(erroneousConfigurationMessage, _UserParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } user = Settings[_UserParameterName]; // get transaction key if (!Settings.ContainsKey(_TransactionKeyParameterName) || String.IsNullOrEmpty(Settings[_TransactionKeyParameterName])) { message = String.Format(erroneousConfigurationMessage, _TransactionKeyParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } password = Settings[_TransactionKeyParameterName]; #endregion bool processRegularTransaction = true; #region --------------- Process Transaction --------------- if (payment.Parent != null && (payment.Parent.Parent is PaymentPlan)) { // get recurring method and determine which type of transaction to perform if (!Settings.ContainsKey(_RecurringMethodParameterName) || String.IsNullOrEmpty(Settings[_RecurringMethodParameterName])) { message = String.Format(erroneousConfigurationMessage, _RecurringMethodParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } recurringMethod = Settings[_RecurringMethodParameterName]; if (String.Compare(recurringMethod, _AuthorizeRecurringMethodParameterValue, StringComparison.OrdinalIgnoreCase) == 0) { processRegularTransaction = false; } } if (processRegularTransaction) { #region Get parameters for the regular transaction // get processing url if (!Settings.ContainsKey(_ProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_ProcessUrlParameterName])) { message = String.Format(erroneousConfigurationMessage, _ProcessUrlParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } processUrl = Settings[_ProcessUrlParameterName]; #endregion #region Process regular transaction AuthorizeNetManager mgr = new AuthorizeNetManager(processUrl, user, password); TransactionData transData = new TransactionData(); transData.card = new CreditCard(); transData.type = Settings[_PaymentOptionParameterName] == "S" ? TransactionType.Sale : TransactionType.Authorization; transData.totalAmount = (double)GetSumInUSD(info.Amount, info.Parent.Parent.BillingCurrency); transData.card.cardNr = info.CreditCardNumber; transData.card.CSC = info.CreditCardSecurityCode; transData.card.expDate = new DateTime(info.ExpirationYear, info.ExpirationMonth, 1); // Find the address OrderAddress address = null; foreach (OrderAddress a in info.Parent.Parent.OrderAddresses) { if (a.Name == info.BillingAddressId) { address = a; break; } } if (address == null) { throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", "Billing address was not specified."); } transData.card.customerAddress = new Authorize.Address(); transData.card.customerAddress.countryCode = address.CountryCode; transData.card.customerAddress.zipCode = address.PostalCode; transData.card.customerAddress.city = address.City; transData.card.customerAddress.state = address.State; transData.card.customerAddress.street = address.Line1; transData.card.customerFirstName = address.FirstName; transData.card.customerLastName = address.LastName; transData.card.customerFax = address.FaxNumber; transData.card.customerPhone = address.DaytimePhoneNumber; transData.card.customerEMail = address.Email; ResponsePackage pkg = null; try { pkg = mgr.PerformCardTransaction(transData); } catch (PaymentException ex) { throw; //message = ex.Message; //return false; } catch { throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway."); } //info.TextResponse = pkg.responseReasonText; info.AuthorizationCode = pkg.responseCode; info.ValidationCode = pkg.approvalCode; #endregion } else { #region Get parameters for the recurring transaction // get processing url if (!Settings.ContainsKey(_RecurringProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_RecurringProcessUrlParameterName])) { message = String.Format(erroneousConfigurationMessage, _RecurringProcessUrlParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } processUrl = Settings[_RecurringProcessUrlParameterName]; // get cancel status if (!Settings.ContainsKey(_CancelStatusParameterName) || String.IsNullOrEmpty(Settings[_CancelStatusParameterName])) { message = String.Format(erroneousConfigurationMessage, _CancelStatusParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } cancelStatus = Settings[_CancelStatusParameterName]; #endregion PaymentPlan plan = (PaymentPlan)payment.Parent.Parent; #region Process recurring Authorize.NET transaction // Payment Plan -> Recurring transaction AuthorizeNetRecurringManager recurringMgr = new AuthorizeNetRecurringManager(processUrl, user, password); ANetApiResponse response = null; try { if (String.Compare(plan.Status, cancelStatus, StringComparison.OrdinalIgnoreCase) == 0) { // cancel subscription if (!String.IsNullOrEmpty(payment.AuthorizationCode)) { ARBCancelSubscriptionResponse cancelResponse = recurringMgr.CancelSubscription(PopulateCancelSubscriptionRequest(info)); // clear the authorization code info.AuthorizationCode = String.Empty; } else { throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "Payment AuthorizationCode cannot be null for the CancelSubscription operation", message); } } else if (plan.CompletedCyclesCount == 0) { if (String.IsNullOrEmpty(info.AuthorizationCode)) { // create subscription ARBCreateSubscriptionResponse createResponse = recurringMgr.CreateSubscription(PopulateCreateSubscriptionRequest(info)); response = (ANetApiResponse)createResponse; info.AuthorizationCode = createResponse.subscriptionId; } else { // update subscription recurringMgr.UpdateSubscription(PopulateUpdateSubscriptionRequest(info)); } } else { message = "The operation is invalid."; } } catch (PaymentException ex) { throw ex; } catch { throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway."); } #endregion } #endregion return(true); }
public override void Add(Document doc, NorthwindConfig config, ref List <TransactionResult> result) { TransactionResult tmpTransactionResult; List <TransactionResult> transactionResult = new List <TransactionResult>(); OrderDocument orderDoc = doc as OrderDocument; #region check input values if (orderDoc == null) { result.Add(doc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_DocumentTypeNotSupported)); return; } string customerID; if (orderDoc.accountid.IsNull) { result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountIDMadatory)); return; } customerID = (string)orderDoc.accountid.Value; if (!customerID.StartsWith(Constants.CustomerIdPrefix)) { result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AddOrdersForCustomersOnly)); return; } #endregion DataSets.OrderTableAdapters.OrdersTableAdapter tableAdapter; DataSets.OrderTableAdapters.Order_DetailsTableAdapter detailsTableAdapter; DataSets.Order order = new DataSets.Order(); DataSets.Order.OrdersRow newOrder = order.Orders.NewOrdersRow(); customerID = customerID.Substring(Constants.CustomerIdPrefix.Length); newOrder.CustomerID = customerID; #region get Company Name DataSet dataSet = new DataSet(); OleDbDataAdapter dataAdapter; string sqlQuery = "Select CompanyName from Customers where CustomerID = '" + customerID + "'"; try { using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { dataAdapter = new OleDbDataAdapter(sqlQuery, connection); if (dataAdapter.Fill(dataSet, "Customers") == 0) { result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_AccountNotFound)); return; } newOrder.ShipName = dataSet.Tables[0].Rows[0][0].ToString(); } } catch (Exception e) { orderDoc.Id = ""; throw; } #endregion #region get Sels rep if (orderDoc.salesrepr.IsNull) { newOrder.SetEmployeeIDNull(); } else { try { newOrder.EmployeeID = int.Parse((string)orderDoc.salesrepr.Value); } catch (Exception) { newOrder.SetEmployeeIDNull(); } if (newOrder.IsEmployeeIDNull()) { try { dataSet = new DataSet(); sqlQuery = "SELECT Employees.EmployeeID FROM Employees where Employees.FirstName + ' ' + Employees.LastName = ? "; using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { dataAdapter = new OleDbDataAdapter(sqlQuery, connection); OleDbParameter parameter = new OleDbParameter("Name", (string)orderDoc.salesrepr.Value); dataAdapter.SelectCommand.Parameters.Add(parameter); if (dataAdapter.Fill(dataSet, "Employees") > 0) { newOrder.EmployeeID = Convert.ToInt32(dataSet.Tables[0].Rows[0][0]); } else { newOrder.EmployeeID = 1; } } } catch (Exception e) { orderDoc.Id = ""; throw; } } } #endregion #region fill dataset from document try { if (orderDoc.opened.IsNull) { newOrder.SetOrderDateNull(); } else { newOrder.OrderDate = (DateTime)orderDoc.opened.Value; } if (orderDoc.deliverydate.IsNull) { newOrder.SetRequiredDateNull(); } else { newOrder.RequiredDate = (DateTime)orderDoc.deliverydate.Value; } if (orderDoc.shippedvia.IsNull) { newOrder.SetShipViaNull(); } else { newOrder.ShipVia = (int)orderDoc.shippedvia.Value; } if (orderDoc.shipaddress.IsNull) { newOrder.SetShipAddressNull(); newOrder.SetShipCityNull(); newOrder.SetShipCountryNull(); newOrder.SetShipPostalCodeNull(); } else { OrderAddress orderAddress = new OrderAddress(); orderAddress.CrmOrderAddress = (string)orderDoc.shipaddress.Value; newOrder.ShipAddress = (string)orderAddress.NorthwindAddress; newOrder.ShipCity = (string)orderAddress.NorthwindCity; newOrder.ShipPostalCode = (string)orderAddress.NorthwindZipCode; newOrder.ShipCountry = (string)orderAddress.NorthwindCountry; } if (orderDoc.freight.IsNull) { newOrder.Freight = (decimal)0; } else { newOrder.Freight = (decimal)orderDoc.freight.Value; } newOrder.CreateUser = config.CrmUser; newOrder.ModifyUser = config.CrmUser; newOrder.CreateID = config.SequenceNumber; newOrder.ModifyID = config.SequenceNumber; } catch (Exception e) { orderDoc.Id = ""; #warning Check error message result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.ToString())); return; } #endregion using (OleDbConnection connection = new OleDbConnection(config.ConnectionString)) { OleDbTransaction transaction = null; try { connection.Open(); transaction = connection.BeginTransaction(); tableAdapter = new DataSets.OrderTableAdapters.OrdersTableAdapter(); tableAdapter.Connection = connection; detailsTableAdapter = new DataSets.OrderTableAdapters.Order_DetailsTableAdapter(); detailsTableAdapter.Connection = connection; tableAdapter.SetTransaction(transaction); detailsTableAdapter.SetTransaction(transaction); order.Orders.AddOrdersRow(newOrder); tableAdapter.Update(order.Orders); OleDbCommand Cmd = new OleDbCommand("SELECT @@IDENTITY", connection); Cmd.Transaction = transaction; object lastid = Cmd.ExecuteScalar(); orderDoc.Id = ((int)lastid).ToString(); // add line Items DataSets.Order.Order_DetailsRow detailRow; Hashtable addedProductsProducts; addedProductsProducts = new Hashtable(); int productID; foreach (LineItemDocument lineItemDoc in orderDoc.orderitems) { try { try { productID = (int)lineItemDoc.productid.Value; } catch (Exception) { #warning only to test unsupported products productID = 0; } if (addedProductsProducts.Contains(productID)) { transaction.Rollback(); orderDoc.Id = ""; result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, Resources.ErrorMessages_OrderContainsProductTwice)); return; } addedProductsProducts.Add(productID, productID); detailRow = order.Order_Details.NewOrder_DetailsRow(); lineItemDoc.Id = orderDoc.Id + "-" + productID.ToString(); detailRow.OrderID = Convert.ToInt32(orderDoc.Id); detailRow.ProductID = productID; detailRow.Quantity = Convert.ToInt16(lineItemDoc.quantity.Value); detailRow.UnitPrice = (Decimal)lineItemDoc.listprice.Value; if ((lineItemDoc.discountsum.IsNull) || (detailRow.Quantity == 0) || (detailRow.UnitPrice == 0)) { detailRow.Discount = (float)0; } else { // discountPC = discountsum / qunatity * listprice //detailRow.Discount = Convert.ToSingle((decimal)lineItemDoc.discountsum.Value / ((decimal)detailRow.Quantity * detailRow.UnitPrice)); float discount = Convert.ToSingle((decimal)lineItemDoc.discountsum.Value / (detailRow.UnitPrice)); if (discount > 1) { discount = 0; } detailRow.Discount = discount; } detailRow.CreateUser = config.CrmUser; detailRow.ModifyUser = config.CrmUser; detailRow.CreateID = config.SequenceNumber; detailRow.ModifyID = config.SequenceNumber; } // this error occours in case of invalid data types catch (Exception e) { transaction.Rollback(); orderDoc.Id = ""; result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.Message)); return; } order.Order_Details.AddOrder_DetailsRow(detailRow); lineItemDoc.SetTransactionStatus(TransactionStatus.Success); } // here could an error ouucour in case on broken database connection // or of same invalid constraints which are unhandled before try { detailsTableAdapter.Update(order.Order_Details); } catch (Exception e) { transaction.Rollback(); orderDoc.Id = ""; result.Add(orderDoc.SetTransactionStatus(TransactionStatus.UnRecoverableError, e.Message)); return; } transaction.Commit(); orderDoc.GetTransactionResult(ref result); } catch (Exception transactionException) { if (transaction != null) { transaction.Rollback(); } orderDoc.Id = ""; throw; } } }
/// <summary> /// Sets the billing addresses. /// </summary> private void SetBillingAddresses() { OrderAddress address = null; if (Cart.OrderAddresses.ToArray().Length > 0) { string billingAddressId = CartHelper.Cart.OrderForms[0].BillingAddressId; if (!string.IsNullOrEmpty(billingAddressId)) { address = CartHelper.FindAddressByName(billingAddressId); } } else { var currentContact = CustomerContext.Current.CurrentContact; var defaultBillingAddress = currentContact == null ? null : currentContact.ContactAddresses.FirstOrDefault( a => currentContact.PreferredBillingAddressId.HasValue && currentContact.PreferredBillingAddressId.Value == a.PrimaryKeyId.Value); // Set default billing address to new order. if (defaultBillingAddress != null) { address = new OrderAddress(); CustomerAddress.CopyCustomerAddressToOrderAddress(defaultBillingAddress, address); Cart.OrderAddresses.Add(address); Cart.OrderForms[0].BillingAddressId = address.Name; } } BillingAddressInfo.OrderAddress = address; BillingAddressInfo.DataBind(); }
//Exercise (E2) Do CheckOut public ActionResult CheckOut(CheckOutViewModel model) { // ToDo: declare a variable for CartHelper CartHelper ch = new CartHelper(Cart.DefaultName); int orderAddressId = 0; // ToDo: Addresses (an If-Else) if (CustomerContext.Current.CurrentContact == null) { // Anonymous... one way of "doing it"... for example, if no other address exist orderAddressId = ch.Cart.OrderAddresses.Add( new OrderAddress { CountryCode = "SWE", CountryName = "Sweden", Name = "SomeCustomerAddress", DaytimePhoneNumber = "123456", FirstName = "John", LastName = "Smith", Email = "*****@*****.**", }); } else { // Logged in if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null) { // no pref. address set... so we set one for the contact CustomerAddress newCustAddress = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId); newCustAddress.AddressType = CustomerAddressTypeEnum.Shipping; // mandatory newCustAddress.ContactId = CustomerContext.Current.CurrentContact.PrimaryKeyId; newCustAddress.CountryCode = "SWE"; newCustAddress.CountryName = "Sweden"; newCustAddress.Name = "new customer address"; // mandatory newCustAddress.DaytimePhoneNumber = "123456"; newCustAddress.FirstName = CustomerContext.Current.CurrentContact.FirstName; newCustAddress.LastName = CustomerContext.Current.CurrentContact.LastName; newCustAddress.Email = "*****@*****.**"; // note: Line1 & City is what is shown in CM at a few places... not the Name CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress); CustomerContext.Current.CurrentContact.SaveChanges(); // ... needs to be in this order CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress; CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again // then, for the cart orderAddressId = ch.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress)); } else { // there is a preferred address set (and, a fourth alternative exists... do later ) OrderAddress orderAddress = new OrderAddress(CustomerContext.Current.CurrentContact.PreferredShippingAddress); // then, for the cart orderAddressId = ch.Cart.OrderAddresses.Add(orderAddress); } } // Depending how it was created... OrderAddress address = ch.FindAddressById(orderAddressId.ToString()); // ToDo: Define Shipping ShippingMethodDto.ShippingMethodRow theShip = ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First(); int shippingId = ch.Cart.OrderForms[0].Shipments.Add( new Shipment { // ...removing anything? ShippingAddressId = address.Name, // note: use no custom prefixes ShippingMethodId = theShip.ShippingMethodId, ShippingMethodName = theShip.Name, ShipmentTotal = theShip.BasePrice, ShipmentTrackingNumber = "My tracking number", }); // get the Shipping ... check to see if the Shipping knows about the LineItem Shipment firstOrderShipment = ch.Cart.OrderForms[0].Shipments.FirstOrDefault(); // First (and only) OrderForm LineItemCollection lineItems = ch.Cart.OrderForms[0].LineItems; // ...basic now... one OrderForm - one Shipping foreach (LineItem lineItem in lineItems) { int index = lineItems.IndexOf(lineItem); if ((firstOrderShipment != null) && (index != -1)) { firstOrderShipment.AddLineItemIndex(index, lineItem.Quantity); } } // Execute the "Shipping & Taxes - WF" (CartPrepare) ... and take care of the return object WorkflowResults resultPrepare = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartPrepareWorkflowName); List <string> wfMessagesPrepare = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultPrepare)); // ToDo: Define Shipping PaymentMethodDto.PaymentMethodRow thePay = PaymentManager.GetPaymentMethod(model.SelectedPayId).PaymentMethod.First(); Payment firstOrderPayment = ch.Cart.OrderForms[0].Payments.AddNew(typeof(OtherPayment)); // ... need both below firstOrderPayment.Amount = firstOrderShipment.SubTotal + firstOrderShipment.ShipmentTotal; // will change... firstOrderPayment.BillingAddressId = address.Name; firstOrderPayment.PaymentMethodId = thePay.PaymentMethodId; firstOrderPayment.PaymentMethodName = thePay.Name; // ch.Cart.CustomerName = "John Smith"; // ... this line overwrites what´s in there, if logged in // Execute the "Payment activation - WF" (CartCheckout) ... and take care of the return object // ...activates the gateway (same for shipping) WorkflowResults resultCheckout = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartCheckOutWorkflowName, false); List <string> wfMessagesCheckout = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultCheckout)); //ch.RunWorkflow("CartValidate") ... can see this (or variations) string trackingNumber = String.Empty; PurchaseOrder purchaseOrder = null; // Add a transaction scope and convert the cart to PO using (var scope = new Mediachase.Data.Provider.TransactionScope()) { purchaseOrder = ch.Cart.SaveAsPurchaseOrder(); ch.Cart.Delete(); ch.Cart.AcceptChanges(); trackingNumber = purchaseOrder.TrackingNumber; scope.Complete(); } // Housekeeping below (Shipping release, OrderNotes and save the order) OrderStatusManager.ReleaseOrderShipment(purchaseOrder.OrderForms[0].Shipments[0]); OrderNotesManager.AddNoteToPurchaseOrder(purchaseOrder, DateTime.UtcNow.ToShortDateString() + " released for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId); purchaseOrder.ExpirationDate = DateTime.UtcNow.AddDays(30); purchaseOrder.Status = OrderStatus.InProgress.ToString(); purchaseOrder.AcceptChanges(); // need this here, else no "order-note" persisted // Final steps, navigate to the order confirmation page StartPage home = _contentLoader.Service.Get <StartPage>(ContentReference.StartPage); ContentReference orderPageReference = home.Settings.orderPage; string passingValue = trackingNumber; return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue })); }
private Document GetDocument(DataSets.Order.CalculatedOrdersRow row, DataSets.Order.CalculatedOrderDetailsDataTable detailDataTable, DataSets.Order.DeletedOrderDetailsDataTable deletedOrderDetailsDataTable, Token lastToken, NorthwindConfig config) { #region Declarations OrderDocument doc; string id; LogState logState = LogState.Updated; Document lineItemDoc; CountryCodes countryCodes = new CountryCodes(); #endregion id = row.OrderID.ToString(); if (lastToken.InitRequest) { logState = LogState.Created; } else if (row.IsCreateIDNull() || row.IsModifyIDNull() || row.IsCreateUserNull() || row.IsModifyUserNull()) { logState = LogState.Created; } else if ((row.CreateID > lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser)) { logState = LogState.Created; } else if ((row.CreateID == lastToken.SequenceNumber) && (row.CreateUser != config.CrmUser) && (id.CompareTo(lastToken.Id.Id) > 0)) { logState = LogState.Created; } else if ((row.ModifyID >= lastToken.SequenceNumber) && (row.ModifyUser != config.CrmUser)) { logState = LogState.Updated; } doc = new OrderDocument(); doc.Id = id; doc.LogState = logState; doc.currency.Value = config.CurrencyCode; doc.pricinglistid.Value = Constants.DefaultValues.PriceList.ID; doc.reference.Value = id; if (row.IsCustomerIDNull()) { doc.accountid.Value = null; } else { doc.accountid.Value = Constants.CustomerIdPrefix + row.CustomerID; } if (row.IsOrderDateNull()) { doc.opened.Value = null; } else { doc.opened.Value = row.OrderDate; } if (row.IsShippedDateNull()) { doc.status.Value = Constants.OrderStatus.Active; } else { doc.status.Value = Constants.OrderStatus.Completed; } //doc.DiscountPercentage.Value = new decimal(0); //doc.grossamt.Value = row.IsTotalQuotedPriceNull() ? new decimal(0) : Convert.ToDecimal(row.TotalQuotedPrice); doc.discountamt.Value = new decimal(0); doc.lineitemdisc.Value = row.IsDiscountAmountNull() ? new decimal(0) : Convert.ToDecimal(row.DiscountAmount); doc.nettamt.Value = row.IsTotalNetPriceNull() ? new decimal(0) : Convert.ToDecimal(row.TotalNetPrice); doc.freight.Value = row.IsFreightNull() ? new decimal(0) : row.Freight; doc.tax.Value = new decimal(0); doc.grossamt.Value = doc.nettamt.Value; if (row.IsRequiredDateNull()) { doc.deliverydate.Value = null; } else { doc.deliverydate.Value = row.RequiredDate; } if (row.IsEmployeeIDNull()) { doc.salesrepr.Value = null; } else { doc.salesrepr.Value = Convert.ToString(row.EmployeeID); } if (row.IsShipViaNull()) { doc.shippedvia.Value = null; } else { doc.shippedvia.Value = row.ShipVia; } OrderAddress orderAddress = new OrderAddress(); orderAddress.SetNorthwindAddress(row.IsShipAddressNull() ? "" : row.ShipAddress, row.IsShipCityNull() ? "" : row.ShipCity, row.IsShipPostalCodeNull() ? "" : row.ShipPostalCode, row.IsShipCountryNull() ? "" : row.ShipCountry); doc.shipaddress.Value = orderAddress.CrmOrderAddress; foreach (DataSets.Order.CalculatedOrderDetailsRow detailRow in detailDataTable.Rows) { lineItemDoc = GetDocumentLineItem(detailRow, lastToken, config); if ((doc.LogState != LogState.Created) && (lineItemDoc.HasNoLogStatus)) { continue; } doc.orderitems.Add(lineItemDoc); } foreach (DataSets.Order.DeletedOrderDetailsRow deletedRow in deletedOrderDetailsDataTable.Rows) { lineItemDoc = new LineItemDocument(); lineItemDoc.Id = deletedRow[0].ToString(); lineItemDoc.LogState = LogState.Deleted; doc.orderitems.Add(lineItemDoc); } return(doc); }
public async Task <Order> CreateOrderAsync(string buyerEmail, string paymentMethod, double deliveryCost, string basketId, OrderAddress address) { var basket = await _basket.GetBasketAsync(basketId); var items = new List <OrderItem>(); var inValidProduct = false; foreach (var item in basket.Items) { var productItem = await _unitOfWork.Repository <Product>().GetByIdAsync(item.Id); if (item.Quantity > productItem.Quantity) { inValidProduct = true; break; } if (!item.IsActive) { inValidProduct = true; break; } var itemOrdered = new ProductItemOrdered(productItem.Id, productItem.Name, productItem.Photos.FirstOrDefault(p => p.IsMain)?.PictureUrl); var orderItem = new OrderItem(itemOrdered, productItem.Price, productItem.NetPrice, item.Quantity); items.Add(orderItem); productItem.Quantity -= item.Quantity; _unitOfWork.Repository <Product>().Update(productItem); } if (!inValidProduct) { var subTotal = items.Sum(it => it.Price * it.Quantity); var order = new Order(items, buyerEmail, subTotal, deliveryCost, address, paymentMethod == "COD" ? PaymentMethod.COD : paymentMethod == "COD**" ? PaymentMethod.COD_ : PaymentMethod.BankTransfer, paymentMethod == "COD" ? OrderStatus.WaitingConfirmation : paymentMethod == "COD**" ? OrderStatus.WaitingConfirmation : OrderStatus.WaitingTransfer); _unitOfWork.Repository <Order>().Add(order); var result = await _unitOfWork.Complete(); if (result <= 0) { return(null); } return(order); } return(null); }
public virtual IDictionary <string, string> GetParameters(PaymentRequest paymentRequest) { Payment payment = paymentRequest.Payment; OrderAddress billingAddress = payment.PurchaseOrder.GetBillingAddress(); var orderAddress = billingAddress; var shipment = payment.PurchaseOrder.Shipments.FirstOrDefault(); if (shipment != null && shipment.ShipmentAddress != null) { orderAddress = shipment.ShipmentAddress; } string orderCurrency = paymentRequest.Payment.PurchaseOrder.BillingCurrency.ISOCode; string referenceId = payment.ReferenceId; string callbackUrl = _callbackUrl.GetCallbackUrl(paymentRequest.PaymentMethod.DynamicProperty <string>().NotifyUrl, payment); string cancelUrl = _absoluteUrlService.GetAbsoluteUrl(paymentRequest.PaymentMethod.DynamicProperty <string>().CancelReturn); IDictionary <string, string> values = new Dictionary <string, string>(); // Set up call values.Add("USER", paymentRequest.PaymentMethod.DynamicProperty <string>().ApiUsername); values.Add("PWD", paymentRequest.PaymentMethod.DynamicProperty <string>().ApiPassword); values.Add("SIGNATURE", paymentRequest.PaymentMethod.DynamicProperty <string>().ApiSignature); values.Add("METHOD", "SetExpressCheckout"); values.Add("VERSION", "98.0"); //Add order values values.Add("RETURNURL", callbackUrl); values.Add("CANCELURL", cancelUrl); values.Add("NOSHIPPING", "1"); values.Add("ALLOWNOTE", "0"); var regionCode = GetRegionCode(paymentRequest); values.Add("LOCALECODE", regionCode); values.Add("SOLUTIONTYPE", "Sole"); values.Add("EMAIL", billingAddress.EmailAddress); //Vendor code to identify uCommerce values.Add("BUTTONSOURCE", "uCommerce_SP"); values.Add("PAYMENTREQUEST_0_SHIPTONAME", Uri.EscapeDataString(string.Format("{0} {1}", orderAddress.FirstName, orderAddress.LastName))); values.Add("PAYMENTREQUEST_0_SHIPTOSTREET", Uri.EscapeDataString(orderAddress.Line1)); values.Add("PAYMENTREQUEST_0_SHIPTOSTREET2", Uri.EscapeDataString(orderAddress.Line2)); values.Add("PAYMENTREQUEST_0_SHIPTOCITY", Uri.EscapeDataString(orderAddress.City)); values.Add("PAYMENTREQUEST_0_SHIPTOSTATE", Uri.EscapeDataString(orderAddress.State)); values.Add("PAYMENTREQUEST_0_SHIPTOZIP", Uri.EscapeDataString(orderAddress.PostalCode)); values.Add("PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE", Uri.EscapeDataString(orderAddress.Country.TwoLetterISORegionName)); values.Add("PAYMENTREQUEST_0_SHIPTOPHONENUM", Uri.EscapeDataString(orderAddress.PhoneNumber)); string fullAmount = NumberWithTwoDecimalDigitsAfterPeriodAndNoThousandsSeperator(payment.Amount); values.Add("PAYMENTREQUEST_0_AMT", fullAmount); values.Add("PAYMENTREQUEST_0_CURRENCYCODE", orderCurrency); PaymentAction pa = EnumExtensions.ParsePaymentActionThrowExceptionOnFailure(payment.PaymentMethod.DynamicProperty <string>().PaymentAction); values.Add("PAYMENTREQUEST_0_PAYMENTACTION", pa.ToString()); values.Add("PAYMENTREQUEST_0_INVNUM", referenceId); return(values); }
public async Task <Result> Post([FromBody] OrderCreateParam model) { if (model == null) { throw new Exception("参数异常"); } if (model.Items == null || model.Items.Count <= 0) { throw new Exception("请添加商品"); } if (model.Items.Any(c => c.Quantity <= 0)) { throw new Exception("购买商品数量必须>0"); } var user = await _workContext.GetCurrentUserAsync(); var customer = await _userRepository.FirstOrDefaultAsync(model.CustomerId); if (customer == null) { throw new Exception("客户不存在"); } var order = new Order() { OrderStatus = OrderStatus.New, CreatedBy = user, UpdatedBy = user, CustomerId = model.CustomerId, AdminNote = model.AdminNote, OrderNote = model.OrderNote, ShippingMethod = model.ShippingMethod, PaymentType = model.PaymentType, ShippingFeeAmount = model.ShippingFeeAmount, OrderTotal = model.OrderTotal, DiscountAmount = model.DiscountAmount, }; OrderAddress orderShipping = null; OrderAddress orderBilling = null; if (model.ShippingUserAddressId.HasValue && model.ShippingUserAddressId.Value > 0) { orderShipping = await this.UserAddressToOrderAddress(model.ShippingUserAddressId.Value, customer.Id, AddressType.Shipping, order); } if (model.BillingUserAddressId.HasValue && model.BillingUserAddressId.Value > 0) { orderBilling = await this.UserAddressToOrderAddress(model.BillingUserAddressId.Value, customer.Id, AddressType.Billing, order); } if (model.ShippingAddress != null && orderShipping == null) { orderShipping = new OrderAddress() { Order = order, AddressType = AddressType.Shipping, AddressLine1 = model.ShippingAddress.AddressLine1, AddressLine2 = model.ShippingAddress.AddressLine2, City = model.ShippingAddress.City, Company = model.ShippingAddress.Company, ContactName = model.ShippingAddress.ContactName, CountryId = model.ShippingAddress.CountryId, Email = model.ShippingAddress.Email, Phone = model.ShippingAddress.Phone, StateOrProvinceId = model.ShippingAddress.StateOrProvinceId, ZipCode = model.ShippingAddress.ZipCode }; } if (model.BillingAddress != null && orderBilling == null) { orderBilling = new OrderAddress() { Order = order, AddressType = AddressType.Billing, AddressLine1 = model.BillingAddress.AddressLine1, AddressLine2 = model.BillingAddress.AddressLine2, City = model.BillingAddress.City, Company = model.BillingAddress.Company, ContactName = model.BillingAddress.ContactName, CountryId = model.BillingAddress.CountryId, Email = model.BillingAddress.Email, Phone = model.BillingAddress.Phone, StateOrProvinceId = model.BillingAddress.StateOrProvinceId, ZipCode = model.BillingAddress.ZipCode }; } var productIds = model.Items.Select(c => c.Id).Distinct(); var products = await _productRepository.Query() .Include(c => c.ThumbnailImage) .Where(c => productIds.Contains(c.Id)).ToListAsync(); if (productIds.Count() <= 0) { throw new Exception("商品不存在"); } var stocks = await _stockRepository.Query().Where(c => productIds.Contains(c.ProductId)).ToListAsync(); var addStockHistories = new List <StockHistory>(); foreach (var item in products) { var first = model.Items.FirstOrDefault(c => c.Id == item.Id); if (first == null) { throw new Exception($"产品[{item.Name}]不存在"); } if (!item.IsPublished) { throw new Exception($"产品[{item.Name}]未发布"); } if (!item.IsAllowToOrder) { throw new Exception($"产品[{item.Name}]不允许购买"); } OrderStockDoWorker(stocks, addStockHistories, item, user, -first.Quantity, order, "创建订单"); var orderItem = new OrderItem() { Order = order, Product = item, ItemWeight = 0, ItemAmount = first.Quantity * first.ProductPrice - first.DiscountAmount, Quantity = first.Quantity, ProductPrice = first.ProductPrice, DiscountAmount = first.DiscountAmount, CreatedBy = user, UpdatedBy = user, ProductName = item.Name, ProductMediaUrl = item.ThumbnailImage?.Url }; order.OrderItems.Add(orderItem); } order.SubTotal = order.OrderItems.Sum(c => c.Quantity * c.ProductPrice); order.SubTotalWithDiscount = order.OrderItems.Sum(c => c.DiscountAmount); _orderRepository.Add(order); // Unable to save changes because a circular dependency was detected in the data to be saved // https://github.com/aspnet/EntityFrameworkCore/issues/11888 // https://docs.microsoft.com/zh-cn/ef/core/saving/transactions // https://stackoverflow.com/questions/40073149/entity-framework-circular-dependency-for-last-entity using (var transaction = _orderRepository.BeginTransaction()) { await _orderRepository.SaveChangesAsync(); order.ShippingAddress = orderShipping; order.BillingAddress = orderBilling; await _orderRepository.SaveChangesAsync(); var orderCreated = new OrderCreated { OrderId = order.Id, Order = order, UserId = order.CreatedById, Note = order.OrderNote }; await _mediator.Publish(orderCreated); await _stockRepository.SaveChangesAsync(); if (addStockHistories.Count > 0) { _stockHistoryRepository.AddRange(addStockHistories); await _stockHistoryRepository.SaveChangesAsync(); } transaction.Commit(); } //TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted } //using (var ts = new TransactionScope()) //{ // ts.Complete(); //} return(Result.Ok()); }
public OrderAddress ToOrderAddress(string name) { var address = new OrderAddress(); address.FirstName = FirstName; address.LastName = LastName; address.Name = name; address.Line1 = StreetAddress; address.PostalCode = ZipCode; address.City = City; address[Constants.Metadata.Address.DeliveryServicePoint] = DeliveryServicePoint; address.CountryCode = CountryCode; return address; }
public void Test_Insert_Site_Then_UpdateOptimistic() { OrderAddress objOrderAddress = new OrderAddress(); //objOrderAddress.OrderAddressID = 0; objOrderAddress.OrderAddressTypeID = (int)OrderAddressTypes.Site; objOrderAddress.MigrationStatusID = (int)MigrationStatuses.STAGED_for_Processing; objOrderAddress.OrderSystemOfRecordID = (int)OrderSystemOfRecords.EON; objOrderAddress.CDWCustomerOrderNumber = DateTime.UtcNow.Ticks.ToString(); objOrderAddress.CDWAddressOne = "72 E 3RD AVE"; objOrderAddress.CDWCity = "SAN MATEO"; objOrderAddress.CDWState = "CA"; objOrderAddress.CDWPostalCode = "94401"; objOrderAddress.CDWCountry = "USA"; objOrderAddress.CDWFloor = String.Empty; objOrderAddress.CDWRoom = String.Empty; objOrderAddress.CDWSuite = String.Empty; objOrderAddress.CDWCLII = null; objOrderAddress.ValidCLII = false; objOrderAddress.NumberOfFailedGLMSiteCalls = 0; objOrderAddress.ExistsInGLMAsSite = true; objOrderAddress.GLMPLNumber = ""; objOrderAddress.NumberOfFailedGLMSiteCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSiteCodeCreationCalls = 0; objOrderAddress.GLMSiteCode = ""; objOrderAddress.HasGLMSiteCode = true; objOrderAddress.NumberOfFailedSAPSiteAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPSiteAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsSiteAddress = true; objOrderAddress.NumberOfRecordsInSAPWithPL = 0; objOrderAddress.NumberOfFailedGLMServiceLocationSearchCalls = 0; objOrderAddress.NumberOfFailedGLMServiceLocationCreationCalls = 0; objOrderAddress.GLMSLNumber = ""; objOrderAddress.ExistsInGLMAsServiceLocation = true; objOrderAddress.NumberOfFailedGLMSCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSCodeCreationCalls = 0; objOrderAddress.GLMSCode = ""; objOrderAddress.HasGLMSCode = true; objOrderAddress.NumberOfFailedSAPServiceLocationAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPServiceLocationAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsServiceLocationAddress = true; objOrderAddress.NumberOfRecordsInSAPWithSL = 0; objOrderAddress.SourceCreationDate = new DateTime(2018, 08, 01); objOrderAddress.SourceLastModifyDate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastMigrationStatusUpdate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastDupDetection = new DateTime(2018, 08, 01); objOrderAddress.DateCreated = new DateTime(2018, 08, 01); objOrderAddress.DateUpdated = new DateTime(2018, 08, 01); string strLastError = String.Empty; Assert.IsTrue(objOrderAddress.Insert(out strLastError)); Assert.IsTrue(objOrderAddress.OrderAddressID > 0); Assert.IsTrue(strLastError == String.Empty); // This will fail... no data hash populated objOrderAddress.CDWCity += " UPDATED VALUE"; Assert.IsFalse(objOrderAddress.UpdateOptimistic(out strLastError)); Assert.IsTrue(strLastError.Contains("Concurrent action violation")); // This should work since it is populated with a method that returns the current data hash OrderAddress objOrderAddressViaGet = new OrderAddress().Get(objOrderAddress.OrderAddressID.Value, out strLastError); objOrderAddressViaGet.CDWCity += " UPDATED VIA GET"; Assert.IsTrue(objOrderAddressViaGet.UpdateOptimistic(out strLastError)); Assert.IsTrue(objOrderAddressViaGet.OrderAddressID > 0); Assert.IsTrue(strLastError == String.Empty); // This should fail since we intentionally override things with a bogus data hash OrderAddress objOrderAddress2ViaGet = new OrderAddress().Get(objOrderAddress.OrderAddressID.Value, out strLastError); objOrderAddress2ViaGet.DataHash += "BogusDataHash"; Assert.IsFalse(objOrderAddress2ViaGet.UpdateOptimistic(out strLastError)); Assert.IsTrue(strLastError.Contains("Concurrent action violation")); }
/// <summary> /// Gets the default shipping addresses. /// </summary> private OrderAddress GetDefaultShippingAddresses() { OrderAddress address = null; var currentContact = CustomerContext.Current.CurrentContact; { var defaultShippingAdd = currentContact == null ? null : currentContact.ContactAddresses.FirstOrDefault( a => currentContact.PreferredShippingAddressId.HasValue && currentContact.PreferredShippingAddressId.Value == a.PrimaryKeyId.Value); // Set default shipping address to new order. if (defaultShippingAdd != null) { address = new OrderAddress(); CustomerAddress.CopyCustomerAddressToOrderAddress(defaultShippingAdd, address); } } return address; }
public async Task CreateOrder(User user, Address billingAddress, Address shippingAddress) { var cart = _cartRepository .Query() .Include(c => c.Items).ThenInclude(x => x.Product) .Where(x => x.UserId == user.Id && x.IsActive).FirstOrDefault(); if (cart == null) { throw new ApplicationException($"Cart of user {user.Id} can no be found"); } decimal discount = 0; if (!string.IsNullOrWhiteSpace(cart.CouponCode)) { var cartInfoForCoupon = new CartInfoForCoupon { Items = cart.Items.Select(x => new CartItemForCoupon { ProductId = x.ProductId, Quantity = x.Quantity }).ToList() }; var couponValidationResult = await _couponService.Validate(cart.CouponCode, cartInfoForCoupon); if (couponValidationResult.Succeeded) { discount = couponValidationResult.DiscountAmount; _couponService.AddCouponUsage(user.Id, couponValidationResult.CouponId); } else { throw new ApplicationException($"Unable to apply coupon {cart.CouponCode}. {couponValidationResult.ErrorMessage}"); } } var orderBillingAddress = new OrderAddress() { AddressLine1 = billingAddress.AddressLine1, AddressLine2 = billingAddress.AddressLine2, ContactName = billingAddress.ContactName, CountryId = billingAddress.CountryId, StateOrProvinceId = billingAddress.StateOrProvinceId, DistrictId = billingAddress.DistrictId, City = billingAddress.City, PostalCode = billingAddress.PostalCode, Phone = billingAddress.Phone }; var orderShippingAddress = new OrderAddress() { AddressLine1 = shippingAddress.AddressLine1, AddressLine2 = shippingAddress.AddressLine2, ContactName = shippingAddress.ContactName, CountryId = shippingAddress.CountryId, StateOrProvinceId = shippingAddress.StateOrProvinceId, DistrictId = shippingAddress.DistrictId, City = shippingAddress.City, PostalCode = shippingAddress.PostalCode, Phone = shippingAddress.Phone }; var order = new Order { CreatedOn = DateTimeOffset.Now, CreatedById = user.Id, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress }; foreach (var cartItem in cart.Items) { var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = cartItem.Product.Price, Quantity = cartItem.Quantity }; order.AddOrderItem(orderItem); } order.CouponCode = cart.CouponCode; order.CouponRuleName = cart.CouponRuleName; order.Discount = discount; order.SubTotal = order.OrderItems.Sum(x => x.ProductPrice * x.Quantity); order.SubTotalWithDiscount = order.SubTotal - discount; _orderRepository.Add(order); cart.IsActive = false; var vendorIds = cart.Items.Where(x => x.Product.VendorId.HasValue).Select(x => x.Product.VendorId.Value).Distinct(); foreach (var vendorId in vendorIds) { var subOrder = new Order { CreatedOn = DateTimeOffset.Now, CreatedById = user.Id, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress, VendorId = vendorId, Parent = order }; foreach (var cartItem in cart.Items.Where(x => x.Product.VendorId == vendorId)) { var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = cartItem.Product.Price, Quantity = cartItem.Quantity }; subOrder.AddOrderItem(orderItem); } subOrder.SubTotal = subOrder.OrderItems.Sum(x => x.ProductPrice * x.Quantity); _orderRepository.Add(subOrder); } _orderRepository.SaveChanges(); }
/// <summary> /// Sets the shipping address /// </summary> /// <param name="address"> Shipping address </param> public void SetShippingAddresses(OrderAddress address) { ShippingAddressInfo.OrderAddress = address; ShippingAddressInfo.DataBind(); }
protected void Page_Load(object sender, EventArgs e) { if (!SetupIsNeeded()) { return; } Guid orderGuid = new Guid(HttpContext.Current.Request.Params["orderGuid"]); var basket = PurchaseOrder.SingleOrDefault(x => x.OrderGuid == orderGuid); //billing/shipping information OrderAddress billingAddress = basket.GetBillingAddress(); OrderAddress shipmentAddress = basket.GetShippingAddress(billingAddress.AddressName); //billing litBillingName.Text = billingAddress.FirstName + " " + billingAddress.LastName; litBillingStreet.Text = billingAddress.Line1; litBillingPostalCode.Text = billingAddress.PostalCode; litBillingCity.Text = billingAddress.City; litBillingCountry.Text = billingAddress.Country.Name; if (!string.IsNullOrEmpty(billingAddress.Attention)) { litBillingAttention.Text = "<text>att. </text>" + billingAddress.Attention; } litBillingPhone.Text = billingAddress.PhoneNumber; litBillingMobilePhone.Text = billingAddress.MobilePhoneNumber; lnkBillingMail.NavigateUrl = "mailto:" + billingAddress.EmailAddress; lnkBillingMail.Text = billingAddress.EmailAddress; //shipping if (shipmentAddress != null) { litShippingName.Text = shipmentAddress.FirstName + " " + shipmentAddress.LastName; litShippingCompany.Text = shipmentAddress.CompanyName; litShippingStreet.Text = shipmentAddress.Line1; litShippingPostalCode.Text = shipmentAddress.PostalCode; litShippingCity.Text = shipmentAddress.City; litShippingCountry.Text = shipmentAddress.Country.Name; if (!string.IsNullOrEmpty(shipmentAddress.Attention)) { litShippingAttention.Text = "<text>att. </text>" + shipmentAddress.Attention; } litShippingPhone.Text = shipmentAddress.PhoneNumber; litShippingMobilePhone.Text = shipmentAddress.MobilePhoneNumber; lnkShippingMail.NavigateUrl = "mailto:" + shipmentAddress.EmailAddress; lnkShippingMail.Text = shipmentAddress.EmailAddress; } else { divShippingAddress.Visible = false; } //Basket information Currency currency = basket.BillingCurrency; var subTotal = new Money(basket.SubTotal.Value, currency); var tax = new Money(basket.VAT.Value, currency); var discount = new Money(basket.DiscountTotal.Value * -1, currency); var shippingTotal = new Money(basket.ShippingTotal.Value, currency); var paymentTotal = new Money(basket.PaymentTotal.Value, currency); var orderTotal = new Money(basket.OrderTotal.Value, currency); var shipments = basket.Shipments; if (basket.SubTotal.HasValue) { subTotal = new Money(basket.SubTotal.Value, currency); } if (basket.VAT.HasValue) { tax = new Money(basket.VAT.Value, currency); } if (basket.OrderTotal.HasValue) { orderTotal = new Money(basket.OrderTotal.Value, currency); } if (discount.Value > 0) { litDiscount.Text = discount.ToString(); } else { trDiscounts.Visible = false; } var rowspan = 3; if (discount.Value > 0) { rowspan++; } if (shippingTotal.Value > 0) { rowspan++; } if (paymentTotal.Value > 0) { rowspan++; } litRowSpan.Text = "<td rowspan=\"" + rowspan + "\" colspan=\"2\"></td>"; string shipmentString = ""; if (shippingTotal.Value > 0) { if (shipments.Count > 1) { shipmentString += "<ul>"; foreach (var shipment in shipments) { shipmentString += "<li>" + shipment.ShipmentName + "</li>"; } shipmentString += "</ul>"; } else { shipmentString += "<text> (via" + shipments.First().ShipmentName + ")</text>"; } litShipments.Text = shipmentString; litShippingTotal.Text = shippingTotal.ToString(); } else { trShipping.Visible = false; } if (paymentTotal.Value > 0) { string paymentString = ""; if (basket.Payments.Count > 1) { paymentString += "<ul>"; foreach (var payment in basket.Payments) { paymentString += "<li>" + payment.PaymentMethodName + "</li>"; } } else { paymentString += "<text> (" + basket.Payments.First().PaymentMethodName + ")</text>"; } litPaymentMethods.Text = paymentString; litPaymentTotal.Text = paymentTotal.ToString(); } else { trPaymentTotal.Visible = false; } litSubTotal.Text = subTotal.ToString(); litVat.Text = tax.ToString(); litOrderTotal.Text = orderTotal.ToString(); rptPreviewItems.DataSource = basket.OrderLines; rptPreviewItems.DataBind(); }
public void Test_Insert_Site_Then_GetByCompositeFields_NullSLFields() { OrderAddress objOrderAddress = new OrderAddress(); //objOrderAddress.OrderAddressID = 0; objOrderAddress.OrderAddressTypeID = (int)OrderAddressTypes.Site; objOrderAddress.MigrationStatusID = (int)MigrationStatuses.STAGED_for_Processing; objOrderAddress.OrderSystemOfRecordID = (int)OrderSystemOfRecords.EON; objOrderAddress.CDWCustomerOrderNumber = DateTime.UtcNow.Ticks.ToString(); objOrderAddress.CDWAddressOne = "72 E 3RD AVE"; objOrderAddress.CDWCity = "SAN MATEO"; objOrderAddress.CDWState = "CA"; objOrderAddress.CDWPostalCode = "94401"; objOrderAddress.CDWCountry = "USA"; objOrderAddress.CDWFloor = String.Empty; objOrderAddress.CDWRoom = String.Empty; objOrderAddress.CDWSuite = String.Empty; objOrderAddress.CDWCLII = null; objOrderAddress.ValidCLII = false; objOrderAddress.NumberOfFailedGLMSiteCalls = 0; objOrderAddress.ExistsInGLMAsSite = true; objOrderAddress.GLMPLNumber = ""; objOrderAddress.NumberOfFailedGLMSiteCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSiteCodeCreationCalls = 0; objOrderAddress.GLMSiteCode = ""; objOrderAddress.HasGLMSiteCode = true; objOrderAddress.NumberOfFailedSAPSiteAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPSiteAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsSiteAddress = true; objOrderAddress.NumberOfRecordsInSAPWithPL = 0; objOrderAddress.NumberOfFailedGLMServiceLocationSearchCalls = 0; objOrderAddress.NumberOfFailedGLMServiceLocationCreationCalls = 0; objOrderAddress.GLMSLNumber = ""; objOrderAddress.ExistsInGLMAsServiceLocation = true; objOrderAddress.NumberOfFailedGLMSCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSCodeCreationCalls = 0; objOrderAddress.GLMSCode = ""; objOrderAddress.HasGLMSCode = true; objOrderAddress.NumberOfFailedSAPServiceLocationAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPServiceLocationAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsServiceLocationAddress = true; objOrderAddress.NumberOfRecordsInSAPWithSL = 0; objOrderAddress.SourceCreationDate = new DateTime(2018, 08, 01); objOrderAddress.SourceLastModifyDate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastMigrationStatusUpdate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastDupDetection = new DateTime(2018, 08, 01); objOrderAddress.DateCreated = new DateTime(2018, 08, 01); objOrderAddress.DateUpdated = new DateTime(2018, 08, 01); string strLastError = String.Empty; Assert.IsTrue(objOrderAddress.Insert(out strLastError)); Assert.IsTrue(objOrderAddress.OrderAddressID > 0); Assert.IsTrue(strLastError == String.Empty); OrderAddress objOrderAddressViaGet = new OrderAddress().Get(objOrderAddress.OrderSystemOfRecordID.Value, objOrderAddress.CDWCustomerOrderNumber, objOrderAddress.CDWAddressOne, objOrderAddress.CDWCity, objOrderAddress.CDWState, objOrderAddress.CDWPostalCode, objOrderAddress.CDWCountry, objOrderAddress.CDWFloor, objOrderAddress.CDWRoom, objOrderAddress.CDWSuite, out strLastError); Assert.IsTrue(objOrderAddressViaGet.OrderAddressID > 0); Assert.IsTrue(strLastError == String.Empty); }
public string BuildRequest(PaymentRequest paymentRequest) { string accountId = paymentRequest.PaymentMethod.DynamicProperty <string>().AccountId; string siteId = paymentRequest.PaymentMethod.DynamicProperty <string>().SiteId; string siteSecurityCode = paymentRequest.PaymentMethod.DynamicProperty <string>().SiteSecurityCode; string callbackUrl = paymentRequest.PaymentMethod.DynamicProperty <string>().CallbackUrl; string acceptUrl = paymentRequest.PaymentMethod.DynamicProperty <string>().AcceptUrl; string cancelUrl = paymentRequest.PaymentMethod.DynamicProperty <string>().CancelUrl; var requestBuilder = new StringBuilder(); OrderAddress billingAddress = paymentRequest.PurchaseOrder.GetBillingAddress(); var md5Hasher = new MD5CryptoServiceProvider(); var encoder = new UTF8Encoding(); string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; string forwardedIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; byte[] hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(paymentRequest.Amount.Value.ToCents() + paymentRequest.Amount.Currency.ISOCode + accountId + siteId + paymentRequest.Payment.ReferenceId)); string signature = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); requestBuilder.AppendFormat(@"<?xml version='1.0' encoding='utf-8'?>"); requestBuilder.AppendFormat(@"<redirecttransaction ua='custom-1.2'>"); requestBuilder.AppendFormat(@" <merchant> "); requestBuilder.AppendFormat(@" <account>{0}</account>", accountId); requestBuilder.AppendFormat(@" <site_id>{0}</site_id>", siteId); requestBuilder.AppendFormat(@" <site_secure_code>{0}</site_secure_code>", siteSecurityCode); requestBuilder.AppendFormat(@" <notification_url>{0}</notification_url>", _callbackUrl.GetCallbackUrl(callbackUrl, paymentRequest.Payment)); requestBuilder.AppendFormat(@" <redirect_url>{0}</redirect_url>", new Uri(_absoluteUrlService.GetAbsoluteUrl(acceptUrl)).AddOrderGuidParameter(paymentRequest.Payment.PurchaseOrder)); requestBuilder.AppendFormat(@" <cancel_url>{0}</cancel_url>", new Uri(_absoluteUrlService.GetAbsoluteUrl(cancelUrl)).AddOrderGuidParameter(paymentRequest.Payment.PurchaseOrder)); requestBuilder.AppendFormat(@" </merchant>"); requestBuilder.AppendFormat(@" <customer>"); requestBuilder.AppendFormat(@" <locale>{0}</locale>", paymentRequest.PurchaseOrder.CultureCode); requestBuilder.AppendFormat(@" <ipaddress>{0}</ipaddress>", ipAddress); requestBuilder.AppendFormat(@" <forwardedip>{0}</forwardedip>", forwardedIp); requestBuilder.AppendFormat(@" <firstname>{0}</firstname>", XmlHelper.ConvertToValidXmlText(billingAddress.FirstName)); requestBuilder.AppendFormat(@" <lastname>{0}</lastname>", XmlHelper.ConvertToValidXmlText(billingAddress.LastName)); requestBuilder.AppendFormat(@" <address1>{0}</address1>", XmlHelper.ConvertToValidXmlText(billingAddress.Line1)); requestBuilder.AppendFormat(@" <address2>{0}</address2>", XmlHelper.ConvertToValidXmlText(billingAddress.Line2)); requestBuilder.AppendFormat(@" <zipcode>{0}</zipcode>", XmlHelper.ConvertToValidXmlText(billingAddress.PostalCode)); requestBuilder.AppendFormat(@" <city>{0}</city>", XmlHelper.ConvertToValidXmlText(billingAddress.City)); requestBuilder.AppendFormat(@" <state>{0}</state>", XmlHelper.ConvertToValidXmlText(billingAddress.State)); requestBuilder.AppendFormat(@" <phone>{0}</phone>", XmlHelper.ConvertToValidXmlText(billingAddress.PhoneNumber)); requestBuilder.AppendFormat(@" <email>{0}</email>", XmlHelper.ConvertToValidXmlText(billingAddress.EmailAddress)); requestBuilder.AppendFormat(@" </customer>"); requestBuilder.AppendFormat(@" <transaction>"); requestBuilder.AppendFormat(@" <id>{0}</id>", paymentRequest.Payment.ReferenceId); requestBuilder.AppendFormat(@" <currency>{0}</currency>", paymentRequest.Amount.Currency.ISOCode); requestBuilder.AppendFormat(@" <amount>{0}</amount>", paymentRequest.Amount.Value.ToCents()); requestBuilder.AppendFormat(@" <description>{0}</description>", paymentRequest.Payment.ReferenceId); var itemStringBuilder = new StringBuilder(); foreach (var orderLine in paymentRequest.PurchaseOrder.OrderLines) { itemStringBuilder.AppendFormat(@"<li>{0} x {1}, {2}</li>", orderLine.Quantity, XmlHelper.ConvertToValidXmlText(orderLine.ProductName), orderLine.Total); } requestBuilder.AppendFormat(@" <items><ul>{0}</ul></items>", itemStringBuilder); requestBuilder.AppendFormat(@" </transaction>"); requestBuilder.AppendFormat(@" <signature>{0}</signature>", signature); requestBuilder.AppendFormat(@"</redirecttransaction>"); return(requestBuilder.ToString()); }
/// <summary> /// Fill in the given request with test data to create a new subscription. /// </summary> /// <param name="payment">The payment object.</param> private static ARBCreateSubscriptionRequest PopulateCreateSubscriptionRequest(CreditCardPayment payment) { ARBCreateSubscriptionRequest request = new ARBCreateSubscriptionRequest(); PaymentPlan plan = (PaymentPlan)payment.Parent.Parent; ARBSubscriptionType sub = new ARBSubscriptionType(); creditCardType creditCard = new creditCardType(); sub.name = CoreConfiguration.Instance.DefaultApplicationName + " - subscription"; creditCard.cardNumber = payment.CreditCardNumber; creditCard.expirationDate = String.Format("{0:d4}-{1:d2}", payment.ExpirationYear, payment.ExpirationMonth); // required format for API is YYYY-MM sub.payment = new paymentType(); sub.payment.Item = creditCard; // Find the address OrderAddress address = null; foreach (OrderAddress a in plan.OrderAddresses) { if (a.Name == payment.BillingAddressId) { address = a; break; } } sub.billTo = new nameAndAddressType(); sub.billTo.firstName = address.FirstName; sub.billTo.lastName = address.LastName; // Create a subscription sub.paymentSchedule = new paymentScheduleType(); sub.paymentSchedule.startDate = plan.StartDate; sub.paymentSchedule.startDateSpecified = true; sub.paymentSchedule.totalOccurrences = Convert.ToInt16(plan.MaxCyclesCount); sub.paymentSchedule.totalOccurrencesSpecified = true; // free 1 month trial //sub.paymentSchedule.trialOccurrences = 1; //sub.paymentSchedule.trialOccurrencesSpecified = true; //sub.trialAmount = 0.00M; //sub.trialAmountSpecified = true; sub.amount = GetSumInUSD(payment.Amount, plan.BillingCurrency); sub.amountSpecified = true; sub.paymentSchedule.interval = GetRecurringPaymentTypeInterval(plan); sub.order = new orderType(); sub.order.invoiceNumber = plan.OrderGroupId.ToString(); sub.customer = new customerType(); sub.customer.email = address.Email; request.subscription = sub; return(request); }
} // End AddPaymentToOrder private IOrderAddress AddAddressToOrder(ICart cart) { IOrderAddress shippingAddress; if (CustomerContext.Current.CurrentContact == null) // anonymous { // Anonymous... one way of "doing it"... for example, if no other address exist var shipment = cart.GetFirstShipment(); // ... moved to shipment - prev. = .OrderAddresses.Add( if (shipment.ShippingAddress != null) { //return false/true; // Should we clean upfirst? } // New School IOrderAddress myOrderAddress = _orderGroupFactory.CreateOrderAddress(cart); myOrderAddress.CountryName = "Sweden"; myOrderAddress.Id = "MyNewAddress"; myOrderAddress.Email = "*****@*****.**"; // temp-fix this shippingAddress = myOrderAddress; // OldSchool //shippingAddress = shipment.ShippingAddress = // // new OrderAddress // { // CountryCode = "USA", // CountryName = "United States", // Name = "SomeCustomerAddressName", // DaytimePhoneNumber = "123456", // FirstName = "John", // LastName = "Smith", // Email = "*****@*****.**", // }; } // end anonymous else { // Logged in if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null) { // no pref. address set... so we set one for the contact CustomerAddress newCustAddress = CustomerAddress.CreateInstance(); newCustAddress.AddressType = CustomerAddressTypeEnum.Shipping | CustomerAddressTypeEnum.Public; // mandatory newCustAddress.ContactId = CustomerContext.Current.CurrentContact.PrimaryKeyId; newCustAddress.CountryCode = "SWE"; newCustAddress.CountryName = "Sweden"; newCustAddress.Name = "new customer address"; // mandatory newCustAddress.DaytimePhoneNumber = "123456"; newCustAddress.FirstName = CustomerContext.Current.CurrentContact.FirstName; newCustAddress.LastName = CustomerContext.Current.CurrentContact.LastName; newCustAddress.Email = "*****@*****.**"; // note: Line1 & City is what is shown in CM at a few places... not the Name CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress); CustomerContext.Current.CurrentContact.SaveChanges(); // ... needs to be in this order CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress; CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again // then, for the cart //.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress)); - OLD shippingAddress = new OrderAddress(newCustAddress); // - NEW } else { // ...a 3:rd vay, there is a preferred address set shippingAddress = new OrderAddress( CustomerContext.Current.CurrentContact.PreferredShippingAddress); } } return(shippingAddress); } //End AddAddressToOrder
/// <summary> /// Gets the item tax in percent. /// </summary> /// <param name="item">The item.</param> /// <param name="addressByName">Name of the address by.</param> /// <returns>Return the tax in percent</returns> private decimal GetItemSaleTax(LineItem item, OrderAddress addressByName) { var itemTax = 0M; // Get the catalogEntryDto var catalogEntryDto = CatalogContext.Current.GetCatalogEntryDto(item.Code, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Variations)); if (catalogEntryDto.CatalogEntry.Count > 0) { // Get the variationrows var variationRows = catalogEntryDto.CatalogEntry[0].GetVariationRows(); if (variationRows.Length > 0) { // Get TaxCategory var taxCategoryNameById = CatalogTaxManager.GetTaxCategoryNameById(variationRows[0].TaxCategoryId); var valueArray = OrderContext.Current.GetTaxes(Guid.Empty, taxCategoryNameById, Thread.CurrentThread.CurrentCulture.Name, addressByName.CountryCode, addressByName.State, addressByName.PostalCode, addressByName.RegionCode, string.Empty, addressByName.City); if (valueArray.Length > 0) { itemTax = (decimal)valueArray.Where(v => v.TaxType == TaxType.SalesTax).Sum(v => v.Percentage); } } } return itemTax; }
public async Task <Order> CreateOrder(User user, string paymentMethod, string shippingMethodName, Address billingAddress, Address shippingAddress) { var cart = _cartRepository .Query() .Include(c => c.Items).ThenInclude(x => x.Product) .Where(x => x.UserId == user.Id && x.IsActive).FirstOrDefault(); if (cart == null) { throw new ApplicationException($"Cart of user {user.Id} cannot be found"); } var discount = await ApplyDiscount(user, cart); var shippingMethod = await ValidateShippingMethod(shippingMethodName, shippingAddress, cart); var orderBillingAddress = new OrderAddress() { AddressLine1 = billingAddress.AddressLine1, AddressLine2 = billingAddress.AddressLine2, ContactName = billingAddress.ContactName, CountryId = billingAddress.CountryId, StateOrProvinceId = billingAddress.StateOrProvinceId, DistrictId = billingAddress.DistrictId, City = billingAddress.City, PostalCode = billingAddress.PostalCode, Phone = billingAddress.Phone }; var orderShippingAddress = new OrderAddress() { AddressLine1 = shippingAddress.AddressLine1, AddressLine2 = shippingAddress.AddressLine2, ContactName = shippingAddress.ContactName, CountryId = shippingAddress.CountryId, StateOrProvinceId = shippingAddress.StateOrProvinceId, DistrictId = shippingAddress.DistrictId, City = shippingAddress.City, PostalCode = shippingAddress.PostalCode, Phone = shippingAddress.Phone }; var order = new Order { CreatedOn = DateTimeOffset.Now, CreatedById = user.Id, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress, PaymentMethod = paymentMethod, }; foreach (var cartItem in cart.Items) { var taxPercent = await _taxService.GetTaxPercent(cartItem.Product.TaxClassId, shippingAddress.CountryId, shippingAddress.StateOrProvinceId); var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = cartItem.Product.Price, Quantity = cartItem.Quantity, TaxPercent = taxPercent, TaxAmount = cartItem.Quantity * (cartItem.Product.Price * taxPercent / 100) }; order.AddOrderItem(orderItem); } order.CouponCode = cart.CouponCode; order.CouponRuleName = cart.CouponRuleName; order.Discount = discount; order.ShippingAmount = shippingMethod.Price; order.ShippingMethod = shippingMethod.Name; order.TaxAmount = order.OrderItems.Sum(x => x.TaxAmount); order.SubTotal = order.OrderItems.Sum(x => x.ProductPrice * x.Quantity); order.SubTotalWithDiscount = order.SubTotal - discount; order.OrderTotal = order.SubTotal + order.TaxAmount + order.ShippingAmount - order.Discount; _orderRepository.Add(order); cart.IsActive = false; var vendorIds = cart.Items.Where(x => x.Product.VendorId.HasValue).Select(x => x.Product.VendorId.Value).Distinct(); foreach (var vendorId in vendorIds) { var subOrder = new Order { CreatedOn = DateTimeOffset.Now, CreatedById = user.Id, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress, VendorId = vendorId, Parent = order }; foreach (var cartItem in cart.Items.Where(x => x.Product.VendorId == vendorId)) { var taxPercent = await _taxService.GetTaxPercent(cartItem.Product.TaxClassId, shippingAddress.CountryId, shippingAddress.StateOrProvinceId); var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = cartItem.Product.Price, Quantity = cartItem.Quantity, TaxPercent = taxPercent, TaxAmount = cartItem.Quantity * (cartItem.Product.Price * taxPercent / 100) }; subOrder.AddOrderItem(orderItem); } subOrder.SubTotal = subOrder.OrderItems.Sum(x => x.ProductPrice * x.Quantity); subOrder.TaxAmount = subOrder.OrderItems.Sum(x => x.TaxAmount); subOrder.OrderTotal = subOrder.SubTotal + subOrder.TaxAmount + subOrder.ShippingAmount - subOrder.Discount; _orderRepository.Add(subOrder); } _orderRepository.SaveChanges(); // await _orderEmailService.SendEmailToUser(user, order); return(order); }
public async Task <Result <Order> > CreateOrder(long cartId, string paymentMethod, decimal paymentFeeAmount, string shippingMethodName, Address billingAddress, Address shippingAddress, OrderStatus orderStatus = OrderStatus.New) { var cart = _cartRepository .Query() .Include(c => c.Items).ThenInclude(x => x.Product) .Where(x => x.Id == cartId).FirstOrDefault(); if (cart == null) { return(Result.Fail <Order>($"Cart id {cartId} cannot be found")); } var checkingDiscountResult = await CheckForDiscountIfAny(cart); if (!checkingDiscountResult.Succeeded) { return(Result.Fail <Order>(checkingDiscountResult.ErrorMessage)); } var validateShippingMethodResult = await ValidateShippingMethod(shippingMethodName, shippingAddress, cart); if (!validateShippingMethodResult.Success) { return(Result.Fail <Order>(validateShippingMethodResult.Error)); } var shippingMethod = validateShippingMethodResult.Value; var orderBillingAddress = new OrderAddress() { AddressLine1 = billingAddress.AddressLine1, AddressLine2 = billingAddress.AddressLine2, ContactName = billingAddress.ContactName, CountryId = billingAddress.CountryId, StateOrProvinceId = billingAddress.StateOrProvinceId, DistrictId = billingAddress.DistrictId, City = billingAddress.City, ZipCode = billingAddress.ZipCode, Phone = billingAddress.Phone }; var orderShippingAddress = new OrderAddress() { AddressLine1 = shippingAddress.AddressLine1, AddressLine2 = shippingAddress.AddressLine2, ContactName = shippingAddress.ContactName, CountryId = shippingAddress.CountryId, StateOrProvinceId = shippingAddress.StateOrProvinceId, DistrictId = shippingAddress.DistrictId, City = shippingAddress.City, ZipCode = shippingAddress.ZipCode, Phone = shippingAddress.Phone }; var order = new Order { CustomerId = cart.CustomerId, CreatedOn = DateTimeOffset.Now, CreatedById = cart.CreatedById, LatestUpdatedOn = DateTimeOffset.Now, LatestUpdatedById = cart.CreatedById, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress, PaymentMethod = paymentMethod, PaymentFeeAmount = paymentFeeAmount }; foreach (var cartItem in cart.Items) { //codigo origen, necesairio revisar validaciones para la compra tipo stock etc //if (!cartItem.Product.IsAllowToOrder || !cartItem.Product.IsPublished || cartItem.Product.IsDeleted) //{ // return Result.Fail<Order>($"The product {cartItem.Product.Name} is not available any more"); //} //if (cartItem.Product.StockTrackingIsEnabled && cartItem.Product.StockQuantity < cartItem.Quantity) //{ // return Result.Fail<Order>($"There are only {cartItem.Product.StockQuantity} items available for {cartItem.Product.Name}"); //} var taxPercent = await _taxService.GetTaxPercent(cartItem.Product.TaxClassId, shippingAddress.CountryId, shippingAddress.StateOrProvinceId, shippingAddress.ZipCode); var productPrice = cartItem.Product.Price; if (cart.IsProductPriceIncludeTax) { productPrice = productPrice / (1 + (taxPercent / 100)); } var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = productPrice, Quantity = cartItem.Quantity, TaxPercent = taxPercent, TaxAmount = cartItem.Quantity * (productPrice * taxPercent / 100) }; var discountedItem = checkingDiscountResult.DiscountedProducts.FirstOrDefault(x => x.Id == cartItem.ProductId); if (discountedItem != null) { orderItem.DiscountAmount = discountedItem.DiscountAmount; } order.AddOrderItem(orderItem); if (cartItem.Product.StockTrackingIsEnabled) { cartItem.Product.StockQuantity = cartItem.Product.StockQuantity - cartItem.Quantity; } } order.OrderStatus = orderStatus; order.OrderNote = cart.OrderNote; order.CouponCode = checkingDiscountResult.CouponCode; order.CouponRuleName = cart.CouponRuleName; order.DiscountAmount = checkingDiscountResult.DiscountAmount; order.ShippingFeeAmount = shippingMethod.Price; order.ShippingMethod = shippingMethod.Name; order.TaxAmount = order.OrderItems.Sum(x => x.TaxAmount); order.SubTotal = order.OrderItems.Sum(x => x.ProductPrice * x.Quantity); order.SubTotalWithDiscount = order.SubTotal - checkingDiscountResult.DiscountAmount; order.OrderTotal = order.SubTotal + order.TaxAmount + order.ShippingFeeAmount + order.PaymentFeeAmount - order.DiscountAmount; _orderRepository.Add(order); cart.IsActive = false; var vendorIds = cart.Items.Where(x => x.Product.VendorId.HasValue).Select(x => x.Product.VendorId.Value).Distinct(); if (vendorIds.Any()) { order.IsMasterOrder = true; } IList <Order> subOrders = new List <Order>(); foreach (var vendorId in vendorIds) { var subOrder = new Order { CustomerId = cart.CustomerId, CreatedOn = DateTimeOffset.Now, CreatedById = cart.CreatedById, LatestUpdatedOn = DateTimeOffset.Now, LatestUpdatedById = cart.CreatedById, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress, VendorId = vendorId, Parent = order }; foreach (var cartItem in cart.Items.Where(x => x.Product.VendorId == vendorId)) { var taxPercent = await _taxService.GetTaxPercent(cartItem.Product.TaxClassId, shippingAddress.CountryId, shippingAddress.StateOrProvinceId, shippingAddress.ZipCode); var productPrice = cartItem.Product.Price; if (cart.IsProductPriceIncludeTax) { productPrice = productPrice / (1 + (taxPercent / 100)); } var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = productPrice, Quantity = cartItem.Quantity, TaxPercent = taxPercent, TaxAmount = cartItem.Quantity * (productPrice * taxPercent / 100) }; if (cart.IsProductPriceIncludeTax) { orderItem.ProductPrice = orderItem.ProductPrice - orderItem.TaxAmount; } subOrder.AddOrderItem(orderItem); } subOrder.SubTotal = subOrder.OrderItems.Sum(x => x.ProductPrice * x.Quantity); subOrder.TaxAmount = subOrder.OrderItems.Sum(x => x.TaxAmount); subOrder.OrderTotal = subOrder.SubTotal + subOrder.TaxAmount + subOrder.ShippingFeeAmount - subOrder.DiscountAmount; _orderRepository.Add(subOrder); subOrders.Add(subOrder); } using (var transaction = _orderRepository.BeginTransaction()) { _orderRepository.SaveChanges(); await PublishOrderCreatedEvent(order); foreach (var subOrder in subOrders) { await PublishOrderCreatedEvent(subOrder); } _couponService.AddCouponUsage(cart.CustomerId, order.Id, checkingDiscountResult); _orderRepository.SaveChanges(); transaction.Commit(); } //aqui tenemos que borrar el carrito return(Result.Ok(order)); }
protected override void BuildBody(StringBuilder page, PaymentRequest paymentRequest) { // Configuration values bool sandboxMode = paymentRequest.PaymentMethod.DynamicProperty <bool>().SandboxMode; bool testMode = paymentRequest.PaymentMethod.DynamicProperty <bool>().TestMode; bool instantAcquire = paymentRequest.PaymentMethod.DynamicProperty <bool>().InstantAcquire; bool itemizeReceipt = paymentRequest.PaymentMethod.DynamicProperty <bool>().ItemizeReceipt; string apiLogin = paymentRequest.PaymentMethod.DynamicProperty <string>().ApiLogin; string transactionKey = paymentRequest.PaymentMethod.DynamicProperty <string>().TransactionKey; string callbackUrl = paymentRequest.PaymentMethod.DynamicProperty <string>().CallbackUrl; string payType = paymentRequest.PaymentMethod.DynamicProperty <string>().PayType; string logoUrl = paymentRequest.PaymentMethod.DynamicProperty <string>().LogoUrl; page.Append(string.Format(@"<form method=""post"" action=""{0}"">", sandboxMode ? "https://test.authorize.net/gateway/transact.dll" : "https://secure.authorize.net/gateway/transact.dll")); AddHiddenField(page, "x_login", apiLogin); AddHiddenField(page, "x_type", instantAcquire ? "AUTH_CAPTURE" : "AUTH_ONLY"); AddHiddenField(page, "x_show_form", "PAYMENT_FORM"); AddHiddenField(page, "x_relay_response", "true"); AddHiddenField(page, "x_relay_url", _callbackUrl.GetCallbackUrl(callbackUrl, paymentRequest.Payment)); AddHiddenField(page, "x_delim_data", "FALSE"); AddHiddenField(page, "x_version", "3.1"); AddHiddenField(page, "x_method", payType); AddHiddenField(page, "x_invoice_num", paymentRequest.Payment.ReferenceId); OrderAddress billingAddress = paymentRequest.Payment.PurchaseOrder.BillingAddress; AddHiddenField(page, "x_first_name", billingAddress.FirstName); AddHiddenField(page, "x_last_name", billingAddress.LastName); AddHiddenField(page, "x_address", billingAddress.Line1 + (string.IsNullOrEmpty(billingAddress.Line2) ? "" : (", " + billingAddress.Line2))); AddHiddenField(page, "x_city", billingAddress.City); AddHiddenField(page, "x_zip", billingAddress.PostalCode); AddHiddenField(page, "x_country", billingAddress.Country.Name); AddHiddenField(page, "x_email", billingAddress.EmailAddress); AddHiddenField(page, "x_phone", billingAddress.PhoneNumber); AddHiddenField(page, "x_company", billingAddress.CompanyName); if (!string.IsNullOrEmpty(billingAddress.State)) { AddHiddenField(page, "x_state", billingAddress.State); } if (itemizeReceipt) { foreach (OrderLine line in paymentRequest.PurchaseOrder.OrderLines) { string fullSku = string.Format("{0}{1}", line.Sku, !string.IsNullOrEmpty(line.VariantSku) ? "-" + line.VariantSku : ""); AddHiddenField(page, "x_line_item", string.Format("{0}<|>{1}<|>{2}<|>{3}<|>{4}<|>N", HttpUtility.HtmlEncode(MaxThirtyChars(fullSku)), HttpUtility.HtmlEncode(MaxThirtyChars(fullSku)), HttpUtility.HtmlEncode(MaxThirtyChars(line.ProductName)), line.Quantity, (line.Price - line.UnitDiscount).ToInvariantString())); } } AddHiddenField(page, "x_header_html_payment_form", "<style type='text/css'>#imgMerchantLogo{}</style>"); if (!string.IsNullOrEmpty(logoUrl)) { AddHiddenField(page, "x_logo_url", logoUrl); } var amount = paymentRequest.Payment.Amount.ToInvariantString(); AddHiddenField(page, "x_amount", amount); AddHiddenField(page, "x_duplicate_window", 28800.ToString()); AddHiddenField(page, "x_customer_ip", HttpContext.Current.Request.UserHostAddress); // To get a transactionsid for authorizations Sandbox mode requires testmode not to be enabled if (testMode && !sandboxMode) { AddHiddenField(page, "x_test_request", "TRUE"); } var hashComputer = new AuthorizedotnetMd5Computer(); string sequence = paymentRequest.Payment.ReferenceId; AddHiddenField(page, "x_fp_sequence", sequence); TimeSpan timeSinceCreate = (paymentRequest.Payment.Created.ToUniversalTime() - new DateTime(1970, 1, 1)); string timestamp = ((int)timeSinceCreate.TotalSeconds).ToString(); AddHiddenField(page, "x_fp_timestamp", timestamp); AddHiddenField(page, "x_fp_hash", hashComputer.GetPreMd5Key(transactionKey, apiLogin, sequence, timestamp, amount)); if (Debug) { AddSubmitButton(page, "ac", "Post it"); } page.Append("</form>"); }
/// <summary> /// Translates the custom party. /// </summary> /// <param name="sourceParty">The source party.</param> /// <param name="destinationAddress">The destination address.</param> protected virtual void TranslateCustomParty([NotNull] Party sourceParty, [NotNull] OrderAddress destinationAddress) { }
public CustomerContact CreateCustomer(string email, string password, string phone, OrderAddress billingAddress, OrderAddress shippingAddress, bool hasPassword, Action <MembershipCreateStatus> userCreationFailed) { MembershipCreateStatus createStatus; var user = Membership.CreateUser(email, password, email, null, null, true, out createStatus); switch (createStatus) { case MembershipCreateStatus.Success: SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.EveryoneRole); SecurityContext.Current.AssignUserToGlobalRole(user, AppRoles.RegisteredRole); var customer = CustomerContext.Current.GetContactForUser(user); customer.FirstName = billingAddress.FirstName; customer.LastName = billingAddress.LastName; customer.FullName = string.Format("{0} {1}", customer.FirstName, customer.LastName); customer.SetPhoneNumber(phone); customer.SetHasPassword(hasPassword); var customerBillingAddress = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId); OrderAddress.CopyOrderAddressToCustomerAddress(billingAddress, customerBillingAddress); customer.AddContactAddress(customerBillingAddress); customer.SaveChanges(); customer.PreferredBillingAddressId = customerBillingAddress.AddressId; customerBillingAddress.Name = string.Format("{0}, {1} {2}", customerBillingAddress.Line1, customerBillingAddress.PostalCode, customerBillingAddress.City); CheckCountryCode(customerBillingAddress); BusinessManager.Update(customerBillingAddress); customer.SaveChanges(); var customerShippingAddress = CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId); OrderAddress.CopyOrderAddressToCustomerAddress(shippingAddress, customerShippingAddress); customer.AddContactAddress(customerShippingAddress); customer.SaveChanges(); customer.PreferredShippingAddressId = customerShippingAddress.AddressId; customerShippingAddress.Name = string.Format("{0}, {1} {2}", customerShippingAddress.Line1, customerShippingAddress.PostalCode, customerShippingAddress.City); CheckCountryCode(customerShippingAddress); BusinessManager.Update(customerShippingAddress); customer.SaveChanges(); return(customer); default: userCreationFailed(createStatus); break; } return(null); }
public async Task <Result <Order> > CreateOrder(User user, string paymentMethod, decimal paymentFeeAmount, string shippingMethodName, Address billingAddress, Address shippingAddress, OrderStatus orderStatus = OrderStatus.New) { var cart = _cartRepository .Query() .Include(c => c.Items).ThenInclude(x => x.Product) .Where(x => x.UserId == user.Id && x.IsActive).FirstOrDefault(); if (cart == null) { return(Result.Fail <Order>($"Cart of user {user.Id} cannot be found")); } var checkingDiscountResult = await CheckForDiscountIfAny(user, cart); if (!checkingDiscountResult.Succeeded) { return(Result.Fail <Order>(checkingDiscountResult.ErrorMessage)); } var validateShippingMethodResult = await ValidateShippingMethod(shippingMethodName, shippingAddress, cart); if (!validateShippingMethodResult.Success) { return(Result.Fail <Order>(validateShippingMethodResult.Error)); } var shippingMethod = validateShippingMethodResult.Value; var orderBillingAddress = new OrderAddress() { AddressLine1 = billingAddress.AddressLine1, AddressLine2 = billingAddress.AddressLine2, ContactName = billingAddress.ContactName, CountryId = billingAddress.CountryId, StateOrProvinceId = billingAddress.StateOrProvinceId, DistrictId = billingAddress.DistrictId, City = billingAddress.City, ZipCode = billingAddress.ZipCode, Phone = billingAddress.Phone }; var orderShippingAddress = new OrderAddress() { AddressLine1 = shippingAddress.AddressLine1, AddressLine2 = shippingAddress.AddressLine2, ContactName = shippingAddress.ContactName, CountryId = shippingAddress.CountryId, StateOrProvinceId = shippingAddress.StateOrProvinceId, DistrictId = shippingAddress.DistrictId, City = shippingAddress.City, ZipCode = shippingAddress.ZipCode, Phone = shippingAddress.Phone }; var order = new Order { CreatedOn = DateTimeOffset.Now, CreatedById = user.Id, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress, PaymentMethod = paymentMethod, PaymentFeeAmount = paymentFeeAmount }; foreach (var cartItem in cart.Items) { if (cartItem.Product.StockQuantity < cartItem.Quantity) { return(Result.Fail <Order>($"There are only {cartItem.Product.StockQuantity} items available for {cartItem.Product.Name}")); } var taxPercent = await _taxService.GetTaxPercent(cartItem.Product.TaxClassId, shippingAddress.CountryId, shippingAddress.StateOrProvinceId, shippingAddress.ZipCode); var productPrice = cartItem.Product.Price; if (cart.IsProductPriceIncludeTax) { productPrice = productPrice / (1 + (taxPercent / 100)); } var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = productPrice, Quantity = cartItem.Quantity, TaxPercent = taxPercent, TaxAmount = cartItem.Quantity * (productPrice * taxPercent / 100) }; var discountedItem = checkingDiscountResult.DiscountedProducts.FirstOrDefault(x => x.Id == cartItem.ProductId); if (discountedItem != null) { orderItem.DiscountAmount = discountedItem.DiscountAmount; } order.AddOrderItem(orderItem); cartItem.Product.StockQuantity = cartItem.Product.StockQuantity - cartItem.Quantity; } order.OrderStatus = orderStatus; order.CouponCode = checkingDiscountResult.CouponCode; order.CouponRuleName = cart.CouponRuleName; order.DiscountAmount = checkingDiscountResult.DiscountAmount; order.ShippingFeeAmount = shippingMethod.Price; order.ShippingMethod = shippingMethod.Name; order.TaxAmount = order.OrderItems.Sum(x => x.TaxAmount); order.SubTotal = order.OrderItems.Sum(x => x.ProductPrice * x.Quantity); order.SubTotalWithDiscount = order.SubTotal - checkingDiscountResult.DiscountAmount; order.OrderTotal = order.SubTotal + order.TaxAmount + order.ShippingFeeAmount + order.PaymentFeeAmount - order.DiscountAmount; _orderRepository.Add(order); cart.IsActive = false; var vendorIds = cart.Items.Where(x => x.Product.VendorId.HasValue).Select(x => x.Product.VendorId.Value).Distinct(); if (vendorIds.Any()) { order.IsMasterOrder = true; } foreach (var vendorId in vendorIds) { var subOrder = new Order { CreatedOn = DateTimeOffset.Now, CreatedById = user.Id, BillingAddress = orderBillingAddress, ShippingAddress = orderShippingAddress, VendorId = vendorId, Parent = order }; foreach (var cartItem in cart.Items.Where(x => x.Product.VendorId == vendorId)) { var taxPercent = await _taxService.GetTaxPercent(cartItem.Product.TaxClassId, shippingAddress.CountryId, shippingAddress.StateOrProvinceId, shippingAddress.ZipCode); var productPrice = cartItem.Product.Price; if (cart.IsProductPriceIncludeTax) { productPrice = productPrice / (1 + (taxPercent / 100)); } var orderItem = new OrderItem { Product = cartItem.Product, ProductPrice = productPrice, Quantity = cartItem.Quantity, TaxPercent = taxPercent, TaxAmount = cartItem.Quantity * (productPrice * taxPercent / 100) }; if (cart.IsProductPriceIncludeTax) { orderItem.ProductPrice = orderItem.ProductPrice - orderItem.TaxAmount; } subOrder.AddOrderItem(orderItem); } subOrder.SubTotal = subOrder.OrderItems.Sum(x => x.ProductPrice * x.Quantity); subOrder.TaxAmount = subOrder.OrderItems.Sum(x => x.TaxAmount); subOrder.OrderTotal = subOrder.SubTotal + subOrder.TaxAmount + subOrder.ShippingFeeAmount - subOrder.DiscountAmount; _orderRepository.Add(subOrder); } using (var transaction = _orderRepository.BeginTransaction()) { _orderRepository.SaveChanges(); _couponService.AddCouponUsage(user.Id, order.Id, checkingDiscountResult); _orderRepository.SaveChanges(); transaction.Commit(); } // await _orderEmailService.SendEmailToUser(user, order); return(Result.Ok(order)); }
protected CustomerContact CreateCustomer(string email, string password, string phone, OrderAddress billingAddress, OrderAddress shippingAddress, bool hasPassword, Action<MembershipCreateStatus> userCreationFailed) { return _customerFactory.CreateCustomer(email, password, phone, billingAddress, shippingAddress, hasPassword, userCreationFailed); }
private void HandleUserCreation(CheckoutViewModel model, OrderAddress billingAddress, OrderAddress shippingAddress, string username) { // has specified password if (!User.Identity.IsAuthenticated && !string.IsNullOrEmpty(model.Password)) { // check if email exists var user = Membership.GetUser(username); if (user != null) { // user exists if (Membership.ValidateUser(username, model.Password)) { // cannot login here because something strange happens with the order //LoginController.CreateAuthenticationCookie(ControllerContext.HttpContext, username, AppContext.Current.ApplicationName, false); } else { ModelState.AddModelError("Password", _localizationService.GetString("/common/account/login_error")); } } else { // create new customer var customer = _customerFactory.CreateCustomer(username, model.Password, model.Phone, billingAddress, shippingAddress, true, createStatus => { switch (createStatus) { case MembershipCreateStatus.DuplicateUserName: ModelState.AddModelError("Password", _localizationService.GetString("/common/account/register_error_unique_username")); break; case MembershipCreateStatus.InvalidPassword: ModelState.AddModelError("Password", _localizationService.GetString("/common/account/register_error")); break; default: ModelState.AddModelError("Password", createStatus.ToString()); break; } }); if (customer != null) { // customer was created // cannot login here because something strange happens with the order // TODO: Investigate this //LoginController.CreateAuthenticationCookie(ControllerContext.HttpContext, username, AppContext.Current.ApplicationName, false); } } } }
private OrderAddressModel MapOrderAddress(OrderAddress address) { return new OrderAddressModel() { City = address.City, CountryCode = address.CountryCode, DeliveryServicePoint = GetDeliveryServicePointFrom(address), FirstName = address.FirstName, LastName = address.LastName, Id = address.Id, Line1 = address.Line1, Name = address.Name, PostalCode = address.PostalCode }; }
private string GetDeliveryServicePointFrom(OrderAddress shippingAddress) { if (string.IsNullOrWhiteSpace((string)shippingAddress[Constants.Metadata.Address.DeliveryServicePoint])) return string.Empty; try { var deliveryServicePoint = JsonConvert.DeserializeObject<ServicePoint>( (string)shippingAddress[Constants.Metadata.Address.DeliveryServicePoint]); return deliveryServicePoint.Name; } catch (Exception ex) { // Todo: Move to method with more documentation about why this can fail Log.Error("Error during deserializing delivery location", ex); } return string.Empty; }
private IEnumerable <ShippingMethodAndRate> GetShippingMethodsWithRates(Cart cart, OrderAddress address) { ShippingMethodDto shippingMethods = ShippingManager.GetShippingMethods(CurrentPage.LanguageID, false); List <ShippingMethodAndRate> shippingMethodsList = new List <ShippingMethodAndRate>(); string outputMessage = string.Empty; string shippingMethodAndPrice = string.Empty; //get the one shipment in the order Shipment ship = null; if (cart.OrderForms[0].Shipments != null && cart.OrderForms[0].Shipments.Count > 0) { ship = cart.OrderForms[0].Shipments[0]; } if (ship != null) { // request rates, make sure we request rates not bound to selected delivery method foreach (ShippingMethodDto.ShippingMethodRow row in shippingMethods.ShippingMethod) { shippingMethodsList.Add(GetShippingRateInfo(row, ship)); } } return(shippingMethodsList); }
public void Test_Select() { List <OrderAddress> lstOrderAddress = new OrderAddress().GetRecords("SELECT '' as DataHash, * FROM tblOrderAddress"); }
public void Test_Insert_Site_Duplicate_BLOCKED_BASICS() { OrderAddress objOrderAddress = new OrderAddress(); //objOrderAddress.OrderAddressID = 0; objOrderAddress.OrderAddressTypeID = (int)OrderAddressTypes.Site; objOrderAddress.MigrationStatusID = (int)MigrationStatuses.STAGED_for_Processing; objOrderAddress.OrderSystemOfRecordID = (int)OrderSystemOfRecords.EON; objOrderAddress.CDWCustomerOrderNumber = DateTime.UtcNow.Ticks.ToString(); objOrderAddress.CDWAddressOne = "72 E 3RD AVE"; objOrderAddress.CDWCity = "SAN MATEO"; objOrderAddress.CDWState = "CA"; objOrderAddress.CDWPostalCode = "94401"; objOrderAddress.CDWCountry = "USA"; objOrderAddress.CDWFloor = String.Empty; objOrderAddress.CDWRoom = String.Empty; objOrderAddress.CDWSuite = String.Empty; objOrderAddress.CDWCLII = null; objOrderAddress.ValidCLII = false; objOrderAddress.NumberOfFailedGLMSiteCalls = 0; objOrderAddress.ExistsInGLMAsSite = true; objOrderAddress.GLMPLNumber = ""; objOrderAddress.NumberOfFailedGLMSiteCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSiteCodeCreationCalls = 0; objOrderAddress.GLMSiteCode = ""; objOrderAddress.HasGLMSiteCode = true; objOrderAddress.NumberOfFailedSAPSiteAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPSiteAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsSiteAddress = true; objOrderAddress.NumberOfRecordsInSAPWithPL = 0; objOrderAddress.NumberOfFailedGLMServiceLocationSearchCalls = 0; objOrderAddress.NumberOfFailedGLMServiceLocationCreationCalls = 0; objOrderAddress.GLMSLNumber = ""; objOrderAddress.ExistsInGLMAsServiceLocation = true; objOrderAddress.NumberOfFailedGLMSCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSCodeCreationCalls = 0; objOrderAddress.GLMSCode = ""; objOrderAddress.HasGLMSCode = true; objOrderAddress.NumberOfFailedSAPServiceLocationAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPServiceLocationAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsServiceLocationAddress = true; objOrderAddress.NumberOfRecordsInSAPWithSL = 0; objOrderAddress.SourceCreationDate = new DateTime(2018, 08, 01); objOrderAddress.SourceLastModifyDate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastMigrationStatusUpdate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastDupDetection = new DateTime(2018, 08, 01); objOrderAddress.DateCreated = new DateTime(2018, 08, 01); objOrderAddress.DateUpdated = new DateTime(2018, 08, 01); string strLastError = String.Empty; Assert.IsTrue(objOrderAddress.Insert(out strLastError)); Assert.IsTrue(objOrderAddress.OrderAddressID > 0); Assert.IsTrue(strLastError == String.Empty); // Try to insert a DUP record OrderAddress objOrderAddressSecondBasic = new OrderAddress(); objOrderAddressSecondBasic.OrderAddressTypeID = (int)OrderAddressTypes.Site; objOrderAddressSecondBasic.MigrationStatusID = (int)MigrationStatuses.STAGED_for_Processing; objOrderAddressSecondBasic.OrderSystemOfRecordID = (int)OrderSystemOfRecords.EON; objOrderAddressSecondBasic.CDWCustomerOrderNumber = objOrderAddress.CDWCustomerOrderNumber; objOrderAddressSecondBasic.CDWAddressOne = "72 E 3RD AVE"; objOrderAddressSecondBasic.CDWCity = "SAN MATEO"; objOrderAddressSecondBasic.CDWState = "CA"; objOrderAddressSecondBasic.CDWPostalCode = "94401"; objOrderAddressSecondBasic.CDWCountry = "USA"; objOrderAddressSecondBasic.CDWFloor = String.Empty; objOrderAddressSecondBasic.CDWRoom = String.Empty; objOrderAddressSecondBasic.CDWSuite = String.Empty; objOrderAddressSecondBasic.ValidCLII = false; objOrderAddressSecondBasic.NumberOfFailedGLMSiteCalls = 0; objOrderAddressSecondBasic.ExistsInGLMAsSite = true; objOrderAddressSecondBasic.GLMPLNumber = ""; objOrderAddressSecondBasic.NumberOfFailedGLMSiteCodeExistenceCalls = 0; objOrderAddressSecondBasic.NumberOfFailedGLMSiteCodeCreationCalls = 0; objOrderAddressSecondBasic.GLMSiteCode = ""; objOrderAddressSecondBasic.HasGLMSiteCode = true; objOrderAddressSecondBasic.NumberOfFailedSAPSiteAddressSearchCalls = 0; objOrderAddressSecondBasic.NumberOfFailedSAPSiteAddressImportCalls = 0; objOrderAddressSecondBasic.ExistsInSAPAsSiteAddress = true; objOrderAddressSecondBasic.NumberOfRecordsInSAPWithPL = 0; objOrderAddressSecondBasic.NumberOfFailedGLMServiceLocationSearchCalls = 0; objOrderAddressSecondBasic.NumberOfFailedGLMServiceLocationCreationCalls = 0; objOrderAddressSecondBasic.GLMSLNumber = ""; objOrderAddressSecondBasic.ExistsInGLMAsServiceLocation = true; objOrderAddressSecondBasic.NumberOfFailedGLMSCodeExistenceCalls = 0; objOrderAddressSecondBasic.NumberOfFailedGLMSCodeCreationCalls = 0; objOrderAddressSecondBasic.GLMSCode = ""; objOrderAddressSecondBasic.HasGLMSCode = true; objOrderAddressSecondBasic.NumberOfFailedSAPServiceLocationAddressSearchCalls = 0; objOrderAddressSecondBasic.NumberOfFailedSAPServiceLocationAddressImportCalls = 0; objOrderAddressSecondBasic.ExistsInSAPAsServiceLocationAddress = true; objOrderAddressSecondBasic.NumberOfRecordsInSAPWithSL = 0; objOrderAddressSecondBasic.SourceCreationDate = new DateTime(2018, 08, 01); objOrderAddressSecondBasic.SourceLastModifyDate = new DateTime(2018, 08, 01); objOrderAddressSecondBasic.DateTimeOfLastMigrationStatusUpdate = new DateTime(2018, 08, 01); objOrderAddressSecondBasic.DateTimeOfLastDupDetection = new DateTime(2018, 08, 01); objOrderAddressSecondBasic.DateCreated = new DateTime(2018, 08, 01); objOrderAddressSecondBasic.DateUpdated = new DateTime(2018, 08, 01); objOrderAddress.OrderAddressID = 0; Assert.IsTrue((objOrderAddress.OrderAddressID == null) || (objOrderAddress.OrderAddressID == 0)); Assert.IsFalse(objOrderAddress.Insert(out strLastError)); Assert.IsTrue(strLastError != String.Empty); }
/// <summary> /// Get shipping address /// </summary> /// <param name="shipmentIndex">Shipment Index</param> /// <returns></returns> private OrderAddress GetShippingAddress(int shipmentIndex) { OrderAddress address = null; var currentContact = CustomerContext.Current.CurrentContact; if (Cart.OrderForms[0].Shipments.Count > 0 && !string.IsNullOrEmpty(CartHelper.Cart.OrderForms[0].Shipments[shipmentIndex].ShippingAddressId)) { string shippingAddressId = CartHelper.Cart.OrderForms[0].Shipments[shipmentIndex].ShippingAddressId; var cusomterAddress = currentContact == null ? null : currentContact.ContactAddresses.FirstOrDefault(ca => ca.Name.ToString().Equals(shippingAddressId)); if (cusomterAddress != null) { address = new OrderAddress(); CustomerAddress.CopyCustomerAddressToOrderAddress(cusomterAddress, address); } else { address = CartHelper.FindAddressByName(shippingAddressId); } } return address; }
public void Test_Insert_Site_No_CLII() { // https://sapecq.corp.intranet/sap/bc/rest/lvlt/address/verify?saml2=disabled&im_sort2=SL0000606479 // https://sapprd.corp.intranet/sap/bc/rest/lvlt/address/verify?saml2=disabled&im_sort2=PL0000025421 OrderAddress objOrderAddress = new OrderAddress(); //objOrderAddress.OrderAddressID = 0; objOrderAddress.OrderAddressTypeID = (int)OrderAddressTypes.Site; objOrderAddress.MigrationStatusID = (int)MigrationStatuses.STAGED_for_Processing; objOrderAddress.OrderSystemOfRecordID = (int)OrderSystemOfRecords.EON; objOrderAddress.CDWCustomerOrderNumber = DateTime.UtcNow.Ticks.ToString(); objOrderAddress.CDWAddressOne = "72 E 3RD AVE"; objOrderAddress.CDWCity = "SAN MATEO"; objOrderAddress.CDWState = "CA"; objOrderAddress.CDWPostalCode = "94401"; objOrderAddress.CDWCountry = "USA"; objOrderAddress.CDWFloor = String.Empty; objOrderAddress.CDWRoom = String.Empty; objOrderAddress.CDWSuite = String.Empty; objOrderAddress.CDWCLII = null; objOrderAddress.ValidCLII = false; objOrderAddress.NumberOfFailedGLMSiteCalls = 0; objOrderAddress.ExistsInGLMAsSite = true; objOrderAddress.GLMPLNumber = ""; objOrderAddress.NumberOfFailedGLMSiteCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSiteCodeCreationCalls = 0; objOrderAddress.GLMSiteCode = ""; objOrderAddress.HasGLMSiteCode = true; objOrderAddress.NumberOfFailedSAPSiteAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPSiteAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsSiteAddress = true; objOrderAddress.NumberOfRecordsInSAPWithPL = 0; objOrderAddress.NumberOfFailedGLMServiceLocationSearchCalls = 0; objOrderAddress.NumberOfFailedGLMServiceLocationCreationCalls = 0; objOrderAddress.GLMSLNumber = ""; objOrderAddress.ExistsInGLMAsServiceLocation = true; objOrderAddress.NumberOfFailedGLMSCodeExistenceCalls = 0; objOrderAddress.NumberOfFailedGLMSCodeCreationCalls = 0; objOrderAddress.GLMSCode = ""; objOrderAddress.HasGLMSCode = true; objOrderAddress.NumberOfFailedSAPServiceLocationAddressSearchCalls = 0; objOrderAddress.NumberOfFailedSAPServiceLocationAddressImportCalls = 0; objOrderAddress.ExistsInSAPAsServiceLocationAddress = true; objOrderAddress.NumberOfRecordsInSAPWithSL = 0; objOrderAddress.SourceCreationDate = new DateTime(2018, 08, 01); objOrderAddress.SourceLastModifyDate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastMigrationStatusUpdate = new DateTime(2018, 08, 01); objOrderAddress.DateTimeOfLastDupDetection = new DateTime(2018, 08, 01); objOrderAddress.DateCreated = new DateTime(2018, 08, 01); objOrderAddress.DateUpdated = new DateTime(2018, 08, 01); objOrderAddress.ServiceOrderNumber = "S" + DateTime.UtcNow.Ticks.ToString(); objOrderAddress.FIRST_ORDER_CREATE_DT = new DateTime(2018, 08, 01); objOrderAddress.OPE_LAST_MODIFY_DATE = new DateTime(2018, 08, 02); objOrderAddress.PL_LAST_MODIFY_DATE = new DateTime(2018, 08, 03); objOrderAddress.PS_LAST_MODIFY_DATE = new DateTime(2018, 08, 04); objOrderAddress.TotalProcessingTimeInTickString = DateTime.Now.Ticks.ToString(); objOrderAddress.TotalProcessingTimeAsHumanReadable = Model.StopwatchUtil.GetHumanReadableTimeElapsedStringFromTicks(DateTime.Now.Ticks + DateTime.Now.Ticks); string strLastError = String.Empty; Assert.IsTrue(objOrderAddress.Insert(out strLastError)); Assert.IsTrue(objOrderAddress.OrderAddressID > 0); Assert.IsTrue(strLastError == String.Empty); }
private OrderAddressViewModel GetAddress(OrderAddress address, IEnumerable<Country> countries, WebStoreClient client) { if (address != null) { IEnumerable<Region> regions = address.RegionId.HasValue ? client.StoreClient.GetRegions(address.CountryId) : Enumerable.Empty<Region>(); return new OrderAddressViewModel { City = address.CityName, Company = address.CompanyName, CountryName = countries.Where(c => c.CountryId == address.CountryId).Select(c => c.Name).FirstOrDefault(), DigiCode = address.DigiCode, Email = address.EmailAddress, FaxNumber = address.FaxNumber, FirstName = address.FirstName, Floor = address.FloorNumber, LastName = address.LastName, Line1 = address.Address1, Line2 = address.Address2, Line3 = address.Address3, MiddleName = address.MiddleName, MobileNumber = address.MobileNumber, Name = address.Name, PhoneNumber = address.PhoneNumber, RegionName = regions.Where(r => r.RegionId == address.RegionId).Select(r => r.Name).FirstOrDefault(), ZipCode = address.ZipCode }; } return null; }
/// <summary> /// Sets the shipping addresses. /// </summary> private void SetShippingAddresses() { OrderAddress address = null; var currentContact = CustomerContext.Current.CurrentContact; if (Cart.OrderForms[0].Shipments.Count > 0 && !string.IsNullOrEmpty(CartHelper.Cart.OrderForms[0].Shipments[0].ShippingAddressId)) { string shippingAddressId = CartHelper.Cart.OrderForms[0].Shipments[0].ShippingAddressId; var customerAddress = currentContact == null ? null : currentContact.ContactAddresses.FirstOrDefault(ca => ca.Name.ToString().Equals(shippingAddressId)); if (customerAddress != null) { address = new OrderAddress(); CustomerAddress.CopyCustomerAddressToOrderAddress(customerAddress, address); } else { address = CartHelper.FindAddressByName(shippingAddressId); } } else { var defaultShippingAdd = currentContact == null ? null : currentContact.ContactAddresses.FirstOrDefault( a => currentContact.PreferredShippingAddressId.HasValue && currentContact.PreferredShippingAddressId.Value == a.PrimaryKeyId.Value); // Set default shipping address to new order. if (defaultShippingAdd != null) { address = new OrderAddress(); CustomerAddress.CopyCustomerAddressToOrderAddress(defaultShippingAdd, address); var shipment = Cart.OrderForms[0].Shipments[0]; shipment.ShippingAddressId = address.Name; Cart.OrderAddresses.Add(address); } } ShippingAddressInfo.OrderAddress = address; ShippingAddressInfo.DataBind(); }