feat: večeře (extra meal slot) — dokončení, sync s masterem
CI / Generate TypeScript types (push) Successful in 34s
CI / Build server (push) Successful in 33s
CI / Server unit tests (push) Successful in 1m11s
CI / Build client (push) Successful in 33s
CI / Playwright E2E tests (push) Successful in 1m20s
CI / Build and push Docker image (push) Has been skipped
CI / Notify (push) Successful in 2s
CI / Generate TypeScript types (push) Successful in 34s
CI / Build server (push) Successful in 33s
CI / Server unit tests (push) Successful in 1m11s
CI / Build client (push) Successful in 33s
CI / Playwright E2E tests (push) Successful in 1m20s
CI / Build and push Docker image (push) Has been skipped
CI / Notify (push) Successful in 2s
- Nová stránka /vecere pro evidenci extra jídla (večeře/pozdní oběd) - MealSlot enum (obed/extra), oddělený storage namespace YYYY-MM-DD_extra - slot parametr na všech food endpointech a GET /api/data - Push reminder: přechod na 60min cooldown, login v payloadu místo endpointu - Smazány chybně přidané root package.json + package-lock.json (gitnexus) - server: slot?: string → slot?: MealSlot, literály nahrazeny enum konstantami - Přidány Jest testy izolace extra/obed storage namespace
This commit is contained in:
+125
-46
@@ -13,12 +13,13 @@ import './App.scss';
|
||||
import { faCircleCheck, faNoteSticky, faTrashCan, faComment } from '@fortawesome/free-regular-svg-icons';
|
||||
import { useSettings } from './context/settings';
|
||||
import Footer from './components/Footer';
|
||||
import { faBasketShopping, faChainBroken, faChevronLeft, faChevronRight, faGear, faSatelliteDish, faSearch, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons';
|
||||
import { faBasketShopping, faChainBroken, faChevronLeft, faChevronRight, faGear, faMoneyBillTransfer, faSatelliteDish, faSearch, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons';
|
||||
import Loader from './components/Loader';
|
||||
import { getHumanDateTime, isInTheFuture, formatDateString } from './Utils';
|
||||
import NoteModal from './components/modals/NoteModal';
|
||||
import PayForAllModal from './components/modals/PayForAllModal';
|
||||
import { useEasterEgg } from './context/eggs';
|
||||
import { ClientData, Food, MealSlot, PizzaOrder, DepartureTime, PizzaDayState, Restaurant, RestaurantDayMenu, RestaurantDayMenuMap, LunchChoice, UserLunchChoice, PizzaVariant, getData, getEasterEggImage, addPizza, removePizza, updatePizzaDayNote, createPizzaDay, deletePizzaDay, lockPizzaDay, unlockPizzaDay, finishOrder, finishDelivery, addChoice, jdemeObed, removeChoices, removeChoice, updateNote, changeDepartureTime, setBuyer, dismissQr } from '../../types';
|
||||
import { ClientData, Food, MealSlot, PizzaOrder, DepartureTime, PizzaDayState, Restaurant, RestaurantDayMenu, RestaurantDayMenuMap, LunchChoice, LocationLunchChoicesMap, UserLunchChoice, PizzaVariant, getData, getEasterEggImage, addPizza, removePizza, updatePizzaDayNote, createPizzaDay, deletePizzaDay, lockPizzaDay, unlockPizzaDay, finishOrder, finishDelivery, addChoice, jdemeObed, removeChoices, removeChoice, updateNote, changeDepartureTime, setBuyer, dismissQr, generateQr } from '../../types';
|
||||
import { getLunchChoiceName } from './enums';
|
||||
// import FallingLeaves, { LEAF_PRESETS, LEAF_COLOR_THEMES } from './FallingLeaves';
|
||||
// import './FallingLeaves.scss';
|
||||
@@ -74,6 +75,7 @@ function App() {
|
||||
const [dayIndex, setDayIndex] = useState<number>();
|
||||
const [loadingPizzaDay, setLoadingPizzaDay] = useState<boolean>(false);
|
||||
const [noteModalOpen, setNoteModalOpen] = useState<boolean>(false);
|
||||
const [payForAllLocationKey, setPayForAllLocationKey] = useState<LunchChoice | null>(null);
|
||||
const [eggImage, setEggImage] = useState<Blob>();
|
||||
const eggRef = useRef<HTMLImageElement>(null);
|
||||
// Prazvláštní workaround, aby socket.io listener viděl aktuální hodnotu
|
||||
@@ -288,6 +290,7 @@ function App() {
|
||||
|
||||
try {
|
||||
await addChoice({ body: { locationKey: location, foodIndex, dayIndex } });
|
||||
await tryAutoSelectDepartureTime();
|
||||
} catch (error: any) {
|
||||
alert(`Chyba při změně volby: ${error.message || error}`);
|
||||
}
|
||||
@@ -314,6 +317,10 @@ function App() {
|
||||
foodChoiceRef.current.value = "";
|
||||
}
|
||||
choiceRef.current?.blur();
|
||||
// Automatický výběr času odchodu pouze pro restaurace s menu
|
||||
if (Object.keys(Restaurant).includes(locationKey)) {
|
||||
await tryAutoSelectDepartureTime();
|
||||
}
|
||||
} catch (error: any) {
|
||||
alert(`Chyba při změně volby: ${error.message || error}`);
|
||||
// Reset výběru zpět
|
||||
@@ -338,6 +345,7 @@ function App() {
|
||||
const locationKey = choiceRef.current.value as LunchChoice;
|
||||
if (auth?.login) {
|
||||
await addChoice({ body: { locationKey, foodIndex: Number(event.target.value), dayIndex } });
|
||||
await tryAutoSelectDepartureTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -386,32 +394,80 @@ function App() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreatePizzaDay = async () => {
|
||||
if (!window.confirm('Opravdu chcete založit Pizza day?')) return;
|
||||
setLoadingPizzaDay(true);
|
||||
await createPizzaDay().then(() => setLoadingPizzaDay(false));
|
||||
}
|
||||
|
||||
const handleDeletePizzaDay = async () => {
|
||||
if (!window.confirm('Opravdu chcete smazat Pizza day? Budou smazány i všechny dosud zadané objednávky.')) return;
|
||||
await deletePizzaDay();
|
||||
}
|
||||
|
||||
const handleLockPizzaDay = async () => {
|
||||
if (!window.confirm('Opravdu chcete uzamknout objednávky? Po uzamčení nebude možné přidávat ani odebírat objednávky.')) return;
|
||||
await lockPizzaDay();
|
||||
}
|
||||
|
||||
const handleUnlockPizzaDay = async () => {
|
||||
if (!window.confirm('Opravdu chcete odemknout objednávky? Uživatelé budou moci opět upravovat své objednávky.')) return;
|
||||
await unlockPizzaDay();
|
||||
}
|
||||
|
||||
const handleFinishOrder = async () => {
|
||||
if (!window.confirm('Opravdu chcete označit objednávky jako objednané? Objednávky zůstanou zamčeny.')) return;
|
||||
await finishOrder();
|
||||
}
|
||||
|
||||
const handleReturnToLocked = async () => {
|
||||
if (!window.confirm('Opravdu chcete vrátit stav zpět do "uzamčeno" (před objednáním)?')) return;
|
||||
await lockPizzaDay();
|
||||
}
|
||||
|
||||
const handleFinishDelivery = async () => {
|
||||
if (!window.confirm(`Opravdu chcete označit pizzy jako doručené?${settings?.bankAccount && settings?.holderName ? ' Uživatelům bude vygenerován QR kód pro platbu.' : ''}`)) return;
|
||||
await finishDelivery({ body: { bankAccount: settings?.bankAccount, bankAccountHolder: settings?.holderName } });
|
||||
}
|
||||
|
||||
const pizzaSuggestions = useMemo(() => {
|
||||
if (!data?.pizzaList) {
|
||||
if (!data?.pizzaList && !data?.salatList) {
|
||||
return [];
|
||||
}
|
||||
const suggestions: SelectSearchOption[] = [];
|
||||
data.pizzaList.forEach((pizza, index) => {
|
||||
data.pizzaList?.forEach((pizza, index) => {
|
||||
const group: SelectSearchOption = { name: pizza.name, type: "group", items: [] }
|
||||
pizza.sizes.forEach((size, sizeIndex) => {
|
||||
const name = `${size.size} (${size.price} Kč)`;
|
||||
const value = `${index}|${sizeIndex}`;
|
||||
const value = `pizza|${index}|${sizeIndex}`;
|
||||
group.items?.push({ name, value });
|
||||
})
|
||||
suggestions.push(group);
|
||||
})
|
||||
});
|
||||
if (data.salatList?.length) {
|
||||
const salatGroup: SelectSearchOption = { name: "Saláty", type: "group", items: [] }
|
||||
data.salatList.forEach((salat, index) => {
|
||||
salatGroup.items?.push({ name: `${salat.name} (${salat.price} Kč)`, value: `salat|${index}` });
|
||||
});
|
||||
suggestions.push(salatGroup);
|
||||
}
|
||||
return suggestions;
|
||||
}, [data?.pizzaList]);
|
||||
}, [data?.pizzaList, data?.salatList]);
|
||||
|
||||
const handlePizzaChange = async (value: SelectedOptionValue | SelectedOptionValue[]) => {
|
||||
if (auth?.login && data?.pizzaList) {
|
||||
if (auth?.login) {
|
||||
if (typeof value !== 'string') {
|
||||
throw new TypeError('Nepodporovaný typ hodnoty: ' + typeof value);
|
||||
}
|
||||
const s = value.split('|');
|
||||
const pizzaIndex = Number.parseInt(s[0]);
|
||||
const pizzaSizeIndex = Number.parseInt(s[1]);
|
||||
await addPizza({ body: { pizzaIndex, pizzaSizeIndex } });
|
||||
if (s[0] === 'salat') {
|
||||
const salatIndex = Number.parseInt(s[1]);
|
||||
await addPizza({ body: { salatIndex } });
|
||||
} else {
|
||||
const pizzaIndex = Number.parseInt(s[1]);
|
||||
const pizzaSizeIndex = Number.parseInt(s[2]);
|
||||
await addPizza({ body: { pizzaIndex, pizzaSizeIndex } });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,6 +489,16 @@ function App() {
|
||||
}
|
||||
}
|
||||
|
||||
// Automaticky nastaví preferovaný čas odchodu 10:45, pokud tento čas ještě nenastal (nebo jde o budoucí den)
|
||||
const tryAutoSelectDepartureTime = async () => {
|
||||
const preferredTime = "10:45" as DepartureTime;
|
||||
const isToday = dayIndex === data?.todayDayIndex;
|
||||
if ((!isToday || isInTheFuture(preferredTime)) && departureChoiceRef.current) {
|
||||
departureChoiceRef.current.value = preferredTime;
|
||||
await changeDepartureTime({ body: { time: preferredTime, dayIndex } });
|
||||
}
|
||||
}
|
||||
|
||||
const handleDayChange = async (dayIndex: number) => {
|
||||
setDayIndex(dayIndex);
|
||||
dayIndexRef.current = dayIndex;
|
||||
@@ -583,7 +649,7 @@ function App() {
|
||||
</Form.Select>
|
||||
<small>Je možné vybrat jen jednu možnost. Výběr jiné odstraní předchozí.</small>
|
||||
{foodChoiceList && !closed && <>
|
||||
<p className="mt-3">Na co dobrého? <small style={{ color: 'var(--luncher-text-muted)' }}>(nepovinné)</small></p>
|
||||
<p className="mt-3">Na co dobrého?</p>
|
||||
<Form.Select ref={foodChoiceRef} onChange={doAddFoodChoice}>
|
||||
<option value="">Vyber jídlo...</option>
|
||||
{foodChoiceList.map((food, index) => <option key={food.name} value={index}>{food.name}</option>)}
|
||||
@@ -594,7 +660,7 @@ function App() {
|
||||
<Form.Select ref={departureChoiceRef} onChange={handleChangeDepartureTime}>
|
||||
<option value="">Vyber čas...</option>
|
||||
{Object.values(DepartureTime)
|
||||
.filter(time => isInTheFuture(time))
|
||||
.filter(time => dayIndex !== data.todayDayIndex || isInTheFuture(time))
|
||||
.map(time => <option key={time} value={time}>{time}</option>)}
|
||||
</Form.Select>
|
||||
</>}
|
||||
@@ -616,6 +682,18 @@ function App() {
|
||||
<td>
|
||||
{locationName}
|
||||
{(locationPickCount ?? 0) > 1 && <span className="ms-1">({locationPickCount})</span>}
|
||||
{locationPickCount >= 2 && auth.login && loginObject[auth.login] !== undefined
|
||||
&& locationKey !== LunchChoice.PIZZA && locationKey !== LunchChoice.NEOBEDVAM && locationKey !== LunchChoice.ROZHODUJI
|
||||
&& settings?.bankAccount && settings?.holderName && (
|
||||
<span title='Zaplatit za všechny a vygenerovat QR kódy ostatním' className="ms-2">
|
||||
<FontAwesomeIcon
|
||||
icon={faMoneyBillTransfer}
|
||||
onClick={() => setPayForAllLocationKey(locationKey)}
|
||||
className='action-icon'
|
||||
style={{ cursor: 'pointer' }}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className='p-0'>
|
||||
<Table className="nested-table">
|
||||
@@ -709,10 +787,7 @@ function App() {
|
||||
</span>
|
||||
:
|
||||
<div>
|
||||
<Button onClick={async () => {
|
||||
setLoadingPizzaDay(true);
|
||||
await createPizzaDay().then(() => setLoadingPizzaDay(false));
|
||||
}}>Založit Pizza day</Button>
|
||||
<Button onClick={handleCreatePizzaDay}>Založit Pizza day</Button>
|
||||
<Button variant="outline-primary" onClick={doJdemeObed}>Jdeme na oběd!</Button>
|
||||
</div>
|
||||
}
|
||||
@@ -731,12 +806,8 @@ function App() {
|
||||
{
|
||||
data.pizzaDay.creator === auth.login &&
|
||||
<div className="mb-4">
|
||||
<Button variant="danger" title="Smaže kompletně pizza day, včetně dosud zadaných objednávek." onClick={async () => {
|
||||
await deletePizzaDay();
|
||||
}}>Smazat Pizza day</Button>
|
||||
<Button title={noOrders ? "Nelze uzamknout - neexistuje žádná objednávka" : "Zamezí přidávat/odebírat objednávky. Použij před samotným objednáním, aby již nemohlo docházet ke změnám."} disabled={noOrders} onClick={async () => {
|
||||
await lockPizzaDay();
|
||||
}}>Uzamknout</Button>
|
||||
<Button variant="danger" title="Smaže kompletně pizza day, včetně dosud zadaných objednávek." onClick={handleDeletePizzaDay}>Smazat Pizza day</Button>
|
||||
<Button title={noOrders ? "Nelze uzamknout - neexistuje žádná objednávka" : "Zamezí přidávat/odebírat objednávky. Použij před samotným objednáním, aby již nemohlo docházet ke změnám."} disabled={noOrders} onClick={handleLockPizzaDay}>Uzamknout</Button>
|
||||
</div>
|
||||
}
|
||||
</>
|
||||
@@ -747,12 +818,8 @@ function App() {
|
||||
<p>Objednávky jsou uzamčeny uživatelem <strong>{data.pizzaDay.creator}</strong></p>
|
||||
{data.pizzaDay.creator === auth.login &&
|
||||
<div className="mb-4">
|
||||
<Button variant="secondary" title="Umožní znovu editovat objednávky." onClick={async () => {
|
||||
await unlockPizzaDay();
|
||||
}}>Odemknout</Button>
|
||||
<Button title={noOrders ? "Nelze objednat - neexistuje žádná objednávka" : "Použij po objednání. Objednávky zůstanou zamčeny."} disabled={noOrders} onClick={async () => {
|
||||
await finishOrder();
|
||||
}}>Objednáno</Button>
|
||||
<Button variant="secondary" title="Umožní znovu editovat objednávky." onClick={handleUnlockPizzaDay}>Odemknout</Button>
|
||||
<Button title={noOrders ? "Nelze objednat - neexistuje žádná objednávka" : "Použij po objednání. Objednávky zůstanou zamčeny."} disabled={noOrders} onClick={handleFinishOrder}>Objednáno</Button>
|
||||
</div>
|
||||
}
|
||||
</>
|
||||
@@ -763,12 +830,8 @@ function App() {
|
||||
<p>Pizzy byly objednány uživatelem <strong>{data.pizzaDay.creator}</strong></p>
|
||||
{data.pizzaDay.creator === auth.login &&
|
||||
<div className="mb-4">
|
||||
<Button variant="secondary" title="Vrátí stav do předchozího kroku (před objednáním)." onClick={async () => {
|
||||
await lockPizzaDay();
|
||||
}}>Vrátit do "uzamčeno"</Button>
|
||||
<Button title="Nastaví stav na 'Doručeno' - koncový stav." onClick={async () => {
|
||||
await finishDelivery({ body: { bankAccount: settings?.bankAccount, bankAccountHolder: settings?.holderName } });
|
||||
}}>Doručeno</Button>
|
||||
<Button variant="secondary" title="Vrátí stav do předchozího kroku (před objednáním)." onClick={handleReturnToLocked}>Vrátit do "uzamčeno"</Button>
|
||||
<Button title="Nastaví stav na 'Doručeno' - koncový stav." onClick={handleFinishDelivery}>Doručeno</Button>
|
||||
</div>
|
||||
}
|
||||
</>
|
||||
@@ -785,7 +848,7 @@ function App() {
|
||||
<SelectSearch
|
||||
search={true}
|
||||
options={pizzaSuggestions}
|
||||
placeholder='Vyhledat pizzu...'
|
||||
placeholder='Vyhledat pizzu nebo salát...'
|
||||
onChange={handlePizzaChange}
|
||||
onBlur={_ => { }}
|
||||
onFocus={_ => { }}
|
||||
@@ -808,11 +871,15 @@ function App() {
|
||||
}
|
||||
<PizzaOrderList state={data.pizzaDay.state!} orders={data.pizzaDay.orders!} onDelete={handlePizzaDelete} creator={data.pizzaDay.creator!} />
|
||||
{
|
||||
data.pizzaDay.state === PizzaDayState.DELIVERED && myOrder?.hasQr &&
|
||||
<div className='qr-code'>
|
||||
<h3>QR platba</h3>
|
||||
<img src={`/api/qr?login=${auth.login}`} alt='QR kód' />
|
||||
</div>
|
||||
data.pizzaDay.state === PizzaDayState.DELIVERED && myOrder?.hasQr && (() => {
|
||||
const pizzaQr = data.pendingQrs?.find(qr => qr.creator === data.pizzaDay?.creator);
|
||||
return pizzaQr ? (
|
||||
<div className='qr-code'>
|
||||
<h3>QR platba</h3>
|
||||
<img src={`/api/qr?login=${auth.login}&id=${pizzaQr.id}`} alt='QR kód' />
|
||||
</div>
|
||||
) : null;
|
||||
})()
|
||||
}
|
||||
</>
|
||||
}
|
||||
@@ -822,18 +889,17 @@ function App() {
|
||||
{data.pendingQrs && data.pendingQrs.length > 0 &&
|
||||
<div className='pizza-section fade-in mt-4'>
|
||||
<h3>Nevyřízené platby</h3>
|
||||
<p>Máte neuhrazené platby z předchozích dní.</p>
|
||||
<p>Máte neuhrazené platby.</p>
|
||||
{data.pendingQrs.map(qr => (
|
||||
<div key={qr.date} className='qr-code mb-3'>
|
||||
<div key={qr.id} className='qr-code mb-3'>
|
||||
<p>
|
||||
<strong>{formatDateString(qr.date)}</strong> — {qr.creator} ({qr.totalPrice} Kč)
|
||||
{qr.purpose && <><br /><span className="text-muted">{qr.purpose}</span></>}
|
||||
</p>
|
||||
<img src={`/api/qr?login=${auth.login}`} alt='QR kód' />
|
||||
<img src={`/api/qr?login=${auth.login}&id=${qr.id}`} alt='QR kód' />
|
||||
<div className='mt-2'>
|
||||
<Button variant="success" onClick={async () => {
|
||||
await dismissQr({ body: { date: qr.date } });
|
||||
// Přenačteme data pro aktualizaci
|
||||
await dismissQr({ body: { id: qr.id } });
|
||||
const response = await getData({ query: { dayIndex } });
|
||||
if (response.data) {
|
||||
setData(response.data);
|
||||
@@ -854,6 +920,19 @@ function App() {
|
||||
/> */}
|
||||
<Footer />
|
||||
<NoteModal isOpen={noteModalOpen} onClose={() => setNoteModalOpen(false)} onSave={saveNote} />
|
||||
{payForAllLocationKey && data && (
|
||||
<PayForAllModal
|
||||
isOpen
|
||||
onClose={() => setPayForAllLocationKey(null)}
|
||||
locationKey={payForAllLocationKey}
|
||||
locationName={getLunchChoiceName(payForAllLocationKey)}
|
||||
locationChoices={data.choices[payForAllLocationKey as keyof typeof data.choices] as LocationLunchChoicesMap}
|
||||
menu={food?.[payForAllLocationKey as Restaurant]}
|
||||
payerLogin={auth.login ?? ''}
|
||||
bankAccount={settings?.bankAccount ?? ''}
|
||||
bankAccountHolder={settings?.holderName ?? ''}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,16 +11,12 @@ import GenerateMockDataModal from "./modals/GenerateMockDataModal";
|
||||
import ClearMockDataModal from "./modals/ClearMockDataModal";
|
||||
import { useNavigate } from "react-router";
|
||||
import { STATS_URL, VECERE_URL } from "../AppRoutes";
|
||||
import { FeatureRequest, getVotes, updateVote, LunchChoices } from "../../../types";
|
||||
import { FeatureRequest, getVotes, updateVote, LunchChoices, getChangelogs } from "../../../types";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faSun, faMoon } from "@fortawesome/free-solid-svg-icons";
|
||||
import { formatDateString } from "../Utils";
|
||||
|
||||
const CHANGELOG = [
|
||||
"Nový moderní design aplikace",
|
||||
"Oprava parsování Sladovnické a TechTower",
|
||||
"Možnost označit se jako objednávající u volby \"budu objednávat\"",
|
||||
"Možnost generovat QR kódy pro platby (i mimo Pizza day)",
|
||||
];
|
||||
const LAST_SEEN_CHANGELOG_KEY = "lastChangelogDate";
|
||||
|
||||
const IS_DEV = process.env.NODE_ENV === 'development';
|
||||
|
||||
@@ -38,6 +34,7 @@ export default function Header({ choices, dayIndex }: Props) {
|
||||
const [pizzaModalOpen, setPizzaModalOpen] = useState<boolean>(false);
|
||||
const [refreshMenuModalOpen, setRefreshMenuModalOpen] = useState<boolean>(false);
|
||||
const [changelogModalOpen, setChangelogModalOpen] = useState<boolean>(false);
|
||||
const [changelogEntries, setChangelogEntries] = useState<Record<string, string[]>>({});
|
||||
const [qrModalOpen, setQrModalOpen] = useState<boolean>(false);
|
||||
const [generateMockModalOpen, setGenerateMockModalOpen] = useState<boolean>(false);
|
||||
const [clearMockModalOpen, setClearMockModalOpen] = useState<boolean>(false);
|
||||
@@ -71,6 +68,19 @@ export default function Header({ choices, dayIndex }: Props) {
|
||||
}
|
||||
}, [auth?.login]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!auth?.login) return;
|
||||
const lastSeen = localStorage.getItem(LAST_SEEN_CHANGELOG_KEY) ?? undefined;
|
||||
getChangelogs({ query: lastSeen ? { since: lastSeen } : {} }).then(response => {
|
||||
const entries = response.data;
|
||||
if (!entries || Object.keys(entries).length === 0) return;
|
||||
setChangelogEntries(entries);
|
||||
setChangelogModalOpen(true);
|
||||
const newestDate = Object.keys(entries).sort((a, b) => b.localeCompare(a))[0];
|
||||
localStorage.setItem(LAST_SEEN_CHANGELOG_KEY, newestDate);
|
||||
});
|
||||
}, [auth?.login]);
|
||||
|
||||
const closeSettingsModal = () => {
|
||||
setSettingsModalOpen(false);
|
||||
}
|
||||
@@ -198,7 +208,17 @@ export default function Header({ choices, dayIndex }: Props) {
|
||||
<NavDropdown.Item onClick={handleQrMenuClick}>Generování QR kódů</NavDropdown.Item>
|
||||
<NavDropdown.Item onClick={() => navigate(STATS_URL)}>Statistiky</NavDropdown.Item>
|
||||
<NavDropdown.Item onClick={() => navigate(VECERE_URL)}>Večeře</NavDropdown.Item>
|
||||
<NavDropdown.Item onClick={() => setChangelogModalOpen(true)}>Novinky</NavDropdown.Item>
|
||||
<NavDropdown.Item onClick={() => {
|
||||
getChangelogs().then(response => {
|
||||
const entries = response.data ?? {};
|
||||
setChangelogEntries(entries);
|
||||
setChangelogModalOpen(true);
|
||||
const dates = Object.keys(entries).sort((a, b) => b.localeCompare(a));
|
||||
if (dates.length > 0) {
|
||||
localStorage.setItem(LAST_SEEN_CHANGELOG_KEY, dates[0]);
|
||||
}
|
||||
});
|
||||
}}>Novinky</NavDropdown.Item>
|
||||
{IS_DEV && (
|
||||
<>
|
||||
<NavDropdown.Divider />
|
||||
@@ -238,16 +258,24 @@ export default function Header({ choices, dayIndex }: Props) {
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<Modal show={changelogModalOpen} onHide={() => setChangelogModalOpen(false)}>
|
||||
<Modal show={changelogModalOpen} onHide={() => setChangelogModalOpen(false)} size="lg">
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title><h2>Novinky</h2></Modal.Title>
|
||||
</Modal.Header>
|
||||
<Modal.Body>
|
||||
<ul>
|
||||
{CHANGELOG.map((item, index) => (
|
||||
<li key={index}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
{Object.keys(changelogEntries).sort((a, b) => b.localeCompare(a)).map(date => (
|
||||
<div key={date}>
|
||||
<strong>{formatDateString(date)}</strong>
|
||||
<ul>
|
||||
{changelogEntries[date].map((item, index) => (
|
||||
<li key={index}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
{Object.keys(changelogEntries).length === 0 && (
|
||||
<p>Žádné novinky.</p>
|
||||
)}
|
||||
</Modal.Body>
|
||||
<Modal.Footer>
|
||||
<Button variant="secondary" onClick={() => setChangelogModalOpen(false)}>
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Modal, Button, Form, Table, Alert } from "react-bootstrap";
|
||||
import { generateQr, LunchChoice, LocationLunchChoicesMap, RestaurantDayMenu, QrRecipient } from "../../../../types";
|
||||
import { parsePriceCzk } from "../../utils/parsePrice";
|
||||
|
||||
type DinerEntry = {
|
||||
login: string;
|
||||
selectedFoods: number[];
|
||||
baseAmount: number;
|
||||
baseAmountParseFailed: boolean;
|
||||
surchargeText: string;
|
||||
surchargeAmount: string;
|
||||
included: boolean;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
locationKey: LunchChoice;
|
||||
locationName: string;
|
||||
locationChoices: LocationLunchChoicesMap;
|
||||
menu: RestaurantDayMenu | undefined;
|
||||
payerLogin: string;
|
||||
bankAccount: string;
|
||||
bankAccountHolder: string;
|
||||
};
|
||||
|
||||
function sanitizeAmount(value: string): string {
|
||||
return value.replace(/[^0-9.,]/g, '').replace(',', '.');
|
||||
}
|
||||
|
||||
function parseAmount(s: string): number | null {
|
||||
if (!s || s.trim().length === 0) return null;
|
||||
const n = parseFloat(s);
|
||||
if (isNaN(n) || n < 0) return null;
|
||||
const parts = s.split('.');
|
||||
if (parts.length === 2 && parts[1].length > 2) return null;
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
export default function PayForAllModal({ isOpen, onClose, locationName, locationChoices, menu, payerLogin, bankAccount, bankAccountHolder }: Readonly<Props>) {
|
||||
const [diners, setDiners] = useState<DinerEntry[]>([]);
|
||||
const [tipTotal, setTipTotal] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
const hasMenu = !!menu;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
const entries: DinerEntry[] = Object.entries(locationChoices).map(([login, choice]) => {
|
||||
const selectedFoods = choice.selectedFoods ?? [];
|
||||
let baseAmount = 0;
|
||||
let baseAmountParseFailed = false;
|
||||
if (menu) {
|
||||
for (const idx of selectedFoods) {
|
||||
const price = parsePriceCzk(menu.food?.[idx]?.price);
|
||||
if (price === null) {
|
||||
baseAmountParseFailed = true;
|
||||
} else {
|
||||
baseAmount += price;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
login,
|
||||
selectedFoods,
|
||||
baseAmount,
|
||||
baseAmountParseFailed,
|
||||
surchargeText: '',
|
||||
surchargeAmount: '',
|
||||
included: login !== payerLogin,
|
||||
};
|
||||
});
|
||||
setDiners(entries);
|
||||
setTipTotal('');
|
||||
setError(null);
|
||||
setSuccess(false);
|
||||
}, [isOpen, locationChoices, menu, payerLogin]);
|
||||
|
||||
const includedDiners = diners.filter(d => d.included && d.login !== payerLogin);
|
||||
const tipPerPerson = (() => {
|
||||
if (includedDiners.length === 0) return 0;
|
||||
const tip = parseAmount(tipTotal);
|
||||
if (tip === null || tip === 0) return 0;
|
||||
return Math.round((tip / includedDiners.length) * 100) / 100;
|
||||
})();
|
||||
|
||||
const getTotal = (d: DinerEntry): number => {
|
||||
const surcharge = parseAmount(d.surchargeAmount) ?? 0;
|
||||
const tip = d.included && d.login !== payerLogin ? tipPerPerson : 0;
|
||||
return Math.round((d.baseAmount + surcharge + tip) * 100) / 100;
|
||||
};
|
||||
|
||||
const handleInclude = useCallback((login: string, checked: boolean) => {
|
||||
setDiners(prev => prev.map(d => d.login === login ? { ...d, included: checked } : d));
|
||||
}, []);
|
||||
|
||||
const handleSurchargeText = useCallback((login: string, value: string) => {
|
||||
setDiners(prev => prev.map(d => d.login === login ? { ...d, surchargeText: value } : d));
|
||||
}, []);
|
||||
|
||||
const handleSurchargeAmount = useCallback((login: string, value: string) => {
|
||||
setDiners(prev => prev.map(d => d.login === login ? { ...d, surchargeAmount: sanitizeAmount(value) } : d));
|
||||
}, []);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
setError(null);
|
||||
const recipients: QrRecipient[] = [];
|
||||
|
||||
for (const d of diners) {
|
||||
if (!d.included || d.login === payerLogin) continue;
|
||||
const total = getTotal(d);
|
||||
if (total <= 0) {
|
||||
setError(`Celková částka pro ${d.login} musí být kladná`);
|
||||
return;
|
||||
}
|
||||
const amountStr = total.toString();
|
||||
if (amountStr.includes('.') && amountStr.split('.')[1].length > 2) {
|
||||
setError(`Částka pro ${d.login} má více než 2 desetinná místa`);
|
||||
return;
|
||||
}
|
||||
const foods = d.selectedFoods.map(i => menu?.food?.[i]?.name).filter(Boolean).join(', ');
|
||||
const purposeBase = `Oběd ${locationName}${foods ? ` — ${foods}` : ''}`;
|
||||
recipients.push({
|
||||
login: d.login,
|
||||
purpose: purposeBase.substring(0, 60),
|
||||
amount: total,
|
||||
});
|
||||
}
|
||||
|
||||
if (recipients.length === 0) {
|
||||
setError("Nebyl vybrán žádný příjemce");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await generateQr({
|
||||
body: { recipients, bankAccount, bankAccountHolder },
|
||||
});
|
||||
if (response.error) {
|
||||
setError((response.error as any).error || 'Nastala chyba při generování QR kódů');
|
||||
} else {
|
||||
setSuccess(true);
|
||||
setTimeout(() => onClose(), 2000);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e.message || 'Nastala chyba při generování QR kódů');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const anyParseFailed = diners.some(d => d.baseAmountParseFailed && d.included);
|
||||
|
||||
return (
|
||||
<Modal show={isOpen} onHide={onClose} size="lg">
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title><h2>Zaplatit za všechny — {locationName}</h2></Modal.Title>
|
||||
</Modal.Header>
|
||||
<Modal.Body>
|
||||
{success ? (
|
||||
<Alert variant="success">
|
||||
QR kódy byly úspěšně vygenerovány! Uživatelé je uvidí v sekci „Nevyřízené platby".
|
||||
</Alert>
|
||||
) : (
|
||||
<>
|
||||
<p>Zaplatili jste za skupinu v restauraci. Nastavte příplatky a dýško, poté vygenerujte QR kódy pro ostatní.</p>
|
||||
|
||||
{!hasMenu && (
|
||||
<Alert variant="info">
|
||||
Pro tuto skupinu nejsou k dispozici ceny jídel — vyplňte příplatky ručně.
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{anyParseFailed && (
|
||||
<Alert variant="warning">
|
||||
U některých jídel se nepodařilo načíst cenu — doplňte ji ručně v sloupci Příplatek.
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="danger" onClose={() => setError(null)} dismissible>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Table striped bordered hover responsive size="sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: 40 }}></th>
|
||||
<th>Strávník</th>
|
||||
<th>Jídla</th>
|
||||
<th style={{ width: 220 }}>Příplatek</th>
|
||||
<th style={{ width: 90 }}>Dýško</th>
|
||||
<th style={{ width: 90 }}>Celkem</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{diners.map(d => {
|
||||
const isPayer = d.login === payerLogin;
|
||||
const foodNames = d.selectedFoods.map(i => menu?.food?.[i]?.name).filter(Boolean).join(', ');
|
||||
const total = getTotal(d);
|
||||
return (
|
||||
<tr key={d.login} className={!d.included && !isPayer ? 'text-muted' : ''}>
|
||||
<td className="text-center">
|
||||
{isPayer ? (
|
||||
<small className="text-muted">plátce</small>
|
||||
) : (
|
||||
<Form.Check
|
||||
type="checkbox"
|
||||
checked={d.included}
|
||||
onChange={e => handleInclude(d.login, e.target.checked)}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
<td><strong>{d.login}</strong></td>
|
||||
<td>
|
||||
<small>
|
||||
{foodNames || <span className="text-muted">—</span>}
|
||||
{hasMenu && d.baseAmount > 0 && <span className="text-muted"> ({d.baseAmount} Kč)</span>}
|
||||
{d.baseAmountParseFailed && <span className="text-warning"> ⚠</span>}
|
||||
</small>
|
||||
</td>
|
||||
<td>
|
||||
{!isPayer && (
|
||||
<div className="d-flex gap-1">
|
||||
<Form.Control
|
||||
type="text"
|
||||
placeholder="popis"
|
||||
value={d.surchargeText}
|
||||
onChange={e => handleSurchargeText(d.login, e.target.value)}
|
||||
disabled={!d.included}
|
||||
size="sm"
|
||||
onKeyDown={e => e.stopPropagation()}
|
||||
/>
|
||||
<Form.Control
|
||||
type="text"
|
||||
placeholder="Kč"
|
||||
value={d.surchargeAmount}
|
||||
onChange={e => handleSurchargeAmount(d.login, e.target.value)}
|
||||
disabled={!d.included}
|
||||
size="sm"
|
||||
style={{ width: 70 }}
|
||||
onKeyDown={e => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="text-end">
|
||||
{!isPayer && d.included ? `${tipPerPerson} Kč` : '—'}
|
||||
</td>
|
||||
<td className="text-end fw-bold">
|
||||
{!isPayer ? `${total} Kč` : '—'}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</Table>
|
||||
|
||||
<div className="d-flex align-items-center gap-2 mt-2">
|
||||
<label className="mb-0 text-nowrap">Dýško celkem (Kč):</label>
|
||||
<Form.Control
|
||||
type="text"
|
||||
placeholder="0"
|
||||
value={tipTotal}
|
||||
onChange={e => setTipTotal(sanitizeAmount(e.target.value))}
|
||||
size="sm"
|
||||
style={{ width: 100 }}
|
||||
onKeyDown={e => e.stopPropagation()}
|
||||
/>
|
||||
<small className="text-muted">
|
||||
{includedDiners.length > 0 && tipPerPerson > 0
|
||||
? `(${tipPerPerson} Kč / osoba)`
|
||||
: ''}
|
||||
</small>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal.Body>
|
||||
<Modal.Footer>
|
||||
{!success && (
|
||||
<>
|
||||
<span className="me-auto text-muted">
|
||||
Příjemci: {includedDiners.length}
|
||||
</span>
|
||||
<Button variant="secondary" onClick={onClose} disabled={loading}>
|
||||
Storno
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleGenerate}
|
||||
disabled={loading || includedDiners.length === 0}
|
||||
>
|
||||
{loading ? 'Generuji...' : 'Vygenerovat QR'}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{success && (
|
||||
<Button variant="secondary" onClick={onClose}>Zavřít</Button>
|
||||
)}
|
||||
</Modal.Footer>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Parsuje cenu ve formátu "135 Kč", "135,50 Kč" nebo "135.50 Kč" na číslo.
|
||||
* Vrátí null při selhání.
|
||||
*/
|
||||
export function parsePriceCzk(raw: string | undefined): number | null {
|
||||
if (!raw) return null;
|
||||
const m = raw.replace(',', '.').match(/(\d+(?:\.\d+)?)/);
|
||||
if (!m) return null;
|
||||
const n = parseFloat(m[1]);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
Reference in New Issue
Block a user