import { TRPCError } from "@trpc/server"; import type { Insertable, Selectable, Updateable } from "kysely"; import type OrdiniTable from "~/schemas/public/Ordini"; import type { Ordini, OrdiniOrdineId, OrdiniUpdate, } from "~/schemas/public/Ordini"; import type { Users, UsersId } from "~/schemas/public/Users"; import { db } from "~/server/db"; export type ServizioOrdiniTable = Omit; export type ServizioOrdini = Selectable; export type NewServizioOrdini = Insertable; export type ServizioOrdiniUpdate = Updateable; export type RinnovoOrdiniTable = Omit; export type RinnovoOrdini = Selectable; export type NewRinnovoOrdini = Insertable; export type RinnovoOrdiniUpdate = Updateable; export type Ordini_w_Utente = Ordini & Pick; export const getOrdini = async ( userId: UsersId | undefined, ): Promise => { try { let qry = db .selectFrom("ordini") .selectAll("ordini") .innerJoin("users", "users.id", "ordini.userid") .select("users.username"); if (userId) { qry = qry.where("ordini.userid", "=", userId); } return await qry.orderBy("created_at", "desc").execute(); } catch (e) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Error fetching ordini by user ID: ${(e as Error).message}`, }); } }; export const getOrdineById = async (ordineId: OrdiniOrdineId) => { try { return await db .selectFrom("ordini") .selectAll("ordini") .innerJoin("users", "users.id", "ordini.userid") .select("users.username") .where("ordini.ordine_id", "=", ordineId) .orderBy("created_at", "desc") .executeTakeFirstOrThrow( () => new Error(`Ordine not found - ordineId: ${ordineId}`), ); } catch (e) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Error fetching ordini by user ID: ${(e as Error).message}`, }); } }; export const createOrdine = async ( data: NewServizioOrdini | NewRinnovoOrdini, ) => { try { return await db .insertInto("ordini") .values(data) .returningAll() .executeTakeFirstOrThrow(() => new Error("Failed to create ordine")); } catch (e) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Error creating ordine: ${(e as Error).message}`, }); } }; export const removeOrder = async (ordineId: OrdiniOrdineId) => { try { await db.deleteFrom("ordini").where("ordine_id", "=", ordineId).execute(); return true; } catch (e) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Error removing order: ${(e as Error).message}`, }); } }; export const updateOrder = async ({ ordineId, data, }: { ordineId: OrdiniOrdineId; data: OrdiniUpdate; }) => { try { const updated = await db .updateTable("ordini") .set(data) .where("ordine_id", "=", ordineId) .returningAll() .executeTakeFirstOrThrow( () => new Error(`Failed to update ordine - ordineId: ${ordineId}`), ); return updated; } catch (e) { throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: `Error updating order: ${(e as Error).message}`, }); } };