Spaces:
Paused
Paused
File size: 13,613 Bytes
70556b7 a8c9c0f 70556b7 f7ed2f8 70556b7 81ce36c 0e68faf 81ce36c 0e68faf 81ce36c 70556b7 f7ed2f8 3ea0aaa 70556b7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | using Application.Abstractions.Interfaces;
using Application.DTOs.OrderDTOs;
using Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RobDeliveryAPI.Extensions;
using System.Security.Claims;
using Application.Abstractions.Exceptions;
namespace RobDeliveryAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class OrderController : ControllerBase
{
private readonly IOrderService _orderService;
private readonly IFileService _fileService;
private readonly IWebHostEnvironment _environment;
public OrderController(
IOrderService orderService,
IFileService fileService,
IWebHostEnvironment environment)
{
_orderService = orderService;
_fileService = fileService;
_environment = environment;
}
/// <summary>
/// Get authenticated user ID from JWT token
/// </summary>
private int GetAuthenticatedUserId()
{
var userIdClaim = User.FindFirst("Id") ?? User.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out int userId))
{
throw new UnauthorizedAccessException("User ID not found in token");
}
return userId;
}
/// <summary>
/// Create a new order with optional images (uses authenticated user from JWT token)
/// </summary>
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> CreateOrder(
[FromForm] string name,
[FromForm] string description,
[FromForm] double weight,
[FromForm] decimal productPrice,
[FromForm] bool isProductPaid,
[FromForm] int recipientId,
[FromForm] int deliveryPayer,
IFormFileCollection? files = null)
{
try
{
int senderId = GetAuthenticatedUserId();
// Create order DTO
var orderDto = new CreateOrderDTO
{
Name = name,
Description = description,
Weight = weight,
ProductPrice = productPrice,
IsProductPaid = isProductPaid,
RecipientId = recipientId,
DeliveryPayer = (Entities.Models.DeliveryPayer)deliveryPayer
};
// Create order
var result = await _orderService.CreateOrderAsync(senderId, orderDto);
// Upload files if provided
if (files != null && files.Count > 0)
{
await _fileService.UploadOrderImagesAsync(result.Id, files.ToFileUploadDTOs(), _environment.ContentRootPath);
// Reload order with images
result = await _orderService.GetOrderByIdAsync(result.Id);
}
return CreatedAtAction(nameof(GetOrderById), new { id = result.Id }, result);
}
catch (UnauthorizedAccessException ex)
{
return Unauthorized(new { error = ex.Message });
}
catch (ArgumentException ex)
{
return BadRequest(new { error = ex.Message });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while creating the order", details = ex.Message });
}
}
/// <summary>
/// Estimate delivery price based on weight
/// </summary>
[HttpGet("estimate-price")]
public async Task<IActionResult> EstimateDeliveryPrice([FromQuery] double weight)
{
if (weight <= 0)
{
return BadRequest(new { error = "Weight must be greater than zero" });
}
var price = await _orderService.CalculateDeliveryPriceAsync(weight);
return Ok(new { deliveryPrice = price });
}
/// <summary>
/// Get order by ID
/// </summary>
[HttpGet("{id}")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetOrderById(int id)
{
try
{
var order = await _orderService.GetOrderByIdAsync(id);
if (order == null)
{
return NotFound(new { error = "Order not found" });
}
return Ok(order);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while retrieving the order", details = ex.Message });
}
}
/// <summary>
/// Get all orders
/// </summary>
[HttpGet]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetAllOrders()
{
try
{
var orders = await _orderService.GetAllOrdersAsync();
return Ok(orders);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while retrieving orders", details = ex.Message });
}
}
/// <summary>
/// Get all orders for authenticated user (sent and received)
/// </summary>
[HttpGet("my-orders")]
public async Task<IActionResult> GetMyOrders()
{
try
{
int userId = GetAuthenticatedUserId();
var orders = await _orderService.GetUserOrdersAsync(userId);
return Ok(orders);
}
catch (UnauthorizedAccessException ex)
{
return Unauthorized(new { error = ex.Message });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while retrieving user orders", details = ex.Message });
}
}
/// <summary>
/// Get all orders for a specific user (sent and received) - Admin only
/// </summary>
[HttpGet("user/{userId}")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetUserOrders(int userId)
{
try
{
var orders = await _orderService.GetUserOrdersAsync(userId);
return Ok(orders);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while retrieving user orders", details = ex.Message });
}
}
/// <summary>
/// Get orders sent by a specific user
/// </summary>
[HttpGet("sent/{senderId}")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetSentOrders(int senderId)
{
try
{
var orders = await _orderService.GetSentOrdersAsync(senderId);
return Ok(orders);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while retrieving sent orders", details = ex.Message });
}
}
/// <summary>
/// Get orders received by a specific user
/// </summary>
[HttpGet("received/{recipientId}")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetReceivedOrders(int recipientId)
{
try
{
var orders = await _orderService.GetReceivedOrdersAsync(recipientId);
return Ok(orders);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while retrieving received orders", details = ex.Message });
}
}
/// <summary>
/// Get orders by status
/// </summary>
[HttpGet("status/{status}")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetOrdersByStatus(OrderStatus status)
{
try
{
var orders = await _orderService.GetOrdersByStatusAsync(status);
return Ok(orders);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while retrieving orders by status", details = ex.Message });
}
}
/// <summary>
/// Update order status
/// </summary>
[HttpPatch]
public async Task<IActionResult> UpdateOrderStatus([FromBody] UpdateOrderStatusDTO updateDto)
{
try
{
var result = await _orderService.UpdateOrderStatusAsync(updateDto.OrderId, updateDto.NewStatus);
if (!result)
{
return NotFound(new { error = "Order not found" });
}
return Ok(new { message = "Order status updated successfully" });
}
catch (InvalidOperationException ex)
{
return BadRequest(new { error = ex.Message });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while updating order status", details = ex.Message });
}
}
/// <summary>
/// Assign a robot to an order
/// </summary>
[HttpPost("{id}/assign-robot")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> AssignRobotToOrder(int id, [FromBody] AssignRobotDTO assignDto)
{
try
{
var result = await _orderService.AssignRobotToOrderAsync(id, assignDto.RobotId);
if (!result)
{
return NotFound(new { error = "Order not found" });
}
return Ok(new { message = "Robot assigned successfully" });
}
catch (ArgumentException ex)
{
return BadRequest(new { error = ex.Message });
}
catch (InvalidOperationException ex)
{
return BadRequest(new { error = ex.Message });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while assigning robot", details = ex.Message });
}
}
/// <summary>
/// Cancel an order (only order sender can cancel)
/// </summary>
[HttpPost("{id}/cancel")]
public async Task<IActionResult> CancelOrder(int id)
{
try
{
int userId = GetAuthenticatedUserId();
var result = await _orderService.CancelOrderAsync(id, userId);
if (!result)
{
return NotFound(new { error = "Order not found" });
}
return Ok(new { message = "Order cancelled successfully" });
}
catch (UnauthorizedAccessException ex)
{
return StatusCode(403, new { error = ex.Message });
}
catch (InvalidOperationException ex)
{
return BadRequest(new { error = ex.Message });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while cancelling the order", details = ex.Message });
}
}
/// <summary>
/// Delete an order
/// </summary>
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteOrder(int id)
{
try
{
var result = await _orderService.DeleteOrderAsync(id);
if (!result)
{
return NotFound(new { error = "Order not found" });
}
return Ok(new { message = "Order deleted successfully" });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while deleting the order", details = ex.Message });
}
}
/// <summary>
/// Execute an order - automatically find and assign optimal drone with route calculation
/// </summary>
[HttpPost("{id}/execute")]
public async Task<IActionResult> ExecuteOrder(int id)
{
try
{
int userId = GetAuthenticatedUserId();
var result = await _orderService.ExecuteOrderAsync(id, userId);
return Ok(result);
}
catch (ArgumentException ex)
{
return NotFound(new { error = ex.Message });
}
catch (RoutingException ex)
{
return BadRequest(new {
error = ex.Message,
debugLogs = ex.DebugLogs
});
}
catch (InvalidOperationException ex)
{
return BadRequest(new { error = ex.Message });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "An error occurred while executing the order", details = ex.Message });
}
}
}
}
|