tickets
All repositories: gitoria
35.3 KB
import { writerOfSession } from './users.hl'// lib/tickets.hl — TICKETS AND THEIR RELATIONS: the central logic of tickets.worldapi.org. Statics only, the server realm.// A face / an API route (components/, lib/api.hl) checks the session or token and calls one function here; every// write answers the rows the push carries.//// CREATOR'S CONVENTIONS (2026-09-24, ticket #38): every primary key is the mpackdb UUID// (`@id`, a string like '0mufbkwhlpjq'), never a `*id` counter; the files live in// storage/mpackdb/. A NUMBER A PERSON SEES is a separate field: tickets are numbered PER// PROJECT from 1 (`number`); tickets migrated from the old global store keep their old// global number as `oldNumber` (docs and comments say "#38"). Order never comes from key// order: lists sort by the stored times, a history by (created, seq).//// ticketsTable pk @id index project state source !path *oldNumber// { project (project @id — NOT the name), number, path ('<project @id>/<number>', unique),// oldNumber?, subject, summary, state, source, created, updated, events,// createdBy (users @id, '' = opened before the login), assignee (users @id, '') }// linksTable pk @id index @ticket @other (ticket #4, mission 017) { kind, ticket, other, user, created }// kind 'parent': `ticket` is a child of `other` (at most one per ticket)// kind 'blockedBy': `ticket` is blocked by `other` (waits on it)// A removed relation is deleted here; the history keeps it ('link' events, lib/events.hl).// Every write appends its event to the history (events.hl putEvent) and stores the ticket with the new// `events` count / `updated`; then the event stream numbers it and tells the listening programs (stream.hl// recordEvent, ticket #26). Projects, members and roles: lib/projects.hl; state names and page shapes:// lib/tickets-helpers.hl.//// WHO MAY is the role in the ticket's project (projects.hl): a refusal for a missing right has// `forbidden = true` (the API answers 403). EVERY WRITE HAS A USER (ticket #7): the logged-in user of the// web session or of the API token (users.hl). `source` is the import key (the ticket file's name) — an// import with a known source is answered with the existing ticket, never a second one.//// reading ticketRowOf, ticketRecord / ticketAt / ticketByRef / ticketByKey, ticketRows, inboxRows,// eventRows, ticketWithEvents, stateChoices, ticketRights// writing createTicket, addComment (with attachments: lib/attachments.hl), changeComment (edit / delete / like, lib/comments.hl), changeState, assignTicket,// editTicket, removeMember// relations relationsOf, relatedViews, setParent, changeBlockerimport { MPackDB } from 'hl:mpackdb'import { now } from 'hl:time'import { storageDir, countOf, first, merged, clean, oneLine, isDigits, localStamp, newestFirst, oldestFirst, ticketHref, ticketApiHref, projectHrefOf } from './util.hl'import { nameOfUser } from './users.hl'import { projectRecord, projectByAnySlug, projectByRef, projectSlugOf, roleOf, rankOf, isMember, mayEditIn, memberRecord, memberRows, userByRef, assignChoices, userOk, authorMissing, removeMembership, projectRecords, isAdminOf, setNumberFloor } from './projects.hl'import { states, inboxStates, stateOf, slugOf, refOf, keyOf, relationViewOf } from './tickets-helpers.hl'import { putEvent, eventsError, eventRecord, eventRowAt, historyOf, creatorNameOf } from './events.hl'import { editComment, deleteComment, likeComment, likersOf } from './comments.hl'import { recordEvent } from './stream.hl'import { checkFiles, storeFiles } from './attachments.hl'static ticketsTable = new MPackDB(file = storageDir + '/tickets.db', primaryKey = '@id', indexes = ['project', 'state', 'source', '!path', '*oldNumber'])static ticketPaths = new MPackDB(file = storageDir + '/ticket-paths.db', primaryKey = '@id', indexes = ['!path'])static linksTable = new MPackDB(file = storageDir + '/links.db', primaryKey = '@id', indexes = ['@ticket', '@other'])// ---- the shapes a page and the API show ---------------------------------------------// A ROW IS A PLAIN HYBRID: what the View reads is what the browser receives.// `id` is the UUID; `number` + `project` (the slug) are what a person uses; `oldNumber` / `oldRef`// only on tickets migrated from the global numbering.static ticketRowOf = (t) => {n = t.events != null ? t.events : 0p = projectRecord(t.project)slug = p != null ? p.slug : ''byId = t.createdBy != null ? t.createdBy : ''toId = t.assignee != null ? t.assignee : ''row = {id = t.idproject = slugprojectId = t.projectprojectTitle = p != null ? p.title : ''number = t.numberref = '#' + t.numbersubject = t.subjectsummary = t.summarystate = t.statestateSlug = slugOf(t.state)source = t.source != null ? t.source : ''created = localStamp(t.created)createdMs = t.createdupdated = localStamp(t.updated)updatedMs = t.updatedevents = nhref = ticketHref(slug, t.number)apiHref = ticketApiHref(slug, t.number)projectHref = projectHrefOf(slug)hasOld = t.oldNumber != nulloldRef = t.oldNumber != null ? '#' + t.oldNumber : ''createdById = byIdcreatedBy = byId != '' ? nameOfUser(byId) : creatorNameOf(t)assigneeId = toIdassignee = toId != '' ? nameOfUser(toId) : ''hasAssignee = toId != ''}if (t.oldNumber != null) { row.oldNumber = t.oldNumber }// ticket #4 (mission 017): the relations, as refs with their states (relationsOf below)rel = relationsOf(t)row.parent = rel.parentrow.children = rel.childrenrow.allChildrenConfirmed = rel.allChildrenConfirmedrow.blockedBy = rel.blockedByrow.blocks = rel.blocksreturn row}// ---- finding a ticket -------------------------------------------------------------------static ticketRecord = (uuid) => { return uuid == null || uuid == '' ? null : ticketsTable.fetch('' + uuid) }// `project` is a slug (a former one too)static ticketAt = (project, number) => {if (project == null || !isDigits(number)) { return null }p = projectByAnySlug(project)if (p == null) { return null }path = p.id + '/' + toNumber('' + number)t = first(ticketsTable.find('path', path))if (t != null) { return t }old = first(ticketPaths.find('path', path))return old != null ? ticketRecord(old.ticket) : null}static ticketByOld = (oldNumber) => {if (!isDigits(oldNumber)) { return null }return first(ticketsTable.find('oldNumber', toNumber('' + oldNumber)))}// what `/api/tickets/:ref` and `/tickets/:ref` accept: the OLD global number (digits)// or the ticket's UUIDstatic ticketByRef = (ref) => {if (ref == null) { return null }if (isDigits(ref)) { return ticketByOld(ref) }return ticketRecord(ref)}// ---- the writes of the #20 migration (lib/migrate.hl calls these; the tickets table is written only here) ----// every ticket record, in the table's orderstatic ticketRecords = () => { return ticketsTable.find(null, null) }// the ticket records of one project (project @id)static ticketRecordsOf = (projectId) => { return ticketsTable.find('project', projectId) }// a ticket from before #20 points at its project by name; it now points at the project record `p`, gets the new// state name, its creator and its assigneestatic moveToProject = (t, p, newState, creatorId, assigneeId) => {ticketsTable.update(t.id, merged(t, { project = p.id path = p.id + '/' + t.number state = newState createdBy = creatorId assignee = assigneeId }))}// ---- reads -------------------------------------------------------------------------// newest update first; both filters optional (null = all); `project` is a slugstatic ticketRows = (project, state) => {rows = []let all = nullif (project != null) {p = projectByAnySlug(project)if (p == null) { return rows }all = ticketsTable.find('project', p.id)} else {all = ticketsTable.find(null, null)}if (countOf(all) == 0) { return rows }for (t of all) {if (state == null || t.state == state) { rows.push(ticketRowOf(t)) }}return newestFirst(rows, 'updatedMs')}// the newest `n` rows of ticketRows and how many there are (the list page draws a page at a time)// (the sort runs on the stored tickets; only the first `n` become rows — a row costs the relations lookup, 500 of them were ~2 s)static firstRows = (project, state, n) => {let recs = []let all = nullif (project != null) {p = projectByAnySlug(project)if (p == null) { return { rows = [] total = 0 } }all = ticketsTable.find('project', p.id)} else {all = ticketsTable.find(null, null)}if (countOf(all) == 0) { return { rows = [] total = 0 } }for (t of all) {if (state == null || t.state == state) { recs.push(t) }}recs = newestFirst(recs, 'updated')rows = []let i = 0while (i < recs.length && i < n) {rows.push(ticketRowOf(recs[i]))i = i + 1}return { rows = rows total = recs.length }}// THE INBOX of a user: the tickets ASSIGNED TO THEM in pending and in review, two listsstatic inboxRows = (user) => {out = { pending = [] review = [] }if (user == null || user.id == null) { return out }a = []b = []ps = ticketsTable.find('state', 'pending')if (countOf(ps) > 0) { for (t of ps) { if (t.assignee == user.id) { a.push(ticketRowOf(t)) } } }rs = ticketsTable.find('state', 'review')if (countOf(rs) > 0) { for (t of rs) { if (t.assignee == user.id) { b.push(ticketRowOf(t)) } } }out.pending = newestFirst(a, 'updatedMs')out.review = newestFirst(b, 'updatedMs')return out}static inboxCountOf = (user) => {x = inboxRows(user)return x.pending.length + x.review.length}// the page's row of `/<project>/<number>` (ticket #25), or nullstatic ticketRowAt = (project, number) => {t = ticketAt(project, number)return t == null ? null : ticketRowOf(t)}// the event history of a ticket (UUID), oldest first (events.hl historyOf)static eventRows = (ticketId) => {t = ticketRecord(ticketId)if (t == null) { return [] }return historyOf(t)}// the options of a state select: [{ value, label }] — the states THIS user may move the ticket to// (a `use` member: only open ⇄ review; `edit` / `admin`: every other state)static stateChoices = (t, user) => {out = []if (t == null || user == null) { return out }role = roleOf(t.project, user)for (s of states) {if (s != t.state && mayMoveTo(role, t.state, s)) { out.push({ value = s label = s }) }}return out}static mayMoveTo = (role, current, target) => {if (rankOf(role) >= 2) { return true }if (rankOf(role) == 1) { return (current == 'open' && target == 'review') || (current == 'review' && target == 'open') }return false}// what a user may do on a ticket (a record): comment (a member), edit / assign (edit, admin), the states they// may move it to, and the members it can be assigned to — the ticket page asks after a login or a changestatic ticketRights = (t, user) => {return { comment = isMember(t.project, user) edit = mayEdit(t, user) options = stateChoices(t, user) members = assignChoices(t.project) moveProjects = moveChoices(t, user) }}// ---- writes: each answers what the push carries --------------------------------------// The author is the user — there is no free author field any more.// the next per-project number: the highest one in the project + 1 (first = 1)static nextNumber = (projectId) => {p = projectRecord(projectId)let top = p != null && p.numberFloor != null ? p.numberFloor : 0all = ticketsTable.find('project', projectId)if (countOf(all) > 0) {for (t of all) { if (t.number != null && t.number > top) { top = t.number } }}return top + 1}// answers { error, field, forbidden? } or { ticket (row), event (row), existed }// `project` = the slug (or id) of an existing project; `assignee` optional (a member's name / id)static createTicket = (project, subject, summary, user, source, assignee) => {s = oneLine(subject)if (clean(project) == '') { return { error = 'project is required' field = 'project' } }if (s == '') { return { error = 'subject is required' field = 'subject' } }if (!userOk(user)) { return authorMissing }p = projectByRef(clean(project))if (p == null) { return { error = 'no such project: ' + clean(project) field = 'project' } }if (!mayEditIn(p.id, user)) { return { error = 'you need the role edit or admin in ' + p.slug + ' to open a ticket' field = 'project' forbidden = true } }let who = ''if (assignee != null && clean(assignee) != '') {r = userByRef(assignee, p.id)if (r.error != null) { return { error = r.error field = 'assignee' } }who = r.user.id}src = clean(source)if (src != '') {known = ticketsTable.find('source', src)if (countOf(known) > 0) { return { ticket = ticketRowOf(known[0]) event = null existed = true } }}t0 = now()n = nextNumber(p.id)id = ticketsTable.put({ project = p.id number = n path = p.id + '/' + n subject = s summary = clean(summary) state = 'open' source = src created = t0 updated = t0 events = 1 createdBy = user.id assignee = who })if (id == null) { return { error = 'could not store the ticket: ' + ticketsTable.lastError() field = '' } }t = ticketsTable.fetch(id)eid = putEvent({ ticket = id seq = 1 kind = 'created' author = user.name user = user.id text = src != '' ? 'imported from ' + src : '' created = t0 })out = { ticket = ticketRowOf(t) event = eventRowAt(eid, t) existed = false }if (who != '') {let seq = 2aid = putEvent({ ticket = id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = '' created = t0 })ticketsTable.update(id, merged(t, { events = seq }))t2 = ticketsTable.fetch(id)out.ticket = ticketRowOf(t2)out.assignEvent = eventRowAt(aid, t2)recordEvent(eid, t2)recordEvent(aid, t2)} else {recordEvent(eid, t)}return out}// answers { error } or { ticket, event }; `ticketId` is the UUID. Any member may comment.// tickets#27 (mission 017): `files` = the attachments ([{ name, type, bytes }], null / [] = none; lib/attachments.hl checks the// limits and the content and stores them). A comment with files may have no text; without files it needs text, as before.static addComment = (ticketId, user, text, files) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }body = clean(text)given = files != null && countOf(files) > 0if (body == '' && !given) { return { error = 'a comment needs text' field = 'text' } }if (!userOk(user)) { return authorMissing }if (!isMember(t.project, user)) { return { error = 'only a member of the project can comment' field = '' forbidden = true } }checked = checkFiles(given ? files : null)if (checked.error != null) { return { error = checked.error field = checked.field tooBig = checked.tooBig } }t0 = now()let seq = (t.events != null ? t.events : 0) + 1eid = putEvent({ ticket = t.id seq = seq kind = 'comment' author = user.name user = user.id text = body created = t0 })stored = storeFiles(eid, t, user, checked.files)if (stored != null) { console.log('attachments: ' + stored.error) }ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))t2 = ticketsTable.fetch(t.id)recordEvent(eid, t2)return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }}// mission 016: EDIT ('edit', with `text`), DELETE ('delete') or LIKE ('like': again = take it back) the comment `commentId`// (an events @id) of ticket `ticketId`. Who may and what is kept: lib/comments.hl (edit / delete: its author; like: any// member). The ticket's `updated` and `events` stay: these are no new history events (and nothing for the event stream).// Answers { error, field, forbidden? } or { ticket, event (the comment's row as it is now), liked (a like: true = the user// likes it now) }.static changeComment = (ticketId, commentId, user, action, text) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }e = commentId == null || hlTypeName(commentId) != 'String' || commentId == '' ? null : eventRecord(commentId)if (e == null || e.ticket != t.id) { return { error = 'no such comment on this ticket' field = 'comment' } }let bad = nullif (action == 'edit') { bad = editComment(e, t, user, text) } else if (action == 'delete') { bad = deleteComment(e, t, user) } else if (action == 'like') { bad = likeComment(e, t, user) } else { bad = { error = 'unknown action ' + action field = '' } }if (bad != null) { return bad }out = { ticket = ticketRowOf(t) event = eventRowAt(e.id, t) }if (action == 'like') { out.liked = likersOf(e.id).includes(user.id) }return out}// the admin who gets a ticket that lands in the inbox with nobody assigned: the oldest adminstatic defaultAssignee = (projectId) => {for (m of memberRows(projectId)) { if (m.role == 'admin') { return m.user } }return ''}// answers { error } or { ticket, event, assignEvent? }; an optional note rides on the state event.// `forbidden = true` on a refusal the user may not overcome (the role does not allow that move).// A ticket that goes to review / pending with nobody assigned is assigned to the project's first admin// (so it reaches an inbox) — a second, 'assign' event.static changeState = (ticketId, state, user, note) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }s = stateOf(state)if (s == null) { return { error = 'unknown state — one of: ' + states.join(', ') field = 'state' } }if (s == t.state) { return { error = 'the ticket is already ' + s field = 'state' } }if (!userOk(user)) { return authorMissing }role = roleOf(t.project, user)if (role == null) { return { error = 'only a member of the project can change the state' field = 'state' forbidden = true } }if (!mayMoveTo(role, t.state, s)) { return { error = 'the role ' + role + ' can only move a ticket between open and review' field = 'state' forbidden = true } }t0 = now()let seq = (t.events != null ? t.events : 0) + 1eid = putEvent({ ticket = t.id seq = seq kind = 'state' author = user.name user = user.id text = clean(note) from = t.state to = s created = t0 })changes = { state = s updated = t0 events = seq }let aid = nulllet auto = ''if (inboxStates.includes(s) && (t.assignee == null || t.assignee == '')) { auto = defaultAssignee(t.project) }if (auto != '') {seq = seq + 1aid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = auto previous = '' created = t0 })changes.assignee = autochanges.events = seq}ticketsTable.update(t.id, merged(t, changes))t2 = ticketsTable.fetch(t.id)recordEvent(eid, t2)if (aid != null) { recordEvent(aid, t2) }out = { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }if (aid != null) { out.assignEvent = eventRowAt(aid, t2) }return out}// answers { error, forbidden? } or { ticket, event }; `assignee` = a member's users @id, '' = nobodystatic assignTicket = (ticketId, user, assignee) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }if (!userOk(user)) { return authorMissing }if (!mayEditIn(t.project, user)) { return { error = 'you need the role edit or admin to assign a ticket' field = 'assignee' forbidden = true } }who = assignee == null ? '' : clean(assignee)if (who != '' && memberRecord(t.project, who) == null) { return { error = 'the assignee must be a member of the project' field = 'assignee' } }was = t.assignee != null ? t.assignee : ''if (who == was) { return { error = who == '' ? 'the ticket is not assigned' : 'the ticket is already assigned to that person' field = 'assignee' } }t0 = now()let seq = (t.events != null ? t.events : 0) + 1eid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = was created = t0 })ticketsTable.update(t.id, merged(t, { assignee = who updated = t0 events = seq }))t2 = ticketsTable.fetch(t.id)recordEvent(eid, t2)return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }}// ---- editing (ticket #8, mission 014; ticket #20: by the role) --------------------------------// THE AUTHOR of a ticket is `createdBy` (users @id), or null for a ticket opened before the login// existed. MAY THIS USER EDIT the ticket (a record)? Any member with the role edit or admin of// its project (`use` members only comment and move it between open and review).static mayEdit = (t, user) => {if (t == null || !userOk(user)) { return false }return mayEditIn(t.project, user)}static mayEditId = (ticketId, user) => { return mayEdit(ticketRecord(ticketId), user) }// answers { error, field?, forbidden? } or { ticket, event }. `subject` / `summary` null = keep// that one. The previous values stay in the 'edit' event (append-only history).static editTicket = (ticketId, user, subject, summary) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }if (!userOk(user)) { return authorMissing }if (!mayEdit(t, user)) { return { error = 'you need the role edit or admin in the project to edit a ticket' field = '' forbidden = true } }if (subject == null && summary == null) { return { error = 'nothing to change: give subject and/or summary' field = '' } }let oldSummary = t.summary != null ? t.summary : ''s = subject != null ? oneLine(subject) : t.subjectif (s == '') { return { error = 'subject is required' field = 'subject' } }sm = summary != null ? clean(summary) : oldSummaryif (s == t.subject && sm == oldSummary) { return { error = 'nothing changed' field = subject != null ? 'subject' : 'summary' } }t0 = now()let seq = (t.events != null ? t.events : 0) + 1eid = putEvent({ ticket = t.id seq = seq kind = 'edit' author = user.name user = user.id text = '' oldSubject = t.subject oldSummary = oldSummary subject = s summary = sm created = t0 })if (eid == null) { return { error = 'could not store the edit: ' + eventsError() field = '' } }ticketsTable.update(t.id, merged(t, { subject = s summary = sm updated = t0 events = seq }))t2 = ticketsTable.fetch(t.id)recordEvent(eid, t2)return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }}// an admin removes a member (projects.hl removeMembership); the tickets assigned to the person are no longer// assigned to anybody. Answers { members } or { error, forbidden? }static removeMember = (projectId, actor, userId) => {r = removeMembership(projectId, actor, userId)if (r.error != null) { return r }all = ticketsTable.find('project', projectId)if (countOf(all) > 0) {for (t of all) {if (t.assignee == userId) { ticketsTable.update(t.id, merged(t, { assignee = '' })) }}}return r}// the API's view of one ticket (a record): the row and its whole historystatic ticketWithEvents = (t) => {if (t == null) { return null }return { ticket = ticketRowOf(t) events = eventRows(t.id) }}// ---- relations: parent / child and blocked-by (ticket #4, mission 017) ----------------------// A ticket has at most ONE PARENT (any project); a parent lists its CHILDREN with their states.// A ticket can be BLOCKED BY other tickets (any project) — it waits on them; the other side// shows what it BLOCKS. The scheduler reads them from the JSON rows (`parent`, `children`,// `blockedBy`, `blocks`, each a ref with the state) and the Markdown view.// PARENT STATE: `allChildrenConfirmed` (the key kept for the clients; it now means DONE) is true when// a ticket has children and every one of them is `done`. It is only SHOWN ("all children done") — the// parent's own state is never changed by it.// WHO MAY set / remove a relation (ticket #20): a member with the role edit or admin in the project of// EITHER of the two tickets. Replacing a parent needs the// right for the old pair AND the new pair. No loops: a ticket cannot be its own ancestor, and// cannot (transitively) wait on itself.// Tickets are named as `<project>#<number>` (spaces around `#` allowed) or by their UUID.// the link records of one side, oldest first (stored time): field 'ticket' = this ticket's own// relations (its parent, its blockers), field 'other' = the ones pointing at it (children, blocked)static linkRecords = (field, ticketId, kind) => {out = []if (ticketId == null || ticketId == '') { return out }all = linksTable.find(field, '' + ticketId)if (countOf(all) == 0) { return out }for (l of all) { if (l.kind == kind) { out.push(l) } }return oldestFirst(out, 'created')}static parentLinkOf = (ticketId) => { return first(linkRecords('ticket', ticketId, 'parent')) }static parentIdOf = (ticketId) => {l = parentLinkOf(ticketId)return l == null ? null : l.other}static idsOfLinks = (links, field) => {out = []for (l of links) { out.push(l[field]) }return out}static childIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'parent'), 'ticket') }static blockerIdsOf = (ticketId) => { return idsOfLinks(linkRecords('ticket', ticketId, 'blockedBy'), 'other') }static blockedIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'blockedBy'), 'ticket') }static refsOfIds = (ids) => {out = []for (i of ids) {t = ticketRecord(i)if (t != null) { out.push(refOf(t)) }}return out}// { parent (ref or null), children, blockedBy, blocks (lists of refs), allChildrenConfirmed }static relationsOf = (t) => {pid = parentIdOf(t.id)p = pid != null ? ticketRecord(pid) : nullkids = refsOfIds(childIdsOf(t.id))let all = kids.length > 0for (c of kids) { if (c.state != 'done') { all = false } }return { parent = p != null ? refOf(p) : null children = kids allChildrenConfirmed = all blockedBy = refsOfIds(blockerIdsOf(t.id)) blocks = refsOfIds(blockedIdsOf(t.id)) }}// the relation views of a ticket AND every ticket related to it (+ `extra` ids: a parent or// blocker just removed) — what a write pushes, so every open page of them followsstatic relatedViews = (ticketId, extra) => {ids = ['' + ticketId]seen = {}seen['' + ticketId] = truemore = []pid = parentIdOf(ticketId)if (pid != null) { more.push(pid) }for (i of childIdsOf(ticketId)) { more.push(i) }for (i of blockerIdsOf(ticketId)) { more.push(i) }for (i of blockedIdsOf(ticketId)) { more.push(i) }for (i of extra) { if (i != null) { more.push(i) } }for (i of more) {if (seen['' + i] != true) {seen['' + i] = trueids.push('' + i)}}out = []for (i of ids) {t = ticketRecord(i)if (t != null) { out.push(relationViewOf(ticketRowOf(t))) }}return out}// `<project>#<number>` (spaces around '#' allowed) or a UUID → the ticket record, or nullstatic ticketByKey = (key) => {k = clean(key)if (k == '') { return null }at = k.indexOf('#')if (at < 0) { return isDigits(k) ? null : ticketRecord(k) }p = k.slice(0, at).trim()n = k.slice(at + 1).trim()if (p == '') { return null }return ticketAt(p, n)}// WHO MAY CHANGE A RELATION (mission ST): a relation is written on ONE ticket — the one whose parent / blocker changes (`a`) — so// the role edit or admin is needed in THAT ticket's project. It used to be enough in EITHER ticket's project: a member of any// project could then hang a parent or a blocker on a ticket of a project they have no role in. `b` (the other ticket) is only named.static mayLink = (a, b, user) => {if (!userOk(user)) { return false }return a != null && mayEditIn(a.project, user)}static linkForbidden = { error = 'you need the role edit or admin in the project of this ticket to change its relations' field = '' forbidden = true }// the history event of a relation change, on ticket `t`; answers { ticket, event, related }static linkEvent = (t, user, linkKind, action, other, previous, extra) => {t0 = now()let seq = (t.events != null ? t.events : 0) + 1// the values BEFORE the literal: an entry named `other` / `user` would shadow the variable// for the entries after it (mission 011 lesson)uname = user.nameuid = user.idoid = other.idoproject = projectSlugOf(other)onumber = other.numberrec = { ticket = t.id seq = seq kind = 'link' author = uname user = uid text = '' linkKind = linkKind action = action other = oid otherProject = oproject otherNumber = onumber created = t0 }if (previous != null) {rec.previous = previous.idrec.previousProject = projectSlugOf(previous)rec.previousNumber = previous.number}eid = putEvent(rec)if (eid == null) { return { error = 'could not store the event: ' + eventsError() field = '' } }ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))t2 = ticketsTable.fetch(t.id)recordEvent(eid, t2)return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) related = relatedViews(t.id, extra) }}// SET (key = `<project>#<n>` / UUID) or REMOVE (key = '') the parent of a ticket (UUID).// Answers { error, field, forbidden? } or { ticket, event, related }.static setParent = (ticketId, user, key) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }if (!userOk(user)) { return authorMissing }k = clean(key)cur = parentLinkOf(t.id)curT = cur != null ? ticketRecord(cur.other) : nullif (k == '') {if (cur == null || curT == null) { return { error = 'the ticket has no parent' field = 'parent' } }if (!mayLink(t, curT, user)) { return linkForbidden }linksTable.delete(cur.id)return linkEvent(t, user, 'parent', 'removed', curT, null, [curT.id])}p = ticketByKey(k)if (p == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = 'parent' } }if (p.id == t.id) { return { error = 'a ticket cannot be its own parent' field = 'parent' } }if (curT != null && curT.id == p.id) { return { error = 'the parent is already ' + keyOf(p) field = 'parent' } }// no loop: the new parent must not be this ticket's child, grandchild, …let up = p.idlet steps = 0while (up != null && steps < 1000) {if (up == t.id) { return { error = 'a loop: ' + keyOf(p) + ' is below this ticket' field = 'parent' } }up = parentIdOf(up)steps = steps + 1}if (!mayLink(t, p, user)) { return linkForbidden }if (curT != null && !mayLink(t, curT, user)) { return linkForbidden }lid = linksTable.put({ kind = 'parent' ticket = t.id other = p.id user = user.id created = now() })if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }if (cur != null) { linksTable.delete(cur.id) }return linkEvent(t, user, 'parent', 'set', p, curT, [curT != null ? curT.id : null])}// does ticket `start` (transitively) wait on ticket `target`? (blocked-by links)static waitsOn = (start, target) => {stack = [start]seen = {}let steps = 0while (stack.length > 0 && steps < 10000) {cur = stack.pop()steps = steps + 1if (cur == target) { return true }if (seen['' + cur] != true) {seen['' + cur] = truefor (i of blockerIdsOf(cur)) { stack.push(i) }}}return false}// ADD (adding = true) or REMOVE a blocker of a ticket (UUID): ticket `key` blocks it.// `field` names the API field ('add' / 'remove'). Answers as setParent.static changeBlocker = (ticketId, user, key, adding, field) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }if (!userOk(user)) { return authorMissing }k = clean(key)if (k == '') { return { error = 'name the blocking ticket as <project>#<number>' field = field } }o = ticketByKey(k)if (o == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = field } }let existing = nullfor (l of linkRecords('ticket', t.id, 'blockedBy')) { if (l.other == o.id) { existing = l } }if (adding) {if (o.id == t.id) { return { error = 'a ticket cannot block itself' field = field } }if (existing != null) { return { error = 'already blocked by ' + keyOf(o) field = field } }if (waitsOn(o.id, t.id)) { return { error = 'a loop: ' + keyOf(o) + ' already waits on this ticket' field = field } }if (!mayLink(t, o, user)) { return linkForbidden }lid = linksTable.put({ kind = 'blockedBy' ticket = t.id other = o.id user = user.id created = now() })if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }return linkEvent(t, user, 'blockedBy', 'set', o, null, [])}if (existing == null) { return { error = 'not blocked by ' + keyOf(o) field = field } }if (!mayLink(t, o, user)) { return linkForbidden }linksTable.delete(existing.id)return linkEvent(t, user, 'blockedBy', 'removed', o, null, [o.id])}// ---- the one-time purge of #94, identity rule (lib/migrate.hl purgeTicket94): the writes of the tickets and links tables ----// removes the relation rows that point from or to a ticket (the other tickets stay); answers how manystatic removeLinksOf = (ticketId) => {hit = []for (field of ['ticket', 'other']) {found = linksTable.find(field, ticketId)if (countOf(found) > 0) { for (l of found) { if (!hit.includes(l.id)) { hit.push(l.id) } } }}for (id of hit) { linksTable.delete(id) }if (hit.length > 0) { linksTable.compactNow() }return hit.length}// a history event of ticket `ticketId` was removed: its count goes down by one (nothing else changes, `updated` stays)static forgetEventOf = (ticketId) => {t = ticketsTable.fetch(ticketId)if (t != null && t.events != null && t.events > 0) { ticketsTable.update(t.id, merged(t, { events = t.events - 1 })) }}static removeTicket = (ticketId) => { ticketsTable.delete(ticketId) }static compactTickets = () => { ticketsTable.compactNow() }// Administrative moves preserve identity; aliases always resolve directly by UUID.static moveChoices = (Hybrid t, Hybrid user) => {out = []if (t == null || !isAdminOf(t.project, user)) { return out }for (p of projectRecords()) {if (p.id != t.project && isAdminOf(p.id, user)) { out.push({ value = p.id label = p.title }) }}return out}static moveTicket = (String ticketId, Hybrid actor, String target) => {t = ticketRecord(ticketId)if (t == null) { return { error = 'no such ticket' } }p = projectByRef(target)if (!isAdminOf(t.project, actor) || p == null || !isAdminOf(p.id, actor)) {return { error = 'moving a ticket requires admin in both projects' forbidden = true field = 'project' }}if (p.id == t.project) { return { error = 'choose another project' field = 'project' } }n = nextNumber(p.id)oldKey = projectSlugOf(t) + '#' + t.numbernewKey = p.slug + '#' + nt0 = now()seq = (t.events != null ? t.events : 0) + 1// Reserve the old number before releasing its unique current path.alias = ticketPaths.put({ path = t.path ticket = t.id })if (alias == null) { return { error = 'could not reserve the old path' } }setNumberFloor(t.project, t.number)moveToProject(merged(t, { number = n }), p, t.state, t.createdBy, t.assignee)ticketsTable.update(t.id, merged(ticketsTable.fetch(t.id), { updated = t0 events = seq moved = true }))t2 = ticketRecord(t.id)eid = putEvent({ ticket = t.id projectId = p.id seq = seq kind = 'move' author = actor.name user = actor.id text = 'moved from ' + oldKey href = ticketHref(p.slug, n) created = t0 })sid = putEvent({ ticket = t.id projectId = t.project sourceOnly = true seq = seq kind = 'move' author = actor.name user = actor.id text = 'moved to ' + newKey href = ticketHref(p.slug, n) created = t0 })recordEvent(eid, t2)recordEvent(sid, t)return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) related = relatedViews(t.id, []) }}static createTicketForSession = (project, subject, summary, session) => {w = writerOfSession(session)if (w.error != null) { return { error = w.error } }return createTicket(project, subject, summary, w.user, null, null)}
Branches
Latest commits
- b8fdeee9Merge branch 'p39-routes' into mainTickets
- a0187a0a|||PR Remove redundant route-order loopmre
- 369e4b9cMerge branch 'k40-lists' into mainTickets
- 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
- 610d8e8aMerge branch 'records-t39' into mainTickets
- 32bcdf24|||PR records: GO P39 K40mre
- 4123c6d1Merge branch 'records-t38' into mainTickets
- cd3641a1|||PR records: day72 deploy live, tickets closedmre
- 7d44d852Merge branch 'records-t37' into mainTickets
- 926f7061|||PR records: merges, D36 deploymre
- bf58534eMerge branch 'l33-final' into mainTickets
- 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
- 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
- 5822cb3aMerge branch 'o34-clean' into mainTickets
- 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
- 14cf96b4Merge branch 'records-t36' into mainTickets
- 07749fa1|||PR records: day72 + #40 mergedmre
- ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre
- 6dea1c60Merge branch 'r35-day72' into mainTickets
- 7bcfdc22|||PR drop worker edits to conductor recordsmre