Implement order cancellation feature in OrdersTab: Added functionality to confirm and cancel orders, including a confirmation dialog. Enhanced payment method display in OrderDetailsDialog and updated VAT calculations. Improved localization for order-related messages across multiple languages.

This commit is contained in:
sebseb7
2025-07-17 21:35:00 +02:00
parent 64048e6d0b
commit cb8ce69903
9 changed files with 185 additions and 53 deletions

View File

@@ -26,14 +26,25 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
const currencyFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }); const currencyFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
// Helper function to translate payment methods
const getPaymentMethodDisplay = (paymentMethod) => {
if (!paymentMethod) return t('orders.details.notSpecified');
switch (paymentMethod.toLowerCase()) {
case 'wire':
return t('payment.methods.bankTransfer');
default:
return paymentMethod;
}
};
const handleCancelOrder = () => { const handleCancelOrder = () => {
// Implement order cancellation logic here // Implement order cancellation logic here
console.log(`Cancel order: ${order.orderId}`); console.log(`Cancel order: ${order.orderId}`);
onClose(); // Close the dialog after action onClose(); // Close the dialog after action
}; };
const subtotal = order.items.reduce((acc, item) => acc + item.price * item.quantity_ordered, 0); const total = order.items.reduce((acc, item) => acc + item.price * item.quantity_ordered, 0);
const total = subtotal + order.delivery_cost;
// Calculate VAT breakdown similar to CartDropdown // Calculate VAT breakdown similar to CartDropdown
const vatCalculations = order.items.reduce((acc, item) => { const vatCalculations = order.items.reduce((acc, item) => {
@@ -83,7 +94,7 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
</Box> </Box>
<Box> <Box>
<Typography variant="body2" color="text.secondary">{t('orders.details.paymentMethod')}</Typography> <Typography variant="body2" color="text.secondary">{t('orders.details.paymentMethod')}</Typography>
<Typography variant="body1">{order.paymentMethod || order.payment_method || t('orders.details.notSpecified')}</Typography> <Typography variant="body1">{getPaymentMethodDisplay(order.paymentMethod || order.payment_method)}</Typography>
</Box> </Box>
</Box> </Box>
</Box> </Box>
@@ -96,6 +107,7 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
<TableCell>{t('orders.details.item')}</TableCell> <TableCell>{t('orders.details.item')}</TableCell>
<TableCell align="right">{t('orders.details.quantity')}</TableCell> <TableCell align="right">{t('orders.details.quantity')}</TableCell>
<TableCell align="right">{t('orders.details.price')}</TableCell> <TableCell align="right">{t('orders.details.price')}</TableCell>
<TableCell align="right">{t('product.vatShort')}</TableCell>
<TableCell align="right">{t('orders.details.total')}</TableCell> <TableCell align="right">{t('orders.details.total')}</TableCell>
</TableRow> </TableRow>
</TableHead> </TableHead>
@@ -105,12 +117,12 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
<TableCell>{item.name}</TableCell> <TableCell>{item.name}</TableCell>
<TableCell align="right">{item.quantity_ordered}</TableCell> <TableCell align="right">{item.quantity_ordered}</TableCell>
<TableCell align="right">{currencyFormatter.format(item.price)}</TableCell> <TableCell align="right">{currencyFormatter.format(item.price)}</TableCell>
<TableCell align="right">{item.vat}%</TableCell>
<TableCell align="right">{currencyFormatter.format(item.price * item.quantity_ordered)}</TableCell> <TableCell align="right">{currencyFormatter.format(item.price * item.quantity_ordered)}</TableCell>
</TableRow> </TableRow>
))} ))}
<TableRow> <TableRow>
<TableCell colSpan={2} /> <TableCell colSpan={4} align="right">
<TableCell align="right">
<Typography fontWeight="bold">{t ? t('tax.totalNet') : 'Gesamtnettopreis'}</Typography> <Typography fontWeight="bold">{t ? t('tax.totalNet') : 'Gesamtnettopreis'}</Typography>
</TableCell> </TableCell>
<TableCell align="right"> <TableCell align="right">
@@ -119,35 +131,18 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
</TableRow> </TableRow>
{vatCalculations.vat7 > 0 && ( {vatCalculations.vat7 > 0 && (
<TableRow> <TableRow>
<TableCell colSpan={2} /> <TableCell colSpan={4} align="right">{t ? t('tax.vat7') : '7% Mehrwertsteuer'}</TableCell>
<TableCell align="right">{t ? t('tax.vat7') : '7% Mehrwertsteuer'}</TableCell>
<TableCell align="right">{currencyFormatter.format(vatCalculations.vat7)}</TableCell> <TableCell align="right">{currencyFormatter.format(vatCalculations.vat7)}</TableCell>
</TableRow> </TableRow>
)} )}
{vatCalculations.vat19 > 0 && ( {vatCalculations.vat19 > 0 && (
<TableRow> <TableRow>
<TableCell colSpan={2} /> <TableCell colSpan={4} align="right">{t ? t('tax.vat19') : '19% Mehrwertsteuer'}</TableCell>
<TableCell align="right">{t ? t('tax.vat19') : '19% Mehrwertsteuer'}</TableCell>
<TableCell align="right">{currencyFormatter.format(vatCalculations.vat19)}</TableCell> <TableCell align="right">{currencyFormatter.format(vatCalculations.vat19)}</TableCell>
</TableRow> </TableRow>
)} )}
<TableRow> <TableRow>
<TableCell colSpan={2} /> <TableCell colSpan={4} align="right">
<TableCell align="right">
<Typography fontWeight="bold">{t ? t('tax.subtotal') : 'Zwischensumme'}</Typography>
</TableCell>
<TableCell align="right">
<Typography fontWeight="bold">{currencyFormatter.format(subtotal)}</Typography>
</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={2} />
<TableCell align="right">{t ? t('cart.summary.shippingCosts') : 'Lieferkosten'}</TableCell>
<TableCell align="right">{currencyFormatter.format(order.delivery_cost)}</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={2} />
<TableCell align="right">
<Typography fontWeight="bold">{t ? t('cart.summary.total') : 'Gesamtsumme'}</Typography> <Typography fontWeight="bold">{t ? t('cart.summary.total') : 'Gesamtsumme'}</Typography>
</TableCell> </TableCell>
<TableCell align="right"> <TableCell align="right">

View File

@@ -15,8 +15,14 @@ import {
Tooltip, Tooltip,
CircularProgress, CircularProgress,
Typography, Typography,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
} from "@mui/material"; } from "@mui/material";
import SearchIcon from "@mui/icons-material/Search"; import SearchIcon from "@mui/icons-material/Search";
import CancelIcon from "@mui/icons-material/Cancel";
import SocketContext from "../../contexts/SocketContext.js"; import SocketContext from "../../contexts/SocketContext.js";
import OrderDetailsDialog from "./OrderDetailsDialog.js"; import OrderDetailsDialog from "./OrderDetailsDialog.js";
@@ -71,6 +77,9 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [selectedOrder, setSelectedOrder] = useState(null); const [selectedOrder, setSelectedOrder] = useState(null);
const [isDetailsDialogOpen, setIsDetailsDialogOpen] = useState(false); const [isDetailsDialogOpen, setIsDetailsDialogOpen] = useState(false);
const [cancelConfirmOpen, setCancelConfirmOpen] = useState(false);
const [orderToCancel, setOrderToCancel] = useState(null);
const [isCancelling, setIsCancelling] = useState(false);
const {socket} = useContext(SocketContext); const {socket} = useContext(SocketContext);
const navigate = useNavigate(); const navigate = useNavigate();
@@ -121,11 +130,7 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
useEffect(() => { useEffect(() => {
if (orderIdFromHash && orders.length > 0) { if (orderIdFromHash && orders.length > 0) {
console.log('OrdersTab: Attempting to open order from hash:', orderIdFromHash);
console.log('OrdersTab: Available orders:', orders.map(o => o.orderId));
handleViewDetails(orderIdFromHash); handleViewDetails(orderIdFromHash);
} else if (orderIdFromHash && orders.length === 0) {
console.log('OrdersTab: Order ID from hash but no orders loaded yet:', orderIdFromHash);
} }
}, [orderIdFromHash, orders, handleViewDetails]); }, [orderIdFromHash, orders, handleViewDetails]);
@@ -147,6 +152,47 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
navigate("/profile#orders", { replace: true }); navigate("/profile#orders", { replace: true });
}; };
// Check if order can be cancelled
const isOrderCancelable = (order) => {
const cancelableStatuses = ['new', 'pending', 'processing'];
return cancelableStatuses.includes(order.status);
};
// Handle cancel button click
const handleCancelClick = (order) => {
setOrderToCancel(order);
setCancelConfirmOpen(true);
};
// Handle cancel confirmation
const handleConfirmCancel = () => {
if (!orderToCancel || !socket) return;
setIsCancelling(true);
socket.emit('cancelOrder', { orderId: orderToCancel.orderId }, (response) => {
setIsCancelling(false);
setCancelConfirmOpen(false);
if (response.success) {
console.log('Order cancelled:', response.orderId);
// Refresh orders list
fetchOrders();
} else {
setError(response.error || 'Failed to cancel order');
}
setOrderToCancel(null);
});
};
// Handle cancel dialog close
const handleCancelDialogClose = () => {
if (!isCancelling) {
setCancelConfirmOpen(false);
setOrderToCancel(null);
}
};
if (loading) { if (loading) {
return ( return (
<Box sx={{ p: { xs: 1, sm: 3 }, display: "flex", justifyContent: "center" }}> <Box sx={{ p: { xs: 1, sm: 3 }, display: "flex", justifyContent: "center" }}>
@@ -181,11 +227,10 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
<TableBody> <TableBody>
{orders.map((order) => { {orders.map((order) => {
const displayStatus = getStatusDisplay(order.status); const displayStatus = getStatusDisplay(order.status);
const subtotal = order.items.reduce( const total = order.items.reduce(
(acc, item) => acc + item.price * item.quantity_ordered, (acc, item) => acc + item.price * item.quantity_ordered,
0 0
); );
const total = subtotal + order.delivery_cost;
return ( return (
<TableRow key={order.orderId} hover> <TableRow key={order.orderId} hover>
<TableCell>{order.orderId}</TableCell> <TableCell>{order.orderId}</TableCell>
@@ -223,15 +268,28 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
{currencyFormatter.format(total)} {currencyFormatter.format(total)}
</TableCell> </TableCell>
<TableCell align="center"> <TableCell align="center">
<Tooltip title="Details anzeigen"> <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center' }}>
<IconButton <Tooltip title={t ? t('orders.tooltips.viewDetails') : 'Details anzeigen'}>
size="small" <IconButton
color="primary" size="small"
onClick={() => handleViewDetails(order.orderId)} color="primary"
> onClick={() => handleViewDetails(order.orderId)}
<SearchIcon /> >
</IconButton> <SearchIcon />
</Tooltip> </IconButton>
</Tooltip>
{isOrderCancelable(order) && (
<Tooltip title={t ? t('orders.tooltips.cancelOrder') : 'Bestellung stornieren'}>
<IconButton
size="small"
color="error"
onClick={() => handleCancelClick(order)}
>
<CancelIcon />
</IconButton>
</Tooltip>
)}
</Box>
</TableCell> </TableCell>
</TableRow> </TableRow>
); );
@@ -249,6 +307,47 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
onClose={handleCloseDetailsDialog} onClose={handleCloseDetailsDialog}
order={selectedOrder} order={selectedOrder}
/> />
{/* Cancel Confirmation Dialog */}
<Dialog
open={cancelConfirmOpen}
onClose={handleCancelDialogClose}
maxWidth="sm"
fullWidth
>
<DialogTitle>
{t ? t('orders.cancelConfirm.title') : 'Bestellung stornieren'}
</DialogTitle>
<DialogContent>
<Typography>
{t ? t('orders.cancelConfirm.message') : 'Sind Sie sicher, dass Sie diese Bestellung stornieren möchten?'}
</Typography>
{orderToCancel && (
<Typography variant="body2" sx={{ mt: 1, fontWeight: 'bold' }}>
{t ? t('orders.table.orderNumber') : 'Bestellnummer'}: {orderToCancel.orderId}
</Typography>
)}
</DialogContent>
<DialogActions>
<Button
onClick={handleCancelDialogClose}
disabled={isCancelling}
>
{t ? t('common.cancel') : 'Abbrechen'}
</Button>
<Button
onClick={handleConfirmCancel}
color="error"
variant="contained"
disabled={isCancelling}
>
{isCancelling
? (t ? t('orders.cancelConfirm.cancelling') : 'Wird storniert...')
: (t ? t('orders.cancelConfirm.confirm') : 'Stornieren')
}
</Button>
</DialogActions>
</Dialog>
</Box> </Box>
); );
}; };

View File

@@ -17,14 +17,14 @@ export default {
"items": "Артикули", "items": "Артикули",
"total": "Общо", "total": "Общо",
"actions": "Действия", "actions": "Действия",
"viewDetails": "Виж подробности" "viewDetails": "Виж детайли"
}, },
"noOrders": "Все още не сте направили поръчки.", "noOrders": "Все още не сте направили поръчки.",
"details": { "details": {
"title": "Подробности за поръчка: {{orderId}}", "title": "Детайли за поръчка: {{orderId}}",
"deliveryAddress": "Адрес за доставка", "deliveryAddress": "Адрес за доставка",
"invoiceAddress": "Адрес за фактура", "invoiceAddress": "Адрес за фактура",
"orderDetails": "Подробности за поръчката", "orderDetails": "Детайли за поръчката",
"deliveryMethod": "Начин на доставка:", "deliveryMethod": "Начин на доставка:",
"paymentMethod": "Начин на плащане:", "paymentMethod": "Начин на плащане:",
"notSpecified": "Не е посочено", "notSpecified": "Не е посочено",
@@ -35,5 +35,11 @@ export default {
"total": "Общо", "total": "Общо",
"cancelOrder": "Отмени поръчката" "cancelOrder": "Отмени поръчката"
}, },
"cancelConfirm": {
"title": "Отмяна на поръчка",
"message": "Сигурни ли сте, че искате да отмените тази поръчка?",
"confirm": "Отмени поръчката",
"cancelling": "Отмяна..."
},
"processing": "Поръчката се обработва...", "processing": "Поръчката се обработва...",
}; };

View File

@@ -35,5 +35,11 @@ export default {
"total": "Celkem", "total": "Celkem",
"cancelOrder": "Zrušit objednávku" "cancelOrder": "Zrušit objednávku"
}, },
"processing": "Objednávka se dokončuje..." "cancelConfirm": {
"title": "Zrušit objednávku",
"message": "Opravdu chcete tuto objednávku zrušit?",
"confirm": "Zrušit objednávku",
"cancelling": "Rušení..."
},
"processing": "Objednávka se dokončuje...",
}; };

View File

@@ -19,6 +19,10 @@ export default {
"actions": "Aktionen", "actions": "Aktionen",
"viewDetails": "Details anzeigen" "viewDetails": "Details anzeigen"
}, },
"tooltips": {
"viewDetails": "Details anzeigen",
"cancelOrder": "Bestellung stornieren"
},
"noOrders": "Sie haben noch keine Bestellungen aufgegeben.", "noOrders": "Sie haben noch keine Bestellungen aufgegeben.",
"details": { "details": {
"title": "Bestelldetails: {{orderId}}", "title": "Bestelldetails: {{orderId}}",
@@ -35,5 +39,11 @@ export default {
"total": "Gesamt", "total": "Gesamt",
"cancelOrder": "Bestellung stornieren" "cancelOrder": "Bestellung stornieren"
}, },
"cancelConfirm": {
"title": "Bestellung stornieren",
"message": "Sind Sie sicher, dass Sie diese Bestellung stornieren möchten?",
"confirm": "Stornieren",
"cancelling": "Wird storniert..."
},
"processing": "Bestellung wird abgeschlossen..." "processing": "Bestellung wird abgeschlossen..."
}; };

View File

@@ -19,6 +19,10 @@ export default {
"actions": "Actions", // Aktionen "actions": "Actions", // Aktionen
"viewDetails": "View details" // Details anzeigen "viewDetails": "View details" // Details anzeigen
}, },
"tooltips": {
"viewDetails": "View details", // Details anzeigen
"cancelOrder": "Cancel order" // Bestellung stornieren
},
"noOrders": "You have not placed any orders yet.", // Sie haben noch keine Bestellungen aufgegeben. "noOrders": "You have not placed any orders yet.", // Sie haben noch keine Bestellungen aufgegeben.
"details": { "details": {
"title": "Order details: {{orderId}}", // Bestelldetails: {{orderId}} "title": "Order details: {{orderId}}", // Bestelldetails: {{orderId}}
@@ -32,8 +36,15 @@ export default {
"item": "Item", // Artikel "item": "Item", // Artikel
"quantity": "Quantity", // Menge "quantity": "Quantity", // Menge
"price": "Price", // Preis "price": "Price", // Preis
"vat": "VAT", // MwSt.
"total": "Total", // Gesamt "total": "Total", // Gesamt
"cancelOrder": "Cancel order" // Bestellung stornieren "cancelOrder": "Cancel order" // Bestellung stornieren
}, },
"cancelConfirm": {
"title": "Cancel Order",
"message": "Are you sure you want to cancel this order?",
"confirm": "Cancel Order",
"cancelling": "Cancelling..."
},
"processing": "Order is being completed...", // Bestellung wird abgeschlossen... "processing": "Order is being completed...", // Bestellung wird abgeschlossen...
}; };

View File

@@ -35,5 +35,11 @@ export default {
"total": "Total", "total": "Total",
"cancelOrder": "Cancelar pedido" "cancelOrder": "Cancelar pedido"
}, },
"processing": "El pedido se está completando..." "cancelConfirm": {
"title": "Cancelar pedido",
"message": "¿Estás seguro de que deseas cancelar este pedido?",
"confirm": "Cancelar pedido",
"cancelling": "Cancelando..."
},
"processing": "El pedido se está completando...",
}; };

View File

@@ -19,7 +19,7 @@ export default {
"actions": "Actions", "actions": "Actions",
"viewDetails": "Voir les détails" "viewDetails": "Voir les détails"
}, },
"noOrders": "Vous n'avez encore passé aucune commande.", "noOrders": "Vous n'avez pas encore passé de commandes.",
"details": { "details": {
"title": "Détails de la commande : {{orderId}}", "title": "Détails de la commande : {{orderId}}",
"deliveryAddress": "Adresse de livraison", "deliveryAddress": "Adresse de livraison",
@@ -35,5 +35,11 @@ export default {
"total": "Total", "total": "Total",
"cancelOrder": "Annuler la commande" "cancelOrder": "Annuler la commande"
}, },
"cancelConfirm": {
"title": "Annuler la commande",
"message": "Êtes-vous sûr de vouloir annuler cette commande ?",
"confirm": "Annuler la commande",
"cancelling": "Annulation en cours..."
},
"processing": "La commande est en cours de traitement...", "processing": "La commande est en cours de traitement...",
}; };

View File

@@ -94,21 +94,17 @@ const ProfilePage = (props) => {
useEffect(() => { useEffect(() => {
const hash = location.hash; const hash = location.hash;
console.log('ProfilePage: Processing hash:', hash);
switch (hash) { switch (hash) {
case '#cart': case '#cart':
console.log('ProfilePage: Switching to cart tab');
setTabValue(0); setTabValue(0);
setOrderIdFromHash(null); setOrderIdFromHash(null);
break; break;
case '#orders': case '#orders':
console.log('ProfilePage: Switching to orders tab');
setTabValue(1); setTabValue(1);
setOrderIdFromHash(null); setOrderIdFromHash(null);
break; break;
case '#settings': case '#settings':
console.log('ProfilePage: Switching to settings tab');
setTabValue(2); setTabValue(2);
setOrderIdFromHash(null); setOrderIdFromHash(null);
break; break;
@@ -117,18 +113,15 @@ const ProfilePage = (props) => {
// Check if it's a potential order ID (starts with # and has alphanumeric characters with dashes) // Check if it's a potential order ID (starts with # and has alphanumeric characters with dashes)
const potentialOrderId = hash.substring(1); const potentialOrderId = hash.substring(1);
if (/^[A-Z0-9]+-[A-Z0-9]+$/i.test(potentialOrderId)) { if (/^[A-Z0-9]+-[A-Z0-9]+$/i.test(potentialOrderId)) {
console.log('ProfilePage: Detected order ID from hash:', potentialOrderId);
setOrderIdFromHash(potentialOrderId); setOrderIdFromHash(potentialOrderId);
setTabValue(1); // Switch to Orders tab setTabValue(1); // Switch to Orders tab
} else { } else {
console.log('ProfilePage: Hash does not match order ID pattern:', potentialOrderId);
setOrderIdFromHash(null); setOrderIdFromHash(null);
} }
} else { } else {
setOrderIdFromHash(null); setOrderIdFromHash(null);
// If no hash is present, set default to cart tab // If no hash is present, set default to cart tab
if (!hash) { if (!hash) {
console.log('ProfilePage: No hash present, redirecting to cart');
navigate('/profile#cart', { replace: true }); navigate('/profile#cart', { replace: true });
} }
} }