public static CustomerOrder ToCoreModel(this CustomerOrderEntity entity, IEnumerable<ShippingMethod> shippingMethods, IEnumerable<PaymentMethod> paymentMethods)
		{
			if (entity == null)
				throw new ArgumentNullException("entity");

			var retVal = new CustomerOrder();

			retVal.InjectFrom(entity);

			retVal.Currency = (CurrencyCodes)Enum.Parse(typeof(CurrencyCodes), entity.Currency);

			if(entity.Discounts != null && entity.Discounts.Any())
			{
				retVal.Discount = entity.Discounts.First().ToCoreModel();
			}
			if (entity.Items != null)
			{
				retVal.Items = entity.Items.Select(x => x.ToCoreModel()).ToList();
			}
			if (entity.Addresses != null)
			{
				retVal.Addresses = entity.Addresses.Select(x => x.ToCoreModel()).ToList();
			}
			if (entity.Shipments != null)
			{
				retVal.Shipments = entity.Shipments.Select(x => x.ToCoreModel(shippingMethods, paymentMethods)).ToList();
			}
			if (entity.InPayments != null)
			{
				retVal.InPayments = entity.InPayments.Select(x => x.ToCoreModel(paymentMethods)).ToList();
			}
			retVal.TaxDetails = entity.TaxDetails.Select(x => x.ToCoreModel()).ToList();
			return retVal;
		}
        public static coreModel.CustomerOrder ToCoreModel(this webModel.CustomerOrder customerOrder)
        {
            var retVal = new coreModel.CustomerOrder();

            retVal.InjectFrom(customerOrder);
            retVal.Currency = customerOrder.Currency;

            if (customerOrder.Properties != null)
            {
                retVal.Properties = customerOrder.Properties.Select(x => x.ToCoreModel()).ToList();
            }
            if (customerOrder.Items != null)
            {
                retVal.Items = customerOrder.Items.Select(x => x.ToCoreModel()).ToList();
            }
            if (customerOrder.Addresses != null)
            {
                retVal.Addresses = customerOrder.Addresses.Select(x => x.ToCoreModel()).ToList();
            }
            if (customerOrder.Shipments != null)
            {
                retVal.Shipments = customerOrder.Shipments.Select(x => x.ToCoreModel()).ToList();
            }
            if (customerOrder.InPayments != null)
            {
                retVal.InPayments = customerOrder.InPayments.Select(x => x.ToCoreModel()).ToList();
            }

            if (customerOrder.Discount != null)
            {
                retVal.Discount = customerOrder.Discount.ToCoreModel();
            }
            retVal.TaxDetails = customerOrder.TaxDetails;
            return(retVal);
        }
		public static coreModel.CustomerOrder ToCoreModel(this webModel.CustomerOrder customerOrder)
		{
			var retVal = new coreModel.CustomerOrder();
			retVal.InjectFrom(customerOrder);
			retVal.Currency = customerOrder.Currency;

		
			if (customerOrder.Items != null)
				retVal.Items = customerOrder.Items.Select(x => x.ToCoreModel()).ToList();
			if (customerOrder.Addresses != null)
				retVal.Addresses = customerOrder.Addresses.Select(x => x.ToCoreModel()).ToList();
			if (customerOrder.Shipments != null)
				retVal.Shipments = customerOrder.Shipments.Select(x => x.ToCoreModel()).ToList();
			if (customerOrder.InPayments != null)
				retVal.InPayments = customerOrder.InPayments.Select(x => x.ToCoreModel()).ToList();

			if (customerOrder.Discount != null)
				retVal.Discount = customerOrder.Discount.ToCoreModel();
			retVal.TaxDetails = customerOrder.TaxDetails;

            if (customerOrder.DynamicProperties != null)
                retVal.DynamicProperties = customerOrder.DynamicProperties;

			return retVal;
		}
Exemplo n.º 4
0
 public IHttpActionResult Total(CustomerOrder order)
 {
     if (!string.IsNullOrEmpty(_taxSettings.Username) && !string.IsNullOrEmpty(_taxSettings.Password)
         && !string.IsNullOrEmpty(_taxSettings.ServiceUrl)
         && !string.IsNullOrEmpty(_taxSettings.CompanyCode) && _taxSettings.IsEnabled)
     {
         var taxSvc = new JsonTaxSvc(_taxSettings.Username, _taxSettings.Password, _taxSettings.ServiceUrl);
         var request = order.ToAvaTaxRequest(_taxSettings.CompanyCode);
         var getTaxResult = taxSvc.GetTax(request);
         if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success))
         {
             var error = string.Join(Environment.NewLine, getTaxResult.Messages.Select(m => m.Details));
             return BadRequest(error);
         }
         else
         {
             foreach (TaxLine taxLine in getTaxResult.TaxLines ?? Enumerable.Empty<TaxLine>())
             {
                 order.Items.ToArray()[Int32.Parse(taxLine.LineNo)].Tax = taxLine.Tax;
                 //foreach (TaxDetail taxDetail in taxLine.TaxDetails ?? Enumerable.Empty<TaxDetail>())
                 //{
                 //}
             }
             order.Tax = getTaxResult.TotalTax;
         }
     }
     else
     {
         return BadRequest();
     }
     return Ok(order);
 }
		public static CustomerOrder ToCustomerOrder(this cart.ShoppingCart cart)
		{
			if (cart == null)
				throw new ArgumentNullException("cart");

			var retVal = new CustomerOrder()
			{
				Id = Guid.NewGuid().ToString(),
				Currency = cart.Currency,
				CustomerId = cart.CustomerId,
				CustomerName = cart.CustomerName,
				StoreId = cart.StoreId,
				OrganizationId = cart.OrganizationId,
                Status = "New"
			};
			
			if(cart.Items != null)
			{
				retVal.Items = cart.Items.Select(x => x.ToOrderCoreModel()).ToList();
			}
			if (cart.Discounts != null)
			{
				retVal.Discount = cart.Discounts.Select(x=>x.ToOrderCoreModel()).FirstOrDefault();
			}
			if (cart.Addresses != null)
			{
				retVal.Addresses = cart.Addresses.Select(x => x.ToCoreModel()).ToList();
			}
			if (cart.Shipments != null)
			{
				retVal.Shipments = cart.Shipments.Select(x => x.ToOrderCoreModel()).ToList();
				//Redistribute order line items to shipment if cart shipment items empty 
				var shipment = retVal.Shipments.FirstOrDefault();
				if(shipment != null && (shipment.Items == null || !shipment.Items.Any()))
				{
					shipment.Items = retVal.Items.Select(x => new ShipmentItem { LineItem = x, Quantity = x.Quantity }).ToList();
				}
			}
			if (cart.Payments != null)
			{
				retVal.InPayments = new List<PaymentIn>();
				foreach(var payment in cart.Payments)
				{
					var paymentIn = payment.ToOrderCoreModel();
					paymentIn.CustomerId = cart.CustomerId;
					retVal.InPayments.Add(paymentIn);
				}
			}
			retVal.TaxDetails = cart.TaxDetails;
			return retVal;
		}
        public static webModel.CustomerOrder ToWebModel(this coreModel.CustomerOrder customerOrder)
        {
            var retVal = new webModel.CustomerOrder();

            retVal.InjectFrom(customerOrder);

            //TODO: resolve id to names
            retVal.Customer       = retVal.CustomerId;
            retVal.StoreId        = retVal.StoreId;
            retVal.OrganizationId = retVal.OrganizationId;
            retVal.EmployeeId     = retVal.EmployeeId;

            if (customerOrder.Discount != null)
            {
                retVal.Discount       = customerOrder.Discount.ToWebModel();
                retVal.DiscountAmount = customerOrder.Discount.DiscountAmount;
            }

            if (customerOrder.Properties != null)
            {
                retVal.Properties = customerOrder.Properties.Select(x => x.ToWebModel()).ToList();
            }

            if (customerOrder.Shipments != null)
            {
                retVal.Shipments = customerOrder.Shipments.Select(x => x.ToWebModel()).ToList();
            }

            if (customerOrder.InPayments != null)
            {
                retVal.InPayments = customerOrder.InPayments.Select(x => x.ToWebModel()).ToList();
            }

            if (customerOrder.Items != null)
            {
                retVal.Items = customerOrder.Items.Select(x => x.ToWebModel()).ToList();
            }

            if (customerOrder.Addresses != null)
            {
                retVal.Addresses = customerOrder.Addresses.Select(x => x.ToWebModel()).ToList();
            }

            retVal.ChildrenOperations = customerOrder.ChildrenOperations.Select(x => x.ToWebModel()).ToList();
            retVal.TaxDetails         = customerOrder.TaxDetails;
            return(retVal);
        }
		public static CustomerOrder ToCustomerOrder(this cart.ShoppingCart cart)
		{
			if (cart == null)
				throw new ArgumentNullException("cart");

			var retVal = new CustomerOrder()
			{
				Id = Guid.NewGuid().ToString(),
				Currency = cart.Currency,
				CustomerId = cart.CustomerId,
				StoreId = cart.StoreId,
				OrganizationId = cart.OrganizationId
			};
			
			if(cart.Items != null)
			{
				retVal.Items = cart.Items.Select(x => x.ToCoreModel()).ToList();
			}
			if (cart.Discounts != null)
			{
				retVal.Discount = cart.Discounts.First().ToCoreModel();
			}
			if (cart.Addresses != null)
			{
				retVal.Addresses = cart.Addresses.Select(x => x.ToCoreModel()).ToList();
			}
			if (cart.Shipments != null)
			{
				retVal.Shipments = cart.Shipments.Select(x => x.ToCoreModel()).ToList();
			}
			if (cart.Payments != null)
			{
				retVal.InPayments = new List<PaymentIn>();
				foreach(var payment in cart.Payments)
				{
					var paymentIn = payment.ToCoreModel();
					paymentIn.CustomerId = cart.CustomerId;
					retVal.InPayments.Add(paymentIn);
				}
			}
			retVal.TaxDetails = cart.TaxDetails;
			return retVal;
		}
		public virtual CustomerOrder Create(CustomerOrder order)
		{
			_eventPublisher.Publish(new OrderChangeEvent(EntryState.Added, null, order));
	
			EnsureThatAllOperationsHasNumber(order);

			//TODO: for approved sipments need decrease inventory

			var orderEntity = order.ToDataModel();
			CustomerOrder retVal = null;
			using (var repository = _repositoryFactory())
			{
				repository.Add(orderEntity);
				CommitChanges(repository);
			}
			retVal = GetById(orderEntity.Id);
			return retVal;

		}
Exemplo n.º 9
0
        public static webModel.CustomerOrder ToWebModel(this coreModel.CustomerOrder customerOrder)
        {
            var retVal = new webModel.CustomerOrder();

            retVal.InjectFrom(customerOrder);

            if (customerOrder.Discount != null)
            {
                retVal.Discount       = customerOrder.Discount.ToWebModel();
                retVal.DiscountAmount = customerOrder.Discount.DiscountAmount;
            }

            if (customerOrder.Shipments != null)
            {
                retVal.Shipments = customerOrder.Shipments.Select(x => x.ToWebModel()).ToList();
            }

            if (customerOrder.InPayments != null)
            {
                retVal.InPayments = customerOrder.InPayments.Select(x => x.ToWebModel()).ToList();
            }

            if (customerOrder.Items != null)
            {
                retVal.Items = customerOrder.Items.Select(x => x.ToWebModel()).ToList();
            }

            if (customerOrder.Addresses != null)
            {
                retVal.Addresses = customerOrder.Addresses.Select(x => x.ToWebModel()).ToList();
            }

            retVal.ChildrenOperations = customerOrder.GetFlatObjectsListWithInterface <coreModel.IOperation>().Except(new[] { customerOrder }).Select(x => x.ToWebModel()).ToList();
            retVal.TaxDetails         = customerOrder.TaxDetails;

            if (customerOrder.DynamicProperties != null)
            {
                retVal.DynamicProperties = customerOrder.DynamicProperties;
            }

            return(retVal);
        }
Exemplo n.º 10
0
        public virtual CustomerOrder Create(CustomerOrder order)
        {
            EnsureThatAllOperationsHaveNumber(order);

            _eventPublisher.Publish(new OrderChangeEvent(EntryState.Added, order, order));
            var pkMap = new PrimaryKeyResolvingMap();
            var entity = order.ToDataModel(pkMap);

            using (var repository = _repositoryFactory())
            {
                repository.Add(entity);
                CommitChanges(repository);
                pkMap.ResolvePrimaryKeys();
            }

            _dynamicPropertyService.SaveDynamicPropertyValues(order);

            var retVal = GetById(entity.Id, CustomerOrderResponseGroup.Full);
            return retVal;
        }
        private void EnsureThatAllOperationsHaveNumber(CustomerOrder order)
        {
            foreach (var operation in order.GetFlatObjectsListWithInterface<IOperation>())
            {
                if (operation.Number == null)
                {
                    var objectTypeName = operation.GetType().Name;
                    // take uppercase chars to form operation type, or just take 2 first chars. (CustomerOrder => CO, PaymentIn => PI, Shipment => SH)
                    var objectType = string.Concat(objectTypeName.Select(c => char.IsUpper(c) ? c.ToString() : ""));
                    if (objectType.Length < 2)
                    {
                        objectType = objectTypeName.Substring(0, 2).ToUpper();
                    }

                    var numberTemplate = _settingManager.GetValue("Order." + objectTypeName + "NewNumberTemplate", objectType + "{0:yyMMdd}-{1:D5}");
                    operation.Number = _uniqueNumberGenerator.GenerateNumber(numberTemplate);
                }
            }

        }
        public void Update(CustomerOrder[] orders)
        {
            var pkMap = new PrimaryKeyResolvingMap();
            using (var repository = _repositoryFactory())
            {
                foreach (var order in orders)
                {
                    EnsureThatAllOperationsHaveNumber(order);
                    var origOrder = GetById(order.Id, CustomerOrderResponseGroup.Full);

                    // Do business logic on temporary order object
                    _eventPublisher.Publish(new OrderChangeEvent(EntryState.Modified, origOrder, order));

                    var sourceOrderEntity = order.ToDataModel(pkMap);
                    var targetOrderEntity = repository.GetCustomerOrderById(order.Id, CustomerOrderResponseGroup.Full);

                    if (targetOrderEntity == null)
                    {
                        throw new NullReferenceException("targetOrderEntity");
                    }

                    using (var changeTracker = GetChangeTracker(repository))
                    {
                        changeTracker.Attach(targetOrderEntity);
                        sourceOrderEntity.Patch(targetOrderEntity);
                    }
                }
                CommitChanges(repository);
                pkMap.ResolvePrimaryKeys();
            }

            //Save dynamic properties
            foreach (var order in orders)
            {
                _dynamicPropertyService.SaveDynamicPropertyValues(order);
            }
        }
Exemplo n.º 13
0
        private void UpdateOrderTaxes(IEnumerable<AvaTaxCalcREST.TaxLine> taxLines, CustomerOrder order)
        {
            //reset items taxes
            if (order.Items.Any())
                order.Items.ForEach(x =>
                {
                    x.Tax = 0;
                    x.TaxDetails = null;
                });

            //reset order shipments taxes
            if (order.Shipments.Any())
                order.Shipments.ForEach(x =>
                {
                    x.Tax = 0;
                    x.TaxDetails = null;
                });

            foreach (var taxLine in taxLines ?? Enumerable.Empty<AvaTaxCalcREST.TaxLine>())
            {
                var lineItem = order.Items.FirstOrDefault(x => x.Id == taxLine.LineNo);
                if (lineItem != null)
                {
                    lineItem.Tax = taxLine.Tax;
                    if (taxLine.TaxDetails != null && taxLine.TaxDetails.Any(td => !string.IsNullOrEmpty(td.TaxName)))
                    {
                        lineItem.TaxDetails =
                            taxLine.TaxDetails.Where(td => !string.IsNullOrEmpty(td.TaxName)).Select(taxDetail => taxDetail.ToDomainTaxDetail()).ToList();
                    }
                }
                else
                {
                    var shipment = order.Shipments.FirstOrDefault(s => s.Id != null ? s.Id.Equals(taxLine.LineNo) : s.ShipmentMethodCode.Equals(taxLine.LineNo));
                    if (shipment != null)
                    {
                        shipment.Tax = taxLine.Tax;
                        if (taxLine.TaxDetails != null && taxLine.TaxDetails.Any(td => !string.IsNullOrEmpty(td.TaxName)))
                        {
                            shipment.TaxDetails =
                                taxLine.TaxDetails.Where(td => !string.IsNullOrEmpty(td.TaxName)).Select(taxDetail => taxDetail.ToDomainTaxDetail()).ToList();
                        }
                    }
                }
            }
        }
Exemplo n.º 14
0
        public virtual void CancelTaxDocument(CustomerOrder order)
        {
            LogInvoker<AvalaraLogger.TaxRequestContext>.Execute(log =>
            {
                if (IsEnabled && !string.IsNullOrEmpty(AccountNumber) && !string.IsNullOrEmpty(LicenseKey)
                    && !string.IsNullOrEmpty(ServiceUrl)
                    && !string.IsNullOrEmpty(CompanyCode))
                {                    
                    var request = order.ToAvaTaxCancelRequest(CompanyCode, CancelCode.DocDeleted);
                    if (request != null)
                    {
                        log.docCode = request.DocCode;
                        log.docType = request.DocType.ToString();

                        var taxSvc = new JsonTaxSvc(AccountNumber, LicenseKey, ServiceUrl);
                        var getTaxResult = taxSvc.CancelTax(request);

                        if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success))
                        {
                            var error = string.Join(Environment.NewLine, getTaxResult.Messages.Select(m => m.Summary));
                            throw new Exception(error);
                        }
                    }
                }
                else
                {
                    throw new Exception("AvaTax credentials not provided or tax calculation disabled");
                }
            })
            .OnError(_logger, AvalaraLogger.EventCodes.TaxCalculationError)
            .OnSuccess(_logger, AvalaraLogger.EventCodes.GetTaxRequestTime);
        }
Exemplo n.º 15
0
        public virtual void AdjustOrderTax(CustomerOrder originalOrder, CustomerOrder modifiedOrder)
        {
            LogInvoker<AvalaraLogger.TaxRequestContext>.Execute(log =>
            {
                if (IsEnabled && !string.IsNullOrEmpty(AccountNumber)
                    && !string.IsNullOrEmpty(LicenseKey)
                    && !string.IsNullOrEmpty(ServiceUrl)
                    && !string.IsNullOrEmpty(CompanyCode))
                {
                    //if all payments completed commit tax document in avalara
                    var isCommit = modifiedOrder.InPayments != null && modifiedOrder.InPayments.Any()
                        && modifiedOrder.InPayments.All(pi => pi.IsApproved);

                    Contact contact = null;
                    if (modifiedOrder.CustomerId != null)
                        contact = _customerSearchService.GetById(modifiedOrder.CustomerId);

                    var request = modifiedOrder.ToAvaTaxAdjustmentRequest(CompanyCode, contact, originalOrder, isCommit);
                    if (request != null)
                    {
                        log.docCode = request.ReferenceCode;
                        log.docType = request.DocType.ToString();
                        log.customerCode = request.CustomerCode;
                        log.amount = (double)originalOrder.Sum;

                        var taxSvc = new JsonTaxSvc(AccountNumber, LicenseKey, ServiceUrl);
                        var getTaxResult = taxSvc.GetTax(request);

                        if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success))
                        {
                            var error = string.Join(Environment.NewLine,
                                getTaxResult.Messages.Select(m => m.Summary));
                            throw new Exception(error);
                        }
                        
                        foreach (var taxLine in getTaxResult.TaxLines ?? Enumerable.Empty<AvaTaxCalcREST.TaxLine>())
                        {
                            var lineItem = modifiedOrder.Items.FirstOrDefault(x => x.Id == taxLine.LineNo);
                            if (lineItem != null)
                            {
                                lineItem.Tax += taxLine.Tax;
                                if (taxLine.TaxDetails != null && taxLine.TaxDetails.Any(td => !string.IsNullOrEmpty(td.TaxName)))
                                {

                                    var taxLines =
                                        taxLine.TaxDetails.Where(td => !string.IsNullOrEmpty(td.TaxName)).Select(taxDetail => taxDetail.ToDomainTaxDetail()).ToList();

                                    lineItem.TaxDetails = lineItem.TaxDetails == null ? taxLines : lineItem.TaxDetails.AddRange(taxLines);
                                }
                            }
                        }

                        modifiedOrder.Tax = 0;
                    }
                }
                else
                {
                    throw new Exception("AvaTax credentials not provided or tax calculation disabled");
                }
            })
            .OnError(_logger, AvalaraLogger.EventCodes.TaxCalculationError)
            .OnSuccess(_logger, AvalaraLogger.EventCodes.GetTaxRequestTime);
        }
Exemplo n.º 16
0
        public virtual void CalculateOrderTax(CustomerOrder order)
        {
            LogInvoker<AvalaraLogger.TaxRequestContext>.Execute(log =>
            {
                if (IsEnabled && !string.IsNullOrEmpty(AccountNumber)
                    && !string.IsNullOrEmpty(LicenseKey)
                    && !string.IsNullOrEmpty(ServiceUrl)
                    && !string.IsNullOrEmpty(CompanyCode))
                {
                    //if all payments completed commit tax document in avalara
                    var isCommit = order.InPayments != null && order.InPayments.Any()
                        && order.InPayments.All(pi => pi.IsApproved);

                    Contact contact = null;
                    if (order.CustomerId != null)
                        contact = _customerSearchService.GetById(order.CustomerId);

                    var request = order.ToAvaTaxRequest(CompanyCode, contact, isCommit);
                    if (request != null)
                    {
                        log.docCode = request.DocCode;
                        log.docType = request.DocType.ToString();
                        log.customerCode = request.CustomerCode;
                        log.amount = (double)order.Sum;
                        log.isCommit = isCommit;

                        var taxSvc = new JsonTaxSvc(AccountNumber, LicenseKey, ServiceUrl);
                        var getTaxResult = taxSvc.GetTax(request);

                        if (!getTaxResult.ResultCode.Equals(SeverityLevel.Success))
                        {
                            //if tax calculation failed create exception with provided error info
                            var error = string.Join(Environment.NewLine, getTaxResult.Messages.Select(m => m.Summary));
                            throw new Exception(error);
                        }
                        
                        UpdateOrderTaxes(getTaxResult.TaxLines, order);

                        order.Tax = getTaxResult.TotalTax;
                    }
                    else
                    {
                        throw new Exception("Failed to create get tax request");
                    }
                }
                else
                {
                    throw new Exception("Failed to create get tax request");
                }
            })
                .OnError(_logger, AvalaraLogger.EventCodes.TaxCalculationError)
                .OnSuccess(_logger, AvalaraLogger.EventCodes.GetSalesInvoiceRequestTime);
        }
        private void EnsureThatAllOperationsHaveNumber(CustomerOrder order)
        {
            foreach (var operation in order.GetFlatObjectsListWithInterface<IOperation>())
            {
                if (operation.Number == null)
                {
                    operation.Number = _operationNumberGenerator.GenerateNumber(operation);
                }
            }

        }
Exemplo n.º 18
0
		private List<OrderLine> GetOrderLineItems(CustomerOrder order)
		{
			List<OrderLine> retVal = new List<OrderLine>();

			foreach (var lineItem in order.Items)
			{
				OrderLine orderLine = new OrderLine
				{
					Type = "physical",
					Reference = lineItem.ProductId,
					Name = lineItem.Name,
					Quantity = lineItem.Quantity,
					UnitPrice = (int)(lineItem.Price * 100),
					TaxRate = null,
					TotalTaxAmount = null,
					TotalAmount = (int)(lineItem.Price * 100) * lineItem.Quantity
				};

				retVal.Add(orderLine);
			}

			if (order.Shipments != null && order.Shipments.Any(s => s.Sum > 0))
			{
				foreach (var shipment in order.Shipments.Where(s => s.Sum > 0))
				{
					OrderLine orderLine = new OrderLine
					{
						Type = "shipping_fee",
						Reference = "SHIPPING",
						Quantity = 1,
						Name = "Shipping Fee",
						UnitPrice = (int)(shipment.Sum * 100),
						TaxRate = null,
						TotalTaxAmount = null,
						TotalAmount = (int)(int)(shipment.Sum * 100)
					};

					retVal.Add(orderLine);
				}
			}

			return retVal;
		}
		private List<Dictionary<string, object>> CreateKlarnaCartItems(CustomerOrder order)
		{
			var cartItems = new List<Dictionary<string, object>>();
			foreach (var lineItem in order.Items)
			{
				var addedItem = new Dictionary<string, object>();

				addedItem.Add("type", "physical");

				if (!string.IsNullOrEmpty(lineItem.Name))
				{
					addedItem.Add("name", lineItem.Name);
				}
				if (lineItem.Quantity > 0)
				{
					addedItem.Add("quantity", lineItem.Quantity);
				}
				if (lineItem.Price > 0)
				{
					addedItem.Add("unit_price", (int)((lineItem.Price + lineItem.Tax / lineItem.Quantity) * 100));
					//addedItem.Add("total_price_excluding_tax", (int)(lineItem.Price * lineItem.Quantity * 100));
				}

				if (lineItem.Tax > 0)
				{
					//addedItem.Add("total_price_including_tax", (int)((lineItem.Price * lineItem.Quantity + lineItem.Tax) * 100));
					//addedItem.Add("total_tax_amount", (int)(lineItem.Tax * 100));
					addedItem.Add("tax_rate", (int)(lineItem.TaxDetails.Sum(td => td.Rate) * 10000));
				}
				else
				{
					addedItem.Add("tax_rate", 0);
				}

				addedItem.Add("discount_rate", 0);
				addedItem.Add("reference", lineItem.ProductId);

				cartItems.Add(addedItem);
			}

			if (order.Shipments != null && order.Shipments.Any(s => s.Sum > 0))
			{
				foreach(var shipment in order.Shipments.Where(s => s.Sum > 0))
				{
					var addedItem = new Dictionary<string, object>();

					addedItem.Add("type", "shipping_fee");
					addedItem.Add("reference", "SHIPPING");
					addedItem.Add("name", "Shipping Fee");
					addedItem.Add("quantity", 1);
					addedItem.Add("unit_price", (int)(shipment.Sum * 100));

					addedItem.Add("tax_rate", 0);

					cartItems.Add(addedItem);
				}
			}

			return cartItems;
		}
		public void Update(CustomerOrder[] orders)
		{

			//Need a call business logic for changes and persist changes
			using (var repository = _repositoryFactory())
			{
				foreach (var order in orders)
				{
					EnsureThatAllOperationsHasNumber(order);
					var origOrder = GetById(order.Id, CustomerOrderResponseGroup.Full);

					//Do business logic on temporary  order object
					_eventPublisher.Publish(new OrderChangeEvent(EntryState.Modified, origOrder, order));

					var sourceOrderEntity = order.ToDataModel();
					var targetOrderEntity = repository.GetCustomerOrderById(order.Id, CustomerOrderResponseGroup.Full);

					if (targetOrderEntity == null)
					{
						throw new NullReferenceException("targetOrderEntity");
					}

					using (var changeTracker = GetChangeTracker(repository, targetOrderEntity))
					{
						changeTracker.Attach(targetOrderEntity);
						sourceOrderEntity.Patch(targetOrderEntity);
					}
				}
				CommitChanges(repository);
			}

		}
		private PayRequest CreatePaypalRequest(CustomerOrder order, PaymentIn payment, string url)
		{
			var receivers = new List<Receiver>();
			receivers.Add(new Receiver { amount = payment.Sum, email = "*****@*****.**", invoiceId = payment.Id });

			PayRequest retVal = new PayRequest
			{
				requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" },
				currencyCode = order.Currency.ToString(),
				receiverList = new ReceiverList(receivers),
				actionType = "PAY",
				cancelUrl = string.Format("{0}/{1}?cancel=true&orderId={2}", url, PaypalPaymentRedirectRelativePath, order.Id) + "&paykey=${paykey}",
				returnUrl = string.Format("{0}/{1}?cancel=false&orderId={2}", url, PaypalPaymentRedirectRelativePath, order.Id) + "&paykey=${paykey}"
			};

			return retVal;
		}
		public static CustomerOrder ToCustomerOrder(this cart.ShoppingCart cart)
		{
			if (cart == null)
				throw new ArgumentNullException("cart");

			var retVal = new CustomerOrder()
			{
				Id = Guid.NewGuid().ToString(),
				Currency = cart.Currency,
				CustomerId = cart.CustomerId,
				CustomerName = cart.CustomerName,
				StoreId = cart.StoreId,
				OrganizationId = cart.OrganizationId,
                Status = "New"
			};
            retVal.Addresses = new List<Address>();

            if (cart.Items != null)
			{
				retVal.Items = cart.Items.Select(x => x.ToOrderCoreModel()).ToList();
			}
			if (cart.Discounts != null)
			{
				retVal.Discount = cart.Discounts.Select(x=>x.ToOrderCoreModel()).FirstOrDefault();
			}
			if (cart.Addresses != null)
			{
				retVal.Addresses = cart.Addresses.Select(x => x.ToCoreModel()).ToList();
			}
			if (cart.Shipments != null)
			{
				retVal.Shipments = cart.Shipments.Select(x => x.ToOrderCoreModel()).ToList();
                //Add shipping address to order
                retVal.Addresses.AddRange(retVal.Shipments.Where(x=>x.DeliveryAddress != null).Select(x => x.DeliveryAddress));
                //Redistribute order line items to shipment if cart shipment items empty 
                var shipment = retVal.Shipments.FirstOrDefault();
				if(shipment != null && shipment.Items.IsNullOrEmpty())
				{
					shipment.Items = retVal.Items.Select(x => new ShipmentItem { LineItem = x, Quantity = x.Quantity }).ToList();
				}
			}
			if (cart.Payments != null)
			{
				retVal.InPayments = new List<PaymentIn>();
				foreach(var payment in cart.Payments)
				{
					var paymentIn = payment.ToOrderCoreModel();
                    if (paymentIn.BillingAddress != null)
                    {
                        //Add billing address to order
                        retVal.Addresses.Add(paymentIn.BillingAddress);
                    }
                    paymentIn.CustomerId = cart.CustomerId;
					retVal.InPayments.Add(paymentIn);
				}
			}

            //Save only disctinct addresses for order
            retVal.Addresses = retVal.Addresses.Distinct().ToList();
			retVal.TaxDetails = cart.TaxDetails;
			return retVal;
		}
Exemplo n.º 23
0
        public IHttpActionResult CancelTax(CustomerOrder order)
        {
            if (!string.IsNullOrEmpty(_taxSettings.Username) && !string.IsNullOrEmpty(_taxSettings.Password)
                && !string.IsNullOrEmpty(_taxSettings.ServiceUrl)
                && !string.IsNullOrEmpty(_taxSettings.CompanyCode) && _taxSettings.IsEnabled)
            {
                var taxSvc = new JsonTaxSvc(_taxSettings.Username, _taxSettings.Password, _taxSettings.ServiceUrl);
                var request = order.ToAvaTaxCancelRequest(_taxSettings.CompanyCode, CancelCode.DocVoided);
                var cancelTaxResult = taxSvc.CancelTax(request);
                if (!cancelTaxResult.ResultCode.Equals(SeverityLevel.Success))
                {
                    var error = string.Join(Environment.NewLine, cancelTaxResult.Messages.Select(m => m.Details));
                    return BadRequest(error);
                }

                return Ok(cancelTaxResult);
            }
            
            return BadRequest();
        }
		private SetExpressCheckoutReq CreatePaypalRequest(CustomerOrder order, Store store, PaymentIn payment)
		{
			var retVal = new SetExpressCheckoutReq();

			var request = new SetExpressCheckoutRequestType();

			var ecDetails = new SetExpressCheckoutRequestDetailsType
			{
				CallbackTimeout = "3",
				ReturnURL = string.Format("{0}/{1}?cancel=false&orderId={2}", store.Url, PaypalPaymentRedirectRelativePath, order.Id),
				CancelURL = string.Format("{0}/{1}?cancel=true&orderId={2}", store.Url, PaypalPaymentRedirectRelativePath, order.Id)
			};

			if (PaypalPaymentModeStoreSetting.Equals("BankCard"))
			{
				ecDetails.SolutionType = SolutionTypeType.SOLE;
				ecDetails.LandingPage = LandingPageType.BILLING;
			}
			else
			{
				ecDetails.SolutionType = SolutionTypeType.MARK;
				ecDetails.LandingPage = LandingPageType.LOGIN;
			}

			var currency = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), order.Currency.ToString());

			var billingAddress = order.Addresses.FirstOrDefault(s => s.AddressType == VirtoCommerce.Domain.Order.Model.AddressType.Billing);

			if (billingAddress != null)
				ecDetails.BuyerEmail = billingAddress.Email;
			else
				billingAddress = order.Addresses.FirstOrDefault();

			if (billingAddress != null && !string.IsNullOrEmpty(billingAddress.Email))
				ecDetails.BuyerEmail = billingAddress.Email;

			ecDetails.PaymentDetails.Add(GetPaypalPaymentDetail(currency, PaymentActionCodeType.SALE, payment));

			request.SetExpressCheckoutRequestDetails = ecDetails;

			retVal.SetExpressCheckoutRequest = request;

			return retVal;
		}
Exemplo n.º 25
0
        private static CustomerOrder GetTestOrder(string id)
        {
            var order = new CustomerOrder
            {
                Id = id,
                Currency = CurrencyCodes.USD,
                CustomerId = "Test Customer",
                EmployeeId = "employee",
                StoreId = "test store",
                CreatedDate = DateTime.Now,
                Addresses = new []
				{
					new Address {	
					AddressType = AddressType.Shipping, 
					Phone = "+68787687",
					PostalCode = "60602",
					CountryCode = "US",
					CountryName = "United states",
					Email = "*****@*****.**",
					FirstName = "first name",
					LastName = "last name",
					Line1 = "45 Fremont Street",
                    City = "Los Angeles",
                    RegionId = "CA",
					Organization = "org1"
					}
				}.ToList(),
                Discount = new Discount
                {
                    PromotionId = "testPromotion",
                    Currency = CurrencyCodes.USD,
                    DiscountAmount = 12,
                    Coupon = new Coupon
                    {
                        Code = "ssss"
                    }
                }
            };
            var item1 = new LineItem
            {
                BasePrice = 10,
                Price = 20,
                ProductId = "shoes",
                CatalogId = "catalog",
                Currency = CurrencyCodes.USD,
                CategoryId = "category",
                Name = "shoes",
                Quantity = 2,
                ShippingMethodCode = "EMS",
                Discount = new Discount
                {
                    PromotionId = "itemPromotion",
                    Currency = CurrencyCodes.USD,
                    DiscountAmount = 12,
                    Coupon = new Coupon
                    {
                        Code = "ssss"
                    }
                }
            };
            var item2 = new LineItem
            {
                BasePrice = 100,
                Price = 100,
                ProductId = "t-shirt",
                CatalogId = "catalog",
                CategoryId = "category",
                Currency = CurrencyCodes.USD,
                Name = "t-shirt",
                Quantity = 2,
                ShippingMethodCode = "EMS",
                Discount = new Discount
                {
                    PromotionId = "testPromotion",
                    Currency = CurrencyCodes.USD,
                    DiscountAmount = 12,
                    Coupon = new Coupon
                    {
                        Code = "ssss"
                    }
                }
            };
            order.Items = new List<LineItem>();
            order.Items.Add(item1);
            order.Items.Add(item2);

            var shipment = new Shipment
            {
                Currency = CurrencyCodes.USD,
                DeliveryAddress = new Address
                {
                    City = "london",
                    CountryName = "England",
                    Phone = "+68787687",
                    PostalCode = "2222",
                    CountryCode = "ENG",
                    Email = "*****@*****.**",
                    FirstName = "first name",
                    LastName = "last name",
                    Line1 = "line 1",
                    Organization = "org1"
                },
                Discount = new Discount
                {
                    PromotionId = "testPromotion",
                    Currency = CurrencyCodes.USD,
                    DiscountAmount = 12,
                    Coupon = new Coupon
                    {
                        Code = "ssss"
                    }
                }
            };
            order.Shipments = new List<Shipment>();
            order.Shipments.Add(shipment);

            var payment = new PaymentIn
            {
                GatewayCode = "PayPal",
                Currency = CurrencyCodes.USD,
                Sum = 10,
                CustomerId = "et"
            };
            order.InPayments = new List<PaymentIn> { payment };

            return order;
        }
        private void EnsureThatAllOperationsHaveNumber(CustomerOrder order)
        {
            foreach (var operation in order.Traverse<Operation>(x => x.ChildrenOperations))
            {
                if (operation.Number == null)
                {
                    operation.Number = _operationNumberGenerator.GenerateNumber(operation);
                }
            }

        }
Exemplo n.º 27
0
		public OrderChangeEvent(EntryState state, CustomerOrder origOrder, CustomerOrder modifiedOrder)
		{
			ChangeState = state;
			OrigOrder = origOrder;
			ModifiedOrder = modifiedOrder;
		}