mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
feat(places): own place identities, duplicate merging and lists linked to a trip
- A user can group the uses of one place (trip places and saved places) into a place identity of their own (user_places, user_place_links). It is personal: it groups their "All places" and is never written into a shared trip or list row. An identity without a use they can still reach is not shown, and one left without links is pruned on their next write and nightly. - Possible duplicates are suggested server side (same provider id, or the same name at the same spot), each pair with what differs and whether the user may merge it. A merge joins two identities in one transaction and can be undone; a dismissed pair does not come back. No trip or list row is deleted or changed. - A trip can link lists (trip_collection_links, needs place_edit and access to the list). A member sees a linked list only with their own access to it; the map layer lists its places and whether each is already in the trip. tripCollections:changed tells the members to read their view again. - REST, MCP tools and client data layer for all of it; migrations on both engines, additive only. - CI: the stage 1 to 2 places-library helper types, and the await-in-loop and non-null counts it had raised.
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
// FE-API-PLACE-IDENTITIES-001 to FE-API-PLACE-IDENTITIES-002
|
||||
//
|
||||
// D5/PLC-13: each method pins its verb, its path and its body or query, and
|
||||
// hands back what the server answered.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { placeIdentitiesApi } from './placeIdentities';
|
||||
|
||||
const BASE = '/api/addons/collections/library';
|
||||
|
||||
let calls: Array<[string, string, Record<string, string>, unknown]> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
function record(data: object) {
|
||||
return async ({ request }: { request: Request }) => {
|
||||
const url = new URL(request.url);
|
||||
const text = request.method === 'GET' ? '' : await request.text();
|
||||
calls.push([request.method, url.pathname, Object.fromEntries(url.searchParams), text ? JSON.parse(text) : null]);
|
||||
return HttpResponse.json(data);
|
||||
};
|
||||
}
|
||||
|
||||
describe('placeIdentitiesApi', () => {
|
||||
it('FE-API-PLACE-IDENTITIES-001: links and unlinks uses of an own place', async () => {
|
||||
const answer = { entry: null };
|
||||
server.use(http.post(`${BASE}/places/link`, record(answer)), http.post(`${BASE}/places/unlink`, record(answer)));
|
||||
expect(await placeIdentitiesApi.link({ uses: [{ kind: 'trip', id: 3 }], identity_id: 2 })).toEqual(answer);
|
||||
expect(await placeIdentitiesApi.unlink({ kind: 'list', id: 4 })).toEqual(answer);
|
||||
expect(calls).toEqual([
|
||||
['POST', `${BASE}/places/link`, {}, { uses: [{ kind: 'trip', id: 3 }], identity_id: 2 }],
|
||||
['POST', `${BASE}/places/unlink`, {}, { kind: 'list', id: 4 }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('FE-API-PLACE-IDENTITIES-002: reads duplicates, dismisses, merges and undoes', async () => {
|
||||
server.use(
|
||||
http.get(`${BASE}/duplicates`, record({ duplicates: [], next_cursor: null })),
|
||||
http.post(`${BASE}/duplicates/dismiss`, record({ success: true })),
|
||||
http.post(`${BASE}/merges`, record({ merge_id: 5, entry: null })),
|
||||
http.post(`${BASE}/merges/5/undo`, record({ success: true }))
|
||||
);
|
||||
expect(await placeIdentitiesApi.duplicates({ limit: 10 })).toEqual({ duplicates: [], next_cursor: null });
|
||||
expect(await placeIdentitiesApi.dismiss('trip:1', 'list:2')).toEqual({ success: true });
|
||||
expect(await placeIdentitiesApi.merge('trip:1', 'list:2')).toEqual({ merge_id: 5, entry: null });
|
||||
expect(await placeIdentitiesApi.undoMerge(5)).toEqual({ success: true });
|
||||
expect(calls).toEqual([
|
||||
['GET', `${BASE}/duplicates`, { limit: '10' }, null],
|
||||
['POST', `${BASE}/duplicates/dismiss`, {}, { a: 'trip:1', b: 'list:2' }],
|
||||
['POST', `${BASE}/merges`, {}, { leading: 'trip:1', other: 'list:2' }],
|
||||
['POST', `${BASE}/merges/5/undo`, {}, null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type {
|
||||
PlacesLibraryDuplicatesQueryInput,
|
||||
PlacesLibraryDuplicatesResponse,
|
||||
PlacesLibraryEntryResponse,
|
||||
PlacesLibraryLinkRequest,
|
||||
PlacesLibraryMergeResponse,
|
||||
PlacesLibraryUse,
|
||||
SuccessResponse,
|
||||
} from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
const base = '/addons/collections/library';
|
||||
|
||||
/** D5/PLC-13: the user's own places in "All places", the duplicate suggestions and merges. */
|
||||
export const placeIdentitiesApi = {
|
||||
link: (body: PlacesLibraryLinkRequest): Promise<PlacesLibraryEntryResponse> =>
|
||||
apiClient.post(`${base}/places/link`, body).then((r) => r.data),
|
||||
unlink: (use: PlacesLibraryUse): Promise<PlacesLibraryEntryResponse> =>
|
||||
apiClient.post(`${base}/places/unlink`, use).then((r) => r.data),
|
||||
duplicates: (
|
||||
query: PlacesLibraryDuplicatesQueryInput = {},
|
||||
signal?: AbortSignal
|
||||
): Promise<PlacesLibraryDuplicatesResponse> =>
|
||||
apiClient.get(`${base}/duplicates`, { params: query, signal }).then((r) => r.data),
|
||||
dismiss: (a: string, b: string): Promise<SuccessResponse> =>
|
||||
apiClient.post(`${base}/duplicates/dismiss`, { a, b }).then((r) => r.data),
|
||||
merge: (leading: string, other: string): Promise<PlacesLibraryMergeResponse> =>
|
||||
apiClient.post(`${base}/merges`, { leading, other }).then((r) => r.data),
|
||||
undoMerge: (mergeId: number): Promise<SuccessResponse> =>
|
||||
apiClient.post(`${base}/merges/${mergeId}/undo`).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
// FE-API-TRIP-COLLECTIONS-001
|
||||
//
|
||||
// PLC-15/PLC-16: each method pins its verb, its path and its body.
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '../../tests/helpers/msw/server';
|
||||
import { tripCollectionsApi } from './tripCollections';
|
||||
|
||||
const links = { links: [], can_link: true };
|
||||
let calls: Array<[string, string, unknown]> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
});
|
||||
|
||||
function record(data: object) {
|
||||
return async ({ request }: { request: Request }) => {
|
||||
const text = request.method === 'POST' ? await request.text() : '';
|
||||
calls.push([request.method, new URL(request.url).pathname, text ? JSON.parse(text) : null]);
|
||||
return HttpResponse.json(data);
|
||||
};
|
||||
}
|
||||
|
||||
describe('tripCollectionsApi', () => {
|
||||
it('FE-API-TRIP-COLLECTIONS-001: lists, maps, links and unlinks the lists of a trip', async () => {
|
||||
server.use(
|
||||
http.get('/api/trips/4/collections', record(links)),
|
||||
http.get('/api/trips/4/collections/places', record({ places: [] })),
|
||||
http.post('/api/trips/4/collections', record(links)),
|
||||
http.delete('/api/trips/4/collections/9', record(links))
|
||||
);
|
||||
expect(await tripCollectionsApi.list(4)).toEqual(links);
|
||||
expect(await tripCollectionsApi.layer(4)).toEqual({ places: [] });
|
||||
expect(await tripCollectionsApi.link(4, 9)).toEqual(links);
|
||||
expect(await tripCollectionsApi.unlink(4, 9)).toEqual(links);
|
||||
expect(calls).toEqual([
|
||||
['GET', '/api/trips/4/collections', null],
|
||||
['GET', '/api/trips/4/collections/places', null],
|
||||
['POST', '/api/trips/4/collections', { collection_id: 9 }],
|
||||
['DELETE', '/api/trips/4/collections/9', null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { TripCollectionLayerResponse, TripCollectionLinksResponse } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/** PLC-15/PLC-16: the lists a trip draws on, and their saved places for the trip map. */
|
||||
export const tripCollectionsApi = {
|
||||
list: (tripId: number, signal?: AbortSignal): Promise<TripCollectionLinksResponse> =>
|
||||
apiClient.get(`/trips/${tripId}/collections`, { signal }).then((r) => r.data),
|
||||
layer: (tripId: number, signal?: AbortSignal): Promise<TripCollectionLayerResponse> =>
|
||||
apiClient.get(`/trips/${tripId}/collections/places`, { signal }).then((r) => r.data),
|
||||
link: (tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> =>
|
||||
apiClient.post(`/trips/${tripId}/collections`, { collection_id: collectionId }).then((r) => r.data),
|
||||
unlink: (tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> =>
|
||||
apiClient.delete(`/trips/${tripId}/collections/${collectionId}`).then((r) => r.data),
|
||||
};
|
||||
@@ -50,6 +50,9 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
|
||||
// hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the
|
||||
// tabs and panels a trip switched off disappear for every member at once.
|
||||
'tripAddons:changed',
|
||||
// Linked lists (PLC-15/PLC-16): store/tripCollectionsStore (watchTripCollections) reads the
|
||||
// trip's linked lists and map layer again; content-free because each member's answer differs.
|
||||
'tripCollections:changed',
|
||||
// components/Roadtrip/useDayBoundaries reloads the shared boundaries.
|
||||
'roadtripBoundary:changed',
|
||||
// In-app notifications: hooks/useInAppNotificationListener, which also keeps
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { placeIdentitiesApi } from '../api/placeIdentities';
|
||||
import { OnlineOnlyError } from './onlineOnly';
|
||||
import { placeIdentitiesRepo } from './placeIdentitiesRepo';
|
||||
|
||||
// FE-REPO-PLACE-IDENTITIES-001 to FE-REPO-PLACE-IDENTITIES-002
|
||||
|
||||
const network = vi.hoisted(() => ({ offline: false }));
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline }));
|
||||
|
||||
beforeEach(() => {
|
||||
network.offline = false;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('placeIdentitiesRepo', () => {
|
||||
it('FE-REPO-PLACE-IDENTITIES-001: sends nothing without a connection', async () => {
|
||||
network.offline = true;
|
||||
const spies = (['link', 'unlink', 'duplicates', 'dismiss', 'merge', 'undoMerge'] as const).map((name) =>
|
||||
vi.spyOn(placeIdentitiesApi, name)
|
||||
);
|
||||
const refused = (call: Promise<unknown>) => expect(call).rejects.toBeInstanceOf(OnlineOnlyError);
|
||||
await refused(placeIdentitiesRepo.link({ uses: [{ kind: 'trip', id: 1 }] }));
|
||||
await refused(placeIdentitiesRepo.unlink({ kind: 'trip', id: 1 }));
|
||||
await refused(placeIdentitiesRepo.duplicates());
|
||||
await refused(placeIdentitiesRepo.dismiss('trip:1', 'list:2'));
|
||||
await refused(placeIdentitiesRepo.merge('trip:1', 'list:2'));
|
||||
await refused(placeIdentitiesRepo.undoMerge(3));
|
||||
for (const spy of spies) expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-REPO-PLACE-IDENTITIES-002: passes each call on and answers what the server said', async () => {
|
||||
const entry = { entry: null };
|
||||
vi.spyOn(placeIdentitiesApi, 'link').mockResolvedValue(entry);
|
||||
vi.spyOn(placeIdentitiesApi, 'unlink').mockResolvedValue(entry);
|
||||
const page = { duplicates: [], next_cursor: null };
|
||||
const duplicates = vi.spyOn(placeIdentitiesApi, 'duplicates').mockResolvedValue(page);
|
||||
const dismiss = vi.spyOn(placeIdentitiesApi, 'dismiss').mockResolvedValue({ success: true });
|
||||
vi.spyOn(placeIdentitiesApi, 'merge').mockResolvedValue({ merge_id: 4, entry: null });
|
||||
const undo = vi.spyOn(placeIdentitiesApi, 'undoMerge').mockResolvedValue({ success: true });
|
||||
const signal = new AbortController().signal;
|
||||
expect(await placeIdentitiesRepo.link({ uses: [{ kind: 'trip', id: 1 }] })).toBe(entry);
|
||||
expect(await placeIdentitiesRepo.unlink({ kind: 'trip', id: 1 })).toBe(entry);
|
||||
expect(await placeIdentitiesRepo.duplicates({ limit: 5 }, signal)).toBe(page);
|
||||
await placeIdentitiesRepo.dismiss('trip:1', 'list:2');
|
||||
expect(await placeIdentitiesRepo.merge('trip:1', 'list:2')).toEqual({ merge_id: 4, entry: null });
|
||||
await placeIdentitiesRepo.undoMerge(4);
|
||||
expect(duplicates).toHaveBeenCalledWith({ limit: 5 }, signal);
|
||||
expect(dismiss).toHaveBeenCalledWith('trip:1', 'list:2');
|
||||
expect(undo).toHaveBeenCalledWith(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import type {
|
||||
PlacesLibraryDuplicatesQueryInput,
|
||||
PlacesLibraryDuplicatesResponse,
|
||||
PlacesLibraryEntryResponse,
|
||||
PlacesLibraryLinkRequest,
|
||||
PlacesLibraryMergeResponse,
|
||||
PlacesLibraryUse,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { placeIdentitiesApi } from '../api/placeIdentities';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
/**
|
||||
* The user's own places in "All places" (D5/PLC-13). Online only, like the
|
||||
* library itself: they group trips and lists the server checks on every call,
|
||||
* and nothing of them is kept on the device.
|
||||
*/
|
||||
export const placeIdentitiesRepo = {
|
||||
async link(body: PlacesLibraryLinkRequest): Promise<PlacesLibraryEntryResponse> {
|
||||
requireOnline();
|
||||
return await placeIdentitiesApi.link(body);
|
||||
},
|
||||
|
||||
async unlink(use: PlacesLibraryUse): Promise<PlacesLibraryEntryResponse> {
|
||||
requireOnline();
|
||||
return await placeIdentitiesApi.unlink(use);
|
||||
},
|
||||
|
||||
async duplicates(
|
||||
query: PlacesLibraryDuplicatesQueryInput = {},
|
||||
signal?: AbortSignal
|
||||
): Promise<PlacesLibraryDuplicatesResponse> {
|
||||
requireOnline();
|
||||
return await placeIdentitiesApi.duplicates(query, signal);
|
||||
},
|
||||
|
||||
async dismiss(a: string, b: string): Promise<void> {
|
||||
requireOnline();
|
||||
await placeIdentitiesApi.dismiss(a, b);
|
||||
},
|
||||
|
||||
async merge(leading: string, other: string): Promise<PlacesLibraryMergeResponse> {
|
||||
requireOnline();
|
||||
return await placeIdentitiesApi.merge(leading, other);
|
||||
},
|
||||
|
||||
async undoMerge(mergeId: number): Promise<void> {
|
||||
requireOnline();
|
||||
await placeIdentitiesApi.undoMerge(mergeId);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { tripCollectionsApi } from '../api/tripCollections';
|
||||
import { OnlineOnlyError } from './onlineOnly';
|
||||
import { tripCollectionsRepo } from './tripCollectionsRepo';
|
||||
|
||||
// FE-REPO-TRIP-COLLECTIONS-001 to FE-REPO-TRIP-COLLECTIONS-002
|
||||
|
||||
const network = vi.hoisted(() => ({ offline: false }));
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline }));
|
||||
|
||||
beforeEach(() => {
|
||||
network.offline = false;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('tripCollectionsRepo', () => {
|
||||
it('FE-REPO-TRIP-COLLECTIONS-001: reads and writes only online', async () => {
|
||||
network.offline = true;
|
||||
const list = vi.spyOn(tripCollectionsApi, 'list');
|
||||
await expect(tripCollectionsRepo.list(4)).rejects.toBeInstanceOf(OnlineOnlyError);
|
||||
await expect(tripCollectionsRepo.layer(4)).rejects.toBeInstanceOf(OnlineOnlyError);
|
||||
await expect(tripCollectionsRepo.link(4, 9)).rejects.toBeInstanceOf(OnlineOnlyError);
|
||||
await expect(tripCollectionsRepo.unlink(4, 9)).rejects.toBeInstanceOf(OnlineOnlyError);
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-REPO-TRIP-COLLECTIONS-002: passes each call on', async () => {
|
||||
const links = { links: [], can_link: true };
|
||||
const list = vi.spyOn(tripCollectionsApi, 'list').mockResolvedValue(links);
|
||||
const layer = vi.spyOn(tripCollectionsApi, 'layer').mockResolvedValue({ places: [] });
|
||||
const link = vi.spyOn(tripCollectionsApi, 'link').mockResolvedValue(links);
|
||||
const unlink = vi.spyOn(tripCollectionsApi, 'unlink').mockResolvedValue(links);
|
||||
const signal = new AbortController().signal;
|
||||
expect(await tripCollectionsRepo.list(4, signal)).toBe(links);
|
||||
expect(await tripCollectionsRepo.layer(4, signal)).toEqual({ places: [] });
|
||||
expect(await tripCollectionsRepo.link(4, 9)).toBe(links);
|
||||
expect(await tripCollectionsRepo.unlink(4, 9)).toBe(links);
|
||||
expect(list).toHaveBeenCalledWith(4, signal);
|
||||
expect(layer).toHaveBeenCalledWith(4, signal);
|
||||
expect(link).toHaveBeenCalledWith(4, 9);
|
||||
expect(unlink).toHaveBeenCalledWith(4, 9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { TripCollectionLayerResponse, TripCollectionLinksResponse } from '@trek/shared';
|
||||
|
||||
import { tripCollectionsApi } from '../api/tripCollections';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
/**
|
||||
* The lists a trip draws on (PLC-15/PLC-16). Online only on purpose: who sees
|
||||
* which linked list is the server's answer for each member, and the lists
|
||||
* themselves are online only.
|
||||
*/
|
||||
export const tripCollectionsRepo = {
|
||||
async list(tripId: number, signal?: AbortSignal): Promise<TripCollectionLinksResponse> {
|
||||
requireOnline();
|
||||
return await tripCollectionsApi.list(tripId, signal);
|
||||
},
|
||||
|
||||
async layer(tripId: number, signal?: AbortSignal): Promise<TripCollectionLayerResponse> {
|
||||
requireOnline();
|
||||
return await tripCollectionsApi.layer(tripId, signal);
|
||||
},
|
||||
|
||||
async link(tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> {
|
||||
requireOnline();
|
||||
return await tripCollectionsApi.link(tripId, collectionId);
|
||||
},
|
||||
|
||||
async unlink(tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> {
|
||||
requireOnline();
|
||||
return await tripCollectionsApi.unlink(tripId, collectionId);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
// FE-STORE-TRIPCOLLECTIONS-001 to FE-STORE-TRIPCOLLECTIONS-003: the lists a trip draws on,
|
||||
// read per account, linked and unlinked, and read again on a push.
|
||||
import { waitFor } from '@testing-library/react';
|
||||
import type { TripCollectionLayerPlace, TripCollectionLink } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildUser } from '../../tests/helpers/factories';
|
||||
import { resetAllStores, seedStore } from '../../tests/helpers/store';
|
||||
import { addListener } from '../api/websocket';
|
||||
import { tripCollectionsRepo } from '../repo/tripCollectionsRepo';
|
||||
import { useAuthStore } from './authStore';
|
||||
import { tripCollectionsEntry, useTripCollectionsStore, watchTripCollections } from './tripCollectionsStore';
|
||||
|
||||
const link: TripCollectionLink = {
|
||||
collection_id: 9,
|
||||
name: 'Food',
|
||||
color: null,
|
||||
role: 'owner',
|
||||
place_count: 2,
|
||||
linked_by: 1,
|
||||
created_at: null,
|
||||
};
|
||||
const place: TripCollectionLayerPlace = {
|
||||
id: 3,
|
||||
collection_id: 9,
|
||||
name: 'Café',
|
||||
lat: 1,
|
||||
lng: 2,
|
||||
category: null,
|
||||
status: 'want',
|
||||
in_trip: false,
|
||||
trip_place_id: null,
|
||||
};
|
||||
const entry = (tripId: number) => tripCollectionsEntry(useTripCollectionsStore.getState(), tripId);
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.restoreAllMocks();
|
||||
vi.mocked(addListener).mockClear();
|
||||
useTripCollectionsStore.setState({ trips: {} });
|
||||
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
|
||||
});
|
||||
|
||||
describe('tripCollectionsStore', () => {
|
||||
it('FE-STORE-TRIPCOLLECTIONS-001: reads the links and the layer for the signed-in account', async () => {
|
||||
vi.spyOn(tripCollectionsRepo, 'list').mockResolvedValue({ links: [link], can_link: true });
|
||||
vi.spyOn(tripCollectionsRepo, 'layer').mockResolvedValue({ places: [place] });
|
||||
await useTripCollectionsStore.getState().load(4);
|
||||
expect(entry(4)).toEqual({ links: [link], canLink: true, layer: null });
|
||||
expect(await useTripCollectionsStore.getState().loadLayer(4)).toEqual([place]);
|
||||
expect(entry(4)?.layer).toEqual([place]);
|
||||
seedStore(useAuthStore, { user: buildUser({ id: 2 }) });
|
||||
expect(entry(4)).toBeUndefined();
|
||||
expect(tripCollectionsEntry(useTripCollectionsStore.getState(), null)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('FE-STORE-TRIPCOLLECTIONS-002: links and unlinks, reading the map layer again once it was asked for', async () => {
|
||||
vi.spyOn(tripCollectionsRepo, 'link').mockResolvedValue({ links: [link], can_link: true });
|
||||
vi.spyOn(tripCollectionsRepo, 'unlink').mockResolvedValue({ links: [], can_link: true });
|
||||
const layer = vi.spyOn(tripCollectionsRepo, 'layer').mockResolvedValue({ places: [place] });
|
||||
await useTripCollectionsStore.getState().link(4, 9);
|
||||
expect(entry(4)?.links).toEqual([link]);
|
||||
expect(layer).not.toHaveBeenCalled();
|
||||
await useTripCollectionsStore.getState().loadLayer(4);
|
||||
layer.mockResolvedValue({ places: [] });
|
||||
await useTripCollectionsStore.getState().unlink(4, 9);
|
||||
expect(entry(4)).toEqual({ links: [], canLink: true, layer: [] });
|
||||
});
|
||||
|
||||
it('FE-STORE-TRIPCOLLECTIONS-003: a push reads a held trip again and leaves others alone', async () => {
|
||||
const list = vi.spyOn(tripCollectionsRepo, 'list').mockResolvedValue({ links: [], can_link: false });
|
||||
vi.spyOn(tripCollectionsRepo, 'layer').mockResolvedValue({ places: [place] });
|
||||
useTripCollectionsStore.setState({ trips: { '1:4': { links: [link], canLink: true, layer: [] } } });
|
||||
const stop = watchTripCollections();
|
||||
const listener = vi.mocked(addListener).mock.calls[0][0] as (event: Record<string, unknown>) => void;
|
||||
listener({ type: 'tripCollections:changed', tripId: 5 });
|
||||
listener({ type: 'tripCollections:changed', tripId: 'x' });
|
||||
listener({ type: 'tripAddons:changed', tripId: 4 });
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
listener({ type: 'tripCollections:changed', tripId: 4 });
|
||||
await waitFor(() => expect(entry(4)).toEqual({ links: [], canLink: false, layer: [place] }));
|
||||
expect(list).toHaveBeenCalledWith(4);
|
||||
stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { TripCollectionLayerPlace, TripCollectionLink } from '@trek/shared';
|
||||
import { create } from 'zustand';
|
||||
|
||||
import { addListener, removeListener } from '../api/websocket';
|
||||
import { tripCollectionsRepo } from '../repo/tripCollectionsRepo';
|
||||
import { useAuthStore } from './authStore';
|
||||
|
||||
/**
|
||||
* The lists each trip draws on (PLC-15) and their saved places for the trip
|
||||
* map (PLC-16), as the server answered for the signed-in account. Keyed by
|
||||
* account and trip, because who sees which linked list is per person. A
|
||||
* `tripCollections:changed` push reads again whatever the store holds for that
|
||||
* trip, so a list linked or unlinked by another member shows up or goes away.
|
||||
*/
|
||||
|
||||
interface TripCollectionsEntry {
|
||||
links: TripCollectionLink[];
|
||||
canLink: boolean;
|
||||
/** The saved places of the linked lists for the map, or null while the map layer was never asked for. */
|
||||
layer: TripCollectionLayerPlace[] | null;
|
||||
}
|
||||
|
||||
interface TripCollectionsState {
|
||||
trips: Record<string, TripCollectionsEntry>;
|
||||
/** Reads the trip's linked lists. Online only; throws when the server refuses or there is no connection. */
|
||||
load: (tripId: number) => Promise<TripCollectionsEntry>;
|
||||
/** Reads the saved places of the linked lists for the map. Online only. */
|
||||
loadLayer: (tripId: number) => Promise<TripCollectionLayerPlace[]>;
|
||||
link: (tripId: number, collectionId: number) => Promise<void>;
|
||||
unlink: (tripId: number, collectionId: number) => Promise<void>;
|
||||
}
|
||||
|
||||
function keyOf(tripId: number): string {
|
||||
return `${useAuthStore.getState().user?.id ?? 'anon'}:${tripId}`;
|
||||
}
|
||||
|
||||
const EMPTY: TripCollectionsEntry = { links: [], canLink: false, layer: null };
|
||||
|
||||
export const useTripCollectionsStore = create<TripCollectionsState>((set, get) => {
|
||||
const put = (tripId: number, change: Partial<TripCollectionsEntry>): TripCollectionsEntry => {
|
||||
const key = keyOf(tripId);
|
||||
const entry = { ...(get().trips[key] ?? EMPTY), ...change };
|
||||
set((state) => ({ trips: { ...state.trips, [key]: entry } }));
|
||||
return entry;
|
||||
};
|
||||
/** After a link or unlink the map layer is read again, if the map asked for it. */
|
||||
const refreshLayer = async (tripId: number) => {
|
||||
if (get().trips[keyOf(tripId)]?.layer) await get().loadLayer(tripId);
|
||||
};
|
||||
|
||||
return {
|
||||
trips: {},
|
||||
|
||||
load: async (tripId) => {
|
||||
const { links, can_link } = await tripCollectionsRepo.list(tripId);
|
||||
return put(tripId, { links, canLink: can_link });
|
||||
},
|
||||
|
||||
loadLayer: async (tripId) => {
|
||||
const { places } = await tripCollectionsRepo.layer(tripId);
|
||||
put(tripId, { layer: places });
|
||||
return places;
|
||||
},
|
||||
|
||||
link: async (tripId, collectionId) => {
|
||||
const { links, can_link } = await tripCollectionsRepo.link(tripId, collectionId);
|
||||
put(tripId, { links, canLink: can_link });
|
||||
await refreshLayer(tripId);
|
||||
},
|
||||
|
||||
unlink: async (tripId, collectionId) => {
|
||||
const { links, can_link } = await tripCollectionsRepo.unlink(tripId, collectionId);
|
||||
put(tripId, { links, canLink: can_link });
|
||||
await refreshLayer(tripId);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
/** The trip's entry for the signed-in account, if the store holds one. */
|
||||
export function tripCollectionsEntry(
|
||||
state: TripCollectionsState,
|
||||
tripId: number | null | undefined
|
||||
): TripCollectionsEntry | undefined {
|
||||
return tripId == null ? undefined : state.trips[keyOf(tripId)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies `tripCollections:changed`: reads again the links (and the map layer,
|
||||
* when it was read) of a trip the store holds. The push carries nothing, since
|
||||
* the answer differs per member. Returns the function that stops listening.
|
||||
*/
|
||||
export function watchTripCollections(): () => void {
|
||||
const onEvent = (event: Record<string, unknown>) => {
|
||||
if (event?.type !== 'tripCollections:changed') return;
|
||||
const tripId = Number(event.tripId);
|
||||
if (!Number.isSafeInteger(tripId) || tripId < 1) return;
|
||||
const entry = tripCollectionsEntry(useTripCollectionsStore.getState(), tripId);
|
||||
if (!entry) return;
|
||||
const store = useTripCollectionsStore.getState();
|
||||
void store
|
||||
.load(tripId)
|
||||
.then(() => (entry.layer ? store.loadLayer(tripId) : undefined))
|
||||
.catch(() => {
|
||||
// Offline or refused: the store keeps the last answer until the next read.
|
||||
return undefined;
|
||||
});
|
||||
};
|
||||
addListener(onEvent);
|
||||
return () => removeListener(onEvent);
|
||||
}
|
||||
Reference in New Issue
Block a user