using FluentValidation; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Meezi.API.Models.Orders; using Meezi.API.Services; using Meezi.Core.Authorization; using Meezi.Core.Enums; using Meezi.Core.Interfaces; using Meezi.Shared; namespace Meezi.API.Controllers; [Route("api/cafes/{cafeId}/orders")] public class OrdersController : CafeApiControllerBase { private readonly IOrderService _orderService; private readonly IAuditLogService _audit; private readonly IValidator _createValidator; private readonly IValidator _statusValidator; private readonly IValidator _paymentsValidator; private readonly IValidator _appendValidator; private readonly IValidator _sessionValidator; private readonly IValidator _correctionValidator; public OrdersController( IOrderService orderService, IAuditLogService audit, IValidator createValidator, IValidator statusValidator, IValidator paymentsValidator, IValidator appendValidator, IValidator sessionValidator, IValidator correctionValidator) { _orderService = orderService; _audit = audit; _createValidator = createValidator; _statusValidator = statusValidator; _paymentsValidator = paymentsValidator; _appendValidator = appendValidator; _sessionValidator = sessionValidator; _correctionValidator = correctionValidator; } [HttpGet] public async Task GetOrders( string cafeId, [FromQuery] OrderStatus? status, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var data = await _orderService.GetOrdersAsync(cafeId, status, cancellationToken); return Ok(new ApiResponse>(true, data)); } [HttpGet("open")] public async Task GetOpenOrders( string cafeId, [FromQuery] string? search, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var data = await _orderService.GetOpenOrdersAsync(cafeId, search, cancellationToken); return Ok(new ApiResponse>(true, data)); } /// Closed orders (delivered/cancelled) of one Iran-calendar day — the /// browsing surface for اصلاح سند payment corrections. [HttpGet("closed")] public async Task GetClosedOrders( string cafeId, ITenantContext tenant, CancellationToken cancellationToken, [FromQuery] string? date = null, [FromQuery] string? branchId = null, [FromQuery] int page = 1, [FromQuery] int pageSize = 30) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; if (EnsureBranchAccess(branchId, tenant) is { } branchDenied) return branchDenied; DateOnly day; if (string.IsNullOrWhiteSpace(date)) day = IranCalendar.TodayInIran; else if (!DateOnly.TryParse(date, out day)) return BadRequest(new ApiResponse( false, null, new ApiError("VALIDATION_ERROR", "Invalid date (expected YYYY-MM-DD).", "date"))); if (page < 1) page = 1; if (pageSize is < 1 or > 100) pageSize = 30; var (items, total) = await _orderService.GetClosedOrdersAsync( cafeId, day, branchId, page, pageSize, cancellationToken); return Ok(new PagedApiResponse(true, items, new PagedMeta(total, page, pageSize))); } [HttpGet("live")] public async Task GetLiveOrders(string cafeId, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var data = await _orderService.GetLiveOrdersAsync(cafeId, cancellationToken); return Ok(new ApiResponse>(true, data)); } [HttpGet("{id}")] public async Task GetOrder(string cafeId, string id, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var data = await _orderService.GetOrderAsync(cafeId, id, cancellationToken); if (data is null) return NotFoundError(); return Ok(new ApiResponse(true, data)); } [HttpPost] public async Task CreateOrder( string cafeId, [FromBody] CreateOrderRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var validation = await _createValidator.ValidateAsync(request, cancellationToken); if (!validation.IsValid) return BadRequest(ValidationError(validation)); var result = await _orderService.CreateOrderAsync(cafeId, tenant, request, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); return Ok(new ApiResponse(true, result.Data)); } [HttpPost("{id}/items")] public async Task AppendItems( string cafeId, string id, [FromBody] AppendOrderItemsRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var validation = await _appendValidator.ValidateAsync(request, cancellationToken); if (!validation.IsValid) return BadRequest(ValidationError(validation)); var result = await _orderService.AppendOrderItemsAsync(cafeId, id, request, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); return Ok(new ApiResponse(true, result.Data)); } [HttpPatch("{id}/items/{itemId}/void")] [Authorize(Roles = "Manager,Owner")] public async Task VoidOrderItem( string cafeId, string id, string itemId, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; if (string.IsNullOrEmpty(tenant.UserId)) return StatusCode(StatusCodes.Status403Forbidden, new ApiResponse(false, null, new ApiError("FORBIDDEN", "User context required."))); var result = await _orderService.VoidOrderItemAsync(cafeId, id, itemId, tenant.UserId, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); await _audit.LogAsync(new AuditEntry { Category = "Order", Action = "ItemVoided", EntityType = "Order", EntityId = id, Summary = $"Voided a line item on order #{result.Data!.DisplayNumber}", Details = new { orderId = id, itemId, displayNumber = result.Data.DisplayNumber } }, cancellationToken); return Ok(new ApiResponse(true, result.Data)); } [HttpPost("{id}/transfer")] [Authorize(Roles = "Manager,Owner,Waiter")] public async Task TransferTable( string cafeId, string id, [FromBody] TransferTableRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var result = await _orderService.TransferTableAsync(cafeId, id, request.TargetTableId, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); return Ok(new ApiResponse(true, result.Data)); } [HttpPatch("{id}/session")] public async Task UpdateSession( string cafeId, string id, [FromBody] UpdateOrderSessionRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var validation = await _sessionValidator.ValidateAsync(request, cancellationToken); if (!validation.IsValid) return BadRequest(ValidationError(validation)); var result = await _orderService.UpdateOrderSessionAsync(cafeId, id, request, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); return Ok(new ApiResponse(true, result.Data)); } [HttpPatch("{id}/status")] public async Task UpdateStatus( string cafeId, string id, [FromBody] UpdateOrderStatusRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var validation = await _statusValidator.ValidateAsync(request, cancellationToken); if (!validation.IsValid) return BadRequest(ValidationError(validation)); var data = await _orderService.UpdateStatusAsync(cafeId, id, request.Status, cancellationToken); if (data is null) return NotFoundError(); return Ok(new ApiResponse(true, data)); } [HttpPost("{id}/cancel")] public async Task CancelOrder( string cafeId, string id, [FromBody] CancelOrderRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; if (EnsurePermission(tenant, Permission.ProcessOrders) is { } forbidden) return forbidden; var result = await _orderService.CancelOrderAsync( cafeId, id, request.Reason, tenant.UserId, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); await _audit.LogAsync(new AuditEntry { Category = "Order", Action = "OrderCancelled", EntityType = "Order", EntityId = id, Summary = $"Order #{result.Data!.DisplayNumber} cancelled" + (string.IsNullOrWhiteSpace(request.Reason) ? "" : $": {request.Reason!.Trim()}"), Details = new { orderId = id, displayNumber = result.Data.DisplayNumber, total = result.Data.Total, reason = request.Reason } }, cancellationToken); return Ok(new ApiResponse(true, result.Data)); } [HttpPost("{id}/payments")] public async Task RecordPayments( string cafeId, string id, [FromBody] RecordPaymentsRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; var validation = await _paymentsValidator.ValidateAsync(request, cancellationToken); if (!validation.IsValid) return BadRequest(ValidationError(validation)); var result = await _orderService.RecordPaymentsAsync( cafeId, id, request, tenant.UserId, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); var paidTotal = result.Data!.Sum(p => p.Amount); await _audit.LogAsync(new AuditEntry { Category = "Payment", Action = "PaymentRecorded", EntityType = "Order", EntityId = id, Summary = $"Recorded payment(s) totalling {paidTotal:0.##} on order", Details = new { orderId = id, total = paidTotal, methods = result.Data!.Select(p => new { p.Method, p.Amount }) } }, cancellationToken); return Ok(new ApiResponse>(true, result.Data)); } /// /// اصلاح سند — void wrongly-recorded payments and/or record replacements on a /// closed order, atomically, with a mandatory reason. Manager/Owner only; /// the full before/after is written to the immutable audit trail. /// [HttpPost("{id}/payments/corrections")] public async Task CorrectPayments( string cafeId, string id, [FromBody] CorrectPaymentsRequest request, ITenantContext tenant, CancellationToken cancellationToken) { if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied; if (EnsureManager(tenant) is { } forbidden) return forbidden; var validation = await _correctionValidator.ValidateAsync(request, cancellationToken); if (!validation.IsValid) return BadRequest(ValidationError(validation)); // Snapshot the payments before the change so the audit row carries a // complete before/after picture even after later corrections. var before = await _orderService.GetOrderAsync(cafeId, id, cancellationToken); var result = await _orderService.CorrectPaymentsAsync( cafeId, id, request, tenant.UserId, cancellationToken); if (!result.Success) return OrderError(result.ErrorCode!, result.Field); await _audit.LogAsync(new AuditEntry { Category = "Payment", Action = "PaymentCorrected", EntityType = "Order", EntityId = id, Summary = $"اصلاح سند: voided {request.VoidPaymentIds.Count} payment(s), " + $"recorded {request.Replacements.Count} replacement(s) — {request.Reason}", Details = new { orderId = id, displayNumber = result.Data!.DisplayNumber, reason = request.Reason, voidedPaymentIds = request.VoidPaymentIds, paymentsBefore = before?.Payments.Select(p => new { p.Id, p.Method, p.Amount, p.Status }), paymentsAfter = result.Data.Payments.Select(p => new { p.Id, p.Method, p.Amount, p.Status }), paidAmountAfter = result.Data.PaidAmount, orderTotal = result.Data.Total } }, cancellationToken); return Ok(new ApiResponse(true, result.Data)); } private IActionResult OrderError(string code, string? field = null) => code switch { "TABLE_NOT_AVAILABLE" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Table is not available for new orders.", field))), "TABLE_OCCUPIED" => Conflict(new ApiResponse( false, null, new ApiError(code, "Table already has an active order.", field))), "ORDER_NOT_OPEN" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Order is not open for changes.", field))), "ORDER_NOT_FOUND" => NotFound(new ApiResponse( false, null, new ApiError(code, "Order not found.", field))), "ORDER_ALREADY_CLOSED" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Order is already closed.", field))), "ORDER_ALREADY_CANCELLED" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Order is already cancelled.", field))), "ORDER_HAS_PAYMENTS" => Conflict(new ApiResponse( false, null, new ApiError(code, "Refund the recorded payments before cancelling this order.", field))), "ITEM_NOT_FOUND" => NotFound(new ApiResponse( false, null, new ApiError(code, "Line item not found.", field))), "ITEM_ALREADY_VOIDED" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Line item is already voided.", field))), "TABLE_NOT_FOUND" => NotFound(new ApiResponse( false, null, new ApiError(code, "Table not found.", field))), "TABLE_CLEANING" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Table is being cleaned.", field))), "NO_OPEN_SHIFT" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Open the cash register shift before taking payment.", field))), "PAYMENT_NOT_FOUND" => NotFound(new ApiResponse( false, null, new ApiError(code, "Payment not found on this order.", field))), "PAYMENT_ALREADY_REFUNDED" => BadRequest(new ApiResponse( false, null, new ApiError(code, "Payment is already refunded.", field))), _ => BadRequest(new ApiResponse( false, null, new ApiError(code, "Invalid order request.", field))) }; }