Better integration of sqlite3 database
This commit is contained in:
@ -12,8 +12,7 @@ import QRCode from 'react-qr-code';
|
||||
import {
|
||||
ContactPerson,
|
||||
Address,
|
||||
Dewar,
|
||||
DefaultService
|
||||
Dewar, ContactsService, AddressesService, ShipmentsService,
|
||||
} from '../../openapi';
|
||||
|
||||
interface DewarDetailsProps {
|
||||
@ -26,18 +25,20 @@ interface DewarDetailsProps {
|
||||
defaultReturnAddress?: Address;
|
||||
shipmentId: string;
|
||||
refreshShipments: () => void;
|
||||
selectedShipment: any;
|
||||
}
|
||||
|
||||
const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
dewar,
|
||||
trackingNumber,
|
||||
//setTrackingNumber,
|
||||
setTrackingNumber,
|
||||
initialContactPersons = [],
|
||||
initialReturnAddresses = [],
|
||||
defaultContactPerson,
|
||||
defaultReturnAddress,
|
||||
shipmentId,
|
||||
refreshShipments,
|
||||
selectedShipment
|
||||
}) => {
|
||||
const [localTrackingNumber, setLocalTrackingNumber] = useState(trackingNumber);
|
||||
const [contactPersons, setContactPersons] = useState<ContactPerson[]>(initialContactPersons);
|
||||
@ -47,12 +48,14 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
const [isCreatingContactPerson, setIsCreatingContactPerson] = useState(false);
|
||||
const [isCreatingReturnAddress, setIsCreatingReturnAddress] = useState(false);
|
||||
const [newContactPerson, setNewContactPerson] = useState({
|
||||
id: 0,
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
phone_number: '',
|
||||
email: '',
|
||||
});
|
||||
const [newReturnAddress, setNewReturnAddress] = useState<Address>({
|
||||
id: 0,
|
||||
street: '',
|
||||
city: '',
|
||||
zipcode: '',
|
||||
@ -61,26 +64,34 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
const [changesMade, setChangesMade] = useState<boolean>(false);
|
||||
const [feedbackMessage, setFeedbackMessage] = useState<string>('');
|
||||
const [openSnackbar, setOpenSnackbar] = useState<boolean>(false);
|
||||
const [updatedDewar, setUpdatedDewar] = useState<Dewar>(dewar);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedContactPerson(
|
||||
(dewar.contact_person?.[0]?.id?.toString() || defaultContactPerson?.id?.toString() || '')
|
||||
);
|
||||
setSelectedReturnAddress(
|
||||
(dewar.return_address?.[0]?.id?.toString() || defaultReturnAddress?.id?.toString() || '')
|
||||
);
|
||||
const setInitialContactPerson = () => {
|
||||
const contactPersonId =
|
||||
selectedShipment?.contact_person?.id?.toString() ||
|
||||
dewar.contact_person?.id?.toString() ||
|
||||
defaultContactPerson?.id?.toString() ||
|
||||
'';
|
||||
setSelectedContactPerson(contactPersonId);
|
||||
};
|
||||
|
||||
const setInitialReturnAddress = () => {
|
||||
const returnAddressId =
|
||||
dewar.return_address?.id?.toString() ||
|
||||
defaultReturnAddress?.id?.toString() ||
|
||||
'';
|
||||
setSelectedReturnAddress(returnAddressId);
|
||||
};
|
||||
|
||||
setLocalTrackingNumber(dewar.tracking_number || '');
|
||||
}, [dewar, defaultContactPerson, defaultReturnAddress]);
|
||||
|
||||
useEffect(() => {
|
||||
console.log('DewarDetails - dewar updated:', dewar);
|
||||
}, [dewar]);
|
||||
setInitialContactPerson();
|
||||
setInitialReturnAddress();
|
||||
}, [dewar, defaultContactPerson, defaultReturnAddress, selectedShipment]);
|
||||
|
||||
useEffect(() => {
|
||||
const getContacts = async () => {
|
||||
try {
|
||||
const c: ContactPerson[] = await DefaultService.getContactsContactsGet();
|
||||
const c: ContactPerson[] = await ContactsService.getContactsContactsGet();
|
||||
setContactPersons(c);
|
||||
} catch {
|
||||
setFeedbackMessage('Failed to load contact persons. Please try again later.');
|
||||
@ -90,7 +101,7 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
|
||||
const getReturnAddresses = async () => {
|
||||
try {
|
||||
const a: Address[] = await DefaultService.getReturnAddressesReturnAddressesGet();
|
||||
const a: Address[] = await AddressesService.getReturnAddressesAddressesGet();
|
||||
setReturnAddresses(a);
|
||||
} catch {
|
||||
setFeedbackMessage('Failed to load return addresses. Please try again later.');
|
||||
@ -111,6 +122,7 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
}
|
||||
|
||||
const handleAddContact = async () => {
|
||||
console.log('handleAddContact called');
|
||||
if (!validateEmail(newContactPerson.email) || !validatePhoneNumber(newContactPerson.phone_number) ||
|
||||
!newContactPerson.firstName || !newContactPerson.lastName) {
|
||||
setFeedbackMessage('Please fill in all new contact person fields correctly.');
|
||||
@ -126,10 +138,10 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
};
|
||||
|
||||
try {
|
||||
const c: ContactPerson = await DefaultService.createContactContactsPost(payload);
|
||||
const c: ContactPerson = await ContactsService.createContactContactsPost(payload);
|
||||
setContactPersons([...contactPersons, c]);
|
||||
setFeedbackMessage('Contact person added successfully.');
|
||||
setNewContactPerson({ firstName: '', lastName: '', phone_number: '', email: '' });
|
||||
setNewContactPerson({ id: 0, firstName: '', lastName: '', phone_number: '', email: '' });
|
||||
setSelectedContactPerson(c.id?.toString() || '');
|
||||
} catch {
|
||||
setFeedbackMessage('Failed to create a new contact person. Please try again later.');
|
||||
@ -141,6 +153,7 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
};
|
||||
|
||||
const handleAddAddress = async () => {
|
||||
console.log('handleAddAddress called');
|
||||
if (!validateZipCode(newReturnAddress.zipcode) || !newReturnAddress.street || !newReturnAddress.city ||
|
||||
!newReturnAddress.country) {
|
||||
setFeedbackMessage('Please fill in all new return address fields correctly.');
|
||||
@ -156,10 +169,10 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
};
|
||||
|
||||
try {
|
||||
const a: Address = await DefaultService.createReturnAddressReturnAddressesPost(payload);
|
||||
const a: Address = await AddressesService.createReturnAddressAddressesPost(payload);
|
||||
setReturnAddresses([...returnAddresses, a]);
|
||||
setFeedbackMessage('Return address added successfully.');
|
||||
setNewReturnAddress({ street: '', city: '', zipcode: '', country: '' });
|
||||
setNewReturnAddress({ id: 0, street: '', city: '', zipcode: '', country: '' });
|
||||
setSelectedReturnAddress(a.id?.toString() || '');
|
||||
} catch {
|
||||
setFeedbackMessage('Failed to create a new return address. Please try again later.');
|
||||
@ -171,10 +184,11 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
};
|
||||
|
||||
const getShipmentById = async (shipmentId: string) => {
|
||||
console.log(`Fetching shipment with ID: ${shipmentId}`);
|
||||
try {
|
||||
const response = await DefaultService.getShipmentsShipmentsGet(shipmentId);
|
||||
const response = await ShipmentsService.fetchShipmentsShipmentsGet(shipmentId);
|
||||
if (response && response.length > 0) {
|
||||
return response[0]; // Since the result is an array, we take the first element
|
||||
return response[0];
|
||||
}
|
||||
throw new Error('Shipment not found');
|
||||
} catch (error) {
|
||||
@ -184,22 +198,32 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
};
|
||||
|
||||
const handleSaveChanges = async () => {
|
||||
console.log('handleSaveChanges called');
|
||||
|
||||
const formatDate = (dateString: string | undefined): string => {
|
||||
if (!dateString) return '2024-01-01'; // Default date if undefined
|
||||
if (!dateString) return '';
|
||||
const date = new Date(dateString);
|
||||
if (isNaN(date.getTime())) return '2024-01-01'; // Default date if invalid
|
||||
if (isNaN(date.getTime())) return '';
|
||||
return date.toISOString().split('T')[0];
|
||||
};
|
||||
|
||||
if (!dewar.dewar_name || !selectedContactPerson || !selectedReturnAddress || !trackingNumber) {
|
||||
console.log('Selected Contact Person:', selectedContactPerson);
|
||||
console.log('Selected Return Address:', selectedReturnAddress);
|
||||
|
||||
// Check if required fields are filled
|
||||
if (!selectedContactPerson || !selectedReturnAddress) {
|
||||
setFeedbackMessage('Please ensure all required fields are filled.');
|
||||
setOpenSnackbar(true);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Saving changes...');
|
||||
console.log('Current Dewar:', dewar);
|
||||
|
||||
let existingShipment;
|
||||
try {
|
||||
existingShipment = await getShipmentById(shipmentId);
|
||||
console.log('Existing Shipment:', existingShipment);
|
||||
} catch {
|
||||
setFeedbackMessage('Failed to fetch existing shipment data. Please try again later.');
|
||||
setOpenSnackbar(true);
|
||||
@ -207,56 +231,58 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
}
|
||||
|
||||
const updatedDewar = {
|
||||
id: dewar.id, // Ensure dewar ID is included
|
||||
id: dewar.id,
|
||||
dewar_name: dewar.dewar_name,
|
||||
return_address: returnAddresses.find((a) => a.id?.toString() === selectedReturnAddress)
|
||||
? [returnAddresses.find((a) => a.id?.toString() === selectedReturnAddress)]
|
||||
: [],
|
||||
contact_person: contactPersons.find((c) => c.id?.toString() === selectedContactPerson)
|
||||
? [contactPersons.find((c) => c.id?.toString() === selectedContactPerson)]
|
||||
: [],
|
||||
tracking_number: dewar.tracking_number,
|
||||
number_of_pucks: dewar.number_of_pucks,
|
||||
number_of_samples: dewar.number_of_samples,
|
||||
qrcode: dewar.qrcode,
|
||||
ready_date: formatDate(dewar.ready_date),
|
||||
shipping_date: formatDate(dewar.shipping_date),
|
||||
status: dewar.status,
|
||||
tracking_number: trackingNumber,
|
||||
ready_date: formatDate(dewar.ready_date ?? undefined),
|
||||
shipping_date: formatDate(dewar.shipping_date ?? undefined),
|
||||
arrival_date: dewar.arrival_date,
|
||||
returning_date: dewar.returning_date,
|
||||
qrcode: dewar.qrcode,
|
||||
return_address_id: selectedReturnAddress,
|
||||
contact_person_id: selectedContactPerson,
|
||||
};
|
||||
|
||||
const payload = {
|
||||
...existingShipment,
|
||||
dewars: existingShipment.dewars?.map(d => d.id === dewar.id ? updatedDewar : d) || [], // Update specific dewar in the dewars array
|
||||
shipment_id: existingShipment.shipment_id,
|
||||
shipment_name: existingShipment.shipment_name,
|
||||
shipment_date: existingShipment.shipment_date,
|
||||
shipment_status: existingShipment.shipment_status,
|
||||
comments: existingShipment.comments,
|
||||
contact_person_id: selectedContactPerson,
|
||||
return_address_id: selectedReturnAddress,
|
||||
proposal_id: existingShipment.proposal?.id,
|
||||
dewars: [
|
||||
updatedDewar
|
||||
],
|
||||
};
|
||||
|
||||
console.log('Payload for update:', JSON.stringify(payload, null, 2));
|
||||
|
||||
try {
|
||||
await DefaultService.updateShipmentShipmentsShipmentIdPut(shipmentId, payload);
|
||||
await ShipmentsService.updateShipmentShipmentsShipmentsShipmentIdPut(shipmentId, payload);
|
||||
setFeedbackMessage('Changes saved successfully.');
|
||||
setChangesMade(false);
|
||||
setUpdatedDewar(updatedDewar);
|
||||
console.log('Calling refreshShipments');
|
||||
refreshShipments(); // Trigger refresh shipments after saving changes
|
||||
refreshShipments();
|
||||
} catch (error) {
|
||||
if (error.response) {
|
||||
console.error('Server Response:', error.response.data);
|
||||
} else {
|
||||
console.error('Update Shipment Error:', error);
|
||||
setFeedbackMessage('Failed to save changes. Please try again later.');
|
||||
}
|
||||
setOpenSnackbar(true);
|
||||
return;
|
||||
console.error('Update Shipment Error:', error);
|
||||
setFeedbackMessage('Failed to save changes. Please try again later.');
|
||||
}
|
||||
setOpenSnackbar(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ marginTop: 2 }}>
|
||||
<Typography variant="h6">Selected Dewar: {updatedDewar.dewar_name}</Typography>
|
||||
<Typography variant="h6">Selected Dewar: {dewar.dewar_name}</Typography>
|
||||
<TextField
|
||||
label="Tracking Number"
|
||||
value={localTrackingNumber}
|
||||
onChange={(e) => {
|
||||
setLocalTrackingNumber(e.target.value);
|
||||
setTrackingNumber(e.target.value); // Ensure parent state is updated if applicable
|
||||
setChangesMade(true);
|
||||
}}
|
||||
variant="outlined"
|
||||
@ -264,8 +290,8 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
/>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', marginBottom: 2 }}>
|
||||
<Box sx={{ width: 80, height: 80, backgroundColor: '#e0e0e0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
|
||||
{updatedDewar.qrcode ? (
|
||||
<QRCode value={updatedDewar.qrcode} size={70} />
|
||||
{dewar.qrcode ? (
|
||||
<QRCode value={dewar.qrcode} size={70} />
|
||||
) : (
|
||||
<Typography>No QR code available</Typography>
|
||||
)}
|
||||
@ -274,14 +300,16 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
Generate QR Code
|
||||
</Button>
|
||||
</Box>
|
||||
<Typography variant="body1">Number of Pucks: {updatedDewar.number_of_pucks}</Typography>
|
||||
<Typography variant="body1">Number of Samples: {updatedDewar.number_of_samples}</Typography>
|
||||
<Typography variant="body1">Number of Pucks: {dewar.number_of_pucks}</Typography>
|
||||
<Typography variant="body1">Number of Samples: {dewar.number_of_samples}</Typography>
|
||||
<Typography variant="body1">Current Contact Person:</Typography>
|
||||
<Select
|
||||
value={selectedContactPerson}
|
||||
onChange={(e) => {
|
||||
setSelectedContactPerson(e.target.value);
|
||||
setIsCreatingContactPerson(e.target.value === 'add');
|
||||
const value = e.target.value;
|
||||
console.log('Contact Person Selected:', value);
|
||||
setSelectedContactPerson(value);
|
||||
setIsCreatingContactPerson(value === 'add');
|
||||
setChangesMade(true);
|
||||
}}
|
||||
fullWidth
|
||||
@ -289,7 +317,7 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
variant="outlined"
|
||||
displayEmpty
|
||||
>
|
||||
{contactPersons?.map((person) => (
|
||||
{Array.isArray(contactPersons) && contactPersons.map((person) => (
|
||||
<MenuItem key={person.id?.toString()} value={person.id?.toString() || ''}>
|
||||
{person.firstname} {person.lastname}
|
||||
</MenuItem>
|
||||
@ -343,8 +371,10 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
<Select
|
||||
value={selectedReturnAddress}
|
||||
onChange={(e) => {
|
||||
setSelectedReturnAddress(e.target.value);
|
||||
setIsCreatingReturnAddress(e.target.value === 'add');
|
||||
const value = e.target.value;
|
||||
console.log('Return Address Selected:', value);
|
||||
setSelectedReturnAddress(value);
|
||||
setIsCreatingReturnAddress(value === 'add');
|
||||
setChangesMade(true);
|
||||
}}
|
||||
fullWidth
|
||||
@ -352,7 +382,7 @@ const DewarDetails: React.FC<DewarDetailsProps> = ({
|
||||
variant="outlined"
|
||||
displayEmpty
|
||||
>
|
||||
{returnAddresses?.map((address) => (
|
||||
{Array.isArray(returnAddresses) && returnAddresses.map((address) => (
|
||||
<MenuItem key={address.id?.toString()} value={address.id?.toString() || ''}>
|
||||
{address.street}, {address.city}
|
||||
</MenuItem>
|
||||
|
@ -2,35 +2,50 @@ import React from 'react';
|
||||
import { Box, Typography, Button, Stack, TextField } from '@mui/material';
|
||||
import QRCode from 'react-qr-code';
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
import { Dewar, Shipment_Input, DefaultService } from "../../openapi";
|
||||
import { Dewar, DewarsService, ShipmentsService, ContactPerson, ApiError } from "../../openapi"; // Ensure ApiError is imported here
|
||||
import { SxProps } from "@mui/system";
|
||||
import CustomStepper from "./DewarStepper";
|
||||
import DewarDetails from './DewarDetails';
|
||||
|
||||
interface ShipmentDetailsProps {
|
||||
isCreatingShipment: boolean;
|
||||
selectedShipment: Shipment_Input;
|
||||
sx?: SxProps;
|
||||
selectedShipment: ShipmentsService | null;
|
||||
selectedDewar: Dewar | null;
|
||||
setSelectedDewar: React.Dispatch<React.SetStateAction<Dewar | null>>;
|
||||
setSelectedShipment: React.Dispatch<React.SetStateAction<Shipment_Input>>;
|
||||
sx?: SxProps;
|
||||
setSelectedShipment: React.Dispatch<React.SetStateAction<ShipmentsService | null>>;
|
||||
refreshShipments: () => void;
|
||||
defaultContactPerson?: ContactPerson;
|
||||
}
|
||||
|
||||
const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
isCreatingShipment,
|
||||
sx,
|
||||
selectedShipment,
|
||||
selectedDewar,
|
||||
setSelectedDewar,
|
||||
setSelectedShipment,
|
||||
sx = {},
|
||||
refreshShipments,
|
||||
defaultContactPerson
|
||||
}) => {
|
||||
const [localSelectedDewar, setLocalSelectedDewar] = React.useState<Dewar | null>(null);
|
||||
const [isAddingDewar, setIsAddingDewar] = React.useState<boolean>(false);
|
||||
const [newDewar, setNewDewar] = React.useState<Partial<Dewar>>({
|
||||
dewar_name: '',
|
||||
});
|
||||
|
||||
// To reset localSelectedDewar when selectedShipment changes
|
||||
const initialNewDewarState: Partial<Dewar> = {
|
||||
dewar_name: '',
|
||||
tracking_number: '',
|
||||
number_of_pucks: 0,
|
||||
number_of_samples: 0,
|
||||
status: 'In preparation',
|
||||
ready_date: null,
|
||||
shipping_date: null,
|
||||
arrival_date: null,
|
||||
returning_date: null,
|
||||
qrcode: 'N/A'
|
||||
};
|
||||
|
||||
const [newDewar, setNewDewar] = React.useState<Partial<Dewar>>(initialNewDewarState);
|
||||
|
||||
React.useEffect(() => {
|
||||
setLocalSelectedDewar(null);
|
||||
}, [selectedShipment]);
|
||||
@ -39,8 +54,8 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
console.log('ShipmentDetails - selectedShipment updated:', selectedShipment);
|
||||
}, [selectedShipment]);
|
||||
|
||||
const totalPucks = selectedShipment.dewars.reduce((acc, dewar) => acc + (dewar.number_of_pucks || 0), 0);
|
||||
const totalSamples = selectedShipment.dewars.reduce((acc, dewar) => acc + (dewar.number_of_samples || 0), 0);
|
||||
const totalPucks = selectedShipment?.dewars?.reduce((acc, dewar) => acc + (dewar.number_of_pucks || 0), 0) || 0;
|
||||
const totalSamples = selectedShipment?.dewars?.reduce((acc, dewar) => acc + (dewar.number_of_samples || 0), 0) || 0;
|
||||
|
||||
const handleDewarSelection = (dewar: Dewar) => {
|
||||
const newSelection = localSelectedDewar?.id === dewar.id ? null : dewar;
|
||||
@ -50,18 +65,12 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
|
||||
const handleDeleteDewar = async (dewarId: string) => {
|
||||
const confirmed = window.confirm('Are you sure you want to delete this dewar?');
|
||||
if (confirmed) {
|
||||
if (confirmed && selectedShipment) {
|
||||
try {
|
||||
console.log('Selected Shipment ID:', selectedShipment.shipment_id);
|
||||
console.log('Dewar ID to be deleted:', dewarId);
|
||||
|
||||
const updatedShipment = await DefaultService.removeDewarFromShipmentShipmentsShipmentIdRemoveDewarDewarIdDelete(
|
||||
selectedShipment.shipment_id, dewarId
|
||||
);
|
||||
|
||||
// Ensure state is updated with server response
|
||||
const updatedShipment = await ShipmentsService.removeDewarFromShipmentShipmentsShipmentIdRemoveDewarDewarIdDelete(selectedShipment.shipment_id, dewarId);
|
||||
setSelectedShipment(updatedShipment);
|
||||
setLocalSelectedDewar(null);
|
||||
refreshShipments();
|
||||
} catch (error) {
|
||||
console.error('Failed to delete dewar:', error);
|
||||
alert('Failed to delete dewar. Please try again.');
|
||||
@ -78,55 +87,42 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
};
|
||||
|
||||
const handleAddDewar = async () => {
|
||||
if (selectedShipment && newDewar.dewar_name) {
|
||||
if (newDewar.dewar_name?.trim()) {
|
||||
try {
|
||||
const newDewarToPost: Dewar = {
|
||||
...newDewar as Dewar,
|
||||
dewar_name: newDewar.dewar_name.trim() || 'Unnamed Dewar',
|
||||
number_of_pucks: newDewar.number_of_pucks ?? 0,
|
||||
number_of_samples: newDewar.number_of_samples ?? 0,
|
||||
return_address: selectedShipment.return_address,
|
||||
contact_person: selectedShipment.contact_person,
|
||||
status: 'In preparation',
|
||||
qrcode: newDewar.qrcode || 'N/A',
|
||||
};
|
||||
...initialNewDewarState,
|
||||
...newDewar,
|
||||
dewar_name: newDewar.dewar_name.trim(),
|
||||
contact_person: selectedShipment?.contact_person,
|
||||
contact_person_id: selectedShipment?.contact_person?.id, // Adding contact_person_id
|
||||
return_address: selectedShipment?.return_address,
|
||||
return_address_id: selectedShipment?.return_address?.id, // Adding return_address_id
|
||||
} as Dewar;
|
||||
|
||||
// Create a new dewar
|
||||
const createdDewar = await DefaultService.createDewarDewarsPost(newDewarToPost);
|
||||
|
||||
console.log('Created Dewar:', createdDewar);
|
||||
|
||||
// Check IDs before calling backend
|
||||
console.log('Adding dewar to shipment:', {
|
||||
shipment_id: selectedShipment.shipment_id,
|
||||
dewar_id: createdDewar.id,
|
||||
});
|
||||
|
||||
// Make an API call to associate the dewar with the shipment
|
||||
const updatedShipment = await DefaultService.addDewarToShipmentShipmentsShipmentIdAddDewarPost(
|
||||
selectedShipment.shipment_id,
|
||||
createdDewar.id
|
||||
);
|
||||
|
||||
if (updatedShipment) {
|
||||
const createdDewar = await DewarsService.createDewarDewarsPost(newDewarToPost);
|
||||
if (createdDewar && selectedShipment) {
|
||||
const updatedShipment = await ShipmentsService.addDewarToShipmentShipmentsShipmentIdAddDewarPost(selectedShipment.shipment_id, createdDewar.id);
|
||||
setSelectedShipment(updatedShipment);
|
||||
} else {
|
||||
throw new Error('Failed to update shipment with new dewar');
|
||||
setIsAddingDewar(false);
|
||||
setNewDewar(initialNewDewarState);
|
||||
refreshShipments();
|
||||
}
|
||||
|
||||
setIsAddingDewar(false);
|
||||
setNewDewar({ dewar_name: '', tracking_number: '' });
|
||||
refreshShipments()
|
||||
|
||||
} catch (error) {
|
||||
alert('Failed to add dewar or update shipment. Please try again.');
|
||||
console.error('Error adding dewar or updating shipment:', error);
|
||||
if (error instanceof ApiError && error.body) {
|
||||
console.error('Validation errors:', error.body.detail); // Log specific validation errors
|
||||
} else {
|
||||
console.error('Unexpected error:', error);
|
||||
}
|
||||
alert('Failed to add dewar or update shipment. Please check the data and try again.');
|
||||
}
|
||||
} else {
|
||||
alert('Please fill in the Dewar Name');
|
||||
}
|
||||
};
|
||||
|
||||
const contactPerson = selectedShipment?.contact_person;
|
||||
|
||||
return (
|
||||
<Box sx={{ ...sx, padding: 2, textAlign: 'left' }}>
|
||||
{!localSelectedDewar && !isAddingDewar && (
|
||||
@ -159,11 +155,19 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Typography variant="h5">{selectedShipment.shipment_name}</Typography>
|
||||
<Typography variant="body1" color="textSecondary">Main contact person: {`${selectedShipment.contact_person[0].firstname} ${selectedShipment.contact_person[0].lastname}`}</Typography>
|
||||
<Typography variant="body1">Number of Pucks: {totalPucks}</Typography>
|
||||
<Typography variant="body1">Number of Samples: {totalSamples}</Typography>
|
||||
<Typography variant="body1">Shipment Date: {selectedShipment.shipment_date}</Typography>
|
||||
{selectedShipment ? (
|
||||
<>
|
||||
<Typography variant="h5">{selectedShipment.shipment_name}</Typography>
|
||||
<Typography variant="body1" color="textSecondary">
|
||||
Main contact person: {contactPerson ? `${contactPerson.firstname} ${contactPerson.lastname}` : 'N/A'}
|
||||
</Typography>
|
||||
<Typography variant="body1">Number of Pucks: {totalPucks}</Typography>
|
||||
<Typography variant="body1">Number of Samples: {totalSamples}</Typography>
|
||||
<Typography variant="body1">Shipment Date: {selectedShipment.shipment_date}</Typography>
|
||||
</>
|
||||
) : (
|
||||
<Typography variant="h5" color="error">No shipment selected</Typography>
|
||||
)}
|
||||
|
||||
{localSelectedDewar && !isAddingDewar && (
|
||||
<DewarDetails
|
||||
@ -172,17 +176,17 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
setTrackingNumber={(value) => {
|
||||
setLocalSelectedDewar((prev) => (prev ? { ...prev, tracking_number: value as string } : prev));
|
||||
}}
|
||||
initialContactPersons={selectedShipment.contact_person}
|
||||
initialReturnAddresses={selectedShipment.return_address}
|
||||
defaultContactPerson={selectedShipment.contact_person[0]}
|
||||
defaultReturnAddress={selectedShipment.return_address[0]}
|
||||
shipmentId={selectedShipment.shipment_id}
|
||||
initialContactPersons={selectedShipment?.contact_person ? [selectedShipment.contact_person] : []}
|
||||
initialReturnAddresses={selectedShipment?.return_address ? [selectedShipment.return_address] : []}
|
||||
defaultContactPerson={contactPerson}
|
||||
defaultReturnAddress={selectedShipment?.return_address}
|
||||
shipmentId={selectedShipment?.shipment_id || ''}
|
||||
refreshShipments={refreshShipments}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Stack spacing={1}>
|
||||
{selectedShipment.dewars.map((dewar) => (
|
||||
{selectedShipment?.dewars?.map((dewar) => (
|
||||
<Button
|
||||
key={dewar.id}
|
||||
onClick={() => handleDewarSelection(dewar)}
|
||||
@ -197,14 +201,7 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
backgroundColor: localSelectedDewar?.id === dewar.id ? '#f0f0f0' : '#fff',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginRight: 2,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginRight: 2 }}>
|
||||
{dewar.qrcode ? (
|
||||
<QRCode value={dewar.qrcode} size={70} />
|
||||
) : (
|
||||
@ -230,7 +227,9 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
<Typography variant="body2">Number of Pucks: {dewar.number_of_pucks || 0}</Typography>
|
||||
<Typography variant="body2">Number of Samples: {dewar.number_of_samples || 0}</Typography>
|
||||
<Typography variant="body2">Tracking Number: {dewar.tracking_number}</Typography>
|
||||
<Typography variant="body2">Contact Person: {`${dewar.contact_person[0].firstname} ${dewar.contact_person[0].lastname}`}</Typography>
|
||||
<Typography variant="body2">
|
||||
Contact Person: {dewar.contact_person?.firstname ? `${dewar.contact_person.firstname} ${dewar.contact_person.lastname}` : 'N/A'}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{
|
||||
@ -243,7 +242,7 @@ const ShipmentDetails: React.FC<ShipmentDetailsProps> = ({
|
||||
<CustomStepper dewar={dewar} />
|
||||
{localSelectedDewar?.id === dewar.id && (
|
||||
<Button
|
||||
onClick={() => handleDeleteDewar(dewar.id)} // <--- Pass the dewar ID here
|
||||
onClick={() => handleDeleteDewar(dewar.id)}
|
||||
color="error"
|
||||
sx={{
|
||||
minWidth: '40px',
|
||||
|
@ -1,14 +1,19 @@
|
||||
import * as React from 'react';
|
||||
import { Box, Button, TextField, Typography, Select, MenuItem, Stack, FormControl, InputLabel } from '@mui/material';
|
||||
import {
|
||||
Box, Button, TextField, Typography, Select, MenuItem, Stack, FormControl, InputLabel
|
||||
} from '@mui/material';
|
||||
import { SelectChangeEvent } from '@mui/material';
|
||||
import { SxProps } from '@mui/system';
|
||||
import { ContactPerson, Address, Proposal, DefaultService, OpenAPI, Shipment_Input } from "../../openapi";
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
ContactPersonCreate, ContactPerson, Address, Proposal, ContactsService, AddressesService, ProposalsService,
|
||||
OpenAPI, ShipmentCreate, ShipmentsService
|
||||
} from '../../openapi';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
interface ShipmentFormProps {
|
||||
sx?: SxProps;
|
||||
onCancel: () => void;
|
||||
refreshShipments: () => void; // Add the refresh function as a prop
|
||||
refreshShipments: () => void;
|
||||
}
|
||||
|
||||
const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshShipments }) => {
|
||||
@ -17,37 +22,26 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
const [proposals, setProposals] = React.useState<Proposal[]>([]);
|
||||
const [isCreatingContactPerson, setIsCreatingContactPerson] = React.useState(false);
|
||||
const [isCreatingReturnAddress, setIsCreatingReturnAddress] = React.useState(false);
|
||||
const [newContactPerson, setNewContactPerson] = React.useState({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
phone_number: '',
|
||||
email: '',
|
||||
const [newContactPerson, setNewContactPerson] = React.useState<ContactPersonCreate>({
|
||||
firstname: '', lastname: '', phone_number: '', email: ''
|
||||
});
|
||||
const [newReturnAddress, setNewReturnAddress] = React.useState<Address>({
|
||||
street: '',
|
||||
city: '',
|
||||
zipcode: '',
|
||||
country: ''
|
||||
const [newReturnAddress, setNewReturnAddress] = React.useState<Omit<Address, 'id'>>({
|
||||
street: '', city: '', zipcode: '', country: ''
|
||||
});
|
||||
const [newShipment, setNewShipment] = React.useState<Shipment_Input>({
|
||||
comments: undefined,
|
||||
contact_person: [],
|
||||
dewars: [],
|
||||
proposal_number: [],
|
||||
return_address: [],
|
||||
shipment_date: "",
|
||||
shipment_id: undefined,
|
||||
shipment_name: "",
|
||||
shipment_status: ""
|
||||
const [newShipment, setNewShipment] = React.useState<Partial<ShipmentCreate>>({
|
||||
shipment_name: '', shipment_status: 'In preparation', comments: ''
|
||||
});
|
||||
const [selectedContactPersonId, setSelectedContactPersonId] = React.useState<number | null>(null);
|
||||
const [selectedReturnAddressId, setSelectedReturnAddressId] = React.useState<number | null>(null);
|
||||
const [selectedProposalId, setSelectedProposalId] = React.useState<number | null>(null);
|
||||
const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
OpenAPI.BASE = 'http://127.0.0.1:8000'; // Define Base URL
|
||||
OpenAPI.BASE = 'http://127.0.0.1:8000';
|
||||
|
||||
const getContacts = async () => {
|
||||
try {
|
||||
const c: ContactPerson[] = await DefaultService.getContactsContactsGet();
|
||||
const c: ContactPerson[] = await ContactsService.getContactsContactsGet();
|
||||
setContactPersons(c);
|
||||
} catch {
|
||||
setErrorMessage('Failed to load contact persons. Please try again later.');
|
||||
@ -56,7 +50,7 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
|
||||
const getAddresses = async () => {
|
||||
try {
|
||||
const a: Address[] = await DefaultService.getReturnAddressesReturnAddressesGet();
|
||||
const a: Address[] = await AddressesService.getReturnAddressesAddressesGet();
|
||||
setReturnAddresses(a);
|
||||
} catch {
|
||||
setErrorMessage('Failed to load return addresses. Please try again later.');
|
||||
@ -65,7 +59,7 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
|
||||
const getProposals = async () => {
|
||||
try {
|
||||
const p: Proposal[] = await DefaultService.getProposalsProposalsGet();
|
||||
const p: Proposal[] = await ProposalsService.getProposalsProposalsGet();
|
||||
setProposals(p);
|
||||
} catch {
|
||||
setErrorMessage('Failed to load proposals. Please try again later.');
|
||||
@ -82,10 +76,10 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
const validateZipCode = (zipcode: string) => /^\d{5}(?:[-\s]\d{4})?$/.test(zipcode);
|
||||
|
||||
const isContactFormValid = () => {
|
||||
const { firstName, lastName, phone_number, email } = newContactPerson;
|
||||
const { firstname, lastname, phone_number, email } = newContactPerson;
|
||||
|
||||
if (isCreatingContactPerson) {
|
||||
if (!firstName || !lastName || !validateEmail(email) || !validatePhoneNumber(phone_number)) return false;
|
||||
if (!firstname || !lastname || !validateEmail(email) || !validatePhoneNumber(phone_number)) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
@ -102,10 +96,10 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
};
|
||||
|
||||
const isFormValid = () => {
|
||||
const { shipment_name, proposal_number, contact_person, return_address } = newShipment;
|
||||
const { shipment_name, shipment_status } = newShipment;
|
||||
|
||||
if (!shipment_name || !proposal_number.length) return false;
|
||||
if (!contact_person.length || !return_address.length) return false;
|
||||
if (!shipment_name) return false;
|
||||
if (!selectedContactPersonId || !selectedReturnAddressId || !selectedProposalId) return false;
|
||||
|
||||
if (isCreatingContactPerson && !isContactFormValid()) return false;
|
||||
if (isCreatingReturnAddress && !isAddressFormValid()) return false;
|
||||
@ -116,15 +110,6 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setNewShipment((prev) => ({ ...prev, [name]: value }));
|
||||
if (name === 'email') {
|
||||
setNewContactPerson((prev) => ({ ...prev, email: value }));
|
||||
}
|
||||
if (name === 'phone_number') {
|
||||
setNewContactPerson((prev) => ({ ...prev, phone_number: value }));
|
||||
}
|
||||
if (name === 'zipcode') {
|
||||
setNewReturnAddress((prev) => ({ ...prev, zipcode: value }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveShipment = async () => {
|
||||
@ -133,39 +118,26 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
return;
|
||||
}
|
||||
|
||||
OpenAPI.BASE = 'http://127.0.0.1:8000';
|
||||
|
||||
const payload: Shipment_Input = {
|
||||
const payload: ShipmentCreate = {
|
||||
shipment_name: newShipment.shipment_name || '',
|
||||
shipment_date: new Date().toISOString().split('T')[0],
|
||||
shipment_status: 'In preparation',
|
||||
contact_person: newShipment.contact_person ? newShipment.contact_person.map(person => ({
|
||||
firstname: person.firstname,
|
||||
lastname: person.lastname,
|
||||
phone_number: person.phone_number,
|
||||
email: person.email
|
||||
})) : [],
|
||||
proposal_number: newShipment.proposal_number ? [{
|
||||
id: 1,
|
||||
number: newShipment.proposal_number
|
||||
}] : [],
|
||||
return_address: newShipment.return_address ? newShipment.return_address.map(address => ({
|
||||
id: address.id,
|
||||
street: address.street,
|
||||
city: address.city,
|
||||
zipcode: address.zipcode,
|
||||
country: address.country
|
||||
})) : [],
|
||||
shipment_date: new Date().toISOString().split('T')[0], // Remove if date is not required at all
|
||||
shipment_status: newShipment.shipment_status || 'In preparation',
|
||||
comments: newShipment.comments || '',
|
||||
dewars: []
|
||||
contact_person_id: selectedContactPersonId!,
|
||||
return_address_id: selectedReturnAddressId!,
|
||||
proposal_id: selectedProposalId!,
|
||||
dewars: newShipment.dewars || []
|
||||
};
|
||||
|
||||
console.log('Shipment Payload being sent:', payload);
|
||||
|
||||
try {
|
||||
await DefaultService.createShipmentShipmentsPost(payload);
|
||||
await ShipmentsService.createShipmentShipmentsPost(payload);
|
||||
setErrorMessage(null);
|
||||
refreshShipments(); // Ensure shipments are refreshed after creation
|
||||
onCancel(); // close the form after saving
|
||||
} catch {
|
||||
refreshShipments();
|
||||
onCancel();
|
||||
} catch (error) {
|
||||
console.error('Failed to save shipment:', error);
|
||||
setErrorMessage('Failed to save shipment. Please try again.');
|
||||
}
|
||||
};
|
||||
@ -174,13 +146,10 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
const value = event.target.value;
|
||||
if (value === 'new') {
|
||||
setIsCreatingContactPerson(true);
|
||||
setNewShipment({ ...newShipment, contact_person: [] });
|
||||
setSelectedContactPersonId(null);
|
||||
} else {
|
||||
setIsCreatingContactPerson(false);
|
||||
const selectedPerson = contactPersons.find((person) => person.lastname === value);
|
||||
if (selectedPerson) {
|
||||
setNewShipment({ ...newShipment, contact_person: [{ ...selectedPerson }] });
|
||||
}
|
||||
setSelectedContactPersonId(parseInt(value));
|
||||
}
|
||||
};
|
||||
|
||||
@ -188,44 +157,44 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
const value = event.target.value;
|
||||
if (value === 'new') {
|
||||
setIsCreatingReturnAddress(true);
|
||||
setNewShipment({ ...newShipment, return_address: [] });
|
||||
setSelectedReturnAddressId(null);
|
||||
} else {
|
||||
setIsCreatingReturnAddress(false);
|
||||
const selectedAddress = returnAddresses.find((address) => address.city === value);
|
||||
if (selectedAddress) {
|
||||
setNewShipment({ ...newShipment, return_address: [{ ...selectedAddress }] });
|
||||
}
|
||||
setSelectedReturnAddressId(parseInt(value));
|
||||
}
|
||||
};
|
||||
|
||||
const handleProposalChange = (event: SelectChangeEvent) => {
|
||||
const selectedProposal = event.target.value;
|
||||
setNewShipment({ ...newShipment, proposal_number: selectedProposal });
|
||||
const value = event.target.value;
|
||||
setSelectedProposalId(parseInt(value));
|
||||
};
|
||||
|
||||
const handleSaveNewContactPerson = async () => {
|
||||
if (!validateEmail(newContactPerson.email) || !validatePhoneNumber(newContactPerson.phone_number) ||
|
||||
!newContactPerson.firstName || !newContactPerson.lastName) {
|
||||
if (!isContactFormValid()) {
|
||||
setErrorMessage('Please fill in all new contact person fields correctly.');
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
firstname: newContactPerson.firstName,
|
||||
lastname: newContactPerson.lastName,
|
||||
const payload: ContactPersonCreate = {
|
||||
firstname: newContactPerson.firstname,
|
||||
lastname: newContactPerson.lastname,
|
||||
phone_number: newContactPerson.phone_number,
|
||||
email: newContactPerson.email,
|
||||
};
|
||||
|
||||
console.log('Contact Person Payload being sent:', payload);
|
||||
|
||||
try {
|
||||
const c: ContactPerson = await DefaultService.createContactContactsPost(payload);
|
||||
setContactPersons([...contactPersons, c]);
|
||||
const newPerson: ContactPerson = await ContactsService.createContactContactsPost(payload);
|
||||
setContactPersons([...contactPersons, newPerson]);
|
||||
setErrorMessage(null);
|
||||
} catch {
|
||||
setSelectedContactPersonId(newPerson.id);
|
||||
} catch (error) {
|
||||
console.error('Failed to create a new contact person:', error);
|
||||
setErrorMessage('Failed to create a new contact person. Please try again later.');
|
||||
}
|
||||
|
||||
setNewContactPerson({ firstName: '', lastName: '', phone_number: '', email: '' });
|
||||
setNewContactPerson({ firstname: '', lastname: '', phone_number: '', email: '' });
|
||||
setIsCreatingContactPerson(false);
|
||||
};
|
||||
|
||||
@ -236,18 +205,22 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
street: newReturnAddress.street.trim(),
|
||||
city: newReturnAddress.city.trim(),
|
||||
zipcode: newReturnAddress.zipcode.trim(),
|
||||
country: newReturnAddress.country.trim(),
|
||||
const payload: AddressCreate = {
|
||||
street: newReturnAddress.street,
|
||||
city: newReturnAddress.city,
|
||||
zipcode: newReturnAddress.zipcode,
|
||||
country: newReturnAddress.country,
|
||||
};
|
||||
|
||||
console.log('Return Address Payload being sent:', payload);
|
||||
|
||||
try {
|
||||
const a: Address = await DefaultService.createReturnAddressReturnAddressesPost(payload);
|
||||
setReturnAddresses([...returnAddresses, a]);
|
||||
const response: Address = await AddressesService.createReturnAddressAddressesPost(payload);
|
||||
setReturnAddresses([...returnAddresses, response]);
|
||||
setErrorMessage(null);
|
||||
} catch {
|
||||
setSelectedReturnAddressId(response.id);
|
||||
} catch (error) {
|
||||
console.error('Failed to create a new return address:', error);
|
||||
setErrorMessage('Failed to create a new return address. Please try again later.');
|
||||
}
|
||||
|
||||
@ -282,18 +255,12 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
<FormControl fullWidth required>
|
||||
<InputLabel>Contact Person</InputLabel>
|
||||
<Select
|
||||
value={
|
||||
isCreatingContactPerson
|
||||
? 'new'
|
||||
: newShipment.contact_person.length > 0
|
||||
? newShipment.contact_person[0].lastname
|
||||
: ''
|
||||
}
|
||||
value={selectedContactPersonId ? selectedContactPersonId.toString() : ''}
|
||||
onChange={handleContactPersonChange}
|
||||
displayEmpty
|
||||
>
|
||||
{contactPersons.map((person) => (
|
||||
<MenuItem key={person.lastname} value={person.lastname}>
|
||||
<MenuItem key={person.id} value={person.id.toString()}>
|
||||
{`${person.lastname}, ${person.firstname}`}
|
||||
</MenuItem>
|
||||
))}
|
||||
@ -306,17 +273,17 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
<>
|
||||
<TextField
|
||||
label="First Name"
|
||||
name="firstName"
|
||||
value={newContactPerson.firstName}
|
||||
onChange={(e) => setNewContactPerson({ ...newContactPerson, firstName: e.target.value })}
|
||||
name="firstname"
|
||||
value={newContactPerson.firstname}
|
||||
onChange={(e) => setNewContactPerson({ ...newContactPerson, firstname: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="Last Name"
|
||||
name="lastName"
|
||||
value={newContactPerson.lastName}
|
||||
onChange={(e) => setNewContactPerson({ ...newContactPerson, lastName: e.target.value })}
|
||||
name="lastname"
|
||||
value={newContactPerson.lastname}
|
||||
onChange={(e) => setNewContactPerson({ ...newContactPerson, lastname: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
/>
|
||||
@ -325,28 +292,22 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
name="phone_number"
|
||||
type="tel"
|
||||
value={newContactPerson.phone_number}
|
||||
onChange={(e) => {
|
||||
setNewContactPerson({ ...newContactPerson, phone_number: e.target.value });
|
||||
handleChange(e);
|
||||
}}
|
||||
onChange={(e) => setNewContactPerson({ ...newContactPerson, phone_number: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
error={!validatePhoneNumber(newContactPerson.phone_number)}
|
||||
helperText={!validatePhoneNumber(newContactPerson.phone_number) ? "Invalid phone number" : ""}
|
||||
helperText={!validatePhoneNumber(newContactPerson.phone_number) ? 'Invalid phone number' : ''}
|
||||
/>
|
||||
<TextField
|
||||
label="Email"
|
||||
name="email"
|
||||
type="email"
|
||||
value={newContactPerson.email}
|
||||
onChange={(e) => {
|
||||
setNewContactPerson({ ...newContactPerson, email: e.target.value });
|
||||
handleChange(e);
|
||||
}}
|
||||
onChange={(e) => setNewContactPerson({ ...newContactPerson, email: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
error={!validateEmail(newContactPerson.email)}
|
||||
helperText={!validateEmail(newContactPerson.email) ? "Invalid email" : ""}
|
||||
helperText={!validateEmail(newContactPerson.email) ? 'Invalid email' : ''}
|
||||
/>
|
||||
<Button
|
||||
variant="contained"
|
||||
@ -361,12 +322,12 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
<FormControl fullWidth required>
|
||||
<InputLabel>Proposal Number</InputLabel>
|
||||
<Select
|
||||
value={newShipment.proposal_number || ''}
|
||||
value={selectedProposalId ? selectedProposalId.toString() : ''}
|
||||
onChange={handleProposalChange}
|
||||
displayEmpty
|
||||
>
|
||||
{proposals.map((proposal) => (
|
||||
<MenuItem key={proposal.id} value={proposal.number}>
|
||||
<MenuItem key={proposal.id} value={proposal.id.toString()}>
|
||||
{proposal.number}
|
||||
</MenuItem>
|
||||
))}
|
||||
@ -375,18 +336,12 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
<FormControl fullWidth required>
|
||||
<InputLabel>Return Address</InputLabel>
|
||||
<Select
|
||||
value={
|
||||
isCreatingReturnAddress
|
||||
? 'new'
|
||||
: newShipment.return_address.length > 0
|
||||
? newShipment.return_address[0].city
|
||||
: ''
|
||||
}
|
||||
value={selectedReturnAddressId ? selectedReturnAddressId.toString() : ''}
|
||||
onChange={handleReturnAddressChange}
|
||||
displayEmpty
|
||||
>
|
||||
{returnAddresses.map((address) => (
|
||||
<MenuItem key={address.city} value={address.city}>
|
||||
<MenuItem key={address.id} value={address.id.toString()}>
|
||||
{`${address.street}, ${address.city}, ${address.zipcode}, ${address.country}`}
|
||||
</MenuItem>
|
||||
))}
|
||||
@ -417,14 +372,11 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
label="Zip Code"
|
||||
name="zipcode"
|
||||
value={newReturnAddress.zipcode}
|
||||
onChange={(e) => {
|
||||
setNewReturnAddress({ ...newReturnAddress, zipcode: e.target.value });
|
||||
handleChange(e);
|
||||
}}
|
||||
onChange={(e) => setNewReturnAddress({ ...newReturnAddress, zipcode: e.target.value })}
|
||||
fullWidth
|
||||
required
|
||||
error={!validateZipCode(newReturnAddress.zipcode)}
|
||||
helperText={!validateZipCode(newReturnAddress.zipcode) ? "Invalid zip code" : ""}
|
||||
helperText={!validateZipCode(newReturnAddress.zipcode) ? 'Invalid zip code' : ''}
|
||||
/>
|
||||
<TextField
|
||||
label="Country"
|
||||
@ -459,7 +411,6 @@ const ShipmentForm: React.FC<ShipmentFormProps> = ({ sx = {}, onCancel, refreshS
|
||||
variant="contained"
|
||||
color="primary"
|
||||
onClick={handleSaveShipment}
|
||||
disabled={!isFormValid()}
|
||||
>
|
||||
Save Shipment
|
||||
</Button>
|
||||
|
@ -1,20 +1,20 @@
|
||||
import * as React from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { Button, Box, Typography, IconButton } from '@mui/material';
|
||||
import { Add as AddIcon, Delete as DeleteIcon, UploadFile as UploadFileIcon, Refresh as RefreshIcon } from '@mui/icons-material';
|
||||
import UploadDialog from './UploadDialog';
|
||||
import { Shipment_Input, Dewar, DefaultService } from '../../openapi';
|
||||
import { Dewar, ShipmentsService } from '../../openapi';
|
||||
import { SxProps } from '@mui/material';
|
||||
import bottleGrey from '/src/assets/icons/bottle-svgrepo-com-grey.svg'
|
||||
import bottleYellow from '/src/assets/icons/bottle-svgrepo-com-yellow.svg'
|
||||
import bottleGreen from '/src/assets/icons/bottle-svgrepo-com-green.svg'
|
||||
import bottleRed from '/src/assets/icons/bottle-svgrepo-com-red.svg'
|
||||
import bottleGrey from '/src/assets/icons/bottle-svgrepo-com-grey.svg';
|
||||
import bottleYellow from '/src/assets/icons/bottle-svgrepo-com-yellow.svg';
|
||||
import bottleGreen from '/src/assets/icons/bottle-svgrepo-com-green.svg';
|
||||
import bottleRed from '/src/assets/icons/bottle-svgrepo-com-red.svg';
|
||||
|
||||
interface ShipmentPanelProps {
|
||||
setCreatingShipment: (value: boolean) => void;
|
||||
selectedPage?: string;
|
||||
selectShipment: (shipment: Shipment_Input | null) => void;
|
||||
selectShipment: (shipment: ShipmentsService | null) => void;
|
||||
selectedShipment: ShipmentsService | null;
|
||||
sx?: SxProps;
|
||||
shipments: Shipment_Input[];
|
||||
shipments: ShipmentsService[];
|
||||
refreshShipments: () => void;
|
||||
error: string | null;
|
||||
}
|
||||
@ -29,13 +29,13 @@ const statusIconMap: Record<string, string> = {
|
||||
const ShipmentPanel: React.FC<ShipmentPanelProps> = ({
|
||||
setCreatingShipment,
|
||||
selectShipment,
|
||||
selectedShipment,
|
||||
sx,
|
||||
shipments,
|
||||
refreshShipments,
|
||||
error
|
||||
}) => {
|
||||
const [selectedShipment, setSelectedShipment] = React.useState<Shipment_Input | null>(null);
|
||||
const [uploadDialogOpen, setUploadDialogOpen] = React.useState(false);
|
||||
const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
|
||||
|
||||
const handleDeleteShipment = async () => {
|
||||
if (selectedShipment) {
|
||||
@ -49,28 +49,31 @@ const ShipmentPanel: React.FC<ShipmentPanelProps> = ({
|
||||
const deleteShipment = async (shipmentId: string | undefined) => {
|
||||
if (!shipmentId) return;
|
||||
try {
|
||||
// Assumes DefaultService.deleteShipmentShipmentsShipmentIdDelete is already defined
|
||||
await DefaultService.deleteShipmentShipmentsShipmentIdDelete(shipmentId);
|
||||
refreshShipments(); // Call the refresh function after deletion
|
||||
setSelectedShipment(null);
|
||||
await ShipmentsService.deleteShipmentShipmentsShipmentIdDelete(shipmentId);
|
||||
refreshShipments();
|
||||
selectShipment(null);
|
||||
} catch (error) {
|
||||
// Handle error
|
||||
console.error('Failed to delete shipment:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShipmentSelection = (shipment: Shipment_Input) => {
|
||||
const handleShipmentSelection = (shipment: ShipmentsService) => {
|
||||
const isSelected = selectedShipment?.shipment_id === shipment.shipment_id;
|
||||
const updatedShipment = isSelected ? null : shipment;
|
||||
setSelectedShipment(updatedShipment);
|
||||
console.log("Shipment selected:", updatedShipment); // debug log
|
||||
selectShipment(updatedShipment);
|
||||
};
|
||||
|
||||
const openUploadDialog = () => setUploadDialogOpen(true);
|
||||
const openUploadDialog = (event: React.MouseEvent) => {
|
||||
event.stopPropagation(); // Prevent event bubbling
|
||||
setUploadDialogOpen(true);
|
||||
};
|
||||
|
||||
const closeUploadDialog = () => setUploadDialogOpen(false);
|
||||
|
||||
const getNumberOfDewars = (shipment: Shipment_Input): number => {
|
||||
return shipment.dewars ? shipment.dewars.length : 0;
|
||||
};
|
||||
const getNumberOfDewars = (shipment: ShipmentsService): number => shipment.dewars?.length || 0;
|
||||
|
||||
console.log("Current selected shipment:", selectedShipment); // debug log
|
||||
|
||||
return (
|
||||
<Box sx={{ width: '90%', borderRight: '1px solid #ccc', padding: 2, ...sx }}>
|
||||
@ -123,37 +126,40 @@ const ShipmentPanel: React.FC<ShipmentPanelProps> = ({
|
||||
},
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center' }}>
|
||||
<div style={{ position: 'relative', marginRight: '8px' }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Box sx={{ position: 'relative', marginRight: '8px' }}>
|
||||
<img
|
||||
src={statusIconMap[shipment.shipment_status] || bottleGrey}
|
||||
alt={`Status: ${shipment.shipment_status}`}
|
||||
width="24"
|
||||
/>
|
||||
<span style={{
|
||||
position: 'absolute',
|
||||
top: '0%',
|
||||
right: '0%',
|
||||
transform: 'translate(50%, -50%)',
|
||||
color: 'white',
|
||||
fontWeight: 'bold',
|
||||
fontSize: '0.6rem',
|
||||
backgroundColor: 'transparent',
|
||||
borderRadius: '50%',
|
||||
padding: '0 2px',
|
||||
}}>
|
||||
{getNumberOfDewars(shipment)} {/* Calculate number of dewars */}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
<div>{shipment.shipment_name}</div>
|
||||
<div style={{ fontSize: '0.6rem', color: '#ccc' }}>{shipment.shipment_date}</div>
|
||||
<div style={{ fontSize: '0.6rem', color: '#ccc' }}>
|
||||
<Typography
|
||||
component="span"
|
||||
sx={{
|
||||
position: 'absolute',
|
||||
top: '0%',
|
||||
right: '0%',
|
||||
transform: 'translate(50%, -50%)',
|
||||
color: 'white',
|
||||
fontWeight: 'bold',
|
||||
fontSize: '0.6rem',
|
||||
backgroundColor: 'transparent',
|
||||
borderRadius: '50%',
|
||||
padding: '0 2px',
|
||||
}}
|
||||
>
|
||||
{getNumberOfDewars(shipment)}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography>{shipment.shipment_name}</Typography>
|
||||
<Typography sx={{ fontSize: '0.6rem', color: '#ccc' }}>{shipment.shipment_date}</Typography>
|
||||
<Typography sx={{ fontSize: '0.6rem', color: '#ccc' }}>
|
||||
Total Pucks: {shipment.dewars.reduce((total, dewar: Dewar) => total + dewar.number_of_pucks, 0)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center' }}>
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<IconButton
|
||||
onClick={openUploadDialog}
|
||||
color="primary"
|
||||
@ -164,7 +170,11 @@ const ShipmentPanel: React.FC<ShipmentPanelProps> = ({
|
||||
</IconButton>
|
||||
{selectedShipment?.shipment_id === shipment.shipment_id && (
|
||||
<IconButton
|
||||
onClick={handleDeleteShipment}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
console.log('Delete button clicked'); // debug log
|
||||
handleDeleteShipment();
|
||||
}}
|
||||
color="error"
|
||||
title="Delete Shipment"
|
||||
sx={{ marginLeft: 1 }}
|
||||
@ -172,7 +182,7 @@ const ShipmentPanel: React.FC<ShipmentPanelProps> = ({
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
</div>
|
||||
</Box>
|
||||
</Button>
|
||||
))}
|
||||
<UploadDialog
|
||||
|
@ -3,24 +3,25 @@ import Grid from '@mui/material/Grid';
|
||||
import ShipmentPanel from '../components/ShipmentPanel';
|
||||
import ShipmentDetails from '../components/ShipmentDetails';
|
||||
import ShipmentForm from '../components/ShipmentForm';
|
||||
import { Dewar, Shipment_Input, DefaultService, OpenAPI, ContactPerson } from '../../openapi';
|
||||
import { Dewar, OpenAPI, ContactPerson, ShipmentsService } from '../../openapi';
|
||||
|
||||
type ShipmentViewProps = React.PropsWithChildren<Record<string, never>>;
|
||||
|
||||
const API_BASE_URL = 'http://127.0.0.1:8000';
|
||||
OpenAPI.BASE = API_BASE_URL;
|
||||
OpenAPI.BASE = API_BASE_URL; // Setting API base URL
|
||||
|
||||
const ShipmentView: React.FC<ShipmentViewProps> = () => {
|
||||
const [isCreatingShipment, setIsCreatingShipment] = useState(false);
|
||||
const [selectedShipment, setSelectedShipment] = useState<Shipment_Input | null>(null);
|
||||
const [selectedShipment, setSelectedShipment] = useState<ShipmentsService | null>(null);
|
||||
const [selectedDewar, setSelectedDewar] = useState<Dewar | null>(null);
|
||||
const [shipments, setShipments] = useState<Shipment_Input[]>([]);
|
||||
const [shipments, setShipments] = useState<ShipmentsService[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [defaultContactPerson, setDefaultContactPerson] = useState<ContactPerson | undefined>();
|
||||
|
||||
// Function to fetch and set shipments
|
||||
const fetchAndSetShipments = async () => {
|
||||
try {
|
||||
const shipmentsData: Shipment_Input[] = await DefaultService.getShipmentsShipmentsGet();
|
||||
const shipmentsData: ShipmentsService[] = await ShipmentsService.fetchShipmentsShipmentsGet();
|
||||
shipmentsData.sort((a, b) => new Date(b.shipment_date).getTime() - new Date(a.shipment_date).getTime());
|
||||
setShipments(shipmentsData);
|
||||
console.log('Fetched and set shipments:', shipmentsData);
|
||||
@ -30,15 +31,18 @@ const ShipmentView: React.FC<ShipmentViewProps> = () => {
|
||||
}
|
||||
};
|
||||
|
||||
// Function to fetch the default contact person
|
||||
const fetchDefaultContactPerson = async () => {
|
||||
try {
|
||||
const c: ContactPerson[] = await DefaultService.getContactsContactsGet();
|
||||
setDefaultContactPerson(c[0]);
|
||||
} catch {
|
||||
const contacts: ContactPerson[] = await ShipmentsService.getShipmentContactPersonsShipmentsContactPersonsGet();
|
||||
setDefaultContactPerson(contacts[0]);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch contact persons:', error);
|
||||
setError('Failed to load contact persons. Please try again later.');
|
||||
}
|
||||
};
|
||||
|
||||
// Use effects to fetch data on component mount
|
||||
useEffect(() => {
|
||||
fetchAndSetShipments();
|
||||
fetchDefaultContactPerson();
|
||||
@ -48,7 +52,8 @@ const ShipmentView: React.FC<ShipmentViewProps> = () => {
|
||||
console.log('Updated shipments:', shipments);
|
||||
}, [shipments]);
|
||||
|
||||
const handleSelectShipment = (shipment: Shipment_Input | null) => {
|
||||
// Handlers for selecting shipment and canceling form
|
||||
const handleSelectShipment = (shipment: ShipmentsService | null) => {
|
||||
setSelectedShipment(shipment);
|
||||
setIsCreatingShipment(false);
|
||||
};
|
||||
@ -57,6 +62,7 @@ const ShipmentView: React.FC<ShipmentViewProps> = () => {
|
||||
setIsCreatingShipment(false);
|
||||
};
|
||||
|
||||
// Render the shipment content based on state
|
||||
const renderShipmentContent = () => {
|
||||
if (isCreatingShipment) {
|
||||
return (
|
||||
@ -76,14 +82,15 @@ const ShipmentView: React.FC<ShipmentViewProps> = () => {
|
||||
selectedDewar={selectedDewar}
|
||||
setSelectedDewar={setSelectedDewar}
|
||||
setSelectedShipment={setSelectedShipment}
|
||||
refreshShipments={fetchAndSetShipments}
|
||||
defaultContactPerson={defaultContactPerson}
|
||||
refreshShipments={fetchAndSetShipments} // Ensure refreshShipments is passed here
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <div>No shipment details available.</div>;
|
||||
};
|
||||
|
||||
// Render the main layout
|
||||
return (
|
||||
<Grid container spacing={2} sx={{ height: '100vh' }}>
|
||||
<Grid
|
||||
@ -97,10 +104,10 @@ const ShipmentView: React.FC<ShipmentViewProps> = () => {
|
||||
}}
|
||||
>
|
||||
<ShipmentPanel
|
||||
selectedPage="Shipments"
|
||||
setCreatingShipment={setIsCreatingShipment}
|
||||
selectShipment={handleSelectShipment}
|
||||
shipments={shipments}
|
||||
selectedShipment={selectedShipment}
|
||||
refreshShipments={fetchAndSetShipments}
|
||||
error={error}
|
||||
/>
|
||||
|
Reference in New Issue
Block a user