Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
407 lines
11 KiB
TypeScript
407 lines
11 KiB
TypeScript
import { CollectionConfig } from "payload";
|
|
import { hasPermission } from "@/utils/access-control/hasPermission";
|
|
import {
|
|
CLOSING_STATUSES,
|
|
STATUS_LABEL,
|
|
TICKET_CATEGORIES,
|
|
TICKET_PRIORITIES,
|
|
TICKET_STATUSES,
|
|
} from "@/lib/tickets/ticketMeta";
|
|
import { plaintextToLexical } from "@/lib/tickets/lexical";
|
|
|
|
type StaffUser = {
|
|
id: number;
|
|
payloadDisplayName?: string | null;
|
|
username?: string | null;
|
|
};
|
|
|
|
const resolveUserId = (value: unknown): number | null => {
|
|
if (value == null) return null;
|
|
if (typeof value === "object") {
|
|
const obj = value as { id?: unknown };
|
|
return typeof obj.id === "number" ? obj.id : null;
|
|
}
|
|
return typeof value === "number" ? value : null;
|
|
};
|
|
|
|
const systemEntry = (message: string, createdAt?: string) => ({
|
|
type: "system",
|
|
content: plaintextToLexical(message),
|
|
created_at: createdAt ?? new Date().toISOString(),
|
|
});
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
function immutableEditValue(value: unknown): string | null {
|
|
if (!isRecord(value)) return null;
|
|
return JSON.stringify({
|
|
before: value.before,
|
|
after: value.after,
|
|
editedBy: resolveUserId(value.editedBy),
|
|
editedAt: value.editedAt,
|
|
});
|
|
}
|
|
|
|
export const Tickets: CollectionConfig = {
|
|
slug: "tickets",
|
|
admin: {
|
|
group: "Helpdesk",
|
|
useAsTitle: "title",
|
|
defaultColumns: [
|
|
"title",
|
|
"status",
|
|
"priority",
|
|
"category",
|
|
"reporter",
|
|
"assignee",
|
|
"updatedAt",
|
|
],
|
|
listSearchableFields: ["title", "id"],
|
|
pagination: { defaultLimit: 50 },
|
|
},
|
|
access: {
|
|
read: async ({ req }) => {
|
|
if (!req.user) return false;
|
|
if (await hasPermission(req.payload, req.user, "tickets:read")) return true;
|
|
return { reporter: { equals: req.user.id } };
|
|
},
|
|
create: ({ req }) => !!req.user,
|
|
update: async ({ req }) => {
|
|
if (!req.user) return false;
|
|
return await hasPermission(req.payload, req.user, "tickets:update");
|
|
},
|
|
delete: async ({ req }) => {
|
|
return await hasPermission(req.payload, req.user, "tickets:delete");
|
|
},
|
|
},
|
|
hooks: {
|
|
beforeChange: [
|
|
async ({ data, originalDoc, req }) => {
|
|
if (!data) return data;
|
|
|
|
const next = data as Record<string, unknown>;
|
|
const prev = originalDoc as Record<string, unknown> | undefined;
|
|
|
|
// Only diff against an existing document — creates start with a system
|
|
// entry appended by the create server action instead.
|
|
if (!prev || !prev.id) return data;
|
|
|
|
if (next.editHistory !== undefined) {
|
|
const previousEdits = Array.isArray(prev.editHistory) ? prev.editHistory : [];
|
|
const nextEdits = Array.isArray(next.editHistory) ? next.editHistory : [];
|
|
const existingEditsChanged = previousEdits.some(
|
|
(entry, index) => immutableEditValue(entry) !== immutableEditValue(nextEdits[index]),
|
|
);
|
|
if (nextEdits.length < previousEdits.length || existingEditsChanged) {
|
|
throw new Error("Ticket edit history is immutable.");
|
|
}
|
|
}
|
|
|
|
const entries = [...((next.activity as unknown[]) ?? [])];
|
|
const now = new Date().toISOString();
|
|
const changes: string[] = [];
|
|
|
|
// Status transitions → system entry + closedAt management.
|
|
const prevStatus = prev.status as string | undefined;
|
|
const nextStatus = next.status as string | undefined;
|
|
if (nextStatus && prevStatus !== nextStatus) {
|
|
const from = STATUS_LABEL[prevStatus as keyof typeof STATUS_LABEL] ?? prevStatus;
|
|
const to = STATUS_LABEL[nextStatus as keyof typeof STATUS_LABEL] ?? nextStatus;
|
|
changes.push(`Status changed from ${from} to ${to}`);
|
|
if (CLOSING_STATUSES.includes(nextStatus as (typeof CLOSING_STATUSES)[number])) {
|
|
next.closedAt = now;
|
|
} else if (prev.closedAt) {
|
|
next.closedAt = null;
|
|
}
|
|
}
|
|
|
|
// Assignment changes → system entry.
|
|
const prevAssigneeId = resolveUserId(prev.assignee);
|
|
const nextAssigneeId = resolveUserId(next.assignee);
|
|
if (prevAssigneeId !== nextAssigneeId) {
|
|
if (nextAssigneeId == null) {
|
|
changes.push("Ticket unassigned");
|
|
} else {
|
|
let name = `User ${nextAssigneeId}`;
|
|
try {
|
|
const assignee = await req.payload.findByID({
|
|
collection: "users",
|
|
id: nextAssigneeId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const staffUser = assignee as unknown as StaffUser;
|
|
name = staffUser.payloadDisplayName || staffUser.username || name;
|
|
} catch {
|
|
// Name resolution is best-effort — fall back to "User <id>".
|
|
}
|
|
changes.push(`Ticket assigned to ${name}`);
|
|
}
|
|
}
|
|
|
|
for (const message of changes) {
|
|
entries.push(systemEntry(message, now));
|
|
}
|
|
|
|
if (changes.length > 0) {
|
|
next.activity = entries;
|
|
}
|
|
|
|
return data;
|
|
},
|
|
],
|
|
},
|
|
fields: [
|
|
{
|
|
name: "title",
|
|
type: "text",
|
|
required: true,
|
|
admin: {
|
|
description: "Short, descriptive summary of the issue or request.",
|
|
},
|
|
},
|
|
{
|
|
name: "description",
|
|
type: "richText",
|
|
required: true,
|
|
admin: {
|
|
description: "Full details of the issue or request.",
|
|
},
|
|
},
|
|
{
|
|
name: "category",
|
|
type: "select",
|
|
required: true,
|
|
defaultValue: "support_request",
|
|
options: TICKET_CATEGORIES.map((c) => ({ label: c.label, value: c.value })),
|
|
index: true,
|
|
},
|
|
{
|
|
name: "priority",
|
|
type: "select",
|
|
required: true,
|
|
defaultValue: "medium",
|
|
options: TICKET_PRIORITIES.map((p) => ({ label: p.label, value: p.value })),
|
|
index: true,
|
|
},
|
|
{
|
|
name: "status",
|
|
type: "select",
|
|
required: true,
|
|
defaultValue: "open",
|
|
options: TICKET_STATUSES.map((s) => ({ label: s.label, value: s.value })),
|
|
index: true,
|
|
},
|
|
{
|
|
name: "reporter",
|
|
type: "relationship",
|
|
relationTo: "users",
|
|
required: true,
|
|
index: true,
|
|
admin: {
|
|
description: "The user who submitted this ticket.",
|
|
},
|
|
},
|
|
{
|
|
name: "assignee",
|
|
type: "relationship",
|
|
relationTo: "users",
|
|
admin: {
|
|
description: "Staff member responsible for this ticket.",
|
|
},
|
|
},
|
|
{
|
|
name: "activity",
|
|
type: "array",
|
|
admin: {
|
|
description:
|
|
"Append-only activity timeline. Messages between the reporter and staff plus system events.",
|
|
},
|
|
fields: [
|
|
{
|
|
name: "type",
|
|
type: "select",
|
|
required: true,
|
|
defaultValue: "system",
|
|
options: [
|
|
{ label: "System", value: "system" },
|
|
{ label: "Staff message", value: "agent_message" },
|
|
{ label: "Reporter message", value: "client_message" },
|
|
],
|
|
},
|
|
{
|
|
name: "content",
|
|
type: "richText",
|
|
required: true,
|
|
},
|
|
{
|
|
name: "author",
|
|
type: "relationship",
|
|
relationTo: "users",
|
|
admin: {
|
|
description: "Who wrote this entry. Omitted for system events.",
|
|
},
|
|
},
|
|
{
|
|
name: "created_at",
|
|
type: "date",
|
|
admin: {
|
|
readOnly: true,
|
|
date: { pickerAppearance: "dayAndTime" },
|
|
},
|
|
defaultValue: () => new Date().toISOString(),
|
|
},
|
|
],
|
|
},
|
|
{
|
|
name: "editHistory",
|
|
type: "array",
|
|
admin: {
|
|
readOnly: true,
|
|
description: "Immutable before/after snapshots captured when the author edits a ticket.",
|
|
},
|
|
fields: [
|
|
{
|
|
name: "before",
|
|
type: "json",
|
|
required: true,
|
|
},
|
|
{
|
|
name: "after",
|
|
type: "json",
|
|
required: true,
|
|
},
|
|
{
|
|
name: "editedBy",
|
|
type: "relationship",
|
|
relationTo: "users",
|
|
required: true,
|
|
},
|
|
{
|
|
name: "editedAt",
|
|
type: "date",
|
|
required: true,
|
|
admin: {
|
|
readOnly: true,
|
|
date: { pickerAppearance: "dayAndTime" },
|
|
},
|
|
},
|
|
],
|
|
},
|
|
{
|
|
name: "closedAt",
|
|
type: "date",
|
|
admin: {
|
|
readOnly: true,
|
|
description: "Set automatically when the ticket reaches a closing status.",
|
|
date: { pickerAppearance: "dayAndTime" },
|
|
},
|
|
},
|
|
|
|
// --- Project tracking fields (Phase 1) ---
|
|
{
|
|
name: "project",
|
|
type: "relationship",
|
|
relationTo: "projects",
|
|
admin: {
|
|
description: "Project this ticket belongs to. Null = standalone/backlog.",
|
|
},
|
|
index: true,
|
|
},
|
|
{
|
|
name: "sprint",
|
|
type: "relationship",
|
|
relationTo: "sprints",
|
|
admin: {
|
|
description: "Sprint this ticket is assigned to.",
|
|
},
|
|
},
|
|
{
|
|
name: "release",
|
|
type: "relationship",
|
|
relationTo: "releases",
|
|
admin: {
|
|
description: "Release this ticket targets.",
|
|
},
|
|
},
|
|
{
|
|
name: "parentTicket",
|
|
type: "relationship",
|
|
relationTo: "tickets",
|
|
admin: {
|
|
description: "Parent ticket (for subtasks / epic children).",
|
|
},
|
|
},
|
|
{
|
|
name: "labels",
|
|
type: "relationship",
|
|
relationTo: "labels",
|
|
hasMany: true,
|
|
admin: {
|
|
description: "Labels for filtering and organization.",
|
|
},
|
|
},
|
|
{
|
|
name: "type",
|
|
type: "select",
|
|
defaultValue: "task",
|
|
options: [
|
|
{ label: "Task", value: "task" },
|
|
{ label: "Bug", value: "bug" },
|
|
{ label: "Story", value: "story" },
|
|
{ label: "Epic", value: "epic" },
|
|
{ label: "Improvement", value: "improvement" },
|
|
],
|
|
admin: {
|
|
description: "Issue type.",
|
|
},
|
|
},
|
|
{
|
|
name: "storyPoints",
|
|
type: "number",
|
|
min: 0,
|
|
admin: {
|
|
description: "Fibonacci story point estimate.",
|
|
},
|
|
},
|
|
{
|
|
name: "estimate",
|
|
type: "number",
|
|
min: 0,
|
|
admin: {
|
|
description: "Time estimate in hours.",
|
|
},
|
|
},
|
|
{
|
|
name: "startDate",
|
|
type: "date",
|
|
admin: {
|
|
description: "When work starts (for Gantt).",
|
|
date: { pickerAppearance: "dayAndTime" },
|
|
},
|
|
},
|
|
{
|
|
name: "dueDate",
|
|
type: "date",
|
|
admin: {
|
|
description: "When work is due (for Gantt).",
|
|
date: { pickerAppearance: "dayAndTime" },
|
|
},
|
|
},
|
|
{
|
|
name: "resolution",
|
|
type: "select",
|
|
options: [
|
|
{ label: "Fixed", value: "fixed" },
|
|
{ label: "Won't Fix", value: "wontfix" },
|
|
{ label: "Duplicate", value: "duplicate" },
|
|
{ label: "Invalid", value: "invalid" },
|
|
],
|
|
admin: {
|
|
description: "How the ticket was resolved.",
|
|
},
|
|
},
|
|
],
|
|
};
|