Example #1
0
        public void CancelOrder(Order order, string cancellationReason, bool finalize = false)
        {
            //get the fulfillments
            var fulfillments         = _orderFulfillmentService.Get(x => x.OrderId == order.Id).ToList();
            var warehouseIds         = fulfillments.Select(x => x.WarehouseId).ToList();
            var productIds           = fulfillments.Select(x => x.OrderItem.ProductId).ToList();
            var productVariantIds    = fulfillments.Select(x => x.OrderItem.ProductVariantId).ToList();
            var warehouseInventories = _warehouseInventoryService.Get(x =>
                                                                      warehouseIds.Contains(x.WarehouseId) &&
                                                                      (productVariantIds.Contains((int)x.ProductVariantId) || productIds.Contains(x.ProductId))).ToList();

            Transaction.Initiate(transaction =>
            {
                foreach (var fulfillment in fulfillments)
                {
                    var inventory = fulfillment.OrderItem.ProductVariantId > 0
                        ? warehouseInventories.FirstOrDefault(x =>
                                                              x.ProductVariantId == fulfillment.OrderItem.ProductVariantId)
                        : warehouseInventories.FirstOrDefault(x => x.ProductId == fulfillment.OrderItem.ProductId);

                    if (inventory == null)
                    {
                        continue;
                    }
                    inventory.ReservedQuantity -= fulfillment.Quantity; //clear from reserve
                    _warehouseInventoryService.Update(inventory, transaction);
                    _orderFulfillmentService.Delete(fulfillment, transaction);
                }

                order.OrderStatus = order.OrderTotal > 0 && !finalize
                    ? OrderStatus
                                    .PendingCancellation /*admin will cancel manually and refund or do whatever needs to be done*/
                    : OrderStatus.Cancelled;
                if (order.Remarks.IsNullEmptyOrWhiteSpace())
                {
                    order.Remarks = $"Cancellation Reason : {cancellationReason}";
                }
                else
                {
                    order.Remarks = order.Remarks + Environment.NewLine + $"Cancellation Reason : {cancellationReason}";;
                }
                _orderService.Update(order, transaction);
            });
        }