jws-backend/src/controllers/04-invoice-controller.ts
Kanjana 50fca4d540
All checks were successful
Spell Check / Spell Check with Typos (push) Successful in 5s
feat: remove customerName add reportDate
2025-07-09 16:02:45 +07:00

263 lines
7.2 KiB
TypeScript

import { Prisma } from "@prisma/client";
import {
Body,
Controller,
Get,
OperationId,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import prisma from "../db";
import { notFoundError } from "../utils/error";
import { RequestWithUser } from "../interfaces/user";
import {
branchRelationPermInclude,
createPermCheck,
createPermCondition,
} from "../services/permission";
import { PaymentStatus } from "../generated/kysely/types";
import { whereDateQuery } from "../utils/relation";
type InvoicePayload = {
quotationId: string;
amount: number;
installmentNo: number[];
};
const MANAGE_ROLES = [
"system",
"head_of_admin",
"admin",
"executive",
"accountant",
"branch_admin",
"branch_manager",
"branch_accountant",
];
function globalAllow(user: RequestWithUser["user"]) {
const listAllowed = ["system", "head_of_admin", "admin", "executive", "accountant"];
return user.roles?.some((v) => listAllowed.includes(v)) || false;
}
const permissionCondCompany = createPermCondition(globalAllow);
const permissionCheck = createPermCheck(globalAllow);
@Route("/api/v1/invoice")
@Tags("Invoice")
export class InvoiceController extends Controller {
@Get("stats")
@OperationId("getInvoiceStats")
@Security("keycloak")
async getInvoiceStats(
@Request() req: RequestWithUser,
@Query() quotationOnly: boolean = true,
@Query() quotationId?: string,
@Query() debitNoteId?: string,
@Query() debitNoteOnly?: boolean,
) {
const where = {
quotation: {
id: quotationId,
isDebitNote: debitNoteId || debitNoteOnly ? true : quotationOnly ? false : undefined,
registeredBranch: {
OR: permissionCondCompany(req.user),
},
},
} satisfies Prisma.InvoiceWhereInput;
const [pay, notPay] = await prisma.$transaction([
prisma.invoice.count({
where: {
...where,
payment: { paymentStatus: PaymentStatus.PaymentSuccess },
},
}),
prisma.invoice.count({
where: {
...where,
payment: { paymentStatus: { not: PaymentStatus.PaymentSuccess } },
},
}),
]);
return {
[PaymentStatus.PaymentSuccess]: pay,
[PaymentStatus.PaymentWait]: notPay,
};
}
@Get()
@OperationId("getInvoiceList")
@Security("keycloak")
async getInvoiceList(
@Request() req: RequestWithUser,
@Query() page: number = 1,
@Query() pageSize: number = 30,
@Query() query: string = "",
@Query() quotationOnly: boolean = true,
@Query() debitNoteOnly?: boolean,
@Query() quotationId?: string,
@Query() debitNoteId?: string,
@Query() pay?: boolean,
@Query() startDate?: Date,
@Query() endDate?: Date,
) {
const where: Prisma.InvoiceWhereInput = {
OR: [
{ code: { contains: query, mode: "insensitive" } },
{ quotation: { workName: { contains: query, mode: "insensitive" } } },
{
quotation: {
customerBranch: {
OR: [
{ code: { contains: query, mode: "insensitive" } },
{ registerName: { contains: query, mode: "insensitive" } },
{ registerNameEN: { contains: query, mode: "insensitive" } },
{ firstName: { contains: query, mode: "insensitive" } },
{ firstNameEN: { contains: query, mode: "insensitive" } },
{ lastName: { contains: query, mode: "insensitive" } },
{ lastNameEN: { contains: query, mode: "insensitive" } },
],
},
},
},
],
payment:
pay !== undefined
? {
paymentStatus: pay
? PaymentStatus.PaymentSuccess
: { not: PaymentStatus.PaymentSuccess },
}
: undefined,
quotation: {
id: quotationId || debitNoteId,
isDebitNote: debitNoteId || debitNoteOnly ? true : quotationOnly ? false : undefined,
registeredBranch: {
OR: permissionCondCompany(req.user),
},
},
...whereDateQuery(startDate, endDate),
};
const [result, total] = await prisma.$transaction([
prisma.invoice.findMany({
where,
include: {
installments: true,
quotation: {
include: {
customerBranch: {
include: { customer: true },
},
},
},
payment: true,
createdBy: true,
},
orderBy: { createdAt: "asc" },
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.invoice.count({ where }),
]);
return { result, page, pageSize, total };
}
@Get("{invoiceId}")
@OperationId("getInvoice")
@Security("keycloak")
async getInvoice(@Path() invoiceId: string) {
const record = await prisma.invoice.findFirst({
where: { id: invoiceId },
include: {
installments: true,
quotation: true,
createdBy: true,
},
orderBy: { createdAt: "asc" },
});
if (!record) throw notFoundError("Invoice");
return record;
}
@Post()
@OperationId("createInvoice")
@Security("keycloak", MANAGE_ROLES.concat(["head_of_sale", "sale"]))
async createInvoice(@Request() req: RequestWithUser, @Body() body: InvoicePayload) {
const [quotation] = await prisma.$transaction([
prisma.quotation.findUnique({
where: { id: body.quotationId },
include: { registeredBranch: { include: branchRelationPermInclude(req.user) } },
}),
]);
if (!quotation) throw notFoundError("Quotation");
await permissionCheck(req.user, quotation.registeredBranch);
return await prisma.$transaction(async (tx) => {
const current = new Date();
const year = `${current.getFullYear()}`.slice(-2).padStart(2, "0");
const month = `${current.getMonth() + 1}`.padStart(2, "0");
const last = await tx.runningNo.upsert({
where: {
key: `INVOICE_${year}${month}`,
},
create: {
key: `INVOICE_${year}${month}`,
value: 1,
},
update: { value: { increment: 1 } },
});
const record = await tx.quotation.update({
include: {
paySplit: {
where: { no: { in: body.installmentNo } },
},
},
where: { id: body.quotationId },
data: {
quotationStatus: "PaymentInProcess",
},
});
await tx.notification.create({
data: {
title: "ใบแจ้งหนี้ใหม่ / New Invoice",
detail: "รหัส / code : " + record.code,
registeredBranchId: record.registeredBranchId,
groupReceiver: { create: { name: "branch_accountant" } },
},
});
return await tx.invoice.create({
data: {
quotationId: body.quotationId,
code: `IV${year}${month}${last.value.toString().padStart(6, "0")}`,
amount: body.amount,
installments: {
connect: record.paySplit.map((v) => ({ id: v.id })),
},
payment: {
create: {
paymentStatus: "PaymentWait",
amount: body.amount,
},
},
createdByUserId: req.user.sub,
},
});
});
}
}