Setup initial project
This commit is contained in:
commit
db79af06f7
119 changed files with 20761 additions and 0 deletions
|
|
@ -0,0 +1,134 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
const { _mockLean, mockExec, mockFindById, mockFindOne, mockFindByIdAndUpdate, mockSave } =
|
||||
vi.hoisted(() => {
|
||||
const mockExec = vi.fn();
|
||||
const mockLean = vi.fn(() => ({ exec: mockExec }));
|
||||
return {
|
||||
mockExec,
|
||||
mockLean,
|
||||
mockFindById: vi.fn(() => ({ lean: mockLean })),
|
||||
mockFindOne: vi.fn(() => ({ lean: mockLean })),
|
||||
mockFindByIdAndUpdate: vi.fn(() => ({ exec: mockExec })),
|
||||
mockSave: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../schemas/household.schema.js', () => {
|
||||
class MockHouseholdModel {
|
||||
_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: 'hh-new', ...this._data };
|
||||
}
|
||||
static findById = mockFindById;
|
||||
static findOne = mockFindOne;
|
||||
static findByIdAndUpdate = mockFindByIdAndUpdate;
|
||||
}
|
||||
return { HouseholdModel: MockHouseholdModel };
|
||||
});
|
||||
|
||||
import { HouseholdsRepository } from './households.repository.js';
|
||||
|
||||
describe('HouseholdsRepository', () => {
|
||||
let repo: HouseholdsRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo = new HouseholdsRepository();
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('calls findById with lean', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test' };
|
||||
mockExec.mockResolvedValue(household);
|
||||
|
||||
const result = await repo.findById('hh1');
|
||||
|
||||
expect(mockFindById).toHaveBeenCalledWith('hh1');
|
||||
expect(result).toEqual(household);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByInviteCode', () => {
|
||||
it('calls findOne with inviteCode', async () => {
|
||||
const household = { _id: 'hh1', inviteCode: 'ABCD' };
|
||||
mockExec.mockResolvedValue(household);
|
||||
|
||||
const result = await repo.findByInviteCode('ABCD');
|
||||
|
||||
expect(mockFindOne).toHaveBeenCalledWith({ inviteCode: 'ABCD' });
|
||||
expect(result).toEqual(household);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a household with owner as first member', async () => {
|
||||
mockSave.mockResolvedValue({});
|
||||
|
||||
const result = await repo.create({ name: 'Test' }, 'owner-1', 'INVITE1');
|
||||
|
||||
expect(mockSave).toHaveBeenCalled();
|
||||
expect(result).toMatchObject({ name: 'Test', ownerUserId: 'owner-1', inviteCode: 'INVITE1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('calls findByIdAndUpdate with $set', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
|
||||
|
||||
const result = await repo.update('hh1', { name: 'Updated' });
|
||||
|
||||
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
{ $set: { name: 'Updated' } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
expect(result).toEqual({ _id: 'hh1', name: 'Updated' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('addMember', () => {
|
||||
it('pushes a new member to the array', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'hh1', members: [] });
|
||||
|
||||
await repo.addMember('hh1', 'user-2', HouseholdRole.MEMBER);
|
||||
|
||||
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
{
|
||||
$push: {
|
||||
members: expect.objectContaining({
|
||||
userId: 'user-2',
|
||||
role: HouseholdRole.MEMBER,
|
||||
}),
|
||||
},
|
||||
},
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateInviteCode', () => {
|
||||
it('sets the new invite code', async () => {
|
||||
mockExec.mockResolvedValue({ _id: 'hh1', inviteCode: 'NEWCODE' });
|
||||
|
||||
const result = await repo.updateInviteCode('hh1', 'NEWCODE');
|
||||
|
||||
expect(mockFindByIdAndUpdate).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
{ $set: { inviteCode: 'NEWCODE' } },
|
||||
{ new: true, lean: true },
|
||||
);
|
||||
expect(result).toEqual({ _id: 'hh1', inviteCode: 'NEWCODE' });
|
||||
});
|
||||
});
|
||||
});
|
||||
55
packages/api/src/modules/households/households.repository.ts
Normal file
55
packages/api/src/modules/households/households.repository.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import type mongoose from 'mongoose';
|
||||
import { HouseholdModel } from '../../schemas/household.schema.js';
|
||||
import type { CreateHouseholdInput, UpdateHouseholdInput } from '@meshitrack/shared';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
export class HouseholdsRepository {
|
||||
public async findById(id: string) {
|
||||
return HouseholdModel.findById(id).lean().exec();
|
||||
}
|
||||
|
||||
public async findByInviteCode(inviteCode: string) {
|
||||
return HouseholdModel.findOne({ inviteCode }).lean().exec();
|
||||
}
|
||||
|
||||
public async create(
|
||||
data: CreateHouseholdInput,
|
||||
ownerUserId: string,
|
||||
inviteCode: string,
|
||||
session?: mongoose.ClientSession,
|
||||
) {
|
||||
const household = new HouseholdModel({
|
||||
...data,
|
||||
ownerUserId,
|
||||
inviteCode,
|
||||
members: [{ userId: ownerUserId, role: HouseholdRole.OWNER, joinedAt: new Date() }],
|
||||
});
|
||||
const saved = await household.save({ session });
|
||||
return saved.toObject();
|
||||
}
|
||||
|
||||
public async update(id: string, data: UpdateHouseholdInput) {
|
||||
return HouseholdModel.findByIdAndUpdate(id, { $set: data }, { new: true, lean: true }).exec();
|
||||
}
|
||||
|
||||
public async addMember(
|
||||
id: string,
|
||||
userId: string,
|
||||
role: HouseholdRole,
|
||||
session?: mongoose.ClientSession,
|
||||
) {
|
||||
return HouseholdModel.findByIdAndUpdate(
|
||||
id,
|
||||
{ $push: { members: { userId, role, joinedAt: new Date() } } },
|
||||
{ new: true, lean: true, session },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async updateInviteCode(id: string, inviteCode: string) {
|
||||
return HouseholdModel.findByIdAndUpdate(
|
||||
id,
|
||||
{ $set: { inviteCode } },
|
||||
{ new: true, lean: true },
|
||||
).exec();
|
||||
}
|
||||
}
|
||||
225
packages/api/src/modules/households/households.routes.test.ts
Normal file
225
packages/api/src/modules/households/households.routes.test.ts
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
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 { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
// Mock jose for auth plugin
|
||||
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: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Hoist mock fns
|
||||
const {
|
||||
mockCreate,
|
||||
mockFindById,
|
||||
mockUpdate,
|
||||
mockUpdateInviteCode,
|
||||
mockFindByInviteCode,
|
||||
mockAddMember,
|
||||
mockFindByKeycloakId,
|
||||
mockUserUpdate,
|
||||
} = vi.hoisted(() => ({
|
||||
mockCreate: vi.fn(),
|
||||
mockFindById: vi.fn(),
|
||||
mockUpdate: vi.fn(),
|
||||
mockUpdateInviteCode: vi.fn(),
|
||||
mockFindByInviteCode: vi.fn(),
|
||||
mockAddMember: vi.fn(),
|
||||
mockFindByKeycloakId: vi.fn(),
|
||||
mockUserUpdate: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./households.repository.js', () => ({
|
||||
HouseholdsRepository: class {
|
||||
create = mockCreate;
|
||||
findById = mockFindById;
|
||||
update = mockUpdate;
|
||||
updateInviteCode = mockUpdateInviteCode;
|
||||
findByInviteCode = mockFindByInviteCode;
|
||||
addMember = mockAddMember;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../users/users.repository.js', () => ({
|
||||
UsersRepository: class {
|
||||
findByKeycloakId = mockFindByKeycloakId;
|
||||
update = mockUserUpdate;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('uuid', () => ({
|
||||
v4: vi.fn(() => '12345678-1234-1234-1234-123456789abc'),
|
||||
}));
|
||||
|
||||
vi.mock('mongoose', () => ({
|
||||
default: {
|
||||
startSession: vi.fn().mockResolvedValue({
|
||||
startTransaction: vi.fn(),
|
||||
commitTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
endSession: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
import authPlugin from '../../plugins/auth.plugin.js';
|
||||
import householdPlugin from '../../plugins/household.plugin.js';
|
||||
import usersRoutes from '../users/users.routes.js';
|
||||
import householdsRoutes from './households.routes.js';
|
||||
|
||||
function makeFakeHousehold(overrides = {}) {
|
||||
return {
|
||||
_id: 'hh1',
|
||||
name: 'Test Household',
|
||||
ownerUserId: 'kc-1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER, joinedAt: new Date().toISOString() }],
|
||||
inviteCode: '12345678',
|
||||
settings: { timezone: 'UTC', currency: 'USD', language: 'en' },
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('households.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(householdsRoutes);
|
||||
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('POST /api/v1/households', () => {
|
||||
it('creates a household', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
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 Household' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json().name).toBe('Test Household');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/v1/households/:id', () => {
|
||||
it('returns a household', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
mockFindById.mockResolvedValue(household);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/hh1',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Test Household');
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/households/:id', () => {
|
||||
it('updates a household', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
mockFindById.mockResolvedValue(household);
|
||||
mockUpdate.mockResolvedValue({ ...household, name: 'Updated' });
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/hh1',
|
||||
headers: authHeaders,
|
||||
payload: { name: 'Updated' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().name).toBe('Updated');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/:id/invite', () => {
|
||||
it('generates a new invite code', async () => {
|
||||
const household = makeFakeHousehold();
|
||||
mockFindById.mockResolvedValue(household);
|
||||
mockUpdateInviteCode.mockResolvedValue({ ...household, inviteCode: '12345678' });
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/hh1/invite',
|
||||
headers: authHeaders,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().inviteCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/v1/households/join', () => {
|
||||
it('joins a household via invite code', async () => {
|
||||
const household = makeFakeHousehold({
|
||||
members: [
|
||||
{ userId: 'kc-other', role: HouseholdRole.OWNER, joinedAt: new Date().toISOString() },
|
||||
],
|
||||
});
|
||||
mockFindByInviteCode.mockResolvedValue(household);
|
||||
mockAddMember.mockResolvedValue({
|
||||
...household,
|
||||
members: [
|
||||
...household.members,
|
||||
{ userId: 'kc-1', role: HouseholdRole.MEMBER, joinedAt: new Date().toISOString() },
|
||||
],
|
||||
});
|
||||
mockFindByKeycloakId.mockResolvedValue({ householdIds: [], defaultHouseholdId: null });
|
||||
mockUserUpdate.mockResolvedValue({});
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/join',
|
||||
headers: authHeaders,
|
||||
payload: { inviteCode: '12345678' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
166
packages/api/src/modules/households/households.routes.ts
Normal file
166
packages/api/src/modules/households/households.routes.ts
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
import fp from 'fastify-plugin';
|
||||
import { asClass, Lifetime } from 'awilix';
|
||||
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
|
||||
import { z } from 'zod/v4';
|
||||
import {
|
||||
CreateHouseholdSchema,
|
||||
UpdateHouseholdSchema,
|
||||
JoinHouseholdSchema,
|
||||
HouseholdResponseSchema,
|
||||
} from '@meshitrack/shared';
|
||||
|
||||
type AnyHouseholdDoc = {
|
||||
_id: string | { toString: () => string };
|
||||
name: string;
|
||||
ownerUserId: string;
|
||||
members: ReadonlyArray<{
|
||||
userId: string;
|
||||
role: string;
|
||||
joinedAt: string | { toISOString: () => string };
|
||||
}>;
|
||||
inviteCode: string;
|
||||
settings?: { timezone?: string; currency?: string; language?: string } | null;
|
||||
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 toHouseholdResponse(doc: AnyHouseholdDoc): z.infer<typeof HouseholdResponseSchema> {
|
||||
return {
|
||||
_id: toStr(doc._id),
|
||||
name: doc.name,
|
||||
ownerUserId: doc.ownerUserId,
|
||||
members: doc.members.map((m) => ({
|
||||
userId: m.userId,
|
||||
role: m.role,
|
||||
joinedAt: toIso(m.joinedAt),
|
||||
})),
|
||||
inviteCode: doc.inviteCode,
|
||||
settings: {
|
||||
timezone: doc.settings?.timezone ?? 'UTC',
|
||||
currency: doc.settings?.currency ?? 'USD',
|
||||
language: doc.settings?.language ?? 'en',
|
||||
},
|
||||
createdAt: toIso(doc.createdAt),
|
||||
updatedAt: toIso(doc.updatedAt),
|
||||
};
|
||||
}
|
||||
import { HouseholdsRepository } from './households.repository.js';
|
||||
import { HouseholdsService } from './households.service.js';
|
||||
|
||||
declare module '@fastify/awilix' {
|
||||
interface Cradle {
|
||||
householdsRepository: HouseholdsRepository;
|
||||
householdsService: HouseholdsService;
|
||||
}
|
||||
}
|
||||
|
||||
export default fp(
|
||||
async (fastify) => {
|
||||
// Register DI
|
||||
fastify.diContainer.register({
|
||||
householdsRepository: asClass(HouseholdsRepository, { lifetime: Lifetime.SINGLETON }),
|
||||
householdsService: asClass(HouseholdsService, { lifetime: Lifetime.SINGLETON }),
|
||||
});
|
||||
|
||||
const app = fastify.withTypeProvider<ZodTypeProvider>();
|
||||
|
||||
// POST /api/v1/households — create a new household
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households',
|
||||
config: { skipHousehold: true },
|
||||
schema: {
|
||||
body: CreateHouseholdSchema,
|
||||
response: { 201: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.create(request.body, request.user.keycloakId);
|
||||
return reply.status(201).send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// GET /api/v1/households/:householdId — get household by id (members only)
|
||||
app.route({
|
||||
method: 'GET',
|
||||
url: '/api/v1/households/:householdId',
|
||||
schema: {
|
||||
params: z.object({ householdId: z.string() }),
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.getById(request.params.householdId);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// PATCH /api/v1/households/:householdId — update household settings
|
||||
app.route({
|
||||
method: 'PATCH',
|
||||
url: '/api/v1/households/:householdId',
|
||||
schema: {
|
||||
params: z.object({ householdId: z.string() }),
|
||||
body: UpdateHouseholdSchema,
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.update(
|
||||
request.params.householdId,
|
||||
request.body,
|
||||
request.user.keycloakId,
|
||||
);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// POST /api/v1/households/:householdId/invite — generate new invite code
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/:householdId/invite',
|
||||
schema: {
|
||||
params: z.object({ householdId: z.string() }),
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.generateInviteCode(
|
||||
request.params.householdId,
|
||||
request.user.keycloakId,
|
||||
);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
|
||||
// POST /api/v1/households/join — join via invite code
|
||||
app.route({
|
||||
method: 'POST',
|
||||
url: '/api/v1/households/join',
|
||||
config: { skipHousehold: true },
|
||||
schema: {
|
||||
body: JoinHouseholdSchema,
|
||||
response: { 200: HouseholdResponseSchema },
|
||||
},
|
||||
handler: async (request, reply) => {
|
||||
const service = fastify.diContainer.resolve('householdsService');
|
||||
const household = await service.join(request.body.inviteCode, request.user.keycloakId);
|
||||
return reply.send(toHouseholdResponse(household));
|
||||
},
|
||||
});
|
||||
},
|
||||
{
|
||||
name: 'households-routes',
|
||||
// users-routes must load first: it registers UsersRepository into the DI container,
|
||||
// which HouseholdsService depends on.
|
||||
dependencies: ['auth-plugin', 'users-routes'],
|
||||
},
|
||||
);
|
||||
253
packages/api/src/modules/households/households.service.test.ts
Normal file
253
packages/api/src/modules/households/households.service.test.ts
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { HouseholdsService } from './households.service.js';
|
||||
import { NotFoundError, ForbiddenError, ConflictError } from '../../common/errors.js';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
|
||||
// Mock uuid to return deterministic values
|
||||
vi.mock('uuid', () => ({
|
||||
v4: vi.fn(() => '12345678-1234-1234-1234-123456789abc'),
|
||||
}));
|
||||
|
||||
const { mockSession } = vi.hoisted(() => ({
|
||||
mockSession: {
|
||||
startTransaction: vi.fn(),
|
||||
commitTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
endSession: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('mongoose', () => ({
|
||||
default: { startSession: vi.fn().mockResolvedValue(mockSession) },
|
||||
}));
|
||||
|
||||
describe('HouseholdsService', () => {
|
||||
const mockHouseholdsRepo = {
|
||||
findById: vi.fn(),
|
||||
findByInviteCode: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
addMember: vi.fn(),
|
||||
updateInviteCode: vi.fn(),
|
||||
};
|
||||
|
||||
const mockUsersRepo = {
|
||||
findByKeycloakId: vi.fn(),
|
||||
findById: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
upsertFromToken: vi.fn(),
|
||||
};
|
||||
|
||||
let service: HouseholdsService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
service = new HouseholdsService({
|
||||
householdsRepository: mockHouseholdsRepo as never,
|
||||
usersRepository: mockUsersRepo as never,
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('creates a household and updates owner user', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test', ownerUserId: 'kc-1', inviteCode: '12345678' };
|
||||
mockHouseholdsRepo.create.mockResolvedValue(household);
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue({
|
||||
householdIds: [],
|
||||
defaultHouseholdId: null,
|
||||
});
|
||||
mockUsersRepo.update.mockResolvedValue({});
|
||||
|
||||
const result = await service.create({ name: 'Test' }, 'kc-1');
|
||||
|
||||
expect(result).toEqual(household);
|
||||
expect(mockHouseholdsRepo.create).toHaveBeenCalledWith(
|
||||
{ name: 'Test' },
|
||||
'kc-1',
|
||||
'12345678',
|
||||
mockSession,
|
||||
);
|
||||
expect(mockUsersRepo.update).toHaveBeenCalledWith(
|
||||
'kc-1',
|
||||
{ householdIds: ['hh1'], defaultHouseholdId: 'hh1' },
|
||||
mockSession,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves existing defaultHouseholdId when user already has one', async () => {
|
||||
const household = { _id: 'hh2', name: 'Second', ownerUserId: 'kc-1' };
|
||||
mockHouseholdsRepo.create.mockResolvedValue(household);
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue({
|
||||
householdIds: ['hh1'],
|
||||
defaultHouseholdId: 'hh1',
|
||||
});
|
||||
mockUsersRepo.update.mockResolvedValue({});
|
||||
|
||||
await service.create({ name: 'Second' }, 'kc-1');
|
||||
|
||||
expect(mockUsersRepo.update).toHaveBeenCalledWith(
|
||||
'kc-1',
|
||||
{ householdIds: ['hh1', 'hh2'], defaultHouseholdId: 'hh1' },
|
||||
mockSession,
|
||||
);
|
||||
});
|
||||
|
||||
it('handles case when owner user not found in db', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test', ownerUserId: 'kc-1' };
|
||||
mockHouseholdsRepo.create.mockResolvedValue(household);
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue(null);
|
||||
|
||||
const result = await service.create({ name: 'Test' }, 'kc-1');
|
||||
|
||||
expect(result).toEqual(household);
|
||||
expect(mockUsersRepo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns household when found', async () => {
|
||||
const household = { _id: 'hh1', name: 'Test' };
|
||||
mockHouseholdsRepo.findById.mockResolvedValue(household);
|
||||
|
||||
const result = await service.getById('hh1');
|
||||
expect(result).toEqual(household);
|
||||
});
|
||||
|
||||
it('throws NotFoundError when not found', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue(null);
|
||||
|
||||
await expect(service.getById('missing')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('allows owner to update', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
mockHouseholdsRepo.update.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
|
||||
|
||||
const result = await service.update('hh1', { name: 'Updated' }, 'kc-1');
|
||||
expect(result).toEqual({ _id: 'hh1', name: 'Updated' });
|
||||
});
|
||||
|
||||
it('allows admin to update', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-2', role: HouseholdRole.ADMIN }],
|
||||
});
|
||||
mockHouseholdsRepo.update.mockResolvedValue({ _id: 'hh1', name: 'Updated' });
|
||||
|
||||
await service.update('hh1', { name: 'Updated' }, 'kc-2');
|
||||
expect(mockHouseholdsRepo.update).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws ForbiddenError for regular member', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-3', role: HouseholdRole.MEMBER }],
|
||||
});
|
||||
|
||||
await expect(service.update('hh1', { name: 'X' }, 'kc-3')).rejects.toThrow(ForbiddenError);
|
||||
});
|
||||
|
||||
it('throws ForbiddenError for non-member', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
|
||||
await expect(service.update('hh1', { name: 'X' }, 'kc-other')).rejects.toThrow(
|
||||
ForbiddenError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateInviteCode', () => {
|
||||
it('generates new invite code for owner', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
mockHouseholdsRepo.updateInviteCode.mockResolvedValue({ inviteCode: '12345678' });
|
||||
|
||||
const result = await service.generateInviteCode('hh1', 'kc-1');
|
||||
expect(mockHouseholdsRepo.updateInviteCode).toHaveBeenCalledWith('hh1', '12345678');
|
||||
expect(result).toEqual({ inviteCode: '12345678' });
|
||||
});
|
||||
|
||||
it('throws ForbiddenError for regular member', async () => {
|
||||
mockHouseholdsRepo.findById.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-3', role: HouseholdRole.MEMBER }],
|
||||
});
|
||||
|
||||
await expect(service.generateInviteCode('hh1', 'kc-3')).rejects.toThrow(ForbiddenError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('join', () => {
|
||||
it('joins a household via invite code', async () => {
|
||||
const household = {
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
};
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
|
||||
mockHouseholdsRepo.addMember.mockResolvedValue({
|
||||
...household,
|
||||
members: [...household.members, { userId: 'kc-2' }],
|
||||
});
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue({
|
||||
householdIds: [],
|
||||
defaultHouseholdId: null,
|
||||
});
|
||||
mockUsersRepo.update.mockResolvedValue({});
|
||||
|
||||
const result = await service.join('ABCD1234', 'kc-2');
|
||||
|
||||
expect(mockHouseholdsRepo.addMember).toHaveBeenCalledWith(
|
||||
'hh1',
|
||||
'kc-2',
|
||||
HouseholdRole.MEMBER,
|
||||
mockSession,
|
||||
);
|
||||
expect(mockUsersRepo.update).toHaveBeenCalledWith(
|
||||
'kc-2',
|
||||
{ householdIds: ['hh1'], defaultHouseholdId: 'hh1' },
|
||||
mockSession,
|
||||
);
|
||||
expect(result).toBeDefined();
|
||||
});
|
||||
|
||||
it('throws NotFoundError for invalid invite code', async () => {
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(null);
|
||||
|
||||
await expect(service.join('INVALID', 'kc-2')).rejects.toThrow(NotFoundError);
|
||||
});
|
||||
|
||||
it('throws ConflictError when already a member', async () => {
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue({
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
});
|
||||
|
||||
await expect(service.join('CODE', 'kc-1')).rejects.toThrow(ConflictError);
|
||||
});
|
||||
|
||||
it('handles case when joining user not found in db', async () => {
|
||||
const household = {
|
||||
_id: 'hh1',
|
||||
members: [{ userId: 'kc-1', role: HouseholdRole.OWNER }],
|
||||
};
|
||||
mockHouseholdsRepo.findByInviteCode.mockResolvedValue(household);
|
||||
mockHouseholdsRepo.addMember.mockResolvedValue({});
|
||||
mockUsersRepo.findByKeycloakId.mockResolvedValue(null);
|
||||
|
||||
await service.join('CODE', 'kc-new');
|
||||
|
||||
expect(mockUsersRepo.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
135
packages/api/src/modules/households/households.service.ts
Normal file
135
packages/api/src/modules/households/households.service.ts
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import mongoose from 'mongoose';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { HouseholdsRepository } from './households.repository.js';
|
||||
import type { UsersRepository } from '../users/users.repository.js';
|
||||
import type { CreateHouseholdInput, UpdateHouseholdInput } from '@meshitrack/shared';
|
||||
import { HouseholdRole } from '@meshitrack/shared';
|
||||
import { NotFoundError, ForbiddenError, ConflictError } from '../../common/errors.js';
|
||||
|
||||
interface Deps {
|
||||
householdsRepository: HouseholdsRepository;
|
||||
usersRepository: UsersRepository;
|
||||
}
|
||||
|
||||
export class HouseholdsService {
|
||||
private readonly householdsRepository: HouseholdsRepository;
|
||||
private readonly usersRepository: UsersRepository;
|
||||
|
||||
public constructor({ householdsRepository, usersRepository }: Deps) {
|
||||
this.householdsRepository = householdsRepository;
|
||||
this.usersRepository = usersRepository;
|
||||
}
|
||||
|
||||
public async create(data: CreateHouseholdInput, ownerKeycloakId: string) {
|
||||
const inviteCode = uuidv4().slice(0, 8).toUpperCase();
|
||||
const session = await mongoose.startSession();
|
||||
try {
|
||||
session.startTransaction();
|
||||
|
||||
const household = await this.householdsRepository.create(
|
||||
data,
|
||||
ownerKeycloakId,
|
||||
inviteCode,
|
||||
session,
|
||||
);
|
||||
|
||||
const user = await this.usersRepository.findByKeycloakId(ownerKeycloakId, session);
|
||||
if (user) {
|
||||
const householdId = household._id.toString();
|
||||
await this.usersRepository.update(
|
||||
ownerKeycloakId,
|
||||
{
|
||||
householdIds: [...user.householdIds, householdId],
|
||||
defaultHouseholdId: user.defaultHouseholdId ?? householdId,
|
||||
},
|
||||
session,
|
||||
);
|
||||
}
|
||||
|
||||
await session.commitTransaction();
|
||||
return household;
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
session.endSession();
|
||||
}
|
||||
}
|
||||
|
||||
public async getById(id: string) {
|
||||
const household = await this.householdsRepository.findById(id);
|
||||
if (!household) {
|
||||
throw new NotFoundError('Household not found');
|
||||
}
|
||||
return household;
|
||||
}
|
||||
|
||||
public async update(id: string, data: UpdateHouseholdInput, requestingUserId: string) {
|
||||
const household = await this.getById(id);
|
||||
const member = household.members.find((m) => m.userId === requestingUserId);
|
||||
if (!member || (member.role !== HouseholdRole.OWNER && member.role !== HouseholdRole.ADMIN)) {
|
||||
throw new ForbiddenError('Only owners and admins can update household settings');
|
||||
}
|
||||
const updated = await this.householdsRepository.update(id, data);
|
||||
if (!updated) throw new NotFoundError('Household not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async generateInviteCode(id: string, requestingUserId: string) {
|
||||
const household = await this.getById(id);
|
||||
const member = household.members.find((m) => m.userId === requestingUserId);
|
||||
if (!member || (member.role !== HouseholdRole.OWNER && member.role !== HouseholdRole.ADMIN)) {
|
||||
throw new ForbiddenError('Only owners and admins can generate invite codes');
|
||||
}
|
||||
const newCode = uuidv4().slice(0, 8).toUpperCase();
|
||||
const updated = await this.householdsRepository.updateInviteCode(id, newCode);
|
||||
if (!updated) throw new NotFoundError('Household not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
public async join(inviteCode: string, userId: string) {
|
||||
const household = await this.householdsRepository.findByInviteCode(inviteCode);
|
||||
if (!household) {
|
||||
throw new NotFoundError('Invalid invite code');
|
||||
}
|
||||
|
||||
const alreadyMember = household.members.some((m) => m.userId === userId);
|
||||
if (alreadyMember) {
|
||||
throw new ConflictError('Already a member of this household');
|
||||
}
|
||||
|
||||
const session = await mongoose.startSession();
|
||||
try {
|
||||
session.startTransaction();
|
||||
|
||||
const updated = await this.householdsRepository.addMember(
|
||||
household._id.toString(),
|
||||
userId,
|
||||
HouseholdRole.MEMBER,
|
||||
session,
|
||||
);
|
||||
if (!updated) throw new NotFoundError('Household not found');
|
||||
|
||||
const user = await this.usersRepository.findByKeycloakId(userId, session);
|
||||
if (user) {
|
||||
const householdId = household._id.toString();
|
||||
await this.usersRepository.update(
|
||||
userId,
|
||||
{
|
||||
householdIds: [...user.householdIds, householdId],
|
||||
defaultHouseholdId: user.defaultHouseholdId ?? householdId,
|
||||
},
|
||||
session,
|
||||
);
|
||||
}
|
||||
|
||||
await session.commitTransaction();
|
||||
return updated;
|
||||
} catch (err) {
|
||||
await session.abortTransaction();
|
||||
throw err;
|
||||
} finally {
|
||||
session.endSession();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue