Implement medicine library and cabinet
This commit is contained in:
parent
db79af06f7
commit
1f66fab30f
72 changed files with 7642 additions and 319 deletions
254
packages/api/src/modules/cabinet/cabinet.repository.test.ts
Normal file
254
packages/api/src/modules/cabinet/cabinet.repository.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
144
packages/api/src/modules/cabinet/cabinet.repository.ts
Normal file
144
packages/api/src/modules/cabinet/cabinet.repository.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
382
packages/api/src/modules/cabinet/cabinet.routes.test.ts
Normal file
382
packages/api/src/modules/cabinet/cabinet.routes.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
245
packages/api/src/modules/cabinet/cabinet.routes.ts
Normal file
245
packages/api/src/modules/cabinet/cabinet.routes.ts
Normal 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'],
|
||||
},
|
||||
);
|
||||
299
packages/api/src/modules/cabinet/cabinet.service.test.ts
Normal file
299
packages/api/src/modules/cabinet/cabinet.service.test.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
});
|
||||
121
packages/api/src/modules/cabinet/cabinet.service.ts
Normal file
121
packages/api/src/modules/cabinet/cabinet.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue