simple-kiosk-app/lib/db.ts

97 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-04-20 19:58:18 +09:00
import { Order } from "@/hooks/useOrder";
import { Database, NewOrderState } from './types' // this is the Database interface we defined earlier
import SQLite from 'better-sqlite3'
import { Kysely, SqliteDialect } from 'kysely'
const dialect = new SqliteDialect({
database: new SQLite('order.sqlite3'),
})
const db = new Kysely<Database>({
dialect,
});
export type Payment = "account" | "cash";
export async function requestOrderNumber() : Promise<number> {
const date = new Date().toISOString().split("T")[0];
return await db.transaction().execute(async trx=> {
const order_number = await trx.selectFrom("Order_Number")
.where("id", "==", date)
.selectAll()
.executeTakeFirst();
if (!order_number) {
await trx.insertInto("Order_Number")
.values({
id: date,
number: 1,
})
.execute();
return 1;
}
const num = order_number.number + 1;
await trx.updateTable("Order_Number")
.set("number", num)
.where("id", "==", date)
.execute();
return num;
});
}
export async function saveOrder(order: Order[], payment: Payment) {
const date = new Date().toISOString().split("T")[0];
const num = await requestOrderNumber();
const id = `${date}/${num}`;
await db.insertInto("Order_State")
.values({
id,
orders: JSON.stringify(order),
completed: 0,
payment,
} as NewOrderState)
.execute();
return id;
}
export async function loadOrder() {
const orders = (await db.selectFrom("Order_State")
.selectAll()
.orderBy(["completed","id desc"])
.execute())
.map(order => ({
...order,
orders: JSON.parse(order.orders as unknown as string) as Order[],
}));
return orders;
}
export async function clearOrder() {
await db.deleteFrom("Order_State")
.execute();
}
export async function cancelOrder(order_id: string) {
await db.deleteFrom("Order_State")
.where("id", "==", order_id)
.execute();
}
export async function completeOrder(uid: string, completed: boolean = true) {
await db.updateTable("Order_State")
.set("completed", completed ? 1 : 0)
.where("id", "==", uid)
.execute();
}
export async function loadOrderById(uid: string) {
const order = await db.selectFrom("Order_State")
.where("id", "==", uid)
.selectAll()
.executeTakeFirst();
return order ? {
...order,
orders: JSON.parse(order.orders as unknown as string) as Order[],
} : null;
}