Compare commits

...

5 Commits

Author SHA1 Message Date
Mihir Motiyani 4e81ee7774 Merge pull request 'feat: show product photos and let staff upload them' (#33) from feat/product-images into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #33
2026-11-26 13:12:02 +05:30
mihir 8cd2145f06 feat: show product photos and let staff upload them
continuous-integration/drone/push Build is passing Details
Catalog cards show each product's main photo and product pages show the gallery. Admin catalog adds a Photos panel to upload (JPEG/PNG/WebP, 2 MiB, up to 8) and remove photos. Nginx allows the upload size on the new route.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:42:50 +05:30
Mihir Motiyani 10f795ebed Merge pull request 'feat: let customers create an account from the sign-in page' (#32) from feat/customer-registration into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #32
2026-11-26 01:15:00 +05:30
mihir bee6281dde feat: let customers create an account from the sign-in page
continuous-integration/drone/push Build is passing Details
Adds a sign-up mode to /workspace that calls POST /auth/register and adopts the returned session through the same checks as sign-in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 00:41:25 +05:30
Mihir Motiyani 2d8c162834 Merge pull request 'fix/staging-hardening' (#31) from fix/staging-hardening into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #31
2026-11-24 15:58:10 +05:30
14 changed files with 398 additions and 194 deletions

View File

@ -27,9 +27,9 @@ docker run --rm -p 8080:80 manicandles-frontend:uat
After the one-time [server setup](docs/STATIC-DEPLOYMENT.md), main-branch Drone pushes upload the checked static build over SSH and activate it through the existing Nginx HTTPS site. Readiness failure restores the previous release. Drone requires the `manicandles_deploy_key` secret. Feature branches run validation without uploading or activating a release.
Storefront list returns only id/name/slug; details return prices/attributes/groups. The API has no product-media fields, so catalog cards use a generic branded placeholder rather than assigning local photos to unknown records. Existing marketing imagery remains intact.
Storefront list returns id/name/slug and the main photo; details return prices/attributes/groups and all photos. Staff upload up to 8 JPEG/PNG/WebP photos per product (2 MiB each) under Admin catalog; products without photos show a branded placeholder. Existing marketing imagery remains intact.
Addresses, cart/checkout, orders, catalog, access, stock, coupons and pricing tools are available after sign-in. Public registration and procurement/production/B2B tools remain subsequent phases. There is no contact-message endpoint; simulated success was replaced with an availability notice. Newsletter signup awaits consent/messaging flows.
Addresses, cart/checkout, orders, catalog, access, stock, coupons and pricing tools are available after sign-in. Customers can create their own account at `/workspace` (requires the backend `/auth/register` endpoint). There is no contact-message endpoint; simulated success was replaced with an availability notice. Newsletter signup awaits consent/messaging flows.
See [delivery phases](docs/PHASES.md) and [UAT evidence](docs/UAT-RESULTS.md).

View File

@ -23,7 +23,7 @@ location /api/ {
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials;
location ~ "^/api/v1/(?:supplier-documents|b2b/artworks)/[0-9a-fA-F-]{36}/versions$" {
location ~ "^/api/v1/(?:(?:supplier-documents|b2b/artworks)/[0-9a-fA-F-]{36}/versions|products/[0-9a-fA-F-]{36}/images)$" {
client_max_body_size 3m;
proxy_pass https://manicandles-backend.midastix.com;
}

View File

@ -38,4 +38,4 @@ Record the active and previous build/commit release IDs before rollout. The SSH
## Operational limits
Pending intents exist only within the active browser session; reloading signs out and discards them. After interruption, inspect orders or the stock ledger before beginning a new intent. The backend currently has no live gateway/carrier, public registration or contact delivery. Staff catalog/role writes follow the backend's existing concurrency policy; coordinate overlapping administration edits. Never reinterpret finalized merchandise as proof of payment or fulfillment.
Pending intents exist only within the active browser session; reloading signs out and discards them. After interruption, inspect orders or the stock ledger before beginning a new intent. The backend currently has no live gateway/carrier or contact delivery; customer self-registration is available. Staff catalog/role writes follow the backend's existing concurrency policy; coordinate overlapping administration edits. Never reinterpret finalized merchandise as proof of payment or fulfillment.

View File

@ -23,7 +23,7 @@ server {
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials;
location ~ "^/api/v1/(?:supplier-documents|b2b/artworks)/[0-9a-fA-F-]{36}/versions$" {
location ~ "^/api/v1/(?:(?:supplier-documents|b2b/artworks)/[0-9a-fA-F-]{36}/versions|products/[0-9a-fA-F-]{36}/images)$" {
client_max_body_size 3m;
proxy_pass https://manicandles-backend.midastix.com;
}

View File

@ -4,7 +4,7 @@ import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import Skeleton from "@mui/material/Skeleton";
import { Flame } from "lucide-react";
import { listProducts } from "@/lib/api";
import { listProducts, productImageUrl } from "@/lib/api";
import { usePlatform } from "@/lib/platform";
import { ApiNotice } from "./ApiNotice";
import "@/pages/products.css";
@ -75,11 +75,21 @@ export function Catalog({
<article className="prod-card" key={product.id}>
<Link
href={`/products/${product.id}`}
className="prod-img-wrap catalog-placeholder"
className={`prod-img-wrap${product.images[0] ? "" : " catalog-placeholder"}`}
aria-label={`View ${product.name}`}
>
<Flame size={48} aria-hidden="true" />
<span>Mani Candles</span>
{product.images[0] ? (
<img
src={productImageUrl(organization, product.id, product.images[0].id)}
alt=""
loading="lazy"
/>
) : (
<>
<Flame size={48} aria-hidden="true" />
<span>Mani Candles</span>
</>
)}
</Link>
<div className="prod-info">
<h3 className="prod-name">

View File

@ -5,7 +5,15 @@ const productSummarySchema = z.object({
id: z.string().uuid(),
name: z.string(),
slug: z.string(),
images: z.array(z.object({ id: z.string().uuid() })).default([]),
});
export function productImageUrl(
organization: string,
productId: string,
imageId: string,
) {
return `/api/v1/storefront/${organization}/products/${productId}/images/${imageId}`;
}
export const productSchema = productSummarySchema.extend({
description: z.string(),
variants: z.array(
@ -235,6 +243,21 @@ export async function login(
}),
);
}
export async function register(
organizationId: string,
name: string,
email: string,
password: string,
) {
const organization = organizationSchema.parse(organizationId);
return parse(
sessionSchema,
await apiRequest("/auth/register", {
method: "POST",
body: { organizationId: organization, name, email, password },
}),
);
}
export async function getPrincipal(token: string) {
return parse(principalSchema, await apiRequest("/auth/me", { token }));
}

View File

@ -154,8 +154,26 @@ export const adminProductSummary = productInput
.pick({ name: true, slug: true })
.extend({ id: uuid, status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]) })
.strip();
export const productImage = z
.object({
id: uuid,
mimeType: z.enum(["image/jpeg", "image/png", "image/webp"]),
size: z.number().int().positive(),
})
.strip();
export const productImageAccept = "image/jpeg,image/png,image/webp";
export function prepareProductImage(file: FormDataEntryValue | null) {
if (!(file instanceof File) || !file.size) throw new Error("Choose a JPEG, PNG or WebP photo.");
if (file.size > 2 * 1024 * 1024) throw new Error("Choose a photo up to 2 MiB.");
if (!productImageAccept.split(",").includes(file.type))
throw new Error("Use a JPEG, PNG or WebP photo.");
const body = new FormData();
body.append("file", file);
return body;
}
export const adminProduct = adminProductSummary.extend({
description: z.string(),
images: z.array(productImage).default([]),
variants: z.array(variant),
groups: z.array(z.object({ group })),
});

View File

@ -18,6 +18,7 @@ import {
login,
organizationSchema,
parse,
register,
type Principal,
type Session,
} from "./api";
@ -29,6 +30,7 @@ const PlatformContext = createContext<{
principal: Principal | null;
scope: string;
signIn: (email: string, password: string) => Promise<void>;
signUp: (name: string, email: string, password: string) => Promise<void>;
signOut: () => Promise<void>;
notice: string;
clearSession: (notice?: string) => void;
@ -110,9 +112,15 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
/* The in-memory setting still works. */
}
}
async function signIn(email: string, password: string) {
function signIn(email: string, password: string) {
return adopt(() => login(organization, email, password));
}
function signUp(name: string, email: string, password: string) {
return adopt(() => register(organization, name, email, password));
}
async function adopt(start: () => ReturnType<typeof login>) {
const version = ++generation.current;
const next = await login(organization, email, password);
const next = await start();
try {
const me = await getPrincipal(next.accessToken);
if (
@ -247,6 +255,7 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
principal,
scope: principal ? `${principal.sessionId}:${accessRevision}` : "",
signIn,
signUp,
signOut,
notice,
clearSession,

View File

@ -12,6 +12,9 @@ import {
group,
groupInput,
money,
prepareProductImage,
productImage,
productImageAccept,
type AdminProduct,
uuid,
} from "@/lib/commerce";
@ -31,6 +34,8 @@ import {
} from "@/components/WorkspaceTools";
import { RecordSelection } from "@/components/RecordSelection";
import { ConfirmAction } from "@/components/ConfirmAction";
import { productImageUrl } from "@/lib/api";
import "./products.css";
function ProductForm({
item,
onSave,
@ -323,8 +328,10 @@ function Products() {
);
}
function ProductEditor({ id }: { id: string }) {
const { request, can } = usePlatform();
const { request, can, organization } = usePlatform();
const query = usePrivateQuery(`/products/${id}`, adminProduct);
const editable = (item: AdminProduct) =>
can("catalog.manage") && item.status !== "ARCHIVED";
const [editingVariant, setEditingVariant] = useState<
z.infer<typeof variant> | undefined
>();
@ -373,6 +380,53 @@ function ProductEditor({ id }: { id: string }) {
</>
)}
</Panel>
<Panel title="Photos">
{!item.images.length && <p>No photos yet. The first photo is shown on the catalog card.</p>}
{item.status !== "PUBLISHED" && item.images.length > 0 && (
<Alert severity="info">Previews appear after the product is published.</Alert>
)}
<div className="product-gallery">
{item.images.map((image, index) => (
<figure key={image.id}>
{item.status === "PUBLISHED" ? (
<img src={productImageUrl(organization, id, image.id)} alt={`${item.name}, photo ${index + 1}`} />
) : (
<p>Photo {index + 1}</p>
)}
<figcaption>
{index === 0 ? "Main photo · " : ""}
{image.mimeType.replace("image/", "").toUpperCase()}, {Math.ceil(image.size / 1024)} KB
{editable(item) && (
<ConfirmAction
label="Remove"
message={`Remove photo ${index + 1}? This cannot be undone.`}
onConfirm={async () => {
await request(`/products/${id}/images/${image.id}`, z.unknown(), { method: "DELETE" });
await query.refetch();
}}
/>
)}
</figcaption>
</figure>
))}
</div>
{editable(item) && item.images.length < 8 && (
<ActionForm
label="Upload photo"
read={(data) => prepareProductImage(data.get("file"))}
submit={async (body) => {
try {
await request(`/products/${id}/images`, productImage, { method: "POST", body });
} finally {
await query.refetch();
}
}}
>
<label htmlFor={`photo-${id}`}>Photo (JPEG, PNG or WebP, up to 2 MiB)</label>
<input id={`photo-${id}`} name="file" type="file" accept={productImageAccept} required />
</ActionForm>
)}
</Panel>
<Panel title="Variants">
<Table
head={["Variant", "SKU", "Price", "Active", "ID", "Action"]}

View File

@ -5,7 +5,7 @@ import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import Skeleton from "@mui/material/Skeleton";
import Chip from "@mui/material/Chip";
import { getProduct } from "@/lib/api";
import { getProduct, productImageUrl } from "@/lib/api";
import { usePlatform } from "@/lib/platform";
import { ApiNotice } from "@/components/ApiNotice";
import "./products.css";
@ -43,6 +43,18 @@ export default function ProductPage({ id }: { id: string }) {
</>
) : (
<div className="product-detail">
{query.data.images.length > 0 && (
<div className="product-gallery">
{query.data.images.map((image, index) => (
<img
key={image.id}
src={productImageUrl(organization, id, image.id)}
alt={`${query.data.name}, photo ${index + 1}`}
loading={index ? "lazy" : "eager"}
/>
))}
</div>
)}
<h1>{query.data.name}</h1>
<p className="product-description">
{query.data.description ||

View File

@ -11,20 +11,25 @@ import "./workspace.css";
import { WorkspaceNavigation } from "@/components/WorkspaceShell";
export default function WorkspacePage() {
const { organization, principal, signIn, signOut, notice } = usePlatform();
const { organization, principal, signIn, signUp, signOut, notice } =
usePlatform();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
const [creating, setCreating] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = event.currentTarget;
const fields = new FormData(form);
setBusy(true);
setError(null);
const name = String(fields.get("name") ?? "");
const email = String(fields.get("email"));
const password = String(fields.get("password"));
form.reset();
try {
await signIn(email, password);
await (creating
? signUp(name, email, password)
: signIn(email, password));
} catch (error) {
setError(error);
} finally {
@ -47,7 +52,7 @@ export default function WorkspacePage() {
<Container maxWidth="md">
<h1>Account Workspace</h1>
<p className="workspace-intro">
Sign in with your approved Mani Candles account.
Sign in, or create a customer account to shop.
</p>
<Paper variant="outlined" className="workspace-panel">
<ApiNotice error={error} />
@ -68,7 +73,7 @@ export default function WorkspacePage() {
))}
</ul>
) : (
<p>No permissions assigned. Contact your administrator.</p>
<p>Customer account. Use your cart, addresses and orders below.</p>
)}
<p className="workspace-intro">
Open a customer or administration tool below.
@ -89,11 +94,20 @@ export default function WorkspacePage() {
backend.
</Alert>
)}
{creating && (
<TextField
label="Full name"
name="name"
autoComplete="name"
required
inputProps={{ maxLength: 160 }}
/>
)}
<TextField
label="Email address"
name="email"
type="email"
autoComplete="username"
autoComplete={creating ? "email" : "username"}
required
inputProps={{ maxLength: 254 }}
/>
@ -101,16 +115,36 @@ export default function WorkspacePage() {
label="Password"
name="password"
type="password"
autoComplete="current-password"
autoComplete={creating ? "new-password" : "current-password"}
required
inputProps={{ maxLength: 128 }}
helperText={creating ? "At least 15 characters." : undefined}
inputProps={{ minLength: creating ? 15 : 1, maxLength: 128 }}
/>
<Button
variant="contained"
type="submit"
disabled={busy || !organization}
>
{busy ? "Signing in…" : "Sign in"}
{creating
? busy
? "Creating account…"
: "Create account"
: busy
? "Signing in…"
: "Sign in"}
</Button>
<Button
variant="text"
type="button"
disabled={busy}
onClick={() => {
setCreating(!creating);
setError(null);
}}
>
{creating
? "Already have an account? Sign in"
: "New customer? Create an account"}
</Button>
<small>
Sessions stay in memory. Reloading or closing this page requires

View File

@ -1,176 +1,176 @@
/* ─── products.css ───────────────────────────────────────── */
/* HERO */
.products-hero {
padding: 6rem 1.5rem;
background: var(--brand-card);
text-align: center;
}
.products-hero h1 {
font-family: var(--font-serif);
font-size: clamp(2.5rem, 6vw, 4rem);
color: var(--brand-purple);
margin-bottom: 1rem;
}
.products-hero p {
font-family: var(--font-sans);
font-size: 1.05rem;
color: var(--brand-muted);
line-height: 1.8;
max-width: 640px;
margin: 0 auto 2rem;
}
/* FILTERS */
.products-body {
padding: 5rem 1.5rem;
background: var(--brand-light-lavender);
}
.filter-bar {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 1rem;
margin-bottom: 4rem;
}
.filter-btn {
font-family: var(--font-display);
font-size: 0.72rem;
letter-spacing: 0.2em;
text-transform: uppercase;
padding: 0.5rem 1.5rem;
background: none;
border: none;
border-bottom: 2px solid transparent;
color: var(--brand-muted);
cursor: pointer;
transition: color 0.3s ease, border-color 0.3s ease;
}
.filter-btn:hover {
color: var(--brand-purple);
}
.filter-btn.active {
color: var(--brand-purple);
border-bottom-color: var(--brand-gold);
}
/* PRODUCT GRID */
.products-grid {
display: grid;
grid-template-columns: 1fr;
gap: 3rem 2rem;
max-width: 1280px;
margin: 0 auto;
}
@media (min-width: 640px) { .products-grid { grid-template-columns: 1fr 1fr; } }
@media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); } }
.prod-card {
display: flex;
flex-direction: column;
cursor: pointer;
}
.prod-img-wrap {
position: relative;
aspect-ratio: 4 / 5;
overflow: hidden;
background: var(--brand-card);
border: 1px solid var(--brand-border);
margin-bottom: 1.25rem;
}
.prod-img-wrap img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 1s ease;
}
.prod-card:hover .prod-img-wrap img {
transform: scale(1.05);
}
.prod-overlay {
position: absolute;
inset: 0;
background: rgba(91,30,140,0.3);
opacity: 0;
display: flex;
align-items: center;
justify-content: center;
backdrop-filter: blur(2px);
transition: opacity 0.5s ease;
}
.prod-card:hover .prod-overlay {
opacity: 1;
}
.prod-overlay-btn {
padding: 0.75rem 2rem;
background: var(--brand-light-lavender);
color: var(--brand-purple);
font-family: var(--font-display);
font-size: 0.72rem;
letter-spacing: 0.18em;
text-transform: uppercase;
border: none;
cursor: pointer;
transform: translateY(32px);
transition: transform 0.5s ease, background 0.3s ease, color 0.3s ease;
box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}
.prod-card:hover .prod-overlay-btn {
transform: translateY(0);
}
.prod-overlay-btn:hover {
background: var(--brand-gold);
color: #ffffff;
}
.prod-info {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.prod-name {
font-family: var(--font-serif);
font-size: 1.4rem;
color: var(--brand-purple);
margin-bottom: 0.25rem;
}
.prod-scent {
font-family: var(--font-sans);
font-size: 0.85rem;
color: var(--brand-muted);
line-height: 1.5;
margin-bottom: 0.75rem;
/* two-line clamp */
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.prod-price {
font-family: var(--font-sans);
font-weight: 500;
font-size: 1.05rem;
color: var(--brand-gold);
}
/* ─── products.css ───────────────────────────────────────── */
/* HERO */
.products-hero {
padding: 6rem 1.5rem;
background: var(--brand-card);
text-align: center;
}
.products-hero h1 {
font-family: var(--font-serif);
font-size: clamp(2.5rem, 6vw, 4rem);
color: var(--brand-purple);
margin-bottom: 1rem;
}
.products-hero p {
font-family: var(--font-sans);
font-size: 1.05rem;
color: var(--brand-muted);
line-height: 1.8;
max-width: 640px;
margin: 0 auto 2rem;
}
/* FILTERS */
.products-body {
padding: 5rem 1.5rem;
background: var(--brand-light-lavender);
}
.filter-bar {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 1rem;
margin-bottom: 4rem;
}
.filter-btn {
font-family: var(--font-display);
font-size: 0.72rem;
letter-spacing: 0.2em;
text-transform: uppercase;
padding: 0.5rem 1.5rem;
background: none;
border: none;
border-bottom: 2px solid transparent;
color: var(--brand-muted);
cursor: pointer;
transition: color 0.3s ease, border-color 0.3s ease;
}
.filter-btn:hover {
color: var(--brand-purple);
}
.filter-btn.active {
color: var(--brand-purple);
border-bottom-color: var(--brand-gold);
}
/* PRODUCT GRID */
.products-grid {
display: grid;
grid-template-columns: 1fr;
gap: 3rem 2rem;
max-width: 1280px;
margin: 0 auto;
}
@media (min-width: 640px) { .products-grid { grid-template-columns: 1fr 1fr; } }
@media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); } }
.prod-card {
display: flex;
flex-direction: column;
cursor: pointer;
}
.prod-img-wrap {
position: relative;
aspect-ratio: 4 / 5;
overflow: hidden;
background: var(--brand-card);
border: 1px solid var(--brand-border);
margin-bottom: 1.25rem;
}
.prod-img-wrap img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 1s ease;
}
.prod-card:hover .prod-img-wrap img {
transform: scale(1.05);
}
.prod-overlay {
position: absolute;
inset: 0;
background: rgba(91,30,140,0.3);
opacity: 0;
display: flex;
align-items: center;
justify-content: center;
backdrop-filter: blur(2px);
transition: opacity 0.5s ease;
}
.prod-card:hover .prod-overlay {
opacity: 1;
}
.prod-overlay-btn {
padding: 0.75rem 2rem;
background: var(--brand-light-lavender);
color: var(--brand-purple);
font-family: var(--font-display);
font-size: 0.72rem;
letter-spacing: 0.18em;
text-transform: uppercase;
border: none;
cursor: pointer;
transform: translateY(32px);
transition: transform 0.5s ease, background 0.3s ease, color 0.3s ease;
box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}
.prod-card:hover .prod-overlay-btn {
transform: translateY(0);
}
.prod-overlay-btn:hover {
background: var(--brand-gold);
color: #ffffff;
}
.prod-info {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.prod-name {
font-family: var(--font-serif);
font-size: 1.4rem;
color: var(--brand-purple);
margin-bottom: 0.25rem;
}
.prod-scent {
font-family: var(--font-sans);
font-size: 0.85rem;
color: var(--brand-muted);
line-height: 1.5;
margin-bottom: 0.75rem;
/* two-line clamp */
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.prod-price {
font-family: var(--font-sans);
font-weight: 500;
font-size: 1.05rem;
color: var(--brand-gold);
}
.catalog-placeholder { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:1rem; color:var(--brand-purple); background:var(--brand-card); }
.catalog-placeholder span { font-family:var(--font-script); font-size:2rem; }
@ -189,3 +189,7 @@
.variant-list dl>div { display:flex; flex-wrap:wrap; gap:.5rem; font-size:.9rem; }
.variant-list dt { font-weight:600; }
@media(max-width:480px) { .variant-list li { flex-direction:column; } .products-body { padding:3rem .5rem; } .catalog-search { flex-direction:column; } }
.product-gallery { display:grid; grid-template-columns:repeat(auto-fill, minmax(200px, 1fr)); gap:1rem; margin:1.5rem 0; }
.product-gallery img { width:100%; aspect-ratio:4 / 5; object-fit:cover; border:1px solid var(--brand-border); }
.product-gallery img:first-child { grid-column:1 / -1; max-height:520px; }

View File

@ -0,0 +1,24 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { productImageUrl, productSchema } from "../src/lib/api.ts";
import { adminProduct, prepareProductImage } from "../src/lib/commerce.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
const product = { id, name: "Rose", slug: "rose", description: "", variants: [], groups: [] };
test("product images default to none and keep their storefront order", () => {
assert.deepEqual(productSchema.parse(product).images, []);
assert.deepEqual(productSchema.parse({ ...product, images: [{ id }] }).images, [{ id }]);
assert.throws(() => productSchema.parse({ ...product, images: [{ id: "../x" }] }));
assert.equal(productImageUrl(id, id, id), `/api/v1/storefront/${id}/products/${id}/images/${id}`);
const admin = adminProduct.parse({ ...product, status: "DRAFT", images: [{ id, mimeType: "image/webp", size: 10 }] });
assert.equal(admin.images[0].mimeType, "image/webp");
});
test("photo uploads accept only JPEG, PNG or WebP up to 2 MiB", () => {
const body = prepareProductImage(new File(["x"], "a.jpg", { type: "image/jpeg" }));
assert.ok(body.get("file") instanceof File);
assert.throws(() => prepareProductImage(new File(["<svg/>"], "a.svg", { type: "image/svg+xml" })), /JPEG, PNG or WebP/);
assert.throws(() => prepareProductImage(new File([new Uint8Array(2 * 1024 * 1024 + 1)], "a.png", { type: "image/png" })), /2 MiB/);
assert.throws(() => prepareProductImage(null), /Choose/);
});

View File

@ -332,3 +332,19 @@ test("organization change cancels private scope and removes cached data", async
await waitFor(() => expect(h.result.current.scope).toBe(""));
expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]);
});
test("sign-up registers in the configured organization and adopts the new session", async () => {
const bodies: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/register")) {
bodies.push(JSON.parse(String(options?.body)));
return json(session, 201);
}
if (url.endsWith("/auth/me")) return json({ ...me, permissions: [] });
throw new Error(`Unexpected request ${url}`);
}));
const h = harness();
await act(() => h.result.current.signUp("Asha Buyer", "buyer@example.com", "a long enough password"));
expect(bodies).toEqual([{ organizationId: id, name: "Asha Buyer", email: "buyer@example.com", password: "a long enough password" }]);
expect(h.result.current.principal).toMatchObject({ userId: id, permissions: [] });
});