From 2891b634a2d4545652a0938b7b0fdcac8b95c5f9 Mon Sep 17 00:00:00 2001 From: ROSHAN GARG Date: Wed, 23 Oct 2024 16:28:34 +0530 Subject: [PATCH] stock done --- src/_nav.js | 12 +- src/views/pages/stock/stockTable.js | 342 +++++++++------------------- 2 files changed, 116 insertions(+), 238 deletions(-) diff --git a/src/_nav.js b/src/_nav.js index f0e52e1..14b4843 100644 --- a/src/_nav.js +++ b/src/_nav.js @@ -102,12 +102,12 @@ const _nav = [ }, ], }, - // { - // component: CNavItem, - // name: 'Stock', - // to: '/stock', - // icon: , - // }, + { + component: CNavItem, + name: 'Opening inventory', + to: '/stock', + icon: , + }, { component: CNavItem, name: 'Announcements', diff --git a/src/views/pages/stock/stockTable.js b/src/views/pages/stock/stockTable.js index aa0799f..fc63b09 100644 --- a/src/views/pages/stock/stockTable.js +++ b/src/views/pages/stock/stockTable.js @@ -1,266 +1,144 @@ -import React, { useState, useEffect } from 'react' +import React, { useEffect, useState } from 'react' import { - TableContainer, Table, + TableBody, + TableCell, + TableContainer, TableHead, TableRow, - TableCell, - TableBody, Paper, + TextField, + Button, Typography, TablePagination, - Skeleton, - TextField, - MenuItem, - Select, - FormControl, - InputLabel, - Grid, - Button, + Box, } from '@mui/material' import axios from 'axios' +import { isAutheticated } from '../../../auth' import Axios from '../../../axios' +import Swal from 'sweetalert2' -function StockTable({ apiEndpoint, totalProducts }) { - const [stocks, setStocks] = useState([]) - const [loading, setLoading] = useState(true) - const [page, setPage] = useState(0) +function StockTable() { + const [stocks, setStocks] = useState([]) // Store stock data + const [loading, setLoading] = useState(true) // Loading state const [rowsPerPage, setRowsPerPage] = useState(5) - const [category, setCategory] = useState('') - const [brand, setBrand] = useState('') - const [productName, setProductName] = useState('') - const [isInitialStockMode, setIsInitialStockMode] = useState(false) - const [initialStock, setInitialStock] = useState([]) - const [products, setProducts] = useState() + const [page, setPage] = useState(0) + const token = isAutheticated() - console.log(initialStock, 'initial stock ') - - const fetchProducts = async () => { - try { - const response = await Axios.get('/api/product/getAll/user/') - setProducts(response.data?.products || []) - console.log(response, 'resp of products ') - } catch (error) { - console.log(error) - } - const response = await Axios.get('/api/product/getAll/user/') - setProducts(response.data?.products || []) - } - // Fetch Products from Backend API + // Fetch stock data from the backend const fetchStocks = async () => { - setLoading(true) try { - const response = await axios.get(apiEndpoint, { - params: { category, brand, productName, page, limit: rowsPerPage }, + const response = await Axios.get('/api/pd/stock', { + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, }) - setStocks(response.data.stocks) + setStocks(response.data.stocks || []) } catch (error) { - console.error('Error fetching products:', error) + console.error('Error fetching stocks:', error) } finally { setLoading(false) } } - useEffect(() => { - fetchProducts() - }, []) - useEffect(() => { - fetchStocks() - }, [category, brand, productName, page, rowsPerPage]) - // Pagination Handlers + // Handle stock value change and persist across pagination + const handleStockChange = (productId, value) => { + setStocks((prevStocks) => + prevStocks.map((stock) => + stock.productid === productId ? { ...stock, Stock: parseInt(value, 10) || 0 } : stock, + ), + ) + } + console.log(stocks, 'stocks') + + // Submit updated stock values + const handleSubmit = async () => { + try { + await Axios.put( + '/api/pd/stock-update', + { products: stocks }, + { + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + }, + }, + ) + Swal.fire('success!', 'Stock updated successfully', 'success') + } catch (error) { + console.error('Error updating stock:', error) + Swal.fire('error!', 'Something went wrong', 'error') + } + } + + // Pagination handlers const handleChangePage = (event, newPage) => setPage(newPage) const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)) setPage(0) } - const handleStockChange = (productId, value) => { - setInitialStock((prevStock) => { - const stockExists = prevStock.find((item) => item.productId === productId) - - if (stockExists) { - // Update the existing stock entry - return prevStock.map((item) => - item.productId === productId ? { ...item, stock: value } : item, - ) - } else { - // Add a new stock entry - return [...prevStock, { productId, stock: value }] - } - }) - } - - const handleSubmitInitialStock = async () => { - try { - await axios.post(`${apiEndpoint}/initial-stock`, { stock: initialStock }) - setIsInitialStockMode(false) - fetchProducts() - } catch (error) { - console.error('Error adding initial stock:', error) - } - } - - const formatDateTime = (dateString) => { - const date = new Date(dateString) - return `${date.toDateString()}, ${formatAMPM(date)}` - } - - const formatAMPM = (date) => { - let hours = date.getHours() - const minutes = date.getMinutes() - const ampm = hours >= 12 ? 'PM' : 'AM' - hours = hours % 12 || 12 - return `${hours}:${minutes < 10 ? '0' + minutes : minutes} ${ampm}` - } - - // Check if stock exists - const stockExists = stocks.length > 0 + // Fetch stocks on component mount + useEffect(() => { + fetchStocks() + }, []) return ( -
- {!stockExists && !isInitialStockMode ? ( - - ) : isInitialStockMode ? ( - <> - - Add Initial Stock - - - - - - Product Name - SKU - Stock - - - - {products.map((product) => ( - - {product.name} - {product.SKU} - - item.productId === product._id)?.stock || '' - } - onChange={(e) => handleStockChange(product._id, e.target.value)} - /> - - - ))} - -
-
- - - ) : ( - <> - {/* Filter Controls */} - - - - Category - - - - - - Brand - - - - - setProductName(e.target.value)} - /> - - - - {/* Products Table */} - - - - - Product Name - SKU - Category - Brand - Added On - Price - Stock - - - - {loading ? ( - Array.from(new Array(rowsPerPage)).map((_, index) => ( - - - - - - )) - ) : stocks.length > 0 ? ( - products.map((product) => ( - - {product.name} - {product.sku} - {product.categoryName} - {product.brandName} - {formatDateTime(product.addedOn)} - {product.price.toFixed(2)} - {product.stock} - - )) - ) : ( - - - Data not found - - - )} - -
- -
- - )} -
+ + ) }