WorkshopTasker/server/api/orders/[id].get.ts
2023-05-24 09:40:45 +02:00

108 lines
2.6 KiB
TypeScript

/* global defineEventHandler, createError */
import { offer as offerType, order } from "~/utils/types/database";
import { database, data } from "~/server/utils/database";
export async function orderExists(id: string) {
const [[exists]] = await database.query(
"SELECT EXISTS(*) AS `exists` FROM `orders` WHERE `id` = ?",
[id],
) as data<{exists: 0 | 1}>;
return exists.exists === 1;
}
export async function getImportedProducts(id: string) {
const [importedProducts] = await database.query(
["SELECT",
"CONVERT(`id`, CHAR) AS `id`,",
"`name`,",
"`link`,",
"`price`,",
"`price_imported`",
"FROM `imported_products`",
"WHERE `order` = ?",
].join(" "),
[id],
) as data<{
id: string,
name: string | null,
link: string,
price: string,
price_imported: string
}>;
return importedProducts;
}
export async function getWork(id: string) {
const [work] = await database.query(
["SELECT",
"CONVERT(`id`, CHAR) AS `id`,",
"CONVERT(`offer`, CHAR) AS `offer`,",
"`price`,",
"`notes`,",
"`is_fulfilled`",
"FROM `work`",
"WHERE `order` = ?",
].join(" "),
[id],
) as data<{
id: string,
offer: offerType,
price: number,
notes: string | null,
is_fulfilled: 0 | 1,
}>;
const [offer] = await database.query(
["SELECT",
"CONVERT(`offer`.`id`, CHAR) AS `id`,",
"`offer`.`name`,",
"`offer`.`description`,",
"`offer`.`recommended_price`",
"FROM",
"`work`",
"LEFT JOIN `offer` ON `work`.`offer` = `offer`.`id`",
"WHERE `work`.`order` = ?",
].join(" "),
[id],
) as data<offerType>;
// @ts-ignore i.offer is string, but it needs to be an offer object
for (const i of work) i.offer = offer.find(e => e.id === i.offer) as offerType;
return work;
}
export async function getOrder(id: string): Promise<order> {
const [[order]] = await database.query(
["SELECT",
"CONVERT(`id`, CHAR) AS `id`,",
"CONVERT(`client`, CHAR) AS `client`,",
"CONVERT(`user`, CHAR) AS `user`, ",
"`is_draft`,",
"`value`",
"FROM `orderSummaries`",
"WHERE `id` = ?",
].join(" "),
[id],
) as data<{
id: string,
client: string,
user: string,
is_draft: 0 | 1,
value: number,
}>;
if (!order) throw createError({ statusCode: 404 });
const importedProducts = await getImportedProducts(id);
const work = await getWork(id);
return { ...order, imported_products: importedProducts, work };
}
export default defineEventHandler((e) => {
const key = e.context.params?.id;
return getOrder(key as string);
});