1
0
Fork 0
mirror of https://github.com/s-frick/effigenix.git synced 2026-03-28 11:59:35 +01:00

feat(production): TUI-Screens für Zutaten verwalten + Rezept aktivieren

This commit is contained in:
Sebastian Frick 2026-02-19 21:48:33 +01:00
parent 63f51bc1a9
commit 5224001dd7
6 changed files with 241 additions and 20 deletions

View file

@ -42,6 +42,7 @@ import { RecipeListScreen } from './components/production/RecipeListScreen.js';
import { RecipeCreateScreen } from './components/production/RecipeCreateScreen.js'; import { RecipeCreateScreen } from './components/production/RecipeCreateScreen.js';
import { RecipeDetailScreen } from './components/production/RecipeDetailScreen.js'; import { RecipeDetailScreen } from './components/production/RecipeDetailScreen.js';
import { AddProductionStepScreen } from './components/production/AddProductionStepScreen.js'; import { AddProductionStepScreen } from './components/production/AddProductionStepScreen.js';
import { AddIngredientScreen } from './components/production/AddIngredientScreen.js';
function ScreenRouter() { function ScreenRouter() {
const { isAuthenticated, loading } = useAuth(); const { isAuthenticated, loading } = useAuth();
@ -109,6 +110,7 @@ function ScreenRouter() {
{current === 'recipe-create' && <RecipeCreateScreen />} {current === 'recipe-create' && <RecipeCreateScreen />}
{current === 'recipe-detail' && <RecipeDetailScreen />} {current === 'recipe-detail' && <RecipeDetailScreen />}
{current === 'recipe-add-production-step' && <AddProductionStepScreen />} {current === 'recipe-add-production-step' && <AddProductionStepScreen />}
{current === 'recipe-add-ingredient' && <AddIngredientScreen />}
</MainLayout> </MainLayout>
); );
} }

View file

@ -0,0 +1,129 @@
import { useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useNavigation } from '../../state/navigation-context.js';
import { FormInput } from '../shared/FormInput.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js';
import { ErrorDisplay } from '../shared/ErrorDisplay.js';
import { client } from '../../utils/api-client.js';
type Field = 'position' | 'articleId' | 'quantity' | 'uom' | 'subRecipeId' | 'substitutable';
const FIELDS: Field[] = ['position', 'articleId', 'quantity', 'uom', 'subRecipeId', 'substitutable'];
const FIELD_LABELS: Record<Field, string> = {
position: 'Position (optional)',
articleId: 'Artikel-ID *',
quantity: 'Menge *',
uom: 'Einheit *',
subRecipeId: 'Sub-Rezept-ID (optional)',
substitutable: 'Austauschbar (ja/nein, optional)',
};
function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : 'Unbekannter Fehler';
}
export function AddIngredientScreen() {
const { params, navigate, back } = useNavigation();
const recipeId = params['recipeId'] ?? '';
const [values, setValues] = useState<Record<Field, string>>({
position: '', articleId: '', quantity: '', uom: '', subRecipeId: '', substitutable: '',
});
const [activeField, setActiveField] = useState<Field>('position');
const [fieldErrors, setFieldErrors] = useState<Partial<Record<Field, string>>>({});
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const setField = (field: Field) => (value: string) => {
setValues((v) => ({ ...v, [field]: value }));
};
useInput((_input, key) => {
if (loading) return;
if (key.tab || key.downArrow) {
setActiveField((f) => {
const idx = FIELDS.indexOf(f);
return FIELDS[(idx + 1) % FIELDS.length] ?? f;
});
}
if (key.upArrow) {
setActiveField((f) => {
const idx = FIELDS.indexOf(f);
return FIELDS[(idx - 1 + FIELDS.length) % FIELDS.length] ?? f;
});
}
if (key.escape) back();
});
const handleSubmit = async () => {
const errors: Partial<Record<Field, string>> = {};
if (!values.articleId.trim()) errors.articleId = 'Artikel-ID ist erforderlich.';
if (!values.quantity.trim()) errors.quantity = 'Menge ist erforderlich.';
if (values.quantity.trim() && isNaN(Number(values.quantity))) errors.quantity = 'Muss eine Zahl sein.';
if (!values.uom.trim()) errors.uom = 'Einheit ist erforderlich.';
if (values.position.trim() && (!Number.isInteger(Number(values.position)) || Number(values.position) < 1)) {
errors.position = 'Muss eine positive Ganzzahl sein.';
}
if (values.substitutable.trim() && !['ja', 'nein'].includes(values.substitutable.trim().toLowerCase())) {
errors.substitutable = 'Muss "ja" oder "nein" sein.';
}
setFieldErrors(errors);
if (Object.keys(errors).length > 0) return;
setLoading(true);
setError(null);
try {
await client.recipes.addIngredient(recipeId, {
articleId: values.articleId.trim(),
quantity: values.quantity.trim(),
uom: values.uom.trim(),
...(values.position.trim() ? { position: Number(values.position) } : {}),
...(values.subRecipeId.trim() ? { subRecipeId: values.subRecipeId.trim() } : {}),
...(values.substitutable.trim() ? { substitutable: values.substitutable.trim().toLowerCase() === 'ja' } : {}),
});
navigate('recipe-detail', { recipeId });
} catch (err: unknown) {
setError(errorMessage(err));
setLoading(false);
}
};
const handleFieldSubmit = (field: Field) => (_value: string) => {
const idx = FIELDS.indexOf(field);
if (idx < FIELDS.length - 1) {
setActiveField(FIELDS[idx + 1] ?? field);
} else {
void handleSubmit();
}
};
if (!recipeId) return <ErrorDisplay message="Keine Rezept-ID vorhanden." onDismiss={back} />;
if (loading) return <Box paddingY={2}><LoadingSpinner label="Zutat wird hinzugefügt..." /></Box>;
return (
<Box flexDirection="column" gap={1}>
<Text color="cyan" bold>Zutat hinzufügen</Text>
{error && <ErrorDisplay message={error} onDismiss={() => setError(null)} />}
<Box flexDirection="column" gap={1} width={60}>
{FIELDS.map((field) => (
<FormInput
key={field}
label={FIELD_LABELS[field]}
value={values[field]}
onChange={setField(field)}
onSubmit={handleFieldSubmit(field)}
focus={activeField === field}
{...(fieldErrors[field] ? { error: fieldErrors[field] } : {})}
/>
))}
</Box>
<Box marginTop={1}>
<Text color="gray" dimColor>
Tab/ Feld wechseln · Enter auf letztem Feld speichern · Escape Abbrechen
</Text>
</Box>
</Box>
);
}

View file

@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { Box, Text, useInput } from 'ink'; import { Box, Text, useInput } from 'ink';
import type { RecipeDTO, RecipeType, ProductionStepDTO } from '@effigenix/api-client'; import type { RecipeDTO, RecipeType, ProductionStepDTO, IngredientDTO } from '@effigenix/api-client';
import { RECIPE_TYPE_LABELS } from '@effigenix/api-client'; import { RECIPE_TYPE_LABELS } from '@effigenix/api-client';
import { useNavigation } from '../../state/navigation-context.js'; import { useNavigation } from '../../state/navigation-context.js';
import { LoadingSpinner } from '../shared/LoadingSpinner.js'; import { LoadingSpinner } from '../shared/LoadingSpinner.js';
@ -9,8 +9,8 @@ import { SuccessDisplay } from '../shared/SuccessDisplay.js';
import { ConfirmDialog } from '../shared/ConfirmDialog.js'; import { ConfirmDialog } from '../shared/ConfirmDialog.js';
import { client } from '../../utils/api-client.js'; import { client } from '../../utils/api-client.js';
type MenuAction = 'add-step' | 'remove-step' | 'back'; type MenuAction = 'add-ingredient' | 'remove-ingredient' | 'add-step' | 'remove-step' | 'activate' | 'back';
type Mode = 'menu' | 'select-step-to-remove' | 'confirm-remove'; type Mode = 'menu' | 'select-step-to-remove' | 'confirm-remove' | 'select-ingredient-to-remove' | 'confirm-remove-ingredient' | 'confirm-activate';
function errorMessage(err: unknown): string { function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : 'Unbekannter Fehler'; return err instanceof Error ? err.message : 'Unbekannter Fehler';
@ -29,25 +29,32 @@ export function RecipeDetailScreen() {
const [successMessage, setSuccessMessage] = useState<string | null>(null); const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [selectedStepIndex, setSelectedStepIndex] = useState(0); const [selectedStepIndex, setSelectedStepIndex] = useState(0);
const [stepToRemove, setStepToRemove] = useState<ProductionStepDTO | null>(null); const [stepToRemove, setStepToRemove] = useState<ProductionStepDTO | null>(null);
const [selectedIngredientIndex, setSelectedIngredientIndex] = useState(0);
const [ingredientToRemove, setIngredientToRemove] = useState<IngredientDTO | null>(null);
const isDraft = recipe?.status === 'DRAFT'; const isDraft = recipe?.status === 'DRAFT';
const menuItems: { id: MenuAction; label: string }[] = [ const menuItems: { id: MenuAction; label: string }[] = [
...(isDraft ? [ ...(isDraft ? [
{ id: 'add-ingredient' as const, label: '[Zutat hinzufügen]' },
{ id: 'remove-ingredient' as const, label: '[Zutat entfernen]' },
{ id: 'add-step' as const, label: '[Schritt hinzufügen]' }, { id: 'add-step' as const, label: '[Schritt hinzufügen]' },
{ id: 'remove-step' as const, label: '[Schritt entfernen]' }, { id: 'remove-step' as const, label: '[Schritt entfernen]' },
{ id: 'activate' as const, label: '[Rezept aktivieren]' },
] : []), ] : []),
{ id: 'back' as const, label: '[Zurück]' }, { id: 'back' as const, label: '[Zurück]' },
]; ];
useEffect(() => { const clampedAction = Math.min(selectedAction, menuItems.length - 1);
setSelectedAction(0);
}, [isDraft]);
const sortedSteps = recipe?.productionSteps const sortedSteps = recipe?.productionSteps
? [...recipe.productionSteps].sort((a, b) => a.stepNumber - b.stepNumber) ? [...recipe.productionSteps].sort((a, b) => a.stepNumber - b.stepNumber)
: []; : [];
const sortedIngredients = recipe?.ingredients
? [...recipe.ingredients].sort((a, b) => a.position - b.position)
: [];
const loadRecipe = useCallback(() => { const loadRecipe = useCallback(() => {
setLoading(true); setLoading(true);
setError(null); setError(null);
@ -77,14 +84,35 @@ export function RecipeDetailScreen() {
} }
if (key.escape) { setMode('menu'); setSelectedStepIndex(0); } if (key.escape) { setMode('menu'); setSelectedStepIndex(0); }
} }
if (mode === 'select-ingredient-to-remove') {
if (key.upArrow) setSelectedIngredientIndex((i) => Math.max(0, i - 1));
if (key.downArrow) setSelectedIngredientIndex((i) => Math.min(sortedIngredients.length - 1, i + 1));
if (key.return && sortedIngredients.length > 0) {
setIngredientToRemove(sortedIngredients[selectedIngredientIndex] ?? null);
setMode('confirm-remove-ingredient');
}
if (key.escape) { setMode('menu'); setSelectedIngredientIndex(0); }
}
}); });
const handleAction = async () => { const handleAction = async () => {
if (!recipe) return; if (!recipe) return;
const item = menuItems[selectedAction]; const item = menuItems[clampedAction];
if (!item) return; if (!item) return;
switch (item.id) { switch (item.id) {
case 'add-ingredient':
navigate('recipe-add-ingredient', { recipeId });
break;
case 'remove-ingredient':
if (sortedIngredients.length === 0) {
setError('Keine Zutaten vorhanden.');
return;
}
setSelectedIngredientIndex(0);
setMode('select-ingredient-to-remove');
break;
case 'add-step': case 'add-step':
navigate('recipe-add-production-step', { recipeId }); navigate('recipe-add-production-step', { recipeId });
break; break;
@ -96,6 +124,9 @@ export function RecipeDetailScreen() {
setSelectedStepIndex(0); setSelectedStepIndex(0);
setMode('select-step-to-remove'); setMode('select-step-to-remove');
break; break;
case 'activate':
setMode('confirm-activate');
break;
case 'back': case 'back':
back(); back();
break; break;
@ -118,6 +149,36 @@ export function RecipeDetailScreen() {
setStepToRemove(null); setStepToRemove(null);
}, [recipe, stepToRemove]); }, [recipe, stepToRemove]);
const handleRemoveIngredient = useCallback(async () => {
if (!recipe || !ingredientToRemove) return;
setMode('menu');
setActionLoading(true);
try {
await client.recipes.removeIngredient(recipe.id, ingredientToRemove.id);
const updated = await client.recipes.getById(recipe.id);
setRecipe(updated);
setSuccessMessage(`Zutat (Position ${ingredientToRemove.position}) entfernt.`);
} catch (err: unknown) {
setError(errorMessage(err));
}
setActionLoading(false);
setIngredientToRemove(null);
}, [recipe, ingredientToRemove]);
const handleActivate = useCallback(async () => {
if (!recipe) return;
setMode('menu');
setActionLoading(true);
try {
const updated = await client.recipes.activateRecipe(recipe.id);
setRecipe(updated);
setSuccessMessage('Rezept wurde aktiviert.');
} catch (err: unknown) {
setError(errorMessage(err));
}
setActionLoading(false);
}, [recipe]);
if (loading) return <LoadingSpinner label="Lade Rezept..." />; if (loading) return <LoadingSpinner label="Lade Rezept..." />;
if (error && !recipe) return <ErrorDisplay message={error} onDismiss={back} />; if (error && !recipe) return <ErrorDisplay message={error} onDismiss={back} />;
if (!recipe) return <Text color="red">Rezept nicht gefunden.</Text>; if (!recipe) return <Text color="red">Rezept nicht gefunden.</Text>;
@ -208,6 +269,28 @@ export function RecipeDetailScreen() {
</Box> </Box>
)} )}
{mode === 'select-ingredient-to-remove' && (
<Box flexDirection="column">
<Text color="yellow" bold>Zutat zum Entfernen auswählen:</Text>
{sortedIngredients.map((ing, index) => (
<Box key={ing.id}>
<Text color={index === selectedIngredientIndex ? 'cyan' : 'white'}>
{index === selectedIngredientIndex ? '▶ ' : ' '}Position {ing.position}: {ing.quantity} {ing.uom} (Artikel: {ing.articleId})
</Text>
</Box>
))}
<Text color="gray" dimColor> auswählen · Enter bestätigen · Escape abbrechen</Text>
</Box>
)}
{mode === 'confirm-remove-ingredient' && ingredientToRemove && (
<ConfirmDialog
message={`Zutat an Position ${ingredientToRemove.position} (Artikel: ${ingredientToRemove.articleId}) entfernen?`}
onConfirm={() => void handleRemoveIngredient()}
onCancel={() => { setMode('menu'); setIngredientToRemove(null); }}
/>
)}
{mode === 'confirm-remove' && stepToRemove && ( {mode === 'confirm-remove' && stepToRemove && (
<ConfirmDialog <ConfirmDialog
message={`Schritt ${stepToRemove.stepNumber} "${stepToRemove.description}" entfernen?`} message={`Schritt ${stepToRemove.stepNumber} "${stepToRemove.description}" entfernen?`}
@ -216,14 +299,22 @@ export function RecipeDetailScreen() {
/> />
)} )}
{mode === 'confirm-activate' && (
<ConfirmDialog
message="Rezept wirklich aktivieren? Der Status wechselt zu ACTIVE."
onConfirm={() => void handleActivate()}
onCancel={() => setMode('menu')}
/>
)}
{mode === 'menu' && ( {mode === 'menu' && (
<Box flexDirection="column"> <Box flexDirection="column">
<Text color="gray" bold>Aktionen:</Text> <Text color="gray" bold>Aktionen:</Text>
{actionLoading && <LoadingSpinner label="Aktion wird ausgeführt..." />} {actionLoading && <LoadingSpinner label="Aktion wird ausgeführt..." />}
{!actionLoading && menuItems.map((item, index) => ( {!actionLoading && menuItems.map((item, index) => (
<Box key={item.id}> <Box key={item.id}>
<Text color={index === selectedAction ? 'cyan' : 'white'}> <Text color={index === clampedAction ? 'cyan' : 'white'}>
{index === selectedAction ? '▶ ' : ' '}{item.label} {index === clampedAction ? '▶ ' : ' '}{item.label}
</Text> </Text>
</Box> </Box>
))} ))}

View file

@ -38,7 +38,8 @@ export type Screen =
| 'recipe-list' | 'recipe-list'
| 'recipe-create' | 'recipe-create'
| 'recipe-detail' | 'recipe-detail'
| 'recipe-add-production-step'; | 'recipe-add-production-step'
| 'recipe-add-ingredient';
interface NavigationState { interface NavigationState {
current: Screen; current: Screen;

View file

@ -1,9 +1,4 @@
/** /** Recipes resource Production BC. */
* Recipes resource Production BC.
* Endpoints: POST /api/recipes,
* POST /api/recipes/{id}/ingredients,
* DELETE /api/recipes/{id}/ingredients/{ingredientId}
*/
import type { AxiosInstance } from 'axios'; import type { AxiosInstance } from 'axios';
import type { import type {
@ -59,10 +54,8 @@ export function createRecipesResource(client: AxiosInstance) {
return res.data; return res.data;
}, },
async removeIngredient(recipeId: string, ingredientId: string): Promise<RecipeDTO> { async removeIngredient(recipeId: string, ingredientId: string): Promise<void> {
await client.delete(`${BASE}/${recipeId}/ingredients/${ingredientId}`); await client.delete(`${BASE}/${recipeId}/ingredients/${ingredientId}`);
const res = await client.get<RecipeDTO>(`${BASE}/${recipeId}`);
return res.data;
}, },
async addProductionStep(id: string, request: AddProductionStepRequest): Promise<RecipeDTO> { async addProductionStep(id: string, request: AddProductionStepRequest): Promise<RecipeDTO> {
@ -73,6 +66,11 @@ export function createRecipesResource(client: AxiosInstance) {
async removeProductionStep(id: string, stepNumber: number): Promise<void> { async removeProductionStep(id: string, stepNumber: number): Promise<void> {
await client.delete(`${BASE}/${id}/steps/${stepNumber}`); await client.delete(`${BASE}/${id}/steps/${stepNumber}`);
}, },
async activateRecipe(id: string): Promise<RecipeDTO> {
const res = await client.post<RecipeDTO>(`${BASE}/${id}/activate`);
return res.data;
},
}; };
} }