gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc69cd5f3c69cd5f3Merge branch 'pr-flow' into mainTicketsc69cd5f3/lib/tickets.hl

32.8 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. p = projectRecord(projectId)
  223. let top = p != null && p.numberFloor != null ? p.numberFloor : 0
  224. all = ticketsTable.find('project', projectId)
  225. if (countOf(all) > 0) {
  226. for (t of all) { if (t.number != null && t.number > top) { top = t.number } }
  227. }
  228. return top + 1
  229. }
  230. // answers { error, field, forbidden? } or { ticket (row), event (row), existed }
  231. // `project` = the slug (or id) of an existing project; `assignee` optional (a member's name / id)
  232. static createTicket = (project, subject, summary, user, source, assignee) => {
  233. s = oneLine(subject)
  234. if (clean(project) == '') { return { error = 'project is required' field = 'project' } }
  235. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  236. if (!userOk(user)) { return authorMissing }
  237. p = projectByRef(clean(project))
  238. if (p == null) { return { error = 'no such project: ' + clean(project) field = 'project' } }
  239. 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 } }
  240. let who = ''
  241. if (assignee != null && clean(assignee) != '') {
  242. r = userByRef(assignee, p.id)
  243. if (r.error != null) { return { error = r.error field = 'assignee' } }
  244. who = r.user.id
  245. }
  246. src = clean(source)
  247. if (src != '') {
  248. known = ticketsTable.find('source', src)
  249. if (countOf(known) > 0) { return { ticket = ticketRowOf(known[0]) event = null existed = true } }
  250. }
  251. t0 = now()
  252. n = nextNumber(p.id)
  253. 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 })
  254. if (id == null) { return { error = 'could not store the ticket: ' + ticketsTable.lastError() field = '' } }
  255. t = ticketsTable.fetch(id)
  256. eid = putEvent({ ticket = id seq = 1 kind = 'created' author = user.name user = user.id text = src != '' ? 'imported from ' + src : '' created = t0 })
  257. out = { ticket = ticketRowOf(t) event = eventRowAt(eid, t) existed = false }
  258. if (who != '') {
  259. let seq = 2
  260. aid = putEvent({ ticket = id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = '' created = t0 })
  261. ticketsTable.update(id, merged(t, { events = seq }))
  262. t2 = ticketsTable.fetch(id)
  263. out.ticket = ticketRowOf(t2)
  264. out.assignEvent = eventRowAt(aid, t2)
  265. recordEvent(eid, t2)
  266. recordEvent(aid, t2)
  267. } else {
  268. recordEvent(eid, t)
  269. }
  270. return out
  271. }
  272. // answers { error } or { ticket, event }; `ticketId` is the UUID. Any member may comment.
  273. // tickets#27 (mission 017): `files` = the attachments ([{ name, type, bytes }], null / [] = none; lib/attachments.hl checks the
  274. // limits and the content and stores them). A comment with files may have no text; without files it needs text, as before.
  275. static addComment = (ticketId, user, text, files) => {
  276. t = ticketRecord(ticketId)
  277. if (t == null) { return { error = 'no such ticket' } }
  278. body = clean(text)
  279. given = files != null && countOf(files) > 0
  280. if (body == '' && !given) { return { error = 'a comment needs text' field = 'text' } }
  281. if (!userOk(user)) { return authorMissing }
  282. if (!isMember(t.project, user)) { return { error = 'only a member of the project can comment' field = '' forbidden = true } }
  283. checked = checkFiles(given ? files : null)
  284. if (checked.error != null) { return { error = checked.error field = checked.field tooBig = checked.tooBig } }
  285. t0 = now()
  286. let seq = (t.events != null ? t.events : 0) + 1
  287. eid = putEvent({ ticket = t.id seq = seq kind = 'comment' author = user.name user = user.id text = body created = t0 })
  288. stored = storeFiles(eid, t, user, checked.files)
  289. if (stored != null) { console.log('attachments: ' + stored.error) }
  290. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  291. t2 = ticketsTable.fetch(t.id)
  292. recordEvent(eid, t2)
  293. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  294. }
  295. // mission 016: EDIT ('edit', with `text`), DELETE ('delete') or LIKE ('like': again = take it back) the comment `commentId`
  296. // (an events @id) of ticket `ticketId`. Who may and what is kept: lib/comments.hl (edit / delete: its author; like: any
  297. // member). The ticket's `updated` and `events` stay: these are no new history events (and nothing for the event stream).
  298. // Answers { error, field, forbidden? } or { ticket, event (the comment's row as it is now), liked (a like: true = the user
  299. // likes it now) }.
  300. static changeComment = (ticketId, commentId, user, action, text) => {
  301. t = ticketRecord(ticketId)
  302. if (t == null) { return { error = 'no such ticket' } }
  303. e = commentId == null || hlTypeName(commentId) != 'String' || commentId == '' ? null : eventRecord(commentId)
  304. if (e == null || e.ticket != t.id) { return { error = 'no such comment on this ticket' field = 'comment' } }
  305. let bad = null
  306. 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 = '' } }
  307. if (bad != null) { return bad }
  308. out = { ticket = ticketRowOf(t) event = eventRowAt(e.id, t) }
  309. if (action == 'like') { out.liked = likersOf(e.id).includes(user.id) }
  310. return out
  311. }
  312. // the admin who gets a ticket that lands in the inbox with nobody assigned: the oldest admin
  313. static defaultAssignee = (projectId) => {
  314. for (m of memberRows(projectId)) { if (m.role == 'admin') { return m.user } }
  315. return ''
  316. }
  317. // answers { error } or { ticket, event, assignEvent? }; an optional note rides on the state event.
  318. // `forbidden = true` on a refusal the user may not overcome (the role does not allow that move).
  319. // A ticket that goes to review / pending with nobody assigned is assigned to the project's first admin
  320. // (so it reaches an inbox) — a second, 'assign' event.
  321. static changeState = (ticketId, state, user, note) => {
  322. t = ticketRecord(ticketId)
  323. if (t == null) { return { error = 'no such ticket' } }
  324. s = stateOf(state)
  325. if (s == null) { return { error = 'unknown state — one of: ' + states.join(', ') field = 'state' } }
  326. if (s == t.state) { return { error = 'the ticket is already ' + s field = 'state' } }
  327. if (!userOk(user)) { return authorMissing }
  328. role = roleOf(t.project, user)
  329. if (role == null) { return { error = 'only a member of the project can change the state' field = 'state' forbidden = true } }
  330. if (!mayMoveTo(role, t.state, s)) { return { error = 'the role ' + role + ' can only move a ticket between open and review' field = 'state' forbidden = true } }
  331. t0 = now()
  332. let seq = (t.events != null ? t.events : 0) + 1
  333. 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 })
  334. changes = { state = s updated = t0 events = seq }
  335. let aid = null
  336. let auto = ''
  337. if (inboxStates.includes(s) && (t.assignee == null || t.assignee == '')) { auto = defaultAssignee(t.project) }
  338. if (auto != '') {
  339. seq = seq + 1
  340. aid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = auto previous = '' created = t0 })
  341. changes.assignee = auto
  342. changes.events = seq
  343. }
  344. ticketsTable.update(t.id, merged(t, changes))
  345. t2 = ticketsTable.fetch(t.id)
  346. recordEvent(eid, t2)
  347. if (aid != null) { recordEvent(aid, t2) }
  348. out = { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  349. if (aid != null) { out.assignEvent = eventRowAt(aid, t2) }
  350. return out
  351. }
  352. // answers { error, forbidden? } or { ticket, event }; `assignee` = a member's users @id, '' = nobody
  353. static assignTicket = (ticketId, user, assignee) => {
  354. t = ticketRecord(ticketId)
  355. if (t == null) { return { error = 'no such ticket' } }
  356. if (!userOk(user)) { return authorMissing }
  357. if (!mayEditIn(t.project, user)) { return { error = 'you need the role edit or admin to assign a ticket' field = 'assignee' forbidden = true } }
  358. who = assignee == null ? '' : clean(assignee)
  359. if (who != '' && memberRecord(t.project, who) == null) { return { error = 'the assignee must be a member of the project' field = 'assignee' } }
  360. was = t.assignee != null ? t.assignee : ''
  361. if (who == was) { return { error = who == '' ? 'the ticket is not assigned' : 'the ticket is already assigned to that person' field = 'assignee' } }
  362. t0 = now()
  363. let seq = (t.events != null ? t.events : 0) + 1
  364. eid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = was created = t0 })
  365. ticketsTable.update(t.id, merged(t, { assignee = who updated = t0 events = seq }))
  366. t2 = ticketsTable.fetch(t.id)
  367. recordEvent(eid, t2)
  368. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  369. }
  370. // ---- editing (ticket #8, mission 014; ticket #20: by the role) --------------------------------
  371. // THE AUTHOR of a ticket is `createdBy` (users @id), or null for a ticket opened before the login
  372. // existed. MAY THIS USER EDIT the ticket (a record)? Any member with the role edit or admin of
  373. // its project (`use` members only comment and move it between open and review).
  374. static mayEdit = (t, user) => {
  375. if (t == null || !userOk(user)) { return false }
  376. return mayEditIn(t.project, user)
  377. }
  378. static mayEditId = (ticketId, user) => { return mayEdit(ticketRecord(ticketId), user) }
  379. // answers { error, field?, forbidden? } or { ticket, event }. `subject` / `summary` null = keep
  380. // that one. The previous values stay in the 'edit' event (append-only history).
  381. static editTicket = (ticketId, user, subject, summary) => {
  382. t = ticketRecord(ticketId)
  383. if (t == null) { return { error = 'no such ticket' } }
  384. if (!userOk(user)) { return authorMissing }
  385. if (!mayEdit(t, user)) { return { error = 'you need the role edit or admin in the project to edit a ticket' field = '' forbidden = true } }
  386. if (subject == null && summary == null) { return { error = 'nothing to change: give subject and/or summary' field = '' } }
  387. let oldSummary = t.summary != null ? t.summary : ''
  388. s = subject != null ? oneLine(subject) : t.subject
  389. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  390. sm = summary != null ? clean(summary) : oldSummary
  391. if (s == t.subject && sm == oldSummary) { return { error = 'nothing changed' field = subject != null ? 'subject' : 'summary' } }
  392. t0 = now()
  393. let seq = (t.events != null ? t.events : 0) + 1
  394. 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 })
  395. if (eid == null) { return { error = 'could not store the edit: ' + eventsError() field = '' } }
  396. ticketsTable.update(t.id, merged(t, { subject = s summary = sm updated = t0 events = seq }))
  397. t2 = ticketsTable.fetch(t.id)
  398. recordEvent(eid, t2)
  399. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  400. }
  401. // an admin removes a member (projects.hl removeMembership); the tickets assigned to the person are no longer
  402. // assigned to anybody. Answers { members } or { error, forbidden? }
  403. static removeMember = (projectId, actor, userId) => {
  404. r = removeMembership(projectId, actor, userId)
  405. if (r.error != null) { return r }
  406. all = ticketsTable.find('project', projectId)
  407. if (countOf(all) > 0) {
  408. for (t of all) {
  409. if (t.assignee == userId) { ticketsTable.update(t.id, merged(t, { assignee = '' })) }
  410. }
  411. }
  412. return r
  413. }
  414. // the API's view of one ticket (a record): the row and its whole history
  415. static ticketWithEvents = (t) => {
  416. if (t == null) { return null }
  417. return { ticket = ticketRowOf(t) events = eventRows(t.id) }
  418. }
  419. // ---- relations: parent / child and blocked-by (ticket #4, mission 017) ----------------------
  420. // A ticket has at most ONE PARENT (any project); a parent lists its CHILDREN with their states.
  421. // A ticket can be BLOCKED BY other tickets (any project) — it waits on them; the other side
  422. // shows what it BLOCKS. The scheduler reads them from the JSON rows (`parent`, `children`,
  423. // `blockedBy`, `blocks`, each a ref with the state) and the Markdown view.
  424. // PARENT STATE: `allChildrenConfirmed` (the key kept for the clients; it now means DONE) is true when
  425. // a ticket has children and every one of them is `done`. It is only SHOWN ("all children done") — the
  426. // parent's own state is never changed by it.
  427. // WHO MAY set / remove a relation (ticket #20): a member with the role edit or admin in the project of
  428. // EITHER of the two tickets. Replacing a parent needs the
  429. // right for the old pair AND the new pair. No loops: a ticket cannot be its own ancestor, and
  430. // cannot (transitively) wait on itself.
  431. // Tickets are named as `<project>#<number>` (spaces around `#` allowed) or by their UUID.
  432. // the link records of one side, oldest first (stored time): field 'ticket' = this ticket's own
  433. // relations (its parent, its blockers), field 'other' = the ones pointing at it (children, blocked)
  434. static linkRecords = (field, ticketId, kind) => {
  435. out = []
  436. if (ticketId == null || ticketId == '') { return out }
  437. all = linksTable.find(field, '' + ticketId)
  438. if (countOf(all) == 0) { return out }
  439. for (l of all) { if (l.kind == kind) { out.push(l) } }
  440. return oldestFirst(out, 'created')
  441. }
  442. static parentLinkOf = (ticketId) => { return first(linkRecords('ticket', ticketId, 'parent')) }
  443. static parentIdOf = (ticketId) => {
  444. l = parentLinkOf(ticketId)
  445. return l == null ? null : l.other
  446. }
  447. static idsOfLinks = (links, field) => {
  448. out = []
  449. for (l of links) { out.push(l[field]) }
  450. return out
  451. }
  452. static childIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'parent'), 'ticket') }
  453. static blockerIdsOf = (ticketId) => { return idsOfLinks(linkRecords('ticket', ticketId, 'blockedBy'), 'other') }
  454. static blockedIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'blockedBy'), 'ticket') }
  455. static refsOfIds = (ids) => {
  456. out = []
  457. for (i of ids) {
  458. t = ticketRecord(i)
  459. if (t != null) { out.push(refOf(t)) }
  460. }
  461. return out
  462. }
  463. // { parent (ref or null), children, blockedBy, blocks (lists of refs), allChildrenConfirmed }
  464. static relationsOf = (t) => {
  465. pid = parentIdOf(t.id)
  466. p = pid != null ? ticketRecord(pid) : null
  467. kids = refsOfIds(childIdsOf(t.id))
  468. let all = kids.length > 0
  469. for (c of kids) { if (c.state != 'done') { all = false } }
  470. return { parent = p != null ? refOf(p) : null children = kids allChildrenConfirmed = all blockedBy = refsOfIds(blockerIdsOf(t.id)) blocks = refsOfIds(blockedIdsOf(t.id)) }
  471. }
  472. // the relation views of a ticket AND every ticket related to it (+ `extra` ids: a parent or
  473. // blocker just removed) — what a write pushes, so every open page of them follows
  474. static relatedViews = (ticketId, extra) => {
  475. ids = ['' + ticketId]
  476. seen = {}
  477. seen['' + ticketId] = true
  478. more = []
  479. pid = parentIdOf(ticketId)
  480. if (pid != null) { more.push(pid) }
  481. for (i of childIdsOf(ticketId)) { more.push(i) }
  482. for (i of blockerIdsOf(ticketId)) { more.push(i) }
  483. for (i of blockedIdsOf(ticketId)) { more.push(i) }
  484. for (i of extra) { if (i != null) { more.push(i) } }
  485. for (i of more) {
  486. if (seen['' + i] != true) {
  487. seen['' + i] = true
  488. ids.push('' + i)
  489. }
  490. }
  491. out = []
  492. for (i of ids) {
  493. t = ticketRecord(i)
  494. if (t != null) { out.push(relationViewOf(ticketRowOf(t))) }
  495. }
  496. return out
  497. }
  498. // `<project>#<number>` (spaces around '#' allowed) or a UUID → the ticket record, or null
  499. static ticketByKey = (key) => {
  500. k = clean(key)
  501. if (k == '') { return null }
  502. at = k.indexOf('#')
  503. if (at < 0) { return isDigits(k) ? null : ticketRecord(k) }
  504. p = k.slice(0, at).trim()
  505. n = k.slice(at + 1).trim()
  506. if (p == '') { return null }
  507. return ticketAt(p, n)
  508. }
  509. // WHO MAY CHANGE A RELATION (mission ST): a relation is written on ONE ticket — the one whose parent / blocker changes (`a`) — so
  510. // 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
  511. // 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.
  512. static mayLink = (a, b, user) => {
  513. if (!userOk(user)) { return false }
  514. return a != null && mayEditIn(a.project, user)
  515. }
  516. static linkForbidden = { error = 'you need the role edit or admin in the project of this ticket to change its relations' field = '' forbidden = true }
  517. // the history event of a relation change, on ticket `t`; answers { ticket, event, related }
  518. static linkEvent = (t, user, linkKind, action, other, previous, extra) => {
  519. t0 = now()
  520. let seq = (t.events != null ? t.events : 0) + 1
  521. // the values BEFORE the literal: an entry named `other` / `user` would shadow the variable
  522. // for the entries after it (mission 011 lesson)
  523. uname = user.name
  524. uid = user.id
  525. oid = other.id
  526. oproject = projectSlugOf(other)
  527. onumber = other.number
  528. 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 }
  529. if (previous != null) {
  530. rec.previous = previous.id
  531. rec.previousProject = projectSlugOf(previous)
  532. rec.previousNumber = previous.number
  533. }
  534. eid = putEvent(rec)
  535. if (eid == null) { return { error = 'could not store the event: ' + eventsError() field = '' } }
  536. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  537. t2 = ticketsTable.fetch(t.id)
  538. recordEvent(eid, t2)
  539. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) related = relatedViews(t.id, extra) }
  540. }
  541. // SET (key = `<project>#<n>` / UUID) or REMOVE (key = '') the parent of a ticket (UUID).
  542. // Answers { error, field, forbidden? } or { ticket, event, related }.
  543. static setParent = (ticketId, user, key) => {
  544. t = ticketRecord(ticketId)
  545. if (t == null) { return { error = 'no such ticket' } }
  546. if (!userOk(user)) { return authorMissing }
  547. k = clean(key)
  548. cur = parentLinkOf(t.id)
  549. curT = cur != null ? ticketRecord(cur.other) : null
  550. if (k == '') {
  551. if (cur == null || curT == null) { return { error = 'the ticket has no parent' field = 'parent' } }
  552. if (!mayLink(t, curT, user)) { return linkForbidden }
  553. linksTable.delete(cur.id)
  554. return linkEvent(t, user, 'parent', 'removed', curT, null, [curT.id])
  555. }
  556. p = ticketByKey(k)
  557. if (p == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = 'parent' } }
  558. if (p.id == t.id) { return { error = 'a ticket cannot be its own parent' field = 'parent' } }
  559. if (curT != null && curT.id == p.id) { return { error = 'the parent is already ' + keyOf(p) field = 'parent' } }
  560. // no loop: the new parent must not be this ticket's child, grandchild, …
  561. let up = p.id
  562. let steps = 0
  563. while (up != null && steps < 1000) {
  564. if (up == t.id) { return { error = 'a loop: ' + keyOf(p) + ' is below this ticket' field = 'parent' } }
  565. up = parentIdOf(up)
  566. steps = steps + 1
  567. }
  568. if (!mayLink(t, p, user)) { return linkForbidden }
  569. if (curT != null && !mayLink(t, curT, user)) { return linkForbidden }
  570. lid = linksTable.put({ kind = 'parent' ticket = t.id other = p.id user = user.id created = now() })
  571. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  572. if (cur != null) { linksTable.delete(cur.id) }
  573. return linkEvent(t, user, 'parent', 'set', p, curT, [curT != null ? curT.id : null])
  574. }
  575. // does ticket `start` (transitively) wait on ticket `target`? (blocked-by links)
  576. static waitsOn = (start, target) => {
  577. stack = [start]
  578. seen = {}
  579. let steps = 0
  580. while (stack.length > 0 && steps < 10000) {
  581. cur = stack.pop()
  582. steps = steps + 1
  583. if (cur == target) { return true }
  584. if (seen['' + cur] != true) {
  585. seen['' + cur] = true
  586. for (i of blockerIdsOf(cur)) { stack.push(i) }
  587. }
  588. }
  589. return false
  590. }
  591. // ADD (adding = true) or REMOVE a blocker of a ticket (UUID): ticket `key` blocks it.
  592. // `field` names the API field ('add' / 'remove'). Answers as setParent.
  593. static changeBlocker = (ticketId, user, key, adding, field) => {
  594. t = ticketRecord(ticketId)
  595. if (t == null) { return { error = 'no such ticket' } }
  596. if (!userOk(user)) { return authorMissing }
  597. k = clean(key)
  598. if (k == '') { return { error = 'name the blocking ticket as <project>#<number>' field = field } }
  599. o = ticketByKey(k)
  600. if (o == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = field } }
  601. let existing = null
  602. for (l of linkRecords('ticket', t.id, 'blockedBy')) { if (l.other == o.id) { existing = l } }
  603. if (adding) {
  604. if (o.id == t.id) { return { error = 'a ticket cannot block itself' field = field } }
  605. if (existing != null) { return { error = 'already blocked by ' + keyOf(o) field = field } }
  606. if (waitsOn(o.id, t.id)) { return { error = 'a loop: ' + keyOf(o) + ' already waits on this ticket' field = field } }
  607. if (!mayLink(t, o, user)) { return linkForbidden }
  608. lid = linksTable.put({ kind = 'blockedBy' ticket = t.id other = o.id user = user.id created = now() })
  609. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  610. return linkEvent(t, user, 'blockedBy', 'set', o, null, [])
  611. }
  612. if (existing == null) { return { error = 'not blocked by ' + keyOf(o) field = field } }
  613. if (!mayLink(t, o, user)) { return linkForbidden }
  614. linksTable.delete(existing.id)
  615. return linkEvent(t, user, 'blockedBy', 'removed', o, null, [o.id])
  616. }
  617. // ---- the one-time purge of #94, identity rule (lib/migrate.hl purgeTicket94): the writes of the tickets and links tables ----
  618. // removes the relation rows that point from or to a ticket (the other tickets stay); answers how many
  619. static removeLinksOf = (ticketId) => {
  620. hit = []
  621. for (field of ['ticket', 'other']) {
  622. found = linksTable.find(field, ticketId)
  623. if (countOf(found) > 0) { for (l of found) { if (!hit.includes(l.id)) { hit.push(l.id) } } }
  624. }
  625. for (id of hit) { linksTable.delete(id) }
  626. if (hit.length > 0) { linksTable.compactNow() }
  627. return hit.length
  628. }
  629. // a history event of ticket `ticketId` was removed: its count goes down by one (nothing else changes, `updated` stays)
  630. static forgetEventOf = (ticketId) => {
  631. t = ticketsTable.fetch(ticketId)
  632. if (t != null && t.events != null && t.events > 0) { ticketsTable.update(t.id, merged(t, { events = t.events - 1 })) }
  633. }
  634. static removeTicket = (ticketId) => { ticketsTable.delete(ticketId) }
  635. static compactTickets = () => { ticketsTable.compactNow() }

Branches

Latest commits

  • c69cd5f3Merge branch 'pr-flow' into mainTickets
  • cc56798cLog gitoria PR-only requestmre
  • d876d0b2|||PR README: changes land as PRsmre
  • fd83ac1fconductor: caramboleyo is the user, not owner/creatorApollo
  • 3b858c91Log backup hard-link fixmre
  • 7f6b37a0deploy.sh backup: tar --hard-dereference (hard links broke mpackdb sidecars on restore)mre
  • e93711d9Log E30 livemre
  • 59c02e4dMerge e30: preserve edited state note labels in Markdownmre
  • 30970796Log E30 deploy GOmre
  • 7c8e6d83Limit edited state note fix to Markdown renderingmre
  • 910536d0Log E30 reviewmre
  • 36984386Preserve state transitions when their notes are editedmre
  • d75cb946Log E30 startmre
  • 0bf3fefaMission 030: edited state note labelmre
  • 691565c6Log neutral-ticket rule checkmre
  • bc3bdecerecords: day38b live, #94 purgedmre
  • f6c5aa0dMerge main (records)mre
  • e23d42acconnect gate: wait for hydration before clicking Disconnectmre
  • a5d45d00records: D38 cause, GOmre
  • 19eeb938records: D38 gates, two day38b failuresmre