12 Commits

17 changed files with 473 additions and 198 deletions

View File

@@ -14,13 +14,13 @@ import './App.scss';
import { SelectSearchOption } from 'react-select-search';
import { faCircleCheck, faNoteSticky, faTrashCan } from '@fortawesome/free-regular-svg-icons';
import { useSettings } from './context/settings';
import { ClientData, Restaurants, Food, Order, Locations, PizzaOrder, PizzaDayState, FoodChoices, DayMenu, DepartureTime } from './types';
import { ClientData, Restaurants, Food, Order, Locations, PizzaOrder, PizzaDayState, FoodChoices, DayMenu, DepartureTime, LocationKey } from './types';
import Footer from './components/Footer';
import { faChainBroken, faChevronLeft, faChevronRight, faGear, faSatelliteDish, faSearch } from '@fortawesome/free-solid-svg-icons';
import Loader from './components/Loader';
import { getData, errorHandler, getQrUrl } from './api/Api';
import { addChoice, removeChoices, removeChoice, changeDepartureTime, jdemeObed, updateNote } from './api/FoodApi';
import { getHumanDateTime } from './Utils';
import { getHumanDateTime, isInTheFuture } from './Utils';
import NoteModal from './components/modals/NoteModal';
import { useEasterEgg } from './context/eggs';
import { getImage } from './api/EasterEggApi';
@@ -141,11 +141,8 @@ function App() {
useEffect(() => {
if (choiceRef?.current?.value && choiceRef.current.value !== "") {
// TODO: wtf, cos pil, když jsi tohle psal?
const key = choiceRef?.current?.value;
const locationIndex = Object.keys(Locations).indexOf(key as unknown as Locations);
const locationsKey = Object.keys(Locations)[locationIndex];
const restaurantKey = Object.keys(Restaurants).indexOf(locationsKey);
const locationKey = choiceRef.current.value as LocationKey;
const restaurantKey = Object.keys(Restaurants).indexOf(locationKey);
if (restaurantKey > -1 && food) {
const restaurant = Object.values(Restaurants)[restaurantKey];
setFoodChoiceList(food[restaurant]?.food);
@@ -194,9 +191,9 @@ function App() {
}, [auth?.login, easterEgg?.duration, easterEgg?.url, eggImage]);
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 LocationKey;
if (auth?.login) {
await errorHandler(() => addChoice(index, undefined, dayIndex));
await errorHandler(() => addChoice(locationKey, undefined, dayIndex));
if (foodChoiceRef.current?.value) {
foodChoiceRef.current.value = "";
}
@@ -211,17 +208,16 @@ function App() {
const doAddFoodChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
if (event.target.value && foodChoiceList?.length && choiceRef.current?.value) {
const restaurantKey = choiceRef.current.value;
const locationKey = choiceRef.current.value as LocationKey;
if (auth?.login) {
const locationIndex = Object.keys(Locations).indexOf(restaurantKey as unknown as Locations);
await errorHandler(() => addChoice(locationIndex, Number(event.target.value), dayIndex));
await errorHandler(() => addChoice(locationKey, Number(event.target.value), dayIndex));
}
}
}
const doRemoveChoices = async (locationKey: string) => {
const doRemoveChoices = async (locationKey: LocationKey) => {
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
if (choiceRef?.current?.value) {
choiceRef.current.value = "";
@@ -232,9 +228,9 @@ function App() {
}
}
const doRemoveFoodChoice = async (locationKey: string, foodIndex: number) => {
const doRemoveFoodChoice = async (locationKey: LocationKey, foodIndex: number) => {
if (auth?.login) {
await errorHandler(() => removeChoice(Number(locationKey), foodIndex, dayIndex));
await errorHandler(() => removeChoice(locationKey, foodIndex, dayIndex));
if (choiceRef?.current?.value) {
choiceRef.current.value = "";
}
@@ -355,7 +351,7 @@ function App() {
} else {
content = <h3>Chyba načtení dat</h3>
}
return <Col md={12} lg={6} className='mt-3'>
return <Col md={12} lg={4} className='mt-3'>
<h3>{name}</h3>
{menu?.lastUpdate && <small>Poslední aktualizace: {getHumanDateTime(new Date(menu.lastUpdate))}</small>}
{content}
@@ -421,6 +417,7 @@ function App() {
{food[Restaurants.SLADOVNICKA] && renderFoodTable('Sladovnická', food[Restaurants.SLADOVNICKA])}
{/* {food[Restaurants.UMOTLIKU] && renderFoodTable('U Motlíků', food[Restaurants.UMOTLIKU])} */}
{food[Restaurants.TECHTOWER] && renderFoodTable('TechTower', food[Restaurants.TECHTOWER])}
{food[Restaurants.ZASTAVKAUMICHALA] && renderFoodTable('Zastávka u Michala', food[Restaurants.ZASTAVKAUMICHALA])}
</Row>
<div className='content-wrapper'>
<div className='content'>
@@ -430,11 +427,8 @@ function App() {
<option></option>
{Object.entries(Locations)
.filter(entry => {
// TODO: wtf, cos pil, když jsi tohle psal? v2
const key = entry[0];
const locationIndex = Object.keys(Locations).indexOf(key as unknown as Locations);
const locationsKey = Object.keys(Locations)[locationIndex];
const restaurantKey = Object.keys(Restaurants).indexOf(locationsKey);
const locationKey = entry[0] as LocationKey;
const restaurantKey = Object.keys(Restaurants).indexOf(locationKey);
const v = Object.values(Restaurants)[restaurantKey];
return v == null || !food[v]?.closed;
})
@@ -452,18 +446,25 @@ function App() {
<p style={{ marginTop: "10px" }}>V kolik hodin preferuješ odchod?</p>
<Form.Select ref={departureChoiceRef} onChange={handleChangeDepartureTime}>
<option></option>
{Object.values(DepartureTime).map(time => <option key={time} value={time}>{time}</option>)}
{Object.values(DepartureTime)
.filter(time => isInTheFuture(time))
.map(time => <option key={time} value={time}>{time}</option>)}
</Form.Select>
</>}
</>}
{Object.keys(data.choices).length > 0 ?
<Table bordered className='mt-5'>
<tbody>
{Object.keys(data.choices).map((locationKey: string) => {
const locationName = Object.values(Locations)[Number(locationKey)];
const locationLoginList = Object.entries(data.choices[Number(locationKey)]);
{Object.keys(data.choices).map(key => {
const locationKey = key as LocationKey;
const locationName = Locations[locationKey];
const loginObject = data.choices[locationKey];
if (!loginObject) {
return;
}
const locationLoginList = Object.entries(loginObject);
return (
<tr key={locationKey}>
<tr key={key}>
<td>{locationName}</td>
<td className='p-0'>
<Table>
@@ -485,20 +486,20 @@ function App() {
setNoteModalOpen(true);
}} title='Upravit poznámku' className='action-icon' icon={faNoteSticky} />}
{login === auth.login && canChangeChoice && <FontAwesomeIcon onClick={() => {
doRemoveChoices(locationKey);
doRemoveChoices(key as LocationKey);
}} title={`Odstranit volbu ${locationName}, včetně případných zvolených jídel`} className='action-icon' icon={faTrashCan} />}
</td>
{userChoices?.length && food ? <td>
<ul>
{userChoices?.map(foodIndex => {
const locationsKey = Object.keys(Locations)[Number(locationKey)]
const restaurantKey = Object.keys(Restaurants).indexOf(locationsKey);
// TODO narovnat, tohle je zbytečně složité
const restaurantKey = Object.keys(Restaurants).indexOf(key);
const restaurant = Object.values(Restaurants)[restaurantKey];
const foodName = food[restaurant]?.food[foodIndex].name;
return <li key={foodIndex}>
{foodName}
{login === auth.login && canChangeChoice && <FontAwesomeIcon onClick={() => {
doRemoveFoodChoice(locationKey, foodIndex);
doRemoveFoodChoice(key as LocationKey, foodIndex);
}} title={`Odstranit ${foodName}`} className='action-icon' icon={faTrashCan} />}
</li>
})}

View File

@@ -1,3 +1,5 @@
import {DepartureTime} from "../../types";
const TOKEN_KEY = "token";
/**
@@ -43,3 +45,15 @@ export function getHumanDateTime(datetime: Date) {
return `${day}.${month}.${year} ${hours}:${minutes}`;
}
}
/**
* Vrátí true, pokud je předaný čas větší než aktuální čas.
*/
export function isInTheFuture(time: DepartureTime) {
const now = new Date();
const currentHours = now.getHours();
const currentMinutes = now.getMinutes();
const [hours, minutes] = time.split(':').map(Number);
return hours > currentHours || (hours === currentHours && minutes > currentMinutes);
}

View File

@@ -63,7 +63,7 @@ async function blobRequest(
export const api = {
get: <TResponse>(url: string) => request<TResponse>(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) => {
@@ -79,5 +79,5 @@ export const getData = async (dayIndex?: number) => {
}
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';
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) => {

View File

@@ -1,27 +1,28 @@
import { AddChoiceRequest, ChangeDepartureTimeRequest, LocationKey, RemoveChoiceRequest, RemoveChoicesRequest, UpdateNoteRequest } from "../types";
import { api } from "./Api";
const FOOD_API_PREFIX = '/api/food';
export const addChoice = async (locationIndex: number, foodIndex?: number, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/addChoice`, JSON.stringify({ locationIndex, foodIndex, dayIndex }));
export const addChoice = async (locationKey: LocationKey, foodIndex?: number, dayIndex?: number) => {
return await api.post<AddChoiceRequest, void>(`${FOOD_API_PREFIX}/addChoice`, { locationKey, foodIndex, dayIndex });
}
export const removeChoices = async (locationIndex: number, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/removeChoices`, JSON.stringify({ locationIndex, dayIndex }));
export const removeChoices = async (locationKey: LocationKey, dayIndex?: number) => {
return await api.post<RemoveChoicesRequest, void>(`${FOOD_API_PREFIX}/removeChoices`, { locationKey, dayIndex });
}
export const removeChoice = async (locationIndex: number, foodIndex: number, dayIndex?: number) => {
return await api.post<any, any>(`${FOOD_API_PREFIX}/removeChoice`, JSON.stringify({ locationIndex, foodIndex, dayIndex }));
export const removeChoice = async (locationKey: LocationKey, foodIndex: number, dayIndex?: number) => {
return await api.post<RemoveChoiceRequest, void>(`${FOOD_API_PREFIX}/removeChoice`, { locationKey, foodIndex, dayIndex });
}
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) => {
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 () => {
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";
const PIZZADAY_API_PREFIX = '/api/pizzaDay';
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 () => {
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 () => {
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 () => {
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 () => {
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) => {
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) => {
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) => {
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) => {
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) => {
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";
const VOTING_API_PREFIX = '/api/voting';
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) => {
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,9 +1,7 @@
import { getDayOfWeekIndex } from "./utils";
// Mockovací data pro podporované podniky, na jeden týden
const MOCK_DATA = {
'sladovnicka': [
[
'sladovnicka': {
'MONDAY': [
{
amount: "0,25l",
name: "Kulajda",
@@ -29,7 +27,7 @@ const MOCK_DATA = {
isSoup: false,
}
],
[
'TUESDAY': [
{
amount: "0,25l",
name: "Hovězí vývar s kapáním",
@@ -55,7 +53,7 @@ const MOCK_DATA = {
isSoup: false,
}
],
[
'WEDNESDAY': [
{
amount: "0,25l",
name: "Zelná polévka s klobásou",
@@ -81,7 +79,7 @@ const MOCK_DATA = {
isSoup: false,
}
],
[
'THURSDAY': [
{
amount: "0,25l",
name: "Kuřecí vývar s nudlemi",
@@ -107,7 +105,7 @@ const MOCK_DATA = {
isSoup: false,
}
],
[
'FRIDAY': [
{
amount: "0,25l",
name: "Dršťková polévka",
@@ -133,7 +131,7 @@ const MOCK_DATA = {
isSoup: false,
}
]
],
},
'uMotliku': [
[
{
@@ -427,6 +425,96 @@ const MOCK_DATA = {
isSoup: false,
}
]
],
'zastavkaUmichala': [
[
{
amount: "-",
name: "Fazolačka s klobásou & zakysačkou",
price: "39\xA0Kč",
isSoup: true,
},
{
amount: "-",
name: "Zeleninová musaka lilek, cuketa, tomatové sugo & sýrový bešamel",
price: "135\xA0Kč",
isSoup: false,
},
{
amount: "-",
name: "Slovácké strapačky s uzenou slaninou, zelím, mletým pepřem & sekanou petrželkou",
price: "140\xA0Kč",
isSoup: false,
},
{
amount: "-",
name: "Hovězí guláš s vejcem, zeleninovou garniturkou & žemlovými knedlíky",
price: "145\xA0Kč",
isSoup: false,
},
{
amount: "-",
name: "Kuřecí roláda s kaštanovou nádivkou, demi-glace & smetanovou bramborovou kaší",
price: "150\xA0Kč",
isSoup: false,
}
],
[
{
amount: "-",
name: "Hovězí vývar se zeleninou a játrovou rýží",
price: "39\xA0Kč",
isSoup: true,
},
{
amount: "-",
name: "Pečené vepřové koleno, křen, hořčice, chléb",
price: "320\xA0Kč",
isSoup: false,
}
],
[
{
amount: "-",
name: "Zeleninová polévka s kuskusem",
price: "39\xA0Kč",
isSoup: true,
},
{
amount: "-",
name: "Poutine (trhané vepřové, hranolky, sýr, čalamáda, pikantní omáčka)",
price: "190\xA0Kč",
isSoup: false,
}
],
[
{
amount: "-",
name: "Hrachová polévka s uzeninou",
price: "39\xA0Kč",
isSoup: true,
},
{
amount: "-",
name: "Vepřový řízek z kotlety, domácí bramborový salát",
price: "170\xA0Kč",
isSoup: false,
}
],
[
{
amount: "-",
name: "Cibulačka se sýrem",
price: "39\xA0Kč",
isSoup: true,
},
{
amount: "-",
name: "Burger z Chuck rollu, hranolky, tatarská omáčka",
price: "200\xA0Kč",
isSoup: false,
}
],
]
}
@@ -1180,8 +1268,11 @@ const MOCK_PIZZA_LIST = [
}
]
export const getTodayMock = () => {
return '2023-05-31'; // středa
/**
* Funkce vrací mock datu ve formátu YYYY-MM-DD
*/
export const getTodayMock = (): Date => {
return new Date('2025-01-08'); // pátek
}
export const getMenuSladovnickaMock = () => {
@@ -1196,6 +1287,10 @@ export const getMenuTechTowerMock = () => {
return MOCK_DATA['techTower'];
}
export const getMenuZastavkaUmichalaMock = () => {
return MOCK_DATA['zastavkaUmichala'];
}
export const getPizzaListMock = () => {
return MOCK_PIZZA_LIST;
}

View File

@@ -1,7 +1,7 @@
import axios from "axios";
import { load } from 'cheerio';
import { Food } from "../../types";
import { getMenuSladovnickaMock, getMenuTechTowerMock, getMenuUMotlikuMock } from "./mock";
import { DayOfWeek, DayOfWeekEnum, DayOfWeekIndex, Food, RestaurantWeeklyMenu } from "../../types";
import { getMenuSladovnickaMock, getMenuTechTowerMock, getMenuUMotlikuMock, getMenuZastavkaUmichalaMock } from "./mock";
// Fráze v názvech jídel, které naznačují že se jedná o polévku
const SOUP_NAMES = [
@@ -13,9 +13,9 @@ const SOUP_NAMES = [
'fazolová',
'cuketový krém',
'boršč',
'slepičí s',
'zeleninová s',
'hovězí s',
'slepičí s ',
'zeleninová s ',
'hovězí s ',
'kachní kaldoun',
'dršťková'
];
@@ -25,6 +25,8 @@ const DAYS_IN_WEEK = ['pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', '
const SLADOVNICKA_URL = 'https://sladovnicka.unasplzenchutna.cz/cz/denni-nabidka';
const U_MOTLIKU_URL = 'https://www.umotliku.cz/menu';
const TECHTOWER_URL = 'https://www.equifarm.cz/restaurace-techtower';
const ZASTAVKAUMICHALA_URL = 'https://www.zastavkaumichala.cz';
const SENKSERIKOVA_URL = 'https://www.menicka.cz/6561-pivovarsky-senk-serikova.html';
/**
* Vrátí true, pokud předaný text obsahuje některé ze slov, které naznačuje, že se jedná o polévku.
@@ -67,7 +69,7 @@ const getHtml = async (url: string): Promise<any> => {
* @param mock zda vrátit mock data
* @returns seznam jídel pro daný týden
*/
export const getMenuSladovnicka = async (firstDayOfWeek: Date, mock: boolean = false): Promise<Food[][]> => {
export const getMenuSladovnicka = async (firstDayOfWeek: Date, mock: boolean = false): Promise<RestaurantWeeklyMenu> => {
if (mock) {
return getMenuSladovnickaMock();
}
@@ -76,7 +78,8 @@ export const getMenuSladovnicka = async (firstDayOfWeek: Date, mock: boolean = f
const $ = load(html);
const list = $('ul.tab-links').children();
const result: Food[][] = [];
const result: RestaurantWeeklyMenu = {};
// TODO upravit až bude enum
for (let dayIndex = 0; dayIndex < 5; dayIndex++) {
const currentDate = new Date(firstDayOfWeek);
currentDate.setDate(firstDayOfWeek.getDate() + dayIndex);
@@ -94,7 +97,8 @@ export const getMenuSladovnicka = async (firstDayOfWeek: Date, mock: boolean = f
})
if (index === undefined) {
// Pravděpodobně svátek, nebo je zavřeno
result[dayIndex] = [{
const index: number = Object.keys(DayOfWeekEnum).indexOf('Casual'); // 1
result[dayIndex as DayOfWeekEnum] = [{
amount: undefined,
name: "Pro daný den nebyla nalezena denní nabídka",
price: "",
@@ -327,3 +331,53 @@ export const getMenuTechTower = async (firstDayOfWeek: Date, mock: boolean = fal
}
return result;
}
/**
* Získá obědovou nabídku ZastavkaUmichala pro jeden týden.
*
* @param firstDayOfWeek první den v týdnu, pro který získat menu
* @param mock zda vrátit mock data
* @returns seznam jídel pro dané datum
*/
export const getMenuZastavkaUmichala = async (firstDayOfWeek: Date, mock: boolean = false): Promise<Food[][]> => {
if (mock) {
return getMenuZastavkaUmichalaMock();
}
const nowDate = new Date().getDate();
const result: Food[][] = [];
for (let dayIndex = 0; dayIndex < 5; dayIndex++) {
const currentDate = new Date(firstDayOfWeek);
currentDate.setDate(firstDayOfWeek.getDate() + dayIndex);
// if (currentDate < now) {
if (currentDate.getDate() !== nowDate) {
result[dayIndex] = [{
amount: undefined,
name: "Pro tento den není uveřejněna nabídka jídel",
price: "",
isSoup: false,
}];
continue;
} else {
// let dateString = formatDate(currentDate, 'DD.MM.YYYY');
// const html = await getHtml(ZASTAVKAUMICHALA_URL + '/?do=dailyMenu-changeDate&dailyMenu-dateString=' + dateString);
const html = await getHtml(ZASTAVKAUMICHALA_URL);
const $ = load(html);
// const row = $($('.foodsList li')[0]).text();
const currentDayFood: Food[] = [];
$('.foodsList li').each((index, element) => {
currentDayFood.push({
amount: '-',
name: sanitizeText($(element).contents().not('span').text()),
price: sanitizeText($(element).find('span').text()),
isSoup: (index === 0),
});
});
result[dayIndex] = currentDayFood;
}
}
return result;
}

View File

@@ -1,10 +1,10 @@
import express from "express";
import express, { Request } from "express";
import { getLogin, getTrusted } from "../auth";
import { addChoice, addVolatileData, getDateForWeekIndex, getToday, removeChoice, removeChoices, updateDepartureTime, updateNote } from "../service";
import { getDayOfWeekIndex, parseToken } from "../utils";
import { getWebsocket } from "../websocket";
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ň
@@ -13,12 +13,12 @@ import { UdalostEnum } from "../../../types";
* @param req request
* @returns index dne v týdnu
*/
const parseValidateFutureDayIndex = (req: any) => {
const parseValidateFutureDayIndex = (req: Request<{}, any, IDayIndex>) => {
if (req.body.dayIndex == null) {
throw Error(`Nebyl předán index dne v týdnu.`);
}
const todayDayIndex = getDayOfWeekIndex(getToday());
const dayIndex = parseInt(req.body.dayIndex);
const dayIndex = req.body.dayIndex;
if (isNaN(dayIndex)) {
throw Error(`Neplatný index dne v týdnu: ${req.body.dayIndex}`);
}
@@ -30,10 +30,9 @@ const parseValidateFutureDayIndex = (req: any) => {
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;
@@ -45,15 +44,13 @@ router.post("/addChoice", async (req, res, next) => {
date = getDateForWeekIndex(dayIndex);
}
try {
const data = await addChoice(login, trusted, req.body.locationIndex, req.body.foodIndex, date);
const data = await addChoice(login, trusted, req.body.locationKey, 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) => {
router.post("/removeChoices", async (req: Request<{}, any, RemoveChoicesRequest>, res, next) => {
const login = getLogin(parseToken(req));
const trusted = getTrusted(parseToken(req));
let date = undefined;
@@ -67,13 +64,13 @@ router.post("/removeChoices", async (req, res, next) => {
date = getDateForWeekIndex(dayIndex);
}
try {
const data = await removeChoices(login, trusted, req.body.locationIndex, date);
const data = await removeChoices(login, trusted, req.body.locationKey, date);
getWebsocket().emit("message", await addVolatileData(data));
res.status(200).json(data);
} catch (e: any) { next(e) }
});
router.post("/removeChoice", 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;
@@ -87,13 +84,13 @@ router.post("/removeChoice", async (req, res, next) => {
date = getDateForWeekIndex(dayIndex);
}
try {
const data = await removeChoice(login, trusted, req.body.locationIndex, req.body.foodIndex, date);
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, res, next) => {
router.post("/updateNote", async (req: Request<{}, any, UpdateNoteRequest>, res, next) => {
const login = getLogin(parseToken(req));
const trusted = getTrusted(parseToken(req));
const note = req.body.note;
@@ -117,7 +114,7 @@ router.post("/updateNote", async (req, res, next) => {
} 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));
let date = undefined;
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 { createPizzaDay, deletePizzaDay, getPizzaList, addPizzaOrder, removePizzaOrder, lockPizzaDay, unlockPizzaDay, finishPizzaOrder, finishPizzaDelivery, updatePizzaDayNote, updatePizzaFee } from "../pizza";
import { parseToken } from "../utils";
import { getWebsocket } from "../websocket";
import { addVolatileData } from "../service";
import { AddPizzaRequest, FinishDeliveryRequest, RemovePizzaRequest, UpdatePizzaDayNoteRequest, UpdatePizzaFeeRequest } from "../../../types";
const router = express.Router();
/** 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 data = await createPizzaDay(login);
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. */
router.post("/delete", async (req, res) => {
router.post("/delete", async (req: Request<{}, any, undefined>, res) => {
const login = getLogin(parseToken(req));
const data = await deletePizzaDay(login);
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));
if (isNaN(req.body?.pizzaIndex)) {
throw Error("Nebyl předán index pizzy");
@@ -47,7 +48,7 @@ router.post("/add", async (req, res) => {
res.status(200).json({});
});
router.post("/remove", async (req, res) => {
router.post("/remove", async (req: Request<{}, any, RemovePizzaRequest>, res) => {
const login = getLogin(parseToken(req));
if (!req.body?.pizzaOrder) {
throw Error("Nebyla předána objednávka");
@@ -57,35 +58,35 @@ router.post("/remove", async (req, res) => {
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 data = await lockPizzaDay(login);
getWebsocket().emit("message", await addVolatileData(data));
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 data = await unlockPizzaDay(login);
getWebsocket().emit("message", await addVolatileData(data));
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 data = await finishPizzaOrder(login);
getWebsocket().emit("message", await addVolatileData(data));
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 data = await finishPizzaDelivery(login, req.body.bankAccount, req.body.bankAccountHolder);
getWebsocket().emit("message", await addVolatileData(data));
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));
try {
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) }
});
router.post("/updatePizzaFee", async (req, res, next) => {
router.post("/updatePizzaFee", async (req: Request<{}, any, UpdatePizzaFeeRequest>, res, next) => {
const login = getLogin(parseToken(req));
if (!req.body.login) {
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 { parseToken } from "../utils";
import { getUserVotes, updateFeatureVote } from "../voting";
import { FeatureRequest, UpdateFeatureVoteRequest } from "../../../types";
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 data = await getUserVotes(login);
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));
if (req.body?.option == null || req.body?.active == null) {
res.status(400).json({ error: "Chybné parametry volání" });

View File

@@ -1,7 +1,7 @@
import { InsufficientPermissions, formatDate, getDayOfWeekIndex, getFirstWorkDayOfWeek, getHumanDate, getHumanTime, getIsWeekend, getLastWorkDayOfWeek, getWeekNumber } from "./utils";
import { ClientData, Locations, Restaurants, DayMenu, DepartureTime, DayData, WeekMenu } from "../../types";
import { InsufficientPermissions, formatDate, getDayOfWeekIndex, getFirstWorkDayOfWeek, getHumanDate, getIsWeekend, getWeekNumber } from "./utils";
import { ClientData, Restaurants, RestaurantDailyMenu, DepartureTime, DayData, WeekMenu, LocationKey, DayOfWeekIndex, daysOfWeeksIndices, DayOfWeekEnum, DayOfWeek } from "../../types";
import getStorage from "./storage";
import { getMenuSladovnicka, getMenuTechTower, getMenuUMotliku } from "./restaurants";
import { getMenuSladovnicka, getMenuTechTower, getMenuUMotliku, getMenuZastavkaUmichala } from "./restaurants";
import { getTodayMock } from "./mock";
const storage = getStorage();
@@ -10,7 +10,7 @@ const MENU_PREFIX = 'menu';
/** Vrátí dnešní datum, případně fiktivní datum pro účely vývoje a testování. */
export function getToday(): Date {
if (process.env.MOCK_DATA === 'true') {
return new Date(getTodayMock());
return getTodayMock();
}
return new Date();
}
@@ -61,6 +61,7 @@ export async function getData(date?: Date): Promise<ClientData> {
[Restaurants.SLADOVNICKA]: await getRestaurantMenu(Restaurants.SLADOVNICKA, date),
// [Restaurants.UMOTLIKU]: await getRestaurantMenu(Restaurants.UMOTLIKU, date),
[Restaurants.TECHTOWER]: await getRestaurantMenu(Restaurants.TECHTOWER, date),
[Restaurants.ZASTAVKAUMICHALA]: await getRestaurantMenu(Restaurants.ZASTAVKAUMICHALA, date),
}
clientData = await addVolatileData(clientData);
return clientData;
@@ -96,7 +97,7 @@ async function getMenu(date: Date): Promise<WeekMenu | undefined> {
* @param date datum, ke kterému získat menu
* @param mock příznak, zda chceme pouze mock data
*/
export async function getRestaurantMenu(restaurant: Restaurants, date?: Date): Promise<DayMenu> {
export async function getRestaurantMenu(restaurant: Restaurants, date?: Date): Promise<RestaurantDailyMenu> {
const usedDate = date ?? getToday();
const dayOfWeekIndex = getDayOfWeekIndex(usedDate);
const now = new Date().getTime();
@@ -110,9 +111,9 @@ export async function getRestaurantMenu(restaurant: Restaurants, date?: Date): P
let menus = await getMenu(usedDate);
if (menus == null) {
menus = [];
menus = {};
}
for (let i = 0; i < 5; i++) {
daysOfWeeksIndices.forEach(i => {
if (menus[i] == null) {
menus[i] = {};
}
@@ -123,6 +124,9 @@ export async function getRestaurantMenu(restaurant: Restaurants, date?: Date): P
food: [],
};
}
})
if (!menus[dayOfWeekIndex]) {
menus[dayOfWeekIndex] = {};
}
if (!menus[dayOfWeekIndex][restaurant]?.food?.length) {
const firstDay = getFirstWorkDayOfWeek(usedDate);
@@ -130,7 +134,15 @@ export async function getRestaurantMenu(restaurant: Restaurants, date?: Date): P
switch (restaurant) {
case Restaurants.SLADOVNICKA:
try {
// TODO tady jsme v háji, protože z následujících metod vracíme arbitrárně dlouhé pole (musíme vracet omezené na maximálně 0-7 prvků)
const sladovnickaFood = await getMenuSladovnicka(firstDay, mock);
for (const i in DayOfWeekEnum) {
menus[i][restaurant]!.food = sladovnickaFood[i];
// Velice chatrný a nespolehlivý způsob detekce uzavření...
if (sladovnickaFood[i].length === 1 && sladovnickaFood[i][0].name.toLowerCase() === 'pro daný den nebyla nalezena denní nabídka') {
menus[i][restaurant]!.closed = true;
}
}
for (let i = 0; i < sladovnickaFood.length; i++) {
menus[i][restaurant]!.food = sladovnickaFood[i];
// Velice chatrný a nespolehlivý způsob detekce uzavření...
@@ -168,6 +180,19 @@ export async function getRestaurantMenu(restaurant: Restaurants, date?: Date): P
} catch (e: any) {
console.error("Selhalo načtení jídel pro podnik TechTower", e);
}
case Restaurants.ZASTAVKAUMICHALA:
try {
const zastavkaUmichalaFood = await getMenuZastavkaUmichala(firstDay, mock);
for (let i = 0; i < zastavkaUmichalaFood.length; i++) {
menus[i][restaurant]!.food = zastavkaUmichalaFood[i];
if (zastavkaUmichalaFood[i]?.length === 1 && zastavkaUmichalaFood[i][0].name === 'Pro tento den není uveřejněna nabídka jídel.') {
menus[i][restaurant]!.closed = true;
}
}
break;
} catch (e: any) {
console.error("Selhalo načtení jídel pro podnik Zastávka u Michala", e);
}
}
await storage.setData(getMenuKey(usedDate), menus);
}
@@ -192,19 +217,19 @@ export async function initIfNeeded(date?: Date) {
*
* @param login login 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
* @returns
*/
export async function removeChoices(login: string, trusted: boolean, location: Locations, date?: Date) {
export async function removeChoices(login: string, trusted: boolean, locationKey: LocationKey, date?: Date) {
const selectedDay = formatDate(date ?? getToday());
let data: DayData = await storage.getData(selectedDay);
validateTrusted(data, login, trusted);
if (location in data.choices) {
if (login in data.choices[location]) {
delete data.choices[location][login]
if (Object.keys(data.choices[location]).length === 0) {
delete data.choices[location]
if (locationKey in data.choices) {
if (data.choices[locationKey] && login in data.choices[locationKey]) {
delete data.choices[locationKey][login]
if (Object.keys(data.choices[locationKey]).length === 0) {
delete data.choices[locationKey]
}
await storage.setData(selectedDay, data);
}
@@ -218,20 +243,20 @@ export async function removeChoices(login: string, trusted: boolean, location: L
*
* @param login login 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 date datum, ke kterému se volba vztahuje
* @returns
*/
export async function removeChoice(login: string, trusted: boolean, location: Locations, foodIndex: number, date?: Date) {
export async function removeChoice(login: string, trusted: boolean, locationKey: LocationKey, foodIndex: number, date?: Date) {
const selectedDay = formatDate(date ?? getToday());
let data: DayData = await storage.getData(selectedDay);
validateTrusted(data, login, trusted);
if (location in data.choices) {
if (login in data.choices[location]) {
const index = data.choices[location][login].options.indexOf(foodIndex);
if (locationKey in data.choices) {
if (data.choices[locationKey] && login in data.choices[locationKey]) {
const index = data.choices[locationKey][login].options.indexOf(foodIndex);
if (index > -1) {
data.choices[location][login].options.splice(index, 1)
data.choices[locationKey][login].options.splice(index, 1)
await storage.setData(selectedDay, data);
}
}
@@ -247,10 +272,11 @@ export async function removeChoice(login: string, trusted: boolean, location: Lo
async function removeChoiceIfPresent(login: string, date: string) {
let data: DayData = await storage.getData(date);
for (const key of Object.keys(data.choices)) {
if (login in data.choices[key]) {
delete data.choices[key][login];
if (Object.keys(data.choices[key]).length === 0) {
delete data.choices[key];
const locationKey = key as LocationKey;
if (data.choices[locationKey] && login in data.choices[locationKey]) {
delete data.choices[locationKey][login];
if (Object.keys(data.choices[locationKey]).length === 0) {
delete data.choices[locationKey];
}
await storage.setData(date, data);
}
@@ -285,13 +311,13 @@ function validateTrusted(data: ClientData, login: string, trusted: boolean) {
*
* @param login login 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 trusted příznak, zda se jedná o ověřeného uživatele
* @param date datum, ke kterému se volba vztahuje
* @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: LocationKey, foodIndex?: number, date?: Date) {
const usedDate = date ?? getToday();
await initIfNeeded(usedDate);
const selectedDate = formatDate(usedDate);
@@ -301,17 +327,21 @@ export async function addChoice(login: string, trusted: boolean, location: Locat
if (foodIndex == null) {
data = await removeChoiceIfPresent(login, selectedDate);
}
if (!(location in data.choices)) {
data.choices[location] = {};
// TODO vytáhnout inicializaci "prázdné struktury" do vlastní funkce
if (!(data.choices[locationKey])) {
data.choices[locationKey] = {}
}
if (!(login in data.choices[location])) {
data.choices[location][login] = {
if (!(login in data.choices[locationKey])) {
if (!data.choices[locationKey]) {
data.choices[locationKey] = {}
}
data.choices[locationKey][login] = {
trusted,
options: []
};
}
if (foodIndex != null && !data.choices[location][login].options.includes(foodIndex)) {
data.choices[location][login].options.push(foodIndex);
if (foodIndex != null && !data.choices[locationKey][login].options.includes(foodIndex)) {
data.choices[locationKey][login].options.push(foodIndex);
}
await storage.setData(selectedDate, data);
return data;

View File

@@ -1,11 +1,13 @@
import { Choices } from "../../types";
import { Choices, DayOfWeekIndex, LocationKey } from "../../types";
/** Vrátí datum v ISO formátu. */
export function formatDate(date: Date) {
let currentDay = String(date.getDate()).padStart(2, '0');
let currentMonth = String(date.getMonth() + 1).padStart(2, "0");
let currentYear = date.getFullYear();
return `${currentYear}-${currentMonth}-${currentDay}`;
export function formatDate(date: Date, format?: string) {
let day = String(date.getDate()).padStart(2, '0');
let month = String(date.getMonth() + 1).padStart(2, "0");
let year = String(date.getFullYear());
const f = (format === undefined) ? 'YYYY-MM-DD' : format;
return f.replace('DD', day).replace('MM', month).replace('YYYY', year);
}
/** Vrátí human-readable reprezentaci předaného data pro zobrazení. */
@@ -30,9 +32,9 @@ export function getHumanTime(time: Date) {
* @param date datum
* @returns index dne v týdnu
*/
export const getDayOfWeekIndex = (date: Date) => {
export const getDayOfWeekIndex = (date: Date): DayOfWeekIndex => {
// https://stackoverflow.com/a/4467559
return (((date.getDay() - 1) % 7) + 7) % 7;
return ((((date.getDay() - 1) % 7) + 7) % 7) as DayOfWeekIndex;
}
/** Vrátí true, pokud je předané datum o víkendu. */
@@ -110,21 +112,21 @@ export const checkBodyParams = (req: any, paramNames: string[]) => {
// TODO umístit do samostatného souboru
export class InsufficientPermissions extends Error { }
export const getUsersByLocation = (data: Choices, login: string): string[] => {
export const getUsersByLocation = (choices: Choices, login: string): string[] => {
const result: string[] = [];
for (const location in data) {
if (data.hasOwnProperty(location)) {
if (data[location][login]) {
for (const username in data[location]) {
if (data[location].hasOwnProperty(username)) {
for (const location of Object.entries(choices)) {
const locationKey = location[0] as LocationKey;
const locationValue = location[1];
if (locationValue[login]) {
for (const username in choices[locationKey]) {
if (choices[locationKey].hasOwnProperty(username)) {
result.push(username);
}
}
break;
}
}
}
return result;
}

56
types/RequestTypes.ts Normal file
View File

@@ -0,0 +1,56 @@
import { FeatureRequest, LocationKey, PizzaOrder } from "./Types";
export type ILocationKey = {
locationKey: LocationKey,
}
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

@@ -3,23 +3,25 @@ export enum Restaurants {
SLADOVNICKA = 'sladovnicka',
// UMOTLIKU = 'uMotliku',
TECHTOWER = 'techTower',
ZASTAVKAUMICHALA = 'zastavkaUmichala',
}
export interface FoodChoices {
export type FoodChoices = {
trusted: boolean,
options: number[],
departureTime?: string,
note?: string,
}
export interface Choices {
[location: string]: {
// TODO okomentovat / rozdělit
export type Choices = {
[location in LocationKey]?: {
[login: string]: FoodChoices
},
}
}
/** Velikost konkrétní pizzy */
export interface PizzaSize {
export type PizzaSize = {
varId: number, // unikátní ID varianty pizzy
size: string, // velikost pizzy, např. "30cm"
pizzaPrice: number, // cena samotné pizzy
@@ -28,14 +30,14 @@ export interface PizzaSize {
}
/** Jedna konkrétní pizza */
export interface Pizza {
export type Pizza = {
name: string, // název pizzy
ingredients: string[], // seznam ingrediencí
sizes: PizzaSize[], // dostupné velikosti pizzy
}
/** Objednávka jedné konkrétní pizzy */
export interface PizzaOrder {
export type PizzaOrder = {
varId: number, // unikátní ID varianty pizzy
name: string, // název pizzy
size: string, // velikost pizzy jako string (30cm)
@@ -43,7 +45,7 @@ export interface PizzaOrder {
}
/** Celková objednávka jednoho člověka */
export interface Order {
export type Order = {
customer: string, // jméno objednatele
pizzaList: PizzaOrder[], // seznam objednaných pizz
fee?: { text?: string, price: number }, // příplatek (např. za extra ingredience)
@@ -68,39 +70,55 @@ interface PizzaDay {
orders: Order[], // seznam objednávek jednotlivých lidí
}
/** Index dne v týdnu (0 = pondělí, 6 = neděle) */
// TODO tohle by měl být (seřazený) enum MONDAY-SUNDAY, ne číslo
export const daysOfWeeksIndices = [0, 1, 2, 3, 4, 5, 6] as const;
export type DayOfWeekIndex = typeof daysOfWeeksIndices[number]
const daysOfWeek = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY'] as const;
export type DayOfWeek = typeof daysOfWeek[number];
/** Denní menu všech dostupných podniků. */
export type DailyMenu = {
[restaurant in Restaurants]?: RestaurantDailyMenu
}
/** Týdenní menu jednotlivých restaurací. */
export interface WeekMenu {
[dayIndex: number]: {
[restaurant in Restaurants]?: DayMenu
}
export type WeekMenu = {
[dayIndex in DayOfWeek]?: DailyMenu
}
/** Týdenní menu jedné restaurace. */
export type RestaurantWeeklyMenu = {
[key in DayOfWeek]?: Food[]
}
/** Data vztahující se k jednomu konkrétnímu dni. */
export interface DayData {
export type DayData = {
date: string, // datum dne
isWeekend: boolean, // příznak, zda je datum víkend
weekIndex: number, // index dne v týdnu (0-6)
weekIndex: DayOfWeekIndex, // index dne v týdnu (0-6)
choices: Choices, // seznam voleb uživatelů
menus?: { [restaurant in Restaurants]?: DayMenu }, // menu jednotlivých restaurací
menus?: { [restaurant in Restaurants]?: RestaurantDailyMenu }, // menu jednotlivých restaurací
pizzaDay?: PizzaDay, // pizza day pro dnešní den, pokud existuje
pizzaList?: Pizza[], // seznam dostupných pizz pro dnešní den
pizzaListLastUpdate?: Date, // datum a čas poslední aktualizace pizz
}
/** Veškerá data pro zobrazení na klientovi. */
export interface ClientData extends DayData {
todayWeekIndex?: number, // index dnešního dne v týdnu (0-6)
export type ClientData = DayData & {
todayWeekIndex?: DayOfWeekIndex, // index dnešního dne v týdnu (0-6)
}
/** Nabídka jídel jednoho podniku pro jeden konkrétní den. */
export interface DayMenu {
export type RestaurantDailyMenu = {
lastUpdate: number, // UNIX timestamp poslední aktualizace menu
closed: boolean, // příznak, zda je daný podnik v tento den zavřený
food: Food[], // seznam jídel v menu
}
/** 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
name: string, // název/popis jídla
price: string, // cena ve formátu '135 Kč'
@@ -112,6 +130,7 @@ export enum Locations {
SLADOVNICKA = 'Sladovnická',
// UMOTLIKU = 'U Motlíků',
TECHTOWER = 'TechTower',
ZASTAVKAUMICHALA = 'Zastávka u Michala',
SPSE = 'SPŠE',
PIZZA = 'Pizza day',
OBJEDNAVAM = 'Budu objednávat',
@@ -119,25 +138,28 @@ export enum Locations {
ROZHODUJI = 'Rozhoduji se',
}
// TODO totéž
export type LocationKey = keyof typeof Locations;
export enum UdalostEnum {
ZAHAJENA_PIZZA = "Zahájen pizza day",
OBJEDNANA_PIZZA = "Objednána pizza",
JDEME_OBED = "Jdeme oběd",
}
export interface NotififaceInput {
export type NotififaceInput = {
udalost: UdalostEnum,
user: string,
}
export interface NotifikaceData {
export type NotifikaceData = {
input: NotififaceInput,
gotify?: boolean,
teams?: boolean,
ntfy?: boolean,
}
export interface GotifyServer {
export type GotifyServer = {
server: string;
api_keys: string[];
}
@@ -174,7 +196,7 @@ export enum FeatureRequest {
DEVELOPMENT = "Zlepšení dokumentace/postupů pro ostatní vývojáře"
}
export interface EasterEgg {
export type EasterEgg = {
path: string;
url: string;
startOffset: number;

View File

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