gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd75cb946d75cb946Log E30 startmred75cb946/lib/projects.hl

16.2 KB

  1. // lib/projects.hl — PROJECTS AND THEIR MEMBERS (ticket #20, 2026-09-26). Statics only, the server realm.
  2. // Two hl:mpackdb tables (storage/mpackdb/, UUID keys — creator's convention):
  3. // projectsTable pk @id index !slug { title, slug, description (Markdown), oldSlugs ('a,b' — the
  4. // slugs it had before; they still resolve), created }
  5. // membersTable pk @id index project user { project (project @id), user (users @id), role, created }
  6. // role = 'use' | 'edit' | 'admin' (below). One row per (project, user).
  7. //
  8. // THE THREE ROLES (a member of a project; anybody else only reads):
  9. // use = comment, and move a ticket between open and review
  10. // edit = use + create, edit, assign, any state, relations
  11. // admin = edit + the project's settings and its members
  12. // ANY logged-in user with a display name opens a project and is its first admin; a project always keeps one admin.
  13. // THE PROJECT SLUG (the URL part) is generated from the title and only holds letters,
  14. // digits, '.', '_' and '-' (URL-safe); an admin can change it, the old one keeps resolving.
  15. // Removing a member also unassigns their tickets: that is tickets.hl removeMember (it owns the tickets table).
  16. import { MPackDB } from 'hl:mpackdb'
  17. import { now } from 'hl:time'
  18. import { storageDir, countOf, first, merged, clean, localStamp, oldestFirst, projectHrefOf, settingsHrefOf } from './util.hl'
  19. import { nameOfUser, userRecord, userRecords } from './users.hl'
  20. static projectsTable = new MPackDB(file = storageDir + '/projects.db', primaryKey = '@id', indexes = ['!slug'])
  21. static membersTable = new MPackDB(file = storageDir + '/members.db', primaryKey = '@id', indexes = ['project', 'user'])
  22. static roles = ['use' 'edit' 'admin']
  23. static rankOf = (role) => { return role == 'admin' ? 3 : (role == 'edit' ? 2 : (role == 'use' ? 1 : 0)) }
  24. // the refusals a write answers (`forbidden = true` → the API answers 403)
  25. static notAdmin = { error = 'only an admin of the project can do that' field = '' forbidden = true }
  26. static userOk = (u) => { return u != null && u.id != null && u.name != null && u.name != '' }
  27. static authorMissing = { error = 'a write needs a logged-in user' field = 'author' }
  28. // ---- finding a project ---------------------------------------------------------------------------
  29. static projectRecord = (id) => { return id == null || id == '' || hlTypeName(id) != 'String' ? null : projectsTable.fetch(id) }
  30. static projectBySlug = (slug) => { return slug == null || hlTypeName(slug) != 'String' ? null : first(projectsTable.find('slug', slug)) }
  31. // projects in the order they were created (stored time, not key order)
  32. static projectRecords = () => {
  33. all = projectsTable.find(null, null)
  34. ps = []
  35. if (countOf(all) == 0) { return ps }
  36. for (p of all) { ps.push(p) }
  37. return oldestFirst(ps, 'created')
  38. }
  39. // ---- the writes of the #20 migration (lib/migrate.hl calls these; the project tables are written only here) ----
  40. // a project record from before #20, `{ name, created }`, becomes `{ title = name, slug = name, description, oldSlugs }`
  41. static rewriteSlug = (p) => {
  42. projectsTable.update(p.id, { id = p.id title = p.name slug = p.name description = '' oldSlugs = '' created = p.created })
  43. }
  44. // a project for a ticket that names a project that has no record: title and slug are that name; answers its record
  45. static addProjectNamed = (name) => {
  46. pid = projectsTable.put({ title = name slug = name description = '' oldSlugs = '' created = now() })
  47. return projectRecord(pid)
  48. }
  49. // does the project have any member row at all?
  50. static hasMembers = (projectId) => { return countOf(membersTable.find('project', projectId)) > 0 }
  51. static oldSlugsOf = (p) => {
  52. out = []
  53. if (p.oldSlugs == null || p.oldSlugs == '') { return out }
  54. for (s of p.oldSlugs.split(',')) { if (s != '') { out.push(s) } }
  55. return out
  56. }
  57. // a project by its CURRENT slug, or by a slug it once had (old links keep working)
  58. static projectByAnySlug = (slug) => {
  59. p = projectBySlug(slug)
  60. if (p != null) { return p }
  61. if (slug == null || hlTypeName(slug) != 'String' || slug == '') { return null }
  62. for (q of projectRecords()) { if (oldSlugsOf(q).includes(slug)) { return q } }
  63. return null
  64. }
  65. // what the API takes for a project: its slug (also an old one) or its id
  66. static projectByRef = (ref) => {
  67. if (ref == null || hlTypeName(ref) != 'String' || ref == '') { return null }
  68. p = projectByAnySlug(ref)
  69. return p != null ? p : projectRecord(ref)
  70. }
  71. // the project part of an /api/projects/<x>/… path (ticket #25): a slug (also an old one) stays as it is, a project's
  72. // id gives its CURRENT slug, anything else stays as it is and names nothing. The routes then work on the slug as before.
  73. static slugOfRef = (ref) => {
  74. if (ref == null || hlTypeName(ref) != 'String' || ref == '' || projectByAnySlug(ref) != null) { return ref }
  75. p = projectRecord(ref)
  76. return p != null ? p.slug : ref
  77. }
  78. static projectNames = () => {
  79. out = []
  80. for (p of projectRecords()) { out.push(p.slug) }
  81. return out
  82. }
  83. // the slug of a ticket's project ('' when the project is gone)
  84. static projectSlugOf = (t) => {
  85. p = projectRecord(t.project)
  86. return p != null ? p.slug : ''
  87. }
  88. static projectRowOf = (p) => {
  89. return { id = p.id title = p.title slug = p.slug description = p.description != null ? p.description : '' href = projectHrefOf(p.slug) settingsHref = settingsHrefOf(p.slug) created = localStamp(p.created) createdMs = p.created }
  90. }
  91. // ---- the slug ------------------------------------------------------------------------------------
  92. // a project slug that a URL carries as is: letters, digits, . _ -
  93. static isSlugChar = (c) => {
  94. return (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 46 || c == 95 || c == 45
  95. }
  96. static validProjectName = (p) => {
  97. if (p == null || hlTypeName(p) != 'String' || p.length == 0 || p.length > 100) { return false }
  98. let i = 0
  99. while (i < p.length) {
  100. if (!isSlugChar(p.charCodeAt(i))) { return false }
  101. i = i + 1
  102. }
  103. return true
  104. }
  105. // RESERVED SLUGS (ticket #25): a project's page is /<slug>, so a slug may not be the first part of a path the app
  106. // or hl:web answers itself (every explicit route of project.hl, hl:web's /__hl/… and the component modules under
  107. // /components/…), nor a name we may want for a page later. Compared in lower case. The gate checks that every
  108. // first segment of a project.hl route is in this list.
  109. static reservedSlugs = ['api' '__hl' 'components' 'shared' 'icons' 'assets' 'favicon.ico' 'robots.txt' 'login' 'login.js' 'logout' 'md-editor.js' 'connect' 'project' 'projects' 'state' 'inbox' 'new-project' 'you' 'my' 'me' 'sign-in' 'sign-out' 'settings' 'tickets' 'search' 'help' 'about' 'admin' '.' '..']
  110. static isReservedSlug = (s) => { return s != null && hlTypeName(s) == 'String' && reservedSlugs.includes(s.toLowerCase()) }
  111. static reservedError = (s) => { return { error = 'the slug ' + s + ' is reserved: /' + s + ' is a page of tickets itself' field = 'slug' } }
  112. // the slug a title proposes: lower case letters and digits, other runs become one '-'
  113. static slugFromTitle = (title) => {
  114. t = clean(title).toLowerCase()
  115. let out = ''
  116. let i = 0
  117. while (i < t.length && out.length < 60) {
  118. c = t.charCodeAt(i)
  119. if ((c >= 48 && c <= 57) || (c >= 97 && c <= 122)) { out = out + t[i] } else if (out != '' && !out.endsWith('-')) { out = out + '-' }
  120. i = i + 1
  121. }
  122. while (out.endsWith('-')) { out = out.slice(0, out.length - 1) }
  123. return out == '' ? 'project' : out
  124. }
  125. // is this slug free? (`except` = the project that may keep it)
  126. static slugFree = (slug, except) => {
  127. for (q of projectRecords()) {
  128. if (except == null || q.id != except) {
  129. if (q.slug == slug || oldSlugsOf(q).includes(slug)) { return false }
  130. }
  131. }
  132. return true
  133. }
  134. // the slug a new project gets: the proposal, or with -2, -3 … when it is taken or reserved
  135. static uniqueSlug = (base) => {
  136. if (slugFree(base, null) && !isReservedSlug(base)) { return base }
  137. let n = 2
  138. while (!slugFree(base + '-' + n, null) && n < 10000) { n = n + 1 }
  139. return base + '-' + n
  140. }
  141. // ---- opening and changing a project ---------------------------------------------------------------
  142. // answers { error, field } or { project (row), members }. A slug is generated from the title unless one is given.
  143. static createProject = (user, title, slug, description) => {
  144. if (!userOk(user)) { return authorMissing }
  145. t = clean(title)
  146. if (t == '') { return { error = 'the title is required' field = 'title' } }
  147. if (t.length > 100) { return { error = 'the title is too long (at most 100 characters)' field = 'title' } }
  148. let s = clean(slug)
  149. if (s == '') { s = uniqueSlug(slugFromTitle(t)) }
  150. if (!validProjectName(s)) { return { error = "a slug has no spaces or slashes: letters, digits, '.', '_' and '-' only" field = 'slug' } }
  151. if (isReservedSlug(s)) { return reservedError(s) }
  152. if (!slugFree(s, null)) { return { error = 'the slug ' + s + ' is already used by a project' field = 'slug' } }
  153. id = projectsTable.put({ title = t slug = s description = clean(description) oldSlugs = '' created = now() })
  154. if (id == null) { return { error = 'could not store the project: ' + projectsTable.lastError() field = '' } }
  155. addMember(id, user.id, 'admin')
  156. return { project = projectRowOf(projectsTable.fetch(id)) members = memberRows(id) }
  157. }
  158. // an admin changes title / slug / description (null = keep). A new slug keeps the old one working.
  159. static updateProject = (projectId, actor, title, slug, description) => {
  160. p = projectRecord(projectId)
  161. if (p == null) { return { error = 'no such project' } }
  162. if (!userOk(actor)) { return authorMissing }
  163. if (!isAdminOf(p.id, actor)) { return notAdmin }
  164. if (title == null && slug == null && description == null) { return { error = 'nothing to change: give title, slug and/or description' field = '' } }
  165. t = title != null ? clean(title) : p.title
  166. if (t == '') { return { error = 'the title is required' field = 'title' } }
  167. if (t.length > 100) { return { error = 'the title is too long (at most 100 characters)' field = 'title' } }
  168. s = slug != null ? clean(slug) : p.slug
  169. if (s == '') { return { error = 'the slug is required' field = 'slug' } }
  170. if (!validProjectName(s)) { return { error = "a slug has no spaces or slashes: letters, digits, '.', '_' and '-' only" field = 'slug' } }
  171. if (s != p.slug && isReservedSlug(s)) { return reservedError(s) }
  172. if (!slugFree(s, p.id)) { return { error = 'the slug ' + s + ' is already used by another project' field = 'slug' } }
  173. d = description != null ? clean(description) : (p.description != null ? p.description : '')
  174. let olds = oldSlugsOf(p)
  175. if (s != p.slug) {
  176. kept = []
  177. for (o of olds) { if (o != s) { kept.push(o) } }
  178. kept.push(p.slug)
  179. olds = kept
  180. }
  181. projectsTable.update(p.id, merged(p, { title = t slug = s description = d oldSlugs = olds.join(',') }))
  182. return { project = projectRowOf(projectsTable.fetch(p.id)) }
  183. }
  184. // ---- members and roles ------------------------------------------------------------------------
  185. static memberRecord = (projectId, userId) => {
  186. if (projectId == null || userId == null || userId == '') { return null }
  187. all = membersTable.find('project', projectId)
  188. if (countOf(all) == 0) { return null }
  189. for (m of all) { if (m.user == userId) { return m } }
  190. return null
  191. }
  192. // the role of a user in a project ('use' | 'edit' | 'admin'), or null
  193. static roleOf = (projectId, user) => {
  194. if (user == null || user.id == null) { return null }
  195. m = memberRecord(projectId, user.id)
  196. return m == null ? null : m.role
  197. }
  198. static atLeast = (projectId, user, role) => { return rankOf(roleOf(projectId, user)) >= rankOf(role) }
  199. static isMember = (projectId, user) => { return roleOf(projectId, user) != null }
  200. static mayEditIn = (projectId, user) => { return atLeast(projectId, user, 'edit') }
  201. static isAdminOf = (projectId, user) => { return atLeast(projectId, user, 'admin') }
  202. // the member rows of a project: [{ id, user (users @id), name, role, rank, created }], the oldest first
  203. static memberRows = (projectId) => {
  204. out = []
  205. all = membersTable.find('project', projectId)
  206. if (countOf(all) == 0) { return out }
  207. for (m of all) { out.push({ id = m.id user = m.user name = nameOfUser(m.user) role = m.role rank = rankOf(m.role) created = m.created }) }
  208. return oldestFirst(out, 'created')
  209. }
  210. // makes `userId` a member with `role` (no permission check: the caller decided); an existing
  211. // member keeps the HIGHER of the two roles. Answers the member record.
  212. static addMember = (projectId, userId, role) => {
  213. m = memberRecord(projectId, userId)
  214. if (m != null) {
  215. if (rankOf(role) > rankOf(m.role)) { membersTable.update(m.id, merged(m, { role = role })) }
  216. return membersTable.fetch(m.id)
  217. }
  218. id = membersTable.put({ project = projectId user = userId role = role created = now() })
  219. return id == null ? null : membersTable.fetch(id)
  220. }
  221. static adminCount = (projectId) => {
  222. let n = 0
  223. for (m of memberRows(projectId)) { if (m.role == 'admin') { n = n + 1 } }
  224. return n
  225. }
  226. // an admin sets a member's role, or adds a person by the ident id / display name of a user that
  227. // has logged in here. Answers { members } or { error, forbidden? }
  228. static setMemberRole = (projectId, actor, userId, role) => {
  229. p = projectRecord(projectId)
  230. if (p == null) { return { error = 'no such project' } }
  231. if (!isAdminOf(p.id, actor)) { return notAdmin }
  232. if (!roles.includes(role)) { return { error = 'role must be one of: ' + roles.join(', ') field = 'role' } }
  233. if (userRecord(userId) == null) { return { error = 'no such user' field = 'user' } }
  234. m = memberRecord(p.id, userId)
  235. if (m != null && m.role == 'admin' && role != 'admin' && adminCount(p.id) < 2) { return { error = 'a project needs at least one admin' field = 'role' } }
  236. if (m == null) { addMember(p.id, userId, role) } else { membersTable.update(m.id, merged(m, { role = role })) }
  237. return { members = memberRows(p.id) }
  238. }
  239. // an admin removes a member (tickets.hl removeMember then unassigns their tickets). Answers { members } or { error }
  240. static removeMembership = (projectId, actor, userId) => {
  241. p = projectRecord(projectId)
  242. if (p == null) { return { error = 'no such project' } }
  243. if (!isAdminOf(p.id, actor)) { return notAdmin }
  244. m = memberRecord(p.id, userId)
  245. if (m == null) { return { error = 'not a member' field = 'user' } }
  246. if (m.role == 'admin' && adminCount(p.id) < 2) { return { error = 'a project needs at least one admin' field = 'user' } }
  247. membersTable.delete(m.id)
  248. return { members = memberRows(p.id) }
  249. }
  250. // the user a name (exact display name), an ident id (identity) or a users @id stands for, among
  251. // the members of a project when `projectId` is given; { user } | { error }
  252. static userByRef = (ref, projectId) => {
  253. r = clean(ref)
  254. if (r == '') { return { error = 'name a person' } }
  255. found = []
  256. all = userRecords()
  257. if (countOf(all) > 0) {
  258. for (u of all) {
  259. if (projectId == null || memberRecord(projectId, u.id) != null) {
  260. if (u.id == r || u.identity == r || (u.name != '' && u.name == r)) { found.push(u) }
  261. }
  262. }
  263. }
  264. if (found.length == 0) { return { error = 'no such person' + (projectId != null ? ' among the members' : '') + ': ' + r } }
  265. if (found.length > 1) { return { error = 'more than one person is called ' + r } }
  266. return { user = found[0] }
  267. }
  268. // the members a ticket can be assigned to: [{ value (users @id), label (display name) }]
  269. static assignChoices = (projectId) => {
  270. out = []
  271. for (m of memberRows(projectId)) { out.push({ value = m.user label = m.name }) }
  272. return out
  273. }
  274. // projects a user may create tickets in: [{ slug, title }] (creation order)
  275. static editableProjects = (user) => {
  276. out = []
  277. if (user == null) { return out }
  278. for (p of projectRecords()) { if (mayEditIn(p.id, user)) { out.push({ slug = p.slug title = p.title }) } }
  279. return out
  280. }
  281. // the projects a user is a member of, with the role: [{ slug, title, role, href }]
  282. static projectsOfUser = (user) => {
  283. out = []
  284. if (user == null) { return out }
  285. for (p of projectRecords()) {
  286. r = roleOf(p.id, user)
  287. if (r != null) { out.push({ slug = p.slug title = p.title role = r href = projectHrefOf(p.slug) }) }
  288. }
  289. return out
  290. }
  291. // ---- the one-time purge of #94, identity rule (lib/migrate.hl purgeTicket94) -------------------------------------
  292. // a project's numbers never go back below `numberFloor` (tickets.hl nextNumber): a removed ticket's number is not given again
  293. static setNumberFloor = (projectId, n) => {
  294. p = projectsTable.fetch(projectId)
  295. if (p == null || (p.numberFloor != null && p.numberFloor >= n)) { return false }
  296. projectsTable.update(p.id, merged(p, { numberFloor = n }))
  297. projectsTable.compactNow()
  298. return true
  299. }

Branches

Latest commits

  • d75cb946Log E30 startmre
  • 0bf3fefaMission 030: edited state note labelmre
  • 691565c6Log neutral-ticket rule checkmre
  • bc3bdecerecords: day38b live, #94 purgedmre
  • f6c5aa0dMerge main (records)mre
  • e23d42acconnect gate: wait for hydration before clicking Disconnectmre
  • a5d45d00records: D38 cause, GOmre
  • 19eeb938records: D38 gates, two day38b failuresmre
  • f8e42a85Re-vendor tickets to Hybriel set day38b (1e554d7)mre
  • 51645016Merge purge-94 (#94, identity rule)mre
  • 94d6ca2arecords: D38 startedmre
  • 9df09aacmission 029: day38b re-vendor + deploymre
  • d2834f65records: #94 backup planmre
  • 4467d8cbrecords: #94 purge readymre
  • aa2d124eREADME: the #94 purge gatemre
  • e843ff7cOne-time purge of miserit-anthar#94 (#94, identity rule): idempotent step in lib/migrate.hl, fixture gate tests/purge94.mjsmre
  • 506a4efdmission 028: #94, identity rulemre
  • 78c7f48eRefine mpackdb holdmre
  • 3d7d89c8Record mpackdb hold until day38mre
  • f1bf7195#51 done; my subscription idmre