gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commiteef80f55eef80f55tickets (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)mreeef80f55/lib/tickets.hl

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

Branches

Latest commits

  • 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
  • 5dc68731docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 8a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre
  • 6309ca81mission brief 014mre
  • c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre
  • a30b5d12mission brief (w13)mre
  • b50a6f93w9 (tickets): re-vendor hybriel 9f912f3b (#146 emit in a lib static, #147) — the 12 live-push emits in lib/api.hl compile as they are; cold start (#148): tests wait TICKETS_COLD_MS for every start, deploy.sh gates browser + events and waits up to 120 s for the URL, container /tmp tmpfs + hybriel-cache volume; events-client stops at EVENTS_MAX inside a chunk; connect.mjs ports by env. bin/hybriel sha256 7421907868ac07d8a7d08296b083c6f8b20407d0e099ce4bebbf7ae053d9060a. Gates (8720–8739): browser 315/0 (+ all-cold 315/0), events 48/0 cold, connect 60/0, short-id 19/0; real-data copy old 0e8a41c vs new: 2,425 reads + 72 writes identical after masking ?v hashes, offline at, route order; event stream on the copy delivers. Not deployed.mre
  • 43be6578w9: re-vendor hybriel master edfd400a; event stream imports sseStart/sseSend/sseAlive from hl:http1 (hybriel#144), useTransport gone; tools/import.hl plain declarations. BLOCKED: hybriel-native refuses `emit client` in a static (lib/api.hl) — the server does not compile on edfd400a, gates fail at start; scratch copy without those emits: events 48/0, gate 254 ok up to the first live pushmre
  • 0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre
  • bb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmre
  • 7538b034mission 011 (ticket #25 web part): short page URLs /<slug> and /<slug>/<number>; /projects/<slug>, /projects/<slug>/<n>, /projects/<slug>/tickets/<n> and /tickets/<ref> answer 301 (current slug); slug pages moved behind hl:web's own routes after construction (they answered /__hl/* and /components/*.hl); reserved slugs refused; API paths unchanged. gate 293/0, connect 60/0, live-data copy 187/0, API old vs new: only page links differmre
  • 0369106emission 010 (code order) 4/4: README file map + import order + 'Same output' test, STATUS (entry, lessons, how to verify), LOG, report; tests/realdata-baseline.mjs + realdata-compare*.py (a cleanup answers the same on live data), tests/letcount.pymre
  • a75e0279mission 010 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (456 lets → plain declarations; Hybriel refuses a plain declaration inside a loop on its 2nd pass). gate 249/0, connect 60/0, real-data reads identical, a 50-step write sequence (API + faces) identical to the old codemre
  • e9d5c618mission 010 (code order) 2/4: one lib/ file per topic — store.hl split into projects / tickets (+ relations) / events / tickets-helpers, util.hl shared helpers (env, storage dir, URLs, sorts, Vienna time), the function routes out of project.hl into lib/api.hl (thin; auth/filters/Accept in api-helpers.hl), invite + member-removal logic out of the faces/routes into invites.hl / tickets.hl; project.hl is the map. /login/callback gets req + the session store by reference. gate 249/0, connect 60/0, real-data reads identicalmre
  • 97e269b5mission 010 (code order) 1/4: .hl files out of the root — lib/ (store, users, connections, invites, migrate, markdown, mdview, import = ticketfile, util = localtime, jsoncheck, api-helpers = api), tools/import.hl, components/styles.hl; import paths only. gate 249/0, connect 60/0, real-data reads identicalmre