feat: export částečných receptů
This commit is contained in:
1 parent
5e76c404fb
commit
8377ce2205
16 files changed
+444
-145
No files matched your search
@@ -384,6 +384,11 @@ v API vždy vyplněná; slaná je výchozí a do úložiště se nezapisuje, `to
|
|||||||
ji při čtení doplní.
|
ji při čtení doplní.
|
||||||
Volitelný je i **čas přípravy** (`prepMinutes`, v minutách).
|
Volitelný je i **čas přípravy** (`prepMinutes`, v minutách).
|
||||||
|
|
||||||
|
**Neúplný recept:** suroviny ani postup nejsou povinné, uložit jde i recept jen
|
||||||
|
s názvem (`ingredients: []`) a doplnit ho později. **Úplný** je recept se
|
||||||
|
surovinami i postupem (`isRecipeComplete` v `Utils.tsx`) — jen ten jde do
|
||||||
|
běžného exportu.
|
||||||
|
|
||||||
**Jednotky surovin:** surovina má množství v gramech (`weight`), nebo v jiné
|
**Jednotky surovin:** surovina má množství v gramech (`weight`), nebo v jiné
|
||||||
jednotce (`amount` + `unit`, `IngredientUnit`: ks, ml, l, lžíce…) — vejce
|
jednotce (`amount` + `unit`, `IngredientUnit`: ks, ml, l, lžíce…) — vejce
|
||||||
na kusy, mléko v litrech. U jiné jednotky je `weight` jen nepovinný **přepočet
|
na kusy, mléko v litrech. U jiné jednotky je `weight` jen nepovinný **přepočet
|
||||||
@@ -413,12 +418,31 @@ Markdownu v jedné cestě, je potřeba upravit i druhou.**
|
|||||||
|
|
||||||
**Export do PDF** (`recipePdf.ts`, pdfmake v prohlížeči, načte se líně až při
|
**Export do PDF** (`recipePdf.ts`, pdfmake v prohlížeči, načte se líně až při
|
||||||
exportu) jde u jednoho receptu (ikona na kartě receptu) i hromadně tlačítkem
|
exportu) jde u jednoho receptu (ikona na kartě receptu) i hromadně tlačítkem
|
||||||
na stránce Jídla — exportují se recepty, které seznam po filtrech ukazuje, bez
|
na stránce Jídla (`RecipeExportButton`) — exportují se recepty, které seznam
|
||||||
filtru všechny. Víc receptů dostane titulní stranu s klikacím obsahem, každý
|
po filtrech ukazuje, bez filtru všechny. Hlavní tlačítko bere jen úplné recepty,
|
||||||
|
nabídka u něj i neúplné. Víc receptů dostane titulní stranu s klikacím obsahem, každý
|
||||||
recept začíná na nové stránce. PDF nese suroviny, hodnoty porce, postup a fotky
|
recept začíná na nové stránce. PDF nese suroviny, hodnoty porce, postup a fotky
|
||||||
jídla (první přes šířku, ostatní menší); pdfmake umí jen JPEG a PNG, jiné
|
jídla (první přes šířku, ostatní menší); pdfmake umí jen JPEG a PNG, jiné
|
||||||
formáty se vynechají. Server se exportu neúčastní.
|
formáty se vynechají. Server se exportu neúčastní.
|
||||||
|
|
||||||
|
**PDF k doplnění** (volba v nabídce exportu, neúplný recept ho dostane vždy):
|
||||||
|
každý recept má vyplnitelná pole pro čas přípravy, počet porcí a hmotnost
|
||||||
|
hotového jídla, předvyplněná tím, co recept už má, aby šla i opravit. Suroviny
|
||||||
|
a postup jsou pole (jedno volné textové) jen tam, kde chybí; chybu v hotových
|
||||||
|
jde popsat v poli Poznámky a opravy, které má každý recept. Energie záměrně ne,
|
||||||
|
tu si uživatel dohledá sám.
|
||||||
|
PDF se pošle někomu, kdo recept zná, a vyplněné údaje se do aplikace přepíšou
|
||||||
|
ručně — nic se zpátky neimportuje. pdfmake formuláře neumí: vykreslí jen
|
||||||
|
popisek a rámeček, `pageBreakBefore` zachytí jeho pozici (a popisek, jehož pole
|
||||||
|
se nevešlo, posune na další stránku) a `pdfFormFields.ts` pak přes pdf-lib
|
||||||
|
položí pole na rámeček. Rámeček proto musí být holý uzel v toku — uvnitř
|
||||||
|
`unbreakable` nebo tabulky pdfmake hlásí pozici z prvního pokusu o rozvržení.
|
||||||
|
Písmo polí je celé Roboto, Helvetica nemá českou diakritiku.
|
||||||
|
|
||||||
|
**Inline formátování v PDF** se skládá do plochého pole textů (`convertInline`
|
||||||
|
v `markdownPdf.ts`) — pdfmake styl vnořeného pole `text` zahodí
|
||||||
|
(bpampuch/pdfmake#1174), tučné a kurzíva by se ztratily třeba v seznamu.
|
||||||
|
|
||||||
**Kolo štěstí** (`SpinWheelModal`, tlačítko v hlavičce) je převzaté z Luncheru.
|
**Kolo štěstí** (`SpinWheelModal`, tlačítko v hlavičce) je převzaté z Luncheru.
|
||||||
Losuje ze všech jídel (skupin ze seznamu jídel — i objednávaných), nebo jen
|
Losuje ze všech jídel (skupin ze seznamu jídel — i objednávaných), nebo jen
|
||||||
z receptů, volitelně zúžených chutí a typem. U všech jídel se nejdřív vybere
|
z receptů, volitelně zúžených chutí a typem. U všech jídel se nejdřív vybere
|
||||||
@@ -429,7 +453,7 @@ rozhoduje. Konfety (`WheelConfetti`) mají vzhled jednoduchého stylu a Hell Gir
|
|||||||
|
|
||||||
Dřív pod stejným klíčem ležely i šablony hotových jídel (`kind: HOTOVE`, nebo
|
Dřív pod stejným klíčem ležely i šablony hotových jídel (`kind: HOTOVE`, nebo
|
||||||
bez `kind`). Ty zanikly: `loadRecipes` je při čtení vynechá (poznají se podle
|
bez `kind`). Ty zanikly: `loadRecipes` je při čtení vynechá (poznají se podle
|
||||||
toho, že nemají suroviny) a první zápis receptu je z úložiště odklidí. **Jídla
|
toho, že pole `ingredients` vůbec nemají — recept ho má vždy, neúplný prázdné) a první zápis receptu je z úložiště odklidí. **Jídla
|
||||||
z nich založená ve dnech zůstávají**, dál nesou `templateId` zaniklé šablony.
|
z nich založená ve dnech zůstávají**, dál nesou `templateId` zaniklé šablony.
|
||||||
|
|
||||||
Jídlo založené z receptu nese `templateId`. Nastavuje ho jen server
|
Jídlo založené z receptu nese `templateId`. Nastavuje ho jen server
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
"@fortawesome/free-regular-svg-icons": "^7.1.0",
|
"@fortawesome/free-regular-svg-icons": "^7.1.0",
|
||||||
"@fortawesome/free-solid-svg-icons": "^7.1.0",
|
"@fortawesome/free-solid-svg-icons": "^7.1.0",
|
||||||
"@fortawesome/react-fontawesome": "^3.1.0",
|
"@fortawesome/react-fontawesome": "^3.1.0",
|
||||||
|
"@pdf-lib/fontkit": "1.1.1",
|
||||||
"@types/mdast": "4.0.4",
|
"@types/mdast": "4.0.4",
|
||||||
"@types/node": "^24.10.0",
|
"@types/node": "^24.10.0",
|
||||||
"@types/pdfmake": "0.3.3",
|
"@types/pdfmake": "0.3.3",
|
||||||
@@ -18,6 +19,7 @@
|
|||||||
"@vitejs/plugin-react": "^5.1.0",
|
"@vitejs/plugin-react": "^5.1.0",
|
||||||
"bootstrap": "^5.3.8",
|
"bootstrap": "^5.3.8",
|
||||||
"mdast-util-from-markdown": "2.0.3",
|
"mdast-util-from-markdown": "2.0.3",
|
||||||
|
"pdf-lib": "1.17.1",
|
||||||
"pdfmake": "0.3.11",
|
"pdfmake": "0.3.11",
|
||||||
"react": "^19.2.0",
|
"react": "^19.2.0",
|
||||||
"react-bootstrap": "^2.10.10",
|
"react-bootstrap": "^2.10.10",
|
||||||
|
|||||||
@@ -393,6 +393,13 @@ export const normalizeSearch = (value: string): string =>
|
|||||||
export const getMealKey = (meal: { name: string, source?: string }): string =>
|
export const getMealKey = (meal: { name: string, source?: string }): string =>
|
||||||
`${normalizeSearch(meal.name)}|${normalizeSearch(meal.source ?? '')}`;
|
`${normalizeSearch(meal.name)}|${normalizeSearch(meal.source ?? '')}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Úplný recept má suroviny i postup. Neúplný jde uložit taky, ale do běžného
|
||||||
|
* exportu nepatří — exportuje se jen jako PDF k doplnění.
|
||||||
|
*/
|
||||||
|
export const isRecipeComplete = (recipe: Pick<MealTemplate, 'ingredients' | 'note'>): boolean =>
|
||||||
|
recipe.ingredients.length > 0 && !!recipe.note?.trim();
|
||||||
|
|
||||||
/** Popíše recept jednou řádkou — zdroj a hodnoty jedné porce, co je vyplněné. */
|
/** Popíše recept jednou řádkou — zdroj a hodnoty jedné porce, co je vyplněné. */
|
||||||
export const describeMealTemplate = (template: MealTemplate): string => [
|
export const describeMealTemplate = (template: MealTemplate): string => [
|
||||||
template.source,
|
template.source,
|
||||||
|
|||||||
@@ -88,7 +88,8 @@ const MealTemplateForm = ({ template, meal, onSaved, onCancel }: Readonly<Props>
|
|||||||
const ingredientWeight = filledIngredients.reduce((sum, item) => sum + (item.weight ?? 0), 0);
|
const ingredientWeight = filledIngredients.reduce((sum, item) => sum + (item.weight ?? 0), 0);
|
||||||
const prepMinutes = parseIntInput(form.prepMinutes);
|
const prepMinutes = parseIntInput(form.prepMinutes);
|
||||||
|
|
||||||
const canSave = form.name.trim().length > 0 && filledIngredients.length > 0 && !busy;
|
// Suroviny ani postup nejsou povinné — neúplný recept se doplní později (třeba z PDF k doplnění)
|
||||||
|
const canSave = form.name.trim().length > 0 && !busy;
|
||||||
|
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
if (!canSave) return;
|
if (!canSave) return;
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { Button, ButtonGroup, Dropdown, Spinner } from "react-bootstrap";
|
||||||
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
|
import { faFilePdf } from "@fortawesome/free-solid-svg-icons";
|
||||||
|
import { MealGroup, MealTemplate } from "../../../types";
|
||||||
|
import { isRecipeComplete } from "../Utils";
|
||||||
|
import { useRecipeExport } from "../useRecipeExport";
|
||||||
|
|
||||||
|
type RecipeItem = Pick<MealGroup, 'photoCount'> & { recipe: MealTemplate };
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
/** Recepty, které seznam po filtrech ukazuje */
|
||||||
|
itemList: RecipeItem[],
|
||||||
|
filtered: boolean,
|
||||||
|
loading: boolean,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hromadný export receptů do PDF. Hlavní tlačítko stáhne jen úplné recepty
|
||||||
|
* (se surovinami i postupem); v nabídce je export všech včetně neúplných
|
||||||
|
* s poli k doplnění a opravě — PDF se pošle někomu, kdo recepty zná.
|
||||||
|
*/
|
||||||
|
const RecipeExportButton = ({ itemList, filtered, loading }: Readonly<Props>) => {
|
||||||
|
const { exporting, exportRecipes } = useRecipeExport();
|
||||||
|
const completeList = itemList.filter(item => isRecipeComplete(item.recipe));
|
||||||
|
const scope = filtered ? 'zobrazené' : 'všechny';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dropdown as={ButtonGroup}>
|
||||||
|
<Button
|
||||||
|
variant="outline-secondary"
|
||||||
|
disabled={exporting || !completeList.length}
|
||||||
|
title={`Stáhnout ${scope} úplné recepty jako PDF`}
|
||||||
|
onClick={() => exportRecipes(completeList)}
|
||||||
|
>
|
||||||
|
{exporting ? <Spinner animation="border" size="sm" /> : <FontAwesomeIcon icon={faFilePdf} />}
|
||||||
|
{' '}Recepty do PDF{!loading && ` (${completeList.length})`}
|
||||||
|
</Button>
|
||||||
|
<Dropdown.Toggle split variant="outline-secondary" disabled={exporting || !itemList.length} />
|
||||||
|
<Dropdown.Menu align="end">
|
||||||
|
<Dropdown.Item onClick={() => exportRecipes(itemList, true)}>
|
||||||
|
K doplnění, včetně neúplných ({itemList.length})
|
||||||
|
<div className="small text-muted">čas, porce, hmotnost, chybějící suroviny a postup i poznámky jde dopsat přímo v PDF</div>
|
||||||
|
</Dropdown.Item>
|
||||||
|
</Dropdown.Menu>
|
||||||
|
</Dropdown>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RecipeExportButton;
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { Button, Form, Modal } from "react-bootstrap";
|
import { Button, Form, Modal } from "react-bootstrap";
|
||||||
|
import { toast } from "react-toastify";
|
||||||
import {
|
import {
|
||||||
DayRecord, MealEntry, MealSuggestion, MealTemplate, MealType, UserSettings,
|
DayRecord, MealEntry, MealSuggestion, MealTemplate, MealType, UserSettings,
|
||||||
addMeal, getMealHistory, getMealTemplates, getSettings, updateMeal,
|
addMeal, getMealHistory, getMealTemplates, getSettings, updateMeal,
|
||||||
@@ -24,8 +25,11 @@ type Props = {
|
|||||||
/** Upravovaný záznam. Pokud chybí, jde o založení nového. */
|
/** Upravovaný záznam. Pokud chybí, jde o založení nového. */
|
||||||
entry?: MealEntry,
|
entry?: MealEntry,
|
||||||
onClose: () => void,
|
onClose: () => void,
|
||||||
/** Zavolá se po uložení s přehledem dne a uloženým jídlem. */
|
/**
|
||||||
onSaved: (day: DayRecord, saved?: MealEntry) => void,
|
* Zavolá se po uložení s přehledem dne a uloženým jídlem. `keepOpen` značí
|
||||||
|
* uložení s pokračováním — formulář zůstává otevřený pro další jídlo.
|
||||||
|
*/
|
||||||
|
onSaved: (day: DayRecord, saved?: MealEntry, keepOpen?: boolean) => void,
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Prázdný formulář pro nové jídlo v daném dni. */
|
/** Prázdný formulář pro nové jídlo v daném dni. */
|
||||||
@@ -93,6 +97,7 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
|||||||
const [history, setHistory] = useState<MealSuggestion[]>([]);
|
const [history, setHistory] = useState<MealSuggestion[]>([]);
|
||||||
/** Název návrhu, ze kterého se formulář naposledy vyplnil — pak už se návrhy nenabízejí. */
|
/** Název návrhu, ze kterého se formulář naposledy vyplnil — pak už se návrhy nenabízejí. */
|
||||||
const [pickedSuggestion, setPickedSuggestion] = useState<string | undefined>();
|
const [pickedSuggestion, setPickedSuggestion] = useState<string | undefined>();
|
||||||
|
const nameRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
// Při každém otevření se formulář naplní dle toho, co se upravuje
|
// Při každém otevření se formulář naplní dle toho, co se upravuje
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -201,7 +206,12 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
|||||||
|
|
||||||
const canSave = form.name.trim().length > 0 && !multiplierInvalid && !nutrientsInvalid && !saving;
|
const canSave = form.name.trim().length > 0 && !multiplierInvalid && !nutrientsInvalid && !saving;
|
||||||
|
|
||||||
const save = async () => {
|
/**
|
||||||
|
* Uloží jídlo. S `keepOpen` formulář nezavře, jen ho vyčistí pro další jídlo —
|
||||||
|
* celý den se tak zapíše bez opakovaného otevírání. Datum a chod zůstanou,
|
||||||
|
* další jídlo bývá ze stejného dne.
|
||||||
|
*/
|
||||||
|
const save = async (keepOpen = false) => {
|
||||||
if (!canSave) return;
|
if (!canSave) return;
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
const body = {
|
const body = {
|
||||||
@@ -228,7 +238,13 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
|||||||
const saved = entry
|
const saved = entry
|
||||||
? response.data.entries.find(item => item.id === entry.id)
|
? response.data.entries.find(item => item.id === entry.id)
|
||||||
: [...response.data.entries].sort((a, b) => a.createdAt.localeCompare(b.createdAt)).pop();
|
: [...response.data.entries].sort((a, b) => a.createdAt.localeCompare(b.createdAt)).pop();
|
||||||
onSaved(response.data, saved);
|
onSaved(response.data, saved, keepOpen);
|
||||||
|
if (keepOpen) {
|
||||||
|
toast.success(`Uloženo: ${body.name}`);
|
||||||
|
setForm({ ...emptyForm(form.date), mealType: form.mealType });
|
||||||
|
setPickedSuggestion(undefined);
|
||||||
|
nameRef.current?.focus();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -242,6 +258,7 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
|||||||
<Form.Group className="mb-3">
|
<Form.Group className="mb-3">
|
||||||
<Form.Label>Jídlo</Form.Label>
|
<Form.Label>Jídlo</Form.Label>
|
||||||
<Form.Control
|
<Form.Control
|
||||||
|
ref={nameRef}
|
||||||
autoFocus
|
autoFocus
|
||||||
value={form.name}
|
value={form.name}
|
||||||
placeholder="Např. Kuřecí gyros s hranolkami"
|
placeholder="Např. Kuřecí gyros s hranolkami"
|
||||||
@@ -433,6 +450,16 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<Button variant="outline-secondary" onClick={onClose}>Zrušit</Button>
|
<Button variant="outline-secondary" onClick={onClose}>Zrušit</Button>
|
||||||
|
{!entry && (
|
||||||
|
<Button
|
||||||
|
variant="outline-primary"
|
||||||
|
title="Uloží jídlo a vyčistí formulář pro další"
|
||||||
|
onClick={() => save(true)}
|
||||||
|
disabled={!canSave}
|
||||||
|
>
|
||||||
|
Uložit a další
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<Button onClick={() => save()} disabled={!canSave}>
|
<Button onClick={() => save()} disabled={!canSave}>
|
||||||
{saving ? 'Ukládám…' : 'Uložit'}
|
{saving ? 'Ukládám…' : 'Uložit'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
+23
-13
@@ -1,6 +1,6 @@
|
|||||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||||
import type { BlockContent, DefinitionContent, ListItem, PhrasingContent, RootContent } from "mdast";
|
import type { BlockContent, DefinitionContent, ListItem, PhrasingContent, RootContent } from "mdast";
|
||||||
import type { Content } from "pdfmake/interfaces";
|
import type { Content, ContentText } from "pdfmake/interfaces";
|
||||||
import { applyLineBreaks } from "./markdownBreaks";
|
import { applyLineBreaks } from "./markdownBreaks";
|
||||||
|
|
||||||
/** Barva odkazů a citací — stejná jako text vedle, jen tlumenější. */
|
/** Barva odkazů a citací — stejná jako text vedle, jen tlumenější. */
|
||||||
@@ -8,31 +8,41 @@ const MUTED_COLOR = '#6b7280';
|
|||||||
const LINK_COLOR = '#15803d';
|
const LINK_COLOR = '#15803d';
|
||||||
const CODE_BACKGROUND = '#f3f4f6';
|
const CODE_BACKGROUND = '#f3f4f6';
|
||||||
|
|
||||||
const convertInline = (nodeList: PhrasingContent[]): Content[] => nodeList.map(convertPhrasing);
|
/** Formátování zděděné od nadřazených uzlů (tučně uvnitř odkazu, kurzíva uvnitř tučného…). */
|
||||||
|
type InlineStyle = Pick<ContentText, 'bold' | 'italics' | 'decoration' | 'background' | 'color' | 'link'>;
|
||||||
|
|
||||||
const convertPhrasing = (node: PhrasingContent): Content => {
|
/**
|
||||||
|
* Inline obsah se skládá do plochého pole textů, každý s celým svým formátováním.
|
||||||
|
* pdfmake styl vnořeného pole `text` zahodí (bpampuch/pdfmake#1174) — tučné
|
||||||
|
* nebo kurzíva by se ztratily, jakmile je kolem ještě další úroveň, typicky
|
||||||
|
* v položce seznamu.
|
||||||
|
*/
|
||||||
|
const convertInline = (nodeList: PhrasingContent[], style: InlineStyle = {}): Content[] =>
|
||||||
|
nodeList.flatMap(node => convertPhrasing(node, style));
|
||||||
|
|
||||||
|
const convertPhrasing = (node: PhrasingContent, style: InlineStyle): Content[] => {
|
||||||
switch (node.type) {
|
switch (node.type) {
|
||||||
case 'text':
|
case 'text':
|
||||||
return node.value;
|
return [{ ...style, text: node.value }];
|
||||||
case 'strong':
|
case 'strong':
|
||||||
return { text: convertInline(node.children), bold: true };
|
return convertInline(node.children, { ...style, bold: true });
|
||||||
case 'emphasis':
|
case 'emphasis':
|
||||||
return { text: convertInline(node.children), italics: true };
|
return convertInline(node.children, { ...style, italics: true });
|
||||||
case 'delete':
|
case 'delete':
|
||||||
return { text: convertInline(node.children), decoration: 'lineThrough' };
|
return convertInline(node.children, { ...style, decoration: 'lineThrough' });
|
||||||
case 'inlineCode':
|
case 'inlineCode':
|
||||||
return { text: node.value, background: CODE_BACKGROUND };
|
return [{ ...style, text: node.value, background: CODE_BACKGROUND }];
|
||||||
case 'break':
|
case 'break':
|
||||||
return '\n';
|
return [{ ...style, text: '\n' }];
|
||||||
case 'link':
|
case 'link':
|
||||||
return { text: convertInline(node.children), link: node.url, color: LINK_COLOR, decoration: 'underline' };
|
return convertInline(node.children, { ...style, link: node.url, color: LINK_COLOR, decoration: 'underline' });
|
||||||
// Obrázky z internetu se do PDF nestahují, zůstane popisek
|
// Obrázky z internetu se do PDF nestahují, zůstane popisek
|
||||||
case 'image':
|
case 'image':
|
||||||
return node.alt ?? '';
|
return [{ ...style, text: node.alt ?? '' }];
|
||||||
case 'html':
|
case 'html':
|
||||||
return node.value;
|
return [{ ...style, text: node.value }];
|
||||||
default:
|
default:
|
||||||
return 'children' in node ? convertInline(node.children as PhrasingContent[]) : '';
|
return 'children' in node ? convertInline(node.children as PhrasingContent[], style) : [];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -421,8 +421,8 @@ export default function DayPage() {
|
|||||||
date={date}
|
date={date}
|
||||||
entry={editedMeal}
|
entry={editedMeal}
|
||||||
onClose={() => setMealModalOpen(false)}
|
onClose={() => setMealModalOpen(false)}
|
||||||
onSaved={(saved, savedEntry) => {
|
onSaved={(saved, savedEntry, keepOpen) => {
|
||||||
setMealModalOpen(false);
|
if (!keepOpen) setMealModalOpen(false);
|
||||||
const hasNutrition = savedEntry?.calories != null || !!savedEntry?.nutrientsPer100g;
|
const hasNutrition = savedEntry?.calories != null || !!savedEntry?.nutrientsPer100g;
|
||||||
setFillOfferEntry(hasNutrition ? savedEntry : undefined);
|
setFillOfferEntry(hasNutrition ? savedEntry : undefined);
|
||||||
// Úprava mohla jídlo přesunout jinam — pak přepneme na jeho nový den
|
// Úprava mohla jídlo přesunout jinam — pak přepneme na jeho nový den
|
||||||
|
|||||||
@@ -2,13 +2,13 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
|||||||
import { Button, Form, Spinner } from "react-bootstrap";
|
import { Button, Form, Spinner } from "react-bootstrap";
|
||||||
import { useLocation } from "react-router";
|
import { useLocation } from "react-router";
|
||||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||||
import { faBookOpen, faCircleCheck, faFilePdf } from "@fortawesome/free-solid-svg-icons";
|
import { faBookOpen, faCircleCheck } from "@fortawesome/free-solid-svg-icons";
|
||||||
import { MealGroup, MealTemplate, getMealGroups } from "../../../types";
|
import { MealGroup, MealTemplate, getMealGroups } from "../../../types";
|
||||||
import { MealGroupAction, RECIPE_FILTER_NAMES, RecipeFilter, SourceFilter } from "../enums";
|
import { MealGroupAction, RECIPE_FILTER_NAMES, RecipeFilter, SourceFilter } from "../enums";
|
||||||
import { getMealKey, normalizeSearch } from "../Utils";
|
import { getMealKey, normalizeSearch } from "../Utils";
|
||||||
import MealGroupRow from "../components/MealGroupRow";
|
import MealGroupRow from "../components/MealGroupRow";
|
||||||
import MealTemplateForm from "../components/MealTemplateForm";
|
import MealTemplateForm from "../components/MealTemplateForm";
|
||||||
import { useRecipeExport } from "../useRecipeExport";
|
import RecipeExportButton from "../components/RecipeExportButton";
|
||||||
import "./templates.scss";
|
import "./templates.scss";
|
||||||
import "./MealGroupsPage.scss";
|
import "./MealGroupsPage.scss";
|
||||||
|
|
||||||
@@ -75,7 +75,6 @@ const MealGroupsPage = () => {
|
|||||||
const [opened, setOpened] = useState<{ key: string, action: MealGroupAction } | undefined>();
|
const [opened, setOpened] = useState<{ key: string, action: MealGroupAction } | undefined>();
|
||||||
const [newRecipeOpen, setNewRecipeOpen] = useState(false);
|
const [newRecipeOpen, setNewRecipeOpen] = useState(false);
|
||||||
const [scrollKey, setScrollKey] = useState<string | undefined>();
|
const [scrollKey, setScrollKey] = useState<string | undefined>();
|
||||||
const { exporting, exportRecipes } = useRecipeExport();
|
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
const response = await getMealGroups();
|
const response = await getMealGroups();
|
||||||
@@ -138,15 +137,7 @@ const MealGroupsPage = () => {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="page-header-actions">
|
<div className="page-header-actions">
|
||||||
<Button
|
<RecipeExportButton itemList={visibleRecipeList} filtered={filtered} loading={loading} />
|
||||||
variant="outline-secondary"
|
|
||||||
disabled={exporting || !visibleRecipeList.length}
|
|
||||||
title={filtered ? 'Stáhnout zobrazené recepty jako PDF' : 'Stáhnout všechny recepty jako PDF'}
|
|
||||||
onClick={() => exportRecipes(visibleRecipeList)}
|
|
||||||
>
|
|
||||||
{exporting ? <Spinner animation="border" size="sm" /> : <FontAwesomeIcon icon={faFilePdf} />}
|
|
||||||
{' '}Recepty do PDF{!loading && ` (${visibleRecipeList.length})`}
|
|
||||||
</Button>
|
|
||||||
<Button variant="outline-secondary" onClick={() => setNewRecipeOpen(open => !open)}>
|
<Button variant="outline-secondary" onClick={() => setNewRecipeOpen(open => !open)}>
|
||||||
<FontAwesomeIcon icon={faBookOpen} /> Nový recept
|
<FontAwesomeIcon icon={faBookOpen} /> Nový recept
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import type { NodeStartPosition } from "pdfmake/interfaces";
|
||||||
|
|
||||||
|
/** Formulářové pole PDF, pro které pdfmake vyhradil místo v dokumentu. */
|
||||||
|
export type PdfFormField = {
|
||||||
|
/** Jednoznačný název pole v dokumentu — bez teček, ty v PDF dělají hierarchii */
|
||||||
|
name: string,
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
multiline: boolean,
|
||||||
|
/** Předvyplněná hodnota, kterou jde v PDF přepsat */
|
||||||
|
value?: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PlacedPdfFormField = PdfFormField & { position: NodeStartPosition };
|
||||||
|
|
||||||
|
/** Odsazení textu od okraje pole, aby se nelepil na rámeček vykreslený pdfmake. */
|
||||||
|
const FIELD_INSET = 2;
|
||||||
|
const FIELD_FONT_SIZE = 10;
|
||||||
|
|
||||||
|
const decodeBase64 = (value: string): Uint8Array => Uint8Array.from(atob(value), char => char.charCodeAt(0));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Doplní do hotového PDF vyplnitelná textová pole. pdfmake formuláře neumí, takže
|
||||||
|
* v dokumentu jen vykreslí rámeček a pole se přes něj položí dodatečně (pdf-lib).
|
||||||
|
* Souřadnice z pdfmake počítají od horního okraje, PDF od spodního.
|
||||||
|
*
|
||||||
|
* Písmo polí je celé (ne podmnožina) Roboto — výchozí Helvetica neumí českou
|
||||||
|
* diakritiku a podmnožina by měla jen znaky, které už v dokumentu jsou.
|
||||||
|
*
|
||||||
|
* @param pdfBytes PDF vygenerované pdfmake
|
||||||
|
* @param fieldList pole s pozicí, kterou pdfmake vyhradil
|
||||||
|
* @param fontBase64 písmo pro text polí (TTF v base64, jak ho nese vfs pdfmake)
|
||||||
|
*/
|
||||||
|
export const addFormFields = async (
|
||||||
|
pdfBytes: Uint8Array, fieldList: PlacedPdfFormField[], fontBase64: string,
|
||||||
|
): Promise<Uint8Array> => {
|
||||||
|
const [{ PDFDocument }, { default: fontkit }] = await Promise.all([import("pdf-lib"), import("@pdf-lib/fontkit")]);
|
||||||
|
const pdf = await PDFDocument.load(pdfBytes);
|
||||||
|
pdf.registerFontkit(fontkit);
|
||||||
|
const font = await pdf.embedFont(decodeBase64(fontBase64), { subset: false });
|
||||||
|
const form = pdf.getForm();
|
||||||
|
|
||||||
|
for (const field of fieldList) {
|
||||||
|
const page = pdf.getPage(field.position.pageNumber - 1);
|
||||||
|
const textField = form.createTextField(field.name);
|
||||||
|
if (field.multiline) textField.enableMultiline();
|
||||||
|
textField.addToPage(page, {
|
||||||
|
x: field.position.left + FIELD_INSET,
|
||||||
|
y: page.getHeight() - field.position.top - field.height + FIELD_INSET,
|
||||||
|
width: field.width - 2 * FIELD_INSET,
|
||||||
|
height: field.height - 2 * FIELD_INSET,
|
||||||
|
font,
|
||||||
|
// Rámeček i podklad kreslí pdfmake, aby pole bylo vidět i po vytištění
|
||||||
|
borderWidth: 0,
|
||||||
|
backgroundColor: undefined,
|
||||||
|
borderColor: undefined,
|
||||||
|
});
|
||||||
|
textField.setFontSize(FIELD_FONT_SIZE);
|
||||||
|
if (field.value) textField.setText(field.value);
|
||||||
|
}
|
||||||
|
form.updateFieldAppearances(font);
|
||||||
|
return pdf.save();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Nabídne PDF ke stažení. */
|
||||||
|
export const downloadPdf = (pdfBytes: Uint8Array, fileName: string) => {
|
||||||
|
const url = URL.createObjectURL(new Blob([pdfBytes as BlobPart], { type: 'application/pdf' }));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = fileName;
|
||||||
|
link.click();
|
||||||
|
// Prohlížeč si soubor převezme až po kliknutí, adresa se uvolní s odstupem
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||||
|
};
|
||||||
+161
-95
@@ -1,10 +1,11 @@
|
|||||||
import type { Content, TDocumentDefinitions } from "pdfmake/interfaces";
|
import type { Content, ContentCanvas, Node, NodeQueries, NodeStartPosition, TDocumentDefinitions } from "pdfmake/interfaces";
|
||||||
import { MealGroup, MealPhoto, MealTemplate, getMealPhotos, getMealTemplates } from "../../types";
|
import { MealGroup, MealPhoto, MealTemplate, getMealPhotos, getMealTemplates } from "../../types";
|
||||||
import { RECIPE_FLAVOR_NAMES, RECIPE_LINK_NAMES, RecipeLinkKind, getRecipeLinkIds } from "./enums";
|
import { RECIPE_FLAVOR_NAMES, RECIPE_LINK_NAMES, RecipeLinkKind, getRecipeLinkIds } from "./enums";
|
||||||
import { convertMarkdownToPdf } from "./markdownPdf";
|
import { convertMarkdownToPdf } from "./markdownPdf";
|
||||||
|
import type { PdfFormField } from "./pdfFormFields";
|
||||||
import {
|
import {
|
||||||
deriveRecipe, formatCalories, formatCount, formatDate, formatDateString, formatIngredientAmount, formatPrepTime,
|
deriveRecipe, formatCalories, formatCount, formatDate, formatDateString, formatIngredientAmount, formatPrepTime,
|
||||||
formatPrice, formatWeight, getIngredientCalories,
|
formatPrice, formatWeight, getIngredientCalories, isRecipeComplete,
|
||||||
} from "./Utils";
|
} from "./Utils";
|
||||||
|
|
||||||
/** Recept s počtem fotek jídla — fotky se stahují jen tam, kde nějaké jsou. */
|
/** Recept s počtem fotek jídla — fotky se stahují jen tam, kde nějaké jsou. */
|
||||||
@@ -13,10 +14,24 @@ type RecipeItem = Pick<MealGroup, 'photoCount'> & { recipe: MealTemplate };
|
|||||||
const PRIMARY_COLOR = '#156080';
|
const PRIMARY_COLOR = '#156080';
|
||||||
const MUTED_COLOR = '#6b7280';
|
const MUTED_COLOR = '#6b7280';
|
||||||
const BORDER_COLOR = '#e5e7eb';
|
const BORDER_COLOR = '#e5e7eb';
|
||||||
|
const FIELD_BORDER_COLOR = '#9ca3af';
|
||||||
|
const FIELD_BACKGROUND = '#f9fafb';
|
||||||
/** Šířka tisknutelné plochy A4 při okrajích 40 pt. */
|
/** Šířka tisknutelné plochy A4 při okrajích 40 pt. */
|
||||||
const CONTENT_WIDTH = 515;
|
const CONTENT_WIDTH = 515;
|
||||||
const PHOTO_GAP = 8;
|
const PHOTO_COLUMN_WIDTH = 220;
|
||||||
const SMALL_PHOTOS_PER_ROW = 3;
|
|
||||||
|
/** Rozměry polí k doplnění v pt. */
|
||||||
|
const SHORT_FIELD_WIDTH = 160;
|
||||||
|
const SHORT_FIELD_HEIGHT = 20;
|
||||||
|
const SHORT_FIELD_GAP = 17;
|
||||||
|
/** Výšky velkých polí jsou zvolené tak, aby se recept jen s názvem vešel na jednu stránku. */
|
||||||
|
const INGREDIENTS_FIELD_HEIGHT = 150;
|
||||||
|
const NOTE_FIELD_HEIGHT = 230;
|
||||||
|
const REMARKS_FIELD_HEIGHT = 90;
|
||||||
|
|
||||||
|
/** Předpony `id` uzlů, podle kterých se v rozvržení pdfmake najdou pole a jejich popisky. */
|
||||||
|
const FIELD_ID_PREFIX = 'pole:';
|
||||||
|
const LABEL_ID_PREFIX = 'popisek:';
|
||||||
|
|
||||||
/** pdfmake umí jen JPEG a PNG; fotky se sice ukládají jako JPEG, API ale přijímá i WebP. */
|
/** pdfmake umí jen JPEG a PNG; fotky se sice ukládají jako JPEG, API ale přijímá i WebP. */
|
||||||
const isSupportedImage = (photo: MealPhoto): boolean => /^data:image\/(jpeg|png)/.test(photo.image);
|
const isSupportedImage = (photo: MealPhoto): boolean => /^data:image\/(jpeg|png)/.test(photo.image);
|
||||||
@@ -24,12 +39,17 @@ const isSupportedImage = (photo: MealPhoto): boolean => /^data:image\/(jpeg|png)
|
|||||||
/** Název souboru bez znaků, které systémy v názvu nepovolí. */
|
/** Název souboru bez znaků, které systémy v názvu nepovolí. */
|
||||||
const toFileName = (name: string): string => `${name.replace(/[\\/:*?"<>|]+/g, '').trim() || 'recept'}.pdf`;
|
const toFileName = (name: string): string => `${name.replace(/[\\/:*?"<>|]+/g, '').trim() || 'recept'}.pdf`;
|
||||||
|
|
||||||
const getRecipeMeta = (recipe: MealTemplate): string => {
|
/**
|
||||||
|
* Čas přípravy a počet porcí se v PDF k doplnění nevypisují — jsou v polích,
|
||||||
|
* kde jdou opravit, a „1 porce" by u nevyplněných porcí tvrdilo něco, co je
|
||||||
|
* teprve k doplnění.
|
||||||
|
*/
|
||||||
|
const getRecipeMeta = (recipe: MealTemplate, editable: boolean): string => {
|
||||||
return [
|
return [
|
||||||
recipe.category,
|
recipe.category,
|
||||||
RECIPE_FLAVOR_NAMES[recipe.flavor].toLowerCase(),
|
RECIPE_FLAVOR_NAMES[recipe.flavor].toLowerCase(),
|
||||||
recipe.prepMinutes != null ? `příprava ${formatPrepTime(recipe.prepMinutes)}` : undefined,
|
!editable && recipe.prepMinutes != null ? `příprava ${formatPrepTime(recipe.prepMinutes)}` : undefined,
|
||||||
formatCount(recipe.servings ?? 1, 'porce', 'porce', 'porcí'),
|
!editable ? formatCount(recipe.servings ?? 1, 'porce', 'porce', 'porcí') : undefined,
|
||||||
recipe.weight != null ? `porce ${formatWeight(recipe.weight)}` : undefined,
|
recipe.weight != null ? `porce ${formatWeight(recipe.weight)}` : undefined,
|
||||||
recipe.calories != null ? `${formatCalories(recipe.calories)} na porci` : undefined,
|
recipe.calories != null ? `${formatCalories(recipe.calories)} na porci` : undefined,
|
||||||
recipe.price != null ? `${formatPrice(recipe.price)} za porci` : undefined,
|
recipe.price != null ? `${formatPrice(recipe.price)} za porci` : undefined,
|
||||||
@@ -63,21 +83,9 @@ const createLinks = (recipe: MealTemplate, recipeList: MealTemplate[], indexMap:
|
|||||||
return [{ text: [{ text: `${RECIPE_LINK_NAMES[kind]}: `, bold: true }, ...nameList], style: 'recipeLinks' }];
|
return [{ text: [{ text: `${RECIPE_LINK_NAMES[kind]}: `, bold: true }, ...nameList], style: 'recipeLinks' }];
|
||||||
});
|
});
|
||||||
|
|
||||||
const PHOTO_COLUMN_WIDTH = 220;
|
|
||||||
const createPhotos = (photoList: MealPhoto[]): Content[] => {
|
const createPhotos = (photoList: MealPhoto[]): Content[] => {
|
||||||
const first = photoList[0];
|
const first = photoList[0];
|
||||||
|
return first ? [{ image: first.image, width: PHOTO_COLUMN_WIDTH, alignment: 'center' }] : [];
|
||||||
if (!first) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
image: first.image,
|
|
||||||
width: PHOTO_COLUMN_WIDTH,
|
|
||||||
alignment: 'center',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const createIngredients = (recipe: MealTemplate): Content[] => {
|
const createIngredients = (recipe: MealTemplate): Content[] => {
|
||||||
@@ -118,92 +126,129 @@ const createIngredients = (recipe: MealTemplate): Content[] => {
|
|||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Místo pro vyplnitelné pole: popisek a rámeček. Samotné pole položí přes
|
||||||
|
* rámeček až `addFormFields`, pdfmake formuláře neumí. Pole se zapíše do
|
||||||
|
* `fieldList`, aby se k němu po rozvržení dohledala pozice.
|
||||||
|
*/
|
||||||
|
const createField = (fieldList: PdfFormField[], field: PdfFormField, label: Content, labelStyle: string): Content[] => {
|
||||||
|
fieldList.push(field);
|
||||||
|
// Typy pdfmake u plátna `id` nepovolují, pdfmake ho ale předá do pageBreakBefore jako u každého uzlu
|
||||||
|
const box: ContentCanvas & { id: string } = {
|
||||||
|
canvas: [{
|
||||||
|
type: 'rect', x: 0, y: 0, w: field.width, h: field.height, r: 2,
|
||||||
|
color: FIELD_BACKGROUND, lineColor: FIELD_BORDER_COLOR, lineWidth: 0.6,
|
||||||
|
}],
|
||||||
|
id: FIELD_ID_PREFIX + field.name,
|
||||||
|
margin: [0, 2, 0, 0],
|
||||||
|
};
|
||||||
|
return [{ text: label, style: labelStyle, id: LABEL_ID_PREFIX + field.name }, box as Content];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pole receptu v PDF k doplnění — vyplní je ten, kdo recept zná, přímo v PDF
|
||||||
|
* a údaje se pak do aplikace přepíšou ručně. Čas, porce a hmotnost jsou vždy,
|
||||||
|
* předvyplněné tím, co recept už má, aby šly i opravit. Suroviny a postup jsou
|
||||||
|
* pole jen tam, kde chybí (jedno volné textové pole); chybu v hotových jde
|
||||||
|
* popsat v poznámkách. Energie chybí záměrně, tu si uživatel dohledá sám.
|
||||||
|
*/
|
||||||
|
const createEditableFields = (recipe: MealTemplate, index: number, fieldList: PdfFormField[]) => {
|
||||||
|
const prefix = `recept${index + 1}`;
|
||||||
|
const shortList = [
|
||||||
|
{ key: 'priprava', label: 'Čas přípravy (minuty)', value: recipe.prepMinutes },
|
||||||
|
{ key: 'porce', label: 'Počet porcí', value: recipe.servings },
|
||||||
|
{ key: 'hmotnost', label: 'Hmotnost hotového jídla (g)', value: recipe.cookedWeight },
|
||||||
|
];
|
||||||
|
|
||||||
|
const details: Content[] = [{
|
||||||
|
columns: shortList.map(item => ({
|
||||||
|
width: SHORT_FIELD_WIDTH,
|
||||||
|
stack: createField(fieldList, {
|
||||||
|
name: `${prefix}_${item.key}`, width: SHORT_FIELD_WIDTH, height: SHORT_FIELD_HEIGHT, multiline: false,
|
||||||
|
value: item.value != null ? String(item.value) : undefined,
|
||||||
|
}, item.label, 'fieldLabel'),
|
||||||
|
})),
|
||||||
|
columnGap: SHORT_FIELD_GAP,
|
||||||
|
margin: [0, 0, 0, 4],
|
||||||
|
}];
|
||||||
|
const ingredients = recipe.ingredients.length ? [] : createField(fieldList, {
|
||||||
|
name: `${prefix}_suroviny`, width: CONTENT_WIDTH, height: INGREDIENTS_FIELD_HEIGHT, multiline: true,
|
||||||
|
}, ['Suroviny', { text: ' jedna na řádek, s množstvím', style: 'fieldHint' }], 'sectionHeading');
|
||||||
|
const note = recipe.note?.trim() ? [] : createField(fieldList, {
|
||||||
|
name: `${prefix}_postup`, width: CONTENT_WIDTH, height: NOTE_FIELD_HEIGHT, multiline: true,
|
||||||
|
}, 'Postup', 'sectionHeading');
|
||||||
|
const remarks = createField(fieldList, {
|
||||||
|
name: `${prefix}_poznamky`, width: CONTENT_WIDTH, height: REMARKS_FIELD_HEIGHT, multiline: true,
|
||||||
|
}, ['Poznámky a opravy', { text: ' chyba v surovinách nebo postupu, cokoli dalšího', style: 'fieldHint' }], 'sectionHeading');
|
||||||
|
|
||||||
|
return { details, ingredients, note, remarks };
|
||||||
|
};
|
||||||
|
|
||||||
type RecipeContext = {
|
type RecipeContext = {
|
||||||
index: number,
|
index: number,
|
||||||
withToc: boolean,
|
withToc: boolean,
|
||||||
recipeList: MealTemplate[],
|
recipeList: MealTemplate[],
|
||||||
indexMap: Map<string, number>,
|
indexMap: Map<string, number>,
|
||||||
|
fieldList: PdfFormField[],
|
||||||
|
/** Všechny recepty dostanou pole k doplnění, nejen neúplné */
|
||||||
|
editable: boolean,
|
||||||
};
|
};
|
||||||
|
|
||||||
const createRecipe = (
|
const createRecipe = (
|
||||||
recipe: MealTemplate, photoList: MealPhoto[], { index, withToc, recipeList, indexMap }: RecipeContext,
|
recipe: MealTemplate, photoList: MealPhoto[],
|
||||||
|
{ index, withToc, recipeList, indexMap, fieldList, editable }: RecipeContext,
|
||||||
): Content => {
|
): Content => {
|
||||||
const hasPhotos = photoList.length > 0;
|
const fields = editable || !isRecipeComplete(recipe) ? createEditableFields(recipe, index, fieldList) : undefined;
|
||||||
return ({
|
const header: Content[] = [
|
||||||
stack: [
|
{ text: recipe.name, style: 'recipeTitle', id: getRecipeAnchor(index), tocItem: withToc },
|
||||||
...(hasPhotos
|
...(recipe.source ? [{ text: recipe.source, style: 'recipeSource' }] : []),
|
||||||
? [{
|
{ text: getRecipeMeta(recipe, !!fields), style: 'recipeMeta' },
|
||||||
columns: [
|
...(fields
|
||||||
{
|
? [{ text: 'Údaje v polích jde doplnit nebo opravit přímo v PDF a soubor uložit.', style: 'fieldHint', margin: [0, -8, 0, 12] as [number, number, number, number] }]
|
||||||
width: '*',
|
|
||||||
stack: [
|
|
||||||
{
|
|
||||||
text: recipe.name,
|
|
||||||
style: 'recipeTitle',
|
|
||||||
id: getRecipeAnchor(index),
|
|
||||||
tocItem: withToc,
|
|
||||||
},
|
|
||||||
|
|
||||||
...(recipe.source
|
|
||||||
? [{ text: recipe.source, style: 'recipeSource' }]
|
|
||||||
: []),
|
: []),
|
||||||
|
|
||||||
{
|
|
||||||
text: getRecipeMeta(recipe),
|
|
||||||
style: 'recipeMeta',
|
|
||||||
},
|
|
||||||
|
|
||||||
...createLinks(recipe, recipeList, indexMap),
|
...createLinks(recipe, recipeList, indexMap),
|
||||||
...createIngredients(recipe),
|
...createIngredients(recipe),
|
||||||
],
|
];
|
||||||
},
|
|
||||||
|
|
||||||
{
|
return {
|
||||||
width: 220,
|
stack: [
|
||||||
stack: createPhotos(photoList),
|
...(photoList.length
|
||||||
},
|
? [{
|
||||||
|
columns: [
|
||||||
|
{ width: '*', stack: header },
|
||||||
|
{ width: PHOTO_COLUMN_WIDTH, stack: createPhotos(photoList) },
|
||||||
],
|
],
|
||||||
columnGap: 20,
|
columnGap: 20,
|
||||||
}]
|
}]
|
||||||
: [
|
: header),
|
||||||
{
|
...(fields?.ingredients ?? []),
|
||||||
text: recipe.name,
|
...(fields?.details ?? []),
|
||||||
style: 'recipeTitle',
|
|
||||||
id: getRecipeAnchor(index),
|
|
||||||
tocItem: withToc,
|
|
||||||
},
|
|
||||||
|
|
||||||
...(recipe.source
|
|
||||||
? [{ text: recipe.source, style: 'recipeSource' }]
|
|
||||||
: []),
|
|
||||||
|
|
||||||
{
|
|
||||||
text: getRecipeMeta(recipe),
|
|
||||||
style: 'recipeMeta',
|
|
||||||
},
|
|
||||||
|
|
||||||
...createLinks(recipe, recipeList, indexMap),
|
|
||||||
...createIngredients(recipe),
|
|
||||||
]),
|
|
||||||
|
|
||||||
...(recipe.note?.trim()
|
...(recipe.note?.trim()
|
||||||
? [
|
? [{ text: 'Postup', style: 'sectionHeading' }, ...convertMarkdownToPdf(recipe.note)]
|
||||||
{
|
: fields?.note ?? []),
|
||||||
text: 'Postup',
|
...(fields?.remarks ?? []),
|
||||||
style: 'sectionHeading',
|
|
||||||
},
|
|
||||||
...convertMarkdownToPdf(recipe.note),
|
|
||||||
]
|
|
||||||
: []),
|
|
||||||
],
|
],
|
||||||
|
|
||||||
// Každý recept začíná na nové stránce, první hned za obsahem
|
// Každý recept začíná na nové stránce, první hned za obsahem
|
||||||
|
...(index > 0 || withToc ? { pageBreak: 'before' as const } : {}),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
...(index > 0 || withToc
|
/**
|
||||||
? { pageBreak: 'before' as const }
|
* Při rozvržení si zapamatuje, kde pdfmake vykreslil rámečky polí, a popisek,
|
||||||
: {}),
|
* jehož pole se na stránku nevešlo, přesune na další stránku za ním. pdfmake
|
||||||
});
|
* jinou cestu k pozicím uzlů nemá; pozice holého uzlu (ne uvnitř `unbreakable`
|
||||||
}
|
* nebo tabulky) odpovídá místu vykreslení.
|
||||||
|
*/
|
||||||
|
const trackFieldPositions = (positionMap: Map<string, NodeStartPosition>) =>
|
||||||
|
(node: Node, { getFollowingNodesOnPage }: NodeQueries): boolean => {
|
||||||
|
if (node.id?.startsWith(FIELD_ID_PREFIX)) {
|
||||||
|
positionMap.set(node.id.slice(FIELD_ID_PREFIX.length), node.startPosition);
|
||||||
|
} else if (node.id?.startsWith(LABEL_ID_PREFIX)) {
|
||||||
|
const fieldId = FIELD_ID_PREFIX + node.id.slice(LABEL_ID_PREFIX.length);
|
||||||
|
return !getFollowingNodesOnPage().some(item => item.id === fieldId);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
const loadPhotos = async (item: RecipeItem): Promise<MealPhoto[]> => {
|
const loadPhotos = async (item: RecipeItem): Promise<MealPhoto[]> => {
|
||||||
if (!item.photoCount) return [];
|
if (!item.photoCount) return [];
|
||||||
@@ -221,17 +266,21 @@ const loadPdfMake = async () => {
|
|||||||
const pdfMake = pdfMakeModule.default;
|
const pdfMake = pdfMakeModule.default;
|
||||||
const vfs = vfsModule.default;
|
const vfs = vfsModule.default;
|
||||||
pdfMake.addVirtualFileSystem(vfs);
|
pdfMake.addVirtualFileSystem(vfs);
|
||||||
return pdfMake;
|
return { pdfMake, vfs: vfs as Record<string, string> };
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stáhne recepty jako PDF — suroviny, hodnoty porce, postup a fotky jídla.
|
* Stáhne recepty jako PDF — suroviny, hodnoty porce, postup a fotky jídla.
|
||||||
* Víc receptů dostane titulní stránku s klikacím obsahem a každý recept
|
* Víc receptů dostane titulní stránku s klikacím obsahem a každý recept
|
||||||
* začíná na nové stránce.
|
* začíná na nové stránce.
|
||||||
|
*
|
||||||
|
* S `editable` dostane každý recept vyplnitelná pole PDF k doplnění a opravě
|
||||||
|
* (`createEditableFields`); neúplný recept (bez surovin nebo postupu) je
|
||||||
|
* dostane vždy.
|
||||||
*/
|
*/
|
||||||
export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> => {
|
export const exportRecipesPdf = async (itemList: RecipeItem[], editable = false): Promise<void> => {
|
||||||
const sortedList = [...itemList].sort((a, b) => a.recipe.name.localeCompare(b.recipe.name, 'cs'));
|
const sortedList = [...itemList].sort((a, b) => a.recipe.name.localeCompare(b.recipe.name, 'cs'));
|
||||||
const [pdfMake, photoLists, recipeResponse] = await Promise.all([
|
const [{ pdfMake, vfs }, photoLists, recipeResponse] = await Promise.all([
|
||||||
loadPdfMake(),
|
loadPdfMake(),
|
||||||
Promise.all(sortedList.map(loadPhotos)),
|
Promise.all(sortedList.map(loadPhotos)),
|
||||||
getMealTemplates(),
|
getMealTemplates(),
|
||||||
@@ -240,6 +289,9 @@ export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> =>
|
|||||||
const indexMap = new Map(sortedList.map((item, index) => [item.recipe.id, index]));
|
const indexMap = new Map(sortedList.map((item, index) => [item.recipe.id, index]));
|
||||||
const withToc = sortedList.length > 1;
|
const withToc = sortedList.length > 1;
|
||||||
const title = withToc ? 'Recepty' : sortedList[0]?.recipe.name ?? 'Recept';
|
const title = withToc ? 'Recepty' : sortedList[0]?.recipe.name ?? 'Recept';
|
||||||
|
const fileName = withToc ? 'recepty.pdf' : toFileName(title);
|
||||||
|
const fieldList: PdfFormField[] = [];
|
||||||
|
const positionMap = new Map<string, NodeStartPosition>();
|
||||||
|
|
||||||
const cover: Content[] = withToc ? [
|
const cover: Content[] = withToc ? [
|
||||||
{ text: 'Recepty', style: 'coverTitle' },
|
{ text: 'Recepty', style: 'coverTitle' },
|
||||||
@@ -253,15 +305,16 @@ export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> =>
|
|||||||
},
|
},
|
||||||
] : [];
|
] : [];
|
||||||
|
|
||||||
|
// Sestavením obsahu se naplní i fieldList, proto musí proběhnout před definicí
|
||||||
|
const recipeContent = sortedList.map((item, index) =>
|
||||||
|
createRecipe(item.recipe, photoLists[index], { index, withToc, recipeList, indexMap, fieldList, editable }));
|
||||||
|
|
||||||
const definition: TDocumentDefinitions = {
|
const definition: TDocumentDefinitions = {
|
||||||
info: { title },
|
info: { title },
|
||||||
pageSize: 'A4',
|
pageSize: 'A4',
|
||||||
pageMargins: [40, 40, 40, 50],
|
pageMargins: [40, 40, 40, 50],
|
||||||
content: [
|
content: [...cover, ...recipeContent],
|
||||||
...cover,
|
pageBreakBefore: fieldList.length ? trackFieldPositions(positionMap) : undefined,
|
||||||
...sortedList.map((item, index) =>
|
|
||||||
createRecipe(item.recipe, photoLists[index], { index, withToc, recipeList, indexMap })),
|
|
||||||
],
|
|
||||||
footer: (currentPage, pageCount) => ({
|
footer: (currentPage, pageCount) => ({
|
||||||
text: `${currentPage} / ${pageCount}`,
|
text: `${currentPage} / ${pageCount}`,
|
||||||
alignment: 'center',
|
alignment: 'center',
|
||||||
@@ -282,8 +335,21 @@ export const exportRecipesPdf = async (itemList: RecipeItem[]): Promise<void> =>
|
|||||||
noteSubheading: { fontSize: 10.5, bold: true, margin: [0, 6, 0, 3] },
|
noteSubheading: { fontSize: 10.5, bold: true, margin: [0, 6, 0, 3] },
|
||||||
noteParagraph: { margin: [0, 0, 0, 6] },
|
noteParagraph: { margin: [0, 0, 0, 6] },
|
||||||
noteList: { margin: [0, 0, 0, 6] },
|
noteList: { margin: [0, 0, 0, 6] },
|
||||||
|
fieldLabel: { fontSize: 9, bold: true, color: MUTED_COLOR, margin: [0, 6, 0, 0] },
|
||||||
|
fieldHint: { fontSize: 9, bold: false, italics: true, color: MUTED_COLOR },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
await pdfMake.createPdf(definition).download(withToc ? 'recepty.pdf' : toFileName(title));
|
const document = pdfMake.createPdf(definition);
|
||||||
|
if (!fieldList.length) {
|
||||||
|
await document.download(fileName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { addFormFields, downloadPdf } = await import("./pdfFormFields");
|
||||||
|
const pdfBytes = new Uint8Array(await document.getBuffer());
|
||||||
|
const placedList = fieldList.flatMap(field => {
|
||||||
|
const position = positionMap.get(field.name);
|
||||||
|
return position ? [{ ...field, position }] : [];
|
||||||
|
});
|
||||||
|
downloadPdf(await addFormFields(pdfBytes, placedList, vfs['Roboto-Regular.ttf']), fileName);
|
||||||
};
|
};
|
||||||
@@ -6,11 +6,11 @@ import { exportRecipesPdf } from "./recipePdf";
|
|||||||
export const useRecipeExport = () => {
|
export const useRecipeExport = () => {
|
||||||
const [exporting, setExporting] = useState(false);
|
const [exporting, setExporting] = useState(false);
|
||||||
|
|
||||||
const exportRecipes = async (itemList: Parameters<typeof exportRecipesPdf>[0]) => {
|
const exportRecipes = async (itemList: Parameters<typeof exportRecipesPdf>[0], editable = false) => {
|
||||||
if (exporting || !itemList.length) return;
|
if (exporting || !itemList.length) return;
|
||||||
setExporting(true);
|
setExporting(true);
|
||||||
try {
|
try {
|
||||||
await exportRecipesPdf(itemList);
|
await exportRecipesPdf(itemList, editable);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Export receptů do PDF selhal', error);
|
console.error('Export receptů do PDF selhal', error);
|
||||||
toast.error('PDF se nepodařilo vytvořit.');
|
toast.error('PDF se nepodařilo vytvořit.');
|
||||||
|
|||||||
+37
-1
@@ -479,6 +479,27 @@
|
|||||||
"@parcel/watcher-win32-arm64" "2.6.0"
|
"@parcel/watcher-win32-arm64" "2.6.0"
|
||||||
"@parcel/watcher-win32-x64" "2.6.0"
|
"@parcel/watcher-win32-x64" "2.6.0"
|
||||||
|
|
||||||
|
"@pdf-lib/fontkit@1.1.1":
|
||||||
|
version "1.1.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/@pdf-lib/fontkit/-/fontkit-1.1.1.tgz#f18473892b65e3253eb73f4569785abd2c03b1e0"
|
||||||
|
integrity sha512-KjMd7grNapIWS/Dm0gvfHEilSyAmeLvrEGVcqLGi0VYebuqqzTbgF29efCx7tvx+IEbG3zQciRSWl3GkUSvjZg==
|
||||||
|
dependencies:
|
||||||
|
pako "^1.0.6"
|
||||||
|
|
||||||
|
"@pdf-lib/standard-fonts@^1.0.0":
|
||||||
|
version "1.0.0"
|
||||||
|
resolved "https://registry.yarnpkg.com/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz#8ba691c4421f71662ed07c9a0294b44528af2d7f"
|
||||||
|
integrity sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==
|
||||||
|
dependencies:
|
||||||
|
pako "^1.0.6"
|
||||||
|
|
||||||
|
"@pdf-lib/upng@^1.0.1":
|
||||||
|
version "1.0.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/@pdf-lib/upng/-/upng-1.0.1.tgz#7dc9c636271aca007a9df4deaf2dd7e7960280cb"
|
||||||
|
integrity sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==
|
||||||
|
dependencies:
|
||||||
|
pako "^1.0.10"
|
||||||
|
|
||||||
"@popperjs/core@^2.11.8":
|
"@popperjs/core@^2.11.8":
|
||||||
version "2.11.8"
|
version "2.11.8"
|
||||||
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.8.tgz#6b79032e760a0899cd4204710beede972a3a185f"
|
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.8.tgz#6b79032e760a0899cd4204710beede972a3a185f"
|
||||||
@@ -1751,7 +1772,7 @@ pako@^0.2.5:
|
|||||||
resolved "https://registry.yarnpkg.com/pako/-/pako-0.2.9.tgz#f3f7522f4ef782348da8161bad9ecfd51bf83a75"
|
resolved "https://registry.yarnpkg.com/pako/-/pako-0.2.9.tgz#f3f7522f4ef782348da8161bad9ecfd51bf83a75"
|
||||||
integrity sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==
|
integrity sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==
|
||||||
|
|
||||||
pako@~1.0.5:
|
pako@^1.0.10, pako@^1.0.11, pako@^1.0.6, pako@~1.0.5:
|
||||||
version "1.0.11"
|
version "1.0.11"
|
||||||
resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf"
|
resolved "https://registry.yarnpkg.com/pako/-/pako-1.0.11.tgz#6c9599d340d54dfd3946380252a35705a6b992bf"
|
||||||
integrity sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==
|
integrity sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==
|
||||||
@@ -1769,6 +1790,16 @@ parse-entities@^4.0.0:
|
|||||||
is-decimal "^2.0.0"
|
is-decimal "^2.0.0"
|
||||||
is-hexadecimal "^2.0.0"
|
is-hexadecimal "^2.0.0"
|
||||||
|
|
||||||
|
pdf-lib@1.17.1:
|
||||||
|
version "1.17.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/pdf-lib/-/pdf-lib-1.17.1.tgz#9e7dd21261a0c1fb17992580885b39e7d08f451f"
|
||||||
|
integrity sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==
|
||||||
|
dependencies:
|
||||||
|
"@pdf-lib/standard-fonts" "^1.0.0"
|
||||||
|
"@pdf-lib/upng" "^1.0.1"
|
||||||
|
pako "^1.0.11"
|
||||||
|
tslib "^1.11.1"
|
||||||
|
|
||||||
pdfkit@^0.19.1:
|
pdfkit@^0.19.1:
|
||||||
version "0.19.1"
|
version "0.19.1"
|
||||||
resolved "https://registry.yarnpkg.com/pdfkit/-/pdfkit-0.19.1.tgz#633d5f031ce6f1ba6ce141325c6cf87fa6acb0a2"
|
resolved "https://registry.yarnpkg.com/pdfkit/-/pdfkit-0.19.1.tgz#633d5f031ce6f1ba6ce141325c6cf87fa6acb0a2"
|
||||||
@@ -2179,6 +2210,11 @@ tsconfck@^3.0.3:
|
|||||||
resolved "https://registry.yarnpkg.com/tsconfck/-/tsconfck-3.1.6.tgz#da1f0b10d82237ac23422374b3fce1edb23c3ead"
|
resolved "https://registry.yarnpkg.com/tsconfck/-/tsconfck-3.1.6.tgz#da1f0b10d82237ac23422374b3fce1edb23c3ead"
|
||||||
integrity sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==
|
integrity sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==
|
||||||
|
|
||||||
|
tslib@^1.11.1:
|
||||||
|
version "1.14.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"
|
||||||
|
integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==
|
||||||
|
|
||||||
tslib@^2.0.0, tslib@^2.8.0:
|
tslib@^2.0.0, tslib@^2.8.0:
|
||||||
version "2.8.1"
|
version "2.8.1"
|
||||||
resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f"
|
resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.8.1.tgz#612efe4ed235d567e8aba5f2a5fab70280ade83f"
|
||||||
|
|||||||
@@ -53,9 +53,11 @@ type StoredRecipe = StoredMealTemplate & { ingredients: RecipeIngredient[] };
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Šablony hotových jídel zanikly — opakovaně jedené jídlo se nabízí z historie.
|
* Šablony hotových jídel zanikly — opakovaně jedené jídlo se nabízí z historie.
|
||||||
* Poznají se podle toho, že nemají suroviny; recept bez surovin uložit nejde.
|
* Poznají se podle toho, že pole surovin vůbec nemají. Recept ho má vždy,
|
||||||
|
* u neúplného receptu prázdné.
|
||||||
*/
|
*/
|
||||||
const isRecipe = (stored: StoredMealTemplate): stored is StoredRecipe => !!stored.ingredients?.length;
|
const isRecipe = (stored: StoredMealTemplate): stored is StoredRecipe =>
|
||||||
|
Array.isArray(stored.ingredients) && stored.kind !== 'HOTOVE';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Odstraní z receptu pole, která patřila jen šablonám hotových jídel, a zaniklý chod.
|
* Odstraní z receptu pole, která patřila jen šablonám hotových jídel, a zaniklý chod.
|
||||||
@@ -310,13 +312,15 @@ export const saveMealTemplate = async (login: string, input: unknown): Promise<M
|
|||||||
if (!name) {
|
if (!name) {
|
||||||
throw new BadRequestError("Nebyl předán název receptu");
|
throw new BadRequestError("Nebyl předán název receptu");
|
||||||
}
|
}
|
||||||
if (!Array.isArray(value.ingredients) || !value.ingredients.length) {
|
// Recept jde uložit i neúplný, bez surovin a postupu, a doplnit později
|
||||||
throw new BadRequestError("Recept musí mít alespoň jednu surovinu");
|
const rawIngredients = value.ingredients ?? [];
|
||||||
|
if (!Array.isArray(rawIngredients)) {
|
||||||
|
throw new BadRequestError("Suroviny receptu musí být seznam");
|
||||||
}
|
}
|
||||||
if (value.ingredients.length > MAX_INGREDIENTS) {
|
if (rawIngredients.length > MAX_INGREDIENTS) {
|
||||||
throw new BadRequestError(`Recept může mít nejvýše ${MAX_INGREDIENTS} surovin`);
|
throw new BadRequestError(`Recept může mít nejvýše ${MAX_INGREDIENTS} surovin`);
|
||||||
}
|
}
|
||||||
const ingredients = value.ingredients.map(normalizeIngredient);
|
const ingredients = rawIngredients.map(normalizeIngredient);
|
||||||
const servings = normalizeNumber(value.servings, 'servings');
|
const servings = normalizeNumber(value.servings, 'servings');
|
||||||
const cookedWeight = normalizeNumber(value.cookedWeight, 'cookedWeight') || undefined;
|
const cookedWeight = normalizeNumber(value.cookedWeight, 'cookedWeight') || undefined;
|
||||||
const prepMinutes = normalizeNumber(value.prepMinutes, 'prepMinutes') || undefined;
|
const prepMinutes = normalizeNumber(value.prepMinutes, 'prepMinutes') || undefined;
|
||||||
|
|||||||
@@ -184,9 +184,16 @@ describe('recepty', () => {
|
|||||||
expect((await getDay(LOGIN, DATE)).entries).toHaveLength(1);
|
expect((await getDay(LOGIN, DATE)).entries).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('odmítne recept bez názvu, bez surovin a neexistující id', async () => {
|
it('uloží neúplný recept bez surovin a postupu', async () => {
|
||||||
|
const [template] = await saveMealTemplate(LOGIN, { name: 'Babiččiny buchty', prepMinutes: 90 });
|
||||||
|
|
||||||
|
expect(template).toMatchObject({ name: 'Babiččiny buchty', ingredients: [], prepMinutes: 90 });
|
||||||
|
expect(template).not.toHaveProperty('calories');
|
||||||
|
expect(await getMealTemplates(LOGIN)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('odmítne recept bez názvu a neexistující id', async () => {
|
||||||
await expect(saveMealTemplate(LOGIN, { ...rizoto, name: ' ' })).rejects.toThrow(/název receptu/);
|
await expect(saveMealTemplate(LOGIN, { ...rizoto, name: ' ' })).rejects.toThrow(/název receptu/);
|
||||||
await expect(saveMealTemplate(LOGIN, { ...rizoto, ingredients: [] })).rejects.toThrow(/surovinu/);
|
|
||||||
await expect(applyMealTemplate(LOGIN, 'neexistuje', DATE)).rejects.toThrow(/nebyl nalezen/);
|
await expect(applyMealTemplate(LOGIN, 'neexistuje', DATE)).rejects.toThrow(/nebyl nalezen/);
|
||||||
await expect(deleteMealTemplate(LOGIN, 'neexistuje')).rejects.toThrow(/nebyl nalezen/);
|
await expect(deleteMealTemplate(LOGIN, 'neexistuje')).rejects.toThrow(/nebyl nalezen/);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1409,7 +1409,8 @@ MealTemplate:
|
|||||||
Recept — vařené jídlo se surovinami a postupem. Hodnoty jedné porce
|
Recept — vařené jídlo se surovinami a postupem. Hodnoty jedné porce
|
||||||
(gramáž, energie, cena) dopočte server ze surovin při uložení a použitím
|
(gramáž, energie, cena) dopočte server ze surovin při uložení a použitím
|
||||||
receptu se z nich založí běžný záznam jídla. Opakovaně jedená hotová jídla
|
receptu se z nich založí běžný záznam jídla. Opakovaně jedená hotová jídla
|
||||||
šablony nemají, nabízejí se z historie (MealSuggestion).
|
šablony nemají, nabízejí se z historie (MealSuggestion). Recept může být
|
||||||
|
neúplný — bez surovin i postupu — a doplnit se později.
|
||||||
type: object
|
type: object
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
required:
|
required:
|
||||||
@@ -1449,7 +1450,7 @@ MealTemplate:
|
|||||||
description: Postup přípravy
|
description: Postup přípravy
|
||||||
type: string
|
type: string
|
||||||
ingredients:
|
ingredients:
|
||||||
description: Suroviny receptu
|
description: Suroviny receptu; u neúplného receptu prázdné
|
||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
$ref: "#/RecipeIngredient"
|
$ref: "#/RecipeIngredient"
|
||||||
@@ -1491,7 +1492,6 @@ MealTemplateInput:
|
|||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
required:
|
required:
|
||||||
- name
|
- name
|
||||||
- ingredients
|
|
||||||
properties:
|
properties:
|
||||||
id:
|
id:
|
||||||
description: Identifikátor upravovaného receptu. Bez něj se založí nový.
|
description: Identifikátor upravovaného receptu. Bez něj se založí nový.
|
||||||
@@ -1508,6 +1508,7 @@ MealTemplateInput:
|
|||||||
note:
|
note:
|
||||||
type: string
|
type: string
|
||||||
ingredients:
|
ingredients:
|
||||||
|
description: Suroviny; bez nich se uloží neúplný recept
|
||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
$ref: "#/RecipeIngredient"
|
$ref: "#/RecipeIngredient"
|
||||||
|
|||||||
Reference in new issue
Block a user