public async Task <IActionResult> CompleteOrder(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." })); } // Order should first be paid before it can be set to completed. if (!orderInfoEnt.IsPaid) { return(BadRequest(new { Error = $"Order has not been paid yet." })); } // 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); // Make sure incoming status is completed only. Each status has its own controller. // Also make sure that the existing order status is set to ready and not already // completed. if (orderStatusName != Entities.Shared.OrderStatus.Completed.ToString() || orderInfoEnt.OrderStatus != Entities.Shared.OrderStatus.Ready) { return(BadRequest(new { Error = $"Invalid order status." })); } // Set accepted time to the current time var orderInfoMod = _ordMapper.OrderInfoEntityToModel(orderInfoEnt); orderInfoMod.DateTimeCompleted = DateTime.Now; // 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.NotifyOrderCompletedAsync(user.DeviceToken, restaurant.Name, order.Id); } catch (Exception) { } } } return(NoContent()); }