using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Localization;
using Resgrid.Model;
using Resgrid.Model.DepartmentTasks;
using Resgrid.Model.Services;
using Resgrid.Web.Areas.User.Models.ShiftLogs;
using Resgrid.Web.Helpers;
namespace Resgrid.Web.Areas.User.Controllers
{
///
/// Workforce Pro SM12 Shift log and handover (shifts-scheduling-modernization-plan.md §11.6): the logs list (current and recent per anchor),
/// the log page (activity digest, entries, handover sign-off and acknowledgement, finalize) and the log schedule (anchors). The pages 404
/// while Workforce.Pro or Workforce.ShiftLog is off; a lapsed add-on leaves them read-only. Plain forms with post-redirect-get; a refused
/// command comes back as a message on the page it was sent from. IShiftLogService enforces every rule (gate, seat, crew, crew lead, next
/// crew); this controller only shapes pages and maps refusals. Protected entry text shows withheld here and is unlocked on the record's own
/// Records page.
///
[Area("User"), Authorize, ResponseCache(NoStore = true, Location = ResponseCacheLocation.None), RequestSizeLimit(128 * 1024)]
[DepartmentLocalTime]
public sealed class ShiftLogsController : SecureBaseController
{
public const string ErrorKey = "ShiftLogsError";
public const string MessageKey = "ShiftLogsMessage";
public const string ShellKey = "ShiftLogShell";
private readonly IShiftLogService _logs;
private readonly IWorkforceProAccessService _workforcePro;
private readonly IShiftsService _shifts;
private readonly IDepartmentGroupsService _groups;
private readonly IStringLocalizer _strings;
private ShiftLogModuleAccess _access;
public ShiftLogsController(IShiftLogService logs, IWorkforceProAccessService workforcePro, IShiftsService shifts, IDepartmentGroupsService groups,
IStringLocalizer strings)
{
_logs = logs; _workforcePro = workforcePro; _shifts = shifts; _groups = groups; _strings = strings;
}
// ---------------------------------------------------------------- request plumbing
internal DepartmentTaskActor Actor => new DepartmentTaskActor
{
DepartmentId = DepartmentId, UserId = UserId, IpAddress = RequestIp(),
UserAgent = Request?.Headers["User-Agent"].ToString() is { Length: > 0 } agent ? (agent.Length > 500 ? agent.Substring(0, 500) : agent) : null
};
private string RequestIp()
{
if (Request == null) return null;
try { return IpAddressHelper.GetRequestIP(Request, true); }
catch (Exception) { return null; }
}
private ShiftLogModuleAccess Access => _access ?? new ShiftLogModuleAccess();
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
Response.Headers["Cache-Control"] = "no-store";
// Workforce Pro (§11.3): invisible while the Workforce.Pro flag is off; the service adds the Workforce.ShiftLog child flag.
var workforcePro = await WorkforceProRequestGate.GetAccessAsync(HttpContext, _workforcePro, DepartmentId);
if (workforcePro == null || !workforcePro.Offered)
{
context.Result = NotFound();
return;
}
_access = await _logs.GetAccessAsync(Actor);
if (_access == null || !_access.Offered)
{
context.Result = NotFound();
return;
}
ViewData[ShellKey] = new ShiftLogShellView
{
Access = _access,
GraceEndsUtc = _access.IsDepartmentAdmin && _access.InDunningGrace ? workforcePro.GraceEndsUtc : null,
Message = TempData?[MessageKey] as string,
Error = TempData?[ErrorKey] as string
};
var executed = await next();
if (executed?.Exception is not ShiftLogException ex || executed.ExceptionHandled)
return;
executed.ExceptionHandled = true;
var action = context.RouteData?.Values["action"]?.ToString();
if (IsGet && (ex.StatusCode == 404 || string.Equals(action, "Index", StringComparison.OrdinalIgnoreCase)))
{
// A refused list page answers with its status (never a redirect back to itself).
executed.Result = ex.StatusCode == 404 ? NotFound() : StatusCode(ex.StatusCode);
return;
}
Flash(error: Message(ex.Code));
executed.Result = IsGet ? RedirectToAction("Index") : BackOrIndex();
}
private bool IsGet => string.Equals(Request?.Method, "GET", StringComparison.OrdinalIgnoreCase);
/// A refusal's localized message ("Error{code}"; signature outcomes share "ErrorSignature"), or the generic one.
internal string Message(string code)
{
if (!string.IsNullOrWhiteSpace(code))
{
var key = code.StartsWith("Signature", StringComparison.Ordinal) ? "ErrorSignature" : "Error" + code;
var text = _strings[key];
if (text != null && !text.ResourceNotFound)
return text.Value;
}
return _strings["ErrorGeneric"].Value;
}
private string L(string key) => _strings[key].Value;
private void Flash(string message = null, string error = null)
{
if (TempData == null) return;
if (!string.IsNullOrWhiteSpace(message)) TempData[MessageKey] = message;
if (!string.IsNullOrWhiteSpace(error)) TempData[ErrorKey] = error;
}
/// Back to the page the form was posted from (same host, shift log pages only), else the logs list.
private IActionResult BackOrIndex()
{
var back = Request?.Headers.Referer.ToString();
if (!string.IsNullOrEmpty(back) && Uri.TryCreate(back, UriKind.Absolute, out var uri) && string.Equals(uri.Host, Request.Host.Host, StringComparison.OrdinalIgnoreCase)
&& uri.AbsolutePath.StartsWith("/User/ShiftLogs", StringComparison.OrdinalIgnoreCase))
return Redirect(uri.PathAndQuery);
return RedirectToAction("Index");
}
// ---------------------------------------------------------------- pages
/// The logs list; "awaiting-review" lists the finalized logs waiting on the member's review instead
/// (the "My reviews" lane's full list), empty for a member who reviews no logs.
[HttpGet]
public async Task Index(string anchorId = null, string filter = null)
{
if (string.Equals(filter, ShiftLogRules.AwaitingReviewFilter, StringComparison.OrdinalIgnoreCase))
{
var queue = await _logs.ListAwaitingReviewAsync(Actor, ShiftLogRules.MaxReviewQueue);
// The anchors' sections are not shown on this list (Anchors stays empty).
return View("Index", new ShiftLogIndexView { AwaitingReview = true, Logs = queue?.Logs ?? new List(), AwaitingReviewCount = queue?.Count ?? 0 });
}
var model = new ShiftLogIndexView
{
Logs = await _logs.ListLogsAsync(Actor, string.IsNullOrWhiteSpace(anchorId) ? null : anchorId),
Anchors = await _logs.ListAnchorsAsync(Actor)
};
return View("Index", model);
}
[HttpGet, ActionName("View")]
public async Task Detail(string id)
{
if (string.IsNullOrWhiteSpace(id)) return NotFound();
return View("Detail", new ShiftLogPageView { Detail = await _logs.GetLogAsync(Actor, id), Statement = L("SignStatement") });
}
/// From a Records page: the shift log of a record.
[HttpGet]
public async Task Record(string id)
{
if (string.IsNullOrWhiteSpace(id)) return NotFound();
var detail = await _logs.GetLogByRecordAsync(Actor, id);
return RedirectToAction("View", new { id = detail.Log.Id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task AddEntry(string id, string time, string category, string text)
{
var at = string.IsNullOrWhiteSpace(time) ? (DateTime?)null : DepartmentTime.From(ViewData)?.ToUtc(DepartmentTime.From(ViewData).Parse(time));
if (!string.IsNullOrWhiteSpace(time) && at == null) throw new ShiftLogException(400, "InvalidTime");
await _logs.AddEntryAsync(Actor, id, new ShiftLogEntryInput { TimeUtc = at, Category = category, Text = text });
Flash(message: L("EntryAdded"));
return RedirectToAction("View", new { id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task SaveSummary(string id, string summary)
{
await _logs.SaveHandoverSummaryAsync(Actor, id, summary);
Flash(message: L("Saved"));
return RedirectToAction("View", new { id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task Sign(string id)
{
var proof = SignatureProof.SessionOnly(UserId, RequestIp(), Request?.Headers["User-Agent"].ToString());
await _logs.SignHandoverAsync(Actor, id, proof, L("SignStatement"));
Flash(message: L("HandoverSigned"));
return RedirectToAction("View", new { id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task Acknowledge(string id)
{
await _logs.AcknowledgeHandoverAsync(Actor, id);
Flash(message: L("HandoverAcknowledged"));
return RedirectToAction("View", new { id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task Finalize(string id)
{
await _logs.FinalizeAsync(Actor, id);
Flash(message: L("LogFinalizedMessage"));
return RedirectToAction("View", new { id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task Reopen(string id)
{
await _logs.ReopenAsync(Actor, id);
Flash(message: L("LogReopenedMessage"));
return RedirectToAction("View", new { id });
}
/// Marks a finalized log reviewed (a seated manager of its group who neither signed it off nor finalized it) at the revision shown.
[HttpPost, ValidateAntiForgeryToken]
public async Task MarkReviewed(string id, int revision)
{
await _logs.MarkReviewedAsync(Actor, id, revision);
Flash(message: L("LogReviewedMessage"));
return RedirectToAction("View", new { id });
}
[HttpPost, ValidateAntiForgeryToken]
public async Task OpenCurrent(string anchorId)
{
var detail = await _logs.OpenCurrentAsync(Actor, anchorId);
return RedirectToAction("View", new { id = detail.Log.Id });
}
// ---------------------------------------------------------------- log schedule (anchors)
[HttpGet]
public async Task Anchors(string id = null)
{
var anchors = await _logs.ListAnchorsAsync(Actor);
var form = new ShiftLogAnchorForm();
if (!string.IsNullOrWhiteSpace(id))
{
var anchor = anchors.FirstOrDefault(a => string.Equals(a.Id, id, StringComparison.OrdinalIgnoreCase));
if (anchor == null) return NotFound();
form = new ShiftLogAnchorForm
{
Id = anchor.Id, Kind = anchor.Kind, ShiftId = anchor.ShiftId, GroupId = anchor.GroupId, DailyStart = ShiftLogAnchorForm.Clock(anchor.DailyStartMinute) ?? "07:00",
IsActive = anchor.IsActive, Revision = anchor.Revision
};
}
return View("Anchors", await AnchorsViewAsync(anchors, form));
}
private async Task AnchorsViewAsync(List anchors, ShiftLogAnchorForm form)
{
var model = new ShiftLogAnchorsView { Anchors = anchors, Form = form, CanManage = Access.CanManageAnchors };
if (!model.CanManage) return model;
foreach (var shift in ((await _shifts.GetAllShiftsByDepartmentAsync(DepartmentId)) ?? new List()).Where(s => s != null).OrderBy(s => s.Name, StringComparer.CurrentCultureIgnoreCase))
model.Shifts.Add(new SelectListItem(shift.Name, shift.ShiftId.ToString(CultureInfo.InvariantCulture), form.ShiftId == shift.ShiftId));
foreach (var group in ((await _groups.GetAllGroupsForDepartmentAsync(DepartmentId)) ?? new List()).Where(g => g != null).OrderBy(g => g.Name, StringComparer.CurrentCultureIgnoreCase))
model.Groups.Add(new SelectListItem(group.Name, group.DepartmentGroupId.ToString(CultureInfo.InvariantCulture), form.GroupId == group.DepartmentGroupId));
return model;
}
[HttpPost, ValidateAntiForgeryToken]
public async Task SaveAnchor(ShiftLogAnchorForm form)
{
if (form == null) throw new ShiftLogException(400, "InvalidInput");
var minutes = form.Kind == (int)ShiftLogAnchorKinds.DailyGroup ? ShiftLogAnchorForm.Minutes(form.DailyStart) : null;
if (form.Kind == (int)ShiftLogAnchorKinds.DailyGroup && minutes == null) throw new ShiftLogException(400, "InvalidStartTime");
await _logs.SaveAnchorAsync(Actor, string.IsNullOrWhiteSpace(form.Id) ? null : form.Id, new ShiftLogAnchorInput
{
Kind = form.Kind, ShiftId = form.Kind == (int)ShiftLogAnchorKinds.ShiftGroup ? form.ShiftId : null, GroupId = form.GroupId, DailyStartMinute = minutes,
IsActive = form.IsActive, Revision = form.Revision
});
Flash(message: L("Saved"));
return RedirectToAction("Anchors");
}
}
}