Compare commits

...

3 Commits

Author SHA1 Message Date
Mihir Motiyani b4f61ff65e Merge pull request 'feat(catalog): add product photos' (#54) from feat/product-images into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #54
2026-11-26 13:11:17 +05:30
mihir 58d3f55b35 feat(catalog): add product photos
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/pr Build is passing Details
Staff with catalog.manage upload JPEG, PNG or WebP photos (2 MiB, 8 per
product, signature checked) and remove them. Published products serve
photos publicly from the storefront with one-day caching; storefront and
admin product views list photo IDs in upload order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 12:52:46 +05:30
Mihir Motiyani b81e8ddad2 Merge pull request 'feat(identity): add customer self-registration' (#53) from feat/customer-registration into main
continuous-integration/drone/push Build is passing Details
Reviewed-on: #53
2026-11-26 01:15:20 +05:30
13 changed files with 416 additions and 3 deletions

View File

@ -25,3 +25,13 @@ Stock quantities are integers. Opening stock is an adjustment. Adjustments requi
Availability equals on-hand stock minus unexpired active reservations. Stock row locks serialize changes. Expired holds stop consuming availability and cannot be committed. Release and commit are idempotent. Commit decrements stock and appends one ledger entry in the same transaction. A database trigger rejects ledger updates/deletes.
Existing system roles receive permissions through migration; custom roles require explicit grants. This phase covers finished goods. Checkout/orders and pricing snapshots follow in Phase 1D; procurement and production in Phase 2.
## Product photos
| Method | Path | Permission | Request / result |
| ------ | -------------------------------------------------------- | ----------------- | -------------------------------------------------------------------- |
| POST | /products/:id/images | catalog.manage | multipart `file`: JPEG, PNG or WebP up to 2 MiB → id, mimeType, size |
| DELETE | /products/:id/images/:imageId | catalog.manage | 204; 404 if missing or out of scope |
| GET | /storefront/:organizationId/products/:id/images/:imageId | Public; throttled | Image bytes for published products only; cached publicly for one day |
The file signature must match the declared type, so renamed scripts or SVGs are rejected. A product holds at most 8 photos, ordered by upload; the first is the main photo. Storefront lists include `images` with the main photo ID; storefront and admin product details include all photos. Images are immutable rows; replace one by deleting and uploading again. Archived products cannot change photos.

View File

@ -19,6 +19,7 @@ model Product {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Restrict)
variants ProductVariant[]
groups ProductGroup[]
images ProductImage[]
@@unique([organizationId, slug])
@@unique([id, organizationId])
@@index([organizationId, status, createdAt, id])

View File

@ -56,5 +56,6 @@
"20261008100000_capture_forecasts": "69b94ac61b9f1c3f47268d5586d7f73c4c392cabdd3049d01f34e5e033cac043",
"20261008110000_accounting_sources": "47b89e83291dbdf7b9fc7f1f25e7260a9f06bde0291ae2f7db01200e75eed396",
"20261008120000_batch_contribution": "4d6c577e6d59e9163c41253b828ed19729b76d881f21197f6b863c2f79233471",
"20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff"
"20261008130000_order_expiry_workflow": "e9ff103b0870e6998e2a906924a4f0394ac8ccbbe811b323d8485c3ee0dd92ff",
"20261126080000_product_images": "ce59729946f37d8958bb9f42974859b76cdaaa67e85491dc5a7eb3fa9e07d9eb"
}

View File

@ -0,0 +1,9 @@
CREATE TABLE product_images (
id UUID NOT NULL, product_id UUID NOT NULL, organization_id UUID NOT NULL,
mime_type VARCHAR(32) NOT NULL, sha256 CHAR(64) NOT NULL, size INTEGER NOT NULL,
content BYTEA NOT NULL, created_at TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT product_images_pkey PRIMARY KEY (id),
CONSTRAINT product_images_product_id_organization_id_fkey FOREIGN KEY (product_id, organization_id) REFERENCES products(id, organization_id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT product_image_valid CHECK (mime_type IN ('image/jpeg', 'image/png', 'image/webp') AND size BETWEEN 1 AND 2097152 AND octet_length(content) = size AND sha256 ~ '^[a-f0-9]{64}$')
);
CREATE INDEX product_images_product_id_created_at_id_idx ON product_images (product_id, created_at, id);

View File

@ -0,0 +1,13 @@
model ProductImage {
id String @id @default(uuid()) @db.Uuid
productId String @map("product_id") @db.Uuid
organizationId String @map("organization_id") @db.Uuid
mimeType String @map("mime_type") @db.VarChar(32)
sha256 String @db.Char(64)
size Int
content Bytes @db.ByteA
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3)
product Product @relation(fields: [productId, organizationId], references: [id, organizationId], onDelete: Cascade)
@@index([productId, createdAt, id])
@@map("product_images")
}

View File

@ -9,6 +9,11 @@ import { ProductsController } from './products.controller';
import { GroupsController } from './groups.controller';
import { StorefrontController } from './storefront.controller';
import { StorefrontGuard } from './storefront.guard';
import { ProductImageStore } from './product-image.store';
import {
ProductImagesController,
StorefrontImagesController,
} from './product-images.controller';
@Module({
imports: [DatabaseModule, IdentityModule],
@ -18,7 +23,14 @@ import { StorefrontGuard } from './storefront.guard';
GroupStore,
StorefrontStore,
StorefrontGuard,
ProductImageStore,
],
controllers: [
ProductsController,
GroupsController,
StorefrontController,
ProductImagesController,
StorefrontImagesController,
],
controllers: [ProductsController, GroupsController, StorefrontController],
})
export class CatalogModule {}

View File

@ -0,0 +1,38 @@
import { AppError } from '../common/errors/app-error';
import { fileDigest } from '../common/file-digest';
import type { UploadedDocument } from '../procurement/supplier-document-file';
export const MAX_PRODUCT_IMAGE_BYTES = 2 * 1024 * 1024;
export const MAX_PRODUCT_IMAGES = 8;
// The declared type must match the file's own signature, so a renamed script or SVG is rejected.
function signature(bytes: Buffer) {
if (bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')))
return 'image/png';
if (bytes.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex')))
return 'image/jpeg';
if (
bytes.subarray(0, 4).toString('latin1') === 'RIFF' &&
bytes.subarray(8, 12).toString('latin1') === 'WEBP'
)
return 'image/webp';
return null;
}
export function inspectProductImage(file?: UploadedDocument) {
const bytes = file?.buffer;
if (
!file ||
!bytes?.length ||
bytes.length > MAX_PRODUCT_IMAGE_BYTES ||
file.size !== bytes.length ||
signature(bytes) !== file.mimetype
)
throw new AppError('PRODUCT_IMAGE_INVALID');
return {
mimeType: file.mimetype,
sha256: fileDigest(bytes),
size: bytes.length,
content: Uint8Array.from(bytes),
};
}

View File

@ -0,0 +1,87 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { AccessStore } from '../identity/access.store';
import { recordAudit } from '../identity/audit';
import type { Principal } from '../identity/identity.types';
import { AppError } from '../common/errors/app-error';
import type { UploadedDocument } from '../procurement/supplier-document-file';
import { editableProduct } from './catalog.helpers';
import { inspectProductImage, MAX_PRODUCT_IMAGES } from './product-image-file';
export const imageSummary = {
id: true,
mimeType: true,
size: true,
createdAt: true,
} as const;
export const imageOrder = [
{ createdAt: 'asc' as const },
{ id: 'asc' as const },
];
@Injectable()
export class ProductImageStore {
constructor(
private readonly db: DatabaseService,
private readonly access: AccessStore,
) {}
add(actor: Principal, productId: string, file?: UploadedDocument) {
const image = inspectProductImage(file);
return this.access.mutate(actor, 'catalog.manage', async (tx) => {
await editableProduct(tx, actor.organizationId, productId);
// The product row lock serializes concurrent uploads against the quota.
await tx.$queryRaw`SELECT id FROM products WHERE id = ${productId}::uuid FOR UPDATE`;
if (
(await tx.productImage.count({ where: { productId } })) >=
MAX_PRODUCT_IMAGES
)
throw new AppError('PRODUCT_IMAGE_LIMIT');
const saved = await tx.productImage.create({
data: { ...image, productId, organizationId: actor.organizationId },
select: imageSummary,
});
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'product.image_added',
productId,
);
return saved;
});
}
remove(actor: Principal, productId: string, imageId: string) {
return this.access.mutate(actor, 'catalog.manage', async (tx) => {
await editableProduct(tx, actor.organizationId, productId);
const { count } = await tx.productImage.deleteMany({
where: { id: imageId, productId, organizationId: actor.organizationId },
});
if (!count) throw new AppError('PRODUCT_IMAGE_NOT_FOUND');
await recordAudit(
tx,
actor.organizationId,
actor.userId,
'product.image_removed',
productId,
);
});
}
// Public: only images of published products in the requested organization.
async publicImage(
organizationId: string,
productId: string,
imageId: string,
) {
const image = await this.db.productImage.findFirst({
where: {
id: imageId,
productId,
organizationId,
product: { status: 'PUBLISHED' },
},
select: { mimeType: true, content: true },
});
if (!image) throw new AppError('PRODUCT_IMAGE_NOT_FOUND');
return image;
}
}

View File

@ -0,0 +1,86 @@
import {
Controller,
Delete,
Get,
HttpCode,
Param,
ParseUUIDPipe,
Post,
Res,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiProduces } from '@nestjs/swagger';
import type { Response } from 'express';
import {
CurrentPrincipal,
Public,
RequirePermission,
} from '../identity/access.decorator';
import type { Principal } from '../identity/identity.types';
import type { UploadedDocument } from '../procurement/supplier-document-file';
import { MAX_PRODUCT_IMAGE_BYTES } from './product-image-file';
import { ProductImageStore } from './product-image.store';
import { StorefrontGuard } from './storefront.guard';
@Controller('products/:id/images')
export class ProductImagesController {
constructor(private readonly images: ProductImageStore) {}
@Post()
@RequirePermission('catalog.manage')
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
required: ['file'],
properties: { file: { type: 'string', format: 'binary' } },
},
})
@UseInterceptors(
FileInterceptor('file', {
limits: { fileSize: MAX_PRODUCT_IMAGE_BYTES + 1, files: 1, fields: 0 },
}),
)
add(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@UploadedFile() file?: UploadedDocument,
) {
return this.images.add(actor, id, file);
}
@Delete(':imageId')
@RequirePermission('catalog.manage')
@HttpCode(204)
remove(
@CurrentPrincipal() actor: Principal,
@Param('id', ParseUUIDPipe) id: string,
@Param('imageId', ParseUUIDPipe) imageId: string,
) {
return this.images.remove(actor, id, imageId);
}
}
@Public()
@UseGuards(StorefrontGuard)
@Controller('storefront/:organizationId/products/:id/images')
export class StorefrontImagesController {
constructor(private readonly images: ProductImageStore) {}
@Get(':imageId')
@ApiProduces('image/jpeg', 'image/png', 'image/webp')
async get(
@Param('organizationId', ParseUUIDPipe) organizationId: string,
@Param('id', ParseUUIDPipe) id: string,
@Param('imageId', ParseUUIDPipe) imageId: string,
@Res() response: Response,
) {
const image = await this.images.publicImage(organizationId, id, imageId);
response.setHeader('Content-Type', image.mimeType);
response.setHeader('X-Content-Type-Options', 'nosniff');
response.setHeader('Content-Security-Policy', 'sandbox');
// Image rows are never edited, so an ID always names the same bytes.
response.setHeader('Cache-Control', 'public, max-age=86400, immutable');
response.send(Buffer.from(image.content));
}
}

View File

@ -11,6 +11,7 @@ import {
validateGroups,
} from './catalog.helpers';
import type { CatalogQuery, ProductInput } from './catalog.schemas';
import { imageOrder, imageSummary } from './product-image.store';
@Injectable()
export class ProductStore {
@ -34,6 +35,7 @@ export class ProductStore {
include: {
variants: { orderBy: { id: 'asc' } },
groups: { include: { group: true } },
images: { orderBy: imageOrder, select: imageSummary },
},
});
}

View File

@ -3,6 +3,7 @@ import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { AppError } from '../common/errors/app-error';
import type { CatalogQuery } from './catalog.schemas';
import { imageOrder } from './product-image.store';
const storefrontView = {
id: true,
@ -21,6 +22,7 @@ const storefrontView = {
attributes: true,
},
},
images: { orderBy: imageOrder, select: { id: true } },
groups: {
select: {
group: { select: { id: true, name: true, slug: true, kind: true } },
@ -33,7 +35,12 @@ export class StorefrontStore {
list(organizationId: string, query: CatalogQuery) {
return this.db.product.findMany({
where: catalogWhere(organizationId, query, true),
select: { id: true, name: true, slug: true },
select: {
id: true,
name: true,
slug: true,
images: { orderBy: imageOrder, take: 1, select: { id: true } },
},
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: query.limit,
skip: query.offset,

View File

@ -10,6 +10,21 @@ export const COMMERCE_ERRORS = {
'Archived products cannot be edited',
'Archived product mutation rejected',
],
PRODUCT_IMAGE_NOT_FOUND: [
404,
'Product image not found',
'Scoped product image lookup failed',
],
PRODUCT_IMAGE_LIMIT: [
409,
'Product image limit reached',
'Product image quota exceeded',
],
PRODUCT_IMAGE_INVALID: [
400,
'Image must be a JPEG, PNG or WebP file up to 2 MiB',
'Product image upload bytes, size or type rejected',
],
VARIANT_NOT_FOUND: [
404,
'Product variant not found',

132
test/product-images.spec.ts Normal file
View File

@ -0,0 +1,132 @@
import { randomUUID } from 'node:crypto';
import { identityApp, type IdentityApp } from './helpers/identity-app';
import { secondActor, seedProduct } from './helpers/commerce';
const png = Buffer.concat([
Buffer.from('89504e470d0a1a0a', 'hex'),
Buffer.from('fake image body'),
]);
const webp = Buffer.concat([
Buffer.from('RIFF'),
Buffer.alloc(4),
Buffer.from('WEBPVP8 body'),
]);
describe('product images', () => {
let ctx: IdentityApp;
const auth = { type: 'bearer' as const };
const upload = (
productId: string,
bytes = png,
contentType = 'image/png',
token = ctx.token,
) =>
ctx
.api()
.post(`/api/v1/products/${productId}/images`)
.auth(token, auth)
.attach('file', bytes, { filename: 'photo', contentType });
const storefront = (path: string) =>
ctx
.api()
.get(`/api/v1/storefront/${ctx.owner.organizationId}/products${path}`);
beforeAll(async () => {
ctx = await identityApp();
}, 60000);
afterAll(async () => {
await ctx?.close();
});
beforeEach(async () => {
await ctx.clearLimits();
});
it('stores images and serves them publicly only for published products', async () => {
const { product } = await seedProduct(ctx);
const first = await upload(product.id).expect(201);
expect(first.body).toMatchObject({
mimeType: 'image/png',
size: png.length,
});
expect(first.body).not.toHaveProperty('content');
await upload(product.id, webp, 'image/webp').expect(201);
const path = `/${product.id}/images/${first.body.id}`;
await storefront(path).expect(404);
await ctx
.api()
.patch(`/api/v1/products/${product.id}/status`)
.auth(ctx.token, auth)
.send({ status: 'PUBLISHED' })
.expect(200);
const served = await storefront(path)
.buffer(true)
.parse((response, done) => {
const chunks: Buffer[] = [];
response.on('data', (chunk: Buffer) => chunks.push(chunk));
response.on('end', () => done(null, Buffer.concat(chunks)));
})
.expect(200);
expect(served.headers['content-type']).toBe('image/png');
expect(served.headers['cache-control']).toContain('public');
expect(Buffer.compare(served.body as Buffer, png)).toBe(0);
const detail = await storefront(`/${product.id}`).expect(200);
expect(detail.body.images).toHaveLength(2);
expect(detail.body.images[0]).toEqual({ id: first.body.id });
const list = await storefront('?limit=100').expect(200);
expect(
list.body.find((item: { id: string }) => item.id === product.id).images,
).toEqual([{ id: first.body.id }]);
await ctx
.api()
.get(`/api/v1/storefront/${randomUUID()}/products${path}`)
.expect(404);
});
it('rejects disguised, oversized and over-quota uploads', async () => {
const { product } = await seedProduct(ctx);
for (const [bytes, type] of [
[Buffer.from('<svg onload=alert(1)>'), 'image/png'],
[png, 'image/jpeg'],
[Buffer.from('<svg/>'), 'image/svg+xml'],
] as const)
expect(
(await upload(product.id, bytes, type).expect(400)).body.code,
).toBe('PRODUCT_IMAGE_INVALID');
const big = Buffer.concat([png, Buffer.alloc(2 * 1024 * 1024)]);
expect((await upload(product.id, big)).status).toBeGreaterThanOrEqual(400);
for (let index = 0; index < 8; index++)
await upload(product.id).expect(201);
expect((await upload(product.id).expect(409)).body.code).toBe(
'PRODUCT_IMAGE_LIMIT',
);
});
it('requires catalog.manage and organization scope to add or remove', async () => {
const { product } = await seedProduct(ctx);
const image = await upload(product.id).expect(201);
const customer = await secondActor(ctx);
await upload(product.id, png, 'image/png', customer.token).expect(403);
const foreign = await secondActor(ctx, false, ['catalog.manage']);
await upload(product.id, png, 'image/png', foreign.token).expect(404);
await ctx
.api()
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
.auth(foreign.token, auth)
.expect(404);
await ctx
.api()
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
.auth(ctx.token, auth)
.expect(204);
await ctx
.api()
.delete(`/api/v1/products/${product.id}/images/${image.body.id}`)
.auth(ctx.token, auth)
.expect(404);
const admin = await ctx
.api()
.get(`/api/v1/products/${product.id}`)
.auth(ctx.token, auth)
.expect(200);
expect(admin.body.images).toEqual([]);
});
});