gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8d8e20538d8e2053Document subscription contract and exercise delta deliverymre8d8e2053/lib/tickets.hl

31.7 KB

  1. // lib/tickets.hl — TICKETS AND THEIR RELATIONS: the central logic of tickets.worldapi.org. Statics only, the server realm.
  2. // A face / an API route (components/, lib/api.hl) checks the session or token and calls one function here; every
  3. // write answers the rows the push carries.
  4. //
  5. // CREATOR'S CONVENTIONS (2026-09-24, ticket #38): every primary key is the mpackdb UUID
  6. // (`@id`, a string like '0mufbkwhlpjq'), never a `*id` counter; the files live in
  7. // storage/mpackdb/. A NUMBER A PERSON SEES is a separate field: tickets are numbered PER
  8. // PROJECT from 1 (`number`); tickets migrated from the old global store keep their old
  9. // global number as `oldNumber` (docs and comments say "#38"). Order never comes from key
  10. // order: lists sort by the stored times, a history by (created, seq).
  11. //
  12. // ticketsTable pk @id index project state source !path *oldNumber
  13. // { project (project @id — NOT the name), number, path ('<project @id>/<number>', unique),
  14. // oldNumber?, subject, summary, state, source, created, updated, events,
  15. // createdBy (users @id, '' = opened before the login), assignee (users @id, '') }
  16. // linksTable pk @id index @ticket @other (ticket #4, mission 017) { kind, ticket, other, user, created }
  17. // kind 'parent': `ticket` is a child of `other` (at most one per ticket)
  18. // kind 'blockedBy': `ticket` is blocked by `other` (waits on it)
  19. // A removed relation is deleted here; the history keeps it ('link' events, lib/events.hl).
  20. // Every write appends its event to the history (events.hl putEvent) and stores the ticket with the new
  21. // `events` count / `updated`; then the event stream numbers it and tells the listening programs (stream.hl
  22. // recordEvent, ticket #26). Projects, members and roles: lib/projects.hl; state names and page shapes:
  23. // lib/tickets-helpers.hl.
  24. //
  25. // WHO MAY is the role in the ticket's project (projects.hl): a refusal for a missing right has
  26. // `forbidden = true` (the API answers 403). EVERY WRITE HAS A USER (ticket #7): the logged-in user of the
  27. // web session or of the API token (users.hl). `source` is the import key (the ticket file's name) — an
  28. // import with a known source is answered with the existing ticket, never a second one.
  29. //
  30. // reading ticketRowOf, ticketRecord / ticketAt / ticketByRef / ticketByKey, ticketRows, inboxRows,
  31. // eventRows, ticketWithEvents, stateChoices, ticketRights
  32. // writing createTicket, addComment (with attachments: lib/attachments.hl), changeComment (edit / delete / like, lib/comments.hl), changeState, assignTicket,
  33. // editTicket, removeMember
  34. // relations relationsOf, relatedViews, setParent, changeBlocker
  35. import { MPackDB } from 'hl:mpackdb'
  36. import { now } from 'hl:time'
  37. import { storageDir, countOf, first, merged, clean, oneLine, isDigits, localStamp, newestFirst, oldestFirst, ticketHref, ticketApiHref, projectHrefOf } from './util.hl'
  38. import { nameOfUser } from './users.hl'
  39. import { projectRecord, projectByAnySlug, projectByRef, projectSlugOf, roleOf, rankOf, isMember, mayEditIn, memberRecord, memberRows, userByRef, assignChoices, userOk, authorMissing, removeMembership } from './projects.hl'
  40. import { states, inboxStates, stateOf, slugOf, refOf, keyOf, relationViewOf } from './tickets-helpers.hl'
  41. import { putEvent, eventsError, eventRecord, eventRowAt, historyOf, creatorNameOf } from './events.hl'
  42. import { editComment, deleteComment, likeComment, likersOf } from './comments.hl'
  43. import { recordEvent } from './stream.hl'
  44. import { checkFiles, storeFiles } from './attachments.hl'
  45. static ticketsTable = new MPackDB(file = storageDir + '/tickets.db', primaryKey = '@id', indexes = ['project', 'state', 'source', '!path', '*oldNumber'])
  46. static linksTable = new MPackDB(file = storageDir + '/links.db', primaryKey = '@id', indexes = ['@ticket', '@other'])
  47. // ---- the shapes a page and the API show ---------------------------------------------
  48. // A ROW IS A PLAIN HYBRID: what the View reads is what the browser receives.
  49. // `id` is the UUID; `number` + `project` (the slug) are what a person uses; `oldNumber` / `oldRef`
  50. // only on tickets migrated from the global numbering.
  51. static ticketRowOf = (t) => {
  52. n = t.events != null ? t.events : 0
  53. p = projectRecord(t.project)
  54. slug = p != null ? p.slug : ''
  55. byId = t.createdBy != null ? t.createdBy : ''
  56. toId = t.assignee != null ? t.assignee : ''
  57. row = {
  58. id = t.id
  59. project = slug
  60. projectId = t.project
  61. projectTitle = p != null ? p.title : ''
  62. number = t.number
  63. ref = '#' + t.number
  64. subject = t.subject
  65. summary = t.summary
  66. state = t.state
  67. stateSlug = slugOf(t.state)
  68. source = t.source != null ? t.source : ''
  69. created = localStamp(t.created)
  70. createdMs = t.created
  71. updated = localStamp(t.updated)
  72. updatedMs = t.updated
  73. events = n
  74. href = ticketHref(slug, t.number)
  75. apiHref = ticketApiHref(slug, t.number)
  76. projectHref = projectHrefOf(slug)
  77. hasOld = t.oldNumber != null
  78. oldRef = t.oldNumber != null ? '#' + t.oldNumber : ''
  79. createdById = byId
  80. createdBy = byId != '' ? nameOfUser(byId) : creatorNameOf(t)
  81. assigneeId = toId
  82. assignee = toId != '' ? nameOfUser(toId) : ''
  83. hasAssignee = toId != ''
  84. }
  85. if (t.oldNumber != null) { row.oldNumber = t.oldNumber }
  86. // ticket #4 (mission 017): the relations, as refs with their states (relationsOf below)
  87. rel = relationsOf(t)
  88. row.parent = rel.parent
  89. row.children = rel.children
  90. row.allChildrenConfirmed = rel.allChildrenConfirmed
  91. row.blockedBy = rel.blockedBy
  92. row.blocks = rel.blocks
  93. return row
  94. }
  95. // ---- finding a ticket -------------------------------------------------------------------
  96. static ticketRecord = (uuid) => { return uuid == null || uuid == '' ? null : ticketsTable.fetch('' + uuid) }
  97. // `project` is a slug (a former one too)
  98. static ticketAt = (project, number) => {
  99. if (project == null || !isDigits(number)) { return null }
  100. p = projectByAnySlug(project)
  101. if (p == null) { return null }
  102. return first(ticketsTable.find('path', p.id + '/' + toNumber('' + number)))
  103. }
  104. static ticketByOld = (oldNumber) => {
  105. if (!isDigits(oldNumber)) { return null }
  106. return first(ticketsTable.find('oldNumber', toNumber('' + oldNumber)))
  107. }
  108. // what `/api/tickets/:ref` and `/tickets/:ref` accept: the OLD global number (digits)
  109. // or the ticket's UUID
  110. static ticketByRef = (ref) => {
  111. if (ref == null) { return null }
  112. if (isDigits(ref)) { return ticketByOld(ref) }
  113. return ticketRecord(ref)
  114. }
  115. // ---- the writes of the #20 migration (lib/migrate.hl calls these; the tickets table is written only here) ----
  116. // every ticket record, in the table's order
  117. static ticketRecords = () => { return ticketsTable.find(null, null) }
  118. // the ticket records of one project (project @id)
  119. static ticketRecordsOf = (projectId) => { return ticketsTable.find('project', projectId) }
  120. // a ticket from before #20 points at its project by name; it now points at the project record `p`, gets the new
  121. // state name, its creator and its assignee
  122. static moveToProject = (t, p, newState, creatorId, assigneeId) => {
  123. ticketsTable.update(t.id, merged(t, { project = p.id path = p.id + '/' + t.number state = newState createdBy = creatorId assignee = assigneeId }))
  124. }
  125. // ---- reads -------------------------------------------------------------------------
  126. // newest update first; both filters optional (null = all); `project` is a slug
  127. static ticketRows = (project, state) => {
  128. rows = []
  129. let all = null
  130. if (project != null) {
  131. p = projectByAnySlug(project)
  132. if (p == null) { return rows }
  133. all = ticketsTable.find('project', p.id)
  134. } else {
  135. all = ticketsTable.find(null, null)
  136. }
  137. if (countOf(all) == 0) { return rows }
  138. for (t of all) {
  139. if (state == null || t.state == state) { rows.push(ticketRowOf(t)) }
  140. }
  141. return newestFirst(rows, 'updatedMs')
  142. }
  143. // the newest `n` rows of ticketRows and how many there are (the list page draws a page at a time)
  144. // (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)
  145. static firstRows = (project, state, n) => {
  146. let recs = []
  147. let all = null
  148. if (project != null) {
  149. p = projectByAnySlug(project)
  150. if (p == null) { return { rows = [] total = 0 } }
  151. all = ticketsTable.find('project', p.id)
  152. } else {
  153. all = ticketsTable.find(null, null)
  154. }
  155. if (countOf(all) == 0) { return { rows = [] total = 0 } }
  156. for (t of all) {
  157. if (state == null || t.state == state) { recs.push(t) }
  158. }
  159. recs = newestFirst(recs, 'updated')
  160. rows = []
  161. let i = 0
  162. while (i < recs.length && i < n) {
  163. rows.push(ticketRowOf(recs[i]))
  164. i = i + 1
  165. }
  166. return { rows = rows total = recs.length }
  167. }
  168. // THE INBOX of a user: the tickets ASSIGNED TO THEM in pending and in review, two lists
  169. static inboxRows = (user) => {
  170. out = { pending = [] review = [] }
  171. if (user == null || user.id == null) { return out }
  172. a = []
  173. b = []
  174. ps = ticketsTable.find('state', 'pending')
  175. if (countOf(ps) > 0) { for (t of ps) { if (t.assignee == user.id) { a.push(ticketRowOf(t)) } } }
  176. rs = ticketsTable.find('state', 'review')
  177. if (countOf(rs) > 0) { for (t of rs) { if (t.assignee == user.id) { b.push(ticketRowOf(t)) } } }
  178. out.pending = newestFirst(a, 'updatedMs')
  179. out.review = newestFirst(b, 'updatedMs')
  180. return out
  181. }
  182. static inboxCountOf = (user) => {
  183. x = inboxRows(user)
  184. return x.pending.length + x.review.length
  185. }
  186. // the page's row of `/<project>/<number>` (ticket #25), or null
  187. static ticketRowAt = (project, number) => {
  188. t = ticketAt(project, number)
  189. return t == null ? null : ticketRowOf(t)
  190. }
  191. // the event history of a ticket (UUID), oldest first (events.hl historyOf)
  192. static eventRows = (ticketId) => {
  193. t = ticketRecord(ticketId)
  194. if (t == null) { return [] }
  195. return historyOf(t)
  196. }
  197. // the options of a state select: [{ value, label }] — the states THIS user may move the ticket to
  198. // (a `use` member: only open ⇄ review; `edit` / `admin`: every other state)
  199. static stateChoices = (t, user) => {
  200. out = []
  201. if (t == null || user == null) { return out }
  202. role = roleOf(t.project, user)
  203. for (s of states) {
  204. if (s != t.state && mayMoveTo(role, t.state, s)) { out.push({ value = s label = s }) }
  205. }
  206. return out
  207. }
  208. static mayMoveTo = (role, current, target) => {
  209. if (rankOf(role) >= 2) { return true }
  210. if (rankOf(role) == 1) { return (current == 'open' && target == 'review') || (current == 'review' && target == 'open') }
  211. return false
  212. }
  213. // what a user may do on a ticket (a record): comment (a member), edit / assign (edit, admin), the states they
  214. // may move it to, and the members it can be assigned to — the ticket page asks after a login or a change
  215. static ticketRights = (t, user) => {
  216. return { comment = isMember(t.project, user) edit = mayEdit(t, user) options = stateChoices(t, user) members = assignChoices(t.project) }
  217. }
  218. // ---- writes: each answers what the push carries --------------------------------------
  219. // The author is the user — there is no free author field any more.
  220. // the next per-project number: the highest one in the project + 1 (first = 1)
  221. static nextNumber = (projectId) => {
  222. let top = 0
  223. all = ticketsTable.find('project', projectId)
  224. if (countOf(all) > 0) {
  225. for (t of all) { if (t.number != null && t.number > top) { top = t.number } }
  226. }
  227. return top + 1
  228. }
  229. // answers { error, field, forbidden? } or { ticket (row), event (row), existed }
  230. // `project` = the slug (or id) of an existing project; `assignee` optional (a member's name / id)
  231. static createTicket = (project, subject, summary, user, source, assignee) => {
  232. s = oneLine(subject)
  233. if (clean(project) == '') { return { error = 'project is required' field = 'project' } }
  234. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  235. if (!userOk(user)) { return authorMissing }
  236. p = projectByRef(clean(project))
  237. if (p == null) { return { error = 'no such project: ' + clean(project) field = 'project' } }
  238. 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 } }
  239. let who = ''
  240. if (assignee != null && clean(assignee) != '') {
  241. r = userByRef(assignee, p.id)
  242. if (r.error != null) { return { error = r.error field = 'assignee' } }
  243. who = r.user.id
  244. }
  245. src = clean(source)
  246. if (src != '') {
  247. known = ticketsTable.find('source', src)
  248. if (countOf(known) > 0) { return { ticket = ticketRowOf(known[0]) event = null existed = true } }
  249. }
  250. t0 = now()
  251. n = nextNumber(p.id)
  252. 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 })
  253. if (id == null) { return { error = 'could not store the ticket: ' + ticketsTable.lastError() field = '' } }
  254. t = ticketsTable.fetch(id)
  255. eid = putEvent({ ticket = id seq = 1 kind = 'created' author = user.name user = user.id text = src != '' ? 'imported from ' + src : '' created = t0 })
  256. out = { ticket = ticketRowOf(t) event = eventRowAt(eid, t) existed = false }
  257. if (who != '') {
  258. let seq = 2
  259. aid = putEvent({ ticket = id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = '' created = t0 })
  260. ticketsTable.update(id, merged(t, { events = seq }))
  261. t2 = ticketsTable.fetch(id)
  262. out.ticket = ticketRowOf(t2)
  263. out.assignEvent = eventRowAt(aid, t2)
  264. recordEvent(eid, t2)
  265. recordEvent(aid, t2)
  266. } else {
  267. recordEvent(eid, t)
  268. }
  269. return out
  270. }
  271. // answers { error } or { ticket, event }; `ticketId` is the UUID. Any member may comment.
  272. // tickets#27 (mission 017): `files` = the attachments ([{ name, type, bytes }], null / [] = none; lib/attachments.hl checks the
  273. // limits and the content and stores them). A comment with files may have no text; without files it needs text, as before.
  274. static addComment = (ticketId, user, text, files) => {
  275. t = ticketRecord(ticketId)
  276. if (t == null) { return { error = 'no such ticket' } }
  277. body = clean(text)
  278. given = files != null && countOf(files) > 0
  279. if (body == '' && !given) { return { error = 'a comment needs text' field = 'text' } }
  280. if (!userOk(user)) { return authorMissing }
  281. if (!isMember(t.project, user)) { return { error = 'only a member of the project can comment' field = '' forbidden = true } }
  282. checked = checkFiles(given ? files : null)
  283. if (checked.error != null) { return { error = checked.error field = checked.field tooBig = checked.tooBig } }
  284. t0 = now()
  285. let seq = (t.events != null ? t.events : 0) + 1
  286. eid = putEvent({ ticket = t.id seq = seq kind = 'comment' author = user.name user = user.id text = body created = t0 })
  287. stored = storeFiles(eid, t, user, checked.files)
  288. if (stored != null) { console.log('attachments: ' + stored.error) }
  289. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  290. t2 = ticketsTable.fetch(t.id)
  291. recordEvent(eid, t2)
  292. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  293. }
  294. // mission 016: EDIT ('edit', with `text`), DELETE ('delete') or LIKE ('like': again = take it back) the comment `commentId`
  295. // (an events @id) of ticket `ticketId`. Who may and what is kept: lib/comments.hl (edit / delete: its author; like: any
  296. // member). The ticket's `updated` and `events` stay: these are no new history events (and nothing for the event stream).
  297. // Answers { error, field, forbidden? } or { ticket, event (the comment's row as it is now), liked (a like: true = the user
  298. // likes it now) }.
  299. static changeComment = (ticketId, commentId, user, action, text) => {
  300. t = ticketRecord(ticketId)
  301. if (t == null) { return { error = 'no such ticket' } }
  302. e = commentId == null || hlTypeName(commentId) != 'String' || commentId == '' ? null : eventRecord(commentId)
  303. if (e == null || e.ticket != t.id) { return { error = 'no such comment on this ticket' field = 'comment' } }
  304. let bad = null
  305. if (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 = '' } }
  306. if (bad != null) { return bad }
  307. out = { ticket = ticketRowOf(t) event = eventRowAt(e.id, t) }
  308. if (action == 'like') { out.liked = likersOf(e.id).includes(user.id) }
  309. return out
  310. }
  311. // the admin who gets a ticket that lands in the inbox with nobody assigned: the oldest admin
  312. static defaultAssignee = (projectId) => {
  313. for (m of memberRows(projectId)) { if (m.role == 'admin') { return m.user } }
  314. return ''
  315. }
  316. // answers { error } or { ticket, event, assignEvent? }; an optional note rides on the state event.
  317. // `forbidden = true` on a refusal the user may not overcome (the role does not allow that move).
  318. // A ticket that goes to review / pending with nobody assigned is assigned to the project's first admin
  319. // (so it reaches an inbox) — a second, 'assign' event.
  320. static changeState = (ticketId, state, user, note) => {
  321. t = ticketRecord(ticketId)
  322. if (t == null) { return { error = 'no such ticket' } }
  323. s = stateOf(state)
  324. if (s == null) { return { error = 'unknown state — one of: ' + states.join(', ') field = 'state' } }
  325. if (s == t.state) { return { error = 'the ticket is already ' + s field = 'state' } }
  326. if (!userOk(user)) { return authorMissing }
  327. role = roleOf(t.project, user)
  328. if (role == null) { return { error = 'only a member of the project can change the state' field = 'state' forbidden = true } }
  329. if (!mayMoveTo(role, t.state, s)) { return { error = 'the role ' + role + ' can only move a ticket between open and review' field = 'state' forbidden = true } }
  330. t0 = now()
  331. let seq = (t.events != null ? t.events : 0) + 1
  332. eid = putEvent({ ticket = t.id seq = seq kind = 'state' author = user.name user = user.id text = clean(note) from = t.state to = s created = t0 })
  333. changes = { state = s updated = t0 events = seq }
  334. let aid = null
  335. let auto = ''
  336. if (inboxStates.includes(s) && (t.assignee == null || t.assignee == '')) { auto = defaultAssignee(t.project) }
  337. if (auto != '') {
  338. seq = seq + 1
  339. aid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = auto previous = '' created = t0 })
  340. changes.assignee = auto
  341. changes.events = seq
  342. }
  343. ticketsTable.update(t.id, merged(t, changes))
  344. t2 = ticketsTable.fetch(t.id)
  345. recordEvent(eid, t2)
  346. if (aid != null) { recordEvent(aid, t2) }
  347. out = { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  348. if (aid != null) { out.assignEvent = eventRowAt(aid, t2) }
  349. return out
  350. }
  351. // answers { error, forbidden? } or { ticket, event }; `assignee` = a member's users @id, '' = nobody
  352. static assignTicket = (ticketId, user, assignee) => {
  353. t = ticketRecord(ticketId)
  354. if (t == null) { return { error = 'no such ticket' } }
  355. if (!userOk(user)) { return authorMissing }
  356. if (!mayEditIn(t.project, user)) { return { error = 'you need the role edit or admin to assign a ticket' field = 'assignee' forbidden = true } }
  357. who = assignee == null ? '' : clean(assignee)
  358. if (who != '' && memberRecord(t.project, who) == null) { return { error = 'the assignee must be a member of the project' field = 'assignee' } }
  359. was = t.assignee != null ? t.assignee : ''
  360. if (who == was) { return { error = who == '' ? 'the ticket is not assigned' : 'the ticket is already assigned to that person' field = 'assignee' } }
  361. t0 = now()
  362. let seq = (t.events != null ? t.events : 0) + 1
  363. eid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = was created = t0 })
  364. ticketsTable.update(t.id, merged(t, { assignee = who updated = t0 events = seq }))
  365. t2 = ticketsTable.fetch(t.id)
  366. recordEvent(eid, t2)
  367. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  368. }
  369. // ---- editing (ticket #8, mission 014; ticket #20: by the role) --------------------------------
  370. // THE AUTHOR of a ticket is `createdBy` (users @id), or null for a ticket opened before the login
  371. // existed. MAY THIS USER EDIT the ticket (a record)? Any member with the role edit or admin of
  372. // its project (`use` members only comment and move it between open and review).
  373. static mayEdit = (t, user) => {
  374. if (t == null || !userOk(user)) { return false }
  375. return mayEditIn(t.project, user)
  376. }
  377. static mayEditId = (ticketId, user) => { return mayEdit(ticketRecord(ticketId), user) }
  378. // answers { error, field?, forbidden? } or { ticket, event }. `subject` / `summary` null = keep
  379. // that one. The previous values stay in the 'edit' event (append-only history).
  380. static editTicket = (ticketId, user, subject, summary) => {
  381. t = ticketRecord(ticketId)
  382. if (t == null) { return { error = 'no such ticket' } }
  383. if (!userOk(user)) { return authorMissing }
  384. if (!mayEdit(t, user)) { return { error = 'you need the role edit or admin in the project to edit a ticket' field = '' forbidden = true } }
  385. if (subject == null && summary == null) { return { error = 'nothing to change: give subject and/or summary' field = '' } }
  386. let oldSummary = t.summary != null ? t.summary : ''
  387. s = subject != null ? oneLine(subject) : t.subject
  388. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  389. sm = summary != null ? clean(summary) : oldSummary
  390. if (s == t.subject && sm == oldSummary) { return { error = 'nothing changed' field = subject != null ? 'subject' : 'summary' } }
  391. t0 = now()
  392. let seq = (t.events != null ? t.events : 0) + 1
  393. eid = 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 })
  394. if (eid == null) { return { error = 'could not store the edit: ' + eventsError() field = '' } }
  395. ticketsTable.update(t.id, merged(t, { subject = s summary = sm updated = t0 events = seq }))
  396. t2 = ticketsTable.fetch(t.id)
  397. recordEvent(eid, t2)
  398. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  399. }
  400. // an admin removes a member (projects.hl removeMembership); the tickets assigned to the person are no longer
  401. // assigned to anybody. Answers { members } or { error, forbidden? }
  402. static removeMember = (projectId, actor, userId) => {
  403. r = removeMembership(projectId, actor, userId)
  404. if (r.error != null) { return r }
  405. all = ticketsTable.find('project', projectId)
  406. if (countOf(all) > 0) {
  407. for (t of all) {
  408. if (t.assignee == userId) { ticketsTable.update(t.id, merged(t, { assignee = '' })) }
  409. }
  410. }
  411. return r
  412. }
  413. // the API's view of one ticket (a record): the row and its whole history
  414. static ticketWithEvents = (t) => {
  415. if (t == null) { return null }
  416. return { ticket = ticketRowOf(t) events = eventRows(t.id) }
  417. }
  418. // ---- relations: parent / child and blocked-by (ticket #4, mission 017) ----------------------
  419. // A ticket has at most ONE PARENT (any project); a parent lists its CHILDREN with their states.
  420. // A ticket can be BLOCKED BY other tickets (any project) — it waits on them; the other side
  421. // shows what it BLOCKS. The scheduler reads them from the JSON rows (`parent`, `children`,
  422. // `blockedBy`, `blocks`, each a ref with the state) and the Markdown view.
  423. // PARENT STATE: `allChildrenConfirmed` (the key kept for the clients; it now means DONE) is true when
  424. // a ticket has children and every one of them is `done`. It is only SHOWN ("all children done") — the
  425. // parent's own state is never changed by it.
  426. // WHO MAY set / remove a relation (ticket #20): a member with the role edit or admin in the project of
  427. // EITHER of the two tickets. Replacing a parent needs the
  428. // right for the old pair AND the new pair. No loops: a ticket cannot be its own ancestor, and
  429. // cannot (transitively) wait on itself.
  430. // Tickets are named as `<project>#<number>` (spaces around `#` allowed) or by their UUID.
  431. // the link records of one side, oldest first (stored time): field 'ticket' = this ticket's own
  432. // relations (its parent, its blockers), field 'other' = the ones pointing at it (children, blocked)
  433. static linkRecords = (field, ticketId, kind) => {
  434. out = []
  435. if (ticketId == null || ticketId == '') { return out }
  436. all = linksTable.find(field, '' + ticketId)
  437. if (countOf(all) == 0) { return out }
  438. for (l of all) { if (l.kind == kind) { out.push(l) } }
  439. return oldestFirst(out, 'created')
  440. }
  441. static parentLinkOf = (ticketId) => { return first(linkRecords('ticket', ticketId, 'parent')) }
  442. static parentIdOf = (ticketId) => {
  443. l = parentLinkOf(ticketId)
  444. return l == null ? null : l.other
  445. }
  446. static idsOfLinks = (links, field) => {
  447. out = []
  448. for (l of links) { out.push(l[field]) }
  449. return out
  450. }
  451. static childIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'parent'), 'ticket') }
  452. static blockerIdsOf = (ticketId) => { return idsOfLinks(linkRecords('ticket', ticketId, 'blockedBy'), 'other') }
  453. static blockedIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'blockedBy'), 'ticket') }
  454. static refsOfIds = (ids) => {
  455. out = []
  456. for (i of ids) {
  457. t = ticketRecord(i)
  458. if (t != null) { out.push(refOf(t)) }
  459. }
  460. return out
  461. }
  462. // { parent (ref or null), children, blockedBy, blocks (lists of refs), allChildrenConfirmed }
  463. static relationsOf = (t) => {
  464. pid = parentIdOf(t.id)
  465. p = pid != null ? ticketRecord(pid) : null
  466. kids = refsOfIds(childIdsOf(t.id))
  467. let all = kids.length > 0
  468. for (c of kids) { if (c.state != 'done') { all = false } }
  469. return { parent = p != null ? refOf(p) : null children = kids allChildrenConfirmed = all blockedBy = refsOfIds(blockerIdsOf(t.id)) blocks = refsOfIds(blockedIdsOf(t.id)) }
  470. }
  471. // the relation views of a ticket AND every ticket related to it (+ `extra` ids: a parent or
  472. // blocker just removed) — what a write pushes, so every open page of them follows
  473. static relatedViews = (ticketId, extra) => {
  474. ids = ['' + ticketId]
  475. seen = {}
  476. seen['' + ticketId] = true
  477. more = []
  478. pid = parentIdOf(ticketId)
  479. if (pid != null) { more.push(pid) }
  480. for (i of childIdsOf(ticketId)) { more.push(i) }
  481. for (i of blockerIdsOf(ticketId)) { more.push(i) }
  482. for (i of blockedIdsOf(ticketId)) { more.push(i) }
  483. for (i of extra) { if (i != null) { more.push(i) } }
  484. for (i of more) {
  485. if (seen['' + i] != true) {
  486. seen['' + i] = true
  487. ids.push('' + i)
  488. }
  489. }
  490. out = []
  491. for (i of ids) {
  492. t = ticketRecord(i)
  493. if (t != null) { out.push(relationViewOf(ticketRowOf(t))) }
  494. }
  495. return out
  496. }
  497. // `<project>#<number>` (spaces around '#' allowed) or a UUID → the ticket record, or null
  498. static ticketByKey = (key) => {
  499. k = clean(key)
  500. if (k == '') { return null }
  501. at = k.indexOf('#')
  502. if (at < 0) { return isDigits(k) ? null : ticketRecord(k) }
  503. p = k.slice(0, at).trim()
  504. n = k.slice(at + 1).trim()
  505. if (p == '') { return null }
  506. return ticketAt(p, n)
  507. }
  508. // WHO MAY CHANGE A RELATION (mission ST): a relation is written on ONE ticket — the one whose parent / blocker changes (`a`) — so
  509. // 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
  510. // 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.
  511. static mayLink = (a, b, user) => {
  512. if (!userOk(user)) { return false }
  513. return a != null && mayEditIn(a.project, user)
  514. }
  515. static linkForbidden = { error = 'you need the role edit or admin in the project of this ticket to change its relations' field = '' forbidden = true }
  516. // the history event of a relation change, on ticket `t`; answers { ticket, event, related }
  517. static linkEvent = (t, user, linkKind, action, other, previous, extra) => {
  518. t0 = now()
  519. let seq = (t.events != null ? t.events : 0) + 1
  520. // the values BEFORE the literal: an entry named `other` / `user` would shadow the variable
  521. // for the entries after it (mission 011 lesson)
  522. uname = user.name
  523. uid = user.id
  524. oid = other.id
  525. oproject = projectSlugOf(other)
  526. onumber = other.number
  527. rec = { ticket = t.id seq = seq kind = 'link' author = uname user = uid text = '' linkKind = linkKind action = action other = oid otherProject = oproject otherNumber = onumber created = t0 }
  528. if (previous != null) {
  529. rec.previous = previous.id
  530. rec.previousProject = projectSlugOf(previous)
  531. rec.previousNumber = previous.number
  532. }
  533. eid = putEvent(rec)
  534. if (eid == null) { return { error = 'could not store the event: ' + eventsError() field = '' } }
  535. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  536. t2 = ticketsTable.fetch(t.id)
  537. recordEvent(eid, t2)
  538. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) related = relatedViews(t.id, extra) }
  539. }
  540. // SET (key = `<project>#<n>` / UUID) or REMOVE (key = '') the parent of a ticket (UUID).
  541. // Answers { error, field, forbidden? } or { ticket, event, related }.
  542. static setParent = (ticketId, user, key) => {
  543. t = ticketRecord(ticketId)
  544. if (t == null) { return { error = 'no such ticket' } }
  545. if (!userOk(user)) { return authorMissing }
  546. k = clean(key)
  547. cur = parentLinkOf(t.id)
  548. curT = cur != null ? ticketRecord(cur.other) : null
  549. if (k == '') {
  550. if (cur == null || curT == null) { return { error = 'the ticket has no parent' field = 'parent' } }
  551. if (!mayLink(t, curT, user)) { return linkForbidden }
  552. linksTable.delete(cur.id)
  553. return linkEvent(t, user, 'parent', 'removed', curT, null, [curT.id])
  554. }
  555. p = ticketByKey(k)
  556. if (p == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = 'parent' } }
  557. if (p.id == t.id) { return { error = 'a ticket cannot be its own parent' field = 'parent' } }
  558. if (curT != null && curT.id == p.id) { return { error = 'the parent is already ' + keyOf(p) field = 'parent' } }
  559. // no loop: the new parent must not be this ticket's child, grandchild, …
  560. let up = p.id
  561. let steps = 0
  562. while (up != null && steps < 1000) {
  563. if (up == t.id) { return { error = 'a loop: ' + keyOf(p) + ' is below this ticket' field = 'parent' } }
  564. up = parentIdOf(up)
  565. steps = steps + 1
  566. }
  567. if (!mayLink(t, p, user)) { return linkForbidden }
  568. if (curT != null && !mayLink(t, curT, user)) { return linkForbidden }
  569. lid = linksTable.put({ kind = 'parent' ticket = t.id other = p.id user = user.id created = now() })
  570. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  571. if (cur != null) { linksTable.delete(cur.id) }
  572. return linkEvent(t, user, 'parent', 'set', p, curT, [curT != null ? curT.id : null])
  573. }
  574. // does ticket `start` (transitively) wait on ticket `target`? (blocked-by links)
  575. static waitsOn = (start, target) => {
  576. stack = [start]
  577. seen = {}
  578. let steps = 0
  579. while (stack.length > 0 && steps < 10000) {
  580. cur = stack.pop()
  581. steps = steps + 1
  582. if (cur == target) { return true }
  583. if (seen['' + cur] != true) {
  584. seen['' + cur] = true
  585. for (i of blockerIdsOf(cur)) { stack.push(i) }
  586. }
  587. }
  588. return false
  589. }
  590. // ADD (adding = true) or REMOVE a blocker of a ticket (UUID): ticket `key` blocks it.
  591. // `field` names the API field ('add' / 'remove'). Answers as setParent.
  592. static changeBlocker = (ticketId, user, key, adding, field) => {
  593. t = ticketRecord(ticketId)
  594. if (t == null) { return { error = 'no such ticket' } }
  595. if (!userOk(user)) { return authorMissing }
  596. k = clean(key)
  597. if (k == '') { return { error = 'name the blocking ticket as <project>#<number>' field = field } }
  598. o = ticketByKey(k)
  599. if (o == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = field } }
  600. let existing = null
  601. for (l of linkRecords('ticket', t.id, 'blockedBy')) { if (l.other == o.id) { existing = l } }
  602. if (adding) {
  603. if (o.id == t.id) { return { error = 'a ticket cannot block itself' field = field } }
  604. if (existing != null) { return { error = 'already blocked by ' + keyOf(o) field = field } }
  605. if (waitsOn(o.id, t.id)) { return { error = 'a loop: ' + keyOf(o) + ' already waits on this ticket' field = field } }
  606. if (!mayLink(t, o, user)) { return linkForbidden }
  607. lid = linksTable.put({ kind = 'blockedBy' ticket = t.id other = o.id user = user.id created = now() })
  608. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  609. return linkEvent(t, user, 'blockedBy', 'set', o, null, [])
  610. }
  611. if (existing == null) { return { error = 'not blocked by ' + keyOf(o) field = field } }
  612. if (!mayLink(t, o, user)) { return linkForbidden }
  613. linksTable.delete(existing.id)
  614. return linkEvent(t, user, 'blockedBy', 'removed', o, null, [o.id])
  615. }

Branches

Latest commits

  • 8d8e2053Document subscription contract and exercise delta deliverymre
  • fd23726aAdd subscription delta API and signed wake bridgemre
  • c5d28fb5Tickets conductor: S51 startedmre
  • fd6ca1e6Tickets conductor: brief 027 waker design, push-test projectmre
  • e448e656Tickets conductor: STATUS #51mre
  • 1c10857bTickets conductor: P51 eval, brief 027mre
  • e725969dTickets conductor: #51 directionmre
  • 1b5c63ddTickets conductor: P51 startedmre
  • 9f13fbdaTickets conductor: brief 026 prioritymre
  • acc477d9Tickets conductor: brief 026 + Vinzenz recommendationsmre
  • 9233a734Tickets conductor: brief 026 completemre
  • 5da589fdTickets conductor: brief 026 + Gitoria's answermre
  • a3cd5329Tickets conductor: tickets#51 opened, brief 026 draftmre
  • 6f6e5797Tickets conductor: STATUS wordingmre
  • 957de51fTickets conductor: T36 live, #36 review, #50 donemre
  • bc2fde32Merge branch 'main' into t36-stylemre
  • b7ca093atests: wait for the new row and normalize editor marker spacesmre
  • 41da3525Tickets conductor: flake cause, T36 deploy stepmre
  • 64c477e6Tickets conductor: deploy waits for Arachnemre
  • 467d7286Tickets conductor: T36 done, deploy questionmre