gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit32bcdf2432bcdf24|||PR records: GO P39 K40mre32bcdf24/lib/projects.hl

16.7 KB

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

Branches

Latest commits

  • 32bcdf24|||PR records: GO P39 K40mre
  • 4123c6d1Merge branch 'records-t38' into mainTickets
  • cd3641a1|||PR records: day72 deploy live, tickets closedmre
  • 7d44d852Merge branch 'records-t37' into mainTickets
  • 926f7061|||PR records: merges, D36 deploymre
  • bf58534eMerge branch 'l33-final' into mainTickets
  • 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
  • 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
  • 5822cb3aMerge branch 'o34-clean' into mainTickets
  • 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
  • 14cf96b4Merge branch 'records-t36' into mainTickets
  • 07749fa1|||PR records: day72 + #40 mergedmre
  • 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