From 5f6c8159281c9a45f6fe0a48362e6e2291f63870 Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:09:55 -0700 Subject: [PATCH 1/2] Add item sources and per-site vote locking Lets another plugin offer items to a board (language requests, for one) with no import either way, and lets a site turn off placed-vote locking. Sync marks vanished items instead of deleting them. Not tested: tags, scopeField sites, very large sources, concurrent syncs, Postgres and SQLite. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++ README.md | 27 ++++++++ docs/decisions.md | 9 +++ docs/test-audit.md | 8 +++ src/api.ts | 2 +- src/collections.ts | 6 ++ src/index.ts | 5 +- src/sources.ts | 74 ++++++++++++++++++++++ src/types.ts | 36 +++++++++++ test/sources.test.ts | 148 +++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 320 insertions(+), 2 deletions(-) create mode 100644 docs/decisions.md create mode 100644 src/sources.ts create mode 100644 test/sources.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e7eb27..802593d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## Unreleased + +- New: `itemSources` option with `syncItemSources(payload)` and `syncItemSource(payload, key)`. External items become ordinary Roadmap items keyed by source key and id; sync updates title, summary and the source's vote count, marks vanished items `sourceGone` (never deletes), and leaves status and curator fields alone. Source items refuse Roadmap votes. `ItemSource` and `SourceItem` are structural types with no import from another plugin. +- New: `votes.lock` (default `true`). `false` lets voters withdraw placed votes at any time. +- Tested: 55 tests pass (8 new, in-memory MongoDB): create, re-sync without duplicates, removed item marked, curator stage and hidden survive, vote refusal through the API and server helpers, signed-out and non-staff writes refused, lock on and off. +- Not tested: tags are ignored; `scopeField` sites (source items get no scope); a source with thousands of items; running sync concurrently; Postgres and SQLite. + ## 0.4.2 (2026-11-11) - Fix: with the catalog on and no `scopeField`, `roadmap-categories` asked MongoDB for two indexes both named `slug_1`, so the site couldn't start. It now asks for one: the `slug` field's own `slug_1`, unique (and sparse, as Payload makes it). With a `scopeField` nothing changes: `_1_slug_1` stays unique per scope, beside a plain `slug_1`, so scoped sites need no index migration. diff --git a/README.md b/README.md index 30b5793..897eb81 100644 --- a/README.md +++ b/README.md @@ -76,12 +76,39 @@ Add the plugin before plugins that wrap collections it creates (e.g. list `roadm | `access.manage` | nobody | Who edits items and sees every vote | | `access.vote` | any signed-in user | Who may vote through the API. Only accounts of `usersSlug` can vote, always as themselves with weight 1; a vote that names another voter, a weight or a ballot is refused (403). Accounts from other auth collections never vote, see or delete votes unless `manage` lets them | | `allocation` | off | `{ earned: ({ payload, user, scope }) => Promise, lockDays?, boards?, releaseStages? }`: extra votes | +| `itemSources` | none | `[{ source, board, status? }]`: items synced from another plugin (below) | +| `votes.lock` | `true` | `false` lets voters withdraw placed votes at any time, ignoring `allocation.lockDays` | | `notices` | off | `{ fields: [{ name, label, options, boards? }] }`: conditional notices (below) | | `catalog` | off | `{ boards?, availableStages?, progressStages?, hiddenStages? }`: features catalog (below) | | `overrides.items` / `.votes` / `.notices` / `.categories` | | `(collection) => collection` | The public reads items that are not `hidden`. Voters read and delete only their own votes. +### Item sources + +Another plugin can offer items to a board without either plugin importing the other. A source is +`{ key, list({ payload }) => Promise<{ externalId, title, description?, votes, tags? }[]> }`. + +```ts +roadmapPlugin({ itemSources: [{ source: mySource, board: 'features', status: 'requested' }] }) + +await syncItemSources(payload) // every source +await syncItemSource(payload, 'my-source-key') // one, e.g. from the source's afterChange hook +``` + +Sync creates ordinary items keyed by source key and `externalId`, and later updates only the +title, the summary and the source's vote count. Status, curator notes and hiding stay as staff +set them. An item the source stops listing is marked `sourceGone`, never deleted. Source items +show the source's count and refuse Roadmap votes, so nothing is counted twice. The source fields +can't be written through the API, by anyone; the sync functions write with `overrideAccess`, so +call them from server code only. Tags are not stored yet. + +### Vote locking + +`allocation.lockDays` holds placed votes until they unlock. `votes: { lock: false }` turns that off +for a site: placed votes can be withdrawn at any time. The default is `true`, as before. The one free +vote per item was never locked. + ### Conditional notices Declare facts about items that editors can match on, and the plugin adds a `roadmap-notices` diff --git a/docs/decisions.md b/docs/decisions.md new file mode 100644 index 0000000..d73376b --- /dev/null +++ b/docs/decisions.md @@ -0,0 +1,9 @@ +# Decisions + +## 2026-11-16: item sources and per-site vote locking + +The owner, 2026-11-16: "languages should appear with everything else and yes, votes don't need to be locked. That should be adjustable per implementation." + +- Roadmap takes external items through an `itemSources` option and sync functions. They become ordinary items, so they appear with everything else on a board. Neither plugin imports the other; the source shape is a structural type here. +- Sync never deletes: an item a source stops listing is marked `sourceGone`, because a curator may have edited it. Roadmap's own fields are left alone, and source items take no Roadmap votes so nothing is counted twice. +- Vote locking is `votes.lock`, default `true` (today's behavior). `false` ignores `allocation.lockDays` for that site. diff --git a/docs/test-audit.md b/docs/test-audit.md index e902ff3..09b849d 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -2,6 +2,14 @@ Newest first. +## 2026-11-16: item sources and `votes.lock` + +Suite: 47 → 55 tests in 4 files. New `test/sources.test.ts` runs real Payload on in-memory MongoDB with two sites (locking default, locking off). Made-up data only. + +- **Covered.** Sync creates items; re-sync updates title, count and text with no duplicates and leaves stage and hidden alone; a removed source item is marked, not deleted, and unmarked when it returns; unknown source refused; a source item refuses a vote through the API, `castVote` and `allocateVotes`; signed-out and non-staff cannot create or update source fields, and staff cannot set them through the API either; placed votes stay locked by default and withdraw at once with `votes.lock: false`. +- **Skipped.** The field access flags on their own (the API tests cover them). +- **Not tested.** Tags (ignored), `scopeField` sites, very large sources, concurrent syncs, Postgres and SQLite. No mutation checks run. + ## 2026-11-11: catalog categories couldn't start without a `scopeField` Suite: 45 → 47 tests in 3 files. Real Payload on an in-memory MongoDB replica set, one database per site. Made-up categories only. diff --git a/src/api.ts b/src/api.ts index 4793e55..faafde7 100644 --- a/src/api.ts +++ b/src/api.ts @@ -221,7 +221,7 @@ export async function allocateVotes(payload: Payload, args: { item: string; user * item in a release stage can be withdrawn at once. */ export const unlocksAt = (opts: ResolvedRoadmapOptions, createdAt: string, stage?: string | null) => { - if (releases(opts, stage)) return null + if (releases(opts, stage) || !opts.votes.lock) return null const days = opts.allocation?.lockDays ?? 0 const at = new Date(new Date(createdAt).getTime() + days * 864e5) return at.getTime() > Date.now() ? at.toISOString() : null diff --git a/src/collections.ts b/src/collections.ts index 8587980..8127768 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -58,6 +58,11 @@ export const itemsCollection = (opts: ResolvedRoadmapOptions): CollectionConfig admin: { position: 'sidebar', description: 'From the title when empty.' }, }, { name: 'key', type: 'text', index: true, admin: { hidden: true } }, + // Set only by the sync functions (overrideAccess); nobody writes them through the API. + { name: 'sourceKey', type: 'text', index: true, admin: { position: 'sidebar', readOnly: true, description: 'The item source this came from. Its title, description and votes follow the source.' }, access: { create: () => false, update: () => false } }, + { name: 'externalId', type: 'text', index: true, admin: { hidden: true }, access: { create: () => false, update: () => false } }, + { name: 'sourceVotes', type: 'number', admin: { position: 'sidebar', readOnly: true, description: 'The source\'s own vote count.' }, access: { create: () => false, update: () => false } }, + { name: 'sourceGone', type: 'checkbox', defaultValue: false, admin: { position: 'sidebar', readOnly: true, description: 'The source no longer lists this item.' }, access: { create: () => false, update: () => false } }, { name: 'voteCount', type: 'number', @@ -282,6 +287,7 @@ export const votesCollection = (opts: ResolvedRoadmapOptions): CollectionConfig req, }) if (!item || (item as { hidden?: boolean }).hidden) throw new APIError('That roadmap item is not open for votes.', 400) + if ((item as { sourceKey?: string }).sourceKey) throw new APIError('Vote for this on the page it came from. It does not take votes here.', 400) if (opts.scopeField) data[opts.scopeField] = idOf((item as unknown as Record)[opts.scopeField]) || undefined return data }, diff --git a/src/index.ts b/src/index.ts index 364632f..646895a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,7 @@ import { docsAfterChange, docsAfterDelete, docsFeatures } from './docs' import { noticesCollection } from './notices' import type { ResolvedRoadmapOptions, RoadmapPluginOptions } from './types' -export type { CatalogStatus, RoadmapNotice, RoadmapNoticeField, RoadmapOption, RoadmapPluginOptions, ResolvedRoadmapOptions } from './types' +export type { ItemSource, ItemSourceConfig, SourceItem, CatalogStatus, RoadmapNotice, RoadmapNoticeField, RoadmapOption, RoadmapPluginOptions, ResolvedRoadmapOptions } from './types' export { getNoticeRules, matchingNotices } from './notices' export type { NoticeRule } from './notices' export { @@ -30,6 +30,7 @@ export { withdrawVotes, } from './api' export type { RoadmapItemDoc } from './api' +export { syncItemSource, syncItemSources } from './sources' export { catalogStatus, getCatalog } from './catalog' export { docsFeatures, type DocsFeature } from './docs' export type { CatalogEntry, CatalogSection } from './catalog' @@ -50,6 +51,8 @@ const resolve = (o: RoadmapPluginOptions): ResolvedRoadmapOptions => ({ subject: o.subject, scopeField: o.scopeField, allocation: o.allocation, + itemSources: o.itemSources ?? [], + votes: { lock: o.votes?.lock ?? true }, slugs: { items: 'roadmap-items', votes: 'roadmap-votes', notices: 'roadmap-notices', categories: 'roadmap-categories', ...o.slugs }, notices: { fields: o.notices?.fields ?? [] }, catalog: o.catalog diff --git a/src/sources.ts b/src/sources.ts new file mode 100644 index 0000000..a2777ff --- /dev/null +++ b/src/sources.ts @@ -0,0 +1,74 @@ +import type { CollectionSlug, Payload } from 'payload' + +import { optionsOf, RoadmapError } from './api' +import type { ItemSourceConfig, SourceItem } from './types' + +type Existing = { id: string; sourceGone?: boolean | null } + +/** Slug from the source key and id, so two sources can't collide on a board. */ +const slugFor = (key: string, externalId: string) => + `${key}-${externalId}` + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 120) + +const syncOne = async (payload: Payload, cfg: ItemSourceConfig) => { + const opts = optionsOf(payload) + const items = opts.slugs.items as CollectionSlug + const { key } = cfg.source + const stage = cfg.status ?? opts.stages[0]!.value + if (!opts.boards.some((b) => b.value === cfg.board)) throw new RoadmapError(`Item source ${key}: unknown board ${cfg.board}.`) + if (!opts.stages.some((s) => s.value === stage)) throw new RoadmapError(`Item source ${key}: unknown stage ${stage}.`) + const listed: SourceItem[] = await cfg.source.list({ payload }) + const known = new Map( + ( + (await payload.find({ collection: items, where: { sourceKey: { equals: key } }, pagination: false, depth: 0, overrideAccess: true })).docs as unknown as (Existing & { + externalId: string + })[] + ).map((d) => [d.externalId, d]), + ) + const result = { created: 0, updated: 0, gone: 0 } + const seen = new Set() + for (const s of listed) { + if (seen.has(s.externalId)) continue + seen.add(s.externalId) + const votes = Math.max(0, Math.floor(Number(s.votes) || 0)) + const have = known.get(s.externalId) + const shared = { title: s.title, summary: s.description ?? '', sourceVotes: votes, voteCount: votes, sourceGone: false } + if (have) { + // Only the source's fields: stage, curator notes, hidden and the rest stay as they are. + await payload.update({ collection: items, id: have.id, data: shared as never, overrideAccess: true, context: { roadmapInternal: true } }) + result.updated++ + } else { + await payload.create({ + collection: items, + data: { ...shared, board: cfg.board, stage, slug: slugFor(key, s.externalId), sourceKey: key, externalId: s.externalId } as never, + overrideAccess: true, + context: { roadmapInternal: true }, + }) + result.created++ + } + } + // Never deleted: a curator may have edited it. Marked, so the site can say the source dropped it. + for (const [externalId, have] of known) + if (!seen.has(externalId) && !have.sourceGone) { + await payload.update({ collection: items, id: have.id, data: { sourceGone: true } as never, overrideAccess: true, context: { roadmapInternal: true } }) + result.gone++ + } + return result +} + +/** Sync one configured item source (call it from the source's own afterChange hook). Server only. */ +export async function syncItemSource(payload: Payload, key: string) { + const cfg = optionsOf(payload).itemSources.find((c) => c.source.key === key) + if (!cfg) throw new RoadmapError(`No item source named ${key}.`) + return syncOne(payload, cfg) +} + +/** Sync every configured item source. Server only; runs with overrideAccess. */ +export async function syncItemSources(payload: Payload) { + const out: Record = {} + for (const cfg of optionsOf(payload).itemSources) out[cfg.source.key] = await syncOne(payload, cfg) + return out +} diff --git a/src/types.ts b/src/types.ts index c2b75e0..4be070b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -17,6 +17,26 @@ export type RoadmapNotice = { id: string; message: string; confirm: boolean } /** How catalog entries are labeled, from their stage and audience. */ export type CatalogStatus = 'available' | 'members' | 'in-progress' | 'planned' +/** One external item a plugin offers to Roadmap. Structural: no import from the plugin that supplies it. */ +export type SourceItem = { + /** Stable within the source, e.g. 'lang:zu'. */ + externalId: string + title: string + description?: string + /** The source's own count. Roadmap shows it and never edits it. */ + votes: number + tags?: string[] +} + +/** What a source gives Roadmap. */ +export type ItemSource = { + key: string + list: (args: { payload: unknown }) => Promise +} + +/** Connects a source to a board: its items become ordinary Roadmap items. */ +export type ItemSourceConfig = { source: ItemSource; board: string; /** Stage for new items. Default: the first stage. */ status?: string } + export type RoadmapPluginOptions = { slugs?: { items?: string; votes?: string; notices?: string; categories?: string } /** The auth collection whose accounts vote. Default 'users'. */ @@ -53,6 +73,20 @@ export type RoadmapPluginOptions = { /** Who may cast/remove their own vote through the REST/GraphQL API. Default: any signed-in user. */ vote?: Access } + /** + * External item sources (e.g. language requests from another plugin). Items sync into + * ordinary Roadmap items with `syncItemSources(payload)` or `syncItemSource(payload, key)`. + * They show the source's vote count and take no Roadmap votes. + */ + itemSources?: ItemSourceConfig[] + /** Vote settings per site. */ + votes?: { + /** + * Whether `allocation.lockDays` holds placed votes until they unlock. Default true. + * False lets voters withdraw placed votes at any time. + */ + lock?: boolean + } /** * Extra ("free agent") votes a user can place anywhere, several on one item * or spread across many, on top of their one free vote per item. The app @@ -110,6 +144,8 @@ export type RoadmapPluginOptions = { export type ResolvedRoadmapOptions = Required> & Pick & { + itemSources: ItemSourceConfig[] + votes: { lock: boolean } slugs: { items: string; votes: string; notices: string; categories: string } notices: { fields: RoadmapNoticeField[] } catalog?: { boards: string[]; availableStages: string[]; progressStages: string[]; hiddenStages: string[]; docs?: { name: string } } diff --git a/test/sources.test.ts b/test/sources.test.ts new file mode 100644 index 0000000..6bd2540 --- /dev/null +++ b/test/sources.test.ts @@ -0,0 +1,148 @@ +import { mongooseAdapter } from '@payloadcms/db-mongodb' +import { MongoMemoryReplSet } from 'mongodb-memory-server' +import { buildConfig, getPayload, type Payload } from 'payload' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +import { allocateVotes, castVote, syncItemSource, syncItemSources, withdrawVotes, roadmapPlugin, type SourceItem } from '../src/index.js' + +// Item sources and vote locking on real Payload over an in-memory MongoDB. Made-up data only. +type Doc = Record // eslint-disable-line @typescript-eslint/no-explicit-any + +let mongo: MongoMemoryReplSet +let a: Payload // locking on (default) +let b: Payload // votes.lock false +let listed: SourceItem[] = [] +const source = { key: 'made-up-source', list: async () => listed } +const PASSWORD = 'a-made-up-test-password' +let voterA: Doc, voterB: Doc, curatorA: Doc + +const build = async (db: string, lock?: boolean) => + getPayload({ + key: db, + config: await buildConfig({ + secret: 'test-secret-not-for-production', + telemetry: false, + typescript: { autoGenerate: false }, + db: mongooseAdapter({ url: mongo.getUri(db), ensureIndexes: true }), + collections: [{ slug: 'users', auth: true, fields: [{ name: 'role', type: 'text' }] }], + plugins: [ + roadmapPlugin({ + itemSources: [{ source, board: 'features' }], + allocation: { earned: async () => 5, lockDays: 30 }, + ...(lock === undefined ? {} : { votes: { lock } }), + access: { manage: ({ req }) => (req.user as Doc | null)?.role === 'curator' }, + }), + ], + }), + }) + +const items = async (p: Payload) => (await p.find({ collection: 'roadmap-items' as never, pagination: false, overrideAccess: true })).docs as Doc[] + +beforeAll(async () => { + mongo = await MongoMemoryReplSet.create({ replSet: { count: 1, storageEngine: 'wiredTiger' } }) + a = await build('sources-a') + b = await build('sources-b', false) + for (const p of [a, b]) { + const models = (p.db as unknown as { collections: Record Promise }> }).collections + for (const m of Object.values(models)) await m.ensureIndexes() + } + const user = (email: string, role = 'voter') => a.create({ collection: 'users', data: { email, password: PASSWORD, role } as never }) as Promise + voterA = await user('v1@example.com') + voterB = await user('v2@example.com') + curatorA = await user('curator@example.com', 'curator') +}, 180_000) + +afterAll(async () => { + await a?.destroy() + await b?.destroy() + await mongo?.stop() +}) + +const asUser = (u: Doc) => ({ ...u, collection: 'users' }) as never + +describe('item sources', () => { + it('creates ordinary items from the source', async () => { + listed = [ + { externalId: 'lang:aa', title: 'Made-up tongue', description: 'About it', votes: 3 }, + { externalId: 'lang:bb', title: 'Other tongue', votes: 0 }, + ] + expect(await syncItemSources(a)).toEqual({ 'made-up-source': { created: 2, updated: 0, gone: 0 } }) + const docs = await items(a) + expect(docs).toHaveLength(2) + expect(docs.find((d) => d.externalId === 'lang:aa')).toMatchObject({ title: 'Made-up tongue', summary: 'About it', voteCount: 3, sourceVotes: 3, board: 'features', stage: 'requested', sourceKey: 'made-up-source', sourceGone: false }) + }) + + it('re-sync updates counts and text without duplicates, and keeps curator fields', async () => { + const aa = (await items(a)).find((d) => d.externalId === 'lang:aa')! + await a.update({ collection: 'roadmap-items' as never, id: aa.id, data: { stage: 'planned', hidden: true } as never, overrideAccess: true }) + listed = [ + { externalId: 'lang:aa', title: 'Made-up tongue (renamed)', votes: 9 }, + { externalId: 'lang:bb', title: 'Other tongue', votes: 1 }, + ] + expect((await syncItemSource(a, 'made-up-source'))).toEqual({ created: 0, updated: 2, gone: 0 }) + const docs = await items(a) + expect(docs).toHaveLength(2) + expect(docs.find((d) => d.externalId === 'lang:aa')).toMatchObject({ title: 'Made-up tongue (renamed)', voteCount: 9, sourceVotes: 9, stage: 'planned', hidden: true }) + }) + + it('marks a removed item instead of deleting it, and clears the mark when it returns', async () => { + listed = [{ externalId: 'lang:aa', title: 'Made-up tongue', votes: 9 }] + expect(await syncItemSource(a, 'made-up-source')).toMatchObject({ gone: 1 }) + let docs = await items(a) + expect(docs).toHaveLength(2) + expect(docs.find((d) => d.externalId === 'lang:bb')).toMatchObject({ sourceGone: true, stage: 'requested' }) + listed = [{ externalId: 'lang:aa', title: 'Made-up tongue', votes: 9 }, { externalId: 'lang:bb', title: 'Other tongue', votes: 2 }] + await syncItemSource(a, 'made-up-source') + docs = await items(a) + expect(docs.find((d) => d.externalId === 'lang:bb')).toMatchObject({ sourceGone: false, voteCount: 2 }) + }) + + it('refuses unknown sources', async () => { + await expect(syncItemSource(a, 'nope')).rejects.toThrow(/No item source/) + }) + + it('refuses a Roadmap vote on a source item, through the API and the server helpers', async () => { + const id = String((await items(a)).find((d) => d.externalId === 'lang:aa')!.id) + await expect(castVote(a, { item: id, user: String(voterA.id) })).rejects.toThrow() + await expect( + a.create({ collection: 'roadmap-votes' as never, data: { item: id } as never, user: asUser(voterA), overrideAccess: false }), + ).rejects.toThrow() + await expect(allocateVotes(a, { item: id, user: String(voterA.id), votes: 1 })).rejects.toThrow() + expect((await items(a)).find((d) => String(d.id) === id)!.voteCount).toBe(9) + }) + + it('does not let signed-out or non-staff users write source fields', async () => { + const doc = (await items(a)).find((d) => d.externalId === 'lang:aa')! + const attempts = [undefined, asUser(voterA)] + for (const user of attempts) { + await expect( + a.create({ collection: 'roadmap-items' as never, data: { title: 'Sneaky', sourceKey: 'made-up-source', externalId: 'x' } as never, user, overrideAccess: false }), + ).rejects.toThrow() + await expect( + a.update({ collection: 'roadmap-items' as never, id: doc.id, data: { sourceVotes: 99, sourceGone: true, voteCount: 99 } as never, user, overrideAccess: false }), + ).rejects.toThrow() + } + // Even staff cannot set source fields through the API; only the sync can. + await a.update({ collection: 'roadmap-items' as never, id: doc.id, data: { sourceVotes: 99, sourceGone: true, externalId: 'zzz' } as never, user: asUser(curatorA), overrideAccess: false }) + expect((await items(a)).find((d) => d.id === doc.id)).toMatchObject({ sourceVotes: 9, sourceGone: false, externalId: doc.externalId }) + }) +}) + +describe('votes.lock', () => { + const place = async (p: Payload, user: Doc) => { + const item = (await p.create({ collection: 'roadmap-items' as never, data: { title: `Made-up ${p === a ? 'a' : 'b'}`, board: 'features' } as never, overrideAccess: true })) as Doc + await allocateVotes(p, { item: String(item.id), user: String(user.id), votes: 2 }) + return String(item.id) + } + + it('on by default: placed votes stay committed for lockDays', async () => { + const id = await place(a, voterA) + expect(await withdrawVotes(a, { item: id, user: String(voterA.id) })).toBe(0) + }) + + it('off: placed votes can be withdrawn at once', async () => { + const user = (await b.create({ collection: 'users', data: { email: 'v3@example.com', password: PASSWORD } as never })) as Doc + const id = await place(b, user) + expect(await withdrawVotes(b, { item: id, user: String(user.id) })).toBe(2) + }) +}) From 5794be209ec8234d50cf88c265673da608655e57 Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:49:22 -0700 Subject: [PATCH 2/2] Keep votes and merges off source items, namespace source keys, skip bad items Votes could be moved onto a source item by a merge or an edit, and a request slug could collide with a source key and stop the whole sync. Source items now refuse merges and moved votes, use a source:: key, and a failing item is skipped and reported. Adds server-side lock tests, option validation and a scope option. Not tested: a tenant plugin with scope; Postgres and SQLite. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++--- README.md | 6 ++-- docs/decisions.md | 2 +- src/api.ts | 7 ++++ src/collections.ts | 31 +++++++++++++---- src/index.ts | 9 ++++- src/sources.ts | 15 ++++++--- src/types.ts | 4 +-- test/sources.test.ts | 80 +++++++++++++++++++++++++++++++++++++++----- 9 files changed, 133 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 802593d..e65dba6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,10 @@ ## Unreleased -- New: `itemSources` option with `syncItemSources(payload)` and `syncItemSource(payload, key)`. External items become ordinary Roadmap items keyed by source key and id; sync updates title, summary and the source's vote count, marks vanished items `sourceGone` (never deletes), and leaves status and curator fields alone. Source items refuse Roadmap votes. `ItemSource` and `SourceItem` are structural types with no import from another plugin. -- New: `votes.lock` (default `true`). `false` lets voters withdraw placed votes at any time. -- Tested: 55 tests pass (8 new, in-memory MongoDB): create, re-sync without duplicates, removed item marked, curator stage and hidden survive, vote refusal through the API and server helpers, signed-out and non-staff writes refused, lock on and off. -- Not tested: tags are ignored; `scopeField` sites (source items get no scope); a source with thousands of items; running sync concurrently; Postgres and SQLite. +- New: `itemSources` option with `syncItemSources(payload)` and `syncItemSource(payload, key)`. External items become ordinary Roadmap items keyed by source key and id; sync updates title, summary and the source's vote count, marks vanished items `sourceGone` (never deletes), and leaves status and curator fields alone. Source items refuse Roadmap votes (a `RoadmapError` from `castVote` and `allocateVotes`), can't be merged into or out of, and can't have votes moved onto them. Their key is `source::`, which no request can claim; one item that fails to sync is skipped and listed in `errors` on the result, and the rest still sync. `ItemSourceConfig.scope` sets the `scopeField` value for new items. `ItemSource` and `SourceItem` are structural types with no import from another plugin. +- New: `votes.lock` (default `true`), one setting for the whole Payload config. `false` lets voters withdraw placed votes at any time. `votes.lock` must be a boolean and `allocation.lockDays` a number of 0 or more, or the plugin refuses to start. +- Tested: 59 tests pass (12 new, in-memory MongoDB): create, re-sync without duplicates, removed item marked, curator stage and hidden survive, vote refusal (by message) through the API, curators and server helpers, merge into and out of a source item refused, a vote moved onto one refused, a request that slugifies like a source id can't block the sync, a bad item skipped with an error while the rest sync, signed-out and non-staff writes refused, the lock refusal (403) on a voter's own API delete with the lock on, and that delete succeeding with it off. +- Not tested: tags are ignored; `scopeField` sites (the `scope` option sets the value, but no test runs a tenant plugin); invalid `lock` and `lockDays` values at startup; a source with thousands of items; running sync concurrently; Postgres and SQLite. ## 0.4.2 (2026-11-11) diff --git a/README.md b/README.md index 897eb81..356c4a8 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Add the plugin before plugins that wrap collections it creates (e.g. list `roadm | `access.manage` | nobody | Who edits items and sees every vote | | `access.vote` | any signed-in user | Who may vote through the API. Only accounts of `usersSlug` can vote, always as themselves with weight 1; a vote that names another voter, a weight or a ballot is refused (403). Accounts from other auth collections never vote, see or delete votes unless `manage` lets them | | `allocation` | off | `{ earned: ({ payload, user, scope }) => Promise, lockDays?, boards?, releaseStages? }`: extra votes | -| `itemSources` | none | `[{ source, board, status? }]`: items synced from another plugin (below) | +| `itemSources` | none | `[{ source, board, status?, scope? }]`: items synced from another plugin (below). `scope` is the `scopeField` value for new items | | `votes.lock` | `true` | `false` lets voters withdraw placed votes at any time, ignoring `allocation.lockDays` | | `notices` | off | `{ fields: [{ name, label, options, boards? }] }`: conditional notices (below) | | `catalog` | off | `{ boards?, availableStages?, progressStages?, hiddenStages? }`: features catalog (below) | @@ -101,12 +101,12 @@ title, the summary and the source's vote count. Status, curator notes and hiding set them. An item the source stops listing is marked `sourceGone`, never deleted. Source items show the source's count and refuse Roadmap votes, so nothing is counted twice. The source fields can't be written through the API, by anyone; the sync functions write with `overrideAccess`, so -call them from server code only. Tags are not stored yet. +call them from server code only. A sync returns `errors` for items it skipped. Source items can't be merged into or out of. Tags are not stored yet. ### Vote locking `allocation.lockDays` holds placed votes until they unlock. `votes: { lock: false }` turns that off -for a site: placed votes can be withdrawn at any time. The default is `true`, as before. The one free +for the whole Payload config (one setting, not one per site): placed votes can be withdrawn at any time. The default is `true`, as before. The one free vote per item was never locked. ### Conditional notices diff --git a/docs/decisions.md b/docs/decisions.md index d73376b..913df9f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -6,4 +6,4 @@ The owner, 2026-11-16: "languages should appear with everything else and yes, vo - Roadmap takes external items through an `itemSources` option and sync functions. They become ordinary items, so they appear with everything else on a board. Neither plugin imports the other; the source shape is a structural type here. - Sync never deletes: an item a source stops listing is marked `sourceGone`, because a curator may have edited it. Roadmap's own fields are left alone, and source items take no Roadmap votes so nothing is counted twice. -- Vote locking is `votes.lock`, default `true` (today's behavior). `false` ignores `allocation.lockDays` for that site. +- Vote locking is `votes.lock`, default `true` (today's behavior). `false` ignores `allocation.lockDays` for the whole config (one setting per Payload config, not per site). Source items can't be merged into or out of, and take no moved votes. Their key is namespaced so requests can't collide with it. diff --git a/src/api.ts b/src/api.ts index faafde7..0fc28ff 100644 --- a/src/api.ts +++ b/src/api.ts @@ -14,6 +14,7 @@ export type RoadmapItemDoc = { board: string stage: string key: string + sourceKey?: string | null voteCount?: number | null parent?: string | { id: string } | null [field: string]: unknown @@ -51,6 +52,8 @@ const isDuplicate = (error: unknown) => { /** A user's free vote on an item has this ballot; placed (allocated) votes get a unique one each. */ export const FREE_BALLOT = 'free' +export const SOURCE_ITEM_MESSAGE = 'Vote for this on the page it came from. It does not take votes here.' + /** Refusals meant for the voter (not enough votes, still locked…). */ export class RoadmapError extends Error {} @@ -95,6 +98,7 @@ const findVote = async (payload: Payload, item: string, user: string) => /** The free vote: one per user per item; returns the existing vote if there is one. */ export async function castVote(payload: Payload, args: { item: string; user: string; note?: string }) { + if ((await getItem(payload, args.item))?.sourceKey) throw new RoadmapError(SOURCE_ITEM_MESSAGE) const existing = await findVote(payload, args.item, args.user) if (existing) return { vote: existing, created: false } try { @@ -184,6 +188,7 @@ export async function allocateVotes(payload: Payload, args: { item: string; user if (!(votes >= 1)) throw new RoadmapError('Choose at least one vote.') const item = await getItem(payload, args.item) if (!item || item.hidden) throw new RoadmapError('That roadmap item is not open for votes.') + if (item.sourceKey) throw new RoadmapError(SOURCE_ITEM_MESSAGE) if (opts.allocation.boards && !opts.allocation.boards.includes(item.board)) throw new RoadmapError('Extra votes can’t be placed on this roadmap.') if (releases(opts, item.stage)) throw new RoadmapError('This item is not planned, so it can’t take extra votes.') for (let attempt = 1; ; attempt++) { @@ -301,6 +306,8 @@ export async function mergeItems(payload: Payload, args: { from: string; into: s const opts = optionsOf(payload) const { req } = args if (args.from === args.into) throw new RoadmapError('An item can’t be merged into itself.') + for (const id of [args.from, args.into]) + if ((await getItem(payload, id))?.sourceKey) throw new RoadmapError('Items from a source can’t be merged into or out of.') const find = async (where: Where) => ( await payload.find({ diff --git a/src/collections.ts b/src/collections.ts index 8127768..e4cbfc8 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -1,6 +1,6 @@ import { APIError, type Access, type CollectionConfig, type CollectionSlug, type Field, type Where } from 'payload' -import { FREE_BALLOT, idOf, itemKey, mergeItems, recountVotes, releases, slugify, unlocksAt } from './api' +import { FREE_BALLOT, SOURCE_ITEM_MESSAGE, idOf, itemKey, mergeItems, recountVotes, releases, slugify, unlocksAt } from './api' import { catalogItemFields } from './catalog' import type { ResolvedRoadmapOptions } from './types' @@ -93,7 +93,7 @@ export const itemsCollection = (opts: ResolvedRoadmapOptions): CollectionConfig description: 'Combine this item into a similar one: its votes move there and this item is hidden. Cannot be undone.', }, filterOptions: ({ id, data }): Where => ({ - and: [{ id: { not_equals: id } }, { board: { equals: data?.board } }, { mergedInto: { exists: false } }] as Where[], + and: [{ id: { not_equals: id } }, { board: { equals: data?.board } }, { mergedInto: { exists: false } }, { sourceKey: { exists: false } }] as Where[], }), }, { @@ -137,6 +137,8 @@ export const itemsCollection = (opts: ResolvedRoadmapOptions): CollectionConfig req, })) as Record | null const doc = { ...originalDoc, ...data } + if (into?.sourceKey || originalDoc?.sourceKey) + throw new APIError('Items from a source can’t be merged into or out of. Hide the item instead.', 400) if ( !into || into.id === originalDoc?.id || @@ -150,7 +152,10 @@ export const itemsCollection = (opts: ResolvedRoadmapOptions): CollectionConfig if (!slug) throw new APIError('A title is required.', 400) const subject = 'subject' in data ? data.subject : originalDoc?.subject const subjectChanged = operation === 'create' || idOf(subject) !== idOf(originalDoc?.subject) - const next: Record = { ...data, slug, key: itemKey(subject, slug) } + const origin = { ...originalDoc, ...data } as { sourceKey?: string; externalId?: string } + // Source items get a key no request can produce (requests are `slug:` or `subject:`). + const key = origin.sourceKey ? `source:${origin.sourceKey}:${origin.externalId}` : itemKey(subject, slug) + const next: Record = { ...data, slug, key } if (opts.subject?.parentOf && subjectChanged) { const parentSubject = idOf(subject) ? await opts.subject.parentOf({ id: idOf(subject), req }) : null next.parentSubject = parentSubject ?? null @@ -257,8 +262,22 @@ export const votesCollection = (opts: ResolvedRoadmapOptions): CollectionConfig ], hooks: { beforeChange: [ - async ({ data, operation, req }) => { - if (operation !== 'create') return data + async ({ data, originalDoc, operation, req }) => { + if (operation !== 'create') { + // Moving a vote onto a source item would spend it where it doesn't count. + if (data?.item && idOf(data.item) !== idOf(originalDoc?.item)) { + const target = await req.payload.findByID({ + collection: opts.slugs.items as CollectionSlug, + id: idOf(data.item), + depth: 0, + overrideAccess: true, + disableErrors: true, + req, + }) + if ((target as { sourceKey?: string } | null)?.sourceKey) throw new APIError('Votes can’t be moved onto an item from a source.', 400) + } + return data + } // API voters cast their own free vote; extra votes go through allocateVotes. // Curators and the server's own Local API calls (no user) may set any voter. // Everyone else must be a signed-in account of usersSlug, voting as itself, @@ -287,7 +306,7 @@ export const votesCollection = (opts: ResolvedRoadmapOptions): CollectionConfig req, }) if (!item || (item as { hidden?: boolean }).hidden) throw new APIError('That roadmap item is not open for votes.', 400) - if ((item as { sourceKey?: string }).sourceKey) throw new APIError('Vote for this on the page it came from. It does not take votes here.', 400) + if ((item as { sourceKey?: string }).sourceKey) throw new APIError(SOURCE_ITEM_MESSAGE, 400) if (opts.scopeField) data[opts.scopeField] = idOf((item as unknown as Record)[opts.scopeField]) || undefined return data }, diff --git a/src/index.ts b/src/index.ts index 646895a..9661483 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,7 +44,14 @@ export const DEFAULT_STAGES = [ { label: 'Not planned', value: 'declined' }, ] -const resolve = (o: RoadmapPluginOptions): ResolvedRoadmapOptions => ({ +const resolve = (o: RoadmapPluginOptions): ResolvedRoadmapOptions => { + if (o.votes?.lock !== undefined && typeof o.votes.lock !== 'boolean') throw new Error('roadmapPlugin: votes.lock must be true or false.') + const days = o.allocation?.lockDays + if (days !== undefined && !(Number.isFinite(days) && days >= 0)) throw new Error('roadmapPlugin: allocation.lockDays must be a number of 0 or more.') + return build(o) +} + +const build = (o: RoadmapPluginOptions): ResolvedRoadmapOptions => ({ usersSlug: o.usersSlug ?? 'users', boards: o.boards?.length ? o.boards : [{ label: 'Features', value: 'features' }], stages: o.stages?.length ? o.stages : DEFAULT_STAGES, diff --git a/src/sources.ts b/src/sources.ts index a2777ff..49a849b 100644 --- a/src/sources.ts +++ b/src/sources.ts @@ -3,9 +3,11 @@ import type { CollectionSlug, Payload } from 'payload' import { optionsOf, RoadmapError } from './api' import type { ItemSourceConfig, SourceItem } from './types' +export type SyncResult = { created: number; updated: number; gone: number; errors: { externalId: string; message: string }[] } + type Existing = { id: string; sourceGone?: boolean | null } -/** Slug from the source key and id, so two sources can't collide on a board. */ +/** Display slug only. The unique key is `source::`, set by the items hook, so slugs may repeat. */ const slugFor = (key: string, externalId: string) => `${key}-${externalId}` .toLowerCase() @@ -28,11 +30,12 @@ const syncOne = async (payload: Payload, cfg: ItemSourceConfig) => { })[] ).map((d) => [d.externalId, d]), ) - const result = { created: 0, updated: 0, gone: 0 } + const result: SyncResult = { created: 0, updated: 0, gone: 0, errors: [] } const seen = new Set() for (const s of listed) { if (seen.has(s.externalId)) continue seen.add(s.externalId) + try { const votes = Math.max(0, Math.floor(Number(s.votes) || 0)) const have = known.get(s.externalId) const shared = { title: s.title, summary: s.description ?? '', sourceVotes: votes, voteCount: votes, sourceGone: false } @@ -43,12 +46,16 @@ const syncOne = async (payload: Payload, cfg: ItemSourceConfig) => { } else { await payload.create({ collection: items, - data: { ...shared, board: cfg.board, stage, slug: slugFor(key, s.externalId), sourceKey: key, externalId: s.externalId } as never, + data: { ...shared, board: cfg.board, stage, slug: slugFor(key, s.externalId), sourceKey: key, externalId: s.externalId, ...(opts.scopeField && cfg.scope ? { [opts.scopeField]: cfg.scope } : {}) } as never, overrideAccess: true, context: { roadmapInternal: true }, }) result.created++ } + } catch (error) { + // One bad item never stops the rest. + result.errors.push({ externalId: String(s.externalId), message: error instanceof Error ? error.message : 'Could not sync this item.' }) + } } // Never deleted: a curator may have edited it. Marked, so the site can say the source dropped it. for (const [externalId, have] of known) @@ -68,7 +75,7 @@ export async function syncItemSource(payload: Payload, key: string) { /** Sync every configured item source. Server only; runs with overrideAccess. */ export async function syncItemSources(payload: Payload) { - const out: Record = {} + const out: Record = {} for (const cfg of optionsOf(payload).itemSources) out[cfg.source.key] = await syncOne(payload, cfg) return out } diff --git a/src/types.ts b/src/types.ts index 4be070b..22dbc63 100644 --- a/src/types.ts +++ b/src/types.ts @@ -35,7 +35,7 @@ export type ItemSource = { } /** Connects a source to a board: its items become ordinary Roadmap items. */ -export type ItemSourceConfig = { source: ItemSource; board: string; /** Stage for new items. Default: the first stage. */ status?: string } +export type ItemSourceConfig = { source: ItemSource; board: string; /** Stage for new items. Default: the first stage. */ status?: string; /** The scopeField value for new items, when the plugin has a scopeField. */ scope?: string } export type RoadmapPluginOptions = { slugs?: { items?: string; votes?: string; notices?: string; categories?: string } @@ -79,7 +79,7 @@ export type RoadmapPluginOptions = { * They show the source's vote count and take no Roadmap votes. */ itemSources?: ItemSourceConfig[] - /** Vote settings per site. */ + /** Vote settings for the whole Payload config. */ votes?: { /** * Whether `allocation.lockDays` holds placed votes until they unlock. Default true. diff --git a/test/sources.test.ts b/test/sources.test.ts index 6bd2540..6c44f01 100644 --- a/test/sources.test.ts +++ b/test/sources.test.ts @@ -3,7 +3,7 @@ import { MongoMemoryReplSet } from 'mongodb-memory-server' import { buildConfig, getPayload, type Payload } from 'payload' import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { allocateVotes, castVote, syncItemSource, syncItemSources, withdrawVotes, roadmapPlugin, type SourceItem } from '../src/index.js' +import { allocateVotes, castVote, mergeItems, requestItem, syncItemSource, syncItemSources, withdrawVotes, roadmapPlugin, type SourceItem } from '../src/index.js' // Item sources and vote locking on real Payload over an in-memory MongoDB. Made-up data only. type Doc = Record // eslint-disable-line @typescript-eslint/no-explicit-any @@ -66,7 +66,7 @@ describe('item sources', () => { { externalId: 'lang:aa', title: 'Made-up tongue', description: 'About it', votes: 3 }, { externalId: 'lang:bb', title: 'Other tongue', votes: 0 }, ] - expect(await syncItemSources(a)).toEqual({ 'made-up-source': { created: 2, updated: 0, gone: 0 } }) + expect(await syncItemSources(a)).toEqual({ 'made-up-source': { created: 2, updated: 0, gone: 0, errors: [] } }) const docs = await items(a) expect(docs).toHaveLength(2) expect(docs.find((d) => d.externalId === 'lang:aa')).toMatchObject({ title: 'Made-up tongue', summary: 'About it', voteCount: 3, sourceVotes: 3, board: 'features', stage: 'requested', sourceKey: 'made-up-source', sourceGone: false }) @@ -79,7 +79,7 @@ describe('item sources', () => { { externalId: 'lang:aa', title: 'Made-up tongue (renamed)', votes: 9 }, { externalId: 'lang:bb', title: 'Other tongue', votes: 1 }, ] - expect((await syncItemSource(a, 'made-up-source'))).toEqual({ created: 0, updated: 2, gone: 0 }) + expect((await syncItemSource(a, 'made-up-source'))).toEqual({ created: 0, updated: 2, gone: 0, errors: [] }) const docs = await items(a) expect(docs).toHaveLength(2) expect(docs.find((d) => d.externalId === 'lang:aa')).toMatchObject({ title: 'Made-up tongue (renamed)', voteCount: 9, sourceVotes: 9, stage: 'planned', hidden: true }) @@ -102,13 +102,19 @@ describe('item sources', () => { }) it('refuses a Roadmap vote on a source item, through the API and the server helpers', async () => { - const id = String((await items(a)).find((d) => d.externalId === 'lang:aa')!.id) - await expect(castVote(a, { item: id, user: String(voterA.id) })).rejects.toThrow() + const doc = (await items(a)).find((d) => d.externalId === 'lang:aa')! + const id = String(doc.id) + await a.update({ collection: 'roadmap-items' as never, id, data: { hidden: false } as never, overrideAccess: true }) + await expect(castVote(a, { item: id, user: String(voterA.id) })).rejects.toThrow(/page it came from/) await expect( a.create({ collection: 'roadmap-votes' as never, data: { item: id } as never, user: asUser(voterA), overrideAccess: false }), - ).rejects.toThrow() - await expect(allocateVotes(a, { item: id, user: String(voterA.id), votes: 1 })).rejects.toThrow() + ).rejects.toThrow(/page it came from/) + await expect( + a.create({ collection: 'roadmap-votes' as never, data: { item: id, user: curatorA.id } as never, user: asUser(curatorA), overrideAccess: false }), + ).rejects.toThrow(/page it came from/) + await expect(allocateVotes(a, { item: id, user: String(voterA.id), votes: 1 })).rejects.toThrow(/page it came from/) expect((await items(a)).find((d) => String(d.id) === id)!.voteCount).toBe(9) + await a.update({ collection: 'roadmap-items' as never, id, data: { hidden: true } as never, overrideAccess: true }) }) it('does not let signed-out or non-staff users write source fields', async () => { @@ -126,15 +132,73 @@ describe('item sources', () => { await a.update({ collection: 'roadmap-items' as never, id: doc.id, data: { sourceVotes: 99, sourceGone: true, externalId: 'zzz' } as never, user: asUser(curatorA), overrideAccess: false }) expect((await items(a)).find((d) => d.id === doc.id)).toMatchObject({ sourceVotes: 9, sourceGone: false, externalId: doc.externalId }) }) + + it('refuses merging into or out of a source item, and moving a vote onto one', async () => { + const src = (await items(a)).find((d) => d.externalId === 'lang:aa')! + const plain = (await a.create({ collection: 'roadmap-items' as never, data: { title: 'Made-up plain', board: 'features' } as never, overrideAccess: true })) as Doc + const vote = (await a.create({ collection: 'roadmap-votes' as never, data: { item: plain.id, user: voterB.id } as never, overrideAccess: true })) as Doc + const asCurator = { user: asUser(curatorA), overrideAccess: false } + await expect(a.update({ collection: 'roadmap-items' as never, id: plain.id, data: { mergedInto: src.id } as never, ...asCurator })).rejects.toThrow(/can’t be merged into or out of/) + await expect(a.update({ collection: 'roadmap-items' as never, id: src.id, data: { mergedInto: plain.id } as never, ...asCurator })).rejects.toThrow(/can’t be merged into or out of/) + await expect(mergeItems(a, { from: plain.id, into: src.id })).rejects.toThrow(/merged into or out of/) + await expect(mergeItems(a, { from: src.id, into: plain.id })).rejects.toThrow(/merged into or out of/) + await expect(a.update({ collection: 'roadmap-votes' as never, id: vote.id, data: { item: src.id } as never, ...asCurator })).rejects.toThrow(/can’t be moved onto/) + const after = await items(a) + expect(after.find((d) => d.id === src.id)).toMatchObject({ voteCount: 9, hidden: true }) + expect(after.find((d) => d.id === plain.id)).toMatchObject({ voteCount: 1 }) + expect(after.find((d) => d.id === plain.id)!.mergedInto).toBeFalsy() + }) + + it('gives source items a key no request can claim, and one bad item never stops the sync', async () => { + // A request whose title slugifies to the old source slug. + await requestItem(a, { board: 'features', title: 'made-up-source lang aa', user: String(voterB.id) } as never) + listed = [ + { externalId: 'lang:zu', title: 'Zu tongue', votes: 1 }, + { externalId: 'lang-zu', title: 'Zu again', votes: 2 }, + { externalId: 'lang:empty', title: '', votes: 1 }, + { externalId: 'lang:last', title: 'Last tongue', votes: 4 }, + ] + const res = await syncItemSource(a, 'made-up-source') + expect(res.created).toBe(3) + expect(res.errors).toHaveLength(1) + expect(res.errors[0]).toMatchObject({ externalId: 'lang:empty' }) + const docs = await items(a) + expect(docs.find((d) => d.externalId === 'lang:last')).toMatchObject({ voteCount: 4, key: 'source:made-up-source:lang:last' }) + expect(docs.filter((d) => ['lang:zu', 'lang-zu'].includes(d.externalId))).toHaveLength(2) + // The items left out of this list are marked gone, so gone-marking still ran. + expect(docs.find((d) => d.externalId === 'lang:aa')).toMatchObject({ sourceGone: true }) + }) }) describe('votes.lock', () => { const place = async (p: Payload, user: Doc) => { - const item = (await p.create({ collection: 'roadmap-items' as never, data: { title: `Made-up ${p === a ? 'a' : 'b'}`, board: 'features' } as never, overrideAccess: true })) as Doc + const item = (await p.create({ collection: 'roadmap-items' as never, data: { title: `Made-up ${p === a ? 'a' : 'b'} ${Math.random().toString(36).slice(2, 8)}`, board: 'features' } as never, overrideAccess: true })) as Doc await allocateVotes(p, { item: String(item.id), user: String(user.id), votes: 2 }) return String(item.id) } + const placed = async (p: Payload, user: Doc) => { + const id = await place(p, user) + const v = (await p.find({ collection: 'roadmap-votes' as never, where: { item: { equals: id } }, overrideAccess: true })).docs[0] as Doc + return String(v.id) + } + + it('on: a voter cannot delete a locked placed vote through the API (403)', async () => { + const vote = await placed(a, voterB) + await expect(a.delete({ collection: 'roadmap-votes' as never, id: vote, user: asUser(voterB), overrideAccess: false })).rejects.toMatchObject({ + status: 403, + message: 'These votes are still committed.', + }) + expect((await a.find({ collection: 'roadmap-votes' as never, where: { id: { equals: vote } }, overrideAccess: true })).totalDocs).toBe(1) + }) + + it('off: the same API delete succeeds', async () => { + const user = (await b.create({ collection: 'users', data: { email: 'v4@example.com', password: PASSWORD } as never })) as Doc + const vote = await placed(b, user) + await b.delete({ collection: 'roadmap-votes' as never, id: vote, user: { ...user, collection: 'users' } as never, overrideAccess: false }) + expect((await b.find({ collection: 'roadmap-votes' as never, where: { id: { equals: vote } }, overrideAccess: true })).totalDocs).toBe(0) + }) + it('on by default: placed votes stay committed for lockDays', async () => { const id = await place(a, voterA) expect(await withdrawVotes(a, { item: id, user: String(voterA.id) })).toBe(0)