import { new_client } from '../db/db_client'; import { Box } from '../types/box'; import { Piece } from '../types/piece'; import { getPiece } from './pieces.service'; import { Either, eitherLeft, eitherRight, Pair, createPair } from '../utils/utils'; type DBBox = { id_boite: number; titre_boite: string; date_boite: string; }; async function getPiecesFromBox(id_box: number): Promise>> { const client = new_client(); const res = await client.query(`SELECT * FROM contenir WHERE id_boite = $1;`, [ id_box ]); const arr: Array> = new Array(); for (let i = 0; i < res.rows.length; ++i) { const piece: Either = await getPiece(res.rows[i]['id_piece']); if (piece.hasRight) continue; arr.push(createPair(piece.left, res.rows[i]['quantite_contenir'] as number)); } return arr; } async function addPiecesToBox(id_box: number, id_piece: number, qty: number) { const client = new_client(); const res = await client.query(`INSERT INTO contenir (id_boite, id_piece, quantite_contenir) VALUES ($1, $2, $3);`, [ id_box, id_piece, qty ]); } async function removePieceFromBox(id_box: number, id_piece: number) { const client = new_client(); const res = await client.query(`DELETE FROM contenir WHERE id_boite = $1 AND id_piece = $2;`, [ id_box, id_piece ]); } async function db2box(data: DBBox): Promise { const box: Box = { id: data.id_boite, title: data.titre_boite, date: new Date(data.date_boite), pieces: await getPiecesFromBox(data.id_boite) }; return box; } const getBox = async (idOrTitle: number | string): Promise> => { const client = new_client(); let res; if (typeof idOrTitle !== 'number') { res = await client.query("SELECT * FROM boites WHERE titre_boite=$1;", [`${idOrTitle}`]); } else { res = await client.query("SELECT * FROM boites WHERE id_boite=$1;", [idOrTitle]); } if (res.rows.length === 0) { return eitherRight("Does not exist."); } const box = await db2box(res.rows[0]); return eitherLeft(box); } const getAllBoxes = async () => { const client = new_client(); const res = await client.query("SELECT * FROM boites"); return await Promise.all(res.rows.map(async (el) => { return await db2box(el) })); } const getAllBoxesFromDate = async (date: Date) => { const client = new_client(); const YYYY = date.getFullYear(); const MM = date.getMonth() + 1; const DD = date.getDate(); const dateString = `${YYYY}-${MM}-${DD}`; const res = await client.query("SELECT * FROM boites WHERE date_boite > $1", [dateString]); return await Promise.all(res.rows.map(async (el) => { return await db2box(el) })); } const boxService = { addPiecesToBox, getBox, getAllBoxes, getAllBoxesFromDate, removePieceFromBox }; export default boxService;