Skip to content

Commit

Permalink
chore: Update ProductDialogContext and ProviderProduct constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
edmdz committed Jul 23, 2024
1 parent b81cc2c commit da16efc
Show file tree
Hide file tree
Showing 6 changed files with 253 additions and 28 deletions.
2 changes: 1 addition & 1 deletion src/models/ProviderProduct.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Price from "./Price";
import Provider from "./Provider";

export class ProviderProduct {
constructor(providerId, productId, priceId, numSeries, price = {}, provider = {}) {
constructor({providerId, productId, priceId, numSeries, price = {}, provider = {}}) {
this.providerId = providerId;
this.productId = productId;
this.priceId = priceId;
Expand Down
23 changes: 11 additions & 12 deletions src/pages/Products/ProductDialog/ModelManager.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import { ProductCarModel } from '../../../models/ProductCarModel';
import Brand from '../../../models/Brand';
import { modifyAndClone } from '../../../util/generalUtils';


const ModelManagerDisplay = ({
product,
brand,
Expand All @@ -29,10 +28,10 @@ const ModelManagerDisplay = ({
readOnly = false,
handleStartYearChange,
handleLastYearChange,
handleOnItemAdded
handleOnItemAdded,
isAddButtonDisabled
}) => {
return (

<ExpandableCard title={"Modelos"}>
<Typography gutterBottom variant="body2" component="p" sx={{ mb: 2 }}>
{readOnly ? '' : 'Agrega y gestiona los modelos.'}
Expand Down Expand Up @@ -100,7 +99,12 @@ const ModelManagerDisplay = ({
/>
</Grid>
</Grid>
<Button onClick={handleCarModelAdded} variant="contained" sx={{ mt: 2 }}>
<Button
onClick={handleCarModelAdded}
variant="contained"
sx={{ mt: 2 }}
disabled={isAddButtonDisabled}
>
Agregar Modelo
</Button>
</>
Expand Down Expand Up @@ -186,11 +190,6 @@ const ModelManager = () => {
handleSetProduct(modifyAndClone(product, 'carModels', newProductsCarModels));
};

const handleCarModelCreated = (model) => {
setModels([...models, new CarModel(model)]);
setProductModel({ ...productModel, carModelId: model.id });
};

const handleStartYearChange = (year) => {
setProductModel({ ...productModel, initialYear: year });
}
Expand All @@ -212,6 +211,7 @@ const ModelManager = () => {
handleSetProduct(modifyAndClone(product, 'carModels', [...product.carModels, productModel]));
}

const isAddButtonDisabled = !productModel.carModelId || !productModel.initialYear || !productModel.lastYear;

return (
<ModelManagerDisplay
Expand All @@ -226,14 +226,13 @@ const ModelManager = () => {
handleModelChange={handleModelChange}
handleDeleteModel={handleDeleteModel}
readOnly={false}
handleCarModelCreated={handleCarModelCreated}
handleStartYearChange={handleStartYearChange}
handleLastYearChange={handleLastYearChange}
handleOnItemAdded={handleOnItemAdded}
handleCarModelAdded={handleCarModelAdded}
isAddButtonDisabled={isAddButtonDisabled}
/>
);
};

export { ModelManager as default, ModelManagerDisplay }

export { ModelManager as default, ModelManagerDisplay }
13 changes: 11 additions & 2 deletions src/pages/Products/ProductDialog/PriceManager.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const PriceManagerDisplay = ({
setPrice,
handleDeletePrice,
handleAddPrice,
isAddButtonDisabled,
readOnly = false
}) => {
return (
Expand Down Expand Up @@ -45,7 +46,12 @@ const PriceManagerDisplay = ({
}}
fullWidth
/>
<Button onClick={handleAddPrice} variant="contained" sx={{ mt: 2 }}>
<Button
onClick={handleAddPrice}
variant="contained"
sx={{ mt: 2 }}
disabled={isAddButtonDisabled}
>
Agregar Precio
</Button>
</Box>
Expand Down Expand Up @@ -91,15 +97,18 @@ const PriceManagerContainer = () => {
handleSetProduct({ ...product, prices: updatedPrices });
};

const isAddButtonDisabled = !price.description || !price.cost;

return (
<PriceManagerDisplay
product={product}
price={price}
setPrice={setPrice}
handleDeletePrice={handleDeletePrice}
handleAddPrice={handleAddPrice}
isAddButtonDisabled={isAddButtonDisabled}
/>
);
};

export { PriceManagerContainer as default, PriceManagerDisplay }
export { PriceManagerContainer as default, PriceManagerDisplay }
1 change: 1 addition & 0 deletions src/pages/Products/ProductDialog/ProductDialogContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export const ProductDialogProvider = ({ children }) => {
const resetState = () => {
setSelectedProduct(null);
setIsEditable(false);
setActiveStep(0);
setProduct(new Product({}));
};

Expand Down
238 changes: 225 additions & 13 deletions src/pages/Products/ProductDialog/ProviderManager.jsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,232 @@
import { Typography, Box } from '@mui/material';
import { useState, useEffect } from 'react';
import {
Button, Table, TableBody, TableCell, TableHead, TableRow, TextField, IconButton, Typography, Grid,
Modal, Box, Card, CardContent
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import ExpandableCard from '../../../components/ExpandableCard';
import CustomSelectWithAdd from '../../../components/CustomSelectWithAdd';
import { useProductDialogContext } from './ProductDialogContext';
import { getAll, createProvider } from '../../../services/ProviderService';
import { useSnackbar } from '../../../components/SnackbarContext';
import { modifyAndClone } from '../../../util/generalUtils';
import Provider from '../../../models/Provider';

const ProviderManager = () => {
// Aquí iría el estado y la lógica para manejar proveedores si fuera necesario
// Por ahora, el componente está preparado pero no implementa funcionalidad específica
const ProviderDetailModal = ({ open, onClose, provider }) => (
<Modal
open={open}
onClose={onClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
p: 4,
}}>
<Card>
<CardContent>
<Typography variant="h5" component="div" sx={{ marginBottom: 2 }}>
Detalles del Proveedor
</Typography>
<Typography variant="body2" color="text.secondary" gutterBottom>
<strong>Nombre:</strong> {provider?.name}
</Typography>
<Typography variant="body2" color="text.secondary" gutterBottom>
<strong>Teléfono:</strong> {provider?.phoneNumber}
</Typography>
<Typography variant="body2" color="text.secondary" gutterBottom>
<strong>Dirección:</strong> {provider?.address}
</Typography>
<Typography variant="body2" color="text.secondary" gutterBottom>
<strong>Comentarios:</strong> {provider?.comments}
</Typography>
<Button variant="contained" onClick={onClose} style={{ marginTop: 2 }}>Cerrar</Button>
</CardContent>
</Card>
</Box>
</Modal>
);

const ProviderManagerDisplay = ({
product,
providers,
selectedProvider,
price,
handleProviderChange,
handlePriceChange,
handleAddProvider,
handleDeleteProvider,
handleOnProviderAdded,
handleProviderClick,
editable
}) => (
<ExpandableCard title="Proveedores">
<Typography gutterBottom variant="body2" component="p" sx={{ mb: 2 }}>
{editable ? 'Añade y gestiona los proveedores del producto.' : ''}
</Typography>
{editable && (
<>
<Grid container spacing={2} sx={{ mb: 2 }}>
<Grid item xs={12} sm={6}>
<CustomSelectWithAdd
elements={providers}
label="Proveedor"
selectedItem={selectedProvider}
setSelectedItem={handleProviderChange}
onItemAdded={handleOnProviderAdded}
dialogFields={[
{ name: 'name', label: 'Nombre del Proveedor', type: 'text', required: true },
{ name: 'phoneNumber', label: 'Número de Teléfono', type: 'tel' },
{ name: 'address', label: 'Dirección', type: 'text' },
{ name: 'comments', label: 'Comentarios', type: 'text' },
]}
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
label="Precio de Compra"
type="number"
value={price}
onChange={handlePriceChange}
fullWidth
/>
</Grid>
</Grid>
<Button onClick={handleAddProvider} variant="contained" sx={{ mt: 2 }} disabled={!selectedProvider || !price}>
Agregar Proveedor
</Button>
</>
)}
<Table size="small" sx={{ mt: 4 }}>
<TableHead>
<TableRow>
<TableCell>Proveedor</TableCell>
<TableCell align="right">Precio de Compra</TableCell>
{editable && <TableCell align="right">Acciones</TableCell>}
</TableRow>
</TableHead>
<TableBody>
{product.providers && product.providers.map((providerProduct, index) => (
<TableRow
key={index}
onClick={() => handleProviderClick(providerProduct.provider)}
sx={{ cursor: 'pointer', '&:hover': { backgroundColor: 'rgba(0, 0, 0, 0.04)' } }}
>
<TableCell>{providerProduct.provider.name}</TableCell>
<TableCell align="right">{providerProduct.price.cost}</TableCell>
{editable && (
<TableCell align="right">
<IconButton
onClick={(e) => {
e.stopPropagation();
handleDeleteProvider(index);
}}
aria-label="delete"
>
<DeleteIcon />
</IconButton>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
</ExpandableCard>
);

const ProviderManager = ({ editable = true }) => {
const [providers, setProviders] = useState([]);
const [selectedProvider, setSelectedProvider] = useState(null);
const [price, setPrice] = useState('');
const [modalOpen, setModalOpen] = useState(false);
const [selectedModalProvider, setSelectedModalProvider] = useState(null);
const { openSnackbar } = useSnackbar();
const { product, handleSetProduct } = useProductDialogContext();

useEffect(() => {
const fetchProviders = async () => {
try {
const response = await getAll();
if (response && response.providers) {
setProviders(response.providers);
}
} catch (error) {
openSnackbar(`Error al obtener los proveedores: ${error.message}`, 'error');
}
};
fetchProviders();
}, []);

const handleProviderChange = (provider) => {
setSelectedProvider(provider);
};

const handlePriceChange = (event) => {
setPrice(event.target.value);
};

const handleAddProvider = () => {
if (selectedProvider && price) {
const newProviderProduct = {
providerId: selectedProvider.id,
provider: selectedProvider,
price: {
cost: parseFloat(price),
description: `Precio de compra de ${selectedProvider.name}`
}
};
handleSetProduct(modifyAndClone(product, 'providers', [...(product.providers || []), newProviderProduct]));
setSelectedProvider(null);
setPrice('');
}
};

const handleDeleteProvider = (index) => {
const newProviders = product.providers.filter((_, i) => i !== index);
handleSetProduct(modifyAndClone(product, 'providers', newProviders));
};

const handleOnProviderAdded = async (providers, newProviderData) => {
try {
const newProvider = await createProvider(new Provider(newProviderData));
setProviders([...providers, newProvider]);
return newProvider.id;
} catch (error) {
openSnackbar(`Error al crear el proveedor: ${error.message}`, 'error');
}
};

const handleProviderClick = (provider) => {
setSelectedModalProvider(provider);
setModalOpen(true);
};

return (
<ExpandableCard title="Proveedores">
<Typography gutterBottom variant="body2" component="p" sx={{ mb: 2 }}>
Añade y gestiona tus proveedores.
</Typography>
<Box sx={{ mb: 2 }}>
</Box>
{/* Aquí iría la lógica para listar y gestionar proveedores */}
</ExpandableCard>
<>
<ProviderManagerDisplay
product={product}
providers={providers}
selectedProvider={selectedProvider}
price={price}
handleProviderChange={handleProviderChange}
handlePriceChange={handlePriceChange}
handleAddProvider={handleAddProvider}
handleDeleteProvider={handleDeleteProvider}
handleOnProviderAdded={handleOnProviderAdded}
handleProviderClick={handleProviderClick}
editable={editable}
/>
<ProviderDetailModal
open={modalOpen}
onClose={() => setModalOpen(false)}
provider={selectedModalProvider}
/>
</>
);
};

export default ProviderManager;
export { ProviderManager as default, ProviderManagerDisplay };
4 changes: 4 additions & 0 deletions src/pages/Products/ProductSummary.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ModelManagerDisplay } from "./ProductDialog/ModelManager";
import { PriceManagerDisplay } from "./ProductDialog/PriceManager";
import ImageUpload from './ProductDialog/ImageUpload';
import { ProductTypes } from './ProductsConstants';
import ProviderManager from './ProductDialog/ProviderManager';

const ProductSummary = ({ productType, product }) => {
let images = product.files.map(file => file.fileData);
Expand Down Expand Up @@ -44,6 +45,9 @@ const ProductSummary = ({ productType, product }) => {
<Grid item xs={12}>
<PriceManagerDisplay product={product} readOnly={true} />
</Grid>
<Grid item xs={12}>
<ProviderManager product={product} editable={false} />
</Grid>
</Grid>
</Box>
</div>
Expand Down

0 comments on commit da16efc

Please sign in to comment.