adding stock management

This commit is contained in:
Flatlogic Bot 2026-03-21 18:03:25 +00:00
parent 1cb1f89067
commit 66038df9e4
12 changed files with 201 additions and 25 deletions

View File

@ -5,12 +5,20 @@ require_once __DIR__ . '/../includes/auth.php';
header('Content-Type: application/json');
if (!is_logged_in()) {
http_response_code(403);
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit;
}
// Check permission
if (!has_permission('inventory')) {
http_response_code(403);
echo json_encode(['error' => 'Forbidden: Stock Management permission required']);
exit;
}
$action = $_GET['action'] ?? '';
$db = db();

View File

@ -0,0 +1,2 @@
ALTER TABLE inventory_transactions ADD COLUMN IF NOT EXISTS department_id INT NULL;
ALTER TABLE inventory_transactions ADD CONSTRAINT fk_inventory_dept FOREIGN KEY (department_id) REFERENCES departments(id) ON DELETE SET NULL;

View File

@ -77,3 +77,10 @@ function require_role($role_slug) {
die("Access Denied: You do not have the required role.");
}
}
function require_permission($permission) {
if (!has_permission($permission)) {
http_response_code(403);
die("Access Denied: You do not have the required permission: " . htmlspecialchars($permission));
}
}

View File

@ -4,6 +4,7 @@ $report_type = $_GET['report'] ?? 'low_stock';
// Data Fetching based on report type
$data = [];
$columns = [];
$departments = $db->query("SELECT id, name_en FROM departments ORDER BY name_en ASC")->fetchAll(PDO::FETCH_ASSOC);
if ($report_type === 'low_stock') {
$title = __('low_stock_report');
@ -41,6 +42,56 @@ if ($report_type === 'low_stock') {
GROUP BY i.id
ORDER BY total_value DESC
")->fetchAll(PDO::FETCH_ASSOC);
} elseif ($report_type === 'consumption') {
$title = __('consumption_report');
$columns = ['department', 'item_name', 'total_quantity', 'total_cost'];
// Filters
$filter_department = $_GET['department_id'] ?? '';
$filter_start = $_GET['start_date'] ?? '';
$filter_end = $_GET['end_date'] ?? '';
$where = "WHERE t.transaction_type = 'out'";
$params = [];
if ($filter_department) {
$where .= " AND t.department_id = ?";
$params[] = $filter_department;
}
if ($filter_start) {
$where .= " AND DATE(t.transaction_date) >= ?";
$params[] = $filter_start;
}
if ($filter_end) {
$where .= " AND DATE(t.transaction_date) <= ?";
$params[] = $filter_end;
}
$sql = "
SELECT d.name_en as department,
i.name_en as item_name,
SUM(t.quantity) as total_quantity,
SUM(t.quantity * COALESCE(b.cost_price, 0)) as total_cost
FROM inventory_transactions t
JOIN departments d ON t.department_id = d.id
JOIN inventory_items i ON t.item_id = i.id
LEFT JOIN inventory_batches b ON t.batch_id = b.id
$where
GROUP BY d.id, i.id
ORDER BY d.name_en ASC, total_cost DESC
";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Calculate totals
$grand_total_qty = 0;
$grand_total_cost = 0;
foreach ($data as $row) {
$grand_total_qty += $row['total_quantity'];
$grand_total_cost += $row['total_cost'];
}
}
?>
@ -51,6 +102,7 @@ if ($report_type === 'low_stock') {
<a href="?report=low_stock" class="btn btn-outline-primary <?php echo $report_type === 'low_stock' ? 'active' : ''; ?>"><?php echo __('low_stock'); ?></a>
<a href="?report=expiry" class="btn btn-outline-primary <?php echo $report_type === 'expiry' ? 'active' : ''; ?>"><?php echo __('expiry_dates'); ?></a>
<a href="?report=valuation" class="btn btn-outline-primary <?php echo $report_type === 'valuation' ? 'active' : ''; ?>"><?php echo __('valuation'); ?></a>
<a href="?report=consumption" class="btn btn-outline-primary <?php echo $report_type === 'consumption' ? 'active' : ''; ?>"><?php echo __('department_consumption'); ?></a>
</div>
</div>
@ -59,12 +111,47 @@ if ($report_type === 'low_stock') {
<h5 class="mb-0 fw-bold"><?php echo htmlspecialchars($title); ?></h5>
</div>
<div class="card-body">
<?php if ($report_type === 'consumption'): ?>
<form method="GET" class="row g-3 mb-4 border-bottom pb-4">
<input type="hidden" name="report" value="consumption">
<div class="col-md-3">
<label class="form-label"><?php echo __('department'); ?></label>
<select name="department_id" class="form-select">
<option value=""><?php echo __('all_departments'); ?></option>
<?php foreach ($departments as $dept): ?>
<option value="<?php echo $dept['id']; ?>" <?php echo (isset($filter_department) && $filter_department == $dept['id']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($dept['name_en']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-3">
<label class="form-label"><?php echo __('start_date'); ?></label>
<input type="date" name="start_date" class="form-control" value="<?php echo htmlspecialchars($filter_start ?? ''); ?>">
</div>
<div class="col-md-3">
<label class="form-label"><?php echo __('end_date'); ?></label>
<input type="date" name="end_date" class="form-control" value="<?php echo htmlspecialchars($filter_end ?? ''); ?>">
</div>
<div class="col-md-3 d-flex align-items-end">
<button type="submit" class="btn btn-primary w-100">
<i class="bi bi-filter"></i> <?php echo __('filter'); ?>
</button>
</div>
</form>
<?php endif; ?>
<div class="table-responsive">
<table class="table table-hover align-middle">
<thead class="table-light">
<tr>
<?php foreach ($columns as $col): ?>
<th><?php echo __(str_replace('_', ' ', $col)); ?></th>
<th><?php echo __($col); ?></th>
<?php endforeach; ?>
</tr>
</thead>
@ -81,7 +168,7 @@ if ($report_type === 'low_stock') {
<?php
if ($col === 'current_stock' || $col === 'total_quantity') {
echo number_format($row[$col]);
} elseif ($col === 'total_value' || $col === 'avg_cost') {
} elseif ($col === 'total_value' || $col === 'avg_cost' || $col === 'total_cost') {
echo formatCurrency($row[$col]);
} elseif ($col === 'status') {
if ($row['current_stock'] == 0) echo '<span class="badge bg-danger">Out of Stock</span>';
@ -101,6 +188,15 @@ if ($report_type === 'low_stock') {
<?php endforeach; ?>
<?php endif; ?>
</tbody>
<?php if ($report_type === 'consumption' && !empty($data)): ?>
<tfoot class="table-light fw-bold">
<tr>
<td colspan="2" class="text-end"><?php echo __('total'); ?>:</td>
<td><?php echo number_format($grand_total_qty); ?></td>
<td><?php echo formatCurrency($grand_total_cost); ?></td>
</tr>
</tfoot>
<?php endif; ?>
</table>
</div>

View File

@ -8,6 +8,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$notes = $_POST['notes'] ?? '';
$reference_type = $_POST['reference_type'] ?? 'manual_adjustment';
$reference_id = 0; // Or pass from somewhere
$department_id = !empty($_POST['department_id']) ? $_POST['department_id'] : null;
if (!$item_id || $quantity <= 0) {
$_SESSION['flash_message'] = '<div class="alert alert-danger">' . __('fill_all_required_fields') . '</div>';
@ -27,8 +28,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$batch_id = $db->lastInsertId();
// Create Transaction Record
$stmt = $db->prepare("INSERT INTO inventory_transactions (item_id, batch_id, transaction_type, quantity, reference_type, reference_id, user_id, notes) VALUES (?, ?, 'in', ?, ?, ?, ?, ?)");
$stmt->execute([$item_id, $batch_id, $quantity, $reference_type, $reference_id, $_SESSION['user_id'], $notes]);
$stmt = $db->prepare("INSERT INTO inventory_transactions (item_id, batch_id, transaction_type, quantity, reference_type, reference_id, user_id, notes, department_id) VALUES (?, ?, 'in', ?, ?, ?, ?, ?, ?)");
$stmt->execute([$item_id, $batch_id, $quantity, $reference_type, $reference_id, $_SESSION['user_id'], $notes, $department_id]);
} elseif ($type === 'out') {
// Deduct from Batch
@ -48,8 +49,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$stmt->execute([$quantity, $batch_id]);
// Create Transaction Record
$stmt = $db->prepare("INSERT INTO inventory_transactions (item_id, batch_id, transaction_type, quantity, reference_type, reference_id, user_id, notes) VALUES (?, ?, 'out', ?, ?, ?, ?, ?)");
$stmt->execute([$item_id, $batch_id, $quantity, $reference_type, $reference_id, $_SESSION['user_id'], $notes]);
$stmt = $db->prepare("INSERT INTO inventory_transactions (item_id, batch_id, transaction_type, quantity, reference_type, reference_id, user_id, notes, department_id) VALUES (?, ?, 'out', ?, ?, ?, ?, ?, ?)");
$stmt->execute([$item_id, $batch_id, $quantity, $reference_type, $reference_id, $_SESSION['user_id'], $notes, $department_id]);
}
$db->commit();
@ -74,11 +75,12 @@ $total_records = $stmt->fetchColumn();
$total_pages = ceil($total_records / $per_page);
$transactions = $db->query("
SELECT t.*, i.name_en as item_name, i.sku, b.batch_number, u.name as user_name
SELECT t.*, i.name_en as item_name, i.sku, b.batch_number, u.name as user_name, d.name_en as department_name
FROM inventory_transactions t
JOIN inventory_items i ON t.item_id = i.id
LEFT JOIN inventory_batches b ON t.batch_id = b.id
LEFT JOIN users u ON t.user_id = u.id
LEFT JOIN departments d ON t.department_id = d.id
ORDER BY t.transaction_date DESC
LIMIT $per_page OFFSET $offset
")->fetchAll(PDO::FETCH_ASSOC);
@ -88,6 +90,9 @@ $items = $db->query("SELECT id, name_en, sku FROM inventory_items WHERE is_activ
// Fetch Suppliers
$suppliers = $db->query("SELECT id, name_en FROM suppliers ORDER BY name_en ASC")->fetchAll(PDO::FETCH_ASSOC);
// Fetch Departments
$departments = $db->query("SELECT id, name_en FROM departments ORDER BY name_en ASC")->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="d-flex justify-content-between align-items-center mb-4">
@ -108,6 +113,7 @@ $suppliers = $db->query("SELECT id, name_en FROM suppliers ORDER BY name_en ASC"
<th><?php echo __('item'); ?></th>
<th><?php echo __('batch'); ?></th>
<th><?php echo __('quantity'); ?></th>
<th><?php echo __('department'); ?></th>
<th><?php echo __('user'); ?></th>
<th><?php echo __('notes'); ?></th>
</tr>
@ -115,7 +121,7 @@ $suppliers = $db->query("SELECT id, name_en FROM suppliers ORDER BY name_en ASC"
<tbody>
<?php if (empty($transactions)): ?>
<tr>
<td colspan="7" class="text-center py-4 text-muted"><?php echo __('no_transactions_found'); ?></td>
<td colspan="8" class="text-center py-4 text-muted"><?php echo __('no_transactions_found'); ?></td>
</tr>
<?php else: ?>
<?php foreach ($transactions as $t): ?>
@ -136,6 +142,7 @@ $suppliers = $db->query("SELECT id, name_en FROM suppliers ORDER BY name_en ASC"
</td>
<td><?php echo htmlspecialchars($t['batch_number'] ?? '-'); ?></td>
<td class="fw-bold"><?php echo $t['quantity']; ?></td>
<td><?php echo htmlspecialchars($t['department_name'] ?? '-'); ?></td>
<td><?php echo htmlspecialchars($t['user_name'] ?? 'System'); ?></td>
<td><?php echo htmlspecialchars($t['notes'] ?? ''); ?></td>
</tr>
@ -222,12 +229,23 @@ $suppliers = $db->query("SELECT id, name_en FROM suppliers ORDER BY name_en ASC"
<!-- Fields for OUT -->
<div id="out_fields" style="display: none;">
<div class="mb-3">
<label class="form-label"><?php echo __('select_batch_to_deduct_from'); ?> <span class="text-danger">*</span></label>
<select name="batch_id" id="batch_select" class="form-select">
<option value=""><?php echo __('select_item_first'); ?></option>
</select>
<div class="form-text text-muted" id="batch_info"></div>
<div class="row g-3 mb-3">
<div class="col-md-6">
<label class="form-label"><?php echo __('select_batch_to_deduct_from'); ?> <span class="text-danger">*</span></label>
<select name="batch_id" id="batch_select" class="form-select">
<option value=""><?php echo __('select_item_first'); ?></option>
</select>
<div class="form-text text-muted" id="batch_info"></div>
</div>
<div class="col-md-6">
<label class="form-label"><?php echo __('department'); ?> <span class="text-danger">*</span></label>
<select name="department_id" id="department_select" class="form-select">
<option value=""><?php echo __('select_department'); ?></option>
<?php foreach ($departments as $dept): ?>
<option value="<?php echo $dept['id']; ?>"><?php echo htmlspecialchars($dept['name_en']); ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
@ -261,8 +279,9 @@ function toggleType() {
document.getElementById('in_fields').style.display = isOut ? 'none' : 'block';
document.getElementById('out_fields').style.display = isOut ? 'block' : 'none';
// Toggle required attribute for batch_select
// Toggle required attribute for batch_select and department_select
document.getElementById('batch_select').required = isOut;
document.getElementById('department_select').required = isOut;
// Clear batch selection if switching
if (isOut) {

View File

@ -69,6 +69,7 @@ $available_permissions = [
'laboratory',
'xray',
'pharmacy',
'inventory',
'billing',
'insurance',
'doctors',

View File

@ -5,6 +5,7 @@ require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/includes/auth.php';
check_auth();
require_permission('inventory');
$db = db();
$lang = $_SESSION['lang'];

View File

@ -5,6 +5,7 @@ require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/includes/auth.php';
check_auth();
require_permission('inventory');
$db = db();
$lang = $_SESSION['lang'];

View File

@ -5,6 +5,7 @@ require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/includes/auth.php';
check_auth();
require_permission('inventory');
$db = db();
$lang = $_SESSION['lang'];

View File

@ -5,6 +5,7 @@ require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/includes/auth.php';
check_auth();
require_permission('inventory');
$db = db();
$lang = $_SESSION['lang'];

View File

@ -5,6 +5,7 @@ require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/includes/auth.php';
check_auth();
require_permission('inventory');
$db = db();
$lang = $_SESSION['lang'];

View File

@ -174,6 +174,25 @@ $translations = [
'print_report' => 'Print Report',
'days_remaining' => 'Days Remaining',
'permission_inventory' => 'Stock Management',
'name_en' => 'Name (English)',
'name_ar' => 'Name (Arabic)',
'no_recent_transactions' => 'No recent transactions',
'no_items_found' => 'No items found',
'item' => 'Item',
'qty' => 'Qty',
'low_stock' => 'Low Stock',
'total_quantity' => 'Total Quantity',
'avg_cost' => 'Average Cost',
'department' => 'Department',
'select_department' => 'Select Department',
'department_consumption' => 'Department Consumption',
'consumption_report' => 'Consumption Report',
'total_cost' => 'Total Cost',
'start_date' => 'Start Date',
'end_date' => 'End Date',
'filter' => 'Filter',
'all_departments' => 'All Departments',
'total' => 'Total',
],
'ar' => [
'dashboard' => 'لوحة التحكم',
@ -349,5 +368,24 @@ $translations = [
'print_report' => 'طباعة التقرير',
'days_remaining' => 'الأيام المتبقية',
'permission_inventory' => 'إدارة المخزون',
'name_en' => 'الاسم (إنجليزي)',
'name_ar' => 'الاسم (عربي)',
'no_recent_transactions' => 'لا توجد معاملات حديثة',
'no_items_found' => 'لم يتم العثور على أصناف',
'item' => 'الصنف',
'qty' => 'الكمية',
'low_stock' => 'مخزون منخفض',
'total_quantity' => 'الكمية الإجمالية',
'avg_cost' => 'متوسط التكلفة',
'department' => 'القسم',
'select_department' => 'اختر القسم',
'department_consumption' => 'استهلاك الأقسام',
'consumption_report' => 'تقرير الاستهلاك',
'total_cost' => 'التكلفة الإجمالية',
'start_date' => 'تاريخ البدء',
'end_date' => 'تاريخ الانتهاء',
'filter' => 'تصفية',
'all_departments' => 'كل الأقسام',
'total' => 'الإجمالي',
]
];