Wire the order parser to the WhatsApp bot. A known user forwards an order, ends it with Done, picks a shop, confirms a summary and the order is saved.
40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
import type { Db } from '../db';
|
|
import { canUseShop } from './shopScope';
|
|
import type { User } from './users';
|
|
|
|
export class ShopNotAllowedError extends Error {
|
|
constructor() {
|
|
super('user cannot use this shop');
|
|
this.name = 'ShopNotAllowedError';
|
|
}
|
|
}
|
|
|
|
export interface SaveOrderInput {
|
|
user: User;
|
|
shopId: number;
|
|
drawDate: string;
|
|
rawText: string;
|
|
lines: { ending: string; qty: number }[];
|
|
source?: 'whatsapp_text' | 'whatsapp_photo';
|
|
}
|
|
export function saveOrder(db: Db, input: SaveOrderInput): number {
|
|
const run = db.transaction((): number => {
|
|
if (!canUseShop(db, input.user, input.shopId)) throw new ShopNotAllowedError();
|
|
|
|
const orderId = Number(
|
|
db
|
|
.prepare(
|
|
`INSERT INTO orders (shop_id, draw_date, source, created_by_user_id, raw_text)
|
|
VALUES (?, ?, ?, ?, ?)`,
|
|
)
|
|
.run(input.shopId, input.drawDate, input.source ?? 'whatsapp_text', input.user.id, input.rawText)
|
|
.lastInsertRowid,
|
|
);
|
|
|
|
const insertLine = db.prepare('INSERT INTO order_lines (order_id, ending, qty) VALUES (?, ?, ?)');
|
|
for (const l of input.lines) insertLine.run(orderId, l.ending, l.qty);
|
|
return orderId;
|
|
});
|
|
return run();
|
|
}
|