const { ObjectId } = require("mongodb"); const { normalizeAccessLevel, getHighestDrugAccessLevels, getRequiredDrugAccessLevels, doctorMeetsDrugAccessLevels, getDoctorAccessLevelQuery, } = require("./drug-access-level"); describe("drug access levels", () => { test("normalizes missing and invalid values to zero", () => { expect([undefined, null, "2", -1, 4].map(normalizeAccessLevel)).toEqual([0, 0, 0, 0, 0]); expect([0, 1, 2, 3].map(normalizeAccessLevel)).toEqual([0, 1, 2, 3]); }); test("calculates the independent highest levels", () => { expect(getHighestDrugAccessLevels([ { antibiotic_level: 3, tumor_use: 1 }, { antibiotic_level: 1, tumor_use: 2 }, { antibiotic_level: 99 }, ])).toEqual({ antibioticLevel: 3, tumorUse: 2 }); expect(getHighestDrugAccessLevels([])).toEqual({ antibioticLevel: 0, tumorUse: 0 }); }); test("queries valid drug ids and treats missing records as zero", async () => { const validId = new ObjectId(); const toArray = jest.fn().mockResolvedValue([{ antibiotic_level: 2 }]); const find = jest.fn().mockReturnValue({ toArray }); const db = { collection: jest.fn().mockReturnValue({ find }) }; await expect(getRequiredDrugAccessLevels(db, [ { _id: validId.toString() }, { _id: "invalid" }, { _id: validId.toString() }, ])).resolves.toEqual({ antibioticLevel: 2, tumorUse: 0 }); expect(find.mock.calls[0][0]._id.$in).toHaveLength(1); expect(find.mock.calls[0][1]).toEqual({ projection: { antibiotic_level: 1, tumor_use: 1 } }); }); test("requires doctors to meet both levels and treats missing fields as zero", () => { const required = { antibioticLevel: 2, tumorUse: 1 }; expect(doctorMeetsDrugAccessLevels({ antibiotic_level: 2, tumor_use: 3 }, required)).toBe(true); expect(doctorMeetsDrugAccessLevels({ antibiotic_level: 1, tumor_use: 3 }, required)).toBe(false); expect(doctorMeetsDrugAccessLevels({}, { antibioticLevel: 0, tumorUse: 0 })).toBe(true); expect(doctorMeetsDrugAccessLevels({}, { antibioticLevel: 1, tumorUse: 0 })).toBe(false); }); test("adds minimum-level query conditions without changing legacy calls", () => { expect(getDoctorAccessLevelQuery()).toEqual({}); expect(getDoctorAccessLevelQuery(0, 0)).toEqual({}); expect(getDoctorAccessLevelQuery(2, 3)).toEqual({ antibiotic_level: { $gte: 2 }, tumor_use: { $gte: 3 }, }); }); });