Phases 6-7
This commit is contained in:
parent
76a516a417
commit
029940b079
111 changed files with 17247 additions and 447 deletions
|
|
@ -0,0 +1,162 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
const {
|
||||
mockFind,
|
||||
mockFindOne,
|
||||
mockFindOneAndUpdate,
|
||||
mockFindOneAndDelete,
|
||||
mockSave,
|
||||
mockFindById,
|
||||
} = vi.hoisted(() => ({
|
||||
mockFind: vi.fn(),
|
||||
mockFindOne: vi.fn(),
|
||||
mockFindOneAndUpdate: vi.fn(),
|
||||
mockFindOneAndDelete: vi.fn(),
|
||||
mockSave: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../schemas/freshness-rule.schema.js', () => {
|
||||
const chain = () => ({
|
||||
sort: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFind,
|
||||
});
|
||||
|
||||
const findOneChain = () => ({
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFindOne,
|
||||
});
|
||||
|
||||
const findByIdChain = () => ({
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFindById,
|
||||
});
|
||||
|
||||
const updateChain = () => ({
|
||||
lean: vi.fn().mockReturnThis(),
|
||||
exec: mockFindOneAndUpdate,
|
||||
});
|
||||
|
||||
const deleteChain = () => ({
|
||||
exec: mockFindOneAndDelete,
|
||||
});
|
||||
|
||||
class FakeModel {
|
||||
data: unknown;
|
||||
constructor(data: unknown) {
|
||||
this.data = data;
|
||||
}
|
||||
save() {
|
||||
mockSave(this.data);
|
||||
return Promise.resolve({ toObject: () => this.data });
|
||||
}
|
||||
static find = vi.fn(() => chain());
|
||||
static findOne = vi.fn(() => findOneChain());
|
||||
static findById = vi.fn(() => findByIdChain());
|
||||
static findOneAndUpdate = vi.fn(() => updateChain());
|
||||
static findOneAndDelete = vi.fn(() => deleteChain());
|
||||
}
|
||||
|
||||
return { FreshnessRuleModel: FakeModel };
|
||||
});
|
||||
|
||||
import { FreshnessRulesRepository } from './freshness-rules.repository.js';
|
||||
|
||||
describe(FreshnessRulesRepository.name, () => {
|
||||
let repo: FreshnessRulesRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new FreshnessRulesRepository();
|
||||
});
|
||||
|
||||
describe('findByHousehold', () => {
|
||||
it('returns paginated results', async () => {
|
||||
mockFind.mockResolvedValue([{ _id: { toString: () => 'id1' } }]);
|
||||
const result = await repo.findByHousehold('hh1', { limit: 50 });
|
||||
expect(result.data).toHaveLength(1);
|
||||
expect(result.pagination.hasMore).toBe(false);
|
||||
});
|
||||
|
||||
it('applies category filter', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { category: 'dairy', limit: 50 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies storageLocation filter', async () => {
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { storageLocation: 'fridge', limit: 50 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies cursor', async () => {
|
||||
const cursor = Buffer.from('abc').toString('base64');
|
||||
mockFind.mockResolvedValue([]);
|
||||
await repo.findByHousehold('hh1', { cursor, limit: 50 });
|
||||
expect(mockFind).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('returns rule', async () => {
|
||||
mockFindById.mockResolvedValue({ _id: 'id1' });
|
||||
const result = await repo.findById('id1');
|
||||
expect(result).toEqual({ _id: 'id1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('findApplicableRule', () => {
|
||||
it('returns household rule when available', async () => {
|
||||
const rule = { _id: 'r1', householdId: 'hh1' };
|
||||
mockFindOne.mockResolvedValueOnce(rule);
|
||||
const result = await repo.findApplicableRule('hh1', 'dairy', 'fridge');
|
||||
expect(result).toEqual(rule);
|
||||
});
|
||||
|
||||
it('falls back to system rule', async () => {
|
||||
const systemRule = { _id: 'r2', householdId: null };
|
||||
mockFindOne.mockResolvedValueOnce(null).mockResolvedValueOnce(systemRule);
|
||||
const result = await repo.findApplicableRule('hh1', 'dairy', 'fridge');
|
||||
expect(result).toEqual(systemRule);
|
||||
});
|
||||
|
||||
it('returns null when no rule found', async () => {
|
||||
mockFindOne.mockResolvedValue(null);
|
||||
const result = await repo.findApplicableRule('hh1', 'dairy', 'fridge');
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('saves and returns rule', async () => {
|
||||
const data = {
|
||||
category: 'dairy',
|
||||
storageLocation: 'fridge',
|
||||
shelfLifeDays: 14,
|
||||
openedLifeDays: 7,
|
||||
};
|
||||
const result = await repo.create(data);
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toEqual(data);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates and returns rule', async () => {
|
||||
mockFindOneAndUpdate.mockResolvedValue({ _id: 'id1' });
|
||||
const result = await repo.update('id1', 'hh1', { shelfLifeDays: 10 });
|
||||
expect(result).toEqual({ _id: 'id1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('deletes rule', async () => {
|
||||
mockFindOneAndDelete.mockResolvedValue({ _id: 'id1' });
|
||||
await repo.delete('id1', 'hh1');
|
||||
expect(mockFindOneAndDelete).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
import { FreshnessRuleModel } from '../../schemas/freshness-rule.schema.js';
|
||||
|
||||
interface FindQuery {
|
||||
category?: string;
|
||||
storageLocation?: string;
|
||||
cursor?: string;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export class FreshnessRulesRepository {
|
||||
public async findByHousehold(householdId: string, query: FindQuery) {
|
||||
const filter: Record<string, unknown> = {
|
||||
$or: [{ householdId }, { householdId: { $exists: false } }, { householdId: null }],
|
||||
};
|
||||
|
||||
if (query.category) filter['category'] = query.category;
|
||||
if (query.storageLocation) filter['storageLocation'] = query.storageLocation;
|
||||
|
||||
if (query.cursor) {
|
||||
const id = Buffer.from(query.cursor, 'base64').toString();
|
||||
filter['_id'] = { $gt: id };
|
||||
}
|
||||
|
||||
const limit = query.limit;
|
||||
const items = await FreshnessRuleModel.find(filter)
|
||||
.sort({ category: 1, storageLocation: 1, _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 findById(id: string) {
|
||||
return FreshnessRuleModel.findById(id).lean().exec();
|
||||
}
|
||||
|
||||
public async findApplicableRule(householdId: string, category: string, storageLocation: string) {
|
||||
// Household override takes priority
|
||||
const householdRule = await FreshnessRuleModel.findOne({
|
||||
householdId,
|
||||
category,
|
||||
storageLocation,
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
if (householdRule) return householdRule;
|
||||
|
||||
// Fall back to system default
|
||||
return FreshnessRuleModel.findOne({
|
||||
$or: [{ householdId: null }, { householdId: { $exists: false } }],
|
||||
category,
|
||||
storageLocation,
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async create(data: Record<string, unknown>) {
|
||||
const doc = new FreshnessRuleModel(data);
|
||||
const saved = await doc.save();
|
||||
return saved.toObject();
|
||||
}
|
||||
|
||||
public async update(id: string, householdId: string, data: Record<string, unknown>) {
|
||||
return FreshnessRuleModel.findOneAndUpdate(
|
||||
{ _id: id, householdId },
|
||||
{ $set: data },
|
||||
{ new: true },
|
||||
)
|
||||
.lean()
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async delete(id: string, householdId: string) {
|
||||
return FreshnessRuleModel.findOneAndDelete({ _id: id, householdId }).exec();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
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',
|
||||
preferred_username: 'testuser',
|
||||
realm_access: { roles: ['member'] },
|
||||
householdIds: ['hh1'],
|
||||
},
|
||||
protectedHeader: { alg: 'RS256' },
|
||||
key: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const { mockFindByHousehold, mockFindById, mockCreate, mockUpdate, mockDelete } = vi.hoisted(
|
||||
() => ({
|
||||
mockFindByHousehold: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
mockCreate: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockDelete: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock('./freshness-rules.repository.js', () => ({
|
||||
FreshnessRulesRepository: class {
|
||||
findByHousehold = mockFindByHousehold;
|
||||
findById = mockFindById;
|
||||
findApplicableRule = vi.fn();
|
||||
create = mockCreate;
|
||||
update = mockUpdate;
|
||||
delete = mockDelete;
|
||||
},
|
||||
}));
|
||||
|
||||
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 freshnessRulesRoutes from './freshness-rules.routes.js';
|
||||
|
||||
function makeRule(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
_id: 'rule-1',
|
||||
householdId: 'hh1',
|
||||
category: 'dairy',
|
||||
storageLocation: 'fridge',
|
||||
shelfLifeDays: 14,
|
||||
openedLifeDays: 7,
|
||||
spoilageSignsToCheck: ['smell'],
|
||||
source: 'household',
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('freshness-rules.routes', () => {
|
||||
let app: Awaited<ReturnType<typeof buildTestApp>>;
|
||||
|
||||
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(freshnessRulesRoutes);
|
||||
await instance.ready();
|
||||
return instance;
|
||||
}
|
||||
|
||||
const authHeaders = { authorization: 'Bearer valid-token' };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
app = await buildTestApp();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (app) await app.close();
|
||||
});
|
||||
|
||||
describe('GET /freshness-rules', () => {
|
||||
it('returns paginated list', async () => {
|
||||
mockFindByHousehold.mockResolvedValue({
|
||||
data: [makeRule()],
|
||||
pagination: { cursor: null, hasMore: false },
|
||||
});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1/freshness-rules',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /freshness-rules', () => {
|
||||
it('creates a rule', async () => {
|
||||
mockCreate.mockResolvedValue(makeRule());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/freshness-rules',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
category: 'dairy',
|
||||
storageLocation: 'fridge',
|
||||
shelfLifeDays: 14,
|
||||
openedLifeDays: 7,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
});
|
||||
|
||||
it('rejects invalid category', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/freshness-rules',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
category: 'invalid',
|
||||
storageLocation: 'fridge',
|
||||
shelfLifeDays: 14,
|
||||
openedLifeDays: 7,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /freshness-rules/:id', () => {
|
||||
it('updates a rule', async () => {
|
||||
mockFindById.mockResolvedValue(makeRule());
|
||||
mockUpdate.mockResolvedValue(makeRule({ shelfLifeDays: 10 }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/freshness-rules/rule-1',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ shelfLifeDays: 10 }),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /freshness-rules/:id with optional fields', () => {
|
||||
it('returns rule with all optional fields', async () => {
|
||||
mockFindById.mockResolvedValue(makeRule());
|
||||
mockUpdate.mockResolvedValue(makeRule({ freezerLifeDays: 90, tips: 'Keep sealed' }));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1/freshness-rules/rule-1',
|
||||
headers: { ...authHeaders, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ freezerLifeDays: 90, tips: 'Keep sealed' }),
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.freezerLifeDays).toBe(90);
|
||||
expect(body.tips).toBe('Keep sealed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('DELETE /freshness-rules/:id', () => {
|
||||
it('deletes a rule', async () => {
|
||||
mockFindById.mockResolvedValue(makeRule());
|
||||
mockDelete.mockResolvedValue(makeRule());
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/hh1/freshness-rules/rule-1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
import fp from 'fastify-plugin';
|
||||
import { asClass, Lifetime } from 'awilix';
|
||||
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
||||
import { z } from 'zod/v4';
|
||||
import {
|
||||
CreateFreshnessRuleSchema,
|
||||
UpdateFreshnessRuleSchema,
|
||||
FreshnessRuleQuerySchema,
|
||||
FreshnessRuleResponseSchema,
|
||||
FreshnessRuleListResponseSchema,
|
||||
type FreshnessRuleSource,
|
||||
type StorageLocation,
|
||||
type ProductCategory,
|
||||
} from '@meshitrack/shared';
|
||||
import { FreshnessRulesRepository } from './freshness-rules.repository.js';
|
||||
import { FreshnessRulesService } from './freshness-rules.service.js';
|
||||
|
||||
const HouseholdParams = z.object({ householdId: z.string() });
|
||||
const RuleParams = z.object({ householdId: z.string(), id: z.string() });
|
||||
|
||||
type AnyRuleDoc = {
|
||||
_id: string | { toString(): string };
|
||||
householdId?: string | null;
|
||||
category: string;
|
||||
storageLocation: string;
|
||||
shelfLifeDays: number;
|
||||
openedLifeDays: number;
|
||||
freezerLifeDays?: number | null;
|
||||
spoilageSignsToCheck: string[];
|
||||
tips?: string | null;
|
||||
source: string;
|
||||
createdAt: string | Date;
|
||||
updatedAt: string | Date;
|
||||
};
|
||||
|
||||
function toStr(v: string | { toString: () => string }): string {
|
||||
return typeof v === 'string' ? v : v.toString();
|
||||
}
|
||||
|
||||
function toIso(v: string | Date): string {
|
||||
return typeof v === 'string' ? v : v.toISOString();
|
||||
}
|
||||
|
||||
function toRuleResponse(doc: AnyRuleDoc): z.infer<typeof FreshnessRuleResponseSchema> {
|
||||
return {
|
||||
_id: toStr(doc._id),
|
||||
...(doc.householdId ? { householdId: doc.householdId } : {}),
|
||||
category: doc.category as ProductCategory,
|
||||
storageLocation: doc.storageLocation as StorageLocation,
|
||||
shelfLifeDays: doc.shelfLifeDays,
|
||||
openedLifeDays: doc.openedLifeDays,
|
||||
...(doc.freezerLifeDays != null ? { freezerLifeDays: doc.freezerLifeDays } : {}),
|
||||
spoilageSignsToCheck: doc.spoilageSignsToCheck,
|
||||
...(doc.tips ? { tips: doc.tips } : {}),
|
||||
source: doc.source as FreshnessRuleSource,
|
||||
createdAt: toIso(doc.createdAt),
|
||||
updatedAt: toIso(doc.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
declare module '@fastify/awilix' {
|
||||
interface Cradle {
|
||||
freshnessRulesRepository: FreshnessRulesRepository;
|
||||
freshnessRulesService: FreshnessRulesService;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
if (!fastify.diContainer.hasRegistration('freshnessRulesRepository')) {
|
||||
fastify.diContainer.register({
|
||||
freshnessRulesRepository: asClass(FreshnessRulesRepository, {
|
||||
lifetime: Lifetime.SINGLETON,
|
||||
}),
|
||||
});
|
||||
}
|
||||
fastify.diContainer.register({
|
||||
freshnessRulesService: asClass(FreshnessRulesService, { lifetime: Lifetime.SINGLETON }),
|
||||
});
|
||||
|
||||
const app = fastify.withTypeProvider<ZodTypeProvider>();
|
||||
|
||||
// GET /freshness-rules
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId/freshness-rules',
|
||||
schema: {
|
||||
params: HouseholdParams,
|
||||
querystring: FreshnessRuleQuerySchema,
|
||||
response: { 200: FreshnessRuleListResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = request.diScope.resolve<FreshnessRulesService>('freshnessRulesService');
|
||||
const result = await service.list(request.params.householdId, request.query);
|
||||
const mapped = {
|
||||
data: result.data.map((d) => toRuleResponse(d as unknown as AnyRuleDoc)),
|
||||
pagination: result.pagination,
|
||||
};
|
||||
return reply.send(mapped);
|
||||
},
|
||||
});
|
||||
|
||||
// POST /freshness-rules
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/freshness-rules',
|
||||
schema: {
|
||||
params: HouseholdParams,
|
||||
body: CreateFreshnessRuleSchema,
|
||||
response: { 201: FreshnessRuleResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = request.diScope.resolve<FreshnessRulesService>('freshnessRulesService');
|
||||
const rule = await service.create(request.body, request.params.householdId);
|
||||
return reply.status(201).send(toRuleResponse(rule as unknown as AnyRuleDoc));
|
||||
},
|
||||
});
|
||||
|
||||
// PATCH /freshness-rules/:id
|
||||
app.route({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/:householdId/freshness-rules/:id',
|
||||
schema: {
|
||||
params: RuleParams,
|
||||
body: UpdateFreshnessRuleSchema,
|
||||
response: { 200: FreshnessRuleResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = request.diScope.resolve<FreshnessRulesService>('freshnessRulesService');
|
||||
const rule = await service.update(
|
||||
request.params.id,
|
||||
request.params.householdId,
|
||||
request.body,
|
||||
);
|
||||
return reply.send(toRuleResponse(rule as unknown as AnyRuleDoc));
|
||||
},
|
||||
});
|
||||
|
||||
// DELETE /freshness-rules/:id
|
||||
app.route({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/households/:householdId/freshness-rules/:id',
|
||||
schema: {
|
||||
params: RuleParams,
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = request.diScope.resolve<FreshnessRulesService>('freshnessRulesService');
|
||||
await service.delete(request.params.id, request.params.householdId);
|
||||
return reply.status(204).send();
|
||||
},
|
||||
});
|
||||
},
|
||||
{ name: 'freshness-rules-routes' },
|
||||
);
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { FreshnessRulesService } from './freshness-rules.service.js';
|
||||
import { NotFoundError, BadRequestError } from '../../common/errors.js';
|
||||
import { FreshnessRuleSource } from '@meshitrack/shared';
|
||||
|
||||
const mockRepo = {
|
||||
findByHousehold: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
findApplicableRule: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
};
|
||||
|
||||
describe(FreshnessRulesService.name, () => {
|
||||
let service: FreshnessRulesService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new FreshnessRulesService({
|
||||
freshnessRulesRepository: mockRepo as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('list', () => {
|
||||
it('delegates to repository', async () => {
|
||||
const expected = { data: [], pagination: { cursor: null, hasMore: false } };
|
||||
mockRepo.findByHousehold.mockResolvedValue(expected);
|
||||
const result = await service.list('hh1', { limit: 50 });
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates household rule', async () => {
|
||||
const data = {
|
||||
category: 'dairy' as never,
|
||||
storageLocation: 'fridge' as never,
|
||||
shelfLifeDays: 14,
|
||||
openedLifeDays: 7,
|
||||
spoilageSignsToCheck: [],
|
||||
};
|
||||
mockRepo.create.mockResolvedValue({ ...data, _id: 'r1', householdId: 'hh1' });
|
||||
|
||||
const result = await service.create(data, 'hh1');
|
||||
expect(mockRepo.create).toHaveBeenCalledWith({
|
||||
...data,
|
||||
householdId: 'hh1',
|
||||
source: FreshnessRuleSource.HOUSEHOLD,
|
||||
});
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('updates household rule', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'r1',
|
||||
householdId: 'hh1',
|
||||
source: FreshnessRuleSource.HOUSEHOLD,
|
||||
});
|
||||
mockRepo.update.mockResolvedValue({ _id: 'r1', shelfLifeDays: 10 });
|
||||
|
||||
const result = await service.update('r1', 'hh1', { shelfLifeDays: 10 });
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
|
||||
it('throws NotFoundError when rule not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
await expect(service.update('missing', 'hh1', {})).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws BadRequestError for system rules', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'r1',
|
||||
householdId: null,
|
||||
source: FreshnessRuleSource.SYSTEM,
|
||||
});
|
||||
await expect(service.update('r1', 'hh1', {})).rejects.toThrow(BadRequestError);
|
||||
});
|
||||
|
||||
it('throws NotFoundError for another household rule', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'r1',
|
||||
householdId: 'other-hh',
|
||||
source: FreshnessRuleSource.HOUSEHOLD,
|
||||
});
|
||||
await expect(service.update('r1', 'hh1', {})).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when update returns null', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'r1',
|
||||
householdId: 'hh1',
|
||||
source: FreshnessRuleSource.HOUSEHOLD,
|
||||
});
|
||||
mockRepo.update.mockResolvedValue(null);
|
||||
await expect(service.update('r1', 'hh1', {})).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('deletes household rule', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'r1',
|
||||
householdId: 'hh1',
|
||||
source: FreshnessRuleSource.HOUSEHOLD,
|
||||
});
|
||||
mockRepo.delete.mockResolvedValue({ _id: 'r1' });
|
||||
await service.delete('r1', 'hh1');
|
||||
expect(mockRepo.delete).toHaveBeenCalledWith('r1', 'hh1');
|
||||
});
|
||||
|
||||
it('throws NotFoundError when rule not found', async () => {
|
||||
mockRepo.findById.mockResolvedValue(null);
|
||||
await expect(service.delete('missing', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws BadRequestError for system rules', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'r1',
|
||||
householdId: null,
|
||||
source: FreshnessRuleSource.SYSTEM,
|
||||
});
|
||||
await expect(service.delete('r1', 'hh1')).rejects.toThrow(BadRequestError);
|
||||
});
|
||||
|
||||
it('throws NotFoundError for another household rule', async () => {
|
||||
mockRepo.findById.mockResolvedValue({
|
||||
_id: 'r1',
|
||||
householdId: 'other-hh',
|
||||
source: FreshnessRuleSource.HOUSEHOLD,
|
||||
});
|
||||
await expect(service.delete('r1', 'hh1')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,64 @@
|
|||
import type { FreshnessRulesRepository } from './freshness-rules.repository.js';
|
||||
import { FreshnessRuleSource } from '@meshitrack/shared';
|
||||
import type {
|
||||
CreateFreshnessRuleInput,
|
||||
UpdateFreshnessRuleInput,
|
||||
FreshnessRuleQueryInput,
|
||||
} from '@meshitrack/shared';
|
||||
import { NotFoundError, BadRequestError } from '../../common/errors.js';
|
||||
|
||||
interface Deps {
|
||||
freshnessRulesRepository: FreshnessRulesRepository;
|
||||
}
|
||||
|
||||
export class FreshnessRulesService {
|
||||
private readonly freshnessRulesRepository: FreshnessRulesRepository;
|
||||
|
||||
public constructor({ freshnessRulesRepository }: Deps) {
|
||||
this.freshnessRulesRepository = freshnessRulesRepository;
|
||||
}
|
||||
|
||||
public async list(householdId: string, query: FreshnessRuleQueryInput) {
|
||||
return this.freshnessRulesRepository.findByHousehold(householdId, query);
|
||||
}
|
||||
|
||||
public async create(data: CreateFreshnessRuleInput, householdId: string) {
|
||||
return this.freshnessRulesRepository.create({
|
||||
...data,
|
||||
householdId,
|
||||
source: FreshnessRuleSource.HOUSEHOLD,
|
||||
});
|
||||
}
|
||||
|
||||
public async update(id: string, householdId: string, data: UpdateFreshnessRuleInput) {
|
||||
const existing = await this.freshnessRulesRepository.findById(id);
|
||||
if (!existing) throw new NotFoundError('Freshness rule not found');
|
||||
|
||||
const rec = existing as Record<string, unknown>;
|
||||
if (rec.source === FreshnessRuleSource.SYSTEM && rec.householdId == null) {
|
||||
throw new BadRequestError('Cannot modify system rules. Create a household override instead.');
|
||||
}
|
||||
if (rec.householdId && rec.householdId !== householdId) {
|
||||
throw new NotFoundError('Freshness rule not found');
|
||||
}
|
||||
|
||||
const updated = await this.freshnessRulesRepository.update(id, householdId, data);
|
||||
if (!updated) throw new NotFoundError('Freshness rule not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async delete(id: string, householdId: string) {
|
||||
const existing = await this.freshnessRulesRepository.findById(id);
|
||||
if (!existing) throw new NotFoundError('Freshness rule not found');
|
||||
|
||||
const rec = existing as Record<string, unknown>;
|
||||
if (rec.source === FreshnessRuleSource.SYSTEM && rec.householdId == null) {
|
||||
throw new BadRequestError('Cannot delete system rules');
|
||||
}
|
||||
if (rec.householdId && rec.householdId !== householdId) {
|
||||
throw new NotFoundError('Freshness rule not found');
|
||||
}
|
||||
|
||||
await this.freshnessRulesRepository.delete(id, householdId);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue