import React, { useState, useEffect } from 'react';
import { Search, ShoppingCart, Package, BarChart2, User, LogOut, Plus, Minus, Trash2, X, Check, DollarSign, Eye, EyeOff, Settings, Printer, Clock, CreditCard, Smartphone, Database, RefreshCw } from 'lucide-react';
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set, get, push, remove, update, onValue, off } from 'firebase/database';
import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut } from 'firebase/auth';
// Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyB23QNvvyZ6TqKlk_nJ3CpSecbCuT8lc1A",
authDomain: "cacid01.firebaseapp.com",
databaseURL: "https://cacid01-default-rtdb.firebaseio.com",
projectId: "cacid01",
storageBucket: "cacid01.firebasestorage.app",
messagingSenderId: "1051604944772",
appId: "1:1051604944772:web:0f3fbdaa45498285093fd1",
measurementId: "G-6RJT513ZRV"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth(app);
// Main POS Application
export default function POSSystem() {
// State management
const [activeTab, setActiveTab] = useState('pos');
const [products, setProducts] = useState([]);
const [cart, setCart] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [user, setUser] = useState(null);
const [sales, setSales] = useState([]);
const [showCheckoutModal, setShowCheckoutModal] = useState(false);
const [paymentMethod, setPaymentMethod] = useState('cash');
const [amountReceived, setAmountReceived] = useState('');
const [showReceiptModal, setShowReceiptModal] = useState(false);
const [currentReceipt, setCurrentReceipt] = useState(null);
const [categories, setCategories] = useState([]);
const [selectedCategory, setSelectedCategory] = useState('all');
const [showAddProductModal, setShowAddProductModal] = useState(false);
const [newProduct, setNewProduct] = useState({
name: '',
price: '',
category: '',
stock: '',
barcode: '',
description: ''
});
const [isDemo, setIsDemo] = useState(false);
const [registeredUsers, setRegisteredUsers] = useState([
{ username: 'admin', password: 'admin123', role: 'admin', email: 'admin@example.com' },
{ username: 'cashier', password: 'cashier123', role: 'cashier', email: 'cashier@example.com' },
{ username: 'manager', password: 'manager123', role: 'manager', email: 'manager@example.com' }
]);
const [showRegisterModal, setShowRegisterModal] = useState(false);
const [newUser, setNewUser] = useState({
username: '',
password: '',
confirmPassword: '',
email: '',
role: 'cashier'
});
const [customers, setCustomers] = useState([]);
const [selectedCustomer, setSelectedCustomer] = useState(null);
const [showAddCustomerModal, setShowAddCustomerModal] = useState(false);
const [newCustomer, setNewCustomer] = useState({
name: '',
phone: '',
email: '',
address: '',
balance: 0
});
const [showSettingsModal, setShowSettingsModal] = useState(false);
const [storeSettings, setStoreSettings] = useState({
name: 'Your Business Name',
address: '123 Main Street, City, State',
phone: '(123) 456-7890',
email: 'business@example.com',
taxRate: 7,
currency: 'USD',
receiptFooter: 'Thank you for your purchase!'
});
const [isSyncing, setIsSyncing] = useState(false);
const [syncStatus, setSyncStatus] = useState('');
const [loginEmail, setLoginEmail] = useState('');
const [loginPassword, setLoginPassword] = useState('');
const [loginError, setLoginError] = useState('');
const [showCustomerWalletModal, setShowCustomerWalletModal] = useState(false);
const [walletTransaction, setWalletTransaction] = useState({
amount: '',
type: 'deposit',
note: ''
});
// Load data on component mount
useEffect(() => {
// Check for existing session
const savedUser = localStorage.getItem('posUser');
const savedIsDemo = localStorage.getItem('posIsDemo');
if (savedUser) {
setUser(JSON.parse(savedUser));
setIsAuthenticated(true);
setIsDemo(savedIsDemo === 'true');
}
// Load registered users from localStorage if available
const savedUsers = localStorage.getItem('posRegisteredUsers');
if (savedUsers) {
setRegisteredUsers(JSON.parse(savedUsers));
} else {
// Save default users to localStorage
localStorage.setItem('posRegisteredUsers', JSON.stringify(registeredUsers));
}
// Load data based on authentication status
if (isAuthenticated) {
loadData();
} else {
setIsLoading(false);
}
}, [isAuthenticated]);
// Load data function
const loadData = async () => {
try {
setIsLoading(true);
if (isDemo) {
// Load demo data
loadDemoData();
setIsLoading(false);
} else {
// Load real data from Firebase
await fetchDataFromFirebase();
}
} catch (error) {
console.error('Error loading data:', error);
setIsLoading(false);
}
};
// Fetch data from Firebase
const fetchDataFromFirebase = async () => {
try {
// Set up listeners for real-time updates
const productsRef = ref(database, 'products');
const salesRef = ref(database, 'sales');
const categoriesRef = ref(database, 'categories');
const customersRef = ref(database, 'customers');
const settingsRef = ref(database, 'settings');
// Products listener
onValue(productsRef, (snapshot) => {
const data = snapshot.val();
if (data) {
const productsArray = Object.entries(data).map(([key, value]) => ({
_id: key,
...value
}));
setProducts(productsArray);
} else {
setProducts([]);
}
});
// Sales listener
onValue(salesRef, (snapshot) => {
const data = snapshot.val();
if (data) {
const salesArray = Object.entries(data).map(([key, value]) => ({
_id: key,
...value
}));
setSales(salesArray);
} else {
setSales([]);
}
});
// Categories listener
onValue(categoriesRef, (snapshot) => {
const data = snapshot.val();
if (data) {
setCategories(data);
} else {
// Initialize with default categories
const defaultCategories = ['Clothing', 'Footwear', 'Accessories', 'Electronics', 'Stationery'];
setCategories(defaultCategories);
// Save default categories to Firebase
set(categoriesRef, defaultCategories);
}
});
// Customers listener
onValue(customersRef, (snapshot) => {
const data = snapshot.val();
if (data) {
const customersArray = Object.entries(data).map(([key, value]) => ({
_id: key,
...value
}));
setCustomers(customersArray);
} else {
setCustomers([]);
}
});
// Settings listener
onValue(settingsRef, (snapshot) => {
const data = snapshot.val();
if (data) {
setStoreSettings(data);
} else {
// Save default settings to Firebase
set(settingsRef, storeSettings);
}
});
setIsLoading(false);
// Clean up listeners on unmount
return () => {
off(productsRef);
off(salesRef);
off(categoriesRef);
off(customersRef);
off(settingsRef);
};
} catch (error) {
console.error('Error fetching data from Firebase:', error);
setIsLoading(false);
}
};
// Load demo data
const loadDemoData = () => {
// Load demo products
const demoProducts = [
{ _id: '1', name: 'T-Shirt', price: 19.99, category: 'Clothing', stock: 45, barcode: '123456789', description: 'Cotton t-shirt' },
{ _id: '2', name: 'Jeans', price: 49.99, category: 'Clothing', stock: 30, barcode: '223456789', description: 'Blue denim jeans' },
{ _id: '3', name: 'Sneakers', price: 79.99, category: 'Footwear', stock: 25, barcode: '323456789', description: 'Running shoes' },
{ _id: '4', name: 'Coffee Mug', price: 12.99, category: 'Accessories', stock: 50, barcode: '423456789', description: 'Ceramic coffee mug' },
{ _id: '5', name: 'Notebook', price: 4.99, category: 'Stationery', stock: 100, barcode: '523456789', description: 'Lined notebook' },
{ _id: '6', name: 'Backpack', price: 39.99, category: 'Accessories', stock: 20, barcode: '623456789', description: 'School backpack' },
{ _id: '7', name: 'Water Bottle', price: 14.99, category: 'Accessories', stock: 40, barcode: '723456789', description: 'Stainless steel water bottle' },
{ _id: '8', name: 'Headphones', price: 89.99, category: 'Electronics', stock: 15, barcode: '823456789', description: 'Wireless headphones' },
];
setProducts(demoProducts);
// Load demo sales
const demoSales = [
{ _id: '1', date: '2023-06-01', total: 149.95, items: 3, paymentMethod: 'credit' },
{ _id: '2', date: '2023-06-02', total: 89.97, items: 2, paymentMethod: 'cash' },
{ _id: '3', date: '2023-06-03', total: 199.96, items: 4, paymentMethod: 'credit' },
{ _id: '4', date: '2023-06-04', total: 59.98, items: 2, paymentMethod: 'cash' },
{ _id: '5', date: '2023-06-05', total: 129.95, items: 3, paymentMethod: 'credit' },
];
setSales(demoSales);
// Load demo categories
const demoCategories = ['Clothing', 'Footwear', 'Accessories', 'Electronics', 'Stationery'];
setCategories(demoCategories);
// Load demo customers
const demoCustomers = [
{ _id: '1', name: 'John Doe', phone: '555-123-4567', email: 'john@example.com', address: '123 Main St', balance: 50.00 },
{ _id: '2', name: 'Jane Smith', phone: '555-987-6543', email: 'jane@example.com', address: '456 Oak Ave', balance: 25.75 },
{ _id: '3', name: 'Bob Johnson', phone: '555-555-5555', email: 'bob@example.com', address: '789 Pine Rd', balance: 0.00 },
];
setCustomers(demoCustomers);
};
// Handle Firebase authentication
const handleFirebaseLogin = async (email, password) => {
try {
setLoginError('');
const userCredential = await signInWithEmailAndPassword(auth, email, password);
const firebaseUser = userCredential.user;
// Get user role from database
const userRef = ref(database, `users/${firebaseUser.uid}`);
const snapshot = await get(userRef);
if (snapshot.exists()) {
const userData = snapshot.val();
return {
uid: firebaseUser.uid,
username: userData.username,
role: userData.role,
email: firebaseUser.email
};
} else {
// Create user data if it doesn't exist
const newUserData = {
username: email.split('@')[0],
role: 'cashier',
email: email
};
await set(userRef, newUserData);
return {
uid: firebaseUser.uid,
username: newUserData.username,
role: newUserData.role,
email: newUserData.email
};
}
} catch (error) {
console.error('Firebase login error:', error);
setLoginError(error.message);
return null;
}
};
// Register user in Firebase
const registerFirebaseUser = async (email, password, username, role) => {
try {
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const firebaseUser = userCredential.user;
// Save user data to database
const userRef = ref(database, `users/${firebaseUser.uid}`);
await set(userRef, {
username,
role,
email
});
return {
uid: firebaseUser.uid,
username,
role,
email
};
} catch (error) {
console.error('Firebase registration error:', error);
throw error;
}
};
// Handle login
const handleLogin = async (userData, demo = false) => {
setUser(userData);
setIsAuthenticated(true);
setIsDemo(demo);
// Save to localStorage
localStorage.setItem('posUser', JSON.stringify(userData));
localStorage.setItem('posIsDemo', demo.toString());
// Load data
await loadData();
};
// Handle logout
const handleLogout = async () => {
if (!isDemo) {
try {
await signOut(auth);
} catch (error) {
console.error('Firebase logout error:', error);
}
}
setUser(null);
setIsAuthenticated(false);
setCart([]);
// Clear from localStorage
localStorage.removeItem('posUser');
localStorage.removeItem('posIsDemo');
};
// Add product to cart
const addToCart = (product) => {
const existingItem = cart.find(item => item._id === product._id);
if (existingItem) {
setCart(cart.map(item =>
item._id === product._id
? { ...item, quantity: item.quantity + 1 }
: item
));
} else {
setCart([...cart, { ...product, quantity: 1 }]);
}
};
// Update cart item quantity
const updateCartItemQuantity = (productId, newQuantity) => {
if (newQuantity <= 0) {
removeFromCart(productId);
return;
}
setCart(cart.map(item =>
item._id === productId
? { ...item, quantity: newQuantity }
: item
));
};
// Remove item from cart
const removeFromCart = (productId) => {
setCart(cart.filter(item => item._id !== productId));
};
// Calculate cart total
const calculateTotal = () => {
return cart.reduce((total, item) => total + (item.price * item.quantity), 0);
};
// Process checkout
const processCheckout = async () => {
if (cart.length === 0) return;
try {
const total = calculateTotal();
const taxRate = storeSettings.taxRate / 100;
const taxAmount = total * taxRate;
const totalWithTax = total + taxAmount;
const change = paymentMethod === 'cash' ? parseFloat(amountReceived) - totalWithTax : 0;
// Create receipt
const receipt = {
date: new Date().toISOString(),
items: cart,
subtotal: total,
taxRate: storeSettings.taxRate,
taxAmount: taxAmount,
total: totalWithTax,
paymentMethod: paymentMethod,
amountReceived: paymentMethod === 'cash' ? parseFloat(amountReceived) : totalWithTax,
change: change,
customer: selectedCustomer ? {
_id: selectedCustomer._id,
name: selectedCustomer.name
} : null
};
// Update inventory and sales
if (isDemo) {
// Update demo data in memory only
updateDemoData(receipt);
} else {
// Update real data in Firebase
await updateFirebaseData(receipt);
}
// Show receipt
setCurrentReceipt(receipt);
setShowReceiptModal(true);
setShowCheckoutModal(false);
// Clear cart and selected customer
setCart([]);
setAmountReceived('');
setSelectedCustomer(null);
} catch (error) {
console.error('Error processing checkout:', error);
}
};
// Update demo data
const updateDemoData = (receipt) => {
// Update products stock
const updatedProducts = products.map(product => {
const cartItem = cart.find(item => item._id === product._id);
if (cartItem) {
return { ...product, stock: product.stock - cartItem.quantity };
}
return product;
});
setProducts(updatedProducts);
// Update sales
const newSale = {
_id: Date.now().toString(),
date: receipt.date,
total: receipt.total,
items: cart.reduce((sum, item) => sum + item.quantity, 0),
paymentMethod: receipt.paymentMethod,
customer: receipt.customer
};
setSales([...sales, newSale]);
// Update customer balance if using wallet
if (receipt.paymentMethod === 'wallet' && selectedCustomer) {
const updatedCustomers = customers.map(customer => {
if (customer._id === selectedCustomer._id) {
return { ...customer, balance: customer.balance - receipt.total };
}
return customer;
});
setCustomers(updatedCustomers);
}
};
// Update Firebase data
const updateFirebaseData = async (receipt) => {
try {
// Add sale to Firebase
const salesRef = ref(database, 'sales');
const newSaleRef = push(salesRef);
const saleId = newSaleRef.key;
const saleData = {
date: receipt.date,
subtotal: receipt.subtotal,
taxAmount: receipt.taxAmount,
total: receipt.total,
items: cart.reduce((sum, item) => sum + item.quantity, 0),
paymentMethod: receipt.paymentMethod,
customer: receipt.customer,
itemsDetail: cart.map(item => ({
productId: item._id,
name: item.name,
price: item.price,
quantity: item.quantity
}))
};
await set(newSaleRef, saleData);
// Update product stock
for (const item of cart) {
const productRef = ref(database, `products/${item._id}`);
const snapshot = await get(productRef);
if (snapshot.exists()) {
const product = snapshot.val();
const newStock = product.stock - item.quantity;
await update(productRef, { stock: newStock });
}
}
// Update customer balance if using wallet
if (receipt.paymentMethod === 'wallet' && selectedCustomer) {
const customerRef = ref(database, `customers/${selectedCustomer._id}`);
const snapshot = await get(customerRef);
if (snapshot.exists()) {
const customer = snapshot.val();
const newBalance = customer.balance - receipt.total;
await update(customerRef, { balance: newBalance });
// Add transaction to customer history
const transactionRef = ref(database, `customers/${selectedCustomer._id}/transactions`);
const newTransactionRef = push(transactionRef);
await set(newTransactionRef, {
date: receipt.date,
amount: -receipt.total,
type: 'purchase',
saleId: saleId,
balance: newBalance
});
}
}
// Set receipt ID
receipt._id = saleId;
} catch (error) {
console.error('Error updating Firebase data:', error);
throw error;
}
};
// Add new product
const handleAddProduct = async () => {
try {
const productToAdd = {
name: newProduct.name,
price: parseFloat(newProduct.price),
category: newProduct.category,
stock: parseInt(newProduct.stock),
barcode: newProduct.barcode,
description: newProduct.description
};
if (isDemo) {
// Add to demo products
const productWithId = {
...productToAdd,
_id: Date.now().toString()
};
setProducts([...products, productWithId]);
} else {
// Add to Firebase
const productsRef = ref(database, 'products');
const newProductRef = push(productsRef);
await set(newProductRef, productToAdd);
}
// Reset form
setNewProduct({
name: '',
price: '',
category: '',
stock: '',
barcode: '',
description: ''
});
setShowAddProductModal(false);
} catch (error) {
console.error('Error adding product:', error);
}
};
// Add new customer
const handleAddCustomer = async () => {
try {
const customerToAdd = {
name: newCustomer.name,
phone: newCustomer.phone,
email: newCustomer.email,
address: newCustomer.address,
balance: parseFloat(newCustomer.balance) || 0
};
if (isDemo) {
// Add to demo customers
const customerWithId = {
...customerToAdd,
_id: Date.now().toString()
};
setCustomers([...customers, customerWithId]);
} else {
// Add to Firebase
const customersRef = ref(database, 'customers');
const newCustomerRef = push(customersRef);
await set(newCustomerRef, customerToAdd);
}
// Reset form
setNewCustomer({
name: '',
phone: '',
email: '',
address: '',
balance: 0
});
setShowAddCustomerModal(false);
} catch (error) {
console.error('Error adding customer:', error);
}
};
// Register new user
const handleRegisterUser = async () => {
// Validate form
if (newUser.password !== newUser.confirmPassword) {
alert("Passwords don't match");
return;
}
if (registeredUsers.some(user => user.username === newUser.username)) {
alert("Username already exists");
return;
}
try {
if (isDemo) {
// Create new user object
const userToAdd = {
username: newUser.username,
password: newUser.password,
email: newUser.email,
role: newUser.role
};
// Add to registered users
const updatedUsers = [...registeredUsers, userToAdd];
setRegisteredUsers(updatedUsers);
// Save to localStorage
localStorage.setItem('posRegisteredUsers', JSON.stringify(updatedUsers));
} else {
// Register user in Firebase
await registerFirebaseUser(newUser.email, newUser.password, newUser.username, newUser.role);
}
// Reset form and close modal
setNewUser({
username: '',
password: '',
confirmPassword: '',
email: '',
role: 'cashier'
});
setShowRegisterModal(false);
} catch (error) {
console.error('Error registering user:', error);
alert(`Registration failed: ${error.message}`);
}
};
// Update store settings
const handleUpdateSettings = async () => {
try {
if (!isDemo) {
// Update settings in Firebase
const settingsRef = ref(database, 'settings');
await set(settingsRef, storeSettings);
}
setShowSettingsModal(false);
} catch (error) {
console.error('Error updating settings:', error);
}
};
// Process wallet transaction
const handleWalletTransaction = async () => {
if (!selectedCustomer || !walletTransaction.amount) return;
try {
const amount = parseFloat(walletTransaction.amount);
const transactionType = walletTransaction.type;
const newBalance = transactionType === 'deposit'
? selectedCustomer.balance + amount
: selectedCustomer.balance - amount;
if (transactionType === 'withdraw' && amount > selectedCustomer.balance) {
alert('Insufficient balance for withdrawal');
return;
}
if (isDemo) {
// Update customer in demo mode
const updatedCustomers = customers.map(customer => {
if (customer._id === selectedCustomer._id) {
return { ...customer, balance: newBalance };
}
return customer;
});
setCustomers(updatedCustomers);
setSelectedCustomer({ ...selectedCustomer, balance: newBalance });
} else {
// Update customer in Firebase
const customerRef = ref(database, `customers/${selectedCustomer._id}`);
await update(customerRef, { balance: newBalance });
// Add transaction to customer history
const transactionRef = ref(database, `customers/${selectedCustomer._id}/transactions`);
const newTransactionRef = push(transactionRef);
await set(newTransactionRef, {
date: new Date().toISOString(),
amount: transactionType === 'deposit' ? amount : -amount,
type: transactionType,
note: walletTransaction.note,
balance: newBalance
});
}
// Reset form
setWalletTransaction({
amount: '',
type: 'deposit',
note: ''
});
setShowCustomerWalletModal(false);
} catch (error) {
console.error('Error processing wallet transaction:', error);
}
};
// Sync data with Firebase
const syncWithFirebase = async () => {
if (isDemo) {
try {
setIsSyncing(true);
setSyncStatus('Syncing data with Firebase...');
// Sync products
setSyncStatus('Syncing products...');
const productsRef = ref(database, 'products');
await remove(productsRef);
for (const product of products) {
const newProductRef = push(productsRef);
const { _id, ...productData } = product;
await set(newProductRef, productData);
}
// Sync sales
setSyncStatus('Syncing sales...');
const salesRef = ref(database, 'sales');
await remove(salesRef);
for (const sale of sales) {
const newSaleRef = push(salesRef);
const { _id, ...saleData } = sale;
await set(newSaleRef, saleData);
}
// Sync categories
setSyncStatus('Syncing categories...');
const categoriesRef = ref(database, 'categories');
await set(categoriesRef, categories);
// Sync customers
setSyncStatus('Syncing customers...');
const customersRef = ref(database, 'customers');
await remove(customersRef);
for (const customer of customers) {
const newCustomerRef = push(customersRef);
const { _id, ...customerData } = customer;
await set(newCustomerRef, customerData);
}
// Sync settings
setSyncStatus('Syncing settings...');
const settingsRef = ref(database, 'settings');
await set(settingsRef, storeSettings);
setSyncStatus('Sync completed successfully!');
setTimeout(() => {
setIsSyncing(false);
setSyncStatus('');
}, 2000);
} catch (error) {
console.error('Error syncing with Firebase:', error);
setSyncStatus(`Sync failed: ${error.message}`);
setTimeout(() => {
setIsSyncing(false);
setSyncStatus('');
}, 3000);
}
}
};
// Filter products based on search and category
const filteredProducts = products.filter(product => {
const matchesSearch = product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
(product.barcode && product.barcode.includes(searchQuery));
const matchesCategory = selectedCategory === 'all' || product.category === selectedCategory;
return matchesSearch && matchesCategory;
});
// Calculate dashboard metrics
const calculateDailyTotal = () => {
const today = new Date().toISOString().split('T')[0];
return sales
.filter(sale => sale.date.startsWith(today))
.reduce((sum, sale) => sum + sale.total, 0);
};
const calculateTotalSales = () => {
return sales.reduce((sum, sale) => sum + sale.total, 0);
};
const calculateAverageOrderValue = () => {
if (sales.length === 0) return 0;
return calculateTotalSales() / sales.length;
};
const calculateLowStockItems = () => {
return products.filter(product => product.stock < 10).length;
};
// Check if user has admin privileges
const isAdmin = user && (user.role === 'admin' || user.role === 'manager');
if (isLoading) {
return (
);
}
if (!isAuthenticated) {
return ;
}
return (
{/* Header */}
POS System {isDemo && DEMO MODE}
{user.username} ({user.role})
{isAdmin && (
<>
>
)}
{isDemo && (
)}
{/* Navigation */}
{/* Sync Status */}
{syncStatus && (
{syncStatus}
)}
{/* Main Content */}
{activeTab === 'pos' && (
{/* Product Catalog */}
{filteredProducts.length === 0 ? (
No products found
{products.length === 0 && (
)}
) : (
{filteredProducts.map(product => (
{product.name}
${product.price.toFixed(2)}
{product.category}
{product.description}
10 ? 'text-green-600' : 'text-red-600'}`}>
Stock: {product.stock}
))}
)}
{/* Shopping Cart */}
Shopping Cart
{customers.length > 0 && (
{selectedCustomer && (
{selectedCustomer.name}
{selectedCustomer.phone}
Wallet Balance
0 ? 'text-green-600' : 'text-gray-600'}`}>
${selectedCustomer.balance.toFixed(2)}
)}
)}
{cart.length === 0 ? (
) : (
{cart.map(item => (
{item.name}
${item.price.toFixed(2)} each
{item.quantity}
))}
)}
Subtotal:
${calculateTotal().toFixed(2)}
Tax ({storeSettings.taxRate}%):
${(calculateTotal() * (storeSettings.taxRate / 100)).toFixed(2)}
Total:
${(calculateTotal() * (1 + storeSettings.taxRate / 100)).toFixed(2)}
)}
{activeTab === 'inventory' && (
Inventory Management
{products.length === 0 ? (
No products found
) : (
| Name |
Category |
Price |
Stock |
Barcode |
Actions |
{filteredProducts.map(product => (
|
{product.name}
{product.description}
|
{product.category} |
${product.price.toFixed(2)} |
10
? 'bg-green-100 text-green-800'
: product.stock > 0
? 'bg-yellow-100 text-yellow-800'
: 'bg-red-100 text-red-800'
}`}>
{product.stock}
|
{product.barcode} |
|
))}
)}
)}
{activeTab === 'customers' && (
Customer Management
{customers.length === 0 ? (
No customers found
) : (
| Name |
Contact |
Address |
Wallet Balance |
Actions |
{customers.map(customer => (
|
{customer.name}
|
{customer.phone}
{customer.email}
|
{customer.address} |
0
? 'bg-green-100 text-green-800'
: 'bg-gray-100 text-gray-800'
}`}>
${customer.balance.toFixed(2)}
|
|
))}
)}
)}
{activeTab === 'reports' && (
Reports & Analytics
{/* Dashboard Cards */}
Today's Sales
${calculateDailyTotal().toFixed(2)}
Total Sales
${calculateTotalSales().toFixed(2)}
Average Order Value
${calculateAverageOrderValue().toFixed(2)}
Low Stock Items
{calculateLowStockItems()}
{/* Sales History */}
Recent Sales
{sales.length === 0 ? (
No sales data available yet
) : (
| Date |
Transaction ID |
Items |
Customer |
Payment Method |
Total |
{sales.map(sale => (
|
{new Date(sale.date).toLocaleDateString()}
|
{sale._id} |
{sale.items} |
{sale.customer ? sale.customer.name : '-'}
|
{sale.paymentMethod === 'cash'
? 'Cash'
: sale.paymentMethod === 'credit'
? 'Credit Card'
: 'Wallet'}
|
${sale.total.toFixed(2)}
|
))}
)}
{/* Low Stock Items */}
Low Stock Items
{products.filter(product => product.stock < 10).length === 0 ? (
) : (
| Name |
Category |
Current Stock |
Status |
{products.filter(product => product.stock < 10).map(product => (
|
{product.name}
|
{product.category} |
{product.stock} |
5
? 'bg-yellow-100 text-yellow-800'
: 'bg-red-100 text-red-800'
}`}>
{product.stock > 5 ? 'Low Stock' : 'Critical'}
|
))}
)}
)}
{/* Checkout Modal */}
{showCheckoutModal && (
Checkout
Order Summary
{cart.map(item => (
{item.name} x {item.quantity}
${(item.price * item.quantity).toFixed(2)}
))}
Subtotal
${calculateTotal().toFixed(2)}
Tax ({storeSettings.taxRate}%)
${(calculateTotal() * (storeSettings.taxRate / 100)).toFixed(2)}
Total
${(calculateTotal() * (1 + storeSettings.taxRate / 100)).toFixed(2)}
Payment Method
{selectedCustomer && selectedCustomer.balance >= calculateTotal() * (1 + storeSettings.taxRate / 100) && (
)}
{selectedCustomer && selectedCustomer.balance > 0 && selectedCustomer.balance < calculateTotal() * (1 + storeSettings.taxRate / 100) && (
Customer wallet balance (${selectedCustomer.balance.toFixed(2)}) is insufficient for the total amount.
)}
{paymentMethod === 'cash' && (
{parseFloat(amountReceived) > 0 && (
Change: ${Math.max(0, parseFloat(amountReceived) - (calculateTotal() * (1 + storeSettings.taxRate / 100))).toFixed(2)}
)}
)}
)}
{/* Receipt Modal */}
{showReceiptModal && currentReceipt && (
Receipt
{storeSettings.name}
{storeSettings.address}
Tel: {storeSettings.phone}
Receipt #:
{currentReceipt._id}
Date:
{new Date(currentReceipt.date).toLocaleString()}
{currentReceipt.customer && (
Customer:
{currentReceipt.customer.name}
)}
{currentReceipt.items.map(item => (
{item.name}
{item.quantity}
${item.price.toFixed(2)}
${(item.price * item.quantity).toFixed(2)}
))}
Subtotal
${currentReceipt.subtotal.toFixed(2)}
Tax ({currentReceipt.taxRate}%)
${currentReceipt.taxAmount.toFixed(2)}
Total
${currentReceipt.total.toFixed(2)}
{currentReceipt.paymentMethod === 'cash' && (
<>
Amount Received
${parseFloat(currentReceipt.amountReceived).toFixed(2)}
Change
${currentReceipt.change.toFixed(2)}
>
)}
Payment Method
{currentReceipt.paymentMethod === 'cash'
? 'Cash'
: currentReceipt.paymentMethod === 'credit'
? 'Credit Card'
: 'Customer Wallet'}
{storeSettings.receiptFooter}
)}
{/* Add Product Modal */}
{showAddProductModal && (
Add New Product
)}
{/* Add Customer Modal */}
{showAddCustomerModal && (
Add New Customer
)}
{/* Register User Modal */}
{showRegisterModal && (
Register New User
)}
{/* Settings Modal */}
{showSettingsModal && (
Store Settings
)}
{/* Customer Wallet Modal */}
{showCustomerWalletModal && selectedCustomer && (
Customer Wallet
{selectedCustomer.name}
{selectedCustomer.phone}
Current Balance
${selectedCustomer.balance.toFixed(2)}
)}
);
}
// Login Screen Component
function LoginScreen({ onLogin, registeredUsers, handleFirebaseLogin, loginEmail, setLoginEmail, loginPassword, setLoginPassword, loginError }) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [isFirebaseLogin, setIsFirebaseLogin] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (isFirebaseLogin) {
// Firebase login
const user = await handleFirebaseLogin(loginEmail, loginPassword);
if (user) {
onLogin(user, false);
}
} else {
// Simple validation for local login
if (!username || !password) {
setError('Please enter both username and password');
return;
}
// Check if user exists
const user = registeredUsers.find(u => u.username === username && u.password === password);
if (user) {
// Real login
onLogin({ username: user.username, role: user.role }, false);
} else {
setError('Invalid username or password');
}
}
};
const handleDemoLogin = () => {
// Demo login
onLogin({ username: 'demo', role: 'admin' }, true);
};
return (
POS System Login
Enter your credentials to access the system
);
}