feat: import jen některých dnů
feat: násobení jídel/cviků feat: refaktor napojování šablon
This commit is contained in:
1 parent
c3990d80f8
commit
8dac67bdd1
37 files changed
+2314
-481
No files matched your search
+127
-1
@@ -702,13 +702,19 @@ body {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.workout-item-weight {
|
||||
width: 100px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
flex-wrap: wrap;
|
||||
|
||||
.workout-item-sets,
|
||||
.workout-item-quantity,
|
||||
.workout-item-unit,
|
||||
.workout-item-rate {
|
||||
.workout-item-rate,
|
||||
.workout-item-weight {
|
||||
width: auto;
|
||||
flex: 1;
|
||||
}
|
||||
@@ -771,3 +777,123 @@ body {
|
||||
font-size: 0.85rem;
|
||||
color: var(--ft-text-secondary);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// NÁSOBEK POLOŽKY DNE
|
||||
// ============================================
|
||||
|
||||
// Výchozí ×1 je nenápadné, změněný násobek musí být vidět na první pohled
|
||||
.multiplier-button {
|
||||
flex: 0 0 auto;
|
||||
background: transparent;
|
||||
border: 1px dashed var(--ft-border);
|
||||
border-radius: 999px;
|
||||
padding: 0 9px;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.6;
|
||||
color: var(--ft-text-muted);
|
||||
transition: var(--ft-transition);
|
||||
|
||||
&:hover {
|
||||
color: var(--ft-text);
|
||||
border-color: var(--ft-text-muted);
|
||||
}
|
||||
|
||||
&.active {
|
||||
border-style: solid;
|
||||
border-color: var(--ft-primary);
|
||||
background: var(--ft-primary-light);
|
||||
color: var(--ft-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.multiplier-popover {
|
||||
.multiplier-presets {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.multiplier-custom {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.multiplier-hint {
|
||||
margin-top: 6px;
|
||||
font-size: 0.78rem;
|
||||
color: var(--ft-text-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// ŠABLONY JÍDEL — návrhy a skupiny
|
||||
// ============================================
|
||||
|
||||
// Návrhy šablon pod názvem jídla ve formuláři
|
||||
.template-suggestions {
|
||||
margin-top: 6px;
|
||||
border: 1px solid var(--ft-border-light);
|
||||
border-radius: var(--ft-radius);
|
||||
overflow: hidden;
|
||||
|
||||
.template-suggestions-title {
|
||||
padding: 4px 10px;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--ft-text-muted);
|
||||
background: var(--ft-bg-hover);
|
||||
}
|
||||
|
||||
.template-suggestion {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 6px 10px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-top: 1px solid var(--ft-border-light);
|
||||
text-align: left;
|
||||
font-size: 0.87rem;
|
||||
color: var(--ft-text);
|
||||
transition: var(--ft-transition);
|
||||
|
||||
&:hover {
|
||||
background: var(--ft-bg-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.template-suggestion-icon {
|
||||
color: var(--ft-primary);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.template-suggestion-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.template-suggestion-detail {
|
||||
margin-left: auto;
|
||||
color: var(--ft-text-muted);
|
||||
font-size: 0.8rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.apply-template-group-title {
|
||||
margin: 16px 0 4px;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--ft-text-muted);
|
||||
|
||||
&:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { MealTemplate } from "../../types";
|
||||
|
||||
const TOKEN_KEY = "token";
|
||||
|
||||
/** Uloží token do local storage prohlížeče. */
|
||||
@@ -253,3 +255,103 @@ export const formatQuantityWithSets = (quantity: number, unitShort: string, sets
|
||||
/** Vrátí celkové množství aktivity — počet sérií krát množství v jedné. */
|
||||
export const getTotalQuantity = (quantity?: number, sets?: number): number | undefined =>
|
||||
quantity == null ? undefined : quantity * Math.max(sets ?? 1, 1);
|
||||
|
||||
/**
|
||||
* Vrátí kalorie záznamu po započtení násobku porce.
|
||||
* Musí dávat stejné výsledky jako `applyMultiplier` na serveru.
|
||||
*/
|
||||
export const applyMultiplier = (calories?: number, multiplier?: number): number | undefined =>
|
||||
calories == null ? undefined : Math.round(calories * (multiplier ?? 1));
|
||||
|
||||
/** Naformátuje násobek, např. 1.5 → "×1,5". */
|
||||
export const formatMultiplier = (multiplier?: number): string =>
|
||||
`×${(multiplier ?? 1).toLocaleString('cs-CZ', { maximumFractionDigits: 2 })}`;
|
||||
|
||||
/** Převede násobek zadaný uživatelem (i s desetinnou čárkou) na číslo; nekladný vstup odmítne. */
|
||||
export const parseMultiplierInput = (value: string): number | undefined => {
|
||||
const trimmed = value.trim().replace(',', '.');
|
||||
if (!trimmed.length) return undefined;
|
||||
const parsed = Number(trimmed);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? Math.round(parsed * 100) / 100 : undefined;
|
||||
};
|
||||
|
||||
/** Převede násobek na text pro editační pole; výchozí 1 nechá prázdné. */
|
||||
export const formatMultiplierInput = (multiplier?: number): string =>
|
||||
multiplier == null || multiplier === 1 ? '' : String(multiplier).replace('.', ',');
|
||||
|
||||
/** Naformátuje dodatečnou zátěž z gramů, např. 12500 → "+12,5 kg". */
|
||||
export const formatExtraWeight = (grams?: number): string =>
|
||||
grams ? `+${(grams / 1000).toLocaleString('cs-CZ', { maximumFractionDigits: 2 })} kg` : '';
|
||||
|
||||
/** Převede gramy na kilogramy pro editační pole bez zbytečných desetinných míst. */
|
||||
export const formatKgInput = (grams?: number): string =>
|
||||
grams ? String(grams / 1000).replace('.', ',') : '';
|
||||
|
||||
/** Surovina receptu tak, jak ji zná výpočet — hodnoty jsou už čísla. */
|
||||
type RecipeIngredientValues = {
|
||||
weight?: number,
|
||||
caloriesPer100g?: number,
|
||||
calories?: number,
|
||||
price?: number,
|
||||
};
|
||||
|
||||
/** Energie suroviny — z gramáže a energie na 100 g, jinak ručně zadaná. */
|
||||
export const getIngredientCalories = (ingredient: RecipeIngredientValues): number | undefined =>
|
||||
ingredient.weight != null && ingredient.caloriesPer100g
|
||||
? Math.round(ingredient.weight / 100 * ingredient.caloriesPer100g)
|
||||
: ingredient.calories;
|
||||
|
||||
/** Sečte vyplněné hodnoty; když není vyplněná žádná, vrátí undefined. */
|
||||
const sumDefined = (valueList: (number | undefined)[]): number | undefined => {
|
||||
const definedList = valueList.filter(value => value != null);
|
||||
return definedList.length ? definedList.reduce((sum, value) => sum + value, 0) : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Dopočte ze surovin hodnoty hotového jídla a jedné porce.
|
||||
* Musí dávat stejné výsledky jako `deriveRecipe` na serveru.
|
||||
*
|
||||
* @param ingredients suroviny receptu
|
||||
* @param servings počet porcí, nevyplněný znamená jednu
|
||||
* @param cookedWeight hmotnost hotového jídla v gramech, bez ní součet surovin
|
||||
*/
|
||||
export const deriveRecipe = (
|
||||
ingredients: RecipeIngredientValues[],
|
||||
servings?: number,
|
||||
cookedWeight?: number,
|
||||
) => {
|
||||
const portions = Math.max(servings ?? 1, 1);
|
||||
const totalCalories = sumDefined(ingredients.map(getIngredientCalories));
|
||||
const totalWeight = cookedWeight || sumDefined(ingredients.map(ingredient => ingredient.weight)) || undefined;
|
||||
const totalPrice = sumDefined(ingredients.map(ingredient => ingredient.price));
|
||||
return {
|
||||
totalCalories,
|
||||
totalWeight,
|
||||
totalPrice,
|
||||
weight: totalWeight != null ? Math.round(totalWeight / portions) : undefined,
|
||||
calories: totalCalories != null ? Math.round(totalCalories / portions) : undefined,
|
||||
caloriesPer100g: totalCalories != null && totalWeight
|
||||
? Math.round(totalCalories / totalWeight * 100)
|
||||
: undefined,
|
||||
price: totalPrice != null ? Math.round(totalPrice / portions) : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
/** Znormalizuje text pro hledání — bez diakritiky a malými písmeny. */
|
||||
export const normalizeSearch = (value: string): string =>
|
||||
value.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim();
|
||||
|
||||
/**
|
||||
* Popíše šablonu jídla jednou řádkou — zdroj, gramáž porce, kalorie a cena,
|
||||
* co je vyplněné. U receptu jsou to hodnoty jedné porce, které dopočítal server.
|
||||
*/
|
||||
export const describeMealTemplate = (template: MealTemplate): string => {
|
||||
const derived = deriveAmounts(template.price, template.pricePer100g, template.weight, template.caloriesPer100g);
|
||||
const calories = derived.calories ?? template.calories;
|
||||
return [
|
||||
template.source,
|
||||
derived.weight != null ? formatWeight(derived.weight) : undefined,
|
||||
calories != null ? formatCalories(calories) : undefined,
|
||||
template.price != null ? formatPrice(template.price) : undefined,
|
||||
].filter(item => !!item).join(' · ');
|
||||
};
|
||||
@@ -1,17 +1,19 @@
|
||||
import { ActivityEntry } from "../../../types";
|
||||
import { ACTIVITY_UNIT_SHORT } from "../enums";
|
||||
import { formatCalories, formatQuantityWithSets } from "../Utils";
|
||||
import { applyMultiplier, formatCalories, formatExtraWeight, formatQuantityWithSets } from "../Utils";
|
||||
import RowActions from "./RowActions";
|
||||
import MultiplierControl from "./MultiplierControl";
|
||||
|
||||
type Props = {
|
||||
entry: ActivityEntry,
|
||||
onEdit: () => void,
|
||||
onDelete: () => void,
|
||||
onSaveTemplate: () => void,
|
||||
onMultiplierChange: (multiplier: number) => void,
|
||||
};
|
||||
|
||||
/** Jeden řádek seznamu pohybových aktivit v přehledu dne. */
|
||||
const ActivityRow = ({ entry, onEdit, onDelete, onSaveTemplate }: Readonly<Props>) => (
|
||||
const ActivityRow = ({ entry, onEdit, onDelete, onSaveTemplate, onMultiplierChange }: Readonly<Props>) => (
|
||||
<div className="meal-row">
|
||||
<div className="meal-main">
|
||||
<div className="meal-name">{entry.name}</div>
|
||||
@@ -19,11 +21,25 @@ const ActivityRow = ({ entry, onEdit, onDelete, onSaveTemplate }: Readonly<Props
|
||||
<span className="tag">
|
||||
{formatQuantityWithSets(entry.quantity, ACTIVITY_UNIT_SHORT[entry.unit], entry.sets)}
|
||||
</span>
|
||||
{!!entry.extraWeightGrams && (
|
||||
<span className="tag" title="Dodatečná zátěž">{formatExtraWeight(entry.extraWeightGrams)}</span>
|
||||
)}
|
||||
{entry.templateId && <span className="tag tag-import">ze šablony</span>}
|
||||
</div>
|
||||
{entry.note && <div className="meal-note">{entry.note}</div>}
|
||||
</div>
|
||||
<div className="meal-price burn">{formatCalories(entry.calories)}</div>
|
||||
<MultiplierControl
|
||||
multiplier={entry.multiplier}
|
||||
calories={entry.calories}
|
||||
onChange={onMultiplierChange}
|
||||
label="aktivity"
|
||||
/>
|
||||
<div
|
||||
className="meal-price burn"
|
||||
title={entry.multiplier ? `${formatCalories(entry.calories)} za jedno provedení` : undefined}
|
||||
>
|
||||
{formatCalories(applyMultiplier(entry.calories, entry.multiplier))}
|
||||
</div>
|
||||
<RowActions onEdit={onEdit} onDelete={onDelete} onSaveTemplate={onSaveTemplate} label="aktivitu" />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Form } from "react-bootstrap";
|
||||
import { ImportMode, ImportResult, MealEntry } from "../../../types";
|
||||
import { MEAL_TYPE_ICONS } from "../enums";
|
||||
import { formatPrice, getDayOfWeek, getHumanDate } from "../Utils";
|
||||
|
||||
type Props = {
|
||||
preview: ImportResult,
|
||||
/** Klíče (`importKey`) zaškrtnutých řádků. */
|
||||
selected: Set<string>,
|
||||
onToggle: (key: string) => void,
|
||||
onToggleDay: (date: string, checked: boolean) => void,
|
||||
/** Rozhodne, jestli jde o záznam, který režim NAHRADIT odebere. */
|
||||
isReplaced: (entry: MealEntry) => boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* Náhled importu rozdělený po dnech.
|
||||
*
|
||||
* U každého dne je vidět, co v něm už je — ručně zadaná jídla i dřívější import —
|
||||
* aby šlo posoudit, jestli se něco nezdvojí, a řádek odškrtnout.
|
||||
*/
|
||||
const ImportPreview = ({ preview, selected, onToggle, onToggleDay, isReplaced }: Readonly<Props>) => {
|
||||
const dateList = Array.from(new Set(preview.entries.map(entry => entry.date))).sort();
|
||||
|
||||
return (
|
||||
<div className="import-preview">
|
||||
{dateList.map(date => {
|
||||
const entryList = preview.entries.filter(entry => entry.date === date);
|
||||
const existingList = preview.existing.filter(entry => entry.date === date);
|
||||
const checkedCount = entryList.filter(entry => selected.has(entry.importKey!)).length;
|
||||
return (
|
||||
<div className="import-preview-day" key={date}>
|
||||
<Form.Check
|
||||
className="import-preview-day-title"
|
||||
id={`import-day-${date}`}
|
||||
checked={checkedCount === entryList.length}
|
||||
label={`${getHumanDate(date)} · ${getDayOfWeek(date)}`}
|
||||
onChange={event => onToggleDay(date, event.target.checked)}
|
||||
/>
|
||||
{existingList.map(entry => {
|
||||
// Nahrazuje se jen ve dnech, do kterých se něco zakládá
|
||||
const replaced = checkedCount > 0 && isReplaced(entry);
|
||||
return (
|
||||
<div key={entry.id} className={`import-preview-existing ${replaced ? 'replaced' : ''}`}>
|
||||
<span>{MEAL_TYPE_ICONS[entry.mealType]}</span>
|
||||
<span className="import-preview-name">
|
||||
{entry.name}
|
||||
<span className="import-preview-note">
|
||||
{replaced
|
||||
? ' · bude nahrazeno'
|
||||
: ` · už máte${entry.importSource ? ' z importu' : ''}`}
|
||||
</span>
|
||||
</span>
|
||||
<span className="import-preview-price">{formatPrice(entry.price)}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{entryList.map(entry => (
|
||||
<Form.Check
|
||||
key={entry.importKey}
|
||||
id={`import-row-${entry.importKey}`}
|
||||
className="import-preview-row"
|
||||
checked={selected.has(entry.importKey!)}
|
||||
onChange={() => onToggle(entry.importKey!)}
|
||||
label={
|
||||
<>
|
||||
<span className="import-preview-name">
|
||||
{entry.name}
|
||||
{entry.source && <span className="text-body-secondary"> · {entry.source}</span>}
|
||||
</span>
|
||||
<span className="import-preview-price">{formatPrice(entry.price)}</span>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{preview.mode === ImportMode.PRIDAT && preview.skipped > 0 && (
|
||||
<div className="import-preview-skipped">
|
||||
{preview.skipped} řádků se přeskočí, protože už je máte z dřívějšího importu.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ImportPreview;
|
||||
@@ -1,30 +1,48 @@
|
||||
import { MealEntry } from "../../../types";
|
||||
import { formatCalories, formatPrice, formatWeight } from "../Utils";
|
||||
import { applyMultiplier, formatCalories, formatPrice, formatWeight } from "../Utils";
|
||||
import RowActions from "./RowActions";
|
||||
import MultiplierControl from "./MultiplierControl";
|
||||
|
||||
type Props = {
|
||||
entry: MealEntry,
|
||||
onEdit: () => void,
|
||||
onDelete: () => void,
|
||||
onSaveTemplate: () => void,
|
||||
onMultiplierChange: (multiplier: number) => void,
|
||||
};
|
||||
|
||||
/** Jeden řádek seznamu jídel v přehledu dne. */
|
||||
const MealRow = ({ entry, onEdit, onDelete, onSaveTemplate }: Readonly<Props>) => (
|
||||
<div className="meal-row">
|
||||
<div className="meal-main">
|
||||
<div className="meal-name">{entry.name}</div>
|
||||
<div className="meal-meta">
|
||||
{entry.source && <span className="tag">{entry.source}</span>}
|
||||
{entry.importSource && <span className="tag tag-import">z Luncheru</span>}
|
||||
{entry.weight != null && <span className="tag">{formatWeight(entry.weight)}</span>}
|
||||
{entry.calories != null && <span className="tag">{formatCalories(entry.calories)}</span>}
|
||||
const MealRow = ({ entry, onEdit, onDelete, onSaveTemplate, onMultiplierChange }: Readonly<Props>) => {
|
||||
const calories = applyMultiplier(entry.calories, entry.multiplier);
|
||||
return (
|
||||
<div className="meal-row">
|
||||
<div className="meal-main">
|
||||
<div className="meal-name">{entry.name}</div>
|
||||
<div className="meal-meta">
|
||||
{entry.source && <span className="tag">{entry.source}</span>}
|
||||
{entry.importSource && <span className="tag tag-import">z Luncheru</span>}
|
||||
{entry.weight != null && <span className="tag">{formatWeight(entry.weight)}</span>}
|
||||
{calories != null && (
|
||||
<span
|
||||
className="tag"
|
||||
title={entry.multiplier ? `${formatCalories(entry.calories)} za porci` : undefined}
|
||||
>
|
||||
{formatCalories(calories)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{entry.note && <div className="meal-note">{entry.note}</div>}
|
||||
</div>
|
||||
{entry.note && <div className="meal-note">{entry.note}</div>}
|
||||
<MultiplierControl
|
||||
multiplier={entry.multiplier}
|
||||
calories={entry.calories}
|
||||
onChange={onMultiplierChange}
|
||||
label="jídla"
|
||||
/>
|
||||
<div className="meal-price">{formatPrice(entry.price)}</div>
|
||||
<RowActions onEdit={onEdit} onDelete={onDelete} onSaveTemplate={onSaveTemplate} label="jídlo" />
|
||||
</div>
|
||||
<div className="meal-price">{formatPrice(entry.price)}</div>
|
||||
<RowActions onEdit={onEdit} onDelete={onDelete} onSaveTemplate={onSaveTemplate} label="jídlo" />
|
||||
</div>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
||||
export default MealRow;
|
||||
@@ -0,0 +1,97 @@
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faPenToSquare, faTrash } from "@fortawesome/free-solid-svg-icons";
|
||||
import { MealTemplate, MealTemplateKind } from "../../../types";
|
||||
import { MEAL_TYPE_ICONS, MEAL_TYPE_NAMES } from "../enums";
|
||||
import {
|
||||
deriveAmounts, deriveRecipe, formatCalories, formatPrice, formatWeight, getIngredientCalories,
|
||||
} from "../Utils";
|
||||
|
||||
type Props = {
|
||||
template: MealTemplate,
|
||||
busy: boolean,
|
||||
onEdit: () => void,
|
||||
onDelete: () => void,
|
||||
};
|
||||
|
||||
/**
|
||||
* Karta šablony jídla na stránce Šablony.
|
||||
*
|
||||
* U receptu ukazuje suroviny, hodnoty celého hrnce i jedné porce a postup;
|
||||
* u hotového jídla jen výsledné hodnoty, které se do dne zakládají.
|
||||
*/
|
||||
const MealTemplateCard = ({ template, busy, onEdit, onDelete }: Readonly<Props>) => {
|
||||
const isRecipe = template.kind === MealTemplateKind.RECEPT;
|
||||
const derived = deriveAmounts(template.price, template.pricePer100g, template.weight, template.caloriesPer100g);
|
||||
const calories = derived.calories ?? template.calories;
|
||||
const recipe = isRecipe
|
||||
? deriveRecipe(template.ingredients ?? [], template.servings, template.cookedWeight)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div className="card-panel template-card">
|
||||
<div className="template-head">
|
||||
<div className="template-title">
|
||||
{template.name}
|
||||
{template.mealType && (
|
||||
<span className="tag">
|
||||
{MEAL_TYPE_ICONS[template.mealType]} {MEAL_TYPE_NAMES[template.mealType]}
|
||||
</span>
|
||||
)}
|
||||
{template.source && <span className="tag">{template.source}</span>}
|
||||
{derived.weight != null && (
|
||||
<span className="tag">{isRecipe ? 'porce ' : ''}{formatWeight(derived.weight)}</span>
|
||||
)}
|
||||
{isRecipe && (template.servings ?? 1) > 1 && (
|
||||
<span className="tag">{template.servings} porcí</span>
|
||||
)}
|
||||
</div>
|
||||
{calories != null && <span className="template-calories">{formatCalories(calories)}</span>}
|
||||
{template.price != null && (
|
||||
<span className="meal-template-price">{formatPrice(template.price)}</span>
|
||||
)}
|
||||
<button className="btn-icon" onClick={() => onEdit()} title="Upravit" aria-label="Upravit šablonu">
|
||||
<FontAwesomeIcon icon={faPenToSquare} />
|
||||
</button>
|
||||
<button
|
||||
className="btn-icon danger"
|
||||
onClick={() => onDelete()}
|
||||
disabled={busy}
|
||||
title="Smazat"
|
||||
aria-label="Smazat šablonu"
|
||||
>
|
||||
<FontAwesomeIcon icon={faTrash} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isRecipe && !!template.ingredients?.length && (
|
||||
<ul className="template-items">
|
||||
{template.ingredients.map((ingredient, index) => (
|
||||
// Suroviny nemají vlastní id, v rámci jednoho receptu je index stabilní
|
||||
<li key={index}>
|
||||
<span className="template-item-name">{ingredient.name}</span>
|
||||
<span className="template-item-quantity">
|
||||
{ingredient.weight != null ? formatWeight(ingredient.weight) : ''}
|
||||
</span>
|
||||
<span className="template-item-calories">
|
||||
{formatCalories(getIngredientCalories(ingredient))}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{recipe && (
|
||||
<div className="recipe-summary">
|
||||
Celkem {formatCalories(recipe.totalCalories)}
|
||||
{recipe.totalWeight != null && <> · {formatWeight(recipe.totalWeight)}</>}
|
||||
{recipe.caloriesPer100g != null && <> · {recipe.caloriesPer100g} kcal/100 g</>}
|
||||
{recipe.totalPrice != null && <> · {formatPrice(recipe.totalPrice)}</>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{template.note && <p className="meal-template-note">{template.note}</p>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MealTemplateCard;
|
||||
@@ -0,0 +1,323 @@
|
||||
import { useState } from "react";
|
||||
import { Alert, Button, ButtonGroup, Form } from "react-bootstrap";
|
||||
import { MealTemplate, MealTemplateKind, MealType, saveMealTemplate } from "../../../types";
|
||||
import {
|
||||
MEAL_TEMPLATE_KINDS_IN_ORDER, MEAL_TEMPLATE_KIND_NAMES, MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES,
|
||||
} from "../enums";
|
||||
import {
|
||||
deriveAmounts, deriveRecipe, formatCalories, formatPrice, formatPriceInput, formatWeight,
|
||||
parseIntInput, parsePriceInput,
|
||||
} from "../Utils";
|
||||
import CalorieLookup from "./CalorieLookup";
|
||||
import RecipeIngredientsEditor, {
|
||||
DraftIngredient, emptyIngredient, toDraftIngredient, toIngredient,
|
||||
} from "./RecipeIngredientsEditor";
|
||||
|
||||
type Props = {
|
||||
/** Upravovaná šablona. Pokud chybí, zakládá se nová. */
|
||||
template?: MealTemplate,
|
||||
onSaved: (templates: MealTemplate[]) => void,
|
||||
onCancel: () => void,
|
||||
};
|
||||
|
||||
/** Naplní formulář z šablony, nebo ho nechá prázdný pro novou. */
|
||||
const createForm = (template?: MealTemplate) => ({
|
||||
kind: template?.kind ?? MealTemplateKind.HOTOVE,
|
||||
name: template?.name ?? '',
|
||||
source: template?.source ?? '',
|
||||
mealType: (template?.mealType ?? '') as MealType | '',
|
||||
weight: template?.weight != null ? String(template.weight) : '',
|
||||
caloriesPer100g: template?.caloriesPer100g != null ? String(template.caloriesPer100g) : '',
|
||||
calories: template?.calories != null ? String(template.calories) : '',
|
||||
price: formatPriceInput(template?.price),
|
||||
pricePer100g: formatPriceInput(template?.pricePer100g),
|
||||
note: template?.note ?? '',
|
||||
servings: template?.servings != null ? String(template.servings) : '',
|
||||
cookedWeight: template?.cookedWeight != null ? String(template.cookedWeight) : '',
|
||||
});
|
||||
|
||||
/**
|
||||
* Formulář šablony jídla.
|
||||
*
|
||||
* Hotové jídlo (objednané, koupené) si pamatuje jen výsledné hodnoty porce.
|
||||
* Recept je vařené jídlo: zapisují se suroviny a postup a hodnoty porce se
|
||||
* z nich dopočtou — stejně jako na serveru, tady jen jako živý náhled.
|
||||
*/
|
||||
const MealTemplateForm = ({ template, onSaved, onCancel }: Readonly<Props>) => {
|
||||
const [form, setForm] = useState(() => createForm(template));
|
||||
const [ingredients, setIngredients] = useState<DraftIngredient[]>(() =>
|
||||
template?.ingredients?.length ? template.ingredients.map(toDraftIngredient) : [emptyIngredient()]);
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const update = (changes: Partial<ReturnType<typeof createForm>>) =>
|
||||
setForm(current => ({ ...current, ...changes }));
|
||||
|
||||
const isRecipe = form.kind === MealTemplateKind.RECEPT;
|
||||
const filledIngredients = ingredients.filter(item => item.name.trim().length > 0).map(toIngredient);
|
||||
const recipe = deriveRecipe(filledIngredients, parseIntInput(form.servings), parseIntInput(form.cookedWeight));
|
||||
const ingredientWeight = filledIngredients.reduce((sum, item) => sum + (item.weight ?? 0), 0);
|
||||
|
||||
const preview = deriveAmounts(
|
||||
parsePriceInput(form.price),
|
||||
parsePriceInput(form.pricePer100g),
|
||||
parseIntInput(form.weight),
|
||||
parseIntInput(form.caloriesPer100g));
|
||||
const previewCalories = preview.calories ?? parseIntInput(form.calories);
|
||||
|
||||
const canSave = form.name.trim().length > 0 && (!isRecipe || filledIngredients.length > 0) && !busy;
|
||||
|
||||
const save = async () => {
|
||||
if (!canSave) return;
|
||||
setBusy(true);
|
||||
setError(undefined);
|
||||
const common = {
|
||||
...(template ? { id: template.id } : {}),
|
||||
kind: form.kind,
|
||||
name: form.name.trim(),
|
||||
...(form.source.trim() ? { source: form.source.trim() } : {}),
|
||||
...(form.mealType ? { mealType: form.mealType } : {}),
|
||||
...(form.note.trim() ? { note: form.note.trim() } : {}),
|
||||
};
|
||||
// Hodnoty porce receptu si server dopočte ze surovin sám
|
||||
const body = isRecipe
|
||||
? {
|
||||
...common,
|
||||
ingredients: filledIngredients,
|
||||
servings: parseIntInput(form.servings),
|
||||
cookedWeight: parseIntInput(form.cookedWeight),
|
||||
}
|
||||
: {
|
||||
...common,
|
||||
weight: parseIntInput(form.weight),
|
||||
caloriesPer100g: parseIntInput(form.caloriesPer100g),
|
||||
calories: parseIntInput(form.calories),
|
||||
price: parsePriceInput(form.price),
|
||||
pricePer100g: parsePriceInput(form.pricePer100g),
|
||||
};
|
||||
const response = await saveMealTemplate({ body });
|
||||
setBusy(false);
|
||||
if (response.data) {
|
||||
onSaved(response.data);
|
||||
} else {
|
||||
setError((response.error as { error?: string })?.error ?? 'Šablonu se nepodařilo uložit');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card-panel template-form">
|
||||
<h2 className="chart-title">{template ? 'Úprava šablony jídla' : 'Nová šablona jídla'}</h2>
|
||||
|
||||
{error && <Alert variant="danger" className="py-2 small">{error}</Alert>}
|
||||
|
||||
<ButtonGroup className="mb-2">
|
||||
{MEAL_TEMPLATE_KINDS_IN_ORDER.map(kind => (
|
||||
<Button
|
||||
key={kind}
|
||||
variant={form.kind === kind ? 'primary' : 'outline-secondary'}
|
||||
size="sm"
|
||||
onClick={() => update({ kind })}
|
||||
>
|
||||
{MEAL_TEMPLATE_KIND_NAMES[kind]}
|
||||
</Button>
|
||||
))}
|
||||
</ButtonGroup>
|
||||
<p className="text-body-secondary small">
|
||||
{isRecipe
|
||||
? 'Vařené jídlo — zapíšete suroviny a postup, kalorie a cena porce se dopočtou samy.'
|
||||
: 'Objednané nebo koupené jídlo — stačí jednou zapsat hodnoty a příště je nemusíte dohledávat.'}
|
||||
</p>
|
||||
|
||||
<div className="row g-3 mb-3">
|
||||
<div className="col-sm-5">
|
||||
<Form.Label>Název</Form.Label>
|
||||
<Form.Control
|
||||
value={form.name}
|
||||
placeholder={isRecipe ? 'Např. Kuřecí rizoto' : 'Např. Sušenka BeBe'}
|
||||
onChange={event => update({ name: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-sm-4">
|
||||
<Form.Label>Zdroj</Form.Label>
|
||||
<Form.Control
|
||||
value={form.source}
|
||||
placeholder={isRecipe ? 'doma' : 'Chefie, Albert…'}
|
||||
onChange={event => update({ source: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Chod</Form.Label>
|
||||
<Form.Select
|
||||
value={form.mealType}
|
||||
onChange={event => update({ mealType: event.target.value as MealType | '' })}
|
||||
>
|
||||
<option value="">— vybrat při použití —</option>
|
||||
{MEAL_TYPES_IN_ORDER.map(type => (
|
||||
<option key={type} value={type}>
|
||||
{MEAL_TYPE_ICONS[type]} {MEAL_TYPE_NAMES[type]}
|
||||
</option>
|
||||
))}
|
||||
</Form.Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isRecipe ? (
|
||||
<>
|
||||
<fieldset className="meal-fieldset mb-3">
|
||||
<legend>Suroviny</legend>
|
||||
<RecipeIngredientsEditor ingredients={ingredients} onChange={setIngredients} />
|
||||
</fieldset>
|
||||
|
||||
<fieldset className="meal-fieldset mb-3">
|
||||
<legend>Výsledek</legend>
|
||||
<div className="row g-3">
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Počet porcí</Form.Label>
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.servings}
|
||||
placeholder="1"
|
||||
onChange={event => update({ servings: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-sm-4">
|
||||
<Form.Label>Hmotnost hotového jídla</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.cookedWeight}
|
||||
placeholder={ingredientWeight ? String(ingredientWeight) : 'volitelné'}
|
||||
onChange={event => update({ cookedWeight: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">g</span>
|
||||
</div>
|
||||
<Form.Text>vařením se mění, bez ní se vezme součet surovin</Form.Text>
|
||||
</div>
|
||||
<div className="col-sm-5">
|
||||
<Form.Label>Celkem / jedna porce</Form.Label>
|
||||
<div className="recipe-summary">
|
||||
{formatCalories(recipe.totalCalories)}
|
||||
{recipe.totalWeight != null && <> · {formatWeight(recipe.totalWeight)}</>}
|
||||
{recipe.caloriesPer100g != null && <> · {recipe.caloriesPer100g} kcal/100 g</>}
|
||||
<div className="recipe-summary-portion">
|
||||
porce {formatWeight(recipe.weight)} · {formatCalories(recipe.calories)}
|
||||
{recipe.price != null && <> · {formatPrice(recipe.price)}</>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</>
|
||||
) : (
|
||||
<fieldset className="meal-fieldset mb-3">
|
||||
<legend>Kalorie, gramáž a cena porce</legend>
|
||||
<div className="row g-3">
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Gramáž</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.weight}
|
||||
placeholder="350"
|
||||
onChange={event => update({ weight: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">g</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Energie na 100 g</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.caloriesPer100g}
|
||||
placeholder="160"
|
||||
onChange={event => update({ caloriesPer100g: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">kcal</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Cena</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={form.price}
|
||||
placeholder="129,00"
|
||||
onChange={event => update({ price: event.target.value })}
|
||||
/>
|
||||
<span className="input-group-text">Kč</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Cena za 100 g</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={form.pricePer100g}
|
||||
placeholder="volitelné"
|
||||
onChange={event => update({ pricePer100g: event.target.value })}
|
||||
/>
|
||||
<span className="input-group-text">Kč</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="row g-3 mt-0">
|
||||
{preview.calories == null && (
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Kalorie porce</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.calories}
|
||||
placeholder="volitelné"
|
||||
onChange={event => update({ calories: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">kcal</span>
|
||||
</div>
|
||||
<Form.Text>když neznáte gramáž ani hodnotu na 100 g</Form.Text>
|
||||
</div>
|
||||
)}
|
||||
<div className="col-sm-6 d-flex align-items-end">
|
||||
<CalorieLookup
|
||||
name={form.name}
|
||||
onPick={value => update({ caloriesPer100g: String(value) })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>{isRecipe ? 'Postup' : 'Poznámka'}</Form.Label>
|
||||
<Form.Control
|
||||
as="textarea"
|
||||
rows={isRecipe ? 6 : 2}
|
||||
value={form.note}
|
||||
placeholder={isRecipe ? 'Jak se jídlo připravuje…' : undefined}
|
||||
onChange={event => update({ note: event.target.value })}
|
||||
/>
|
||||
</Form.Group>
|
||||
|
||||
<div className="workout-form-footer">
|
||||
{!isRecipe && previewCalories != null && (
|
||||
<span className="workout-draft-calories">
|
||||
{preview.weight != null && `${formatWeight(preview.weight)} · `}
|
||||
{formatCalories(previewCalories)}
|
||||
</span>
|
||||
)}
|
||||
{isRecipe && recipe.calories != null && (
|
||||
<span className="workout-draft-calories">porce {formatCalories(recipe.calories)}</span>
|
||||
)}
|
||||
{template && (
|
||||
<Button variant="outline-secondary" size="sm" onClick={() => onCancel()}>Zrušit úpravu</Button>
|
||||
)}
|
||||
<Button size="sm" onClick={() => save()} disabled={!canSave}>
|
||||
{template ? 'Uložit změny' : 'Vytvořit šablonu'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MealTemplateForm;
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState } from "react";
|
||||
import { Button, Form, OverlayTrigger, Popover } from "react-bootstrap";
|
||||
import { MULTIPLIER_PRESETS } from "../enums";
|
||||
import { applyMultiplier, formatMultiplier, formatMultiplierInput, parseMultiplierInput } from "../Utils";
|
||||
|
||||
type Props = {
|
||||
multiplier?: number,
|
||||
/** Kalorie jedné porce — v nabídce se z nich ukazuje, kolik vyjde po vynásobení. */
|
||||
calories?: number,
|
||||
onChange: (multiplier: number) => void,
|
||||
/** Doplní se do popisku pro čtečky, např. "jídla". */
|
||||
label: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Násobek položky dne přímo v přehledu, bez otevírání formuláře.
|
||||
*
|
||||
* Nabízí běžné předvolby a vlastní hodnotu, i necelou — polovina nedojedeného
|
||||
* jídla je 0,5, dvě sušenky 2. Násobí se jen kalorie.
|
||||
*/
|
||||
const MultiplierControl = ({ multiplier, calories, onChange, label }: Readonly<Props>) => {
|
||||
const [show, setShow] = useState(false);
|
||||
const [input, setInput] = useState('');
|
||||
const current = multiplier ?? 1;
|
||||
const parsed = parseMultiplierInput(input);
|
||||
|
||||
const pick = (value: number) => {
|
||||
setShow(false);
|
||||
if (value !== current) onChange(value);
|
||||
};
|
||||
|
||||
const popover = (
|
||||
<Popover className="multiplier-popover">
|
||||
<Popover.Body>
|
||||
<div className="multiplier-presets">
|
||||
{MULTIPLIER_PRESETS.map(preset => (
|
||||
<Button
|
||||
key={preset}
|
||||
size="sm"
|
||||
variant={preset === current ? 'primary' : 'outline-secondary'}
|
||||
onClick={() => pick(preset)}
|
||||
>
|
||||
{formatMultiplier(preset)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<Form
|
||||
className="multiplier-custom"
|
||||
onSubmit={event => { event.preventDefault(); if (parsed != null) pick(parsed); }}
|
||||
>
|
||||
<Form.Control
|
||||
size="sm"
|
||||
inputMode="decimal"
|
||||
value={input}
|
||||
placeholder="vlastní, např. 1,25"
|
||||
aria-label="Vlastní násobek"
|
||||
onChange={event => setInput(event.target.value)}
|
||||
/>
|
||||
<Button size="sm" type="submit" disabled={parsed == null}>OK</Button>
|
||||
</Form>
|
||||
{calories != null && parsed != null && (
|
||||
<div className="multiplier-hint">
|
||||
{calories} kcal {formatMultiplier(parsed)} = {applyMultiplier(calories, parsed)} kcal
|
||||
</div>
|
||||
)}
|
||||
</Popover.Body>
|
||||
</Popover>
|
||||
);
|
||||
|
||||
return (
|
||||
<OverlayTrigger
|
||||
trigger="click"
|
||||
placement="bottom-end"
|
||||
rootClose
|
||||
show={show}
|
||||
onToggle={next => { setShow(next); if (next) setInput(formatMultiplierInput(multiplier)); }}
|
||||
overlay={popover}
|
||||
>
|
||||
<button
|
||||
className={`multiplier-button ${current !== 1 ? 'active' : ''}`}
|
||||
title="Násobek porce — kolikrát se položka snědla nebo odcvičila"
|
||||
aria-label={`Násobek ${label}`}
|
||||
>
|
||||
{formatMultiplier(current)}
|
||||
</button>
|
||||
</OverlayTrigger>
|
||||
);
|
||||
};
|
||||
|
||||
export default MultiplierControl;
|
||||
@@ -0,0 +1,137 @@
|
||||
import { Button, Form } from "react-bootstrap";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons";
|
||||
import { RecipeIngredient } from "../../../types";
|
||||
import { formatCalories, formatPriceInput, getIngredientCalories, parseIntInput, parsePriceInput } from "../Utils";
|
||||
|
||||
/** Rozpracovaná surovina — hodnoty jsou texty, protože se editují v polích. */
|
||||
export type DraftIngredient = {
|
||||
name: string,
|
||||
weight: string,
|
||||
caloriesPer100g: string,
|
||||
calories: string,
|
||||
price: string,
|
||||
};
|
||||
|
||||
export const emptyIngredient = (): DraftIngredient => ({
|
||||
name: '',
|
||||
weight: '',
|
||||
caloriesPer100g: '',
|
||||
calories: '',
|
||||
price: '',
|
||||
});
|
||||
|
||||
/** Převede uloženou surovinu na rozpracovanou pro editaci. */
|
||||
export const toDraftIngredient = (ingredient: RecipeIngredient): DraftIngredient => ({
|
||||
name: ingredient.name,
|
||||
weight: ingredient.weight != null ? String(ingredient.weight) : '',
|
||||
caloriesPer100g: ingredient.caloriesPer100g != null ? String(ingredient.caloriesPer100g) : '',
|
||||
calories: ingredient.calories != null ? String(ingredient.calories) : '',
|
||||
price: formatPriceInput(ingredient.price),
|
||||
});
|
||||
|
||||
/** Převede rozpracovanou surovinu na hodnoty pro výpočet a uložení. */
|
||||
export const toIngredient = (draft: DraftIngredient): RecipeIngredient => ({
|
||||
name: draft.name.trim(),
|
||||
weight: parseIntInput(draft.weight),
|
||||
caloriesPer100g: parseIntInput(draft.caloriesPer100g),
|
||||
calories: parseIntInput(draft.calories),
|
||||
price: parsePriceInput(draft.price),
|
||||
});
|
||||
|
||||
type Props = {
|
||||
ingredients: DraftIngredient[],
|
||||
onChange: (ingredients: DraftIngredient[]) => void,
|
||||
};
|
||||
|
||||
/**
|
||||
* Editor surovin receptu.
|
||||
*
|
||||
* Energie suroviny se dopočte z gramáže a hodnoty na 100 g; ručně jde zadat jen
|
||||
* tam, kde dopočítat nejde (třeba „lžíce oleje" bez vážení).
|
||||
*/
|
||||
const RecipeIngredientsEditor = ({ ingredients, onChange }: Readonly<Props>) => {
|
||||
const updateAt = (index: number, changes: Partial<DraftIngredient>) =>
|
||||
onChange(ingredients.map((item, i) => (i === index ? { ...item, ...changes } : item)));
|
||||
|
||||
return (
|
||||
<>
|
||||
{ingredients.map((ingredient, index) => {
|
||||
const derived = getIngredientCalories({
|
||||
weight: parseIntInput(ingredient.weight),
|
||||
caloriesPer100g: parseIntInput(ingredient.caloriesPer100g),
|
||||
});
|
||||
return (
|
||||
// Suroviny nemají vlastní id, v rámci rozpracovaného receptu je index jediný klíč
|
||||
<div className="workout-item-row recipe-ingredient-row" key={index}>
|
||||
<Form.Control
|
||||
value={ingredient.name}
|
||||
placeholder="Surovina"
|
||||
aria-label="Název suroviny"
|
||||
onChange={event => updateAt(index, { name: event.target.value })}
|
||||
/>
|
||||
<div className="input-group recipe-ingredient-weight">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={ingredient.weight}
|
||||
placeholder="200"
|
||||
aria-label="Množství v gramech"
|
||||
onChange={event => updateAt(index, { weight: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">g</span>
|
||||
</div>
|
||||
<Form.Control
|
||||
className="recipe-ingredient-rate"
|
||||
inputMode="numeric"
|
||||
value={ingredient.caloriesPer100g}
|
||||
placeholder="kcal/100 g"
|
||||
aria-label="Energie na 100 g"
|
||||
onChange={event => updateAt(index, { caloriesPer100g: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
{derived != null ? (
|
||||
<div className="recipe-ingredient-calories">{formatCalories(derived)}</div>
|
||||
) : (
|
||||
<Form.Control
|
||||
className="recipe-ingredient-calories"
|
||||
inputMode="numeric"
|
||||
value={ingredient.calories}
|
||||
placeholder="kcal"
|
||||
title="Energie použitého množství, když ji nejde dopočítat z gramáže"
|
||||
onChange={event => updateAt(index, { calories: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
)}
|
||||
<div className="input-group recipe-ingredient-price">
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={ingredient.price}
|
||||
placeholder="cena"
|
||||
aria-label="Cena použitého množství"
|
||||
onChange={event => updateAt(index, { price: event.target.value })}
|
||||
/>
|
||||
<span className="input-group-text">Kč</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-icon danger"
|
||||
onClick={() => onChange(ingredients.filter((_, i) => i !== index))}
|
||||
disabled={ingredients.length === 1}
|
||||
title="Odebrat surovinu"
|
||||
aria-label="Odebrat surovinu"
|
||||
>
|
||||
<FontAwesomeIcon icon={faTrash} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Button
|
||||
variant="outline-secondary"
|
||||
size="sm"
|
||||
onClick={() => onChange([...ingredients, emptyIngredient()])}
|
||||
>
|
||||
<FontAwesomeIcon icon={faPlus} /> Surovina
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default RecipeIngredientsEditor;
|
||||
@@ -0,0 +1,53 @@
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faBookmark, faBookOpen } from "@fortawesome/free-solid-svg-icons";
|
||||
import { MealTemplate, MealTemplateKind } from "../../../types";
|
||||
import { describeMealTemplate, normalizeSearch } from "../Utils";
|
||||
|
||||
type Props = {
|
||||
templates: MealTemplate[],
|
||||
/** Rozepsaný název jídla, podle kterého se šablony hledají. */
|
||||
query: string,
|
||||
onPick: (template: MealTemplate) => void,
|
||||
};
|
||||
|
||||
/** Kolik návrhů se nabídne — víc by formulář zbytečně natahovalo. */
|
||||
const SUGGESTION_LIMIT = 5;
|
||||
|
||||
/**
|
||||
* Návrhy šablon k rozepsanému názvu jídla.
|
||||
*
|
||||
* Když uživatel jí něco, co už někdy měl (sušenka, oblíbená objednávka),
|
||||
* nemusí hodnoty dohledávat znovu — stačí začít psát název a vybrat šablonu.
|
||||
*/
|
||||
const TemplateSuggestions = ({ templates, query, onPick }: Readonly<Props>) => {
|
||||
const key = normalizeSearch(query);
|
||||
if (key.length < 2) return null;
|
||||
const matchList = templates
|
||||
.filter(template => normalizeSearch(template.name).includes(key))
|
||||
.slice(0, SUGGESTION_LIMIT);
|
||||
if (!matchList.length) return null;
|
||||
|
||||
return (
|
||||
<div className="template-suggestions">
|
||||
<div className="template-suggestions-title">Už jste to měli?</div>
|
||||
{matchList.map(template => (
|
||||
<button
|
||||
type="button"
|
||||
className="template-suggestion"
|
||||
key={template.id}
|
||||
onClick={() => onPick(template)}
|
||||
title="Vyplnit hodnoty ze šablony"
|
||||
>
|
||||
<FontAwesomeIcon
|
||||
icon={template.kind === MealTemplateKind.RECEPT ? faBookOpen : faBookmark}
|
||||
className="template-suggestion-icon"
|
||||
/>
|
||||
<span className="template-suggestion-name">{template.name}</span>
|
||||
<span className="template-suggestion-detail">{describeMealTemplate(template)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TemplateSuggestions;
|
||||
@@ -5,7 +5,10 @@ import {
|
||||
addActivity, createWorkoutTemplateFromActivities, updateActivity,
|
||||
} from "../../../../types";
|
||||
import { ACTIVITY_PRESETS, ACTIVITY_UNITS_IN_ORDER, ACTIVITY_UNIT_NAMES } from "../../enums";
|
||||
import { deriveActivityCalories, formatCalories, parseIntInput } from "../../Utils";
|
||||
import {
|
||||
applyMultiplier, deriveActivityCalories, formatCalories, formatKgInput, formatMultiplier,
|
||||
formatMultiplierInput, parseIntInput, parseMultiplierInput, parseWeightKgInput,
|
||||
} from "../../Utils";
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean,
|
||||
@@ -28,6 +31,8 @@ function emptyForm(date: string) {
|
||||
caloriesPer100Units: '',
|
||||
calories: '',
|
||||
note: '',
|
||||
extraWeight: '',
|
||||
multiplier: '',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -37,6 +42,9 @@ function emptyForm(date: string) {
|
||||
* Kalorie se dopočítají z množství a spotřeby na 100 jednotek — sto proto, že
|
||||
* u kroků by sazba na jeden krok byla zlomek. Výběr známé aktivity předvyplní
|
||||
* jednotku i orientační sazbu.
|
||||
*
|
||||
* Dodatečná zátěž (činky, vesta) se eviduje jako informace o tréninku, kalorie
|
||||
* nemění — spotřebu se zátěží si uživatel promítne do sazby.
|
||||
*/
|
||||
export default function ActivityModal({ isOpen, date, entry, onClose, onSaved }: Readonly<Props>) {
|
||||
const [form, setForm] = useState(() => emptyForm(date));
|
||||
@@ -56,6 +64,8 @@ export default function ActivityModal({ isOpen, date, entry, onClose, onSaved }:
|
||||
caloriesPer100Units: entry.caloriesPer100Units != null ? String(entry.caloriesPer100Units) : '',
|
||||
calories: entry.calories != null ? String(entry.calories) : '',
|
||||
note: entry.note ?? '',
|
||||
extraWeight: formatKgInput(entry.extraWeightGrams),
|
||||
multiplier: formatMultiplierInput(entry.multiplier),
|
||||
}
|
||||
: emptyForm(date));
|
||||
}, [isOpen, entry, date]);
|
||||
@@ -82,8 +92,12 @@ export default function ActivityModal({ isOpen, date, entry, onClose, onSaved }:
|
||||
const derivedCalories = deriveActivityCalories(quantity, caloriesPer100Units, sets);
|
||||
const manualCalories = parseIntInput(form.calories);
|
||||
const effectiveCalories = derivedCalories ?? manualCalories;
|
||||
const extraWeightGrams = parseWeightKgInput(form.extraWeight);
|
||||
const multiplier = parseMultiplierInput(form.multiplier);
|
||||
const multiplierInvalid = form.multiplier.trim().length > 0 && multiplier == null;
|
||||
const totalCalories = applyMultiplier(effectiveCalories, multiplier);
|
||||
|
||||
const canSave = form.name.trim().length > 0 && quantity != null && !saving;
|
||||
const canSave = form.name.trim().length > 0 && quantity != null && !multiplierInvalid && !saving;
|
||||
|
||||
const save = async () => {
|
||||
if (!canSave) return;
|
||||
@@ -98,6 +112,8 @@ export default function ActivityModal({ isOpen, date, entry, onClose, onSaved }:
|
||||
// Server si kalorie dopočte sám, ručně zadané použije jen jako zálohu
|
||||
calories: derivedCalories != null ? undefined : manualCalories,
|
||||
note: form.note.trim() || undefined,
|
||||
extraWeightGrams,
|
||||
multiplier,
|
||||
};
|
||||
const response = entry
|
||||
? await updateActivity({ body: { id: entry.id, ...body } })
|
||||
@@ -213,6 +229,32 @@ export default function ActivityModal({ isOpen, date, entry, onClose, onSaved }:
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row g-3 mt-0">
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Zátěž</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={form.extraWeight}
|
||||
placeholder="bez zátěže"
|
||||
title="Dodatečná váha — činky, zátěžová vesta. Kalorie nemění."
|
||||
onChange={event => update({ extraWeight: event.target.value })}
|
||||
/>
|
||||
<span className="input-group-text">kg</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-2">
|
||||
<Form.Label>Násobek</Form.Label>
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={form.multiplier}
|
||||
placeholder="1"
|
||||
isInvalid={multiplierInvalid}
|
||||
title="Kolikrát jste aktivitu provedli, třeba 2 nebo 0,5"
|
||||
onChange={event => update({ multiplier: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<Form.Group>
|
||||
@@ -235,7 +277,12 @@ export default function ActivityModal({ isOpen, date, entry, onClose, onSaved }:
|
||||
onChange={event => setAlsoTemplate(event.target.checked)}
|
||||
/>
|
||||
<div className="meal-modal-summary">
|
||||
{effectiveCalories != null && <span>{formatCalories(effectiveCalories)}</span>}
|
||||
{totalCalories != null && (
|
||||
<span>
|
||||
{formatCalories(totalCalories)}
|
||||
{multiplier != null && multiplier !== 1 && ` (${formatMultiplier(multiplier)})`}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="outline-secondary" onClick={onClose}>Zrušit</Button>
|
||||
<Button onClick={save} disabled={!canSave}>
|
||||
|
||||
@@ -4,8 +4,10 @@ import { useNavigate } from "react-router";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faPlay, faBowlFood } from "@fortawesome/free-solid-svg-icons";
|
||||
import { DayOverview, MealTemplate, MealType, applyMealTemplate, getMealTemplates } from "../../../../types";
|
||||
import { MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES } from "../../enums";
|
||||
import { deriveAmounts, formatCalories, formatPrice, formatWeight } from "../../Utils";
|
||||
import {
|
||||
MEAL_TEMPLATE_KINDS_IN_ORDER, MEAL_TEMPLATE_KIND_NAMES, MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES,
|
||||
} from "../../enums";
|
||||
import { describeMealTemplate, normalizeSearch, parseMultiplierInput } from "../../Utils";
|
||||
import { SABLONY_URL } from "../../routes";
|
||||
|
||||
type Props = {
|
||||
@@ -17,28 +19,19 @@ type Props = {
|
||||
onApplied: (day: DayOverview) => void,
|
||||
};
|
||||
|
||||
/** Popíše šablonu jednou řádkou — gramáž, kalorie a cena, co je vyplněné. */
|
||||
const describe = (template: MealTemplate): string => {
|
||||
const derived = deriveAmounts(template.price, template.pricePer100g, template.weight, template.caloriesPer100g);
|
||||
const calories = derived.calories ?? template.calories;
|
||||
return [
|
||||
template.source,
|
||||
derived.weight != null ? formatWeight(derived.weight) : undefined,
|
||||
calories != null ? formatCalories(calories) : undefined,
|
||||
template.price != null ? formatPrice(template.price) : undefined,
|
||||
].filter(Boolean).join(' · ');
|
||||
};
|
||||
|
||||
/**
|
||||
* Výběr šablony jídla k založení do dne.
|
||||
*
|
||||
* Zakládání a úpravy šablon se řeší na stránce Šablony, sem chodí uživatel jen
|
||||
* vybrat hotové jídlo. Chod lze při zakládání přepsat, protože totéž jídlo může
|
||||
* být jednou oběd a podruhé večeře.
|
||||
* vybrat hotové jídlo nebo uvařený recept. Chod lze při zakládání přepsat,
|
||||
* protože totéž jídlo může být jednou oběd a podruhé večeře, a násobkem se
|
||||
* zapíší třeba dvě stejné sušenky naráz.
|
||||
*/
|
||||
const ApplyMealModal = ({ isOpen, date, onClose, onApplied }: Readonly<Props>) => {
|
||||
const [templates, setTemplates] = useState<MealTemplate[]>([]);
|
||||
const [mealType, setMealType] = useState<MealType | ''>('');
|
||||
const [multiplierInput, setMultiplierInput] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
@@ -47,16 +40,21 @@ const ApplyMealModal = ({ isOpen, date, onClose, onApplied }: Readonly<Props>) =
|
||||
if (!isOpen) return;
|
||||
setLoading(true);
|
||||
setMealType('');
|
||||
setMultiplierInput('');
|
||||
setSearch('');
|
||||
getMealTemplates().then(response => {
|
||||
setTemplates(response.data ?? []);
|
||||
setLoading(false);
|
||||
});
|
||||
}, [isOpen]);
|
||||
|
||||
const multiplier = parseMultiplierInput(multiplierInput);
|
||||
const multiplierInvalid = multiplierInput.trim().length > 0 && multiplier == null;
|
||||
|
||||
const apply = async (id: string) => {
|
||||
setBusy(true);
|
||||
const response = await applyMealTemplate({
|
||||
body: { id, date, ...(mealType ? { mealType } : {}) },
|
||||
body: { id, date, ...(mealType ? { mealType } : {}), ...(multiplier != null ? { multiplier } : {}) },
|
||||
});
|
||||
setBusy(false);
|
||||
if (response.data) {
|
||||
@@ -64,6 +62,15 @@ const ApplyMealModal = ({ isOpen, date, onClose, onApplied }: Readonly<Props>) =
|
||||
}
|
||||
};
|
||||
|
||||
const key = normalizeSearch(search);
|
||||
const groupList = MEAL_TEMPLATE_KINDS_IN_ORDER
|
||||
.map(kind => ({
|
||||
kind,
|
||||
templates: templates.filter(template => template.kind === kind
|
||||
&& (!key.length || normalizeSearch(template.name).includes(key))),
|
||||
}))
|
||||
.filter(group => group.templates.length > 0);
|
||||
|
||||
return (
|
||||
<Modal show={isOpen} onHide={onClose} centered size="lg">
|
||||
<Modal.Header closeButton>
|
||||
@@ -80,36 +87,77 @@ const ApplyMealModal = ({ isOpen, date, onClose, onApplied }: Readonly<Props>) =
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon"><FontAwesomeIcon icon={faBowlFood} /></div>
|
||||
<div className="empty-title">Zatím nemáte žádnou šablonu jídla</div>
|
||||
<p className="empty-description">Vytvořit si ji můžete na stránce Šablony.</p>
|
||||
<p className="empty-description">
|
||||
Vytvořit si ji můžete na stránce Šablony, nebo u jídla v přehledu dne tlačítkem
|
||||
„Uložit jako šablonu".
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && !!templates.length && (
|
||||
<>
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Založit jako</Form.Label>
|
||||
<Form.Select
|
||||
value={mealType}
|
||||
onChange={event => setMealType(event.target.value as MealType | '')}
|
||||
>
|
||||
<option value="">— chod ze šablony —</option>
|
||||
{MEAL_TYPES_IN_ORDER.map(type => (
|
||||
<option key={type} value={type}>
|
||||
{MEAL_TYPE_ICONS[type]} {MEAL_TYPE_NAMES[type]}
|
||||
</option>
|
||||
))}
|
||||
</Form.Select>
|
||||
</Form.Group>
|
||||
<div className="row g-3 mb-3">
|
||||
<div className="col-sm-5">
|
||||
<Form.Label>Hledat</Form.Label>
|
||||
<Form.Control
|
||||
autoFocus
|
||||
value={search}
|
||||
placeholder="Název jídla"
|
||||
onChange={event => setSearch(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-sm-4">
|
||||
<Form.Label>Založit jako</Form.Label>
|
||||
<Form.Select
|
||||
value={mealType}
|
||||
onChange={event => setMealType(event.target.value as MealType | '')}
|
||||
>
|
||||
<option value="">— chod ze šablony —</option>
|
||||
{MEAL_TYPES_IN_ORDER.map(type => (
|
||||
<option key={type} value={type}>
|
||||
{MEAL_TYPE_ICONS[type]} {MEAL_TYPE_NAMES[type]}
|
||||
</option>
|
||||
))}
|
||||
</Form.Select>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Násobek</Form.Label>
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={multiplierInput}
|
||||
placeholder="1"
|
||||
isInvalid={multiplierInvalid}
|
||||
title="Kolik porcí jste snědli, třeba 2 nebo 0,5"
|
||||
onChange={event => setMultiplierInput(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{templates.map(template => (
|
||||
<div className="workout-row" key={template.id}>
|
||||
<div className="workout-info">
|
||||
<div className="workout-name">{template.name}</div>
|
||||
<div className="workout-items">{describe(template)}</div>
|
||||
</div>
|
||||
<Button size="sm" onClick={() => apply(template.id)} disabled={busy}>
|
||||
<FontAwesomeIcon icon={faPlay} /> Použít
|
||||
</Button>
|
||||
{!groupList.length && (
|
||||
<p className="text-body-secondary small">Žádná šablona neodpovídá hledání.</p>
|
||||
)}
|
||||
|
||||
{groupList.map(group => (
|
||||
<div className="apply-template-group" key={group.kind}>
|
||||
<h3 className="apply-template-group-title">{MEAL_TEMPLATE_KIND_NAMES[group.kind]}</h3>
|
||||
{group.templates.map(template => (
|
||||
<div className="workout-row" key={template.id}>
|
||||
<div className="workout-info">
|
||||
<div className="workout-name">{template.name}</div>
|
||||
<div className="workout-items">
|
||||
{describeMealTemplate(template)}
|
||||
{!!template.ingredients?.length && ` · ${template.ingredients.length} surovin, hodnoty za porci`}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => apply(template.id)}
|
||||
disabled={busy || multiplierInvalid}
|
||||
>
|
||||
<FontAwesomeIcon icon={faPlay} /> Použít
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
|
||||
@@ -2,9 +2,10 @@ import { useEffect, useState } from "react";
|
||||
import { Alert, Button, Form, Modal, Spinner } from "react-bootstrap";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faFileImport, faTriangleExclamation } from "@fortawesome/free-solid-svg-icons";
|
||||
import { ImportResult, MealType, importLuncher } from "../../../../types";
|
||||
import { MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES } from "../../enums";
|
||||
import { formatDateString, formatPrice, readFileAsBase64 } from "../../Utils";
|
||||
import { ImportMode, ImportResult, MealEntry, MealType, importLuncher } from "../../../../types";
|
||||
import { IMPORT_MODE_NAMES, MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES } from "../../enums";
|
||||
import { formatPrice, readFileAsBase64 } from "../../Utils";
|
||||
import ImportPreview from "../ImportPreview";
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean,
|
||||
@@ -13,19 +14,24 @@ type Props = {
|
||||
onImported: () => void,
|
||||
};
|
||||
|
||||
/** Kolik záznamů náhledu se vypíše, než se zbytek shrne do jednoho řádku. */
|
||||
const PREVIEW_LIMIT = 8;
|
||||
/** Označení záznamů z importu Luncheru — shodné s `IMPORT_SOURCE` na serveru. */
|
||||
const LUNCHER_IMPORT_SOURCE = 'luncher';
|
||||
|
||||
const IMPORT_MODES_IN_ORDER: ImportMode[] = [ImportMode.PRIDAT, ImportMode.NAHRADIT];
|
||||
|
||||
/**
|
||||
* Dialog pro import měsíčního přehledu ze stránky statistik Luncheru.
|
||||
*
|
||||
* Import běží dvoufázově — nejdřív náhled (dryRun), aby uživatel viděl, co se
|
||||
* založí a kolik řádků už má, a teprve po potvrzení se data uloží.
|
||||
* Import běží dvoufázově — nejdřív náhled (dryRun), ve kterém uživatel vidí,
|
||||
* co se založí i co už v dotčených dnech má, a může jednotlivé řádky odškrtnout.
|
||||
* Teprve po potvrzení se uloží vybrané řádky.
|
||||
*/
|
||||
export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Props>) {
|
||||
const [file, setFile] = useState<File | undefined>();
|
||||
const [mealType, setMealType] = useState<MealType>(MealType.OBED);
|
||||
const [mode, setMode] = useState<ImportMode>(ImportMode.PRIDAT);
|
||||
const [preview, setPreview] = useState<ImportResult | undefined>();
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [result, setResult] = useState<ImportResult | undefined>();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
@@ -35,21 +41,30 @@ export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Pr
|
||||
setFile(undefined);
|
||||
setPreview(undefined);
|
||||
setResult(undefined);
|
||||
setSelected(new Set());
|
||||
setBusy(false);
|
||||
}, [isOpen]);
|
||||
|
||||
/** Odešle soubor na server — buď jako náhled, nebo jako ostrý import. */
|
||||
/** Odešle soubor na server — buď jako náhled, nebo jako ostrý import vybraných řádků. */
|
||||
const send = async (dryRun: boolean) => {
|
||||
if (!file) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const content = await readFileAsBase64(file);
|
||||
const response = await importLuncher({
|
||||
body: { fileName: file.name, content, defaultMealType: mealType, dryRun },
|
||||
body: {
|
||||
fileName: file.name,
|
||||
content,
|
||||
defaultMealType: mealType,
|
||||
dryRun,
|
||||
mode,
|
||||
...(dryRun ? {} : { selectedKeys: Array.from(selected) }),
|
||||
},
|
||||
});
|
||||
if (!response.data) return;
|
||||
if (dryRun) {
|
||||
setPreview(response.data);
|
||||
setSelected(new Set(response.data.entries.map(entry => entry.importKey!)));
|
||||
} else {
|
||||
setResult(response.data);
|
||||
setPreview(undefined);
|
||||
@@ -60,14 +75,49 @@ export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Pr
|
||||
}
|
||||
};
|
||||
|
||||
const chooseFile = (chosen?: File) => {
|
||||
setFile(chosen);
|
||||
/** Změna souboru, chodu nebo režimu mění, co se založí — náhled je pak neplatný. */
|
||||
const invalidate = () => {
|
||||
setPreview(undefined);
|
||||
setResult(undefined);
|
||||
};
|
||||
|
||||
const toggle = (key: string) => setSelected(current => {
|
||||
const next = new Set(current);
|
||||
if (next.has(key)) next.delete(key); else next.add(key);
|
||||
return next;
|
||||
});
|
||||
|
||||
const toggleDay = (date: string, checked: boolean) => setSelected(current => {
|
||||
const next = new Set(current);
|
||||
preview?.entries
|
||||
.filter(entry => entry.date === date)
|
||||
.forEach(entry => (checked ? next.add(entry.importKey!) : next.delete(entry.importKey!)));
|
||||
return next;
|
||||
});
|
||||
|
||||
/**
|
||||
* Odškrtne řádky ve dnech, kde už je ručně zadané jídlo stejného chodu.
|
||||
* Typicky oběd, který si uživatel zapsal dřív, než udělal import.
|
||||
*/
|
||||
const uncheckManualDays = () => {
|
||||
const manualDays = new Set((preview?.existing ?? [])
|
||||
.filter(entry => !entry.importSource && entry.mealType === mealType)
|
||||
.map(entry => entry.date));
|
||||
setSelected(current => new Set(Array.from(current).filter(key =>
|
||||
!manualDays.has(preview?.entries.find(entry => entry.importKey === key)?.date ?? ''))));
|
||||
};
|
||||
|
||||
const selectedEntries = preview?.entries.filter(entry => selected.has(entry.importKey!)) ?? [];
|
||||
const selectedDays = new Set(selectedEntries.map(entry => entry.date));
|
||||
const isReplaced = (entry: MealEntry) =>
|
||||
mode === ImportMode.NAHRADIT && entry.importSource === LUNCHER_IMPORT_SOURCE;
|
||||
const replacedCount = (preview?.existing ?? [])
|
||||
.filter(entry => isReplaced(entry) && selectedDays.has(entry.date)).length;
|
||||
const hasManualConflict = (preview?.existing ?? [])
|
||||
.some(entry => !entry.importSource && entry.mealType === mealType);
|
||||
|
||||
return (
|
||||
<Modal show={isOpen} onHide={onClose} centered size="lg">
|
||||
<Modal show={isOpen} onHide={onClose} centered size="lg" scrollable>
|
||||
<Modal.Header closeButton>
|
||||
<Modal.Title>
|
||||
<FontAwesomeIcon icon={faFileImport} /> Import z Luncheru
|
||||
@@ -76,8 +126,8 @@ export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Pr
|
||||
<Modal.Body>
|
||||
<p className="text-body-secondary small">
|
||||
Na stránce statistik v Luncheru si stáhněte přehled za měsíc (XLSX, CSV nebo JSON)
|
||||
a nahrajte ho sem. Záznamy se založí do dnů, ke kterým patří. Opakovaný import
|
||||
stejného měsíce data nezduplikuje.
|
||||
a nahrajte ho sem. V náhledu uvidíte, co se založí i co už v jednotlivých dnech máte,
|
||||
a řádky, které nechcete, můžete odškrtnout.
|
||||
</p>
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
@@ -85,27 +135,45 @@ export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Pr
|
||||
<Form.Control
|
||||
type="file"
|
||||
accept=".xlsx,.csv,.json"
|
||||
onChange={event => chooseFile((event.target as HTMLInputElement).files?.[0])}
|
||||
onChange={event => { setFile((event.target as HTMLInputElement).files?.[0]); invalidate(); }}
|
||||
/>
|
||||
</Form.Group>
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Založit jako</Form.Label>
|
||||
<Form.Select
|
||||
value={mealType}
|
||||
onChange={event => { setMealType(event.target.value as MealType); setPreview(undefined); }}
|
||||
>
|
||||
{MEAL_TYPES_IN_ORDER.map(type => (
|
||||
<option key={type} value={type}>
|
||||
{MEAL_TYPE_ICONS[type]} {MEAL_TYPE_NAMES[type]}
|
||||
</option>
|
||||
<div className="row g-3 mb-3">
|
||||
<div className="col-sm-6">
|
||||
<Form.Label>Založit jako</Form.Label>
|
||||
<Form.Select
|
||||
value={mealType}
|
||||
onChange={event => { setMealType(event.target.value as MealType); invalidate(); }}
|
||||
>
|
||||
{MEAL_TYPES_IN_ORDER.map(type => (
|
||||
<option key={type} value={type}>
|
||||
{MEAL_TYPE_ICONS[type]} {MEAL_TYPE_NAMES[type]}
|
||||
</option>
|
||||
))}
|
||||
</Form.Select>
|
||||
<Form.Text>Luncher řeší výběr obědů, proto je předvolený oběd.</Form.Text>
|
||||
</div>
|
||||
<div className="col-sm-6">
|
||||
<Form.Label>Dřívější import stejných dnů</Form.Label>
|
||||
{IMPORT_MODES_IN_ORDER.map(item => (
|
||||
<Form.Check
|
||||
key={item}
|
||||
type="radio"
|
||||
id={`import-mode-${item}`}
|
||||
name="import-mode"
|
||||
checked={mode === item}
|
||||
label={IMPORT_MODE_NAMES[item]}
|
||||
onChange={() => { setMode(item); invalidate(); }}
|
||||
/>
|
||||
))}
|
||||
</Form.Select>
|
||||
<Form.Text>
|
||||
Luncher řeší výběr obědů, proto je předvolený oběd. Jednotlivá jídla si pak
|
||||
můžete v přehledu dne upravit nebo doplnit o další.
|
||||
</Form.Text>
|
||||
</Form.Group>
|
||||
<Form.Text>
|
||||
{mode === ImportMode.PRIDAT
|
||||
? 'Už naimportované řádky se přeskočí, nic se nemaže.'
|
||||
: 'Dřív naimportované záznamy dotčených dnů se smažou a založí znovu. Ručně zadaná jídla zůstanou.'}
|
||||
</Form.Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{busy && (
|
||||
<div className="text-center py-3">
|
||||
@@ -114,36 +182,46 @@ export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Pr
|
||||
)}
|
||||
|
||||
{preview && !busy && (
|
||||
<Alert variant={preview.imported ? 'success' : 'secondary'}>
|
||||
<strong>Náhled importu</strong>
|
||||
<div className="small mt-1">
|
||||
V souboru je {preview.rowCount} řádků. Založí se {preview.imported} záznamů
|
||||
{preview.skipped > 0 && <> a {preview.skipped} se přeskočí, protože už je máte</>}.
|
||||
{preview.days.length > 0 && (
|
||||
<> Dotčené dny: {formatDateString(preview.days[0])}
|
||||
{preview.days.length > 1 && <> – {formatDateString(preview.days[preview.days.length - 1])}</>}
|
||||
{' '}({preview.days.length}).</>
|
||||
)}
|
||||
{' '}Celkem za {formatPrice(preview.totalPrice)}.
|
||||
</div>
|
||||
<>
|
||||
<Alert variant={selectedEntries.length ? 'success' : 'secondary'} className="py-2">
|
||||
<strong>Náhled importu</strong>
|
||||
<div className="small mt-1">
|
||||
V souboru je {preview.rowCount} řádků. Vybráno {selectedEntries.length}
|
||||
{' '}z {preview.entries.length} za{' '}
|
||||
{formatPrice(selectedEntries.reduce((sum, entry) => sum + (entry.price ?? 0), 0))}
|
||||
{selectedDays.size > 0 && <> ve {selectedDays.size} dnech</>}.
|
||||
{replacedCount > 0 && <> Nahradí se {replacedCount} dřív naimportovaných záznamů.</>}
|
||||
</div>
|
||||
</Alert>
|
||||
|
||||
{preview.entries.length > 0 && (
|
||||
<ul className="import-preview-list">
|
||||
{preview.entries.slice(0, PREVIEW_LIMIT).map(entry => (
|
||||
<li key={entry.id}>
|
||||
<span className="import-preview-date">{formatDateString(entry.date)}</span>
|
||||
{entry.name}
|
||||
{entry.source && <span className="text-body-secondary"> · {entry.source}</span>}
|
||||
<span className="import-preview-price">{formatPrice(entry.price)}</span>
|
||||
</li>
|
||||
))}
|
||||
{preview.entries.length > PREVIEW_LIMIT && (
|
||||
<li className="text-body-secondary">
|
||||
… a dalších {preview.entries.length - PREVIEW_LIMIT}
|
||||
</li>
|
||||
<div className="import-preview-toolbar">
|
||||
<Button
|
||||
variant="outline-secondary"
|
||||
size="sm"
|
||||
onClick={() => setSelected(new Set(preview.entries.map(entry => entry.importKey!)))}
|
||||
>
|
||||
Vybrat vše
|
||||
</Button>
|
||||
<Button variant="outline-secondary" size="sm" onClick={() => setSelected(new Set())}>
|
||||
Zrušit výběr
|
||||
</Button>
|
||||
{hasManualConflict && (
|
||||
<Button variant="outline-secondary" size="sm" onClick={() => uncheckManualDays()}>
|
||||
Odškrtnout dny, kde už máte {MEAL_TYPE_NAMES[mealType].toLowerCase()}
|
||||
</Button>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</Alert>
|
||||
|
||||
<ImportPreview
|
||||
preview={preview}
|
||||
selected={selected}
|
||||
onToggle={toggle}
|
||||
onToggleDay={toggleDay}
|
||||
isReplaced={isReplaced}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{result && !busy && (
|
||||
@@ -151,7 +229,8 @@ export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Pr
|
||||
<strong>Import dokončen</strong>
|
||||
<div className="small mt-1">
|
||||
Založeno {result.imported} záznamů ve {result.days.length} dnech
|
||||
{result.skipped > 0 && <>, {result.skipped} přeskočeno jako již existující</>}.
|
||||
{result.skipped > 0 && <>, {result.skipped} přeskočeno</>}
|
||||
{result.replaced > 0 && <>, {result.replaced} dřívějších nahrazeno</>}.
|
||||
Celkem za {formatPrice(result.totalPrice)}.
|
||||
</div>
|
||||
</Alert>
|
||||
@@ -173,8 +252,8 @@ export default function ImportModal({ isOpen, onClose, onImported }: Readonly<Pr
|
||||
</Button>
|
||||
)}
|
||||
{!result && preview && (
|
||||
<Button onClick={() => send(false)} disabled={busy || preview.imported === 0}>
|
||||
Naimportovat {preview.imported} záznamů
|
||||
<Button onClick={() => send(false)} disabled={busy || !selectedEntries.length}>
|
||||
Naimportovat {selectedEntries.length} záznamů
|
||||
</Button>
|
||||
)}
|
||||
</Modal.Footer>
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Button, Form, Modal } from "react-bootstrap";
|
||||
import {
|
||||
DayRecord, MealEntry, MealType, UserSettings,
|
||||
addMeal, createMealTemplateFromMeal, getSettings, updateMeal,
|
||||
DayRecord, MealEntry, MealTemplate, MealTemplateKind, MealType, UserSettings,
|
||||
addMeal, createMealTemplateFromMeal, getMealTemplates, getSettings, updateMeal,
|
||||
} from "../../../../types";
|
||||
import { MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES } from "../../enums";
|
||||
import {
|
||||
deriveAmounts, formatCalories, formatPriceInput, formatWeight, parseIntInput, parsePriceInput,
|
||||
applyMultiplier, deriveAmounts, formatCalories, formatMultiplier, formatMultiplierInput, formatPriceInput,
|
||||
formatWeight, parseIntInput, parseMultiplierInput, parsePriceInput,
|
||||
} from "../../Utils";
|
||||
import CalorieLookup from "../CalorieLookup";
|
||||
import TemplateSuggestions from "../TemplateSuggestions";
|
||||
|
||||
type Props = {
|
||||
isOpen: boolean,
|
||||
@@ -33,12 +35,13 @@ function emptyForm(date: string) {
|
||||
caloriesPer100g: '',
|
||||
calories: '',
|
||||
note: '',
|
||||
multiplier: '',
|
||||
};
|
||||
}
|
||||
|
||||
/** Znormalizuje název zdroje pro porovnání se sazbami z nastavení. */
|
||||
function normalizeSource(source: string): string {
|
||||
return source.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().trim();
|
||||
return source.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -48,17 +51,24 @@ function normalizeSource(source: string): string {
|
||||
* se dopočte z ceny a sazby, ale dá se přepsat. Z gramáže a energie na 100 g se
|
||||
* pak dopočtou kalorie. Každá položka má vlastní sazbu, takže hlavní jídlo a salát
|
||||
* s jiným cenováním můžou být ve stejném dni vedle sebe.
|
||||
*
|
||||
* U nového jídla se k rozepsanému názvu nabízejí šablony, takže jídlo, které už
|
||||
* uživatel někdy měl, nemusí dohledávat znovu.
|
||||
*/
|
||||
export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Readonly<Props>) {
|
||||
const [form, setForm] = useState(() => emptyForm(date));
|
||||
const [settings, setSettings] = useState<UserSettings | undefined>();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [alsoTemplate, setAlsoTemplate] = useState(false);
|
||||
const [templates, setTemplates] = useState<MealTemplate[]>([]);
|
||||
/** Název šablony, ze které se formulář naposledy vyplnil — pak už se návrhy nenabízejí. */
|
||||
const [pickedTemplate, setPickedTemplate] = useState<string | undefined>();
|
||||
|
||||
// Při každém otevření se formulář naplní dle toho, co se upravuje
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
setAlsoTemplate(false);
|
||||
setPickedTemplate(undefined);
|
||||
setForm(entry
|
||||
? {
|
||||
date: entry.date,
|
||||
@@ -71,10 +81,17 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
caloriesPer100g: entry.caloriesPer100g != null ? String(entry.caloriesPer100g) : '',
|
||||
calories: entry.calories != null ? String(entry.calories) : '',
|
||||
note: entry.note ?? '',
|
||||
multiplier: formatMultiplierInput(entry.multiplier),
|
||||
}
|
||||
: emptyForm(date));
|
||||
}, [isOpen, entry, date]);
|
||||
|
||||
// Šablony se nabízejí jen při zakládání; načtou se při každém otevření, mohly přibýt
|
||||
useEffect(() => {
|
||||
if (!isOpen || entry) return;
|
||||
getMealTemplates().then(response => setTemplates(response.data ?? []));
|
||||
}, [isOpen, entry]);
|
||||
|
||||
// Sazby podniků se načtou jednou při otevření a slouží k předvyplnění Kč/100 g
|
||||
useEffect(() => {
|
||||
if (!isOpen || settings) return;
|
||||
@@ -83,6 +100,24 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
|
||||
const update = (changes: Partial<typeof form>) => setForm(current => ({ ...current, ...changes }));
|
||||
|
||||
/** Vyplní formulář hodnotami ze šablony; datum a násobek zůstanou, jak jsou. */
|
||||
const applyTemplate = (template: MealTemplate) => {
|
||||
setPickedTemplate(template.name);
|
||||
setForm(current => ({
|
||||
...current,
|
||||
name: template.name,
|
||||
mealType: template.mealType ?? current.mealType,
|
||||
source: template.source ?? '',
|
||||
price: formatPriceInput(template.price),
|
||||
pricePer100g: formatPriceInput(template.pricePer100g),
|
||||
weight: template.weight != null ? String(template.weight) : '',
|
||||
caloriesPer100g: template.caloriesPer100g != null ? String(template.caloriesPer100g) : '',
|
||||
calories: template.calories != null ? String(template.calories) : '',
|
||||
// Postup receptu do záznamu dne nepatří, zůstává u šablony
|
||||
note: template.kind === MealTemplateKind.RECEPT ? '' : template.note ?? '',
|
||||
}));
|
||||
};
|
||||
|
||||
/** Sazba nastavená pro právě zadaný zdroj, pokud nějaká je. */
|
||||
const rateForSource = useMemo(() => {
|
||||
const key = normalizeSource(form.source);
|
||||
@@ -109,8 +144,11 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
/** Kalorie zadané ručně se použijí jen tehdy, když nejdou dopočítat. */
|
||||
const manualCalories = parseIntInput(form.calories);
|
||||
const effectiveCalories = derived.calories ?? manualCalories;
|
||||
const multiplier = parseMultiplierInput(form.multiplier);
|
||||
const multiplierInvalid = form.multiplier.trim().length > 0 && multiplier == null;
|
||||
const totalCalories = applyMultiplier(effectiveCalories, multiplier);
|
||||
|
||||
const canSave = form.name.trim().length > 0 && !saving;
|
||||
const canSave = form.name.trim().length > 0 && !multiplierInvalid && !saving;
|
||||
|
||||
const save = async () => {
|
||||
if (!canSave) return;
|
||||
@@ -127,6 +165,7 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
// Server si kalorie dopočte sám, ručně poslané použije jen jako zálohu
|
||||
calories: derived.calories != null ? undefined : manualCalories,
|
||||
note: form.note.trim() || undefined,
|
||||
multiplier,
|
||||
};
|
||||
const response = entry
|
||||
? await updateMeal({ body: { id: entry.id, ...body } })
|
||||
@@ -159,8 +198,14 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
autoFocus
|
||||
value={form.name}
|
||||
placeholder="Např. Kuřecí gyros s hranolkami"
|
||||
onChange={event => update({ name: event.target.value })}
|
||||
onChange={event => { update({ name: event.target.value }); setPickedTemplate(undefined); }}
|
||||
/>
|
||||
{!entry && pickedTemplate !== form.name && (
|
||||
<TemplateSuggestions templates={templates} query={form.name} onPick={applyTemplate} />
|
||||
)}
|
||||
{!entry && pickedTemplate === form.name && (
|
||||
<Form.Text>vyplněno ze šablony, hodnoty jde upravit</Form.Text>
|
||||
)}
|
||||
</Form.Group>
|
||||
|
||||
<div className="row g-3 mb-3">
|
||||
@@ -255,7 +300,7 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
<fieldset className="meal-fieldset mb-3">
|
||||
<legend>Kalorie</legend>
|
||||
<div className="row g-3">
|
||||
<div className="col-sm-4">
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Energie na 100 g</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
@@ -267,8 +312,8 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
<span className="input-group-text">kcal</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-4">
|
||||
<Form.Label>Kalorie celkem</Form.Label>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Kalorie porce</Form.Label>
|
||||
{derived.calories != null ? (
|
||||
<div className="derived-value">{formatCalories(derived.calories)}</div>
|
||||
) : (
|
||||
@@ -288,6 +333,17 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
</Form.Text>
|
||||
)}
|
||||
</div>
|
||||
<div className="col-sm-2">
|
||||
<Form.Label>Násobek</Form.Label>
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={form.multiplier}
|
||||
placeholder="1"
|
||||
isInvalid={multiplierInvalid}
|
||||
title="Kolik porcí jste snědli, třeba 2 nebo 0,5. Cena se nenásobí."
|
||||
onChange={event => update({ multiplier: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-sm-4 d-flex align-items-end">
|
||||
<CalorieLookup
|
||||
name={form.name}
|
||||
@@ -318,10 +374,15 @@ export default function MealModal({ isOpen, date, entry, onClose, onSaved }: Rea
|
||||
/>
|
||||
<div className="meal-modal-summary">
|
||||
{derived.weight != null && <span>{formatWeight(derived.weight)}</span>}
|
||||
{effectiveCalories != null && <span>{formatCalories(effectiveCalories)}</span>}
|
||||
{totalCalories != null && (
|
||||
<span>
|
||||
{formatCalories(totalCalories)}
|
||||
{multiplier != null && multiplier !== 1 && ` (${formatMultiplier(multiplier)})`}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="outline-secondary" onClick={onClose}>Zrušit</Button>
|
||||
<Button onClick={save} disabled={!canSave}>
|
||||
<Button onClick={() => save()} disabled={!canSave}>
|
||||
{saving ? 'Ukládám…' : 'Uložit'}
|
||||
</Button>
|
||||
</Modal.Footer>
|
||||
|
||||
+18
-1
@@ -1,4 +1,4 @@
|
||||
import { ActivityUnit, MealType, Pohlavi } from "../../types";
|
||||
import { ActivityUnit, ImportMode, MealTemplateKind, MealType, Pohlavi } from "../../types";
|
||||
|
||||
/** Lidsky čitelné názvy typů jídel. */
|
||||
export const MEAL_TYPE_NAMES: Record<MealType, string> = {
|
||||
@@ -117,3 +117,20 @@ export const TEMPLATE_TAB_NAMES: Record<TemplateTab, string> = {
|
||||
TRENINKY: 'Tréninky',
|
||||
JIDLA: 'Jídla',
|
||||
};
|
||||
|
||||
/** Lidsky čitelné názvy druhů šablon jídel. */
|
||||
export const MEAL_TEMPLATE_KIND_NAMES: Record<MealTemplateKind, string> = {
|
||||
HOTOVE: 'Hotové jídlo',
|
||||
RECEPT: 'Recept',
|
||||
};
|
||||
|
||||
export const MEAL_TEMPLATE_KINDS_IN_ORDER: MealTemplateKind[] = [MealTemplateKind.HOTOVE, MealTemplateKind.RECEPT];
|
||||
|
||||
/** Názvy režimů importu. */
|
||||
export const IMPORT_MODE_NAMES: Record<ImportMode, string> = {
|
||||
PRIDAT: 'Přidat k tomu, co už mám',
|
||||
NAHRADIT: 'Nahradit dřívější import',
|
||||
};
|
||||
|
||||
/** Předvolby násobku porce nabízené v přehledu dne. */
|
||||
export const MULTIPLIER_PRESETS = [0.5, 1, 1.5, 2, 3];
|
||||
@@ -7,11 +7,11 @@ import {
|
||||
} from "@fortawesome/free-solid-svg-icons";
|
||||
import {
|
||||
ActivityEntry, DayOverview, MealEntry, createMealTemplateFromMeal,
|
||||
deleteActivity, deleteMeal, getDayOverview, saveSleep,
|
||||
deleteActivity, deleteMeal, getDayOverview, saveSleep, setActivityMultiplier, setMealMultiplier,
|
||||
} from "../../../types";
|
||||
import { DayTab, DAY_TAB_NAMES, MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES } from "../enums";
|
||||
import {
|
||||
formatBalance, formatCalories, formatDate, formatPrice, formatSleep,
|
||||
applyMultiplier, formatBalance, formatCalories, formatDate, formatPrice, formatSleep,
|
||||
formatSleepInput, getDayOfWeek, getHumanDate, parseSleepInput, shiftDate,
|
||||
} from "../Utils";
|
||||
import MealModal from "../components/modals/MealModal";
|
||||
@@ -48,6 +48,7 @@ export default function DayPage() {
|
||||
const [saveWorkoutOpen, setSaveWorkoutOpen] = useState(false);
|
||||
const [preselectedActivities, setPreselectedActivities] = useState<string[]>([]);
|
||||
const [savedNotice, setSavedNotice] = useState<string | undefined>();
|
||||
const [errorNotice, setErrorNotice] = useState<string | undefined>();
|
||||
|
||||
const loadDay = useCallback(async (forDate: string) => {
|
||||
setLoading(true);
|
||||
@@ -94,12 +95,26 @@ export default function DayPage() {
|
||||
};
|
||||
|
||||
const saveMealAsTemplate = async (entry: MealEntry) => {
|
||||
setErrorNotice(undefined);
|
||||
const response = await createMealTemplateFromMeal({ body: { id: entry.id, date: entry.date } });
|
||||
if (response.data) {
|
||||
showNotice(`„${entry.name}" uloženo jako šablonu jídla.`);
|
||||
} else {
|
||||
// Typicky recept stejného názvu, který se ze záznamu dne přepsat nesmí
|
||||
setErrorNotice((response.error as { error?: string })?.error ?? 'Šablonu se nepodařilo uložit');
|
||||
}
|
||||
};
|
||||
|
||||
const changeMealMultiplier = async (entry: MealEntry, multiplier: number) => {
|
||||
const response = await setMealMultiplier({ body: { id: entry.id, date: entry.date, multiplier } });
|
||||
if (response.data) setDay(response.data);
|
||||
};
|
||||
|
||||
const changeActivityMultiplier = async (entry: ActivityEntry, multiplier: number) => {
|
||||
const response = await setActivityMultiplier({ body: { id: entry.id, date: entry.date, multiplier } });
|
||||
if (response.data) setDay(response.data);
|
||||
};
|
||||
|
||||
/** Otevře dialog pro uložení tréninku, se zaškrtnutou jednou aktivitou nebo všemi. */
|
||||
const openSaveWorkout = (entry?: ActivityEntry) => {
|
||||
setPreselectedActivities(entry ? [entry.id] : []);
|
||||
@@ -118,7 +133,7 @@ export default function DayPage() {
|
||||
{tab === DayTab.PRIJEM ? (
|
||||
<div className="header-actions">
|
||||
<Button variant="outline-secondary" onClick={() => setMealTemplateModalOpen(true)}>
|
||||
<FontAwesomeIcon icon={faBowlFood} /> Šablony
|
||||
<FontAwesomeIcon icon={faBowlFood} /> Ze šablony
|
||||
</Button>
|
||||
<Button onClick={() => { setEditedMeal(undefined); setMealModalOpen(true); }}>
|
||||
<FontAwesomeIcon icon={faPlus} /> Přidat jídlo
|
||||
@@ -132,7 +147,7 @@ export default function DayPage() {
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline-secondary" onClick={() => setWorkoutModalOpen(true)}>
|
||||
<FontAwesomeIcon icon={faDumbbell} /> Šablony
|
||||
<FontAwesomeIcon icon={faDumbbell} /> Ze šablony
|
||||
</Button>
|
||||
<Button onClick={() => { setEditedActivity(undefined); setActivityModalOpen(true); }}>
|
||||
<FontAwesomeIcon icon={faPlus} /> Přidat aktivitu
|
||||
@@ -224,6 +239,11 @@ export default function DayPage() {
|
||||
</div>
|
||||
|
||||
{savedNotice && <Alert variant="success" className="py-2 small">{savedNotice}</Alert>}
|
||||
{errorNotice && (
|
||||
<Alert variant="danger" className="py-2 small" dismissible onClose={() => setErrorNotice(undefined)}>
|
||||
{errorNotice}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="day-tabs">
|
||||
<button
|
||||
@@ -265,6 +285,9 @@ export default function DayPage() {
|
||||
<span className="meal-group-icon">{MEAL_TYPE_ICONS[group.mealType]}</span>
|
||||
{MEAL_TYPE_NAMES[group.mealType]}
|
||||
<span className="meal-group-total">
|
||||
{formatCalories(group.entries.reduce(
|
||||
(sum, entry) => sum + (applyMultiplier(entry.calories, entry.multiplier) ?? 0), 0))}
|
||||
{' · '}
|
||||
{formatPrice(group.entries.reduce((sum, entry) => sum + (entry.price ?? 0), 0))}
|
||||
</span>
|
||||
</h2>
|
||||
@@ -276,6 +299,7 @@ export default function DayPage() {
|
||||
onEdit={() => { setEditedMeal(entry); setMealModalOpen(true); }}
|
||||
onDelete={() => removeMeal(entry)}
|
||||
onSaveTemplate={() => saveMealAsTemplate(entry)}
|
||||
onMultiplierChange={multiplier => changeMealMultiplier(entry, multiplier)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -304,6 +328,7 @@ export default function DayPage() {
|
||||
onEdit={() => { setEditedActivity(entry); setActivityModalOpen(true); }}
|
||||
onDelete={() => removeActivity(entry)}
|
||||
onSaveTemplate={() => openSaveWorkout(entry)}
|
||||
onMultiplierChange={multiplier => changeActivityMultiplier(entry, multiplier)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -1,41 +1,26 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Alert, Button, Form, Spinner } from "react-bootstrap";
|
||||
import { Spinner } from "react-bootstrap";
|
||||
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
||||
import { faTrash, faPenToSquare, faBowlFood } from "@fortawesome/free-solid-svg-icons";
|
||||
import { MealTemplate, MealType, deleteMealTemplate, getMealTemplates, saveMealTemplate } from "../../../types";
|
||||
import { MEAL_TYPES_IN_ORDER, MEAL_TYPE_ICONS, MEAL_TYPE_NAMES } from "../enums";
|
||||
import {
|
||||
deriveAmounts, formatCalories, formatPrice, formatPriceInput, formatWeight,
|
||||
parseIntInput, parsePriceInput,
|
||||
} from "../Utils";
|
||||
|
||||
/** Prázdný formulář nové šablony jídla. */
|
||||
const emptyForm = () => ({
|
||||
name: '',
|
||||
source: '',
|
||||
mealType: '' as MealType | '',
|
||||
weight: '',
|
||||
caloriesPer100g: '',
|
||||
calories: '',
|
||||
price: '',
|
||||
pricePer100g: '',
|
||||
note: '',
|
||||
});
|
||||
import { faBowlFood } from "@fortawesome/free-solid-svg-icons";
|
||||
import { MealTemplate, deleteMealTemplate, getMealTemplates } from "../../../types";
|
||||
import { MEAL_TEMPLATE_KINDS_IN_ORDER, MEAL_TEMPLATE_KIND_NAMES } from "../enums";
|
||||
import MealTemplateCard from "../components/MealTemplateCard";
|
||||
import MealTemplateForm from "../components/MealTemplateForm";
|
||||
|
||||
/**
|
||||
* Panel se správou šablon jídel.
|
||||
*
|
||||
* Na rozdíl od šablon tréninků se neskládají z jiných — jsou to ploché záznamy.
|
||||
* Poznámka slouží i na postup přípravy u domácích jídel; strukturované suroviny
|
||||
* mohou přibýt později, aniž by se model musel měnit.
|
||||
* Šablony jsou dvojího druhu: hotová jídla (objednané, koupené — pamatují si
|
||||
* výsledné hodnoty) a recepty (vařené — nesou suroviny a postup a hodnoty porce
|
||||
* se z nich dopočtou). Na rozdíl od šablon tréninků se neskládají z jiných.
|
||||
*/
|
||||
const MealTemplatesPanel = () => {
|
||||
const [templates, setTemplates] = useState<MealTemplate[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editedId, setEditedId] = useState<string | undefined>();
|
||||
const [form, setForm] = useState(emptyForm);
|
||||
const [error, setError] = useState<string | undefined>();
|
||||
const [edited, setEdited] = useState<MealTemplate | undefined>();
|
||||
const [busy, setBusy] = useState(false);
|
||||
/** Po uložení se zvýší, aby se formulář vyprázdnil i u nové šablony. */
|
||||
const [formVersion, setFormVersion] = useState(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
@@ -46,85 +31,32 @@ const MealTemplatesPanel = () => {
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
const update = (changes: Partial<ReturnType<typeof emptyForm>>) =>
|
||||
setForm(current => ({ ...current, ...changes }));
|
||||
|
||||
const resetForm = () => {
|
||||
setEditedId(undefined);
|
||||
setForm(emptyForm());
|
||||
setError(undefined);
|
||||
};
|
||||
|
||||
const canSave = form.name.trim().length > 0 && !busy;
|
||||
|
||||
const save = async () => {
|
||||
if (!canSave) return;
|
||||
setBusy(true);
|
||||
setError(undefined);
|
||||
const response = await saveMealTemplate({
|
||||
body: {
|
||||
...(editedId ? { id: editedId } : {}),
|
||||
name: form.name.trim(),
|
||||
...(form.source.trim() ? { source: form.source.trim() } : {}),
|
||||
...(form.mealType ? { mealType: form.mealType } : {}),
|
||||
...(form.note.trim() ? { note: form.note.trim() } : {}),
|
||||
weight: parseIntInput(form.weight),
|
||||
caloriesPer100g: parseIntInput(form.caloriesPer100g),
|
||||
calories: parseIntInput(form.calories),
|
||||
price: parsePriceInput(form.price),
|
||||
pricePer100g: parsePriceInput(form.pricePer100g),
|
||||
},
|
||||
});
|
||||
setBusy(false);
|
||||
if (response.data) {
|
||||
setTemplates(response.data);
|
||||
resetForm();
|
||||
} else {
|
||||
setError((response.error as { error?: string })?.error ?? 'Šablonu se nepodařilo uložit');
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: string) => {
|
||||
setBusy(true);
|
||||
const response = await deleteMealTemplate({ body: { id } });
|
||||
setBusy(false);
|
||||
if (response.data) {
|
||||
setTemplates(response.data);
|
||||
if (editedId === id) resetForm();
|
||||
if (edited?.id === id) setEdited(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const edit = (template: MealTemplate) => {
|
||||
setEditedId(template.id);
|
||||
setError(undefined);
|
||||
setForm({
|
||||
name: template.name,
|
||||
source: template.source ?? '',
|
||||
mealType: template.mealType ?? '',
|
||||
weight: template.weight != null ? String(template.weight) : '',
|
||||
caloriesPer100g: template.caloriesPer100g != null ? String(template.caloriesPer100g) : '',
|
||||
calories: template.calories != null ? String(template.calories) : '',
|
||||
price: formatPriceInput(template.price),
|
||||
pricePer100g: formatPriceInput(template.pricePer100g),
|
||||
note: template.note ?? '',
|
||||
});
|
||||
setEdited(template);
|
||||
globalThis.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
|
||||
};
|
||||
|
||||
/** Živý náhled toho, co šablona při použití založí. */
|
||||
const preview = deriveAmounts(
|
||||
parsePriceInput(form.price),
|
||||
parsePriceInput(form.pricePer100g),
|
||||
parseIntInput(form.weight),
|
||||
parseIntInput(form.caloriesPer100g));
|
||||
const previewCalories = preview.calories ?? parseIntInput(form.calories);
|
||||
const groupList = MEAL_TEMPLATE_KINDS_IN_ORDER
|
||||
.map(kind => ({ kind, templates: templates.filter(template => template.kind === kind) }))
|
||||
.filter(group => group.templates.length > 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<p className="text-body-secondary small">
|
||||
Šablona jídla je opakovaně jedené jídlo, které v přehledu dne založíte jedním
|
||||
kliknutím. Stačí název; gramáž, kalorie a cena se vyplňují podle toho, co o jídle
|
||||
víte. U domácích jídel jde do poznámky zapsat i postup přípravy.
|
||||
Šablona jídla se v přehledu dne založí jedním kliknutím, nebo se nabídne, když začnete
|
||||
psát název jídla. <strong>Hotové jídlo</strong> je objednávka nebo koupená věc, u které si
|
||||
jen pamatujete kalorie a cenu. <strong>Recept</strong> je vařené jídlo — zapíšete suroviny
|
||||
a postup a kalorie porce se spočítají samy.
|
||||
</p>
|
||||
|
||||
{loading && (
|
||||
@@ -141,185 +73,27 @@ const MealTemplatesPanel = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && templates.map(template => {
|
||||
const derived = deriveAmounts(
|
||||
template.price, template.pricePer100g, template.weight, template.caloriesPer100g);
|
||||
const calories = derived.calories ?? template.calories;
|
||||
return (
|
||||
<div className="card-panel template-card" key={template.id}>
|
||||
<div className="template-head">
|
||||
<div className="template-title">
|
||||
{template.name}
|
||||
{template.mealType && (
|
||||
<span className="tag">
|
||||
{MEAL_TYPE_ICONS[template.mealType]} {MEAL_TYPE_NAMES[template.mealType]}
|
||||
</span>
|
||||
)}
|
||||
{template.source && <span className="tag">{template.source}</span>}
|
||||
{derived.weight != null && <span className="tag">{formatWeight(derived.weight)}</span>}
|
||||
{template.note && <span className="tag">s postupem</span>}
|
||||
</div>
|
||||
{calories != null && (
|
||||
<span className="template-calories">{formatCalories(calories)}</span>
|
||||
)}
|
||||
{template.price != null && (
|
||||
<span className="meal-template-price">{formatPrice(template.price)}</span>
|
||||
)}
|
||||
<button className="btn-icon" onClick={() => edit(template)} title="Upravit" aria-label="Upravit šablonu">
|
||||
<FontAwesomeIcon icon={faPenToSquare} />
|
||||
</button>
|
||||
<button
|
||||
className="btn-icon danger"
|
||||
onClick={() => remove(template.id)}
|
||||
disabled={busy}
|
||||
title="Smazat"
|
||||
aria-label="Smazat šablonu"
|
||||
>
|
||||
<FontAwesomeIcon icon={faTrash} />
|
||||
</button>
|
||||
</div>
|
||||
{template.note && <p className="meal-template-note">{template.note}</p>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<div className="card-panel template-form">
|
||||
<h2 className="chart-title">{editedId ? 'Úprava šablony jídla' : 'Nová šablona jídla'}</h2>
|
||||
|
||||
{error && <Alert variant="danger" className="py-2 small">{error}</Alert>}
|
||||
|
||||
<div className="row g-3 mb-3">
|
||||
<div className="col-sm-5">
|
||||
<Form.Label>Název</Form.Label>
|
||||
<Form.Control
|
||||
value={form.name}
|
||||
placeholder="Např. Těstovinový salát"
|
||||
onChange={event => update({ name: event.target.value })}
|
||||
{!loading && groupList.map(group => (
|
||||
<div key={group.kind}>
|
||||
<h3 className="apply-template-group-title">{MEAL_TEMPLATE_KIND_NAMES[group.kind]}</h3>
|
||||
{group.templates.map(template => (
|
||||
<MealTemplateCard
|
||||
key={template.id}
|
||||
template={template}
|
||||
busy={busy}
|
||||
onEdit={() => edit(template)}
|
||||
onDelete={() => remove(template.id)}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-sm-4">
|
||||
<Form.Label>Zdroj</Form.Label>
|
||||
<Form.Control
|
||||
value={form.source}
|
||||
placeholder="Chefie, doma…"
|
||||
onChange={event => update({ source: event.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Chod</Form.Label>
|
||||
<Form.Select
|
||||
value={form.mealType}
|
||||
onChange={event => update({ mealType: event.target.value as MealType | '' })}
|
||||
>
|
||||
<option value="">— vybrat při použití —</option>
|
||||
{MEAL_TYPES_IN_ORDER.map(type => (
|
||||
<option key={type} value={type}>
|
||||
{MEAL_TYPE_ICONS[type]} {MEAL_TYPE_NAMES[type]}
|
||||
</option>
|
||||
))}
|
||||
</Form.Select>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
|
||||
<fieldset className="meal-fieldset mb-3">
|
||||
<legend>Kalorie, gramáž a cena</legend>
|
||||
<div className="row g-3">
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Gramáž</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.weight}
|
||||
placeholder="350"
|
||||
onChange={event => update({ weight: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">g</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Energie na 100 g</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.caloriesPer100g}
|
||||
placeholder="160"
|
||||
onChange={event => update({ caloriesPer100g: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">kcal</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Cena</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={form.price}
|
||||
placeholder="129,00"
|
||||
onChange={event => update({ price: event.target.value })}
|
||||
/>
|
||||
<span className="input-group-text">Kč</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Cena za 100 g</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="decimal"
|
||||
value={form.pricePer100g}
|
||||
placeholder="volitelné"
|
||||
onChange={event => update({ pricePer100g: event.target.value })}
|
||||
/>
|
||||
<span className="input-group-text">Kč</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Kalorie celé porce dávají smysl jen tam, kde se nedají dopočítat z gramáže */}
|
||||
{preview.calories == null && (
|
||||
<div className="row g-3 mt-0">
|
||||
<div className="col-sm-3">
|
||||
<Form.Label>Kalorie porce</Form.Label>
|
||||
<div className="input-group">
|
||||
<Form.Control
|
||||
inputMode="numeric"
|
||||
value={form.calories}
|
||||
placeholder="volitelné"
|
||||
onChange={event => update({ calories: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<span className="input-group-text">kcal</span>
|
||||
</div>
|
||||
<Form.Text>když neznáte gramáž ani hodnotu na 100 g</Form.Text>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
<Form.Group className="mb-3">
|
||||
<Form.Label>Poznámka / postup</Form.Label>
|
||||
<Form.Control
|
||||
as="textarea"
|
||||
rows={3}
|
||||
value={form.note}
|
||||
placeholder="U domácích jídel sem lze zapsat recept…"
|
||||
onChange={event => update({ note: event.target.value })}
|
||||
/>
|
||||
</Form.Group>
|
||||
|
||||
<div className="workout-form-footer">
|
||||
{previewCalories != null && (
|
||||
<span className="workout-draft-calories">
|
||||
{preview.weight != null && `${formatWeight(preview.weight)} · `}
|
||||
{formatCalories(previewCalories)}
|
||||
</span>
|
||||
)}
|
||||
{editedId && (
|
||||
<Button variant="outline-secondary" size="sm" onClick={() => resetForm()}>Zrušit úpravu</Button>
|
||||
)}
|
||||
<Button size="sm" onClick={() => save()} disabled={!canSave}>
|
||||
{editedId ? 'Uložit změny' : 'Vytvořit šablonu'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<MealTemplateForm
|
||||
key={`${edited?.id ?? 'new'}-${formVersion}`}
|
||||
template={edited}
|
||||
onSaved={saved => { setTemplates(saved); setEdited(undefined); setFormVersion(current => current + 1); }}
|
||||
onCancel={() => setEdited(undefined)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -140,3 +140,69 @@
|
||||
color: var(--ft-warning);
|
||||
padding: 3px 0;
|
||||
}
|
||||
|
||||
// Náhled importu po dnech — u každého dne i jídla, která v něm už jsou
|
||||
.import-preview {
|
||||
font-size: 0.85rem;
|
||||
|
||||
.import-preview-day {
|
||||
padding: 6px 0;
|
||||
border-top: 1px solid var(--ft-border-light);
|
||||
}
|
||||
|
||||
.import-preview-day-title {
|
||||
font-weight: 700;
|
||||
color: var(--ft-text);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.import-preview-row {
|
||||
margin-left: 22px;
|
||||
|
||||
.form-check-label {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.import-preview-existing {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-left: 22px;
|
||||
padding: 1px 0;
|
||||
color: var(--ft-text-muted);
|
||||
|
||||
&.replaced .import-preview-name {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
}
|
||||
|
||||
.import-preview-note {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.import-preview-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.import-preview-price {
|
||||
margin-left: auto;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.import-preview-skipped {
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--ft-border-light);
|
||||
color: var(--ft-text-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.import-preview-toolbar {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
@@ -92,3 +92,55 @@
|
||||
color: var(--ft-text-secondary);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
// Řádek suroviny receptu — název se roztáhne, číselná pole mají pevnou šířku
|
||||
.recipe-ingredient-row {
|
||||
align-items: center;
|
||||
|
||||
.recipe-ingredient-weight {
|
||||
width: 110px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.recipe-ingredient-rate {
|
||||
width: 100px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.recipe-ingredient-calories {
|
||||
width: 90px;
|
||||
flex: 0 0 auto;
|
||||
font-weight: 600;
|
||||
font-size: 0.87rem;
|
||||
color: var(--ft-warning);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.recipe-ingredient-price {
|
||||
width: 110px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
flex-wrap: wrap;
|
||||
|
||||
.recipe-ingredient-weight,
|
||||
.recipe-ingredient-rate,
|
||||
.recipe-ingredient-calories,
|
||||
.recipe-ingredient-price {
|
||||
width: auto;
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.recipe-summary {
|
||||
margin-top: 8px;
|
||||
font-size: 0.87rem;
|
||||
font-weight: 600;
|
||||
color: var(--ft-text-secondary);
|
||||
|
||||
.recipe-summary-portion {
|
||||
color: var(--ft-primary);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,10 @@ import {
|
||||
deleteWorkoutTemplate, getWorkoutTemplates, saveWorkoutTemplate,
|
||||
} from "../../../types";
|
||||
import { ACTIVITY_PRESETS, ACTIVITY_UNITS_IN_ORDER, ACTIVITY_UNIT_NAMES, ACTIVITY_UNIT_SHORT } from "../enums";
|
||||
import { deriveActivityCalories, formatCalories, formatQuantityWithSets, parseIntInput } from "../Utils";
|
||||
import {
|
||||
deriveActivityCalories, formatCalories, formatExtraWeight, formatKgInput, formatQuantityWithSets,
|
||||
parseIntInput, parseWeightKgInput,
|
||||
} from "../Utils";
|
||||
|
||||
/** Rozpracovaná položka — hodnoty jsou texty, protože se editují v polích. */
|
||||
type DraftItem = {
|
||||
@@ -17,6 +20,8 @@ type DraftItem = {
|
||||
quantity: string,
|
||||
sets: string,
|
||||
caloriesPer100Units: string,
|
||||
/** Dodatečná zátěž v kg, jak ji uživatel píše */
|
||||
extraWeight: string,
|
||||
templateRefId: string,
|
||||
};
|
||||
|
||||
@@ -27,6 +32,7 @@ const emptyExercise = (): DraftItem => ({
|
||||
quantity: '',
|
||||
sets: '',
|
||||
caloriesPer100Units: '',
|
||||
extraWeight: '',
|
||||
templateRefId: '',
|
||||
});
|
||||
|
||||
@@ -107,6 +113,9 @@ const WorkoutTemplatesPanel = () => {
|
||||
...(parseIntInput(item.caloriesPer100Units) != null
|
||||
? { caloriesPer100Units: parseIntInput(item.caloriesPer100Units) }
|
||||
: {}),
|
||||
...(parseWeightKgInput(item.extraWeight) != null
|
||||
? { extraWeightGrams: parseWeightKgInput(item.extraWeight) }
|
||||
: {}),
|
||||
});
|
||||
|
||||
const canSave = name.trim().length > 0 && toItems().length > 0 && !busy;
|
||||
@@ -153,6 +162,7 @@ const WorkoutTemplatesPanel = () => {
|
||||
quantity: item.quantity != null ? String(item.quantity) : '',
|
||||
sets: item.sets != null ? String(item.sets) : '',
|
||||
caloriesPer100Units: item.caloriesPer100Units != null ? String(item.caloriesPer100Units) : '',
|
||||
extraWeight: formatKgInput(item.extraWeightGrams),
|
||||
templateRefId: '',
|
||||
}));
|
||||
globalThis.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
|
||||
@@ -172,7 +182,8 @@ const WorkoutTemplatesPanel = () => {
|
||||
<p className="text-body-secondary small">
|
||||
Šablona je pojmenovaný seznam cviků, který jde v přehledu dne založit jedním kliknutím.
|
||||
Mezi položky lze zařadit i jinou šablonu — třeba rozcvičku, kterou máte v každém tréninku.
|
||||
Zanoření je kvůli jednoduchosti jen na jednu úroveň.
|
||||
Zanoření je kvůli jednoduchosti jen na jednu úroveň. U cviku jde zapsat
|
||||
i dodatečnou zátěž (činky, vesta) — je to jen informace, kalorie nemění.
|
||||
</p>
|
||||
|
||||
{loading && (
|
||||
@@ -235,6 +246,11 @@ const WorkoutTemplatesPanel = () => {
|
||||
<span className="template-item-quantity">
|
||||
{formatQuantityWithSets(item.quantity ?? 0, ACTIVITY_UNIT_SHORT[item.unit!], item.sets)}
|
||||
</span>
|
||||
{!!item.extraWeightGrams && (
|
||||
<span className="tag" title="Dodatečná zátěž">
|
||||
{formatExtraWeight(item.extraWeightGrams)}
|
||||
</span>
|
||||
)}
|
||||
<span className="template-item-calories">
|
||||
{formatCalories(deriveActivityCalories(item.quantity, item.caloriesPer100Units, item.sets))}
|
||||
</span>
|
||||
@@ -318,6 +334,14 @@ const WorkoutTemplatesPanel = () => {
|
||||
placeholder="kcal/100"
|
||||
onChange={event => updateItem(index, { caloriesPer100Units: event.target.value.replace(/\D/g, '') })}
|
||||
/>
|
||||
<Form.Control
|
||||
className="workout-item-weight"
|
||||
inputMode="decimal"
|
||||
value={item.extraWeight}
|
||||
placeholder="zátěž kg"
|
||||
title="Dodatečná zátěž v kg — činky, vesta. Kalorie nemění."
|
||||
onChange={event => updateItem(index, { extraWeight: event.target.value })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
|
||||
Reference in new issue
Block a user