refactor: update to receipt only instead of set

This commit is contained in:
Methapon2001 2024-12-24 10:11:11 +07:00
parent ce51b8cc0f
commit aecf52fdc9
2 changed files with 57 additions and 32 deletions

View file

@ -331,6 +331,14 @@ export class FlowAccountController extends Controller {
const result = await flowAccount.issueInvoice(payment.invoice.id); const result = await flowAccount.issueInvoice(payment.invoice.id);
const documentId = result?.body?.data?.documentId; const documentId = result?.body?.data?.documentId;
if (!documentId) {
throw new HttpError(
HttpStatus.INTERNAL_SERVER_ERROR,
"FlowAccount error",
"flowAccountError",
);
}
await prisma.invoice.update({ await prisma.invoice.update({
where: { id: payment.invoice.id }, where: { id: payment.invoice.id },
data: { flowAccountRecordId: String(documentId) }, data: { flowAccountRecordId: String(documentId) },

View file

@ -1,6 +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"; import { CustomerType, PayCondition } 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");
@ -105,7 +105,7 @@ const flowAccountAPI = {
return { token, tokenExpire }; return { token, tokenExpire };
}, },
async createInvoice( async createReceipt(
data: { data: {
recordId?: string; recordId?: string;
contactCode?: string; contactCode?: string;
@ -153,9 +153,9 @@ const flowAccountAPI = {
saleAndPurchaseChannel?: SaleAndPurchaseChannel; saleAndPurchaseChannel?: SaleAndPurchaseChannel;
items: ProductAndService[]; items: ProductAndService[];
/** This must be in yyyy-MM-dd format if pass as string */ /** This must be in yyyy-MM-dd format if pass as string */
paymentDate: Date | string; // paymentDate: Date | string;
paymentDeductionType?: PaymentDeductionType; // paymentDeductionType?: PaymentDeductionType;
collected: number; // collected: number;
}, },
withPayment?: boolean, withPayment?: boolean,
) { ) {
@ -175,21 +175,24 @@ 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")}`;
} }
if (data.paymentDate instanceof Date) { /* if (data.paymentDate instanceof Date) {
let date = data.paymentDate.getDate(); let date = data.paymentDate.getDate();
let month = data.paymentDate.getMonth() + 1; let month = data.paymentDate.getMonth() + 1;
let year = data.paymentDate.getFullYear(); let year = data.paymentDate.getFullYear();
data.paymentDate = `${year}-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`; data.paymentDate = `${year}-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`;
} } */
const res = await fetch(api + "/tax-invoices/inline" + (withPayment ? "/with-payment" : ""), { const res = await fetch(
method: "POST", api + "/upgrade/receipts/inline" + (withPayment ? "/with-payment" : ""),
headers: { {
["Content-Type"]: `application/json`, method: "POST",
["Authorization"]: `Bearer ${token}`, headers: {
["Content-Type"]: `application/json`,
["Authorization"]: `Bearer ${token}`,
},
body: JSON.stringify({ ...data, referenceDocument: [] }),
}, },
body: JSON.stringify(data), );
});
return { return {
ok: res.ok, ok: res.ok,
@ -201,7 +204,7 @@ const flowAccountAPI = {
async getInvoiceDocument(recordId: string) { async getInvoiceDocument(recordId: string) {
const { token } = await flowAccountAPI.auth(); const { token } = await flowAccountAPI.auth();
const res = await fetch(api + "/tax-invoices/sharedocument", { const res = await fetch(api + "/receipts/sharedocument", {
method: "POST", method: "POST",
headers: { headers: {
["Content-Type"]: `application/json`, ["Content-Type"]: `application/json`,
@ -226,6 +229,7 @@ const flowAccount = {
const data = await prisma.invoice.findFirst({ const data = await prisma.invoice.findFirst({
where: { id: invoiceId }, where: { id: invoiceId },
include: { include: {
installments: true,
quotation: { quotation: {
include: { include: {
registeredBranch: { registeredBranch: {
@ -258,9 +262,13 @@ const flowAccount = {
const quotation = data.quotation; const quotation = data.quotation;
const customer = quotation.customerBranch; const customer = quotation.customerBranch;
const branch = quotation.registeredBranch; const product =
const product = quotation.productServiceList; quotation.payCondition === PayCondition.BillFull ||
quotation.payCondition === PayCondition.Full
? quotation.productServiceList
: quotation.productServiceList.filter((lhs) =>
data.installments.some((rhs) => rhs.no === lhs.installmentNo),
);
const payload = { const payload = {
contactCode: customer.code, contactCode: customer.code,
contactName: contactName:
@ -269,12 +277,12 @@ const flowAccount = {
: customer.registerName) || "-", : customer.registerName) || "-",
contactAddress: [ contactAddress: [
customer.address, customer.address,
!!customer.moo ? "หมู่" + customer.moo : null, !!customer.moo ? "หมู่ " + customer.moo : null,
!!customer.soi ? "ซอย" + customer.soi : null, !!customer.soi ? "ซอย " + customer.soi : null,
!!customer.street ? "ถนน" + customer.street : null, !!customer.street ? "ถนน " + customer.street : null,
(customer.province?.id === "10" ? "แขวง" : "อำเภอ") + customer.subDistrict?.name, (customer.province?.id === "10" ? "แขวง" : "อำเภอ") + customer.subDistrict?.name,
(customer.province?.id === "10" ? "เขต" : "ตำบล") + customer.district?.name, (customer.province?.id === "10" ? "เขต" : "ตำบล") + customer.district?.name,
customer.province?.name, "จังหวัด" + customer.province?.name,
customer.subDistrict?.zipCode, customer.subDistrict?.zipCode,
] ]
.filter(Boolean) .filter(Boolean)
@ -296,18 +304,27 @@ const flowAccount = {
isVatInclusive: true, isVatInclusive: true,
isVat: true, isVat: true,
useReceiptDeduction: true, useReceiptDeduction: false,
discounPercentage: 0, discounPercentage: 0,
discountAmount: quotation.totalDiscount, discountAmount: quotation.totalDiscount,
subTotal: quotation.totalPrice, subTotal:
totalAfterDiscount: quotation.finalPrice, quotation.payCondition === "BillSplitCustom" || quotation.payCondition === "SplitCustom"
vatAmount: quotation.vat, ? 0
grandTotal: quotation.finalPrice, : quotation.totalPrice,
totalAfterDiscount:
paymentDate: data.payment?.createdAt ?? new Date(), quotation.payCondition === "BillSplitCustom" || quotation.payCondition === "SplitCustom"
collected: quotation.finalPrice, ? 0
: quotation.finalPrice,
vatAmount:
quotation.payCondition === "BillSplitCustom" || quotation.payCondition === "SplitCustom"
? 0
: quotation.vat,
grandTotal:
quotation.payCondition === "BillSplitCustom" || quotation.payCondition === "SplitCustom"
? data.installments.reduce((a, c) => a + c.amount, 0)
: quotation.finalPrice,
items: product.map((v) => ({ items: product.map((v) => ({
type: ProductAndServiceType.ProductNonInv, type: ProductAndServiceType.ProductNonInv,
@ -316,11 +333,11 @@ 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: Math.round(VAT_DEFAULT * 100), vatRate: v.vat === 0 ? 0 : Math.round(VAT_DEFAULT * 100),
})), })),
}; };
return await flowAccountAPI.createInvoice(payload, false); return await flowAccountAPI.createReceipt(payload, false);
}, },
getInvoiceDocument: async (recordId: string) => { getInvoiceDocument: async (recordId: string) => {