feat: add payment for split

This commit is contained in:
Methapon Metanipat 2024-10-15 13:29:40 +07:00
parent ca6b1e74d0
commit 20b7e56a0d
4 changed files with 151 additions and 30 deletions

View file

@ -0,0 +1,37 @@
/*
Warnings:
- The values [PaymentWait] on the enum `QuotationStatus` will be removed. If these variants are still used in the database, this will fail.
*/
-- CreateEnum
CREATE TYPE "PaymentStatus" AS ENUM ('PaymentWait', 'PaymentSuccess');
-- AlterEnum
BEGIN;
CREATE TYPE "QuotationStatus_new" AS ENUM ('PaymentPending', 'PaymentInProcess', 'PaymentSuccess', 'ProcessComplete', 'Canceled');
ALTER TABLE "Quotation" ALTER COLUMN "quotationStatus" DROP DEFAULT;
ALTER TABLE "Quotation" ALTER COLUMN "quotationStatus" TYPE "QuotationStatus_new" USING ("quotationStatus"::text::"QuotationStatus_new");
ALTER TYPE "QuotationStatus" RENAME TO "QuotationStatus_old";
ALTER TYPE "QuotationStatus_new" RENAME TO "QuotationStatus";
DROP TYPE "QuotationStatus_old";
ALTER TABLE "Quotation" ALTER COLUMN "quotationStatus" SET DEFAULT 'PaymentPending';
COMMIT;
-- AlterTable
ALTER TABLE "Quotation" ALTER COLUMN "quotationStatus" SET DEFAULT 'PaymentPending';
-- CreateTable
CREATE TABLE "QuotationPayment" (
"id" TEXT NOT NULL,
"paymentStatus" "PaymentStatus" NOT NULL,
"date" TIMESTAMP(3) NOT NULL,
"amount" DOUBLE PRECISION NOT NULL,
"remark" TEXT,
"quotationId" TEXT NOT NULL,
CONSTRAINT "QuotationPayment_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "QuotationPayment" ADD CONSTRAINT "QuotationPayment_quotationId_fkey" FOREIGN KEY ("quotationId") REFERENCES "Quotation"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View file

@ -1074,9 +1074,10 @@ model WorkProduct {
enum QuotationStatus { enum QuotationStatus {
PaymentPending PaymentPending
PaymentWait PaymentInProcess // For Installments / Split Payment
PaymentSuccess PaymentSuccess
ProcessComplete ProcessComplete
Canceled
} }
enum PayCondition { enum PayCondition {
@ -1095,7 +1096,8 @@ model Quotation {
status Status @default(CREATED) status Status @default(CREATED)
statusOrder Int @default(0) statusOrder Int @default(0)
quotationStatus QuotationStatus @default(PaymentWait) quotationStatus QuotationStatus @default(PaymentPending)
quotationPaymentData QuotationPayment[]
code String code String
@ -1137,6 +1139,24 @@ model Quotation {
updatedByUserId String? updatedByUserId String?
} }
enum PaymentStatus {
PaymentWait
PaymentSuccess
}
model QuotationPayment {
id String @id @default(cuid())
paymentStatus PaymentStatus
date DateTime
amount Float
remark String?
quotation Quotation @relation(fields: [quotationId], references: [id])
quotationId String
}
model QuotationPaySplit { model QuotationPaySplit {
id String @id @default(cuid()) id String @id @default(cuid())

View file

@ -1,21 +1,37 @@
import { Controller, Path, Post, Put, Route, Tags } from "tsoa"; import { Body, Controller, Get, Path, Post, Put, Query, Request, Route, Tags } from "tsoa";
import express from "express";
import prisma from "../db"; import prisma from "../db";
import { notFoundError } from "../utils/error"; import { notFoundError } from "../utils/error";
import HttpError from "../interfaces/http-error"; import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status"; import HttpStatus from "../interfaces/http-status";
import { fileLocation, getFile, setFile } from "../utils/minio";
@Tags("Quotation") @Tags("Quotation")
@Route("api/v1/quotation/{quotationId}/payment") @Route("api/v1/quotation/{quotationId}/payment")
export class QuotationPayment extends Controller { export class QuotationPayment extends Controller {
@Post("submit") @Get("quotationId")
async submitPayment(@Path("quotationId") id: string) { async getPayment(@Path() quotationId: string) {
const record = await prisma.quotation.findFirst({
where: { id: quotationId },
include: {
quotationPaymentData: true,
createdBy: true,
updatedBy: true,
},
});
return record;
}
@Post()
async addPayment(@Path() quotationId: string, @Body() body: { amount: number; date: Date }) {
const record = await prisma.quotation.findUnique({ const record = await prisma.quotation.findUnique({
where: { id }, where: { id: quotationId },
}); });
if (!record) throw notFoundError("Quotation"); if (!record) throw notFoundError("Quotation");
if (record.quotationStatus !== "PaymentPending" && record.quotationStatus !== "PaymentWait") { if (record.quotationStatus !== "PaymentPending") {
// NOTE: The quotation must be in waiting for payment or waiting for payment confirmation (re-submit payment) // NOTE: The quotation must be in waiting for payment or waiting for payment confirmation (re-submit payment)
throw new HttpError( throw new HttpError(
HttpStatus.PRECONDITION_FAILED, HttpStatus.PRECONDITION_FAILED,
@ -24,21 +40,43 @@ export class QuotationPayment extends Controller {
); );
} }
await prisma.quotation.update({ return await prisma.quotation.update({
where: { id }, where: { id: quotationId },
data: { quotationStatus: "PaymentWait" }, include: { quotationPaymentData: true },
data: {
quotationStatus: "PaymentInProcess",
quotationPaymentData: {
create: {
paymentStatus: "PaymentWait",
...body,
},
},
},
}); });
} }
@Put("file") @Get("{paymentId}/file")
async uploadPayment(@Path("quotationId") id: string) { async getPaymentFile(
@Request() req: express.Request,
@Path() quotationId: string,
@Path() paymentId: string,
) {
return req.res?.redirect(await getFile(fileLocation.quotation.payment(quotationId, paymentId)));
}
@Put("{paymentId}/file")
async uploadPayment(
@Request() req: express.Request,
@Path() quotationId: string,
@Path() paymentId: string,
) {
const record = await prisma.quotation.findUnique({ const record = await prisma.quotation.findUnique({
where: { id }, where: { id: quotationId },
}); });
if (!record) throw notFoundError("Quotation"); if (!record) throw notFoundError("Quotation");
if (record.quotationStatus !== "PaymentPending" && record.quotationStatus !== "PaymentWait") { if (record.quotationStatus !== "PaymentPending") {
// NOTE: The quotation must be in waiting for payment or waiting for payment confirmation (re-submit payment) // NOTE: The quotation must be in waiting for payment or waiting for payment confirmation (re-submit payment)
throw new HttpError( throw new HttpError(
HttpStatus.PRECONDITION_FAILED, HttpStatus.PRECONDITION_FAILED,
@ -46,13 +84,22 @@ export class QuotationPayment extends Controller {
"quotationStatusWrong", "quotationStatusWrong",
); );
} }
return req.res?.redirect(await setFile(fileLocation.quotation.payment(quotationId, paymentId)));
} }
@Post("confirm") @Post("confirm")
async confirmPayment(@Path("quotationId") id: string) { async confirmPayment(@Path() quotationId: string, @Query() paymentId?: string) {
const record = await prisma.quotation.findUnique({ const record = await prisma.quotation.findUnique({
include: { include: {
_count: {
select: {
quotationPaymentData: true,
paySplit: true,
},
},
worker: true, worker: true,
quotationPaymentData: true,
productServiceList: { productServiceList: {
include: { include: {
worker: true, worker: true,
@ -62,28 +109,44 @@ export class QuotationPayment extends Controller {
}, },
}, },
}, },
where: { id }, where: { id: quotationId },
}); });
if (!record) throw notFoundError("Quotation"); if (!record) throw notFoundError("Quotation");
await prisma.$transaction(async (tx) => { await prisma.$transaction(async (tx) => {
await tx.quotation.update({ await tx.quotation.update({
where: { id }, where: { id: quotationId },
data: { data: {
quotationStatus: "PaymentSuccess", quotationStatus:
requestData: { record.payCondition === "Full" ||
create: record.worker.map((v) => ({ record.payCondition === "BillFull" ||
employeeId: v.employeeId, record._count.paySplit === record._count.quotationPaymentData
requestWork: { ? "PaymentSuccess"
create: record.productServiceList.flatMap((item) => : undefined,
item.worker.findIndex((w) => w.employeeId === v.employeeId) !== -1 quotationPaymentData: {
? { productServiceId: item.id } update: paymentId
: [], ? {
), where: { id: paymentId },
}, data: { paymentStatus: "PaymentSuccess" },
})), }
: undefined,
}, },
requestData:
record.quotationStatus === "PaymentPending"
? {
create: record.worker.map((v) => ({
employeeId: v.employeeId,
requestWork: {
create: record.productServiceList.flatMap((item) =>
item.worker.findIndex((w) => w.employeeId === v.employeeId) !== -1
? { productServiceId: item.id }
: [],
),
},
})),
}
: undefined,
}, },
}); });
}); });

View file

@ -91,7 +91,8 @@ export const fileLocation = {
img: (serviceId: string, name?: string) => `service/img-${serviceId}/${name || ""}`, img: (serviceId: string, name?: string) => `service/img-${serviceId}/${name || ""}`,
}, },
quotation: { quotation: {
payment: (quotationId: string) => `quotation/payment-${quotationId}`, payment: (quotationId: string, paymentId: string) =>
`quotation/payment-${quotationId}/${paymentId || ""}`,
}, },
request: { request: {
attachment: (requestId: string, name?: string) => attachment: (requestId: string, name?: string) =>