36293-vm/export_project_finance.php
Flatlogic Bot 8be23f0e45 Final2
2025-11-26 10:17:48 +00:00

145 lines
5.3 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
// --- DATA FETCHING & CALCULATION ---
$project = null;
$project_id = $_GET['project_id'] ?? null;
$financial_data = [];
$months = [];
$metrics = ["Opening Balance", "Billings", "WIP", "Expenses", "Cost", "NSR", "Margin"];
if (!$project_id) {
header("HTTP/1.0 400 Bad Request");
echo "Project ID is required.";
exit;
}
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = :id");
$stmt->execute([':id' => $project_id]);
$project = $stmt->fetch(PDO::FETCH_ASSOC);
if ($project) {
function get_month_range($start_date_str, $end_date_str) {
$months = [];
if (empty($start_date_str) || empty($end_date_str)) return $months;
$start = new DateTime($start_date_str);
$end = new DateTime($end_date_str);
$current = clone $start;
$current->modify('first day of this month');
while ($current <= $end) {
$months[] = $current->format('Y-m-01');
$current->modify('+1 month');
}
return $months;
}
$months = get_month_range($project['startDate'], $project['endDate']);
// --- Financial Calculations ---
// 1. Fetch base monthly data
$monthly_costs = [];
$monthly_wip = [];
$forecast_stmt = $pdo->prepare("SELECT id FROM forecasting WHERE projectId = :pid ORDER BY versionNumber DESC LIMIT 1");
$forecast_stmt->execute([':pid' => $project_id]);
$latest_forecast = $forecast_stmt->fetch(PDO::FETCH_ASSOC);
if ($latest_forecast) {
$fid = $latest_forecast['id'];
// Base Monthly Cost
$cost_sql = "SELECT fa.month, SUM(fa.allocatedDays * (r.totalMonthlyCost / 20)) FROM forecastAllocation fa JOIN roster r ON fa.rosterId = r.id WHERE fa.forecastingId = :fid GROUP BY fa.month";
$cost_stmt = $pdo->prepare($cost_sql);
$cost_stmt->execute([':fid' => $fid]);
$monthly_costs = $cost_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
// Base Monthly WIP
$wip_sql = "SELECT fa.month, SUM(fa.allocatedDays * r.discountedRevenue) FROM forecastAllocation fa JOIN roster r ON fa.rosterId = r.id WHERE fa.forecastingId = :fid GROUP BY fa.month";
$wip_stmt = $pdo->prepare($wip_sql);
$wip_stmt->execute([':fid' => $fid]);
$monthly_wip = $wip_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
}
// Base Monthly Billings
$billing_stmt = $pdo->prepare("SELECT month, amount FROM billingMonthly WHERE projectId = :pid");
$billing_stmt->execute([':pid' => $project_id]);
$monthly_billing = $billing_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
// 2. Calculate cumulative values month by month
$cumulative_billing = 0;
$cumulative_cost = 0;
$previous_month_wip = 0;
foreach ($months as $month) {
// Normalize month keys from fetched data
$cost = $monthly_costs[$month] ?? 0;
$base_monthly_wip = $monthly_wip[$month] ?? 0;
$billing = $monthly_billing[$month] ?? 0;
$expenses = 0; // Placeholder for expenses
// Cumulative calculations
$cumulative_billing += $billing;
$cumulative_cost += $cost;
// WIP Calculation (new formula)
// current month WIP = previous month WIP + Month Expenses + base_monthly_wip - month Billing
$current_wip = $previous_month_wip + $expenses + $base_monthly_wip - $billing;
$financial_data['WIP'][$month] = $current_wip;
$financial_data['Billings'][$month] = $cumulative_billing;
$financial_data['Cost'][$month] = $cumulative_cost;
$financial_data['Opening Balance'][$month] = 0; // Placeholder
$financial_data['Expenses'][$month] = $expenses;
// Calculated metrics (NSR and Margin)
$nsr = $financial_data['WIP'][$month] + $financial_data['Billings'][$month] - $financial_data['Opening Balance'][$month] - $financial_data['Expenses'][$month];
$financial_data['NSR'][$month] = $nsr;
$margin = ($nsr != 0) ? (($nsr - $financial_data['Cost'][$month]) / $nsr) : 0;
$financial_data['Margin'][$month] = $margin;
// Update previous month's WIP for the next iteration
$previous_month_wip = $current_wip;
}
}
} catch (PDOException $e) {
header("HTTP/1.0 500 Internal Server Error");
echo "Database error: " . $e->getMessage();
exit;
}
if (!$project) {
header("HTTP/1.0 404 Not Found");
echo "Project not found.";
exit;
}
// --- CSV EXPORT ---
$filename = "project_finance_" . preg_replace('/[^a-zA-Z0-9_]/', '_', $project['name']) . ".csv";
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$output = fopen('php://output', 'w');
// Header row
$header = ['Metric'];
foreach ($months as $month) {
$header[] = date('M Y', strtotime($month));
}
fputcsv($output, $header);
// Data rows
foreach ($metrics as $metric) {
$row = [$metric];
foreach ($months as $month) {
$row[] = number_format($financial_data[$metric][$month] ?? 0, 2);
}
fputcsv($output, $row);
}
fclose($output);
exit;