feat: podpora více odkazů na podnik při objednávání
This commit is contained in:
@@ -2,8 +2,9 @@ import { useState } from "react";
|
|||||||
import { Modal, Button, Form, ListGroup, Alert } from "react-bootstrap";
|
import { Modal, Button, Form, ListGroup, Alert } from "react-bootstrap";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import { faTrashCan } from "@fortawesome/free-regular-svg-icons";
|
import { faTrashCan } from "@fortawesome/free-regular-svg-icons";
|
||||||
import { faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";
|
import { faPlus, faUpRightFromSquare, faXmark } from "@fortawesome/free-solid-svg-icons";
|
||||||
import { addStore, deleteStore, Store } from "../../../../types";
|
import { addStore, deleteStore, Store } from "../../../../types";
|
||||||
|
import { getStoreUrls, storeUrlLabel } from "../../utils/storeUrls";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -14,23 +15,33 @@ type Props = {
|
|||||||
|
|
||||||
export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChanged }: Readonly<Props>) {
|
export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChanged }: Readonly<Props>) {
|
||||||
const [newName, setNewName] = useState('');
|
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 [heslo, setHeslo] = useState('');
|
const [heslo, setHeslo] = useState('');
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const setUrlAt = (index: number, value: string) =>
|
||||||
|
setNewUrls(prev => prev.map((u, i) => (i === index ? value : u)));
|
||||||
|
|
||||||
|
const addUrlRow = () => setNewUrls(prev => [...prev, '']);
|
||||||
|
|
||||||
|
const removeUrlRow = (index: number) =>
|
||||||
|
setNewUrls(prev => (prev.length === 1 ? [''] : prev.filter((_, i) => i !== index)));
|
||||||
|
|
||||||
const handleAdd = async () => {
|
const handleAdd = async () => {
|
||||||
if (!newName.trim()) return;
|
if (!newName.trim()) return;
|
||||||
setError(null);
|
setError(null);
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await addStore({ body: { name: newName.trim(), url: newUrl.trim() || undefined, heslo } });
|
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 (res.error) {
|
if (res.error) {
|
||||||
setError((res.error as any).error || 'Nastala chyba');
|
setError((res.error as any).error || 'Nastala chyba');
|
||||||
} else if (res.data) {
|
} else if (res.data) {
|
||||||
onStoresChanged(res.data as Store[]);
|
onStoresChanged(res.data as Store[]);
|
||||||
setNewName('');
|
setNewName('');
|
||||||
setNewUrl('');
|
setNewUrls(['']);
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e.message || 'Nastala chyba');
|
setError(e.message || 'Nastala chyba');
|
||||||
@@ -89,14 +100,32 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
|||||||
onChange={e => setNewName(e.target.value)}
|
onChange={e => setNewName(e.target.value)}
|
||||||
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
|
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
|
||||||
/>
|
/>
|
||||||
<div className="d-flex gap-2 mb-3">
|
{newUrls.map((url, index) => (
|
||||||
|
<div key={index} className="d-flex gap-2 mb-2 align-items-center">
|
||||||
<Form.Control
|
<Form.Control
|
||||||
type="url"
|
type="url"
|
||||||
placeholder="URL na nabídku (volitelné, např. Bolt Food/Wolt)"
|
placeholder={index === 0
|
||||||
value={newUrl}
|
? 'URL na nabídku (volitelné, např. Bolt Food/Wolt)'
|
||||||
onChange={e => setNewUrl(e.target.value)}
|
: 'Další URL na nabídku (jiná dovozová služba)'}
|
||||||
|
value={url}
|
||||||
|
onChange={e => setUrlAt(index, e.target.value)}
|
||||||
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
|
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleAdd(); }}
|
||||||
/>
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline-secondary"
|
||||||
|
onClick={() => removeUrlRow(index)}
|
||||||
|
disabled={newUrls.length === 1 && !url}
|
||||||
|
title="Odebrat tuto URL"
|
||||||
|
>
|
||||||
|
<FontAwesomeIcon icon={faXmark} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div className="d-flex justify-content-between align-items-center mb-3">
|
||||||
|
<Button variant="link" size="sm" className="p-0" onClick={addUrlRow}>
|
||||||
|
<FontAwesomeIcon icon={faPlus} className="me-1" />
|
||||||
|
Přidat další URL
|
||||||
|
</Button>
|
||||||
<Button variant="primary" onClick={handleAdd} disabled={loading || !newName.trim() || !heslo}>
|
<Button variant="primary" onClick={handleAdd} disabled={loading || !newName.trim() || !heslo}>
|
||||||
Přidat
|
Přidat
|
||||||
</Button>
|
</Button>
|
||||||
@@ -107,16 +136,29 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
|||||||
<p className="text-muted">Žádné obchody v seznamu</p>
|
<p className="text-muted">Žádné obchody v seznamu</p>
|
||||||
) : (
|
) : (
|
||||||
<ListGroup>
|
<ListGroup>
|
||||||
{stores.map(s => (
|
{stores.map(s => {
|
||||||
<ListGroup.Item key={s.name} className="d-flex justify-content-between align-items-center">
|
const urls = getStoreUrls(s);
|
||||||
<span>
|
return (
|
||||||
{s.name}
|
<ListGroup.Item key={s.name} className="d-flex justify-content-between align-items-start">
|
||||||
{s.url && /^https?:\/\//i.test(s.url) && (
|
<div>
|
||||||
<a href={s.url} target="_blank" rel="noopener noreferrer" className="ms-2" title="Otevřít nabídku v nové záložce">
|
<div>{s.name}</div>
|
||||||
<FontAwesomeIcon icon={faUpRightFromSquare} />
|
{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>
|
</a>
|
||||||
|
))}
|
||||||
|
</small>
|
||||||
)}
|
)}
|
||||||
</span>
|
</div>
|
||||||
<FontAwesomeIcon
|
<FontAwesomeIcon
|
||||||
icon={faTrashCan}
|
icon={faTrashCan}
|
||||||
className="action-icon"
|
className="action-icon"
|
||||||
@@ -125,7 +167,8 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
|||||||
style={{ cursor: 'pointer' }}
|
style={{ cursor: 'pointer' }}
|
||||||
/>
|
/>
|
||||||
</ListGroup.Item>
|
</ListGroup.Item>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</ListGroup>
|
</ListGroup>
|
||||||
)}
|
)}
|
||||||
</Modal.Body>
|
</Modal.Body>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
getData, createGroup, deleteGroup, addGroupMember, removeGroupMember, updateGroupMember, setGroupState, updateGroupTimes, setTracking, getOrderDates,
|
getData, createGroup, deleteGroup, addGroupMember, removeGroupMember, updateGroupMember, setGroupState, updateGroupTimes, setTracking, getOrderDates,
|
||||||
} from '../../../types';
|
} from '../../../types';
|
||||||
import { computeFeeShare, computeMemberTotal, countActiveMembers } from '../utils/groupFees';
|
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 { EVENT_MESSAGE, EVENT_PENDING_QR, SocketContext } from '../context/socket';
|
||||||
import { useAuth } from '../context/auth';
|
import { useAuth } from '../context/auth';
|
||||||
import { useSettings } from '../context/settings';
|
import { useSettings } from '../context/settings';
|
||||||
@@ -125,6 +126,8 @@ export default function OrderGroupsPage() {
|
|||||||
// ISO data dnů, ve kterých existuje aspoň jedna objednávka (pro zvýraznění v date pickeru)
|
// ISO data dnů, ve kterých existuje aspoň jedna objednávka (pro zvýraznění v date pickeru)
|
||||||
const [orderDates, setOrderDates] = useState<string[]>([]);
|
const [orderDates, setOrderDates] = useState<string[]>([]);
|
||||||
const [newGroupName, setNewGroupName] = useState('');
|
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 [creating, setCreating] = useState(false);
|
||||||
const [adminModalOpen, setAdminModalOpen] = useState(false);
|
const [adminModalOpen, setAdminModalOpen] = useState(false);
|
||||||
const [editAmounts, setEditAmounts] = useState<Record<string, string>>({});
|
const [editAmounts, setEditAmounts] = useState<Record<string, string>>({});
|
||||||
@@ -248,11 +251,18 @@ export default function OrderGroupsPage() {
|
|||||||
const handleCreate = async () => {
|
const handleCreate = async () => {
|
||||||
if (!newGroupName || !auth?.login) return;
|
if (!newGroupName || !auth?.login) return;
|
||||||
setCreating(true);
|
setCreating(true);
|
||||||
const ok = await refresh(() => createGroup({ body: { name: newGroupName } }));
|
// Pojistka, kdyby se seznam obchodů mezitím změnil (socket) — vezmeme první URL podniku
|
||||||
if (ok) setNewGroupName('');
|
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);
|
setCreating(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const handleJoin = (groupId: string) =>
|
const handleJoin = (groupId: string) =>
|
||||||
refresh(() => addGroupMember({ body: { id: groupId } }));
|
refresh(() => addGroupMember({ body: { id: groupId } }));
|
||||||
|
|
||||||
@@ -359,6 +369,8 @@ export default function OrderGroupsPage() {
|
|||||||
|
|
||||||
const stores = data.stores ?? [];
|
const stores = data.stores ?? [];
|
||||||
const groups = data.groups ?? [];
|
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)
|
// Zobrazené datum a režim historie (vše read-only, pokud nejde o aktuální den)
|
||||||
const displayedIso = data.isoDate;
|
const displayedIso = data.isoDate;
|
||||||
@@ -456,12 +468,29 @@ export default function OrderGroupsPage() {
|
|||||||
<div className="d-flex gap-2 align-items-center flex-wrap">
|
<div className="d-flex gap-2 align-items-center flex-wrap">
|
||||||
<Form.Select
|
<Form.Select
|
||||||
value={newGroupName}
|
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 }}
|
style={{ maxWidth: 260 }}
|
||||||
>
|
>
|
||||||
<option value="">— vyberte obchod —</option>
|
<option value="">— vyberte obchod —</option>
|
||||||
{stores.map(s => <option key={s.name} value={s.name}>{s.name}</option>)}
|
{stores.map(s => <option key={s.name} value={s.name}>{s.name}</option>)}
|
||||||
</Form.Select>
|
</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}>
|
<Button variant="primary" onClick={handleCreate} disabled={creating || !newGroupName}>
|
||||||
Vytvořit skupinu
|
Vytvořit skupinu
|
||||||
</Button>
|
</Button>
|
||||||
@@ -485,10 +514,13 @@ export default function OrderGroupsPage() {
|
|||||||
const isLocked = group.state === GroupState.LOCKED;
|
const isLocked = group.state === GroupState.LOCKED;
|
||||||
const memberEntries = Object.entries(group.members) as [string, OrderGroupMember][];
|
const memberEntries = Object.entries(group.members) as [string, OrderGroupMember][];
|
||||||
const editingTimes = group.id in editTimes;
|
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:).
|
// 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 groupStoreUrls = getStoreUrls(stores.find(s => s.name === group.name));
|
||||||
const storeUrl = rawStoreUrl && /^https?:\/\//i.test(rawStoreUrl) ? rawStoreUrl : undefined;
|
const storeUrl = isHttpUrl(group.url)
|
||||||
|
? group.url
|
||||||
|
: (groupStoreUrls.length === 1 ? groupStoreUrls[0] : undefined);
|
||||||
|
|
||||||
const totalFees = (group.fees ?? 0) + (group.shipping ?? 0) + (group.tip ?? 0);
|
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).
|
// Poplatky se dělí jen mezi aktivní strávníky (kdo si reálně něco objednal).
|
||||||
|
|||||||
@@ -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,5 @@
|
|||||||
[
|
[
|
||||||
"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"
|
||||||
]
|
]
|
||||||
|
|||||||
+26
-4
@@ -47,19 +47,41 @@ export async function getOrderDates(): Promise<string[]> {
|
|||||||
return dates.sort();
|
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();
|
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ů');
|
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 data = await getExtraData(date);
|
||||||
const canonical = stores.find(s => s.name.toLowerCase() === name.trim().toLowerCase())!.name;
|
|
||||||
const group: OrderGroup = {
|
const group: OrderGroup = {
|
||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
name: canonical,
|
name: store.name,
|
||||||
creatorLogin,
|
creatorLogin,
|
||||||
state: GroupState.OPEN,
|
state: GroupState.OPEN,
|
||||||
members: { [creatorLogin]: {} },
|
members: { [creatorLogin]: {} },
|
||||||
|
...(selectedUrl ? { url: selectedUrl } : {}),
|
||||||
};
|
};
|
||||||
data.groups = [...(data.groups ?? []), group];
|
data.groups = [...(data.groups ?? []), group];
|
||||||
return saveExtraData(data, date);
|
return saveExtraData(data, date);
|
||||||
|
|||||||
@@ -21,12 +21,15 @@ router.get("/dates", async (_req, res, next) => {
|
|||||||
|
|
||||||
router.post("/create", async (req: Request, res, next) => {
|
router.post("/create", async (req: Request, res, next) => {
|
||||||
const login = getLogin(parseToken(req));
|
const login = getLogin(parseToken(req));
|
||||||
const { name } = req.body ?? {};
|
const { name, url } = req.body ?? {};
|
||||||
if (!name || typeof name !== 'string') {
|
if (!name || typeof name !== 'string') {
|
||||||
return res.status(400).json({ error: 'Nebyl předán název skupiny' });
|
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 {
|
try {
|
||||||
const data = await createGroup(login, name);
|
const data = await createGroup(login, name, undefined, url);
|
||||||
broadcastExtra(data);
|
broadcastExtra(data);
|
||||||
res.status(200).json(data);
|
res.status(200).json(data);
|
||||||
} catch (e: any) { next(e); }
|
} catch (e: any) { next(e); }
|
||||||
|
|||||||
@@ -11,18 +11,18 @@ router.get("/", async (_req, res, next) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
router.post("/add", 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') {
|
if (!name || typeof name !== 'string') {
|
||||||
return res.status(400).json({ error: 'Nebyl předán název obchodu' });
|
return res.status(400).json({ error: 'Nebyl předán název obchodu' });
|
||||||
}
|
}
|
||||||
if (!heslo || typeof heslo !== 'string') {
|
if (!heslo || typeof heslo !== 'string') {
|
||||||
return res.status(400).json({ error: 'Nebylo předáno heslo' });
|
return res.status(400).json({ error: 'Nebylo předáno heslo' });
|
||||||
}
|
}
|
||||||
if (url != null && typeof url !== 'string') {
|
if (urls != null && (!Array.isArray(urls) || urls.some((u: unknown) => typeof u !== 'string'))) {
|
||||||
return res.status(400).json({ error: 'Neplatná URL obchodu' });
|
return res.status(400).json({ error: 'Neplatný seznam URL obchodu' });
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const stores = await addStore(name, heslo, url);
|
const stores = await addStore(name, heslo, urls);
|
||||||
res.status(200).json(stores);
|
res.status(200).json(stores);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (e.message === 'UNAUTHORIZED') {
|
if (e.message === 'UNAUTHORIZED') {
|
||||||
|
|||||||
+60
-20
@@ -4,16 +4,68 @@ import getStorage from "./storage";
|
|||||||
const storage = getStorage();
|
const storage = getStorage();
|
||||||
const STORES_KEY = 'stores';
|
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
|
* Podoby, v jakých mohou být obchody uloženy ve storage:
|
||||||
* formátem, kdy byly obchody uloženy jako pole řetězců (převede je na objekty).
|
* - ř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[]> {
|
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) {
|
if (!raw) {
|
||||||
return [];
|
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 name název obchodu
|
||||||
* @param heslo admin heslo
|
* @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;
|
const adminPassword = process.env.ADMIN_PASSWORD;
|
||||||
if (!adminPassword || heslo !== adminPassword) {
|
if (!adminPassword || heslo !== adminPassword) {
|
||||||
throw new Error('UNAUTHORIZED');
|
throw new Error('UNAUTHORIZED');
|
||||||
@@ -36,20 +88,8 @@ export async function addStore(name: string, heslo: string, url?: string): Promi
|
|||||||
if (stores.some(s => s.name.toLowerCase() === trimmed.toLowerCase())) {
|
if (stores.some(s => s.name.toLowerCase() === trimmed.toLowerCase())) {
|
||||||
throw new Error('Obchod s tímto názvem již existuje');
|
throw new Error('Obchod s tímto názvem již existuje');
|
||||||
}
|
}
|
||||||
const trimmedUrl = url?.trim();
|
const normalizedUrls = normalizeUrls(urls);
|
||||||
if (trimmedUrl) {
|
const store: Store = normalizedUrls.length > 0 ? { name: trimmed, urls: normalizedUrls } : { name: trimmed };
|
||||||
// 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 updated = [...stores, store];
|
const updated = [...stores, store];
|
||||||
await storage.setData(STORES_KEY, updated);
|
await storage.setData(STORES_KEY, updated);
|
||||||
return updated;
|
return updated;
|
||||||
|
|||||||
@@ -40,6 +40,42 @@ describe('createGroup', () => {
|
|||||||
expect(d2.groups).toHaveLength(2);
|
expect(d2.groups).toHaveLength(2);
|
||||||
expect(d2.groups![1].id).not.toBe(d2.groups![0].id);
|
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', () => {
|
describe('deleteGroup', () => {
|
||||||
|
|||||||
@@ -28,6 +28,13 @@ describe('getStores', () => {
|
|||||||
const stores = await getStores();
|
const stores = await getStores();
|
||||||
expect(stores).toEqual([{ name: 'McDonald\'s' }, { name: 'KFC' }]);
|
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', () => {
|
describe('addStore', () => {
|
||||||
@@ -37,21 +44,46 @@ describe('addStore', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('uloží volitelnou URL a ořízne mezery', async () => {
|
test('uloží volitelnou URL a ořízne mezery', async () => {
|
||||||
const stores = await addStore('Bistro', ADMIN_PW, ' https://wolt.com/bistro ');
|
const stores = await addStore('Bistro', ADMIN_PW, [' https://wolt.com/bistro ']);
|
||||||
expect(stores).toContainEqual({ name: 'Bistro', url: 'https://wolt.com/bistro' });
|
expect(stores).toContainEqual({ name: 'Bistro', urls: ['https://wolt.com/bistro'] });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('bez URL uloží obchod bez pole url', async () => {
|
test('uloží více URL na jeden podnik (různé dovozové služby)', async () => {
|
||||||
const stores = await addStore('KFC', ADMIN_PW, ' ');
|
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' });
|
expect(stores).toContainEqual({ name: 'KFC' });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('odmítne URL s nepovoleným schématem (javascript:)', async () => {
|
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 () => {
|
test('odmítne nevalidní URL i mezi platnými', async () => {
|
||||||
await expect(addStore('Zlo', ADMIN_PW, 'nfdjska')).rejects.toThrow('Neplatná URL');
|
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 () => {
|
test('vyhodí UNAUTHORIZED s nesprávným heslem', async () => {
|
||||||
|
|||||||
@@ -13,6 +13,9 @@ post:
|
|||||||
name:
|
name:
|
||||||
description: Název obchodu/restaurace (musí být v seznamu povolených obchodů)
|
description: Název obchodu/restaurace (musí být v seznamu povolených obchodů)
|
||||||
type: string
|
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:
|
responses:
|
||||||
"200":
|
"200":
|
||||||
$ref: "../../api.yml#/components/responses/ClientDataResponse"
|
$ref: "../../api.yml#/components/responses/ClientDataResponse"
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ post:
|
|||||||
name:
|
name:
|
||||||
description: Název obchodu/restaurace
|
description: Název obchodu/restaurace
|
||||||
type: string
|
type: string
|
||||||
url:
|
urls:
|
||||||
description: Volitelná URL na nabídku podniku (např. Bolt Food/Wolt/Foodora)
|
description: Volitelný seznam URL na nabídku podniku (např. Bolt Food/Wolt/Foodora)
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
type: string
|
type: string
|
||||||
heslo:
|
heslo:
|
||||||
description: Admin heslo (ADMIN_PASSWORD)
|
description: Admin heslo (ADMIN_PASSWORD)
|
||||||
|
|||||||
@@ -886,8 +886,10 @@ Store:
|
|||||||
name:
|
name:
|
||||||
description: Název obchodu/restaurace
|
description: Název obchodu/restaurace
|
||||||
type: string
|
type: string
|
||||||
url:
|
urls:
|
||||||
description: Volitelná URL na nabídku podniku (např. Bolt Food/Wolt/Foodora)
|
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
|
type: string
|
||||||
|
|
||||||
TrackingProvider:
|
TrackingProvider:
|
||||||
@@ -950,6 +952,9 @@ OrderGroup:
|
|||||||
name:
|
name:
|
||||||
description: Název obchodu/restaurace
|
description: Název obchodu/restaurace
|
||||||
type: string
|
type: string
|
||||||
|
url:
|
||||||
|
description: URL na nabídku podniku vybraná při zakládání skupiny (jedna z URL obchodu)
|
||||||
|
type: string
|
||||||
creatorLogin:
|
creatorLogin:
|
||||||
description: Login zakladatele skupiny
|
description: Login zakladatele skupiny
|
||||||
type: string
|
type: string
|
||||||
|
|||||||
Reference in New Issue
Block a user