using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Resgrid.Model.DepartmentTasks;
using Resgrid.Model.Services;
using Resgrid.Providers.Claims;
using Resgrid.Web.Services.Helpers;
using Resgrid.Web.Services.Models.v4.DepartmentTasks;
namespace Resgrid.Web.Services.Controllers.v4
{
///
/// Workforce Pro SM10a Tasks for Omni and integrations (shifts-scheduling-modernization-plan.md §11.4 "v4"): the module access, my tasks
/// by lane, the supervisor board and its counts, a task with its timeline and per-item action flags (Omni gates every button by
/// ), categories, record work, and each step of a task. The service enforces the same gate as the
/// web (§11.3): 404 TasksUnavailable while Workforce.Pro or Workforce.Tasks is off, 402 WorkforceProRequired for writes after a lapse,
/// 403 PermissionRequired / SeatRequired for managing others. Private text (description, notes, comments) is revealed only with the
/// X-Resgrid-Protected-Grant header for protected departments; lists carry operational fields only. Errors are ProblemDetails with the
/// service's stable code in code.
///
[Route("api/v{VersionId:apiVersion}/[controller]")]
[ApiVersion("4.0")]
[ApiExplorerSettings(GroupName = "v4")]
[Authorize(Policy = ResgridResources.Department_View)]
public class TasksController : V4AuthenticatedApiControllerbase, IAsyncActionFilter
{
public const int MaxTake = 100;
private const string ProtectedDataRequired = "ProtectedDataRequired";
private readonly IDepartmentTasksService _tasks;
// SM10b: completion signatures read this session's step-up evidence (ApiSignatureProof); without it an L2 signature is refused.
private readonly IMfaEvidenceService _evidence;
private readonly IMfaPolicyService _mfaPolicy;
public TasksController(IDepartmentTasksService tasks, IMfaEvidenceService evidence = null, IMfaPolicyService mfaPolicy = null)
{
_tasks = tasks;
_evidence = evidence;
_mfaPolicy = mfaPolicy;
}
/// One file (10 MB) plus the form fields.
public const int UploadRequestLimit = DepartmentTaskRules.MaxFileBytes + 512 * 1024;
private Task ProofAsync(CancellationToken cancellationToken) =>
ApiSignatureProof.BuildAsync(HttpContext, UserId, DepartmentId, _evidence, _mfaPolicy, cancellationToken);
private static async Task UploadAsync(IFormFile file, CancellationToken cancellationToken)
{
if (file == null || file.Length == 0) return null;
if (file.Length > DepartmentTaskRules.MaxFileBytes) throw new DepartmentTaskException(400, "InvalidFile");
using var buffer = new System.IO.MemoryStream();
await file.CopyToAsync(buffer, cancellationToken);
return new DepartmentTaskFileUpload { FileName = System.IO.Path.GetFileName(file.FileName), ContentType = file.ContentType, Data = buffer.ToArray() };
}
/// The acting member, with the ADP grant from the request (null without one) and the request metadata for audit rows.
private DepartmentTaskActor Actor => new DepartmentTaskActor
{
DepartmentId = DepartmentId,
UserId = UserId,
GrantToken = NullIfEmpty(Request.Headers[DataProtectionController.GrantHeader].ToString()),
IpAddress = RequestIp(),
UserAgent = NullIfEmpty(Request.Headers["User-Agent"].ToString())
};
private static string NullIfEmpty(string value) => string.IsNullOrWhiteSpace(value) ? null : value;
private string RequestIp()
{
try
{
return IpAddressHelper.GetRequestIP(Request, true);
}
catch (Exception)
{
return null; // Audit metadata only; never a reason to refuse the request.
}
}
private OkObjectResult Reply(T data, int count = 1)
{
var result = new TasksApiResult { Data = data, Status = ResponseHelper.Success, PageSize = count };
ResponseHelper.PopulateV4ResponseData(result);
return Ok(result);
}
private static T Required(T input) where T : class => input ?? throw new DepartmentTaskException(400, "InvalidInput");
private static string RequiredId(string id) => string.IsNullOrWhiteSpace(id) ? throw new DepartmentTaskException(400, "InvalidInput") : id;
[NonAction]
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
Response.Headers["Cache-Control"] = "no-store";
if (!context.ModelState.IsValid) { context.Result = Failure(400, "InvalidInput"); return; }
var executed = await next();
if (executed.Exception is DepartmentTaskException ex)
{
executed.ExceptionHandled = true;
executed.Result = Failure(ex.StatusCode, ex.Code);
}
}
/// The service's status and code as ProblemDetails; a missing ADP grant reads as protected_data_required with IsRedacted.
[NonAction]
public static ObjectResult Failure(int status, string code)
{
var protectedData = code == ProtectedDataRequired;
var problem = new ProblemDetails { Status = status, Type = protectedData ? "protected_data_required" : "department_task_" + code, Title = code };
problem.Extensions["code"] = code;
problem.Extensions["IsRedacted"] = protectedData;
return new ObjectResult(problem) { StatusCode = status };
}
private static DepartmentTaskQuery Query(DepartmentTaskLanes lane, int[] states, string categoryId, int? audienceKind, string audienceId, bool overdueOnly,
int skip, int take) => new DepartmentTaskQuery
{
Lane = lane,
States = states == null || states.Length == 0 ? null : states.Distinct().ToList(),
CategoryId = NullIfEmpty(categoryId),
AudienceKind = audienceKind,
AudienceId = NullIfEmpty(audienceId),
OverdueOnly = overdueOnly,
Skip = Math.Max(0, skip),
Take = take <= 0 ? 50 : Math.Min(take, MaxTake)
};
private OkObjectResult Page(DepartmentTaskPage page) => Reply(page, page?.Items?.Count ?? 0);
/// What the member may do in the module: offered, writable or read-only after a lapse, seat, Manage tasks.
[HttpGet("GetAccess")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetAccess() => Reply(await _tasks.GetAccessAsync(Actor));
///
/// My tasks by lane: 1 assigned to me or claimed by me, 2 unclaimed in my roles, groups and units, 3 created by me (the board is
/// GetBoard). Without states: open work plus Done awaiting verification. Page with skip and take (at most 100).
///
[HttpGet("GetMyTasks")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetMyTasks([FromQuery] int lane = (int)DepartmentTaskLanes.Mine, [FromQuery] int[] states = null,
[FromQuery] string categoryId = null, [FromQuery] bool overdueOnly = false, [FromQuery] int skip = 0, [FromQuery] int take = 50)
{
if (lane != (int)DepartmentTaskLanes.Mine && lane != (int)DepartmentTaskLanes.MyAudiences && lane != (int)DepartmentTaskLanes.CreatedByMe)
throw new DepartmentTaskException(400, "InvalidInput");
return Page(await _tasks.ListAsync(Actor, Query((DepartmentTaskLanes)lane, states, categoryId, null, null, overdueOnly, skip, take)));
}
/// The supervisor board (Manage tasks with a seat), filtered by state, category, audience or overdue.
[HttpGet("GetBoard")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetBoard([FromQuery] int[] states = null, [FromQuery] string categoryId = null,
[FromQuery] int? audienceKind = null, [FromQuery] string audienceId = null, [FromQuery] bool overdueOnly = false, [FromQuery] int skip = 0, [FromQuery] int take = 50) =>
Page(await _tasks.ListAsync(Actor, Query(DepartmentTaskLanes.Board, states, categoryId, audienceKind, audienceId, overdueOnly, skip, take)));
/// The board tiles: open, overdue, blocked, needs an owner, awaiting verification.
[HttpGet("GetBoardCounts")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetBoardCounts() => Reply(await _tasks.GetBoardCountsAsync(Actor));
/// One task with its private text (redacted without a grant in a protected department), timeline and per-item Can flags.
[HttpGet("GetTask/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task>> GetTask(string id) => Reply(await _tasks.GetAsync(Actor, RequiredId(id)));
[HttpGet("GetCategories")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>>> GetCategories([FromQuery] bool includeArchived = false)
{
var categories = await _tasks.GetCategoriesAsync(Actor, includeArchived) ?? new List();
return Reply(categories, categories.Count);
}
/// The member's open Records work assignments, read-only (D36): open the record to work on them.
[HttpGet("GetRecordWork")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>>> GetRecordWork()
{
var items = await _tasks.GetRecordWorkAsync(Actor) ?? new List();
return Reply(items, items.Count);
}
/// Creates a task. With no audience it is the member's own task (no seat needed). A resent RequestId returns the stored task.
[HttpPost("CreateTask")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> CreateTask([FromBody] TaskCreateInput input, CancellationToken cancellationToken)
{
Required(input);
var audienceKind = input.AudienceKind ?? (int)DepartmentTaskAudienceKinds.Person;
var audienceId = NullIfEmpty(input.AudienceId);
if (audienceKind == (int)DepartmentTaskAudienceKinds.Person && audienceId == null)
audienceId = UserId;
return Reply(await _tasks.CreateAsync(Actor, new DepartmentTaskInput
{
Title = input.Title,
Description = input.Description,
CategoryId = NullIfEmpty(input.CategoryId),
Priority = input.Priority,
DueOn = input.DueOn,
AudienceKind = audienceKind,
AudienceId = audienceId,
SourceKind = input.SourceKind ?? (int)DepartmentTaskSourceKinds.Manual,
SourceRef = NullIfEmpty(input.SourceRef),
SourceLabel = NullIfEmpty(input.SourceLabel),
CallId = input.CallId,
RequestId = NullIfEmpty(input.RequestId)
}, cancellationToken));
}
[HttpPost("EditTask")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> EditTask([FromBody] TaskEditInput input)
{
Required(input);
return Reply(await _tasks.EditAsync(Actor, RequiredId(input.TaskId), new DepartmentTaskEdit
{
Title = input.Title,
Description = input.Description,
CategoryId = NullIfEmpty(input.CategoryId),
Priority = input.Priority,
DueOn = input.DueOn,
Revision = input.Revision
}));
}
/// Takes a shared task (role, group or unit audience). Two members claiming at once: one wins, the other gets 409.
[HttpPost("Claim")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Claim([FromBody] TaskCommandInput input) =>
Reply(await _tasks.ClaimAsync(Actor, CommandId(input), input.Revision));
/// Gives a claimed shared task back to its audience (the claimer or a manager).
[HttpPost("Release")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Release([FromBody] TaskCommandInput input) =>
Reply(await _tasks.ReleaseAsync(Actor, CommandId(input), input.Revision));
[HttpPost("Start")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Start([FromBody] TaskCommandInput input) =>
Reply(await _tasks.StartAsync(Actor, CommandId(input), input.Revision));
/// Blocks a task; Note is the reason (private text).
[HttpPost("Block")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Block([FromBody] TaskCommandInput input) =>
Reply(await _tasks.BlockAsync(Actor, CommandId(input), input.Revision, input.Note));
[HttpPost("Unblock")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Unblock([FromBody] TaskCommandInput input) =>
Reply(await _tasks.UnblockAsync(Actor, CommandId(input), input.Revision));
/// Completes a task; Note is the completion note (required when the category asks for one). A category that asks for a signature
/// is signed with this session (L2 needs a fresh step-up); one that asks for a photo needs CompleteWithFile.
[HttpPost("Complete")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Complete([FromBody] TaskCommandInput input, CancellationToken cancellationToken)
{
var id = CommandId(input);
return Reply(await _tasks.CompleteAsync(Actor, id, input.Revision, new DepartmentTaskCompletionInput { Note = input.Note, Proof = await ProofAsync(cancellationToken) }, cancellationToken));
}
/// Completes with the category's policy as multipart/form-data (the photo, or the FileId of one attached first).
[HttpPost("CompleteWithFile")]
[Consumes("multipart/form-data")]
[RequestSizeLimit(UploadRequestLimit), RequestFormLimits(MultipartBodyLengthLimit = UploadRequestLimit)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> CompleteWithFile([FromForm] TaskCompleteForm form, CancellationToken cancellationToken)
{
if (form == null || string.IsNullOrWhiteSpace(form.TaskId)) throw new DepartmentTaskException(400, "InvalidInput");
return Reply(await _tasks.CompleteAsync(Actor, form.TaskId, form.Revision, new DepartmentTaskCompletionInput
{
Note = form.Note, File = await UploadAsync(form.File, cancellationToken), FileId = NullIfEmpty(form.FileId), Statement = NullIfEmpty(form.Statement),
Proof = await ProofAsync(cancellationToken)
}, cancellationToken));
}
/// Attaches a file to a task's timeline (multipart/form-data). ERT-D13: scanning off stores it "Not scanned" (ScanState 3).
[HttpPost("AttachFile")]
[Consumes("multipart/form-data")]
[RequestSizeLimit(UploadRequestLimit), RequestFormLimits(MultipartBodyLengthLimit = UploadRequestLimit)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> AttachFile([FromForm] TaskAttachForm form, CancellationToken cancellationToken)
{
if (form == null || string.IsNullOrWhiteSpace(form.TaskId)) throw new DepartmentTaskException(400, "InvalidInput");
var upload = await UploadAsync(form.File, cancellationToken) ?? throw new DepartmentTaskException(400, "InvalidFile");
return Reply(await _tasks.AttachFileAsync(Actor, form.TaskId, upload, NullIfEmpty(form.Note), cancellationToken));
}
/// A task file's bytes (the reveal path: X-Resgrid-Protected-Grant for a protected department).
[HttpGet("GetFile/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task GetFile(string id)
{
var file = await _tasks.GetFileAsync(Actor, RequiredId(id)) ?? throw new DepartmentTaskException(404, "FileNotFound");
Response.Headers["X-Content-Type-Options"] = "nosniff";
return File(file.Data, file.ContentType, file.FileName);
}
/// Promotes open work to a Readiness Pro work order (seated manager; 402 MaintenanceRequired without Readiness Pro).
[HttpPost("Promote")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Promote([FromBody] TaskCommandInput input) =>
Reply(await _tasks.PromoteAsync(Actor, CommandId(input), input.Revision, input.Note));
/// Skips one recurrence occurrence (seated manager): Cancelled with CancelKind Skipped, kept.
[HttpPost("SkipOccurrence")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> SkipOccurrence([FromBody] TaskCommandInput input) =>
Reply(await _tasks.SkipOccurrenceAsync(Actor, CommandId(input), input.Revision, input.Note));
[HttpGet("GetRecurrences")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>>> GetRecurrences([FromQuery] bool includeInactive = false)
{
var items = await _tasks.GetRecurrencesAsync(Actor, includeInactive) ?? new List();
return Reply(items, items.Count);
}
[HttpGet("GetRecurrence/{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetRecurrence(string id) => Reply(await _tasks.GetRecurrenceAsync(Actor, RequiredId(id)));
/// Creates (blank RecurrenceId) or edits a recurring task (Manage tasks with a seat).
[HttpPost("SaveRecurrence")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> SaveRecurrence([FromBody] TaskRecurrenceSaveInput input)
{
if (input?.Recurrence == null) throw new DepartmentTaskException(400, "InvalidInput");
return Reply(await _tasks.SaveRecurrenceAsync(Actor, NullIfEmpty(input.RecurrenceId), input.Recurrence));
}
/// Pauses (future untouched occurrences cancelled) or resumes (from now, no backfill) a recurring task.
[HttpPost("SetRecurrenceActive")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> SetRecurrenceActive([FromBody] TaskRecurrenceActiveInput input)
{
Required(input);
return Reply(await _tasks.SetRecurrenceActiveAsync(Actor, RequiredId(input.RecurrenceId), input.Revision, input.Active));
}
/// Board bulk reassign or cancel: per-item results (a stale revision fails alone).
[HttpPost("Bulk")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Bulk([FromBody] TaskBulkApiInput input)
{
Required(input);
return Reply(await _tasks.BulkAsync(Actor, new DepartmentTaskBulkInput
{
Action = input.Action, Items = input.Items ?? new List(), AudienceKind = input.AudienceKind, AudienceId = NullIfEmpty(input.AudienceId), Note = input.Note
}));
}
/// The tasks linked to a source: sourceKind 2 (a Records row, "{recordId}:{sectionKey}:{rowKey}"), 3 (an inspection violation id) or 4 (a call id).
[HttpGet("GetLinkedTasks")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetLinkedTasks([FromQuery] int sourceKind, [FromQuery] string sourceRef) =>
Reply(await _tasks.GetLinkedTasksAsync(Actor, sourceKind, RequiredId(sourceRef)));
/// A pre-filled task for a source (sourceKind 2, 3 or 4; a Records row pre-fills title, due and owner from its open columns); create it with
/// CreateTask and the same SourceKind and SourceRef.
[HttpGet("GetSourceDraft")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetSourceDraft([FromQuery] int sourceKind, [FromQuery] string sourceRef) =>
Reply(await _tasks.GetSourceDraftAsync(Actor, sourceKind, RequiredId(sourceRef)));
/// "Task completion and overdue" by owner (groupBy 1) or category (2) for [fromUtc, untilUtc) (Manage tasks; counts only).
[HttpGet("GetCompletionReport")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> GetCompletionReport([FromQuery] DateTime fromUtc, [FromQuery] DateTime untilUtc, [FromQuery] int groupBy = 1) =>
Reply(await _tasks.GetReportAsync(Actor, new DepartmentTaskReportQuery { FromUtc = fromUtc, UntilUtc = untilUtc, GroupBy = groupBy }));
/// Verifies a Done task (Manage tasks with a seat; never the member who completed it when the category says so).
[HttpPost("Verify")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Verify([FromBody] TaskCommandInput input) =>
Reply(await _tasks.VerifyAsync(Actor, CommandId(input), input.Revision));
/// The verifier sends a Done task back to In progress; Note says why.
[HttpPost("Return")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Return([FromBody] TaskCommandInput input) =>
Reply(await _tasks.ReturnAsync(Actor, CommandId(input), input.Revision, input.Note));
[HttpPost("Cancel")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Cancel([FromBody] TaskCommandInput input) =>
Reply(await _tasks.CancelAsync(Actor, CommandId(input), input.Revision, input.Note));
[HttpPost("Reopen")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Reopen([FromBody] TaskCommandInput input) =>
Reply(await _tasks.ReopenAsync(Actor, CommandId(input), input.Revision, input.Note));
[HttpPost("Reassign")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Reassign([FromBody] TaskReassignInput input)
{
Required(input);
return Reply(await _tasks.ReassignAsync(Actor, RequiredId(input.TaskId), input.Revision, input.AudienceKind, NullIfEmpty(input.AudienceId)));
}
/// Adds a comment (private text) and returns the task with its timeline.
[HttpPost("Comment")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task>> Comment([FromBody] TaskCommentInput input)
{
Required(input);
var actor = Actor;
var taskId = RequiredId(input.TaskId);
await _tasks.CommentAsync(actor, taskId, input.Note);
return Reply(await _tasks.GetAsync(actor, taskId));
}
private static string CommandId(TaskCommandInput input) => RequiredId(Required(input).TaskId);
}
}