Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | 3x 3x 1x 1x 1x 1x 5x 5x 3x 3x 1x 1x 133x 4x 4x 1x 1x 1x 2x 2x 2x 121x 121x 121x 121x 67x 51x 103x 42x 42x 42x 42x 46x 46x 113x 113x 117x 117x 117x 14x 31x 31x 31x 21x 21x 54x 54x 54x 54x 7x 7x 7x 54x 54x 54x 49x 100x 48x 7x 7x 5x 16x 16x 16x 16x 13x 13x 13x 13x 38x 13x 32x 15x 11x 2x 2x 2x 2x 2x 2x 16x 16x 16x 16x 16x 16x 3x 3x 1x 36x 13x 13x 13x 13x 13x 13x 13x 12x 36x 12x 12x 36x 12x 24x 12x 5x 5x 6x 12x 12x 12x 12x 12x 11x 20x 20x 20x 20x 20x 20x 20x 18x 18x 18x 18x 5x 17x 12x 12x 11x 9x 9x 9x 9x 9x 9x 9x 7x 7x 2x 7x 8x 8x 8x 9x 8x 7x 7x 6x 4x 4x 4x 4x 4x 3x 3x 3x 2x 5x 5x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x | import { randomBytes } from "crypto";
import type { SortResult, SortResultItem, SortResultShare } from "@/types";
import type { Database } from "@/lib/db";
import { lockCollectionCurator, lockSaveKey, withTransaction } from "@/lib/transactions";
import {
SortResultRepository,
isResultNumberConflict,
} from "@/server/repositories/implementations/SortResultRepository";
import { SortResultItemRepository } from "@/server/repositories/implementations/SortResultItemRepository";
import { SortResultShareRepository } from "@/server/repositories/implementations/SortResultShareRepository";
import { ItemRepository } from "@/server/repositories/implementations/ItemRepository";
import { allocateWithRetry } from "@/server/repositories/allocateWithRetry";
import { CollectionPreferenceItemRepository } from "@/server/repositories/implementations/CollectionPreferenceItemRepository";
import { SessionRepository } from "@/server/repositories/implementations/SessionRepository";
import { DecisionEventRepository } from "@/server/repositories/implementations/DecisionEventRepository";
import { loadCuratorDecisionEvents } from "@/server/services/decision-log";
import { lockCollectionCurators } from "@/server/services/purge-lock";
import { deriveUsage, type UsageAnswer } from "@/lib/derive-usage";
import {
rankPreferencesToItems,
cloneItemsFrom,
buildRanking,
pinsFromRows,
placePin,
savedOrderPositions,
pinsLostToRevision,
type MaterializedItem,
type Pin,
} from "./sortResultMaterialization";
/** Thrown when supersede targets a result that is not finalized; the route maps it to 409. */
export class SupersedeStateError extends Error {
constructor() {
super("Can only supersede finalized results");
this.name = "SupersedeStateError";
}
}
/** A revision would set the open draft's hand placements aside; the person confirms first → 409. */
export class RevisionDiscardsPinsError extends Error {
readonly code = "revision_discards_pins";
constructor(readonly pinCount: number) {
super("Your hand-placed pieces would move. Start the revision anyway?");
this.name = "RevisionDiscardsPinsError";
}
}
/** Thrown when delete targets a result that is not a draft; the route maps it to 409. */
export class DeleteResultStateError extends Error {
constructor() {
super("Can only delete draft results");
this.name = "DeleteResultStateError";
}
}
/** Thrown when finalize targets a result that is already finalized; the route maps it to 409. */
export class FinalizeStateError extends Error {
constructor() {
super("Can only finalize draft results");
this.name = "FinalizeStateError";
}
}
/**
* Thrown when the (collection, number) race could not be won within the retry
* budget. Distinct from a mid-transaction failure so ops can tell "retry storm
* lost" apart from "DB fell over". The route maps it to 500.
*/
export class ResultNumberExhaustedError extends Error {
constructor() {
super("Could not allocate a result number");
this.name = "ResultNumberExhaustedError";
}
}
/** The open draft's name until Save and share names it. */
const OPEN_DRAFT_NAME = "Still deciding";
/** Pin target is not a Love/Like/Maybe piece of this curator in this collection → 404. */
export class PinTargetError extends Error {
constructor() {
super("That piece can't be placed here.");
this.name = "PinTargetError";
}
}
/** Nothing is ranked yet → 409 (the button is hidden then; this is the direct-API net). */
export class NothingToSaveError extends Error {
readonly code = "nothing_to_save";
constructor() {
super("There's nothing to save yet — sort a few first.");
this.name = "NothingToSaveError";
}
}
/** A save key reused for another collection, or whose link was revoked → 409. */
export class SaveKeyConflictError extends Error {
readonly code = "save_key_conflict";
constructor() {
super("That save can't be repeated here.");
this.name = "SaveKeyConflictError";
}
}
export interface SavedRanking {
result: SortResult;
shareToken: string;
created: boolean;
}
export class SortResultService {
constructor(
private sortResultRepo: SortResultRepository,
private sortResultItemRepo: SortResultItemRepository,
private preferenceRepo: CollectionPreferenceItemRepository,
private db: Database,
) {}
static fromDb(db: Database): SortResultService {
return new SortResultService(
new SortResultRepository(db),
new SortResultItemRepository(db),
new CollectionPreferenceItemRepository(db),
db,
);
}
/**
* Epic S: derive the curator's usage standing for the items being materialized,
* from their CURRENT cross-session decision log (the SAME log the Standing
* surface reads — loadCuratorDecisionEvents). Called by every materialization
* path (fresh draft + revision), so a revision re-derives usage at its own
* moment (fresh-fold) rather than carrying the original snapshot forward. A
* usage-unknown item is simply absent from the map → stamped NULL.
*/
private async deriveCuratorUsage(
collectionId: string,
curatorId: string,
items: MaterializedItem[],
): Promise<Map<string, UsageAnswer>> {
const events = await loadCuratorDecisionEvents(
new SessionRepository(this.db),
new DecisionEventRepository(this.db),
collectionId,
curatorId,
);
return deriveUsage(events, new Set(items.map((i) => i.itemId)));
}
async createDraftResult(collectionId: string, curatorId: string, name: string): Promise<SortResult> {
const preferences = await this.preferenceRepo.findByCollection(collectionId, curatorId);
const items = rankPreferencesToItems(preferences);
const usageByItemId = await this.deriveCuratorUsage(collectionId, curatorId, items);
// One open draft per (collection, curator) (sort_results_open_draft_unique): the
// prior draft is reaped INSIDE the same locked transaction, before the insert,
// so the index never sees two and a failure leaves the old draft in place.
return this.inCuratorTx(collectionId, curatorId, "materialize_result", async (tx) => {
await this.deleteDrafts(tx, collectionId, curatorId);
return this.insertResultWithItems(tx, collectionId, curatorId, name, items, usageByItemId);
});
}
/**
* The ranking writers run here — pin, unpin, save, revision, finalize, delete and
* the legacy create: one transaction holding the (collection, curator) advisory
* lock, so they serialize and the open-draft index is a backstop, never a 500.
* (The owner's purge-prep crosses curators and takes all of them:
* lockCollectionCurators.) The (collection, number) race — another curator saving in the same
* collection — aborts the transaction, so it is retried at this boundary.
*/
private async inCuratorTx<T>(
collectionId: string,
curatorId: string,
op: string,
fn: (tx: Database) => Promise<T>,
): Promise<T> {
try {
return await allocateWithRetry(
() =>
withTransaction(
this.db,
async (tx) => {
await lockCollectionCurator(tx, collectionId, curatorId);
return fn(tx);
},
{ op, ctx: { collectionId, curatorId } },
),
isResultNumberConflict,
);
} catch (error) {
throw isResultNumberConflict(error) ? new ResultNumberExhaustedError() : error;
}
}
/** Lazily open the one draft (spec §4.3) — an empty row; pins add their own rows. */
private async getOrCreateOpenDraft(tx: Database, collectionId: string, curatorId: string): Promise<SortResult> {
const repo = new SortResultRepository(tx);
const open = await repo.findDraftForUpdate(collectionId, curatorId);
if (open) return open;
const number = await repo.getNextResultNumber(collectionId);
return repo.insertWithNumber({ collectionId, curatorId, name: OPEN_DRAFT_NAME, status: "draft", number });
}
/** Children first: neither the shares nor the items FK has ON DELETE CASCADE. */
private async deleteDrafts(tx: Database, collectionId: string, curatorId: string): Promise<void> {
const resultRepo = new SortResultRepository(tx);
const itemRepo = new SortResultItemRepository(tx);
const shareRepo = new SortResultShareRepository(tx);
for (const draft of await resultRepo.findDrafts(collectionId, curatorId)) {
await shareRepo.deleteByResult(draft.id);
await itemRepo.deleteByResult(draft.id);
await resultRepo.delete(draft.id);
}
}
// Invariant: tx-bound repos only — a write on this.sortResultRepo would not roll back.
// One multi-row insert under the curator lock (purses-w7ss.23); `slots` pins rows at insert
// (a revision's saved loved order — distinct slots, see savedOrderPositions).
// ponytail: one createMany binds ~10 params per row, so it breaks past ~6,500 rows (Postgres'
// 65,535-param limit) — saveAndShare has the same ceiling; collections are hundreds of pieces.
// Chunk the insert if a collection ever nears it.
private async insertResultWithItems(
tx: Database,
collectionId: string,
curatorId: string,
name: string,
items: MaterializedItem[],
usageByItemId: ReadonlyMap<string, UsageAnswer>,
slots: ReadonlyMap<string, number> = new Map(),
): Promise<SortResult> {
const resultRepo = new SortResultRepository(tx);
const number = await resultRepo.getNextResultNumber(collectionId);
const result = await resultRepo.insertWithNumber({ collectionId, curatorId, name, status: "draft", number });
await new SortResultItemRepository(tx).createMany(
items.map((item) => ({
sortResultId: result.id,
...item,
manualRank: slots.get(item.itemId) ?? null,
usage: usageByItemId.get(item.itemId) ?? null,
})),
);
return result;
}
/** The open draft's pins (read-only — viewing the ranking creates nothing). */
async listPins(collectionId: string, curatorId: string): Promise<Pin[]> {
const draft = await this.sortResultRepo.findDraft(collectionId, curatorId);
if (!draft) return [];
return pinsFromRows(await this.sortResultItemRepo.findByResult(draft.id));
}
/**
* Hand-place one piece (spec §4 "Adjusting"); the first pin opens the draft. The
* pinned pieces the move passes over shift with it (placePin), so the saved order
* is the splice the person saw, even when every piece is pinned.
*/
async pinItem(collectionId: string, curatorId: string, itemId: string, position: number): Promise<void> {
await this.inCuratorTx(collectionId, curatorId, "pin_ranking_item", async (tx) => {
const prefRepo = new CollectionPreferenceItemRepository(tx);
const pref = await prefRepo.findByItem(itemId, curatorId);
if (!pref || pref.collectionId !== collectionId || pref.rankBucket === "low") throw new PinTargetError();
const draft = await this.getOrCreateOpenDraft(tx, collectionId, curatorId);
const itemRepo = new SortResultItemRepository(tx);
const rows = await itemRepo.findByResult(draft.id);
const pins = pinsFromRows(rows);
const liveIds = new Set((await new ItemRepository(tx).findByCollection(collectionId)).map((i) => i.id));
const { loved } = buildRanking(await prefRepo.findByCollection(collectionId, curatorId), liveIds, pins);
for (const [movedId, slot] of placePin(loved.map((e) => e.itemId), pins, itemId, position)) {
const row =
rows.find((r) => r.itemId === movedId) ??
(await itemRepo.create({ sortResultId: draft.id, itemId: movedId, computedRank: slot - 1, computedBucket: pref.rankBucket }));
// manualRank is 0-based (existing convention); a slot is 1-based.
await itemRepo.update(row.id, { manualRank: slot - 1, manualBucket: null });
}
});
}
/** Unpin: the piece returns to its derived place. Idempotent; opens nothing. */
async unpinItem(collectionId: string, curatorId: string, itemId: string): Promise<void> {
await this.inCuratorTx(collectionId, curatorId, "unpin_ranking_item", async (tx) => {
const draft = await new SortResultRepository(tx).findDraftForUpdate(collectionId, curatorId);
Iif (!draft) return;
const itemRepo = new SortResultItemRepository(tx);
const row = await itemRepo.findByResultAndItem(draft.id, itemId);
if (row && row.manualRank !== null) await itemRepo.update(row.id, { manualRank: null, manualBucket: null });
});
}
/**
* Spec §4.4: ONE transaction — reuse-or-create the open draft, rebuild its rows
* from the live ranking (pins applied, usage stamped), finalize it, close the
* curator's open session, create the share link, and carry the hand-placed pieces
* into a fresh open draft so they stay where the person put them. Idempotent on
* `saveKey`: a replay returns the same result and link and writes nothing.
*/
async saveAndShare(collectionId: string, curatorId: string, name: string, saveKey: string): Promise<SavedRanking> {
return this.inCuratorTx(collectionId, curatorId, "save_and_share", async (tx) => {
// Same key in two collections takes two curator locks; this one serializes them so the loser 409s, not 500s.
await lockSaveKey(tx, curatorId, saveKey);
const resultRepo = new SortResultRepository(tx);
const shareRepo = new SortResultShareRepository(tx);
const replay = await resultRepo.findBySaveKey(curatorId, saveKey);
if (replay) {
const share = (await shareRepo.findByResult(replay.id)).find((s) => s.status === "active");
if (replay.collectionId !== collectionId || !share) throw new SaveKeyConflictError();
return { result: replay, shareToken: share.shareToken, created: false };
}
const liveIds = new Set((await new ItemRepository(tx).findByCollection(collectionId)).map((i) => i.id));
const preferences = await new CollectionPreferenceItemRepository(tx).findByCollection(collectionId, curatorId);
const draft = await this.getOrCreateOpenDraft(tx, collectionId, curatorId);
const itemRepo = new SortResultItemRepository(tx);
const pins = pinsFromRows(await itemRepo.findByResult(draft.id));
const { loved, onward } = buildRanking(preferences, liveIds, pins);
const ordered = [...loved, ...onward];
if (ordered.length === 0) throw new NothingToSaveError();
const events = await loadCuratorDecisionEvents(new SessionRepository(tx), new DecisionEventRepository(tx), collectionId, curatorId);
const usage = deriveUsage(events, new Set(ordered.map((e) => e.itemId)));
await itemRepo.deleteByResult(draft.id);
await itemRepo.createMany(
ordered.map((entry, index) => ({
sortResultId: draft.id,
itemId: entry.itemId,
computedRank: index,
computedBucket: entry.bucket,
usage: usage.get(entry.itemId) ?? null,
})),
);
const result = await resultRepo.markSaved(draft.id, name, saveKey);
// The saved draft is finalized now, so the open-draft index admits a new one.
// Only the explicit pins travel — the rest keep flowing with later answers.
const keptPins = loved.flatMap((entry, slot) => (entry.pinned ? [{ entry, slot }] : []));
if (keptPins.length > 0) {
const next = await this.getOrCreateOpenDraft(tx, collectionId, curatorId);
await itemRepo.createMany(
keptPins.map(({ entry, slot }) => ({
sortResultId: next.id, itemId: entry.itemId, computedRank: slot, computedBucket: entry.bucket, manualRank: slot,
})),
);
}
const sessionRepo = new SessionRepository(tx);
const open = await sessionRepo.findInProgress(collectionId, curatorId);
if (open) await sessionRepo.update(open.id, { status: "completed" });
const shareToken = randomBytes(32).toString("hex");
await shareRepo.create({ sortResultId: result.id, shareToken });
return { result, shareToken, created: true };
});
}
async getResult(id: string): Promise<{ result: SortResult; items: SortResultItem[] } | null> {
const result = await this.sortResultRepo.findById(id);
if (!result) return null;
const items = await this.sortResultItemRepo.findByResult(id);
return { result, items };
}
/**
* Finalize a draft into an immutable snapshot AND close the pass it belongs
* to (spec §E, "sessions as invisible bookkeeping"): both writes commit or
* roll back together in ONE transaction. `sort_results` carries no
* sessionId — a result can be finalized from any of the curator's sessions —
* so the curator's currently open (active|paused) session for the result's
* collection is resolved AT FINALIZE TIME, by (collectionId, curatorId). No
* open session is not an error: the result finalizes alone.
*
* The result row is locked (`findByIdForUpdate`) inside the transaction so a
* concurrent finalize serializes here instead of racing the state guard
* (the finalized-immutability TOCTOU guard).
*/
async finalizeResult(id: string): Promise<SortResult> {
// The pre-tx read only supplies the lock key (collection and curator never change);
// status is re-asserted under the lock, so a concurrent save serializes ahead of us.
const owner = await this.sortResultRepo.findById(id);
Iif (!owner) throw new Error("Result not found");
return this.inCuratorTx(owner.collectionId, owner.curatorId, "finalize_result", async (tx) => {
const resultRepo = new SortResultRepository(tx);
const result = await resultRepo.findByIdForUpdate(id);
Iif (!result) throw new Error("Result not found");
if (result.status === "finalized") throw new FinalizeStateError();
const finalized = await resultRepo.update(id, {
status: "finalized",
finalizedAt: new Date(),
});
const sessionRepo = new SessionRepository(tx);
const openSession = await sessionRepo.findInProgress(result.collectionId, result.curatorId);
if (openSession) {
await sessionRepo.update(openSession.id, { status: "completed" });
}
return finalized;
});
}
async supersedeResult(id: string, opts: { discardPins?: boolean } = {}): Promise<SortResult | null> {
const source = await this.sortResultRepo.findById(id);
if (!source) return null;
if (source.status !== "finalized") throw new SupersedeStateError();
// Source is finalized/immutable, so reading its items pre-tx is benign.
const sourceItems = await this.sortResultItemRepo.findByResult(id);
const items = cloneItemsFrom(sourceItems);
const usageByItemId = await this.deriveCuratorUsage(source.collectionId, source.curatorId, items);
// Spec §4.4 "Make a revision opens a new copy to adjust": the copy becomes THE open
// draft (replacing any other) with the saved loved order pinned, so the live
// Ranking shows the saved order until the person moves or unpins something.
// When that other draft holds hand placements the revision would move, the
// person confirms first (`discardPins`).
const slots = savedOrderPositions(sourceItems);
const outcome = await this.inCuratorTx<{ pinsLost: number } | { revision: SortResult }>(source.collectionId, source.curatorId, "supersede_result", async (tx) => {
const itemRepo = new SortResultItemRepository(tx);
if (!opts.discardPins) {
// Checked before any write, so returning early commits nothing. A sentinel, not a
// throw: withTransaction logs every throw as a DB error, and this is a prompt.
let lost = 0;
for (const draft of await new SortResultRepository(tx).findDrafts(source.collectionId, source.curatorId)) {
lost += pinsLostToRevision(await itemRepo.findByResult(draft.id), slots);
}
if (lost > 0) return { pinsLost: lost };
}
await this.deleteDrafts(tx, source.collectionId, source.curatorId);
const revision = await this.insertResultWithItems(
tx, source.collectionId, source.curatorId, `${source.name} (Revision)`, items, usageByItemId, slots,
);
return { revision };
});
if ("pinsLost" in outcome) throw new RevisionDiscardsPinsError(outcome.pinsLost);
return outcome.revision;
}
/**
* Hard-delete a DRAFT result with its shares and items, ATOMICALLY under the
* curator lock: children first (neither FK to sort_results has ON DELETE
* CASCADE), so the deletes commit or roll back together and a mid-delete
* failure leaves nothing changed (purses-nea established the transaction
* pattern; prod runs postgres-js).
*
* Returns false when the result is absent (route -> 404); throws
* DeleteResultStateError when the result is not a draft (route -> 409).
*/
async deleteResult(id: string): Promise<boolean> {
const result = await this.sortResultRepo.findById(id);
if (!result) return false;
if (result.status !== "draft") throw new DeleteResultStateError();
// Status re-asserted under the lock: a save that finalized this draft meanwhile wins.
return this.inCuratorTx(result.collectionId, result.curatorId, "delete_result", async (tx) => {
const resultRepo = new SortResultRepository(tx);
const locked = await resultRepo.findByIdForUpdate(id);
Iif (!locked) return false;
if (locked.status !== "draft") throw new DeleteResultStateError();
await new SortResultShareRepository(tx).deleteByResult(id);
await new SortResultItemRepository(tx).deleteByResult(id);
await resultRepo.delete(id);
return true;
});
}
/**
* Mint a share link under the result's curator lock (purses-w7ss.18): account deletion, a
* collection purge and a draft delete all remove sort_result_shares before sort_results, so a
* share inserted in between would 23503 their sort_results delete. The pre-tx read only supplies
* the lock key; the row is re-read under the lock, and gone → null (route 404).
*/
async createShare(id: string, expiresAt?: Date): Promise<(SortResultShare & { shareToken: string }) | null> {
const owner = await this.sortResultRepo.findById(id);
if (!owner) return null;
return this.inCuratorTx(owner.collectionId, owner.curatorId, "create_share", async (tx) => {
if (!(await new SortResultRepository(tx).findByIdForUpdate(id))) return null;
const shareToken = randomBytes(32).toString("hex");
const share = await new SortResultShareRepository(tx).create({ sortResultId: id, shareToken, expiresAt });
return { ...share, shareToken };
});
}
/**
* Owner-only purge-prep: detach an item from every DRAFT result it sits in
* (across all curators), in one transaction, then report how many FINALIZED
* results still reference it. The deliberate t9l exception — purge is a
* collection-owner op, so clearing draft sorts is its necessary consequence;
* finalized results stay immutable and preferences are untouched.
*
* Invariant: every write inside the transaction goes to the tx-bound repo, not
* the injected `this.sortResultItemRepo`. The finalized count runs in the same
* transaction so `removed`/`remainingInFinalized` are a consistent snapshot.
* Takes every curator's lock for the collection (purge-lock), like the purge itself.
*/
async removeItemFromDraftResults(
collectionId: string,
itemId: string,
): Promise<{ removed: number; remainingInFinalized: number }> {
return withTransaction(
this.db,
async (tx) => {
// Crosses curators, so it serializes with EVERY curator's pin/save/revision.
await lockCollectionCurators(tx, collectionId);
const repo = new SortResultItemRepository(tx);
const removed = await repo.deleteByItemInDraftResults(itemId);
const remainingInFinalized = await repo.countByItemInFinalizedResults(itemId);
return { removed, remainingInFinalized };
},
{ op: "remove_item_from_draft_results", ctx: { collectionId } },
);
}
}
|