- Introduced new columns `status`, `created_by`, and `updated_by` in the `users` table to track user status and ownership. - Updated the `employees` table to include a foreign key reference to the `users` table via `user_id`. - Created migration script `0012_users_primary.sql` to apply these changes to the database schema. - Enhanced the `EmployeesService` and `EmployeesRepository` to support user assignments and related data retrieval. - Updated DTOs and service methods to reflect the new user and employee relationships. - Added unit tests to validate the new functionality and ensure data integrity. - Modified existing controllers to accommodate the new fields and relationships in user and employee management.
267 lines
8.3 KiB
TypeScript
267 lines
8.3 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('Customers (e2e)', () => {
|
|
let app: INestApplication<App>;
|
|
let db: DrizzleDB;
|
|
|
|
const password = 'password123';
|
|
const adminUsername = `cu_admin_${Date.now()}`;
|
|
const otherUsername = `cu_other_${Date.now()}`;
|
|
|
|
let adminAccessToken: string;
|
|
let adminUserId: string;
|
|
let otherAccessToken: string;
|
|
|
|
const payload = {
|
|
code: `CUST_${Date.now().toString().slice(-6)}`,
|
|
name: 'Acme Corp',
|
|
phone: '+6281234567890',
|
|
address: 'Jl Sudirman No 1',
|
|
};
|
|
|
|
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: 'Customer Admin',
|
|
code: `CU_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 customers list without permission', async () => {
|
|
await request(app.getHttpServer())
|
|
.get('/customers')
|
|
.set('Authorization', `Bearer ${otherAccessToken}`)
|
|
.expect(403);
|
|
});
|
|
|
|
it('rejects unauthenticated access', async () => {
|
|
await request(app.getHttpServer()).get('/customers').expect(401);
|
|
});
|
|
|
|
it('CRUD customers with contacts, uniqueness, nested routes, and bulk', async () => {
|
|
const created = await request(app.getHttpServer())
|
|
.post('/customers')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({
|
|
...payload,
|
|
contacts: [
|
|
{
|
|
name: 'Jean Luc',
|
|
jobTitle: 'Buyer',
|
|
phone: '+6281234567891',
|
|
},
|
|
],
|
|
})
|
|
.expect(201);
|
|
|
|
expect(created.body).toMatchObject({
|
|
code: payload.code,
|
|
name: 'Acme Corp',
|
|
phone: '+6281234567890',
|
|
status: 'draft',
|
|
createdBy: adminUserId,
|
|
latitude: null,
|
|
nfcId: null,
|
|
});
|
|
expect(
|
|
(created.body as { contacts: Array<{ name: string }> }).contacts,
|
|
).toEqual([expect.objectContaining({ name: 'Jean Luc' })]);
|
|
const id = (created.body as { id: string }).id;
|
|
|
|
await request(app.getHttpServer())
|
|
.post('/customers')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ ...payload, code: 'BAD 01', name: 'Other Corp' })
|
|
.expect(400);
|
|
|
|
await request(app.getHttpServer())
|
|
.post('/customers')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ ...payload, code: 'PHN_01', phone: '081234567890' })
|
|
.expect(400);
|
|
|
|
await request(app.getHttpServer())
|
|
.post('/customers')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ ...payload, code: payload.code, name: 'Other Corp' })
|
|
.expect(409);
|
|
|
|
const detail = await request(app.getHttpServer())
|
|
.get(`/customers/${id}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(200);
|
|
expect((detail.body as { contacts: unknown[] }).contacts.length).toBe(1);
|
|
|
|
await request(app.getHttpServer())
|
|
.patch(`/customers/${id}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({
|
|
name: 'Acme International',
|
|
latitude: -6.2,
|
|
longitude: 106.8,
|
|
nfcId: 'NFC-001',
|
|
contacts: [{ name: 'Ada Lovelace', jobTitle: 'Director' }],
|
|
})
|
|
.expect(200);
|
|
|
|
const replaced = await request(app.getHttpServer())
|
|
.get(`/customers/${id}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(200);
|
|
expect(
|
|
(replaced.body as { contacts: Array<{ name: string }> }).contacts,
|
|
).toEqual([expect.objectContaining({ name: 'Ada Lovelace' })]);
|
|
|
|
await request(app.getHttpServer())
|
|
.patch(`/customers/${id}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ status: 'active' })
|
|
.expect(400);
|
|
|
|
await request(app.getHttpServer())
|
|
.patch(`/customers/${id}/status`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ status: 'active' })
|
|
.expect(200);
|
|
|
|
const added = await request(app.getHttpServer())
|
|
.post(`/customers/${id}/contacts`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ name: 'Grace Hopper', mobilePhone: '+6281234567892' })
|
|
.expect(201);
|
|
const contacts = (
|
|
added.body as { contacts: Array<{ id: string; name: string }> }
|
|
).contacts;
|
|
expect(contacts.map((c) => c.name)).toEqual(
|
|
expect.arrayContaining(['Ada Lovelace', 'Grace Hopper']),
|
|
);
|
|
const graceId = contacts.find((c) => c.name === 'Grace Hopper')!.id;
|
|
|
|
await request(app.getHttpServer())
|
|
.patch(`/customers/${id}/contacts/${graceId}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ jobTitle: 'Engineer' })
|
|
.expect(200);
|
|
|
|
await request(app.getHttpServer())
|
|
.delete(`/customers/${id}/contacts/${graceId}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(204);
|
|
|
|
const list = await request(app.getHttpServer())
|
|
.get('/customers?search=Acme')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(200);
|
|
expect(
|
|
(list.body as { data: unknown[] }).data.length,
|
|
).toBeGreaterThanOrEqual(1);
|
|
expect(
|
|
(list.body as { data: Array<{ contacts?: unknown }> }).data[0],
|
|
).not.toHaveProperty('contacts');
|
|
expect((list.body as { meta?: unknown }).meta).toBeDefined();
|
|
|
|
const extra = await request(app.getHttpServer())
|
|
.post('/customers')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({
|
|
...payload,
|
|
code: `OTH_${Date.now().toString().slice(-6)}`,
|
|
name: 'Beta Corp',
|
|
})
|
|
.expect(201);
|
|
|
|
await request(app.getHttpServer())
|
|
.post('/customers/bulk-status')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ ids: [(extra.body as { id: string }).id], status: 'archived' })
|
|
.expect(200);
|
|
|
|
await request(app.getHttpServer())
|
|
.post('/customers/bulk-delete')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.send({ ids: [(extra.body as { id: string }).id] })
|
|
.expect(200);
|
|
|
|
await request(app.getHttpServer())
|
|
.delete(`/customers/${id}`)
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.expect(204);
|
|
});
|
|
|
|
it('imports customers from CSV', async () => {
|
|
const suffix = Date.now().toString().slice(-6);
|
|
const csv =
|
|
'code,name,phone,address,status\n' +
|
|
`IMP_${suffix},Imported Corp,+6281234567890,Jl Imported No 1,draft\n`;
|
|
const res = await request(app.getHttpServer())
|
|
.post('/customers/import')
|
|
.set('Authorization', `Bearer ${adminAccessToken}`)
|
|
.attach('file', Buffer.from(csv, 'utf8'), 'customers.csv')
|
|
.expect(201);
|
|
|
|
expect(res.body as { imported: number }).toMatchObject({ imported: 1 });
|
|
});
|
|
});
|