Files
MyPOS/server/controller/inventoryController.js
T
2025-11-13 19:09:00 +08:00

69 lines
2.2 KiB
JavaScript

import supabase from "../config/supabaseClient.js";
// Get all inventory logs
export const getInventoryLogs = async (req, res) => {
try {
const { product_id } = req.query;
let query = supabase
.from('inventory_logs')
.select(`*, products(name), users(full_name)`)
.order('log_date', { ascending: false });
if (product_id) query = query.eq('product_id', product_id);
const { data, error } = await query;
if (error) throw error;
res.json(data);
} catch (error) {
console.error("Error fetching inventory logs:", error);
res.status(500).json({ error: "Failed to fetch inventory logs" });
}
};
// Add a log (add, remove, adjust, sale)
export const createInventoryLog = async (req, res) => {
const { product_id, user_id, action, quantity, remarks } = req.body;
if (!product_id || !user_id || !action || !quantity) {
return res.status(400).json({ error: "Missing required fields" });
}
try {
// Insert log
const { data: log, error } = await supabase
.from('inventory_logs')
.insert([{ product_id, user_id, action, quantity, remarks }])
.select()
.single();
if (error) throw error;
// Update product stock
// Add/subtract quantity depending on action
const { data: product, error: fetchError } = await supabase
.from('products')
.select('stock')
.eq('product_id', product_id)
.single();
if (fetchError) throw fetchError;
let newStock = product.stock;
if (action === "add" || action === "adjust") newStock += quantity;
else if (action === "remove" || action === "sale") newStock -= quantity;
const { error: updateError } = await supabase
.from('products')
.update({ stock: newStock })
.eq('product_id', product_id);
if (updateError) throw updateError;
res.status(201).json(log);
} catch (error) {
console.error("Error creating inventory log:", error);
res.status(500).json({ error: "Failed to create inventory log" });
}
};