Cotton code
122 lines · 6.4 KB · TypeScriptRaw
/** * `merge_people { keep, merge }`: fold a duplicate person into the one who * stays, in one write and one version (the Rust rule, rules/people/merge.rs, * carried out on the object's own rows): * * - The survivor gains what the duplicate held and they did not: an empty *   column fills, a list column unions without repeats; nothing the survivor *   holds is overwritten. * - The device card (`device_contact_id` with its snapshot) moves when only *   the duplicate holds one; either way the duplicate lets go of it, so an *   import never finds the binned row by its Contacts card again. * - Every row that links the duplicate through a link column a definition *   declares (`link_to: "person"`, any table) is repointed at the survivor. *   A repointed row that repeats one the survivor already has — same table, *   same link, the same title and the same choices — goes to the bin. * - The duplicate goes to the bin, LAST, so restore_from_bin brings it back. */import { fail, requireString, type Data, type ToolContext, type Writer } from "../../context.ts";import type { StoredRow } from "../../../store.ts";import { sameJson } from "./values.ts";import { recordName } from "./shape.ts";import { noLongerHere, resolveTable, visibleTables, type Table } from "./table.ts";/** The device card: one Contacts card belongs to one person, so its two columns move together. */const DEVICE_CARD = ["device_contact_id", "device_contact_snapshot"];function empty(v: unknown): boolean {  return v === null || v === undefined || v === "" || (Array.isArray(v) && v.length === 0);}function person(ctx: ToolContext, t: Table, id: string, role: "keep" | "merge"): StoredRow {  const row = ctx.get(t.id, id) ?? fail(`${role} is not a person: there is no person ${JSON.stringify(id)}`);  if (t.binned(row) !== null) fail(`${role} is a person in the bin: restore_from_bin brings them back first`);  return row;}/** What the survivor gains: empty columns filled, list columns unioned; the duplicate's own state (bin, archive, the device card) never travels. */function survivorPatch(t: Table, keep: Data, merge: Data): { patch: Data; filled: string[]; combined: string[] } {  const archive = t.archive;  const staying = new Set([t.binColumn, archive && "column" in archive ? archive.column : null, ...DEVICE_CARD]);  const patch: Data = {};  const filled: string[] = [];  const combined: string[] = [];  for (const c of t.columns) {    if (staying.has(c.key) || (c.computed !== undefined && c.computed !== null)) continue;    const mine = keep[c.key];    const theirs = merge[c.key];    if (empty(theirs)) continue;    if (empty(mine)) {      patch[c.key] = theirs;      filled.push(c.key);    } else if (Array.isArray(mine) && Array.isArray(theirs)) {      const union = [...mine];      for (const v of theirs) if (!union.some((u) => sameJson(u, v))) union.push(v);      if (union.length > mine.length) {        patch[c.key] = union;        combined.push(c.key);      }    }  }  return { patch, filled, combined };}/** Where a row repeats another: its title and every single choice, as written. */function likeness(t: Table, data: Data): string {  const keys = [t.title, ...t.columns.filter((c) => c.type === "choice" && c.multiple !== true).map((c) => c.key)].filter((k) => k && t.column(k));  return JSON.stringify(keys.map((k) => (typeof data[k] === "string" ? (data[k] as string).trim().toLowerCase() : (data[k] ?? null))));}export function mergePeople(ctx: ToolContext, args: Data): Data {  const keepId = requireString(args, "keep", "keep is required: the id of the person who stays");  const mergeId = requireString(args, "merge", "merge is required: the id of the person folded into keep");  const t = resolveTable(ctx, "person");  const bin = t.binColumn ?? fail(`${t.plural} have no bin, so a merged person would be gone for good: nothing was merged`);  if (keepId === mergeId) fail("keep and merge are the same person: name two people");  const keep = person(ctx, t, keepId, "keep");  const merge = person(ctx, t, mergeId, "merge");  const { patch, filled, combined } = survivorPatch(t, keep.data, merge.data);  const theirCard = !empty(merge.data.device_contact_id);  const myCard = !empty(keep.data.device_contact_id);  const deviceCard = !theirCard ? (myCard ? "kept" : "none") : myCard ? "orphaned" : "moved";  if (deviceCard === "moved") for (const k of DEVICE_CARD) if (t.column(k) && !empty(merge.data[k])) patch[k] = merge.data[k];  // Every link a definition declares to a person, on every table.  const links = visibleTables(ctx).flatMap((table) => table.columns.filter((c) => c.type === "link" && c.link_to === t.id && (c.computed === undefined || c.computed === null)).map((c) => ({ table, column: c.key })));  const repointed: Record<string, number> = {};  const binnedRepeats: Record<string, number> = {};  const now = ctx.now;  ctx.write((w: Writer) => {    if (Object.keys(patch).length) w.update(keep, patch);    for (const { table, column } of links) {      const moving = ctx.where(table.id, column, mergeId).filter((row) => !(table.id === t.id && row.id === mergeId));      if (!moving.length) continue;      const held = new Set(ctx.where(table.id, column, keepId).filter((row) => table.binned(row) === null).map((row) => likeness(table, row.data)));      for (const row of moving) {        const repeat = table.binColumn !== null && table.binned(row) === null && held.has(likeness(table, row.data));        w.update(row, { [column]: keepId, ...(repeat ? { [table.binColumn!]: now } : {}) });        if (repeat) binnedRepeats[table.id] = (binnedRepeats[table.id] ?? 0) + 1;        else held.add(likeness(table, row.data));      }      repointed[`${table.id}.${column}`] = moving.length;    }    // The duplicate goes last: it lets go of the device card and waits in the bin.    const release: Data = { [bin]: now };    for (const k of DEVICE_CARD) if (t.column(k) && !empty(merge.data[k])) release[k] = null;    w.update(ctx.get(t.id, mergeId) ?? fail(noLongerHere(t)), release);  });  const kept = ctx.get(t.id, keepId) ?? fail(noLongerHere(t));  return {    kept: { id: keepId, name: recordName(t, kept.data) },    merged: { id: mergeId, name: recordName(t, merge.data), [bin]: now },    filled,    combined,    device_card: deviceCard,    repointed,    repeats_binned: binnedRepeats,    said: `Merged ${recordName(t, merge.data)} into ${recordName(t, kept.data)}; ${recordName(t, merge.data)} waits in the bin`,  };}