@lupinum/ginko-server 0.0.0-stage → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/convex/_generated/api.d.ts +185 -0
- package/convex/_generated/api.js +23 -0
- package/convex/_generated/dataModel.d.ts +60 -0
- package/convex/_generated/server.d.ts +162 -0
- package/convex/_generated/server.js +101 -0
- package/convex/account.ts +110 -0
- package/convex/agent.ts +814 -0
- package/convex/auth.config.ts +4 -0
- package/convex/auth.ts +62 -0
- package/convex/backup.ts +94 -0
- package/convex/betterAuth/_generated/api.ts +56 -0
- package/convex/betterAuth/_generated/component.ts +431 -0
- package/convex/betterAuth/_generated/dataModel.ts +60 -0
- package/convex/betterAuth/_generated/server.ts +169 -0
- package/convex/betterAuth/adapter.ts +7 -0
- package/convex/betterAuth/convex.config.ts +3 -0
- package/convex/betterAuth/schema.ts +102 -0
- package/convex/betterAuth/schemaMetadata.ts +697 -0
- package/convex/betterAuth/schemaOptions.ts +13 -0
- package/convex/betterAuth/schemaPlugins.ts +13 -0
- package/convex/bundle.ts +183 -0
- package/convex/changes.ts +136 -0
- package/convex/cleanup.ts +44 -0
- package/convex/connect.ts +143 -0
- package/convex/convex.config.ts +7 -0
- package/convex/crons.ts +14 -0
- package/convex/demo.ts +72 -0
- package/convex/entries.ts +1770 -0
- package/convex/facts.ts +129 -0
- package/convex/files.ts +631 -0
- package/convex/http.ts +21 -0
- package/convex/image.ts +45 -0
- package/convex/images.ts +54 -0
- package/convex/invites.ts +227 -0
- package/convex/lib/access.ts +180 -0
- package/convex/lib/agentTools.ts +331 -0
- package/convex/lib/content.ts +317 -0
- package/convex/lib/corpus.ts +83 -0
- package/convex/lib/diff.ts +50 -0
- package/convex/lib/fail.ts +27 -0
- package/convex/lib/files.ts +70 -0
- package/convex/lib/history.ts +103 -0
- package/convex/lib/i18n.ts +52 -0
- package/convex/lib/input.ts +57 -0
- package/convex/lib/library.ts +28 -0
- package/convex/lib/lifecycle.ts +100 -0
- package/convex/lib/list.ts +112 -0
- package/convex/lib/migrations.ts +126 -0
- package/convex/lib/names.ts +56 -0
- package/convex/lib/pending.ts +84 -0
- package/convex/lib/policy.ts +155 -0
- package/convex/lib/publicness.ts +87 -0
- package/convex/lib/reminders.ts +27 -0
- package/convex/lib/search.ts +132 -0
- package/convex/lib/siteUrl.ts +95 -0
- package/convex/lib/status.ts +109 -0
- package/convex/lib/translation.ts +56 -0
- package/convex/lib/trees.ts +43 -0
- package/convex/lib/write.ts +296 -0
- package/convex/mail.ts +136 -0
- package/convex/members.ts +129 -0
- package/convex/migrations.ts +105 -0
- package/convex/navigation.ts +276 -0
- package/convex/ops.ts +50 -0
- package/convex/proposals.ts +753 -0
- package/convex/refresh.ts +163 -0
- package/convex/release.ts +435 -0
- package/convex/reminders.ts +116 -0
- package/convex/retention.ts +121 -0
- package/convex/routes/bundle.ts +62 -0
- package/convex/routes/connect.ts +80 -0
- package/convex/routes/export.ts +23 -0
- package/convex/routes/file.ts +34 -0
- package/convex/routes/key.ts +53 -0
- package/convex/routes/mcp.ts +300 -0
- package/convex/routes/release.ts +66 -0
- package/convex/routes/upload.ts +94 -0
- package/convex/schema.ts +443 -0
- package/convex/search.ts +58 -0
- package/convex/seed.ts +624 -0
- package/convex/siteDeletion.ts +78 -0
- package/convex/sites.ts +393 -0
- package/convex/tasks.ts +51 -0
- package/convex/tsconfig.json +27 -0
- package/convex/uploads.ts +429 -0
- package/convex/uploadsNode.ts +86 -0
- package/convex/views.ts +111 -0
- package/i18n/de.json +364 -0
- package/i18n/en.json +364 -0
- package/i18n/es.json +364 -0
- package/i18n/fr.json +364 -0
- package/package.json +45 -3
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
// Approvals and releases (SPEC 17): "a change that needs a yes". The write operations in
|
|
2
|
+
// entries.ts create the proposals (lib/policy.ts); this file decides them. Approving runs the
|
|
3
|
+
// same operation again as the author, with the approver named in the change row, so there is one
|
|
4
|
+
// write path. A change that no longer fits (revision moved on) becomes `stale` and writes nothing.
|
|
5
|
+
import type { Json } from '@lupinum/ginko'
|
|
6
|
+
import type { Schema } from '@lupinum/ginko/internal'
|
|
7
|
+
import { paginationOptsValidator } from 'convex/server'
|
|
8
|
+
import { ConvexError, v } from 'convex/values'
|
|
9
|
+
import { internal } from './_generated/api'
|
|
10
|
+
import type { Doc, Id } from './_generated/dataModel'
|
|
11
|
+
import { internalAction, internalMutation, mutation, query, type MutationCtx, type QueryCtx } from './_generated/server'
|
|
12
|
+
import { checkFuture, createAs, publishAs, removeAs, saveAs, unpublishAs } from './entries'
|
|
13
|
+
import { currentUser, fail, memberOf, type Actor } from './lib/access'
|
|
14
|
+
import { rootOf } from './lib/content'
|
|
15
|
+
import { diffFields } from './lib/diff'
|
|
16
|
+
import { historyText, msg, type HistoryMsg, type Param } from './lib/history'
|
|
17
|
+
import { localeOfUser, t, type MessageKey } from './lib/i18n'
|
|
18
|
+
import { queueMail, mailAvailable, siteOrigin } from './mail'
|
|
19
|
+
import { labeler, namer, type Labeler } from './lib/names'
|
|
20
|
+
import { pendingOf } from './lib/pending'
|
|
21
|
+
import { taskOf } from './lib/policy'
|
|
22
|
+
|
|
23
|
+
const PAGE_SIZE = 50
|
|
24
|
+
/** SPEC 17: a release groups at most this many proposals. */
|
|
25
|
+
export const RELEASE_MAX = 50
|
|
26
|
+
const REASON_MAX = 300
|
|
27
|
+
const NAME_MAX = 80
|
|
28
|
+
|
|
29
|
+
const status = v.union(v.literal('open'), v.literal('approved'), v.literal('scheduled'), v.literal('applied'), v.literal('rejected'), v.literal('stale'), v.literal('withdrawn'))
|
|
30
|
+
|
|
31
|
+
// ---- Who may do what ----
|
|
32
|
+
|
|
33
|
+
/** Approvers are owners and admins. Staff reads and proposes, never decides. */
|
|
34
|
+
const isApprover = (actor: Actor) => actor.role !== 'staff'
|
|
35
|
+
|
|
36
|
+
/** Nobody approves their own proposal, except one made by their own agent key: that is "show me first". */
|
|
37
|
+
function requireDecide(actor: Actor, p: Doc<'proposals'>) {
|
|
38
|
+
if (!isApprover(actor)) fail('FORBIDDEN', 'errors.ownersOnly')
|
|
39
|
+
if (p.author === actor.user.id && p.via !== 'agent') fail('FORBIDDEN', 'errors.cannotApproveOwnProposal')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The signed-in person as a member of the proposal's site. A foreign proposal looks like a missing one. */
|
|
43
|
+
async function actorForProposal(ctx: QueryCtx, id: string): Promise<{ actor: Actor; proposal: Doc<'proposals'> }> {
|
|
44
|
+
const user = await currentUser(ctx)
|
|
45
|
+
const key = ctx.db.normalizeId('proposals', id)
|
|
46
|
+
const proposal = key ? await ctx.db.get(key) : null
|
|
47
|
+
const site = proposal ? await ctx.db.get(proposal.site) : null
|
|
48
|
+
const actor = site ? await memberOf(ctx, site, user) : null
|
|
49
|
+
if (!proposal || !actor) fail('NOT_FOUND', 'errors.proposalNotFound')
|
|
50
|
+
return { actor, proposal }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function actorForRelease(ctx: QueryCtx, id: string): Promise<{ actor: Actor; release: Doc<'releases'> }> {
|
|
54
|
+
const user = await currentUser(ctx)
|
|
55
|
+
const key = ctx.db.normalizeId('releases', id)
|
|
56
|
+
const release = key ? await ctx.db.get(key) : null
|
|
57
|
+
const site = release ? await ctx.db.get(release.site) : null
|
|
58
|
+
const actor = site ? await memberOf(ctx, site, user) : null
|
|
59
|
+
if (!release || !actor) fail('NOT_FOUND', 'errors.releaseNotFound')
|
|
60
|
+
return { actor, release }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function siteActor(ctx: QueryCtx, slug: string): Promise<Actor> {
|
|
64
|
+
const user = await currentUser(ctx)
|
|
65
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', slug)).unique()
|
|
66
|
+
const actor = site ? await memberOf(ctx, site, user) : null
|
|
67
|
+
if (!actor) fail('FORBIDDEN', 'errors.noAccess')
|
|
68
|
+
return actor
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ---- Applying ----
|
|
72
|
+
|
|
73
|
+
/** Why a proposal no longer fits: the German text (stored in `reason`, the fallback) and the catalog message (`reasonMsg`) the Studio renders in the reader's language. */
|
|
74
|
+
type Stale = { reason: string; msg: HistoryMsg }
|
|
75
|
+
|
|
76
|
+
const staleBecause = (key: MessageKey, params?: Record<string, Param>): Stale => {
|
|
77
|
+
const message = msg(key, params)
|
|
78
|
+
return { reason: historyText(message, 'de', undefined), msg: message }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type Applied = { ok: true; change?: Id<'changes'>; liveFrom?: string } | ({ ok: false } & Stale)
|
|
82
|
+
|
|
83
|
+
/** A refusal of the operation (`fail`: code, catalog key, params) as the reason: its own text, then the ask to propose again. */
|
|
84
|
+
function reasonOf(data: { code?: string; key?: string; params?: Record<string, string | number> }): Stale {
|
|
85
|
+
if (data.code === 'CHANGED_SINCE') return staleBecause('history.staleChanged')
|
|
86
|
+
const why = data.key ? msg(data.key as MessageKey, data.params) : msg('history.staleNoLonger')
|
|
87
|
+
return staleBecause('history.staleRefused', { why })
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Runs the proposal's operation as its author, with `approver` named in the change row. The
|
|
92
|
+
* operations check everything before they write, so a refusal leaves nothing behind: it becomes the
|
|
93
|
+
* reason the proposal is stale. Any other error is a bug and is thrown.
|
|
94
|
+
*/
|
|
95
|
+
async function applyNow(ctx: MutationCtx, p: Doc<'proposals'>, approver: string): Promise<Applied> {
|
|
96
|
+
const site = await ctx.db.get(p.site)
|
|
97
|
+
if (!site) return { ok: false, ...staleBecause('history.staleSiteGone') }
|
|
98
|
+
const author = await memberOf(ctx, site, { id: p.author })
|
|
99
|
+
if (!author) return { ok: false, ...staleBecause('history.staleAuthorLeft') }
|
|
100
|
+
const actor: Actor = { ...author, approvedBy: approver, ...(p.agentKey ? { agentKey: p.agentKey } : {}) }
|
|
101
|
+
// A new op ID per proposal: a retry of the same apply finds its stored result.
|
|
102
|
+
const { copy, ...stored } = p.args as { copy?: boolean }
|
|
103
|
+
const args = { ...stored, opId: `p-${p._id}` } as never
|
|
104
|
+
try {
|
|
105
|
+
let result: Json
|
|
106
|
+
switch (p.op) {
|
|
107
|
+
case 'save': result = await saveAs(ctx, actor, args); break
|
|
108
|
+
case 'create': result = await createAs(ctx, actor, args, copy ? { copy } : {}); break
|
|
109
|
+
case 'remove': result = await removeAs(ctx, actor, args); break
|
|
110
|
+
case 'publish': result = await publishAs(ctx, actor, args); break
|
|
111
|
+
case 'unpublish': result = await unpublishAs(ctx, actor, args); break
|
|
112
|
+
}
|
|
113
|
+
const data = result as { change?: Id<'changes'>; entry?: Id<'entries'>; liveFrom?: string }
|
|
114
|
+
// Only a save can end without a change (the values were already there); every other operation writes one.
|
|
115
|
+
const entry = data.entry ?? p.entry
|
|
116
|
+
const change = data.change ?? (p.op !== 'save' && entry ? (await ctx.db.query('changes').withIndex('by_entry', (q) => q.eq('entry', entry)).order('desc').first())?._id : undefined)
|
|
117
|
+
return { ok: true, ...(change ? { change } : {}), ...(data.liveFrom ? { liveFrom: data.liveFrom } : {}) }
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (error instanceof ConvexError && typeof error.data === 'object' && error.data !== null && 'code' in error.data) return { ok: false, ...reasonOf(error.data as { code?: string; key?: string; params?: Record<string, string | number> }) }
|
|
120
|
+
throw error
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** What earlier members of the same release already touched, so the check sees conflicts between them. */
|
|
125
|
+
type Touched = Map<string, { roots: Set<string>; life: boolean }>
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Whether the proposal still fits, without writing: the same preconditions the operation checks
|
|
129
|
+
* (SPEC 4.2). Returns the reason (German text and catalog message) when it does not. Used before a
|
|
130
|
+
* release is applied, so a stale member blocks the release without half of it being written.
|
|
131
|
+
*/
|
|
132
|
+
async function staleReason(ctx: QueryCtx, p: Doc<'proposals'>, touched: Touched = new Map()): Promise<Stale | null> {
|
|
133
|
+
const retry = staleBecause('history.staleChanged')
|
|
134
|
+
const site = await ctx.db.get(p.site)
|
|
135
|
+
if (!site) return staleBecause('history.staleSiteGone')
|
|
136
|
+
if (!(await memberOf(ctx, site, { id: p.author }))) return staleBecause('history.staleAuthorLeft')
|
|
137
|
+
if (!p.entry) return null
|
|
138
|
+
const entry = await ctx.db.get(p.entry)
|
|
139
|
+
if (!entry || entry.site !== p.site) return staleBecause('history.staleEntryGone')
|
|
140
|
+
if (entry.deletedAt) return staleBecause('history.staleEntryDeleted')
|
|
141
|
+
const args = p.args as { baseRev?: number; lifeRev?: number; rev?: number; fields?: Record<string, Json>; confirm?: string[] }
|
|
142
|
+
const seen = touched.get(entry._id)
|
|
143
|
+
if (p.op === 'save') {
|
|
144
|
+
const roots = [...new Set([...Object.keys(args.fields ?? {}), ...(args.confirm ?? []).map(rootOf)])]
|
|
145
|
+
const base = args.baseRev ?? 0
|
|
146
|
+
if (base > entry.rev || roots.some((r) => (entry.fieldRevs[r] ?? 0) > base) || roots.some((r) => seen?.roots.has(r))) return retry
|
|
147
|
+
touched.set(entry._id, { roots: new Set([...(seen?.roots ?? []), ...roots]), life: seen?.life ?? false })
|
|
148
|
+
return null
|
|
149
|
+
}
|
|
150
|
+
if (entry.lifeRev !== args.lifeRev || seen?.life) return retry
|
|
151
|
+
if (p.op === 'publish' && (entry.state ?? 'live') !== 'draft') {
|
|
152
|
+
// Publishing unpublished changes: they must still be the ones the author sent (the rev moves with every save).
|
|
153
|
+
if (args.rev === undefined) return staleBecause('history.staleAlreadyLive')
|
|
154
|
+
if (entry.rev !== args.rev || !(await pendingOf(ctx, entry._id))) return retry
|
|
155
|
+
}
|
|
156
|
+
if (p.op === 'unpublish' && (entry.state ?? 'live') === 'draft' && entry.publishAt === undefined) return staleBecause('history.staleAlreadyDraft')
|
|
157
|
+
// Taking the time off unpublished changes (the entry stays online): only while they still have one.
|
|
158
|
+
if (p.op === 'unpublish' && (p.after as { state?: string } | undefined)?.state === 'live' && (await pendingOf(ctx, entry._id))?.publishAt === undefined) return retry
|
|
159
|
+
touched.set(entry._id, { roots: seen?.roots ?? new Set(), life: true })
|
|
160
|
+
return null
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** `running`: the call comes from the proposal's own scheduled job, which has nothing left to cancel. */
|
|
164
|
+
async function markStale(ctx: MutationCtx, p: Doc<'proposals'>, why: Stale, by: string, running = false) {
|
|
165
|
+
if (p.job && !running) await ctx.scheduler.cancel(p.job)
|
|
166
|
+
await ctx.db.patch(p._id, { status: 'stale', reason: why.reason, reasonMsg: why.msg, decidedBy: by, decidedAt: Date.now(), job: undefined })
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function markApplied(ctx: MutationCtx, p: Doc<'proposals'>, by: string, change: Id<'changes'> | undefined) {
|
|
170
|
+
await ctx.db.patch(p._id, { status: 'applied', decidedBy: by, decidedAt: Date.now(), job: undefined, ...(change ? { change } : {}) })
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Release member status back to open (a scheduled release that could not run). */
|
|
174
|
+
async function reopen(ctx: MutationCtx, p: Doc<'proposals'>) {
|
|
175
|
+
await ctx.db.patch(p._id, { status: 'open', at: undefined, decidedBy: undefined, decidedAt: undefined })
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ---- Deciding one proposal ----
|
|
179
|
+
|
|
180
|
+
export const approve = mutation({
|
|
181
|
+
args: { proposal: v.string(), at: v.optional(v.number()) },
|
|
182
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
183
|
+
const { actor, proposal: p } = await actorForProposal(ctx, args.proposal)
|
|
184
|
+
requireDecide(actor, p)
|
|
185
|
+
if (p.status !== 'open') fail('CHANGED_SINCE', 'errors.proposalNoLongerOpen', undefined, { status: p.status })
|
|
186
|
+
if (p.release) fail('INVALID', 'errors.proposalInReleaseApproveRelease')
|
|
187
|
+
const by = actor.user.id
|
|
188
|
+
|
|
189
|
+
if (args.at !== undefined) {
|
|
190
|
+
checkFuture(args.at)
|
|
191
|
+
const reason = await staleReason(ctx, p)
|
|
192
|
+
if (reason) {
|
|
193
|
+
await markStale(ctx, p, reason, by)
|
|
194
|
+
return { proposal: p._id, status: 'stale', reason: reason.reason, reasonMsg: reason.msg }
|
|
195
|
+
}
|
|
196
|
+
const job = await ctx.scheduler.runAt(args.at, internal.proposals.applyScheduled, { proposal: p._id, at: args.at })
|
|
197
|
+
await ctx.db.patch(p._id, { status: 'scheduled', at: args.at, job, decidedBy: by, decidedAt: Date.now() })
|
|
198
|
+
return { proposal: p._id, status: 'scheduled', at: args.at }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const applied = await applyNow(ctx, p, by)
|
|
202
|
+
if (!applied.ok) {
|
|
203
|
+
await markStale(ctx, p, applied, by)
|
|
204
|
+
return { proposal: p._id, status: 'stale', reason: applied.reason, reasonMsg: applied.msg }
|
|
205
|
+
}
|
|
206
|
+
await markApplied(ctx, p, by, applied.change)
|
|
207
|
+
// A week planned ahead or a planned price: the approver is told from when it shows.
|
|
208
|
+
return { proposal: p._id, status: 'applied', change: applied.change ?? null, ...(applied.liveFrom ? { liveFrom: applied.liveFrom } : {}) }
|
|
209
|
+
},
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
/** The run of a scheduled approval: re-checks everything now. A change in between makes the proposal stale. */
|
|
213
|
+
export const applyScheduled = internalMutation({
|
|
214
|
+
args: { proposal: v.id('proposals'), at: v.number() },
|
|
215
|
+
handler: async (ctx, args): Promise<null> => {
|
|
216
|
+
const p = await ctx.db.get(args.proposal)
|
|
217
|
+
if (!p || p.status !== 'scheduled' || p.at !== args.at || !p.decidedBy) return null
|
|
218
|
+
const site = await ctx.db.get(p.site)
|
|
219
|
+
const approver = site && await memberOf(ctx, site, { id: p.decidedBy })
|
|
220
|
+
if (!approver || !isApprover(approver) || (p.author === p.decidedBy && p.via !== 'agent')) {
|
|
221
|
+
await markStale(ctx, p, staleBecause('history.staleApproverNotAllowed'), p.decidedBy, true)
|
|
222
|
+
return null
|
|
223
|
+
}
|
|
224
|
+
const applied = await applyNow(ctx, p, p.decidedBy)
|
|
225
|
+
if (applied.ok) {
|
|
226
|
+
await markApplied(ctx, p, p.decidedBy, applied.change)
|
|
227
|
+
return null
|
|
228
|
+
}
|
|
229
|
+
await markStale(ctx, p, applied, p.decidedBy, true)
|
|
230
|
+
await mailNotLive(ctx, p.site, p.decidedBy, (p.msg as HistoryMsg | undefined) ?? p.sentence)
|
|
231
|
+
return null
|
|
232
|
+
},
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
export const reject = mutation({
|
|
236
|
+
args: { proposal: v.string(), reason: v.string() },
|
|
237
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
238
|
+
const { actor, proposal: p } = await actorForProposal(ctx, args.proposal)
|
|
239
|
+
requireDecide(actor, p)
|
|
240
|
+
const reason = args.reason.trim()
|
|
241
|
+
if (reason.length < 1 || reason.length > REASON_MAX) fail('INVALID', 'errors.reasonOneSentence', { reasonMax: REASON_MAX })
|
|
242
|
+
if (p.status !== 'open' && !(p.status === 'scheduled' && !p.release)) fail('CHANGED_SINCE', 'errors.proposalNoLongerOpen', undefined, { status: p.status })
|
|
243
|
+
if (p.job) await ctx.scheduler.cancel(p.job)
|
|
244
|
+
await ctx.db.patch(p._id, { status: 'rejected', reason, decidedBy: actor.user.id, decidedAt: Date.now(), job: undefined, release: undefined })
|
|
245
|
+
// A rejection needs the author to act, often the same day; an approval needs nothing (decisions: email on rejection only).
|
|
246
|
+
if (p.author !== actor.user.id) await mailRejected(ctx, p, reason)
|
|
247
|
+
return { proposal: p._id, status: 'rejected' }
|
|
248
|
+
},
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
/** The author takes their own proposal back, as long as nobody decided it. */
|
|
252
|
+
export const withdraw = mutation({
|
|
253
|
+
args: { proposal: v.string() },
|
|
254
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
255
|
+
const { actor, proposal: p } = await actorForProposal(ctx, args.proposal)
|
|
256
|
+
if (p.author !== actor.user.id) fail('FORBIDDEN', 'errors.onlyProposerCanWithdraw')
|
|
257
|
+
if (p.status !== 'open') fail('CHANGED_SINCE', 'errors.proposalNoLongerOpen', undefined, { status: p.status })
|
|
258
|
+
await ctx.db.patch(p._id, { status: 'withdrawn', decidedBy: actor.user.id, decidedAt: Date.now(), release: undefined })
|
|
259
|
+
return { proposal: p._id, status: 'withdrawn' }
|
|
260
|
+
},
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
// ---- Reading ----
|
|
264
|
+
|
|
265
|
+
async function summary(p: Doc<'proposals'>, actor: Actor, names: Labeler) {
|
|
266
|
+
return {
|
|
267
|
+
proposal: p._id, op: p.op, brick: p.brick, entry: p.entry ?? null, task: taskOf(p.args) ?? null, sentence: p.sentence, msg: p.msg ?? null, status: p.status,
|
|
268
|
+
author: await names.who(p.author), mine: p.author === actor.user.id, via: p.via, agent: await names.key(p.agentKey),
|
|
269
|
+
createdAt: p.createdAt, at: p.at ?? null, release: p.release ?? null,
|
|
270
|
+
decidedBy: p.decidedBy ? await names.who(p.decidedBy) : null, decidedAt: p.decidedAt ?? null, reason: p.reason ?? null, reasonMsg: p.reasonMsg ?? null,
|
|
271
|
+
change: p.change ?? null,
|
|
272
|
+
/** Whether the signed-in person may approve or reject it (not staff, not their own). */
|
|
273
|
+
canDecide: isApprover(actor) && (p.author !== actor.user.id || p.via === 'agent') && (p.status === 'open' || p.status === 'scheduled'),
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** A row of the inbox: an open or scheduled one carries `conflict` (and its message `conflictMsg`), why it would be stale if decided now. */
|
|
278
|
+
async function inboxRow(ctx: QueryCtx, p: Doc<'proposals'>, actor: Actor, names: Labeler) {
|
|
279
|
+
const conflict = p.status === 'open' || p.status === 'scheduled' ? await staleReason(ctx, p) : null
|
|
280
|
+
return { ...(await summary(p, actor, names)), conflict: conflict?.reason ?? null, conflictMsg: conflict?.msg ?? null }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Open proposals this person has to look at: for an approver all of the site, for an author their own. */
|
|
284
|
+
async function openCount(ctx: QueryCtx, actor: Actor): Promise<number> {
|
|
285
|
+
const open = await ctx.db.query('proposals').withIndex('by_site_status', (q) => q.eq('site', actor.site._id).eq('status', 'open')).collect()
|
|
286
|
+
return open.filter((p) => isApprover(actor) || p.author === actor.user.id).length
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Proposals of a site, newest first (`order: 'oldest'` reverses it). Approvers see all of them, authors their own.
|
|
291
|
+
* `status` narrows. A paginated query (`useConvexPaginatedQuery`), at most 50 rows a page. Every row is an
|
|
292
|
+
* `inboxRow`, so the inbox needs no `get` per row. `count` is the number of open ones.
|
|
293
|
+
*/
|
|
294
|
+
export const list = query({
|
|
295
|
+
args: { site: v.string(), status: v.optional(status), order: v.optional(v.union(v.literal('newest'), v.literal('oldest'))), paginationOpts: paginationOptsValidator },
|
|
296
|
+
handler: async (ctx, args) => {
|
|
297
|
+
const actor = await siteActor(ctx, args.site)
|
|
298
|
+
const site = actor.site._id
|
|
299
|
+
const wanted = args.status
|
|
300
|
+
const rows = isApprover(actor)
|
|
301
|
+
? wanted
|
|
302
|
+
? ctx.db.query('proposals').withIndex('by_site_status', (q) => q.eq('site', site).eq('status', wanted))
|
|
303
|
+
: ctx.db.query('proposals').withIndex('by_site', (q) => q.eq('site', site))
|
|
304
|
+
: ctx.db.query('proposals').withIndex('by_site_author', (q) => q.eq('site', site).eq('author', actor.user.id)).filter((q) => (wanted ? q.eq(q.field('status'), wanted) : true))
|
|
305
|
+
const opts = args.paginationOpts
|
|
306
|
+
let page
|
|
307
|
+
try {
|
|
308
|
+
page = await rows.order(args.order === 'oldest' ? 'asc' : 'desc').paginate({ ...opts, numItems: Math.min(opts.numItems, PAGE_SIZE) })
|
|
309
|
+
} catch (error) {
|
|
310
|
+
// The cursor comes from the client; the database refuses one it did not hand out.
|
|
311
|
+
if (opts.cursor === null) throw error
|
|
312
|
+
fail('INVALID', 'errors.pageMarkerInvalid')
|
|
313
|
+
}
|
|
314
|
+
const names = await labeler(ctx, actor)
|
|
315
|
+
return { ...page, page: await Promise.all(page.page.map((p) => inboxRow(ctx, p, actor, names))) }
|
|
316
|
+
},
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* The actor's own proposals of one status (else of any), 50 at most: newest first; of one decided status the
|
|
321
|
+
* latest decided first. `since` keeps only those decided after it.
|
|
322
|
+
*/
|
|
323
|
+
async function ownDocs(ctx: QueryCtx, actor: Actor, wanted?: Doc<'proposals'>['status'], since?: number) {
|
|
324
|
+
const own = wanted
|
|
325
|
+
? ctx.db.query('proposals').withIndex('by_site_author_status_decided', (q) => {
|
|
326
|
+
const status = q.eq('site', actor.site._id).eq('author', actor.user.id).eq('status', wanted)
|
|
327
|
+
return since === undefined ? status : status.gt('decidedAt', since)
|
|
328
|
+
})
|
|
329
|
+
: ctx.db.query('proposals').withIndex('by_site_author', (q) => q.eq('site', actor.site._id).eq('author', actor.user.id))
|
|
330
|
+
return own.order('desc').take(PAGE_SIZE)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** The actor's own proposals, newest first (50 at most), also for an approver: the agent door tells a person what of theirs still waits (SPEC 16). */
|
|
334
|
+
export async function ownAs(ctx: QueryCtx, actor: Actor, wanted?: Doc<'proposals'>['status']) {
|
|
335
|
+
const rows = await ownDocs(ctx, actor, wanted)
|
|
336
|
+
const names = await labeler(ctx, actor)
|
|
337
|
+
return Promise.all(rows.map((p) => summary(p, actor, names)))
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Long enough to be read after a weekend off; older rejections and failed plans are only in the approver's history. */
|
|
341
|
+
const RECENT_MS = 14 * 24 * 60 * 60 * 1000
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* The top of History (UI.md 10.4), also for an approver: the person's own open proposals (`open`), their own
|
|
345
|
+
* proposals rejected in the last two weeks (`rejected`), and planned changes that did not go live in the last
|
|
346
|
+
* two weeks because they no longer fitted at their time (`notLive`): for an approver of the whole site, who
|
|
347
|
+
* planned them, else their own. Each list reads at most 50 rows through an index.
|
|
348
|
+
*/
|
|
349
|
+
export const mine = query({
|
|
350
|
+
args: { site: v.string() },
|
|
351
|
+
handler: async (ctx, args) => {
|
|
352
|
+
const actor = await siteActor(ctx, args.site)
|
|
353
|
+
// The window is an index range over decidedAt, so a proposal created long ago and decided today is not
|
|
354
|
+
// crowded out by 50 newer ones. Convex does not re-run a query as time passes: a row may stay past day 14
|
|
355
|
+
// until something else changes the result.
|
|
356
|
+
const since = Date.now() - RECENT_MS
|
|
357
|
+
const stale = isApprover(actor)
|
|
358
|
+
? await ctx.db.query('proposals').withIndex('by_site_status_decided', (q) => q.eq('site', actor.site._id).eq('status', 'stale').gt('decidedAt', since)).order('desc').take(PAGE_SIZE)
|
|
359
|
+
: await ownDocs(ctx, actor, 'stale', since)
|
|
360
|
+
const names = await labeler(ctx, actor)
|
|
361
|
+
const rows = (docs: Doc<'proposals'>[]) => Promise.all(docs.map((p) => summary(p, actor, names)))
|
|
362
|
+
// A rejected save stays only while it is still the thing to fix (`followUp`): not after a newer proposal on the
|
|
363
|
+
// entry, nor after a later change of its fields.
|
|
364
|
+
const recent = await ownDocs(ctx, actor)
|
|
365
|
+
const rejected = []
|
|
366
|
+
for (const p of await ownDocs(ctx, actor, 'rejected', since)) {
|
|
367
|
+
if (p.op !== 'save' || !p.entry || p.via !== 'ui' || (await followUp(ctx, recent, p.entry))?._id === p._id) rejected.push(p)
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
open: await rows(await ownDocs(ctx, actor, 'open')),
|
|
371
|
+
rejected: await rows(rejected),
|
|
372
|
+
notLive: await rows(stale.filter((p) => p.at !== undefined)),
|
|
373
|
+
}
|
|
374
|
+
},
|
|
375
|
+
})
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* The author's proposal to follow up on for one entry in the Studio, from their newest own proposals (`ownDocs`): their
|
|
379
|
+
* newest save of the entry made in the Studio (an agent's proposals are reviewed in the inbox) when it is open, or when
|
|
380
|
+
* it was rejected in the last two weeks and still fits (`staleReason`). A newer own proposal on the entry, or a later
|
|
381
|
+
* change of those fields, makes an older rejection moot.
|
|
382
|
+
*/
|
|
383
|
+
async function followUp(ctx: QueryCtx, recent: Doc<'proposals'>[], entry: Id<'entries'>): Promise<Doc<'proposals'> | null> {
|
|
384
|
+
const p = recent.find((r) => r.op === 'save' && r.via === 'ui' && r.entry === entry)
|
|
385
|
+
if (!p) return null
|
|
386
|
+
if (p.status === 'open') return p
|
|
387
|
+
if (p.status !== 'rejected' || (p.decidedAt ?? 0) <= Date.now() - RECENT_MS) return null
|
|
388
|
+
return (await staleReason(ctx, p)) ? null : p
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* The signed-in person's own proposal for an entry that a task sheet starts from (`followUp`): the fields it sent,
|
|
393
|
+
* and for a rejection who rejected it and why. `fits` is false for an open one whose fields someone changed since
|
|
394
|
+
* (`staleReason`): the sheet then starts from the stored values, so sending again does not bring the old ones back
|
|
395
|
+
* with a fresh base. `null` when there is nothing to follow up.
|
|
396
|
+
*/
|
|
397
|
+
export const ownFor = query({
|
|
398
|
+
args: { site: v.string(), entry: v.string() },
|
|
399
|
+
handler: async (ctx, args) => {
|
|
400
|
+
const actor = await siteActor(ctx, args.site)
|
|
401
|
+
const entry = ctx.db.normalizeId('entries', args.entry)
|
|
402
|
+
const p = entry ? await followUp(ctx, await ownDocs(ctx, actor), entry) : null
|
|
403
|
+
if (!p) return null
|
|
404
|
+
const names = await labeler(ctx, actor)
|
|
405
|
+
const sent = p.args as { fields?: Record<string, Json> }
|
|
406
|
+
return {
|
|
407
|
+
proposal: p._id, status: p.status, task: taskOf(p.args) ?? null, fields: sent.fields ?? {}, createdAt: p.createdAt,
|
|
408
|
+
// A rejection `followUp` returns fits already.
|
|
409
|
+
fits: p.status !== 'open' || (await staleReason(ctx, p)) === null,
|
|
410
|
+
decidedAt: p.decidedAt ?? null, decidedBy: p.decidedBy ? await names.who(p.decidedBy) : null, reason: p.reason ?? null,
|
|
411
|
+
}
|
|
412
|
+
},
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
/** "Zu prüfen (n)": open proposals a signed-in approver has to look at; for authors their own open ones. */
|
|
416
|
+
export const count = query({
|
|
417
|
+
args: { site: v.string() },
|
|
418
|
+
handler: async (ctx, args): Promise<number> => {
|
|
419
|
+
const actor = await siteActor(ctx, args.site)
|
|
420
|
+
return openCount(ctx, actor)
|
|
421
|
+
},
|
|
422
|
+
})
|
|
423
|
+
|
|
424
|
+
/** One proposal with before/after per field, for the diff. `conflict` is the reason it would be stale if decided now. */
|
|
425
|
+
export const get = query({
|
|
426
|
+
args: { site: v.string(), proposal: v.string() },
|
|
427
|
+
handler: async (ctx, args) => {
|
|
428
|
+
const actor = await siteActor(ctx, args.site)
|
|
429
|
+
const id = ctx.db.normalizeId('proposals', args.proposal)
|
|
430
|
+
const p = id ? await ctx.db.get(id) : null
|
|
431
|
+
if (!p || p.site !== actor.site._id || (!isApprover(actor) && p.author !== actor.user.id)) fail('NOT_FOUND', 'errors.proposalNotFound')
|
|
432
|
+
const schema = actor.site.schema as Schema
|
|
433
|
+
const brick = Object.hasOwn(schema.bricks, p.brick) ? schema.bricks[p.brick] : undefined
|
|
434
|
+
const before = (p.before ?? {}) as Record<string, Json>
|
|
435
|
+
const after = (p.after ?? {}) as Record<string, Json>
|
|
436
|
+
// In the reader's language; the dates are written in the site's zone.
|
|
437
|
+
const locale = await localeOfUser(ctx, actor.user.id)
|
|
438
|
+
const when = (state: Json | undefined, publishAt: Json | undefined) => {
|
|
439
|
+
if (typeof state !== 'string') return null
|
|
440
|
+
const name = state === 'draft' ? msg('history.stateDraft') : state === 'live' ? msg('history.stateLive') : undefined
|
|
441
|
+
if (typeof publishAt !== 'number') return name ? historyText(name, locale, schema) : state
|
|
442
|
+
return historyText(msg('history.stateScheduled', { state: name ?? state, at: publishAt }), locale, schema)
|
|
443
|
+
}
|
|
444
|
+
// Publishing unpublished changes shows their fields; any other publish or unpublish shows the state.
|
|
445
|
+
const diff = (p.op === 'publish' || p.op === 'unpublish') && before.state !== undefined
|
|
446
|
+
? [{ field: 'state', label: t(locale, 'history.stateField'), kind: 'state', before: when(before.state, before.publishAt), after: when(after.state, after.publishAt) }]
|
|
447
|
+
: diffFields(brick?.fields, before, after, schema.locales[0]!)
|
|
448
|
+
const names = await labeler(ctx, actor)
|
|
449
|
+
const conflict = p.status === 'open' || p.status === 'scheduled' ? await staleReason(ctx, p) : null
|
|
450
|
+
return {
|
|
451
|
+
...(await summary(p, actor, names)), diff, base: p.base as Json,
|
|
452
|
+
conflict: conflict?.reason ?? null, conflictMsg: conflict?.msg ?? null,
|
|
453
|
+
}
|
|
454
|
+
},
|
|
455
|
+
})
|
|
456
|
+
|
|
457
|
+
// ---- Releases: proposals approved together, all or none ----
|
|
458
|
+
|
|
459
|
+
/** A release with every member as an `inboxRow`, so the inbox shows the members whichever page of `list` is loaded. */
|
|
460
|
+
const releaseSummary = async (ctx: QueryCtx, r: Doc<'releases'>, actor: Actor, names: Labeler) => {
|
|
461
|
+
const members = await ctx.db.query('proposals').withIndex('by_release', (q) => q.eq('release', r._id)).collect()
|
|
462
|
+
return {
|
|
463
|
+
release: r._id, name: r.name, status: r.status, at: r.at ?? null, createdAt: r.createdAt, decidedAt: r.decidedAt ?? null,
|
|
464
|
+
proposals: await Promise.all(members.map((p) => inboxRow(ctx, p, actor, names))),
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* The site's releases still to decide (open or stale), newest first (50 at most), each with its proposals.
|
|
470
|
+
* Decided ones are left out: each member costs reads of its entry. Approvers only: staff sees proposals, not their grouping.
|
|
471
|
+
*/
|
|
472
|
+
export const releases = query({
|
|
473
|
+
args: { site: v.string() },
|
|
474
|
+
handler: async (ctx, args) => {
|
|
475
|
+
const actor = await siteActor(ctx, args.site)
|
|
476
|
+
if (!isApprover(actor)) fail('FORBIDDEN', 'errors.ownersOnly')
|
|
477
|
+
const of = (status: 'open' | 'stale') =>
|
|
478
|
+
ctx.db.query('releases').withIndex('by_site_status', (q) => q.eq('site', actor.site._id).eq('status', status)).order('desc').take(50)
|
|
479
|
+
const rows = [...(await of('open')), ...(await of('stale'))].sort((a, b) => b._creationTime - a._creationTime).slice(0, 50)
|
|
480
|
+
const names = await labeler(ctx, actor)
|
|
481
|
+
return Promise.all(rows.map((r) => releaseSummary(ctx, r, actor, names)))
|
|
482
|
+
},
|
|
483
|
+
})
|
|
484
|
+
|
|
485
|
+
/** A new release; `at` is the planned time (an approval may set another). */
|
|
486
|
+
export const createRelease = mutation({
|
|
487
|
+
args: { site: v.string(), name: v.string(), at: v.optional(v.number()) },
|
|
488
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
489
|
+
const actor = await siteActor(ctx, args.site)
|
|
490
|
+
if (!isApprover(actor)) fail('FORBIDDEN', 'errors.ownersOnly')
|
|
491
|
+
const name = args.name.trim()
|
|
492
|
+
if (name.length < 1 || name.length > NAME_MAX) fail('INVALID', 'errors.nameLength1ToMax', { nameMax: NAME_MAX })
|
|
493
|
+
if (args.at !== undefined) checkFuture(args.at)
|
|
494
|
+
const release = await ctx.db.insert('releases', { site: actor.site._id, name, status: 'open', createdBy: actor.user.id, createdAt: Date.now(), ...(args.at === undefined ? {} : { at: args.at }) })
|
|
495
|
+
return { release, status: 'open' }
|
|
496
|
+
},
|
|
497
|
+
})
|
|
498
|
+
|
|
499
|
+
const EDITABLE = new Set(['open', 'stale'])
|
|
500
|
+
|
|
501
|
+
export const addToRelease = mutation({
|
|
502
|
+
args: { release: v.string(), proposal: v.string() },
|
|
503
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
504
|
+
const { actor, release } = await actorForRelease(ctx, args.release)
|
|
505
|
+
if (!isApprover(actor)) fail('FORBIDDEN', 'errors.ownersOnly')
|
|
506
|
+
const key = ctx.db.normalizeId('proposals', args.proposal)
|
|
507
|
+
const p = key ? await ctx.db.get(key) : null
|
|
508
|
+
if (!p || p.site !== release.site) fail('NOT_FOUND', 'errors.proposalNotFound')
|
|
509
|
+
if (!EDITABLE.has(release.status)) fail('CHANGED_SINCE', 'errors.releaseNoLongerOpen', undefined, { status: release.status })
|
|
510
|
+
if (p.status !== 'open') fail('CHANGED_SINCE', 'errors.proposalNoLongerOpen', undefined, { status: p.status })
|
|
511
|
+
if (p.release === release._id) return { release: release._id, proposals: (await ctx.db.query('proposals').withIndex('by_release', (q) => q.eq('release', release._id)).collect()).length }
|
|
512
|
+
if (p.release) fail('INVALID', 'errors.proposalInOtherRelease')
|
|
513
|
+
const members = await ctx.db.query('proposals').withIndex('by_release', (q) => q.eq('release', release._id)).collect()
|
|
514
|
+
if (members.length >= RELEASE_MAX) fail('INVALID', 'errors.releaseTooManyProposals', { releaseMax: RELEASE_MAX })
|
|
515
|
+
await ctx.db.patch(p._id, { release: release._id })
|
|
516
|
+
return { release: release._id, proposals: members.length + 1 }
|
|
517
|
+
},
|
|
518
|
+
})
|
|
519
|
+
|
|
520
|
+
export const removeFromRelease = mutation({
|
|
521
|
+
args: { release: v.string(), proposal: v.string() },
|
|
522
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
523
|
+
const { actor, release } = await actorForRelease(ctx, args.release)
|
|
524
|
+
if (!isApprover(actor)) fail('FORBIDDEN', 'errors.ownersOnly')
|
|
525
|
+
const key = ctx.db.normalizeId('proposals', args.proposal)
|
|
526
|
+
const p = key ? await ctx.db.get(key) : null
|
|
527
|
+
if (!p || p.release !== release._id) fail('NOT_FOUND', 'errors.proposalNotInRelease')
|
|
528
|
+
if (!EDITABLE.has(release.status)) fail('CHANGED_SINCE', 'errors.releaseNoLongerOpen', undefined, { status: release.status })
|
|
529
|
+
await ctx.db.patch(p._id, { release: undefined })
|
|
530
|
+
return { release: release._id }
|
|
531
|
+
},
|
|
532
|
+
})
|
|
533
|
+
|
|
534
|
+
/** Stale members of a release, checked together without writing (a member can also collide with an earlier one). */
|
|
535
|
+
async function staleMembers(ctx: QueryCtx, members: Doc<'proposals'>[]) {
|
|
536
|
+
const touched: Touched = new Map()
|
|
537
|
+
const stale: { proposal: Id<'proposals'>; sentence: string; reason: string; reasonMsg: HistoryMsg }[] = []
|
|
538
|
+
for (const p of members) {
|
|
539
|
+
const reason = await staleReason(ctx, p, touched)
|
|
540
|
+
if (reason) stale.push({ proposal: p._id, sentence: p.sentence, reason: reason.reason, reasonMsg: reason.msg })
|
|
541
|
+
}
|
|
542
|
+
return stale
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Applies every proposal of the release in one mutation: all or none. A member that no longer fits
|
|
547
|
+
* is found first and marked stale; it blocks the release, which is answered with the list. Remove
|
|
548
|
+
* the stale members (removeFromRelease) and approve again. With `at` (or the release's planned
|
|
549
|
+
* time, when it is still ahead) the release is scheduled and re-checked when it runs.
|
|
550
|
+
*/
|
|
551
|
+
export const approveRelease = mutation({
|
|
552
|
+
args: { release: v.string(), at: v.optional(v.number()) },
|
|
553
|
+
handler: async (ctx, args): Promise<Json> => {
|
|
554
|
+
const { actor, release } = await actorForRelease(ctx, args.release)
|
|
555
|
+
if (!isApprover(actor)) fail('FORBIDDEN', 'errors.ownersOnly')
|
|
556
|
+
if (!EDITABLE.has(release.status)) fail('CHANGED_SINCE', 'errors.releaseNoLongerOpen', undefined, { status: release.status })
|
|
557
|
+
const by = actor.user.id
|
|
558
|
+
const all = await ctx.db.query('proposals').withIndex('by_release', (q) => q.eq('release', release._id)).collect()
|
|
559
|
+
const members = all.filter((p) => p.status === 'open')
|
|
560
|
+
const blocked = all.filter((p) => p.status === 'stale').map((p) => ({ proposal: p._id, sentence: p.sentence, reason: p.reason ?? '', reasonMsg: p.reasonMsg ?? null }))
|
|
561
|
+
if (!members.length && !blocked.length) fail('INVALID', 'errors.releaseEmpty')
|
|
562
|
+
for (const p of members) requireDecide(actor, p)
|
|
563
|
+
if (blocked.length) return { release: release._id, status: 'stale', stale: blocked }
|
|
564
|
+
|
|
565
|
+
if (args.at !== undefined) checkFuture(args.at)
|
|
566
|
+
const now = Date.now()
|
|
567
|
+
const at = args.at ?? (release.at !== undefined && release.at > now ? release.at : undefined)
|
|
568
|
+
const stale = await staleMembers(ctx, members)
|
|
569
|
+
if (stale.length) {
|
|
570
|
+
for (const s of stale) await markStale(ctx, members.find((p) => p._id === s.proposal)!, { reason: s.reason, msg: s.reasonMsg }, by)
|
|
571
|
+
await ctx.db.patch(release._id, { status: 'stale' })
|
|
572
|
+
return { release: release._id, status: 'stale', stale }
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
if (at !== undefined) {
|
|
576
|
+
const job = await ctx.scheduler.runAt(at, internal.proposals.applyReleaseScheduled, { release: release._id, at })
|
|
577
|
+
for (const p of members) await ctx.db.patch(p._id, { status: 'scheduled', at, decidedBy: by, decidedAt: now })
|
|
578
|
+
await ctx.db.patch(release._id, { status: 'scheduled', at, job, decidedBy: by, decidedAt: now })
|
|
579
|
+
return { release: release._id, status: 'scheduled', at }
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// Oldest first. The first failure throws: the mutation, and with it every write above, is rolled back.
|
|
583
|
+
for (const p of members.sort((a, b) => a._creationTime - b._creationTime)) {
|
|
584
|
+
const applied = await applyNow(ctx, p, by)
|
|
585
|
+
if (!applied.ok) fail('STALE', 'errors.proposalNoLongerFitsRelease', undefined, { release: release._id, stale: [{ proposal: p._id, sentence: p.sentence, reason: applied.reason, reasonMsg: applied.msg }] })
|
|
586
|
+
await markApplied(ctx, p, by, applied.change)
|
|
587
|
+
}
|
|
588
|
+
await ctx.db.patch(release._id, { status: 'applied', decidedBy: by, decidedAt: now, job: undefined })
|
|
589
|
+
return { release: release._id, status: 'applied', applied: members.length }
|
|
590
|
+
},
|
|
591
|
+
})
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* The run of a scheduled release. A member that went stale blocks it; the others go back to open.
|
|
595
|
+
* Applying is all or none, so a member that fails while being written rolls the whole run back. The
|
|
596
|
+
* job is an action for that case: the failure is then recorded in its own mutation (`releaseFailed`)
|
|
597
|
+
* instead of leaving the release "scheduled" with nobody told.
|
|
598
|
+
*/
|
|
599
|
+
export const applyReleaseScheduled = internalAction({
|
|
600
|
+
args: { release: v.id('releases'), at: v.number() },
|
|
601
|
+
handler: async (ctx, args): Promise<null> => {
|
|
602
|
+
try {
|
|
603
|
+
await ctx.runMutation(internal.proposals.runScheduledRelease, args)
|
|
604
|
+
} catch (error) {
|
|
605
|
+
const data = error instanceof ConvexError ? error.data as { code?: string; details?: { stale?: StaleMember[] } } : undefined
|
|
606
|
+
await ctx.runMutation(internal.proposals.releaseFailed, { ...args, stale: data?.code === 'STALE' ? data.details?.stale ?? [] : [] })
|
|
607
|
+
// Anything but a member that no longer fits is a bug: it stays visible in the logs.
|
|
608
|
+
if (data?.code !== 'STALE') throw error
|
|
609
|
+
}
|
|
610
|
+
return null
|
|
611
|
+
},
|
|
612
|
+
})
|
|
613
|
+
|
|
614
|
+
type StaleMember = { proposal: Id<'proposals'>; reason: string; reasonMsg: HistoryMsg }
|
|
615
|
+
|
|
616
|
+
export const runScheduledRelease = internalMutation({
|
|
617
|
+
args: { release: v.id('releases'), at: v.number() },
|
|
618
|
+
handler: async (ctx, args): Promise<null> => {
|
|
619
|
+
const release = await ctx.db.get(args.release)
|
|
620
|
+
if (!release || release.status !== 'scheduled' || release.at !== args.at || !release.decidedBy) return null
|
|
621
|
+
const by = release.decidedBy
|
|
622
|
+
const members = await scheduledMembers(ctx, release._id)
|
|
623
|
+
const site = await ctx.db.get(release.site)
|
|
624
|
+
const approver = site && await memberOf(ctx, site, { id: by })
|
|
625
|
+
const stale = approver && isApprover(approver)
|
|
626
|
+
? await staleMembers(ctx, members)
|
|
627
|
+
: members.map((p) => { const why = staleBecause('history.staleApproverNotAllowed'); return { proposal: p._id, sentence: p.sentence, reason: why.reason, reasonMsg: why.msg } })
|
|
628
|
+
if (stale.length) {
|
|
629
|
+
await blockRelease(ctx, release, members, stale)
|
|
630
|
+
return null
|
|
631
|
+
}
|
|
632
|
+
for (const p of members) {
|
|
633
|
+
const applied = await applyNow(ctx, p, by)
|
|
634
|
+
if (!applied.ok) fail('STALE', 'errors.proposalNoLongerFitsRelease', undefined, { release: release._id, stale: [{ proposal: p._id, reason: applied.reason, reasonMsg: applied.msg }] })
|
|
635
|
+
await markApplied(ctx, p, by, applied.change)
|
|
636
|
+
}
|
|
637
|
+
await ctx.db.patch(release._id, { status: 'applied', job: undefined })
|
|
638
|
+
return null
|
|
639
|
+
},
|
|
640
|
+
})
|
|
641
|
+
|
|
642
|
+
/** A scheduled release whose run was rolled back: the failing member is stale with its reason, the others are open again. */
|
|
643
|
+
export const releaseFailed = internalMutation({
|
|
644
|
+
args: { release: v.id('releases'), at: v.number(), stale: v.array(v.object({ proposal: v.id('proposals'), reason: v.string(), reasonMsg: v.any() })) },
|
|
645
|
+
handler: async (ctx, args): Promise<null> => {
|
|
646
|
+
const release = await ctx.db.get(args.release)
|
|
647
|
+
if (!release || release.status !== 'scheduled' || release.at !== args.at) return null
|
|
648
|
+
await blockRelease(ctx, release, await scheduledMembers(ctx, release._id), args.stale as StaleMember[])
|
|
649
|
+
return null
|
|
650
|
+
},
|
|
651
|
+
})
|
|
652
|
+
|
|
653
|
+
const scheduledMembers = async (ctx: QueryCtx, release: Id<'releases'>) =>
|
|
654
|
+
(await ctx.db.query('proposals').withIndex('by_release', (q) => q.eq('release', release)).collect())
|
|
655
|
+
.filter((p) => p.status === 'scheduled').sort((a, b) => a._creationTime - b._creationTime)
|
|
656
|
+
|
|
657
|
+
/** The release did not go live: stale members keep their reason, the rest go back to open, and the approver is told. */
|
|
658
|
+
async function blockRelease(ctx: MutationCtx, release: Doc<'releases'>, members: Doc<'proposals'>[], stale: StaleMember[]) {
|
|
659
|
+
const by = release.decidedBy!
|
|
660
|
+
for (const p of members) {
|
|
661
|
+
const s = stale.find((x) => x.proposal === p._id)
|
|
662
|
+
if (s) await markStale(ctx, p, { reason: s.reason, msg: s.reasonMsg }, by, true)
|
|
663
|
+
else await reopen(ctx, p)
|
|
664
|
+
}
|
|
665
|
+
await ctx.db.patch(release._id, { status: 'stale', job: undefined })
|
|
666
|
+
await mailNotLive(ctx, release.site, by, release.name)
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Tells the approver that a change they planned did not go live (SPEC 17). Without this, a planned
|
|
671
|
+
* change that no longer fits fails at night and the inbox still says "scheduled".
|
|
672
|
+
*/
|
|
673
|
+
async function mailNotLive(ctx: MutationCtx, siteId: Id<'sites'>, approver: string, what: HistoryMsg | string) {
|
|
674
|
+
const site = await ctx.db.get(siteId)
|
|
675
|
+
if (!site || !mailAvailable()) return
|
|
676
|
+
const member = await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', site._id)).filter((q) => q.eq(q.field('user'), approver)).first()
|
|
677
|
+
if (!member?.email) return
|
|
678
|
+
const locale = await localeOfUser(ctx, member.user)
|
|
679
|
+
await queueMail(ctx, {
|
|
680
|
+
to: member.email,
|
|
681
|
+
subject: t(locale, 'mail.notLive.subject', { site: site.name }),
|
|
682
|
+
text: t(locale, 'mail.notLive.text', { site: site.name, what: typeof what === 'string' ? what : historyText(what, locale, site.schema as Schema), path: `${siteOrigin()}/s/${site.slug}/history` }),
|
|
683
|
+
})
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Tells the author at once that their proposal was not approved, with the approver's reason and a link that reopens
|
|
688
|
+
* it in its task (Schnell ändern), else Schnell ändern itself. An assistant's proposal is not reopened in the Studio
|
|
689
|
+
* (`followUp`): its link is Verlauf, which lists it with the reason. In the author's language.
|
|
690
|
+
*/
|
|
691
|
+
async function mailRejected(ctx: MutationCtx, p: Doc<'proposals'>, reason: string) {
|
|
692
|
+
const site = await ctx.db.get(p.site)
|
|
693
|
+
if (!site || !mailAvailable()) return
|
|
694
|
+
const member = await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', site._id)).filter((q) => q.eq(q.field('user'), p.author)).first()
|
|
695
|
+
if (!member?.email) return
|
|
696
|
+
const locale = await localeOfUser(ctx, member.user)
|
|
697
|
+
const task = taskOf(p.args)
|
|
698
|
+
const fix = p.via === 'agent' ? '/history' : p.op === 'save' && p.entry && task ? `?task=${encodeURIComponent(task)}&reopen=${p._id}` : ''
|
|
699
|
+
await queueMail(ctx, {
|
|
700
|
+
to: member.email,
|
|
701
|
+
subject: t(locale, 'mail.rejected.subject', { site: site.name }),
|
|
702
|
+
text: t(locale, 'mail.rejected.text', { site: site.name, what: p.msg ? historyText(p.msg as HistoryMsg, locale, site.schema as Schema) : p.sentence, reason, path: `${siteOrigin()}/s/${site.slug}${fix}` }),
|
|
703
|
+
})
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// ---- Mail: one digest for the approvers ----
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* The digest mail (SPEC 17): runs 10 minutes after the first open proposal of a site and lists every
|
|
710
|
+
* open proposal not yet mailed, so proposals made in the window share one mail. Goes to the owners
|
|
711
|
+
* of the site; nothing is sent when none is still open or mail is not set up.
|
|
712
|
+
*/
|
|
713
|
+
export const sendDigest = internalMutation({
|
|
714
|
+
args: { site: v.id('sites') },
|
|
715
|
+
handler: async (ctx, args): Promise<null> => {
|
|
716
|
+
const site = await ctx.db.get(args.site)
|
|
717
|
+
if (!site || site.deleting) return null
|
|
718
|
+
await ctx.db.patch(site._id, { digestAt: undefined })
|
|
719
|
+
const open = (await ctx.db.query('proposals').withIndex('by_site_status', (q) => q.eq('site', site._id).eq('status', 'open')).collect())
|
|
720
|
+
.filter((p) => p.mailedAt === undefined)
|
|
721
|
+
if (!open.length || !mailAvailable()) return null
|
|
722
|
+
const members = await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', site._id)).collect()
|
|
723
|
+
const emailOf = new Map(members.map((m) => [m.user as string, m.email]))
|
|
724
|
+
const nameOf = namer(ctx)
|
|
725
|
+
const schema = site.schema as Schema
|
|
726
|
+
const who: { author: string; name?: string; viaAgent: boolean; ai: string | null; sentence: string; msg?: HistoryMsg }[] = []
|
|
727
|
+
for (const p of open) {
|
|
728
|
+
// The key's label ("Claude Code"); null when the key is gone, then the line says only "via AI".
|
|
729
|
+
const ai = p.agentKey ? (await ctx.db.get(p.agentKey))?.label ?? null : null
|
|
730
|
+
const name = await nameOf(p.author)
|
|
731
|
+
who.push({ author: p.author, ...(name ? { name } : {}), viaAgent: p.via === 'agent', ai, sentence: p.sentence, ...(p.msg ? { msg: p.msg as HistoryMsg } : {}) })
|
|
732
|
+
}
|
|
733
|
+
// Each owner gets the mail in their own language.
|
|
734
|
+
for (const owner of members.filter((m) => m.role === 'owner' && m.email)) {
|
|
735
|
+
const locale = await localeOfUser(ctx, owner.user)
|
|
736
|
+
const lines = who.map((w) => {
|
|
737
|
+
// As the Studio shows people to owners: the name the person set, with the address they verified.
|
|
738
|
+
const email = emailOf.get(w.author)
|
|
739
|
+
const name = email ? (w.name ? `${w.name} (${email})` : email) : w.name ?? t(locale, 'mail.digest.someone')
|
|
740
|
+
const via = !w.viaAgent ? '' : ` ${w.ai ? t(locale, 'mail.digest.viaAi', { ai: w.ai }) : t(locale, 'mail.digest.viaAiUnnamed')}`
|
|
741
|
+
return `- ${name}${via}: ${w.msg ? historyText(w.msg, locale, schema) : w.sentence}`
|
|
742
|
+
})
|
|
743
|
+
await queueMail(ctx, {
|
|
744
|
+
to: owner.email!,
|
|
745
|
+
subject: t(locale, 'mail.digest.subject', { count: open.length, site: site.name }),
|
|
746
|
+
text: t(locale, 'mail.digest.text', { count: open.length, site: site.name, lines: lines.join('\n'), path: `${siteOrigin()}/s/${site.slug}/review` }),
|
|
747
|
+
})
|
|
748
|
+
}
|
|
749
|
+
const now = Date.now()
|
|
750
|
+
for (const p of open) await ctx.db.patch(p._id, { mailedAt: now })
|
|
751
|
+
return null
|
|
752
|
+
},
|
|
753
|
+
})
|