359 lines
18 KiB
PHP
359 lines
18 KiB
PHP
<?php
|
|
require_once __DIR__ . '/db/config.php';
|
|
|
|
// --- DATABASE MIGRATION ---
|
|
function execute_sql_from_file($pdo, $filepath) {
|
|
try {
|
|
$sql = file_get_contents($filepath);
|
|
if ($sql === false) return false;
|
|
$pdo->exec($sql);
|
|
return true;
|
|
} catch (PDOException $e) {
|
|
// Ignore errors about tables/columns that already exist
|
|
if (strpos($e->getMessage(), 'already exists') === false && strpos($e->getMessage(), 'Duplicate column name') === false && strpos($e->getMessage(), 'Duplicate key name') === false) {
|
|
error_log("SQL Execution Error in $filepath: " . $e->getMessage());
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
$migration_files = glob(__DIR__ . '/db/migrations/*.sql');
|
|
sort($migration_files);
|
|
foreach ($migration_files as $file) {
|
|
execute_sql_from_file($pdo, $file);
|
|
}
|
|
} catch (PDOException $e) {
|
|
$db_error = "Database connection failed: " . $e->getMessage();
|
|
// Stop execution if DB connection fails
|
|
die($db_error);
|
|
}
|
|
|
|
// --- DATA FETCHING & CALCULATION ---
|
|
$project = null;
|
|
$project_id = $_GET['id'] ?? null;
|
|
$financial_data = [];
|
|
$months = [];
|
|
$metrics = ["Opening Balance", "Billings", "WIP", "Expenses", "Cost", "NSR", "Margin", "Payment"];
|
|
|
|
if ($project_id) {
|
|
$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = :id");
|
|
$stmt->execute([':id' => $project_id]);
|
|
$project = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($project) {
|
|
// Helper to generate month range
|
|
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']);
|
|
|
|
// Initialize financial data structure
|
|
foreach ($metrics as $metric) {
|
|
foreach ($months as $month) {
|
|
$financial_data[$metric][$month] = 0;
|
|
}
|
|
}
|
|
|
|
// --- 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);
|
|
|
|
// Base Monthly Expenses
|
|
$expenses_stmt = $pdo->prepare("SELECT month, amount FROM expensesMonthly WHERE projectId = :pid");
|
|
$expenses_stmt->execute([':pid' => $project_id]);
|
|
$monthly_expenses = $expenses_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
|
|
|
|
// Fetch confirmed override data
|
|
$finance_override_stmt = $pdo->prepare("SELECT * FROM projectFinanceMonthly WHERE projectId = :pid ORDER BY month ASC");
|
|
$finance_override_stmt->execute([':pid' => $project_id]);
|
|
$overrides_raw = $finance_override_stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
$finance_overrides = [];
|
|
foreach ($overrides_raw as $row) {
|
|
$finance_overrides[$row['month']] = $row;
|
|
}
|
|
|
|
// 2. Calculate cumulative values month by month
|
|
$cumulative_billing = 0;
|
|
$cumulative_cost = 0;
|
|
$cumulative_expenses = 0;
|
|
$previous_month_wip = 0;
|
|
|
|
foreach ($months as $month) {
|
|
if (isset($finance_overrides[$month])) {
|
|
// This month has saved data. Use its values.
|
|
$financial_data['Opening Balance'][$month] = $finance_overrides[$month]['opening_balance'];
|
|
$financial_data['Billings'][$month] = $finance_overrides[$month]['payment'];
|
|
$financial_data['Payment'][$month] = $finance_overrides[$month]['payment'];
|
|
$financial_data['WIP'][$month] = $finance_overrides[$month]['wip'];
|
|
$financial_data['Expenses'][$month] = $finance_overrides[$month]['expenses'];
|
|
$financial_data['Cost'][$month] = $finance_overrides[$month]['cost'];
|
|
$financial_data['NSR'][$month] = $finance_overrides[$month]['nsr'];
|
|
$financial_data['Margin'][$month] = $finance_overrides[$month]['margin'];
|
|
|
|
// Update cumulative trackers for the next potential calculation
|
|
$cumulative_billing = $financial_data['Billings'][$month];
|
|
$cumulative_cost = $financial_data['Cost'][$month];
|
|
$cumulative_expenses= $financial_data['Expenses'][$month];
|
|
$previous_month_wip = $financial_data['WIP'][$month];
|
|
} else {
|
|
// This month has no saved data. Calculate as usual.
|
|
$cost = $monthly_costs[$month] ?? 0;
|
|
$base_monthly_wip = $monthly_wip[$month] ?? 0;
|
|
$billing = $monthly_billing[$month] ?? 0;
|
|
$expenses = $monthly_expenses[$month] ?? 0;
|
|
|
|
// Cumulative calculations
|
|
$cumulative_billing += $billing;
|
|
$cumulative_cost += $cost;
|
|
$cumulative_expenses += $expenses;
|
|
|
|
// WIP Calculation
|
|
$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] = $cumulative_expenses;
|
|
$financial_data['Payment'][$month] = 0; // Not overridden, so no payment input
|
|
|
|
// 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;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- PAGE RENDER ---
|
|
if (!$project) {
|
|
http_response_code(404);
|
|
$page_title = "Project Not Found";
|
|
} else {
|
|
$page_title = "Details for " . htmlspecialchars($project['name']);
|
|
}
|
|
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="en" data-bs-theme="dark">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title><?php echo $page_title; ?></title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
|
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
|
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
|
|
</head>
|
|
<body>
|
|
<div class="top-navbar">
|
|
Project Financials
|
|
</div>
|
|
<div class="main-wrapper">
|
|
<nav class="sidebar">
|
|
<ul class="nav flex-column">
|
|
<li class="nav-item"><a class="nav-link" href="roster.php"><i class="bi bi-people-fill me-2"></i>Roster</a></li>
|
|
<li class="nav-item"><a class="nav-link active" href="projects.php"><i class="bi bi-briefcase-fill me-2"></i>Projects</a></li>
|
|
</ul>
|
|
</nav>
|
|
|
|
<main class="content-wrapper">
|
|
<?php if (!$project): ?>
|
|
<div class="alert alert-danger">Project with ID <?php echo htmlspecialchars($project_id); ?> not found.</div>
|
|
<?php else: ?>
|
|
<div class="page-header">
|
|
<h1 class="h2">Project: <?php echo htmlspecialchars($project['name']); ?></h1>
|
|
<div class="header-actions">
|
|
<a href="billing.php?id=<?php echo $project['id']; ?>" class="btn btn-primary"><i class="bi bi-credit-card-fill me-2"></i>Billing</a>
|
|
<a href="expenses.php?id=<?php echo $project['id']; ?>" class="btn btn-danger me-2"><i class="bi bi-wallet-fill me-2"></i>Expenses</a>
|
|
<a href="forecasting.php?projectId=<?php echo $project['id']; ?>" class="btn btn-success"><i class="bi bi-bar-chart-line-fill me-2"></i>Forecasting</a>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Section 1: Project Information -->
|
|
<div class="card mb-4">
|
|
<div class="card-header">
|
|
<h5 class="card-title mb-0">Project Information</h5>
|
|
</div>
|
|
<div class="card-body">
|
|
<div class="row">
|
|
<div class="col-md-6">
|
|
<dl class="row">
|
|
<dt class="col-sm-4">Name</dt>
|
|
<dd class="col-sm-8"><?php echo htmlspecialchars($project['name']); ?></dd>
|
|
<dt class="col-sm-4">WBS</dt>
|
|
<dd class="col-sm-8"><?php echo htmlspecialchars($project['wbs'] ?? 'N/A'); ?></dd>
|
|
<dt class="col-sm-4">Start Date</dt>
|
|
<dd class="col-sm-8"><?php echo htmlspecialchars($project['startDate']); ?></dd>
|
|
<dt class="col-sm-4">End Date</dt>
|
|
<dd class="col-sm-8"><?php echo htmlspecialchars($project['endDate']); ?></dd>
|
|
</dl>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<dl class="row">
|
|
<dt class="col-sm-4">Budget</dt>
|
|
<dd class="col-sm-8">€<?php echo number_format($project['budget'], 2); ?></dd>
|
|
<dt class="col-sm-4">Recoverability</dt>
|
|
<dd class="col-sm-8"><?php echo number_format($project['recoverability'], 2); ?>%</dd>
|
|
<dt class="col-sm-4">Target Margin</dt>
|
|
<dd class="col-sm-8"><?php echo number_format($project['targetMargin'], 2); ?>%</dd>
|
|
</dl>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Section 2: Monthly Financials -->
|
|
<div class="card mb-4">
|
|
<div class="card-header d-flex justify-content-between align-items-center">
|
|
<h5 class="card-title mb-0">Monthly Financials</h5>
|
|
<div class="actions">
|
|
<button class="btn btn-secondary disabled" disabled><i class="bi bi-upload me-2"></i>Import</button>
|
|
<a href="export_project_finance.php?project_id=<?php echo $project['id']; ?>" class="btn btn-secondary"><i class="bi bi-download me-2"></i>Export</a>
|
|
</div>
|
|
</div>
|
|
<div class="table-responsive">
|
|
<?php
|
|
// Determine override eligibility
|
|
$override_eligible_month = null;
|
|
foreach ($months as $month) {
|
|
if (!isset($finance_overrides[$month]) || !$finance_overrides[$month]['is_confirmed']) {
|
|
$override_eligible_month = $month;
|
|
break;
|
|
}
|
|
}
|
|
?>
|
|
<table class="table table-bordered table-hover" id="financials-table">
|
|
<thead>
|
|
<tr class="text-center">
|
|
<th class="bg-body-tertiary" style="min-width: 150px;">Metric</th>
|
|
<?php foreach ($months as $month): ?>
|
|
<th>
|
|
<?php echo date('M Y', strtotime($month)); ?><br>
|
|
<?php
|
|
$is_confirmed = isset($finance_overrides[$month]) && $finance_overrides[$month]['is_confirmed'];
|
|
$is_eligible = ($month === $override_eligible_month);
|
|
|
|
if ($is_confirmed) {
|
|
echo '<span class="badge bg-success mt-1">Confirmed</span>';
|
|
} elseif ($is_eligible) {
|
|
echo '<button class="btn btn-sm btn-warning override-btn mt-1" data-month="' . $month . '">Override</button>';
|
|
} else {
|
|
echo '<button class="btn btn-sm btn-secondary mt-1" disabled>Override</button>';
|
|
}
|
|
?>
|
|
</th>
|
|
<?php endforeach; ?>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
<?php foreach ($metrics as $metric): ?>
|
|
<tr data-metric="<?php echo htmlspecialchars($metric); ?>">
|
|
<td class="fw-bold bg-body-tertiary"><?php echo $metric; ?></td>
|
|
<?php foreach ($months as $month): ?>
|
|
<td class="text-end financial-metric" data-month="<?php echo $month; ?>" data-metric="<?php echo htmlspecialchars($metric); ?>">
|
|
<?php
|
|
if ($metric === 'Margin') {
|
|
echo number_format(($financial_data[$metric][$month] ?? 0) * 100, 2) . '%';
|
|
} else {
|
|
echo '€' . number_format($financial_data[$metric][$month] ?? 0, 2);
|
|
}
|
|
?>
|
|
</td>
|
|
<?php endforeach; ?>
|
|
</tr>
|
|
<?php endforeach; ?>
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<?php endif; ?>
|
|
</main>
|
|
</div>
|
|
|
|
<script id="financial-data" type="application/json">
|
|
<?php
|
|
$project_id_js = $project['id'];
|
|
|
|
$finance_overrides_js = [];
|
|
foreach($finance_overrides as $month => $data) {
|
|
$finance_overrides_js[$month] = [
|
|
'is_confirmed' => $data['is_confirmed'],
|
|
'Opening Balance' => $data['opening_balance'],
|
|
'Billings' => $data['payment'],
|
|
'Payment' => $data['payment'],
|
|
'WIP' => $data['wip'],
|
|
'Expenses' => $data['expenses'],
|
|
'Cost' => $data['cost'],
|
|
'NSR' => $data['nsr'],
|
|
'Margin' => $data['margin']
|
|
];
|
|
}
|
|
|
|
$js_data = [
|
|
'projectId' => $project_id_js,
|
|
'months' => $months,
|
|
'metrics' => $metrics,
|
|
'initialFinancialData' => $financial_data,
|
|
'baseData' => [
|
|
'monthly_costs' => $monthly_costs,
|
|
'monthly_wip' => $monthly_wip,
|
|
'monthly_billing' => $monthly_billing,
|
|
'monthly_expenses' => $monthly_expenses,
|
|
],
|
|
'overrides' => $finance_overrides_js
|
|
];
|
|
echo json_encode($js_data, JSON_PRETTY_PRINT);
|
|
?>
|
|
</script>
|
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
|
|
<script src="assets/js/project_details.js?v=<?php echo time(); ?>"></script>
|
|
</body>
|
|
</html>
|