38438-vm/import_expenses.php
2026-02-15 16:55:38 +00:00

190 lines
7.7 KiB
PHP

<?php
require_once 'db/config.php';
$pageTitle = 'Import Expenses';
$message = '';
$error = '';
$results = [];
// Helper to get maps for lookups
function getLookupMaps() {
$db = db();
$maps = [
'projects' => [],
'suppliers' => [],
'types' => []
];
$s = $db->query("SELECT id, project_code FROM projects");
while($r = $s->fetch(PDO::FETCH_ASSOC)) $maps['projects'][strtolower($r['project_code'])] = $r['id'];
$s = $db->query("SELECT id, name FROM suppliers");
while($r = $s->fetch(PDO::FETCH_ASSOC)) $maps['suppliers'][strtolower($r['name'])] = $r['id'];
$s = $db->query("SELECT id, name FROM expense_types");
while($r = $s->fetch(PDO::FETCH_ASSOC)) $maps['types'][strtolower($r['name'])] = $r['id'];
return $maps;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
$file = $_FILES['csv_file'];
if ($file['error'] !== UPLOAD_ERR_OK) {
$error = 'File upload failed.';
} else {
$handle = fopen($file['tmp_name'], 'r');
$header = fgetcsv($handle);
$expected = ['project_code', 'supplier_name', 'expense_type', 'amount', 'date', 'notes'];
if (!$header || count(array_intersect($expected, $header)) < 3) {
$error = 'Invalid CSV format. Please ensure project_code, supplier_name, and expense_type are present.';
} else {
$columnMap = array_flip($header);
$maps = getLookupMaps();
$rowCount = 0;
$importCount = 0;
$skippedCount = 0;
db()->beginTransaction();
try {
$stmt = db()->prepare("INSERT INTO expenses (tenant_id, project_id, supplier_id, expense_type_id, amount, allocation_percent, entry_date, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
while (($row = fgetcsv($handle)) !== false) {
$rowCount++;
$data = [];
foreach ($expected as $col) {
$data[$col] = isset($columnMap[$col]) && isset($row[$columnMap[$col]]) ? trim($row[$columnMap[$col]]) : '';
}
$projId = $maps['projects'][strtolower($data['project_code'])] ?? null;
$suppId = $maps['suppliers'][strtolower($data['supplier_name'])] ?? null;
$typeId = $maps['types'][strtolower($data['expense_type'])] ?? null;
if (!$projId) {
$results[] = "Row $rowCount: Skipped (Unknown Project Code: " . htmlspecialchars($data['project_code']) . ")";
$skippedCount++;
continue;
}
if (!$suppId) {
$results[] = "Row $rowCount: Skipped (Unknown Supplier: " . htmlspecialchars($data['supplier_name']) . ")";
$skippedCount++;
continue;
}
if (!$typeId) {
$results[] = "Row $rowCount: Skipped (Unknown Expense Type: " . htmlspecialchars($data['expense_type']) . ")";
$skippedCount++;
continue;
}
$amount = floatval($data['amount']);
$date = empty($data['date']) ? date('Y-m-d') : $data['date'];
$stmt->execute([
1, // tenant_id
$projId,
$suppId,
$typeId,
$amount,
100.00, // Default allocation_percent
$date,
$data['notes']
]);
$importCount++;
}
db()->commit();
$message = "Import completed. $importCount expenses imported, $skippedCount skipped.";
} catch (Exception $e) {
db()->rollBack();
$error = 'Database error: ' . $e->getMessage();
}
}
fclose($handle);
}
}
include 'includes/header.php';
?>
<div class="container mt-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<h2><i class="bi bi-receipt me-2"></i>Import Expenses</h2>
<a href="samples/expenses_template.csv" class="btn btn-outline-primary btn-sm">
<i class="bi bi-download me-1"></i>Download Template
</a>
</div>
<?php if ($message): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?= $message ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= $error ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<div class="row">
<div class="col-md-6">
<div class="card shadow-sm border-0">
<div class="card-body p-4">
<form action="import_expenses.php" method="POST" enctype="multipart/form-data">
<div class="mb-4">
<label for="csv_file" class="form-label fw-bold">Select CSV File</label>
<input type="file" class="form-control" id="csv_file" name="csv_file" accept=".csv" required>
<div class="form-text mt-2">
Max file size: 2MB. Only .csv files are allowed.
</div>
</div>
<button type="submit" class="btn btn-primary w-100 py-2">
<i class="bi bi-upload me-2"></i>Upload and Import
</button>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card shadow-sm border-0 h-100">
<div class="card-header bg-white py-3">
<h5 class="mb-0">Import Instructions</h5>
</div>
<div class="card-body">
<ol class="small text-muted">
<li>Download the CSV template.</li>
<li>Ensure <strong>project_code</strong>, <strong>supplier_name</strong>, and <strong>expense_type</strong> match existing records in the system.</li>
<li><strong>amount</strong> should be a numeric value.</li>
<li><strong>date</strong> should be in YYYY-MM-DD format (defaults to today if empty).</li>
</ol>
<div class="alert alert-warning py-2 small mb-0">
<i class="bi bi-exclamation-triangle me-1"></i> Rows with unknown projects, suppliers, or types will be skipped.
</div>
</div>
</div>
</div>
</div>
<?php if (!empty($results)): ?>
<div class="card shadow-sm border-0 mt-4">
<div class="card-header bg-white py-3">
<h5 class="mb-0">Import Logs</h5>
</div>
<div class="card-body">
<div class="list-group list-group-flush small">
<?php foreach ($results as $res): ?>
<div class="list-group-item px-0 border-0 py-1">
<i class="bi bi-dot me-1"></i><?= $res ?>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<?php endif; ?>
</div>
<?php include 'includes/footer.php'; ?>