Get data loading in frontend

This commit is contained in:
2025-01-09 17:08:46 -05:00
parent 608f376790
commit 9034897ef1
9 changed files with 253 additions and 201 deletions

View File

@@ -1,36 +1,35 @@
const express = require('express');
const router = express.Router();
// Get dashboard statistics
// Get dashboard stats
router.get('/stats', async (req, res) => {
const pool = req.app.locals.pool;
try {
const [totalProducts] = await pool.query(
'SELECT COUNT(*) as count FROM products WHERE visible = true'
);
const [lowStockProducts] = await pool.query(
'SELECT COUNT(*) as count FROM products WHERE stock_quantity <= 10 AND visible = true'
);
const [orderStats] = await pool.query(`
const [stats] = await pool.query(`
SELECT
COUNT(DISTINCT order_number) as total_orders,
AVG(price * quantity - COALESCE(discount, 0)) as avg_order_value
FROM orders
WHERE canceled = false
AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
COUNT(*) as totalProducts,
COUNT(CASE WHEN stock_quantity <= 5 THEN 1 END) as lowStockProducts,
COALESCE(
(SELECT COUNT(DISTINCT order_number) FROM orders WHERE DATE(date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND canceled = false),
0
) as totalOrders,
COALESCE(
(SELECT AVG(subtotal) FROM (
SELECT order_number, SUM(price * quantity) as subtotal
FROM orders
WHERE DATE(date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
AND canceled = false
GROUP BY order_number
) t),
0
) as averageOrderValue
FROM products
WHERE visible = true
`);
res.json({
totalProducts: totalProducts[0].count,
lowStockProducts: lowStockProducts[0].count,
totalOrders: orderStats[0].total_orders || 0,
averageOrderValue: orderStats[0].avg_order_value || 0
});
res.json(stats[0]);
} catch (error) {
console.error('Error fetching dashboard stats:', error);
res.status(500).json({ error: 'Failed to fetch dashboard statistics' });
res.status(500).json({ error: 'Failed to fetch dashboard stats' });
}
});
@@ -41,15 +40,17 @@ router.get('/sales-overview', async (req, res) => {
const [rows] = await pool.query(`
SELECT
DATE(date) as date,
SUM(price * quantity - COALESCE(discount, 0)) as total
SUM(price * quantity) as total
FROM orders
WHERE canceled = false
AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
WHERE DATE(date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
AND canceled = false
GROUP BY DATE(date)
ORDER BY date ASC
`);
res.json(rows);
res.json(rows.map(row => ({
...row,
total: parseFloat(row.total || 0)
})));
} catch (error) {
console.error('Error fetching sales overview:', error);
res.status(500).json({ error: 'Failed to fetch sales overview' });
@@ -62,31 +63,35 @@ router.get('/recent-orders', async (req, res) => {
try {
const [rows] = await pool.query(`
SELECT
order_number as id,
customer,
date,
SUM(price * quantity - COALESCE(discount, 0)) as amount
FROM orders
WHERE canceled = false
GROUP BY order_number, customer, date
ORDER BY date DESC
o1.order_number as order_id,
o1.customer as customer_name,
SUM(o2.price * o2.quantity) as total_amount,
o1.date as order_date
FROM orders o1
JOIN orders o2 ON o1.order_number = o2.order_number
WHERE o1.canceled = false
GROUP BY o1.order_number, o1.customer, o1.date
ORDER BY o1.date DESC
LIMIT 5
`);
res.json(rows);
res.json(rows.map(row => ({
...row,
total_amount: parseFloat(row.total_amount || 0),
order_date: row.order_date
})));
} catch (error) {
console.error('Error fetching recent orders:', error);
res.status(500).json({ error: 'Failed to fetch recent orders' });
}
});
// Get category statistics
// Get category stats
router.get('/category-stats', async (req, res) => {
const pool = req.app.locals.pool;
try {
const [rows] = await pool.query(`
SELECT
COALESCE(NULLIF(categories, ''), 'Uncategorized') as category,
categories,
COUNT(*) as count
FROM products
WHERE visible = true
@@ -94,11 +99,10 @@ router.get('/category-stats', async (req, res) => {
ORDER BY count DESC
LIMIT 10
`);
res.json(rows);
} catch (error) {
console.error('Error fetching category stats:', error);
res.status(500).json({ error: 'Failed to fetch category statistics' });
res.status(500).json({ error: 'Failed to fetch category stats' });
}
});
@@ -109,13 +113,12 @@ router.get('/stock-levels', async (req, res) => {
const [rows] = await pool.query(`
SELECT
SUM(CASE WHEN stock_quantity = 0 THEN 1 ELSE 0 END) as outOfStock,
SUM(CASE WHEN stock_quantity > 0 AND stock_quantity <= 10 THEN 1 ELSE 0 END) as lowStock,
SUM(CASE WHEN stock_quantity > 10 AND stock_quantity <= 50 THEN 1 ELSE 0 END) as inStock,
SUM(CASE WHEN stock_quantity > 50 THEN 1 ELSE 0 END) as overStock
SUM(CASE WHEN stock_quantity > 0 AND stock_quantity <= 5 THEN 1 ELSE 0 END) as lowStock,
SUM(CASE WHEN stock_quantity > 5 AND stock_quantity <= 20 THEN 1 ELSE 0 END) as inStock,
SUM(CASE WHEN stock_quantity > 20 THEN 1 ELSE 0 END) as overStock
FROM products
WHERE visible = true
`);
res.json(rows[0]);
} catch (error) {
console.error('Error fetching stock levels:', error);

View File

@@ -1,21 +1,32 @@
const express = require('express');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const { importProductsFromCSV } = require('../utils/csvImporter');
const multer = require('multer');
const { importProductsFromCSV } = require('../utils/csvImporter');
// Configure multer for file uploads
const upload = multer({ dest: 'uploads/' });
// Get all products with their current inventory levels
// Get all products
router.get('/', async (req, res) => {
const pool = req.app.locals.pool;
try {
const [rows] = await pool.query(`
SELECT p.*, il.quantity, il.reorder_point, il.reorder_quantity
FROM products p
LEFT JOIN inventory_levels il ON p.id = il.product_id
ORDER BY p.created_at DESC
SELECT
product_id,
title,
SKU,
stock_quantity,
price,
regular_price,
cost_price,
vendor,
brand,
categories,
visible,
managing_stock
FROM products
WHERE visible = true
ORDER BY title ASC
`);
res.json(rows);
} catch (error) {
@@ -24,16 +35,14 @@ router.get('/', async (req, res) => {
}
});
// Get a single product with its inventory details
// Get a single product
router.get('/:id', async (req, res) => {
const pool = req.app.locals.pool;
try {
const [rows] = await pool.query(`
SELECT p.*, il.quantity, il.reorder_point, il.reorder_quantity
FROM products p
LEFT JOIN inventory_levels il ON p.id = il.product_id
WHERE p.id = ?
`, [req.params.id]);
const [rows] = await pool.query(
'SELECT * FROM products WHERE product_id = ? AND visible = true',
[req.params.id]
);
if (rows.length === 0) {
return res.status(404).json({ error: 'Product not found' });
@@ -45,41 +54,6 @@ router.get('/:id', async (req, res) => {
}
});
// Create a new product
router.post('/', async (req, res) => {
const pool = req.app.locals.pool;
const { sku, name, description, category } = req.body;
const id = uuidv4();
try {
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
await connection.query(
'INSERT INTO products (id, sku, name, description, category) VALUES (?, ?, ?, ?, ?)',
[id, sku, name, description, category]
);
await connection.query(
'INSERT INTO inventory_levels (id, product_id, quantity) VALUES (?, ?, 0)',
[uuidv4(), id]
);
await connection.commit();
res.status(201).json({ id, sku, name, description, category });
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
} catch (error) {
console.error('Error creating product:', error);
res.status(500).json({ error: 'Failed to create product' });
}
});
// Import products from CSV
router.post('/import', upload.single('file'), async (req, res) => {
if (!req.file) {
@@ -97,41 +71,4 @@ router.post('/import', upload.single('file'), async (req, res) => {
}
});
// Update product inventory
router.post('/:id/inventory', async (req, res) => {
const pool = req.app.locals.pool;
const { quantity, type, notes } = req.body;
try {
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
// Create inventory transaction
await connection.query(
'INSERT INTO inventory_transactions (id, product_id, transaction_type, quantity, notes) VALUES (?, ?, ?, ?, ?)',
[uuidv4(), req.params.id, type, quantity, notes]
);
// Update inventory level
const quantityChange = type === 'sale' ? -quantity : quantity;
await connection.query(
'UPDATE inventory_levels SET quantity = quantity + ? WHERE product_id = ?',
[quantityChange, req.params.id]
);
await connection.commit();
res.json({ success: true });
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
} catch (error) {
console.error('Error updating inventory:', error);
res.status(500).json({ error: 'Failed to update inventory' });
}
});
module.exports = router;

View File

@@ -2,7 +2,7 @@ const path = require('path');
const fs = require('fs');
// Get the absolute path to the .env file
const envPath = path.resolve('/var/www/html/inventory/.env');
const envPath = path.resolve(process.cwd(), '.env');
console.log('Current working directory:', process.cwd());
console.log('Looking for .env file at:', envPath);
console.log('.env file exists:', fs.existsSync(envPath));
@@ -10,6 +10,13 @@ console.log('.env file exists:', fs.existsSync(envPath));
try {
require('dotenv').config({ path: envPath });
console.log('.env file loaded successfully');
console.log('Environment check:', {
NODE_ENV: process.env.NODE_ENV || 'not set',
PORT: process.env.PORT || 'not set',
DB_HOST: process.env.DB_HOST || 'not set',
DB_USER: process.env.DB_USER || 'not set',
DB_NAME: process.env.DB_NAME || 'not set',
});
} catch (error) {
console.error('Error loading .env file:', error);
}
@@ -39,15 +46,18 @@ const dashboardRouter = require('./routes/dashboard');
const app = express();
// CORS configuration
// CORS configuration - move before route handlers
app.use(cors({
origin: ['https://inventory.kent.pw', 'https://www.inventory.kent.pw'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
credentials: true,
optionsSuccessStatus: 200 // Some legacy browsers (IE11) choke on 204
}));
// Body parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Request logging middleware
app.use((req, res, next) => {
@@ -61,6 +71,16 @@ app.use((req, res, next) => {
next();
});
// Error handling middleware - move before route handlers
app.use((err, req, res, next) => {
console.error(`[${new Date().toISOString()}] Error:`, err);
res.status(500).json({
error: process.env.NODE_ENV === 'production'
? 'An internal server error occurred'
: err.message
});
});
// Database connection pool
const pool = mysql.createPool({
host: process.env.DB_HOST,
@@ -101,16 +121,6 @@ app.get('/health', (req, res) => {
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(`[${new Date().toISOString()}] Error:`, err);
res.status(500).json({
error: process.env.NODE_ENV === 'production'
? 'An internal server error occurred'
: err.message
});
});
// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
console.error(`[${new Date().toISOString()}] Uncaught Exception:`, err);

View File

@@ -4,7 +4,7 @@ import { Bar, BarChart, ResponsiveContainer, XAxis, YAxis } from 'recharts';
import config from '../../config';
interface CategoryStats {
category: string;
categories: string;
count: number;
}
@@ -16,7 +16,7 @@ interface StockLevels {
}
export function InventoryStats() {
const { data: categoryStats } = useQuery<CategoryStats[]>({
const { data: categoryStats, isLoading: categoryLoading, error: categoryError } = useQuery<CategoryStats[]>({
queryKey: ['category-stats'],
queryFn: async () => {
const response = await fetch(`${config.apiUrl}/dashboard/category-stats`);
@@ -27,7 +27,7 @@ export function InventoryStats() {
},
});
const { data: stockLevels } = useQuery<StockLevels>({
const { data: stockLevels, isLoading: stockLoading, error: stockError } = useQuery<StockLevels>({
queryKey: ['stock-levels'],
queryFn: async () => {
const response = await fetch(`${config.apiUrl}/dashboard/stock-levels`);
@@ -38,6 +38,14 @@ export function InventoryStats() {
},
});
if (categoryLoading || stockLoading) {
return <div>Loading inventory stats...</div>;
}
if (categoryError || stockError) {
return <div className="text-red-500">Error loading inventory stats</div>;
}
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
<Card className="col-span-4">
@@ -48,7 +56,7 @@ export function InventoryStats() {
<ResponsiveContainer width="100%" height={350}>
<BarChart data={categoryStats}>
<XAxis
dataKey="category"
dataKey="categories"
stroke="#888888"
fontSize={12}
tickLine={false}

View File

@@ -8,14 +8,19 @@ interface SalesData {
}
export function Overview() {
const { data, isLoading } = useQuery<SalesData[]>({
const { data, isLoading, error } = useQuery<SalesData[]>({
queryKey: ['sales-overview'],
queryFn: async () => {
const response = await fetch(`${config.apiUrl}/dashboard/sales-overview`);
if (!response.ok) {
throw new Error('Failed to fetch sales overview');
}
return response.json();
const rawData = await response.json();
return rawData.map((item: SalesData) => ({
...item,
total: parseFloat(item.total.toString()),
date: new Date(item.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}));
},
});
@@ -23,6 +28,10 @@ export function Overview() {
return <div>Loading chart...</div>;
}
if (error) {
return <div className="text-red-500">Error loading sales overview</div>;
}
return (
<ResponsiveContainer width="100%" height={350}>
<LineChart data={data}>
@@ -38,9 +47,12 @@ export function Overview() {
fontSize={12}
tickLine={false}
axisLine={false}
tickFormatter={(value) => `$${value}`}
tickFormatter={(value) => `$${value.toLocaleString()}`}
/>
<Tooltip
formatter={(value: number) => [`$${value.toLocaleString()}`, 'Sales']}
labelFormatter={(label) => `Date: ${label}`}
/>
<Tooltip />
<Line
type="monotone"
dataKey="total"

View File

@@ -3,21 +3,25 @@ import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import config from '../../config';
interface RecentOrder {
id: string;
customer: string;
amount: number;
date: string;
order_id: string;
customer_name: string;
total_amount: number;
order_date: string;
}
export function RecentSales() {
const { data: recentOrders, isLoading } = useQuery<RecentOrder[]>({
const { data: recentOrders, isLoading, error } = useQuery<RecentOrder[]>({
queryKey: ['recent-orders'],
queryFn: async () => {
const response = await fetch(`${config.apiUrl}/dashboard/recent-orders`);
if (!response.ok) {
throw new Error('Failed to fetch recent orders');
}
return response.json();
const data = await response.json();
return data.map((order: RecentOrder) => ({
...order,
total_amount: parseFloat(order.total_amount.toString())
}));
},
});
@@ -25,26 +29,35 @@ export function RecentSales() {
return <div>Loading recent sales...</div>;
}
if (error) {
return <div className="text-red-500">Error loading recent sales</div>;
}
return (
<div className="space-y-8">
{recentOrders?.map((order) => (
<div key={order.id} className="flex items-center">
<div key={order.order_id} className="flex items-center">
<Avatar className="h-9 w-9">
<AvatarFallback>
{order.customer.split(' ').map(n => n[0]).join('')}
{order.customer_name?.split(' ').map(n => n[0]).join('') || '??'}
</AvatarFallback>
</Avatar>
<div className="ml-4 space-y-1">
<p className="text-sm font-medium leading-none">Order #{order.id}</p>
<p className="text-sm font-medium leading-none">Order #{order.order_id}</p>
<p className="text-sm text-muted-foreground">
{new Date(order.date).toLocaleDateString()}
{new Date(order.order_date).toLocaleDateString()}
</p>
</div>
<div className="ml-auto font-medium">
+${order.amount.toFixed(2)}
${order.total_amount.toFixed(2)}
</div>
</div>
))}
{!recentOrders?.length && (
<div className="text-center text-muted-foreground">
No recent orders found
</div>
)}
</div>
);
}

View File

@@ -13,19 +13,41 @@ interface DashboardStats {
averageOrderValue: number;
}
interface Order {
order_id: string;
customer_name: string;
total_amount: number;
order_date: string;
}
export function Dashboard() {
const { data: stats, isLoading } = useQuery<DashboardStats>({
const { data: stats, isLoading: statsLoading } = useQuery<DashboardStats>({
queryKey: ['dashboard-stats'],
queryFn: async () => {
const response = await fetch(`${config.apiUrl}/dashboard/stats`);
if (!response.ok) {
throw new Error('Failed to fetch dashboard stats');
}
const data = await response.json();
return {
...data,
averageOrderValue: parseFloat(data.averageOrderValue) || 0
};
},
});
const { data: orders, isLoading: ordersLoading } = useQuery<Order[]>({
queryKey: ['recent-orders'],
queryFn: async () => {
const response = await fetch(`${config.apiUrl}/dashboard/recent-orders`);
if (!response.ok) {
throw new Error('Failed to fetch recent orders');
}
return response.json();
},
});
if (isLoading) {
if (statsLoading) {
return <div className="p-8">Loading dashboard...</div>;
}
@@ -49,7 +71,7 @@ export function Dashboard() {
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats?.totalProducts}</div>
<div className="text-2xl font-bold">{stats?.totalProducts || 0}</div>
</CardContent>
</Card>
<Card>
@@ -59,7 +81,7 @@ export function Dashboard() {
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats?.lowStockProducts}</div>
<div className="text-2xl font-bold">{stats?.lowStockProducts || 0}</div>
</CardContent>
</Card>
<Card>
@@ -69,7 +91,7 @@ export function Dashboard() {
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stats?.totalOrders}</div>
<div className="text-2xl font-bold">{stats?.totalOrders || 0}</div>
</CardContent>
</Card>
<Card>
@@ -80,7 +102,7 @@ export function Dashboard() {
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
${stats?.averageOrderValue.toFixed(2)}
${(stats?.averageOrderValue || 0).toFixed(2)}
</div>
</CardContent>
</Card>
@@ -107,6 +129,45 @@ export function Dashboard() {
<TabsContent value="inventory" className="space-y-4">
<InventoryStats />
</TabsContent>
<TabsContent value="orders" className="space-y-4">
<div className="grid gap-4">
<Card>
<CardHeader>
<CardTitle>Recent Orders</CardTitle>
</CardHeader>
<CardContent>
{ordersLoading ? (
<div>Loading orders...</div>
) : orders && orders.length > 0 ? (
<div className="space-y-8">
{orders.map((order) => (
<div key={order.order_id} className="flex items-center">
<div className="ml-4 space-y-1">
<p className="text-sm font-medium leading-none">
Order #{order.order_id}
</p>
<p className="text-sm text-muted-foreground">
{order.customer_name}
</p>
<p className="text-sm text-muted-foreground">
{new Date(order.order_date).toLocaleDateString()}
</p>
</div>
<div className="ml-auto font-medium">
${order.total_amount.toFixed(2)}
</div>
</div>
))}
</div>
) : (
<div className="text-center text-muted-foreground">
No recent orders found
</div>
)}
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>
</div>
);

View File

@@ -2,14 +2,18 @@ import { useQuery } from '@tanstack/react-query';
import config from '../config';
interface Product {
id: string;
sku: string;
name: string;
description: string | null;
category: string | null;
quantity: number;
reorder_point: number | null;
reorder_quantity: number | null;
product_id: string;
title: string;
SKU: string;
stock_quantity: number;
price: number;
regular_price: number;
cost_price: number;
vendor: string;
brand: string;
categories: string;
visible: boolean;
managing_stock: boolean;
}
export function Products() {
@@ -20,7 +24,13 @@ export function Products() {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
const data = await response.json();
return data.map((product: Product) => ({
...product,
price: parseFloat(product.price?.toString() || '0'),
regular_price: parseFloat(product.regular_price?.toString() || '0'),
cost_price: parseFloat(product.cost_price?.toString() || '0')
}));
},
});
@@ -34,38 +44,29 @@ export function Products() {
return (
<div className="p-8">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold">Products</h1>
<button className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90">
Add Product
</button>
</div>
<h1 className="text-2xl font-bold mb-6">Products</h1>
<div className="border rounded-lg">
<table className="w-full">
<thead>
<tr className="border-b bg-muted/50">
<th className="text-left p-4 font-medium">SKU</th>
<th className="text-left p-4 font-medium">Name</th>
<th className="text-left p-4 font-medium">Category</th>
<th className="text-right p-4 font-medium">Quantity</th>
<th className="text-right p-4 font-medium">Reorder Point</th>
<th className="text-right p-4 font-medium">Actions</th>
<th className="text-left p-4 font-medium">Title</th>
<th className="text-left p-4 font-medium">Brand</th>
<th className="text-left p-4 font-medium">Vendor</th>
<th className="text-right p-4 font-medium">Stock</th>
<th className="text-right p-4 font-medium">Price</th>
</tr>
</thead>
<tbody>
{products?.map((product) => (
<tr key={product.id} className="border-b">
<td className="p-4">{product.sku}</td>
<td className="p-4">{product.name}</td>
<td className="p-4">{product.category || '-'}</td>
<td className="p-4 text-right">{product.quantity}</td>
<td className="p-4 text-right">{product.reorder_point || '-'}</td>
<td className="p-4 text-right">
<button className="text-sm text-primary hover:underline">
Edit
</button>
</td>
<tr key={product.product_id} className="border-b">
<td className="p-4">{product.SKU}</td>
<td className="p-4">{product.title}</td>
<td className="p-4">{product.brand || '-'}</td>
<td className="p-4">{product.vendor || '-'}</td>
<td className="p-4 text-right">{product.stock_quantity}</td>
<td className="p-4 text-right">${(product.price || 0).toFixed(2)}</td>
</tr>
))}
{!products?.length && (

7
mountremote.command Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/zsh
#Clear previous mount in case its still there
umount ~/Dev/inventory/inventory-server
#Mount
sshfs matt@dashboard.kent.pw:/var/www/html/inventory -p 22122 ~/Dev/inventory/inventory-server/