feat(labs): keep a marker's panel when it is merged into one without

A merge into a target without a panel now takes over the first panel
a source carries, in the order the sources were given, so the merged
marker keeps its category. The result reports it as adoptedPanel, on
a dry run as well, and the merge preview says so before the person
confirms. A target with its own panel keeps it. The ledger does not
record panels; a merge has no undo.

The integration suite also proves the clear path end to end: an
explicit null on PUT clears panel, context and both bounds.

Refs #1349
This commit is contained in:
Marc-André Bombeck committed 2026-11-06 17:53:56 +01:00
1 parent 910f28dcfe
commit 65f1a3db91
17 files changed
+232 -54

No files matched your search

@@ -1,7 +1,7 @@
{
"$comment": "Production functions over 200 lines, keyed \"file :: name\", and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 344,
"total": 111553,
"total": 111520,
"entries": {
"app/achievements/page.tsx :: AchievementsPage": 206,
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 275,
@@ -132,7 +132,7 @@
"components/insights/trends-row.tsx :: TrendsRow": 215,
"components/labs/biomarker-form.tsx :: BiomarkerForm": 229,
"components/labs/biomarker-manager.tsx :: BiomarkerManager": 242,
"components/labs/biomarker-merge-sheet.tsx :: BiomarkerMergeSheet": 250,
"components/labs/biomarker-merge-sheet.tsx :: BiomarkerMergeSheet": 239,
"components/labs/lab-biomarker-chart.tsx :: LabBiomarkerChart": 370,
"components/labs/lab-biomarker-detail.tsx :: LabBiomarkerDetail": 481,
"components/labs/lab-form.tsx :: LabForm": 473,
@@ -314,7 +314,7 @@
"lib/jobs/reminder/medication-reminder-check.ts :: handleReminderCheck": 592,
"lib/jobs/reminder/medication-reminder-check.ts :: handleReminderCheck > withBackgroundEvent(arg)": 587,
"lib/jobs/workout-insight-generate.ts :: runWorkoutInsightGenerate": 324,
"lib/labs/biomarker-merge.ts :: runMerge": 254,
"lib/labs/biomarker-merge.ts :: runMerge": 232,
"lib/measurements/consolidate-daily-mean.ts :: consolidateDailyMean": 278,
"lib/measurements/consolidate-legacy-steps.ts :: consolidateLegacySteps": 263,
"lib/measurements/dense-intraday-retention.ts :: runDenseIntradayRetention": 539,
+27 -12
View File
@@ -204,18 +204,7 @@ export function BiomarkerMergeSheet({
</li>
))}
</ul>
{preview.aliasesAdded.length > 0 ? (
<div className="space-y-1.5">
<p className="text-muted-foreground text-xs">
{t("labs.merge.aliasesAdded")}
</p>
<div className="flex flex-wrap gap-1.5">
{preview.aliasesAdded.map((alias) => (
<TagChip key={alias}>{alias}</TagChip>
))}
</div>
</div>
) : null}
<MergePreviewNotes preview={preview} />
{(refused?.length ?? 0) > 0 ? (
<p role="alert" className="text-destructive text-sm">
{t("labs.merge.blocked")}
@@ -283,3 +272,29 @@ export function BiomarkerMergeSheet({
</ResponsiveSheet>
);
}
/** What the kept marker gains besides the readings: spellings and a panel. */
function MergePreviewNotes({ preview }: { preview: BiomarkerMergeResultDto }) {
const { t } = useTranslations();
return (
<>
{preview.aliasesAdded.length > 0 ? (
<div className="space-y-1.5">
<p className="text-muted-foreground text-xs">
{t("labs.merge.aliasesAdded")}
</p>
<div className="flex flex-wrap gap-1.5">
{preview.aliasesAdded.map((alias) => (
<TagChip key={alias}>{alias}</TagChip>
))}
</div>
</div>
) : null}
{preview.adoptedPanel ? (
<p className="text-sm" data-slot="biomarker-merge-adopts-panel">
{t("labs.merge.adoptsPanel", { panel: preview.adoptedPanel })}
</p>
) : null}
</>
);
}
+2
View File
@@ -183,5 +183,7 @@ export interface BiomarkerMergeResultDto {
movedReadings: number;
convertedReadings: number;
aliasesAdded: string[];
/** The panel the target takes over from a source, or null. */
adoptedPanel: string | null;
mergeId: string | null;
}
+81 -39
View File
@@ -22,6 +22,8 @@
* - one `biomarker_merges` row per source, and the rows that already pointed
* at a source now point at the target, so an id merged twice still finds
* where it went;
* - a target without a panel takes the first panel a source carries, in
* the order the sources were given (the dry run reports it too);
* - the sources are deleted.
*
* There is no undo. The ledger keeps what a later split would need to know
@@ -62,6 +64,8 @@ export interface BiomarkerMergeResult {
movedReadings: number;
convertedReadings: number;
aliasesAdded: string[];
/** The panel the target takes over from a source, or null (dry run too). */
adoptedPanel: string | null;
mergeId: string | null;
}
@@ -230,47 +234,18 @@ async function runMerge(
}
const convertedReadings = convertedLive;
// The spellings the target gains: each source's name and its aliases, once
// each, except what the target's name already is or another marker (not a
// source) already answers to.
const sourceAliases = await tx.biomarkerAlias.findMany({
where: { userId, biomarkerId: { in: [...sourceIds] } },
select: { id: true, name: true, nameFolded: true },
const { sourceAliases, added } = await planMergeAliases(tx, {
userId,
target,
sources,
});
const otherAliases = await tx.biomarkerAlias.findMany({
where: { userId, biomarkerId: { notIn: [...sourceIds] } },
select: { biomarkerId: true, nameFolded: true },
});
const blocked = new Set(
otherAliases
.filter((a) => a.biomarkerId !== targetId)
.map((a) => a.nameFolded),
);
const targetAliasFolds = new Set(
otherAliases
.filter((a) => a.biomarkerId === targetId)
.map((a) => a.nameFolded),
);
const otherMarkerFolds = new Set(
(
await tx.biomarker.findMany({
where: { userId, id: { notIn: [targetId, ...sourceIds] } },
select: { name: true },
})
).map((m) => foldForMatch(m.name)),
);
const targetFold = foldForMatch(target.name);
const added = new Map<string, string>();
const consider = (name: string) => {
const folded = foldForMatch(name).slice(0, BIOMARKER_ALIAS_MAX_LENGTH);
if (!folded || folded === targetFold) return;
if (targetAliasFolds.has(folded) || added.has(folded)) return;
if (blocked.has(folded) || otherMarkerFolds.has(folded)) return;
added.set(folded, name.trim().slice(0, BIOMARKER_ALIAS_MAX_LENGTH));
};
for (const source of sources) consider(source.name);
for (const alias of sourceAliases) consider(alias.name);
const aliasesAdded = [...added.values()];
// A target without a panel takes the first one a source carries, in the
// order the sources were given, so the merged marker keeps its category.
const adoptedPanel =
target.panel === null
? (sources.find((source) => source.panel !== null)?.panel ?? null)
: null;
const refused = summaries.filter((s) => s.conversion === "refused");
if (!dryRun && refused.length > 0) {
@@ -346,6 +321,12 @@ async function runMerge(
});
mergeId ??= row.id;
}
if (adoptedPanel !== null) {
await tx.biomarker.update({
where: { id: targetId },
data: { panel: adoptedPanel },
});
}
await tx.biomarker.deleteMany({
where: { userId, id: { in: [...sourceIds] } },
});
@@ -365,11 +346,72 @@ async function runMerge(
movedReadings,
convertedReadings,
aliasesAdded,
adoptedPanel,
mergeId,
},
};
}
/**
* The spellings the target gains: each source's name and its aliases, once
* each, except what the target's name already is or another marker (not a
* source) already answers to.
*/
async function planMergeAliases(
tx: Prisma.TransactionClient,
input: {
userId: string;
target: { id: string; name: string };
sources: ReadonlyArray<{ id: string; name: string }>;
},
): Promise<{
sourceAliases: Array<{ id: string; name: string; nameFolded: string }>;
added: Map<string, string>;
}> {
const { userId, target, sources } = input;
const targetId = target.id;
const sourceIds = sources.map((source) => source.id);
const sourceAliases = await tx.biomarkerAlias.findMany({
where: { userId, biomarkerId: { in: [...sourceIds] } },
select: { id: true, name: true, nameFolded: true },
});
const otherAliases = await tx.biomarkerAlias.findMany({
where: { userId, biomarkerId: { notIn: [...sourceIds] } },
select: { biomarkerId: true, nameFolded: true },
});
const blocked = new Set(
otherAliases
.filter((a) => a.biomarkerId !== targetId)
.map((a) => a.nameFolded),
);
const targetAliasFolds = new Set(
otherAliases
.filter((a) => a.biomarkerId === targetId)
.map((a) => a.nameFolded),
);
const otherMarkerFolds = new Set(
(
await tx.biomarker.findMany({
where: { userId, id: { notIn: [targetId, ...sourceIds] } },
select: { name: true },
})
).map((m) => foldForMatch(m.name)),
);
const targetFold = foldForMatch(target.name);
const added = new Map<string, string>();
const consider = (name: string) => {
const folded = foldForMatch(name).slice(0, BIOMARKER_ALIAS_MAX_LENGTH);
if (!folded || folded === targetFold) return;
if (targetAliasFolds.has(folded) || added.has(folded)) return;
if (blocked.has(folded) || otherMarkerFolds.has(folded)) return;
added.set(folded, name.trim().slice(0, BIOMARKER_ALIAS_MAX_LENGTH));
};
for (const source of sources) consider(source.name);
for (const alias of sourceAliases) consider(alias.name);
return { sourceAliases, added };
}
/**
* Where a merged marker went: the target of the newest merge that removed
* `id`, or null. Chains resolve because a merge re-points the rows that named
+6
View File
@@ -229,6 +229,12 @@ const biomarkerMergeResult = z
aliasesAdded: z
.array(z.string())
.describe("Names that become aliases of the target."),
adoptedPanel: z
.string()
.nullable()
.describe(
"The panel the target takes over: when the target has none, the first panel a source carries, in the order the sources were given. `null` when the target keeps its own panel or no source has one. Reported on a dry run too, while `target.panel` there is still the stored one.",
),
mergeId: z.string().nullable().describe("`null` on a dry run."),
})
.meta({