gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit81f10e4e81f10e4eident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre81f10e4e/lib/tickets.hl

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

Branches

Latest commits

  • 81f10e4eident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • f51029abMerge branch 'sy-sync'mre
  • eae6e8c7sync components.hybriel 4922f9c: comments like / Edit / Delete / 'edited' are 44 px targets; gate: 'edited' hit-area padding, thread targets check (SY)mre
  • 0de4750btheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 4eeb7bfeST2 report wordingmre
  • 2558f56cst2-sec: keep the hlsid session cookie name (no one is signed out), Secure flag only; gate: a cookie issued by main stays signed in; ident stub serves selector.js; security.mjs in deploy GATESmre
  • ea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmre
  • 7c8c2282sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b6277497report MT-mobile, LOGmre
  • 6709398blist paging: the newest rows come first (the sorted array was not used); filter rows hide their scrollbar; gate checks the ordermre
  • 31736a80gate: member-name check fails on the old row layout toomre
  • e03ae537gate: the phone checks run on without the Show more button (so old code reports every failed check)mre
  • adf7f132gate: 390 px checks for the mobile audit fixes (row number, filters, field widths, Edit, member names, relation taps, paging)mre
  • 28e9c938ticket list: draw the newest 50 rows and a Show more button (500 rows were a 2-4 s first paint, 740 KB, a 90 000 px phone page)mre
  • ccebb0c7mobile: ticket number stays on one line, filter chips one scrolling row, fields full width under their caption, Edit/action buttons, member names whole, 44 px relation linksmre
  • f2dc7741gate: the phone toolbar is two even rows (E2)mre
  • 20f7c33async components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
  • d74a5482sync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
  • 9d02c540sync components.hybriel 6b0936a: the 'edited' foldable drops the theme's border and marginmre
  • 22751914sync components.hybriel 8d79ff7: bubble hugs its content, quiet 'edited' label; gate checksmre