Compare commits
13 Commits
c311cc2fd7
...
feat/jdeme
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f39d04120 | ||
|
|
8137ca6fc0 | ||
|
|
3817126ac0 | ||
|
|
c1856b2eee | ||
|
|
eaf0bc353d | ||
| ff650ec3b8 | |||
| f8aa293413 | |||
| cafcd0a467 | |||
| 9e247eb2a1 | |||
| 469a6b9031 | |||
|
|
89dec1c194 | ||
|
|
f3af64923c | ||
|
|
44b09a9d1a |
22
.gitignore
vendored
22
.gitignore
vendored
@@ -1,23 +1 @@
|
|||||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
|
||||||
|
|
||||||
# dependencies
|
|
||||||
node_modules
|
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*
|
|
||||||
|
|||||||
56
.woodpecker/workflow.yaml
Normal file
56
.woodpecker/workflow.yaml
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
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,7 +54,6 @@ WORKDIR /app
|
|||||||
# Vykopírování sestaveného serveru
|
# Vykopírování sestaveného serveru
|
||||||
COPY --from=builder /build/server/node_modules ./server/node_modules
|
COPY --from=builder /build/server/node_modules ./server/node_modules
|
||||||
COPY --from=builder /build/server/dist ./
|
COPY --from=builder /build/server/dist ./
|
||||||
COPY server/resources ./server/resources
|
|
||||||
|
|
||||||
# Vykopírování sestaveného klienta
|
# Vykopírování sestaveného klienta
|
||||||
COPY --from=builder /build/client/dist ./public
|
COPY --from=builder /build/client/dist ./public
|
||||||
@@ -63,8 +62,10 @@ COPY --from=builder /build/client/dist ./public
|
|||||||
COPY /server/.env.production ./server/src
|
COPY /server/.env.production ./server/src
|
||||||
|
|
||||||
# Zkopírování konfigurace easter eggů
|
# Zkopírování konfigurace easter eggů
|
||||||
# TODO tohle spadne když nebude existovat!
|
RUN if [ -f /server/.easter-eggs.json ]; then cp /server/.easter-eggs.json ./server/; fi
|
||||||
COPY /server/.easter-eggs.json ./server/
|
|
||||||
|
# Export /data/db.json do složky /data
|
||||||
|
VOLUME ["/data"]
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|
||||||
|
|||||||
21
Dockerfile-Woodpecker
Normal file
21
Dockerfile-Woodpecker
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
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,3 +1,2 @@
|
|||||||
build
|
build
|
||||||
dist
|
dist
|
||||||
src/types
|
|
||||||
@@ -189,6 +189,13 @@ function App() {
|
|||||||
}
|
}
|
||||||
}, [auth?.login, easterEgg?.duration, easterEgg?.url, eggImage]);
|
}, [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 doAddChoice = async (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
const locationKey = event.target.value as LocationKey;
|
const locationKey = event.target.value as LocationKey;
|
||||||
if (auth?.login) {
|
if (auth?.login) {
|
||||||
@@ -199,9 +206,9 @@ function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const doJdemeObed = async () => {
|
const doJdemeObed = async (locationKey: LocationKey) => {
|
||||||
if (auth?.login) {
|
if (auth?.login) {
|
||||||
await jdemeObed();
|
await jdemeObed(locationKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -331,15 +338,16 @@ function App() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const renderFoodTable = (name: string, menu: DayMenu) => {
|
const renderFoodTable = (location: Locations, menu: DayMenu) => {
|
||||||
let content;
|
let content;
|
||||||
if (menu?.closed) {
|
if (menu?.closed) {
|
||||||
content = <h3>Zavřeno</h3>
|
content = <h3>Zavřeno</h3>
|
||||||
} else if (menu?.food?.length > 0) {
|
} else if (menu?.food?.length > 0) {
|
||||||
|
const hideSoups = settings?.hideSoups;
|
||||||
content = <Table striped bordered hover>
|
content = <Table striped bordered hover>
|
||||||
<tbody>
|
<tbody style={{ cursor: 'pointer' }}>
|
||||||
{menu.food.filter(f => (settings?.hideSoups ? !f.isSoup : true)).map((f: any, index: number) =>
|
{menu.food.filter(f => (hideSoups ? !f.isSoup : true)).map((f: any, index: number) =>
|
||||||
<tr key={index}>
|
<tr key={index} onClick={() => doAddClickFoodChoice(location, hideSoups ? index + 1 : index)}>
|
||||||
<td>{f.amount}</td>
|
<td>{f.amount}</td>
|
||||||
<td>{f.name}</td>
|
<td>{f.name}</td>
|
||||||
<td>{f.price}</td>
|
<td>{f.price}</td>
|
||||||
@@ -351,7 +359,7 @@ function App() {
|
|||||||
content = <h3>Chyba načtení dat</h3>
|
content = <h3>Chyba načtení dat</h3>
|
||||||
}
|
}
|
||||||
return <Col md={12} lg={3} className='mt-3'>
|
return <Col md={12} lg={3} className='mt-3'>
|
||||||
<h3>{name}</h3>
|
<h3 style={{ cursor: 'pointer' }} onClick={() => doAddClickFoodChoice(location, undefined)}>{location}</h3>
|
||||||
{menu?.lastUpdate && <small>Poslední aktualizace: {getHumanDateTime(new Date(menu.lastUpdate))}</small>}
|
{menu?.lastUpdate && <small>Poslední aktualizace: {getHumanDateTime(new Date(menu.lastUpdate))}</small>}
|
||||||
{content}
|
{content}
|
||||||
</Col>
|
</Col>
|
||||||
@@ -401,8 +409,8 @@ function App() {
|
|||||||
<img src='snowman.png' style={{ position: "absolute", height: "110px", right: 10, top: 5 }} />
|
<img src='snowman.png' style={{ position: "absolute", height: "110px", right: 10, top: 5 }} />
|
||||||
Poslední změny:
|
Poslední změny:
|
||||||
<ul>
|
<ul>
|
||||||
<li>Přidání restaurace Zastávka u Michala</li>
|
<li>Přidání restaurací Zastávka u Michala a Pivovarský šenk Šeříková</li>
|
||||||
<li>Přidání restaurace Pivovarský šenk Šeříková</li>
|
<li>Možnost výběru restaurace a jídel kliknutím v tabulce</li>
|
||||||
</ul>
|
</ul>
|
||||||
</Alert>
|
</Alert>
|
||||||
{dayIndex != null &&
|
{dayIndex != null &&
|
||||||
@@ -413,11 +421,11 @@ function App() {
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<Row className='food-tables'>
|
<Row className='food-tables'>
|
||||||
{food[Restaurants.SLADOVNICKA] && renderFoodTable('Sladovnická', food[Restaurants.SLADOVNICKA])}
|
{food[Restaurants.SLADOVNICKA] && renderFoodTable(Locations.SLADOVNICKA, food[Restaurants.SLADOVNICKA])}
|
||||||
{/* {food[Restaurants.UMOTLIKU] && renderFoodTable('U Motlíků', food[Restaurants.UMOTLIKU])} */}
|
{/* {food[Restaurants.UMOTLIKU] && renderFoodTable(food[Restaurants.UMOTLIKU])} */}
|
||||||
{food[Restaurants.TECHTOWER] && renderFoodTable('TechTower', food[Restaurants.TECHTOWER])}
|
{food[Restaurants.TECHTOWER] && renderFoodTable(Locations.TECHTOWER, food[Restaurants.TECHTOWER])}
|
||||||
{food[Restaurants.ZASTAVKAUMICHALA] && renderFoodTable('Zastávka u Michala', food[Restaurants.ZASTAVKAUMICHALA])}
|
{food[Restaurants.ZASTAVKAUMICHALA] && renderFoodTable(Locations.ZASTAVKAUMICHALA, food[Restaurants.ZASTAVKAUMICHALA])}
|
||||||
{food[Restaurants.SENKSERIKOVA] && renderFoodTable('Pivovarský šenk Šeříková', food[Restaurants.SENKSERIKOVA])}
|
{food[Restaurants.SENKSERIKOVA] && renderFoodTable(Locations.SENKSERIKOVA, food[Restaurants.SENKSERIKOVA])}
|
||||||
</Row>
|
</Row>
|
||||||
<div className='content-wrapper'>
|
<div className='content-wrapper'>
|
||||||
<div className='content'>
|
<div className='content'>
|
||||||
@@ -463,6 +471,7 @@ function App() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const locationLoginList = Object.entries(loginObject);
|
const locationLoginList = Object.entries(loginObject);
|
||||||
|
const disabled = false;
|
||||||
return (
|
return (
|
||||||
<tr key={key}>
|
<tr key={key}>
|
||||||
<td>{locationName}</td>
|
<td>{locationName}</td>
|
||||||
@@ -511,6 +520,9 @@ function App() {
|
|||||||
</tbody>
|
</tbody>
|
||||||
</Table>
|
</Table>
|
||||||
</td>
|
</td>
|
||||||
|
<td>
|
||||||
|
<Button onClick={() => doJdemeObed(locationKey)} disabled={false}>Jdeme na oběd</Button>
|
||||||
|
</td>
|
||||||
</tr>)
|
</tr>)
|
||||||
}
|
}
|
||||||
)}
|
)}
|
||||||
@@ -534,7 +546,6 @@ function App() {
|
|||||||
setLoadingPizzaDay(true);
|
setLoadingPizzaDay(true);
|
||||||
await createPizzaDay().then(() => setLoadingPizzaDay(false));
|
await createPizzaDay().then(() => setLoadingPizzaDay(false));
|
||||||
}}>Založit Pizza day</Button>
|
}}>Založit Pizza day</Button>
|
||||||
<Button onClick={doJdemeObed} style={{ marginLeft: "14px" }}>Jdeme na oběd !</Button>
|
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
import { AddChoiceRequest, ChangeDepartureTimeRequest, LocationKey, RemoveChoiceRequest, RemoveChoicesRequest, UpdateNoteRequest } from "../../../types";
|
import {
|
||||||
|
AddChoiceRequest,
|
||||||
|
ChangeDepartureTimeRequest,
|
||||||
|
JdemeObedRequest,
|
||||||
|
LocationKey,
|
||||||
|
RemoveChoiceRequest,
|
||||||
|
RemoveChoicesRequest,
|
||||||
|
UpdateNoteRequest
|
||||||
|
} from "../../../types";
|
||||||
import { api } from "./Api";
|
import { api } from "./Api";
|
||||||
|
|
||||||
const FOOD_API_PREFIX = '/api/food';
|
const FOOD_API_PREFIX = '/api/food';
|
||||||
@@ -23,6 +31,6 @@ export const changeDepartureTime = async (time: string, dayIndex?: number) => {
|
|||||||
return await api.post<ChangeDepartureTimeRequest, void>(`${FOOD_API_PREFIX}/changeDepartureTime`, { time, dayIndex });
|
return await api.post<ChangeDepartureTimeRequest, void>(`${FOOD_API_PREFIX}/changeDepartureTime`, { time, dayIndex });
|
||||||
}
|
}
|
||||||
|
|
||||||
export const jdemeObed = async () => {
|
export const jdemeObed = async (locationKey: LocationKey) => {
|
||||||
return await api.post<undefined, void>(`${FOOD_API_PREFIX}/jdemeObed`);
|
return await api.post<JdemeObedRequest, void>(`${FOOD_API_PREFIX}/jdemeObed`, { locationKey });
|
||||||
}
|
}
|
||||||
|
|||||||
4
server/.gitignore
vendored
4
server/.gitignore
vendored
@@ -1,7 +1,5 @@
|
|||||||
/node_modules
|
|
||||||
/dist
|
/dist
|
||||||
data.json
|
/resources/easterEggs
|
||||||
.env.production
|
.env.production
|
||||||
.env.development
|
.env.development
|
||||||
.easter-eggs.json
|
.easter-eggs.json
|
||||||
/resources/easterEggs
|
|
||||||
@@ -100,7 +100,9 @@ app.use("/api/", (req, res, next) => {
|
|||||||
const emailHeader = req.header('remote-email');
|
const emailHeader = req.header('remote-email');
|
||||||
if (userHeader !== undefined && nameHeader !== undefined) {
|
if (userHeader !== undefined && nameHeader !== undefined) {
|
||||||
const remoteName = Buffer.from(nameHeader, 'latin1').toString();
|
const remoteName = Buffer.from(nameHeader, 'latin1').toString();
|
||||||
console.log("Tvuj username, name a email: %s, %s, %s.", userHeader, remoteName, emailHeader);
|
if (ENVIRONMENT !== "production"){
|
||||||
|
console.log("Tvuj username, name a email: %s, %s, %s.", userHeader, remoteName, emailHeader);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!req.headers.authorization) {
|
if (!req.headers.authorization) {
|
||||||
|
|||||||
@@ -1,58 +1,58 @@
|
|||||||
/** Notifikace pro gotify*/
|
/** Notifikace */
|
||||||
import { ClientData, GotifyServer, NotififaceInput, NotifikaceData } from '../../types';
|
import {ClientData, Locations, NotififaceInput} from '../../types';
|
||||||
import axios, { AxiosError } from 'axios';
|
import axios from 'axios';
|
||||||
import dotenv from 'dotenv';
|
import dotenv from 'dotenv';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { getToday } from "./service";
|
import { getToday } from "./service";
|
||||||
import { formatDate, getUsersByLocation } from "./utils";
|
import {formatDate, getUsersByLocation, getHumanTime} from "./utils";
|
||||||
import getStorage from "./storage";
|
import getStorage from "./storage";
|
||||||
|
|
||||||
const storage = getStorage();
|
const storage = getStorage();
|
||||||
const ENVIRONMENT = process.env.NODE_ENV || 'production'
|
const ENVIRONMENT = process.env.NODE_ENV || 'production'
|
||||||
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
|
dotenv.config({ path: path.resolve(__dirname, `../.env.${ENVIRONMENT}`) });
|
||||||
|
|
||||||
const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
|
// const gotifyDataRaw = process.env.GOTIFY_SERVERS_AND_KEYS || "{}";
|
||||||
const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
|
// const gotifyData: GotifyServer[] = JSON.parse(gotifyDataRaw);
|
||||||
export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
|
// export const gotifyCall = async (data: NotififaceInput, gotifyServers?: GotifyServer[]): Promise<any[]> => {
|
||||||
if (!Array.isArray(gotifyServers)) {
|
// if (!Array.isArray(gotifyServers)) {
|
||||||
return []
|
// return []
|
||||||
}
|
// }
|
||||||
const urls = gotifyServers.flatMap(gotifyServer =>
|
// const urls = gotifyServers.flatMap(gotifyServer =>
|
||||||
gotifyServer.api_keys.map(apiKey => `${gotifyServer.server}/message?token=${apiKey}`));
|
// gotifyServer.api_keys.map(apiKey => `${gotifyServer.server}/message?token=${apiKey}`));
|
||||||
|
//
|
||||||
const dataPayload = {
|
// const dataPayload = {
|
||||||
title: "Luncher",
|
// title: "Luncher",
|
||||||
message: `${data.udalost} - spustil:${data.user}`,
|
// message: `${data.udalost} - spustil:${data.user}`,
|
||||||
priority: 7,
|
// priority: 7,
|
||||||
};
|
// };
|
||||||
|
//
|
||||||
const headers = { "Content-Type": "application/json" };
|
// const headers = { "Content-Type": "application/json" };
|
||||||
|
//
|
||||||
const promises = urls.map(url =>
|
// const promises = urls.map(url =>
|
||||||
axios.post(url, dataPayload, { headers }).then(response => {
|
// axios.post(url, dataPayload, { headers }).then(response => {
|
||||||
response.data = {
|
// response.data = {
|
||||||
success: true,
|
// success: true,
|
||||||
message: "Notifikace doručena",
|
// message: "Notifikace doručena",
|
||||||
};
|
// };
|
||||||
return response;
|
// return response;
|
||||||
}).catch(error => {
|
// }).catch(error => {
|
||||||
if (axios.isAxiosError(error)) {
|
// if (axios.isAxiosError(error)) {
|
||||||
const axiosError = error as AxiosError;
|
// const axiosError = error as AxiosError;
|
||||||
if (axiosError.response) {
|
// if (axiosError.response) {
|
||||||
axiosError.response.data = {
|
// axiosError.response.data = {
|
||||||
success: false,
|
// success: false,
|
||||||
message: "fail",
|
// message: "fail",
|
||||||
};
|
// };
|
||||||
console.log(error)
|
// console.log(error)
|
||||||
return axiosError.response;
|
// return axiosError.response;
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
// Handle unknown error without a response
|
// // Handle unknown error without a response
|
||||||
console.log(error, "unknown error");
|
// console.log(error, "unknown error");
|
||||||
})
|
// })
|
||||||
);
|
// );
|
||||||
return promises;
|
// return promises;
|
||||||
};
|
// };
|
||||||
|
|
||||||
export const ntfyCall = async (data: NotififaceInput) => {
|
export const ntfyCall = async (data: NotififaceInput) => {
|
||||||
const url = process.env.NTFY_HOST
|
const url = process.env.NTFY_HOST
|
||||||
@@ -72,10 +72,10 @@ export const ntfyCall = async (data: NotififaceInput) => {
|
|||||||
}
|
}
|
||||||
const today = formatDate(getToday());
|
const today = formatDate(getToday());
|
||||||
let clientData: ClientData = await storage.getData(today);
|
let clientData: ClientData = await storage.getData(today);
|
||||||
const userByCLocation = getUsersByLocation(clientData.choices, data.user)
|
const usersByLocation = getUsersByLocation(clientData.choices, data.user)
|
||||||
|
|
||||||
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
|
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
|
||||||
const promises = userByCLocation.map(async user => {
|
const promises = usersByLocation.map(async user => {
|
||||||
try {
|
try {
|
||||||
// Odstraníme mezery a diakritiku a převedeme na lowercase
|
// Odstraníme mezery a diakritiku a převedeme na lowercase
|
||||||
const topic = user.normalize('NFD').replace(' ', '').replace(/[\u0300-\u036f]/g, '').toLowerCase();
|
const topic = user.normalize('NFD').replace(' ', '').replace(/[\u0300-\u036f]/g, '').toLowerCase();
|
||||||
@@ -97,27 +97,64 @@ export const ntfyCall = async (data: NotififaceInput) => {
|
|||||||
return promises;
|
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*/
|
/** 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, teams = true, gotify = false, ntfy = true }: NotifikaceData) => {
|
export const callNotifikace = async (input: NotififaceInput) => {
|
||||||
const notifications = [];
|
const notifications = [];
|
||||||
if (ntfy) {
|
|
||||||
const ntfyPromises = await ntfyCall(input);
|
|
||||||
if (ntfyPromises) {
|
|
||||||
notifications.push(...ntfyPromises);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Zatím není
|
|
||||||
if (teams) {
|
|
||||||
notifications.push(teamsCall(input));
|
|
||||||
}*/
|
|
||||||
|
|
||||||
// Add more notifications as necessary
|
const ntfyPromises = await ntfyCall(input);
|
||||||
|
if (ntfyPromises) {
|
||||||
//gotify bych řekl, že už je deprecated
|
notifications.push(...ntfyPromises);
|
||||||
if (gotify) {
|
|
||||||
const gotifyPromises = await gotifyCall(input, gotifyData);
|
|
||||||
notifications.push(...gotifyPromises);
|
|
||||||
}
|
}
|
||||||
|
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);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const results = await Promise.all(notifications);
|
const results = await Promise.all(notifications);
|
||||||
@@ -126,4 +163,4 @@ export const callNotifikace = async ({ input, teams = true, gotify = false, ntfy
|
|||||||
console.error("Error in callNotifikace: ", error);
|
console.error("Error in callNotifikace: ", error);
|
||||||
// Handle the error as needed
|
// Handle the error as needed
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ export async function createPizzaDay(creator: string): Promise<ClientData> {
|
|||||||
const pizzaList = await getPizzaList();
|
const pizzaList = await getPizzaList();
|
||||||
const data: ClientData = { pizzaDay: { state: PizzaDayState.CREATED, creator, orders: [] }, pizzaList, ...clientData };
|
const data: ClientData = { pizzaDay: { state: PizzaDayState.CREATED, creator, orders: [] }, pizzaList, ...clientData };
|
||||||
await storage.setData(today, data);
|
await storage.setData(today, data);
|
||||||
callNotifikace({ input: { udalost: UdalostEnum.ZAHAJENA_PIZZA, user: creator } })
|
callNotifikace({ udalost: UdalostEnum.ZAHAJENA_PIZZA, user: creator })
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -207,7 +207,7 @@ export async function finishPizzaOrder(login: string) {
|
|||||||
}
|
}
|
||||||
clientData.pizzaDay.state = PizzaDayState.ORDERED;
|
clientData.pizzaDay.state = PizzaDayState.ORDERED;
|
||||||
await storage.setData(today, clientData);
|
await storage.setData(today, clientData);
|
||||||
callNotifikace({ input: { udalost: UdalostEnum.OBJEDNANA_PIZZA, user: clientData?.pizzaDay?.creator } })
|
callNotifikace({ udalost: UdalostEnum.OBJEDNANA_PIZZA, user: clientData?.pizzaDay?.creator })
|
||||||
return clientData;
|
return clientData;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,16 @@ import { addChoice, addVolatileData, getDateForWeekIndex, getToday, removeChoice
|
|||||||
import { getDayOfWeekIndex, parseToken } from "../utils";
|
import { getDayOfWeekIndex, parseToken } from "../utils";
|
||||||
import { getWebsocket } from "../websocket";
|
import { getWebsocket } from "../websocket";
|
||||||
import { callNotifikace } from "../notifikace";
|
import { callNotifikace } from "../notifikace";
|
||||||
import { AddChoiceRequest, ChangeDepartureTimeRequest, IDayIndex, RemoveChoiceRequest, RemoveChoicesRequest, UdalostEnum, UpdateNoteRequest } from "../../../types";
|
import {
|
||||||
|
AddChoiceRequest,
|
||||||
|
ChangeDepartureTimeRequest,
|
||||||
|
IDayIndex,
|
||||||
|
JdemeObedRequest,
|
||||||
|
RemoveChoiceRequest,
|
||||||
|
RemoveChoicesRequest,
|
||||||
|
UdalostEnum,
|
||||||
|
UpdateNoteRequest
|
||||||
|
} from "../../../types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ověří a vrátí index dne v týdnu z požadavku, za předpokladu, že byl předán, a je zároveň
|
* Ověří a vrátí index dne v týdnu z požadavku, za předpokladu, že byl předán, a je zároveň
|
||||||
@@ -133,10 +142,10 @@ router.post("/changeDepartureTime", async (req: Request<{}, any, ChangeDeparture
|
|||||||
} catch (e: any) { next(e) }
|
} catch (e: any) { next(e) }
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post("/jdemeObed", async (req, res, next) => {
|
router.post("/jdemeObed", async (req: Request<{}, any, JdemeObedRequest>, res, next) => {
|
||||||
const login = getLogin(parseToken(req));
|
const login = getLogin(parseToken(req));
|
||||||
try {
|
try {
|
||||||
await callNotifikace({ input: { user: login, udalost: UdalostEnum.JDEME_OBED }, gotify: false })
|
await callNotifikace({ user: login, udalost: UdalostEnum.JDEME_OBED, locationKey: req.body.locationKey });
|
||||||
res.status(200).json({});
|
res.status(200).json({});
|
||||||
} catch (e: any) { next(e) }
|
} catch (e: any) { next(e) }
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -268,14 +268,19 @@ export async function removeChoice(login: string, trusted: boolean, locationKey:
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Odstraní kompletně volbu uživatele.
|
* Odstraní kompletně volbu uživatele, vyjma ignoredLocationKey (pokud byla předána a existuje).
|
||||||
*
|
*
|
||||||
* @param login login 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) {
|
async function removeChoiceIfPresent(login: string, date: string, ignoredLocationKey?: LocationKey) {
|
||||||
let data: DayData = await storage.getData(date);
|
let data: DayData = await storage.getData(date);
|
||||||
for (const key of Object.keys(data.choices)) {
|
for (const key of Object.keys(data.choices)) {
|
||||||
const locationKey = key as LocationKey;
|
const locationKey = key as LocationKey;
|
||||||
|
if (ignoredLocationKey != null && ignoredLocationKey == locationKey) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (data.choices[locationKey] && login in data.choices[locationKey]) {
|
if (data.choices[locationKey] && login in data.choices[locationKey]) {
|
||||||
delete data.choices[locationKey][login];
|
delete data.choices[locationKey][login];
|
||||||
if (Object.keys(data.choices[locationKey]).length === 0) {
|
if (Object.keys(data.choices[locationKey]).length === 0) {
|
||||||
@@ -329,6 +334,9 @@ export async function addChoice(login: string, trusted: boolean, locationKey: Lo
|
|||||||
// Pokud měníme pouze lokaci, mažeme případné předchozí
|
// Pokud měníme pouze lokaci, mažeme případné předchozí
|
||||||
if (foodIndex == null) {
|
if (foodIndex == null) {
|
||||||
data = await removeChoiceIfPresent(login, selectedDate);
|
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
|
// TODO vytáhnout inicializaci "prázdné struktury" do vlastní funkce
|
||||||
if (!(data.choices[locationKey])) {
|
if (!(data.choices[locationKey])) {
|
||||||
|
|||||||
@@ -1,8 +1,17 @@
|
|||||||
import JSONdb from 'simple-json-db';
|
import JSONdb from 'simple-json-db';
|
||||||
import { StorageInterface } from "./StorageInterface";
|
import { StorageInterface } from "./StorageInterface";
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
const db = new JSONdb('./data.json');
|
const dbPath = path.resolve(__dirname, '../../data/db.json');
|
||||||
|
const dbDir = path.dirname(dbPath);
|
||||||
|
|
||||||
|
// 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.
|
* Implementace úložiště používající JSON soubor.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Choices, LocationKey } from "../../types";
|
import {Choices, LocationKey } from "../../types";
|
||||||
|
|
||||||
/** Vrátí datum v ISO formátu. */
|
/** Vrátí datum v ISO formátu. */
|
||||||
export function formatDate(date: Date, format?: string) {
|
export function formatDate(date: Date, format?: string) {
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ export type RemoveChoiceRequest = IDayIndex & ILocationKey & {
|
|||||||
foodIndex: number,
|
foodIndex: number,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type JdemeObedRequest = ILocationKey;
|
||||||
|
|
||||||
export type UpdateNoteRequest = IDayIndex & {
|
export type UpdateNoteRequest = IDayIndex & {
|
||||||
note?: string,
|
note?: string,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -111,6 +111,7 @@ export type Food = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO tohle je dost špatné pojmenování, vzhledem k tomu co to obsahuje
|
// 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 {
|
export enum Locations {
|
||||||
SLADOVNICKA = 'Sladovnická',
|
SLADOVNICKA = 'Sladovnická',
|
||||||
// UMOTLIKU = 'U Motlíků',
|
// UMOTLIKU = 'U Motlíků',
|
||||||
@@ -130,21 +131,15 @@ export type LocationKey = keyof typeof Locations;
|
|||||||
export enum UdalostEnum {
|
export enum UdalostEnum {
|
||||||
ZAHAJENA_PIZZA = "Zahájen pizza day",
|
ZAHAJENA_PIZZA = "Zahájen pizza day",
|
||||||
OBJEDNANA_PIZZA = "Objednána pizza",
|
OBJEDNANA_PIZZA = "Objednána pizza",
|
||||||
JDEME_OBED = "Jdeme oběd",
|
JDEME_OBED = "Jdeme na oběd",
|
||||||
}
|
}
|
||||||
|
|
||||||
export type NotififaceInput = {
|
export type NotififaceInput = {
|
||||||
|
locationKey?: LocationKey,
|
||||||
udalost: UdalostEnum,
|
udalost: UdalostEnum,
|
||||||
user: string,
|
user: string,
|
||||||
}
|
}
|
||||||
|
|
||||||
export type NotifikaceData = {
|
|
||||||
input: NotififaceInput,
|
|
||||||
gotify?: boolean,
|
|
||||||
teams?: boolean,
|
|
||||||
ntfy?: boolean,
|
|
||||||
}
|
|
||||||
|
|
||||||
export type GotifyServer = {
|
export type GotifyServer = {
|
||||||
server: string;
|
server: string;
|
||||||
api_keys: string[];
|
api_keys: string[];
|
||||||
|
|||||||
Reference in New Issue
Block a user