From 83d18988d2b44086e48af255383b16dbeccf1d7d Mon Sep 17 00:00:00 2001 From: Clarence Date: Tue, 1 Dec 2026 23:48:50 +0800 Subject: [PATCH 1/2] refactor: adopt shared csv, download and media-query helpers from @merqo/ui Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 6 ++++ package.json | 2 +- src/app/dashboard/products/README.md | 2 +- src/app/dashboard/products/actions.ts | 23 +++++--------- .../products/export-history-button.tsx | 4 +-- .../dashboard/products/products-workspace.tsx | 16 +++------- src/components/dashboard-tour.dom.test.tsx | 31 +++++++------------ src/components/dashboard-tour.tsx | 17 ++-------- 8 files changed, 37 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f118fbd..10453ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [0.7.3] - 2026-12-01 + +### Changed + +- The stock-history CSV, its download and the viewport checks in the dashboard tour and products list now use the shared `@merqo/ui` helpers (`toCsv`, `downloadCsv`, `useMediaQuery`) instead of local copies. The downloaded CSV now starts with a UTF-8 byte-order mark so Excel reads non-ASCII text correctly. + ## [0.7.2] - 2026-12-01 ### Security diff --git a/package.json b/package.json index cc3d8ff..3cb224b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stockkit", - "version": "0.7.2", + "version": "0.7.3", "private": true, "type": "module", "packageManager": "pnpm@11.10.0", diff --git a/src/app/dashboard/products/README.md b/src/app/dashboard/products/README.md index c6ff15d..aad5f96 100644 --- a/src/app/dashboard/products/README.md +++ b/src/app/dashboard/products/README.md @@ -88,7 +88,7 @@ product's movement history. - `exportProductMovementsCsv(productId)`: Pro-only (`entitlement.csvExport`), returns the product's full stock-movement ledger as CSV text (`date,reason,delta,note` header + one row per movement) or a friendly - rejection on Free. Fields are RFC 4180-escaped (`csvField` helper) so a + rejection on Free. Fields are RFC 4180-escaped (`toCsv` from `@merqo/ui`, plus a local `csvNote` for whitespace- or newline-prefixed formulas) so a note containing a comma, double quote, or newline can't corrupt the output. The History tab's "Download CSV" button calls it. diff --git a/src/app/dashboard/products/actions.ts b/src/app/dashboard/products/actions.ts index f2eaae9..1ed2058 100644 --- a/src/app/dashboard/products/actions.ts +++ b/src/app/dashboard/products/actions.ts @@ -15,6 +15,7 @@ import { import { createServerClient } from '@/lib/supabase/server'; import type { Product, StockMovement } from '@/lib/types'; import { readVendorTier } from '@/lib/vendor-entitlement'; +import { toCsv } from '@merqo/ui'; import type { ActionResult } from '@merqo/ui/kit-api'; type SaveProductResult = ActionResult<{ productId: string }>; @@ -291,25 +292,17 @@ export async function exportProductMovementsCsv(productId: string): Promise - [m.created_at, m.reason, String(m.delta), csvNote(m.note ?? '')].map(csvField).join(',') + const csv = toCsv( + [ + ['date', 'reason', 'delta', 'note'], + ...movements.map((m) => [m.created_at, m.reason, m.delta, csvNote(m.note ?? '')]), + ], + { eol: '\n' } ); - const csv = ['date,reason,delta,note', ...rows].join('\n'); return { success: true, csv }; } -/** - * RFC 4180 field escaping: a field containing a comma, double-quote, or - * newline is wrapped in double quotes, with embedded double-quotes doubled. - * Applied uniformly to all CSV fields (not just the free-text ones) — - * simpler and safer than special-casing which columns need it. - */ -function csvField(value: string): string { - if (/[",\n\r]/.test(value)) return `"${value.replace(/"/g, '""')}"`; - return value; -} - -/** Keep user-controlled notes as spreadsheet text, including control-prefixed formulas. */ +// csvCell skips leading-whitespace and newline-prefixed formulas that notes can carry. function csvNote(value: string): string { return /^\s*[=+@-]|^[\t\r\n]/.test(value) ? `'${value}` : value; } diff --git a/src/app/dashboard/products/export-history-button.tsx b/src/app/dashboard/products/export-history-button.tsx index 31b7da2..95acf72 100644 --- a/src/app/dashboard/products/export-history-button.tsx +++ b/src/app/dashboard/products/export-history-button.tsx @@ -2,7 +2,7 @@ import { Lock } from 'lucide-react'; import { useState } from 'react'; -import { DownloadButton, downloadBlob } from '@merqo/ui'; +import { DownloadButton, downloadCsv } from '@merqo/ui'; import { Button } from '@merqo/ui/primitives'; import { exportProductMovementsCsv } from './actions'; @@ -22,7 +22,7 @@ export function ExportHistoryButton({ productId, locked = false }: Props) { setError(result.error); return; } - downloadBlob(new Blob([result.csv], { type: 'text/csv;charset=utf-8' }), 'stock-history.csv'); + downloadCsv('stock-history.csv', result.csv); } function onError() { setError('Could not download the CSV. Try again.'); diff --git a/src/app/dashboard/products/products-workspace.tsx b/src/app/dashboard/products/products-workspace.tsx index 96f6597..1fd0d45 100644 --- a/src/app/dashboard/products/products-workspace.tsx +++ b/src/app/dashboard/products/products-workspace.tsx @@ -5,7 +5,7 @@ import { useEffect, useState } from 'react'; import { productStatusFor } from '@/lib/stock'; import type { Product } from '@/lib/types'; -import { EmptyState, PageHeader, SearchField, SegmentedControl } from '@merqo/ui'; +import { EmptyState, PageHeader, SearchField, SegmentedControl, useMediaQuery } from '@merqo/ui'; import { Button, Dialog, @@ -36,14 +36,6 @@ const FILTER_OPTIONS = [ { value: 'archived', label: 'Archived' }, ] as const; -const DESKTOP_QUERY = '(min-width: 768px)'; - -// Tailwind's md breakpoint. Without matchMedia (tests, old browsers) the -// desktop two-pane flow is the safe default. -function isDesktop(): boolean { - return typeof window.matchMedia !== 'function' || window.matchMedia(DESKTOP_QUERY).matches; -} - function matchesFilter(product: Product, filter: Filter): boolean { const status = productStatusFor(product); if (filter === 'all') return status !== 'archived'; @@ -67,6 +59,8 @@ export function ProductsWorkspace({ const [mobileDialog, setMobileDialog] = useState(null); const [filter, setFilter] = useState('all'); const [query, setQuery] = useState(''); + // Negated so environments without matchMedia (tests) default to the desktop two-pane flow. + const isDesktop = !useMediaQuery('(max-width: 767px)'); // Server actions revalidatePath, which re-fetches this page's server data // and passes a fresh `initialProducts` array down — sync local state to it. @@ -108,12 +102,12 @@ export function ProductsWorkspace({ function selectProduct(productId: string) { setSelectedId(productId); setMode('view'); - if (!isDesktop()) setMobileDialog({ kind: 'product', productId }); + if (!isDesktop) setMobileDialog({ kind: 'product', productId }); } function startNew() { setMode('new'); - if (isDesktop()) setSelectedId(null); + if (isDesktop) setSelectedId(null); else setMobileDialog({ kind: 'new' }); } diff --git a/src/components/dashboard-tour.dom.test.tsx b/src/components/dashboard-tour.dom.test.tsx index 428da7b..ae3a81c 100644 --- a/src/components/dashboard-tour.dom.test.tsx +++ b/src/components/dashboard-tour.dom.test.tsx @@ -9,7 +9,7 @@ import { DashboardTour } from './dashboard-tour'; // @merqo/ui's own DashboardTour. This file's job is narrower: confirm // stockkit wires the right props through to it. const mocks = vi.hoisted(() => { - const state = { pathname: '/dashboard', lastProps: null as unknown }; + const state = { pathname: '/dashboard', lastProps: null as unknown, mobile: false }; return { state, push: vi.fn(), @@ -21,7 +21,10 @@ const mocks = vi.hoisted(() => { }; }); -vi.mock('@merqo/ui', () => ({ DashboardTour: mocks.SharedDashboardTour })); +vi.mock('@merqo/ui', () => ({ + DashboardTour: mocks.SharedDashboardTour, + useMediaQuery: () => mocks.state.mobile, +})); vi.mock('@/app/dashboard/tour-actions', () => ({ markTourSeen: mocks.markTourSeen, })); @@ -44,30 +47,18 @@ beforeEach(() => { vi.clearAllMocks(); mocks.state.pathname = '/dashboard'; mocks.state.lastProps = null; + mocks.state.mobile = false; }); describe('DashboardTour', () => { - it('passes a lazy steps resolver that resolves mobile-vs-desktop via matchMedia at start time', () => { + it('passes a steps resolver that picks the desktop or mobile list by viewport', () => { render(); expect(typeof props().steps).toBe('function'); + expect((props().steps as () => unknown[])()).toHaveLength(4); - // Not a bare array: the resolver must be called to get steps, and it - // must consult matchMedia at that point, not at render time. - const resolver = props().steps as () => { element: string }[]; - expect(resolver()).toHaveLength(4); // desktop list (jsdom matchMedia absent) - - const original = window.matchMedia; - window.matchMedia = ((query: string) => ({ - matches: true, - media: query, - addEventListener() {}, - removeEventListener() {}, - })) as unknown as typeof window.matchMedia; - try { - expect(resolver()).toHaveLength(3); // mobile list - } finally { - window.matchMedia = original; - } + mocks.state.mobile = true; + render(); + expect((props().steps as () => unknown[])()).toHaveLength(3); }); it('passes seen through unchanged', () => { diff --git a/src/components/dashboard-tour.tsx b/src/components/dashboard-tour.tsx index 7b4486a..18fb5a7 100644 --- a/src/components/dashboard-tour.tsx +++ b/src/components/dashboard-tour.tsx @@ -1,23 +1,11 @@ 'use client'; -import { DashboardTour as SharedDashboardTour } from '@merqo/ui'; +import { DashboardTour as SharedDashboardTour, useMediaQuery } from '@merqo/ui'; import { usePathname, useRouter } from 'next/navigation'; import { markTourSeen } from '@/app/dashboard/tour-actions'; import { tourSteps } from './tour-steps'; -// Matches Tailwind's `sm` breakpoint: below 640px the nav links collapse -// behind the burger, so the mobile step list spotlights that instead. -// Resolved lazily (only at tour-start time, per @merqo/ui's `steps` contract) -// rather than during render, so this stays SSR-safe. -function resolveTourSteps(exampleIndicator: string) { - const isMobile = - typeof window !== 'undefined' && - typeof window.matchMedia === 'function' && - window.matchMedia('(max-width: 639px)').matches; - return tourSteps(isMobile, exampleIndicator); -} - /** * stockkit's wiring for `@merqo/ui`'s `DashboardTour`: supplies this kit's * own step content, mark-seen action, and routing, while the tour mechanism @@ -34,10 +22,11 @@ export function DashboardTour({ }) { const pathname = usePathname(); const router = useRouter(); + const isMobile = useMediaQuery('(max-width: 639px)'); return ( resolveTourSteps(exampleIndicator)} + steps={() => tourSteps(isMobile, exampleIndicator)} seen={seen} onFirstSeen={markTourSeen} isHomeRoute={pathname === '/dashboard'} From fe775cda72bcd82cb4ae3e4bb9420ec6544703c0 Mon Sep 17 00:00:00 2001 From: Clarence Date: Wed, 2 Dec 2026 00:01:33 +0800 Subject: [PATCH 2/2] docs: note shared helper adoption in root and components READMEs Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 ++ src/components/README.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 83434d2..3df4345 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ spinner. The `/mfa` two-step sign-in form is the shared `MfaForm` from `@merqo/ui` behind a thin local adapter (`src/app/mfa/mfa-form.tsx`) that wires Supabase enrol and verify. +The stock-history CSV export, its file download and the viewport checks in the dashboard tour and products list use the shared `toCsv`, `downloadCsv` and `useMediaQuery` from `@merqo/ui`. + Archiving a product shows an Undo toast and saves when it closes; the product search has a clear button. The admin console now has a "Back to dashboard" link in its nav, uses the shared page header, and shows flat bordered panels and tiles; a vendor with no waste ratio shows "None" instead of a dash. Signed-in visits to the landing pages no longer return a 500. The public nav labels a signed-in account with the shared stall name the dashboard shows, read without creating a profile row. diff --git a/src/components/README.md b/src/components/README.md index 3395d2a..e004170 100644 --- a/src/components/README.md +++ b/src/components/README.md @@ -16,7 +16,7 @@ supplies stockkit's own step content (`tour-steps.ts`'s `tourSteps(isMobile)`, an ordered list each keyed to a `data-tour="..."` anchor elsewhere in the dashboard, with a mobile variant that spotlights the collapsed nav burger instead of the inline -links below Tailwind's `sm` breakpoint), the `markTourSeen` server +links below Tailwind's `sm` breakpoint, chosen with the shared `useMediaQuery`), the `markTourSeen` server action, and routing. Tour prose spells the brand lowercase ("stockkit"); only the logo mark is PascalCase. The first step's description embeds a `.tour-example` HTML snippet (styled in `src/app/globals.css`, rendered