Welcome to the final lesson of Authentication, Authorization, and Ticket Workflows! Your API can now authenticate users, scope customer collections, enforce ticket ownership, and restrict operations by role. In this lesson, you’ll build explicit workflow actions for assigning, closing, and reopening tickets.
Previously, generic PATCH requests could modify several ticket fields directly. That approach works for ordinary edits, but workflow changes have additional business rules. You’ll move those rules into a service layer and expose named endpoints that communicate the intended action clearly.
Moving Beyond Generic Updates
A generic update endpoint is appropriate for ordinary editable fields:
text
PATCH /api/tickets/:ticketId
JSON
{ "title": "Updated ticket title", "description": "More context about the issue.", "priority": "high"}
Status transitions and assignment are different. They represent business operations rather than simple field replacement.
The API therefore introduces three explicit actions:
text
POST /api/tickets/:ticketId/assignPOST /api/tickets/:ticketId/closePOST /api/tickets/:ticketId/reopen
These routes make the client’s intent visible:
assign selects a staff member and moves the ticket into active work.
close completes a ticket.
reopen returns a closed ticket to the open state.
The route does not need to infer intent from a combination of fields. Each endpoint delegates to one workflow function with its own rules.
Understanding the Workflow Layers
A successful action moves through four application layers:
text
Route ↓Workflow service ↓Repository mutation ↓PostgreSQL
Each layer has a focused responsibility:
The route handles HTTP concerns such as authorization, JSON requirements, Zod validation, and the final status code.
The service loads related records and applies workflow rules.
The repository performs parameterized SQL without deciding whether the transition is allowed.
PostgreSQL stores the final state and returns the persisted row.
This separation prevents business policy from becoming scattered across route handlers and SQL functions.
The Supported Ticket Transitions
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
The workflow can be summarized as:
open ├── assign ──→ in_progress └── close ───→ closedin_progress ├── assign ──→ in_progress └── close ───→ closedclosed └── reopen ──→ open
Assignment can replace the current assignee while a ticket is open or already in progress. Every successful assignment sets the status to "in_progress".
Reusing the Ticket Column Projection
The repository in src/repositories/ticket-repository.ts defines one shared column projection.
Every repository function that returns a ticket needs the same columns. Keeping the projection in one constant avoids repeating the list across SELECT, INSERT, and UPDATE statements.
The selected fields match the private TicketRow interface and provide everything required by mapTicketRow().
Workflow mutations can therefore return the same public Ticket representation as the collection, creation, detail, and generic update functions.
Persisting Ticket Assignment
Persisting Status Changes
Separating Persistence from Business Rules
A repository should answer questions such as:
How do I store this assignee?How do I update this status?Which row did PostgreSQL return?
The service layer answers different questions:
May a closed ticket be assigned?Does this assignee exist?Is this assignee an agent or administrator?May this ticket be closed?May this ticket be reopened?
If these rules were embedded in SQL functions, they would become harder to read, test, and reuse. If they were repeated in routes, different endpoints could enforce slightly different versions of the same policy.
The workflow service gives the application one home for those decisions.
Restricting the Generic PATCH Schema
The generic update schema in src/schemas/ticket-schemas.ts no longer accepts status.
export const updateTicketBodySchema = z .object({ title: z.string().trim().min(3).max(120).optional(), description: z.string().trim().max(1000).optional(), priority: z.enum(ticketPriorities).optional(), }) .refine((value) => Object.keys(value).length > 0, { message: "At least one field is required.", });
Clients can still update a ticket’s title, description, and priority through generic PATCH.
Status is deliberately absent from the public request schema. A body containing only { "status": "closed" } is no longer a valid generic patch.
Clients must use /close or /reopen, ensuring that the service layer evaluates the transition.
The empty-object refinement remains in place, so a patch must contain at least one supported editable field.
The repository’s lower-level update function remains available for ordinary ticket fields, but the HTTP validation boundary prevents clients from bypassing named workflow actions.
Defining Assignment Input
Assignment needs a dedicated request contract because it accepts one action-specific field.
assigneeId must be a non-empty string after trimming.
Zod validates the shape and normalization of the body, but it cannot determine whether the user exists or has an allowed role.
The inferred AssignTicketBody type keeps the route synchronized with the runtime schema.
A valid assignment body looks like:
{ "assigneeId": "usr_agent_1"}
A structurally valid ID can still refer to a missing user or a customer. Those cases are handled by the workflow service.
Assigning Through the Service Layer
The workflow functions live in src/services/ticket-service.ts. Assignment begins by loading the current ticket.
export async function assignTicket( ticketId: string, assigneeId: string,) { const ticket = await findTicketById(ticketId); if (!ticket) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", ); }
The service reads the latest persisted ticket before evaluating workflow rules.
A validly shaped but missing ID produces 404 TICKET_NOT_FOUND.
Throwing AppError lets Express 5 forward the rejected async function into the centralized error handler.
Assignment is rejected when the ticket is already closed.
if (ticket.status === "closed") { throw new AppError( 409, "INVALID_TICKET_TRANSITION", "A closed ticket cannot be assigned.", );}
The failure uses HTTP 409 Conflict because the requested action conflicts with the ticket’s current state.
The stable code INVALID_TICKET_TRANSITION lets clients recognize workflow conflicts without parsing the message.
Open and in-progress tickets continue to the assignee check.
The proposed assignee is then resolved from PostgreSQL.
const assignee = await findUserById(assigneeId);if ( !assignee || !["agent", "admin"].includes(assignee.role)) { throw new AppError( 400, "INVALID_ASSIGNEE", "assigneeId must reference an agent or admin.", );}
A missing user and a user with an unsupported role both produce 400 INVALID_ASSIGNEE.
Customers cannot be assigned to tickets.
Both agents and administrators are valid assignees.
The service uses the persisted user role rather than trusting role information supplied by the client.
After all policy checks pass, the service delegates the mutation.
const updated = await setTicketAssignment( ticketId, assignee.id,);if (!updated) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", );}return updated;
The repository receives the normalized persisted user ID.
The mutation sets both the assignee and "in_progress" status.
The service still handles a null repository result defensively. Even after the earlier read, the row could disappear before the update, so the service converts that case into 404 TICKET_NOT_FOUND.
Closing a Ticket
The close workflow also begins with a fresh ticket lookup.
export async function closeTicket( ticketId: string,) { const ticket = await findTicketById(ticketId); if (!ticket) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", ); } if (ticket.status === "closed") { throw new AppError( 409, "INVALID_TICKET_TRANSITION", "Ticket is already closed.", ); } return ( await setTicketStatus(ticketId, "closed") )!;}
A missing ticket produces the same focused 404 used by other ticket operations.
Both "open" and "in_progress" tickets can be closed.
Repeating the action on an already closed ticket produces 409 INVALID_TICKET_TRANSITION.
The repository receives the final "closed" value only after the service approves the transition.
The action is intentionally not idempotent in this contract: attempting to close an already closed ticket is reported as a workflow conflict rather than silently returning success.
Reopening a Ticket
Reopening applies the inverse state rule.
export async function reopenTicket( ticketId: string,) { const ticket = await findTicketById(ticketId); if (!ticket) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", ); } if (ticket.status !== "closed") { throw new AppError( 409, "INVALID_TICKET_TRANSITION", "Only closed tickets can be reopened.", ); } return ( await setTicketStatus(ticketId, "open") )!;}
Only a closed ticket can be reopened.
Trying to reopen an open or in-progress ticket produces 409 INVALID_TICKET_TRANSITION.
A successful reopen changes the status to "open".
Reopening does not clear the current assignee in this implementation. The service changes only the status defined by the workflow contract.
Registering Action Routes Before the Detail Route
The explicit action routes are declared in src/routes/ticket-routes.ts before the broad /:ticketId route.
ticketRoutes.post( "/:ticketId/assign", // Assignment middleware and handler);ticketRoutes.post( "/:ticketId/close", // Close middleware and handler);ticketRoutes.post( "/:ticketId/reopen", // Reopen middleware and handler);ticketRoutes.route("/:ticketId") // GET, PATCH, and DELETE
The action URLs contain an additional path segment after the ticket ID.
Declaring named actions before the broad detail route keeps the routing table easy to understand and prevents future dynamic-route changes from obscuring the specific workflow endpoints.
Every action uses POST because it performs a state-changing command.
A GET request never performs or imitates assignment, close, or reopen behavior.
The ticket router already mounts authenticate globally, so every workflow request requires a valid Bearer token.
Exposing the Assignment Action
The assignment route composes authorization, media-type enforcement, validation, and service delegation.
authorizeRoles("agent", "admin") prevents customers from entering the workflow.
requireJson ensures that assignment requests use Content-Type: application/json.
Zod validates both the ticket ID and the assignment body.
The route does not load the ticket, inspect its status, or resolve the assignee. It delegates all workflow rules to assignTicket().
A successful action returns HTTP 200 with the complete updated ticket.
The middleware flow is:
Router-wide authentication ↓Agent or admin authorization ↓JSON media-type check ↓Parameter and body validation ↓Assignment service ↓Repository UPDATE
The complete response also preserves the ticket’s ID, requester, priority, description, creation timestamp, and refreshed updatedAt.
Send a later detail request:
GET /api/tickets/tkt_1001
The same values should appear, confirming that PostgreSQL persisted the assignment.
Testing Invalid Assignees
Try assigning a customer:
{ "assigneeId": "usr_customer_1"}
The service should return:
400 INVALID_ASSIGNEE
A missing user produces the same business error:
{ "assigneeId": "usr_missing"}
This keeps the public workflow contract focused: the assignee must reference a real agent or administrator.
Testing Close and Reopen
With agent-token-1, send:
POST /api/tickets/tkt_1001/close
The response should show:
{ "status": "closed"}
Repeat the same request. The ticket is already closed, so the service should return:
409 INVALID_TICKET_TRANSITION
Now send:
POST /api/tickets/tkt_1001/reopen
The response should show:
{ "status": "open"}
Repeat the reopen request while the ticket is open. The service should again return:
409 INVALID_TICKET_TRANSITION
Testing Role Protection
Switch the Authorization token to:
customer-token-1
Try any workflow action:
POST /api/tickets/tkt_1001/close
The response should be:
403 FORBIDDEN
Authentication succeeded, but the customer role is not allowed to perform staff workflow actions.
Switching back to agent-token-1 or using the administrator token allows the request to proceed to the workflow service.
Confirming Generic PATCH Cannot Change Status
Authenticate as an agent and try:
PATCH /api/tickets/tkt_1001
{ "status": "closed"}
Because status is not part of updateTicketBodySchema, this request does not provide a supported update field and should fail validation.
Use the explicit action instead:
POST /api/tickets/tkt_1001/close
Generic patching remains available for ordinary changes:
{ "priority": "high", "description": "Updated without changing workflow state directly."}
This prevents clients from skipping close and reopen transition rules.
Completing the Workflow Checkpoint
Use an agent token and exercise the complete lifecycle:
POST /api/tickets/<id>/assignPOST /api/tickets/<id>/closePOST /api/tickets/<id>/reopenGET /api/tickets/<id>
Confirm that:
Assignment sets the assignee and changes the status to "in_progress".
Closing changes the status to "closed".
Repeating close produces a transition conflict.
Reopening changes the status to "open".
Every successful action refreshes updatedAt.
The final detail request shows the complete persisted state.
Recap
You’ve completed the course by turning ticket state changes into explicit, protected workflow actions.
The repository now provides narrow assignment and status mutations using parameterized UPDATE ... RETURNING queries. The service layer owns ticket existence checks, assignee eligibility, and valid state transitions, while AppError expresses expected business failures through the centralized error pipeline.
The public generic PATCH route no longer accepts status changes. Agents and administrators instead use /assign, /close, and /reopen, making the requested business action visible and ensuring that every transition passes through one consistent set of rules.
With authentication, role authorization, ownership checks, customer-scoped data access, nested comments, and service-backed ticket workflows working together, the support API now has a coherent security and lifecycle model.
The narrow assignment mutation is implemented by setTicketAssignment() in src/repositories/ticket-repository.ts.
TypeScript
export async function setTicketAssignment( id: string, assigneeId: string,): Promise<Ticket | null> { const result = await query<TicketRow>( `UPDATE tickets SET assignee_id = $2, status = 'in_progress', updated_at = now() WHERE id = $1 RETURNING ${ticketColumns}`, [id, assigneeId], ); return result.rows[0] ? mapTicketRow(result.rows[0]) : null;}
The ticket ID uses $1, while the new assignee ID uses $2. Both values remain in the parameter array and are never interpolated into the SQL text.
Assignment always sets the ticket status to "in_progress". This ensures that a ticket assigned for active work cannot remain "open".
updated_at = now() records the mutation using PostgreSQL’s clock.
RETURNING provides the complete stored ticket without requiring a second SELECT.
A matching row is mapped into the API-facing Ticket shape. A missing ticket produces null, although the service normally confirms the ticket exists before calling this function.
This repository function does not decide whether the ticket is closed or whether the proposed assignee has an appropriate role. Those decisions belong to the service layer.
Status transitions use a second narrow repository function.
TypeScript
export async function setTicketStatus( id: string, status: TicketStatus,): Promise<Ticket | null> { const result = await query<TicketRow>( `UPDATE tickets SET status = $2, updated_at = now() WHERE id = $1 RETURNING ${ticketColumns}`, [id, status], ); return result.rows[0] ? mapTicketRow(result.rows[0]) : null;}
Both the target ticket and new status are parameterized. The query receives the ticket ID as $1 and the status as $2.
The repository does not contain branches for closing or reopening. It simply persists the status selected by a trusted service function.
PostgreSQL refreshes updated_at and returns the complete row.
Reusing mapTicketRow() keeps the response format identical across every ticket operation.
Keeping this function policy-free makes it reusable for several named workflow actions.
text
How do I store this assignee?How do I update this status?Which row did PostgreSQL return?
text
May a closed ticket be assigned?Does this assignee exist?Is this assignee an agent or administrator?May this ticket be closed?May this ticket be reopened?
TypeScript
export const updateTicketBodySchema = z .object({ title: z.string().trim().min(3).max(120).optional(), description: z.string().trim().max(1000).optional(), priority: z.enum(ticketPriorities).optional(), }) .refine((value) => Object.keys(value).length > 0, { message: "At least one field is required.", });
export async function assignTicket( ticketId: string, assigneeId: string,) { const ticket = await findTicketById(ticketId); if (!ticket) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", ); }
TypeScript
if (ticket.status === "closed") { throw new AppError( 409, "INVALID_TICKET_TRANSITION", "A closed ticket cannot be assigned.", );}
TypeScript
const assignee = await findUserById(assigneeId);if ( !assignee || !["agent", "admin"].includes(assignee.role)) { throw new AppError( 400, "INVALID_ASSIGNEE", "assigneeId must reference an agent or admin.", );}
TypeScript
const updated = await setTicketAssignment( ticketId, assignee.id,);if (!updated) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", );}return updated;
TypeScript
export async function closeTicket( ticketId: string,) { const ticket = await findTicketById(ticketId); if (!ticket) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", ); } if (ticket.status === "closed") { throw new AppError( 409, "INVALID_TICKET_TRANSITION", "Ticket is already closed.", ); } return ( await setTicketStatus(ticketId, "closed") )!;}
TypeScript
export async function reopenTicket( ticketId: string,) { const ticket = await findTicketById(ticketId); if (!ticket) { throw new AppError( 404, "TICKET_NOT_FOUND", "Ticket not found.", ); } if (ticket.status !== "closed") { throw new AppError( 409, "INVALID_TICKET_TRANSITION", "Only closed tickets can be reopened.", ); } return ( await setTicketStatus(ticketId, "open") )!;}
TypeScript
ticketRoutes.post( "/:ticketId/assign", // Assignment middleware and handler);ticketRoutes.post( "/:ticketId/close", // Close middleware and handler);ticketRoutes.post( "/:ticketId/reopen", // Reopen middleware and handler);ticketRoutes.route("/:ticketId") // GET, PATCH, and DELETE
Router-wide authentication ↓Agent or admin authorization ↓JSON media-type check ↓Parameter and body validation ↓Assignment service ↓Repository UPDATE