VEU.WathBody/3-app/2-cli/Server.WatchBody.Web/Controllers/ProgramController.cs

66 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Server.WatchBody.Core.Dal.Src.Repository;
using Server.WatchBody.Web.Dto;
namespace Server.WatchBody.Web.Controllers;
/// <summary>GET api/v1/programs/active — активная версия программы (spec 05).</summary>
public class ProgramController : Controller
{
private readonly IProgramRepository _programs;
private readonly IProgramVersionRepository _versions;
public ProgramController(IProgramRepository programs, IProgramVersionRepository versions)
{
_programs = programs;
_versions = versions;
}
public ActionResult Active()
{
var athleteId = AthleteId();
if (athleteId < 0) return Error(401, "unauthorized");
var program = _programs.Select(athleteId).FirstOrDefault();
var activeMeta = program == null
? null
: _versions.Select(new ProgramVersionFilter
{
AthleteId = athleteId,
ProgramId = program.Id,
Status = "active",
}).FirstOrDefault();
if (program == null || activeMeta == null)
return Error(404, "no_active_program");
// body — отдельным get (program_version_select его не возвращает)
var active = _versions.Get(athleteId, activeMeta.Id);
if (active == null) return Error(404, "no_active_program");
return new JsonResult(new ActiveProgramResponse
{
ProgramId = program.Id,
VersionId = active.Id,
Version = active.Version,
BasedOnVersion = active.BasedOnVersion,
Author = active.Author,
Status = active.Status,
Body = JsonDocument.Parse(active.Body).RootElement.Clone(),
Rationale = active.Rationale,
CreatedAt = active.CreatedAt,
});
}
private int AthleteId() =>
HttpContext.Items.TryGetValue(Middleware.ApiKeyMiddleware.AthleteIdItem, out var value)
? (int)value!
: -1;
private ActionResult Error(int statusCode, string message)
{
Response.StatusCode = statusCode;
return new JsonResult(new ErrorResponse { Error = message });
}
}