add lucide-react dependency and update form handling in MainForm

- Added lucide-react to package dependencies
- Refactored MainForm to improve form handling and user selection
- Removed SuccessPage component and related logic
- Updated localization files to include new keys for invoice details
- Created interfaces for form data and messages
This commit is contained in:
2026-05-10 19:39:32 +02:00
parent 746530ae4c
commit 5c035ba1c0
8 changed files with 413 additions and 581 deletions
+248 -391
View File
@@ -1,120 +1,138 @@
import {
TextField,
FormControlLabel,
Checkbox,
Button,
Alert,
CircularProgress,
Autocomplete,
Chip,
Box,
Paper,
Typography,
IconButton,
} from "@mui/material";
import { useTranslation } from "../../node_modules/react-i18next";
import { useTranslation } from "react-i18next";
import { useState, useEffect } from "react";
import { submitFormData } from "../utils/sender";
import Cookies from "../../node_modules/@types/js-cookie";
import * as React from "react";
import TranslateIcon from "@mui/icons-material/Translate";
import Cookies from "js-cookie";
import { Languages } from "lucide-react";
import {
Sheet,
Input,
Button,
Checkbox,
Chip,
IconButton,
Alert,
Typography,
FormControl,
FormLabel,
Autocomplete,
} from "@mui/joy";
import { submitFormData } from "../utils/sender";
import { API_BASE } from "../config/api.config";
import type { FormData, Message } from "../config/interfaces.config";
interface Message {
type: "error" | "info" | "success" | "warning";
headline: string;
text: string;
}
const PAYMENT_METHODS = ["bar", "paypal", "andere"] as const;
const PAYMENT_LABELS: Record<string, string> = {
bar: "Cash",
paypal: "PayPal",
andere: "Transfer",
};
const DEFAULT_FORM: FormData = {
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
tickets: 1,
companyName: "",
cmpFirstName: "",
cpmLastName: "",
cpmEmail: "",
cpmPhoneNumber: "",
street: "",
postalCode: "",
paymentMethod: "",
};
// ─── Field component lives OUTSIDE MainForm so React doesn't treat it as a
// new component type on every render, which would cause inputs to lose focus.
const Field = ({
label,
name,
type = "text",
required = true,
formData,
onChange,
}: {
label: string;
name: keyof FormData;
type?: string;
required?: boolean;
formData: FormData;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}) => (
<FormControl required={required}>
<FormLabel>{label}</FormLabel>
<Input
name={name}
type={type}
value={formData[name] as string}
onChange={onChange}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
</FormControl>
);
export const MainForm = () => {
const { t, i18n } = useTranslation();
const [invoice, setInvoice] = useState(false);
const [msg, setMsg] = useState<Message | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [nextID, setNextID] = useState<number | null>(null);
const [formData, setFormData] = useState({
firstName: "",
lastName: "",
email: "",
phoneNumber: "",
tickets: 1,
companyName: "",
cmpFirstName: "",
cpmLastName: "",
cpmEmail: "",
cpmPhoneNumber: "",
street: "",
postalCode: "",
paymentMethod: "",
});
const [users, setUsers] = useState<string[]>([]);
const [selectedUser, setSelectedUser] = useState<string | null>(null);
const changeTranslation = () => {
const clientLng = i18n.language;
if (clientLng === "en") {
i18n.changeLanguage("de");
} else if (clientLng === "de") {
i18n.changeLanguage("en");
} else {
setMsg({
type: "error",
headline: "Error",
text: "Cannot change langugage.",
});
}
};
useEffect(() => {
// Fetch user data or any other data needed for the form
try {
const fetchUsers = async () => {
const response = await fetch(`${API_BASE}/default/users`);
const data = await response.json();
setUsers(data.users);
};
fetchUsers();
console.log(users);
} catch (error) {
setMsg({
type: "error",
headline: t("error"),
text: t("failed-to-load-users"),
});
console.error("Error fetching users:", error);
}
if (Cookies.get("selectedUser")) {
const cookieUser = Cookies.get("selectedUser")!;
setSelectedUser(cookieUser);
confirmUser(cookieUser);
}
}, [isLoading]);
const [formData, setFormData] = useState<FormData>(DEFAULT_FORM);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const confirmUser = async (selectedUser: string) => {
const confirmUser = async (username: string) => {
try {
const response = await fetch(
`${API_BASE}/default/confirm-user?username=${selectedUser}`,
const res = await fetch(
`${API_BASE}/default/confirm-user?username=${username}`,
);
const data = await response.json();
const data = await res.json();
setNextID(data.nextID);
} catch (error) {
console.error("Error confirming user:", error);
}
};
const handleUserSelection = (selectedUser: string | null) => {
if (!selectedUser) return;
setSelectedUser(selectedUser);
confirmUser(selectedUser);
Cookies.set("selectedUser", selectedUser);
const handleUserSelection = (username: string | null) => {
if (!username) return;
setSelectedUser(username);
confirmUser(username);
Cookies.set("selectedUser", username);
};
const toggleLanguage = () => {
i18n.changeLanguage(i18n.language === "en" ? "de" : "en");
};
useEffect(() => {
(async () => {
try {
const res = await fetch(`${API_BASE}/default/users`);
const data = await res.json();
setUsers(data.users);
} catch {
setMsg({
type: "danger",
headline: t("error"),
text: t("failed-to-load-users"),
});
}
})();
const cookieUser = Cookies.get("selectedUser");
if (cookieUser) {
setSelectedUser(cookieUser);
confirmUser(cookieUser);
}
}, []);
const handleSubmit = async () => {
setIsLoading(true);
try {
@@ -123,7 +141,7 @@ export const MainForm = () => {
document.location.href = `/success?id=${nextID}&tickets=${formData.tickets}`;
} else {
setMsg({
type: "error",
type: "danger",
headline: t("error"),
text: result.error || t("form-submission-failed"),
});
@@ -133,44 +151,35 @@ export const MainForm = () => {
}
};
// Shorthand so we don't repeat formData + onChange on every Field usage
const fieldProps = { formData, onChange: handleChange };
return (
<Box
className="bg-gray-100 py-10 px-4"
sx={{
minHeight: "100vh",
width: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Paper
elevation={6}
className="w-full rounded-2xl"
<div className="min-h-screen w-full flex items-center justify-center bg-gradient-to-br from-slate-100 to-blue-50 p-4">
<Sheet
variant="plain"
className="w-full"
sx={{
position: "relative",
backgroundColor: "#fff",
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)",
width: "100%",
maxWidth: {
xs: 360, // kompakte Handy-Ansicht
sm: 420, // kleine Tablets / große Phones
md: 480, // Desktop, bleibt angenehm schmal
},
padding: {
xs: "1.5rem",
sm: "2rem",
},
maxWidth: 460,
borderRadius: "24px",
p: { xs: "1.5rem", sm: "2rem" },
boxShadow: "0 24px 64px -12px rgba(0,0,0,0.18)",
background: "#fff",
}}
>
<Box sx={{ position: "absolute", top: 12, right: 12 }}>
<IconButton
onClick={() => changeTranslation()}
aria-label="translate"
>
<TranslateIcon />
</IconButton>
</Box>
{/* Language toggle */}
<IconButton
onClick={toggleLanguage}
size="sm"
variant="plain"
color="neutral"
aria-label="toggle language"
sx={{ position: "absolute", top: 12, right: 12 }}
>
<Languages size={18} />
</IconButton>
<form
onSubmit={(e) => {
e.preventDefault();
@@ -178,337 +187,185 @@ export const MainForm = () => {
}}
className="flex flex-col gap-4"
>
{/* User Selection */}
{/* User selection */}
<Autocomplete
disablePortal
options={users}
value={selectedUser}
fullWidth
renderInput={(params) => (
<TextField {...params} label={t("user")} variant="filled" />
)}
onChange={(_event, value) => handleUserSelection(value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.defaultMuiPrevented = true;
}
onChange={(_, value) => handleUserSelection(value)}
placeholder={t("user")}
variant="soft"
sx={{ borderRadius: "10px" }}
onKeyDown={(e) => {
if (e.key === "Enter") e.preventDefault();
}}
/>
{/* Next ID Chip */}
{/* Next ID badge */}
<Chip
label={`#${nextID ?? "N/A"}`}
size="md"
variant="solid"
color="primary"
sx={{
alignSelf: "flex-start",
fontWeight: 500,
fontSize: "0.9rem",
mt: 0.5,
mb: 0.5,
py: 0.5,
px: 1.25,
borderRadius: "999px",
background: "linear-gradient(135deg, #1976d2 0%, #1565c0 100%)",
fontWeight: 600,
}}
/>
>
#{nextID ?? "N/A"}
</Chip>
{/* Name Fields - Two Columns */}
<Box className="grid grid-cols-2 gap-3">
<TextField
required
id="first-name"
label={t("first-name")}
variant="filled"
value={formData.firstName}
onChange={handleChange}
name="firstName"
fullWidth
/>
<TextField
required
id="last-name"
label={t("last-name")}
variant="filled"
value={formData.lastName}
onChange={handleChange}
name="lastName"
fullWidth
/>
</Box>
{/* Name row */}
<div className="grid grid-cols-2 gap-3">
<Field label={t("first-name")} name="firstName" {...fieldProps} />
<Field label={t("last-name")} name="lastName" {...fieldProps} />
</div>
{/* Email */}
<TextField
required
id="email"
label={t("email")}
variant="filled"
type="email"
value={formData.email}
onChange={handleChange}
name="email"
fullWidth
/>
{/* Phone Number */}
<TextField
required
id="phone-number"
<Field label={t("email")} name="email" type="email" {...fieldProps} />
<Field
label={t("phone-number")}
variant="filled"
type="tel"
value={formData.phoneNumber}
onChange={handleChange}
name="phoneNumber"
fullWidth
type="tel"
{...fieldProps}
/>
{/* Tickets and Invoice Checkbox */}
<Box className="grid grid-cols-2 gap-3 items-center">
<TextField
required
id="tickets"
type="number"
label={t("tickets")}
variant="filled"
value={formData.tickets}
onChange={handleChange}
name="tickets"
fullWidth
inputProps={{ min: 1 }}
/>
<FormControlLabel
control={
<Checkbox
checked={invoice}
onChange={(e) => setInvoice(e.target.checked)}
/>
}
label={t("invoice")}
className="justify-end"
/>
</Box>
{/* Tickets + Invoice toggle */}
<div className="grid grid-cols-2 gap-3 items-end">
<FormControl required>
<FormLabel>{t("tickets")}</FormLabel>
<Input
name="tickets"
type="number"
value={formData.tickets}
onChange={handleChange}
slotProps={{ input: { min: 1 } }}
variant="soft"
sx={{ borderRadius: "10px" }}
/>
</FormControl>
<div className="flex items-center pb-2">
<Checkbox
checked={invoice}
onChange={(e) => setInvoice(e.target.checked)}
label={t("invoice")}
variant="outlined"
/>
</div>
</div>
{/* Invoice Fields */}
{/* Invoice details (conditional) */}
{invoice && (
<Box
className="flex flex-col gap-2 pt-3 mt-2"
sx={{
borderTop: "2px solid",
borderColor: "primary.light",
borderRadius: "0",
}}
>
<TextField
required
id="company-name"
<div className="flex flex-col gap-3 pt-4 border-t border-blue-200">
<Typography level="title-sm" color="primary">
{t("invoice-details")}
</Typography>
<Field
label={t("company-name")}
variant="filled"
value={formData.companyName}
onChange={handleChange}
name="companyName"
fullWidth
{...fieldProps}
/>
{/* Invoice Name Fields - Two Columns */}
<Box className="grid grid-cols-2 gap-3">
<TextField
required
id="first-name_invoice"
<div className="grid grid-cols-2 gap-3">
<Field
label={t("first-name")}
variant="filled"
value={formData.cmpFirstName}
onChange={handleChange}
name="cmpFirstName"
fullWidth
{...fieldProps}
/>
<TextField
required
id="last-name_invoice"
<Field
label={t("last-name")}
variant="filled"
value={formData.cpmLastName}
onChange={handleChange}
name="cpmLastName"
fullWidth
{...fieldProps}
/>
</Box>
<TextField
required
id="street"
label={t("street")}
variant="filled"
value={formData.street}
onChange={handleChange}
name="street"
fullWidth
/>
<TextField
required
id="postal-code"
</div>
<Field label={t("street")} name="street" {...fieldProps} />
<Field
label={t("postal-code")}
variant="filled"
value={formData.postalCode}
onChange={handleChange}
name="postalCode"
fullWidth
{...fieldProps}
/>
<TextField
required
id="phone-number_invoice"
<Field
label={t("phone-number")}
variant="filled"
type="tel"
value={formData.cpmPhoneNumber}
onChange={handleChange}
name="cpmPhoneNumber"
fullWidth
type="tel"
{...fieldProps}
/>
<TextField
required
id="email_invoice"
<Field
label={t("email")}
variant="filled"
type="email"
value={formData.cpmEmail}
onChange={handleChange}
name="cpmEmail"
fullWidth
type="email"
{...fieldProps}
/>
</Box>
</div>
)}
{/* Payment Methods */}
<Box className="flex flex-col gap-2 mt-2">
<Typography
component="label"
sx={{
fontSize: "0.875rem",
fontWeight: 500,
color: "text.secondary",
display: "flex",
alignItems: "center",
gap: 0.5,
}}
>
{t("select-payment-method")} *
</Typography>
<Box className="flex gap-2 flex-wrap">
<Button
variant={
formData.paymentMethod === "bar" ? "contained" : "outlined"
}
onClick={() =>
setFormData({ ...formData, paymentMethod: "bar" })
}
sx={{
flex: 1,
minWidth: "100px",
py: 1.5,
borderRadius: "12px",
textTransform: "none",
fontWeight: formData.paymentMethod === "bar" ? 600 : 400,
}}
>
{t("cash")}
</Button>
<Button
variant={
formData.paymentMethod === "paypal" ? "contained" : "outlined"
}
onClick={() =>
setFormData({ ...formData, paymentMethod: "paypal" })
}
sx={{
flex: 1,
minWidth: "100px",
py: 1.5,
borderRadius: "12px",
textTransform: "none",
fontWeight: formData.paymentMethod === "paypal" ? 600 : 400,
}}
>
{t("paypal")}
</Button>
<Button
variant={
formData.paymentMethod === "andere" ? "contained" : "outlined"
}
onClick={() =>
setFormData({ ...formData, paymentMethod: "andere" })
}
sx={{
flex: 1,
minWidth: "100px",
py: 1.5,
borderRadius: "12px",
textTransform: "none",
fontWeight: formData.paymentMethod === "andere" ? 600 : 400,
}}
>
{t("transfer")}
</Button>
</Box>
{/* Payment method selection */}
<FormControl required>
<FormLabel>{t("select-payment-method")} *</FormLabel>
<div className="flex gap-2 flex-wrap mt-1">
{PAYMENT_METHODS.map((method) => (
<Button
key={method}
variant={formData.paymentMethod === method ? "solid" : "soft"}
color="primary"
onClick={() =>
setFormData((prev) => ({ ...prev, paymentMethod: method }))
}
sx={{
flex: 1,
minWidth: "90px",
borderRadius: "12px",
py: 1.5,
textTransform: "none",
fontWeight: formData.paymentMethod === method ? 700 : 400,
}}
>
{PAYMENT_LABELS[method]}
</Button>
))}
</div>
{/* Hidden required input to enforce payment selection on submit */}
{!formData.paymentMethod && (
<input
tabIndex={-1}
autoComplete="off"
required
value=""
onChange={() => {}}
style={{
opacity: 0,
width: 0,
height: 0,
position: "absolute",
}}
required
value={formData.paymentMethod}
onChange={() => {}}
/>
)}
</Box>
</FormControl>
{/* Submit Button */}
{/* Submit button */}
<Button
type="submit"
variant="contained"
disabled={isLoading || !formData.paymentMethod}
fullWidth
size="large"
loading={isLoading}
disabled={!formData.paymentMethod}
size="lg"
sx={{
mt: 3,
py: 2,
textTransform: "uppercase",
fontWeight: "bold",
borderRadius: "12px",
fontSize: "1rem",
background: "linear-gradient(135deg, #1976d2 0%, #1565c0 100%)",
boxShadow: "0 4px 14px 0 rgba(25, 118, 210, 0.39)",
mt: 2,
borderRadius: "14px",
fontWeight: 700,
letterSpacing: "0.05em",
background: "linear-gradient(135deg, #2563eb, #1d4ed8)",
"&:hover": {
background: "linear-gradient(135deg, #1565c0 0%, #0d47a1 100%)",
boxShadow: "0 6px 20px 0 rgba(25, 118, 210, 0.5)",
},
"&:disabled": {
background: "#e0e0e0",
boxShadow: "none",
background: "linear-gradient(135deg, #1d4ed8, #1e40af)",
},
}}
>
{isLoading ? (
<CircularProgress size={24} color="inherit" />
) : (
t("submit")
)}
{t("submit")}
</Button>
{/* Alert Message */}
{/* Alert message */}
{msg && (
<Alert severity={msg.type} sx={{ mt: 2 }}>
{msg.headline}: {msg.text}
<Alert color={msg.type} sx={{ borderRadius: "12px" }}>
<strong>{msg.headline}:</strong> {msg.text}
</Alert>
)}
</form>
</Paper>
</Box>
</Sheet>
</div>
);
};