app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

selling-index.spec.ts (14297B)


      1 import { expect, test } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { svelte } from '@sveltejs/vite-plugin-svelte';
      4 import { fileURLToPath } from 'node:url';
      5 import { once } from 'node:events';
      6 import { writeFile } from 'node:fs/promises';
      7 import { WebSocketServer } from 'ws';
      8 import { createStaticHarness } from '../integration/harness/static.ts';
      9 import type * as Fixture from './harness/selling-index.ts';
     10 import type { NostrEvent } from 'applesauce-core/helpers';
     11 declare global {
     12   interface Window {
     13     hcp121: typeof Fixture;
     14     hcp121Fixture: Awaited<ReturnType<typeof Fixture.createFixture>>;
     15   }
     16 }
     17 let server: Awaited<ReturnType<typeof createStaticHarness>>,
     18   sockets: WebSocketServer,
     19   endpoint: string,
     20   bundle: string;
     21 let events: NostrEvent[] = [],
     22   effects = 0;
     23 test.beforeAll(async () => {
     24   server = await createStaticHarness();
     25   sockets = new WebSocketServer({
     26     host: '127.0.0.1',
     27     port: 0,
     28     maxPayload: 262144
     29   });
     30   await once(sockets, 'listening');
     31   const address = sockets.address();
     32   if (!address || typeof address === 'string') throw Error('loopback missing');
     33   endpoint = 'ws://127.0.0.1:' + address.port;
     34   sockets.on('connection', (socket) =>
     35     socket.on('message', (bytes) => {
     36       const raw = Buffer.isBuffer(bytes)
     37         ? bytes
     38         : Array.isArray(bytes)
     39           ? Buffer.concat(bytes)
     40           : Buffer.from(bytes);
     41       const frame = JSON.parse(raw.toString()) as unknown[];
     42       if (frame[0] === 'EVENT') {
     43         effects++;
     44         return;
     45       }
     46       if (frame[0] !== 'REQ') return;
     47       const filters = frame.slice(2) as {
     48         kinds?: number[];
     49         authors?: string[];
     50         ids?: string[];
     51         '#d'?: string[];
     52       }[];
     53       for (const event of events)
     54         if (
     55           filters.some(
     56             (filter) =>
     57               (!filter.kinds || filter.kinds.includes(event.kind)) &&
     58               (!filter.authors || filter.authors.includes(event.pubkey)) &&
     59               (!filter.ids || filter.ids.includes(event.id)) &&
     60               (!filter['#d'] ||
     61                 event.tags.some(
     62                   (tag) => tag[0] === 'd' && filter['#d']!.includes(tag[1])
     63                 ))
     64           )
     65         )
     66           socket.send(JSON.stringify(['EVENT', frame[1], event]));
     67       socket.send(JSON.stringify(['EOSE', frame[1]]));
     68     })
     69   );
     70   const built = await build({
     71     configFile: false,
     72     plugins: [svelte({ configFile: false })],
     73     resolve: { conditions: ['browser'] },
     74     logLevel: 'silent',
     75     build: {
     76       write: false,
     77       minify: false,
     78       lib: {
     79         entry: fileURLToPath(
     80           new URL('./harness/selling-index.ts', import.meta.url)
     81         ),
     82         name: 'hcp121',
     83         formats: ['iife']
     84       }
     85     }
     86   });
     87   const result = Array.isArray(built) ? built[0] : built;
     88   if (!('output' in result)) throw Error('actual fixture bundle missing');
     89   const chunks = result.output.filter((row) => row.type === 'chunk');
     90   expect(chunks).toHaveLength(1);
     91   bundle = chunks[0].code;
     92 });
     93 test.afterAll(async () => {
     94   for (const socket of sockets?.clients ?? []) socket.terminate();
     95   if (sockets)
     96     await new Promise<void>((resolve, reject) =>
     97       sockets.close((error) => (error ? reject(error) : resolve()))
     98     );
     99   await server?.close();
    100 });
    101 test.beforeEach(async ({ page }) => {
    102   events = [];
    103   effects = 0;
    104   await page.addInitScript((endpoint) => {
    105     const Native = window.WebSocket;
    106     window.WebSocket = class extends Native {
    107       constructor(url: string | URL, protocols?: string | string[]) {
    108         if (
    109           ![
    110             'wss://discovery.example.org',
    111             'wss://inbox.example.org',
    112             'wss://second.example.org'
    113           ].includes(new URL(url.toString()).origin)
    114         )
    115           throw Error('no live relay permission');
    116         super(endpoint, protocols);
    117       }
    118     };
    119   }, endpoint);
    120   await page.goto(server.url + '/search');
    121   await page.addScriptTag({ content: bundle });
    122 });
    123 test.afterEach(async ({ page }) => {
    124   await page.evaluate(async () => {
    125     await window.hcp121Fixture?.close();
    126   });
    127 });
    128 async function start(
    129   page: import('@playwright/test').Page,
    130   mode: 'empty' | 'retained' = 'retained'
    131 ) {
    132   const event = await page.evaluate(async (mode) => {
    133     window.hcp121Fixture = await window.hcp121.createFixture(mode);
    134     return window.hcp121Fixture.event;
    135   }, mode);
    136   if (event) events.push(event);
    137 }
    138 async function render(page: import('@playwright/test').Page) {
    139   await page.evaluate(() => window.hcp121Fixture.render());
    140 }
    141 test('HCP121 genuine empty workspace has a real List food link and omits empty panels', async ({
    142   page
    143 }) => {
    144   await start(page, 'empty');
    145   await render(page);
    146   const section = page.locator('#hcp121-selling');
    147   // Immediate DOM count supplies meaningful pre-producer RED without waiting
    148   // for a future link that the original AccountGate does not render.
    149   expect(
    150     await section.getByRole('link', { name: 'List food', exact: true }).count()
    151   ).toBe(1);
    152   await expect(section).toContainText('No listings yet.');
    153   for (const name of ['Needs attention', 'Drafts', 'Listings'])
    154     await expect(
    155       section.getByRole('heading', { name, exact: true })
    156     ).toHaveCount(0);
    157   await expect(
    158     section.getByRole('link', { name: 'List food', exact: true })
    159   ).toHaveAttribute('href', '/sell');
    160   expect(effects).toBe(0);
    161 });
    162 test('HCP121 unresolved original listing is one attention row without duplicate draft/listing and retains exact target detail', async ({
    163   page
    164 }) => {
    165   await start(page);
    166   const before = await page.evaluate(() => window.hcp121Fixture.records());
    167   const counts = await page.evaluate(() => window.hcp121Fixture.counts());
    168   await render(page);
    169   const section = page.locator('#hcp121-selling');
    170   await expect(
    171     section.getByRole('heading', { name: 'Needs attention', exact: true })
    172   ).toBeVisible();
    173   await expect(section.locator('article')).toHaveCount(1);
    174   await expect(
    175     section.getByRole('heading', { name: 'Drafts', exact: true })
    176   ).toHaveCount(0);
    177   await expect(
    178     section.getByRole('heading', { name: 'Listings', exact: true })
    179   ).toHaveCount(0);
    180   await section.getByText('Delivery details', { exact: true }).click();
    181   await expect(section).toContainText(
    182     'Relay acceptance recorded for 0 of 2 targets.'
    183   );
    184   await expect(section).toContainText(
    185     'Exact read-back recorded for 0 of 2 targets.'
    186   );
    187   expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
    188     before
    189   );
    190   expect((await page.evaluate(() => window.hcp121Fixture.counts())).signs).toBe(
    191     counts.signs
    192   );
    193   expect(effects).toBe(0);
    194   await writeFile(
    195     test.info().outputPath('hcp121-original-native-records.json'),
    196     JSON.stringify(before, null, 2)
    197   );
    198 });
    199 test('HCP121 explicit same-author reconnect reacquires original seller work without native mutation or publication', async ({
    200   page
    201 }) => {
    202   await start(page);
    203   const before = await page.evaluate(() => window.hcp121Fixture.records());
    204   const counts = await page.evaluate(() => window.hcp121Fixture.counts());
    205   await render(page);
    206   const section = page.locator('#hcp121-selling');
    207   await expect(section.locator('article')).toHaveCount(1);
    208   await page.evaluate(() => window.hcp121Fixture.reconnect());
    209   await expect(section.locator('article')).toHaveCount(1);
    210   await expect(
    211     section.getByRole('heading', { name: 'Needs attention', exact: true })
    212   ).toBeVisible();
    213   expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
    214     before
    215   );
    216   expect((await page.evaluate(() => window.hcp121Fixture.counts())).signs).toBe(
    217     counts.signs
    218   );
    219   expect(effects).toBe(0);
    220 });
    221 test('HCP121 changed proposed draft stays on its original attention row with exact saved values', async ({
    222   page
    223 }) => {
    224   await start(page);
    225   const draft = await page.evaluate(() =>
    226     window.hcp121Fixture.changeCapturedDraft()
    227   );
    228   const before = await page.evaluate(() => window.hcp121Fixture.records());
    229   await render(page);
    230   const section = page.locator('#hcp121-selling');
    231   await expect(
    232     section.getByRole('heading', { name: 'Needs attention', exact: true })
    233   ).toBeVisible();
    234   await expect(section.locator('article')).toHaveCount(1);
    235   await expect(
    236     section.getByRole('heading', { name: 'Drafts', exact: true })
    237   ).toHaveCount(0);
    238   await expect(
    239     section.getByRole('link', { name: 'Continue editing', exact: true })
    240   ).toHaveAttribute('href', '/selling/drafts/' + draft.id);
    241   expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
    242     before
    243   );
    244   expect(draft.form.title).toBe('Unfinished proposed carrots');
    245   expect(draft.form.description).toBe('');
    246   expect(effects).toBe(0);
    247 });
    248 
    249 test('HCP121 external own source stays visible and read-only with safe source-aware links', async ({
    250   page
    251 }) => {
    252   await start(page);
    253   const event = await page.evaluate(() => window.hcp121Fixture.external());
    254   events = event ? [event] : [];
    255   await page.evaluate(() => window.hcp121Fixture.settled());
    256   await render(page);
    257   const section = page.locator('#hcp121-selling');
    258   await expect(
    259     section.getByRole('heading', { name: 'Listings', exact: true })
    260   ).toBeVisible();
    261   await expect(section).toContainText('Read-only');
    262   await expect(
    263     section.getByRole('link', { name: 'Edit', exact: true })
    264   ).toHaveCount(0);
    265   await expect(
    266     section.getByRole('link', { name: 'View listing', exact: true })
    267   ).toHaveAttribute('href', /^\/products\/naddr1/);
    268   expect(effects).toBe(0);
    269 });
    270 test('HCP121 actual bounded remote-only own listing never becomes an adopted local source', async ({
    271   page
    272 }) => {
    273   await start(page, 'empty');
    274   events = [await page.evaluate(() => window.hcp121Fixture.remoteListing())];
    275   const before = await page.evaluate(() => window.hcp121Fixture.records());
    276   expect(before).toEqual({ drafts: [], operations: [] });
    277   await render(page);
    278   const section = page.locator('#hcp121-selling');
    279   await expect(
    280     section.getByRole('heading', { name: 'Listings', exact: true })
    281   ).toBeVisible();
    282   await expect(section).toContainText('Remote own eggs');
    283   await expect(section).toContainText('Bounded remote discovery');
    284   await expect(section).toContainText('Read-only');
    285   await expect(
    286     section.getByRole('link', { name: 'Edit', exact: true })
    287   ).toHaveCount(0);
    288   expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
    289     before
    290   );
    291   expect(effects).toBe(0);
    292 });
    293 
    294 test('HCP121 actual installed account switch retires original local rows without adopting foreign records', async ({
    295   page
    296 }) => {
    297   await start(page);
    298   await render(page);
    299   const section = page.locator('#hcp121-selling');
    300   await expect(section.locator('article')).toHaveCount(1);
    301   const before = await page.evaluate(() => window.hcp121Fixture.records());
    302   const next = await page.evaluate(() => window.hcp121Fixture.switchOwner());
    303   await expect(section.locator('article')).toHaveCount(0);
    304   await expect(section).toContainText(
    305     'The extension identity changed. Connect again to continue.'
    306   );
    307   await page.evaluate(() => window.hcp121Fixture.reconnect());
    308   await expect(section).toContainText('No listings yet.');
    309   await expect(section.getByText('Carrots', { exact: true })).toHaveCount(0);
    310   expect(next).not.toBe(events[0].pubkey);
    311   expect(await page.evaluate(() => window.hcp121Fixture.records())).toEqual(
    312     before
    313   );
    314   expect(effects).toBe(0);
    315 });
    316 
    317 test('HCP121 settled retained listing and unfinished draft preserve ordering values links and minimal controls', async ({
    318   page
    319 }) => {
    320   await start(page);
    321   await page.evaluate(() => window.hcp121Fixture.settled());
    322   const draft = await page.evaluate(() => window.hcp121Fixture.draft());
    323   await render(page);
    324   const section = page.locator('#hcp121-selling');
    325   await expect(
    326     section.getByRole('heading', { name: 'Drafts', exact: true })
    327   ).toBeVisible();
    328   await expect(
    329     section.getByRole('heading', { name: 'Listings', exact: true })
    330   ).toBeVisible();
    331   await expect(
    332     section.getByRole('link', { name: 'Continue editing', exact: true })
    333   ).toHaveAttribute('href', '/selling/drafts/' + draft.id);
    334   await expect(
    335     section.getByRole('link', { name: 'Edit', exact: true })
    336   ).toHaveAttribute('href', /^\/products\/naddr1.+\/edit$/);
    337   await expect(section).toContainText('Unfinished spinach');
    338   await expect(
    339     section.getByRole('heading', { name: 'Needs attention', exact: true })
    340   ).toHaveCount(0);
    341   const headings = await section
    342     .locator(':scope > .page > section > h2')
    343     .allTextContents();
    344   expect(headings).toEqual(['Drafts', 'Listings']);
    345   expect(await section.getByRole('checkbox').count()).toBe(0);
    346   expect(
    347     await section
    348       .getByText(/revenue|orders|inventory total|bulk|performance graph/i)
    349       .count()
    350   ).toBe(0);
    351   expect(effects).toBe(0);
    352 });
    353 test('HCP121 original partial delivery keeps acceptance distinct from readback and disconnect retires account rows', async ({
    354   page
    355 }) => {
    356   await start(page);
    357   await page.evaluate(() =>
    358     window.hcp121Fixture.observed('accepted', 0, false)
    359   );
    360   await render(page);
    361   const section = page.locator('#hcp121-selling');
    362   await section.getByText('Delivery details', { exact: true }).click();
    363   await expect(section).toContainText(
    364     'Relay acceptance recorded for 1 of 2 targets.'
    365   );
    366   await expect(section).toContainText(
    367     'Exact read-back recorded for 0 of 2 targets.'
    368   );
    369   await page.evaluate(() => window.hcp121Fixture.disconnect());
    370   await expect(section.locator('article')).toHaveCount(0);
    371   await expect(
    372     section.getByRole('link', { name: 'Edit', exact: true })
    373   ).toHaveCount(0);
    374   expect(effects).toBe(0);
    375 });
    376 for (const width of [320, 1024])
    377   test(`HCP121 ${width}px index has readable rows and separately operable visible links`, async ({
    378     page
    379   }) => {
    380     await page.setViewportSize({ width, height: 800 });
    381     await start(page);
    382     await render(page);
    383     const section = page.locator('#hcp121-selling');
    384     await expect(section.locator('article')).toHaveCount(1);
    385     await section.getByText('Delivery details', { exact: true }).click();
    386     const overflow = await page.evaluate(
    387       () => document.documentElement.scrollWidth > window.innerWidth
    388     );
    389     expect(overflow).toBe(false);
    390     expect(effects).toBe(0);
    391   });