using FastEndpoints;
using FrameworkBLL.WorkFlow;
using GB5Shared.DTO.Framework.Login;
using GB5Shared.DTO.Framework.ResponseStandard;
using GB5Shared.DTO.WorkFlow;
using GB5Shared.FastEndPoint;
using GB5Shared.WorkFlow.WorkFlowEngine;
using static FrameworkDAL.Constant.Constant;
using static GB5Shared.DTO.WorkFlow.ContractsDTO;
namespace FrameworkSL.Endpoints.WorkFlow
{
///
/// POST /WorkFlow/StartWorkflow
///
/// Starts a new workflow instance for a document that has been saved.
///
/// The caller should:
/// 1. Save the document (e.g. Task) in its own transaction.
/// 2. Build a from the saved DTO.
/// 3. Call this endpoint to initiate the approval chain.
///
/// Request body — :
/// EntityId — MENTITY.ENTITYID of the document
/// OUId — Current session OU (LoginDTO.WorkOUId if omitted)
/// BizTransactionClassId — MBIZTRANSACTIONCLASS.BIZTRANSACTIONCLASSID (-1 = any)
/// BizTransactionId — MBIZTRANSACTION.BIZTRANSACTIONID (-1 = any)
/// ObjectId — PK of the saved record (e.g. TaskId)
/// DataJson — Snapshot of the saved document (for audit trail)
/// Comment — Optional submitter comment
/// Facts — Key/value pairs from the DTO evaluated against workflow
/// conditions (e.g. { "TaskDetailType": 2 })
///
/// Response:
/// 200 — workflow started (or no workflow configured — saves normally)
/// 400 — validation / configuration error with a descriptive message
///
public class StartWorkflow
: BaseEndpoint>
{
private readonly IWorkFlowBLL _bll;
public StartWorkflow(IWorkFlowBLL bll) => _bll = bll;
public override void Configure()
{
Post("/WorkFlow/StartWorkflow");
AllowAnonymous();
}
public record StartWorkflowParameters(
[property: FromHeader] string Login,
[property: FromBody] WorkflowStartRequest Request
);
protected override string? GetCacheKey(
StartWorkflowParameters req, LoginDTO login) => null;
protected override async Task> ExecuteAsync(
StartWorkflowParameters req,
LoginDTO login,
CancellationToken ct)
{
try
{
// Default OUId from session if caller omits it
if (req.Request.OUId == 0)
req.Request.OUId = login.WorkOUId;
var result = await _bll.StartWorkflow(req.Request, login);
string message = result.IsStarted
? "Workflow started successfully."
: "No workflow configured for this document — saved normally.";
return await GB5Shared.ResponseStandard.Response
.CreateSuccessResponse(message, CacheKeyLevel.NotRequired, login);
}
catch (WorkflowEngineException ex)
{
// Business-rule / configuration errors — return 400 with exact message
return await GB5Shared.ResponseStandard.Response
.CreateExceptionError(ex, CacheKeyLevel.NotRequired,
login, ex.Message, 400);
}
catch (Exception ex)
{
return await GB5Shared.ResponseStandard.Response
.CreateExceptionError(ex, CacheKeyLevel.NotRequired,
login, ex.Message, 500);
}
}
}
}