gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7ed2e5e57ed2e5e5deploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the script silently (grep under pipefail), as gitoria/layoutsmre7ed2e5e5/lib/tickets.hl

29.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, 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. // ---- reads -------------------------------------------------------------------------
  116. // newest update first; both filters optional (null = all); `project` is a slug
  117. static ticketRows = (project, state) => {
  118. rows = []
  119. let all = null
  120. if (project != null) {
  121. p = projectByAnySlug(project)
  122. if (p == null) { return rows }
  123. all = ticketsTable.find('project', p.id)
  124. } else {
  125. all = ticketsTable.find(null, null)
  126. }
  127. if (countOf(all) == 0) { return rows }
  128. for (t of all) {
  129. if (state == null || t.state == state) { rows.push(ticketRowOf(t)) }
  130. }
  131. return newestFirst(rows, 'updatedMs')
  132. }
  133. // THE INBOX of a user: the tickets ASSIGNED TO THEM in pending and in review, two lists
  134. static inboxRows = (user) => {
  135. out = { pending = [] review = [] }
  136. if (user == null || user.id == null) { return out }
  137. a = []
  138. b = []
  139. ps = ticketsTable.find('state', 'pending')
  140. if (countOf(ps) > 0) { for (t of ps) { if (t.assignee == user.id) { a.push(ticketRowOf(t)) } } }
  141. rs = ticketsTable.find('state', 'review')
  142. if (countOf(rs) > 0) { for (t of rs) { if (t.assignee == user.id) { b.push(ticketRowOf(t)) } } }
  143. out.pending = newestFirst(a, 'updatedMs')
  144. out.review = newestFirst(b, 'updatedMs')
  145. return out
  146. }
  147. static inboxCountOf = (user) => {
  148. x = inboxRows(user)
  149. return x.pending.length + x.review.length
  150. }
  151. // the page's row of `/<project>/<number>` (ticket #25), or null
  152. static ticketRowAt = (project, number) => {
  153. t = ticketAt(project, number)
  154. return t == null ? null : ticketRowOf(t)
  155. }
  156. // the event history of a ticket (UUID), oldest first (events.hl historyOf)
  157. static eventRows = (ticketId) => {
  158. t = ticketRecord(ticketId)
  159. if (t == null) { return [] }
  160. return historyOf(t)
  161. }
  162. // the options of a state select: [{ value, label }] — the states THIS user may move the ticket to
  163. // (a `use` member: only open ⇄ review; `edit` / `admin`: every other state)
  164. static stateChoices = (t, user) => {
  165. out = []
  166. if (t == null || user == null) { return out }
  167. role = roleOf(t.project, user)
  168. for (s of states) {
  169. if (s != t.state && mayMoveTo(role, t.state, s)) { out.push({ value = s label = s }) }
  170. }
  171. return out
  172. }
  173. static mayMoveTo = (role, current, target) => {
  174. if (rankOf(role) >= 2) { return true }
  175. if (rankOf(role) == 1) { return (current == 'open' && target == 'review') || (current == 'review' && target == 'open') }
  176. return false
  177. }
  178. // what a user may do on a ticket (a record): comment (a member), edit / assign (edit, admin), the states they
  179. // may move it to, and the members it can be assigned to — the ticket page asks after a login or a change
  180. static ticketRights = (t, user) => {
  181. return { comment = isMember(t.project, user) edit = mayEdit(t, user) options = stateChoices(t, user) members = assignChoices(t.project) }
  182. }
  183. // ---- writes: each answers what the push carries --------------------------------------
  184. // The author is the user — there is no free author field any more.
  185. // the next per-project number: the highest one in the project + 1 (first = 1)
  186. static nextNumber = (projectId) => {
  187. let top = 0
  188. all = ticketsTable.find('project', projectId)
  189. if (countOf(all) > 0) {
  190. for (t of all) { if (t.number != null && t.number > top) { top = t.number } }
  191. }
  192. return top + 1
  193. }
  194. // answers { error, field, forbidden? } or { ticket (row), event (row), existed }
  195. // `project` = the slug (or id) of an existing project; `assignee` optional (a member's name / id)
  196. static createTicket = (project, subject, summary, user, source, assignee) => {
  197. s = clean(subject)
  198. if (clean(project) == '') { return { error = 'project is required' field = 'project' } }
  199. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  200. if (!userOk(user)) { return authorMissing }
  201. p = projectByRef(clean(project))
  202. if (p == null) { return { error = 'no such project: ' + clean(project) field = 'project' } }
  203. 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 } }
  204. let who = ''
  205. if (assignee != null && clean(assignee) != '') {
  206. r = userByRef(assignee, p.id)
  207. if (r.error != null) { return { error = r.error field = 'assignee' } }
  208. who = r.user.id
  209. }
  210. src = clean(source)
  211. if (src != '') {
  212. known = ticketsTable.find('source', src)
  213. if (countOf(known) > 0) { return { ticket = ticketRowOf(known[0]) event = null existed = true } }
  214. }
  215. t0 = now()
  216. n = nextNumber(p.id)
  217. 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 })
  218. if (id == null) { return { error = 'could not store the ticket: ' + ticketsTable.lastError() field = '' } }
  219. t = ticketsTable.fetch(id)
  220. eid = putEvent({ ticket = id seq = 1 kind = 'created' author = user.name user = user.id text = src != '' ? 'imported from ' + src : '' created = t0 })
  221. out = { ticket = ticketRowOf(t) event = eventRowAt(eid, t) existed = false }
  222. if (who != '') {
  223. let seq = 2
  224. aid = putEvent({ ticket = id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = '' created = t0 })
  225. ticketsTable.update(id, merged(t, { events = seq }))
  226. t2 = ticketsTable.fetch(id)
  227. out.ticket = ticketRowOf(t2)
  228. out.assignEvent = eventRowAt(aid, t2)
  229. recordEvent(eid, t2)
  230. recordEvent(aid, t2)
  231. } else {
  232. recordEvent(eid, t)
  233. }
  234. return out
  235. }
  236. // answers { error } or { ticket, event }; `ticketId` is the UUID. Any member may comment.
  237. // tickets#27 (mission 017): `files` = the attachments ([{ name, type, bytes }], null / [] = none; lib/attachments.hl checks the
  238. // limits and the content and stores them). A comment with files may have no text; without files it needs text, as before.
  239. static addComment = (ticketId, user, text, files) => {
  240. t = ticketRecord(ticketId)
  241. if (t == null) { return { error = 'no such ticket' } }
  242. body = clean(text)
  243. given = files != null && countOf(files) > 0
  244. if (body == '' && !given) { return { error = 'a comment needs text' field = 'text' } }
  245. if (!userOk(user)) { return authorMissing }
  246. if (!isMember(t.project, user)) { return { error = 'only a member of the project can comment' field = '' forbidden = true } }
  247. checked = checkFiles(given ? files : null)
  248. if (checked.error != null) { return { error = checked.error field = checked.field tooBig = checked.tooBig } }
  249. t0 = now()
  250. let seq = (t.events != null ? t.events : 0) + 1
  251. eid = putEvent({ ticket = t.id seq = seq kind = 'comment' author = user.name user = user.id text = body created = t0 })
  252. stored = storeFiles(eid, t, user, checked.files)
  253. if (stored != null) { console.log('attachments: ' + stored.error) }
  254. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  255. t2 = ticketsTable.fetch(t.id)
  256. recordEvent(eid, t2)
  257. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  258. }
  259. // mission 016: EDIT ('edit', with `text`), DELETE ('delete') or LIKE ('like': again = take it back) the comment `commentId`
  260. // (an events @id) of ticket `ticketId`. Who may and what is kept: lib/comments.hl (edit / delete: its author; like: any
  261. // member). The ticket's `updated` and `events` stay: these are no new history events (and nothing for the event stream).
  262. // Answers { error, field, forbidden? } or { ticket, event (the comment's row as it is now), liked (a like: true = the user
  263. // likes it now) }.
  264. static changeComment = (ticketId, commentId, user, action, text) => {
  265. t = ticketRecord(ticketId)
  266. if (t == null) { return { error = 'no such ticket' } }
  267. e = commentId == null || hlTypeName(commentId) != 'String' || commentId == '' ? null : eventRecord(commentId)
  268. if (e == null || e.ticket != t.id) { return { error = 'no such comment on this ticket' field = 'comment' } }
  269. let bad = null
  270. 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 = '' } }
  271. if (bad != null) { return bad }
  272. out = { ticket = ticketRowOf(t) event = eventRowAt(e.id, t) }
  273. if (action == 'like') { out.liked = likersOf(e.id).includes(user.id) }
  274. return out
  275. }
  276. // the admin who gets a ticket that lands in the inbox with nobody assigned: the oldest admin
  277. static defaultAssignee = (projectId) => {
  278. for (m of memberRows(projectId)) { if (m.role == 'admin') { return m.user } }
  279. return ''
  280. }
  281. // answers { error } or { ticket, event, assignEvent? }; an optional note rides on the state event.
  282. // `forbidden = true` on a refusal the user may not overcome (the role does not allow that move).
  283. // A ticket that goes to review / pending with nobody assigned is assigned to the project's first admin
  284. // (so it reaches an inbox) — a second, 'assign' event.
  285. static changeState = (ticketId, state, user, note) => {
  286. t = ticketRecord(ticketId)
  287. if (t == null) { return { error = 'no such ticket' } }
  288. s = stateOf(state)
  289. if (s == null) { return { error = 'unknown state — one of: ' + states.join(', ') field = 'state' } }
  290. if (s == t.state) { return { error = 'the ticket is already ' + s field = 'state' } }
  291. if (!userOk(user)) { return authorMissing }
  292. role = roleOf(t.project, user)
  293. if (role == null) { return { error = 'only a member of the project can change the state' field = 'state' forbidden = true } }
  294. if (!mayMoveTo(role, t.state, s)) { return { error = 'the role ' + role + ' can only move a ticket between open and review' field = 'state' forbidden = true } }
  295. t0 = now()
  296. let seq = (t.events != null ? t.events : 0) + 1
  297. 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 })
  298. changes = { state = s updated = t0 events = seq }
  299. let aid = null
  300. let auto = ''
  301. if (inboxStates.includes(s) && (t.assignee == null || t.assignee == '')) { auto = defaultAssignee(t.project) }
  302. if (auto != '') {
  303. seq = seq + 1
  304. aid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = auto previous = '' created = t0 })
  305. changes.assignee = auto
  306. changes.events = seq
  307. }
  308. ticketsTable.update(t.id, merged(t, changes))
  309. t2 = ticketsTable.fetch(t.id)
  310. recordEvent(eid, t2)
  311. if (aid != null) { recordEvent(aid, t2) }
  312. out = { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  313. if (aid != null) { out.assignEvent = eventRowAt(aid, t2) }
  314. return out
  315. }
  316. // answers { error, forbidden? } or { ticket, event }; `assignee` = a member's users @id, '' = nobody
  317. static assignTicket = (ticketId, user, assignee) => {
  318. t = ticketRecord(ticketId)
  319. if (t == null) { return { error = 'no such ticket' } }
  320. if (!userOk(user)) { return authorMissing }
  321. if (!mayEditIn(t.project, user)) { return { error = 'you need the role edit or admin to assign a ticket' field = 'assignee' forbidden = true } }
  322. who = assignee == null ? '' : clean(assignee)
  323. if (who != '' && memberRecord(t.project, who) == null) { return { error = 'the assignee must be a member of the project' field = 'assignee' } }
  324. was = t.assignee != null ? t.assignee : ''
  325. if (who == was) { return { error = who == '' ? 'the ticket is not assigned' : 'the ticket is already assigned to that person' field = 'assignee' } }
  326. t0 = now()
  327. let seq = (t.events != null ? t.events : 0) + 1
  328. eid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = was created = t0 })
  329. ticketsTable.update(t.id, merged(t, { assignee = who updated = t0 events = seq }))
  330. t2 = ticketsTable.fetch(t.id)
  331. recordEvent(eid, t2)
  332. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  333. }
  334. // ---- editing (ticket #8, mission 014; ticket #20: by the role) --------------------------------
  335. // THE AUTHOR of a ticket is `createdBy` (users @id), or null for a ticket opened before the login
  336. // existed. MAY THIS USER EDIT the ticket (a record)? Any member with the role edit or admin of
  337. // its project (`use` members only comment and move it between open and review).
  338. static mayEdit = (t, user) => {
  339. if (t == null || !userOk(user)) { return false }
  340. return mayEditIn(t.project, user)
  341. }
  342. static mayEditId = (ticketId, user) => { return mayEdit(ticketRecord(ticketId), user) }
  343. // answers { error, field?, forbidden? } or { ticket, event }. `subject` / `summary` null = keep
  344. // that one. The previous values stay in the 'edit' event (append-only history).
  345. static editTicket = (ticketId, user, subject, summary) => {
  346. t = ticketRecord(ticketId)
  347. if (t == null) { return { error = 'no such ticket' } }
  348. if (!userOk(user)) { return authorMissing }
  349. if (!mayEdit(t, user)) { return { error = 'you need the role edit or admin in the project to edit a ticket' field = '' forbidden = true } }
  350. if (subject == null && summary == null) { return { error = 'nothing to change: give subject and/or summary' field = '' } }
  351. let oldSummary = t.summary != null ? t.summary : ''
  352. s = subject != null ? clean(subject) : t.subject
  353. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  354. sm = summary != null ? clean(summary) : oldSummary
  355. if (s == t.subject && sm == oldSummary) { return { error = 'nothing changed' field = subject != null ? 'subject' : 'summary' } }
  356. t0 = now()
  357. let seq = (t.events != null ? t.events : 0) + 1
  358. 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 })
  359. if (eid == null) { return { error = 'could not store the edit: ' + eventsError() field = '' } }
  360. ticketsTable.update(t.id, merged(t, { subject = s summary = sm updated = t0 events = seq }))
  361. t2 = ticketsTable.fetch(t.id)
  362. recordEvent(eid, t2)
  363. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  364. }
  365. // an admin removes a member (projects.hl removeMembership); the tickets assigned to the person are no longer
  366. // assigned to anybody. Answers { members } or { error, forbidden? }
  367. static removeMember = (projectId, actor, userId) => {
  368. r = removeMembership(projectId, actor, userId)
  369. if (r.error != null) { return r }
  370. all = ticketsTable.find('project', projectId)
  371. if (countOf(all) > 0) {
  372. for (t of all) {
  373. if (t.assignee == userId) { ticketsTable.update(t.id, merged(t, { assignee = '' })) }
  374. }
  375. }
  376. return r
  377. }
  378. // the API's view of one ticket (a record): the row and its whole history
  379. static ticketWithEvents = (t) => {
  380. if (t == null) { return null }
  381. return { ticket = ticketRowOf(t) events = eventRows(t.id) }
  382. }
  383. // ---- relations: parent / child and blocked-by (ticket #4, mission 017) ----------------------
  384. // A ticket has at most ONE PARENT (any project); a parent lists its CHILDREN with their states.
  385. // A ticket can be BLOCKED BY other tickets (any project) — it waits on them; the other side
  386. // shows what it BLOCKS. The scheduler reads them from the JSON rows (`parent`, `children`,
  387. // `blockedBy`, `blocks`, each a ref with the state) and the Markdown view.
  388. // PARENT STATE: `allChildrenConfirmed` (the key kept for the clients; it now means DONE) is true when
  389. // a ticket has children and every one of them is `done`. It is only SHOWN ("all children done") — the
  390. // parent's own state is never changed by it.
  391. // WHO MAY set / remove a relation (ticket #20): a member with the role edit or admin in the project of
  392. // EITHER of the two tickets. Replacing a parent needs the
  393. // right for the old pair AND the new pair. No loops: a ticket cannot be its own ancestor, and
  394. // cannot (transitively) wait on itself.
  395. // Tickets are named as `<project>#<number>` (spaces around `#` allowed) or by their UUID.
  396. // the link records of one side, oldest first (stored time): field 'ticket' = this ticket's own
  397. // relations (its parent, its blockers), field 'other' = the ones pointing at it (children, blocked)
  398. static linkRecords = (field, ticketId, kind) => {
  399. out = []
  400. if (ticketId == null || ticketId == '') { return out }
  401. all = linksTable.find(field, '' + ticketId)
  402. if (countOf(all) == 0) { return out }
  403. for (l of all) { if (l.kind == kind) { out.push(l) } }
  404. return oldestFirst(out, 'created')
  405. }
  406. static parentLinkOf = (ticketId) => { return first(linkRecords('ticket', ticketId, 'parent')) }
  407. static parentIdOf = (ticketId) => {
  408. l = parentLinkOf(ticketId)
  409. return l == null ? null : l.other
  410. }
  411. static idsOfLinks = (links, field) => {
  412. out = []
  413. for (l of links) { out.push(l[field]) }
  414. return out
  415. }
  416. static childIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'parent'), 'ticket') }
  417. static blockerIdsOf = (ticketId) => { return idsOfLinks(linkRecords('ticket', ticketId, 'blockedBy'), 'other') }
  418. static blockedIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'blockedBy'), 'ticket') }
  419. static refsOfIds = (ids) => {
  420. out = []
  421. for (i of ids) {
  422. let t = ticketRecord(i)
  423. if (t != null) { out.push(refOf(t)) }
  424. }
  425. return out
  426. }
  427. // { parent (ref or null), children, blockedBy, blocks (lists of refs), allChildrenConfirmed }
  428. static relationsOf = (t) => {
  429. pid = parentIdOf(t.id)
  430. p = pid != null ? ticketRecord(pid) : null
  431. kids = refsOfIds(childIdsOf(t.id))
  432. let all = kids.length > 0
  433. for (c of kids) { if (c.state != 'done') { all = false } }
  434. return { parent = p != null ? refOf(p) : null children = kids allChildrenConfirmed = all blockedBy = refsOfIds(blockerIdsOf(t.id)) blocks = refsOfIds(blockedIdsOf(t.id)) }
  435. }
  436. // the relation views of a ticket AND every ticket related to it (+ `extra` ids: a parent or
  437. // blocker just removed) — what a write pushes, so every open page of them follows
  438. static relatedViews = (ticketId, extra) => {
  439. ids = ['' + ticketId]
  440. seen = {}
  441. seen['' + ticketId] = true
  442. more = []
  443. pid = parentIdOf(ticketId)
  444. if (pid != null) { more.push(pid) }
  445. for (i of childIdsOf(ticketId)) { more.push(i) }
  446. for (i of blockerIdsOf(ticketId)) { more.push(i) }
  447. for (i of blockedIdsOf(ticketId)) { more.push(i) }
  448. for (i of extra) { if (i != null) { more.push(i) } }
  449. for (i of more) {
  450. if (seen['' + i] != true) {
  451. seen['' + i] = true
  452. ids.push('' + i)
  453. }
  454. }
  455. out = []
  456. for (i of ids) {
  457. let t = ticketRecord(i)
  458. if (t != null) { out.push(relationViewOf(ticketRowOf(t))) }
  459. }
  460. return out
  461. }
  462. // `<project>#<number>` (spaces around '#' allowed) or a UUID → the ticket record, or null
  463. static ticketByKey = (key) => {
  464. k = clean(key)
  465. if (k == '') { return null }
  466. at = k.indexOf('#')
  467. if (at < 0) { return isDigits(k) ? null : ticketRecord(k) }
  468. p = k.slice(0, at).trim()
  469. n = k.slice(at + 1).trim()
  470. if (p == '') { return null }
  471. return ticketAt(p, n)
  472. }
  473. static mayLink = (a, b, user) => {
  474. if (!userOk(user)) { return false }
  475. if (a != null && mayEditIn(a.project, user)) { return true }
  476. if (b != null && mayEditIn(b.project, user)) { return true }
  477. return false
  478. }
  479. static linkForbidden = { error = 'you need the role edit or admin in the project of either ticket to change this relation' field = '' forbidden = true }
  480. // the history event of a relation change, on ticket `t`; answers { ticket, event, related }
  481. static linkEvent = (t, user, linkKind, action, other, previous, extra) => {
  482. t0 = now()
  483. let seq = (t.events != null ? t.events : 0) + 1
  484. // the values BEFORE the literal: an entry named `other` / `user` would shadow the variable
  485. // for the entries after it (mission 011 lesson)
  486. uname = user.name
  487. uid = user.id
  488. oid = other.id
  489. oproject = projectSlugOf(other)
  490. onumber = other.number
  491. 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 }
  492. if (previous != null) {
  493. rec.previous = previous.id
  494. rec.previousProject = projectSlugOf(previous)
  495. rec.previousNumber = previous.number
  496. }
  497. eid = putEvent(rec)
  498. if (eid == null) { return { error = 'could not store the event: ' + eventsError() field = '' } }
  499. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  500. t2 = ticketsTable.fetch(t.id)
  501. recordEvent(eid, t2)
  502. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) related = relatedViews(t.id, extra) }
  503. }
  504. // SET (key = `<project>#<n>` / UUID) or REMOVE (key = '') the parent of a ticket (UUID).
  505. // Answers { error, field, forbidden? } or { ticket, event, related }.
  506. static setParent = (ticketId, user, key) => {
  507. t = ticketRecord(ticketId)
  508. if (t == null) { return { error = 'no such ticket' } }
  509. if (!userOk(user)) { return authorMissing }
  510. k = clean(key)
  511. cur = parentLinkOf(t.id)
  512. curT = cur != null ? ticketRecord(cur.other) : null
  513. if (k == '') {
  514. if (cur == null || curT == null) { return { error = 'the ticket has no parent' field = 'parent' } }
  515. if (!mayLink(t, curT, user)) { return linkForbidden }
  516. linksTable.delete(cur.id)
  517. return linkEvent(t, user, 'parent', 'removed', curT, null, [curT.id])
  518. }
  519. p = ticketByKey(k)
  520. if (p == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = 'parent' } }
  521. if (p.id == t.id) { return { error = 'a ticket cannot be its own parent' field = 'parent' } }
  522. if (curT != null && curT.id == p.id) { return { error = 'the parent is already ' + keyOf(p) field = 'parent' } }
  523. // no loop: the new parent must not be this ticket's child, grandchild, …
  524. let up = p.id
  525. let steps = 0
  526. while (up != null && steps < 1000) {
  527. if (up == t.id) { return { error = 'a loop: ' + keyOf(p) + ' is below this ticket' field = 'parent' } }
  528. up = parentIdOf(up)
  529. steps = steps + 1
  530. }
  531. if (!mayLink(t, p, user)) { return linkForbidden }
  532. if (curT != null && !mayLink(t, curT, user)) { return linkForbidden }
  533. lid = linksTable.put({ kind = 'parent' ticket = t.id other = p.id user = user.id created = now() })
  534. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  535. if (cur != null) { linksTable.delete(cur.id) }
  536. return linkEvent(t, user, 'parent', 'set', p, curT, [curT != null ? curT.id : null])
  537. }
  538. // does ticket `start` (transitively) wait on ticket `target`? (blocked-by links)
  539. static waitsOn = (start, target) => {
  540. stack = [start]
  541. seen = {}
  542. let steps = 0
  543. while (stack.length > 0 && steps < 10000) {
  544. let cur = stack.pop()
  545. steps = steps + 1
  546. if (cur == target) { return true }
  547. if (seen['' + cur] != true) {
  548. seen['' + cur] = true
  549. for (i of blockerIdsOf(cur)) { stack.push(i) }
  550. }
  551. }
  552. return false
  553. }
  554. // ADD (adding = true) or REMOVE a blocker of a ticket (UUID): ticket `key` blocks it.
  555. // `field` names the API field ('add' / 'remove'). Answers as setParent.
  556. static changeBlocker = (ticketId, user, key, adding, field) => {
  557. t = ticketRecord(ticketId)
  558. if (t == null) { return { error = 'no such ticket' } }
  559. if (!userOk(user)) { return authorMissing }
  560. k = clean(key)
  561. if (k == '') { return { error = 'name the blocking ticket as <project>#<number>' field = field } }
  562. o = ticketByKey(k)
  563. if (o == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = field } }
  564. let existing = null
  565. for (l of linkRecords('ticket', t.id, 'blockedBy')) { if (l.other == o.id) { existing = l } }
  566. if (adding) {
  567. if (o.id == t.id) { return { error = 'a ticket cannot block itself' field = field } }
  568. if (existing != null) { return { error = 'already blocked by ' + keyOf(o) field = field } }
  569. if (waitsOn(o.id, t.id)) { return { error = 'a loop: ' + keyOf(o) + ' already waits on this ticket' field = field } }
  570. if (!mayLink(t, o, user)) { return linkForbidden }
  571. lid = linksTable.put({ kind = 'blockedBy' ticket = t.id other = o.id user = user.id created = now() })
  572. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  573. return linkEvent(t, user, 'blockedBy', 'set', o, null, [])
  574. }
  575. if (existing == null) { return { error = 'not blocked by ' + keyOf(o) field = field } }
  576. if (!mayLink(t, o, user)) { return linkForbidden }
  577. linksTable.delete(existing.id)
  578. return linkEvent(t, user, 'blockedBy', 'removed', o, null, [o.id])
  579. }

Branches

Latest commits

  • 7ed2e5e5deploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the script silently (grep under pipefail), as gitoria/layoutsmre
  • bf9064a3mission 022: tickets on the layouts theme (step 1): shell, styles, gates, audit, E2E; reportmre
  • f3d61711mission 022 WIP: tickets on the layouts theme (dbe3de7): AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst shell, styles reduced to the app's own, check-theme in the gates, 390 audit + real-Chrome walk scriptmre
  • 31cabfccmission 021: E2E script, report, LOG, STATUSmre
  • 6aea8683editor look: .empty rule only for p.empty, files off where tickets has no upload, state note one line, events test scrolls the editor into view; synced md-editor (components d702d76+6f27ad3); gate 377/0, events 52/0mre
  • dce6ffa6Merge branch 'w28-deflake'mre
  • 536092a1tickets (mission 019): de-flake the m016 comment clicks (B: unliked) — calmClick waits until the button stops moving; test only, no app changemre
  • 9c5fd42amission 020: attachments E2E proof (lisbeth Chrome, real-data copy), reportmre
  • 1206404fREADME attachments, report 018, LOG/STATUSmre
  • 3d9e7f3ctests: m017 gate fixes (list count, waits before delete clicks); gate 373/0mre
  • dd41d5bcre-sync components 15be2ac; mission 018mre
  • 420ad1bbtickets (mission 017 WIP, tickets#27): comment attachments — lib/attachments.hl (storage/attachments, limits, type by content, members-only GET /api/attachments/:id, delete drops, edit keeps), multipart POST …/comments (lib/multipart.hl), Respond block in FilesUpload (blocks verbatim from components w27c 1f8d79d), gate m017 checks written (not yet run); report, LOG, STATUSmre
  • a7a1380dmission brief 017mre
  • f83d9c0dtickets (mission 016): report reports/016-comments-block.md, LOG, STATUS, README gate countmre
  • eef80f55tickets (mission 016): comments through the shared Comments block (layouts#2) — edit (author, earlier versions kept), delete (author, asks; leaves one line in the history), like (members, toggle) on the server (lib/comments.hl, append-only tables), faces + API …/comments/:comment/{edit,delete,like}, push commentChanged; every run of comments is a block in place in the history; Markdown fields on the Hybriel MdEditor (shared/md-editor.js retired: it took over the block's <md-editor>); blocks copied verbatim from components.hybriel 9db927d (tools/sync-components.sh); gates browser 351/0 (old 326/0), events 52/0 (old 52/0)mre
  • eb7aeeb9mission brief 016mre
  • e4c34759paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 26efb23freport w6-events (events test)mre
  • c6bfab04mission 015: re-vendor Hybriel 0f396652 (static build), reportmre
  • b7ec5981mission brief 015mre