feat: delete created data when flow account create fail one
All checks were successful
Spell Check / Spell Check with Typos (push) Successful in 6s

This commit is contained in:
HAM 2025-09-29 09:44:41 +07:00
parent 3454e46212
commit 5dc88c22dc

View file

@ -454,7 +454,7 @@ const flowAccount = {
},
// flowAccount POST create Product
async createProducts(code: String, body: JsonObject) {
async createProducts(code: string, body: JsonObject) {
const { token } = await flowAccountAPI.auth();
const commonBody = {
@ -470,7 +470,7 @@ const flowAccount = {
const createProduct = async (name: string, price: any, vatIncluded: boolean) => {
try {
const res = await fetch(api + "/products", {
const res = await fetch(`${api}/products`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -478,22 +478,17 @@ const flowAccount = {
},
body: JSON.stringify({
...commonBody,
name: name,
name,
sellPrice: price,
sellVatType: vatIncluded ? 1 : 3,
}),
});
if (!res.ok) {
throw new Error(`Request failed with status ${res.status} ${res}`);
}
if (!res.ok) throw new Error(`HTTP ${res.status}: Failed to create product`);
let json: any = null;
try {
json = await res.json();
} catch {
throw new Error("Response is not valid JSON");
}
const json = await res.json().catch(() => {
throw new Error("Invalid JSON response from FlowAccount API");
});
return json?.data?.list?.[0]?.id ?? null;
} catch (err) {
@ -502,7 +497,18 @@ const flowAccount = {
}
};
const [sellId, agentId] = await Promise.all([
const deleteProduct = async (id: string) => {
try {
await fetch(`${api}/products/${id}`, {
method: "DELETE",
headers: { Authorization: `Bearer ${token}` },
});
} catch (err) {
console.error("Rollback delete failed:", err);
}
};
const [sellResult, agentResult] = await Promise.allSettled([
createProduct(`${code} ${body.name}`, body.price, /true/.test(`${body.vatIncluded}`)),
createProduct(
`${code} ${body.name} (ราคาตัวแทน)`,
@ -511,9 +517,25 @@ const flowAccount = {
),
]);
const sellId = sellResult.status === "fulfilled" ? sellResult.value : null;
const agentId = agentResult.status === "fulfilled" ? agentResult.value : null;
// --- validation ---
if (!sellId && !agentId) {
throw new Error("FlowAccountProductError.BOTH_CREATION_FAILED");
}
if (!sellId && agentId) {
await deleteProduct(agentId);
throw new Error("FlowAccountProductError.SELL_PRICE_CREATION_FAILED");
}
if (sellId && !agentId) {
await deleteProduct(sellId);
throw new Error("FlowAccountProductError.AGENT_PRICE_CREATION_FAILED");
}
return {
ok: !!(agentId && sellId),
status: agentId && sellId ? 200 : 500,
ok: true,
status: 200,
data: {
productIdSellPrice: sellId,
productIdAgentPrice: agentId,