Exemplo n.º 1
0
Arquivo: Main.cs Projeto: jabza/LD30
 void unloadShipment(Shipment shipment)
 {
     mTotalPackages[(int)DESTINATION.A] += shipment.packageCounts[(int)DESTINATION.A];
     mTotalPackages[(int)DESTINATION.B] += shipment.packageCounts[(int)DESTINATION.B];
     mTotalPackages[(int)DESTINATION.C] += shipment.packageCounts[(int)DESTINATION.C];
     mTotalPackages[(int)DESTINATION.D] += shipment.packageCounts[(int)DESTINATION.D];
 }
Exemplo n.º 2
0
 private ShippingRate GetRate(Shipment shipment, ShippingMethodDto.ShippingMethodRow shippingMethodRow)
 {
     var type = Type.GetType(shippingMethodRow.ShippingOptionRow.ClassName);
     var shippingGateway = (IShippingGateway)Activator.CreateInstance(type, _currentMarket.GetCurrentMarket());
     string message = null;
     return shippingGateway.GetRate(shippingMethodRow.ShippingMethodId, shipment, ref message);
 }
Exemplo n.º 3
0
		public static Shipment ToCoreModel(this ShipmentEntity entity)
		{
			if (entity == null)
				throw new ArgumentNullException("entity");

			var retVal = new Shipment();
			retVal.InjectFrom(entity);
			retVal.Currency = (CurrencyCodes)Enum.Parse(typeof(CurrencyCodes), entity.Currency);

			if (entity.Properties != null)
			{
				retVal.Properties = entity.Properties.Select(x => x.ToCoreModel()).ToList();
			}
			if (entity.Addresses != null && entity.Addresses.Any())
			{
				retVal.DeliveryAddress = entity.Addresses.First().ToCoreModel();
			}
			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.InPayments != null)
			{
				retVal.InPayments = entity.InPayments.Select(x => x.ToCoreModel()).ToList();
			}

			retVal.TaxDetails = entity.TaxDetails.Select(x => x.ToCoreModel()).ToList();
			return retVal;
		}
        private async Task<ShipmentQuantity> TotalQuantityReceived(Guid importNotificationId, Shipment shipment)
        {
            await authorization.EnsureAccessAsync(importNotificationId);

            var movements = await context.ImportMovements.Where(m => m.NotificationId == importNotificationId).ToArrayAsync();

            var allMovementReceipts = new List<ImportMovementReceipt>();

            foreach (var movement in movements)
            {
                var movementReceipts = await context.ImportMovementReceipts.Where(mr => mr.MovementId == movement.Id).ToListAsync();
                allMovementReceipts = allMovementReceipts.Union(movementReceipts).ToList();
            }

            if (!allMovementReceipts.Any())
            {
                return new ShipmentQuantity(0, shipment == null ? ShipmentQuantityUnits.Tonnes : shipment.Quantity.Units);
            }
            
            var totalReceived = allMovementReceipts.Sum(m =>
                ShipmentQuantityUnitConverter.ConvertToTarget(
                    m.Unit,
                    shipment.Quantity.Units,
                    m.Quantity));

            return new ShipmentQuantity(totalReceived, shipment.Quantity.Units);
        }
Exemplo n.º 5
0
 public void UpdateShipment(Shipment shipment, ShippingRate shippingCost)
 {
     shipment.ShippingMethodId = shippingCost.Id;
     shipment.ShippingMethodName = shippingCost.Name;
     shipment.SubTotal = shippingCost.Money.Amount;
     shipment.ShippingSubTotal = shippingCost.Money.Amount;
     shipment.AcceptChanges();
 }
Exemplo n.º 6
0
 public double CalculateCost(Shipment shipment)
 {
     double cost = ToStateCost(shipment.StateOrProvince);
     cost += shipment.PurchaseInsurance ? .5 : 0;
     cost += shipment.RequireSignature ? .25 : 0;
     shipment.Cost = cost * (multiplier > 0 ? multiplier : 1) ;
     return shipment.Cost;
 }
Exemplo n.º 7
0
 public void CalculateCost(Shipment shipment)
 {
     double cost = ToStateCost(shipment.StateOrProvince);
     cost += CourierCost(shipment.Vendor);
     cost += shipment.PurchaseInsurance ? .5 : 0;
     cost += shipment.RequireSignature ? .25 : 0;
     shipment.Cost = cost;
 }
        private Shipment createShipmentFromScreen()
        {
            Shipment shipment = new Shipment();
            shipment.PurchaseInsurance = _screen.PurchaseInsurance;
            shipment.StateOrProvince = _screen.StateOrProvince;
            // so on, and so forth

            return shipment;
        }
 protected static OrderShipmentStatus GetShipmentStatus(Shipment shipment)
 {
     OrderShipmentStatus retVal = OrderShipmentStatus.InventoryAssigned;
     if (!string.IsNullOrEmpty(shipment.Status))
     {
         retVal = (OrderShipmentStatus)Enum.Parse(typeof(OrderShipmentStatus), shipment.Status);
     }
     return retVal;
 }
Exemplo n.º 10
0
 public ShipmentViewModel(Shipment data)
 {
     UnitsSelectList = new SelectList(EnumHelper.GetValues(typeof(ShipmentQuantityUnits)), "Key", "Value");
     StartDate = new OptionalDateInputViewModel(data.StartDate);
     EndDate = new OptionalDateInputViewModel(data.EndDate);
     TotalQuantity = data.Quantity;
     Units = data.Unit;
     TotalShipments = data.TotalShipments;
 }
Exemplo n.º 11
0
        public Shipment CalculateShipping(Order order) {

            Shipment result = new Shipment(order);
            result.ShippingOptions = new List<ShippingMethod>();
            result.ShippingOptions.Add(new ShippingMethod(1,"Test Carrier", "Overnight", 10, 1,5));
            result.ShippingOptions.Add(new ShippingMethod(2,"Test Carrier", "Next Day", 5, 2,10));
            result.ShippingOptions.Add(new ShippingMethod(3,"Test Carrier", "Ground", 2,  5,20));
            return result;
        }
        public ActionResult Create(Shipment shipment)
        {
            if (ModelState.IsValid)
            {
                db.Shipments.Add(shipment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(shipment);
        }
 public Shipment Insert_Shipment_select(int ID)
 {
     Shipment = Shipment.Select(ID);
     Insert_WarehouseID_txt.Text = Convert.ToString(Shipment.WarehouseID);
     Insert_Tracking_Num_txt.Text = Convert.ToString(Shipment.Tracking_Num);
     Insert_Ship_Method_txt.Text = Convert.ToString(Shipment.Ship_Method);
     Insert_Other_txt.Text = Convert.ToString(Shipment.Other);
     Insert_OrderRecByID_txt.Text = Convert.ToString(Shipment.OrderRecByID);
     Insert_FullOrderReceived_txt.Text = Convert.ToString(Shipment.FullOrderReceived);
     return Shipment;
 }
 private void DeleteLineItemFromShipment(Shipment shipment, LineItem lineItem)
 {
     var orderForm = OrderGroup.OrderForms.ToArray().Where(of => of.LineItems.ToArray().Contains(lineItem)).FirstOrDefault();
     if (orderForm != null)
     {
         var lineItemIndex = orderForm.LineItems.IndexOf(lineItem);
         decimal shipmentQty = Shipment.GetLineItemQuantity(shipment, lineItem.LineItemId);
         lineItem.Quantity -= shipmentQty;
         shipment.RemoveLineItemIndex(lineItemIndex);
     }
 }
 private static Shipment GetValidShipment(Guid importNotificationId)
 {
     var shipment = new Shipment(importNotificationId)
     {
         TotalShipments = 10,
         Quantity = 1000.0000M,
         Unit = ShipmentQuantityUnits.Tonnes,
         StartDate = new DateTime(2015, 12, 1),
         EndDate = new DateTime(2016, 11, 30)
     };
     return shipment;
 }
        public void SetUpTest()
        {
            shipment = new Shipment();
            shipment.StateOrProvince = "Testville";
            shipment.Vendor = "Test";
            shipment.ShippingOption = "Carrier Pigeon";

            mocks = new MockRepository();
            service = mocks.CreateMock<IShippingService>();
            screen = mocks.CreateMock<IShippingScreen>();
            presenter = new ShippingScreenPresenter(screen, service, shipment);
        }
 private static decimal CalculateShipmentSubtotal(Shipment shipment)
 {
     var retVal = 0m;
     foreach (var lineItem in Shipment.GetShipmentLineItems(shipment))
     {
         if (lineItem.Quantity > 0)
         {
             retVal += lineItem.ExtendedPrice / lineItem.Quantity * Shipment.GetLineItemQuantity(shipment, lineItem.LineItemId);
         }
     }
     return Math.Floor(retVal * 100) * 0.01m;
 }
Exemplo n.º 18
0
 public DeliveryOptions GetDeliveryOptions(Shipment shipment)
 {
     DeliveryOptions options = new DeliveryOptions();
     if(shipment.Vendor == "USPS")
     {
         options.PurchaseInsuranceEnabled = false;
         options.RequireSignatureEnabled = false;
     }
     else
     {
         options.PurchaseInsuranceEnabled = true;
         options.RequireSignatureEnabled = true;
     }
     return options;
 }
 private void ChangeShipmentLineItemQty(Shipment shipment, LineItem lineItem, decimal delta)
 {
     var orderForm = OrderGroup.OrderForms.ToArray().Where(of => of.LineItems.ToArray().Contains(lineItem)).FirstOrDefault();
     if (orderForm != null)
     {
         var lineItemIndex = orderForm.LineItems.IndexOf(lineItem);
         {
             //Decrease qty in all shipment contains line item
             var shipmentQty = Shipment.GetLineItemQuantity(shipment, lineItem.LineItemId);
             var newShipmentQty = shipmentQty - delta;
             newShipmentQty = newShipmentQty > 0 ? newShipmentQty : 0;
             //Set new line item qty in shipment
             shipment.SetLineItemQuantity(lineItemIndex, newShipmentQty);
             delta -= Math.Min(delta, shipmentQty);
         }
     }
 }
Exemplo n.º 20
0
		public static Shipment ToCoreModel(this cartCoreModel.Shipment shipment)
		{
			var retVal = new Shipment();
			retVal.InjectFrom(shipment);
			retVal.Currency = shipment.Currency;
			retVal.Sum = shipment.ShippingPrice;
			retVal.Tax = shipment.TaxTotal;

			if(shipment.DeliveryAddress != null)
			{
				retVal.DeliveryAddress = shipment.DeliveryAddress.ToCoreModel();
			}
			if(shipment.Items != null)
			{
				retVal.Items = shipment.Items.Select(x => x.ToCoreShipmentItemModel()).ToList();
			}
			retVal.TaxDetails = shipment.TaxDetails;
			return retVal;
		}
Exemplo n.º 21
0
		public static Shipment ToCoreModel(this ShipmentEntity entity, IEnumerable<ShippingMethod> shippingMethods, IEnumerable<PaymentMethod> paymentMethods)
		{
			if (entity == null)
				throw new ArgumentNullException("entity");

			var retVal = new Shipment();
			retVal.InjectFrom(entity);
			retVal.Currency = entity.Currency;

			if (entity.Addresses != null && entity.Addresses.Any())
			{
				retVal.DeliveryAddress = entity.Addresses.First().ToCoreModel();
			}
			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.InPayments != null)
			{
				retVal.InPayments = entity.InPayments.Select(x => x.ToCoreModel(paymentMethods)).ToList();
			}
			if (entity.Packages != null)
			{
				retVal.Packages = entity.Packages.Select(x => x.ToCoreModel()).ToList();
			}
			retVal.TaxDetails = entity.TaxDetails.Select(x => x.ToCoreModel()).ToList();

            //Set shipment method for shipment by code
            if (shippingMethods != null)
            {
                retVal.ShippingMethod = shippingMethods.FirstOrDefault(x => String.Equals(x.Code, entity.ShipmentMethodCode, StringComparison.InvariantCultureIgnoreCase));
            }
         

            return retVal;
		}
Exemplo n.º 22
0
        public string[] GetShippingOptions(Shipment shipment)
        {
            if (string.IsNullOrEmpty(shipment.Vendor))
                return new string[] {};

            if(shipment.Vendor.EndsWith("Courier"))
                return new string[] {"Bicycle", "Car"};

            switch(shipment.Vendor.ToUpper())
            {
                case "DHL":
                    return new string[] { "Van", "Truck", "Air"};
                case "FEDEX":
                    return new string[] { "Semi", "Air"};
                case "UPS":
                    return new string[] { "Train", "Air"};
                case "USPS":
                    return new string[] { "Air", "Truck", "Trailer"};
                default:
                    return new string[]{};
            }
        }
Exemplo n.º 23
0
		public static Shipment ToOrderCoreModel(this cartCoreModel.Shipment shipment)
		{
			var retVal = new Shipment();
			retVal.InjectFrom(shipment);
			retVal.Currency = shipment.Currency;
			retVal.Sum = shipment.Total;
			retVal.Tax = shipment.TaxTotal;
            retVal.DiscountAmount = shipment.DiscountTotal;
            retVal.Status = "New";
            if (shipment.DeliveryAddress != null)
			{
				retVal.DeliveryAddress = shipment.DeliveryAddress.ToCoreModel();
			}
			if(shipment.Items != null)
			{
				retVal.Items = shipment.Items.Select(x => x.ToOrderCoreModel()).ToList();
			}
            if (shipment.Discounts != null)
            {
                retVal.Discount = shipment.Discounts.Select(x => x.ToOrderCoreModel()).FirstOrDefault();
            }
            retVal.TaxDetails = shipment.TaxDetails;
			return retVal;
		}
Exemplo n.º 24
0
 public UpdateShipmentWithBoundry(Shipment shipment)
 {
     TrackingCode   = shipment.TrackingCode;
     Implementation = shipment.BoundryImplementation;
     Id             = shipment.Id.ToString();
 }
Exemplo n.º 25
0
 public static GrpcShipmentEvents Present(Shipment shipment) =>
 new ShipmentEventsPresenter(shipment).GetPresented();
Exemplo n.º 26
0
 public void Add(Shipment shipment)
 {
     _context.Shipments.Add(shipment);
 }
        /// <summary>
        /// Saves the shipment information to the current directory or the specified save file directory
        /// in settings, if the user has set one. May throw an exception if unable to save file to the directory.
        /// Also saves the entire ZPL string to a text file, in case user doesn't have a ZPL thermal label,
        /// an online tool can be used.
        /// </summary>
        public void SaveShipmentToFile()
        {
            //get the entire ZPL string
            string zplLabelsString = "";

            foreach (ZPLLabel label in LabelsFactory.BoxLabels)
            {
                zplLabelsString += label.ZPLCommand;
            }


            try
            {   //save shipment in txt file as JSON
                File.WriteAllText(SaveDirectory + "\\" + Shipment.ShipmentID + ".txt", Shipment.ToString());

                //save zpl string of labels to text file
                File.WriteAllText(SaveDirectory + "\\" + Shipment.ShipmentID + "-ZPL.txt", zplLabelsString);
            }
            catch (Exception ex)
            {
                throw new NonSaveableException(message: "Unable to save the contents of shipment '" + Shipment.ShipmentID + "' for the following reason:" + ex.Message);
            }
        }
Exemplo n.º 28
0
        private void ChangeShipmentsLineItemQuantity(LineItem lineItem, decimal delta, Shipment shipment)
        {
            if (shipment == null)
            {
                return;
            }
            //Decrease qty in all shipment contains line item
            var shipmentQty    = Shipment.GetLineItemQuantity(shipment, lineItem.LineItemId);
            var newShipmentQty = shipmentQty - delta;

            newShipmentQty = newShipmentQty > 0 ? newShipmentQty : 0;
            shipment.SetLineItemQuantity(shipment.Parent.LineItems.IndexOf(lineItem), newShipmentQty);
        }
        /// <summary>
        /// Create split shipment for the first time.
        /// </summary>
        private void CreateDataSplitShipment()
        {
            // Create shipment for each lineitem for the first time to demo showcase multishipment.
            if (Cart.OrderForms.Count > 0)
            {
                var lineItems = Cart.OrderForms[0].LineItems;
                if (Cart.OrderForms[0].Shipments.Count != lineItems.Count)
                {
                    foreach (MetaObject shipment in Cart.OrderForms[0].Shipments)
                    {
                        shipment.Delete();
                    }

                    foreach (LineItem lineItem in lineItems)
                    {
                        Shipment shipment = new Shipment();
                        shipment.CreatorId = SecurityContext.Current.CurrentUserId.ToString();
                        shipment.Created = DateTime.UtcNow;
                        shipment.AddLineItemIndex(lineItems.IndexOf(lineItem), lineItem.Quantity);
                        shipment.WarehouseCode = lineItem.WarehouseCode;

                        // For Shipping method "In store pickup"
                        IWarehouse warehouse = WarehouseHelper.GetWarehouse(lineItem.WarehouseCode);
                        if (!warehouse.IsFulfillmentCenter && warehouse.IsPickupLocation)
                        {
                            if (CartHelper.FindAddressByName(warehouse.Name) == null)
                            {
                                var address = warehouse.ContactInformation.ToOrderAddress();
                                address.Name = warehouse.Name;
                                Cart.OrderAddresses.Add(address);
                            }

                            shipment.ShippingAddressId = warehouse.Name;
                            shipment.ShippingMethodName = ShippingManager.PickupShippingMethodName;

                            var instorepickupShippingMethod = ShippingManager.GetShippingMethods("en").ShippingMethod.ToArray().Where(m => m.Name.Equals(ShippingManager.PickupShippingMethodName)).FirstOrDefault();
                            if (instorepickupShippingMethod != null)
                            {
                                shipment.ShippingMethodId = instorepickupShippingMethod.ShippingMethodId;
                            }
                        }

                        Cart.OrderForms[0].Shipments.Add(shipment);
                    }
                }

                Cart.AcceptChanges();
            }
        }
Exemplo n.º 30
0
        protected void AppendVariable(string name, Shipment value, bool alwaysinclude, ref string output)
        {
            string body = null;

            if (value != null)
            {
                if (string.IsNullOrWhiteSpace(value.id))
                {
                    AppendVariable(name + "[batch_id]", value.batch_id, false, ref body);
                    AppendVariable(name + "[batch_status]", value.batch_status, false, ref body);
                    AppendVariable(name + "[buyer_address]", value.buyer_address, false, ref body);
                    AppendVariable(name + "[customs_info]", value.customs_info, false, ref body);

                    if (value.fees != null && value.fees.Length > 0)
                    {
                        for (var i = 0; i < value.fees.Length; i++)
                        {
                            AppendVariable(name + "[fees][" + i + "]", value.fees[i], false, ref body);
                        }
                    }

                    if (value.forms != null && value.forms.Length > 0)
                    {
                        for (var i = 0; i < value.forms.Length; i++)
                        {
                            AppendVariable(name + "[forms][" + i + "]", value.forms[i], false, ref body);
                        }
                    }

                    AppendVariable(name + "[from_address]", value.from_address, false, ref body);

                    AppendVariable(name + "[insurance]", value.insurance, false, ref body);
                    AppendVariable(name + "[is_return]", value.is_return, false, ref body);
                    AppendVariable(name + "[options]", value.options, false, ref body);
                    AppendVariable(name + "[parcel]", value.parcel, false, ref body);
                    AppendVariable(name + "[postage_label]", value.postage_label, false, ref body);
                    if (value.rates != null && value.rates.Length > 0)
                    {
                        for (var i = 0; i < value.rates.Length; i++)
                        {
                            AppendVariable(name + "[rates][" + i + "]", value.rates[i], false, ref body);
                        }
                    }
                    AppendVariable(name + "[reference]", value.reference, false, ref body);
                    AppendVariable(name + "[refund_status]", value.refund_status, false, ref body);
                    AppendVariable(name + "[return_address]", value.return_address, false, ref body);
                    AppendVariable(name + "[scan_form]", value.scan_form, false, ref body);
                    AppendVariable(name + "[selected_rate]", value.selected_rate, false, ref body);
                    AppendVariable(name + "[status]", value.status, false, ref body);
                    AppendVariable(name + "[to_address]", value.to_address, false, ref body);
                    AppendVariable(name + "[tracker]", value.tracker, false, ref body);
                    AppendVariable(name + "[tracking_code]", value.tracking_code, false, ref body);
                    AppendVariable(name + "[usps_zone]", value.usps_zone, false, ref body);
                }
                else
                {
                    AppendVariable(name + "[id]", value.id, false, ref body);
                }
            }
            else if (alwaysinclude)
            {
                body = name + "=";
            }
            if (body != null)
            {
                if (output != null && output.Length > 0)
                {
                    output += "&";
                }
                output += body;
            }
        }
Exemplo n.º 31
0
 public static ShipmentDto ToDto(this Shipment shipment)
 {
     return(shipment.MapTo <Shipment, ShipmentDto>());
 }
Exemplo n.º 32
0
 public ShipmentSentEvent(Shipment shipment)
 {
     this._shipment = shipment;
 }
Exemplo n.º 33
0
 public ShipmentDeliveredEvent(Shipment shipment)
 {
     this._shipment = shipment;
 }
Exemplo n.º 34
0
        /// <summary>
        /// Prepare the shipment details model
        /// </summary>
        /// <param name="shipment">Shipment</param>
        /// <returns>Shipment details model</returns>
        public virtual ShipmentDetailsModel PrepareShipmentDetailsModel(Shipment shipment)
        {
            if (shipment == null)
            {
                throw new ArgumentNullException(nameof(shipment));
            }

            var order = shipment.Order;

            if (order == null)
            {
                throw new Exception("order cannot be loaded");
            }
            var model = new ShipmentDetailsModel
            {
                Id = shipment.Id
            };

            if (shipment.ShippedDateUtc.HasValue)
            {
                model.ShippedDate = _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
            }
            if (shipment.DeliveryDateUtc.HasValue)
            {
                model.DeliveryDate = _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
            }

            //tracking number and shipment information
            if (!string.IsNullOrEmpty(shipment.TrackingNumber))
            {
                model.TrackingNumber = shipment.TrackingNumber;
                var shipmentTracker = shipment.GetShipmentTracker(_shippingService, _shippingSettings);
                if (shipmentTracker != null)
                {
                    model.TrackingNumberUrl = shipmentTracker.GetUrl(shipment.TrackingNumber);
                    if (_shippingSettings.DisplayShipmentEventsToCustomers)
                    {
                        var shipmentEvents = shipmentTracker.GetShipmentEvents(shipment.TrackingNumber);
                        if (shipmentEvents != null)
                        {
                            foreach (var shipmentEvent in shipmentEvents)
                            {
                                var shipmentStatusEventModel = new ShipmentDetailsModel.ShipmentStatusEventModel();
                                var shipmentEventCountry     = _countryService.GetCountryByTwoLetterIsoCode(shipmentEvent.CountryCode);
                                shipmentStatusEventModel.Country = shipmentEventCountry != null
                                                                        ? shipmentEventCountry.GetLocalized(x => x.Name)
                                                                        : shipmentEvent.CountryCode;

                                shipmentStatusEventModel.Date      = shipmentEvent.Date;
                                shipmentStatusEventModel.EventName = shipmentEvent.EventName;
                                shipmentStatusEventModel.Location  = shipmentEvent.Location;
                                model.ShipmentStatusEvents.Add(shipmentStatusEventModel);
                            }
                        }
                    }
                }
            }

            //products in this shipment
            model.ShowSku = _catalogSettings.ShowSkuOnProductDetailsPage;
            foreach (var shipmentItem in shipment.ShipmentItems)
            {
                var orderItem = _orderService.GetOrderItemById(shipmentItem.OrderItemId);
                if (orderItem == null)
                {
                    continue;
                }

                var shipmentItemModel = new ShipmentDetailsModel.ShipmentItemModel
                {
                    Id              = shipmentItem.Id,
                    Sku             = orderItem.Product.FormatSku(orderItem.AttributesXml, _productAttributeParser),
                    ProductId       = orderItem.Product.Id,
                    ProductName     = orderItem.Product.GetLocalized(x => x.Name),
                    ProductSeName   = orderItem.Product.GetSeName(),
                    AttributeInfo   = orderItem.AttributeDescription,
                    QuantityOrdered = orderItem.Quantity,
                    QuantityShipped = shipmentItem.Quantity,
                };
                //rental info
                if (orderItem.Product.IsRental)
                {
                    var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalStartDateUtc.Value) : "";
                    var rentalEndDate   = orderItem.RentalEndDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalEndDateUtc.Value) : "";
                    shipmentItemModel.RentalInfo = string.Format(_localizationService.GetResource("Order.Rental.FormattedDate"),
                                                                 rentalStartDate, rentalEndDate);
                }
                model.Items.Add(shipmentItemModel);
            }

            //order details model
            model.Order = PrepareOrderDetailsModel(order);

            return(model);
        }
Exemplo n.º 35
0
 /// <summary>
 /// Updates the shipment
 /// </summary>
 /// <param name="shipment">Shipment</param>
 public void UpdateShipment([FromBody] Shipment shipment)
 {
     _shipmentService.UpdateShipment(shipment);
 }
Exemplo n.º 36
0
 /// <summary>
 /// Gets the orders by order ids.
 /// </summary>
 /// <param name="ids">The ids.</param>
 /// <param name="fcn">SQL connection.</param>
 /// <param name="ftrns">SQL transaction.</param>
 /// <returns>The matching orders.</returns>
 public static List<Order> GetOrdersByOrderIds(int[] ids, SqlConnection fcn, SqlTransaction ftrns)
 {
     List<Order> orders = new List<Order>();
     if(ids.Length == 0) { return orders; };
     List<SqlDataRecord> rowData = new List<SqlDataRecord>();
     SqlMetaData[] hashTable = {
         new SqlMetaData("keyName",SqlDbType.VarChar,100),
         new SqlMetaData("keyValue",SqlDbType.Variant),
         new SqlMetaData("primary_key",SqlDbType.Bit),
         new SqlMetaData("dataType",SqlDbType.VarChar,50),
         new SqlMetaData("dataLength",SqlDbType.Int),
         new SqlMetaData("varCharMaxValue",SqlDbType.VarChar,-1)
     };
     StringBuilder s = new StringBuilder();
     foreach(int id in ids) {
         SqlDataRecord rec = new SqlDataRecord(hashTable);
         rec.SetValue(0, "orderId");
         rec.SetValue(1, id);
         rec.SetBoolean(2, false);
         rec.SetString(3, "int");
         rec.SetValue(4, 8);
         rowData.Add(rec);
     }
     SqlConnection cn;
     if(fcn != null) {
         cn = fcn;
     } else {
         cn = Site.SqlConnection;
     }
     using(SqlCommand cmd = cn.CreateCommand()) {
         if(fcn != null) {
             cmd.Transaction = ftrns;
         }
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.CommandText = "dbo.getOrders";
         cmd.Parameters.Add("@orderIds", SqlDbType.Structured);
         cmd.Parameters["@orderIds"].Direction = ParameterDirection.Input;
         cmd.Parameters["@orderIds"].Value = rowData;
         using(SqlDataReader u = cmd.ExecuteReader()) {
             int orderId = -1;
             DateTime orderDate = DateTime.MinValue;
             decimal grandTotal = 0;
             decimal taxTotal = 0;
             decimal subTotal = 0;
             decimal shippingTotal = 0;
             decimal service1 = 0;
             decimal service2 = 0;
             string manifest = "";
             string purchaseOrder = "";
             decimal discount = 0;
             string comment = "";
             decimal paid = 0;
             Guid billToAddressId = Guid.Empty;
             bool closed = false;
             bool canceled = false;
             Guid paymentMethodId = Guid.Empty;
             int termId = -1;
             int userId = -1;
             string orderNumber = "";
             bool creditMemo = false;
             string scanned_order_image = "";
             DateTime readyForExport = DateTime.MinValue;
             DateTime recalculatedOn = DateTime.MinValue;
             Guid sessionId = Guid.Empty;
             int soldBy = -1;
             int requisitionedBy = -1;
             int approvedBy = -1;
             DateTime deliverBy = DateTime.MinValue;
             string vendor_accountNo = "";
             string FOB = "";
             int parentOrderId = -1;
             int order_status = -1;
             List<Line> lines = new List<Line>();
             while(u.Read()) {
                 /* #44 is orderId */
                 if(u.GetInt32(44) != orderId && orderId != -1) {
                     /*the orderId has changed, add the previous order */
                     orders.Add(new Order(
                         orderId, orderDate, grandTotal, taxTotal, subTotal, shippingTotal, service1,
                         service2, manifest, purchaseOrder, discount, comment, paid, billToAddressId, closed,
                         canceled, paymentMethodId, termId, userId, orderNumber, creditMemo, scanned_order_image,
                         readyForExport, recalculatedOn, sessionId, soldBy, requisitionedBy, approvedBy, deliverBy,
                         vendor_accountNo, FOB, parentOrderId, lines, order_status, cn, ftrns
                     ));
                     lines = new List<Line>();/* create a new list of lines for the next order */
                 }
                 orderId = u.GetInt32(44);
                 orderDate = u.GetDateTime(132);
                 grandTotal = u.GetDecimal(133);
                 taxTotal = u.GetDecimal(134);
                 subTotal = u.GetDecimal(135);
                 shippingTotal = u.GetDecimal(136);
                 service1 = u.GetDecimal(137);
                 service2 = u.GetDecimal(138);
                 manifest = u.GetString(139);
                 purchaseOrder = u.GetString(140);
                 discount = u.GetDecimal(164);
                 comment = u.GetString(141);
                 paid = u.GetDecimal(190);
                 billToAddressId = u.GetGuid(103);
                 closed = u.GetBoolean(191);
                 canceled = u.GetBoolean(191);
                 termId = u.GetInt32(84);
                 userId = u.GetInt32(55);
                 orderNumber = u.GetString(46);
                 creditMemo = u.GetBoolean(193);
                 scanned_order_image = u.GetString(53);
                 readyForExport = u.GetDateTime(7);
                 recalculatedOn = u.GetDateTime(194);
                 sessionId = u.GetGuid(38);
                 soldBy = u.GetInt32(195);
                 requisitionedBy = u.GetInt32(196);
                 approvedBy = u.GetInt32(197);
                 deliverBy = u.GetDateTime(198);
                 vendor_accountNo = u.GetString(199);
                 FOB = u.GetString(200);
                 parentOrderId = u.GetInt32(201);
                 order_status = u.GetInt32(5);
                 /* always add every line */
                 lines.Add(new Line(
                     u.GetGuid(37)/*cartId*/,
                     u.GetGuid(38)/*sessionId*/,
                     u.GetInt32(39)/*qty*/,
                     u.GetString(0)/*itemNumber*/,
                     u.GetDecimal(41)/*price*/,
                     u.GetDateTime(42)/*add time*/,
                     u.GetInt32(44)/*orderId*/,
                     u.GetInt32(45)/*serialId*/,
                     u.GetString(46)/*orderNumber*/,
                     u.GetString(47)/*serialNumber*/,
                     u.GetGuid(48)/*addressId*/,
                     u.GetInt32(49)/*shipmentId*/,
                     u.GetString(50)/*shipmentNumber*/,
                     u.GetInt32(51)/*lineNumber*/,
                     u.GetString(52)/*epsmmcsoutput*/,
                     u.GetString(54)/*epsmmcsfilename*/,
                     u.GetDecimal(170)/*valueCostTotal*/,
                     u.GetDecimal(171)/*noTaxValueCostTotal*/,
                     u.GetDateTime(203)/*fullfillmentDate*/,
                     u.GetDateTime(204)/*estimatedFulfillmentDate*/,
                     u.GetGuid(202)/*parentCartId*/,
                     u.GetInt32(12)/*backorderedqty*/,
                     u.GetInt32(13)/*canceledQty*/,
                     u.GetString(174)/*customLineNumber*/,
                     u.GetInt32(205)/*kitAllocationId*/,
                     u.GetInt32(206)/*kitQty*/,
                     u.GetBoolean(207)/*showAsSeperateLineOnInvoice*/,
                     u.GetGuid(208)/*vendorItemKitAssignmentId*/,
                     u.GetGuid(209)/*kitAllocationCartId*/,
                     u.GetInt32(1)/*line_status*/
                 ));
             }
             /* add the last order */
             orders.Add(new Order(
                 orderId, orderDate, grandTotal, taxTotal, subTotal, shippingTotal, service1,
                 service2, manifest, purchaseOrder, discount, comment, paid, billToAddressId, closed,
                 canceled, paymentMethodId, termId, userId, orderNumber, creditMemo, scanned_order_image,
                 readyForExport, recalculatedOn, sessionId, soldBy, requisitionedBy, approvedBy, deliverBy,
                 vendor_accountNo, FOB, parentOrderId, lines, order_status, cn, ftrns
             ));
             /* now all the shipments that belong to the orders */
             u.NextResult();
             while(u.Read()) {
                 int shipmentOrderId = u.GetInt32(0);
                 /* find the order that goes to this shipment */
                 Commerce.Order sOrd = orders.Find(delegate(Commerce.Order ord) {
                     return ord.OrderId == shipmentOrderId;
                 });
                 if(sOrd == null) { continue; }
                 /*
                 cart.orderId,addressUpdateId,cart.shipmentNumber,tracking,
                 dateShipped,actualWeight,actualService,actualCost,
                 actualBilledWeight,packageLength,packageWidth,
                 packageHeight,thirdPartyAccount,voidStatus,
                 emailSent,addDate
                 */
                 Shipment shp = new Shipment(sOrd.ShipToAddress, sOrd,
                 u.GetGuid(1), u.GetString(2), u.GetString(3),
                 u.GetString(4), u.GetString(5),
                 u.GetString(6), u.GetString(7),
                 u.GetString(8), u.GetString(9),
                 u.GetString(10), u.GetString(11),
                 u.GetString(12), u.GetString(13),
                 u.GetDateTime(14), u.GetDateTime(15));
                 sOrd.Shipments.Add(shp);
             }
             /* next batch... line detail
             cartDetailId, cartDetail.cartId,
             inputName, value, cartDetail.sessionId */
             u.NextResult();
             while(u.Read()) {
                 LineDetail lineDetail = new LineDetail(
                     u.GetGuid(0),
                     u.GetGuid(1),
                     u.GetGuid(4),
                     u.GetString(2),
                     u.GetString(3)
                 );
                 /* find the line to attach this line detail to */
                 Line line = lines.Find(delegate(Commerce.Line l) {
                     return l.CartId == lineDetail.CartId;
                 });
                 if(line != null) {
                     line.LineDetail.Add(lineDetail);
                 }
             }
             /* next batch... form source
             * order_line_forms.cartId, sourceCode, formName  */
             u.NextResult();
             while(u.Read()) {
                 Guid id = u.GetGuid(0);
                 Line line = lines.Find(delegate(Commerce.Line l) {
                     return l.CartId == id;
                 });
                 if(line != null) {
                     if(u.IsDBNull(1)) {
                         line.SourceCode = "";
                         line.FormName = "NO FORM";
                     } else {
                         line.SourceCode = u.GetString(1);
                         line.FormName = u.GetString(2);
                     }
                 }
             }
         }
     }
     return orders;
 }
Exemplo n.º 37
0
        public void CanCreateShipment()
        {
            var shipment = new Shipment(ImportNotificationId, period, quantity, 50);

            Assert.IsType<Shipment>(shipment);
        }
 internal Money CalculateShippingCostSubTotal(Shipment shipment, CartHelper cartHelper)
 {
     return CalculateShippingCostSubTotal(new List<Shipment>(1) { shipment }, cartHelper);
 }
Exemplo n.º 39
0
 /// <summary>
 /// Inserts a shipment
 /// </summary>
 /// <param name="shipment">Shipment</param>
 public void InsertShipment([FromBody] Shipment shipment)
 {
     _shipmentService.InsertShipment(shipment);
 }
        public virtual async Task <(Shipment shipment, decimal?totalWeight)> PrepareShipment(Order order, IList <OrderItem> orderItems, IFormCollection form)
        {
            Shipment shipment    = null;
            decimal? totalWeight = null;

            foreach (var orderItem in orderItems)
            {
                //is shippable
                var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId);

                if (!product.IsShipEnabled)
                {
                    continue;
                }

                //ensure that this product can be shipped (have at least one item to ship)
                var maxQtyToAdd = await orderItem.GetTotalNumberOfItemsCanBeAddedToShipment(_orderService, _shipmentService);

                if (maxQtyToAdd <= 0)
                {
                    continue;
                }

                int qtyToAdd = 0; //parse quantity
                foreach (string formKey in form.Keys)
                {
                    if (formKey.Equals(string.Format("qtyToAdd{0}", orderItem.Id), StringComparison.OrdinalIgnoreCase))
                    {
                        int.TryParse(form[formKey], out qtyToAdd);
                        break;
                    }
                }

                string warehouseId = "";
                if (((product.ManageInventoryMethod == ManageInventoryMethod.ManageStock || product.ManageInventoryMethod == ManageInventoryMethod.ManageStockByAttributes) &&
                     product.UseMultipleWarehouses) || (product.ManageInventoryMethod == ManageInventoryMethod.ManageStockByBundleProducts))
                {
                    //multiple warehouses supported
                    //warehouse is chosen by a store owner
                    foreach (string formKey in form.Keys)
                    {
                        if (formKey.Equals(string.Format("warehouse_{0}", orderItem.Id), StringComparison.OrdinalIgnoreCase))
                        {
                            warehouseId = form[formKey];
                            break;
                        }
                    }
                }
                else
                {
                    //multiple warehouses are not supported
                    warehouseId = product.WarehouseId;
                }

                foreach (string formKey in form.Keys)
                {
                    if (formKey.Equals(string.Format("qtyToAdd{0}", orderItem.Id), StringComparison.OrdinalIgnoreCase))
                    {
                        int.TryParse(form[formKey], out qtyToAdd);
                        break;
                    }
                }

                //validate quantity
                if (qtyToAdd <= 0)
                {
                    continue;
                }
                if (qtyToAdd > maxQtyToAdd)
                {
                    qtyToAdd = maxQtyToAdd;
                }

                //ok. we have at least one item. let's create a shipment (if it does not exist)

                var orderItemTotalWeight = orderItem.ItemWeight.HasValue ? orderItem.ItemWeight * qtyToAdd : null;
                if (orderItemTotalWeight.HasValue)
                {
                    if (!totalWeight.HasValue)
                    {
                        totalWeight = 0;
                    }
                    totalWeight += orderItemTotalWeight.Value;
                }
                if (shipment == null)
                {
                    var trackingNumber = form["TrackingNumber"];
                    var adminComment   = form["AdminComment"];
                    shipment = new Shipment {
                        OrderId         = order.Id,
                        TrackingNumber  = trackingNumber,
                        TotalWeight     = null,
                        ShippedDateUtc  = null,
                        DeliveryDateUtc = null,
                        AdminComment    = adminComment,
                        CreatedOnUtc    = DateTime.UtcNow,
                        StoreId         = order.StoreId,
                    };
                    if (_workContext.CurrentVendor != null)
                    {
                        shipment.VendorId = _workContext.CurrentVendor.Id;
                    }
                }
                //create a shipment item
                var shipmentItem = new ShipmentItem {
                    ProductId    = orderItem.ProductId,
                    OrderItemId  = orderItem.Id,
                    Quantity     = qtyToAdd,
                    WarehouseId  = warehouseId,
                    AttributeXML = orderItem.AttributesXml
                };
                shipment.ShipmentItems.Add(shipmentItem);
            }
            return(shipment, totalWeight);
        }
        /// <summary>
        /// Saves the shipment data to the Database. If it exists in DB, it is edited; else it's added.
        /// </summary>
        public void SaveShipmentToDB()
        {
            using (var db = new Models.AppContext())
            {
                //create shipment entity and set props
                Entities.Shipment entShipment = new Shipment()
                {
                    ShipmentId = Shipment.ShipmentID, Boxes = new List <ShipmentBox>(), ShipmentDate = Shipment.ShipmentDate
                };

                //add each box one to entShipment entity
                foreach (var box in Shipment.Boxes)
                {
                    ShipmentBox entBox = new ShipmentBox
                    {
                        BoxContentString = box.FBALabel(),
                        BoxNumber        = box.BoxNumber,
                        BoxId            = box.BoxID,
                        Shipment         = entShipment
                    };

                    entShipment.Boxes.Add(entBox);
                }//end foreach loop

                //get amazon warehouse entity and set to ShipmentEntity
                AmazonWarehouse amz = db.AmazonWarehouses.Where(a => a.Id == Shipment.FullfillmentShipTo.Id).FirstOrDefault();
                entShipment.ShipToCenter = amz;

                //get company address entity and set to shipmententity
                CompanyAddress comp = db.CompanyAddresses.Where(c => c.Id == Shipment.CompanyShipFrom.Id).FirstOrDefault();
                entShipment.ShipFromCenter = comp;

                //check if shipment exists in the database
                if (db.Shipments.Any(s => s.ShipmentId == Shipment.ShipmentID))
                {
                    Shipment shipmentDel = db.Shipments.Find(Shipment.ShipmentID);


                    var bx = db.Boxes.Where((b => b.Shipment.ShipmentId == shipmentDel.ShipmentId)).ToList();

                    for (int i = 0; i < bx.Count(); i++)
                    {
                        db.Boxes.Remove(bx[i]);
                    }


                    db.SaveChanges();

                    //then delete the shipment with shipmentID
                    db.Shipments.Remove(shipmentDel);

                    //finally add the shipment back into shipments table
                    db.Shipments.Add(entShipment);
                }
                else
                {
                    //add shipment to DB and save
                    db.Shipments.Add(entShipment);
                }


                db.SaveChanges();
            }
        }
        public virtual async Task <ShipmentModel> PrepareShipmentModel(Shipment shipment, bool prepareProducts, bool prepareShipmentEvent = false)
        {
            //measures
            var baseWeight = await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId);

            var baseWeightIn  = baseWeight != null ? baseWeight.Name : "";
            var baseDimension = await _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId);

            var baseDimensionIn = baseDimension != null ? baseDimension.Name : "";
            var order           = await _orderService.GetOrderById(shipment.OrderId);

            var model = new ShipmentModel {
                Id                = shipment.Id,
                ShipmentNumber    = shipment.ShipmentNumber,
                OrderId           = shipment.OrderId,
                OrderNumber       = order != null ? order.OrderNumber : 0,
                TrackingNumber    = shipment.TrackingNumber,
                TotalWeight       = shipment.TotalWeight.HasValue ? string.Format("{0:F2} [{1}]", shipment.TotalWeight, baseWeightIn) : "",
                ShippedDate       = shipment.ShippedDateUtc.HasValue ? _dateTimeHelper.ConvertToUserTime(shipment.ShippedDateUtc.Value, DateTimeKind.Utc) : new DateTime?(),
                ShippedDateUtc    = shipment.ShippedDateUtc,
                CanShip           = !shipment.ShippedDateUtc.HasValue,
                DeliveryDate      = shipment.DeliveryDateUtc.HasValue ? _dateTimeHelper.ConvertToUserTime(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc) : new DateTime?(),
                DeliveryDateUtc   = shipment.DeliveryDateUtc,
                CanDeliver        = shipment.ShippedDateUtc.HasValue && !shipment.DeliveryDateUtc.HasValue,
                AdminComment      = shipment.AdminComment,
                GenericAttributes = shipment.GenericAttributes
            };

            if (prepareProducts)
            {
                foreach (var shipmentItem in shipment.ShipmentItems)
                {
                    var orderItem = order.OrderItems.Where(x => x.Id == shipmentItem.OrderItemId).FirstOrDefault();
                    if (orderItem == null)
                    {
                        continue;
                    }

                    if (_workContext.CurrentVendor != null)
                    {
                        if (orderItem.VendorId != _workContext.CurrentVendor.Id)
                        {
                            continue;
                        }
                    }

                    //quantities
                    var qtyInThisShipment = shipmentItem.Quantity;
                    var maxQtyToAdd       = await orderItem.GetTotalNumberOfItemsCanBeAddedToShipment(_orderService, _shipmentService);

                    var qtyOrdered        = shipmentItem.Quantity;
                    var qtyInAllShipments = await orderItem.GetTotalNumberOfItemsInAllShipment(_orderService, _shipmentService);

                    var product = await _productService.GetProductByIdIncludeArch(orderItem.ProductId);

                    if (product != null)
                    {
                        var warehouse = await _shippingService.GetWarehouseById(shipmentItem.WarehouseId);

                        var shipmentItemModel = new ShipmentModel.ShipmentItemModel {
                            Id                     = shipmentItem.Id,
                            OrderItemId            = orderItem.Id,
                            ProductId              = orderItem.ProductId,
                            ProductName            = product.Name,
                            Sku                    = product.FormatSku(orderItem.AttributesXml, _productAttributeParser),
                            AttributeInfo          = orderItem.AttributeDescription,
                            ShippedFromWarehouse   = warehouse != null ? warehouse.Name : null,
                            ShipSeparately         = product.ShipSeparately,
                            ItemWeight             = orderItem.ItemWeight.HasValue ? string.Format("{0:F2} [{1}]", orderItem.ItemWeight, baseWeightIn) : "",
                            ItemDimensions         = string.Format("{0:F2} x {1:F2} x {2:F2} [{3}]", product.Length, product.Width, product.Height, baseDimensionIn),
                            QuantityOrdered        = qtyOrdered,
                            QuantityInThisShipment = qtyInThisShipment,
                            QuantityInAllShipments = qtyInAllShipments,
                            QuantityToAdd          = maxQtyToAdd,
                        };

                        model.Items.Add(shipmentItemModel);
                    }
                }
            }

            if (prepareShipmentEvent && !String.IsNullOrEmpty(shipment.TrackingNumber))
            {
                var srcm = _shippingService.LoadShippingRateComputationMethodBySystemName(order.ShippingRateComputationMethodSystemName);
                if (srcm != null &&
                    srcm.PluginDescriptor.Installed &&
                    srcm.IsShippingRateComputationMethodActive(_shippingSettings))
                {
                    var shipmentTracker = srcm.ShipmentTracker;
                    if (shipmentTracker != null)
                    {
                        model.TrackingNumberUrl = await shipmentTracker.GetUrl(shipment.TrackingNumber);

                        if (_shippingSettings.DisplayShipmentEventsToStoreOwner)
                        {
                            var shipmentEvents = await shipmentTracker.GetShipmentEvents(shipment.TrackingNumber);

                            if (shipmentEvents != null)
                            {
                                foreach (var shipmentEvent in shipmentEvents)
                                {
                                    var shipmentStatusEventModel = new ShipmentModel.ShipmentStatusEventModel();
                                    var shipmentEventCountry     = await _countryService.GetCountryByTwoLetterIsoCode(shipmentEvent.CountryCode);

                                    shipmentStatusEventModel.Country = shipmentEventCountry != null
                                        ? shipmentEventCountry.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id)
                                        : shipmentEvent.CountryCode;

                                    shipmentStatusEventModel.Date      = shipmentEvent.Date;
                                    shipmentStatusEventModel.EventName = shipmentEvent.EventName;
                                    shipmentStatusEventModel.Location  = shipmentEvent.Location;
                                    model.ShipmentStatusEvents.Add(shipmentStatusEventModel);
                                }
                            }
                        }
                    }
                }
            }

            return(model);
        }
        protected virtual async Task <object> CreateModelPartAsync(Shipment part, MessageContext messageContext)
        {
            Guard.NotNull(messageContext, nameof(messageContext));
            Guard.NotNull(part, nameof(part));

            var itemParts = new List <object>();

            // TODO: (mh) (core) Uncomment when IOrderService is available.
            //var orderService = _services.Resolve<IOrderService>();
            //var orderItems = orderService.GetOrderItemsByOrderIds(new int[] { part.OrderId })[part.OrderId];
            //var orderItemsDic = orderItems.ToDictionarySafe(x => x.Id);

            //foreach (var shipmentItem in part.ShipmentItems)
            //{
            //    if (orderItemsDic.TryGetValue(shipmentItem.OrderItemId, out var orderItem) && orderItem.Product != null)
            //    {
            //        var itemPart = CreateModelPart(orderItem, messageContext) as Dictionary<string, object>;
            //        itemPart["Qty"] = shipmentItem.Quantity;

            //        itemParts.Add(itemPart);
            //    }
            //}

            var trackingUrl = part.TrackingUrl;

            if (trackingUrl.IsEmpty() && part.TrackingNumber.HasValue() && part.Order.ShippingRateComputationMethodSystemName.HasValue())
            {
                // Try to get URL from tracker.
                var srcm = _services.Resolve <IShippingService>()
                           .LoadActiveShippingRateComputationMethods(systemName: part.Order.ShippingRateComputationMethodSystemName)
                           .FirstOrDefault();

                if (srcm != null && srcm.Value.IsActive)
                {
                    var tracker = srcm.Value.ShipmentTracker;
                    if (tracker != null)
                    {
                        var shippingSettings = await _services.SettingFactory.LoadSettingsAsync <ShippingSettings>(part.Order.StoreId);

                        if (srcm.IsShippingRateComputationMethodActive(shippingSettings))
                        {
                            trackingUrl = tracker.GetUrl(part.TrackingNumber);
                        }
                    }
                }
            }

            var m = new Dictionary <string, object>
            {
                { "Id", part.Id },
                { "TrackingNumber", part.TrackingNumber.NullEmpty() },
                { "TrackingUrl", trackingUrl.NullEmpty() },
                { "TotalWeight", part.TotalWeight },
                { "CreatedOn", ToUserDate(part.CreatedOnUtc, messageContext) },
                { "DeliveredOn", ToUserDate(part.DeliveryDateUtc, messageContext) },
                { "ShippedOn", ToUserDate(part.ShippedDateUtc, messageContext) },
                { "Url", BuildActionUrl("ShipmentDetails", "Order", new { id = part.Id, area = "" }, messageContext) },
                { "Items", itemParts },
            };

            await PublishModelPartCreatedEventAsync(part, m);

            return(m);
        }
Exemplo n.º 44
0
 public void Insert(Shipment shipment)
 {
     shipmentRepository.Insert(shipment);
     unitOfWork.SaveChanges();
 }
Exemplo n.º 45
0
        // [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "OrderID,OrderDate,OrderQty,RemainQty,CustomerID,ProductID,OrderCode,DeletedFlag,CarrierID,VehicleID,OrderStatusID,OrderDeliveryDT")] Order order, FormCollection formCollection)
        {
            try {
                if (ModelState.IsValid)
                {
                    if (order.OrderID.Equals(0))
                    {
                        var shipment = new Shipment()
                        {
                            ProductID        = order.ProductID,
                            IsManual         = false,
                            CreatedDate      = DateTime.Now,
                            CreatedBy        = User.Identity.Name,
                            ModifiedDate     = DateTime.Now,
                            ModifiedBy       = User.Identity.Name,
                            ShipmentStatusID = 1,
                            OrderID          = order.OrderID,
                            CustomerName     = formCollection["Customer.CustomerName"],
                            CarrierName      = formCollection["Carrier.CarrierName"],
                            VehicleCode      = formCollection["Vehicle.VehicleCode"],
                            DriverName       = formCollection["Vehicle.Driver.DriverName"],
                            DriverCNIC       = formCollection["Vehicle.Driver.CNIC"]
                        };
                        ///////////////////////////////////////////////////////////////
                        order.CreatedDate  = DateTime.Now;
                        order.CreatedBy    = User.Identity.Name;
                        order.ModifiedDate = DateTime.Now;
                        order.ModifiedBy   = User.Identity.Name;
                        db.Orders.Add(order);
                        //////////////////////////////////////////////////////////////
                        db.Shipments.Add(shipment);
                        db.SaveChanges();
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        Shipment ship = db.Shipments.Where(x => x.OrderID == order.OrderID).FirstOrDefault <Shipment>();
                        ship.ModifiedDate = DateTime.Now;
                        ship.ModifiedBy   = User.Identity.Name;
                        ship.CustomerName = formCollection["Customer.CustomerName"];
                        ship.CarrierName  = formCollection["Carrier.CarrierName"];
                        ship.VehicleCode  = formCollection["Vehicle.VehicleCode"];
                        ship.DriverName   = formCollection["Vehicle.Driver.DriverName"];
                        ship.DriverCNIC   = formCollection["Vehicle.Driver.CNIC"];
                        ship.ProductID    = order.ProductID;
                        db.Shipments.Attach(ship);
                        db.Entry(ship).Property(x => x.ModifiedDate).IsModified = true;
                        db.Entry(ship).Property(x => x.ModifiedBy).IsModified   = true;
                        db.Entry(ship).Property(x => x.CustomerName).IsModified = true;
                        db.Entry(ship).Property(x => x.CarrierName).IsModified  = true;
                        db.Entry(ship).Property(x => x.VehicleCode).IsModified  = true;
                        db.Entry(ship).Property(x => x.DriverName).IsModified   = true;
                        db.Entry(ship).Property(x => x.DriverCNIC).IsModified   = true;
                        db.Entry(ship).Property(x => x.ProductID).IsModified    = true;
                        db.Entry(ship).State = EntityState.Modified;
                        /////////////////////////////////////////////////////////////////////////////////////
                        order.ModifiedDate    = DateTime.Now;
                        order.ModifiedBy      = User.Identity.Name;
                        db.Entry(order).State = EntityState.Modified;
                        db.Entry(order).Property(x => x.CreatedDate).IsModified = false;
                        db.Entry(order).Property(x => x.CreatedBy).IsModified   = false;
                        ////////////////////////////////////////////////////////////////////////////////////
                        db.SaveChanges();
                        return(RedirectToAction("Index"));
                    }
                }
                else
                {
                    var errors = ModelState.Values.SelectMany(v => v.Errors);
                }
            }
            catch
            {
                TempData["CustomError"] = "Order Code is not Unique";
                return(RedirectToAction("Index"));
            }

            ViewBag.CarrierID     = new SelectList(db.Carriers, "CarrierID", "CarrierName", order.CarrierID);
            ViewBag.CustomerID    = new SelectList(db.Customers, "CustomerID", "CustomerName", order.CustomerID);
            ViewBag.ProductID     = new SelectList(db.Products, "ProductID", "ProductName", order.ProductID);
            ViewBag.OrderStatusID = new SelectList(db.OrderStatus, "ID", "Status", order.OrderStatusID);
            ViewBag.VehicleID     = new SelectList(db.Vehicles, "VehicleID", "VehicleCode", order.VehicleID);
            return(View(order));
        }
Exemplo n.º 46
0
 public void Update(Shipment shipment)
 {
     shipmentRepository.Update(shipment);
     unitOfWork.SaveChanges();
 }
Exemplo n.º 47
0
 public ShipmentEventsPresenter(Shipment shipment) => Shipment = shipment;
Exemplo n.º 48
0
        public void Can_Create_A_Customer_Invoice_And_Order()
        {
            // Adding the shipmethod is typically done in the back office through the UI.
            // Interested in the use case to dynamically add theses?
            var key = Constants.ProviderKeys.Shipping.FixedRateShippingProviderKey;
            var defaultCatalogKey = Constants.DefaultKeys.Warehouse.DefaultWarehouseCatalogKey;

            // this would have to be done through the back office as it uses an internal service
            var us        = MerchelloContext.Current.Services.StoreSettingService.GetCountryByCode("US");
            var usCountry = new ShipCountry(defaultCatalogKey, us);

            ((ServiceContext)MerchelloContext.Current.Services).ShipCountryService.Save(usCountry);

            // we can use this later.
            var rateTableProvider = (FixedRateShippingGatewayProvider)MerchelloContext.Current.Gateways.Shipping.GetProviderByKey(key);

            // again usually done in the back office
            if (!rateTableProvider.ShipMethods.Any())
            {
                // creates the rate table for ship rate quotes
                var gwShipmeMethod = (FixedRateShippingGatewayMethod)rateTableProvider.CreateShipMethod(FixedRateShippingGatewayMethod.QuoteType.VaryByWeight, usCountry, "Ground (Vary by Weight)");
                gwShipmeMethod.RateTable.AddRow(0, 10, 5);
                gwShipmeMethod.RateTable.AddRow(10, 15, 10); // total weight should be 10M so we should hit this tier
                gwShipmeMethod.RateTable.AddRow(15, 25, 25);
                gwShipmeMethod.RateTable.AddRow(25, 10000, 100);
                rateTableProvider.SaveShippingGatewayMethod(gwShipmeMethod);
            }



            // Get the persisted customer
            const string loginName = "rusty";

            var customerService = MerchelloContext.Current.Services.CustomerService;

            var customer = customerService.GetByLoginName(loginName)
                           ?? customerService.CreateCustomerWithKey(loginName, "Rusty", "Swayne", "*****@*****.**");

            // I'll use this for billing and shipping
            var billingAddress = new Address()
            {
                Name        = "Mindfly Web Design Studio",
                Address1    = "114 W. Magnolia St. Suite 300",
                Locality    = "Bellingham",
                Region      = "WA",
                PostalCode  = "98225",
                CountryCode = "US"
            };

            // Most of the time this information is brought in from the IProductVariant - but the idea is you can
            // describe things on the fly
            var extendedData = new ExtendedDataCollection();

            // this is used to determine where a shipment originates
            extendedData.SetValue(Constants.ExtendedDataKeys.WarehouseCatalogKey, defaultCatalogKey.ToString());
            // items set to shippable
            extendedData.SetValue(Constants.ExtendedDataKeys.TrackInventory, "false");
            extendedData.SetValue(Constants.ExtendedDataKeys.Shippable, "true");
            extendedData.SetValue(Constants.ExtendedDataKeys.Weight, "1.25");
            extendedData.SetValue(Constants.ExtendedDataKeys.CurrencyCode, "USD");

            var item = new InvoiceLineItem(LineItemType.Product, "My product", "mySku", 2, 10M, extendedData);

            var invoiceService = MerchelloContext.Current.Services.InvoiceService;

            var invoice = invoiceService.CreateInvoice(Constants.DefaultKeys.InvoiceStatus.Unpaid);

            // I'd say we need to add a parameter to the service so we don't have to do this
            // http://issues.merchello.com/youtrack/issue/M-434
            ((Invoice)invoice).CustomerKey = customer.Key;

            // The version key is useful in some cases to invalidate shipping quotes or taxation calculations
            invoice.VersionKey = Guid.NewGuid();

            invoice.Items.Add(item);

            // at this point the invoice is not saved and we don't have an invoice number
            // however, we may want to quote shipping so we need a shipment

            // Shipment Statuses are new in 1.5.0
            var warehouse = MerchelloContext.Current.Services.WarehouseService.GetDefaultWarehouse();

            var shipmentStatus =
                MerchelloContext.Current.Services.ShipmentService.GetShipmentStatusByKey(
                    Constants.DefaultKeys.ShipmentStatus.Quoted);

            // since we know all the items in the invoice will be shipped we don't need to filter
            var shipment = new Shipment(shipmentStatus, warehouse.AsAddress(), billingAddress, invoice.Items);

            // since we already know the shipping provider we want from above we can do
            var quotes = rateTableProvider.QuoteShippingGatewayMethodsForShipment(shipment);

            // if we wanted Merchello to get quotes from all shipping providers we'd do the following
            // var quotes = shipment.ShipmentRateQuotes();

            if (quotes.Any())
            {
                // this check makes certain a quote was returned.  For example if the collection of items was outside the allowable
                // weight range, the provider would not return a quote.

                // Add the first quote to the invoice.

                invoice.Items.Add(quotes.FirstOrDefault().AsLineItemOf <InvoiceLineItem>());
            }

            // you do need to update the total ... this is usually done in the InvoiceBuilder in
            // instantiated by a SalesPreparation sub class
            var charges   = invoice.Items.Where(x => x.LineItemType != LineItemType.Discount).Sum(x => x.TotalPrice);
            var discounts = invoice.Items.Where(x => x.LineItemType == LineItemType.Discount).Sum(x => x.TotalPrice);

            // total the invoice
            decimal converted;

            invoice.Total = decimal.TryParse((charges - discounts).ToString(CultureInfo.InvariantCulture), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture.NumberFormat, out converted) ? converted : 0;

            // Now we save the invoice since we have to have a real record of something to collect a payment against
            // This also generates the invoice number
            invoiceService.Save(invoice);

            Console.WriteLine(invoice.InvoiceNumber);

            // cash payment method
            var cashProvider = MerchelloContext.Current.Gateways.Payment.GetProviderByKey(Constants.ProviderKeys.Payment.CashPaymentProviderKey);

            if (cashProvider != null)
            {
                var cash = cashProvider.PaymentMethods.FirstOrDefault(); // default install has a single payment method "Cash"

                // I usually Authorize a cash payment if taken online since we don't really see the money.  Capture is used
                // when the money comes in.  In your inquiry, it looks like you are assuming the money is in hand at the
                // time of the purchase, so we'll use AuthorizeCapture straight away.

                var attempt = invoice.AuthorizeCapturePayment(cash.Key);

                if (!attempt.Payment.Success)
                {
                    // handle the error
                }

                // otherwise you'll notice
                var approved = attempt.ApproveOrderCreation; // equals true

                // the order will be automatically created by the event handler in Merchello.Core.Gateways.GatewayEvents

                // however in this test I don't have the event wired up so I have to do it manuall
                if (approved)
                {
                    var order = invoice.PrepareOrder();
                    MerchelloContext.Current.Services.OrderService.Save(order);

                    var items = order.Items;
                }
            }
            // Cash provider is not active
        }
Exemplo n.º 49
0
        internal void ReadShippingNotification(string editext) {
            string trackingcode = "";
            string purchaseOrderID = "";
            string shipmentNumber = "";
            string weight = "";
            Cart order = new Cart();
            List<Shipment> shipments = new List<Shipment>();
            DateTime shipdate = DateTime.Now;
            Settings settings = new Settings();
            string EDIPOPreface = settings.Get("EDIPOPreface");

            List<string> edilines = editext.Split('~').ToList<string>();
            foreach (string line in edilines) {
                List<string> lineelements = line.Split('*').ToList<string>();
                switch (lineelements[0]) {
                    case "ST":
                        // Beginning of invoice
                        order = new Cart();
                        shipments = new List<Shipment>();
                        weight = "";
                        break;
                    case "BSN":
                        // Original Shipment Number from Shipper
                        shipmentNumber = lineelements[2];
                        break;
                    case "PRF":
                        // Purchase Order Reference
                        purchaseOrderID = lineelements[1];
                        if (EDIPOPreface != "") {
                            purchaseOrderID = purchaseOrderID.Replace(EDIPOPreface, "");
                        }
                        break;
                    case "REF":
                        // Tracking Code reference
                        trackingcode = lineelements[2];
                        Shipment shipment = new Shipment {
                            tracking_number = trackingcode
                        };
                        shipments.Add(shipment);
                        break;
                    case "DTM":
                        shipdate = Convert.ToDateTime(lineelements[2].Substring(4, 2) + "/" + lineelements[2].Substring(6, 2) + "/20" + lineelements[2].Substring(2, 2));
                        break;
                    case "TD1":
                        weight = lineelements[7] + " " + lineelements[8];
                        break;
                    case "SE":
                        // End of Invoice
                        try {
                            order = new Cart().GetByPaymentID(Convert.ToInt32(purchaseOrderID));
                            order.SetStatus((int)OrderStatuses.Shipped);
                            foreach (Shipment s in shipments) {
                                s.order_id = order.ID;
                                s.dateShipped = shipdate;
                                s.shipment_number = shipmentNumber;
                                s.weight = weight;
                            }
                            EcommercePlatformDataContext db = new EcommercePlatformDataContext();
                            db.Shipments.InsertAllOnSubmit(shipments);
                            db.SubmitChanges();
                            order.SendShippingNotification();
                        } catch { }
                        break;
                }
            }
        }
Exemplo n.º 50
0
 public void ComposeInvoice(Shipment shipment)
 {
     if (shipment.RecipientPaysShipment == shipment.RecipientPaysTaxesDuties)
     {
         Invoice invoice = new Invoice();
         invoice.WaybillId = shipment.WaybillId;
         if (db.TrackingSystemRecords.Count() == 0)
         {
             invoice.ShipDate = DateTime.Now;
         }
         else
         {
             invoice.ShipDate = db.TrackingSystemRecords.Where(s => s.WaybillId == shipment.WaybillId).OrderBy(S => S.DateTimeOfRecord).First().DateTimeOfRecord;
         }
         ShippingAccount rec;
         if (shipment.RecipientPaysShipment)
         {
             rec = db.ShippingAccounts.Find(shipment.RecipientId);
         }
         else
         {
             rec = shipment.Sender;
         }
         invoice.ShippingAccountId = rec.ShippingAccountId;
         try
         {
             BusinessShippingAccount BSA = (BusinessShippingAccount)rec;
             invoice.RecipientName = BSA.ContactPersonName;
         }
         catch (Exception)
         {
             PersonalShippingAccount PSA = (PersonalShippingAccount)rec;
             invoice.RecipientName = PSA.FirstName + " " + PSA.LastName;
         }
         invoice.Origin        = shipment.Origin;
         invoice.Destination   = shipment.Destination;
         invoice.ServiceType   = shipment.ServiceType;
         invoice.InvoiceAmount = shipment.ShipmentFee + shipment.TotalTaxes + shipment.TotalDuties;
         db.Invoices.Add(invoice);
         db.SaveChanges();
     }
     else
     {
         Invoice invoice  = new Invoice();
         Invoice invoice2 = new Invoice();
         invoice.WaybillId  = shipment.WaybillId;
         invoice.ShipDate   = db.TrackingSystemRecords.Where(s => s.WaybillId == shipment.WaybillId).OrderBy(S => S.DateTimeOfRecord).First().DateTimeOfRecord;
         invoice2.WaybillId = shipment.WaybillId;
         invoice2.ShipDate  = db.TrackingSystemRecords.Where(s => s.WaybillId == shipment.WaybillId).OrderBy(S => S.DateTimeOfRecord).First().DateTimeOfRecord;
         ShippingAccount sen, rec;
         sen = shipment.Sender;
         rec = db.ShippingAccounts.Find(shipment.RecipientId);
         try
         {
             BusinessShippingAccount BSA = (BusinessShippingAccount)sen;
             invoice.RecipientName = BSA.ContactPersonName;
         }
         catch (Exception)
         {
             PersonalShippingAccount PSA = (PersonalShippingAccount)sen;
             invoice.RecipientName = PSA.FirstName + " " + PSA.LastName;
         }
         try
         {
             BusinessShippingAccount BSA = (BusinessShippingAccount)rec;
             invoice2.RecipientName = BSA.ContactPersonName;
         }
         catch (Exception)
         {
             PersonalShippingAccount PSA = (PersonalShippingAccount)rec;
             invoice2.RecipientName = PSA.FirstName + " " + PSA.LastName;
         }
         invoice.Origin       = shipment.Origin;
         invoice.Destination  = shipment.Destination;
         invoice.ServiceType  = shipment.ServiceType;
         invoice2.Origin      = shipment.Origin;
         invoice2.Destination = shipment.Destination;
         invoice2.ServiceType = shipment.ServiceType;
         if (shipment.RecipientPaysShipment)
         {
             invoice.InvoiceAmount  = shipment.ShipmentFee;
             invoice2.InvoiceAmount = shipment.TotalTaxes + shipment.TotalDuties;
         }
         else
         {
             invoice2.InvoiceAmount = shipment.ShipmentFee;
             invoice.InvoiceAmount  = shipment.TotalTaxes + shipment.TotalDuties;
         }
         db.Invoices.Add(invoice);
         db.Invoices.Add(invoice2);
         db.SaveChanges();
     }
 }
Exemplo n.º 51
0
        /// <summary>
        /// Creates a <see cref="IShipment"/> without persisting it to the database.
        /// </summary>
        /// <param name="shipmentStatus">
        /// The shipment status.
        /// </param>
        /// <param name="origin">
        /// The origin.
        /// </param>
        /// <param name="destination">
        /// The destination.
        /// </param>
        /// <param name="items">
        /// The items.
        /// </param>
        /// <param name="raiseEvents">
        /// Optional boolean indicating whether or not to raise events
        /// </param>
        /// <returns>
        /// The <see cref="IShipment"/>.
        /// </returns>
        public IShipment CreateShipment(IShipmentStatus shipmentStatus, IAddress origin, IAddress destination, LineItemCollection items, bool raiseEvents = true)
        {
            Mandate.ParameterNotNull(shipmentStatus, "shipmentStatus");
            Mandate.ParameterNotNull(origin, "origin");
            Mandate.ParameterNotNull(destination, "destination");
            Mandate.ParameterNotNull(items, "items");

            // Use the visitor to filter out and validate shippable line items
            var visitor = new ShippableProductVisitor();
            items.Accept(visitor);

            var lineItemCollection = new LineItemCollection();

            foreach (var item in visitor.ShippableItems)
            {
                lineItemCollection.Add(item);
            }

            var shipment = new Shipment(shipmentStatus, origin, destination, lineItemCollection)
                               {
                                   VersionKey = Guid.NewGuid()
                               };

            if (!raiseEvents)
            {
                return shipment;
            }

            Creating.RaiseEvent(new Events.NewEventArgs<IShipment>(shipment), this);
            return shipment;
        }
Exemplo n.º 52
0
        public void UpdateShipmentFee(int shipmentId, bool estimated)
        {
            decimal  fee      = 0;
            Shipment shipment = db.Shipments.Find(shipmentId);

            if (shipment != null)
            {
                foreach (var p in shipment.Packages)
                {
                    if (estimated)
                    {
                        ServiceType       st = db.ServiceTypes.Where(s => s.Type == shipment.ServiceType).Single();
                        PackageType       pt = p.PackageTypeSize.PackageType;
                        ServicePackageFee spf = db.ServicePackageFees.Where(s => s.ServiceTypeID == st.ServiceTypeID).Where(s => s.PackageTypeID == pt.PackageTypeID).Single();
                        decimal           PackageFee, FeePerKG, MinimumFee, MaximumWeight;
                        FeePerKG = spf.Fee;
                        try
                        {
                            MaximumWeight = p.PackageTypeSize.WeightLimit;
                        }
                        catch (Exception)
                        {
                            MaximumWeight = 0;
                        }

                        MinimumFee = spf.MinimumFee;
                        PackageFee = (decimal)p.EstimatedWeight * FeePerKG;
                        if (PackageFee < MinimumFee)
                        {
                            PackageFee = MinimumFee;
                        }
                        if (p.EstimatedWeight > MaximumWeight && MaximumWeight != 0)
                        {
                            PackageFee += spf.Penalty;
                        }
                        if (spf.PackageTypeID == 1)
                        {
                            PackageFee = MinimumFee;
                        }
                        fee += PackageFee;
                    }
                    else
                    {
                        ServiceType       st = db.ServiceTypes.Where(s => s.Type == shipment.ServiceType).Single();
                        PackageType       pt = p.PackageTypeSize.PackageType;
                        ServicePackageFee spf = db.ServicePackageFees.Where(s => s.ServiceTypeID == st.ServiceTypeID).Where(s => s.PackageTypeID == pt.PackageTypeID).Single();
                        decimal           PackageFee, FeePerKG, MinimumFee, MaximumWeight;
                        FeePerKG = spf.Fee;
                        try
                        {
                            MaximumWeight = p.PackageTypeSize.WeightLimit;
                        }
                        catch (Exception)
                        {
                            MaximumWeight = 0;
                        }

                        MinimumFee = spf.MinimumFee;
                        PackageFee = (decimal)p.Weight * FeePerKG;
                        if (PackageFee < MinimumFee)
                        {
                            PackageFee = MinimumFee;
                        }
                        if (p.Weight > MaximumWeight && MaximumWeight != 0)
                        {
                            PackageFee += spf.Penalty;
                        }
                        if (spf.PackageTypeID == 1)
                        {
                            PackageFee = MinimumFee;
                        }
                        fee += PackageFee;
                    }
                }
                Shipment ss = db.Shipments.Find(shipment.WaybillId);
                ss.ShipmentFee     = fee;
                db.Entry(ss).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
Exemplo n.º 53
0
 public Shipment Update(Shipment shipment)
 {
     _context.Shipment.Update(shipment);
     _context.SaveChanges();
     return(shipment);
 }
Exemplo n.º 54
0
        /// <summary>
        /// Prepare the shipment details model
        /// </summary>
        /// <param name="shipment">Shipment</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the shipment details model
        /// </returns>
        public virtual async Task <ShipmentDetailsModel> PrepareShipmentDetailsModelAsync(Shipment shipment)
        {
            if (shipment == null)
            {
                throw new ArgumentNullException(nameof(shipment));
            }

            var order = await _orderService.GetOrderByIdAsync(shipment.OrderId);

            if (order == null)
            {
                throw new Exception("order cannot be loaded");
            }
            var model = new ShipmentDetailsModel
            {
                Id = shipment.Id
            };

            if (shipment.ShippedDateUtc.HasValue)
            {
                model.ShippedDate = await _dateTimeHelper.ConvertToUserTimeAsync(shipment.ShippedDateUtc.Value, DateTimeKind.Utc);
            }
            if (shipment.ReadyForPickupDateUtc.HasValue)
            {
                model.ReadyForPickupDate = await _dateTimeHelper.ConvertToUserTimeAsync(shipment.ReadyForPickupDateUtc.Value, DateTimeKind.Utc);
            }
            if (shipment.DeliveryDateUtc.HasValue)
            {
                model.DeliveryDate = await _dateTimeHelper.ConvertToUserTimeAsync(shipment.DeliveryDateUtc.Value, DateTimeKind.Utc);
            }

            //tracking number and shipment information
            if (!string.IsNullOrEmpty(shipment.TrackingNumber))
            {
                model.TrackingNumber = shipment.TrackingNumber;
                var shipmentTracker = await _shipmentService.GetShipmentTrackerAsync(shipment);

                if (shipmentTracker != null)
                {
                    model.TrackingNumberUrl = await shipmentTracker.GetUrlAsync(shipment.TrackingNumber, shipment);

                    if (_shippingSettings.DisplayShipmentEventsToCustomers)
                    {
                        var shipmentEvents = await shipmentTracker.GetShipmentEventsAsync(shipment.TrackingNumber, shipment);

                        if (shipmentEvents != null)
                        {
                            foreach (var shipmentEvent in shipmentEvents)
                            {
                                var shipmentStatusEventModel = new ShipmentDetailsModel.ShipmentStatusEventModel();
                                var shipmentEventCountry     = await _countryService.GetCountryByTwoLetterIsoCodeAsync(shipmentEvent.CountryCode);

                                shipmentStatusEventModel.Country = shipmentEventCountry != null
                                    ? await _localizationService.GetLocalizedAsync(shipmentEventCountry, x => x.Name) : shipmentEvent.CountryCode;

                                shipmentStatusEventModel.Status    = shipmentEvent.Status;
                                shipmentStatusEventModel.Date      = shipmentEvent.Date;
                                shipmentStatusEventModel.EventName = shipmentEvent.EventName;
                                shipmentStatusEventModel.Location  = shipmentEvent.Location;
                                model.ShipmentStatusEvents.Add(shipmentStatusEventModel);
                            }
                        }
                    }
                }
            }

            //products in this shipment
            model.ShowSku = _catalogSettings.ShowSkuOnProductDetailsPage;
            foreach (var shipmentItem in await _shipmentService.GetShipmentItemsByShipmentIdAsync(shipment.Id))
            {
                var orderItem = await _orderService.GetOrderItemByIdAsync(shipmentItem.OrderItemId);

                if (orderItem == null)
                {
                    continue;
                }

                var product = await _productService.GetProductByIdAsync(orderItem.ProductId);

                var shipmentItemModel = new ShipmentDetailsModel.ShipmentItemModel
                {
                    Id              = shipmentItem.Id,
                    Sku             = await _productService.FormatSkuAsync(product, orderItem.AttributesXml),
                    ProductId       = product.Id,
                    ProductName     = await _localizationService.GetLocalizedAsync(product, x => x.Name),
                    ProductSeName   = await _urlRecordService.GetSeNameAsync(product),
                    AttributeInfo   = orderItem.AttributeDescription,
                    QuantityOrdered = orderItem.Quantity,
                    QuantityShipped = shipmentItem.Quantity,
                };
                //rental info
                if (product.IsRental)
                {
                    var rentalStartDate = orderItem.RentalStartDateUtc.HasValue
                        ? _productService.FormatRentalDate(product, orderItem.RentalStartDateUtc.Value) : "";
                    var rentalEndDate = orderItem.RentalEndDateUtc.HasValue
                        ? _productService.FormatRentalDate(product, orderItem.RentalEndDateUtc.Value) : "";
                    shipmentItemModel.RentalInfo = string.Format(await _localizationService.GetResourceAsync("Order.Rental.FormattedDate"),
                                                                 rentalStartDate, rentalEndDate);
                }
                model.Items.Add(shipmentItemModel);
            }

            //order details model
            model.Order = await PrepareOrderDetailsModelAsync(order);

            return(model);
        }
Exemplo n.º 55
0
 public Shipment Add(Shipment shipment)
 {
     _context.Shipment.Add(shipment);
     _context.SaveChanges();
     return(shipment);
 }
 /// <summary>
 /// Translates the specified request.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <param name="sourceShipment">The source shipment.</param>
 /// <param name="destinationShippingInfo">The destination shipping information.</param>
 protected override void Translate(TranslateShipmentToEntityRequest request, Shipment sourceShipment, ShippingInfo destinationShippingInfo)
 {
     base.Translate(request, sourceShipment, destinationShippingInfo);
     destinationShippingInfo.Properties.Add("ShippingMethodName", sourceShipment.ShippingMethodName);
 }
Exemplo n.º 57
0
        public virtual async Task FillFromQuoteRequestAsync(QuoteRequest quoteRequest)
        {
            EnsureCartExists();

            var productIds = quoteRequest.Items.Select(i => i.ProductId);
            var products   = await _catalogService.GetProductsAsync(productIds.ToArray(), ItemResponseGroup.ItemLarge);

            Cart.Items.Clear();
            foreach (var product in products)
            {
                var quoteItem = quoteRequest.Items.FirstOrDefault(i => i.ProductId == product.Id);
                if (quoteItem != null)
                {
                    var lineItem = product.ToLineItem(Cart.Language, (int)quoteItem.SelectedTierPrice.Quantity);
                    lineItem.Product   = product;
                    lineItem.ListPrice = quoteItem.ListPrice;
                    lineItem.SalePrice = quoteItem.SelectedTierPrice.Price;
                    if (lineItem.ListPrice < lineItem.SalePrice)
                    {
                        lineItem.ListPrice = lineItem.SalePrice;
                    }
                    lineItem.DiscountAmount = lineItem.ListPrice - lineItem.SalePrice;
                    lineItem.IsReadOnly     = true;
                    lineItem.Id             = null;
                    Cart.Items.Add(lineItem);
                }
            }

            if (quoteRequest.RequestShippingQuote)
            {
                Cart.Shipments.Clear();
                var shipment = new Shipment(Cart.Currency);

                if (quoteRequest.ShippingAddress != null)
                {
                    shipment.DeliveryAddress = quoteRequest.ShippingAddress;
                }

                if (quoteRequest.ShipmentMethod != null)
                {
                    var availableShippingMethods = await GetAvailableShippingMethodsAsync();

                    var availableShippingMethod = availableShippingMethods?.FirstOrDefault(sm => sm.ShipmentMethodCode == quoteRequest.ShipmentMethod.ShipmentMethodCode);

                    if (availableShippingMethod != null)
                    {
                        shipment = quoteRequest.ShipmentMethod.ToCartShipment(Cart.Currency);
                    }
                }
                Cart.Shipments.Add(shipment);
            }

            var payment = new Payment(Cart.Currency)
            {
                Amount = quoteRequest.Totals.GrandTotalInclTax
            };

            if (quoteRequest.BillingAddress != null)
            {
                payment.BillingAddress = quoteRequest.BillingAddress;
            }

            Cart.Payments.Clear();
            Cart.Payments.Add(payment);
        }
Exemplo n.º 58
0
 /// <summary>
 /// Deletes a shipment
 /// </summary>
 /// <param name="shipment">Shipment</param>
 public void DeleteShipment([FromBody] Shipment shipment)
 {
     _shipmentService.DeleteShipment(shipment);
 }
 internal Money CalculateShippingDiscounts(Shipment shipment, Currency currency, out string shippingDiscountMessage)
 {
     return CalculateShippingDiscounts(new List<Shipment>(1) { shipment }, currency, out shippingDiscountMessage);
 }
        public virtual async Task <IList <ShipmentModel.ShipmentNote> > PrepareShipmentNotes(Shipment shipment)
        {
            //shipment notes
            var shipmentNoteModels = new List <ShipmentModel.ShipmentNote>();

            foreach (var shipmentNote in (await _shipmentService.GetShipmentNotes(shipment.Id))
                     .OrderByDescending(on => on.CreatedOnUtc))
            {
                var download = await _downloadService.GetDownloadById(shipmentNote.DownloadId);

                shipmentNoteModels.Add(new ShipmentModel.ShipmentNote {
                    Id                = shipmentNote.Id,
                    ShipmentId        = shipment.Id,
                    DownloadId        = String.IsNullOrEmpty(shipmentNote.DownloadId) ? "" : shipmentNote.DownloadId,
                    DownloadGuid      = download != null ? download.DownloadGuid : Guid.Empty,
                    DisplayToCustomer = shipmentNote.DisplayToCustomer,
                    Note              = shipmentNote.Note,
                    CreatedOn         = _dateTimeHelper.ConvertToUserTime(shipmentNote.CreatedOnUtc, DateTimeKind.Utc),
                    CreatedByCustomer = shipmentNote.CreatedByCustomer
                });
            }
            return(shipmentNoteModels);
        }