Compare commits
8
Commits
93242b7c7e
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a12bdb179
|
||
|
|
31b398a1d6
|
||
|
|
b6834cb7aa
|
||
|
|
ecc28ee82d
|
||
|
|
1af40bd572
|
||
|
|
e5fc358c0a
|
||
|
|
6f6567a2a9
|
||
|
|
ce051447e6
|
+6
-2
@@ -63,13 +63,15 @@ function App() {
|
||||
const settings = useSettings();
|
||||
const navigate = useNavigate();
|
||||
const [easterEgg, _] = useEasterEgg(auth);
|
||||
const [isConnected, setIsConnected] = useState<boolean>(false);
|
||||
const socket = useContext(SocketContext);
|
||||
// Socket je singleton mimo React, takže při návratu v historii prohlížeče (remount
|
||||
// komponenty) už žádný "connect" event nepřijde - stav proto inicializujeme z něj
|
||||
const [isConnected, setIsConnected] = useState<boolean>(() => socket.connected);
|
||||
const [data, setData] = useState<ClientData>();
|
||||
const [food, setFood] = useState<RestaurantDayMenuMap>();
|
||||
const [myOrder, setMyOrder] = useState<PizzaOrder>();
|
||||
const [foodChoiceList, setFoodChoiceList] = useState<Food[]>();
|
||||
const [closed, setClosed] = useState<boolean>(false);
|
||||
const socket = useContext(SocketContext);
|
||||
const choiceRef = useRef<HTMLSelectElement>(null);
|
||||
const foodChoiceRef = useRef<HTMLSelectElement>(null);
|
||||
const departureChoiceRef = useRef<HTMLSelectElement>(null);
|
||||
@@ -121,6 +123,8 @@ function App() {
|
||||
|
||||
// Registrace socket eventů
|
||||
useEffect(() => {
|
||||
// Srovnání se skutečným stavem socketu (mohl se změnit mezi renderem a efektem)
|
||||
setIsConnected(socket.connected);
|
||||
socket.on(EVENT_CONNECT, () => {
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { useState } from "react";
|
||||
import { Modal, Button, Form, Alert } from "react-bootstrap";
|
||||
import { generateMockOrders } from "../../../../types";
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
/** Příznak, zda je pro dnešní den založena alespoň jedna skupina objednávky. */
|
||||
hasGroups: boolean;
|
||||
/** Příznak, zda je nadefinován alespoň jeden obchod (bez něj nelze generovat). */
|
||||
hasStores: boolean;
|
||||
};
|
||||
|
||||
const DEFAULT_COUNT = '3';
|
||||
const DEFAULT_MIN_AMOUNT = '100';
|
||||
const DEFAULT_MAX_AMOUNT = '1000';
|
||||
|
||||
/** Vybere český tvar slova podle počtu (1 osoba / 2 osoby / 5 osob). */
|
||||
function plural(count: number, one: string, few: string, many: string): string {
|
||||
if (count === 1) return one;
|
||||
if (count >= 2 && count <= 4) return few;
|
||||
return many;
|
||||
}
|
||||
|
||||
/** Modální dialog pro generování mock dat sekce Objednání (pouze DEV). */
|
||||
export default function GenerateMockOrdersModal({ isOpen, onClose, hasGroups, hasStores }: Readonly<Props>) {
|
||||
const [count, setCount] = useState<string>(DEFAULT_COUNT);
|
||||
const [minAmount, setMinAmount] = useState<string>(DEFAULT_MIN_AMOUNT);
|
||||
const [maxAmount, setMaxAmount] = useState<string>(DEFAULT_MAX_AMOUNT);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
setError(null);
|
||||
|
||||
const countNum = parseInt(count, 10);
|
||||
if (isNaN(countNum) || countNum < 1 || countNum > 50) {
|
||||
setError('Počet osob musí být číslo mezi 1 a 50');
|
||||
return;
|
||||
}
|
||||
const minNum = parseInt(minAmount, 10);
|
||||
const maxNum = parseInt(maxAmount, 10);
|
||||
if (isNaN(minNum) || isNaN(maxNum) || minNum < 0 || maxNum < minNum) {
|
||||
setError('Zadejte platný rozsah částek (od ≤ do)');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await generateMockOrders({
|
||||
body: { count: countNum, minAmount: minNum, maxAmount: maxNum },
|
||||
});
|
||||
if (response.error) {
|
||||
setError((response.error as any).error || 'Nastala chyba při generování dat');
|
||||
} else {
|
||||
const groups = response.data?.groups ?? [];
|
||||
const total = response.data?.count ?? 0;
|
||||
const created = groups.find(g => g.created);
|
||||
setSuccess(
|
||||
`Doplněno: ${total} ${plural(total, 'osoba', 'osoby', 'osob')}`
|
||||
+ ` / ${groups.length} ${plural(groups.length, 'skupina', 'skupiny', 'skupin')}`
|
||||
+ (created ? ` (skupina „${created.name}“ byla nově založena).` : '.')
|
||||
);
|
||||
setTimeout(() => {
|
||||
onClose();
|
||||
setSuccess(null);
|
||||
}, 2000);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e.message || 'Nastala chyba při generování dat');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal show={isOpen} onHide={handleClose}>
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title><h2>Generovat mock objednávky</h2></Modal.Title>
|
||||
</Modal.Header>
|
||||
<Modal.Body>
|
||||
{success ? (
|
||||
<Alert variant="success">{success}</Alert>
|
||||
) : (
|
||||
<>
|
||||
<Alert variant="warning">
|
||||
<strong>DEV režim</strong> - Tato funkce je dostupná pouze ve vývojovém prostředí.
|
||||
Data se generují vždy jen pro aktuální den.
|
||||
</Alert>
|
||||
|
||||
{error && (
|
||||
<Alert variant="danger" onClose={() => setError(null)} dismissible>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{hasStores ? (
|
||||
<>
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Počet osob</Form.Label>
|
||||
<Form.Control
|
||||
type="number"
|
||||
value={count}
|
||||
onChange={e => setCount(e.target.value)}
|
||||
min={1}
|
||||
max={50}
|
||||
onKeyDown={e => e.stopPropagation()}
|
||||
/>
|
||||
<Form.Text className="text-muted">
|
||||
{hasGroups
|
||||
? 'Zadaný počet osob se doplní do každé existující skupiny.'
|
||||
: 'Není založena žádná skupina — jedna se založí z náhodně vybraného obchodu a doplní se do ní zadaný počet osob.'}
|
||||
</Form.Text>
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Rozsah částek (Kč)</Form.Label>
|
||||
<div className="d-flex gap-2 align-items-center">
|
||||
<Form.Control
|
||||
type="number"
|
||||
value={minAmount}
|
||||
onChange={e => setMinAmount(e.target.value)}
|
||||
min={0}
|
||||
onKeyDown={e => e.stopPropagation()}
|
||||
/>
|
||||
<span>—</span>
|
||||
<Form.Control
|
||||
type="number"
|
||||
value={maxAmount}
|
||||
onChange={e => setMaxAmount(e.target.value)}
|
||||
min={0}
|
||||
onKeyDown={e => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
<Form.Text className="text-muted">
|
||||
Každé osobě se nastaví náhodná částka z tohoto rozmezí a do poznámky náhodné jídlo.
|
||||
</Form.Text>
|
||||
</Form.Group>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-muted mb-0">
|
||||
Není nadefinován žádný obchod — mock objednávky nelze vygenerovat.
|
||||
Nejprve přidejte obchod ve správě obchodů.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Modal.Body>
|
||||
<Modal.Footer>
|
||||
{!success && (
|
||||
<>
|
||||
<Button variant="secondary" onClick={handleClose} disabled={loading}>
|
||||
Storno
|
||||
</Button>
|
||||
<Button variant="primary" onClick={handleGenerate} disabled={loading || !hasStores}>
|
||||
{loading ? 'Generuji...' : 'Generovat'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{success && (
|
||||
<Button variant="secondary" onClick={handleClose}>
|
||||
Zavřít
|
||||
</Button>
|
||||
)}
|
||||
</Modal.Footer>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Modal, Button, Form, Table, Alert } from "react-bootstrap";
|
||||
import { generateQr, OrderGroup, OrderGroupMember, QrRecipient } from "../../../../types";
|
||||
import { generateQr, GroupState, OrderGroup, OrderGroupMember, QrRecipient } from "../../../../types";
|
||||
import { sanitizeQrMessage } from "../../Utils";
|
||||
import { computeFeeShare, computeMemberTotal, countActiveMembers, isActiveMember } from "../../utils/groupFees";
|
||||
|
||||
@@ -102,6 +102,8 @@ export default function PayForGroupModal({ isOpen, onClose, onSuccess, group, pa
|
||||
};
|
||||
|
||||
const hasFees = totalFees > 0;
|
||||
// Generování QR je poslední krok objednávky — server skupinu zároveň překlopí do stavu Doručeno
|
||||
const willBeMarkedDelivered = group.state !== GroupState.DELIVERED;
|
||||
|
||||
return (
|
||||
<Modal show={isOpen} onHide={onClose} size="lg">
|
||||
@@ -115,6 +117,12 @@ export default function PayForGroupModal({ isOpen, onClose, onSuccess, group, pa
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
{willBeMarkedDelivered && (
|
||||
<Alert variant="info">
|
||||
Objednávka není ve stavu <strong>Doručeno</strong> — vygenerováním QR kódů se do tohoto stavu automaticky přepne.
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<p>Zaplatili jste za skupinu. Vyberte, komu vygenerovat QR kód k úhradě.</p>
|
||||
|
||||
{error && (
|
||||
|
||||
@@ -2,8 +2,9 @@ import { useState } from "react";
|
||||
import { Modal, Button, Form, ListGroup, Alert } from "react-bootstrap";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faTrashCan } from "@fortawesome/free-regular-svg-icons";
|
||||
import { faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";
|
||||
import { addStore, deleteStore, Store } from "../../../../types";
|
||||
import { faPen, faPlus, faUpRightFromSquare, faXmark } from "@fortawesome/free-solid-svg-icons";
|
||||
import { addStore, deleteStore, updateStore, Store } from "../../../../types";
|
||||
import { getStoreUrls, storeUrlLabel } from "../../utils/storeUrls";
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean;
|
||||
@@ -12,25 +13,85 @@ type Props = {
|
||||
onStoresChanged: (stores: Store[]) => void;
|
||||
};
|
||||
|
||||
/** Rozpracovaná editace obchodu — původní název slouží k jeho identifikaci na serveru. */
|
||||
type EditState = {
|
||||
originalName: string;
|
||||
name: string;
|
||||
urls: string[];
|
||||
};
|
||||
|
||||
/** Vstupní pole pro URL nabídek — vždy alespoň jedno prázdné, aby bylo kam psát. */
|
||||
function toUrlInputs(urls: string[]): string[] {
|
||||
return urls.length > 0 ? urls : [''];
|
||||
}
|
||||
|
||||
export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChanged }: Readonly<Props>) {
|
||||
const [newName, setNewName] = useState('');
|
||||
const [newUrl, setNewUrl] = useState('');
|
||||
// Jeden podnik může být dostupný přes více dovozových služeb — proto seznam URL
|
||||
const [newUrls, setNewUrls] = useState<string[]>(['']);
|
||||
const [edit, setEdit] = useState<EditState | null>(null);
|
||||
const [heslo, setHeslo] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const addUrlRow = (urls: string[]) => [...urls, ''];
|
||||
|
||||
const removeUrlRow = (urls: string[], index: number) =>
|
||||
urls.length === 1 ? [''] : urls.filter((_, i) => i !== index);
|
||||
|
||||
const setUrlAt = (urls: string[], index: number, value: string) =>
|
||||
urls.map((u, i) => (i === index ? value : u));
|
||||
|
||||
/** Zpracuje odpověď API — vrací true při úspěchu. Chybu z API hlásí globální toaster. */
|
||||
const applyResult = (res: { data?: unknown; error?: unknown }): boolean => {
|
||||
if (res.error) {
|
||||
return false;
|
||||
}
|
||||
if (res.data) {
|
||||
onStoresChanged(res.data as Store[]);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!newName.trim()) return;
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await addStore({ body: { name: newName.trim(), url: newUrl.trim() || undefined, heslo } });
|
||||
if (res.error) {
|
||||
setError((res.error as any).error || 'Nastala chyba');
|
||||
} else if (res.data) {
|
||||
onStoresChanged(res.data as Store[]);
|
||||
const urls = newUrls.map(u => u.trim()).filter(Boolean);
|
||||
const res = await addStore({ body: { name: newName.trim(), urls: urls.length > 0 ? urls : undefined, heslo } });
|
||||
if (applyResult(res)) {
|
||||
setNewName('');
|
||||
setNewUrl('');
|
||||
setNewUrls(['']);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e.message || 'Nastala chyba');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const startEdit = (store: Store) => {
|
||||
setError(null);
|
||||
setEdit({ originalName: store.name, name: store.name, urls: toUrlInputs(store.urls ?? []) });
|
||||
};
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
if (!edit || !edit.name.trim()) return;
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await updateStore({
|
||||
body: {
|
||||
name: edit.originalName,
|
||||
newName: edit.name.trim(),
|
||||
urls: edit.urls.map(u => u.trim()).filter(Boolean),
|
||||
heslo,
|
||||
},
|
||||
});
|
||||
if (applyResult(res)) {
|
||||
setEdit(null);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e.message || 'Nastala chyba');
|
||||
@@ -44,10 +105,8 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await deleteStore({ body: { name, heslo } });
|
||||
if (res.error) {
|
||||
setError((res.error as any).error || 'Nastala chyba');
|
||||
} else if (res.data) {
|
||||
onStoresChanged(res.data as Store[]);
|
||||
if (applyResult(res) && edit?.originalName === name) {
|
||||
setEdit(null);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e.message || 'Nastala chyba');
|
||||
@@ -56,6 +115,37 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
||||
}
|
||||
};
|
||||
|
||||
/** Řádky se vstupy pro URL — používá se pro přidání i pro editaci obchodu. */
|
||||
const renderUrlInputs = (urls: string[], onChange: (urls: string[]) => void, onSubmit: () => void) => (
|
||||
<>
|
||||
{urls.map((url, index) => (
|
||||
<div key={index} className="d-flex gap-2 mb-2 align-items-center">
|
||||
<Form.Control
|
||||
type="url"
|
||||
placeholder={index === 0
|
||||
? 'URL na nabídku (volitelné, např. Bolt Food/Wolt)'
|
||||
: 'Další URL na nabídku (jiná dovozová služba)'}
|
||||
value={url}
|
||||
onChange={e => onChange(setUrlAt(urls, index, e.target.value))}
|
||||
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') onSubmit(); }}
|
||||
/>
|
||||
<Button
|
||||
variant="outline-secondary"
|
||||
onClick={() => onChange(removeUrlRow(urls, index))}
|
||||
disabled={urls.length === 1 && !url}
|
||||
title="Odebrat tuto URL"
|
||||
>
|
||||
<FontAwesomeIcon icon={faXmark} />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="link" size="sm" className="p-0" onClick={() => onChange(addUrlRow(urls))}>
|
||||
<FontAwesomeIcon icon={faPlus} className="me-1" />
|
||||
Přidat další URL
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<Modal show={isOpen} onHide={onClose}>
|
||||
<Modal.Header closeButton>
|
||||
@@ -89,14 +179,8 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
||||
onChange={e => setNewName(e.target.value)}
|
||||
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
|
||||
/>
|
||||
<div className="d-flex gap-2 mb-3">
|
||||
<Form.Control
|
||||
type="url"
|
||||
placeholder="URL na nabídku (volitelné, např. Bolt Food/Wolt)"
|
||||
value={newUrl}
|
||||
onChange={e => setNewUrl(e.target.value)}
|
||||
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
|
||||
/>
|
||||
{renderUrlInputs(newUrls, setNewUrls, handleAdd)}
|
||||
<div className="d-flex justify-content-end mb-3">
|
||||
<Button variant="primary" onClick={handleAdd} disabled={loading || !newName.trim() || !heslo}>
|
||||
Přidat
|
||||
</Button>
|
||||
@@ -107,16 +191,68 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
||||
<p className="text-muted">Žádné obchody v seznamu</p>
|
||||
) : (
|
||||
<ListGroup>
|
||||
{stores.map(s => (
|
||||
<ListGroup.Item key={s.name} className="d-flex justify-content-between align-items-center">
|
||||
<span>
|
||||
{s.name}
|
||||
{s.url && /^https?:\/\//i.test(s.url) && (
|
||||
<a href={s.url} target="_blank" rel="noopener noreferrer" className="ms-2" title="Otevřít nabídku v nové záložce">
|
||||
<FontAwesomeIcon icon={faUpRightFromSquare} />
|
||||
{stores.map(s => {
|
||||
const urls = getStoreUrls(s);
|
||||
const isEditing = edit?.originalName === s.name;
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<ListGroup.Item key={s.name}>
|
||||
<Form.Control
|
||||
className="mb-2"
|
||||
type="text"
|
||||
placeholder="Název obchodu"
|
||||
value={edit.name}
|
||||
onChange={e => setEdit({ ...edit, name: e.target.value })}
|
||||
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleSaveEdit(); }}
|
||||
/>
|
||||
{renderUrlInputs(edit.urls, next => setEdit({ ...edit, urls: next }), handleSaveEdit)}
|
||||
<div className="d-flex justify-content-end gap-2 mt-2">
|
||||
<Button variant="secondary" size="sm" onClick={() => setEdit(null)}>
|
||||
Zrušit
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
onClick={handleSaveEdit}
|
||||
disabled={loading || !edit.name.trim() || !heslo}
|
||||
>
|
||||
Uložit
|
||||
</Button>
|
||||
</div>
|
||||
</ListGroup.Item>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ListGroup.Item key={s.name} className="d-flex justify-content-between align-items-start">
|
||||
<div>
|
||||
<div>{s.name}</div>
|
||||
{urls.length > 0 && (
|
||||
<small className="text-muted d-flex flex-wrap gap-2">
|
||||
{urls.map(url => (
|
||||
<a
|
||||
key={url}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title={url}
|
||||
>
|
||||
{storeUrlLabel(url)}
|
||||
<FontAwesomeIcon icon={faUpRightFromSquare} className="ms-1" />
|
||||
</a>
|
||||
))}
|
||||
</small>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="d-flex gap-3">
|
||||
<FontAwesomeIcon
|
||||
icon={faPen}
|
||||
className="action-icon"
|
||||
title="Upravit"
|
||||
onClick={() => startEdit(s)}
|
||||
style={{ cursor: 'pointer' }}
|
||||
/>
|
||||
<FontAwesomeIcon
|
||||
icon={faTrashCan}
|
||||
className="action-icon"
|
||||
@@ -124,8 +260,10 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
||||
onClick={() => handleRemove(s.name)}
|
||||
style={{ cursor: 'pointer' }}
|
||||
/>
|
||||
</div>
|
||||
</ListGroup.Item>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</ListGroup>
|
||||
)}
|
||||
</Modal.Body>
|
||||
|
||||
@@ -31,7 +31,8 @@ getConfig().then(({ data }) => {
|
||||
client.interceptors.response.use(async response => {
|
||||
// TODO opravit - login je zatím výjimka, voláme ho "naprázdno" abychom zjistili, zda nás nepřihlásily trusted headers
|
||||
if (!response.ok && !response.url.includes("/login")) {
|
||||
const json = await response.json();
|
||||
// Čteme z klonu, aby tělo odpovědi zůstalo k dispozici i generovanému SDK
|
||||
const json = await response.clone().json();
|
||||
toast.error(json.error, { theme: "colored" });
|
||||
// Serverové chyby hlásíme do Sentry; 4xx jsou očekávané (chyby uživatele)
|
||||
if (response.status >= 500) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useCallback, useContext, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Badge, Button, Card, Form, Modal, OverlayTrigger, Table, Tooltip } from 'react-bootstrap';
|
||||
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||
import { faTrashCan } from '@fortawesome/free-regular-svg-icons';
|
||||
import { faBasketShopping, faChevronLeft, faChevronRight, faCircleCheck, faClockRotateLeft, faGear, faLock, faLockOpen, faPen, faSearch, faUserPlus } from '@fortawesome/free-solid-svg-icons';
|
||||
import { faBasketShopping, faChevronLeft, faChevronRight, faCircleCheck, faClockRotateLeft, faGear, faLock, faLockOpen, faPen, faSearch, faTruck, faUserPlus } from '@fortawesome/free-solid-svg-icons';
|
||||
import DatePicker, { registerLocale } from 'react-datepicker';
|
||||
import { cs } from 'date-fns/locale';
|
||||
import 'react-datepicker/dist/react-datepicker.css';
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
getData, createGroup, deleteGroup, addGroupMember, removeGroupMember, updateGroupMember, setGroupState, updateGroupTimes, setTracking, getOrderDates,
|
||||
} from '../../../types';
|
||||
import { computeFeeShare, computeMemberTotal, countActiveMembers } from '../utils/groupFees';
|
||||
import { getStoreUrls, isHttpUrl, storeUrlLabel } from '../utils/storeUrls';
|
||||
import { EVENT_MESSAGE, EVENT_PENDING_QR, SocketContext } from '../context/socket';
|
||||
import { useAuth } from '../context/auth';
|
||||
import { useSettings } from '../context/settings';
|
||||
@@ -23,6 +24,7 @@ import StoreAdminModal from '../components/modals/StoreAdminModal';
|
||||
import PayForGroupModal from '../components/modals/PayForGroupModal';
|
||||
import EditGroupFeesModal from '../components/modals/EditGroupFeesModal';
|
||||
import BoltSimulationModal from '../components/modals/BoltSimulationModal';
|
||||
import GenerateMockOrdersModal from '../components/modals/GenerateMockOrdersModal';
|
||||
import PendingPayments from '../components/PendingPayments';
|
||||
import OrderProgress, { PROVIDER_LABEL } from '../components/OrderProgress';
|
||||
|
||||
@@ -100,11 +102,17 @@ function isoToDate(iso?: string): Date | null {
|
||||
return iso ? new Date(`${iso}T00:00:00`) : null;
|
||||
}
|
||||
|
||||
/** Stavy, ve kterých je objednávka již odeslána do podniku (objednáno/doručeno) — skupina se nesmí upravovat. */
|
||||
function isSubmittedState(state: GroupState): boolean {
|
||||
return state === GroupState.ORDERED || state === GroupState.DELIVERED;
|
||||
}
|
||||
|
||||
function stateBadge(state: GroupState) {
|
||||
const map: Record<GroupState, { bg: string; label: string }> = {
|
||||
[GroupState.OPEN]: { bg: 'success', label: 'Otevřeno' },
|
||||
[GroupState.LOCKED]: { bg: 'warning', label: 'Uzamčeno' },
|
||||
[GroupState.ORDERED]: { bg: 'secondary', label: 'Objednáno' },
|
||||
[GroupState.DELIVERED]: { bg: 'info', label: 'Doručeno' },
|
||||
};
|
||||
const { bg, label } = map[state] ?? { bg: 'light', label: state };
|
||||
return <Badge bg={bg}>{label}</Badge>;
|
||||
@@ -125,6 +133,8 @@ export default function OrderGroupsPage() {
|
||||
// ISO data dnů, ve kterých existuje aspoň jedna objednávka (pro zvýraznění v date pickeru)
|
||||
const [orderDates, setOrderDates] = useState<string[]>([]);
|
||||
const [newGroupName, setNewGroupName] = useState('');
|
||||
// Vybraná URL na nabídku — podnik může být dostupný přes více dovozových služeb
|
||||
const [newGroupUrl, setNewGroupUrl] = useState('');
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [adminModalOpen, setAdminModalOpen] = useState(false);
|
||||
const [editAmounts, setEditAmounts] = useState<Record<string, string>>({});
|
||||
@@ -134,6 +144,7 @@ export default function OrderGroupsPage() {
|
||||
const [payModal, setPayModal] = useState<OrderGroup | null>(null);
|
||||
const [feesModal, setFeesModal] = useState<OrderGroup | null>(null);
|
||||
const [boltSimModal, setBoltSimModal] = useState<OrderGroup | null>(null);
|
||||
const [mockOrdersModalOpen, setMockOrdersModalOpen] = useState(false);
|
||||
const [confirmOrderGroup, setConfirmOrderGroup] = useState<OrderGroup | null>(null);
|
||||
const [pageError, setPageError] = useState<string | null>(null);
|
||||
|
||||
@@ -248,11 +259,18 @@ export default function OrderGroupsPage() {
|
||||
const handleCreate = async () => {
|
||||
if (!newGroupName || !auth?.login) return;
|
||||
setCreating(true);
|
||||
const ok = await refresh(() => createGroup({ body: { name: newGroupName } }));
|
||||
if (ok) setNewGroupName('');
|
||||
// Pojistka, kdyby se seznam obchodů mezitím změnil (socket) — vezmeme první URL podniku
|
||||
const urls = getStoreUrls((data?.stores ?? []).find(s => s.name === newGroupName));
|
||||
const url = urls.includes(newGroupUrl) ? newGroupUrl : urls[0];
|
||||
const ok = await refresh(() => createGroup({ body: { name: newGroupName, url } }));
|
||||
if (ok) {
|
||||
setNewGroupName('');
|
||||
setNewGroupUrl('');
|
||||
}
|
||||
setCreating(false);
|
||||
};
|
||||
|
||||
|
||||
const handleJoin = (groupId: string) =>
|
||||
refresh(() => addGroupMember({ body: { id: groupId } }));
|
||||
|
||||
@@ -269,6 +287,12 @@ export default function OrderGroupsPage() {
|
||||
const handleRevertOrdered = (group: OrderGroup) =>
|
||||
refresh(() => setGroupState({ body: { id: group.id, state: GroupState.LOCKED } }));
|
||||
|
||||
const handleSetDelivered = (group: OrderGroup) =>
|
||||
refresh(() => setGroupState({ body: { id: group.id, state: GroupState.DELIVERED } }));
|
||||
|
||||
const handleRevertDelivered = (group: OrderGroup) =>
|
||||
refresh(() => setGroupState({ body: { id: group.id, state: GroupState.ORDERED } }));
|
||||
|
||||
const handleDelete = (groupId: string) =>
|
||||
refresh(() => deleteGroup({ body: { id: groupId } }));
|
||||
|
||||
@@ -334,7 +358,7 @@ export default function OrderGroupsPage() {
|
||||
// Historie (jiný než aktuální den) je vždy read-only.
|
||||
const canEditMember = (group: OrderGroup, targetLogin: string) => {
|
||||
if (selectedDate) return false;
|
||||
if (group.state === GroupState.ORDERED) return false;
|
||||
if (isSubmittedState(group.state)) return false;
|
||||
if (auth?.login === group.creatorLogin) return true;
|
||||
if (auth?.login === targetLogin && group.state === GroupState.OPEN) return true;
|
||||
return false;
|
||||
@@ -342,7 +366,7 @@ export default function OrderGroupsPage() {
|
||||
|
||||
const canManageMembers = (group: OrderGroup) => {
|
||||
if (selectedDate) return false;
|
||||
if (group.state === GroupState.ORDERED) return false;
|
||||
if (isSubmittedState(group.state)) return false;
|
||||
if (auth?.login === group.creatorLogin) return true;
|
||||
return group.state === GroupState.OPEN;
|
||||
};
|
||||
@@ -359,6 +383,8 @@ export default function OrderGroupsPage() {
|
||||
|
||||
const stores = data.stores ?? [];
|
||||
const groups = data.groups ?? [];
|
||||
// URL na nabídku vybíraného podniku — výběr nabízíme, jen když jich je víc
|
||||
const newStoreUrls = getStoreUrls(stores.find(s => s.name === newGroupName));
|
||||
|
||||
// Zobrazené datum a režim historie (vše read-only, pokud nejde o aktuální den)
|
||||
const displayedIso = data.isoDate;
|
||||
@@ -389,11 +415,18 @@ export default function OrderGroupsPage() {
|
||||
<div className="wrapper">
|
||||
<div className="d-flex align-items-center justify-content-between mb-1">
|
||||
<h1 className="title mb-0">Objednání</h1>
|
||||
<div className="d-flex gap-2">
|
||||
{IS_DEV && !isReadOnly && (
|
||||
<Button variant="outline-warning" size="sm" onClick={() => setMockOrdersModalOpen(true)} title="Generovat mock objednávky (DEV)">
|
||||
🔧 Mock objednávky
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline-primary" size="sm" onClick={() => setAdminModalOpen(true)} title="Správa obchodů">
|
||||
<FontAwesomeIcon icon={faGear} className="me-1" />
|
||||
Obchody
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p style={{ color: 'var(--luncher-text-muted)' }}>Skupinové objednávky z obchodů a restaurací</p>
|
||||
|
||||
{/* Navigace mezi dny – šipky kolem výběru data (i klávesami ←/→) */}
|
||||
@@ -456,12 +489,29 @@ export default function OrderGroupsPage() {
|
||||
<div className="d-flex gap-2 align-items-center flex-wrap">
|
||||
<Form.Select
|
||||
value={newGroupName}
|
||||
onChange={e => setNewGroupName(e.target.value)}
|
||||
onChange={e => {
|
||||
const name = e.target.value;
|
||||
setNewGroupName(name);
|
||||
// Výběr nabídky se resetuje na první URL nově vybraného podniku
|
||||
setNewGroupUrl(getStoreUrls(stores.find(s => s.name === name))[0] ?? '');
|
||||
}}
|
||||
style={{ maxWidth: 260 }}
|
||||
>
|
||||
<option value="">— vyberte obchod —</option>
|
||||
{stores.map(s => <option key={s.name} value={s.name}>{s.name}</option>)}
|
||||
</Form.Select>
|
||||
{newStoreUrls.length > 1 && (
|
||||
<Form.Select
|
||||
value={newStoreUrls.includes(newGroupUrl) ? newGroupUrl : newStoreUrls[0]}
|
||||
onChange={e => setNewGroupUrl(e.target.value)}
|
||||
style={{ maxWidth: 220 }}
|
||||
title="Odkud se bude objednávat"
|
||||
>
|
||||
{newStoreUrls.map(url => (
|
||||
<option key={url} value={url}>{storeUrlLabel(url)}</option>
|
||||
))}
|
||||
</Form.Select>
|
||||
)}
|
||||
<Button variant="primary" onClick={handleCreate} disabled={creating || !newGroupName}>
|
||||
Vytvořit skupinu
|
||||
</Button>
|
||||
@@ -482,13 +532,19 @@ export default function OrderGroupsPage() {
|
||||
const isCreator = login === group.creatorLogin;
|
||||
const isMember = login in group.members;
|
||||
const isOrdered = group.state === GroupState.ORDERED;
|
||||
const isDelivered = group.state === GroupState.DELIVERED;
|
||||
// Objednáno i Doručeno = objednávka je odeslána do podniku, skupina se už needituje
|
||||
const isSubmitted = isOrdered || isDelivered;
|
||||
const isLocked = group.state === GroupState.LOCKED;
|
||||
const memberEntries = Object.entries(group.members) as [string, OrderGroupMember][];
|
||||
const editingTimes = group.id in editTimes;
|
||||
// URL na nabídku podniku (pokud ji má dohledatelný obchod vyplněnou).
|
||||
// URL na nabídku podniku — přednostně ta, kterou zakladatel vybral při vytvoření
|
||||
// skupiny. Skupiny z doby před výběrem URL ji nemají, pak zkusíme jedinou URL obchodu.
|
||||
// Povolíme jen http(s), aby odkaz nemohl být zneužit (např. javascript:).
|
||||
const rawStoreUrl = stores.find(s => s.name === group.name)?.url;
|
||||
const storeUrl = rawStoreUrl && /^https?:\/\//i.test(rawStoreUrl) ? rawStoreUrl : undefined;
|
||||
const groupStoreUrls = getStoreUrls(stores.find(s => s.name === group.name));
|
||||
const storeUrl = isHttpUrl(group.url)
|
||||
? group.url
|
||||
: (groupStoreUrls.length === 1 ? groupStoreUrls[0] : undefined);
|
||||
|
||||
const totalFees = (group.fees ?? 0) + (group.shipping ?? 0) + (group.tip ?? 0);
|
||||
// Poplatky se dělí jen mezi aktivní strávníky (kdo si reálně něco objednal).
|
||||
@@ -515,7 +571,7 @@ export default function OrderGroupsPage() {
|
||||
<small className="text-muted">zakladatel: {group.creatorLogin}</small>
|
||||
</div>
|
||||
<div className="d-flex gap-2">
|
||||
{!isReadOnly && isCreator && !isOrdered && (
|
||||
{!isReadOnly && isCreator && !isSubmitted && (
|
||||
<>
|
||||
<Button variant="outline-info" size="sm" onClick={() => setFeesModal(group)} title="Upravit poplatky a slevu">
|
||||
Poplatky
|
||||
@@ -533,20 +589,32 @@ export default function OrderGroupsPage() {
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{!isReadOnly && isCreator && isOrdered && (
|
||||
{!isReadOnly && isCreator && isSubmitted && (
|
||||
<>
|
||||
{isOrdered && (
|
||||
<Button variant="outline-success" size="sm" onClick={() => handleSetDelivered(group)} title="Označit objednávku jako doručenou">
|
||||
<FontAwesomeIcon icon={faTruck} className="me-1" />
|
||||
Doručeno
|
||||
</Button>
|
||||
)}
|
||||
{settings?.bankAccount && settings?.holderName && !group.qrGenerated && (
|
||||
<Button variant="primary" size="sm" onClick={() => setPayModal(group)}>
|
||||
<FontAwesomeIcon icon={faBasketShopping} className="me-1" />
|
||||
Generovat QR
|
||||
</Button>
|
||||
)}
|
||||
{isDelivered ? (
|
||||
<Button variant="outline-warning" size="sm" onClick={() => handleRevertDelivered(group)} title="Vrátit na Objednáno">
|
||||
<FontAwesomeIcon icon={faClockRotateLeft} />
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="outline-warning" size="sm" onClick={() => handleRevertOrdered(group)} title="Vrátit na Uzamčeno (smaže QR kódy)">
|
||||
<FontAwesomeIcon icon={faLockOpen} />
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{!isReadOnly && !isMember && !isOrdered && !isLocked && (
|
||||
{!isReadOnly && !isMember && !isSubmitted && !isLocked && (
|
||||
<Button variant="outline-success" size="sm" onClick={() => handleJoin(group.id)}>
|
||||
<FontAwesomeIcon icon={faUserPlus} className="me-1" />
|
||||
Přidat se
|
||||
@@ -732,7 +800,7 @@ export default function OrderGroupsPage() {
|
||||
)}
|
||||
|
||||
{/* Časy objednání a doručení */}
|
||||
{isOrdered && (
|
||||
{isSubmitted && (
|
||||
<div className="px-3 py-2 border-top">
|
||||
{!isReadOnly && isCreator && editingTimes ? (
|
||||
<div className="d-flex align-items-center gap-3 flex-wrap">
|
||||
@@ -923,6 +991,19 @@ export default function OrderGroupsPage() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{IS_DEV && (
|
||||
<GenerateMockOrdersModal
|
||||
isOpen={mockOrdersModalOpen}
|
||||
onClose={() => {
|
||||
setMockOrdersModalOpen(false);
|
||||
// Data přijdou i websocketem, po založení skupiny se ale mění i dny s objednávkou
|
||||
fetchData();
|
||||
fetchOrderDates();
|
||||
}}
|
||||
hasGroups={groups.length > 0}
|
||||
hasStores={stores.length > 0}
|
||||
/>
|
||||
)}
|
||||
{IS_DEV && boltSimModal && (
|
||||
<BoltSimulationModal
|
||||
isOpen={!!boltSimModal}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Store } from '../../../types';
|
||||
|
||||
/** Známé dovozové služby — hostname (bez www) → čitelný název pro nabídku. */
|
||||
const KNOWN_SERVICES: { match: string; label: string }[] = [
|
||||
{ match: 'bolt.eu', label: 'Bolt Food' },
|
||||
{ match: 'wolt.com', label: 'Wolt' },
|
||||
{ match: 'foodora.cz', label: 'Foodora' },
|
||||
{ match: 'damejidlo.cz', label: 'Dáme jídlo' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Ověří, že jde o odkaz s protokolem http(s) — jiné protokoly (např. javascript:)
|
||||
* by mohly být zneužity, proto je jako odkaz nezobrazujeme.
|
||||
*/
|
||||
export function isHttpUrl(url?: string): boolean {
|
||||
return !!url && /^https?:\/\//i.test(url);
|
||||
}
|
||||
|
||||
/** Vrátí platné URL na nabídku daného obchodu. */
|
||||
export function getStoreUrls(store?: Store): string[] {
|
||||
return (store?.urls ?? []).filter(isHttpUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Popisek URL pro výběr nabídky — u známých dovozových služeb jejich název,
|
||||
* jinak hostname odkazu (např. "restaurace-u-nas.cz").
|
||||
*/
|
||||
export function storeUrlLabel(url: string): string {
|
||||
let hostname: string;
|
||||
try {
|
||||
hostname = new URL(url).hostname.toLowerCase().replace(/^www\./, '');
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
const known = KNOWN_SERVICES.find(s => hostname === s.match || hostname.endsWith(`.${s.match}`));
|
||||
return known ? known.label : hostname;
|
||||
}
|
||||
@@ -1,3 +1,7 @@
|
||||
[
|
||||
"Statistiky se nově načtou i pro aktuální týden, který ještě neskončil"
|
||||
"Statistiky se nově načtou i pro aktuální týden, který ještě neskončil",
|
||||
"Podnik může mít více odkazů na nabídku (např. Bolt Food, Wolt i Foodora)",
|
||||
"Při vytváření skupiny lze vybrat, přes kterou službu se bude objednávat — odkaz v záhlaví skupiny pak vede přímo na ni",
|
||||
"Existující podnik lze upravit — přejmenovat i změnit odkazy na nabídku, bez nutnosti smazat a znovu přidat",
|
||||
"Ve Správě obchodů se při chybě už nezobrazuje matoucí technická hláška, jen srozumitelné hlášení o chybě"
|
||||
]
|
||||
|
||||
+62
-14
@@ -29,6 +29,26 @@ function findGroup(data: ClientData, id: string): OrderGroup | undefined {
|
||||
return data.groups?.find(g => g.id === id);
|
||||
}
|
||||
|
||||
/** České názvy stavů pro chybová hlášení. */
|
||||
const STATE_LABEL: Record<GroupState, string> = {
|
||||
[GroupState.OPEN]: 'otevřeno',
|
||||
[GroupState.LOCKED]: 'uzamčeno',
|
||||
[GroupState.ORDERED]: 'objednáno',
|
||||
[GroupState.DELIVERED]: 'doručeno',
|
||||
};
|
||||
|
||||
/** Stavy, ve kterých je objednávka již odeslána do podniku a nelze ji tedy upravovat. */
|
||||
function isSubmitted(state: GroupState): boolean {
|
||||
return state === GroupState.ORDERED || state === GroupState.DELIVERED;
|
||||
}
|
||||
|
||||
/** Ověří, že skupina není v odeslaném stavu (objednáno/doručeno), jinak vyhodí chybu. */
|
||||
function assertNotSubmitted(group: OrderGroup): void {
|
||||
if (isSubmitted(group.state)) {
|
||||
throw new Error(`Skupinu ve stavu "${STATE_LABEL[group.state]}" nelze upravovat`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vrátí seznam ISO dat (YYYY-MM-DD), pro která existuje alespoň jedna objednávková skupina.
|
||||
* Slouží ke zvýraznění dnů v date pickeru na stránce objednávání.
|
||||
@@ -47,19 +67,41 @@ export async function getOrderDates(): Promise<string[]> {
|
||||
return dates.sort();
|
||||
}
|
||||
|
||||
export async function createGroup(creatorLogin: string, name: string, date?: Date): Promise<ClientData> {
|
||||
/**
|
||||
* Vytvoří novou skupinu objednávky.
|
||||
*
|
||||
* @param creatorLogin login zakladatele
|
||||
* @param name název obchodu (musí být v seznamu povolených obchodů)
|
||||
* @param date den, ke kterému skupina patří (výchozí dnešní)
|
||||
* @param url vybraná URL na nabídku podniku — musí být jednou z URL obchodu.
|
||||
* Pokud není předána a obchod má právě jednu URL, dosadí se automaticky.
|
||||
*/
|
||||
export async function createGroup(creatorLogin: string, name: string, date?: Date, url?: string): Promise<ClientData> {
|
||||
const stores = await getStores();
|
||||
if (!stores.some(s => s.name.toLowerCase() === name.trim().toLowerCase())) {
|
||||
const store = stores.find(s => s.name.toLowerCase() === name.trim().toLowerCase());
|
||||
if (!store) {
|
||||
throw new Error('Obchod není v seznamu povolených obchodů');
|
||||
}
|
||||
const storeUrls = store.urls ?? [];
|
||||
const requestedUrl = url?.trim();
|
||||
let selectedUrl: string | undefined;
|
||||
if (requestedUrl) {
|
||||
selectedUrl = storeUrls.find(u => u === requestedUrl);
|
||||
if (!selectedUrl) {
|
||||
throw new Error('Vybraná URL nepatří k tomuto obchodu');
|
||||
}
|
||||
} else if (storeUrls.length === 1) {
|
||||
// Obchod má jedinou nabídku — vybírat není z čeho
|
||||
selectedUrl = storeUrls[0];
|
||||
}
|
||||
const data = await getExtraData(date);
|
||||
const canonical = stores.find(s => s.name.toLowerCase() === name.trim().toLowerCase())!.name;
|
||||
const group: OrderGroup = {
|
||||
id: crypto.randomUUID(),
|
||||
name: canonical,
|
||||
name: store.name,
|
||||
creatorLogin,
|
||||
state: GroupState.OPEN,
|
||||
members: { [creatorLogin]: {} },
|
||||
...(selectedUrl ? { url: selectedUrl } : {}),
|
||||
};
|
||||
data.groups = [...(data.groups ?? []), group];
|
||||
return saveExtraData(data, date);
|
||||
@@ -78,7 +120,7 @@ export async function addGroupMember(login: string, groupId: string, targetLogin
|
||||
const data = await getExtraData(date);
|
||||
const group = findGroup(data, groupId);
|
||||
if (!group) throw new Error('Skupina nebyla nalezena');
|
||||
if (group.state === GroupState.ORDERED) throw new Error('Skupinu ve stavu "objednáno" nelze upravovat');
|
||||
assertNotSubmitted(group);
|
||||
if (login !== group.creatorLogin && login !== targetLogin) {
|
||||
throw new Error('Přidat jiného uživatele může pouze zakladatel');
|
||||
}
|
||||
@@ -94,7 +136,7 @@ export async function removeGroupMember(login: string, groupId: string, targetLo
|
||||
const data = await getExtraData(date);
|
||||
const group = findGroup(data, groupId);
|
||||
if (!group) throw new Error('Skupina nebyla nalezena');
|
||||
if (group.state === GroupState.ORDERED) throw new Error('Skupinu ve stavu "objednáno" nelze upravovat');
|
||||
assertNotSubmitted(group);
|
||||
if (login !== group.creatorLogin && login !== targetLogin) {
|
||||
throw new Error('Odebrat jiného uživatele může pouze zakladatel');
|
||||
}
|
||||
@@ -111,7 +153,7 @@ export async function updateGroupMember(login: string, groupId: string, targetLo
|
||||
const data = await getExtraData(date);
|
||||
const group = findGroup(data, groupId);
|
||||
if (!group) throw new Error('Skupina nebyla nalezena');
|
||||
if (group.state === GroupState.ORDERED) throw new Error('Skupinu ve stavu "objednáno" nelze upravovat');
|
||||
assertNotSubmitted(group);
|
||||
const isSelf = login === targetLogin;
|
||||
const isCreator = login === group.creatorLogin;
|
||||
if (!isSelf && !isCreator) throw new Error('Upravit jiného uživatele může pouze zakladatel');
|
||||
@@ -126,7 +168,8 @@ export async function updateGroupMember(login: string, groupId: string, targetLo
|
||||
const VALID_TRANSITIONS: Record<GroupState, GroupState[]> = {
|
||||
[GroupState.OPEN]: [GroupState.LOCKED],
|
||||
[GroupState.LOCKED]: [GroupState.OPEN, GroupState.ORDERED],
|
||||
[GroupState.ORDERED]: [GroupState.LOCKED],
|
||||
[GroupState.ORDERED]: [GroupState.LOCKED, GroupState.DELIVERED],
|
||||
[GroupState.DELIVERED]: [GroupState.ORDERED],
|
||||
};
|
||||
|
||||
function getCurrentHHMM(): string {
|
||||
@@ -140,7 +183,7 @@ export async function setGroupState(login: string, groupId: string, newState: Gr
|
||||
if (!group) throw new Error('Skupina nebyla nalezena');
|
||||
if (group.creatorLogin !== login) throw new Error('Stav může měnit pouze zakladatel');
|
||||
if (!VALID_TRANSITIONS[group.state].includes(newState)) {
|
||||
throw new Error(`Nelze přejít ze stavu "${group.state}" do stavu "${newState}"`);
|
||||
throw new Error(`Nelze přejít ze stavu "${STATE_LABEL[group.state]}" do stavu "${STATE_LABEL[newState]}"`);
|
||||
}
|
||||
if (newState === GroupState.ORDERED) {
|
||||
group.orderedAt = getCurrentHHMM();
|
||||
@@ -163,14 +206,19 @@ export async function setGroupState(login: string, groupId: string, newState: Gr
|
||||
return saveExtraData(data, date);
|
||||
}
|
||||
|
||||
export async function markGroupQrGenerated(login: string, groupId: string, date?: Date): Promise<void> {
|
||||
/**
|
||||
* Označí skupinu za vygenerovanou (blokuje opakované generování QR) a zároveň ji
|
||||
* překlopí do stavu "doručeno" — generování QR je poslední krok objednávky.
|
||||
*/
|
||||
export async function markGroupQrGenerated(login: string, groupId: string, date?: Date): Promise<ClientData> {
|
||||
const data = await getExtraData(date);
|
||||
const group = findGroup(data, groupId);
|
||||
if (!group) throw new Error('Skupina nebyla nalezena');
|
||||
if (group.creatorLogin !== login) throw new Error('QR kódy může generovat pouze zakladatel');
|
||||
if (group.state !== GroupState.ORDERED) throw new Error('QR kódy lze generovat pouze ve stavu "objednáno"');
|
||||
if (!isSubmitted(group.state)) throw new Error('QR kódy lze generovat pouze ve stavu "objednáno" nebo "doručeno"');
|
||||
group.qrGenerated = true;
|
||||
await saveExtraData(data, date);
|
||||
group.state = GroupState.DELIVERED;
|
||||
return saveExtraData(data, date);
|
||||
}
|
||||
|
||||
export async function markGroupMemberPaid(login: string, groupId: string, date?: Date): Promise<ClientData | null> {
|
||||
@@ -186,7 +234,7 @@ export async function updateGroupFees(login: string, groupId: string, fees?: num
|
||||
const group = findGroup(data, groupId);
|
||||
if (!group) throw new Error('Skupina nebyla nalezena');
|
||||
if (group.creatorLogin !== login) throw new Error('Poplatky může měnit pouze zakladatel');
|
||||
if (group.state === GroupState.ORDERED) throw new Error('Skupinu ve stavu "objednáno" nelze upravovat');
|
||||
assertNotSubmitted(group);
|
||||
if (fees !== undefined) group.fees = fees > 0 ? fees : undefined;
|
||||
if (shipping !== undefined) group.shipping = shipping > 0 ? shipping : undefined;
|
||||
if (tip !== undefined) group.tip = tip > 0 ? tip : undefined;
|
||||
@@ -216,7 +264,7 @@ export async function setGroupTracking(login: string, groupId: string, shareUrl?
|
||||
group.trackingOrderState = undefined;
|
||||
group.trackingCourierState = undefined;
|
||||
} else {
|
||||
if (group.state !== GroupState.ORDERED) throw new Error('Sledování objednávky lze nastavit pouze ve stavu "objednáno"');
|
||||
if (!isSubmitted(group.state)) throw new Error('Sledování objednávky lze nastavit pouze ve stavu "objednáno" nebo "doručeno"');
|
||||
const tracking = extractTracking(shareUrl);
|
||||
if (!tracking) throw new Error('Neplatný odkaz na sledování objednávky');
|
||||
if (tracking.code !== group.trackingCode || tracking.provider !== group.trackingProvider) {
|
||||
|
||||
@@ -22,7 +22,9 @@ const SOUP_NAMES = [
|
||||
'zeleninová s ',
|
||||
'hovězí s ',
|
||||
'kachní kaldoun',
|
||||
'dršťková'
|
||||
'dršťková',
|
||||
'žampionový krém',
|
||||
'zelná',
|
||||
];
|
||||
const DAYS_IN_WEEK = ['pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota', 'neděle'];
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@ import { getWebsocket } from "../websocket";
|
||||
import { getLogin } from "../auth";
|
||||
import { parseToken } from "../utils";
|
||||
import webpush from 'web-push';
|
||||
import { ClientData, GroupState, TrackingProvider } from "../../../types/gen/types.gen";
|
||||
import { ClientData, GroupState, MealSlot, OrderGroupMember, TrackingProvider } from "../../../types/gen/types.gen";
|
||||
import { getStores } from "../stores";
|
||||
import { createGroup } from "../groups";
|
||||
import {
|
||||
startBoltSimulation, advanceBoltSimulation, setBoltSimulationStep,
|
||||
stopBoltSimulationByGroup, getBoltSimulation,
|
||||
@@ -36,6 +38,39 @@ const LUNCH_CHOICES = [
|
||||
'ROZHODUJI',
|
||||
];
|
||||
|
||||
// Náhodné názvy jídel do poznámek mock objednávek
|
||||
const MOCK_ORDER_FOODS = [
|
||||
'Malá kuřecí tortilla',
|
||||
'Jalapenos burger',
|
||||
'Chicken Palak',
|
||||
'Pad Thai s kuřecím',
|
||||
'Bún bò nam bo',
|
||||
'Trhané hovězí v bulce',
|
||||
'Caesar salát s kuřetem',
|
||||
'Kuřecí vindaloo',
|
||||
'Smažený sýr s hranolkami',
|
||||
'Pizza Diavola',
|
||||
'Burrito s trhaným masem',
|
||||
'Ramen s vepřovým bůčkem',
|
||||
'Falafel wrap v pitě',
|
||||
'Krůtí steak s bramborovou kaší',
|
||||
'Gyros se zeleninou',
|
||||
'Losos s grilovanou zeleninou',
|
||||
'Svíčková na smetaně s knedlíkem',
|
||||
'Kuřecí kung pao',
|
||||
'Poke bowl s tuňákem',
|
||||
'Vepřový řízek s bramborovým salátem',
|
||||
];
|
||||
|
||||
/** Výchozí hodnoty dialogu pro generování mock objednávek. */
|
||||
const DEFAULT_ORDER_MEMBER_COUNT = 3;
|
||||
const DEFAULT_MIN_AMOUNT = 100;
|
||||
const DEFAULT_MAX_AMOUNT = 1000;
|
||||
/** Nejvyšší povolený počet osob doplněných do jedné skupiny. */
|
||||
const MAX_ORDER_MEMBER_COUNT = 50;
|
||||
/** Nejvyšší povolená částka (v Kč) — musí odpovídat OpenAPI definici. */
|
||||
const MAX_ORDER_AMOUNT = 100000;
|
||||
|
||||
// Restaurace s menu
|
||||
const RESTAURANTS_WITH_MENU = [
|
||||
'SLADOVNICKA',
|
||||
@@ -249,6 +284,112 @@ router.post("/testPush", async (req, res, next) => {
|
||||
} catch (e: any) { next(e) }
|
||||
});
|
||||
|
||||
// --- DEV mock data pro sekci Objednání ---
|
||||
|
||||
/** Vrátí náhodné celé číslo z intervalu <min, max>. */
|
||||
function randomInt(min: number, max: number): number {
|
||||
return min + Math.floor(Math.random() * (max - min + 1));
|
||||
}
|
||||
|
||||
/** Vrátí náhodný prvek neprázdného pole. */
|
||||
function randomItem<Type>(items: Type[]): Type {
|
||||
return items[randomInt(0, items.length - 1)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vybere jméno, které ve skupině ještě není použité.
|
||||
* Po vyčerpání seznamu jmen přidává číselný sufix (Alice2, Alice3, …).
|
||||
*/
|
||||
function pickMemberName(members: Record<string, OrderGroupMember>): string {
|
||||
const free = MOCK_NAMES.filter(name => !members[name]);
|
||||
if (free.length > 0) {
|
||||
return randomItem(free);
|
||||
}
|
||||
const base = randomItem(MOCK_NAMES);
|
||||
let suffix = 2;
|
||||
while (members[`${base}${suffix}`]) {
|
||||
suffix++;
|
||||
}
|
||||
return `${base}${suffix}`;
|
||||
}
|
||||
|
||||
/** Rozešle klientům aktuální data sekce Objednání (dnešní den). */
|
||||
async function broadcastExtra() {
|
||||
getWebsocket().emit("message", await getData(getToday(), MealSlot.EXTRA));
|
||||
}
|
||||
|
||||
/**
|
||||
* Vygeneruje mock data pro sekci Objednání — vždy jen pro aktuální den.
|
||||
* Do každé existující skupiny doplní zadaný počet osob s náhodnou částkou
|
||||
* a názvem náhodného jídla v poznámce. Pokud žádná skupina neexistuje,
|
||||
* založí jednu z náhodně vybraného obchodu.
|
||||
*/
|
||||
router.post("/generateOrders", async (req: Request<{}, any, any>, res, next) => {
|
||||
try {
|
||||
const login = getLogin(parseToken(req));
|
||||
const count: number = req.body?.count ?? DEFAULT_ORDER_MEMBER_COUNT;
|
||||
const minAmount: number = req.body?.minAmount ?? DEFAULT_MIN_AMOUNT;
|
||||
const maxAmount: number = req.body?.maxAmount ?? DEFAULT_MAX_AMOUNT;
|
||||
|
||||
if (!Number.isInteger(count) || count < 1 || count > MAX_ORDER_MEMBER_COUNT) {
|
||||
return res.status(400).json({ error: `Počet osob musí být celé číslo mezi 1 a ${MAX_ORDER_MEMBER_COUNT}` });
|
||||
}
|
||||
if (!Number.isInteger(minAmount) || !Number.isInteger(maxAmount)
|
||||
|| minAmount < 0 || maxAmount > MAX_ORDER_AMOUNT || minAmount > maxAmount) {
|
||||
return res.status(400).json({ error: 'Neplatný rozsah částek' });
|
||||
}
|
||||
|
||||
const stores = await getStores();
|
||||
if (stores.length === 0) {
|
||||
return res.status(400).json({ error: 'Není nadefinován žádný obchod — mock data pro objednávání nelze vygenerovat' });
|
||||
}
|
||||
|
||||
const key = `${formatDate(getToday())}_extra`;
|
||||
const existing = await storage.getData<ClientData>(key);
|
||||
let createdGroupId: string | undefined;
|
||||
|
||||
// Bez skupiny není kam objednávky doplnit — jednu založíme z náhodně vybraného obchodu
|
||||
if (!existing?.groups?.length) {
|
||||
const store = randomItem(stores);
|
||||
const urls = store.urls ?? [];
|
||||
const created = await createGroup(login, store.name, undefined, urls.length > 0 ? randomItem(urls) : undefined);
|
||||
createdGroupId = created.groups?.[created.groups.length - 1]?.id;
|
||||
}
|
||||
|
||||
const results: { id: string, name: string, added: number, created?: boolean }[] = [];
|
||||
await storage.updateData<ClientData>(key, current => {
|
||||
const data = current!;
|
||||
// Mutátor může být (u Redis) zavolán opakovaně — výsledky proto vždy sestavíme znovu
|
||||
results.length = 0;
|
||||
for (const group of data.groups ?? []) {
|
||||
for (let i = 0; i < count; i++) {
|
||||
group.members[pickMemberName(group.members)] = {
|
||||
amount: randomInt(minAmount, maxAmount) * 100,
|
||||
note: randomItem(MOCK_ORDER_FOODS),
|
||||
};
|
||||
}
|
||||
results.push({
|
||||
id: group.id,
|
||||
name: group.name,
|
||||
added: count,
|
||||
...(group.id === createdGroupId ? { created: true } : {}),
|
||||
});
|
||||
}
|
||||
return data;
|
||||
});
|
||||
|
||||
await broadcastExtra();
|
||||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
count: results.reduce((sum, group) => sum + group.added, 0),
|
||||
groups: results,
|
||||
});
|
||||
} catch (e: any) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
// --- DEV simulace sledování Bolt Food (Wolt simulaci zatím nemá) ---
|
||||
|
||||
/** Nastaví/zruší sledovací token skupiny a zajistí stav ORDERED. Vrátí aktualizovaná data. */
|
||||
|
||||
@@ -21,12 +21,15 @@ router.get("/dates", async (_req, res, next) => {
|
||||
|
||||
router.post("/create", async (req: Request, res, next) => {
|
||||
const login = getLogin(parseToken(req));
|
||||
const { name } = req.body ?? {};
|
||||
const { name, url } = req.body ?? {};
|
||||
if (!name || typeof name !== 'string') {
|
||||
return res.status(400).json({ error: 'Nebyl předán název skupiny' });
|
||||
}
|
||||
if (url != null && typeof url !== 'string') {
|
||||
return res.status(400).json({ error: 'Neplatná URL nabídky' });
|
||||
}
|
||||
try {
|
||||
const data = await createGroup(login, name);
|
||||
const data = await createGroup(login, name, undefined, url);
|
||||
broadcastExtra(data);
|
||||
res.status(200).json(data);
|
||||
} catch (e: any) { next(e); }
|
||||
|
||||
@@ -4,7 +4,7 @@ import { parseToken, formatDate } from "../utils";
|
||||
import { generateQr } from "../qr";
|
||||
import { addPendingQr } from "../pizza";
|
||||
import { markGroupQrGenerated } from "../groups";
|
||||
import { emitToUser } from "../websocket";
|
||||
import { emitToUser, getWebsocket } from "../websocket";
|
||||
import { GenerateQrData } from "../../../types";
|
||||
import crypto from "crypto";
|
||||
|
||||
@@ -59,7 +59,9 @@ router.post("/generate", async (req: Request<{}, any, GenerateQrData["body"]>, r
|
||||
}
|
||||
|
||||
if (groupId) {
|
||||
await markGroupQrGenerated(login, groupId);
|
||||
// Skupina se zároveň překlopí do stavu "doručeno" — rozešleme nová data všem
|
||||
const data = await markGroupQrGenerated(login, groupId);
|
||||
getWebsocket().emit("message", data);
|
||||
}
|
||||
|
||||
res.status(200).json({ success: true, count: recipients.length });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import express from "express";
|
||||
import { getStores, addStore, removeStore } from "../stores";
|
||||
import { getStores, addStore, updateStore, removeStore } from "../stores";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -11,18 +11,43 @@ router.get("/", async (_req, res, next) => {
|
||||
});
|
||||
|
||||
router.post("/add", async (req, res, next) => {
|
||||
const { name, heslo, url } = req.body ?? {};
|
||||
const { name, heslo, urls } = req.body ?? {};
|
||||
if (!name || typeof name !== 'string') {
|
||||
return res.status(400).json({ error: 'Nebyl předán název obchodu' });
|
||||
}
|
||||
if (!heslo || typeof heslo !== 'string') {
|
||||
return res.status(400).json({ error: 'Nebylo předáno heslo' });
|
||||
}
|
||||
if (url != null && typeof url !== 'string') {
|
||||
return res.status(400).json({ error: 'Neplatná URL obchodu' });
|
||||
if (urls != null && (!Array.isArray(urls) || urls.some((u: unknown) => typeof u !== 'string'))) {
|
||||
return res.status(400).json({ error: 'Neplatný seznam URL obchodu' });
|
||||
}
|
||||
try {
|
||||
const stores = await addStore(name, heslo, url);
|
||||
const stores = await addStore(name, heslo, urls);
|
||||
res.status(200).json(stores);
|
||||
} catch (e: any) {
|
||||
if (e.message === 'UNAUTHORIZED') {
|
||||
return res.status(403).json({ error: 'Nesprávné heslo' });
|
||||
}
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/update", async (req, res, next) => {
|
||||
const { name, newName, heslo, urls } = req.body ?? {};
|
||||
if (!name || typeof name !== 'string') {
|
||||
return res.status(400).json({ error: 'Nebyl předán název obchodu' });
|
||||
}
|
||||
if (!heslo || typeof heslo !== 'string') {
|
||||
return res.status(400).json({ error: 'Nebylo předáno heslo' });
|
||||
}
|
||||
if (newName != null && typeof newName !== 'string') {
|
||||
return res.status(400).json({ error: 'Neplatný název obchodu' });
|
||||
}
|
||||
if (urls != null && (!Array.isArray(urls) || urls.some((u: unknown) => typeof u !== 'string'))) {
|
||||
return res.status(400).json({ error: 'Neplatný seznam URL obchodu' });
|
||||
}
|
||||
try {
|
||||
const stores = await updateStore(name, heslo, newName ?? undefined, urls ?? undefined);
|
||||
res.status(200).json(stores);
|
||||
} catch (e: any) {
|
||||
if (e.message === 'UNAUTHORIZED') {
|
||||
|
||||
@@ -259,8 +259,10 @@ export async function getRestaurantMenu(restaurant: Restaurant, date?: Date, for
|
||||
const lastFetchExpired = !existingMenu?.lastUpdate ||
|
||||
existingMenu.lastUpdate === now || // freshly initialized, never fetched
|
||||
(now - existingMenu.lastUpdate) > MENU_REFETCH_TTL_MS;
|
||||
const shouldFetch = forceRefresh ||
|
||||
(!existingMenu?.food?.length && !existingMenu?.closed && lastFetchExpired);
|
||||
// Data označená jako "z minulého týdne" se musí zkoušet načíst znovu, jinak by u nich
|
||||
// varování zůstalo viset celý týden i poté, co podnik nabídku na svém webu aktualizuje.
|
||||
const needsData = existingMenu?.isStale || (!existingMenu?.food?.length && !existingMenu?.closed);
|
||||
const shouldFetch = forceRefresh || (needsData && lastFetchExpired);
|
||||
if (shouldFetch) {
|
||||
const firstDay = getFirstWorkDayOfWeek(usedDate);
|
||||
|
||||
|
||||
+100
-20
@@ -4,16 +4,68 @@ import getStorage from "./storage";
|
||||
const storage = getStorage();
|
||||
const STORES_KEY = 'stores';
|
||||
|
||||
/** Maximální počet URL na jeden obchod (ochrana proti nafouknutí dat). */
|
||||
const MAX_URLS = 10;
|
||||
|
||||
/**
|
||||
* Vrátí seznam povolených obchodů. Zachovává zpětnou kompatibilitu se starším
|
||||
* formátem, kdy byly obchody uloženy jako pole řetězců (převede je na objekty).
|
||||
* Podoby, v jakých mohou být obchody uloženy ve storage:
|
||||
* - řetězec — nejstarší formát (jen název),
|
||||
* - objekt s `url` — formát s jednou URL na nabídku,
|
||||
* - objekt s `urls` — aktuální formát s více URL.
|
||||
*/
|
||||
type StoredStore = string | { name: string; url?: string; urls?: string[] };
|
||||
|
||||
/**
|
||||
* Vrátí seznam povolených obchodů. Zachovává zpětnou kompatibilitu se staršími
|
||||
* formáty uložených dat (pole řetězců, resp. jediná URL v poli `url`) — vše
|
||||
* převede na aktuální podobu se seznamem `urls`.
|
||||
*/
|
||||
export async function getStores(): Promise<Store[]> {
|
||||
const raw = await storage.getData<(string | Store)[]>(STORES_KEY);
|
||||
const raw = await storage.getData<StoredStore[]>(STORES_KEY);
|
||||
if (!raw) {
|
||||
return [];
|
||||
}
|
||||
return raw.map(s => (typeof s === 'string' ? { name: s } : s));
|
||||
return raw.map(s => {
|
||||
if (typeof s === 'string') {
|
||||
return { name: s };
|
||||
}
|
||||
const urls = s.urls ?? (s.url ? [s.url] : []);
|
||||
return urls.length > 0 ? { name: s.name, urls } : { name: s.name };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ověří a upraví seznam URL obchodu — ořeže mezery, zahodí prázdné hodnoty,
|
||||
* odstraní duplicity a zkontroluje, že jde o platné http(s) odkazy.
|
||||
*/
|
||||
function normalizeUrls(urls?: string[]): string[] {
|
||||
if (!urls) {
|
||||
return [];
|
||||
}
|
||||
const result: string[] = [];
|
||||
for (const raw of urls) {
|
||||
const trimmed = raw?.trim();
|
||||
if (!trimmed) {
|
||||
continue;
|
||||
}
|
||||
// Povolíme pouze http(s), aby URL nemohla být zneužita (např. javascript: → XSS)
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(trimmed);
|
||||
} catch {
|
||||
throw new Error('Neplatná URL obchodu');
|
||||
}
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error('URL musí začínat http:// nebo https://');
|
||||
}
|
||||
if (!result.some(u => u.toLowerCase() === trimmed.toLowerCase())) {
|
||||
result.push(trimmed);
|
||||
}
|
||||
}
|
||||
if (result.length > MAX_URLS) {
|
||||
throw new Error(`Obchod může mít nejvýše ${MAX_URLS} URL`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -21,9 +73,9 @@ export async function getStores(): Promise<Store[]> {
|
||||
*
|
||||
* @param name název obchodu
|
||||
* @param heslo admin heslo
|
||||
* @param url volitelná URL na nabídku podniku
|
||||
* @param urls volitelný seznam URL na nabídku podniku (různé dovozové služby)
|
||||
*/
|
||||
export async function addStore(name: string, heslo: string, url?: string): Promise<Store[]> {
|
||||
export async function addStore(name: string, heslo: string, urls?: string[]): Promise<Store[]> {
|
||||
const adminPassword = process.env.ADMIN_PASSWORD;
|
||||
if (!adminPassword || heslo !== adminPassword) {
|
||||
throw new Error('UNAUTHORIZED');
|
||||
@@ -36,25 +88,53 @@ export async function addStore(name: string, heslo: string, url?: string): Promi
|
||||
if (stores.some(s => s.name.toLowerCase() === trimmed.toLowerCase())) {
|
||||
throw new Error('Obchod s tímto názvem již existuje');
|
||||
}
|
||||
const trimmedUrl = url?.trim();
|
||||
if (trimmedUrl) {
|
||||
// Povolíme pouze http(s), aby URL nemohla být zneužita (např. javascript: → XSS)
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(trimmedUrl);
|
||||
} catch {
|
||||
throw new Error('Neplatná URL obchodu');
|
||||
}
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new Error('URL musí začínat http:// nebo https://');
|
||||
}
|
||||
}
|
||||
const store: Store = trimmedUrl ? { name: trimmed, url: trimmedUrl } : { name: trimmed };
|
||||
const normalizedUrls = normalizeUrls(urls);
|
||||
const store: Store = normalizedUrls.length > 0 ? { name: trimmed, urls: normalizedUrls } : { name: trimmed };
|
||||
const updated = [...stores, store];
|
||||
await storage.setData(STORES_KEY, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upraví existující obchod — název a/nebo seznam URL na nabídku.
|
||||
*
|
||||
* @param name aktuální název obchodu (identifikuje upravovaný obchod)
|
||||
* @param heslo admin heslo
|
||||
* @param newName nový název; pokud není předán, název zůstane nezměněn
|
||||
* @param urls nový seznam URL (nahradí stávající); pokud není předán, URL zůstanou nezměněné
|
||||
*/
|
||||
export async function updateStore(name: string, heslo: string, newName?: string, urls?: string[]): Promise<Store[]> {
|
||||
const adminPassword = process.env.ADMIN_PASSWORD;
|
||||
if (!adminPassword || heslo !== adminPassword) {
|
||||
throw new Error('UNAUTHORIZED');
|
||||
}
|
||||
const stores = await getStores();
|
||||
const index = stores.findIndex(s => s.name.toLowerCase() === name.trim().toLowerCase());
|
||||
if (index < 0) {
|
||||
throw new Error('Obchod nebyl nalezen');
|
||||
}
|
||||
const current = stores[index];
|
||||
|
||||
let finalName = current.name;
|
||||
if (newName !== undefined) {
|
||||
const trimmedName = newName.trim();
|
||||
if (!trimmedName) {
|
||||
throw new Error('Název obchodu nesmí být prázdný');
|
||||
}
|
||||
// Nový název nesmí kolidovat s jiným obchodem (shoda se sebou samým je v pořádku)
|
||||
if (stores.some((s, i) => i !== index && s.name.toLowerCase() === trimmedName.toLowerCase())) {
|
||||
throw new Error('Obchod s tímto názvem již existuje');
|
||||
}
|
||||
finalName = trimmedName;
|
||||
}
|
||||
|
||||
const finalUrls = urls !== undefined ? normalizeUrls(urls) : (current.urls ?? []);
|
||||
const updatedStore: Store = finalUrls.length > 0 ? { name: finalName, urls: finalUrls } : { name: finalName };
|
||||
const updated = stores.map((s, i) => (i === index ? updatedStore : s));
|
||||
await storage.setData(STORES_KEY, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Odebere obchod ze seznamu povolených (dle názvu).
|
||||
*
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
import bodyParser from 'body-parser';
|
||||
import { generateToken } from '../auth';
|
||||
import { resetMemoryStorage } from '../storage/memory';
|
||||
import getStorage from '../storage';
|
||||
import devRouter from '../routes/devRoutes';
|
||||
import { createGroup } from '../groups';
|
||||
import { ClientData, Store } from '../../../types/gen/types.gen';
|
||||
import { formatDate } from '../utils';
|
||||
import { getToday } from '../service';
|
||||
|
||||
// Websocket v testech neexistuje – broadcast jen odchytíme
|
||||
jest.mock('../websocket', () => ({
|
||||
getWebsocket: () => ({ emit: jest.fn() }),
|
||||
emitToUser: jest.fn(),
|
||||
}));
|
||||
|
||||
const storage = getStorage();
|
||||
const TOKEN = `Bearer ${generateToken('testuser')}`;
|
||||
|
||||
function buildApp() {
|
||||
const app = express();
|
||||
app.use(bodyParser.json());
|
||||
app.use('/api/dev', devRouter);
|
||||
app.use((err: any, _req: any, res: any, _next: any) => {
|
||||
res.status(400).json({ error: err.message });
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
/** Vrátí uložená data sekce Objednání pro dnešní den. */
|
||||
async function getExtra(): Promise<ClientData | undefined> {
|
||||
return storage.getData<ClientData>(`${formatDate(getToday())}_extra`);
|
||||
}
|
||||
|
||||
async function setStores(stores: Store[]) {
|
||||
await storage.setData('stores', stores);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetMemoryStorage();
|
||||
});
|
||||
|
||||
test('POST /dev/generateOrders bez nadefinovaného obchodu vrátí 400', async () => {
|
||||
const res = await request(buildApp())
|
||||
.post('/api/dev/generateOrders')
|
||||
.set('Authorization', TOKEN)
|
||||
.send({});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
test('POST /dev/generateOrders bez existující skupiny založí jednu a doplní do ní osoby', async () => {
|
||||
await setStores([{ name: 'Bistro', urls: ['https://example.com/bistro'] }]);
|
||||
|
||||
const res = await request(buildApp())
|
||||
.post('/api/dev/generateOrders')
|
||||
.set('Authorization', TOKEN)
|
||||
.send({ count: 4, minAmount: 100, maxAmount: 1000 });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.count).toBe(4);
|
||||
expect(res.body.groups).toHaveLength(1);
|
||||
expect(res.body.groups[0].created).toBe(true);
|
||||
|
||||
const data = await getExtra();
|
||||
const group = data?.groups?.[0];
|
||||
expect(group?.name).toBe('Bistro');
|
||||
expect(group?.url).toBe('https://example.com/bistro');
|
||||
// Zakladatel (přihlášený uživatel) + 4 doplněné osoby
|
||||
const members = Object.entries(group!.members);
|
||||
expect(members).toHaveLength(5);
|
||||
const mockMembers = members.filter(([login]) => login !== 'testuser');
|
||||
expect(mockMembers).toHaveLength(4);
|
||||
for (const [, member] of mockMembers) {
|
||||
expect(member.amount).toBeGreaterThanOrEqual(100 * 100);
|
||||
expect(member.amount).toBeLessThanOrEqual(1000 * 100);
|
||||
expect(member.note).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /dev/generateOrders doplní osoby do všech existujících skupin', async () => {
|
||||
await setStores([{ name: 'Bistro' }, { name: 'Pizzerie' }]);
|
||||
await createGroup('testuser', 'Bistro');
|
||||
await createGroup('kolega', 'Pizzerie');
|
||||
|
||||
const res = await request(buildApp())
|
||||
.post('/api/dev/generateOrders')
|
||||
.set('Authorization', TOKEN)
|
||||
.send({ count: 2 });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.count).toBe(4);
|
||||
expect(res.body.groups).toHaveLength(2);
|
||||
expect(res.body.groups.every((g: any) => g.created === undefined)).toBe(true);
|
||||
|
||||
const data = await getExtra();
|
||||
expect(data?.groups).toHaveLength(2);
|
||||
for (const group of data!.groups!) {
|
||||
// Zakladatel + 2 doplněné osoby
|
||||
expect(Object.keys(group.members)).toHaveLength(3);
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /dev/generateOrders použije výchozí hodnoty, když nejsou zadány', async () => {
|
||||
await setStores([{ name: 'Bistro' }]);
|
||||
|
||||
const res = await request(buildApp())
|
||||
.post('/api/dev/generateOrders')
|
||||
.set('Authorization', TOKEN)
|
||||
.send({});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
// Výchozí počet osob je 3
|
||||
expect(res.body.count).toBe(3);
|
||||
|
||||
const data = await getExtra();
|
||||
for (const [login, member] of Object.entries(data!.groups![0].members)) {
|
||||
if (login === 'testuser') continue;
|
||||
// Výchozí rozsah částek je 100–1000 Kč
|
||||
expect(member.amount).toBeGreaterThanOrEqual(100 * 100);
|
||||
expect(member.amount).toBeLessThanOrEqual(1000 * 100);
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /dev/generateOrders zvládne počet osob přesahující seznam jmen', async () => {
|
||||
await setStores([{ name: 'Bistro' }]);
|
||||
|
||||
const res = await request(buildApp())
|
||||
.post('/api/dev/generateOrders')
|
||||
.set('Authorization', TOKEN)
|
||||
.send({ count: 50 });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.count).toBe(50);
|
||||
|
||||
const data = await getExtra();
|
||||
// Všechna jména musí být unikátní (zakladatel + 50 doplněných osob)
|
||||
expect(Object.keys(data!.groups![0].members)).toHaveLength(51);
|
||||
});
|
||||
|
||||
test('POST /dev/generateOrders odmítne neplatný počet osob a rozsah částek', async () => {
|
||||
await setStores([{ name: 'Bistro' }]);
|
||||
const app = buildApp();
|
||||
|
||||
const badCount = await request(app)
|
||||
.post('/api/dev/generateOrders')
|
||||
.set('Authorization', TOKEN)
|
||||
.send({ count: 0 });
|
||||
expect(badCount.status).toBe(400);
|
||||
|
||||
const badRange = await request(app)
|
||||
.post('/api/dev/generateOrders')
|
||||
.set('Authorization', TOKEN)
|
||||
.send({ minAmount: 500, maxAmount: 100 });
|
||||
expect(badRange.status).toBe(400);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { resetMemoryStorage } from '../storage/memory';
|
||||
import { getStores, addStore } from '../stores';
|
||||
import { createGroup, deleteGroup, addGroupMember, removeGroupMember, updateGroupMember, setGroupState, setGroupTracking, markGroupMemberPaid } from '../groups';
|
||||
import { createGroup, deleteGroup, addGroupMember, removeGroupMember, updateGroupMember, setGroupState, setGroupTracking, markGroupMemberPaid, markGroupQrGenerated } from '../groups';
|
||||
import { GroupState } from '../../../types/gen/types.gen';
|
||||
|
||||
const CREATOR = 'tomas';
|
||||
@@ -40,6 +40,42 @@ describe('createGroup', () => {
|
||||
expect(d2.groups).toHaveLength(2);
|
||||
expect(d2.groups![1].id).not.toBe(d2.groups![0].id);
|
||||
});
|
||||
|
||||
describe('výběr URL na nabídku', () => {
|
||||
const MULTI_STORE = 'Bistro';
|
||||
const WOLT_URL = 'https://wolt.com/bistro';
|
||||
const BOLT_URL = 'https://food.bolt.eu/bistro';
|
||||
|
||||
beforeEach(async () => {
|
||||
await addStore(MULTI_STORE, ADMIN_PW, [WOLT_URL, BOLT_URL]);
|
||||
});
|
||||
|
||||
test('uloží vybranou URL do skupiny', async () => {
|
||||
const data = await createGroup(CREATOR, MULTI_STORE, TODAY, BOLT_URL);
|
||||
expect(data.groups![0].url).toBe(BOLT_URL);
|
||||
});
|
||||
|
||||
test('odmítne URL, která k obchodu nepatří', async () => {
|
||||
await expect(createGroup(CREATOR, MULTI_STORE, TODAY, 'https://wolt.com/jine'))
|
||||
.rejects.toThrow('nepatří');
|
||||
});
|
||||
|
||||
test('bez výběru zůstane skupina bez URL, když má obchod více nabídek', async () => {
|
||||
const data = await createGroup(CREATOR, MULTI_STORE, TODAY);
|
||||
expect(data.groups![0].url).toBeUndefined();
|
||||
});
|
||||
|
||||
test('dosadí jedinou URL obchodu automaticky', async () => {
|
||||
await addStore('Pizzerie', ADMIN_PW, [WOLT_URL]);
|
||||
const data = await createGroup(CREATOR, 'Pizzerie', TODAY);
|
||||
expect(data.groups![0].url).toBe(WOLT_URL);
|
||||
});
|
||||
|
||||
test('obchod bez URL vytvoří skupinu bez URL', async () => {
|
||||
const data = await createGroup(CREATOR, STORE, TODAY);
|
||||
expect(data.groups![0].url).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteGroup', () => {
|
||||
@@ -183,12 +219,48 @@ describe('setGroupState', () => {
|
||||
await expect(setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY)).rejects.toThrow('Nelze přejít');
|
||||
});
|
||||
|
||||
test('ordered je terminální stav', async () => {
|
||||
test('ordered → open není povoleno', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
await expect(setGroupState(CREATOR, groupId, GroupState.OPEN, TODAY)).rejects.toThrow('Nelze přejít');
|
||||
});
|
||||
|
||||
test('ordered → delivered', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
const d = await setGroupState(CREATOR, groupId, GroupState.DELIVERED, TODAY);
|
||||
expect(d.groups![0].state).toBe(GroupState.DELIVERED);
|
||||
});
|
||||
|
||||
test('delivered → ordered (vrácení)', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.DELIVERED, TODAY);
|
||||
const d = await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
expect(d.groups![0].state).toBe(GroupState.ORDERED);
|
||||
});
|
||||
|
||||
test('locked → delivered není povoleno', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await expect(setGroupState(CREATOR, groupId, GroupState.DELIVERED, TODAY)).rejects.toThrow('Nelze přejít');
|
||||
});
|
||||
|
||||
test('delivered → locked není povoleno', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.DELIVERED, TODAY);
|
||||
await expect(setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY)).rejects.toThrow('Nelze přejít');
|
||||
});
|
||||
|
||||
test('skupinu ve stavu delivered nelze upravovat', async () => {
|
||||
await addGroupMember(CREATOR, groupId, USER, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.DELIVERED, TODAY);
|
||||
await expect(updateGroupMember(CREATOR, groupId, USER, { amount: 100 }, TODAY)).rejects.toThrow('doručeno');
|
||||
await expect(addGroupMember(CREATOR, groupId, 'dalsi', TODAY)).rejects.toThrow('doručeno');
|
||||
});
|
||||
|
||||
test('nečlen nemůže měnit stav', async () => {
|
||||
await expect(setGroupState(USER, groupId, GroupState.LOCKED, TODAY)).rejects.toThrow('zakladatel');
|
||||
});
|
||||
@@ -204,6 +276,42 @@ describe('setGroupState', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('markGroupQrGenerated', () => {
|
||||
let groupId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
const d = await createGroup(CREATOR, STORE, TODAY);
|
||||
groupId = d.groups![0].id;
|
||||
});
|
||||
|
||||
test('ze stavu ordered přepne skupinu na delivered', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
const d = await markGroupQrGenerated(CREATOR, groupId, TODAY);
|
||||
expect(d.groups![0].state).toBe(GroupState.DELIVERED);
|
||||
expect(d.groups![0].qrGenerated).toBe(true);
|
||||
});
|
||||
|
||||
test('funguje i ve stavu delivered', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.DELIVERED, TODAY);
|
||||
const d = await markGroupQrGenerated(CREATOR, groupId, TODAY);
|
||||
expect(d.groups![0].state).toBe(GroupState.DELIVERED);
|
||||
});
|
||||
|
||||
test('ve stavu locked selže', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await expect(markGroupQrGenerated(CREATOR, groupId, TODAY)).rejects.toThrow('objednáno');
|
||||
});
|
||||
|
||||
test('QR může generovat pouze zakladatel', async () => {
|
||||
await setGroupState(CREATOR, groupId, GroupState.LOCKED, TODAY);
|
||||
await setGroupState(CREATOR, groupId, GroupState.ORDERED, TODAY);
|
||||
await expect(markGroupQrGenerated(USER, groupId, TODAY)).rejects.toThrow('zakladatel');
|
||||
});
|
||||
});
|
||||
|
||||
describe('markGroupMemberPaid', () => {
|
||||
test('označí člena jako zaplaceného pro daný den', async () => {
|
||||
const d = await createGroup(CREATOR, STORE, TODAY);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
const mockStorageData = new Map<string, any>();
|
||||
jest.mock('../storage', () => ({
|
||||
__esModule: true,
|
||||
default: () => ({
|
||||
hasData: async (key: string) => mockStorageData.has(key),
|
||||
getData: async <T>(key: string) => mockStorageData.get(key) as T,
|
||||
setData: async <T>(key: string, val: T) => void mockStorageData.set(key, val),
|
||||
}),
|
||||
storageReady: Promise.resolve(),
|
||||
}));
|
||||
|
||||
const mockGetMenuTechTower = jest.fn();
|
||||
jest.mock('../restaurants', () => ({
|
||||
...jest.requireActual('../restaurants'),
|
||||
getMenuTechTower: (...args: any[]) => mockGetMenuTechTower(...args),
|
||||
}));
|
||||
|
||||
import { getMenuKey, getRestaurantMenu } from '../service';
|
||||
|
||||
// Středa 2025-01-08 (týden 2025-02)
|
||||
const STREDA = new Date('2025-01-08T10:00:00');
|
||||
const HODINA = 60 * 60 * 1000;
|
||||
|
||||
/** Menu jednoho dne se všemi náležitostmi, aby nevznikala jiná varování. */
|
||||
const denniMenu = (nazev: string) => [
|
||||
{ amount: '-', name: `Polévka ${nazev}`, price: '30 Kč', isSoup: true },
|
||||
{ amount: '-', name: nazev, price: '150 Kč', isSoup: false },
|
||||
];
|
||||
|
||||
/** Naplní storage týdenním menu TechTower s předaným příznakem zastaralosti. */
|
||||
const seedWeekMenu = (isStale: boolean, lastUpdate: number) => {
|
||||
const week = [0, 1, 2, 3, 4].map(i => ({
|
||||
TECHTOWER: {
|
||||
lastUpdate,
|
||||
closed: false,
|
||||
isStale,
|
||||
food: denniMenu(`Jídlo z minulého týdne ${i}`),
|
||||
},
|
||||
}));
|
||||
mockStorageData.set(getMenuKey(STREDA), week);
|
||||
};
|
||||
|
||||
describe('getRestaurantMenu – obnovení dat z minulého týdne', () => {
|
||||
beforeAll(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.setSystemTime(STREDA);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockStorageData.clear();
|
||||
mockGetMenuTechTower.mockReset();
|
||||
});
|
||||
|
||||
test('zastaralá data se znovu načtou a varování zmizí', async () => {
|
||||
seedWeekMenu(true, Date.now() - 2 * HODINA);
|
||||
mockGetMenuTechTower.mockResolvedValue([0, 1, 2, 3, 4].map(i => denniMenu(`Aktuální jídlo ${i}`)));
|
||||
|
||||
const menu = await getRestaurantMenu('TECHTOWER', STREDA);
|
||||
|
||||
expect(mockGetMenuTechTower).toHaveBeenCalledTimes(1);
|
||||
expect(menu.isStale).toBe(false);
|
||||
expect(menu.food?.[1].name).toBe('Aktuální jídlo 2');
|
||||
expect(menu.warnings).not.toContain('Data jsou z minulého týdne');
|
||||
});
|
||||
|
||||
test('aktuální data se znovu nenačítají', async () => {
|
||||
seedWeekMenu(false, Date.now() - 2 * HODINA);
|
||||
|
||||
const menu = await getRestaurantMenu('TECHTOWER', STREDA);
|
||||
|
||||
expect(mockGetMenuTechTower).not.toHaveBeenCalled();
|
||||
expect(menu.warnings).toEqual([]);
|
||||
});
|
||||
|
||||
test('zastaralá data se neobnovují častěji než jednou za hodinu', async () => {
|
||||
seedWeekMenu(true, Date.now() - 5 * 60 * 1000);
|
||||
|
||||
const menu = await getRestaurantMenu('TECHTOWER', STREDA);
|
||||
|
||||
expect(mockGetMenuTechTower).not.toHaveBeenCalled();
|
||||
expect(menu.warnings).toContain('Data jsou z minulého týdne');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { resetMemoryStorage } from '../storage/memory';
|
||||
import getStorage from '../storage';
|
||||
import { getStores, addStore, removeStore } from '../stores';
|
||||
import { getStores, addStore, updateStore, removeStore } from '../stores';
|
||||
|
||||
const ADMIN_PW = 'testadmin';
|
||||
|
||||
@@ -28,6 +28,13 @@ describe('getStores', () => {
|
||||
const stores = await getStores();
|
||||
expect(stores).toEqual([{ name: 'McDonald\'s' }, { name: 'KFC' }]);
|
||||
});
|
||||
|
||||
test('převede starý formát s jednou URL na seznam urls', async () => {
|
||||
// Simulace dat uložených před zavedením více URL na jeden podnik
|
||||
await getStorage().setData('stores', [{ name: 'Bistro', url: 'https://wolt.com/bistro' }]);
|
||||
const stores = await getStores();
|
||||
expect(stores).toEqual([{ name: 'Bistro', urls: ['https://wolt.com/bistro'] }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addStore', () => {
|
||||
@@ -37,21 +44,46 @@ describe('addStore', () => {
|
||||
});
|
||||
|
||||
test('uloží volitelnou URL a ořízne mezery', async () => {
|
||||
const stores = await addStore('Bistro', ADMIN_PW, ' https://wolt.com/bistro ');
|
||||
expect(stores).toContainEqual({ name: 'Bistro', url: 'https://wolt.com/bistro' });
|
||||
const stores = await addStore('Bistro', ADMIN_PW, [' https://wolt.com/bistro ']);
|
||||
expect(stores).toContainEqual({ name: 'Bistro', urls: ['https://wolt.com/bistro'] });
|
||||
});
|
||||
|
||||
test('bez URL uloží obchod bez pole url', async () => {
|
||||
const stores = await addStore('KFC', ADMIN_PW, ' ');
|
||||
test('uloží více URL na jeden podnik (různé dovozové služby)', async () => {
|
||||
const stores = await addStore('Bistro', ADMIN_PW, [
|
||||
'https://wolt.com/bistro',
|
||||
'https://food.bolt.eu/bistro',
|
||||
]);
|
||||
expect(stores).toContainEqual({
|
||||
name: 'Bistro',
|
||||
urls: ['https://wolt.com/bistro', 'https://food.bolt.eu/bistro'],
|
||||
});
|
||||
});
|
||||
|
||||
test('zahodí prázdné URL a duplicity (case-insensitive)', async () => {
|
||||
const stores = await addStore('Bistro', ADMIN_PW, [
|
||||
'https://wolt.com/bistro',
|
||||
' ',
|
||||
'https://WOLT.com/bistro',
|
||||
]);
|
||||
expect(stores).toContainEqual({ name: 'Bistro', urls: ['https://wolt.com/bistro'] });
|
||||
});
|
||||
|
||||
test('bez URL uloží obchod bez pole urls', async () => {
|
||||
const stores = await addStore('KFC', ADMIN_PW, [' ']);
|
||||
expect(stores).toContainEqual({ name: 'KFC' });
|
||||
});
|
||||
|
||||
test('odmítne URL s nepovoleným schématem (javascript:)', async () => {
|
||||
await expect(addStore('Zlo', ADMIN_PW, 'javascript:alert(1)')).rejects.toThrow('http');
|
||||
await expect(addStore('Zlo', ADMIN_PW, ['javascript:alert(1)'])).rejects.toThrow('http');
|
||||
});
|
||||
|
||||
test('odmítne nevalidní URL', async () => {
|
||||
await expect(addStore('Zlo', ADMIN_PW, 'nfdjska')).rejects.toThrow('Neplatná URL');
|
||||
test('odmítne nevalidní URL i mezi platnými', async () => {
|
||||
await expect(addStore('Zlo', ADMIN_PW, ['https://wolt.com/x', 'nfdjska'])).rejects.toThrow('Neplatná URL');
|
||||
});
|
||||
|
||||
test('odmítne příliš mnoho URL', async () => {
|
||||
const urls = Array.from({ length: 11 }, (_, i) => `https://wolt.com/bistro${i}`);
|
||||
await expect(addStore('Bistro', ADMIN_PW, urls)).rejects.toThrow('nejvýše');
|
||||
});
|
||||
|
||||
test('vyhodí UNAUTHORIZED s nesprávným heslem', async () => {
|
||||
@@ -81,6 +113,82 @@ describe('addStore', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateStore', () => {
|
||||
const WOLT_URL = 'https://wolt.com/bistro';
|
||||
const BOLT_URL = 'https://food.bolt.eu/bistro';
|
||||
|
||||
beforeEach(async () => {
|
||||
await addStore('Bistro', ADMIN_PW, [WOLT_URL]);
|
||||
});
|
||||
|
||||
test('přidá další URL k existujícímu obchodu', async () => {
|
||||
const stores = await updateStore('Bistro', ADMIN_PW, undefined, [WOLT_URL, BOLT_URL]);
|
||||
expect(stores).toContainEqual({ name: 'Bistro', urls: [WOLT_URL, BOLT_URL] });
|
||||
});
|
||||
|
||||
test('přejmenuje obchod a zachová URL', async () => {
|
||||
const stores = await updateStore('Bistro', ADMIN_PW, ' Bistro U Nás ');
|
||||
expect(stores).toContainEqual({ name: 'Bistro U Nás', urls: [WOLT_URL] });
|
||||
});
|
||||
|
||||
test('prázdné pole URL odstraní všechny URL', async () => {
|
||||
const stores = await updateStore('Bistro', ADMIN_PW, undefined, []);
|
||||
expect(stores).toContainEqual({ name: 'Bistro' });
|
||||
});
|
||||
|
||||
test('bez předaných URL zůstanou URL nezměněné', async () => {
|
||||
const stores = await updateStore('Bistro', ADMIN_PW, 'Bistro 2');
|
||||
expect(stores).toContainEqual({ name: 'Bistro 2', urls: [WOLT_URL] });
|
||||
});
|
||||
|
||||
test('zachová pozici obchodu v seznamu', async () => {
|
||||
await addStore('KFC', ADMIN_PW);
|
||||
const stores = await updateStore('Bistro', ADMIN_PW, 'Bistro 2');
|
||||
expect(names(stores)).toEqual(['Bistro 2', 'KFC']);
|
||||
});
|
||||
|
||||
test('funguje case-insensitive dle názvu', async () => {
|
||||
const stores = await updateStore('BISTRO', ADMIN_PW, undefined, [BOLT_URL]);
|
||||
expect(stores).toContainEqual({ name: 'Bistro', urls: [BOLT_URL] });
|
||||
});
|
||||
|
||||
test('ponechání stejného názvu není bráno jako duplikát', async () => {
|
||||
const stores = await updateStore('Bistro', ADMIN_PW, 'bistro');
|
||||
expect(names(stores)).toEqual(['bistro']);
|
||||
});
|
||||
|
||||
test('odmítne název kolidující s jiným obchodem', async () => {
|
||||
await addStore('KFC', ADMIN_PW);
|
||||
await expect(updateStore('Bistro', ADMIN_PW, 'kfc')).rejects.toThrow('existuje');
|
||||
});
|
||||
|
||||
test('odmítne prázdný název', async () => {
|
||||
await expect(updateStore('Bistro', ADMIN_PW, ' ')).rejects.toThrow('prázdný');
|
||||
});
|
||||
|
||||
test('odmítne nevalidní URL', async () => {
|
||||
await expect(updateStore('Bistro', ADMIN_PW, undefined, ['javascript:alert(1)'])).rejects.toThrow('http');
|
||||
});
|
||||
|
||||
test('vyhodí chybu u neexistujícího obchodu', async () => {
|
||||
await expect(updateStore('Neexistuje', ADMIN_PW, 'Nový')).rejects.toThrow('nebyl nalezen');
|
||||
});
|
||||
|
||||
test('vyhodí UNAUTHORIZED s nesprávným heslem', async () => {
|
||||
await expect(updateStore('Bistro', 'spatne', 'Hacknuto')).rejects.toThrow('UNAUTHORIZED');
|
||||
});
|
||||
|
||||
test('vyhodí UNAUTHORIZED pokud ADMIN_PASSWORD není nastaven', async () => {
|
||||
delete process.env.ADMIN_PASSWORD;
|
||||
await expect(updateStore('Bistro', '', 'Hacknuto')).rejects.toThrow('UNAUTHORIZED');
|
||||
});
|
||||
|
||||
test('při nesprávném heslu se obchod nezmění', async () => {
|
||||
await expect(updateStore('Bistro', 'spatne', 'Hacknuto')).rejects.toThrow('UNAUTHORIZED');
|
||||
expect(names(await getStores())).toEqual(['Bistro']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeStore', () => {
|
||||
beforeEach(async () => {
|
||||
await addStore('McDonald\'s', ADMIN_PW);
|
||||
|
||||
@@ -152,6 +152,8 @@ paths:
|
||||
$ref: "./paths/stores/listStores.yml"
|
||||
/stores/add:
|
||||
$ref: "./paths/stores/addStore.yml"
|
||||
/stores/update:
|
||||
$ref: "./paths/stores/updateStore.yml"
|
||||
/stores/delete:
|
||||
$ref: "./paths/stores/deleteStore.yml"
|
||||
|
||||
@@ -160,6 +162,8 @@ paths:
|
||||
$ref: "./paths/dev/generate.yml"
|
||||
/dev/clear:
|
||||
$ref: "./paths/dev/clear.yml"
|
||||
/dev/generateOrders:
|
||||
$ref: "./paths/dev/generateOrders.yml"
|
||||
/dev/bolt/simulate:
|
||||
$ref: "./paths/dev/boltSimulate.yml"
|
||||
/dev/bolt/advance:
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
post:
|
||||
operationId: generateMockOrders
|
||||
summary: Vygenerování mock dat pro sekci Objednání – vždy jen pro aktuální den (pouze DEV režim)
|
||||
requestBody:
|
||||
required: false
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "../../schemas/_index.yml#/GenerateMockOrdersRequest"
|
||||
responses:
|
||||
"200":
|
||||
description: Mock data pro objednávání byla úspěšně vygenerována
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
success:
|
||||
type: boolean
|
||||
count:
|
||||
description: Celkový počet doplněných osob
|
||||
type: integer
|
||||
groups:
|
||||
description: Rozpis doplněných osob po skupinách
|
||||
type: array
|
||||
items:
|
||||
$ref: "../../schemas/_index.yml#/MockOrdersGroupResult"
|
||||
"400":
|
||||
description: Chybný požadavek (např. není nadefinován žádný obchod)
|
||||
"403":
|
||||
description: Endpoint není dostupný v tomto režimu
|
||||
@@ -13,6 +13,9 @@ post:
|
||||
name:
|
||||
description: Název obchodu/restaurace (musí být v seznamu povolených obchodů)
|
||||
type: string
|
||||
url:
|
||||
description: Volitelná URL na nabídku podniku (musí být jednou z URL daného obchodu). Pokud má obchod právě jednu URL, dosadí se automaticky.
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
$ref: "../../api.yml#/components/responses/ClientDataResponse"
|
||||
|
||||
@@ -14,8 +14,10 @@ post:
|
||||
name:
|
||||
description: Název obchodu/restaurace
|
||||
type: string
|
||||
url:
|
||||
description: Volitelná URL na nabídku podniku (např. Bolt Food/Wolt/Foodora)
|
||||
urls:
|
||||
description: Volitelný seznam URL na nabídku podniku (např. Bolt Food/Wolt/Foodora)
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
heslo:
|
||||
description: Admin heslo (ADMIN_PASSWORD)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
post:
|
||||
operationId: updateStore
|
||||
summary: Upraví existující obchod — název a/nebo seznam URL na nabídku (vyžaduje admin heslo).
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required:
|
||||
- name
|
||||
- heslo
|
||||
properties:
|
||||
name:
|
||||
description: Aktuální název obchodu (identifikuje upravovaný obchod)
|
||||
type: string
|
||||
newName:
|
||||
description: Nový název obchodu. Pokud není předán, název zůstane nezměněn.
|
||||
type: string
|
||||
urls:
|
||||
description: Nový seznam URL na nabídku podniku — nahradí stávající. Prázdné pole URL odstraní. Pokud není předán, URL zůstanou nezměněné.
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
heslo:
|
||||
description: Admin heslo (ADMIN_PASSWORD)
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: Obchod byl upraven
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: "../../schemas/_index.yml#/Store"
|
||||
@@ -783,6 +783,47 @@ MockDataDayResult:
|
||||
count:
|
||||
description: Počet vygenerovaných záznamů pro daný den
|
||||
type: integer
|
||||
GenerateMockOrdersRequest:
|
||||
description: Request pro generování mock dat sekce Objednání (pouze DEV režim)
|
||||
type: object
|
||||
additionalProperties: false
|
||||
properties:
|
||||
count:
|
||||
description: Počet osob, které se doplní do každé existující skupiny objednávky
|
||||
type: integer
|
||||
minimum: 1
|
||||
maximum: 50
|
||||
minAmount:
|
||||
description: Dolní hranice náhodně generované částky v Kč
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 100000
|
||||
maxAmount:
|
||||
description: Horní hranice náhodně generované částky v Kč
|
||||
type: integer
|
||||
minimum: 0
|
||||
maximum: 100000
|
||||
MockOrdersGroupResult:
|
||||
description: Výsledek doplnění mock osob do jedné skupiny objednávky
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required:
|
||||
- id
|
||||
- name
|
||||
- added
|
||||
properties:
|
||||
id:
|
||||
description: ID skupiny objednávky
|
||||
type: string
|
||||
name:
|
||||
description: Název obchodu skupiny
|
||||
type: string
|
||||
added:
|
||||
description: Počet osob doplněných do skupiny
|
||||
type: integer
|
||||
created:
|
||||
description: Příznak, zda byla skupina právě založena (neexistovala žádná)
|
||||
type: boolean
|
||||
ClearMockDataRequest:
|
||||
description: Request pro smazání mock dat (pouze DEV režim)
|
||||
type: object
|
||||
@@ -886,8 +927,10 @@ Store:
|
||||
name:
|
||||
description: Název obchodu/restaurace
|
||||
type: string
|
||||
url:
|
||||
description: Volitelná URL na nabídku podniku (např. Bolt Food/Wolt/Foodora)
|
||||
urls:
|
||||
description: Seznam URL na nabídku podniku — jeden podnik může být dostupný přes více dovozových služeb (např. Bolt Food/Wolt/Foodora)
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
|
||||
TrackingProvider:
|
||||
@@ -907,10 +950,12 @@ GroupState:
|
||||
- open
|
||||
- locked
|
||||
- ordered
|
||||
- delivered
|
||||
x-enum-varnames:
|
||||
- OPEN
|
||||
- LOCKED
|
||||
- ORDERED
|
||||
- DELIVERED
|
||||
|
||||
OrderGroupMember:
|
||||
description: Data člena skupiny objednávky
|
||||
@@ -950,6 +995,9 @@ OrderGroup:
|
||||
name:
|
||||
description: Název obchodu/restaurace
|
||||
type: string
|
||||
url:
|
||||
description: URL na nabídku podniku vybraná při zakládání skupiny (jedna z URL obchodu)
|
||||
type: string
|
||||
creatorLogin:
|
||||
description: Login zakladatele skupiny
|
||||
type: string
|
||||
|
||||
Reference in New Issue
Block a user