4 Commits

Author SHA1 Message Date
bc039a361d Magic bullshit 2025-01-09 00:35:47 +01:00
fd9aa547e2 Migrace "interface" na "type" 2025-01-08 20:53:48 +01:00
e611d36995 Otypování requestů na API 2025-01-08 17:58:49 +01:00
414664b2d7 Úprava API pro podporu TypeScript 2025-01-08 17:43:47 +01:00
14 changed files with 231 additions and 151 deletions

View File

@@ -194,9 +194,9 @@ function App() {
}, [auth?.login, easterEgg?.duration, easterEgg?.url, eggImage]); }, [auth?.login, easterEgg?.duration, easterEgg?.url, eggImage]);
const doAddChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => { const doAddChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
const index = Object.keys(Locations).indexOf(event.target.value as unknown as Locations); const locationKey = event.target.value as Locations;
if (auth?.login) { if (auth?.login) {
await errorHandler(() => addChoice(index, undefined, dayIndex)); await errorHandler(() => addChoice(locationKey, undefined, dayIndex));
if (foodChoiceRef.current?.value) { if (foodChoiceRef.current?.value) {
foodChoiceRef.current.value = ""; foodChoiceRef.current.value = "";
} }
@@ -211,17 +211,16 @@ function App() {
const doAddFoodChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => { const doAddFoodChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
if (event.target.value && foodChoiceList?.length && choiceRef.current?.value) { if (event.target.value && foodChoiceList?.length && choiceRef.current?.value) {
const restaurantKey = choiceRef.current.value; const locationKey = choiceRef.current.value as Locations;
if (auth?.login) { if (auth?.login) {
const locationIndex = Object.keys(Locations).indexOf(restaurantKey as unknown as Locations); await errorHandler(() => addChoice(locationKey, Number(event.target.value), dayIndex));
await errorHandler(() => addChoice(locationIndex, Number(event.target.value), dayIndex));
} }
} }
} }
const doRemoveChoices = async (locationKey: string) => { const doRemoveChoices = async (locationKey: Locations) => {
if (auth?.login) { if (auth?.login) {
await errorHandler(() => removeChoices(Number(locationKey), dayIndex)); await errorHandler(() => removeChoices(locationKey, dayIndex));
// Vyresetujeme výběr, aby bylo jasné pro který případně vybíráme jídlo // Vyresetujeme výběr, aby bylo jasné pro který případně vybíráme jídlo
if (choiceRef?.current?.value) { if (choiceRef?.current?.value) {
choiceRef.current.value = ""; choiceRef.current.value = "";
@@ -232,9 +231,9 @@ function App() {
} }
} }
const doRemoveFoodChoice = async (locationKey: string, foodIndex: number) => { const doRemoveFoodChoice = async (locationKey: Locations, foodIndex: number) => {
if (auth?.login) { if (auth?.login) {
await errorHandler(() => removeChoice(Number(locationKey), foodIndex, dayIndex)); await errorHandler(() => removeChoice(locationKey, foodIndex, dayIndex));
if (choiceRef?.current?.value) { if (choiceRef?.current?.value) {
choiceRef.current.value = ""; choiceRef.current.value = "";
} }
@@ -459,11 +458,21 @@ function App() {
{Object.keys(data.choices).length > 0 ? {Object.keys(data.choices).length > 0 ?
<Table bordered className='mt-5'> <Table bordered className='mt-5'>
<tbody> <tbody>
{Object.keys(data.choices).map((locationKey: string) => { {Object.keys(data.choices).map(key => {
const locationName = Object.values(Locations)[Number(locationKey)]; const locationKey = key as keyof typeof Locations;
const locationLoginList = Object.entries(data.choices[Number(locationKey)]); console.log("Mapuji location key", locationKey);
const locationName = Locations[locationKey];
console.log("Location name", locationName);
console.log("Obsah data.choices", data.choices);
const loginObject = data.choices[locationKey];
// TODO toto je hovnokód, mělo by to být napsané tak, aby si na to TypeScript nemohl stěžovat
if (!loginObject) {
return;
}
const locationLoginList = Object.entries(loginObject);
console.log("Entries", locationLoginList);
return ( return (
<tr key={locationKey}> <tr key={key}>
<td>{locationName}</td> <td>{locationName}</td>
<td className='p-0'> <td className='p-0'>
<Table> <Table>
@@ -485,20 +494,20 @@ function App() {
setNoteModalOpen(true); setNoteModalOpen(true);
}} title='Upravit poznámku' className='action-icon' icon={faNoteSticky} />} }} title='Upravit poznámku' className='action-icon' icon={faNoteSticky} />}
{login === auth.login && canChangeChoice && <FontAwesomeIcon onClick={() => { {login === auth.login && canChangeChoice && <FontAwesomeIcon onClick={() => {
doRemoveChoices(locationKey); doRemoveChoices(key as Locations); // TODO dořešit
}} title={`Odstranit volbu ${locationName}, včetně případných zvolených jídel`} className='action-icon' icon={faTrashCan} />} }} title={`Odstranit volbu ${locationName}, včetně případných zvolených jídel`} className='action-icon' icon={faTrashCan} />}
</td> </td>
{userChoices?.length && food ? <td> {userChoices?.length && food ? <td>
<ul> <ul>
{userChoices?.map(foodIndex => { {userChoices?.map(foodIndex => {
const locationsKey = Object.keys(Locations)[Number(locationKey)] const locationsKey = Object.keys(Locations)[Number(key)]
const restaurantKey = Object.keys(Restaurants).indexOf(locationsKey); const restaurantKey = Object.keys(Restaurants).indexOf(locationsKey);
const restaurant = Object.values(Restaurants)[restaurantKey]; const restaurant = Object.values(Restaurants)[restaurantKey];
const foodName = food[restaurant]?.food[foodIndex].name; const foodName = food[restaurant]?.food[foodIndex].name;
return <li key={foodIndex}> return <li key={foodIndex}>
{foodName} {foodName}
{login === auth.login && canChangeChoice && <FontAwesomeIcon onClick={() => { {login === auth.login && canChangeChoice && <FontAwesomeIcon onClick={() => {
doRemoveFoodChoice(locationKey, foodIndex); doRemoveFoodChoice(key as Locations, foodIndex); // TODO dořešit
}} title={`Odstranit ${foodName}`} className='action-icon' icon={faTrashCan} />} }} title={`Odstranit ${foodName}`} className='action-icon' icon={faTrashCan} />}
</li> </li>
})} })}

View File

@@ -63,7 +63,7 @@ async function blobRequest(
export const api = { export const api = {
get: <TResponse>(url: string) => request<TResponse>(url), get: <TResponse>(url: string) => request<TResponse>(url),
blobGet: (url: string) => blobRequest(url), blobGet: (url: string) => blobRequest(url),
post: <TBody extends BodyInit, TResponse>(url: string, body: TBody) => request<TResponse>(url, { method: 'POST', body, headers: { 'Content-Type': 'application/json' } }), post: <TBody, TResponse>(url: string, body?: TBody) => request<TResponse>(url, { method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }),
} }
export const getQrUrl = (login: string) => { export const getQrUrl = (login: string) => {
@@ -79,5 +79,5 @@ export const getData = async (dayIndex?: number) => {
} }
export const login = async (login?: string) => { export const login = async (login?: string) => {
return await api.post<any, any>('/api/login', JSON.stringify({ login })); return await api.post<any, any>('/api/login', { login });
} }

View File

@@ -4,7 +4,7 @@ import { api } from "./Api";
const EASTER_EGGS_API_PREFIX = '/api/easterEggs'; const EASTER_EGGS_API_PREFIX = '/api/easterEggs';
export const getEasterEgg = async (): Promise<EasterEgg | undefined> => { export const getEasterEgg = async (): Promise<EasterEgg | undefined> => {
return await api.get(`${EASTER_EGGS_API_PREFIX}`); return await api.get<EasterEgg>(`${EASTER_EGGS_API_PREFIX}`);
} }
export const getImage = async (url: string) => { export const getImage = async (url: string) => {

View File

@@ -1,27 +1,28 @@
import { AddChoiceRequest, ChangeDepartureTimeRequest, Locations, RemoveChoiceRequest, RemoveChoicesRequest, UpdateNoteRequest } from "../types";
import { api } from "./Api"; import { api } from "./Api";
const FOOD_API_PREFIX = '/api/food'; const FOOD_API_PREFIX = '/api/food';
export const addChoice = async (locationIndex: number, foodIndex?: number, dayIndex?: number) => { export const addChoice = async (locationKey: keyof typeof Locations, foodIndex?: number, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/addChoice`, JSON.stringify({ locationIndex, foodIndex, dayIndex })); return await api.post<AddChoiceRequest, void>(`${FOOD_API_PREFIX}/addChoice`, { locationKey, foodIndex, dayIndex });
} }
export const removeChoices = async (locationIndex: number, dayIndex?: number) => { export const removeChoices = async (locationKey: keyof typeof Locations, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/removeChoices`, JSON.stringify({ locationIndex, dayIndex })); return await api.post<RemoveChoicesRequest, void>(`${FOOD_API_PREFIX}/removeChoices`, { locationKey, dayIndex });
} }
export const removeChoice = async (locationIndex: number, foodIndex: number, dayIndex?: number) => { export const removeChoice = async (locationKey: keyof typeof Locations, foodIndex: number, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/removeChoice`, JSON.stringify({ locationIndex, foodIndex, dayIndex })); return await api.post<RemoveChoiceRequest, void>(`${FOOD_API_PREFIX}/removeChoice`, { locationKey, foodIndex, dayIndex });
} }
export const updateNote = async (note?: string, dayIndex?: number) => { export const updateNote = async (note?: string, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/updateNote`, JSON.stringify({ note, dayIndex })); return await api.post<UpdateNoteRequest, void>(`${FOOD_API_PREFIX}/updateNote`, { note, dayIndex });
} }
export const changeDepartureTime = async (time: string, dayIndex?: number) => { export const changeDepartureTime = async (time: string, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/changeDepartureTime`, JSON.stringify({ time, dayIndex })); return await api.post<ChangeDepartureTimeRequest, void>(`${FOOD_API_PREFIX}/changeDepartureTime`, { time, dayIndex });
} }
export const jdemeObed = async () => { export const jdemeObed = async () => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/jdemeObed`, JSON.stringify({})); return await api.post<undefined, void>(`${FOOD_API_PREFIX}/jdemeObed`);
} }

View File

@@ -1,44 +1,44 @@
import { PizzaOrder } from "../types"; import { AddPizzaRequest, FinishDeliveryRequest, PizzaOrder, RemovePizzaRequest, UpdatePizzaDayNoteRequest, UpdatePizzaFeeRequest } from "../types";
import { api } from "./Api"; import { api } from "./Api";
const PIZZADAY_API_PREFIX = '/api/pizzaDay'; const PIZZADAY_API_PREFIX = '/api/pizzaDay';
export const createPizzaDay = async () => { export const createPizzaDay = async () => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/create`, undefined); return await api.post<undefined, void>(`${PIZZADAY_API_PREFIX}/create`);
} }
export const deletePizzaDay = async () => { export const deletePizzaDay = async () => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/delete`, undefined); return await api.post<undefined, void>(`${PIZZADAY_API_PREFIX}/delete`);
} }
export const lockPizzaDay = async () => { export const lockPizzaDay = async () => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/lock`, undefined); return await api.post<undefined, void>(`${PIZZADAY_API_PREFIX}/lock`);
} }
export const unlockPizzaDay = async () => { export const unlockPizzaDay = async () => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/unlock`, undefined); return await api.post<undefined, void>(`${PIZZADAY_API_PREFIX}/unlock`);
} }
export const finishOrder = async () => { export const finishOrder = async () => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/finishOrder`, undefined); return await api.post<undefined, void>(`${PIZZADAY_API_PREFIX}/finishOrder`);
} }
export const finishDelivery = async (bankAccount?: string, bankAccountHolder?: string) => { export const finishDelivery = async (bankAccount?: string, bankAccountHolder?: string) => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/finishDelivery`, JSON.stringify({ bankAccount, bankAccountHolder })); return await api.post<FinishDeliveryRequest, void>(`${PIZZADAY_API_PREFIX}/finishDelivery`, { bankAccount, bankAccountHolder });
} }
export const addPizza = async (pizzaIndex: number, pizzaSizeIndex: number) => { export const addPizza = async (pizzaIndex: number, pizzaSizeIndex: number) => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/add`, JSON.stringify({ pizzaIndex, pizzaSizeIndex })); return await api.post<AddPizzaRequest, void>(`${PIZZADAY_API_PREFIX}/add`, { pizzaIndex, pizzaSizeIndex });
} }
export const removePizza = async (pizzaOrder: PizzaOrder) => { export const removePizza = async (pizzaOrder: PizzaOrder) => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/remove`, JSON.stringify({ pizzaOrder })); return await api.post<RemovePizzaRequest, void>(`${PIZZADAY_API_PREFIX}/remove`, { pizzaOrder });
} }
export const updatePizzaDayNote = async (note?: string) => { export const updatePizzaDayNote = async (note?: string) => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/updatePizzaDayNote`, JSON.stringify({ note })); return await api.post<UpdatePizzaDayNoteRequest, void>(`${PIZZADAY_API_PREFIX}/updatePizzaDayNote`, { note });
} }
export const updatePizzaFee = async (login: string, text?: string, price?: number) => { export const updatePizzaFee = async (login: string, text?: string, price?: number) => {
return await api.post<any, any>(`${PIZZADAY_API_PREFIX}/updatePizzaFee`, JSON.stringify({ login, text, price })); return await api.post<UpdatePizzaFeeRequest, void>(`${PIZZADAY_API_PREFIX}/updatePizzaFee`, { login, text, price });
} }

View File

@@ -1,12 +1,12 @@
import { FeatureRequest } from "../types"; import { FeatureRequest, UpdateFeatureVoteRequest } from "../types";
import { api } from "./Api"; import { api } from "./Api";
const VOTING_API_PREFIX = '/api/voting'; const VOTING_API_PREFIX = '/api/voting';
export const getFeatureVotes = async () => { export const getFeatureVotes = async () => {
return await api.get<any>(`${VOTING_API_PREFIX}/getVotes`); return await api.get<FeatureRequest[]>(`${VOTING_API_PREFIX}/getVotes`);
} }
export const updateFeatureVote = async (option: FeatureRequest, active: boolean) => { export const updateFeatureVote = async (option: FeatureRequest, active: boolean) => {
return await api.post<any, any>(`${VOTING_API_PREFIX}/updateVote`, JSON.stringify({ option, active })); return await api.post<UpdateFeatureVoteRequest, void>(`${VOTING_API_PREFIX}/updateVote`, { option, active });
} }

View File

@@ -1,10 +1,10 @@
import express from "express"; import express, { Request } from "express";
import { getLogin, getTrusted } from "../auth"; import { getLogin, getTrusted } from "../auth";
import { addChoice, addVolatileData, getDateForWeekIndex, getToday, removeChoice, removeChoices, updateDepartureTime, updateNote } from "../service"; import { addChoice, addVolatileData, getDateForWeekIndex, getToday, removeChoice, removeChoices, updateDepartureTime, updateNote } from "../service";
import { getDayOfWeekIndex, parseToken } from "../utils"; import { getDayOfWeekIndex, parseToken } from "../utils";
import { getWebsocket } from "../websocket"; import { getWebsocket } from "../websocket";
import { callNotifikace } from "../notifikace"; import { callNotifikace } from "../notifikace";
import { UdalostEnum } from "../../../types"; import { AddChoiceRequest, ChangeDepartureTimeRequest, IDayIndex, RemoveChoiceRequest, RemoveChoicesRequest, UdalostEnum, UpdateNoteRequest } from "../../../types";
/** /**
* Ověří a vrátí index dne v týdnu z požadavku, za předpokladu, že byl předán, a je zároveň * Ověří a vrátí index dne v týdnu z požadavku, za předpokladu, že byl předán, a je zároveň
@@ -13,12 +13,12 @@ import { UdalostEnum } from "../../../types";
* @param req request * @param req request
* @returns index dne v týdnu * @returns index dne v týdnu
*/ */
const parseValidateFutureDayIndex = (req: any) => { const parseValidateFutureDayIndex = (req: Request<{}, any, IDayIndex>) => {
if (req.body.dayIndex == null) { if (req.body.dayIndex == null) {
throw Error(`Nebyl předán index dne v týdnu.`); throw Error(`Nebyl předán index dne v týdnu.`);
} }
const todayDayIndex = getDayOfWeekIndex(getToday()); const todayDayIndex = getDayOfWeekIndex(getToday());
const dayIndex = parseInt(req.body.dayIndex); const dayIndex = req.body.dayIndex;
if (isNaN(dayIndex)) { if (isNaN(dayIndex)) {
throw Error(`Neplatný index dne v týdnu: ${req.body.dayIndex}`); throw Error(`Neplatný index dne v týdnu: ${req.body.dayIndex}`);
} }
@@ -30,30 +30,7 @@ const parseValidateFutureDayIndex = (req: any) => {
const router = express.Router(); const router = express.Router();
router.post("/addChoice", async (req, res, next) => { router.post("/addChoice", async (req: Request<{}, any, AddChoiceRequest>, res, next) => {
const login = getLogin(parseToken(req));
const trusted = getTrusted(parseToken(req));
if (req.body.locationIndex > -1) {
let date = undefined;
if (req.body.dayIndex != null) {
let dayIndex;
try {
dayIndex = parseValidateFutureDayIndex(req);
} catch (e: any) {
return res.status(400).json({ error: e.message });
}
date = getDateForWeekIndex(dayIndex);
}
try {
const data = await addChoice(login, trusted, req.body.locationIndex, req.body.foodIndex, date);
getWebsocket().emit("message", await addVolatileData(data));
return res.status(200).json(data);
} catch (e: any) { next(e) }
}
return res.status(400); // TODO přidat popis chyby
});
router.post("/removeChoices", async (req, res, next) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const trusted = getTrusted(parseToken(req)); const trusted = getTrusted(parseToken(req));
let date = undefined; let date = undefined;
@@ -67,13 +44,13 @@ router.post("/removeChoices", async (req, res, next) => {
date = getDateForWeekIndex(dayIndex); date = getDateForWeekIndex(dayIndex);
} }
try { try {
const data = await removeChoices(login, trusted, req.body.locationIndex, date); const data = await addChoice(login, trusted, req.body.locationKey, req.body.foodIndex, date);
getWebsocket().emit("message", await addVolatileData(data)); getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json(data); return res.status(200).json(data);
} catch (e: any) { next(e) } } catch (e: any) { next(e) }
}); });
router.post("/removeChoice", async (req, res, next) => { router.post("/removeChoices", async (req: Request<{}, any, RemoveChoicesRequest>, res, next) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const trusted = getTrusted(parseToken(req)); const trusted = getTrusted(parseToken(req));
let date = undefined; let date = undefined;
@@ -87,13 +64,33 @@ router.post("/removeChoice", async (req, res, next) => {
date = getDateForWeekIndex(dayIndex); date = getDateForWeekIndex(dayIndex);
} }
try { try {
const data = await removeChoice(login, trusted, req.body.locationIndex, req.body.foodIndex, date); const data = await removeChoices(login, trusted, req.body.locationKey, date);
getWebsocket().emit("message", await addVolatileData(data)); getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json(data); res.status(200).json(data);
} catch (e: any) { next(e) } } catch (e: any) { next(e) }
}); });
router.post("/updateNote", async (req, res, next) => { router.post("/removeChoice", async (req: Request<{}, any, RemoveChoiceRequest>, res, next) => {
const login = getLogin(parseToken(req));
const trusted = getTrusted(parseToken(req));
let date = undefined;
if (req.body.dayIndex != null) {
let dayIndex;
try {
dayIndex = parseValidateFutureDayIndex(req);
} catch (e: any) {
return res.status(400).json({ error: e.message });
}
date = getDateForWeekIndex(dayIndex);
}
try {
const data = await removeChoice(login, trusted, req.body.locationKey, req.body.foodIndex, date);
getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json(data);
} catch (e: any) { next(e) }
});
router.post("/updateNote", async (req: Request<{}, any, UpdateNoteRequest>, res, next) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const trusted = getTrusted(parseToken(req)); const trusted = getTrusted(parseToken(req));
const note = req.body.note; const note = req.body.note;
@@ -117,7 +114,7 @@ router.post("/updateNote", async (req, res, next) => {
} catch (e: any) { next(e) } } catch (e: any) { next(e) }
}); });
router.post("/changeDepartureTime", async (req, res, next) => { router.post("/changeDepartureTime", async (req: Request<{}, any, ChangeDepartureTimeRequest>, res, next) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
let date = undefined; let date = undefined;
if (req.body.dayIndex != null) { if (req.body.dayIndex != null) {

View File

@@ -1,14 +1,15 @@
import express from "express"; import express, { Request } from "express";
import { getLogin } from "../auth"; import { getLogin } from "../auth";
import { createPizzaDay, deletePizzaDay, getPizzaList, addPizzaOrder, removePizzaOrder, lockPizzaDay, unlockPizzaDay, finishPizzaOrder, finishPizzaDelivery, updatePizzaDayNote, updatePizzaFee } from "../pizza"; import { createPizzaDay, deletePizzaDay, getPizzaList, addPizzaOrder, removePizzaOrder, lockPizzaDay, unlockPizzaDay, finishPizzaOrder, finishPizzaDelivery, updatePizzaDayNote, updatePizzaFee } from "../pizza";
import { parseToken } from "../utils"; import { parseToken } from "../utils";
import { getWebsocket } from "../websocket"; import { getWebsocket } from "../websocket";
import { addVolatileData } from "../service"; import { addVolatileData } from "../service";
import { AddPizzaRequest, FinishDeliveryRequest, RemovePizzaRequest, UpdatePizzaDayNoteRequest, UpdatePizzaFeeRequest } from "../../../types";
const router = express.Router(); const router = express.Router();
/** Založí pizza day pro aktuální den, za předpokladu že dosud neexistuje. */ /** Založí pizza day pro aktuální den, za předpokladu že dosud neexistuje. */
router.post("/create", async (req, res) => { router.post("/create", async (req: Request<{}, any, undefined>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const data = await createPizzaDay(login); const data = await createPizzaDay(login);
res.status(200).json(data); res.status(200).json(data);
@@ -16,13 +17,13 @@ router.post("/create", async (req, res) => {
}); });
/** Smaže pizza day pro aktuální den, za předpokladu že existuje. */ /** Smaže pizza day pro aktuální den, za předpokladu že existuje. */
router.post("/delete", async (req, res) => { router.post("/delete", async (req: Request<{}, any, undefined>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const data = await deletePizzaDay(login); const data = await deletePizzaDay(login);
getWebsocket().emit("message", await addVolatileData(data)); getWebsocket().emit("message", await addVolatileData(data));
}); });
router.post("/add", async (req, res) => { router.post("/add", async (req: Request<{}, any, AddPizzaRequest>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
if (isNaN(req.body?.pizzaIndex)) { if (isNaN(req.body?.pizzaIndex)) {
throw Error("Nebyl předán index pizzy"); throw Error("Nebyl předán index pizzy");
@@ -47,7 +48,7 @@ router.post("/add", async (req, res) => {
res.status(200).json({}); res.status(200).json({});
}); });
router.post("/remove", async (req, res) => { router.post("/remove", async (req: Request<{}, any, RemovePizzaRequest>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
if (!req.body?.pizzaOrder) { if (!req.body?.pizzaOrder) {
throw Error("Nebyla předána objednávka"); throw Error("Nebyla předána objednávka");
@@ -57,35 +58,35 @@ router.post("/remove", async (req, res) => {
res.status(200).json({}); res.status(200).json({});
}); });
router.post("/lock", async (req, res) => { router.post("/lock", async (req: Request<{}, any, undefined>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const data = await lockPizzaDay(login); const data = await lockPizzaDay(login);
getWebsocket().emit("message", await addVolatileData(data)); getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json({}); res.status(200).json({});
}); });
router.post("/unlock", async (req, res) => { router.post("/unlock", async (req: Request<{}, any, undefined>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const data = await unlockPizzaDay(login); const data = await unlockPizzaDay(login);
getWebsocket().emit("message", await addVolatileData(data)); getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json({}); res.status(200).json({});
}); });
router.post("/finishOrder", async (req, res) => { router.post("/finishOrder", async (req: Request<{}, any, undefined>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const data = await finishPizzaOrder(login); const data = await finishPizzaOrder(login);
getWebsocket().emit("message", await addVolatileData(data)); getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json({}); res.status(200).json({});
}); });
router.post("/finishDelivery", async (req, res) => { router.post("/finishDelivery", async (req: Request<{}, any, FinishDeliveryRequest>, res) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const data = await finishPizzaDelivery(login, req.body.bankAccount, req.body.bankAccountHolder); const data = await finishPizzaDelivery(login, req.body.bankAccount, req.body.bankAccountHolder);
getWebsocket().emit("message", await addVolatileData(data)); getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json({}); res.status(200).json({});
}); });
router.post("/updatePizzaDayNote", async (req, res, next) => { router.post("/updatePizzaDayNote", async (req: Request<{}, any, UpdatePizzaDayNoteRequest>, res, next) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
try { try {
if (req.body.note && req.body.note.length > 70) { if (req.body.note && req.body.note.length > 70) {
@@ -97,7 +98,7 @@ router.post("/updatePizzaDayNote", async (req, res, next) => {
} catch (e: any) { next(e) } } catch (e: any) { next(e) }
}); });
router.post("/updatePizzaFee", async (req, res, next) => { router.post("/updatePizzaFee", async (req: Request<{}, any, UpdatePizzaFeeRequest>, res, next) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
if (!req.body.login) { if (!req.body.login) {
return res.status(400).json({ error: "Nebyl předán login cílového uživatele" }); return res.status(400).json({ error: "Nebyl předán login cílového uživatele" });

View File

@@ -1,17 +1,18 @@
import express from "express"; import express, { Request, Response } from "express";
import { getLogin } from "../auth"; import { getLogin } from "../auth";
import { parseToken } from "../utils"; import { parseToken } from "../utils";
import { getUserVotes, updateFeatureVote } from "../voting"; import { getUserVotes, updateFeatureVote } from "../voting";
import { FeatureRequest, UpdateFeatureVoteRequest } from "../../../types";
const router = express.Router(); const router = express.Router();
router.get("/getVotes", async (req, res) => { router.get("/getVotes", async (req: Request<{}, any, undefined>, res: Response<FeatureRequest[]>) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
const data = await getUserVotes(login); const data = await getUserVotes(login);
res.status(200).json(data); res.status(200).json(data);
}); });
router.post("/updateVote", async (req, res, next) => { router.post("/updateVote", async (req: Request<{}, any, UpdateFeatureVoteRequest>, res, next) => {
const login = getLogin(parseToken(req)); const login = getLogin(parseToken(req));
if (req.body?.option == null || req.body?.active == null) { if (req.body?.option == null || req.body?.active == null) {
res.status(400).json({ error: "Chybné parametry volání" }); res.status(400).json({ error: "Chybné parametry volání" });

View File

@@ -192,19 +192,19 @@ export async function initIfNeeded(date?: Date) {
* *
* @param login login uživatele * @param login login uživatele
* @param trusted příznak, zda se jedná o ověřeného uživatele * @param trusted příznak, zda se jedná o ověřeného uživatele
* @param location vybrané "umístění" * @param locationKey vybrané "umístění"
* @param date datum, ke kterému se volba vztahuje * @param date datum, ke kterému se volba vztahuje
* @returns * @returns
*/ */
export async function removeChoices(login: string, trusted: boolean, location: Locations, date?: Date) { export async function removeChoices(login: string, trusted: boolean, locationKey: keyof typeof Locations, date?: Date) {
const selectedDay = formatDate(date ?? getToday()); const selectedDay = formatDate(date ?? getToday());
let data: DayData = await storage.getData(selectedDay); let data: DayData = await storage.getData(selectedDay);
validateTrusted(data, login, trusted); validateTrusted(data, login, trusted);
if (location in data.choices) { if (locationKey in data.choices) {
if (login in data.choices[location]) { if (data.choices[locationKey] && login in data.choices[locationKey]) {
delete data.choices[location][login] delete data.choices[locationKey][login]
if (Object.keys(data.choices[location]).length === 0) { if (Object.keys(data.choices[locationKey]).length === 0) {
delete data.choices[location] delete data.choices[locationKey]
} }
await storage.setData(selectedDay, data); await storage.setData(selectedDay, data);
} }
@@ -218,20 +218,20 @@ export async function removeChoices(login: string, trusted: boolean, location: L
* *
* @param login login uživatele * @param login login uživatele
* @param trusted příznak, zda se jedná o ověřeného uživatele * @param trusted příznak, zda se jedná o ověřeného uživatele
* @param location vybrané "umístění" * @param locationKey vybrané "umístění"
* @param foodIndex index jídla v jídelním lístku daného umístění, pokud existuje * @param foodIndex index jídla v jídelním lístku daného umístění, pokud existuje
* @param date datum, ke kterému se volba vztahuje * @param date datum, ke kterému se volba vztahuje
* @returns * @returns
*/ */
export async function removeChoice(login: string, trusted: boolean, location: Locations, foodIndex: number, date?: Date) { export async function removeChoice(login: string, trusted: boolean, locationKey: keyof typeof Locations, foodIndex: number, date?: Date) {
const selectedDay = formatDate(date ?? getToday()); const selectedDay = formatDate(date ?? getToday());
let data: DayData = await storage.getData(selectedDay); let data: DayData = await storage.getData(selectedDay);
validateTrusted(data, login, trusted); validateTrusted(data, login, trusted);
if (location in data.choices) { if (locationKey in data.choices) {
if (login in data.choices[location]) { if (data.choices[locationKey] && login in data.choices[locationKey]) {
const index = data.choices[location][login].options.indexOf(foodIndex); const index = data.choices[locationKey][login].options.indexOf(foodIndex);
if (index > -1) { if (index > -1) {
data.choices[location][login].options.splice(index, 1) data.choices[locationKey][login].options.splice(index, 1)
await storage.setData(selectedDay, data); await storage.setData(selectedDay, data);
} }
} }
@@ -247,10 +247,11 @@ export async function removeChoice(login: string, trusted: boolean, location: Lo
async function removeChoiceIfPresent(login: string, date: string) { async function removeChoiceIfPresent(login: string, date: string) {
let data: DayData = await storage.getData(date); let data: DayData = await storage.getData(date);
for (const key of Object.keys(data.choices)) { for (const key of Object.keys(data.choices)) {
if (login in data.choices[key]) { const locationKey = key as keyof typeof Locations;
delete data.choices[key][login]; if (data.choices[locationKey] && login in data.choices[locationKey]) {
if (Object.keys(data.choices[key]).length === 0) { delete data.choices[locationKey][login];
delete data.choices[key]; if (Object.keys(data.choices[locationKey]).length === 0) {
delete data.choices[locationKey];
} }
await storage.setData(date, data); await storage.setData(date, data);
} }
@@ -285,13 +286,13 @@ function validateTrusted(data: ClientData, login: string, trusted: boolean) {
* *
* @param login login uživatele * @param login login uživatele
* @param trusted příznak, zda se jedná o ověřeného uživatele * @param trusted příznak, zda se jedná o ověřeného uživatele
* @param location vybrané "umístění" * @param locationKey vybrané "umístění"
* @param foodIndex volitelný index jídla v daném umístění * @param foodIndex volitelný index jídla v daném umístění
* @param trusted příznak, zda se jedná o ověřeného uživatele * @param trusted příznak, zda se jedná o ověřeného uživatele
* @param date datum, ke kterému se volba vztahuje * @param date datum, ke kterému se volba vztahuje
* @returns aktuální data * @returns aktuální data
*/ */
export async function addChoice(login: string, trusted: boolean, location: Locations, foodIndex?: number, date?: Date) { export async function addChoice(login: string, trusted: boolean, locationKey: keyof typeof Locations, foodIndex?: number, date?: Date) {
const usedDate = date ?? getToday(); const usedDate = date ?? getToday();
await initIfNeeded(usedDate); await initIfNeeded(usedDate);
const selectedDate = formatDate(usedDate); const selectedDate = formatDate(usedDate);
@@ -301,18 +302,29 @@ export async function addChoice(login: string, trusted: boolean, location: Locat
if (foodIndex == null) { if (foodIndex == null) {
data = await removeChoiceIfPresent(login, selectedDate); data = await removeChoiceIfPresent(login, selectedDate);
} }
if (!(location in data.choices)) { if (!data.choices) {
data.choices[location] = {}; console.log("Klíč", Locations[locationKey]); // TODO smazat
} data.choices = {
if (!(login in data.choices[location])) { [Locations[locationKey]]: {}
data.choices[location][login] = { }
trusted,
options: []
};
}
if (foodIndex != null && !data.choices[location][login].options.includes(foodIndex)) {
data.choices[location][login].options.push(foodIndex);
} }
console.log("Máme choices", data.choices);
console.log("Hodnota locationKey", locationKey);
// if (!(data.choices[locationKey])) {
// data?.choices[locationKey] = {}
// }
// if (!(login in data.choices[locationKey])) {
// if (!data.choices[locationKey]) {
// data.choices[locationKey] = {}
// }
// data.choices[locationKey][login] = {
// trusted,
// options: []
// };
// }
// if (foodIndex != null && !data.choices[locationKey][login].options.includes(foodIndex)) {
// data.choices[locationKey][login].options.push(foodIndex);
// }
await storage.setData(selectedDate, data); await storage.setData(selectedDate, data);
return data; return data;
} }

View File

@@ -1,4 +1,4 @@
import { Choices } from "../../types"; import { Choices, Locations } from "../../types";
/** Vrátí datum v ISO formátu. */ /** Vrátí datum v ISO formátu. */
export function formatDate(date: Date) { export function formatDate(date: Date) {
@@ -110,20 +110,22 @@ export const checkBodyParams = (req: any, paramNames: string[]) => {
// TODO umístit do samostatného souboru // TODO umístit do samostatného souboru
export class InsufficientPermissions extends Error { } export class InsufficientPermissions extends Error { }
export const getUsersByLocation = (data: Choices, login: string): string[] => { export const getUsersByLocation = (choices: Choices, login: string): string[] => {
const result: string[] = []; const result: string[] = [];
for (const location in data) { for (const location of Object.entries(choices)) {
if (data.hasOwnProperty(location)) { const locationKey = location[0];
if (data[location][login]) { const locationValue = location[1];
for (const username in data[location]) { console.log("locationKey", locationKey);
if (data[location].hasOwnProperty(username)) { console.log("locationValue", locationValue);
result.push(username); // if (locationValues[login]) {
} // for (const username in choices[locationKey]) {
} // if (choices[locationKey].hasOwnProperty(username)) {
break; // result.push(username);
} // }
} // }
// break;
// }
} }
return result; return result;

56
types/RequestTypes.ts Normal file
View File

@@ -0,0 +1,56 @@
import { FeatureRequest, Locations, PizzaOrder } from "./Types";
export type ILocationKey = {
locationKey: keyof typeof Locations,
}
export type IDayIndex = {
dayIndex?: number,
}
export type AddChoiceRequest = IDayIndex & ILocationKey & {
foodIndex?: number,
}
export type RemoveChoicesRequest = IDayIndex & ILocationKey;
export type RemoveChoiceRequest = IDayIndex & ILocationKey & {
foodIndex: number,
}
export type UpdateNoteRequest = IDayIndex & {
note?: string,
}
export type ChangeDepartureTimeRequest = IDayIndex & {
time: string,
}
export type FinishDeliveryRequest = {
bankAccount?: string,
bankAccountHolder?: string,
}
export type AddPizzaRequest = {
pizzaIndex: number,
pizzaSizeIndex: number,
}
export type RemovePizzaRequest = {
pizzaOrder: PizzaOrder,
}
export type UpdatePizzaDayNoteRequest = {
note?: string,
}
export type UpdatePizzaFeeRequest = {
login: string,
text?: string,
price?: number,
}
export type UpdateFeatureVoteRequest = {
option: FeatureRequest,
active: boolean,
}

View File

@@ -5,21 +5,21 @@ export enum Restaurants {
TECHTOWER = 'techTower', TECHTOWER = 'techTower',
} }
export interface FoodChoices { export type FoodChoices = {
trusted: boolean, trusted: boolean,
options: number[], options: number[],
departureTime?: string, departureTime?: string,
note?: string, note?: string,
} }
export interface Choices { export type Choices = {
[location: string]: { [location in keyof typeof Locations]?: {
[login: string]: FoodChoices [login: string]: FoodChoices
}, }
} }
/** Velikost konkrétní pizzy */ /** Velikost konkrétní pizzy */
export interface PizzaSize { export type PizzaSize = {
varId: number, // unikátní ID varianty pizzy varId: number, // unikátní ID varianty pizzy
size: string, // velikost pizzy, např. "30cm" size: string, // velikost pizzy, např. "30cm"
pizzaPrice: number, // cena samotné pizzy pizzaPrice: number, // cena samotné pizzy
@@ -28,14 +28,14 @@ export interface PizzaSize {
} }
/** Jedna konkrétní pizza */ /** Jedna konkrétní pizza */
export interface Pizza { export type Pizza = {
name: string, // název pizzy name: string, // název pizzy
ingredients: string[], // seznam ingrediencí ingredients: string[], // seznam ingrediencí
sizes: PizzaSize[], // dostupné velikosti pizzy sizes: PizzaSize[], // dostupné velikosti pizzy
} }
/** Objednávka jedné konkrétní pizzy */ /** Objednávka jedné konkrétní pizzy */
export interface PizzaOrder { export type PizzaOrder = {
varId: number, // unikátní ID varianty pizzy varId: number, // unikátní ID varianty pizzy
name: string, // název pizzy name: string, // název pizzy
size: string, // velikost pizzy jako string (30cm) size: string, // velikost pizzy jako string (30cm)
@@ -43,7 +43,7 @@ export interface PizzaOrder {
} }
/** Celková objednávka jednoho člověka */ /** Celková objednávka jednoho člověka */
export interface Order { export type Order = {
customer: string, // jméno objednatele customer: string, // jméno objednatele
pizzaList: PizzaOrder[], // seznam objednaných pizz pizzaList: PizzaOrder[], // seznam objednaných pizz
fee?: { text?: string, price: number }, // příplatek (např. za extra ingredience) fee?: { text?: string, price: number }, // příplatek (např. za extra ingredience)
@@ -69,14 +69,14 @@ interface PizzaDay {
} }
/** Týdenní menu jednotlivých restaurací. */ /** Týdenní menu jednotlivých restaurací. */
export interface WeekMenu { export type WeekMenu = {
[dayIndex: number]: { [dayIndex: number]: {
[restaurant in Restaurants]?: DayMenu [restaurant in Restaurants]?: DayMenu
} }
} }
/** Data vztahující se k jednomu konkrétnímu dni. */ /** Data vztahující se k jednomu konkrétnímu dni. */
export interface DayData { export type DayData = {
date: string, // datum dne date: string, // datum dne
isWeekend: boolean, // příznak, zda je datum víkend isWeekend: boolean, // příznak, zda je datum víkend
weekIndex: number, // index dne v týdnu (0-6) weekIndex: number, // index dne v týdnu (0-6)
@@ -88,19 +88,19 @@ export interface DayData {
} }
/** Veškerá data pro zobrazení na klientovi. */ /** Veškerá data pro zobrazení na klientovi. */
export interface ClientData extends DayData { export type ClientData = DayData & {
todayWeekIndex?: number, // index dnešního dne v týdnu (0-6) todayWeekIndex?: number, // index dnešního dne v týdnu (0-6)
} }
/** Nabídka jídel jednoho podniku pro jeden konkrétní den. */ /** Nabídka jídel jednoho podniku pro jeden konkrétní den. */
export interface DayMenu { export type DayMenu = {
lastUpdate: number, // UNIX timestamp poslední aktualizace menu lastUpdate: number, // UNIX timestamp poslední aktualizace menu
closed: boolean, // příznak, zda je daný podnik v tento den zavřený closed: boolean, // příznak, zda je daný podnik v tento den zavřený
food: Food[], // seznam jídel v menu food: Food[], // seznam jídel v menu
} }
/** Jídlo z obědového menu restaurace. */ /** Jídlo z obědového menu restaurace. */
export interface Food { export type Food = {
amount?: string, // množství standardní porce, např. 0,33l nebo 150g amount?: string, // množství standardní porce, např. 0,33l nebo 150g
name: string, // název/popis jídla name: string, // název/popis jídla
price: string, // cena ve formátu '135 Kč' price: string, // cena ve formátu '135 Kč'
@@ -125,19 +125,19 @@ export enum UdalostEnum {
JDEME_OBED = "Jdeme oběd", JDEME_OBED = "Jdeme oběd",
} }
export interface NotififaceInput { export type NotififaceInput = {
udalost: UdalostEnum, udalost: UdalostEnum,
user: string, user: string,
} }
export interface NotifikaceData { export type NotifikaceData = {
input: NotififaceInput, input: NotififaceInput,
gotify?: boolean, gotify?: boolean,
teams?: boolean, teams?: boolean,
ntfy?: boolean, ntfy?: boolean,
} }
export interface GotifyServer { export type GotifyServer = {
server: string; server: string;
api_keys: string[]; api_keys: string[];
} }
@@ -174,7 +174,7 @@ export enum FeatureRequest {
DEVELOPMENT = "Zlepšení dokumentace/postupů pro ostatní vývojáře" DEVELOPMENT = "Zlepšení dokumentace/postupů pro ostatní vývojáře"
} }
export interface EasterEgg { export type EasterEgg = {
path: string; path: string;
url: string; url: string;
startOffset: number; startOffset: number;

View File

@@ -1 +1,2 @@
export * from './Types'; export * from './Types';
export * from './RequestTypes';