Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5fc358c0a
|
||
|
|
6f6567a2a9
|
||
|
|
ce051447e6
|
@@ -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 { faPen, faPlus, faUpRightFromSquare, faXmark } from "@fortawesome/free-solid-svg-icons";
|
||||||
import { addStore, deleteStore, Store } from "../../../../types";
|
import { addStore, deleteStore, updateStore, Store } from "../../../../types";
|
||||||
|
import { getStoreUrls, storeUrlLabel } from "../../utils/storeUrls";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
@@ -12,25 +13,85 @@ type Props = {
|
|||||||
onStoresChanged: (stores: Store[]) => void;
|
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>) {
|
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 [edit, setEdit] = useState<EditState | null>(null);
|
||||||
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 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 () => {
|
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);
|
||||||
if (res.error) {
|
const res = await addStore({ body: { name: newName.trim(), urls: urls.length > 0 ? urls : undefined, heslo } });
|
||||||
setError((res.error as any).error || 'Nastala chyba');
|
if (applyResult(res)) {
|
||||||
} else if (res.data) {
|
|
||||||
onStoresChanged(res.data as Store[]);
|
|
||||||
setNewName('');
|
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) {
|
} catch (e: any) {
|
||||||
setError(e.message || 'Nastala chyba');
|
setError(e.message || 'Nastala chyba');
|
||||||
@@ -44,10 +105,8 @@ export default function StoreAdminModal({ isOpen, onClose, stores, onStoresChang
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const res = await deleteStore({ body: { name, heslo } });
|
const res = await deleteStore({ body: { name, heslo } });
|
||||||
if (res.error) {
|
if (applyResult(res) && edit?.originalName === name) {
|
||||||
setError((res.error as any).error || 'Nastala chyba');
|
setEdit(null);
|
||||||
} else if (res.data) {
|
|
||||||
onStoresChanged(res.data as Store[]);
|
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
setError(e.message || 'Nastala chyba');
|
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 (
|
return (
|
||||||
<Modal show={isOpen} onHide={onClose}>
|
<Modal show={isOpen} onHide={onClose}>
|
||||||
<Modal.Header closeButton>
|
<Modal.Header closeButton>
|
||||||
@@ -89,14 +179,8 @@ 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">
|
{renderUrlInputs(newUrls, setNewUrls, handleAdd)}
|
||||||
<Form.Control
|
<div className="d-flex justify-content-end mb-3">
|
||||||
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(); }}
|
|
||||||
/>
|
|
||||||
<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,25 +191,79 @@ 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>
|
const isEditing = edit?.originalName === s.name;
|
||||||
{s.name}
|
|
||||||
{s.url && /^https?:\/\//i.test(s.url) && (
|
if (isEditing) {
|
||||||
<a href={s.url} target="_blank" rel="noopener noreferrer" className="ms-2" title="Otevřít nabídku v nové záložce">
|
return (
|
||||||
<FontAwesomeIcon icon={faUpRightFromSquare} />
|
<ListGroup.Item key={s.name}>
|
||||||
</a>
|
<Form.Control
|
||||||
)}
|
className="mb-2"
|
||||||
</span>
|
type="text"
|
||||||
<FontAwesomeIcon
|
placeholder="Název obchodu"
|
||||||
icon={faTrashCan}
|
value={edit.name}
|
||||||
className="action-icon"
|
onChange={e => setEdit({ ...edit, name: e.target.value })}
|
||||||
title="Odebrat"
|
onKeyDown={e => { e.stopPropagation(); if (e.key === 'Enter') handleSaveEdit(); }}
|
||||||
onClick={() => handleRemove(s.name)}
|
/>
|
||||||
style={{ cursor: 'pointer' }}
|
{renderUrlInputs(edit.urls, next => setEdit({ ...edit, urls: next }), handleSaveEdit)}
|
||||||
/>
|
<div className="d-flex justify-content-end gap-2 mt-2">
|
||||||
</ListGroup.Item>
|
<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>
|
||||||
|
)}
|
||||||
|
</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"
|
||||||
|
title="Odebrat"
|
||||||
|
onClick={() => handleRemove(s.name)}
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</ListGroup.Item>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</ListGroup>
|
</ListGroup>
|
||||||
)}
|
)}
|
||||||
</Modal.Body>
|
</Modal.Body>
|
||||||
|
|||||||
@@ -31,7 +31,8 @@ getConfig().then(({ data }) => {
|
|||||||
client.interceptors.response.use(async response => {
|
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
|
// 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")) {
|
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" });
|
toast.error(json.error, { theme: "colored" });
|
||||||
// Serverové chyby hlásíme do Sentry; 4xx jsou očekávané (chyby uživatele)
|
// Serverové chyby hlásíme do Sentry; 4xx jsou očekávané (chyby uživatele)
|
||||||
if (response.status >= 500) {
|
if (response.status >= 500) {
|
||||||
|
|||||||
@@ -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,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ě"
|
||||||
]
|
]
|
||||||
|
|||||||
+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); }
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import express from "express";
|
import express from "express";
|
||||||
import { getStores, addStore, removeStore } from "../stores";
|
import { getStores, addStore, updateStore, removeStore } from "../stores";
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -11,18 +11,43 @@ 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);
|
||||||
|
} 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);
|
res.status(200).json(stores);
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (e.message === 'UNAUTHORIZED') {
|
if (e.message === 'UNAUTHORIZED') {
|
||||||
|
|||||||
+100
-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,25 +88,53 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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).
|
* Odebere obchod ze seznamu povolených (dle názvu).
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -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', () => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { resetMemoryStorage } from '../storage/memory';
|
import { resetMemoryStorage } from '../storage/memory';
|
||||||
import getStorage from '../storage';
|
import getStorage from '../storage';
|
||||||
import { getStores, addStore, removeStore } from '../stores';
|
import { getStores, addStore, updateStore, removeStore } from '../stores';
|
||||||
|
|
||||||
const ADMIN_PW = 'testadmin';
|
const ADMIN_PW = 'testadmin';
|
||||||
|
|
||||||
@@ -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 () => {
|
||||||
@@ -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', () => {
|
describe('removeStore', () => {
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await addStore('McDonald\'s', ADMIN_PW);
|
await addStore('McDonald\'s', ADMIN_PW);
|
||||||
|
|||||||
@@ -152,6 +152,8 @@ paths:
|
|||||||
$ref: "./paths/stores/listStores.yml"
|
$ref: "./paths/stores/listStores.yml"
|
||||||
/stores/add:
|
/stores/add:
|
||||||
$ref: "./paths/stores/addStore.yml"
|
$ref: "./paths/stores/addStore.yml"
|
||||||
|
/stores/update:
|
||||||
|
$ref: "./paths/stores/updateStore.yml"
|
||||||
/stores/delete:
|
/stores/delete:
|
||||||
$ref: "./paths/stores/deleteStore.yml"
|
$ref: "./paths/stores/deleteStore.yml"
|
||||||
|
|
||||||
|
|||||||
@@ -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,9 +14,11 @@ 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: string
|
type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
heslo:
|
heslo:
|
||||||
description: Admin heslo (ADMIN_PASSWORD)
|
description: Admin heslo (ADMIN_PASSWORD)
|
||||||
type: string
|
type: string
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -886,9 +886,11 @@ 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: string
|
type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
|
||||||
TrackingProvider:
|
TrackingProvider:
|
||||||
description: Rozvozová služba, přes kterou lze sledovat stav objednávky
|
description: Rozvozová služba, přes kterou lze sledovat stav objednávky
|
||||||
@@ -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