CI / Generate TypeScript types (push) Successful in 12s
CI / Server unit tests (push) Successful in 26s
CI / Build server (push) Successful in 32s
CI / Build client (push) Successful in 41s
CI / Playwright E2E tests (push) Successful in 1m47s
CI / Build and push Docker image (push) Successful in 49s
CI / Notify (push) Successful in 2s
387 lines
19 KiB
TypeScript
387 lines
19 KiB
TypeScript
import { useEffect, useState } from "react";
|
||
import { Modal, Button, Form, ListGroup, Alert, OverlayTrigger, Tooltip } from "react-bootstrap";
|
||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||
import { faTrashCan } from "@fortawesome/free-regular-svg-icons";
|
||
import { faArrowsRotate, faPen, faPlus, faUpRightFromSquare, faXmark } from "@fortawesome/free-solid-svg-icons";
|
||
import { addStore, deleteStore, updateStore, getStoreMenuStatus, refreshStoreMenu, Store, StoreMenuProvider, StoreScrapeInfo, StoreScrapeStatus } from "../../../../types";
|
||
import { getHumanDateTime } from "../../Utils";
|
||
import PriceHistory from "../PriceHistory";
|
||
import { useAppConfig } from "../../hooks/useGroupLimits";
|
||
import { getStoreUrls, storeUrlLabel } from "../../utils/storeUrls";
|
||
|
||
type Props = {
|
||
isOpen: boolean;
|
||
onClose: () => void;
|
||
stores: Store[];
|
||
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[];
|
||
};
|
||
|
||
const PROVIDER_LABELS: Record<StoreMenuProvider, string> = { bolt: 'Bolt Food', wolt: 'Wolt' };
|
||
|
||
/** Krátký popis stavu stahování nabídky od jedné služby. */
|
||
function describeScrape(p: StoreScrapeStatus): { text: string, className: string, title?: string } {
|
||
const when = (iso?: string) => iso ? getHumanDateTime(new Date(iso)) : '';
|
||
switch (p.state) {
|
||
case 'ok':
|
||
return { text: `${p.dishCount} hlavních jídel (${when(p.lastSuccessAt)})${p.lastError ? ` · poslední obnovení selhalo: ${p.lastError}` : ''}`, className: 'text-success' };
|
||
case 'failed':
|
||
return { text: `selhalo ${p.failures}× (${when(p.lastAttemptAt)}): ${p.lastError ?? ''} · zkusí se znovu`, className: 'text-warning' };
|
||
case 'blocked':
|
||
return { text: `zablokováno po ${p.failures} neúspěších (${when(p.lastAttemptAt)}): ${p.lastError ?? ''}`, className: 'text-danger' };
|
||
default:
|
||
return { text: 'nestaženo', className: 'text-muted', title: 'Stáhne se automaticky, až bude nabídka potřeba v kole štěstí (a žádná jiná služba ji nemá)' };
|
||
}
|
||
}
|
||
|
||
/** 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('');
|
||
// 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);
|
||
// Server bez admin hesla — správa (přidání/úprava/odebrání/obnovení) nejde, zbývá jen přehled.
|
||
// undefined = konfigurace nenačtena, chováme se jako dřív (správa zapnutá).
|
||
const adminEnabled = useAppConfig().storeAdmin !== false;
|
||
const [scrapeInfo, setScrapeInfo] = useState<Record<string, StoreScrapeInfo>>({});
|
||
const [refreshing, setRefreshing] = useState<string | null>(null);
|
||
// Rozbalená historie cen („obchod|služba")
|
||
const [historyOpen, setHistoryOpen] = useState<string | null>(null);
|
||
|
||
// Stav stahování nabídek (Bolt Food/Wolt) — při otevření a po změně seznamu obchodů
|
||
useEffect(() => {
|
||
if (!isOpen) return;
|
||
getStoreMenuStatus().then(res => {
|
||
setScrapeInfo(Object.fromEntries((res.data ?? []).map(i => [i.store, i])));
|
||
}).catch(() => { /* stav je jen informativní */ });
|
||
}, [isOpen, stores]);
|
||
|
||
const handleRefreshMenu = async (name: string, provider: StoreMenuProvider) => {
|
||
setError(null);
|
||
setRefreshing(`${name}|${provider}`);
|
||
try {
|
||
const res = await refreshStoreMenu({ body: { name, provider, heslo } });
|
||
if (res.data) {
|
||
setScrapeInfo(prev => ({ ...prev, [name]: res.data! }));
|
||
}
|
||
// Znovu načíst případně otevřenou historii (mohla přibýt nová verze)
|
||
if (historyOpen === `${name}|${provider}`) {
|
||
setHistoryOpen(null);
|
||
setTimeout(() => setHistoryOpen(`${name}|${provider}`));
|
||
}
|
||
} catch (e: any) {
|
||
setError(e.message || 'Nastala chyba');
|
||
} finally {
|
||
setRefreshing(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 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('');
|
||
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');
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
const handleRemove = async (name: string) => {
|
||
setError(null);
|
||
setLoading(true);
|
||
try {
|
||
const res = await deleteStore({ body: { name, heslo } });
|
||
if (applyResult(res) && edit?.originalName === name) {
|
||
setEdit(null);
|
||
}
|
||
} catch (e: any) {
|
||
setError(e.message || 'Nastala chyba');
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
/** Řá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} size="lg">
|
||
<Modal.Header closeButton>
|
||
<Modal.Title><h2>Správa obchodů</h2></Modal.Title>
|
||
</Modal.Header>
|
||
<Modal.Body>
|
||
{error && (
|
||
<Alert variant="danger" onClose={() => setError(null)} dismissible>
|
||
{error}
|
||
</Alert>
|
||
)}
|
||
|
||
{!adminEnabled && (
|
||
<Alert variant="info">
|
||
Správa obchodů není na tomto serveru zapnutá (chybí <code>ADMIN_PASSWORD</code>).
|
||
Seznam obchodů, stav nabídek a historii cen lze jen prohlížet.
|
||
</Alert>
|
||
)}
|
||
|
||
{adminEnabled && <>
|
||
<Form.Group className="mb-3">
|
||
<Form.Label>Admin heslo</Form.Label>
|
||
<Form.Control
|
||
type="password"
|
||
placeholder="Heslo"
|
||
value={heslo}
|
||
onChange={e => setHeslo(e.target.value)}
|
||
onKeyDown={e => e.stopPropagation()}
|
||
/>
|
||
<Form.Text className="text-muted">
|
||
Potřeba pro přidání, úpravu a odebrání obchodu i pro obnovení nabídky (<FontAwesomeIcon icon={faArrowsRotate} />).
|
||
</Form.Text>
|
||
</Form.Group>
|
||
|
||
<hr />
|
||
<h6>Přidat obchod</h6>
|
||
<Form.Control
|
||
className="mb-2"
|
||
type="text"
|
||
placeholder="Název obchodu"
|
||
value={newName}
|
||
onChange={e => setNewName(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>
|
||
</div>
|
||
</>}
|
||
|
||
<h6>Aktuální seznam</h6>
|
||
{stores.length === 0 ? (
|
||
<p className="text-muted">Žádné obchody v seznamu</p>
|
||
) : (
|
||
<ListGroup>
|
||
{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>
|
||
)}
|
||
{scrapeInfo[s.name]?.providers.map(p => {
|
||
const { text, className, title } = describeScrape(p);
|
||
const key = `${s.name}|${p.provider}`;
|
||
return (
|
||
<div key={p.provider}>
|
||
<small className="d-flex align-items-baseline gap-2 mt-1">
|
||
<span className="text-nowrap text-muted">Menu {PROVIDER_LABELS[p.provider]}:</span>
|
||
<span className={className} title={title}>{text}</span>
|
||
{/* Zakázané tlačítko nezobrazí tooltip — obalení do span ho zobrazí i bez hesla */}
|
||
{adminEnabled && <OverlayTrigger
|
||
placement="top"
|
||
overlay={
|
||
<Tooltip>
|
||
{heslo
|
||
? `Znovu stáhnout nabídku z ${PROVIDER_LABELS[p.provider]}`
|
||
: 'Pro obnovení nabídky zadejte nahoře admin heslo'}
|
||
</Tooltip>
|
||
}
|
||
>
|
||
<span className="d-inline-block" style={{ cursor: heslo ? undefined : 'not-allowed' }}>
|
||
<Button
|
||
variant="link"
|
||
size="sm"
|
||
className="p-0"
|
||
disabled={!heslo || refreshing != null}
|
||
style={heslo ? undefined : { pointerEvents: 'none' }}
|
||
aria-label={`Znovu stáhnout nabídku z ${PROVIDER_LABELS[p.provider]}`}
|
||
onClick={() => handleRefreshMenu(s.name, p.provider)}
|
||
>
|
||
<FontAwesomeIcon icon={faArrowsRotate} spin={refreshing === key} />
|
||
</Button>
|
||
</span>
|
||
</OverlayTrigger>}
|
||
{p.dishCount > 0 && (
|
||
<Button variant="link" size="sm" className="p-0 text-nowrap"
|
||
onClick={() => setHistoryOpen(historyOpen === key ? null : key)}>
|
||
{historyOpen === key ? 'skrýt historii' : 'historie cen'}
|
||
</Button>
|
||
)}
|
||
</small>
|
||
{historyOpen === key && <PriceHistory store={s.name} provider={p.provider} />}
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
{adminEnabled && <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>
|
||
)}
|
||
</Modal.Body>
|
||
<Modal.Footer>
|
||
<Button variant="secondary" onClick={onClose}>Zavřít</Button>
|
||
</Modal.Footer>
|
||
</Modal>
|
||
);
|
||
}
|