38438-vm/api/export_expenses.php
2026-02-15 15:54:39 +00:00

58 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
require_once __DIR__ . '/../db/config.php';
$tenant_id = 1;
$filter_project = (int)($_GET['project_id'] ?? 0);
$filter_supplier = (int)($_GET['supplier_id'] ?? 0);
$filter_start = $_GET['start_date'] ?? '';
$filter_end = $_GET['end_date'] ?? '';
$where = ["e.tenant_id = ?"];
$params = [$tenant_id];
if ($filter_project) {
$where[] = "e.project_id = ?";
$params[] = $filter_project;
}
if ($filter_supplier) {
$where[] = "e.supplier_id = ?";
$params[] = $filter_supplier;
}
if ($filter_start) {
$where[] = "e.entry_date >= ?";
$params[] = $filter_start;
}
if ($filter_end) {
$where[] = "e.entry_date <= ?";
$params[] = $filter_end;
}
$where_clause = implode(" AND ", $where);
$stmt = db()->prepare("
SELECT e.entry_date, s.name as supplier_name, p.name as project_name, e.amount, e.allocation_percent, et.name as expense_type, e.notes
FROM expenses e
JOIN projects p ON e.project_id = p.id
JOIN suppliers s ON e.supplier_id = s.id
LEFT JOIN expense_types et ON e.expense_type_id = et.id
WHERE $where_clause
ORDER BY e.entry_date DESC
");
$stmt->execute($params);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$filename_suffix = date('Y-m-d_H-i-s');
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=expenses_export_' . $filename_suffix . '.csv');
$output = fopen('php://output', 'w');
fputcsv($output, ['Date', 'Supplier', 'Project', 'Amount', 'Allocation %', 'Expense Type', 'Notes']);
foreach ($data as $row) {
fputcsv($output, $row);
}
fclose($output);
exit;