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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "stockkit",
"version": "0.7.2",
"version": "0.7.3",
"private": true,
"type": "module",
"packageManager": "pnpm@11.10.0",
Expand Down
2 changes: 1 addition & 1 deletion src/app/dashboard/products/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
23 changes: 8 additions & 15 deletions src/app/dashboard/products/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }>;
Expand Down Expand Up @@ -291,25 +292,17 @@ export async function exportProductMovementsCsv(productId: string): Promise<Expo
const { movements, failed } = await readMovementPages(supabase, productId, null);
if (failed) return { success: false, error: 'Could not export history' };

const rows = movements.map((m) =>
[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;
}
4 changes: 2 additions & 2 deletions src/app/dashboard/products/export-history-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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.');
Expand Down
16 changes: 5 additions & 11 deletions src/app/dashboard/products/products-workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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';
Expand All @@ -67,6 +59,8 @@ export function ProductsWorkspace({
const [mobileDialog, setMobileDialog] = useState<MobileDialogState>(null);
const [filter, setFilter] = useState<Filter>('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.
Expand Down Expand Up @@ -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' });
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 11 additions & 20 deletions src/components/dashboard-tour.dom.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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,
}));
Expand All @@ -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(<DashboardTour exampleIndicator="trusted-example" seen={false} />);
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(<DashboardTour exampleIndicator="trusted-example" seen={false} />);
expect((props().steps as () => unknown[])()).toHaveLength(3);
});

it('passes seen through unchanged', () => {
Expand Down
17 changes: 3 additions & 14 deletions src/components/dashboard-tour.tsx
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -34,10 +22,11 @@ export function DashboardTour({
}) {
const pathname = usePathname();
const router = useRouter();
const isMobile = useMediaQuery('(max-width: 639px)');

return (
<SharedDashboardTour
steps={() => resolveTourSteps(exampleIndicator)}
steps={() => tourSteps(isMobile, exampleIndicator)}
seen={seen}
onFirstSeen={markTourSeen}
isHomeRoute={pathname === '/dashboard'}
Expand Down
Loading