Files
trackgo-be/test/sales-invoices.e2e-spec.ts
shancheas 0e73d14381 Add address fields to sales invoices and implement related validations
- Introduced new columns `address`, `latitude`, and `longitude` in the `sales_invoices` table to store location details.
- Updated the `SalesInvoicesService` to handle the new fields, including validation for address format and geographical coordinates.
- Enhanced the `SalesInvoiceDto` and related data transfer objects to include the new fields for API requests and responses.
- Added unit and e2e tests to ensure proper handling of the new fields and validate their integration within the sales invoice workflow.
- Created a new migration script to apply the database schema changes for the sales invoices.
2026-09-01 09:50:19 +07:00

202 lines
5.7 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('Sales invoices (e2e)', () => {
let app: INestApplication<App>;
let db: DrizzleDB;
let token: string;
let otherToken: string;
let salesPersonId: string;
let branchId: string;
let divisionId: string;
let customerId: string;
let productId: string;
const password = 'password123';
const suffix = Date.now().toString().slice(-6);
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,
`si_admin_${suffix}`,
password,
);
token = admin.accessToken;
const adminUserId = admin.userId;
const other = await registerAndActivate(
app,
db,
`si_other_${suffix}`,
password,
);
otherToken = other.accessToken;
const now = Date.now();
const [priv] = await db
.insert(privileges)
.values({
name: 'Invoice Admin',
code: `SI_ADMIN_${now}`,
status: 'active',
createdAt: now,
updatedAt: now,
createdBy: adminUserId,
updatedBy: adminUserId,
})
.returning();
const keys = await db.select().from(privilegeKeys);
await db.insert(privilegeDetails).values(
keys.flatMap((key) =>
PRIVILEGE_ACTIONS.map((action) => ({
privilegeId: priv.id,
privilegeKeyId: key.id,
action,
value: true,
})),
),
);
await db
.update(users)
.set({ privilegeId: priv.id, updatedAt: Date.now() })
.where(eq(users.id, adminUserId));
const auth = { Authorization: `Bearer ${token}` };
const division = await request(app.getHttpServer())
.post('/divisions')
.set(auth)
.send({ code: `D_${suffix}`, name: 'Sales Division' })
.expect(201);
divisionId = (division.body as { id: string }).id;
const branch = await request(app.getHttpServer())
.post('/branches')
.set(auth)
.send({
code: `B_${suffix}`,
name: 'Jakarta Pusat',
phone: '+6281234567890',
address: 'Jl Sudirman 1',
workingDaysStart: 'monday',
workingDaysEnd: 'friday',
workingHoursStart: '08:00',
workingHoursEnd: '17:00',
divisionId,
})
.expect(201);
branchId = (branch.body as { id: string }).id;
const employee = await request(app.getHttpServer())
.post('/employees')
.set(auth)
.send({
code: `E_${suffix}`,
name: 'Ada Lovelace',
phone: '+6281234567890',
position: 'sales',
})
.expect(201);
salesPersonId = (employee.body as { id: string }).id;
const customer = await request(app.getHttpServer())
.post('/customers')
.set(auth)
.send({
code: `C_${suffix}`,
name: 'Acme Corp',
phone: '+6281234567890',
address: 'Jl Sudirman 1',
})
.expect(201);
customerId = (customer.body as { id: string }).id;
const product = await request(app.getHttpServer())
.post('/products')
.set(auth)
.send({
code: `P_${suffix}`,
name: 'Fuel 95',
price: '12500.0000',
})
.expect(201);
productId = (product.body as { id: string }).id;
});
afterAll(async () => {
await app.close();
});
it('rejects unauthenticated access', async () => {
await request(app.getHttpServer()).get('/sales-invoices').expect(401);
});
it('forbids list without permission', async () => {
await request(app.getHttpServer())
.get('/sales-invoices')
.set('Authorization', `Bearer ${otherToken}`)
.expect(403);
});
it('creates an invoice with catalog price and stored balance', async () => {
const created = await request(app.getHttpServer())
.post('/sales-invoices')
.set('Authorization', `Bearer ${token}`)
.send({
date: '2026-08-24T10:00:00+07:00',
salesPersonId,
branchId,
divisionId,
customerId,
address: 'Jl Sudirman 1',
latitude: -6.2,
longitude: 106.8,
products: [{ productId, quantity: '2' }],
})
.expect(201);
expect(created.body).toMatchObject({
status: 'draft',
balance: '25000.0000',
address: 'Jl Sudirman 1',
latitude: -6.2,
longitude: 106.8,
});
expect((created.body as { code: string }).code).toMatch(/^SI-/);
const id = (created.body as { id: string }).id;
await request(app.getHttpServer())
.patch(`/sales-invoices/${id}`)
.set('Authorization', `Bearer ${token}`)
.send({ status: 'processed' })
.expect(400);
await request(app.getHttpServer())
.patch(`/sales-invoices/${id}/status`)
.set('Authorization', `Bearer ${token}`)
.send({ status: 'processed' })
.expect(200);
await request(app.getHttpServer())
.delete(`/sales-invoices/${id}`)
.set('Authorization', `Bearer ${token}`)
.expect(204);
});
});