59 lines
1.9 KiB
C#
59 lines
1.9 KiB
C#
using Management.Data;
|
|
using Management.Security;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.Text.Json;
|
|
|
|
namespace Management.Controllers.Admin;
|
|
|
|
/// <summary>
|
|
/// Base class for admin controllers with shared functionality.
|
|
/// </summary>
|
|
public abstract class AdminControllerBase : ControllerBase
|
|
{
|
|
protected readonly SqlService Sql;
|
|
protected readonly ClientContext Client;
|
|
protected readonly ILogger Logger;
|
|
|
|
protected AdminControllerBase(SqlService sql, ClientContext client, ILogger logger)
|
|
{
|
|
Sql = sql;
|
|
Client = client;
|
|
Logger = logger;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Execute stored procedure and return appropriate IActionResult.
|
|
/// </summary>
|
|
protected async Task<IActionResult> CallProc(string proc, string action, object rqst, CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
var json = JsonSerializer.Serialize(rqst);
|
|
var resp = await Sql.ExecProcAsync($"dbo.{proc}", action, json, ct: ct);
|
|
|
|
if (string.IsNullOrWhiteSpace(resp))
|
|
return StatusCode(500, new { ok = false, error = "Service unavailable" });
|
|
|
|
using var doc = JsonDocument.Parse(resp);
|
|
var root = doc.RootElement;
|
|
|
|
if (root.TryGetProperty("ok", out var okProp) && okProp.GetBoolean())
|
|
return Content(resp, "application/json");
|
|
|
|
var error = root.TryGetProperty("error", out var errProp) ? errProp.GetString() : "Operation failed";
|
|
return BadRequest(new { ok = false, error });
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Logger.LogError(ex, "[Admin] {Proc}.{Action} error", proc, action);
|
|
return StatusCode(500, new { ok = false, error = "Operation failed", detail = ex.Message });
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Return BadRequest for validation failures.
|
|
/// </summary>
|
|
protected IActionResult ValidationError(string error)
|
|
=> BadRequest(new { ok = false, error });
|
|
}
|