Spaces:
Paused
Paused
File size: 12,392 Bytes
70556b7 e7a18fe 70556b7 0e68faf 3be30d5 70556b7 3be30d5 70556b7 0e68faf 3be30d5 70556b7 0e68faf 769004e 3be30d5 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 | using Application.Abstractions.Interfaces;
using Application.DTOs.AdminDTOs;
using Application.DTOs.UserDTOs;
using Application.DTOs.OrderDTOs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace RobDeliveryAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase
{
private readonly IAdminService _adminService;
private readonly ISettingsService _settingsService;
private readonly IUserService _userService;
private readonly IOrderService _orderService;
public AdminController(
IAdminService adminService,
ISettingsService settingsService,
IUserService userService,
IOrderService orderService)
{
_adminService = adminService;
_settingsService = settingsService;
_userService = userService;
_orderService = orderService;
}
/// <summary>
/// Get system statistics for dashboard
/// </summary>
[HttpGet("stats")]
public async Task<IActionResult> GetSystemStats()
{
try
{
var stats = await _adminService.GetSystemStatsAsync();
return Ok(stats);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to retrieve system stats", details = ex.Message });
}
}
/// <summary>
/// Export delivery history as JSON
/// </summary>
[HttpGet("export/delivery-history")]
public async Task<IActionResult> ExportDeliveryHistory()
{
try
{
var historyJson = await _adminService.ExportDeliveryHistoryAsync();
var fileName = $"DeliveryHistory_{DateTime.Now:yyyyMMdd_HHmmss}.json";
return File(
System.Text.Encoding.UTF8.GetBytes(historyJson),
"application/json",
fileName
);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to export delivery history", details = ex.Message });
}
}
/// <summary>
/// Create database backup
/// </summary>
[HttpPost("backup")]
public async Task<IActionResult> CreateBackup([FromBody] BackupRequestDTO request)
{
try
{
string backupPath = request.BackupPath ?? "Backups";
var success = await _adminService.CreateDatabaseBackupAsync(backupPath);
if (success)
{
return Ok(new { message = "Backup created successfully", path = backupPath });
}
else
{
return StatusCode(500, new { error = "Failed to create backup" });
}
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to create backup", details = ex.Message });
}
}
/// <summary>
/// Get robot efficiency analytics
/// </summary>
[HttpGet("analytics/robot-efficiency")]
public async Task<IActionResult> GetRobotEfficiency()
{
try
{
var efficiency = await _adminService.GetRobotEfficiencyAsync();
return Ok(efficiency);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to retrieve robot efficiency", details = ex.Message });
}
}
/// <summary>
/// Generate a new admin registration key
/// </summary>
[HttpPost("keys/generate")]
public async Task<IActionResult> GenerateAdminKey([FromBody] CreateAdminKeyDTO request)
{
try
{
var userIdClaim = User.FindFirst("Id")?.Value;
if (userIdClaim == null || !int.TryParse(userIdClaim, out int adminId))
{
return Unauthorized(new { error = "Invalid token" });
}
var adminKey = await _adminService.GenerateAdminKeyAsync(
adminId,
request.ExpiresAt,
request.Description
);
return Ok(new
{
message = "Admin key generated successfully",
key = adminKey
});
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to generate admin key", details = ex.Message });
}
}
/// <summary>
/// Get all admin keys
/// </summary>
[HttpGet("keys")]
public async Task<IActionResult> GetAllAdminKeys()
{
try
{
var keys = await _adminService.GetAllAdminKeysAsync();
return Ok(keys);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to retrieve admin keys", details = ex.Message });
}
}
/// <summary>
/// Get unused admin keys
/// </summary>
[HttpGet("keys/unused")]
public async Task<IActionResult> GetUnusedAdminKeys()
{
try
{
var keys = await _adminService.GetUnusedAdminKeysAsync();
return Ok(keys);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to retrieve unused admin keys", details = ex.Message });
}
}
/// <summary>
/// Revoke an admin key
/// </summary>
[HttpPost("keys/{keyId}/revoke")]
public async Task<IActionResult> RevokeAdminKey(int keyId)
{
try
{
var success = await _adminService.RevokeAdminKeyAsync(keyId);
if (success)
{
return Ok(new { message = "Admin key revoked successfully" });
}
else
{
return NotFound(new { error = "Admin key not found or already used" });
}
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to revoke admin key", details = ex.Message });
}
}
/// <summary>
/// Get current delivery pricing settings
/// </summary>
[HttpGet("pricing")]
public async Task<IActionResult> GetPricingSettings()
{
try
{
var settings = await _settingsService.GetPricingSettingsAsync();
return Ok(settings);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to retrieve pricing settings", details = ex.Message });
}
}
/// <summary>
/// Update delivery pricing settings
/// </summary>
[HttpPut("pricing")]
public async Task<IActionResult> UpdatePricingSettings([FromBody] UpdatePricingDTO request)
{
try
{
var success = await _settingsService.UpdatePricingSettingsAsync(request);
if (success)
{
return Ok(new { message = "Pricing settings updated successfully" });
}
return BadRequest(new { error = "Failed to update pricing settings" });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to update pricing settings", details = ex.Message });
}
}
/// <summary>
/// Download database backup file
/// </summary>
[HttpGet("backup/download")]
public async Task<IActionResult> DownloadBackup()
{
try
{
var (content, contentType, fileName) = await _adminService.DownloadDatabaseAsync();
return File(content, contentType, fileName);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to download backup", details = ex.Message });
}
}
/// <summary>
/// Restore database from uploaded file
/// </summary>
[HttpPost("backup/restore")]
[Consumes("multipart/form-data")]
public async Task<IActionResult> RestoreBackup(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest(new { error = "No file uploaded" });
}
try
{
using (var stream = file.OpenReadStream())
{
var success = await _adminService.RestoreDatabaseAsync(stream);
if (success)
{
return Ok(new { message = "Database restored successfully. Application may need to restart to apply changes completely." });
}
}
return StatusCode(500, new { error = "Failed to restore database" });
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Failed to restore database", details = ex.Message });
}
}
// --- USER MANAGEMENT ---
[HttpGet("users")]
public async Task<IActionResult> GetAllUsers()
{
var users = await _userService.GetAllUsersAsync();
return Ok(users);
}
[HttpPut("users")]
public async Task<IActionResult> UpdateUser([FromBody] AdminUpdateUserDTO updateDto)
{
var success = await _userService.AdminUpdateUserAsync(updateDto);
return success ? Ok(new { message = "User updated successfully" }) : NotFound(new { error = "User not found" });
}
[HttpDelete("users/{userId}")]
public async Task<IActionResult> DeleteUser(int userId)
{
var success = await _userService.DeleteUserAsync(userId);
return success ? Ok(new { message = "User deleted successfully" }) : NotFound(new { error = "User not found" });
}
// --- ORDER MANAGEMENT ---
[HttpGet("orders")]
public async Task<IActionResult> GetAllOrders()
{
var orders = await _orderService.GetAllOrdersAsync();
return Ok(orders);
}
[HttpPut("orders")]
public async Task<IActionResult> UpdateOrder([FromBody] AdminUpdateOrderDTO updateDto)
{
var success = await _orderService.AdminUpdateOrderAsync(updateDto);
return success ? Ok(new { message = "Order updated successfully" }) : NotFound(new { error = "Order not found" });
}
[HttpDelete("orders/{orderId}")]
public async Task<IActionResult> DeleteOrder(int orderId)
{
var success = await _orderService.DeleteOrderAsync(orderId);
return success ? Ok(new { message = "Order deleted successfully" }) : NotFound(new { error = "Order not found" });
}
// --- KEY MANAGEMENT (EXPANDED) ---
[HttpPut("keys")]
public async Task<IActionResult> UpdateAdminKey([FromBody] AdminUpdateKeyDTO updateDto)
{
var success = await _adminService.UpdateAdminKeyAsync(updateDto);
return success ? Ok(new { message = "Admin key updated successfully" }) : NotFound(new { error = "Admin key not found" });
}
[HttpDelete("keys/{keyId}")]
public async Task<IActionResult> DeleteAdminKey(int keyId)
{
var success = await _adminService.DeleteAdminKeyAsync(keyId);
return success ? Ok(new { message = "Admin key deleted successfully" }) : NotFound(new { error = "Admin key not found" });
}
}
public class BackupRequestDTO
{
public string? BackupPath { get; set; }
}
}
|