diff --git a/DESIGN.md b/DESIGN.md
index 0a9a05b5..756d2dcd 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -361,7 +361,7 @@ A bottom tab bar holds four tabs, in this order: **Recent, Collection, Decks, Sc
- A reload when the tab gains focus and a new page keep the tiles already shown and bring no skeleton grid back.
- With no copies, the tab shows its empty state with a **Scan cards** button, which opens the Scan tab. See Empty states.
- When the read fails, the tab shows the empty state "Could not load your collection" with a **Try again** button, which reloads the binder grid.
- - One quiet meta line under each card shows the set icon in its rarity color, the collector number, and the condition when it is not NM. Foil and etched copies carry a sheen on the card image instead of a finish label. Later, badges also show whether the copy is in a deck, held by a planned swap, or protected.
+ - One quiet meta line under each card shows a warning shield when the copy is protected, the set icon in its rarity color, the collector number, and the condition when it is not NM. Foil and etched copies carry a sheen on the card image instead of a finish label. Later, badges also show whether the copy is in a deck or held by a planned swap.
- A price line under the meta line shows the copy's current price (owner decision, #120). A copy with no current price shows "–". A stale price has a clock symbol.
- Tapping a tile opens the copy page for that copy, from the binder and from search results alike.
- A native search bar sits under the large title. See Collection search. Filters: All, Free, Allocated, Protected.
@@ -474,9 +474,10 @@ Pushed screens cover the whole screen, including the app tab bar. There are **no
- **Price**: value rows for "Current price" with the stale clock, "Added" with the day, such as "12 October 2026", and "Purchase-day price", then the credit "Current prices from Scryfall, in USD". A missing price shows a text dim "–", and VoiceOver hears "no price". A stale current price adds the hint "The price may be out of date.";
- **Rules**: the Oracle text in a surface card, with each face's name over its text for a card with more than one face, then a "Commander" value row: "Legal", "Banned", "Not legal", or "Unknown".
- Section headings are lime body strong text.
- - A ••• bar button with the `ellipsis` symbol sits on the right of the header, over the hero. VoiceOver reads it as "More". It opens the actions menu, a native menu of what the user can do to this copy. Its last item is **Delete copy**, in red.
+ - A ••• bar button with the `ellipsis` symbol sits on the right of the header, over the hero. VoiceOver reads it as "More". It opens the actions menu, a native menu of what the user can do to this copy. Its first item is **Protect** for a free copy or **Unprotect** for a protected copy. Its last item is **Delete copy**, in red.
+ - **Protect** and **Unprotect** act at once on this copy only, and the Protected chip changes. When the write fails, a native alert says "Could not protect this card" or "Could not unprotect this card" and "Check your connection.", and the copy stays as it was.
- **Delete copy** shows a native alert "Delete this copy?" with "It leaves your collection with its user tags. This cannot be undone.", **Delete copy** in red, and **Cancel**. After the delete, the app goes back to the binder, which reloads without the tile. When the delete fails, a native alert says "Could not delete this copy" and "Check your connection.", and the page stays.
- - A copy that no longer exists, such as one deleted on another phone, shows a native alert "This card is no longer in your collection." with **OK**, which goes back to the binder.
+ - A copy that no longer exists, such as one deleted on another phone, shows a native alert "This card is no longer in your collection." with **OK**, which goes back to the binder. The same alert shows when the copy is gone by the time the user picks an action.
- When the read fails, the page shows the empty state "Could not load this card" with a **Try again** button. See Empty states.
- **Deck screen**, from the gallery or a deck tag:
- The top bar is a compact header: the commander picture, the deck name, and chips for priority, validity, and estimated bracket. When the deck is not valid, its violations and the bracket signals show under the chips. Nothing else goes in the header.
@@ -630,13 +631,13 @@ Liquid Glass is Apple's glass material from iOS 26 (owner decision, #113).
- The phone saves the scan batch for each account, so they survive a restart. Another account on the phone does not see them.
- **Binder tile.** One copy's card image with a meta line and a price line under it. There is no quantity badge and no chip.
- Until the image loads, the tile is a line-colored card shape.
- - The meta line sits 4 px below the card image, centered, in meta text in text muted: the set's expansion symbol from Scryfall at 16 px tinted with the rarity color of the card printing (see Colors), then the collector number. When the card catalog has no symbol for the set, or it has not loaded, the set code in capitals takes its place. A copy that is not NM adds a text dim " · " and its condition: "[symbol] 136 · MP". Every condition uses the same text muted color.
+ - The meta line sits 4 px below the card image, centered, in meta text in text muted: the set's expansion symbol from Scryfall at 16 px tinted with the rarity color of the card printing (see Colors), then the collector number. A protected copy starts the line with an 11 px `shield.fill` symbol in warning, before the set symbol: "[shield] [symbol] 136". When the card catalog has no symbol for the set, or it has not loaded, the set code in capitals takes its place. A copy that is not NM adds a text dim " · " and its condition: "[symbol] 136 · MP". Every condition uses the same text muted color.
- The line never names the finish. A foil copy has a faint rainbow sheen over its card image, and an etched copy has a faint silver sheen. Nonfoil copies have none. The sheen does not move. It is a diagonal gradient at 30% opacity, so the card art reads normally.
- The price line sits 4 px below the meta line, centered, in price type (12 px, semibold) in text price, slightly brighter than the meta line. It shows the copy's current price in full, such as "$1,635.37". The price is the current Scryfall price for the card printing and finish. Condition and language do not change it. The currency is USD for now.
- A copy with no price for its card printing and finish shows a text dim "–". A price is never taken from another finish or card printing.
- A stale price, older than 24 hours, has a small 11 px `clock` symbol in text price before it. The symbol is neutral, not a warning.
- - VoiceOver reads the tile as one button: the name, the set code in capitals and the collector number, then the finish when it is not nonfoil and the condition when it is not NM, in words, then the price or "no price": "Bloomvine Regent // Claim Territory, TDM 136, foil, moderately played, $1,635.37". A stale price adds the hint "The price may be out of date."
- - Tapping the tile opens the copy page. The badges for decks, planned swaps, and protected copies come later.
+ - VoiceOver reads the tile as one button: the name, the set code in capitals and the collector number, then the finish when it is not nonfoil and the condition when it is not NM, in words, then "protected" for a protected copy, then the price or "no price": "Bloomvine Regent // Claim Territory, TDM 136, foil, moderately played, protected, $1,635.37". A stale price adds the hint "The price may be out of date."
+ - Tapping the tile opens the copy page. The badges for decks and planned swaps come later.
- **Empty states.** Every empty state uses one layout, variant C of the HTML prototype (`prototypes/empty-states/index.html` on `prototype/empty-states`, commit 961e3ae). The `EmptyState` molecule draws it, and each page passes its own illustration.
- From top to bottom: an illustration, a title in sheet title type in text white, one line of body text in text muted, and at most one primary (lime) button, 16 px apart. The text is centered.
- The illustration is made of shapes from the app in line color, such as empty binder slots or ghost rows. It uses no images. On the background, it fades downward into the background from 30% of its height (`gradients.emptyStateFade`). Over the camera and in batch review it does not fade.
diff --git a/README.md b/README.md
index ec99b158..88fdeeb4 100644
--- a/README.md
+++ b/README.md
@@ -209,6 +209,14 @@ Signed-in users read one copy with `supabase.rpc('get_copy', { query })`. The qu
- From its card: `type_line`, `faces` with each face's `name` and `oracle_text` in face order, and `commander_legality`.
- The function runs with the caller's rights, so another user's copy is refused with `not_found` on `copy_id`, like a copy that does not exist. A refused query has the code `invalid_argument` and the field at fault. An anonymous caller and the secret key are refused.
+### Protect a copy
+
+Signed-in users protect or unprotect one of their copies with `supabase.rpc('set_copy_protected', { request })`. The request has `copy_id` and `protected`, `true` or `false`. `supabase/collection.ts` has the shared types. The copy page's actions menu calls it.
+
+- It changes only that copy, in one transaction, and returns `copy_id` and `protected`. Doing what is already done changes nothing.
+- Only a free copy can be protected. Protecting a copy that is not free is refused with `copy_not_free` on `copy_id`. Until decks exist, every copy is free.
+- Another user's copy is refused with `not_found` on `copy_id`, like a copy that does not exist. A refused request has the code `invalid_argument` and the field at fault. An anonymous caller and the secret key are refused.
+
### Copy delete
Signed-in users delete one copy with `supabase.rpc('delete_copy', { request })`. The request has only `copy_id`. `supabase/collection.ts` has the shared type. The copy page deletes its copy through it.
diff --git a/apps/mobile/src/app/(tabs)/(collection)/collection.tsx b/apps/mobile/src/app/(tabs)/(collection)/collection.tsx
index 3f390c56..adbc3070 100644
--- a/apps/mobile/src/app/(tabs)/(collection)/collection.tsx
+++ b/apps/mobile/src/app/(tabs)/(collection)/collection.tsx
@@ -75,6 +75,7 @@ function BinderTile({ copy, setIconUri }: { copy: CollectionCopyRow; setIconUri:
copy.name,
`${copy.set.toUpperCase()} ${copy.collector_number}`,
...spokenFinishAndCondition(copy),
+ ...(copy.protected ? ['protected'] : []),
price ?? 'no price',
].join(', ')}
accessibilityHint={copy.price?.stale ? 'The price may be out of date.' : undefined}
@@ -85,6 +86,7 @@ function BinderTile({ copy, setIconUri }: { copy: CollectionCopyRow; setIconUri:
setIconUri={setIconUri}
collectorNumber={copy.collector_number}
condition={shownCondition(copy.condition)}
+ isProtected={copy.protected}
/>
diff --git a/apps/mobile/src/app/copy.tsx b/apps/mobile/src/app/copy.tsx
index 51752ed9..b24cb7b3 100644
--- a/apps/mobile/src/app/copy.tsx
+++ b/apps/mobile/src/app/copy.tsx
@@ -2,7 +2,7 @@ import { router, Stack, useLocalSearchParams } from 'expo-router';
import { useEffect } from 'react';
import { Alert, View } from 'react-native';
-import { deleteCopy } from '@/collection/copy-writes';
+import { deleteCopy, setCopyProtected } from '@/collection/copy-writes';
import { copyPriceCurrency, useCopy } from '@/collection/use-copy';
import { DashedCardFrame } from '@/components/molecules/empty-state-illustrations';
import { ReadFailure } from '@/components/molecules/read-failure';
@@ -31,6 +31,14 @@ export default function CopyScreen() {
}
}
+ async function changeProtected(isProtected: boolean) {
+ if ((await setCopyProtected(copyId, isProtected)) === 'failed') {
+ Alert.alert(isProtected ? 'Could not protect this card' : 'Could not unprotect this card', 'Check your connection.');
+ return;
+ }
+ reload();
+ }
+
function confirmDelete() {
Alert.alert('Delete this copy?', 'It leaves your collection with its user tags. This cannot be undone.', [
{ text: 'Delete copy', style: 'destructive', onPress: deleteThisCopy },
@@ -42,7 +50,9 @@ export default function CopyScreen() {
{read.status === 'loaded' ? (
<>
- {copyActionsMenu({ onDelete: confirmDelete })}
+
+ {copyActionsMenu({ copy: read.copy, onSetProtected: changeProtected, onDelete: confirmDelete })}
+
>
) : null}
diff --git a/apps/mobile/src/collection/copy-writes.ts b/apps/mobile/src/collection/copy-writes.ts
index 6a0393fc..73f788fd 100644
--- a/apps/mobile/src/collection/copy-writes.ts
+++ b/apps/mobile/src/collection/copy-writes.ts
@@ -1,15 +1,25 @@
-import type { DeleteCopyRequest } from '@mtgscan/supabase/collection';
+import type { CopyProtectedRequest, DeleteCopyRequest } from '@mtgscan/supabase/collection';
import { readSearchError } from '@mtgscan/supabase/search';
import { supabase } from '@/lib/supabase';
export type CopyWriteResult = 'done' | 'missing' | 'failed';
-export async function deleteCopy(copyId: string): Promise {
- const request: DeleteCopyRequest = { copy_id: copyId };
- const { error } = await supabase.rpc('delete_copy', { request });
+function resultOf(error: Parameters[0] | null): CopyWriteResult {
if (!error) {
return 'done';
}
return readSearchError(error).code === 'not_found' ? 'missing' : 'failed';
}
+
+export async function setCopyProtected(copyId: string, isProtected: boolean): Promise {
+ const request: CopyProtectedRequest = { copy_id: copyId, protected: isProtected };
+ const { error } = await supabase.rpc('set_copy_protected', { request });
+ return resultOf(error);
+}
+
+export async function deleteCopy(copyId: string): Promise {
+ const request: DeleteCopyRequest = { copy_id: copyId };
+ const { error } = await supabase.rpc('delete_copy', { request });
+ return resultOf(error);
+}
diff --git a/apps/mobile/src/components/molecules/copy-meta.tsx b/apps/mobile/src/components/molecules/copy-meta.tsx
index 8a2d0a74..2b69aebf 100644
--- a/apps/mobile/src/components/molecules/copy-meta.tsx
+++ b/apps/mobile/src/components/molecules/copy-meta.tsx
@@ -2,7 +2,9 @@ import type { ComponentProps } from 'react';
import { View } from 'react-native';
import { SetIcon } from '@/components/atoms/set-icon';
+import { SymbolView } from '@/components/atoms/symbol-view';
import { Text } from '@/components/atoms/text';
+import { sizes } from '@/theme';
type CopyMetaProps = {
setCode: string;
@@ -10,12 +12,14 @@ type CopyMetaProps = {
setIconUri: string | undefined;
collectorNumber: string;
condition?: string;
+ isProtected?: boolean;
};
-export function CopyMeta({ setCode, rarity, setIconUri, collectorNumber, condition }: CopyMetaProps) {
+export function CopyMeta({ setCode, rarity, setIconUri, collectorNumber, condition, isProtected = false }: CopyMetaProps) {
const setLabel = setCode.toUpperCase();
return (
+ {isProtected && }
{setIconUri ? (
diff --git a/apps/mobile/src/components/organisms/copy-actions-menu.tsx b/apps/mobile/src/components/organisms/copy-actions-menu.tsx
index 6b8b7f43..037232e5 100644
--- a/apps/mobile/src/components/organisms/copy-actions-menu.tsx
+++ b/apps/mobile/src/components/organisms/copy-actions-menu.tsx
@@ -1,14 +1,23 @@
+import type { CopyDetails } from '@mtgscan/supabase/collection';
import { Stack } from 'expo-router';
import { colors } from '@/theme';
type CopyActionsMenuProps = {
+ copy: Pick;
+ onSetProtected: (isProtected: boolean) => void;
onDelete: () => void;
};
-export function copyActionsMenu({ onDelete }: CopyActionsMenuProps) {
+export function copyActionsMenu({ copy, onSetProtected, onDelete }: CopyActionsMenuProps) {
return (
+ {copy.protected ? (
+ onSetProtected(false)}>Unprotect
+ ) : null}
+ {!copy.protected && copy.free ? (
+ onSetProtected(true)}>Protect
+ ) : null}
Delete copy
diff --git a/apps/mobile/src/primitive-catalog/primitive-catalog.tsx b/apps/mobile/src/primitive-catalog/primitive-catalog.tsx
index 8e158696..5941256c 100644
--- a/apps/mobile/src/primitive-catalog/primitive-catalog.tsx
+++ b/apps/mobile/src/primitive-catalog/primitive-catalog.tsx
@@ -228,6 +228,10 @@ function CardTiles() {
+
+
+
+
{['CMM 464', 'C21 263'].map((caption) => (
{
+ startSignedIn();
+});
+
+function actionsMenuRows() {
+ return headerMenuRows(pushedScreen(), 'More').map((row) => row.title);
+}
+
+async function chooseAction(title: string) {
+ await pressHeaderMenuAction(pushedScreen(), 'More', [title]);
+}
+
+describe('the actions menu', () => {
+ test('the actions menu of a free copy offers Protect', async () => {
+ ownCopies([copyOf('copy-1')]);
+
+ await openCopyPage(/^Angelic Curator/);
+
+ expect(actionsMenuRows()).toEqual(['Protect', 'Delete copy']);
+ });
+
+ test('the actions menu of a protected copy offers Unprotect', async () => {
+ ownCopies([copyOf('copy-1', { protected: true })]);
+
+ await openCopyPage(/^Angelic Curator/);
+
+ expect(actionsMenuRows()).toEqual(['Unprotect', 'Delete copy']);
+ });
+
+ test('the actions menu of a copy that is not free offers no Protect', async () => {
+ ownCopies([copyOf('copy-1', { free: false })]);
+
+ await openCopyPage(/^Angelic Curator/);
+
+ expect(actionsMenuRows()).not.toContain('Protect');
+ });
+
+ test('Protect protects this copy only, shows the Protected chip, and the menu then offers Unprotect', async () => {
+ ownCopies([copyOf('copy-1'), copyOf('copy-2')]);
+ await openCollection();
+ await fireEvent.press(within(selectedTab()).getAllByRole('button', { name: /^Angelic Curator/ })[1]!);
+ await screen.findByRole('header', { name: 'Price' });
+
+ await chooseAction('Protect');
+
+ expect(await screen.findByLabelText('Protected')).toBeOnTheScreen();
+ expect(copyProtectedWritesSent()).toEqual([{ copy_id: 'copy-2', protected: true }]);
+ expect(actionsMenuRows()).toEqual(['Unprotect', 'Delete copy']);
+ });
+
+ test('Unprotect unprotects this copy and removes the Protected chip', async () => {
+ ownCopies([copyOf('copy-1', { protected: true })]);
+ await openCopyPage(/^Angelic Curator/);
+
+ await chooseAction('Unprotect');
+
+ expect(copyProtectedWritesSent()).toEqual([{ copy_id: 'copy-1', protected: false }]);
+ await screen.findByLabelText('MH2');
+ expect(screen.queryByLabelText('Protected')).not.toBeOnTheScreen();
+ expect(actionsMenuRows()).toEqual(['Protect', 'Delete copy']);
+ });
+
+ test('after Protect, the binder tile of this copy shows the shield and the other tile does not', async () => {
+ ownCopies([copyOf('copy-1', { condition: 'lightly_played' }), copyOf('copy-2')]);
+ await openCopyPage('Angelic Curator, MH2 262, lightly played, $0.35');
+
+ await chooseAction('Protect');
+ await screen.findByLabelText('Protected');
+ await swipeBackFromThePushedScreen();
+
+ const collection = within(selectedTab());
+ const protectedTile = await collection.findByRole('button', { name: 'Angelic Curator, MH2 262, lightly played, protected, $0.35' });
+ expect(symbolNames(protectedTile)).toEqual(['shield.fill']);
+ expect(symbolNames(collection.getByRole('button', { name: 'Angelic Curator, MH2 262, $0.35' }))).toEqual([]);
+ });
+
+ test('a copy that no longer exists when the user protects it says so and goes back to the binder', async () => {
+ ownCopies([copyOf('copy-1'), copyOf('copy-2', { condition: 'damaged' })]);
+ await openCopyPage('Angelic Curator, MH2 262, damaged, $0.35');
+ removeCopyFromTheCollection('copy-2');
+
+ await chooseAction('Protect');
+
+ expect(presentedAlert()).toEqual({ title: 'This card is no longer in your collection.', message: undefined, buttons: ['OK'] });
+ await pressAlertButton('OK');
+ expect(screen.queryByRole('header', { name: 'Price' })).not.toBeOnTheScreen();
+ expect(within(selectedTab()).getAllByRole('button', { name: /^Angelic Curator/ })).toHaveLength(1);
+ });
+
+ test('a write that fails says so and leaves the copy as it was', async () => {
+ ownCopies([copyOf('copy-1')]);
+ failCopyWrites(1);
+ await openCopyPage(/^Angelic Curator/);
+
+ await chooseAction('Protect');
+
+ expect(presentedAlert()).toEqual({ title: 'Could not protect this card', message: 'Check your connection.', buttons: ['OK'] });
+ await pressAlertButton('OK');
+ expect(screen.queryByLabelText('Protected')).not.toBeOnTheScreen();
+ expect(actionsMenuRows()).toEqual(['Protect', 'Delete copy']);
+ });
+});
+
+describe('the binder tile', () => {
+ test('a protected copy has the shield in the warning color, 11 px, before the set icon in its meta line', async () => {
+ ownCopies([copyOf('copy-1', { protected: true })]);
+
+ const collection = await openCollection();
+
+ const tile = collection.getByRole('button', { name: 'Angelic Curator, MH2 262, protected, $0.35' });
+ expect(symbolNames(tile)).toEqual(['shield.fill']);
+ expect(symbolTintColor(tile)).toBe(warning);
+ expect(symbolIn(tile).props.size).toBe(11);
+ expect(appearsBefore(symbolIn(tile), within(tile).getByLabelText('MH2'))).toBe(true);
+ });
+
+ test('VoiceOver hears "protected" after the finish and condition and before the price', async () => {
+ ownCopies([copyOf('copy-1', { protected: true, finish: 'foil', condition: 'moderately_played' })]);
+
+ const collection = await openCollection();
+
+ expect(collection.getByRole('button', { name: 'Angelic Curator, MH2 262, foil, moderately played, protected, $0.35' })).toBeOnTheScreen();
+ });
+});
diff --git a/apps/mobile/test/fake-supabase.ts b/apps/mobile/test/fake-supabase.ts
index 6474fd88..51bc8a5b 100644
--- a/apps/mobile/test/fake-supabase.ts
+++ b/apps/mobile/test/fake-supabase.ts
@@ -11,6 +11,7 @@ import type {
CollectionQuery,
CollectionTotal,
CopyDetails,
+ CopyProtectedRequest,
CopyQuery,
DeleteCopyRequest,
ScanBatch,
@@ -45,6 +46,8 @@ let copyDetails = new Map();
let failingCopyReads = 0;
let copyDeletes: string[] = [];
let failingCopyDeletes = 0;
+let copyProtectedWrites: CopyProtectedRequest[] = [];
+let failingCopyWrites = 0;
const emptyCollectionTotal: CollectionTotal = {
total: '0.00',
currency: 'USD',
@@ -156,16 +159,39 @@ function collectionCopiesPage({ rows, cursor, limit = 60, ...search }: Collectio
const networkFailure = { code: '', message: 'TypeError: Network request failed', details: null, hint: '' };
+const copyNotFound = {
+ data: null,
+ error: { code: 'not_found', message: 'copy_id is not a copy in your collection.', details: 'copy_id' },
+};
+
+function ownedCopyDetails(copyId: string) {
+ return collectionCopies.some((copy) => copy.copy_id === copyId) ? copyDetails.get(copyId) : undefined;
+}
+
function copyRead({ copy_id }: CopyQuery) {
if (failingCopyReads > 0) {
failingCopyReads -= 1;
return { data: null, error: networkFailure };
}
- const details = copyDetails.get(copy_id);
- if (!details || !collectionCopies.some((copy) => copy.copy_id === copy_id)) {
- return { data: null, error: { code: 'not_found', message: 'copy_id is not a copy in your collection.', details: 'copy_id' } };
+ const details = ownedCopyDetails(copy_id);
+ return details ? { data: details, error: null } : copyNotFound;
+}
+
+function setCopyProtected(request: CopyProtectedRequest) {
+ copyProtectedWrites = [...copyProtectedWrites, request];
+ if (failingCopyWrites > 0) {
+ failingCopyWrites -= 1;
+ return { data: null, error: networkFailure };
+ }
+ const details = ownedCopyDetails(request.copy_id);
+ if (!details) {
+ return copyNotFound;
}
- return { data: details, error: null };
+ copyDetails.set(request.copy_id, { ...details, protected: request.protected });
+ collectionCopies = collectionCopies.map((copy) =>
+ copy.copy_id === request.copy_id ? { ...copy, protected: request.protected } : copy,
+ );
+ return { data: request, error: null };
}
function deleteCopy({ copy_id }: DeleteCopyRequest) {
@@ -174,7 +200,7 @@ function deleteCopy({ copy_id }: DeleteCopyRequest) {
return { data: null, error: networkFailure };
}
if (!collectionCopies.some((copy) => copy.copy_id === copy_id)) {
- return { data: null, error: { code: 'not_found', message: 'copy_id is not a copy in your collection.', details: 'copy_id' } };
+ return copyNotFound;
}
copyDeletes = [...copyDeletes, copy_id];
removeCopyFromTheCollection(copy_id);
@@ -316,6 +342,7 @@ export const fakeSupabase = {
| { query: CopyQuery }
| { query: { text: string; limit: number } }
| { request: DeleteCopyRequest }
+ | { request: CopyProtectedRequest }
| { batch: ScanBatch },
) {
if (name === 'search_collection' && 'query' in args) {
@@ -331,6 +358,9 @@ export const fakeSupabase = {
if (name === 'delete_copy' && 'request' in args) {
return deleteCopy(args.request);
}
+ if (name === 'set_copy_protected' && 'request' in args) {
+ return setCopyProtected(args.request as CopyProtectedRequest);
+ }
if (name === 'get_collection_total') {
return { data: collectionTotal, error: null };
}
@@ -428,6 +458,14 @@ export function failCopyReads(count: number) {
failingCopyReads = count;
}
+export function failCopyWrites(count: number) {
+ failingCopyWrites = count;
+}
+
+export function copyProtectedWritesSent() {
+ return copyProtectedWrites;
+}
+
export function ownCollectionTotal(total: CollectionTotal) {
collectionTotal = total;
}
@@ -505,6 +543,8 @@ export function resetFakeSupabase() {
failingCopyReads = 0;
copyDeletes = [];
failingCopyDeletes = 0;
+ copyProtectedWrites = [];
+ failingCopyWrites = 0;
collectionTotal = emptyCollectionTotal;
failingCollectionReads = 0;
collectionSearches = [];
diff --git a/apps/mobile/test/molecules.test.tsx b/apps/mobile/test/molecules.test.tsx
index 10ff8946..b8d6e799 100644
--- a/apps/mobile/test/molecules.test.tsx
+++ b/apps/mobile/test/molecules.test.tsx
@@ -46,6 +46,7 @@ import {
blurredImageUris,
cardImageOutline,
cardImageUri,
+ appearsBefore,
cardSheen,
dashedOutlinesColored,
fadesDown,
@@ -57,12 +58,15 @@ import {
swipeHandleMovesAfterRelease,
swipeHandlePosition,
swipeRight,
+ symbolIn,
symbolNames,
+ symbolSizes,
+ symbolTintColor,
touchTarget,
} from './native-ui';
import { tokenColors } from './token-colors';
-const { primary: lime, onPrimary, surface, surfaceControl, line, text: white, textMuted, textDim, textPrice } = tokenColors;
+const { primary: lime, onPrimary, surface, surfaceControl, line, text: white, textMuted, textDim, textPrice, warning } = tokenColors;
const solRing = 'https://cards.scryfall.io/normal/front/sol-ring.jpg';
const mh3Symbol = 'https://svgs.scryfall.io/sets/mh3.svg';
const conditions = ['NM', 'LP', 'MP', 'HP', 'DMG'] as const;
@@ -533,6 +537,16 @@ describe('CopyMeta', () => {
expect(screen.getByText('MP')).toHaveStyle({ color: textMuted, fontSize: 12 });
expect(screen.getByText('MP').parent).toHaveStyle({ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' });
});
+
+ test('a copy meta line of a protected copy starts with an 11 px shield in the warning color', async () => {
+ await render();
+
+ const line = screen.getByText('136').parent!;
+ expect(symbolNames(line)).toEqual(['shield.fill']);
+ expect(symbolSizes(line)).toEqual([11]);
+ expect(symbolTintColor(line)).toBe(warning);
+ expect(appearsBefore(symbolIn(line), screen.getByLabelText('MH3'))).toBe(true);
+ });
});
describe('PriceLine', () => {
diff --git a/apps/mobile/test/primitive-catalog.test.tsx b/apps/mobile/test/primitive-catalog.test.tsx
index b81f8ec3..e3b4b00f 100644
--- a/apps/mobile/test/primitive-catalog.test.tsx
+++ b/apps/mobile/test/primitive-catalog.test.tsx
@@ -47,6 +47,7 @@ test('the primitive catalog shows every primitive', async () => {
expect(screen.getByRole('image', { name: 'Sol Ring, M10 216, foil, lightly played, $1,635.37' })).toBeOnTheScreen();
expect(screen.getByRole('image', { name: 'Sol Ring, C21 263, etched, no price' })).toBeOnTheScreen();
expect(screen.getByRole('image', { name: 'Sol Ring, M10 216, $1.25' })).toHaveProp('accessibilityHint', 'The price may be out of date.');
+ expect(screen.getByRole('image', { name: 'Sol Ring, M10 216, protected, $1.25' })).toBeOnTheScreen();
expect(screen.getByRole('button', { name: 'Sign in with Apple' })).toBeBusy();
expect(screen.getAllByRole('button', { name: 'Continue with Google' }).map((button) => button.props.accessibilityState.busy)).toEqual([false, true]);
expect(screen.getByRole('button', { name: 'Sign-in disabled' })).toBeDisabled();
diff --git a/docs/agents/local-development.md b/docs/agents/local-development.md
index 1ae3e9f5..89119e34 100644
--- a/docs/agents/local-development.md
+++ b/docs/agents/local-development.md
@@ -27,7 +27,7 @@ A development build against local Supabase can sign in a local test user with on
- Production builds leave the test sign-in out. `bun run test:production-bundle` in `apps/mobile` builds a production bundle with the test sign-in on and fails if the bundle holds the test sign-in. CI runs it.
1. Start local Supabase as in Local Supabase.
-2. Seed or reset the test user from `supabase`. The command deletes the test user and its collection, and creates it again. `--sample-collection` also adds 30 sample collection entries through `add_scan_batch`, with 1 to 4 copies each. Some are foil, one is etched, and some are LP or MP. The sample needs the card catalog, and the binder tiles show current prices from the price import, so import both fixtures first:
+2. Seed or reset the test user from `supabase`. The command deletes the test user and its collection, and creates it again. `--sample-collection` also adds 30 sample collection entries through `add_scan_batch`, with 1 to 4 copies each. Some are foil, one is etched, and some are LP or MP. One copy is protected. The sample needs the card catalog, and the binder tiles show current prices from the price import, so import both fixtures first:
```bash
cd supabase
diff --git a/supabase/collection.ts b/supabase/collection.ts
index 832daae4..ce4c93fb 100644
--- a/supabase/collection.ts
+++ b/supabase/collection.ts
@@ -108,6 +108,11 @@ export type CopyQuery = {
price_currency?: PriceCurrency;
};
+export type CopyProtectedRequest = {
+ copy_id: string;
+ protected: boolean;
+};
+
export type DeleteCopyRequest = {
copy_id: string;
};
diff --git a/supabase/database.types.ts b/supabase/database.types.ts
index d615d1a6..f848a3a4 100644
--- a/supabase/database.types.ts
+++ b/supabase/database.types.ts
@@ -552,6 +552,9 @@ isOneToOne: false
"search_oracle_tags":
{ Args: { "query": Json }; Returns: Json
},
+"set_copy_protected":
+{ Args: { "request": Json }; Returns: Json
+ },
"stage_import_batch":
{ Args: { "batch_number": number,"batch_rows": Json,"run_id": string,"target": string }; Returns: number
}
diff --git a/supabase/migrations/20261031120000_protect_and_unprotect_a_copy.sql b/supabase/migrations/20261031120000_protect_and_unprotect_a_copy.sql
new file mode 100644
index 00000000..c14550e1
--- /dev/null
+++ b/supabase/migrations/20261031120000_protect_and_unprotect_a_copy.sql
@@ -0,0 +1,43 @@
+create function public.set_copy_protected(request jsonb)
+returns jsonb
+language plpgsql
+security definer
+set search_path = ''
+as $$
+declare
+ caller uuid;
+ chosen_copy_id uuid;
+ protecting boolean;
+ copy_is_free boolean;
+begin
+ caller := private.caller_user_id();
+ chosen_copy_id := private.checked_copy_id(request, array['protected']);
+ if not request ? 'protected' then
+ perform private.invalid_argument('protected', 'protected is required.');
+ end if;
+ protecting := private.checked_boolean('protected', request -> 'protected')::boolean;
+
+ perform 1 from public.copies copy where copy.user_id = caller and copy.id = chosen_copy_id for update;
+ if not found then
+ perform private.raise_copy_not_found();
+ end if;
+
+ if protecting then
+ select a.is_free into copy_is_free
+ from private.collection_availability a
+ where a.user_id = caller and a.copy_id = chosen_copy_id;
+ if copy_is_free is not true then
+ perform private.raise_search_error('copy_not_free', 'Only a free copy can be protected.', 'copy_id');
+ end if;
+ end if;
+
+ update public.copies copy
+ set is_protected = protecting
+ where copy.user_id = caller and copy.id = chosen_copy_id;
+
+ return jsonb_build_object('copy_id', chosen_copy_id, 'protected', protecting);
+end;
+$$;
+
+revoke all on function public.set_copy_protected(jsonb) from public, anon, service_role;
+grant execute on function public.set_copy_protected(jsonb) to authenticated;
diff --git a/supabase/test-user/main.ts b/supabase/test-user/main.ts
index 6e57372b..fc595add 100644
--- a/supabase/test-user/main.ts
+++ b/supabase/test-user/main.ts
@@ -2,7 +2,7 @@ import { parseArgs } from 'node:util';
import { createClient } from '@supabase/supabase-js';
-import type { CardCondition, ScanBatch } from '../collection';
+import type { CardCondition, CopyProtectedRequest, ScanBatch } from '../collection';
import type { Finish } from '../search';
import type { Database, Json } from '../database.types';
import { isLocalStack, localSupabaseUrl, testUser } from './account';
@@ -127,6 +127,12 @@ async function addSampleCollection(admin: LocalClient) {
fail('Could not add sample collection entries', error.message);
}
console.log(`Added ${batch.items.length} sample collection entries.`);
+ const request: CopyProtectedRequest = { copy_id: batch.items[0]!.copy_ids[0]!, protected: true };
+ const { error: protectError } = await testUserClient.rpc('set_copy_protected', { request });
+ if (protectError) {
+ fail('Could not protect a sample copy', protectError.message);
+ }
+ console.log('Protected 1 sample copy.');
}
const admin = localClient();
diff --git a/supabase/tests/copy-protection.test.ts b/supabase/tests/copy-protection.test.ts
new file mode 100644
index 00000000..2d8ac963
--- /dev/null
+++ b/supabase/tests/copy-protection.test.ts
@@ -0,0 +1,132 @@
+import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
+
+import type { CollectionCopyRow, CollectionPage } from '../collection';
+import type { Json } from '../database.types';
+import { readSearchError } from '../search';
+import { catalogFixtureManifest, resetCardCatalog, runCatalogImport } from './catalog-import-command';
+import { anonymousClient, secretKeyClient, signUpNewUser, type AppClient, type TestUser } from './local-stack';
+import { committed, scanBatch, stack } from './scan-batches';
+
+setDefaultTimeout(60_000);
+
+const permissionDenied = '42501';
+const angelicCurator = '332352c2-98f2-4eb8-b49a-026a39df227b';
+const delverInnistrad = '11bf83bb-c95b-4b4f-9a56-ce7a1816307a';
+
+let alice: TestUser;
+
+beforeAll(async () => {
+ alice = await signUpNewUser();
+ await resetCardCatalog();
+ expect((await runCatalogImport(catalogFixtureManifest)).exitCode).toBe(0);
+});
+
+async function setCopyProtected(client: AppClient, request: Record | unknown[]) {
+ const { data, error } = await client.rpc('set_copy_protected', { request: request as Json });
+ return { result: data, error: error && readSearchError(error) };
+}
+
+async function protectedFlags(user: TestUser) {
+ const { data, error } = await user.client.rpc('search_collection', { query: { rows: 'copies', limit: 120 } });
+ expect(error).toBeNull();
+ const { items } = data as unknown as CollectionPage;
+ return Object.fromEntries(items.map((copy) => [copy.copy_id, copy.protected]));
+}
+
+async function scannedCopies(user: TestUser) {
+ const curators = stack(angelicCurator, { copies: 2 });
+ const delver = stack(delverInnistrad);
+ await committed(user, scanBatch([curators, delver]));
+ return [...curators.copy_ids, ...delver.copy_ids] as [string, string, string];
+}
+
+describe('protecting a copy', () => {
+ test('protecting a copy protects only that copy, and returns it', async () => {
+ const user = await signUpNewUser();
+ const [protectedCopy, otherCurator, delver] = await scannedCopies(user);
+
+ const { result, error } = await setCopyProtected(user.client, { copy_id: protectedCopy, protected: true });
+
+ expect(error).toBeNull();
+ expect(result).toEqual({ copy_id: protectedCopy, protected: true });
+ expect(await protectedFlags(user)).toEqual({ [protectedCopy]: true, [otherCurator]: false, [delver]: false });
+ });
+
+ test('unprotecting a copy unprotects only that copy', async () => {
+ const user = await signUpNewUser();
+ const [first, second, delver] = await scannedCopies(user);
+ for (const copyId of [first, second, delver]) {
+ expect((await setCopyProtected(user.client, { copy_id: copyId, protected: true })).error).toBeNull();
+ }
+
+ const { result, error } = await setCopyProtected(user.client, { copy_id: second, protected: false });
+
+ expect(error).toBeNull();
+ expect(result).toEqual({ copy_id: second, protected: false });
+ expect(await protectedFlags(user)).toEqual({ [first]: true, [second]: false, [delver]: true });
+ });
+
+ test('protecting a protected copy again changes nothing', async () => {
+ const user = await signUpNewUser();
+ const [first, second, delver] = await scannedCopies(user);
+ await setCopyProtected(user.client, { copy_id: first, protected: true });
+
+ expect((await setCopyProtected(user.client, { copy_id: first, protected: true })).error).toBeNull();
+
+ expect(await protectedFlags(user)).toEqual({ [first]: true, [second]: false, [delver]: false });
+ });
+
+ test.each<[string, Record | unknown[], string | null]>([
+ ['a request that is not an object', [], null],
+ ['a request with no copy ID', { protected: true }, 'copy_id'],
+ ['a request with no protected flag', { copy_id: crypto.randomUUID() }, 'protected'],
+ ['a copy ID that is not a UUID', { copy_id: 'copy-1', protected: true }, 'copy_id'],
+ ['a protected flag that is not true or false', { copy_id: crypto.randomUUID(), protected: 'yes' }, 'protected'],
+ ['an unknown field', { copy_id: crypto.randomUUID(), protected: true, quantity: 1 }, 'quantity'],
+ ])('%s is refused with invalid_argument', async (_, request, field) => {
+ const { result, error } = await setCopyProtected(alice.client, request);
+
+ expect(result).toBeNull();
+ expect(error).toMatchObject({ code: 'invalid_argument', field });
+ });
+
+ test('a copy ID that is not in the collection is not_found', async () => {
+ const { error } = await setCopyProtected(alice.client, { copy_id: crypto.randomUUID(), protected: true });
+
+ expect(error).toMatchObject({ code: 'not_found', field: 'copy_id' });
+ });
+});
+
+describe('access', () => {
+ test("another user's copy is not_found and stays as it was", async () => {
+ const [copyId] = await scannedCopies(alice);
+ const bob = await signUpNewUser();
+
+ const { result, error } = await setCopyProtected(bob.client, { copy_id: copyId, protected: true });
+
+ expect(result).toBeNull();
+ expect(error).toMatchObject({ code: 'not_found', field: 'copy_id' });
+ expect((await protectedFlags(alice))[copyId]).toBe(false);
+ });
+
+ test.each<[string, () => AppClient]>([
+ ['an anonymous caller', anonymousClient],
+ ['the secret key', secretKeyClient],
+ ])('%s cannot protect a copy', async (_, client) => {
+ const [copyId] = await scannedCopies(alice);
+
+ const { data, error } = await client().rpc('set_copy_protected', { request: { copy_id: copyId, protected: true } });
+
+ expect(data).toBeNull();
+ expect(error?.code).toBe(permissionDenied);
+ });
+
+ test('a user cannot protect a copy by writing to it directly', async () => {
+ const [copyId] = await scannedCopies(alice);
+
+ const { error } = await alice.client.from('copies').update({ is_protected: true }).eq('id', copyId);
+
+ expect(error?.code).toBe(permissionDenied);
+ expect((await protectedFlags(alice))[copyId]).toBe(false);
+ });
+});
diff --git a/supabase/tests/test-user.test.ts b/supabase/tests/test-user.test.ts
index 8e1c96e9..1e6edcdf 100644
--- a/supabase/tests/test-user.test.ts
+++ b/supabase/tests/test-user.test.ts
@@ -76,6 +76,7 @@ describe('the test user command', () => {
expect(entries.some((entry) => entry.finish === 'foil')).toBe(true);
expect(entries.some((entry) => entry.finish === 'etched')).toBe(true);
expect(entries.some((entry) => entry.condition !== 'near_mint')).toBe(true);
+ expect((await ownedCopies(client)).filter((copy) => copy.protected)).toHaveLength(1);
expect(await additions(client)).toEqual([{ copy_count: (await ownedCopies(client)).length, source: 'scan_batch' }]);
});