Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 14 additions & 22 deletions app/_actions/deck/__tests__/bulk-edit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,32 +280,24 @@ describe("bulkReplaceDeck", () => {
expect(result.removed).toBe(0);
});

it("returns unmatched card names without generating an add op", async () => {
it("keeps the deck intact when a bulk edit contains an unresolved name", async () => {
asOwner();
// Forest resolves; "Not A Real Card" does not (no exact, no fuzzy prefix).
mockCardFindMany
.mockResolvedValueOnce([{ id: 1, name: "Forest" }] as never)
// Fuzzy lookup for the unmatched name
.mockResolvedValueOnce([] as never);
mockDeckCardFindMany.mockResolvedValue([] as never);
.mockResolvedValueOnce([{ id: 2, name: "Sol Ring" }] as never);
mockDeckCardFindMany.mockResolvedValue([
{ id: "dc-1", cardId: 1, zone: Zone.MAINBOARD, quantity: 1, categoryLinks: [] },
{ id: "dc-2", cardId: 2, zone: Zone.MAINBOARD, quantity: 1, categoryLinks: [] },
] as never);

const result = await bulkReplaceDeck(
DECK_ID,
"1 Forest\n1 Not A Real Card Xyz",
);
const result = await bulkReplaceDeck(DECK_ID, "4 Forest\n1 Sol Rign");

expect(result.unmatchedNames).toEqual(["Not A Real Card Xyz"]);
const [, , changes] = mockApply.mock.calls[0]!;
// Only the Forest add — no add for the unmatched name.
expect(changes).toEqual<BulkChange[]>([
{
op: "add",
cardId: 1,
quantity: 1,
zone: Zone.MAINBOARD,
categories: [],
},
]);
expect(result.added).toBe(1);
expect(mockApply).not.toHaveBeenCalled();
expect(result).toMatchObject({
added: 0,
removed: 0,
updated: 0,
unmatchedNames: ["Sol Rign"],
});
});
});
28 changes: 12 additions & 16 deletions app/_components/builder/bulk-edit-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export function BulkEditDialog({
const [result, setResult] = useState<BulkReplaceResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const hasUnmatchedNames = (result?.unmatchedNames.length ?? 0) > 0;

const summary = useMemo(() => {
const parsed = parseDecklist(text, detectFormat(text));
Expand Down Expand Up @@ -140,15 +141,16 @@ export function BulkEditDialog({
)}

{result && (
<Alert>
{result.unmatchedNames.length === 0 && result.warnings.length === 0 ? (
<Alert variant={hasUnmatchedNames ? "destructive" : "default"}>
{!hasUnmatchedNames && result.warnings.length === 0 ? (
<CheckCircle2 />
) : (
<AlertCircle />
)}
<AlertTitle>
Saved — added {result.added}, removed {result.removed}, updated{" "}
{result.updated}
{hasUnmatchedNames
? "Fix unmatched card names before saving"
: `Saved. Added ${result.added}, removed ${result.removed}, updated ${result.updated}.`}
</AlertTitle>
<AlertDescription>
<div className="flex flex-col gap-2">
Expand All @@ -159,18 +161,12 @@ export function BulkEditDialog({
))}
</ul>
)}
{result.unmatchedNames.length > 0 && (
<div>
<p className="mb-1">
{result.unmatchedNames.length} unmatched card
{result.unmatchedNames.length !== 1 ? "s" : ""} skipped:
</p>
<ul className="font-mono text-xs flex flex-col gap-0.5 pl-2">
{result.unmatchedNames.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
</div>
{hasUnmatchedNames && (
<ul className="font-mono text-xs flex flex-col gap-0.5 pl-2">
{result.unmatchedNames.map((name) => (
<li key={name}>{name}</li>
))}
</ul>
)}
</div>
</AlertDescription>
Expand Down
41 changes: 40 additions & 1 deletion lib/deck/io/__tests__/card-resolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,46 @@ describe("resolveCardNames", () => {
expect(row!.warnings).toHaveLength(0);
});

it("picks the closest-length candidate", async () => {
it("rejects a same-prefix, similar-length but different card (false positive)", async () => {
mockFindMany
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([{ id: 42, name: "Lightning Helix" }] as never);

const [row] = await resolveCardNames([parsed("Lightning Bolt")]);

expect(row).toMatchObject({ cardId: null, match: { kind: "none" } });
expect(row!.warnings).toHaveLength(0);
});

it("still fuzzy-matches a real typo", async () => {
mockFindMany
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([
{ id: 1, name: "Lightning Helix" },
{ id: 2, name: "Lightning Bolt" },
] as never);

const [row] = await resolveCardNames([parsed("Lightnign Bolt")]);

expect(row).toMatchObject({ cardId: 2, matchedName: "Lightning Bolt" });
expect(row!.match.kind).toBe("fuzzy");
expect(row!.warnings).toHaveLength(1);
});

it("returns none when two candidates tie", async () => {
mockFindMany
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([
{ id: 1, name: "Shockwave" },
{ id: 2, name: "Shockwaze" },
] as never);

const [row] = await resolveCardNames([parsed("Shockwaxe")]);

expect(row).toMatchObject({ cardId: null, match: { kind: "none" } });
});

it("picks the closest candidate", async () => {
mockFindMany
.mockResolvedValueOnce([] as never)
.mockResolvedValueOnce([
Expand Down
44 changes: 31 additions & 13 deletions lib/deck/io/card-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,52 @@ type CardResolution = {
};

const FUZZY_PREFIX_LEN = 4;
const FUZZY_TAKE = 20;
const FUZZY_MIN_CONFIDENCE = 0.7;
const FUZZY_TAKE = 100;
const FUZZY_MIN_CONFIDENCE = 0.85;

/** Pick the candidate whose name length is closest to the target name. */
function editDistance(a: string, b: string): number {
let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
const curr = [i];
for (let j = 1; j <= b.length; j++) {
curr[j] = Math.min(
prev[j]! + 1,
curr[j - 1]! + 1,
prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
);
}
prev = curr;
}
return prev[b.length]!;
}

/**
* Pick the prefix candidate with the lowest edit distance to the target.
* Returns undefined when no candidate shares the prefix or the top two tie
* (ambiguous, so substituting either would be a guess).
*/
function pickClosest(
target: string,
candidates: ReadonlyArray<{ id: number; name: string }>,
): { id: number; name: string } | undefined {
return [...candidates]
const ranked = candidates
.filter((c) =>
c.name.toLowerCase().startsWith(target.slice(0, FUZZY_PREFIX_LEN)),
)
.sort(
(a, b) =>
Math.abs(a.name.length - target.length) -
Math.abs(b.name.length - target.length),
)[0];
.map((c) => ({ c, d: editDistance(c.name.toLowerCase(), target) }))
.sort((x, y) => x.d - y.d);
if (ranked.length > 1 && ranked[0]!.d === ranked[1]!.d) return undefined;
return ranked[0]?.c;
}

function fuzzyConfidence(matchedName: string, target: string): number {
const lenDelta = Math.abs(matchedName.length - target.length);
const raw = 1 - lenDelta / Math.max(target.length, 1);
return Math.max(0, Math.min(1, raw));
const dist = editDistance(matchedName.toLowerCase(), target);
return Math.max(0, 1 - dist / Math.max(matchedName.length, target.length, 1));
}

/**
* Resolve parsed card names to canonical Card rows. Tries exact (case-insensitive)
* first, then a length-delta fuzzy match per unmatched name.
* first, then a edit-distance fuzzy match per unmatched name.
*/
export async function resolveCardNames(
parsed: readonly ParsedCard[],
Expand Down
6 changes: 4 additions & 2 deletions lib/deck/io/intake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,10 @@ export async function intakeDecklist(input: IntakeInput): Promise<IntakeResult>
// that yielded nothing would delete every card. A parse failure produces
// zero parsed cards *with* warnings — distinct from a legitimately empty
// paste (zero cards, no warnings), which may intentionally clear the deck.
// Abort with a warning-only result rather than silently wiping the deck.
if (mode === "replace" && parsed.cards.length === 0 && warnings.length > 0) {
if (
mode === "replace" &&
(unmatchedNames.length > 0 || (parsed.cards.length === 0 && warnings.length > 0))
) {
return { applied: 0, added: 0, removed: 0, updated: 0, unmatchedNames, warnings };
}

Expand Down