- Introduced `EmployeeUserWrite` type to manage user details associated with employees. - Updated `EmployeesService` and `EmployeesRepository` to support user assignment and retrieval by user ID. - Enhanced DTOs to include user information for employee creation and updates. - Implemented validation to ensure proper handling of user data during employee operations. - Added unit and e2e tests to validate the new functionality and ensure data integrity in user-employee relationships. - Modified existing controllers to accommodate the new user linkage features in employee management.
229 lines
6.8 KiB
TypeScript
229 lines
6.8 KiB
TypeScript
import { INestApplication } from '@nestjs/common';
|
|
import { Test, TestingModule } from '@nestjs/testing';
|
|
import { eq } from 'drizzle-orm';
|
|
import request from 'supertest';
|
|
import { App } from 'supertest/types';
|
|
import { AppModule } from '../src/app.module';
|
|
import { configureApp } from '../src/common/configure-app';
|
|
import { DRIZZLE, type DrizzleDB } from '../src/database/database.module';
|
|
import {
|
|
privilegeDetails,
|
|
privilegeKeys,
|
|
privileges,
|
|
users,
|
|
} from '../src/database/schema';
|
|
import { PRIVILEGE_ACTIONS } from '../src/modules/privileges/privilege-action';
|
|
import { registerAndActivate } from './helpers/activate-user';
|
|
|
|
describe('Users (e2e)', () => {
|
|
let app: INestApplication<App>;
|
|
let db: DrizzleDB;
|
|
|
|
const password = 'password123';
|
|
const adminUsername = `usr_admin_${Date.now()}`;
|
|
const otherUsername = `usr_other_${Date.now()}`;
|
|
|
|
let adminAccessToken: string;
|
|
let adminUserId: string;
|
|
let otherAccessToken: string;
|
|
|
|
beforeAll(async () => {
|
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
|
imports: [AppModule],
|
|
}).compile();
|
|
|
|
app = moduleFixture.createNestApplication();
|
|
configureApp(app, {
|
|
NODE_ENV: 'test',
|
|
SWAGGER_ENABLED: 'false',
|
|
});
|
|
await app.init();
|
|
db = app.get(DRIZZLE);
|
|
|
|
const admin = await registerAndActivate(app, db, adminUsername, password);
|
|
adminAccessToken = admin.accessToken;
|
|
adminUserId = admin.userId;
|
|
|
|
const other = await registerAndActivate(app, db, otherUsername, password);
|
|
otherAccessToken = other.accessToken;
|
|
|
|
const now = Date.now();
|
|
const [priv] = await db
|
|
.insert(privileges)
|
|
.values({
|
|
name: 'User Admin',
|
|
code: `USR_ADMIN_${now}`,
|
|
status: 'active',
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
createdBy: adminUserId,
|
|
updatedBy: adminUserId,
|
|
})
|
|
.returning();
|
|
|
|
const keys = await db.select().from(privilegeKeys);
|
|
const detailRows = keys.flatMap((key) =>
|
|
PRIVILEGE_ACTIONS.map((action) => ({
|
|
privilegeId: priv.id,
|
|
privilegeKeyId: key.id,
|
|
action,
|
|
value: true,
|
|
})),
|
|
);
|
|
await db.insert(privilegeDetails).values(detailRows);
|
|
|
|
await db
|
|
.update(users)
|
|
.set({ privilegeId: priv.id, updatedAt: Date.now() })
|
|
.where(eq(users.id, adminUserId));
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await app.close();
|
|
});
|
|
|
|
it('forbids users list without permission', async () => {
|
|
await request(app.getHttpServer())
|
|
.get('/users')
|
|
.set('Authorization', `Bearer ${otherAccessToken}`)
|
|
.expect(403);
|
|
});
|
|
|
|
it('rejects unauthenticated access', async () => {
|
|
await request(app.getHttpServer()).get('/users').expect(401);
|
|
});
|
|
|
|
it('CRUD users with status, privilege, search, bulk, and import', async () => {
|
|
const created = await request(app.getHttpServer())
|
|
.post('/users')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({
|
|
username: `usr_${Date.now().toString().slice(-6)}`,
|
|
password: 'password123',
|
|
})
|
|
.expect(201);
|
|
|
|
expect(created.body).toMatchObject({
|
|
status: 'draft',
|
|
privilege: null,
|
|
employee: null,
|
|
});
|
|
expect(created.body).not.toHaveProperty('passwordHash');
|
|
const id = (created.body as { id: string }).id;
|
|
|
|
await request(app.getHttpServer())
|
|
.get(`/users/${id}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(200);
|
|
|
|
const listed = await request(app.getHttpServer())
|
|
.get('/users')
|
|
.query({ search: 'usr_' })
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(200);
|
|
expect(listed.body.data.length).toBeGreaterThan(0);
|
|
expect(listed.body.meta).toBeDefined();
|
|
|
|
await request(app.getHttpServer())
|
|
.patch(`/users/${id}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ status: 'active' })
|
|
.expect(400);
|
|
|
|
await request(app.getHttpServer())
|
|
.patch(`/users/${id}/status`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ status: 'active' })
|
|
.expect(200);
|
|
|
|
await request(app.getHttpServer())
|
|
.post('/users/bulk-status')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ ids: [id], status: 'archived' })
|
|
.expect(200);
|
|
|
|
const csv = `username,password\nusr_imp_${Date.now().toString().slice(-5)},password123\n`;
|
|
await request(app.getHttpServer())
|
|
.post('/users/import')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.attach('file', Buffer.from(csv, 'utf8'), 'users.csv')
|
|
.expect(200);
|
|
|
|
await request(app.getHttpServer())
|
|
.post('/users/bulk-delete')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ ids: [id] })
|
|
.expect(200);
|
|
});
|
|
|
|
it('creates and updates a linked employee from the user payload', async () => {
|
|
const suffix = Date.now().toString().slice(-6);
|
|
const employee = await request(app.getHttpServer())
|
|
.post('/employees')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({
|
|
code: `UE_${suffix}`,
|
|
name: 'Ada Lovelace',
|
|
phone: '+6281234567890',
|
|
position: 'sales',
|
|
})
|
|
.expect(201);
|
|
const employeeId = (employee.body as { id: string }).id;
|
|
|
|
const created = await request(app.getHttpServer())
|
|
.post('/users')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({
|
|
username: `usr_emp_${suffix}`,
|
|
password: 'password123',
|
|
employeeId,
|
|
})
|
|
.expect(201);
|
|
|
|
expect(created.body.employee).toMatchObject({
|
|
id: employeeId,
|
|
code: `UE_${suffix}`,
|
|
name: 'Ada Lovelace',
|
|
});
|
|
const userId = (created.body as { id: string }).id;
|
|
|
|
const linked = await request(app.getHttpServer())
|
|
.get(`/employees/${employeeId}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(200);
|
|
expect(linked.body.user).toMatchObject({
|
|
id: userId,
|
|
username: `usr_emp_${suffix}`,
|
|
});
|
|
|
|
const existing = await request(app.getHttpServer())
|
|
.post('/employees')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({
|
|
code: `UL_${suffix}`,
|
|
name: 'Grace Hopper',
|
|
phone: '+6281234567891',
|
|
position: 'crew',
|
|
})
|
|
.expect(201);
|
|
const existingId = (existing.body as { id: string }).id;
|
|
|
|
const reassigned = await request(app.getHttpServer())
|
|
.patch(`/users/${userId}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ employeeId: existingId })
|
|
.expect(200);
|
|
expect(reassigned.body.employee).toMatchObject({
|
|
id: existingId,
|
|
name: 'Grace Hopper',
|
|
});
|
|
|
|
const unlinked = await request(app.getHttpServer())
|
|
.patch(`/users/${userId}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ employeeId: null })
|
|
.expect(200);
|
|
expect(unlinked.body.employee).toBeNull();
|
|
});
|
|
});
|