Compare commits
2 Commits
feat/jdeme
...
feat/DayOf
| Author | SHA1 | Date | |
|---|---|---|---|
| a8dc6c317d | |||
| cfcbd7a68b |
22
.gitignore
vendored
22
.gitignore
vendored
@@ -1 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
variables:
|
||||
- &node_image 'node:18-alpine3.18'
|
||||
- &branch 'master'
|
||||
|
||||
when:
|
||||
- event: push
|
||||
branch: *branch
|
||||
|
||||
steps:
|
||||
- name: Install server dependencies
|
||||
image: *node_image
|
||||
commands:
|
||||
- cd server
|
||||
- yarn install --frozen-lockfile
|
||||
- name: Install client dependencies
|
||||
image: *node_image
|
||||
commands:
|
||||
- cd client
|
||||
- yarn install --frozen-lockfile
|
||||
- name: Build server
|
||||
depends_on: [Install server dependencies]
|
||||
image: *node_image
|
||||
commands:
|
||||
- cd server
|
||||
- yarn build
|
||||
- name: Build client
|
||||
depends_on: [Install client dependencies]
|
||||
image: *node_image
|
||||
commands:
|
||||
- cd client
|
||||
- yarn build
|
||||
- name: Build Docker image
|
||||
depends_on: [Build server, Build client]
|
||||
image: woodpeckerci/plugin-docker-buildx
|
||||
settings:
|
||||
dockerfile: Dockerfile-Woodpecker
|
||||
platforms: linux/amd64
|
||||
registry:
|
||||
from_secret: REPO_URL
|
||||
username:
|
||||
from_secret: REPO_USERNAME
|
||||
password:
|
||||
from_secret: REPO_PASSWORD
|
||||
repo:
|
||||
from_secret: REPO_NAME
|
||||
- name: Discord notification - build
|
||||
image: appleboy/drone-discord
|
||||
depends_on: [Build Docker image]
|
||||
when:
|
||||
- status: [success, failure]
|
||||
settings:
|
||||
webhook_id:
|
||||
from_secret: DISCORD_WEBHOOK_ID
|
||||
webhook_token:
|
||||
from_secret: DISCORD_WEBHOOK_TOKEN
|
||||
message: "{{#success build.status}}✅ Sestavení {{build.number}} proběhlo úspěšně.{{else}}❌ Sestavení {{build.number}} selhalo.{{/success}}\n\nPipeline: {{build.link}}\nPoslední commit: {{commit.message}}Autor: {{commit.author}}"
|
||||
@@ -54,6 +54,7 @@ WORKDIR /app
|
||||
# Vykopírování sestaveného serveru
|
||||
COPY --from=builder /build/server/node_modules ./server/node_modules
|
||||
COPY --from=builder /build/server/dist ./
|
||||
COPY server/resources ./server/resources
|
||||
|
||||
# Vykopírování sestaveného klienta
|
||||
COPY --from=builder /build/client/dist ./public
|
||||
@@ -62,10 +63,8 @@ COPY --from=builder /build/client/dist ./public
|
||||
COPY /server/.env.production ./server/src
|
||||
|
||||
# Zkopírování konfigurace easter eggů
|
||||
RUN if [ -f /server/.easter-eggs.json ]; then cp /server/.easter-eggs.json ./server/; fi
|
||||
|
||||
# Export /data/db.json do složky /data
|
||||
VOLUME ["/data"]
|
||||
# TODO tohle spadne když nebude existovat!
|
||||
COPY /server/.easter-eggs.json ./server/
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
FROM node:18-alpine3.18
|
||||
ENV LANG=cs_CZ.UTF-8
|
||||
ENV NODE_ENV=production
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Vykopírování sestaveného serveru
|
||||
COPY ./server/node_modules ./server/node_modules
|
||||
COPY ./server/dist ./
|
||||
# TODO tohle není dobře, má to být součástí serveru
|
||||
# COPY ./server/resources ./resources
|
||||
|
||||
# Vykopírování sestaveného klienta
|
||||
COPY ./client/dist ./public
|
||||
|
||||
# Zkopírování konfigurace easter eggů
|
||||
RUN if [ -f ./server/.easter-eggs.json ]; then cp ./server/.easter-eggs.json ./server/; fi
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD [ "node", "./server/src/index.js" ]
|
||||
1
client/.gitignore
vendored
1
client/.gitignore
vendored
@@ -1,2 +1,3 @@
|
||||
build
|
||||
dist
|
||||
src/types
|
||||
@@ -31,8 +31,9 @@
|
||||
"vite-tsconfig-paths": "^5.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "yarn vite",
|
||||
"build": "yarn vite build"
|
||||
"copy-types": "cp -r ../types ./src",
|
||||
"start": "yarn copy-types && vite",
|
||||
"build": "yarn copy-types && vite build"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
|
||||
@@ -8,12 +8,13 @@ import { Alert, Button, Col, Form, Row, Table } from 'react-bootstrap';
|
||||
import Header from './components/Header';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
|
||||
import PizzaOrderList from './components/PizzaOrderList';
|
||||
import SelectSearch, {SelectedOptionValue, SelectSearchOption} from 'react-select-search';
|
||||
import SelectSearch, { SelectedOptionValue } from 'react-select-search';
|
||||
import 'react-select-search/style.css';
|
||||
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, LocationKey } 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';
|
||||
@@ -189,13 +190,6 @@ function App() {
|
||||
}
|
||||
}, [auth?.login, easterEgg?.duration, easterEgg?.url, eggImage]);
|
||||
|
||||
const doAddClickFoodChoice = async (location: Locations, foodIndex?: number) => {
|
||||
const locationKey = Object.keys(Locations).find(key => Locations[key as keyof typeof Locations] === location) as LocationKey;
|
||||
if (auth?.login) {
|
||||
await errorHandler(() => addChoice(locationKey, foodIndex, dayIndex));
|
||||
}
|
||||
}
|
||||
|
||||
const doAddChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const locationKey = event.target.value as LocationKey;
|
||||
if (auth?.login) {
|
||||
@@ -206,9 +200,9 @@ function App() {
|
||||
}
|
||||
}
|
||||
|
||||
const doJdemeObed = async (locationKey: LocationKey) => {
|
||||
const doJdemeObed = async () => {
|
||||
if (auth?.login) {
|
||||
await jdemeObed(locationKey);
|
||||
await jdemeObed();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,16 +332,15 @@ function App() {
|
||||
}
|
||||
}
|
||||
|
||||
const renderFoodTable = (location: Locations, menu: DayMenu) => {
|
||||
const renderFoodTable = (name: string, menu: DayMenu) => {
|
||||
let content;
|
||||
if (menu?.closed) {
|
||||
content = <h3>Zavřeno</h3>
|
||||
} else if (menu?.food?.length > 0) {
|
||||
const hideSoups = settings?.hideSoups;
|
||||
content = <Table striped bordered hover>
|
||||
<tbody style={{ cursor: 'pointer' }}>
|
||||
{menu.food.filter(f => (hideSoups ? !f.isSoup : true)).map((f: any, index: number) =>
|
||||
<tr key={index} onClick={() => doAddClickFoodChoice(location, hideSoups ? index + 1 : index)}>
|
||||
<tbody>
|
||||
{menu.food.filter(f => (settings?.hideSoups ? !f.isSoup : true)).map((f: any, index: number) =>
|
||||
<tr key={index}>
|
||||
<td>{f.amount}</td>
|
||||
<td>{f.name}</td>
|
||||
<td>{f.price}</td>
|
||||
@@ -358,8 +351,8 @@ function App() {
|
||||
} else {
|
||||
content = <h3>Chyba načtení dat</h3>
|
||||
}
|
||||
return <Col md={12} lg={3} className='mt-3'>
|
||||
<h3 style={{ cursor: 'pointer' }} onClick={() => doAddClickFoodChoice(location, undefined)}>{location}</h3>
|
||||
return <Col md={12} lg={4} className='mt-3'>
|
||||
<h3>{name}</h3>
|
||||
{menu?.lastUpdate && <small>Poslední aktualizace: {getHumanDateTime(new Date(menu.lastUpdate))}</small>}
|
||||
{content}
|
||||
</Col>
|
||||
@@ -409,8 +402,8 @@ function App() {
|
||||
<img src='snowman.png' style={{ position: "absolute", height: "110px", right: 10, top: 5 }} />
|
||||
Poslední změny:
|
||||
<ul>
|
||||
<li>Přidání restaurací Zastávka u Michala a Pivovarský šenk Šeříková</li>
|
||||
<li>Možnost výběru restaurace a jídel kliknutím v tabulce</li>
|
||||
<li>Zimní atmosféra</li>
|
||||
<li>Odstranění podniku U Motlíků</li>
|
||||
</ul>
|
||||
</Alert>
|
||||
{dayIndex != null &&
|
||||
@@ -421,11 +414,10 @@ function App() {
|
||||
</div>
|
||||
}
|
||||
<Row className='food-tables'>
|
||||
{food[Restaurants.SLADOVNICKA] && renderFoodTable(Locations.SLADOVNICKA, food[Restaurants.SLADOVNICKA])}
|
||||
{/* {food[Restaurants.UMOTLIKU] && renderFoodTable(food[Restaurants.UMOTLIKU])} */}
|
||||
{food[Restaurants.TECHTOWER] && renderFoodTable(Locations.TECHTOWER, food[Restaurants.TECHTOWER])}
|
||||
{food[Restaurants.ZASTAVKAUMICHALA] && renderFoodTable(Locations.ZASTAVKAUMICHALA, food[Restaurants.ZASTAVKAUMICHALA])}
|
||||
{food[Restaurants.SENKSERIKOVA] && renderFoodTable(Locations.SENKSERIKOVA, food[Restaurants.SENKSERIKOVA])}
|
||||
{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'>
|
||||
@@ -471,7 +463,6 @@ function App() {
|
||||
return;
|
||||
}
|
||||
const locationLoginList = Object.entries(loginObject);
|
||||
const disabled = false;
|
||||
return (
|
||||
<tr key={key}>
|
||||
<td>{locationName}</td>
|
||||
@@ -520,9 +511,6 @@ function App() {
|
||||
</tbody>
|
||||
</Table>
|
||||
</td>
|
||||
<td>
|
||||
<Button onClick={() => doJdemeObed(locationKey)} disabled={false}>Jdeme na oběd</Button>
|
||||
</td>
|
||||
</tr>)
|
||||
}
|
||||
)}
|
||||
@@ -546,6 +534,7 @@ function App() {
|
||||
setLoadingPizzaDay(true);
|
||||
await createPizzaDay().then(() => setLoadingPizzaDay(false));
|
||||
}}>Založit Pizza day</Button>
|
||||
<Button onClick={doJdemeObed} style={{ marginLeft: "14px" }}>Jdeme na oběd !</Button>
|
||||
</>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -53,12 +53,7 @@ export function isInTheFuture(time: DepartureTime) {
|
||||
const now = new Date();
|
||||
const currentHours = now.getHours();
|
||||
const currentMinutes = now.getMinutes();
|
||||
const currentDate = now.toDateString();
|
||||
const [hours, minutes] = time.split(':').map(Number);
|
||||
|
||||
if (currentDate === now.toDateString()) {
|
||||
return hours > currentHours || (hours === currentHours && minutes > currentMinutes);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { EasterEgg } from "../../../types";
|
||||
import { EasterEgg } from "../types";
|
||||
import { api } from "./Api";
|
||||
|
||||
const EASTER_EGGS_API_PREFIX = '/api/easterEggs';
|
||||
|
||||
@@ -1,12 +1,4 @@
|
||||
import {
|
||||
AddChoiceRequest,
|
||||
ChangeDepartureTimeRequest,
|
||||
JdemeObedRequest,
|
||||
LocationKey,
|
||||
RemoveChoiceRequest,
|
||||
RemoveChoicesRequest,
|
||||
UpdateNoteRequest
|
||||
} from "../../../types";
|
||||
import { AddChoiceRequest, ChangeDepartureTimeRequest, LocationKey, RemoveChoiceRequest, RemoveChoicesRequest, UpdateNoteRequest } from "../types";
|
||||
import { api } from "./Api";
|
||||
|
||||
const FOOD_API_PREFIX = '/api/food';
|
||||
@@ -31,6 +23,6 @@ export const changeDepartureTime = async (time: string, dayIndex?: number) => {
|
||||
return await api.post<ChangeDepartureTimeRequest, void>(`${FOOD_API_PREFIX}/changeDepartureTime`, { time, dayIndex });
|
||||
}
|
||||
|
||||
export const jdemeObed = async (locationKey: LocationKey) => {
|
||||
return await api.post<JdemeObedRequest, void>(`${FOOD_API_PREFIX}/jdemeObed`, { locationKey });
|
||||
export const jdemeObed = async () => {
|
||||
return await api.post<undefined, void>(`${FOOD_API_PREFIX}/jdemeObed`);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AddPizzaRequest, FinishDeliveryRequest, PizzaOrder, RemovePizzaRequest, UpdatePizzaDayNoteRequest, UpdatePizzaFeeRequest } from "../../../types";
|
||||
import { AddPizzaRequest, FinishDeliveryRequest, PizzaOrder, RemovePizzaRequest, UpdatePizzaDayNoteRequest, UpdatePizzaFeeRequest } from "../types";
|
||||
import { api } from "./Api";
|
||||
|
||||
const PIZZADAY_API_PREFIX = '/api/pizzaDay';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FeatureRequest, UpdateFeatureVoteRequest } from "../../../types";
|
||||
import { FeatureRequest, UpdateFeatureVoteRequest } from "../types";
|
||||
import { api } from "./Api";
|
||||
|
||||
const VOTING_API_PREFIX = '/api/voting';
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useAuth } from "../context/auth";
|
||||
import SettingsModal from "./modals/SettingsModal";
|
||||
import { useSettings } from "../context/settings";
|
||||
import FeaturesVotingModal from "./modals/FeaturesVotingModal";
|
||||
import { FeatureRequest } from "../../../types";
|
||||
import { FeatureRequest } from "../types";
|
||||
import { errorHandler } from "../api/Api";
|
||||
import { getFeatureVotes, updateFeatureVote } from "../api/VotingApi";
|
||||
import PizzaCalculatorModal from "./modals/PizzaCalculatorModal";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Table } from "react-bootstrap";
|
||||
import { Order, PizzaDayState, PizzaOrder } from "../../../types";
|
||||
import { Order, PizzaDayState, PizzaOrder } from "../types";
|
||||
import PizzaOrderRow from "./PizzaOrderRow";
|
||||
import { updatePizzaFee } from "../api/PizzaDayApi";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { useState } from "react";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faMoneyBill1, faTrashCan } from "@fortawesome/free-regular-svg-icons";
|
||||
import { useAuth } from "../context/auth";
|
||||
import { Order, PizzaDayState, PizzaOrder } from "../../../types";
|
||||
import { Order, PizzaDayState, PizzaOrder } from "../types";
|
||||
import PizzaAdditionalFeeModal from "./modals/PizzaAdditionalFeeModal";
|
||||
|
||||
type Props = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Modal, Button, Form } from "react-bootstrap"
|
||||
import { FeatureRequest } from "../../../../types";
|
||||
import { FeatureRequest } from "../../types";
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { getEasterEgg } from "../api/EasterEggApi";
|
||||
import { AuthContextProps } from "./auth";
|
||||
import { EasterEgg } from "../../../types";
|
||||
import { EasterEgg } from "../types";
|
||||
|
||||
export const useEasterEgg = (auth?: AuthContextProps | null): [EasterEgg | undefined, boolean] => {
|
||||
const [result, setResult] = useState<EasterEgg | undefined>();
|
||||
|
||||
4
server/.gitignore
vendored
4
server/.gitignore
vendored
@@ -1,5 +1,7 @@
|
||||
/node_modules
|
||||
/dist
|
||||
/resources/easterEggs
|
||||
data.json
|
||||
.env.production
|
||||
.env.development
|
||||
.easter-eggs.json
|
||||
/resources/easterEggs
|
||||
@@ -100,11 +100,9 @@ app.use("/api/", (req, res, next) => {
|
||||
const emailHeader = req.header('remote-email');
|
||||
if (userHeader !== undefined && nameHeader !== undefined) {
|
||||
const remoteName = Buffer.from(nameHeader, 'latin1').toString();
|
||||
if (ENVIRONMENT !== "production"){
|
||||
console.log("Tvuj username, name a email: %s, %s, %s.", userHeader, remoteName, emailHeader);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!req.headers.authorization) {
|
||||
return res.status(401).json({ error: 'Nebyl předán autentizační token' });
|
||||
}
|
||||
|
||||
@@ -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': [
|
||||
[
|
||||
{
|
||||
@@ -517,91 +515,7 @@ const MOCK_DATA = {
|
||||
isSoup: false,
|
||||
}
|
||||
],
|
||||
],
|
||||
'senkSerikova': [
|
||||
[
|
||||
{
|
||||
amount: "-",
|
||||
name: "Drůbeží vývar s masem a nudlemi",
|
||||
price: "45\xA0Kč",
|
||||
isSoup: true,
|
||||
},
|
||||
{
|
||||
amount: "-",
|
||||
name: "Vepřová pečeně se zelím a houskovým knedlíkem",
|
||||
price: "155\xA0Kč",
|
||||
isSoup: false,
|
||||
},
|
||||
{
|
||||
amount: "-",
|
||||
name: "Špagety s kuřecím masem, špenátem a smetanou",
|
||||
price: "145\xA0Kč",
|
||||
isSoup: false,
|
||||
},
|
||||
{
|
||||
amount: "-",
|
||||
name: "Medailonky z vepřové panenky s fazolkami se slaninou, šťouchané brambory",
|
||||
price: "185\xA0Kč",
|
||||
isSoup: false,
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
amount: "-",
|
||||
name: "Mrkvová polévka se zázvorem a kokosovým mlékem",
|
||||
price: "45\xA0Kč",
|
||||
isSoup: true,
|
||||
},
|
||||
{
|
||||
amount: "-",
|
||||
name: "Hovězí po Burgundsku, bramborová kaše",
|
||||
price: "155\xA0Kč",
|
||||
isSoup: false,
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
amount: "-",
|
||||
name: "Hovězí vývar s játrovými knedlíčky",
|
||||
price: "45\xA0Kč",
|
||||
isSoup: true,
|
||||
},
|
||||
{
|
||||
amount: "-",
|
||||
name: "Kuřecí plátky na sušených rajčatech, bylinkách a česneku, bramborová kaše",
|
||||
price: "155\xA0Kč",
|
||||
isSoup: false,
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
amount: "-",
|
||||
name: "Kuřecí vývar s rýží",
|
||||
price: "45\xA0Kč",
|
||||
isSoup: true,
|
||||
},
|
||||
{
|
||||
amount: "-",
|
||||
name: "Rajská s plněnou paprikou, knedlík",
|
||||
price: "170\xA0Kč",
|
||||
isSoup: false,
|
||||
}
|
||||
],
|
||||
[
|
||||
{
|
||||
amount: "-",
|
||||
name: "Mexická fazolová polévka",
|
||||
price: "45\xA0Kč",
|
||||
isSoup: true,
|
||||
},
|
||||
{
|
||||
amount: "-",
|
||||
name: "Ragú z trhané kachny, onsen vejce, soté ze špenátu a ředkvičky, bramborové pyré, lanýžová sůl, zelený olej",
|
||||
price: "189\xA0Kč",
|
||||
isSoup: false,
|
||||
}
|
||||
],
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
// Mockovací data pro Pizza day
|
||||
@@ -1358,7 +1272,7 @@ const MOCK_PIZZA_LIST = [
|
||||
* Funkce vrací mock datu ve formátu YYYY-MM-DD
|
||||
*/
|
||||
export const getTodayMock = (): Date => {
|
||||
return new Date('2025-01-10'); // pátek
|
||||
return new Date('2025-01-08'); // pátek
|
||||
}
|
||||
|
||||
export const getMenuSladovnickaMock = () => {
|
||||
@@ -1377,10 +1291,6 @@ export const getMenuZastavkaUmichalaMock = () => {
|
||||
return MOCK_DATA['zastavkaUmichala'];
|
||||
}
|
||||
|
||||
export const getMenuSenkSerikovaMock = () => {
|
||||
return MOCK_DATA['senkSerikova'];
|
||||
}
|
||||
|
||||
export const getPizzaListMock = () => {
|
||||
return MOCK_PIZZA_LIST;
|
||||
}
|
||||
@@ -1,58 +1,58 @@
|
||||
/** Notifikace */
|
||||
import {ClientData, Locations, NotififaceInput} from '../../types';
|
||||
import axios from 'axios';
|
||||
/** Notifikace pro gotify*/
|
||||
import { ClientData, GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
|
||||
import axios, { AxiosError } from 'axios';
|
||||
import dotenv from 'dotenv';
|
||||
import path from 'path';
|
||||
import { getToday } from "./service";
|
||||
import {formatDate, getUsersByLocation, getHumanTime} from "./utils";
|
||||
import { formatDate, getUsersByLocation } from "./utils";
|
||||
import getStorage from "./storage";
|
||||
|
||||
const storage = getStorage();
|
||||
const ENVIRONMENT = process.env.NODE_ENV || 'production'
|
||||
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
|
||||
|
||||
// const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
|
||||
// const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
|
||||
// export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
|
||||
// if (!Array.isArray(gotifyServers)) {
|
||||
// return []
|
||||
// }
|
||||
// const urls = gotifyServers.flatMap(gotifyServer =>
|
||||
// gotifyServer.api_keys.map(apiKey => `${gotifyServer.server}/message?token=${apiKey}`));
|
||||
//
|
||||
// const dataPayload = {
|
||||
// title: "Luncher",
|
||||
// message: `${data.udalost} - spustil:${data.user}`,
|
||||
// priority: 7,
|
||||
// };
|
||||
//
|
||||
// const headers = { "Content-Type": "application/json" };
|
||||
//
|
||||
// const promises = urls.map(url =>
|
||||
// axios.post(url, dataPayload, { headers }).then(response => {
|
||||
// response.data = {
|
||||
// success: true,
|
||||
// message: "Notifikace doručena",
|
||||
// };
|
||||
// return response;
|
||||
// }).catch(error => {
|
||||
// if (axios.isAxiosError(error)) {
|
||||
// const axiosError = error as AxiosError;
|
||||
// if (axiosError.response) {
|
||||
// axiosError.response.data = {
|
||||
// success: false,
|
||||
// message: "fail",
|
||||
// };
|
||||
// console.log(error)
|
||||
// return axiosError.response;
|
||||
// }
|
||||
// }
|
||||
// // Handle unknown error without a response
|
||||
// console.log(error, "unknown error");
|
||||
// })
|
||||
// );
|
||||
// return promises;
|
||||
// };
|
||||
const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
|
||||
const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
|
||||
export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
|
||||
if (!Array.isArray(gotifyServers)) {
|
||||
return []
|
||||
}
|
||||
const urls = gotifyServers.flatMap(gotifyServer =>
|
||||
gotifyServer.api_keys.map(apiKey => `${gotifyServer.server}/message?token=${apiKey}`));
|
||||
|
||||
const dataPayload = {
|
||||
title: "Luncher",
|
||||
message: `${data.udalost} - spustil:${data.user}`,
|
||||
priority: 7,
|
||||
};
|
||||
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
|
||||
const promises = urls.map(url =>
|
||||
axios.post(url, dataPayload, { headers }).then(response => {
|
||||
response.data = {
|
||||
success: true,
|
||||
message: "Notifikace doručena",
|
||||
};
|
||||
return response;
|
||||
}).catch(error => {
|
||||
if (axios.isAxiosError(error)) {
|
||||
const axiosError = error as AxiosError;
|
||||
if (axiosError.response) {
|
||||
axiosError.response.data = {
|
||||
success: false,
|
||||
message: "fail",
|
||||
};
|
||||
console.log(error)
|
||||
return axiosError.response;
|
||||
}
|
||||
}
|
||||
// Handle unknown error without a response
|
||||
console.log(error, "unknown error");
|
||||
})
|
||||
);
|
||||
return promises;
|
||||
};
|
||||
|
||||
export const ntfyCall = async (data: NotififaceInput) => {
|
||||
const url = process.env.NTFY_HOST
|
||||
@@ -72,10 +72,10 @@ export const ntfyCall = async (data: NotififaceInput) => {
|
||||
}
|
||||
const today = formatDate(getToday());
|
||||
let clientData: ClientData = await storage.getData(today);
|
||||
const usersByLocation = getUsersByLocation(clientData.choices, data.user)
|
||||
const userByCLocation = getUsersByLocation(clientData.choices, data.user)
|
||||
|
||||
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
|
||||
const promises = usersByLocation.map(async user => {
|
||||
const promises = userByCLocation.map(async user => {
|
||||
try {
|
||||
// Odstraníme mezery a diakritiku a převedeme na lowercase
|
||||
const topic = user.normalize('NFD').replace(' ', '').replace(/[\u0300-\u036f]/g, '').toLowerCase();
|
||||
@@ -97,64 +97,27 @@ export const ntfyCall = async (data: NotififaceInput) => {
|
||||
return promises;
|
||||
|
||||
}
|
||||
|
||||
export const teamsCall = async (data: NotififaceInput) => {
|
||||
const url = process.env.TEAMS_WEBHOOK_URL;
|
||||
if (!url) {
|
||||
console.log("TEAMS_WEBHOOK_URL není definován v env")
|
||||
return
|
||||
}
|
||||
const title = data.udalost;
|
||||
// const today = formatDate(getToday());
|
||||
// let clientData: ClientData = await storage.getData(today);
|
||||
// const usersByLocation = getUsersByLocation(clientData.choices, data.user)
|
||||
let location = data.locationKey ? ` odcházíme do ${Locations[data.locationKey] ?? ''}` : ' jdeme na oběd';
|
||||
const message = 'V ' + getHumanTime(getToday()) + location;
|
||||
const card = {
|
||||
'@type': 'MessageCard',
|
||||
'@context': 'http://schema.org/extensions',
|
||||
'themeColor': "0072C6", // light blue
|
||||
summary: 'Summary description',
|
||||
sections: [
|
||||
{
|
||||
activityTitle: title,
|
||||
text: message,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
if (!url) {
|
||||
console.log("TEAMS_WEBHOOK_URL není definován v env")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await axios.post(url, card, {
|
||||
headers: {
|
||||
'content-type': 'application/vnd.microsoft.teams.card.o365connector'
|
||||
},
|
||||
});
|
||||
return `${response.status} - ${response.statusText}`;
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Zavolá notifikace na všechny konfigurované způsoby notifikace, přetížení proměných na false pro jednotlivé způsoby je vypne*/
|
||||
export const callNotifikace = async (input: NotififaceInput) => {
|
||||
export const callNotifikace = async ({ input, teams = true, gotify = false, ntfy = true }: NotifikaceData) => {
|
||||
const notifications = [];
|
||||
|
||||
if (ntfy) {
|
||||
const ntfyPromises = await ntfyCall(input);
|
||||
if (ntfyPromises) {
|
||||
notifications.push(...ntfyPromises);
|
||||
}
|
||||
const teamsPromises = await teamsCall(input);
|
||||
if (teamsPromises) {
|
||||
notifications.push(teamsPromises);
|
||||
}
|
||||
// gotify bych řekl, že už je deprecated
|
||||
// const gotifyPromises = await gotifyCall(input, gotifyData);
|
||||
// notifications.push(...gotifyPromises);
|
||||
/* Zatím není
|
||||
if (teams) {
|
||||
notifications.push(teamsCall(input));
|
||||
}*/
|
||||
|
||||
// Add more notifications as necessary
|
||||
|
||||
//gotify bych řekl, že už je deprecated
|
||||
if (gotify) {
|
||||
const gotifyPromises = await gotifyCall(input, gotifyData);
|
||||
notifications.push(...gotifyPromises);
|
||||
}
|
||||
|
||||
try {
|
||||
const results = await Promise.all(notifications);
|
||||
|
||||
@@ -52,7 +52,7 @@ export async function createPizzaDay(creator: string): Promise<ClientData> {
|
||||
const pizzaList = await getPizzaList();
|
||||
const data: ClientData = { pizzaDay: { state: PizzaDayState.CREATED, creator, orders: [] }, pizzaList, ...clientData };
|
||||
await storage.setData(today, data);
|
||||
callNotifikace({ udalost: UdalostEnum.ZAHAJENA_PIZZA, user: creator })
|
||||
callNotifikace({ input: { udalost: UdalostEnum.ZAHAJENA_PIZZA, user: creator } })
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ export async function finishPizzaOrder(login: string) {
|
||||
}
|
||||
clientData.pizzaDay.state = PizzaDayState.ORDERED;
|
||||
await storage.setData(today, clientData);
|
||||
callNotifikace({ udalost: UdalostEnum.OBJEDNANA_PIZZA, user: clientData?.pizzaDay?.creator })
|
||||
callNotifikace({ input: { udalost: UdalostEnum.OBJEDNANA_PIZZA, user: clientData?.pizzaDay?.creator } })
|
||||
return clientData;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import axios from "axios";
|
||||
import { load } from 'cheerio';
|
||||
import { Food } from "../../types";
|
||||
import {getMenuSladovnickaMock, getMenuTechTowerMock, getMenuUMotlikuMock, getMenuZastavkaUmichalaMock, getMenuSenkSerikovaMock} from "./mock";
|
||||
import {formatDate} from "./utils";
|
||||
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 = [
|
||||
@@ -70,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();
|
||||
}
|
||||
@@ -79,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);
|
||||
@@ -97,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: "",
|
||||
@@ -344,16 +345,13 @@ export const getMenuZastavkaUmichala = async (firstDayOfWeek: Date, mock: boolea
|
||||
}
|
||||
|
||||
const nowDate = new Date().getDate();
|
||||
const headers = {
|
||||
"Cookie": "_nss=1; PHPSESSID=9e37de17e0326b0942613d6e67a30e69",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36",
|
||||
};
|
||||
const result: Food[][] = [];
|
||||
for (let dayIndex = 0; dayIndex < 5; dayIndex++) {
|
||||
const currentDate = new Date(firstDayOfWeek);
|
||||
currentDate.setDate(firstDayOfWeek.getDate() + dayIndex);
|
||||
|
||||
if (currentDate.getDate() < nowDate || (currentDate.getDate() === nowDate && new Date().getHours() >= 14)) {
|
||||
// if (currentDate < now) {
|
||||
if (currentDate.getDate() !== nowDate) {
|
||||
result[dayIndex] = [{
|
||||
amount: undefined,
|
||||
name: "Pro tento den není uveřejněna nabídka jídel",
|
||||
@@ -362,13 +360,13 @@ export const getMenuZastavkaUmichala = async (firstDayOfWeek: Date, mock: boolea
|
||||
}];
|
||||
continue;
|
||||
} else {
|
||||
const url = (currentDate.getDate() === nowDate) ?
|
||||
ZASTAVKAUMICHALA_URL : ZASTAVKAUMICHALA_URL + '/?do=dailyMenu-changeDate&dailyMenu-dateString=' + formatDate(currentDate, 'DD.MM.YYYY');
|
||||
const html = await axios.get(url, {
|
||||
headers,
|
||||
}).then(res => res.data).then(content => content);
|
||||
// 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({
|
||||
@@ -383,52 +381,3 @@ export const getMenuZastavkaUmichala = async (firstDayOfWeek: Date, mock: boolea
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Získá obědovou nabídku SenkSerikova 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 getMenuSenkSerikova = async (firstDayOfWeek: Date, mock: boolean = false): Promise<Food[][]> => {
|
||||
if (mock) {
|
||||
return getMenuSenkSerikovaMock();
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder('windows-1250');
|
||||
const html = await axios.get(SENKSERIKOVA_URL, {
|
||||
responseType: 'arraybuffer',
|
||||
responseEncoding: 'binary'
|
||||
}).then(res => decoder.decode(new Uint8Array(res.data))).then(content => content);
|
||||
const $ = load(html);
|
||||
|
||||
const nowDate = new Date().getDate();
|
||||
const currentDate = new Date(firstDayOfWeek);
|
||||
const result: Food[][] = [];
|
||||
let dayIndex = 0;
|
||||
while(currentDate.getDate() < nowDate) {
|
||||
result[dayIndex] = [{
|
||||
amount: undefined,
|
||||
name: "Pro tento den není uveřejněna nabídka jídel",
|
||||
price: "",
|
||||
isSoup: false,
|
||||
}];
|
||||
dayIndex = dayIndex + 1;
|
||||
currentDate.setDate(firstDayOfWeek.getDate() + dayIndex);
|
||||
}
|
||||
|
||||
$('.menicka').each((i, element) => {
|
||||
const currentDayFood: Food[] = [];
|
||||
$(element).find('.popup-gallery li').each((j, element) => {
|
||||
currentDayFood.push({
|
||||
amount: '-',
|
||||
name: $(element).children('div.polozka').text(),
|
||||
price: $(element).children('div.cena').text().replace(/ /g, '\xA0'),
|
||||
isSoup: $(element).hasClass('polevka'),
|
||||
});
|
||||
});
|
||||
result[dayIndex++] = currentDayFood;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -4,16 +4,7 @@ import { addChoice, addVolatileData, getDateForWeekIndex, getToday, removeChoice
|
||||
import { getDayOfWeekIndex, parseToken } from "../utils";
|
||||
import { getWebsocket } from "../websocket";
|
||||
import { callNotifikace } from "../notifikace";
|
||||
import {
|
||||
AddChoiceRequest,
|
||||
ChangeDepartureTimeRequest,
|
||||
IDayIndex,
|
||||
JdemeObedRequest,
|
||||
RemoveChoiceRequest,
|
||||
RemoveChoicesRequest,
|
||||
UdalostEnum,
|
||||
UpdateNoteRequest
|
||||
} 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ň
|
||||
@@ -142,10 +133,10 @@ router.post("/changeDepartureTime", async (req: Request<{}, any, ChangeDeparture
|
||||
} catch (e: any) { next(e) }
|
||||
});
|
||||
|
||||
router.post("/jdemeObed", async (req: Request<{}, any, JdemeObedRequest>, res, next) => {
|
||||
router.post("/jdemeObed", async (req, res, next) => {
|
||||
const login = getLogin(parseToken(req));
|
||||
try {
|
||||
await callNotifikace({ user: login, udalost: UdalostEnum.JDEME_OBED, locationKey: req.body.locationKey });
|
||||
await callNotifikace({ input: { user: login, udalost: UdalostEnum.JDEME_OBED }, gotify: false })
|
||||
res.status(200).json({});
|
||||
} catch (e: any) { next(e) }
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { InsufficientPermissions, formatDate, getDayOfWeekIndex, getFirstWorkDayOfWeek, getHumanDate, getIsWeekend, getWeekNumber } from "./utils";
|
||||
import { ClientData, Restaurants, DayMenu, DepartureTime, DayData, WeekMenu, LocationKey } from "../../types";
|
||||
import { ClientData, Restaurants, RestaurantDailyMenu, DepartureTime, DayData, WeekMenu, LocationKey, DayOfWeekIndex, daysOfWeeksIndices, DayOfWeekEnum, DayOfWeek } from "../../types";
|
||||
import getStorage from "./storage";
|
||||
import { getMenuSladovnicka, getMenuTechTower, getMenuUMotliku, getMenuZastavkaUmichala, getMenuSenkSerikova } from "./restaurants";
|
||||
import { getMenuSladovnicka, getMenuTechTower, getMenuUMotliku, getMenuZastavkaUmichala } from "./restaurants";
|
||||
import { getTodayMock } from "./mock";
|
||||
|
||||
const storage = getStorage();
|
||||
@@ -62,7 +62,6 @@ export async function getData(date?: Date): Promise<ClientData> {
|
||||
// [Restaurants.UMOTLIKU]: await getRestaurantMenu(Restaurants.UMOTLIKU, date),
|
||||
[Restaurants.TECHTOWER]: await getRestaurantMenu(Restaurants.TECHTOWER, date),
|
||||
[Restaurants.ZASTAVKAUMICHALA]: await getRestaurantMenu(Restaurants.ZASTAVKAUMICHALA, date),
|
||||
[Restaurants.SENKSERIKOVA]: await getRestaurantMenu(Restaurants.SENKSERIKOVA, date),
|
||||
}
|
||||
clientData = await addVolatileData(clientData);
|
||||
return clientData;
|
||||
@@ -98,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();
|
||||
@@ -112,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] = {};
|
||||
}
|
||||
@@ -125,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);
|
||||
@@ -132,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í...
|
||||
@@ -183,19 +193,6 @@ export async function getRestaurantMenu(restaurant: Restaurants, date?: Date): P
|
||||
} catch (e: any) {
|
||||
console.error("Selhalo načtení jídel pro podnik Zastávka u Michala", e);
|
||||
}
|
||||
case Restaurants.SENKSERIKOVA:
|
||||
try {
|
||||
const senkSerikovaFood = await getMenuSenkSerikova(firstDay, mock);
|
||||
for (let i = 0; i < senkSerikovaFood.length; i++) {
|
||||
menus[i][restaurant]!.food = senkSerikovaFood[i];
|
||||
if (senkSerikovaFood[i]?.length === 1 && senkSerikovaFood[i][0].name === 'Pro tento den nebylo zadáno menu.') {
|
||||
menus[i][restaurant]!.closed = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
} catch (e: any) {
|
||||
console.error("Selhalo načtení jídel pro podnik Pivovarský šenk Šeříková", e);
|
||||
}
|
||||
}
|
||||
await storage.setData(getMenuKey(usedDate), menus);
|
||||
}
|
||||
@@ -268,19 +265,14 @@ export async function removeChoice(login: string, trusted: boolean, locationKey:
|
||||
}
|
||||
|
||||
/**
|
||||
* Odstraní kompletně volbu uživatele, vyjma ignoredLocationKey (pokud byla předána a existuje).
|
||||
* Odstraní kompletně volbu uživatele.
|
||||
*
|
||||
* @param login login uživatele
|
||||
* @param date datum, ke kterému se volby vztahují
|
||||
* @param ignoredLocationKey volba, která nebude odstraněna, pokud existuje
|
||||
*/
|
||||
async function removeChoiceIfPresent(login: string, date: string, ignoredLocationKey?: LocationKey) {
|
||||
async function removeChoiceIfPresent(login: string, date: string) {
|
||||
let data: DayData = await storage.getData(date);
|
||||
for (const key of Object.keys(data.choices)) {
|
||||
const locationKey = key as LocationKey;
|
||||
if (ignoredLocationKey != null && ignoredLocationKey == locationKey) {
|
||||
continue;
|
||||
}
|
||||
if (data.choices[locationKey] && login in data.choices[locationKey]) {
|
||||
delete data.choices[locationKey][login];
|
||||
if (Object.keys(data.choices[locationKey]).length === 0) {
|
||||
@@ -334,9 +326,6 @@ export async function addChoice(login: string, trusted: boolean, locationKey: Lo
|
||||
// Pokud měníme pouze lokaci, mažeme případné předchozí
|
||||
if (foodIndex == null) {
|
||||
data = await removeChoiceIfPresent(login, selectedDate);
|
||||
} else {
|
||||
// Mažeme případné ostatní volby (měla by být maximálně jedna)
|
||||
removeChoiceIfPresent(login, selectedDate, locationKey);
|
||||
}
|
||||
// TODO vytáhnout inicializaci "prázdné struktury" do vlastní funkce
|
||||
if (!(data.choices[locationKey])) {
|
||||
|
||||
@@ -1,17 +1,8 @@
|
||||
import JSONdb from 'simple-json-db';
|
||||
import { StorageInterface } from "./StorageInterface";
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
const dbPath = path.resolve(__dirname, '../../data/db.json');
|
||||
const dbDir = path.dirname(dbPath);
|
||||
const db = new JSONdb('./data.json');
|
||||
|
||||
// Zajistěte, že adresář existuje
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
const db = new JSONdb(dbPath);
|
||||
/**
|
||||
* Implementace úložiště používající JSON soubor.
|
||||
*/
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Choices, LocationKey } from "../../types";
|
||||
import { Choices, DayOfWeekIndex, LocationKey } from "../../types";
|
||||
|
||||
/** Vrátí datum v ISO formátu. */
|
||||
export function formatDate(date: Date, format?: string) {
|
||||
@@ -32,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. */
|
||||
|
||||
@@ -18,8 +18,6 @@ export type RemoveChoiceRequest = IDayIndex & ILocationKey & {
|
||||
foodIndex: number,
|
||||
}
|
||||
|
||||
export type JdemeObedRequest = ILocationKey;
|
||||
|
||||
export type UpdateNoteRequest = IDayIndex & {
|
||||
note?: string,
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ export enum Restaurants {
|
||||
// UMOTLIKU = 'uMotliku',
|
||||
TECHTOWER = 'techTower',
|
||||
ZASTAVKAUMICHALA = 'zastavkaUmichala',
|
||||
SENKSERIKOVA = 'senkSerikova',
|
||||
}
|
||||
|
||||
export type FoodChoices = {
|
||||
@@ -71,20 +70,36 @@ 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 type WeekMenu = {
|
||||
[dayIndex: number]: {
|
||||
[restaurant in Restaurants]?: DayMenu
|
||||
}
|
||||
[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 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
|
||||
@@ -92,11 +107,11 @@ export type DayData = {
|
||||
|
||||
/** Veškerá data pro zobrazení na klientovi. */
|
||||
export type ClientData = DayData & {
|
||||
todayWeekIndex?: number, // index dnešního dne v týdnu (0-6)
|
||||
todayWeekIndex?: DayOfWeekIndex, // index dnešního dne v týdnu (0-6)
|
||||
}
|
||||
|
||||
/** Nabídka jídel jednoho podniku pro jeden konkrétní den. */
|
||||
export type 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
|
||||
@@ -111,13 +126,11 @@ export type Food = {
|
||||
}
|
||||
|
||||
// TODO tohle je dost špatné pojmenování, vzhledem k tomu co to obsahuje
|
||||
// TODO pokud by se použilo ovládáni výběru obědu kliknutím, pak bych restaurace z tohoto výčtu vyhodil
|
||||
export enum Locations {
|
||||
SLADOVNICKA = 'Sladovnická',
|
||||
// UMOTLIKU = 'U Motlíků',
|
||||
TECHTOWER = 'TechTower',
|
||||
ZASTAVKAUMICHALA = 'Zastávka u Michala',
|
||||
SENKSERIKOVA = 'Pivovarský šenk Šeříková',
|
||||
SPSE = 'SPŠE',
|
||||
PIZZA = 'Pizza day',
|
||||
OBJEDNAVAM = 'Budu objednávat',
|
||||
@@ -131,15 +144,21 @@ export type LocationKey = keyof typeof Locations;
|
||||
export enum UdalostEnum {
|
||||
ZAHAJENA_PIZZA = "Zahájen pizza day",
|
||||
OBJEDNANA_PIZZA = "Objednána pizza",
|
||||
JDEME_OBED = "Jdeme na oběd",
|
||||
JDEME_OBED = "Jdeme oběd",
|
||||
}
|
||||
|
||||
export type NotififaceInput = {
|
||||
locationKey?: LocationKey,
|
||||
udalost: UdalostEnum,
|
||||
user: string,
|
||||
}
|
||||
|
||||
export type NotifikaceData = {
|
||||
input: NotififaceInput,
|
||||
gotify?: boolean,
|
||||
teams?: boolean,
|
||||
ntfy?: boolean,
|
||||
}
|
||||
|
||||
export type GotifyServer = {
|
||||
server: string;
|
||||
api_keys: string[];
|
||||
|
||||
Reference in New Issue
Block a user