Implement medicine library and cabinet

This commit is contained in:
Aerilyn Weber 2026-03-28 08:19:48 +09:00
parent db79af06f7
commit 1f66fab30f
72 changed files with 7642 additions and 319 deletions

View file

@ -11,6 +11,9 @@ vi.mock('mongoose', () => {
this.paths['createdAt'] = { path: 'createdAt' };
this.paths['updatedAt'] = { path: 'updatedAt' };
}
index() {
return this;
}
}
const models: Record<string, unknown> = {};

View file

@ -28,6 +28,9 @@ import householdPlugin from './plugins/household.plugin.js';
import healthRoutes from './modules/health/health.routes.js';
import usersRoutes from './modules/users/users.routes.js';
import householdsRoutes from './modules/households/households.routes.js';
import medicinesRoutes from './modules/medicines/medicines.routes.js';
import medicineProductsRoutes from './modules/medicine-products/medicine-products.routes.js';
import cabinetRoutes from './modules/cabinet/cabinet.routes.js';
export async function buildApp(opts: { logger?: boolean | object } = {}) {
const app = Fastify({
@ -42,8 +45,16 @@ export async function buildApp(opts: { logger?: boolean | object } = {}) {
app.setSerializerCompiler(serializerCompiler);
// Security & compression
await app.register(helmet);
await app.register(cors, { origin: config.cors.origin, credentials: true });
await app.register(helmet, {
crossOriginResourcePolicy: { policy: 'cross-origin' },
contentSecurityPolicy: false,
});
await app.register(cors, {
origin: config.cors.origin,
credentials: true,
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
});
await app.register(compress);
// Swagger / OpenAPI
@ -89,6 +100,9 @@ export async function buildApp(opts: { logger?: boolean | object } = {}) {
await app.register(healthRoutes);
await app.register(usersRoutes);
await app.register(householdsRoutes);
await app.register(medicinesRoutes);
await app.register(medicineProductsRoutes);
await app.register(cabinetRoutes);
// Global error handler
app.setErrorHandler((error, request, reply) => {

View file

@ -0,0 +1,254 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const { mockFind, mockFindOne, mockFindOneAndUpdate, mockSave, mockCountDocuments, mockAggregate } =
vi.hoisted(() => ({
mockFind: vi.fn(),
mockFindOne: vi.fn(),
mockFindOneAndUpdate: vi.fn(),
mockSave: vi.fn(),
mockCountDocuments: vi.fn(),
mockAggregate: vi.fn(),
}));
vi.mock('../../schemas/cabinet-item.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 updateChain = () => ({
exec: mockFindOneAndUpdate,
});
const countChain = () => ({
exec: mockCountDocuments,
});
const aggChain = () => ({
exec: mockAggregate,
});
class FakeModel {
data: unknown;
constructor(data: unknown) {
this.data = data;
}
save = mockSave;
toObject() {
return this.data;
}
static find = vi.fn(() => chain());
static findOne = vi.fn(() => findOneChain());
static findOneAndUpdate = vi.fn(() => updateChain());
static countDocuments = vi.fn(() => countChain());
static aggregate = vi.fn(() => aggChain());
}
return { CabinetItemModel: FakeModel };
});
import { CabinetRepository } from './cabinet.repository.js';
describe(CabinetRepository.name, () => {
let repo: CabinetRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new CabinetRepository();
});
describe('findByHousehold', () => {
it('returns paginated items', async () => {
const items = [{ _id: 'ci-1', quantity: 30 }];
mockFind.mockResolvedValue(items);
const result = await repo.findByHousehold('hh1', { limit: 20 });
expect(result.data).toEqual(items);
expect(result.pagination.hasMore).toBe(false);
});
it('handles cursor-based pagination', async () => {
const items = [{ _id: 'ci-2', quantity: 10 }];
mockFind.mockResolvedValue(items);
const cursor = Buffer.from('ci-1').toString('base64');
const result = await repo.findByHousehold('hh1', { cursor, limit: 20 });
expect(result.data).toEqual(items);
expect(result.pagination.hasMore).toBe(false);
});
it('sets hasMore when more items exist', async () => {
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `ci-${i}`, quantity: i }));
mockFind.mockResolvedValue(items);
const result = await repo.findByHousehold('hh1', { limit: 2 });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(true);
expect(result.pagination.cursor).toBeTruthy();
});
it('returns null cursor when no data', async () => {
mockFind.mockResolvedValue([]);
const result = await repo.findByHousehold('hh1', { limit: 20 });
expect(result.pagination.cursor).toBeNull();
});
it('filters by medicineId', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', { medicineId: 'med-1', limit: 20 });
expect(mockFind).toHaveBeenCalled();
});
it('filters by status', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', {
status: 'active' as never,
limit: 20,
});
expect(mockFind).toHaveBeenCalled();
});
it('filters by expiringWithin', async () => {
mockFind.mockResolvedValue([]);
await repo.findByHousehold('hh1', { expiringWithin: 30, limit: 20 });
expect(mockFind).toHaveBeenCalled();
});
});
describe('findById', () => {
it('returns item by id and householdId', async () => {
const item = { _id: 'ci-1', householdId: 'hh1', quantity: 30 };
mockFindOne.mockResolvedValue(item);
const result = await repo.findById('ci-1', 'hh1');
expect(result).toEqual(item);
});
});
describe('getAggregateSummary', () => {
it('returns aggregate data', async () => {
const aggregated = [{ _id: 'med-1', totalQuantity: 60, itemCount: 2 }];
mockAggregate.mockResolvedValue(aggregated);
const result = await repo.getAggregateSummary('hh1');
expect(result).toEqual(aggregated);
});
});
describe('create', () => {
it('creates and returns cabinet item', async () => {
const data = {
medicineId: 'med-1',
medicineName: 'Metformin',
medicineStrength: 500,
medicineStrengthUnit: 'mg',
medicineForm: 'tablet',
quantity: 30,
unit: 'tablet' as const,
};
mockSave.mockImplementation(function (this: { toObject: () => unknown }) {
return Promise.resolve(this);
});
const result = await repo.create(data, 'hh1', 'user-1');
expect(result).toBeTruthy();
expect(mockSave).toHaveBeenCalled();
});
});
describe('update', () => {
it('updates and returns item', async () => {
const updated = { _id: 'ci-1', quantity: 25 };
mockFindOneAndUpdate.mockResolvedValue(updated);
const result = await repo.update('ci-1', 'hh1', { quantity: 25 });
expect(result).toEqual(updated);
});
});
describe('adjustQuantity', () => {
it('adjusts quantity and returns updated item', async () => {
mockFindOne.mockResolvedValue({ _id: 'ci-1', quantity: 30, status: 'active' });
const updated = { _id: 'ci-1', quantity: 27, status: 'active' };
mockFindOneAndUpdate.mockResolvedValue(updated);
const result = await repo.adjustQuantity('ci-1', 'hh1', -3);
expect(result).toEqual(updated);
});
it('floors quantity at 0 and sets depleted status', async () => {
mockFindOne.mockResolvedValue({ _id: 'ci-1', quantity: 2, status: 'active' });
const updated = { _id: 'ci-1', quantity: 0, status: 'depleted' };
mockFindOneAndUpdate.mockResolvedValue(updated);
const result = await repo.adjustQuantity('ci-1', 'hh1', -5);
expect(result).toEqual(updated);
});
it('re-activates depleted item when adding stock', async () => {
mockFindOne.mockResolvedValue({ _id: 'ci-1', quantity: 0, status: 'depleted' });
const updated = { _id: 'ci-1', quantity: 10, status: 'active' };
mockFindOneAndUpdate.mockResolvedValue(updated);
const result = await repo.adjustQuantity('ci-1', 'hh1', 10);
expect(result).toEqual(updated);
});
it('returns null if item not found', async () => {
mockFindOne.mockResolvedValue(null);
const result = await repo.adjustQuantity('ci-missing', 'hh1', 5);
expect(result).toBeNull();
});
});
describe('findExpiringSoon', () => {
it('returns items expiring within N days', async () => {
const items = [{ _id: 'ci-1', expirationDate: new Date() }];
mockFind.mockResolvedValue(items);
const result = await repo.findExpiringSoon('hh1', 30);
expect(result).toEqual(items);
});
});
describe('countByMedicineId', () => {
it('returns count', async () => {
mockCountDocuments.mockResolvedValue(3);
const result = await repo.countByMedicineId('med-1');
expect(result).toBe(3);
});
});
describe('softDelete', () => {
it('soft deletes and returns item', async () => {
const deleted = { _id: 'ci-1', isDeleted: true };
mockFindOneAndUpdate.mockResolvedValue(deleted);
const result = await repo.softDelete('ci-1', 'hh1');
expect(result).toEqual(deleted);
});
});
});

View file

@ -0,0 +1,144 @@
import { CabinetItemModel } from '../../schemas/cabinet-item.schema.js';
import type { CabinetItemStatus, CreateCabinetItemInput, UpdateCabinetItemInput } from '@meshitrack/shared';
interface FindByHouseholdQuery {
medicineId?: string;
status?: CabinetItemStatus;
expiringWithin?: number;
cursor?: string;
limit: number;
}
export class CabinetRepository {
public async findByHousehold(householdId: string, query: FindByHouseholdQuery) {
const filter: Record<string, unknown> = { householdId, isDeleted: false };
if (query.medicineId) filter['medicineId'] = query.medicineId;
if (query.status) filter['status'] = query.status;
if (query.expiringWithin) {
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() + query.expiringWithin);
filter['expirationDate'] = { $lte: cutoff, $gt: new Date() };
filter['status'] = 'active';
}
if (query.cursor) {
const id = Buffer.from(query.cursor, 'base64').toString();
filter['_id'] = { $gt: id };
}
const limit = query.limit;
const items = await CabinetItemModel.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 findById(id: string, householdId: string) {
return CabinetItemModel.findOne({ _id: id, householdId, isDeleted: false }).lean().exec();
}
public async getAggregateSummary(householdId: string) {
return CabinetItemModel.aggregate([
{ $match: { householdId, isDeleted: false, status: 'active' } },
{
$group: {
_id: '$medicineId',
medicineName: { $first: '$medicineName' },
medicineStrength: { $first: '$medicineStrength' },
medicineStrengthUnit: { $first: '$medicineStrengthUnit' },
medicineForm: { $first: '$medicineForm' },
totalQuantity: { $sum: '$quantity' },
unit: { $first: '$unit' },
earliestExpiry: { $min: '$expirationDate' },
itemCount: { $sum: 1 },
},
},
{ $sort: { medicineName: 1 } },
]).exec();
}
public async create(
data: CreateCabinetItemInput & {
medicineName: string;
medicineStrength: number;
medicineStrengthUnit: string;
medicineForm: string;
medicineProductBrand?: string;
concentration?: number;
concentrationUnit?: string;
},
householdId: string,
createdBy: string,
) {
const item = new CabinetItemModel({ ...data, householdId, createdBy });
const saved = await item.save();
return saved.toObject();
}
public async update(id: string, householdId: string, data: UpdateCabinetItemInput) {
return CabinetItemModel.findOneAndUpdate(
{ _id: id, householdId, isDeleted: false },
{ $set: data },
{ new: true, lean: true },
).exec();
}
public async adjustQuantity(id: string, householdId: string, delta: number) {
const item = await CabinetItemModel.findOne({
_id: id,
householdId,
isDeleted: false,
})
.lean()
.exec();
if (!item) return null;
const newQuantity = Math.max(0, item.quantity + delta);
const newStatus =
newQuantity === 0 ? 'depleted' : item.status === 'depleted' ? 'active' : item.status;
return CabinetItemModel.findOneAndUpdate(
{ _id: id, householdId, isDeleted: false },
{ $set: { quantity: newQuantity, status: newStatus } },
{ new: true, lean: true },
).exec();
}
public async findExpiringSoon(householdId: string, withinDays: number) {
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() + withinDays);
return CabinetItemModel.find({
householdId,
isDeleted: false,
status: 'active',
expirationDate: { $lte: cutoff, $gt: new Date() },
})
.sort({ expirationDate: 1 })
.lean()
.exec();
}
public async countByMedicineId(medicineId: string): Promise<number> {
return CabinetItemModel.countDocuments({ medicineId, isDeleted: false }).exec();
}
public async softDelete(id: string, householdId: string) {
return CabinetItemModel.findOneAndUpdate(
{ _id: id, householdId, isDeleted: false },
{ $set: { isDeleted: true } },
{ new: true, lean: true },
).exec();
}
}

View file

@ -0,0 +1,382 @@
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';
import { DosageUnit, MedicineForm, StrengthUnit, CabinetItemStatus } from '@meshitrack/shared';
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,
mockGetAggregateSummary,
mockCreate,
mockUpdate,
mockAdjustQuantity,
mockFindExpiringSoon,
mockSoftDelete,
mockCountByMedicineId,
} = vi.hoisted(() => ({
mockFindByHousehold: vi.fn(),
mockFindById: vi.fn(),
mockGetAggregateSummary: vi.fn(),
mockCreate: vi.fn(),
mockUpdate: vi.fn(),
mockAdjustQuantity: vi.fn(),
mockFindExpiringSoon: vi.fn(),
mockSoftDelete: vi.fn(),
mockCountByMedicineId: vi.fn(),
}));
vi.mock('./cabinet.repository.js', () => ({
CabinetRepository: class {
findByHousehold = mockFindByHousehold;
findById = mockFindById;
getAggregateSummary = mockGetAggregateSummary;
create = mockCreate;
update = mockUpdate;
adjustQuantity = mockAdjustQuantity;
findExpiringSoon = mockFindExpiringSoon;
softDelete = mockSoftDelete;
countByMedicineId = mockCountByMedicineId;
},
}));
const { mockMedicineFindById } = vi.hoisted(() => ({
mockMedicineFindById: vi.fn(),
}));
vi.mock('../medicines/medicines.repository.js', () => ({
MedicinesRepository: class {
findById = mockMedicineFindById;
findByHousehold = vi.fn();
findDuplicate = vi.fn();
create = vi.fn();
update = vi.fn();
softDelete = vi.fn();
},
}));
const { mockProductFindById } = vi.hoisted(() => ({
mockProductFindById: vi.fn(),
}));
vi.mock('../medicine-products/medicine-products.repository.js', () => ({
MedicineProductsRepository: class {
findById = mockProductFindById;
findByMedicine = vi.fn();
create = vi.fn();
update = vi.fn();
softDelete = vi.fn();
countByMedicineId = vi.fn();
},
}));
vi.mock('../medicine-products/medicine-products.service.js', () => ({
MedicineProductsService: class {
listByMedicine = vi.fn();
getById = vi.fn();
create = vi.fn();
update = vi.fn();
delete = vi.fn();
},
}));
vi.mock('../medicines/medicines.service.js', () => ({
MedicinesService: class {
list = vi.fn();
getById = vi.fn();
create = vi.fn();
update = vi.fn();
delete = vi.fn();
},
}));
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 medicinesRoutes from '../medicines/medicines.routes.js';
import medicineProductsRoutes from '../medicine-products/medicine-products.routes.js';
import cabinetRoutes from './cabinet.routes.js';
function makeFakeCabinetItem(overrides = {}) {
return {
_id: 'ci-1',
householdId: 'hh1',
medicineId: 'med-1',
medicineName: 'Metformin',
medicineStrength: 500,
medicineStrengthUnit: StrengthUnit.MG,
medicineForm: MedicineForm.TABLET,
quantity: 30,
unit: DosageUnit.TABLET,
status: CabinetItemStatus.ACTIVE,
createdBy: 'kc-1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
};
}
describe('cabinet.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(medicinesRoutes);
await instance.register(medicineProductsRoutes);
await instance.register(cabinetRoutes);
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 /api/v1/households/:householdId/cabinet', () => {
it('returns paginated list', async () => {
const item = makeFakeCabinetItem();
mockFindByHousehold.mockResolvedValue({
data: [item],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0].medicineName).toBe('Metformin');
expect(body.pagination.hasMore).toBe(false);
});
it('handles ObjectId and Date objects in response', async () => {
const item = makeFakeCabinetItem({
_id: { toString: () => 'ci-obj' },
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
expirationDate: new Date('2026-06-01T00:00:00.000Z'),
notes: 'Main supply',
medicineProductId: 'prod-1',
medicineProductBrand: 'Glucophage',
});
mockFindByHousehold.mockResolvedValue({
data: [item],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0]._id).toBe('ci-obj');
expect(body.data[0].expirationDate).toBe('2026-06-01T00:00:00.000Z');
expect(body.data[0].medicineProductBrand).toBe('Glucophage');
});
it('handles string dates in response', async () => {
const item = makeFakeCabinetItem({
expirationDate: '2026-12-31T00:00:00.000Z',
createdAt: new Date('2024-01-01T00:00:00.000Z'),
updatedAt: new Date('2024-01-02T00:00:00.000Z'),
});
mockFindByHousehold.mockResolvedValue({
data: [item],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0].expirationDate).toBe('2026-12-31T00:00:00.000Z');
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
});
});
describe('GET /api/v1/households/:householdId/cabinet/summary', () => {
it('returns aggregate summary', async () => {
mockGetAggregateSummary.mockResolvedValue([
{
_id: 'med-1',
medicineName: 'Metformin',
medicineStrength: 500,
medicineStrengthUnit: 'mg',
medicineForm: 'tablet',
totalQuantity: 60,
unit: 'tablet',
earliestExpiry: new Date('2026-06-01T00:00:00.000Z'),
itemCount: 2,
},
]);
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet/summary',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0].totalQuantity).toBe(60);
});
});
describe('GET /api/v1/households/:householdId/cabinet/expiring-soon', () => {
it('returns items expiring within N days', async () => {
mockFindExpiringSoon.mockResolvedValue([makeFakeCabinetItem()]);
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet/expiring-soon?days=30',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
});
});
describe('GET /api/v1/households/:householdId/cabinet/:id', () => {
it('returns a cabinet item', async () => {
mockFindById.mockResolvedValue(makeFakeCabinetItem());
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/cabinet/ci-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().quantity).toBe(30);
});
});
describe('POST /api/v1/households/:householdId/cabinet', () => {
it('creates a cabinet item', async () => {
mockMedicineFindById.mockResolvedValue({
_id: 'med-1',
name: 'Metformin',
strength: 500,
strengthUnit: 'mg',
form: 'tablet',
});
mockCreate.mockResolvedValue(makeFakeCabinetItem());
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/cabinet',
headers: authHeaders,
payload: {
medicineId: 'med-1',
quantity: 30,
unit: DosageUnit.TABLET,
},
});
expect(res.statusCode).toBe(201);
expect(res.json().medicineName).toBe('Metformin');
});
});
describe('PATCH /api/v1/households/:householdId/cabinet/:id', () => {
it('updates a cabinet item', async () => {
mockFindById.mockResolvedValue(makeFakeCabinetItem());
mockUpdate.mockResolvedValue(makeFakeCabinetItem({ quantity: 25 }));
const res = await app.inject({
method: 'PATCH',
url: '/api/v1/households/hh1/cabinet/ci-1',
headers: authHeaders,
payload: { quantity: 25 },
});
expect(res.statusCode).toBe(200);
expect(res.json().quantity).toBe(25);
});
});
describe('POST /api/v1/households/:householdId/cabinet/:id/adjust', () => {
it('adjusts quantity', async () => {
mockFindById.mockResolvedValue(makeFakeCabinetItem({ quantity: 30 }));
mockAdjustQuantity.mockResolvedValue(makeFakeCabinetItem({ quantity: 27 }));
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/cabinet/ci-1/adjust',
headers: authHeaders,
payload: { delta: -3 },
});
expect(res.statusCode).toBe(200);
expect(res.json().quantity).toBe(27);
});
});
describe('DELETE /api/v1/households/:householdId/cabinet/:id', () => {
it('soft deletes a cabinet item', async () => {
mockFindById.mockResolvedValue(makeFakeCabinetItem());
mockSoftDelete.mockResolvedValue(makeFakeCabinetItem({ isDeleted: true }));
const res = await app.inject({
method: 'DELETE',
url: '/api/v1/households/hh1/cabinet/ci-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(204);
});
});
});

View file

@ -0,0 +1,245 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
CreateCabinetItemSchema,
UpdateCabinetItemSchema,
AdjustQuantitySchema,
CabinetQuerySchema,
CabinetItemResponseSchema,
CabinetItemListResponseSchema,
CabinetSummaryResponseSchema,
} from '@meshitrack/shared';
import { CabinetRepository } from './cabinet.repository.js';
import { CabinetService } from './cabinet.service.js';
type AnyCabinetDoc = {
_id: string | { toString: () => string };
householdId: string;
medicineId: string;
medicineName: string;
medicineStrength: number;
medicineStrengthUnit: string;
medicineForm: string;
medicineProductId?: string | null;
medicineProductBrand?: string | null;
concentration?: number | null;
concentrationUnit?: string | null;
quantity: number;
unit: string;
expirationDate?: Date | string | null;
status: string;
notes?: string | null;
createdBy: string;
createdAt: string | { toISOString: () => string };
updatedAt: string | { toISOString: () => string };
};
function toStr(v: string | { toString: () => string }): string {
return typeof v === 'string' ? v : v.toString();
}
function toIso(v: string | Date | { toISOString: () => string }): string {
if (typeof v === 'string') return v;
if (v instanceof Date) return v.toISOString();
return v.toISOString();
}
function toOptIso(v: Date | string | null | undefined): string | undefined {
/* v8 ignore next */
if (!v) return undefined;
if (typeof v === 'string') return v;
return v.toISOString();
}
function toCabinetItemResponse(doc: AnyCabinetDoc): z.infer<typeof CabinetItemResponseSchema> {
return {
_id: toStr(doc._id),
householdId: doc.householdId,
medicineId: doc.medicineId,
medicineName: doc.medicineName,
medicineStrength: doc.medicineStrength,
medicineStrengthUnit: doc.medicineStrengthUnit,
medicineForm: doc.medicineForm,
...(doc.medicineProductId ? { medicineProductId: doc.medicineProductId } : {}),
...(doc.medicineProductBrand ? { medicineProductBrand: doc.medicineProductBrand } : {}),
...(doc.concentration != null ? { concentration: doc.concentration } : {}),
...(doc.concentrationUnit ? { concentrationUnit: doc.concentrationUnit } : {}),
quantity: doc.quantity,
unit: doc.unit,
...(doc.expirationDate ? { expirationDate: toOptIso(doc.expirationDate) } : {}),
status: doc.status,
...(doc.notes ? { notes: doc.notes } : {}),
createdBy: doc.createdBy,
createdAt: toIso(doc.createdAt),
updatedAt: toIso(doc.updatedAt),
};
}
declare module '@fastify/awilix' {
interface Cradle {
cabinetRepository: CabinetRepository;
cabinetService: CabinetService;
}
}
export default fp(
async (fastify) => {
fastify.diContainer.register({
cabinetRepository: asClass(CabinetRepository, { lifetime: Lifetime.SINGLETON }),
cabinetService: asClass(CabinetService, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
const householdParams = z.object({ householdId: z.string() });
// GET /api/v1/households/:householdId/cabinet — list items
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/cabinet',
schema: {
params: householdParams,
querystring: CabinetQuerySchema,
response: { 200: CabinetItemListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
const result = await service.list(request.params.householdId, request.query);
return reply.send({
data: result.data.map(toCabinetItemResponse),
pagination: result.pagination,
});
},
});
// GET /api/v1/households/:householdId/cabinet/summary — aggregate per medicine
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/cabinet/summary',
schema: {
params: householdParams,
response: { 200: CabinetSummaryResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
const data = await service.getSummary(request.params.householdId);
return reply.send({ data });
},
});
// GET /api/v1/households/:householdId/cabinet/expiring-soon — items expiring within N days
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/cabinet/expiring-soon',
schema: {
params: householdParams,
querystring: z.object({
days: z.coerce.number().int().min(1).max(365).default(30),
}),
response: {
200: z.object({ data: z.array(CabinetItemResponseSchema) }),
},
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
const items = await service.getExpiringSoon(request.params.householdId, request.query.days);
return reply.send({ data: items.map(toCabinetItemResponse) });
},
});
// GET /api/v1/households/:householdId/cabinet/:id — get single item
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/cabinet/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
response: { 200: CabinetItemResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
const item = await service.getById(request.params.id, request.params.householdId);
return reply.send(toCabinetItemResponse(item));
},
});
// POST /api/v1/households/:householdId/cabinet — add item
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/cabinet',
schema: {
params: householdParams,
body: CreateCabinetItemSchema,
response: { 201: CabinetItemResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
const item = await service.addItem(
request.body,
request.params.householdId,
request.user.keycloakId,
);
return reply.status(201).send(toCabinetItemResponse(item));
},
});
// PATCH /api/v1/households/:householdId/cabinet/:id — update item
app.route({
method: 'PATCH',
url: '/api/v1/households/:householdId/cabinet/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
body: UpdateCabinetItemSchema,
response: { 200: CabinetItemResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
const item = await service.update(
request.params.id,
request.params.householdId,
request.body,
);
return reply.send(toCabinetItemResponse(item));
},
});
// POST /api/v1/households/:householdId/cabinet/:id/adjust — adjust quantity
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/cabinet/:id/adjust',
schema: {
params: householdParams.extend({ id: z.string() }),
body: AdjustQuantitySchema,
response: { 200: CabinetItemResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
const item = await service.adjustQuantity(
request.params.id,
request.params.householdId,
request.body.delta,
);
return reply.send(toCabinetItemResponse(item));
},
});
// DELETE /api/v1/households/:householdId/cabinet/:id — soft delete
app.route({
method: 'DELETE',
url: '/api/v1/households/:householdId/cabinet/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
response: { 204: z.undefined() },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('cabinetService');
await service.delete(request.params.id, request.params.householdId);
return reply.status(204).send();
},
});
},
{
name: 'cabinet-routes',
dependencies: ['auth-plugin'],
},
);

View file

@ -0,0 +1,299 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { CabinetService } from './cabinet.service.js';
describe(CabinetService.name, () => {
const mockCabinetRepo = {
findByHousehold: vi.fn(),
findById: vi.fn(),
getAggregateSummary: vi.fn(),
create: vi.fn(),
update: vi.fn(),
adjustQuantity: vi.fn(),
findExpiringSoon: vi.fn(),
softDelete: vi.fn(),
countByMedicineId: vi.fn(),
};
const mockMedicinesRepo = {
findById: vi.fn(),
findByHousehold: vi.fn(),
findDuplicate: vi.fn(),
create: vi.fn(),
update: vi.fn(),
softDelete: vi.fn(),
};
const mockProductsRepo = {
findById: vi.fn(),
findByMedicine: vi.fn(),
create: vi.fn(),
update: vi.fn(),
softDelete: vi.fn(),
countByMedicineId: vi.fn(),
};
let service: CabinetService;
beforeEach(() => {
vi.clearAllMocks();
service = new CabinetService({
cabinetRepository: mockCabinetRepo as never,
medicinesRepository: mockMedicinesRepo as never,
medicineProductsRepository: mockProductsRepo as never,
});
});
describe('list', () => {
it('delegates to repository', async () => {
const result = { data: [], pagination: { cursor: null, hasMore: false } };
mockCabinetRepo.findByHousehold.mockResolvedValue(result);
const response = await service.list('hh1', { limit: 20 });
expect(response).toEqual(result);
expect(mockCabinetRepo.findByHousehold).toHaveBeenCalledWith('hh1', { limit: 20 });
});
});
describe('getById', () => {
it('returns item when found', async () => {
const item = { _id: 'ci-1', quantity: 30 };
mockCabinetRepo.findById.mockResolvedValue(item);
const result = await service.getById('ci-1', 'hh1');
expect(result).toEqual(item);
});
it('throws NotFoundError when not found', async () => {
mockCabinetRepo.findById.mockResolvedValue(null);
await expect(service.getById('ci-missing', 'hh1')).rejects.toThrow('Cabinet item not found');
});
});
describe('getSummary', () => {
it('returns aggregated summary with formatted dates', async () => {
const expiryDate = new Date('2026-06-01T00:00:00.000Z');
mockCabinetRepo.getAggregateSummary.mockResolvedValue([
{
_id: 'med-1',
medicineName: 'Metformin',
medicineStrength: 500,
medicineStrengthUnit: 'mg',
medicineForm: 'tablet',
totalQuantity: 60,
unit: 'tablet',
earliestExpiry: expiryDate,
itemCount: 2,
},
]);
const result = await service.getSummary('hh1');
expect(result).toHaveLength(1);
expect(result[0].medicineId).toBe('med-1');
expect(result[0].earliestExpiry).toBe('2026-06-01T00:00:00.000Z');
});
it('handles null expiry dates', async () => {
mockCabinetRepo.getAggregateSummary.mockResolvedValue([
{
_id: 'med-1',
medicineName: 'Test',
medicineStrength: 10,
medicineStrengthUnit: 'mg',
medicineForm: 'tablet',
totalQuantity: 30,
unit: 'tablet',
earliestExpiry: null,
itemCount: 1,
},
]);
const result = await service.getSummary('hh1');
expect(result[0].earliestExpiry).toBeNull();
});
});
describe('addItem', () => {
const createInput = {
medicineId: 'med-1',
quantity: 30,
unit: 'tablet' as const,
};
it('creates item with denormalized medicine fields', async () => {
mockMedicinesRepo.findById.mockResolvedValue({
_id: 'med-1',
name: 'Metformin',
strength: 500,
strengthUnit: 'mg',
form: 'tablet',
});
const created = { _id: 'ci-1', ...createInput, medicineName: 'Metformin' };
mockCabinetRepo.create.mockResolvedValue(created);
const result = await service.addItem(createInput, 'hh1', 'user-1');
expect(result).toEqual(created);
expect(mockCabinetRepo.create).toHaveBeenCalledWith(
expect.objectContaining({
medicineName: 'Metformin',
medicineStrength: 500,
medicineStrengthUnit: 'mg',
medicineForm: 'tablet',
}),
'hh1',
'user-1',
);
});
it('throws NotFoundError when medicine not found', async () => {
mockMedicinesRepo.findById.mockResolvedValue(null);
await expect(service.addItem(createInput, 'hh1', 'user-1')).rejects.toThrow(
'Medicine not found',
);
});
it('denormalizes product brand when medicineProductId given', async () => {
mockMedicinesRepo.findById.mockResolvedValue({
_id: 'med-1',
name: 'Metformin',
strength: 500,
strengthUnit: 'mg',
form: 'tablet',
});
mockProductsRepo.findById.mockResolvedValue({
_id: 'prod-1',
brand: 'Glucophage',
});
mockCabinetRepo.create.mockResolvedValue({ _id: 'ci-1' });
await service.addItem({ ...createInput, medicineProductId: 'prod-1' }, 'hh1', 'user-1');
expect(mockCabinetRepo.create).toHaveBeenCalledWith(
expect.objectContaining({ medicineProductBrand: 'Glucophage' }),
'hh1',
'user-1',
);
});
it('throws NotFoundError when product not found', async () => {
mockMedicinesRepo.findById.mockResolvedValue({
_id: 'med-1',
name: 'Metformin',
strength: 500,
strengthUnit: 'mg',
form: 'tablet',
});
mockProductsRepo.findById.mockResolvedValue(null);
await expect(
service.addItem({ ...createInput, medicineProductId: 'prod-missing' }, 'hh1', 'user-1'),
).rejects.toThrow('Medicine product not found');
});
});
describe('update', () => {
it('updates and returns item', async () => {
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1' });
const updated = { _id: 'ci-1', quantity: 25 };
mockCabinetRepo.update.mockResolvedValue(updated);
const result = await service.update('ci-1', 'hh1', { quantity: 25 });
expect(result).toEqual(updated);
});
it('throws NotFoundError when item does not exist', async () => {
mockCabinetRepo.findById.mockResolvedValue(null);
await expect(service.update('ci-missing', 'hh1', { quantity: 25 })).rejects.toThrow(
'Cabinet item not found',
);
});
it('throws NotFoundError when update returns null', async () => {
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1' });
mockCabinetRepo.update.mockResolvedValue(null);
await expect(service.update('ci-1', 'hh1', { quantity: 25 })).rejects.toThrow(
'Cabinet item not found',
);
});
});
describe('adjustQuantity', () => {
it('adjusts quantity and returns item', async () => {
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1', quantity: 30 });
const updated = { _id: 'ci-1', quantity: 27 };
mockCabinetRepo.adjustQuantity.mockResolvedValue(updated);
const result = await service.adjustQuantity('ci-1', 'hh1', -3);
expect(result).toEqual(updated);
});
it('throws BadRequestError when delta is 0', async () => {
await expect(service.adjustQuantity('ci-1', 'hh1', 0)).rejects.toThrow(
'Delta must be non-zero',
);
});
it('throws NotFoundError when item does not exist', async () => {
mockCabinetRepo.findById.mockResolvedValue(null);
await expect(service.adjustQuantity('ci-missing', 'hh1', 5)).rejects.toThrow(
'Cabinet item not found',
);
});
it('throws NotFoundError when adjust returns null', async () => {
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1' });
mockCabinetRepo.adjustQuantity.mockResolvedValue(null);
await expect(service.adjustQuantity('ci-1', 'hh1', 5)).rejects.toThrow(
'Cabinet item not found',
);
});
});
describe('getExpiringSoon', () => {
it('delegates to repository', async () => {
const items = [{ _id: 'ci-1' }];
mockCabinetRepo.findExpiringSoon.mockResolvedValue(items);
const result = await service.getExpiringSoon('hh1', 30);
expect(result).toEqual(items);
expect(mockCabinetRepo.findExpiringSoon).toHaveBeenCalledWith('hh1', 30);
});
});
describe('delete', () => {
it('soft deletes item', async () => {
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1' });
mockCabinetRepo.softDelete.mockResolvedValue({ _id: 'ci-1', isDeleted: true });
const result = await service.delete('ci-1', 'hh1');
expect(result.isDeleted).toBe(true);
});
it('throws NotFoundError when item does not exist', async () => {
mockCabinetRepo.findById.mockResolvedValue(null);
await expect(service.delete('ci-missing', 'hh1')).rejects.toThrow('Cabinet item not found');
});
it('throws NotFoundError when softDelete returns null', async () => {
mockCabinetRepo.findById.mockResolvedValue({ _id: 'ci-1' });
mockCabinetRepo.softDelete.mockResolvedValue(null);
await expect(service.delete('ci-1', 'hh1')).rejects.toThrow('Cabinet item not found');
});
});
});

View file

@ -0,0 +1,121 @@
import type { CabinetRepository } from './cabinet.repository.js';
import type { MedicinesRepository } from '../medicines/medicines.repository.js';
import type { MedicineProductsRepository } from '../medicine-products/medicine-products.repository.js';
import type {
CreateCabinetItemInput,
UpdateCabinetItemInput,
CabinetQueryInput,
} from '@meshitrack/shared';
import { NotFoundError, BadRequestError } from '../../common/errors.js';
interface Deps {
cabinetRepository: CabinetRepository;
medicinesRepository: MedicinesRepository;
medicineProductsRepository: MedicineProductsRepository;
}
export class CabinetService {
private readonly cabinetRepository: CabinetRepository;
private readonly medicinesRepository: MedicinesRepository;
private readonly medicineProductsRepository: MedicineProductsRepository;
public constructor({ cabinetRepository, medicinesRepository, medicineProductsRepository }: Deps) {
this.cabinetRepository = cabinetRepository;
this.medicinesRepository = medicinesRepository;
this.medicineProductsRepository = medicineProductsRepository;
}
public async list(householdId: string, query: CabinetQueryInput) {
return this.cabinetRepository.findByHousehold(householdId, query);
}
public async getById(id: string, householdId: string) {
const item = await this.cabinetRepository.findById(id, householdId);
if (!item) {
throw new NotFoundError('Cabinet item not found');
}
return item;
}
public async getSummary(householdId: string) {
const results = await this.cabinetRepository.getAggregateSummary(householdId);
return results.map((r: Record<string, unknown>) => ({
medicineId: r._id as string,
medicineName: r.medicineName as string,
medicineStrength: r.medicineStrength as number,
medicineStrengthUnit: r.medicineStrengthUnit as string,
medicineForm: r.medicineForm as string,
totalQuantity: r.totalQuantity as number,
unit: r.unit as string,
earliestExpiry: r.earliestExpiry ? (r.earliestExpiry as Date).toISOString() : null,
itemCount: r.itemCount as number,
}));
}
public async addItem(data: CreateCabinetItemInput, householdId: string, createdBy: string) {
const medicine = await this.medicinesRepository.findById(data.medicineId, householdId);
if (!medicine) {
throw new NotFoundError('Medicine not found');
}
let productBrand: string | undefined;
let concentration: number | undefined;
let concentrationUnit: string | undefined;
if (data.medicineProductId) {
const product = await this.medicineProductsRepository.findById(
data.medicineProductId,
householdId,
);
if (!product) {
throw new NotFoundError('Medicine product not found');
}
productBrand = product.brand;
concentration = product.concentration ?? undefined;
concentrationUnit = product.concentrationUnit ?? undefined;
}
return this.cabinetRepository.create(
{
...data,
medicineName: medicine.name,
medicineStrength: medicine.strength,
medicineStrengthUnit: medicine.strengthUnit,
medicineForm: medicine.form,
medicineProductBrand: productBrand,
concentration,
concentrationUnit,
},
householdId,
createdBy,
);
}
public async update(id: string, householdId: string, data: UpdateCabinetItemInput) {
await this.getById(id, householdId);
const updated = await this.cabinetRepository.update(id, householdId, data);
if (!updated) throw new NotFoundError('Cabinet item not found');
return updated;
}
public async adjustQuantity(id: string, householdId: string, delta: number) {
if (delta === 0) {
throw new BadRequestError('Delta must be non-zero');
}
await this.getById(id, householdId);
const updated = await this.cabinetRepository.adjustQuantity(id, householdId, delta);
if (!updated) throw new NotFoundError('Cabinet item not found');
return updated;
}
public async getExpiringSoon(householdId: string, withinDays: number) {
return this.cabinetRepository.findExpiringSoon(householdId, withinDays);
}
public async delete(id: string, householdId: string) {
await this.getById(id, householdId);
const deleted = await this.cabinetRepository.softDelete(id, householdId);
if (!deleted) throw new NotFoundError('Cabinet item not found');
return deleted;
}
}

View file

@ -56,6 +56,7 @@ vi.mock('../users/users.repository.js', () => ({
UsersRepository: class {
findByKeycloakId = mockFindByKeycloakId;
update = mockUserUpdate;
upsertFromToken = vi.fn().mockResolvedValue({ householdIds: ['hh1'] });
},
}));
@ -117,6 +118,8 @@ describe('households.routes', () => {
beforeEach(async () => {
vi.clearAllMocks();
// Default: auth plugin finds user with hh1 membership (routes with householdId guard pass)
mockFindByKeycloakId.mockResolvedValue({ householdIds: ['hh1'], defaultHouseholdId: null });
app = await buildTestApp();
});
@ -143,6 +146,43 @@ describe('households.routes', () => {
});
});
describe('POST /api/v1/households (ObjectId/Date conversion)', () => {
it('handles ObjectId and Date objects in response', async () => {
const household = makeFakeHousehold({
_id: { toString: () => 'hh-obj' },
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
members: [
{
userId: 'kc-1',
role: HouseholdRole.OWNER,
joinedAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
},
],
settings: null,
});
mockCreate.mockResolvedValue(household);
mockFindByKeycloakId.mockResolvedValue({ householdIds: [], defaultHouseholdId: null });
mockUserUpdate.mockResolvedValue({});
const res = await app.inject({
method: 'POST',
url: '/api/v1/households',
headers: authHeaders,
payload: { name: 'Test' },
});
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body._id).toBe('hh-obj');
expect(body.createdAt).toBe('2024-01-01T00:00:00.000Z');
expect(body.members[0].joinedAt).toBe('2024-01-01T00:00:00.000Z');
expect(body.settings.timezone).toBe('UTC');
expect(body.settings.currency).toBe('USD');
expect(body.settings.language).toBe('en');
});
});
describe('GET /api/v1/households/:id', () => {
it('returns a household', async () => {
const household = makeFakeHousehold();

View file

@ -93,6 +93,15 @@ describe('HouseholdsService', () => {
);
});
it('aborts transaction on error', async () => {
mockHouseholdsRepo.create.mockRejectedValue(new Error('DB error'));
await expect(service.create({ name: 'Test' }, 'kc-1')).rejects.toThrow('DB error');
expect(mockSession.abortTransaction).toHaveBeenCalled();
expect(mockSession.endSession).toHaveBeenCalled();
});
it('handles case when owner user not found in db', async () => {
const household = { _id: 'hh1', name: 'Test', ownerUserId: 'kc-1' };
mockHouseholdsRepo.create.mockResolvedValue(household);
@ -153,6 +162,16 @@ describe('HouseholdsService', () => {
await expect(service.update('hh1', { name: 'X' }, 'kc-3')).rejects.toThrow(ForbiddenError);
});
it('throws NotFoundError when repo update returns null', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
});
mockHouseholdsRepo.update.mockResolvedValue(null);
await expect(service.update('hh1', { name: 'X' }, 'kc-1')).rejects.toThrow(NotFoundError);
});
it('throws ForbiddenError for non-member', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
@ -186,6 +205,16 @@ describe('HouseholdsService', () => {
await expect(service.generateInviteCode('hh1', 'kc-3')).rejects.toThrow(ForbiddenError);
});
it('throws NotFoundError when updateInviteCode returns null', async () => {
mockHouseholdsRepo.findById.mockResolvedValue({
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
});
mockHouseholdsRepo.updateInviteCode.mockResolvedValue(null);
await expect(service.generateInviteCode('hh1', 'kc-1')).rejects.toThrow(NotFoundError);
});
});
describe('join', () => {
@ -236,6 +265,31 @@ describe('HouseholdsService', () => {
await expect(service.join('CODE', 'kc-1')).rejects.toThrow(ConflictError);
});
it('throws NotFoundError when addMember returns null', async () => {
const household = {
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
};
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
mockHouseholdsRepo.addMember.mockResolvedValue(null);
await expect(service.join('CODE', 'kc-2')).rejects.toThrow(NotFoundError);
});
it('aborts transaction on error during join', async () => {
const household = {
_id: 'hh1',
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
};
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
mockHouseholdsRepo.addMember.mockRejectedValue(new Error('DB error'));
await expect(service.join('CODE', 'kc-2')).rejects.toThrow('DB error');
expect(mockSession.abortTransaction).toHaveBeenCalled();
expect(mockSession.endSession).toHaveBeenCalled();
});
it('handles case when joining user not found in db', async () => {
const household = {
_id: 'hh1',

View file

@ -0,0 +1,192 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { DosageUnit, MedicineProductSource } from '@meshitrack/shared';
const {
mockExec,
_mockLean,
mockFind,
mockFindOne,
mockFindOneAndUpdate,
mockSave,
_mockSort,
_mockLimit,
mockCountDocuments,
} = vi.hoisted(() => {
const mockExec = vi.fn();
const mockLean = vi.fn(() => ({ exec: mockExec }));
const mockLimit = vi.fn(() => ({ lean: mockLean }));
const mockSort = vi.fn(() => ({ limit: mockLimit }));
const mockCountDocuments = vi.fn();
return {
mockExec,
mockLean,
mockFind: vi.fn(() => ({ sort: mockSort })),
mockFindOne: vi.fn(() => ({ lean: mockLean })),
mockFindOneAndUpdate: vi.fn(() => ({ exec: mockExec })),
mockSave: vi.fn(),
mockSort,
mockLimit,
mockCountDocuments,
};
});
vi.mock('../../schemas/medicine-product.schema.js', () => {
class MockMedicineProductModel {
_data: Record<string, unknown>;
constructor(data: Record<string, unknown>) {
this._data = data;
Object.assign(this, data);
}
save() {
mockSave();
return Promise.resolve(this);
}
toObject() {
return { _id: 'mp-new', ...this._data };
}
static find = mockFind;
static findOne = mockFindOne;
static findOneAndUpdate = mockFindOneAndUpdate;
static countDocuments = vi.fn(() => ({ exec: mockCountDocuments }));
}
return { MedicineProductModel: MockMedicineProductModel };
});
import { MedicineProductsRepository } from './medicine-products.repository.js';
describe(MedicineProductsRepository.name, () => {
let repo: MedicineProductsRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new MedicineProductsRepository();
});
describe('findByMedicine', () => {
it('returns paginated results', async () => {
const items = [
{ _id: 'mp-1', brand: 'CVS' },
{ _id: 'mp-2', brand: 'Kirkland' },
];
mockExec.mockResolvedValue(items);
const result = await repo.findByMedicine('hh1', 'med-1', { limit: 20 });
expect(mockFind).toHaveBeenCalledWith({
householdId: 'hh1',
medicineId: 'med-1',
isDeleted: false,
});
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(false);
});
it('detects hasMore when extra item returned', async () => {
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `mp-${i}`, brand: `Brand ${i}` }));
mockExec.mockResolvedValue(items);
const result = await repo.findByMedicine('hh1', 'med-1', { limit: 2 });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(true);
expect(result.pagination.cursor).toBeTruthy();
});
it('decodes cursor for pagination', async () => {
mockExec.mockResolvedValue([]);
const cursor = Buffer.from('mp-5').toString('base64');
await repo.findByMedicine('hh1', 'med-1', { cursor, limit: 20 });
expect(mockFind).toHaveBeenCalledWith(expect.objectContaining({ _id: { $gt: 'mp-5' } }));
});
it('returns null cursor when no data', async () => {
mockExec.mockResolvedValue([]);
const result = await repo.findByMedicine('hh1', 'med-1', { limit: 20 });
expect(result.pagination.cursor).toBeNull();
expect(result.pagination.hasMore).toBe(false);
});
});
describe('findById', () => {
it('finds by id and householdId', async () => {
const product = { _id: 'mp-1', brand: 'CVS' };
mockExec.mockResolvedValue(product);
const result = await repo.findById('mp-1', 'hh1');
expect(mockFindOne).toHaveBeenCalledWith({
_id: 'mp-1',
householdId: 'hh1',
isDeleted: false,
});
expect(result).toEqual(product);
});
});
describe('create', () => {
it('creates a medicine product', async () => {
mockSave.mockResolvedValue({});
const data = {
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
source: MedicineProductSource.MANUAL,
};
const result = await repo.create(data, 'hh1', 'med-1', 'Metformin', 'kc-1');
expect(mockSave).toHaveBeenCalled();
expect(result).toMatchObject({
brand: 'CVS Health',
householdId: 'hh1',
medicineId: 'med-1',
medicineName: 'Metformin',
createdBy: 'kc-1',
});
});
});
describe('update', () => {
it('updates a medicine product', async () => {
mockExec.mockResolvedValue({ _id: 'mp-1', brand: 'Updated' });
const result = await repo.update('mp-1', 'hh1', { brand: 'Updated' });
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'mp-1', householdId: 'hh1', isDeleted: false },
{ $set: { brand: 'Updated' } },
{ new: true, lean: true },
);
expect(result).toEqual({ _id: 'mp-1', brand: 'Updated' });
});
});
describe('softDelete', () => {
it('sets isDeleted to true', async () => {
mockExec.mockResolvedValue({ _id: 'mp-1', isDeleted: true });
await repo.softDelete('mp-1', 'hh1');
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'mp-1', householdId: 'hh1', isDeleted: false },
{ $set: { isDeleted: true } },
{ new: true, lean: true },
);
});
});
describe('countByMedicineId', () => {
it('returns count of non-deleted products for medicine', async () => {
mockCountDocuments.mockResolvedValue(3);
const result = await repo.countByMedicineId('med-1');
expect(result).toBe(3);
});
});
});

View file

@ -0,0 +1,74 @@
import { MedicineProductModel } from '../../schemas/medicine-product.schema.js';
import type { CreateMedicineProductInput, UpdateMedicineProductInput } from '@meshitrack/shared';
interface FindByMedicineQuery {
cursor?: string;
limit: number;
}
export class MedicineProductsRepository {
public async findByMedicine(householdId: string, medicineId: string, query: FindByMedicineQuery) {
const filter: Record<string, unknown> = { householdId, medicineId, isDeleted: false };
if (query.cursor) {
const id = Buffer.from(query.cursor, 'base64').toString();
filter['_id'] = { $gt: id };
}
const limit = query.limit;
const items = await MedicineProductModel.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 findById(id: string, householdId: string) {
return MedicineProductModel.findOne({ _id: id, householdId, isDeleted: false }).lean().exec();
}
public async create(
data: CreateMedicineProductInput,
householdId: string,
medicineId: string,
medicineName: string,
createdBy: string,
) {
const product = new MedicineProductModel({
...data,
householdId,
medicineId,
medicineName,
createdBy,
});
const saved = await product.save();
return saved.toObject();
}
public async update(id: string, householdId: string, data: UpdateMedicineProductInput) {
return MedicineProductModel.findOneAndUpdate(
{ _id: id, householdId, isDeleted: false },
{ $set: data },
{ new: true, lean: true },
).exec();
}
public async countByMedicineId(medicineId: string): Promise<number> {
return MedicineProductModel.countDocuments({ medicineId, isDeleted: false }).exec();
}
public async softDelete(id: string, householdId: string) {
return MedicineProductModel.findOneAndUpdate(
{ _id: id, householdId, isDeleted: false },
{ $set: { isDeleted: true } },
{ new: true, lean: true },
).exec();
}
}

View file

@ -0,0 +1,234 @@
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';
import { DosageUnit, MedicineProductSource } from '@meshitrack/shared';
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 {
mockFindByMedicine,
mockFindById,
mockCreate,
mockUpdate,
mockSoftDelete,
mockMedicineFindById,
} = vi.hoisted(() => ({
mockFindByMedicine: vi.fn(),
mockFindById: vi.fn(),
mockCreate: vi.fn(),
mockUpdate: vi.fn(),
mockSoftDelete: vi.fn(),
mockMedicineFindById: vi.fn(),
}));
vi.mock('./medicine-products.repository.js', () => ({
MedicineProductsRepository: class {
findByMedicine = mockFindByMedicine;
findById = mockFindById;
create = mockCreate;
update = mockUpdate;
softDelete = mockSoftDelete;
},
}));
vi.mock('../medicines/medicines.repository.js', () => ({
MedicinesRepository: class {
findById = mockMedicineFindById;
},
}));
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 medicinesRoutes from '../medicines/medicines.routes.js';
import medicineProductsRoutes from './medicine-products.routes.js';
function makeFakeProduct(overrides = {}) {
return {
_id: 'mp-1',
householdId: 'hh1',
medicineId: 'med-1',
medicineName: 'Metformin',
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
source: MedicineProductSource.MANUAL,
createdBy: 'kc-1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
};
}
describe('medicine-products.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(medicinesRoutes);
await instance.register(medicineProductsRoutes);
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 /api/v1/households/:householdId/medicines/:medicineId/products', () => {
it('returns paginated list', async () => {
const product = makeFakeProduct();
mockFindByMedicine.mockResolvedValue({
data: [product],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicines/med-1/products',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0].brand).toBe('CVS Health');
expect(body.pagination.hasMore).toBe(false);
});
it('handles ObjectId and Date objects in response', async () => {
const product = makeFakeProduct({
_id: { toString: () => 'mp-obj' },
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
manufacturer: 'Pfizer',
imageUrl: 'https://example.com/img.png',
notes: 'Store in cool place',
});
mockFindByMedicine.mockResolvedValue({
data: [product],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicines/med-1/products',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0]._id).toBe('mp-obj');
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
expect(body.data[0].manufacturer).toBe('Pfizer');
expect(body.data[0].imageUrl).toBe('https://example.com/img.png');
expect(body.data[0].notes).toBe('Store in cool place');
});
});
describe('GET /api/v1/households/:householdId/medicine-products/:id', () => {
it('returns a product', async () => {
mockFindById.mockResolvedValue(makeFakeProduct());
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicine-products/mp-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().brand).toBe('CVS Health');
});
});
describe('POST /api/v1/households/:householdId/medicines/:medicineId/products', () => {
it('creates a product', async () => {
mockMedicineFindById.mockResolvedValue({ _id: 'med-1', name: 'Metformin' });
mockCreate.mockResolvedValue(makeFakeProduct());
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/medicines/med-1/products',
headers: authHeaders,
payload: {
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
},
});
expect(res.statusCode).toBe(201);
expect(res.json().brand).toBe('CVS Health');
});
});
describe('PATCH /api/v1/households/:householdId/medicine-products/:id', () => {
it('updates a product', async () => {
mockFindById.mockResolvedValue(makeFakeProduct());
mockUpdate.mockResolvedValue(makeFakeProduct({ brand: 'Updated' }));
const res = await app.inject({
method: 'PATCH',
url: '/api/v1/households/hh1/medicine-products/mp-1',
headers: authHeaders,
payload: { brand: 'Updated' },
});
expect(res.statusCode).toBe(200);
expect(res.json().brand).toBe('Updated');
});
});
describe('DELETE /api/v1/households/:householdId/medicine-products/:id', () => {
it('soft deletes a product', async () => {
mockFindById.mockResolvedValue(makeFakeProduct());
mockSoftDelete.mockResolvedValue(makeFakeProduct({ isDeleted: true }));
const res = await app.inject({
method: 'DELETE',
url: '/api/v1/households/hh1/medicine-products/mp-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(204);
});
});
});

View file

@ -0,0 +1,183 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
CreateMedicineProductSchema,
UpdateMedicineProductSchema,
MedicineProductResponseSchema,
MedicineProductListResponseSchema,
} from '@meshitrack/shared';
import { MedicineProductsRepository } from './medicine-products.repository.js';
import { MedicineProductsService } from './medicine-products.service.js';
type AnyProductDoc = {
_id: string | { toString: () => string };
householdId: string;
medicineId: string;
medicineName: string;
brand: string;
manufacturer?: string | null;
packageSize: number;
packageUnit: string;
concentration?: number | null;
concentrationUnit?: string | null;
imageUrl?: string | null;
notes?: string | null;
source: string;
createdBy: string;
createdAt: string | { toISOString: () => string };
updatedAt: string | { toISOString: () => string };
};
function toStr(v: string | { toString: () => string }): string {
return typeof v === 'string' ? v : v.toString();
}
function toIso(v: string | { toISOString: () => string }): string {
return typeof v === 'string' ? v : v.toISOString();
}
function toProductResponse(doc: AnyProductDoc): z.infer<typeof MedicineProductResponseSchema> {
return {
_id: toStr(doc._id),
householdId: doc.householdId,
medicineId: doc.medicineId,
medicineName: doc.medicineName,
brand: doc.brand,
...(doc.manufacturer ? { manufacturer: doc.manufacturer } : {}),
packageSize: doc.packageSize,
packageUnit: doc.packageUnit,
...(doc.concentration ? { concentration: doc.concentration } : {}),
...(doc.concentrationUnit ? { concentrationUnit: doc.concentrationUnit } : {}),
...(doc.imageUrl ? { imageUrl: doc.imageUrl } : {}),
...(doc.notes ? { notes: doc.notes } : {}),
source: doc.source,
createdBy: doc.createdBy,
createdAt: toIso(doc.createdAt),
updatedAt: toIso(doc.updatedAt),
};
}
declare module '@fastify/awilix' {
interface Cradle {
medicineProductsRepository: MedicineProductsRepository;
medicineProductsService: MedicineProductsService;
}
}
export default fp(
async (fastify) => {
fastify.diContainer.register({
medicineProductsRepository: asClass(MedicineProductsRepository, {
lifetime: Lifetime.SINGLETON,
}),
medicineProductsService: asClass(MedicineProductsService, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
const householdParams = z.object({ householdId: z.string() });
const paginationQuery = z.object({
cursor: z.string().optional(),
limit: z.coerce.number().int().min(1).max(100).default(20),
});
// GET /api/v1/households/:householdId/medicines/:medicineId/products — list by medicine
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/medicines/:medicineId/products',
schema: {
params: householdParams.extend({ medicineId: z.string() }),
querystring: paginationQuery,
response: { 200: MedicineProductListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicineProductsService');
const result = await service.listByMedicine(
request.params.householdId,
request.params.medicineId,
request.query,
);
return reply.send({
data: result.data.map(toProductResponse),
pagination: result.pagination,
});
},
});
// GET /api/v1/households/:householdId/medicine-products/:id — get by id
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/medicine-products/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
response: { 200: MedicineProductResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicineProductsService');
const product = await service.getById(request.params.id, request.params.householdId);
return reply.send(toProductResponse(product));
},
});
// POST /api/v1/households/:householdId/medicines/:medicineId/products — create
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/medicines/:medicineId/products',
schema: {
params: householdParams.extend({ medicineId: z.string() }),
body: CreateMedicineProductSchema,
response: { 201: MedicineProductResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicineProductsService');
const product = await service.create(
request.body,
request.params.householdId,
request.params.medicineId,
request.user.keycloakId,
);
return reply.status(201).send(toProductResponse(product));
},
});
// PATCH /api/v1/households/:householdId/medicine-products/:id — update
app.route({
method: 'PATCH',
url: '/api/v1/households/:householdId/medicine-products/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
body: UpdateMedicineProductSchema,
response: { 200: MedicineProductResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicineProductsService');
const product = await service.update(
request.params.id,
request.params.householdId,
request.body,
);
return reply.send(toProductResponse(product));
},
});
// DELETE /api/v1/households/:householdId/medicine-products/:id — soft delete
app.route({
method: 'DELETE',
url: '/api/v1/households/:householdId/medicine-products/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
response: { 204: z.undefined() },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicineProductsService');
await service.delete(request.params.id, request.params.householdId);
return reply.status(204).send();
},
});
},
{
name: 'medicine-products-routes',
dependencies: ['auth-plugin'],
},
);

View file

@ -0,0 +1,140 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MedicineProductsService } from './medicine-products.service.js';
import { NotFoundError } from '../../common/errors.js';
import { DosageUnit, MedicineProductSource } from '@meshitrack/shared';
describe(MedicineProductsService.name, () => {
const mockProductsRepo = {
findByMedicine: vi.fn(),
findById: vi.fn(),
create: vi.fn(),
update: vi.fn(),
softDelete: vi.fn(),
};
const mockMedicinesRepo = {
findById: vi.fn(),
};
let service: MedicineProductsService;
beforeEach(() => {
vi.clearAllMocks();
service = new MedicineProductsService({
medicineProductsRepository: mockProductsRepo as never,
medicinesRepository: mockMedicinesRepo as never,
});
});
describe('listByMedicine', () => {
it('delegates to repository', async () => {
const expected = { data: [], pagination: { cursor: null, hasMore: false } };
mockProductsRepo.findByMedicine.mockResolvedValue(expected);
const result = await service.listByMedicine('hh1', 'med-1', { limit: 20 });
expect(mockProductsRepo.findByMedicine).toHaveBeenCalledWith('hh1', 'med-1', { limit: 20 });
expect(result).toEqual(expected);
});
});
describe('getById', () => {
it('returns product when found', async () => {
const product = { _id: 'mp-1', brand: 'CVS' };
mockProductsRepo.findById.mockResolvedValue(product);
const result = await service.getById('mp-1', 'hh1');
expect(result).toEqual(product);
});
it('throws NotFoundError when not found', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(service.getById('missing', 'hh1')).rejects.toThrow(NotFoundError);
});
});
describe('create', () => {
const data = {
brand: 'CVS Health',
packageSize: 90,
packageUnit: DosageUnit.TABLET,
source: MedicineProductSource.MANUAL,
};
it('creates when parent medicine exists', async () => {
mockMedicinesRepo.findById.mockResolvedValue({ _id: 'med-1', name: 'Metformin' });
mockProductsRepo.create.mockResolvedValue({
_id: 'mp-1',
...data,
medicineName: 'Metformin',
});
const result = await service.create(data, 'hh1', 'med-1', 'kc-1');
expect(mockMedicinesRepo.findById).toHaveBeenCalledWith('med-1', 'hh1');
expect(mockProductsRepo.create).toHaveBeenCalledWith(
data,
'hh1',
'med-1',
'Metformin',
'kc-1',
);
expect(result._id).toBe('mp-1');
});
it('throws NotFoundError when parent medicine does not exist', async () => {
mockMedicinesRepo.findById.mockResolvedValue(null);
await expect(service.create(data, 'hh1', 'missing', 'kc-1')).rejects.toThrow(NotFoundError);
expect(mockProductsRepo.create).not.toHaveBeenCalled();
});
});
describe('update', () => {
it('updates a product', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1', brand: 'CVS' });
mockProductsRepo.update.mockResolvedValue({ _id: 'mp-1', brand: 'Updated' });
const result = await service.update('mp-1', 'hh1', { brand: 'Updated' });
expect(result.brand).toBe('Updated');
});
it('throws NotFoundError when product does not exist', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(service.update('missing', 'hh1', { brand: 'X' })).rejects.toThrow(NotFoundError);
});
it('throws NotFoundError when update returns null', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1' });
mockProductsRepo.update.mockResolvedValue(null);
await expect(service.update('mp-1', 'hh1', { brand: 'X' })).rejects.toThrow(NotFoundError);
});
});
describe('delete', () => {
it('soft deletes a product', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1' });
mockProductsRepo.softDelete.mockResolvedValue({ _id: 'mp-1', isDeleted: true });
await service.delete('mp-1', 'hh1');
expect(mockProductsRepo.softDelete).toHaveBeenCalledWith('mp-1', 'hh1');
});
it('throws NotFoundError when not found', async () => {
mockProductsRepo.findById.mockResolvedValue(null);
await expect(service.delete('missing', 'hh1')).rejects.toThrow(NotFoundError);
});
it('throws NotFoundError when softDelete returns null', async () => {
mockProductsRepo.findById.mockResolvedValue({ _id: 'mp-1' });
mockProductsRepo.softDelete.mockResolvedValue(null);
await expect(service.delete('mp-1', 'hh1')).rejects.toThrow(NotFoundError);
});
});
});

View file

@ -0,0 +1,69 @@
import type { MedicineProductsRepository } from './medicine-products.repository.js';
import type { MedicinesRepository } from '../medicines/medicines.repository.js';
import type { CreateMedicineProductInput, UpdateMedicineProductInput } from '@meshitrack/shared';
import { NotFoundError } from '../../common/errors.js';
interface Deps {
medicineProductsRepository: MedicineProductsRepository;
medicinesRepository: MedicinesRepository;
}
export class MedicineProductsService {
private readonly medicineProductsRepository: MedicineProductsRepository;
private readonly medicinesRepository: MedicinesRepository;
public constructor({ medicineProductsRepository, medicinesRepository }: Deps) {
this.medicineProductsRepository = medicineProductsRepository;
this.medicinesRepository = medicinesRepository;
}
public async listByMedicine(
householdId: string,
medicineId: string,
query: { cursor?: string; limit: number },
) {
return this.medicineProductsRepository.findByMedicine(householdId, medicineId, query);
}
public async getById(id: string, householdId: string) {
const product = await this.medicineProductsRepository.findById(id, householdId);
if (!product) {
throw new NotFoundError('Medicine product not found');
}
return product;
}
public async create(
data: CreateMedicineProductInput,
householdId: string,
medicineId: string,
createdBy: string,
) {
const medicine = await this.medicinesRepository.findById(medicineId, householdId);
if (!medicine) {
throw new NotFoundError('Medicine not found');
}
return this.medicineProductsRepository.create(
data,
householdId,
medicineId,
medicine.name,
createdBy,
);
}
public async update(id: string, householdId: string, data: UpdateMedicineProductInput) {
await this.getById(id, householdId);
const updated = await this.medicineProductsRepository.update(id, householdId, data);
if (!updated) throw new NotFoundError('Medicine product not found');
return updated;
}
public async delete(id: string, householdId: string) {
await this.getById(id, householdId);
const deleted = await this.medicineProductsRepository.softDelete(id, householdId);
if (!deleted) throw new NotFoundError('Medicine product not found');
return deleted;
}
}

View file

@ -0,0 +1,215 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';
const {
mockExec,
_mockLean,
mockFind,
mockFindOne,
mockFindOneAndUpdate,
mockSave,
_mockSort,
_mockLimit,
} = vi.hoisted(() => {
const mockExec = vi.fn();
const mockLean = vi.fn(() => ({ exec: mockExec }));
const mockLimit = vi.fn(() => ({ lean: mockLean }));
const mockSort = vi.fn(() => ({ limit: mockLimit }));
return {
mockExec,
mockLean,
mockFind: vi.fn(() => ({ sort: mockSort })),
mockFindOne: vi.fn(() => ({ lean: mockLean })),
mockFindOneAndUpdate: vi.fn(() => ({ exec: mockExec })),
mockSave: vi.fn(),
mockSort,
mockLimit,
};
});
vi.mock('../../schemas/medicine.schema.js', () => {
class MockMedicineModel {
_data: Record<string, unknown>;
constructor(data: Record<string, unknown>) {
this._data = data;
Object.assign(this, data);
}
save() {
mockSave();
return Promise.resolve(this);
}
toObject() {
return { _id: 'med-new', ...this._data };
}
static find = mockFind;
static findOne = mockFindOne;
static findOneAndUpdate = mockFindOneAndUpdate;
}
return { MedicineModel: MockMedicineModel };
});
import { MedicinesRepository } from './medicines.repository.js';
describe(MedicinesRepository.name, () => {
let repo: MedicinesRepository;
beforeEach(() => {
vi.clearAllMocks();
repo = new MedicinesRepository();
});
describe('findByHousehold', () => {
it('returns paginated results', async () => {
const items = [
{ _id: 'med-1', name: 'Aspirin' },
{ _id: 'med-2', name: 'Ibuprofen' },
];
mockExec.mockResolvedValue(items);
const result = await repo.findByHousehold('hh1', { limit: 20 });
expect(mockFind).toHaveBeenCalledWith({ householdId: 'hh1', isDeleted: false });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(false);
});
it('applies partial name search when q is provided', async () => {
mockExec.mockResolvedValue([]);
await repo.findByHousehold('hh1', { q: 'asp', limit: 20 });
expect(mockFind).toHaveBeenCalledWith(
expect.objectContaining({ name: { $regex: 'asp', $options: 'i' } }),
);
});
it('applies category filter', async () => {
mockExec.mockResolvedValue([]);
await repo.findByHousehold('hh1', { category: MedicineCategory.PRESCRIPTION, limit: 20 });
expect(mockFind).toHaveBeenCalledWith(
expect.objectContaining({ category: MedicineCategory.PRESCRIPTION }),
);
});
it('applies form filter', async () => {
mockExec.mockResolvedValue([]);
await repo.findByHousehold('hh1', { form: MedicineForm.TABLET, limit: 20 });
expect(mockFind).toHaveBeenCalledWith(expect.objectContaining({ form: MedicineForm.TABLET }));
});
it('detects hasMore when extra item returned', async () => {
const items = Array.from({ length: 3 }, (_, i) => ({ _id: `med-${i}`, name: `Med ${i}` }));
mockExec.mockResolvedValue(items);
const result = await repo.findByHousehold('hh1', { limit: 2 });
expect(result.data).toHaveLength(2);
expect(result.pagination.hasMore).toBe(true);
expect(result.pagination.cursor).toBeTruthy();
});
it('decodes cursor for pagination', async () => {
mockExec.mockResolvedValue([]);
const cursor = Buffer.from('med-5').toString('base64');
await repo.findByHousehold('hh1', { cursor, limit: 20 });
expect(mockFind).toHaveBeenCalledWith(expect.objectContaining({ _id: { $gt: 'med-5' } }));
});
});
describe('findById', () => {
it('finds by id and householdId', async () => {
const medicine = { _id: 'med-1', name: 'Aspirin' };
mockExec.mockResolvedValue(medicine);
const result = await repo.findById('med-1', 'hh1');
expect(mockFindOne).toHaveBeenCalledWith({
_id: 'med-1',
householdId: 'hh1',
isDeleted: false,
});
expect(result).toEqual(medicine);
});
});
describe('findDuplicate', () => {
it('finds medicine with matching fields', async () => {
mockExec.mockResolvedValue({ _id: 'med-1' });
const result = await repo.findDuplicate('hh1', 'Aspirin', 500, 'mg', 'tablet');
expect(mockFindOne).toHaveBeenCalledWith({
householdId: 'hh1',
name: 'Aspirin',
strength: 500,
strengthUnit: 'mg',
form: 'tablet',
isDeleted: false,
});
expect(result).toBeTruthy();
});
it('excludes specified id', async () => {
mockExec.mockResolvedValue(null);
await repo.findDuplicate('hh1', 'Aspirin', 500, 'mg', 'tablet', 'med-1');
expect(mockFindOne).toHaveBeenCalledWith(expect.objectContaining({ _id: { $ne: 'med-1' } }));
});
});
describe('create', () => {
it('creates a medicine', async () => {
mockSave.mockResolvedValue({});
const data = {
name: 'Aspirin',
form: MedicineForm.TABLET,
strength: 500,
strengthUnit: StrengthUnit.MG,
category: MedicineCategory.OTC,
tags: [],
};
const result = await repo.create(data, 'hh1', 'kc-1');
expect(mockSave).toHaveBeenCalled();
expect(result).toMatchObject({ name: 'Aspirin', householdId: 'hh1', createdBy: 'kc-1' });
});
});
describe('update', () => {
it('updates a medicine', async () => {
mockExec.mockResolvedValue({ _id: 'med-1', name: 'Updated' });
const result = await repo.update('med-1', 'hh1', { name: 'Updated' });
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'med-1', householdId: 'hh1', isDeleted: false },
{ $set: { name: 'Updated' } },
{ new: true, lean: true },
);
expect(result).toEqual({ _id: 'med-1', name: 'Updated' });
});
});
describe('softDelete', () => {
it('sets isDeleted to true', async () => {
mockExec.mockResolvedValue({ _id: 'med-1', isDeleted: true });
await repo.softDelete('med-1', 'hh1');
expect(mockFindOneAndUpdate).toHaveBeenCalledWith(
{ _id: 'med-1', householdId: 'hh1', isDeleted: false },
{ $set: { isDeleted: true } },
{ new: true, lean: true },
);
});
});
});

View file

@ -0,0 +1,81 @@
import { MedicineModel } from '../../schemas/medicine.schema.js';
import type {
CreateMedicineInput,
UpdateMedicineInput,
MedicineQueryInput,
} from '@meshitrack/shared';
export class MedicinesRepository {
public async findByHousehold(householdId: string, query: MedicineQueryInput) {
const filter: Record<string, unknown> = { householdId, isDeleted: false };
if (query.category) filter['category'] = query.category;
if (query.form) filter['form'] = query.form;
if (query.q) filter['name'] = { $regex: query.q, $options: 'i' };
if (query.cursor) {
const id = Buffer.from(query.cursor, 'base64').toString();
filter['_id'] = { $gt: id };
}
const limit = query.limit;
const items = await MedicineModel.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 findById(id: string, householdId: string) {
return MedicineModel.findOne({ _id: id, householdId, isDeleted: false }).lean().exec();
}
public async findDuplicate(
householdId: string,
name: string,
strength: number,
strengthUnit: string,
form: string,
excludeId?: string,
) {
const filter: Record<string, unknown> = {
householdId,
name,
strength,
strengthUnit,
form,
isDeleted: false,
};
if (excludeId) filter['_id'] = { $ne: excludeId };
return MedicineModel.findOne(filter).lean().exec();
}
public async create(data: CreateMedicineInput, householdId: string, createdBy: string) {
const medicine = new MedicineModel({ ...data, householdId, createdBy });
const saved = await medicine.save();
return saved.toObject();
}
public async update(id: string, householdId: string, data: UpdateMedicineInput) {
return MedicineModel.findOneAndUpdate(
{ _id: id, householdId, isDeleted: false },
{ $set: data },
{ new: true, lean: true },
).exec();
}
public async softDelete(id: string, householdId: string) {
return MedicineModel.findOneAndUpdate(
{ _id: id, householdId, isDeleted: false },
{ $set: { isDeleted: true } },
{ new: true, lean: true },
).exec();
}
}

View file

@ -0,0 +1,247 @@
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';
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';
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,
mockFindDuplicate,
mockCreate,
mockUpdate,
mockSoftDelete,
mockCountByMedicineId,
} = vi.hoisted(() => ({
mockFindByHousehold: vi.fn(),
mockFindById: vi.fn(),
mockFindDuplicate: vi.fn(),
mockCreate: vi.fn(),
mockUpdate: vi.fn(),
mockSoftDelete: vi.fn(),
mockCountByMedicineId: vi.fn(),
}));
vi.mock('./medicines.repository.js', () => ({
MedicinesRepository: class {
findByHousehold = mockFindByHousehold;
findById = mockFindById;
findDuplicate = mockFindDuplicate;
create = mockCreate;
update = mockUpdate;
softDelete = mockSoftDelete;
},
}));
vi.mock('../medicine-products/medicine-products.repository.js', () => ({
MedicineProductsRepository: class {
countByMedicineId = mockCountByMedicineId;
},
}));
vi.mock('../medicine-products/medicine-products.service.js', () => ({
MedicineProductsService: class {
listByMedicine = vi.fn();
getById = vi.fn();
create = vi.fn();
update = vi.fn();
delete = vi.fn();
},
}));
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 medicinesRoutes from './medicines.routes.js';
import medicineProductsRoutes from '../medicine-products/medicine-products.routes.js';
function makeFakeMedicine(overrides = {}) {
return {
_id: 'med-1',
householdId: 'hh1',
name: 'Metformin',
form: MedicineForm.TABLET,
strength: 500,
strengthUnit: StrengthUnit.MG,
category: MedicineCategory.PRESCRIPTION,
tags: [],
createdBy: 'kc-1',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
};
}
describe('medicines.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(medicineProductsRoutes);
await instance.register(medicinesRoutes);
await instance.ready();
return instance;
}
const authHeaders = { authorization: 'Bearer valid-token' };
beforeEach(async () => {
vi.clearAllMocks();
mockCountByMedicineId.mockResolvedValue(0);
app = await buildTestApp();
});
afterEach(async () => {
if (app) await app.close();
});
describe('GET /api/v1/households/:householdId/medicines', () => {
it('returns paginated list', async () => {
const medicine = makeFakeMedicine();
mockFindByHousehold.mockResolvedValue({
data: [medicine],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicines',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0].name).toBe('Metformin');
expect(body.pagination.hasMore).toBe(false);
});
it('handles ObjectId and Date objects in response', async () => {
const medicine = makeFakeMedicine({
_id: { toString: () => 'med-obj' },
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
notes: 'Take with food',
});
mockFindByHousehold.mockResolvedValue({
data: [medicine],
pagination: { cursor: null, hasMore: false },
});
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicines',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body.data[0]._id).toBe('med-obj');
expect(body.data[0].createdAt).toBe('2024-01-01T00:00:00.000Z');
expect(body.data[0].notes).toBe('Take with food');
});
});
describe('GET /api/v1/households/:householdId/medicines/:id', () => {
it('returns a medicine', async () => {
mockFindById.mockResolvedValue(makeFakeMedicine());
const res = await app.inject({
method: 'GET',
url: '/api/v1/households/hh1/medicines/med-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(200);
expect(res.json().name).toBe('Metformin');
});
});
describe('POST /api/v1/households/:householdId/medicines', () => {
it('creates a medicine', async () => {
mockFindDuplicate.mockResolvedValue(null);
mockCreate.mockResolvedValue(makeFakeMedicine());
const res = await app.inject({
method: 'POST',
url: '/api/v1/households/hh1/medicines',
headers: authHeaders,
payload: {
name: 'Metformin',
form: MedicineForm.TABLET,
strength: 500,
strengthUnit: StrengthUnit.MG,
category: MedicineCategory.PRESCRIPTION,
},
});
expect(res.statusCode).toBe(201);
expect(res.json().name).toBe('Metformin');
});
});
describe('PATCH /api/v1/households/:householdId/medicines/:id', () => {
it('updates a medicine', async () => {
mockFindById.mockResolvedValue(makeFakeMedicine());
mockFindDuplicate.mockResolvedValue(null);
mockUpdate.mockResolvedValue(makeFakeMedicine({ name: 'Updated' }));
const res = await app.inject({
method: 'PATCH',
url: '/api/v1/households/hh1/medicines/med-1',
headers: authHeaders,
payload: { name: 'Updated' },
});
expect(res.statusCode).toBe(200);
expect(res.json().name).toBe('Updated');
});
});
describe('DELETE /api/v1/households/:householdId/medicines/:id', () => {
it('soft deletes a medicine', async () => {
mockFindById.mockResolvedValue(makeFakeMedicine());
mockSoftDelete.mockResolvedValue(makeFakeMedicine({ isDeleted: true }));
const res = await app.inject({
method: 'DELETE',
url: '/api/v1/households/hh1/medicines/med-1',
headers: authHeaders,
});
expect(res.statusCode).toBe(204);
});
});
});

View file

@ -0,0 +1,165 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import {
CreateMedicineSchema,
UpdateMedicineSchema,
MedicineQuerySchema,
MedicineResponseSchema,
MedicineListResponseSchema,
} from '@meshitrack/shared';
import { MedicinesRepository } from './medicines.repository.js';
import { MedicinesService } from './medicines.service.js';
type AnyMedicineDoc = {
_id: string | { toString: () => string };
householdId: string;
name: string;
form: string;
strength: number;
strengthUnit: string;
category: string;
notes?: string | null;
tags: string[];
createdBy: string;
createdAt: string | { toISOString: () => string };
updatedAt: string | { toISOString: () => string };
};
function toStr(v: string | { toString: () => string }): string {
return typeof v === 'string' ? v : v.toString();
}
function toIso(v: string | { toISOString: () => string }): string {
return typeof v === 'string' ? v : v.toISOString();
}
function toMedicineResponse(doc: AnyMedicineDoc): z.infer<typeof MedicineResponseSchema> {
return {
_id: toStr(doc._id),
householdId: doc.householdId,
name: doc.name,
form: doc.form,
strength: doc.strength,
strengthUnit: doc.strengthUnit,
category: doc.category,
...(doc.notes ? { notes: doc.notes } : {}),
tags: doc.tags,
createdBy: doc.createdBy,
createdAt: toIso(doc.createdAt),
updatedAt: toIso(doc.updatedAt),
};
}
declare module '@fastify/awilix' {
interface Cradle {
medicinesRepository: MedicinesRepository;
medicinesService: MedicinesService;
}
}
export default fp(
async (fastify) => {
fastify.diContainer.register({
medicinesRepository: asClass(MedicinesRepository, { lifetime: Lifetime.SINGLETON }),
medicinesService: asClass(MedicinesService, { lifetime: Lifetime.SINGLETON }),
});
const app = fastify.withTypeProvider<ZodTypeProvider>();
const householdParams = z.object({ householdId: z.string() });
// GET /api/v1/households/:householdId/medicines — list/search
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/medicines',
schema: {
params: householdParams,
querystring: MedicineQuerySchema,
response: { 200: MedicineListResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicinesService');
const result = await service.list(request.params.householdId, request.query);
return reply.send({
data: result.data.map(toMedicineResponse),
pagination: result.pagination,
});
},
});
// GET /api/v1/households/:householdId/medicines/:id — get by id
app.route({
method: 'GET',
url: '/api/v1/households/:householdId/medicines/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
response: { 200: MedicineResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicinesService');
const medicine = await service.getById(request.params.id, request.params.householdId);
return reply.send(toMedicineResponse(medicine));
},
});
// POST /api/v1/households/:householdId/medicines — create
app.route({
method: 'POST',
url: '/api/v1/households/:householdId/medicines',
schema: {
params: householdParams,
body: CreateMedicineSchema,
response: { 201: MedicineResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicinesService');
const medicine = await service.create(
request.body,
request.params.householdId,
request.user.keycloakId,
);
return reply.status(201).send(toMedicineResponse(medicine));
},
});
// PATCH /api/v1/households/:householdId/medicines/:id — update
app.route({
method: 'PATCH',
url: '/api/v1/households/:householdId/medicines/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
body: UpdateMedicineSchema,
response: { 200: MedicineResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicinesService');
const medicine = await service.update(
request.params.id,
request.params.householdId,
request.body,
);
return reply.send(toMedicineResponse(medicine));
},
});
// DELETE /api/v1/households/:householdId/medicines/:id — soft delete
app.route({
method: 'DELETE',
url: '/api/v1/households/:householdId/medicines/:id',
schema: {
params: householdParams.extend({ id: z.string() }),
response: { 204: z.undefined() },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('medicinesService');
await service.delete(request.params.id, request.params.householdId);
return reply.status(204).send();
},
});
},
{
name: 'medicines-routes',
dependencies: ['auth-plugin'],
},
);

View file

@ -0,0 +1,182 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MedicinesService } from './medicines.service.js';
import { NotFoundError, ConflictError } from '../../common/errors.js';
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';
describe(MedicinesService.name, () => {
const mockRepo = {
findByHousehold: vi.fn(),
findById: vi.fn(),
findDuplicate: vi.fn(),
create: vi.fn(),
update: vi.fn(),
softDelete: vi.fn(),
};
const mockProductsRepo = {
countByMedicineId: vi.fn(),
};
let service: MedicinesService;
beforeEach(() => {
vi.clearAllMocks();
service = new MedicinesService({
medicinesRepository: mockRepo as never,
medicineProductsRepository: mockProductsRepo 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: 20 });
expect(mockRepo.findByHousehold).toHaveBeenCalledWith('hh1', { limit: 20 });
expect(result).toEqual(expected);
});
});
describe('getById', () => {
it('returns medicine when found', async () => {
const medicine = { _id: 'med-1', name: 'Aspirin' };
mockRepo.findById.mockResolvedValue(medicine);
const result = await service.getById('med-1', 'hh1');
expect(result).toEqual(medicine);
});
it('throws NotFoundError when not found', async () => {
mockRepo.findById.mockResolvedValue(null);
await expect(service.getById('missing', 'hh1')).rejects.toThrow(NotFoundError);
});
});
describe('create', () => {
const data = {
name: 'Aspirin',
form: MedicineForm.TABLET,
strength: 500,
strengthUnit: StrengthUnit.MG,
category: MedicineCategory.OTC,
tags: [],
};
it('creates when no duplicate exists', async () => {
mockRepo.findDuplicate.mockResolvedValue(null);
mockRepo.create.mockResolvedValue({ _id: 'med-1', ...data });
const result = await service.create(data, 'hh1', 'kc-1');
expect(mockRepo.findDuplicate).toHaveBeenCalledWith(
'hh1',
'Aspirin',
500,
StrengthUnit.MG,
MedicineForm.TABLET,
);
expect(result._id).toBe('med-1');
});
it('throws ConflictError when duplicate exists', async () => {
mockRepo.findDuplicate.mockResolvedValue({ _id: 'existing' });
await expect(service.create(data, 'hh1', 'kc-1')).rejects.toThrow(ConflictError);
expect(mockRepo.create).not.toHaveBeenCalled();
});
});
describe('update', () => {
it('updates a medicine', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'med-1',
name: 'Aspirin',
strength: 500,
strengthUnit: StrengthUnit.MG,
form: MedicineForm.TABLET,
});
mockRepo.findDuplicate.mockResolvedValue(null);
mockRepo.update.mockResolvedValue({ _id: 'med-1', name: 'Updated' });
const result = await service.update('med-1', 'hh1', { name: 'Updated' });
expect(result.name).toBe('Updated');
});
it('throws NotFoundError when medicine does not exist', async () => {
mockRepo.findById.mockResolvedValue(null);
await expect(service.update('missing', 'hh1', { name: 'X' })).rejects.toThrow(NotFoundError);
});
it('throws ConflictError when update would create duplicate', async () => {
mockRepo.findById.mockResolvedValue({
_id: 'med-1',
name: 'Aspirin',
strength: 500,
strengthUnit: StrengthUnit.MG,
form: MedicineForm.TABLET,
});
mockRepo.findDuplicate.mockResolvedValue({ _id: 'med-2' });
await expect(service.update('med-1', 'hh1', { name: 'Ibuprofen' })).rejects.toThrow(
ConflictError,
);
});
it('throws NotFoundError when repo update returns null', async () => {
mockRepo.findById.mockResolvedValue({ _id: 'med-1', name: 'Aspirin' });
mockRepo.update.mockResolvedValue(null);
await expect(service.update('med-1', 'hh1', { notes: 'Updated' })).rejects.toThrow(
NotFoundError,
);
});
it('skips dedup check when no identity fields change', async () => {
mockRepo.findById.mockResolvedValue({ _id: 'med-1', name: 'Aspirin' });
mockRepo.update.mockResolvedValue({ _id: 'med-1', notes: 'Updated notes' });
await service.update('med-1', 'hh1', { notes: 'Updated notes' });
expect(mockRepo.findDuplicate).not.toHaveBeenCalled();
});
});
describe('delete', () => {
it('soft deletes a medicine', async () => {
mockRepo.findById.mockResolvedValue({ _id: 'med-1' });
mockProductsRepo.countByMedicineId.mockResolvedValue(0);
mockRepo.softDelete.mockResolvedValue({ _id: 'med-1', isDeleted: true });
await service.delete('med-1', 'hh1');
expect(mockProductsRepo.countByMedicineId).toHaveBeenCalledWith('med-1');
expect(mockRepo.softDelete).toHaveBeenCalledWith('med-1', 'hh1');
});
it('throws ConflictError when linked products exist', async () => {
mockRepo.findById.mockResolvedValue({ _id: 'med-1' });
mockProductsRepo.countByMedicineId.mockResolvedValue(3);
await expect(service.delete('med-1', 'hh1')).rejects.toThrow(ConflictError);
expect(mockRepo.softDelete).not.toHaveBeenCalled();
});
it('throws NotFoundError when not found', async () => {
mockRepo.findById.mockResolvedValue(null);
await expect(service.delete('missing', 'hh1')).rejects.toThrow(NotFoundError);
});
it('throws NotFoundError when softDelete returns null', async () => {
mockRepo.findById.mockResolvedValue({ _id: 'med-1' });
mockProductsRepo.countByMedicineId.mockResolvedValue(0);
mockRepo.softDelete.mockResolvedValue(null);
await expect(service.delete('med-1', 'hh1')).rejects.toThrow(NotFoundError);
});
});
});

View file

@ -0,0 +1,92 @@
import type { MedicinesRepository } from './medicines.repository.js';
import type { MedicineProductsRepository } from '../medicine-products/medicine-products.repository.js';
import type {
CreateMedicineInput,
UpdateMedicineInput,
MedicineQueryInput,
} from '@meshitrack/shared';
import { NotFoundError, ConflictError } from '../../common/errors.js';
interface Deps {
medicinesRepository: MedicinesRepository;
medicineProductsRepository: MedicineProductsRepository;
}
export class MedicinesService {
private readonly medicinesRepository: MedicinesRepository;
private readonly medicineProductsRepository: MedicineProductsRepository;
public constructor({ medicinesRepository, medicineProductsRepository }: Deps) {
this.medicinesRepository = medicinesRepository;
this.medicineProductsRepository = medicineProductsRepository;
}
public async list(householdId: string, query: MedicineQueryInput) {
return this.medicinesRepository.findByHousehold(householdId, query);
}
public async getById(id: string, householdId: string) {
const medicine = await this.medicinesRepository.findById(id, householdId);
if (!medicine) {
throw new NotFoundError('Medicine not found');
}
return medicine;
}
public async create(data: CreateMedicineInput, householdId: string, createdBy: string) {
const existing = await this.medicinesRepository.findDuplicate(
householdId,
data.name,
data.strength,
data.strengthUnit,
data.form,
);
if (existing) {
throw new ConflictError('A medicine with the same name, strength, and form already exists');
}
return this.medicinesRepository.create(data, householdId, createdBy);
}
public async update(id: string, householdId: string, data: UpdateMedicineInput) {
await this.getById(id, householdId);
if (data.name || data.strength || data.strengthUnit || data.form) {
const current = await this.medicinesRepository.findById(id, householdId);
const name = data.name ?? current!.name;
const strength = data.strength ?? current!.strength;
const strengthUnit = data.strengthUnit ?? current!.strengthUnit;
const form = data.form ?? current!.form;
const duplicate = await this.medicinesRepository.findDuplicate(
householdId,
name,
strength,
strengthUnit,
form,
id,
);
if (duplicate) {
throw new ConflictError('A medicine with the same name, strength, and form already exists');
}
}
const updated = await this.medicinesRepository.update(id, householdId, data);
if (!updated) throw new NotFoundError('Medicine not found');
return updated;
}
public async delete(id: string, householdId: string) {
await this.getById(id, householdId);
const productCount = await this.medicineProductsRepository.countByMedicineId(id);
if (productCount > 0) {
throw new ConflictError(
`Cannot delete medicine with ${productCount} linked product(s). Delete them first.`,
);
}
const deleted = await this.medicinesRepository.softDelete(id, householdId);
if (!deleted) throw new NotFoundError('Medicine not found');
return deleted;
}
}

View file

@ -20,10 +20,14 @@ vi.mock('jose', () => ({
}));
// Mock the users repository module with a real class
const mockUpsertFromToken = vi.hoisted(() => vi.fn());
const { mockUpsertFromToken, mockFindByKeycloakId } = vi.hoisted(() => ({
mockUpsertFromToken: vi.fn(),
mockFindByKeycloakId: vi.fn(),
}));
vi.mock('./users.repository.js', () => ({
UsersRepository: class MockUsersRepository {
upsertFromToken = mockUpsertFromToken;
findByKeycloakId = mockFindByKeycloakId;
},
}));
@ -47,6 +51,55 @@ describe('users.routes', () => {
beforeEach(() => {
vi.clearAllMocks();
mockFindByKeycloakId.mockResolvedValue({ householdIds: ['hh1'] });
});
it('returns 404 when syncFromToken returns null', async () => {
mockUpsertFromToken.mockResolvedValue(null);
const app = await buildTestApp();
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/api/v1/users/me',
headers: { authorization: 'Bearer valid-token' },
});
expect(res.statusCode).toBe(404);
await app.close();
});
it('handles ObjectId and Date objects in response', async () => {
const mockUser = {
_id: { toString: () => 'u-obj' },
keycloakId: 'kc-1',
displayName: 'testuser',
email: 'test@example.com',
householdIds: ['hh1'],
defaultHouseholdId: 'hh1',
createdAt: { toISOString: () => '2024-01-01T00:00:00.000Z' },
updatedAt: { toISOString: () => '2024-01-02T00:00:00.000Z' },
};
mockUpsertFromToken.mockResolvedValue(mockUser);
const app = await buildTestApp();
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/api/v1/users/me',
headers: { authorization: 'Bearer valid-token' },
});
expect(res.statusCode).toBe(200);
const body = res.json();
expect(body._id).toBe('u-obj');
expect(body.createdAt).toBe('2024-01-01T00:00:00.000Z');
expect(body.defaultHouseholdId).toBe('hh1');
await app.close();
});
it('GET /api/v1/users/me syncs user from token and returns profile', async () => {

View file

@ -1,7 +1,7 @@
import fp from 'fastify-plugin';
import { asClass, Lifetime } from 'awilix';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import { z } from 'zod/v4';
import { UserResponseSchema } from '@meshitrack/shared';
import { UsersRepository } from './users.repository.js';
import { UsersService } from './users.service.js';
import { NotFoundError } from '../../common/errors.js';
@ -56,18 +56,7 @@ export default fp(
url: '/api/v1/users/me',
config: { skipHousehold: true },
schema: {
response: {
200: z.object({
_id: z.string(),
keycloakId: z.string(),
displayName: z.string(),
email: z.string(),
householdIds: z.array(z.string()),
defaultHouseholdId: z.string().nullable(),
createdAt: z.string(),
updatedAt: z.string(),
}),
},
response: { 200: UserResponseSchema },
},
handler: async (request, reply) => {
const service = fastify.diContainer.resolve('usersService');

View file

@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify from 'fastify';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import { asValue } from 'awilix';
const { MockJOSEError } = vi.hoisted(() => ({
MockJOSEError: class JOSEError extends Error {},
@ -12,21 +14,38 @@ vi.mock('jose', () => ({
errors: { JOSEError: MockJOSEError },
}));
const { mockFindByKeycloakId, mockUpsertFromToken } = vi.hoisted(() => ({
mockFindByKeycloakId: vi.fn(),
mockUpsertFromToken: vi.fn(),
}));
import authPlugin from './auth.plugin.js';
import * as jose from 'jose';
describe('auth.plugin', () => {
function buildApp() {
async function buildApp() {
const app = Fastify({ logger: false });
await app.register(fastifyAwilixPlugin, {
disposeOnClose: true,
disposeOnResponse: true,
strictBooleanEnforced: true,
});
app.diContainer.register({
usersRepository: asValue({
findByKeycloakId: mockFindByKeycloakId,
upsertFromToken: mockUpsertFromToken,
}),
});
return app;
}
beforeEach(() => {
vi.clearAllMocks();
mockFindByKeycloakId.mockResolvedValue({ householdIds: ['hh1'] });
});
it('skips auth for routes marked as public', async () => {
const app = buildApp();
const app = await buildApp();
await app.register(authPlugin);
app.get('/public', { config: { public: true } as never }, async () => ({ ok: true }));
@ -37,7 +56,7 @@ describe('auth.plugin', () => {
});
it('throws 401 when no Authorization header', async () => {
const app = buildApp();
const app = await buildApp();
await app.register(authPlugin);
app.get('/protected', async () => ({ ok: true }));
@ -49,7 +68,7 @@ describe('auth.plugin', () => {
});
it('throws 401 when Authorization header is not Bearer', async () => {
const app = buildApp();
const app = await buildApp();
await app.register(authPlugin);
app.get('/protected', async () => ({ ok: true }));
@ -66,7 +85,7 @@ describe('auth.plugin', () => {
it('throws 401 when token is invalid', async () => {
vi.mocked(jose.jwtVerify).mockRejectedValue(new MockJOSEError('Invalid token'));
const app = buildApp();
const app = await buildApp();
await app.register(authPlugin);
app.get('/protected', async () => ({ ok: true }));
@ -88,15 +107,15 @@ describe('auth.plugin', () => {
email: 'test@example.com',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
iss: 'http://localhost:8080/realms/meshitrack',
aud: 'meshitrack-api',
},
protectedHeader: { alg: 'RS256' },
key: {} as never,
} as never);
mockFindByKeycloakId.mockResolvedValue({ householdIds: ['hh1'] });
const app = buildApp();
const app = await buildApp();
await app.register(authPlugin);
let capturedUser: unknown;
@ -122,18 +141,37 @@ describe('auth.plugin', () => {
});
});
it('rethrows non-JOSE errors as-is', async () => {
vi.mocked(jose.jwtVerify).mockRejectedValue(new Error('Network failure'));
const app = await buildApp();
await app.register(authPlugin);
app.get('/protected', async () => ({ ok: true }));
await app.ready();
const res = await app.inject({
method: 'GET',
url: '/protected',
headers: { authorization: 'Bearer some-token' },
});
expect(res.statusCode).toBe(500);
});
it('handles missing optional fields in JWT payload', async () => {
vi.mocked(jose.jwtVerify).mockResolvedValue({
payload: {
// sub, email, preferred_username, realm_access, householdIds all missing
// sub, email, preferred_username, realm_access all missing
iss: 'http://localhost:8080/realms/meshitrack',
aud: 'meshitrack-api',
},
protectedHeader: { alg: 'RS256' },
key: {} as never,
} as never);
mockFindByKeycloakId.mockResolvedValue(null);
mockUpsertFromToken.mockResolvedValue({ householdIds: [] });
const app = buildApp();
const app = await buildApp();
await app.register(authPlugin);
let capturedUser: unknown;

View file

@ -3,6 +3,7 @@ import * as jose from 'jose';
import config from '../config/configuration.js';
import type { AuthUser } from '../common/types.js';
import { UnauthorizedError } from '../common/errors.js';
import type { UsersRepository } from '../modules/users/users.repository.js';
let jwks: jose.JWTVerifyGetKey | undefined;
@ -49,12 +50,25 @@ export default fp(
audience: config.keycloak.clientId,
});
const keycloakId = payload.sub ?? '';
const email = (payload['email'] as string) ?? '';
const displayName = (payload['preferred_username'] as string) ?? '';
const roles = (payload['realm_access'] as Record<string, string[]>)?.['roles'] ?? [];
// Look up user from DB to get fresh householdIds (application state
// belongs in the database, not baked into the JWT).
const usersRepository = fastify.diContainer.resolve<UsersRepository>('usersRepository');
let dbUser = await usersRepository.findByKeycloakId(keycloakId);
if (!dbUser) {
dbUser = await usersRepository.upsertFromToken(keycloakId, email, displayName);
}
const user: AuthUser = {
keycloakId: payload.sub ?? '',
email: (payload['email'] as string) ?? '',
displayName: (payload['preferred_username'] as string) ?? '',
roles: (payload['realm_access'] as Record<string, string[]>)?.['roles'] ?? [],
householdIds: (payload['householdIds'] as string[]) ?? [],
keycloakId,
email,
displayName,
roles,
householdIds: dbUser?.householdIds ?? [],
};
request.user = user;

View file

@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import Fastify from 'fastify';
import { fastifyAwilixPlugin } from '@fastify/awilix';
import { asValue } from 'awilix';
// Mock jose for the auth plugin dependency
vi.mock('jose', () => ({
@ -10,19 +12,33 @@ vi.mock('jose', () => ({
email: 'test@example.com',
preferred_username: 'testuser',
realm_access: { roles: ['member'] },
householdIds: ['hh1'],
},
protectedHeader: { alg: 'RS256' },
key: {},
}),
}));
const { mockFindByKeycloakId } = vi.hoisted(() => ({
mockFindByKeycloakId: vi.fn(),
}));
import authPlugin from './auth.plugin.js';
import householdPlugin from './household.plugin.js';
describe('household.plugin', () => {
async function buildApp() {
const app = Fastify({ logger: false });
await app.register(fastifyAwilixPlugin, {
disposeOnClose: true,
disposeOnResponse: true,
strictBooleanEnforced: true,
});
app.diContainer.register({
usersRepository: asValue({
findByKeycloakId: mockFindByKeycloakId,
upsertFromToken: vi.fn().mockResolvedValue({ householdIds: ['hh1'] }),
}),
});
await app.register(authPlugin);
await app.register(householdPlugin);
return app;
@ -30,6 +46,7 @@ describe('household.plugin', () => {
beforeEach(() => {
vi.clearAllMocks();
mockFindByKeycloakId.mockResolvedValue({ householdIds: ['hh1'] });
});
it('skips household check for public routes', async () => {

View file

@ -0,0 +1,48 @@
import mongoose from 'mongoose';
import {
CabinetItemStatus,
ConcentrationUnit,
DosageUnit,
MedicineForm,
StrengthUnit,
} from '@meshitrack/shared';
const cabinetItemSchema = new mongoose.Schema(
{
householdId: { type: String, required: true },
medicineId: { type: String, required: true },
medicineName: { type: String, required: true },
medicineStrength: { type: Number, required: true },
medicineStrengthUnit: { type: String, enum: Object.values(StrengthUnit), required: true },
medicineForm: { type: String, enum: Object.values(MedicineForm), required: true },
medicineProductId: { type: String },
medicineProductBrand: { type: String },
concentration: { type: Number },
concentrationUnit: { type: String, enum: Object.values(ConcentrationUnit) },
quantity: { type: Number, required: true, min: 0 },
unit: { type: String, enum: Object.values(DosageUnit), required: true },
expirationDate: { type: Date },
status: {
type: String,
enum: Object.values(CabinetItemStatus),
default: CabinetItemStatus.ACTIVE,
},
notes: { type: String },
createdBy: { type: String, required: true },
isDeleted: { type: Boolean, default: false },
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
cabinetItemSchema.index({ householdId: 1, medicineId: 1, status: 1 });
cabinetItemSchema.index({ householdId: 1, status: 1 });
cabinetItemSchema.index({ householdId: 1, expirationDate: 1 });
export const CabinetItemModel = mongoose.model('CabinetItem', cabinetItemSchema);
export type CabinetItemDocument = mongoose.InferSchemaType<typeof cabinetItemSchema> & {
_id: mongoose.Types.ObjectId;
};

View file

@ -0,0 +1,23 @@
import { describe, it, expect } from 'vitest';
import { MedicineProductModel } from './medicine-product.schema.js';
describe(MedicineProductModel.name, () => {
it('is a valid mongoose model', () => {
expect(MedicineProductModel.modelName).toBe('MedicineProduct');
});
it('has expected schema paths', () => {
const paths = Object.keys(MedicineProductModel.schema.paths);
expect(paths).toContain('householdId');
expect(paths).toContain('medicineId');
expect(paths).toContain('medicineName');
expect(paths).toContain('brand');
expect(paths).toContain('packageSize');
expect(paths).toContain('packageUnit');
expect(paths).toContain('source');
expect(paths).toContain('createdBy');
expect(paths).toContain('isDeleted');
expect(paths).toContain('createdAt');
expect(paths).toContain('updatedAt');
});
});

View file

@ -0,0 +1,38 @@
import mongoose from 'mongoose';
import { ConcentrationUnit, DosageUnit, MedicineProductSource } from '@meshitrack/shared';
const medicineProductSchema = new mongoose.Schema(
{
householdId: { type: String, required: true },
medicineId: { type: String, required: true },
medicineName: { type: String, required: true },
brand: { type: String, required: true },
manufacturer: { type: String },
packageSize: { type: Number, required: true },
packageUnit: { type: String, enum: Object.values(DosageUnit), required: true },
concentration: { type: Number },
concentrationUnit: { type: String, enum: Object.values(ConcentrationUnit) },
imageUrl: { type: String },
notes: { type: String },
source: {
type: String,
enum: Object.values(MedicineProductSource),
default: MedicineProductSource.MANUAL,
},
createdBy: { type: String, required: true },
isDeleted: { type: Boolean, default: false },
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
medicineProductSchema.index({ householdId: 1, medicineId: 1 });
medicineProductSchema.index({ householdId: 1, brand: 'text' });
export const MedicineProductModel = mongoose.model('MedicineProduct', medicineProductSchema);
export type MedicineProductDocument = mongoose.InferSchemaType<typeof medicineProductSchema> & {
_id: mongoose.Types.ObjectId;
};

View file

@ -0,0 +1,23 @@
import { describe, it, expect } from 'vitest';
import { MedicineModel } from './medicine.schema.js';
describe(MedicineModel.name, () => {
it('is a valid mongoose model', () => {
expect(MedicineModel.modelName).toBe('Medicine');
});
it('has expected schema paths', () => {
const paths = Object.keys(MedicineModel.schema.paths);
expect(paths).toContain('householdId');
expect(paths).toContain('name');
expect(paths).toContain('form');
expect(paths).toContain('strength');
expect(paths).toContain('strengthUnit');
expect(paths).toContain('category');
expect(paths).toContain('tags');
expect(paths).toContain('createdBy');
expect(paths).toContain('isDeleted');
expect(paths).toContain('createdAt');
expect(paths).toContain('updatedAt');
});
});

View file

@ -0,0 +1,37 @@
import mongoose from 'mongoose';
import { MedicineForm, StrengthUnit, MedicineCategory } from '@meshitrack/shared';
const medicineSchema = new mongoose.Schema(
{
householdId: { type: String, required: true },
name: { type: String, required: true },
form: { type: String, enum: Object.values(MedicineForm), required: true },
strength: { type: Number, required: true },
strengthUnit: { type: String, enum: Object.values(StrengthUnit), required: true },
category: { type: String, enum: Object.values(MedicineCategory), required: true },
notes: { type: String },
tags: { type: [String], default: [] },
createdBy: { type: String, required: true },
isDeleted: { type: Boolean, default: false },
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
medicineSchema.index(
{ householdId: 1, name: 'text', tags: 'text' },
{ name: 'medicine_text_search' },
);
medicineSchema.index({ householdId: 1, category: 1 });
medicineSchema.index(
{ householdId: 1, name: 1, strength: 1, strengthUnit: 1, form: 1 },
{ name: 'medicine_dedup' },
);
export const MedicineModel = mongoose.model('Medicine', medicineSchema);
export type MedicineDocument = mongoose.InferSchemaType<typeof medicineSchema> & {
_id: mongoose.Types.ObjectId;
};