This commit is contained in:
Aerilyn Weber 2026-05-14 18:57:57 +09:00
parent e396f5088c
commit a1801af63b
36 changed files with 4783 additions and 31 deletions

View file

@ -27,6 +27,7 @@
"@fastify/rate-limit": "^10.3.0",
"@fastify/swagger": "^9.7.0",
"@fastify/swagger-ui": "^5.2.5",
"@fastify/websocket": "^11.2.0",
"@meshitrack/shared": "*",
"awilix": "^13.0.3",
"fastify": "^5.8.4",

View file

@ -44,6 +44,9 @@ import freshnessRulesRoutes from './modules/freshness-rules/freshness-rules.rout
import productsRoutes from './modules/products/products.routes.js';
import mealPlansRoutes from './modules/meal-plans/meal-plans.routes.js';
import nutritionTargetsRoutes from './modules/nutrition-targets/nutrition-target.routes.js';
import websocket from '@fastify/websocket';
import pricesRoutes from './modules/prices/prices.routes.js';
import shoppingListsRoutes from './modules/shopping-lists/shopping-lists.routes.js';
export async function buildApp(opts: { logger?: boolean | object } = {}) {
const app = Fastify({
@ -109,6 +112,9 @@ export async function buildApp(opts: { logger?: boolean | object } = {}) {
await app.register(authPlugin);
await app.register(householdPlugin);
// WebSocket Plugin for persistent synchronizations
await app.register(websocket);
// Route modules
await app.register(healthRoutes);
await app.register(usersRoutes);
@ -129,6 +135,8 @@ export async function buildApp(opts: { logger?: boolean | object } = {}) {
await app.register(freshnessRulesRoutes);
await app.register(mealPlansRoutes);
await app.register(nutritionTargetsRoutes);
await app.register(pricesRoutes);
await app.register(shoppingListsRoutes);
// Global error handler
app.setErrorHandler((error, request, reply) => {

View file

@ -0,0 +1,162 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { PricesRepository } from './prices.repository.js';
const { mockSave, MockPriceRecordModel } = vi.hoisted(() => {
const mockSave = vi.fn();
function MockModel(this: { save: typeof mockSave }, data: unknown) {
Object.assign(this, data);
this.save = mockSave;
}
Object.assign(MockModel, {
findOne: vi.fn(),
find: vi.fn(),
findOneAndUpdate: vi.fn(),
insertMany: vi.fn(),
aggregate: vi.fn(),
});
return { mockSave, MockPriceRecordModel: MockModel };
});
vi.mock('../../schemas/price-record.schema.js', () => ({
PriceRecordModel: MockPriceRecordModel,
}));
const { PriceRecordModel } = await import('../../schemas/price-record.schema.js');
function makeChain(result: unknown = null) {
return {
sort: vi.fn().mockReturnThis(),
limit: vi.fn().mockReturnThis(),
lean: vi.fn().mockReturnThis(),
exec: vi.fn().mockResolvedValue(result),
};
}
describe(PricesRepository.name, () => {
let repo: PricesRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new PricesRepository();
});
describe('create', () => {
it('saves and returns new document toObject', async () => {
const data = { householdId: 'h1', productId: 'p1', productName: 'Apple', storeId: 's1', storeName: 'Store', price: 1, currency: 'USD', quantity: 1, unit: 'g', pricePerUnit: 1, date: new Date(), createdBy: 'u1' };
mockSave.mockResolvedValue({ toObject: () => ({ ...data, _id: 'id1' }) });
const result = await repo.create(data);
expect(mockSave).toHaveBeenCalled();
expect(result._id).toBe('id1');
});
});
describe('createMany', () => {
it('inserts multiple records and returns mapped toObjects', async () => {
const inputs = [{ price: 1 }, { price: 2 }];
const returns = inputs.map((x, idx) => ({ ...x, _id: `id${idx}`, toObject: function() { return this; } }));
vi.mocked(PriceRecordModel.insertMany).mockResolvedValue(returns as any);
const result = await repo.createMany(inputs as any);
expect(PriceRecordModel.insertMany).toHaveBeenCalledWith(inputs);
expect(result).toHaveLength(2);
expect(result[0]._id).toBe('id0');
});
});
describe('findByProduct', () => {
it('applies complex filters and pagination cursor decoding/encoding', async () => {
const baseFilter = { householdId: 'h1', productId: 'prod1' };
const startDate = new Date('2026-01-01').toISOString();
const endDate = new Date('2026-01-10').toISOString();
const cursorId = '507f1f77bcf86cd799439011';
const cursorStr = Buffer.from(cursorId).toString('base64');
const mockItems = [
{ _id: '607f1f77bcf86cd799439012', price: 10 },
{ _id: '607f1f77bcf86cd799439013', price: 12 }
];
const chain = makeChain(mockItems);
vi.mocked(PriceRecordModel.find).mockReturnValue(chain as any);
const result = await repo.findByProduct('h1', 'prod1', {
storeId: 'st1',
startDate,
endDate,
cursor: cursorStr,
limit: 2
});
expect(PriceRecordModel.find).toHaveBeenCalledWith({
householdId: 'h1',
productId: 'prod1',
storeId: 'st1',
date: {
$gte: new Date(startDate),
$lte: new Date(endDate),
},
_id: { $lt: cursorId }
});
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(false);
});
it('correctly indicates hasMore and generates next base64 cursor', async () => {
const mockItems = [
{ _id: '607f1f77bcf86cd799439011', price: 10 },
{ _id: '607f1f77bcf86cd799439012', price: 11 },
{ _id: '607f1f77bcf86cd799439013', price: 12 }
];
const chain = makeChain(mockItems);
vi.mocked(PriceRecordModel.find).mockReturnValue(chain as any);
const result = await repo.findByProduct('h1', 'prod1', { limit: 2 });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(true);
expect(result.pagination.cursor).toBe(Buffer.from('607f1f77bcf86cd799439012').toString('base64'));
});
});
describe('compareStores', () => {
it('runs group/aggregate queries ordered by deviance', async () => {
const mockAggResult = [
{ _id: 's1', storeName: 'Cheap', latestPrice: 10, latestPricePerUnit: 1, currency: 'USD', date: new Date() }
];
vi.mocked(PriceRecordModel.aggregate).mockReturnValue({
exec: vi.fn().mockResolvedValue(mockAggResult)
} as any);
const result = await repo.compareStores('h1', 'p1');
expect(PriceRecordModel.aggregate).toHaveBeenCalled();
expect(result).toHaveLength(1);
expect(result[0].storeId).toBe('s1');
expect(result[0].latestPricePerUnit).toBe(1);
});
});
describe('getLatestForProduct', () => {
it('queries latest pricing document ordered by date descending', async () => {
const chain = makeChain({ _id: 'pr1' });
vi.mocked(PriceRecordModel.findOne).mockReturnValue(chain as any);
await repo.getLatestForProduct('h1', 'p1', 's1');
expect(PriceRecordModel.findOne).toHaveBeenCalledWith({ householdId: 'h1', productId: 'p1', storeId: 's1' });
expect(chain.sort).toHaveBeenCalledWith({ date: -1 });
});
});
describe('getAnalytics', () => {
it('executes Promise.all parallel pipeline aggregations for periods, buckets, categories, and inflation', async () => {
const mockExec = vi.fn().mockResolvedValue([]);
vi.mocked(PriceRecordModel.aggregate).mockReturnValue({
exec: mockExec
} as any);
await repo.getAnalytics('h1');
// 4 explicit pipeline calls should have fired in Promise.all + inflation alert
expect(PriceRecordModel.aggregate).toHaveBeenCalledTimes(4);
});
});
});

View file

@ -0,0 +1,244 @@
import { PriceRecordModel } from '../../schemas/price-record.schema.js';
import type { PriceHistoryQueryInput } from '@meshitrack/shared';
export interface CreatePriceRecordData {
householdId: string;
productId: string;
productName: string;
storeId: string;
storeName: string;
price: number;
currency: string;
quantity: number;
unit: string;
pricePerUnit: number;
date: Date;
receiptImageUrl?: string;
notes?: string;
createdBy: string;
}
export class PricesRepository {
public async create(data: CreatePriceRecordData) {
const record = new PriceRecordModel(data);
const saved = await record.save();
return saved.toObject();
}
public async createMany(data: CreatePriceRecordData[]) {
const records = await PriceRecordModel.insertMany(data);
return records.map(r => r.toObject());
}
public async findByProduct(
householdId: string,
productId: string,
query: PriceHistoryQueryInput
) {
const filter: Record<string, unknown> = { householdId, productId };
if (query.storeId) filter['storeId'] = query.storeId;
if (query.startDate || query.endDate) {
const dateFilter: Record<string, Date> = {};
if (query.startDate) dateFilter['$gte'] = new Date(query.startDate);
if (query.endDate) dateFilter['$lte'] = new Date(query.endDate);
filter['date'] = dateFilter;
}
if (query.cursor) {
const id = Buffer.from(query.cursor, 'base64').toString();
filter['_id'] = { $lt: id };
}
const limit = query.limit || 20;
const items = await PriceRecordModel.find(filter)
.sort({ _id: -1 })
.limit(limit + 1)
.lean()
.exec();
const hasMore = items.length > limit;
const data = hasMore ? items.slice(0, limit) : items;
const cursor =
data.length > 0 ? Buffer.from(data[data.length - 1]._id.toString()).toString('base64') : null;
return { data, pagination: { cursor: hasMore ? cursor : null, hasMore } };
}
public async compareStores(householdId: string, productId: string) {
const results = await PriceRecordModel.aggregate([
{ $match: { householdId, productId } },
{ $sort: { storeId: 1, date: -1 } },
{
$group: {
_id: '$storeId',
storeName: { $first: '$storeName' },
latestPrice: { $first: '$price' },
latestPricePerUnit: { $first: '$pricePerUnit' },
currency: { $first: '$currency' },
date: { $first: '$date' },
},
},
{ $sort: { latestPricePerUnit: 1 } },
]).exec();
return results.map((r) => ({
storeId: r._id as string,
storeName: r.storeName as string,
latestPrice: r.latestPrice as number,
latestPricePerUnit: r.latestPricePerUnit as number,
currency: r.currency as string,
date: r.date as Date,
}));
}
public async getLatestForProduct(householdId: string, productId: string, storeId?: string) {
const filter: Record<string, unknown> = { householdId, productId };
if (storeId) filter['storeId'] = storeId;
return PriceRecordModel.findOne(filter).sort({ date: -1 }).lean().exec();
}
public async getAnalytics(householdId: string) {
const [spendingOverTime, averageBasketByStore, spendingByCategory] = await Promise.all([
// 1. Total Spending Over Time (by month)
PriceRecordModel.aggregate([
{ $match: { householdId } },
{
$group: {
_id: { $dateToString: { format: '%Y-%m', date: '$date' } },
total: { $sum: '$price' },
},
},
{ $sort: { _id: 1 } },
{ $project: { _id: 0, period: '$_id', total: 1 } },
]).exec(),
// 2. Average basket by store (grouping by Day + StoreId to simulate distinct trips)
PriceRecordModel.aggregate([
{ $match: { householdId } },
{
$group: {
_id: {
storeId: '$storeId',
day: { $dateToString: { format: '%Y-%m-%d', date: '$date' } },
},
storeName: { $first: '$storeName' },
tripTotal: { $sum: '$price' },
},
},
{
$group: {
_id: '$_id.storeId',
storeName: { $first: '$storeName' },
avgTotal: { $avg: '$tripTotal' },
tripCount: { $sum: 1 },
},
},
{ $sort: { avgTotal: -1 } },
{ $project: { _id: 0, storeId: '$_id', storeName: 1, avgTotal: 1, tripCount: 1 } },
]).exec(),
// 3. Spending by Category (Requires lookup join with Products)
PriceRecordModel.aggregate([
{ $match: { householdId } },
// Safeguard converting the dynamic string field to a valid ObjectId for proper joins
{
$addFields: {
prodObjId: { $toObjectId: '$productId' },
},
},
{
$lookup: {
from: 'products',
localField: 'prodObjId',
foreignField: '_id',
as: 'matchedProduct',
},
},
{ $unwind: { path: '$matchedProduct', preserveNullAndEmptyArrays: true } },
{
$group: {
_id: { $ifNull: ['$matchedProduct.category', 'other'] },
total: { $sum: '$price' },
avgPerItem: { $avg: '$price' },
},
},
{ $sort: { total: -1 } },
{ $project: { _id: 0, category: '$_id', total: 1, avgPerItem: 1 } },
]).exec(),
]);
// 4. Detect product inflation alerts (>10% price rise on last purchase compared to prior one)
const priceAlerts = await PriceRecordModel.aggregate([
{ $match: { householdId } },
{ $sort: { productId: 1, storeId: 1, date: -1 } },
{
$group: {
_id: { productId: '$productId', storeId: '$storeId' },
productName: { $first: '$productName' },
storeName: { $first: '$storeName' },
prices: { $push: '$pricePerUnit' },
dates: { $push: '$date' },
},
},
{ $match: { 'prices.1': { $exists: true } } },
{
$addFields: {
currentPrice: { $arrayElemAt: ['$prices', 0] },
previousPrice: { $arrayElemAt: ['$prices', 1] },
alertDate: { $arrayElemAt: ['$dates', 0] },
},
},
{
$addFields: {
changePercent: {
$multiply: [
{ $divide: [{ $subtract: ['$currentPrice', '$previousPrice'] }, '$previousPrice'] },
100,
],
},
},
},
{ $match: { changePercent: { $gt: 10 } } },
{
$project: {
_id: 0,
productId: '$_id.productId',
storeId: '$_id.storeId',
productName: 1,
storeName: 1,
previousPrice: 1,
currentPrice: 1,
changePercent: 1,
date: '$alertDate',
},
},
]).exec();
return {
spendingOverTime: spendingOverTime as { period: string; total: number }[],
averageBasketByStore: averageBasketByStore as {
storeId: string;
storeName: string;
avgTotal: number;
tripCount: number;
}[],
spendingByCategory: spendingByCategory as {
category: string;
total: number;
avgPerItem: number;
}[],
priceAlerts: priceAlerts as {
productId: string;
storeId: string;
productName: string;
storeName: string;
previousPrice: number;
currentPrice: number;
changePercent: number;
date: Date;
}[],
};
}
}

View file

@ -0,0 +1,182 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Fastify from 'fastify';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
vi.mock('jose', () => ({
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
jwtVerify: vi.fn().mockResolvedValue({
payload: {
sub: 'kc-1',
email: 'test@example.com',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: {},
key: {},
}),
}));
const mockCreate = vi.fn();
const mockCreateMany = vi.fn();
const mockFindByProduct = vi.fn();
const mockCompareStores = vi.fn();
const mockGetAnalytics = vi.fn();
vi.mock('./prices.repository.js', () => ({
PricesRepository: class {
create = mockCreate;
createMany = mockCreateMany;
findByProduct = mockFindByProduct;
compareStores = mockCompareStores;
getAnalytics = mockGetAnalytics;
},
}));
vi.mock('../products/products.repository.js', () => ({
ProductsRepository: class {
findById = vi.fn().mockResolvedValue({ name: 'Mock Product' });
findByIds = vi.fn().mockResolvedValue([{ _id: 'p1', name: 'Mock Product' }]);
},
}));
vi.mock('../stores/stores.repository.js', () => ({
StoresRepository: class {
findById = vi.fn().mockResolvedValue({ name: 'Mock Store' });
},
}));
vi.mock('../users/users.repository.js', () => ({
UsersRepository: class {
findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
},
}));
import authPlugin from '../../plugins/auth.plugin.js';
import householdPlugin from '../../plugins/household.plugin.js';
import usersRoutes from '../users/users.routes.js';
import pricesRoutes from './prices.routes.js';
describe('prices.routes', () => {
let app: any;
async function buildTestApp() {
const instance = Fastify({ logger: false });
instance.setValidatorCompiler(validatorCompiler);
instance.setSerializerCompiler(serializerCompiler);
await instance.register(fastifyAwilixPlugin, {
disposeOnClose: true,
disposeOnResponse: true,
strictBooleanEnforced: true,
});
await instance.register(authPlugin);
await instance.register(householdPlugin);
await instance.register(usersRoutes);
await instance.register(pricesRoutes);
await instance.ready();
return instance;
}
const authHeaders = { authorization: 'Bearer valid' };
beforeEach(async () => {
vi.clearAllMocks();
app = await buildTestApp();
});
afterEach(async () => {
if (app) await app.close();
});
function makeRecord(overrides = {}) {
return {
_id: 'r1',
householdId: 'hh1',
productId: 'p1',
productName: 'Apples',
storeId: 's1',
storeName: 'Store',
price: 10,
currency: 'USD',
quantity: 1,
unit: 'piece',
pricePerUnit: 10,
date: new Date(),
createdBy: 'kc-1',
createdAt: new Date(),
...overrides,
};
}
describe('POST /api/v1/households/:householdId/prices', () => {
it('records price and returns 201 response', async () => {
mockCreate.mockResolvedValue(makeRecord());
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/prices',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({
productId: 'p1',
storeId: 's1',
price: 5.99,
currency: 'USD',
quantity: 1,
unit: 'piece',
}),
});
if (res.statusCode === 500) {
console.log('ERROR PAYLOAD:', res.payload);
}
expect(res.statusCode).toBe(201);
expect(res.json().productName).toBe('Apples');
});
});
describe('GET /api/v1/households/:householdId/prices/history/:productId', () => {
it('returns a paginated envelope of historical pricing data', async () => {
mockFindByProduct.mockResolvedValue({
data: [makeRecord()],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/prices/history/p1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.pagination.hasMore).toBe(false);
});
});
describe('GET /api/v1/households/:householdId/prices/analytics', () => {
it('returns analytical metrics suite with properly formatted dates', async () => {
mockGetAnalytics.mockResolvedValue({
spendingOverTime: [],
averageBasketByStore: [],
spendingByCategory: [],
priceAlerts: [{ productId: 'p1', productName: 'Bread', storeId: 's1', storeName: 'Store', previousPrice: 2, currentPrice: 2.5, changePercent: 25, date: new Date() }],
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/prices/analytics',
headers: authHeaders,
});
if (res.statusCode === 500) {
console.log('ERROR PAYLOAD:', res.payload);
}
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.priceAlerts).toHaveLength(1);
expect(typeof body.priceAlerts[0].date).toBe('string');
});
});
});

View file

@ -0,0 +1,188 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
CreatePriceRecordSchema,
BulkPriceRecordInputSchema,
PriceHistoryQuerySchema,
PriceRecordResponseSchema,
PriceHistoryResponseSchema,
FoodStoreComparisonResponseSchema,
FoodSpendingAnalyticsResponseSchema,
} from '@meshitrack/shared';
import { PricesRepository } from './prices.repository.js';
import { PricesService } from './prices.service.js';
import { ProductsRepository } from '../products/products.repository.js';
import { StoresRepository } from '../stores/stores.repository.js';
type AnyPriceDoc = {
_id: string | { toString: () => string };
householdId: string;
productId: string;
productName: string;
storeId: string;
storeName: string;
price: number;
currency: string;
quantity: number;
unit: string;
pricePerUnit: number;
date: Date | string | { toISOString: () => string };
receiptImageUrl?: string;
notes?: string;
createdBy: string;
createdAt: Date | string | { toISOString: () => string };
};
function toIso(v: Date | string | { toISOString: () => string }): string {
if (typeof v === 'string') return v;
return v.toISOString();
}
function toPriceRecordResponse(rawDoc: unknown) {
const doc = rawDoc as AnyPriceDoc;
return {
_id: typeof doc._id === 'string' ? doc._id : doc._id.toString(),
householdId: doc.householdId,
productId: doc.productId,
productName: doc.productName,
storeId: doc.storeId,
storeName: doc.storeName,
price: doc.price,
currency: doc.currency,
quantity: doc.quantity,
unit: doc.unit,
pricePerUnit: doc.pricePerUnit,
date: toIso(doc.date),
...(doc.receiptImageUrl ? { receiptImageUrl: doc.receiptImageUrl } : {}),
...(doc.notes != null ? { notes: doc.notes } : {}),
createdBy: doc.createdBy,
createdAt: toIso(doc.createdAt),
};
}
declare module '@fastify/awilix' {
interface Cradle {
pricesRepository: PricesRepository;
pricesService: PricesService;
}
}
export default fp(
async (fastify) => {
// Register DI containers
fastify.diContainer.register({
pricesRepository: asClass(PricesRepository, { lifetime: Lifetime.SINGLETON }),
pricesService: asClass(PricesService, { lifetime: Lifetime.SINGLETON }),
productsRepository: asClass(ProductsRepository, { lifetime: Lifetime.SINGLETON }),
storesRepository: asClass(StoresRepository, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
const householdParams = z.object({ householdId: z.string() });
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/prices',
schema: {
params: householdParams,
body: CreatePriceRecordSchema,
response: { 201: PriceRecordResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('pricesService');
const record = await service.recordPrice(
request.body,
request.params.householdId,
request.user.keycloakId
);
return reply.status(201).send(toPriceRecordResponse(record));
},
});
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/prices/bulk',
schema: {
params: householdParams,
body: BulkPriceRecordInputSchema,
response: { 201: z.array(PriceRecordResponseSchema) },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('pricesService');
const records = await service.recordBulkPrices(
request.body,
request.params.householdId,
request.user.keycloakId
);
return reply.status(201).send(records.map(toPriceRecordResponse));
},
});
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/prices/history/:productId',
schema: {
params: householdParams.extend({ productId: z.string() }),
querystring: PriceHistoryQuerySchema,
response: { 200: PriceHistoryResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('pricesService');
const result = await service.getPriceHistory(
request.params.productId,
request.params.householdId,
request.query
);
return reply.send({
data: result.data.map(toPriceRecordResponse),
pagination: result.pagination,
});
},
});
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/prices/compare/:productId',
schema: {
params: householdParams.extend({ productId: z.string() }),
response: { 200: FoodStoreComparisonResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('pricesService');
const results = await service.compareStores(
request.params.productId,
request.params.householdId
);
return reply.send({
data: results.map((r) => ({
...r,
date: toIso(r.date),
})),
});
},
});
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/prices/analytics',
schema: {
params: householdParams,
response: { 200: FoodSpendingAnalyticsResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('pricesService');
const analytics = await service.getAnalytics(request.params.householdId);
return reply.send({
...analytics,
priceAlerts: analytics.priceAlerts.map((a) => ({ ...a, date: toIso(a.date) })),
});
},
});
},
{
name: 'prices-routes',
dependencies: ['auth-plugin'],
}
);

View file

@ -0,0 +1,102 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { PricesService } from './prices.service.js';
import { NotFoundError } from '../../common/errors.js';
describe('PricesService', () => {
let service: PricesService;
const mockPricesRepo = {
create: vi.fn(),
createMany: vi.fn(),
findByProduct: vi.fn(),
compareStores: vi.fn(),
getAnalytics: vi.fn(),
getLatestForProduct: vi.fn(),
};
const mockProductsRepo = {
findById: vi.fn(),
findByIds: vi.fn(),
};
const mockStoresRepo = {
findById: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
service = new PricesService({
pricesRepository: mockPricesRepo as any,
productsRepository: mockProductsRepo as any,
storesRepository: mockStoresRepo as any,
});
});
describe('recordPrice', () => {
it('calculates unit price and persists data on existing linkages', async () => {
mockProductsRepo.findById.mockResolvedValue({ name: 'Milk' });
mockStoresRepo.findById.mockResolvedValue({ name: 'Target' });
mockPricesRepo.create.mockResolvedValue({ _id: 'rec1' });
const result = await service.recordPrice(
{ productId: 'p1', storeId: 's1', price: 4, quantity: 2, unit: 'ml' as any, currency: 'USD' },
'hh1',
'u1'
);
expect(mockPricesRepo.create).toHaveBeenCalledWith(
expect.objectContaining({
productName: 'Milk',
storeName: 'Target',
pricePerUnit: 2,
})
);
expect(result._id).toBe('rec1');
});
it('throws NotFound if product is invalid', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(
service.recordPrice(
{ productId: 'p1', storeId: 's1', price: 1, quantity: 1, unit: 'g' as any, currency: 'USD' },
'hh1',
'u1'
)
).rejects.toThrow(NotFoundError);
});
});
describe('recordBulkPrices', () => {
it('ingests multiple mappings throwing notFound if one catalog match fails', async () => {
mockStoresRepo.findById.mockResolvedValue({ name: 'Aldi' });
mockProductsRepo.findByIds.mockResolvedValue([{ _id: 'p1', name: 'Bread' }]);
mockPricesRepo.createMany.mockImplementation(args => args);
const result = await service.recordBulkPrices(
{
storeId: 's1',
items: [{ productId: 'p1', price: 3, quantity: 1, unit: 'g' as any }],
},
'hh1',
'u1'
);
expect(mockPricesRepo.createMany).toHaveBeenCalled();
expect(result).toHaveLength(1);
expect(result[0].productName).toBe('Bread');
});
});
describe('estimatePrice', () => {
it('falls back to generic if requested store history is missing', async () => {
// First call (restricted to storeId): empty
mockPricesRepo.getLatestForProduct.mockResolvedValueOnce(null);
// Second call (generic): matches
mockPricesRepo.getLatestForProduct.mockResolvedValueOnce({ price: 12 });
const val = await service.estimatePrice('prod1', 'hh1', 'storeA');
expect(mockPricesRepo.getLatestForProduct).toHaveBeenCalledTimes(2);
expect(val).toBe(12);
});
});
});

View file

@ -0,0 +1,145 @@
import type { PricesRepository } from './prices.repository.js';
import type { ProductsRepository } from '../products/products.repository.js';
import type { StoresRepository } from '../stores/stores.repository.js';
import type {
CreatePriceRecordInput,
BulkPriceRecordInput,
PriceHistoryQueryInput,
} from '@meshitrack/shared';
import { NotFoundError } from '../../common/errors.js';
interface Deps {
pricesRepository: PricesRepository;
productsRepository: ProductsRepository;
storesRepository: StoresRepository;
}
export class PricesService {
private readonly pricesRepository: PricesRepository;
private readonly productsRepository: ProductsRepository;
private readonly storesRepository: StoresRepository;
public constructor({ pricesRepository, productsRepository, storesRepository }: Deps) {
this.pricesRepository = pricesRepository;
this.productsRepository = productsRepository;
this.storesRepository = storesRepository;
}
/**
* Validates entity existence, computes pricePerUnit, and persists record
*/
public async recordPrice(
data: CreatePriceRecordInput,
householdId: string,
userId: string
) {
const [product, store] = await Promise.all([
this.productsRepository.findById(data.productId, householdId),
this.storesRepository.findById(data.storeId, householdId),
]);
if (!product) throw new NotFoundError(`Product not found: ${data.productId}`);
if (!store) throw new NotFoundError(`Store not found: ${data.storeId}`);
const pricePerUnit = data.quantity > 0 ? data.price / data.quantity : data.price;
return this.pricesRepository.create({
householdId,
productId: data.productId,
productName: product.name as string,
storeId: data.storeId,
storeName: store.name as string,
price: data.price,
currency: data.currency,
quantity: data.quantity,
unit: data.unit,
pricePerUnit,
date: data.date ? new Date(data.date) : new Date(),
receiptImageUrl: data.receiptImageUrl,
notes: data.notes,
createdBy: userId,
});
}
/**
* Ingests a list of purchased products in a single transaction
*/
public async recordBulkPrices(
data: BulkPriceRecordInput,
householdId: string,
userId: string
) {
const store = await this.storesRepository.findById(data.storeId, householdId);
if (!store) throw new NotFoundError(`Store not found: ${data.storeId}`);
const recordDate = data.date ? new Date(data.date) : new Date();
const productIds = data.items.map((it) => it.productId);
const products = await this.productsRepository.findByIds(householdId, productIds);
const productMap = new Map(products.map((p) => [p._id.toString(), p]));
const creationPayloads = data.items.map((item) => {
const product = productMap.get(item.productId);
if (!product) {
throw new NotFoundError(`Product not found in catalog: ${item.productId}`);
}
const pricePerUnit = item.quantity > 0 ? item.price / item.quantity : item.price;
return {
householdId,
productId: item.productId,
productName: product.name as string,
storeId: data.storeId,
storeName: store.name as string,
price: item.price,
currency: 'USD', // Base fallback or pulled from household settings in future
quantity: item.quantity,
unit: item.unit,
pricePerUnit,
date: recordDate,
notes: item.notes,
createdBy: userId,
};
});
return this.pricesRepository.createMany(creationPayloads);
}
public async getPriceHistory(
productId: string,
householdId: string,
query: PriceHistoryQueryInput
) {
return this.pricesRepository.findByProduct(householdId, productId, query);
}
public async compareStores(productId: string, householdId: string) {
return this.pricesRepository.compareStores(householdId, productId);
}
public async getAnalytics(householdId: string) {
return this.pricesRepository.getAnalytics(householdId);
}
/**
* Retrieves the most recent price recorded for this item (optionally restricted to a store)
* to enable quick population of estimated basket subtotals on fresh lists.
*/
public async estimatePrice(
productId: string,
householdId: string,
storeId?: string
): Promise<number | null> {
const latest = await this.pricesRepository.getLatestForProduct(householdId, productId, storeId);
if (!latest) {
// If a specific store was requested but has no history, fall back to the generic latest across all stores
if (storeId) {
const genericLatest = await this.pricesRepository.getLatestForProduct(householdId, productId);
return genericLatest ? genericLatest.price : null;
}
return null;
}
return latest.price;
}
}

View file

@ -0,0 +1,164 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ShoppingListsRepository } from './shopping-lists.repository.js';
const { mockSave, MockShoppingListModel } = vi.hoisted(() => {
const mockSave = vi.fn();
function MockModel(this: { save: typeof mockSave }, data: unknown) {
Object.assign(this, data);
this.save = mockSave;
}
Object.assign(MockModel, {
findOne: vi.fn(),
find: vi.fn(),
findOneAndUpdate: vi.fn(),
findOneAndDelete: vi.fn(),
});
return { mockSave, MockShoppingListModel: MockModel };
});
vi.mock('../../schemas/shopping-list.schema.js', () => ({
ShoppingListModel: MockShoppingListModel,
}));
const { ShoppingListModel } = await import('../../schemas/shopping-list.schema.js');
function makeChain(result: unknown = null) {
return {
sort: vi.fn().mockReturnThis(),
lean: vi.fn().mockReturnThis(),
exec: vi.fn().mockResolvedValue(result),
};
}
describe(ShoppingListsRepository.name, () => {
let repo: ShoppingListsRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new ShoppingListsRepository();
});
describe('create', () => {
it('saves new shopping list model and returns simple object', async () => {
const doc = { _id: 'list1', name: 'Test List' };
mockSave.mockResolvedValue({ toObject: () => doc });
const result = await repo.create({ name: 'Test List', householdId: 'h1', createdBy: 'u1', status: 'active' });
expect(mockSave).toHaveBeenCalled();
expect(result._id).toBe('list1');
});
});
describe('list', () => {
it('queries lists for household ordered newest first', async () => {
const chain = makeChain([]);
vi.mocked(ShoppingListModel.find).mockReturnValue(chain as any);
await repo.list('h1');
expect(ShoppingListModel.find).toHaveBeenCalledWith({ householdId: 'h1' });
expect(chain.sort).toHaveBeenCalledWith({ createdAt: -1 });
});
});
describe('findById', () => {
it('queries distinct document by ID and householdId', async () => {
const chain = makeChain({ _id: 'list1' });
vi.mocked(ShoppingListModel.findOne).mockReturnValue(chain as any);
const result = await repo.findById('list1', 'h1');
expect(ShoppingListModel.findOne).toHaveBeenCalledWith({ _id: 'list1', householdId: 'h1' });
expect(result?._id).toBe('list1');
});
});
describe('findActiveByHousehold', () => {
it('queries specifically active/shopping lists sorted by update recency', async () => {
const chain = makeChain([]);
vi.mocked(ShoppingListModel.find).mockReturnValue(chain as any);
await repo.findActiveByHousehold('h1');
expect(ShoppingListModel.find).toHaveBeenCalledWith({
householdId: 'h1',
status: { $in: ['active', 'shopping'] }
});
expect(chain.sort).toHaveBeenCalledWith({ updatedAt: -1 });
});
});
describe('update', () => {
it('sets top level list variables atomically', async () => {
const chain = makeChain({});
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
await repo.update('list1', 'h1', { name: 'New Name' });
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'list1', householdId: 'h1' },
{ $set: { name: 'New Name' } },
{ new: true }
);
});
});
describe('delete', () => {
it('executes findOneAndDelete targeting target IDs', async () => {
const chain = makeChain({});
vi.mocked(ShoppingListModel.findOneAndDelete).mockReturnValue(chain as any);
await repo.delete('list1', 'h1');
expect(ShoppingListModel.findOneAndDelete).toHaveBeenCalledWith({ _id: 'list1', householdId: 'h1' });
});
});
// --- Atomic Subdocument Array Actions Tests ---
describe('addItem', () => {
it('executes $push operator targeting list subdocuments', async () => {
const chain = makeChain({});
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
const mockItem = { id: 'itm1', quantity: 1, unit: 'g', checked: false, addedToPantry: false };
await repo.addItem('list1', 'h1', mockItem as any);
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'list1', householdId: 'h1' },
{ $push: { items: mockItem } },
{ new: true }
);
});
});
describe('updateItem', () => {
it('maps partial payload to flattened positional $ keys', async () => {
const chain = makeChain({});
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
await repo.updateItem('list1', 'h1', 'itm1', { checked: true, actualPrice: 5.5 });
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'list1', householdId: 'h1', 'items.id': 'itm1' },
{
$set: {
'items.$.checked': true,
'items.$.actualPrice': 5.5
}
},
{ new: true }
);
});
});
describe('removeItem', () => {
it('executes $pull operator matching inner item tracking id', async () => {
const chain = makeChain({});
vi.mocked(ShoppingListModel.findOneAndUpdate).mockReturnValue(chain as any);
await repo.removeItem('list1', 'h1', 'itm1');
expect(ShoppingListModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'list1', householdId: 'h1' },
{ $pull: { items: { id: 'itm1' } } },
{ new: true }
);
});
});
});

View file

@ -0,0 +1,81 @@
import { ShoppingListModel } from '../../schemas/shopping-list.schema.js';
import type {
CreateShoppingListInput,
UpdateShoppingListInput,
ShoppingItem,
} from '@meshitrack/shared';
export class ShoppingListsRepository {
public async create(data: CreateShoppingListInput & { householdId: string; createdBy: string; status: string }) {
const list = new ShoppingListModel(data);
const saved = await list.save();
return saved.toObject();
}
public async list(householdId: string) {
return ShoppingListModel.find({ householdId })
.sort({ createdAt: -1 })
.lean()
.exec();
}
public async findById(id: string, householdId: string) {
return ShoppingListModel.findOne({ _id: id, householdId }).lean().exec();
}
public async findActiveByHousehold(householdId: string) {
return ShoppingListModel.find({ householdId, status: { $in: ['active', 'shopping'] } })
.sort({ updatedAt: -1 })
.lean()
.exec();
}
public async update(id: string, householdId: string, data: UpdateShoppingListInput) {
return ShoppingListModel.findOneAndUpdate(
{ _id: id, householdId },
{ $set: data },
{ new: true }
).lean().exec();
}
public async delete(id: string, householdId: string) {
return ShoppingListModel.findOneAndDelete({ _id: id, householdId }).lean().exec();
}
// --- Granular Atomic Subdocument Actions ---
public async addItem(id: string, householdId: string, item: ShoppingItem) {
return ShoppingListModel.findOneAndUpdate(
{ _id: id, householdId },
{ $push: { items: item } },
{ new: true }
).lean().exec();
}
public async updateItem(
id: string,
householdId: string,
itemId: string,
updates: Partial<ShoppingItem>
) {
const setUpdates: Record<string, unknown> = {};
for (const [key, val] of Object.entries(updates)) {
// Flatten parameters mapping them precisely to the positional positional matched index
setUpdates[`items.$.${key}`] = val;
}
return ShoppingListModel.findOneAndUpdate(
{ _id: id, householdId, 'items.id': itemId },
{ $set: setUpdates },
{ new: true }
).lean().exec();
}
public async removeItem(id: string, householdId: string, itemId: string) {
return ShoppingListModel.findOneAndUpdate(
{ _id: id, householdId },
{ $pull: { items: { id: itemId } } },
{ new: true }
).lean().exec();
}
}

View file

@ -0,0 +1,211 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Fastify from 'fastify';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';
vi.mock('jose', () => ({
createRemoteJWKSet: vi.fn(() => 'mock-jwks'),
jwtVerify: vi.fn().mockResolvedValue({
payload: {
sub: 'kc-1',
email: 'test@example.com',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: {},
key: {},
}),
}));
const mockList = vi.fn();
const mockFindById = vi.fn();
const mockCreate = vi.fn();
const mockUpdate = vi.fn();
const mockDelete = vi.fn();
const mockAddItem = vi.fn();
const mockUpdateItem = vi.fn();
const mockRemoveItem = vi.fn();
vi.mock('./shopping-lists.repository.js', () => ({
ShoppingListsRepository: class {
list = mockList;
findById = mockFindById;
create = mockCreate;
update = mockUpdate;
delete = mockDelete;
addItem = mockAddItem;
updateItem = mockUpdateItem;
removeItem = mockRemoveItem;
},
}));
vi.mock('../meal-plans/shopping-gap.service.js', () => ({
ShoppingGapService: class {
calculateGap = vi.fn().mockResolvedValue({ missingItems: [] });
},
}));
vi.mock('../pantry/pantry.service.js', () => ({
PantryService: class {
create = vi.fn().mockResolvedValue({ _id: 'pant1' });
},
}));
vi.mock('../products/products.repository.js', () => ({
ProductsRepository: class {
findById = vi.fn().mockResolvedValue({ category: 'dairy' });
},
}));
vi.mock('../prices/prices.service.js', () => ({
PricesService: class {
estimatePrice = vi.fn().mockResolvedValue(5.0);
recordPrice = vi.fn().mockResolvedValue({});
compareStores = vi.fn().mockResolvedValue([]);
},
}));
vi.mock('../meal-plans/meal-plans.repository.js', () => ({
MealPlanRepository: class {
findById = vi.fn().mockResolvedValue({ _id: 'mp1', weekStartDate: new Date() });
update = vi.fn().mockResolvedValue({});
},
}));
vi.mock('../users/users.repository.js', () => ({
UsersRepository: class {
findByKeycloakId = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
},
}));
import authPlugin from '../../plugins/auth.plugin.js';
import householdPlugin from '../../plugins/household.plugin.js';
import usersRoutes from '../users/users.routes.js';
import shoppingListsRoutes from './shopping-lists.routes.js';
describe('shopping-lists.routes', () => {
let app: any;
async function buildTestApp() {
const instance = Fastify({ logger: false });
instance.setValidatorCompiler(validatorCompiler);
instance.setSerializerCompiler(serializerCompiler);
await instance.register(fastifyAwilixPlugin, {
disposeOnClose: true,
disposeOnResponse: true,
strictBooleanEnforced: true,
});
await instance.register(authPlugin);
await instance.register(householdPlugin);
await instance.register(usersRoutes);
await instance.register(shoppingListsRoutes);
await instance.ready();
return instance;
}
const authHeaders = { authorization: 'Bearer valid' };
beforeEach(async () => {
vi.clearAllMocks();
app = await buildTestApp();
});
afterEach(async () => {
if (app) await app.close();
});
function makeShoppingList(overrides = {}) {
return {
_id: 'list1',
householdId: 'hh1',
name: 'Weekly Checklist',
items: [],
status: 'active',
createdBy: 'kc-1',
createdAt: new Date(),
updatedAt: new Date(),
...overrides,
};
}
describe('GET /api/v1/households/:householdId/shopping-lists', () => {
it('returns all lists belonging to household', async () => {
mockList.mockResolvedValue([makeShoppingList()]);
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/shopping-lists',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json()).toHaveLength(1);
});
});
describe('POST /api/v1/households/:householdId/shopping-lists', () => {
it('persists metadata and returns 201 response', async () => {
mockCreate.mockImplementation(arg => Promise.resolve({ ...arg, _id: 'newListA', createdAt: new Date(), updatedAt: new Date() }));
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/shopping-lists',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({
name: 'Costco Run',
items: []
}),
});
expect(res.statusCode).toBe(201);
expect(res.json().name).toBe('Costco Run');
});
});
describe('POST /api/v1/households/:householdId/shopping-lists/:id/items', () => {
it('adds new checklist subdocument item generating tracking UUIDs', async () => {
mockFindById.mockResolvedValue(makeShoppingList());
const updated = makeShoppingList({
items: [{ id: 'itemuuid123', productId: 'p1', quantity: 1, unit: 'piece', checked: false, addedToPantry: false }]
});
mockAddItem.mockResolvedValue(updated);
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/shopping-lists/list1/items',
headers: { ...authHeaders, 'content-type': 'application/json' },
body: JSON.stringify({
productId: 'p1',
quantity: 1,
unit: 'piece'
}),
});
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body.items).toHaveLength(1);
expect(body.items[0].productId).toBe('p1');
});
});
describe('POST /api/v1/households/:householdId/shopping-lists/:id/sync-to-pantry', () => {
it('executes batch synchronized promotions resulting in completed summaries', async () => {
const populatedList = makeShoppingList({
items: [{ id: 'itemA', productId: 'p1', checked: true, addedToPantry: false, quantity: 1, unit: 'piece' }]
});
mockFindById.mockResolvedValue(populatedList);
mockUpdateItem.mockResolvedValue({});
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/shopping-lists/list1/sync-to-pantry',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.addedCount).toBe(1);
});
});
});

View file

@ -0,0 +1,376 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import type { WebSocket } from 'ws';
import {
CreateShoppingListSchema,
UpdateShoppingListSchema,
AddShoppingItemSchema,
UpdateShoppingItemSchema,
ShoppingListResponseSchema,
ShoppingListSyncToPantryResponseSchema,
BasketStoreComparisonResponseSchema,
} from '@meshitrack/shared';
import { ShoppingListsRepository } from './shopping-lists.repository.js';
import { ShoppingListsService } from './shopping-lists.service.js';
import { ShoppingGapService } from '../meal-plans/shopping-gap.service.js';
import { PantryService } from '../pantry/pantry.service.js';
import { ProductsRepository } from '../products/products.repository.js';
import { PricesService } from '../prices/prices.service.js';
import { MealPlanRepository } from '../meal-plans/meal-plans.repository.js';
import { PantryRepository } from '../pantry/pantry.repository.js';
import { RecipesRepository } from '../recipes/recipes.repository.js';
import { StoresRepository } from '../stores/stores.repository.js';
import { PricesRepository } from '../prices/prices.repository.js';
// Memory track for live concurrent websocket clients per active list session
const activeListSockets = new Map<string, Set<WebSocket>>();
function broadcastToList(listId: string, excludeSocket: WebSocket, message: any) {
const set = activeListSockets.get(listId);
if (!set) return;
const payload = JSON.stringify(message);
for (const socket of set) {
if (socket !== excludeSocket && socket.readyState === 1 /* OPEN */) {
socket.send(payload);
}
}
}
declare module '@fastify/awilix' {
interface Cradle {
shoppingListsRepository: ShoppingListsRepository;
shoppingListsService: ShoppingListsService;
}
}
function serializeList(doc: any) {
return {
...doc,
_id: doc._id.toString(),
createdAt: doc.createdAt?.toISOString(),
updatedAt: doc.updatedAt?.toISOString(),
completedAt: doc.completedAt?.toISOString(),
items: doc.items.map((it: any) => ({
...it,
checkedAt: it.checkedAt?.toISOString(),
})),
};
}
export default fp(
async (fastify) => {
// Register Awilix classes
fastify.diContainer.register({
shoppingListsRepository: asClass(ShoppingListsRepository, { lifetime: Lifetime.SINGLETON }),
shoppingListsService: asClass(ShoppingListsService, { lifetime: Lifetime.SINGLETON }),
// Cross-domain requirements to service the list workflow orchestrations
shoppingGapService: asClass(ShoppingGapService, { lifetime: Lifetime.SINGLETON }),
pantryService: asClass(PantryService, { lifetime: Lifetime.SINGLETON }),
pantryRepository: asClass(PantryRepository, { lifetime: Lifetime.SINGLETON }),
productsRepository: asClass(ProductsRepository, { lifetime: Lifetime.SINGLETON }),
pricesService: asClass(PricesService, { lifetime: Lifetime.SINGLETON }),
pricesRepository: asClass(PricesRepository, { lifetime: Lifetime.SINGLETON }),
mealPlanRepository: asClass(MealPlanRepository, { lifetime: Lifetime.SINGLETON }),
recipesRepository: asClass(RecipesRepository, { lifetime: Lifetime.SINGLETON }),
storesRepository: asClass(StoresRepository, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
const householdParams = z.object({ householdId: z.string() });
const listIdParams = householdParams.extend({ id: z.string() });
// 1. Standard List CRUD
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/shopping-lists',
schema: {
params: householdParams,
response: { 200: z.array(ShoppingListResponseSchema) },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const lists = await service.list(request.params.householdId);
return reply.send(lists.map(serializeList));
},
});
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/shopping-lists',
schema: {
params: householdParams,
body: CreateShoppingListSchema,
response: { 201: ShoppingListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const list = await service.create(
request.body,
request.params.householdId,
request.user.keycloakId
);
return reply.status(201).send(serializeList(list));
},
});
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/shopping-lists/:id',
schema: {
params: listIdParams,
response: { 200: ShoppingListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const list = await service.getById(request.params.id, request.params.householdId);
return reply.send(serializeList(list));
},
});
app.route({
method: 'PATCH',
url: '/api/v1/households/:householdId/shopping-lists/:id',
schema: {
params: listIdParams,
body: UpdateShoppingListSchema,
response: { 200: ShoppingListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const list = await service.update(
request.params.id,
request.params.householdId,
request.body
);
return reply.send(serializeList(list));
},
});
app.route({
method: 'DELETE',
url: '/api/v1/households/:householdId/shopping-lists/:id',
schema: {
params: listIdParams,
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
await service.delete(request.params.id, request.params.householdId);
return reply.status(204).send();
},
});
// 2. Nested Item Modifications
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/shopping-lists/:id/items',
schema: {
params: listIdParams,
body: AddShoppingItemSchema,
response: { 201: ShoppingListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const { list, addedItem } = await service.addItem(
request.params.id,
request.params.householdId,
request.body
);
// Emit real-time update notification to existing connected viewers
broadcastToList(request.params.id, null as any, {
type: 'ITEM_ADDED',
item: { ...addedItem, checkedAt: undefined },
});
return reply.status(201).send(serializeList(list));
},
});
app.route({
method: 'PATCH',
url: '/api/v1/households/:householdId/shopping-lists/:id/items/:itemId',
schema: {
params: listIdParams.extend({ itemId: z.string() }),
body: UpdateShoppingItemSchema,
response: { 200: ShoppingListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const updatedList = await service.updateItem(
request.params.id,
request.params.householdId,
request.params.itemId,
request.body,
request.user.keycloakId
);
// Broadcast the precise item differential state update to sibling websocket listeners
const matchedItem = updatedList.items.find((i) => i.id === request.params.itemId);
if (matchedItem) {
broadcastToList(request.params.id, null as any, {
type: 'ITEM_UPDATED',
itemId: request.params.itemId,
updates: {
...request.body,
checkedAt: matchedItem.checkedAt?.toISOString(),
checkedBy: matchedItem.checkedBy,
},
});
}
return reply.send(serializeList(updatedList));
},
});
app.route({
method: 'DELETE',
url: '/api/v1/households/:householdId/shopping-lists/:id/items/:itemId',
schema: {
params: listIdParams.extend({ itemId: z.string() }),
response: { 200: ShoppingListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const list = await service.removeItem(
request.params.id,
request.params.householdId,
request.params.itemId
);
broadcastToList(request.params.id, null as any, {
type: 'ITEM_REMOVED',
itemId: request.params.itemId,
});
return reply.send(serializeList(list));
},
});
// 3. Domain Workflow Hooks
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/shopping-lists/from-meal-plan/:mealPlanId',
schema: {
params: householdParams.extend({ mealPlanId: z.string() }),
response: { 201: ShoppingListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const list = await service.createFromMealPlan(
request.params.mealPlanId,
request.params.householdId,
request.user.keycloakId
);
return reply.status(201).send(serializeList(list));
},
});
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/shopping-lists/:id/sync-to-pantry',
schema: {
params: listIdParams,
response: { 200: ShoppingListSyncToPantryResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const results = await service.syncCheckedToPantry(
request.params.id,
request.params.householdId,
request.user.keycloakId
);
return reply.send(results);
},
});
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/shopping-lists/:id/stores',
schema: {
params: listIdParams,
response: { 200: BasketStoreComparisonResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('shoppingListsService');
const comparison = await service.getStoreComparison(
request.params.id,
request.params.householdId
);
return reply.send(comparison);
},
});
// 4. Persist Collaborative WebSocket Handshakes
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/shopping-lists/:id/sync',
websocket: true,
handler: (socket, request) => {
const listId = request.params.id;
// Setup connection context
if (!activeListSockets.has(listId)) {
activeListSockets.set(listId, new Set());
}
activeListSockets.get(listId)!.add(socket);
request.log.info({ listId }, 'Active client joined shopping list sync channel');
socket.on('message', async (messageBuffer) => {
try {
const payload = JSON.parse(messageBuffer.toString());
// Handlers for inbound events e.g. real-time toggle checks from frontends
if (payload.type === 'TOGGLE_ITEM') {
const service = fastify.diContainer.resolve('shoppingListsService');
const updatedList = await service.updateItem(
listId,
request.params.householdId,
payload.itemId,
{ checked: payload.checked },
request.user.keycloakId
);
const matched = updatedList.items.find(it => it.id === payload.itemId);
// Echo back differential confirmation to everyone else on the floor
broadcastToList(listId, socket, {
type: 'ITEM_UPDATED',
itemId: payload.itemId,
updates: {
checked: payload.checked,
checkedAt: matched?.checkedAt?.toISOString(),
checkedBy: matched?.checkedBy,
}
});
}
} catch (err) {
request.log.error(err, 'WebSocket message sync processing error');
}
});
socket.on('close', () => {
const set = activeListSockets.get(listId);
if (set) {
set.delete(socket);
if (set.size === 0) {
activeListSockets.delete(listId);
}
}
request.log.info({ listId }, 'Client severed sync handshake connection');
});
}
});
},
{
name: 'shopping-lists-routes',
dependencies: ['auth-plugin'],
}
);

View file

@ -0,0 +1,224 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ShoppingListsService } from './shopping-lists.service.js';
import { NotFoundError } from '../../common/errors.js';
describe('ShoppingListsService', () => {
let service: ShoppingListsService;
const mockListsRepo = {
list: vi.fn(),
findById: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
addItem: vi.fn(),
updateItem: vi.fn(),
removeItem: vi.fn(),
};
const mockGapService = {
calculateGap: vi.fn(),
};
const mockPantryService = {
create: vi.fn(),
};
const mockProductsRepo = {
findById: vi.fn(),
};
const mockPricesService = {
estimatePrice: vi.fn(),
recordPrice: vi.fn(),
compareStores: vi.fn(),
};
const mockMealPlanRepo = {
findById: vi.fn(),
update: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
service = new ShoppingListsService({
shoppingListsRepository: mockListsRepo as any,
shoppingGapService: mockGapService as any,
pantryService: mockPantryService as any,
productsRepository: mockProductsRepo as any,
pricesService: mockPricesService as any,
mealPlanRepository: mockMealPlanRepo as any,
});
});
describe('create', () => {
it('populates initial estimates and auto-generates internal tracking UUIDs', async () => {
mockProductsRepo.findById.mockResolvedValue({ category: 'produce' });
mockPricesService.estimatePrice.mockResolvedValue(5);
mockListsRepo.create.mockImplementation(arg => arg);
const result = await service.create(
{
name: 'Weekly run',
items: [{ productId: 'p1', quantity: 1, unit: 'g' as any }],
},
'hh1',
'u1'
);
expect(result.items).toHaveLength(1);
expect(result.items[0].id).toBeDefined();
expect(result.items[0].estimatedPrice).toBe(5);
expect(result.totalEstimatedCost).toBe(5);
});
});
describe('addItem', () => {
it('hydrates single product pricing and pushes to list repository', async () => {
mockListsRepo.findById.mockResolvedValue({ _id: 'list1' });
mockProductsRepo.findById.mockResolvedValue({ category: 'meat' });
mockPricesService.estimatePrice.mockResolvedValue(10);
mockListsRepo.addItem.mockResolvedValue({ _id: 'list1' });
const res = await service.addItem('list1', 'hh1', {
productId: 'prodA',
quantity: 1,
unit: 'g' as any,
});
expect(mockListsRepo.addItem).toHaveBeenCalledWith(
'list1',
'hh1',
expect.objectContaining({
productId: 'prodA',
estimatedPrice: 10,
category: 'meat',
})
);
expect(res.addedItem.id).toBeDefined();
});
});
describe('updateItem', () => {
it('injects correct checked timestamps on check-off state mutations', async () => {
mockListsRepo.updateItem.mockResolvedValue({});
await service.updateItem('list1', 'hh1', 'itemA', { checked: true }, 'userIdX');
expect(mockListsRepo.updateItem).toHaveBeenCalledWith(
'list1',
'hh1',
'itemA',
expect.objectContaining({
checked: true,
checkedBy: 'userIdX',
checkedAt: expect.any(Date),
})
);
});
});
describe('createFromMealPlan', () => {
it('runs shopping gap report and populates distinct grocery array linked back to source plan', async () => {
mockMealPlanRepo.findById.mockResolvedValue({ _id: 'mp1', weekStartDate: '2026-05-18' });
mockGapService.calculateGap.mockResolvedValue({
missingItems: [
{ productId: 'gapProd', missingQuantity: 5, unit: 'g', category: 'dairy' }
]
});
mockPricesService.estimatePrice.mockResolvedValue(2);
mockListsRepo.create.mockResolvedValue({ _id: 'newList1' });
const res = await service.createFromMealPlan('mp1', 'hh1', 'userIdZ');
expect(mockGapService.calculateGap).toHaveBeenCalledWith('hh1', 'mp1');
expect(mockListsRepo.create).toHaveBeenCalledWith(
expect.objectContaining({
mealPlanId: 'mp1',
items: [
expect.objectContaining({
productId: 'gapProd',
quantity: 5,
estimatedPrice: 2,
})
]
})
);
// Assert link-back invocation
expect(mockMealPlanRepo.update).toHaveBeenCalledWith('mp1', 'hh1', {
shoppingListId: 'newList1',
});
});
});
describe('syncCheckedToPantry', () => {
it('iterates checked items, creating pantry items and recording actual prices in ledger', async () => {
const mockList = {
_id: 'list1',
preferredStoreId: 'storeA',
items: [
{
id: 'itmA',
productId: 'p1',
checked: true,
addedToPantry: false,
quantity: 2,
unit: 'g',
actualPrice: 15.50,
}
]
};
mockListsRepo.findById.mockResolvedValue(mockList);
const summary = await service.syncCheckedToPantry('list1', 'hh1', 'userAlpha');
// 1. Verify pantry promotion
expect(mockPantryService.create).toHaveBeenCalledWith(
expect.objectContaining({
productId: 'p1',
quantity: 2,
purchasePrice: 15.50,
storeId: 'storeA',
}),
'hh1',
'userAlpha'
);
// 2. Verify point-in-time ledger price logging
expect(mockPricesService.recordPrice).toHaveBeenCalledWith(
expect.objectContaining({
productId: 'p1',
price: 15.50,
storeId: 'storeA',
}),
'hh1',
'userAlpha'
);
// 3. Verify completion bit toggled in list subdocument
expect(mockListsRepo.updateItem).toHaveBeenCalledWith('list1', 'hh1', 'itmA', {
addedToPantry: true,
});
expect(summary.addedCount).toBe(1);
expect(summary.pricesLogged).toBe(1);
});
});
describe('getStoreComparison', () => {
it('collates individual store deviation lists to rank optimized single store trips', async () => {
mockListsRepo.findById.mockResolvedValue({
items: [{ productId: 'p1' }]
});
mockPricesService.compareStores.mockResolvedValue([
{ storeId: 'sA', storeName: 'Walmart', latestPrice: 10 },
{ storeId: 'sB', storeName: 'Whole Foods', latestPrice: 18 },
]);
const comparison = await service.getStoreComparison('list1', 'hh1');
expect(comparison.singleStoreOptions).toHaveLength(2);
expect(comparison.singleStoreOptions[0].storeName).toBe('Walmart');
expect(comparison.singleStoreOptions[0].estimatedTotal).toBe(10);
});
});
});

View file

@ -0,0 +1,356 @@
import type { ShoppingListsRepository } from './shopping-lists.repository.js';
import type { ShoppingGapService } from '../meal-plans/shopping-gap.service.js';
import type { PantryService } from '../pantry/pantry.service.js';
import type { ProductsRepository } from '../products/products.repository.js';
import type { PricesService } from '../prices/prices.service.js';
import type { MealPlanRepository } from '../meal-plans/meal-plans.repository.js';
import type {
CreateShoppingListInput,
UpdateShoppingListInput,
AddShoppingItemInput,
UpdateShoppingItemInput,
ShoppingListStatus,
ShoppingItem,
} from '@meshitrack/shared';
import { ShoppingListSourceType } from '@meshitrack/shared';
import { StorageLocation, ServingUnit } from '@meshitrack/shared';
import { NotFoundError } from '../../common/errors.js';
import { v4 as uuidv4 } from 'uuid';
interface Deps {
shoppingListsRepository: ShoppingListsRepository;
shoppingGapService: ShoppingGapService;
pantryService: PantryService;
productsRepository: ProductsRepository;
pricesService: PricesService;
mealPlanRepository: MealPlanRepository;
}
export class ShoppingListsService {
private readonly shoppingListsRepository: ShoppingListsRepository;
private readonly shoppingGapService: ShoppingGapService;
private readonly pantryService: PantryService;
private readonly productsRepository: ProductsRepository;
private readonly pricesService: PricesService;
private readonly mealPlanRepository: MealPlanRepository;
public constructor({
shoppingListsRepository,
shoppingGapService,
pantryService,
productsRepository,
pricesService,
mealPlanRepository,
}: Deps) {
this.shoppingListsRepository = shoppingListsRepository;
this.shoppingGapService = shoppingGapService;
this.pantryService = pantryService;
this.productsRepository = productsRepository;
this.pricesService = pricesService;
this.mealPlanRepository = mealPlanRepository;
}
public async list(householdId: string) {
return this.shoppingListsRepository.list(householdId);
}
public async getById(id: string, householdId: string) {
const list = await this.shoppingListsRepository.findById(id, householdId);
if (!list) throw new NotFoundError('Shopping list not found');
return list;
}
public async create(data: CreateShoppingListInput, householdId: string, userId: string) {
// Optionally calculate estimates for pre-populated items
const hydratedItems: ShoppingItem[] = [];
let runningTotal = 0;
for (const it of data.items || []) {
const itemId = uuidv4();
let estimatedPrice: number | undefined;
let category: string | undefined = it.category;
if (it.productId) {
const [p, est] = await Promise.all([
this.productsRepository.findById(it.productId, householdId),
this.pricesService.estimatePrice(it.productId, householdId, data.preferredStoreId),
]);
if (p) category = category || p.category;
if (est) {
estimatedPrice = est;
runningTotal += est;
}
}
hydratedItems.push({
id: itemId,
productId: it.productId,
customName: it.customName,
quantity: it.quantity,
unit: it.unit,
checked: false,
addedToPantry: false,
notes: it.notes,
estimatedPrice,
category: category as any,
});
}
return this.shoppingListsRepository.create({
...data,
items: hydratedItems,
householdId,
createdBy: userId,
status: 'active',
totalEstimatedCost: runningTotal > 0 ? Math.round(runningTotal * 100) / 100 : undefined,
});
}
public async update(id: string, householdId: string, data: UpdateShoppingListInput) {
const list = await this.getById(id, householdId);
const updated = await this.shoppingListsRepository.update(id, householdId, data);
if (!updated) throw new NotFoundError('Shopping list not found');
return updated;
}
public async delete(id: string, householdId: string) {
await this.getById(id, householdId);
return this.shoppingListsRepository.delete(id, householdId);
}
// --- Live Item Actions ---
public async addItem(id: string, householdId: string, data: AddShoppingItemInput) {
await this.getById(id, householdId);
let estimatedPrice: number | undefined;
let category: string | undefined = data.category;
if (data.productId) {
const [p, est] = await Promise.all([
this.productsRepository.findById(data.productId, householdId),
this.pricesService.estimatePrice(data.productId, householdId),
]);
if (p) category = category || p.category;
if (est) estimatedPrice = est;
}
const newItem: ShoppingItem = {
id: uuidv4(),
productId: data.productId,
customName: data.customName,
quantity: data.quantity,
unit: data.unit,
checked: false,
addedToPantry: false,
notes: data.notes,
estimatedPrice,
category: category as any,
};
const updated = await this.shoppingListsRepository.addItem(id, householdId, newItem);
if (!updated) throw new NotFoundError('Shopping list not found');
return { list: updated, addedItem: newItem };
}
public async updateItem(
id: string,
householdId: string,
itemId: string,
data: UpdateShoppingItemInput,
userId: string
) {
const updates: Partial<ShoppingItem> = { ...data };
if (data.checked !== undefined) {
updates.checkedAt = data.checked ? new Date() : undefined;
updates.checkedBy = data.checked ? userId : undefined;
}
const updated = await this.shoppingListsRepository.updateItem(id, householdId, itemId, updates);
if (!updated) throw new NotFoundError('Shopping item or list not found');
return updated;
}
public async removeItem(id: string, householdId: string, itemId: string) {
const updated = await this.shoppingListsRepository.removeItem(id, householdId, itemId);
if (!updated) throw new NotFoundError('Shopping list not found');
return updated;
}
// --- Workflow Methods ---
/**
* Analyzes missing ingredients for a meal plan and pre-builds a targeted list.
*/
public async createFromMealPlan(mealPlanId: string, householdId: string, userId: string) {
const plan = await this.mealPlanRepository.findById(mealPlanId, householdId);
if (!plan) throw new NotFoundError('Meal plan not found');
const report = await this.shoppingGapService.calculateGap(householdId, mealPlanId);
const listItems: ShoppingItem[] = [];
let runningTotal = 0;
for (const gap of report.missingItems) {
const estPrice = await this.pricesService.estimatePrice(gap.productId, householdId);
if (estPrice) runningTotal += estPrice;
listItems.push({
id: uuidv4(),
productId: gap.productId,
quantity: gap.missingQuantity,
unit: gap.unit as ServingUnit,
checked: false,
addedToPantry: false,
category: gap.category as any,
estimatedPrice: estPrice || undefined,
});
}
const dateStr = new Date((plan as any).weekStartDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
const name = `Groceries for Week of ${dateStr}`;
const newList = await this.shoppingListsRepository.create({
name,
items: listItems,
householdId,
createdBy: userId,
status: 'active',
createdFrom: {
type: ShoppingListSourceType.MEAL_PLAN,
referenceId: mealPlanId,
},
mealPlanId,
totalEstimatedCost: runningTotal > 0 ? Math.round(runningTotal * 100) / 100 : undefined,
});
// Re-link backing meal plan to its generated list for simplified visual tracking
await this.mealPlanRepository.update(mealPlanId, householdId, {
shoppingListId: newList._id.toString(),
});
return newList;
}
/**
* Migrates all checked grocery items into active pantry items and records final purchase prices.
*/
public async syncCheckedToPantry(id: string, householdId: string, userId: string) {
const list = await this.getById(id, householdId);
let addedCount = 0;
let pricesLogged = 0;
const pendingItems = list.items.filter((it) => it.checked && !it.addedToPantry && it.productId);
for (const item of pendingItems) {
if (!item.productId) continue;
// 1. Promote item to active pantry
await this.pantryService.create(
{
productId: item.productId,
storageLocation: StorageLocation.PANTRY, // Generic fallback location
quantity: item.quantity,
unit: item.unit as ServingUnit,
purchasePrice: item.actualPrice || undefined,
storeId: item.storeId || list.preferredStoreId || undefined,
notes: item.notes,
},
householdId,
userId
);
addedCount++;
// 2. Log final point-in-time pricing ledger entry if user input final price
if (item.actualPrice !== undefined && item.actualPrice > 0) {
const storeId = item.storeId || list.preferredStoreId;
if (storeId) {
await this.pricesService.recordPrice(
{
productId: item.productId,
storeId,
price: item.actualPrice,
quantity: item.quantity,
unit: item.unit as ServingUnit,
currency: 'USD',
},
householdId,
userId
);
pricesLogged++;
}
}
// 3. Set item flag avoiding future sync duplications
await this.shoppingListsRepository.updateItem(id, householdId, item.id, {
addedToPantry: true,
});
}
return { addedCount, pricesLogged };
}
/**
* Analyzes price history to identify the cheapest store option for this basket.
*/
public async getStoreComparison(id: string, householdId: string) {
const list = await this.getById(id, householdId);
const validItems = list.items.filter((it) => it.productId);
// 1. Collate all recent pricing permutations for all products in this basket
const storePricesMap = new Map<string, Map<string, number>>(); // storeId -> Map<productId, latestPrice>
const storeNamesMap = new Map<string, string>();
const allProductIds = validItems.map((it) => it.productId!);
for (const productId of allProductIds) {
const options = await this.pricesService.compareStores(productId, householdId);
for (const opt of options) {
storeNamesMap.set(opt.storeId, opt.storeName);
if (!storePricesMap.has(opt.storeId)) {
storePricesMap.set(opt.storeId, new Map());
}
storePricesMap.get(opt.storeId)!.set(productId, opt.latestPrice);
}
}
// 2. Compile comparative totals per store option
const singleStoreOptions: Array<{
storeId: string;
storeName: string;
estimatedTotal: number;
itemsCovered: number;
itemsMissing: string[];
}> = [];
for (const [storeId, priceMap] of storePricesMap.entries()) {
let sum = 0;
let count = 0;
const missing: string[] = [];
for (const item of validItems) {
const p = priceMap.get(item.productId!);
if (p !== undefined) {
sum += p; // Simple unit scaling could be factored in, using simple latest price sum here
count++;
} else {
missing.push(item.productId!);
}
}
singleStoreOptions.push({
storeId,
storeName: storeNamesMap.get(storeId) || 'Store',
estimatedTotal: Math.round(sum * 100) / 100,
itemsCovered: count,
itemsMissing: missing,
});
}
// Sort to surface the cheapest/fullest single store options first
singleStoreOptions.sort((a, b) => b.itemsCovered - a.itemsCovered || a.estimatedTotal - b.estimatedTotal);
return { singleStoreOptions };
}
}

View file

@ -0,0 +1,31 @@
import mongoose from 'mongoose';
const priceRecordSchema = new mongoose.Schema(
{
householdId: { type: String, required: true },
productId: { type: String, required: true },
productName: { type: String, required: true },
storeId: { type: String, required: true },
storeName: { type: String, required: true },
price: { type: Number, required: true },
currency: { type: String, required: true },
quantity: { type: Number, required: true },
unit: { type: String, required: true },
pricePerUnit: { type: Number, required: true },
date: { type: Date, required: true },
receiptImageUrl: { type: String },
notes: { type: String },
createdBy: { type: String, required: true },
},
{ timestamps: { createdAt: true, updatedAt: false } }
);
// Performance Indexes for Lookup Speed and Aggregations
priceRecordSchema.index({ householdId: 1, productId: 1, storeId: 1, date: -1 });
priceRecordSchema.index({ householdId: 1, productId: 1, date: -1 });
priceRecordSchema.index({ householdId: 1, storeId: 1, date: -1 });
export const PriceRecordModel = mongoose.model('PriceRecord', priceRecordSchema);
export type PriceRecordDocument = mongoose.InferSchemaType<typeof priceRecordSchema> & {
_id: mongoose.Types.ObjectId;
};

View file

@ -0,0 +1,54 @@
import mongoose from 'mongoose';
const shoppingItemSchema = new mongoose.Schema(
{
id: { type: String, required: true }, // Client or server generated tracking UUID
productId: { type: String },
customName: { type: String },
quantity: { type: Number, required: true },
unit: { type: String, required: true },
checked: { type: Boolean, required: true, default: false },
checkedAt: { type: Date },
checkedBy: { type: String },
estimatedPrice: { type: Number },
actualPrice: { type: Number },
storeId: { type: String },
notes: { type: String },
category: { type: String },
addedToPantry: { type: Boolean, required: true, default: false },
},
{ _id: false }
);
const shoppingListSchema = new mongoose.Schema(
{
householdId: { type: String, required: true },
name: { type: String, required: true },
items: { type: [shoppingItemSchema], required: true, default: [] },
status: { type: String, required: true }, // values from ShoppingListStatus
createdFrom: {
type: {
type: { type: String, required: true }, // values from ShoppingListSourceType
referenceId: { type: String },
},
required: false,
_id: false,
},
mealPlanId: { type: String },
totalEstimatedCost: { type: Number },
preferredStoreId: { type: String },
completedAt: { type: Date },
createdBy: { type: String, required: true },
},
{ timestamps: true }
);
shoppingListSchema.index({ householdId: 1, status: 1 });
shoppingListSchema.index({ householdId: 1, createdAt: -1 });
export const ShoppingListModel = mongoose.model('ShoppingList', shoppingListSchema);
export type ShoppingListDocument = mongoose.InferSchemaType<typeof shoppingListSchema> & {
_id: mongoose.Types.ObjectId;
createdAt: Date;
updatedAt: Date;
};