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" });
// 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 = () => {
// Implement order cancellation logic here
console.log(`Cancel order: ${order.orderId}`);
onClose(); // Close the dialog after action
};
const subtotal = order.items.reduce((acc, item) => acc + item.price * item.quantity_ordered, 0);
const total = subtotal + order.delivery_cost;
const total = order.items.reduce((acc, item) => acc + item.price * item.quantity_ordered, 0);
// Calculate VAT breakdown similar to CartDropdown
const vatCalculations = order.items.reduce((acc, item) => {
@@ -83,7 +94,7 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
</Box>
<Box>
<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>
@@ -96,6 +107,7 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
<TableCell>{t('orders.details.item')}</TableCell>
<TableCell align="right">{t('orders.details.quantity')}</TableCell>
<TableCell align="right">{t('orders.details.price')}</TableCell>
<TableCell align="right">{t('product.vatShort')}</TableCell>
<TableCell align="right">{t('orders.details.total')}</TableCell>
</TableRow>
</TableHead>
@@ -105,12 +117,12 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
<TableCell>{item.name}</TableCell>
<TableCell align="right">{item.quantity_ordered}</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>
</TableRow>
))}
<TableRow>
<TableCell colSpan={2} />
<TableCell align="right">
<TableCell colSpan={4} align="right">
<Typography fontWeight="bold">{t ? t('tax.totalNet') : 'Gesamtnettopreis'}</Typography>
</TableCell>
<TableCell align="right">
@@ -119,35 +131,18 @@ const OrderDetailsDialog = ({ open, onClose, order }) => {
</TableRow>
{vatCalculations.vat7 > 0 && (
<TableRow>
<TableCell colSpan={2} />
<TableCell align="right">{t ? t('tax.vat7') : '7% Mehrwertsteuer'}</TableCell>
<TableCell colSpan={4} align="right">{t ? t('tax.vat7') : '7% Mehrwertsteuer'}</TableCell>
<TableCell align="right">{currencyFormatter.format(vatCalculations.vat7)}</TableCell>
</TableRow>
)}
{vatCalculations.vat19 > 0 && (
<TableRow>
<TableCell colSpan={2} />
<TableCell align="right">{t ? t('tax.vat19') : '19% Mehrwertsteuer'}</TableCell>
<TableCell colSpan={4} align="right">{t ? t('tax.vat19') : '19% Mehrwertsteuer'}</TableCell>
<TableCell align="right">{currencyFormatter.format(vatCalculations.vat19)}</TableCell>
</TableRow>
)}
<TableRow>
<TableCell colSpan={2} />
<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">
<TableCell colSpan={4} align="right">
<Typography fontWeight="bold">{t ? t('cart.summary.total') : 'Gesamtsumme'}</Typography>
</TableCell>
<TableCell align="right">

View File

@@ -15,8 +15,14 @@ import {
Tooltip,
CircularProgress,
Typography,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
} from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import CancelIcon from "@mui/icons-material/Cancel";
import SocketContext from "../../contexts/SocketContext.js";
import OrderDetailsDialog from "./OrderDetailsDialog.js";
@@ -71,6 +77,9 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
const [error, setError] = useState(null);
const [selectedOrder, setSelectedOrder] = useState(null);
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 navigate = useNavigate();
@@ -121,11 +130,7 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
useEffect(() => {
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);
} else if (orderIdFromHash && orders.length === 0) {
console.log('OrdersTab: Order ID from hash but no orders loaded yet:', orderIdFromHash);
}
}, [orderIdFromHash, orders, handleViewDetails]);
@@ -147,6 +152,47 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
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) {
return (
<Box sx={{ p: { xs: 1, sm: 3 }, display: "flex", justifyContent: "center" }}>
@@ -181,11 +227,10 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
<TableBody>
{orders.map((order) => {
const displayStatus = getStatusDisplay(order.status);
const subtotal = order.items.reduce(
const total = order.items.reduce(
(acc, item) => acc + item.price * item.quantity_ordered,
0
);
const total = subtotal + order.delivery_cost;
return (
<TableRow key={order.orderId} hover>
<TableCell>{order.orderId}</TableCell>
@@ -223,15 +268,28 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
{currencyFormatter.format(total)}
</TableCell>
<TableCell align="center">
<Tooltip title="Details anzeigen">
<IconButton
size="small"
color="primary"
onClick={() => handleViewDetails(order.orderId)}
>
<SearchIcon />
</IconButton>
</Tooltip>
<Box sx={{ display: 'flex', gap: 1, justifyContent: 'center' }}>
<Tooltip title={t ? t('orders.tooltips.viewDetails') : 'Details anzeigen'}>
<IconButton
size="small"
color="primary"
onClick={() => handleViewDetails(order.orderId)}
>
<SearchIcon />
</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>
</TableRow>
);
@@ -249,6 +307,47 @@ const OrdersTab = ({ orderIdFromHash, t }) => {
onClose={handleCloseDetailsDialog}
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>
);
};

View File

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

View File

@@ -35,5 +35,11 @@ export default {
"total": "Celkem",
"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",
"viewDetails": "Details anzeigen"
},
"tooltips": {
"viewDetails": "Details anzeigen",
"cancelOrder": "Bestellung stornieren"
},
"noOrders": "Sie haben noch keine Bestellungen aufgegeben.",
"details": {
"title": "Bestelldetails: {{orderId}}",
@@ -35,5 +39,11 @@ export default {
"total": "Gesamt",
"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..."
};

View File

@@ -19,6 +19,10 @@ export default {
"actions": "Actions", // Aktionen
"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.
"details": {
"title": "Order details: {{orderId}}", // Bestelldetails: {{orderId}}
@@ -32,8 +36,15 @@ export default {
"item": "Item", // Artikel
"quantity": "Quantity", // Menge
"price": "Price", // Preis
"vat": "VAT", // MwSt.
"total": "Total", // Gesamt
"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...
};

View File

@@ -35,5 +35,11 @@ export default {
"total": "Total",
"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",
"viewDetails": "Voir les détails"
},
"noOrders": "Vous n'avez encore passé aucune commande.",
"noOrders": "Vous n'avez pas encore passé de commandes.",
"details": {
"title": "Détails de la commande : {{orderId}}",
"deliveryAddress": "Adresse de livraison",
@@ -35,5 +35,11 @@ export default {
"total": "Total",
"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...",
};

View File

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