public async Task <IActionResult> CancelOrder(int orderInfoId, [FromBody] JsonPatchDocument <Models.OrderInfo> patchDoc) { if (patchDoc == null) { return(BadRequest()); } var orderInfoEnt = await _ordService.GetOrderInfoAsync(orderInfoId); if (orderInfoEnt == null) { return(NotFound(new { Error = $"Order info with the ID '{orderInfoId}' could not be found." })); } // This could become an attribute for all order related controller actions. if (orderInfoEnt.IsCancelled) { return(BadRequest(new { Error = "Order has been cancelled." })); } // Check that a valid OrderStatus Value was supplied. if (patchDoc.Operations.Count != 1 || !Enum.TryParse(typeof(OrderStatus), (string)patchDoc.Operations[0].value, out object newOrderStatus)) { return(BadRequest(new { Error = "Invalid order status name." })); } var orderStatus = (OrderStatus)newOrderStatus; // var orderStatusName = Enum.GetName(typeof(OrderStatus), orderStatus); // Also make sure that the existing order status is set to placed or accepted and not already // ready/completed/cancelled. if (orderInfoEnt.OrderStatus == Entities.Shared.OrderStatus.Ready || orderInfoEnt.OrderStatus == Entities.Shared.OrderStatus.Completed || orderInfoEnt.OrderStatus == Entities.Shared.OrderStatus.Cancelled) { return(BadRequest(new { Error = $"Invalid order status." })); } // Set cancelled time to the current time. ***Not yet implemented. var orderInfoMod = _ordMapper.OrderInfoEntityToModel(orderInfoEnt); orderInfoMod.DateTimeCancelled = DateTime.Now; orderInfoMod.IsCancelled = true; // Apply patchdoc to model patchDoc.ApplyTo(orderInfoMod); TryValidateModel(orderInfoMod); // Validation if (!ModelState.IsValid) { return(new UnprocessableEntityObjectResult(ModelState)); } // Map model back to entity _ordMapper.MapOrderInfoModelToEntity(orderInfoMod, orderInfoEnt); _ordService.UpdateOrderInfo(orderInfoEnt); if (!await _ordService.SaveOrderChangesAsync()) { throw new Exception($"Error updating order info with Id '{orderInfoEnt.Id}'."); } // Notift the user that the order has been accepted using Google Cloud Messaging var order = await _ordService.GetOrderAsync(orderInfoEnt.OrderId); var restaurant = await _restService.GetRestaurantAsync(order.RestaurantId); var user = await _ordUserService.GetOrdUserAsync(order.OrdUserId); if (order != null) { if (restaurant != null && user != null && user.DeviceToken != null) { try { // *** Send message here *** // await _fcmService.NotifyOrderCancelledAsync(user.DeviceToken, restaurant.Name, order.Id); } catch (Exception) { } } } return(NoContent()); }