refactor: update flow-account api function

This commit is contained in:
Methapon2001 2024-12-12 10:32:53 +07:00
parent eb8e311d3d
commit 4245bcaca8

View file

@ -1,5 +1,6 @@
import prisma from "../db"; import prisma from "../db";
import config from "../config.json"; import config from "../config.json";
import { CustomerType } from "@prisma/client";
if (!process.env.FLOW_ACCOUNT_URL) throw new Error("Require FLOW_ACCOUNT_URL"); if (!process.env.FLOW_ACCOUNT_URL) throw new Error("Require FLOW_ACCOUNT_URL");
if (!process.env.FLOW_ACCOUNT_CLIENT_ID) throw new Error("Require FLOW_ACCOUNT_CLIENT_ID"); if (!process.env.FLOW_ACCOUNT_CLIENT_ID) throw new Error("Require FLOW_ACCOUNT_CLIENT_ID");
@ -50,6 +51,13 @@ enum ProductAndServiceType {
ProductInv = 5, ProductInv = 5,
} }
enum PaymentDeductionType {
SpecialDiscount = 1,
Commission = 3,
Process = 5,
Round = 7,
}
type ProductAndService = { type ProductAndService = {
type?: ProductAndServiceType; type?: ProductAndServiceType;
name: string; name: string;
@ -144,6 +152,10 @@ const flowAccountAPI = {
documentStructureType?: "SimpleDocument" | null; documentStructureType?: "SimpleDocument" | null;
saleAndPurchaseChannel?: SaleAndPurchaseChannel; saleAndPurchaseChannel?: SaleAndPurchaseChannel;
items: ProductAndService[]; items: ProductAndService[];
/** This must be in yyyy-MM-dd format if pass as string */
paymentDate: Date | string;
paymentDeductionType?: PaymentDeductionType;
collected: number;
}, },
withPayment?: boolean, withPayment?: boolean,
) { ) {
@ -163,7 +175,14 @@ const flowAccountAPI = {
data.dueDate = `${year}-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`; data.dueDate = `${year}-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`;
} }
const res = await fetch(api + "/tax-invoices/inline" + withPayment ? "/with-payment" : "", { if (data.paymentDate instanceof Date) {
let date = data.paymentDate.getDate();
let month = data.paymentDate.getMonth() + 1;
let year = data.paymentDate.getFullYear();
data.paymentDate = `${year}-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`;
}
const res = await fetch(api + "/tax-invoices/inline" + (withPayment ? "/with-payment" : ""), {
method: "POST", method: "POST",
headers: { headers: {
["Content-Type"]: `application/json`, ["Content-Type"]: `application/json`,
@ -180,14 +199,16 @@ const flowAccountAPI = {
}, },
async getInvoiceDocument(recordId: string) { async getInvoiceDocument(recordId: string) {
const res = await fetch(api + "tax-invoices/shareddocument", { const { token } = await flowAccountAPI.auth();
const res = await fetch(api + "/tax-invoices/sharedocument", {
method: "POST", method: "POST",
headers: { headers: {
["Content-Type"]: `application/json`, ["Content-Type"]: `application/json`,
["Authorization"]: `Bearer ${token}`, ["Authorization"]: `Bearer ${token}`,
}, },
body: JSON.stringify({ body: JSON.stringify({
recordId, documentId: recordId,
culture: "th", culture: "th",
}), }),
}); });
@ -195,13 +216,13 @@ const flowAccountAPI = {
return { return {
ok: res.ok, ok: res.ok,
status: res.status, status: res.status,
body: await res.json(), body: await res.text(),
}; };
}, },
}; };
const flowAccount = { const flowAccount = {
issueInvoiceWithPayment: async (invoiceId: string) => { issueInvoice: async (invoiceId: string) => {
const data = await prisma.invoice.findFirst({ const data = await prisma.invoice.findFirst({
where: { id: invoiceId }, where: { id: invoiceId },
include: { include: {
@ -240,10 +261,12 @@ const flowAccount = {
const branch = quotation.registeredBranch; const branch = quotation.registeredBranch;
const product = quotation.productServiceList; const product = quotation.productServiceList;
return await flowAccountAPI.createInvoice( const payload = {
{
contactCode: customer.code, contactCode: customer.code,
contactName: [customer.firstName, customer.lastName].join(" "), contactName:
(customer.customer.customerType === CustomerType.PERS
? [customer.firstName, customer.lastName].join(" ").trim()
: customer.registerName) || "-",
contactAddress: [ contactAddress: [
customer.address, customer.address,
!!customer.moo ? "หมู่" + customer.moo : null, !!customer.moo ? "หมู่" + customer.moo : null,
@ -257,11 +280,14 @@ const flowAccount = {
.filter(Boolean) .filter(Boolean)
.join(" "), .join(" "),
contactTaxId: customer.citizenId || customer.code, contactTaxId: customer.citizenId || customer.code,
contactBranch: customer.authorizedName ?? undefined, contactBranch:
contactPerson: branch.contactName ?? undefined, (customer.customer.customerType === CustomerType.PERS
contactEmail: branch.email, ? [customer.firstName, customer.lastName].join(" ").trim()
contactNumber: branch.telephoneNo, : customer.registerName) || "-",
contactZipCode: branch.subDistrict?.zipCode, contactPerson: customer.contactName ?? undefined,
contactEmail: customer.email,
contactNumber: customer.telephoneNo,
contactZipCode: customer.subDistrict?.zipCode,
contactGroup: contactGroup:
customer.customer.customerType === "PERS" ? ContactGroup.PERS : ContactGroup.CORP, customer.customer.customerType === "PERS" ? ContactGroup.PERS : ContactGroup.CORP,
dueDate: quotation.dueDate, dueDate: quotation.dueDate,
@ -280,6 +306,9 @@ const flowAccount = {
vatAmount: quotation.vat, vatAmount: quotation.vat,
grandTotal: quotation.finalPrice, grandTotal: quotation.finalPrice,
paymentDate: data.payment?.createdAt ?? new Date(),
collected: quotation.finalPrice,
items: product.map((v) => ({ items: product.map((v) => ({
type: ProductAndServiceType.ProductNonInv, type: ProductAndServiceType.ProductNonInv,
name: v.product.name, name: v.product.name,
@ -287,20 +316,19 @@ const flowAccount = {
quantity: v.amount, quantity: v.amount,
discountAmount: v.discount, discountAmount: v.discount,
total: (v.pricePerUnit - (v.discount || 0)) * v.amount + v.vat, total: (v.pricePerUnit - (v.discount || 0)) * v.amount + v.vat,
vatRate: VAT_DEFAULT * 100, vatRate: Math.round(VAT_DEFAULT * 100),
})), })),
}, };
true,
); return await flowAccountAPI.createInvoice(payload, false);
}, },
getInvoiceDocument: async (recordId: string) => { getInvoiceDocument: async (recordId: string) => {
const ret = await flowAccountAPI.getInvoiceDocument(recordId); const ret = await flowAccountAPI.getInvoiceDocument(recordId);
console.log(ret);
if (ret && ret.ok) { if (ret && ret.ok) {
return ret.body.data.link; return ret.body;
} }
return null; return null;
}, },
}; };