gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchl33-thinecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mrel33-thin/lib/tickets.hl

35.3 KB

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

Branches

Latest commits

  • ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre
  • 6dea1c60Merge branch 'r35-day72' into mainTickets
  • 7bcfdc22|||PR drop worker edits to conductor recordsmre
  • 2617b6ee|||PR dialogs: host flag cleared on close, dialog gate (tickets#40)mre
  • 6e701371|||PR record partial day72 dialog validationmre
  • b9fb9a91|||PR bind ticket dialog visibility to member flagsmre
  • 0788e65f|||PR re-vendor Hybriel day72mre
  • e2a6bdcfMerge branch 'records-t35' into mainTickets
  • d8d54df1|||PR records: R35 day72 + #40mre
  • 8a7f475aMerge branch 'records-t33' into mainTickets
  • e685d0c2|||PR records: PROCEDURES merge callmre
  • b42aff2b|||PR records: GO 2026-11-23, workers L33 O34, PROCEDURES.mdmre
  • ed091d44Merge branch 'records' into mainTickets
  • 180c0cdb|||PR records: ticket move live (M32), hybriel#439mre
  • 497cae7bMerge branch 'm32-move' into mainTickets
  • 772e0696|||PR Allow project admins to move tickets between their projectsmre
  • be92a560Merge branch 'records' into mainTickets
  • 0daf2ea8|||PR records: PR-only workflow, #50 donemre
  • 0185d0b6Log PR 1 deploymre
  • f5bf16e2Mission 031: deploy PR 1mre