index.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. // web/index.php
  3. declare(strict_types=1);
  4. // ---- DB config from env ----
  5. $DB_HOST = getenv('MYSQL_HOST') ?: 'db';
  6. $DB_NAME = getenv('MYSQL_DATABASE') ?: 'councils';
  7. $DB_USER = getenv('MYSQL_USER') ?: 'root';
  8. $DB_PASS = getenv('MYSQL_PASSWORD') ?: getenv('MYSQL_ROOT_PASSWORD');
  9. $DB_PORT = (int)(getenv('MYSQL_PORT') ?: 3306);
  10. // ---- Connect ----
  11. $dsn = "mysql:host={$DB_HOST};port={$DB_PORT};dbname={$DB_NAME};charset=utf8mb4";
  12. $pdo = new PDO($dsn, $DB_USER, $DB_PASS, [
  13. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  14. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  15. ]);
  16. // ---- Inputs ----
  17. $q = trim((string)($_GET['q'] ?? ''));
  18. $councilKeySel = trim((string)($_GET['council_key'] ?? '')); // table name like da_meandervalley
  19. $includeClosed = isset($_GET['include_closed']);
  20. $sort = (string)($_GET['sort'] ?? 'close'); // close|council|address|ref
  21. // ---- Discover da_* tables ----
  22. $allTables = [];
  23. $st = $pdo->query("SHOW TABLES");
  24. while ($row = $st->fetch(PDO::FETCH_NUM)) {
  25. $t = $row[0];
  26. if (strpos($t, 'da_') === 0) $allTables[] = $t;
  27. }
  28. // Exclude tables you don't want to UNION
  29. $exclude = ['geo_cache', 'da_plandata', 'da_plan_data', 'da_dorset_stages']; // add more here if needed
  30. $allTables = array_values(array_filter($allTables, fn($t) => !in_array($t, $exclude, true)));
  31. if (!$allTables) {
  32. http_response_code(200);
  33. echo "<h1>No da_* tables found</h1>";
  34. exit;
  35. }
  36. // Helpers
  37. /**
  38. * Return "`existing_col` AS `alias`" from the first column that exists,
  39. * otherwise "'' AS `alias`".
  40. */
  41. function aliasFirstExisting(PDO $pdo, string $table, array $candidates, string $alias): string {
  42. foreach ($candidates as $c) {
  43. if (tableHasColumn($pdo, $table, $c)) {
  44. return "`$c` AS `$alias`";
  45. }
  46. }
  47. return "'' AS `$alias`";
  48. }
  49. /** Abort if $table is not a safe da_* or da_*_stages identifier. */
  50. function validate_table_name(string $table): void {
  51. if (!preg_match('/\Ada_[a-z0-9_]+\z/', $table)) {
  52. http_response_code(500);
  53. exit("Invalid table name");
  54. }
  55. }
  56. function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
  57. function council_name_from_key(string $k): string {
  58. $base = preg_replace('/^da_/', '', $k);
  59. $base = str_replace('_', ' ', $base);
  60. $map = [
  61. 'flinders_council' => 'Flinders',
  62. 'southernmidlands' => 'Southern Midlands',
  63. ];
  64. if (isset($map[$base])) return $map[$base];
  65. return ucwords($base);
  66. }
  67. function days_left(?string $ymd): ?int {
  68. if (!$ymd) return null;
  69. $d = DateTime::createFromFormat('Y-m-d', $ymd);
  70. if (!$d) return null;
  71. $today = new DateTime('today');
  72. return (int)$today->diff($d)->format('%r%a');
  73. }
  74. function tableHasColumn(PDO $pdo, string $table, string $col): bool {
  75. validate_table_name($table);
  76. $q = $pdo->prepare("SHOW COLUMNS FROM `{$table}` LIKE ?");
  77. $q->execute([$col]);
  78. return (bool)$q->fetch();
  79. }
  80. function fmt_date(?string $ymd, string $fmt = 'd M y'): string {
  81. if (!$ymd) return '';
  82. $dt = DateTime::createFromFormat('Y-m-d', $ymd);
  83. return $dt ? $dt->format($fmt) : '';
  84. }
  85. function tableExists(PDO $pdo, string $table): bool {
  86. $st = $pdo->prepare("SHOW TABLES LIKE ?");
  87. $st->execute([$table]);
  88. return (bool)$st->fetch(PDO::FETCH_NUM);
  89. }
  90. /** Return the first non-empty from an array of possible keys */
  91. function firstField(array $row, array $candidates, $default = null) {
  92. foreach ($candidates as $k) {
  93. if (array_key_exists($k, $row) && $row[$k] !== null && $row[$k] !== '') {
  94. return $row[$k];
  95. }
  96. }
  97. return $default;
  98. }
  99. // Build council options
  100. $councilOptions = array_map(fn($t) => ['key' => $t, 'label' => council_name_from_key($t)], $allTables);
  101. usort($councilOptions, fn($a, $b) => strcasecmp($a['label'], $b['label']));
  102. $validKeys = array_column($councilOptions, 'key');
  103. if ($councilKeySel !== '' && !in_array($councilKeySel, $validKeys, true)) {
  104. $councilKeySel = '';
  105. }
  106. // Apply table filter
  107. $tables = $councilKeySel ? [$councilKeySel] : $allTables;
  108. // ---- Prefetch *_stages into [$council_key][$council_reference] ----
  109. $stagesByRef = [];
  110. foreach ($tables as $t) {
  111. $stageT = $t . '_stages';
  112. if (!tableExists($pdo, $stageT)) continue;
  113. validate_table_name($stageT);
  114. // Pull everything (small tables) – adjust/WHERE if needed
  115. $st2 = $pdo->query("SELECT * FROM `{$stageT}`");
  116. while ($r = $st2->fetch()) {
  117. $ref = $r['council_reference'] ?? null;
  118. if (!$ref) continue;
  119. // Normalise column names from varying scrapers
  120. $milestone = firstField($r, ['milestone']);
  121. $stageDesc = firstField($r, ['stage_desc','stage','stage_description']);
  122. $opened = firstField($r, ['opened','open_date']);
  123. $target = firstField($r, ['target_date','target']);
  124. $completed = firstField($r, ['completed','completed_date']);
  125. $status = firstField($r, ['status','stage_status']);
  126. $stagesByRef[$t][$ref][] = [
  127. 'milestone' => $milestone,
  128. 'stage' => $stageDesc,
  129. 'opened' => $opened,
  130. 'target' => $target,
  131. 'completed' => $completed,
  132. 'status' => $status,
  133. ];
  134. }
  135. // Optional: sort stages by opened date (NULLs last)
  136. if (!empty($stagesByRef[$t])) {
  137. foreach ($stagesByRef[$t] as &$lst) {
  138. usort($lst, function($a,$b){
  139. $A = $a['opened'] ?: '9999-12-31';
  140. $B = $b['opened'] ?: '9999-12-31';
  141. return strcmp($A,$B);
  142. });
  143. }
  144. unset($lst);
  145. }
  146. }
  147. // Build UNION with per-table optional columns
  148. $selects = [];
  149. foreach ($tables as $t) {
  150. // description can be named differently across scrapers
  151. $descriptionExpr = aliasFirstExisting(
  152. $pdo,
  153. $t,
  154. ['description','proposal','application_details','work_description','details','brief_description','desc'],
  155. 'description'
  156. );
  157. $cols = [
  158. "'{$t}' AS council_key",
  159. $descriptionExpr,
  160. "date_received",
  161. "date_received_raw",
  162. "on_notice_to",
  163. "on_notice_to_raw",
  164. "address",
  165. "council_reference",
  166. "property_id",
  167. ];
  168. // optional columns
  169. $cols[] = tableHasColumn($pdo, $t, 'address_std') ? "address_std" : "'' AS address_std";
  170. $cols[] = tableHasColumn($pdo, $t, 'applicant') ? "applicant" : "'' AS applicant";
  171. $cols[] = tableHasColumn($pdo, $t, 'owner') ? "owner" : "'' AS owner";
  172. $cols[] = tableHasColumn($pdo, $t, 'title_reference') ? "title_reference" : "'' AS title_reference";
  173. $cols[] = tableHasColumn($pdo, $t, 'document_url') ? "COALESCE(document_url,'') AS document_url" : "'' AS document_url";
  174. $cols[] = tableHasColumn($pdo, $t, 'local_document_url') ? "COALESCE(local_document_url,'') AS local_document_url" : "'' AS local_document_url";
  175. validate_table_name($t);
  176. $selects[] = "SELECT ".implode(", ", $cols)." FROM `{$t}`";
  177. }
  178. $sql = "SELECT * FROM (".implode(" UNION ALL ", $selects).") AS x";
  179. // Where
  180. $where = [];
  181. $params = [];
  182. if (!$includeClosed) {
  183. // show items that are still open today or later, or unknown close date
  184. $where[] = "(x.on_notice_to IS NULL OR x.on_notice_to >= CURDATE())";
  185. }
  186. if ($q !== '') {
  187. $where[] = "(x.address LIKE ? OR x.description LIKE ? OR x.council_reference LIKE ? OR x.address_std LIKE ?)";
  188. $like = "%{$q}%";
  189. array_push($params, $like, $like, $like, $like);
  190. }
  191. if ($where) $sql .= " WHERE ".implode(" AND ", $where);
  192. // Sort
  193. // Sort
  194. $dir = strtolower((string)($_GET['dir'] ?? 'desc')) === 'asc' ? 'ASC' : 'DESC';
  195. switch ($sort) {
  196. case 'council':
  197. // within a council, order by date
  198. $order = "x.council_key ASC, x.date_received $dir, x.address ASC";
  199. break;
  200. case 'address':
  201. $order = "x.address $dir";
  202. break;
  203. case 'ref':
  204. $order = "x.council_reference $dir";
  205. break;
  206. case 'close':
  207. default:
  208. // primary sort by close date
  209. $order = "(x.on_notice_to IS NULL) ASC, x.on_notice_to $dir, x.council_key ASC, x.address ASC";
  210. }
  211. $sql .= " ORDER BY {$order}";
  212. // Query
  213. $st = $pdo->prepare($sql);
  214. $st->execute($params);
  215. $rows = $st->fetchAll();
  216. ?>
  217. <!doctype html>
  218. <html lang="en">
  219. <head>
  220. <meta charset="utf-8">
  221. <meta name="viewport" content="width=device-width, initial-scale=1">
  222. <title>Advertised DAs</title>
  223. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
  224. <style>
  225. body { padding: 24px; }
  226. header form .form-control, header form select { min-width: 220px; }
  227. .badge-council { background:#6c757d; }
  228. .badge-open { background:#198754; }
  229. .badge-today { background:#ffc107; }
  230. .badge-closed { background:#dc3545; }
  231. .badge-unknown { background:#ced4da; }
  232. .muted { color:#6c757d; }
  233. .accordion-button .meta { margin-left:auto; display:flex; gap:.5rem; align-items:center; }
  234. .nowrap { white-space:nowrap; }
  235. </style>
  236. </head>
  237. <body>
  238. <header class="container mb-3">
  239. <h1 class="h3 mb-3">Currently Advertised Applications</h1>
  240. <a class="btn btn-outline-secondary btn-sm" href="councils.php">Council status</a>
  241. <form method="get" class="row g-2 align-items-center">
  242. <div class="col-auto">
  243. <input type="text" name="q" class="form-control" placeholder="Search address, ref, description" value="<?=h($q)?>">
  244. </div>
  245. <div class="col-auto">
  246. <select name="council_key" class="form-select">
  247. <option value="">All councils</option>
  248. <?php foreach ($councilOptions as $opt): ?>
  249. <option value="<?= h($opt['key']) ?>" <?= $opt['key']===$councilKeySel ? 'selected' : '' ?>>
  250. <?= h($opt['label']) ?>
  251. </option>
  252. <?php endforeach; ?>
  253. </select>
  254. </div>
  255. <div class="col-auto form-check">
  256. <input class="form-check-input" type="checkbox" name="include_closed" value="1" id="incClosed" <?= $includeClosed ? 'checked' : '' ?>>
  257. <label class="form-check-label" for="incClosed">include closed</label>
  258. </div>
  259. <div class="col-auto">
  260. <select name="sort" class="form-select">
  261. <option value="close" <?= $sort==='close'?'selected':'' ?>>sort by close date</option>
  262. <option value="council" <?= $sort==='council'?'selected':'' ?>>sort by council</option>
  263. <option value="address" <?= $sort==='address'?'selected':'' ?>>sort by address</option>
  264. <option value="ref" <?= $sort==='ref'?'selected':'' ?>>sort by reference</option>
  265. </select>
  266. </div>
  267. <div class="col-auto">
  268. <select name="dir" class="form-select">
  269. <option value="desc" <?= (($_GET['dir'] ?? '')==='desc') ? 'selected' : '' ?>>newest first</option>
  270. <option value="asc" <?= (($_GET['dir'] ?? '')!=='desc') ? 'selected' : '' ?>>oldest first</option>
  271. </select>
  272. </div>
  273. <div class="col-auto">
  274. <button type="submit" class="btn btn-primary">Apply</button>
  275. </div>
  276. </form>
  277. <div class="muted mt-2"><?= count($rows) ?> item(s)</div>
  278. </header>
  279. <div class="container">
  280. <div class="accordion" id="advertisedDA">
  281. <?php foreach ($rows as $i => $r):
  282. $uid = 'acc' . $i;
  283. $cname = council_name_from_key($r['council_key']);
  284. $days = days_left($r['on_notice_to']);
  285. $closeLabel = $r['on_notice_to'] ? h($r['on_notice_to']) : h($r['on_notice_to_raw']);
  286. $statusBadge = '';
  287. if ($r['on_notice_to']) {
  288. if ($days !== null && $days < 0) {
  289. $statusBadge = '<span class="badge badge-closed">closed</span>';
  290. } elseif ($days === 0) {
  291. $statusBadge = '<span class="badge badge-today">today</span>';
  292. } elseif ($days > 0) {
  293. $statusBadge = '<span class="badge badge-open">due '.$days.'d</span>';
  294. }
  295. } else {
  296. $statusBadge = '<span class="badge badge-unknown">unknown</span>';
  297. }
  298. // prefer local file, fallback to council URL
  299. $docLocal = trim((string)($r['local_document_url'] ?? ''));
  300. $docWeb = trim((string)($r['document_url'] ?? ''));
  301. $docHref = $docLocal !== '' ? $docLocal : $docWeb;
  302. ?>
  303. <div class="accordion-item">
  304. <h2 class="accordion-header" id="<?= $uid ?>-head">
  305. <button class="accordion-button collapsed py-2" type="button"
  306. data-bs-toggle="collapse"
  307. data-bs-target="#<?= $uid ?>-body"
  308. aria-expanded="false"
  309. aria-controls="<?= $uid ?>-body">
  310. <div class="col-2 align-self-start"><?= h($r['council_reference'] ?: '[no ref]') ?></div>
  311. <div class="col align-self-center"><?= h(($r['address_std'] ?: $r['address']) ?: '[no address]') ?></div>
  312. <div class="col align-self-emd meta ">
  313. <div class="col"><span class="badge badge-council"><?= h($cname) ?></span></div>
  314. <?php if ($closeLabel): ?>
  315. <div class="col"><span class="badge text-bg-light border nowrap">Close <?= $closeLabel ?></span></div>
  316. <?php endif; ?>
  317. <div class="col me-1"><?= $statusBadge ?></div>
  318. </div>
  319. </button>
  320. </h2>
  321. <div id="<?= $uid ?>-body" class="accordion-collapse collapse" aria-labelledby="<?= $uid ?>-head" data-bs-parent="#advertisedDA">
  322. <div class="accordion-body">
  323. <div class="row gy-2">
  324. <div class="col-md-3">
  325. <label class="form-label">Reference</label>
  326. <input type="text" class="form-control form-control-sm" value="<?= h($r['council_reference']) ?>" disabled readonly>
  327. </div>
  328. <div class="col-md-3">
  329. <label class="form-label">Title</label>
  330. <input type="text" class="form-control form-control-sm" value="<?= h($r['title_reference'] ?? '') ?>" disabled readonly>
  331. </div>
  332. <div class="col-md-3">
  333. <label class="form-label">Property ID</label>
  334. <input type="text" class="form-control form-control-sm" value="<?= h($r['property_id'] ?? '') ?>" disabled readonly>
  335. </div>
  336. <div class="col-md-3">
  337. <label class="form-label">Council</label>
  338. <input type="text" class="form-control form-control-sm" value="<?= h($cname) ?>" disabled readonly>
  339. </div>
  340. <div class="col-6">
  341. <label class="form-label">Owner</label>
  342. <input type="text" class="form-control form-control-sm" value="<?= h($r['owner'] ?? '') ?>" disabled readonly>
  343. </div>
  344. <div class="col-6">
  345. <label class="form-label">Applicant</label>
  346. <input type="text" class="form-control form-control-sm" value="<?= h($r['applicant'] ?? '') ?>" disabled readonly>
  347. </div>
  348. <div class="col-12">
  349. <label class="form-label">Address</label>
  350. <input type="text" class="form-control form-control-sm" value="<?= h(($r['address_std'] ?: $r['address']) ?? '') ?>" disabled readonly>
  351. </div>
  352. <div class="col-12">
  353. <label class="form-label">Description</label>
  354. <textarea class="form-control form-control-sm" rows="2" disabled readonly><?= h($r['description']) ?></textarea>
  355. </div>
  356. <div class="col-md-4">
  357. <label class="form-label">Received date</label>
  358. <input type="text" class="form-control form-control-sm" value="<?= h(fmt_date($r['date_received']) ?: ($r['date_received_raw'] ?? '')) ?>" disabled readonly>
  359. </div>
  360. <div class="col-md-4">
  361. <label class="form-label">Close date</label>
  362. <input type="text" class="form-control form-control-sm" value="<?= h(fmt_date($r['on_notice_to']) ?: ($r['on_notice_to_raw'] ?? '')) ?>" disabled readonly>
  363. </div>
  364. <div class="col-md-4">
  365. <label class="form-label">Days remaining</label>
  366. <input type="text" class="form-control form-control-sm" value="<?= is_null($days) ? '' : $days ?>" disabled readonly>
  367. </div>
  368. <div class="col-12">
  369. <?php if ($docHref !== ''): ?>
  370. <a class="btn btn-outline-secondary" href="<?= h($docHref) ?>" target="_blank" rel="noopener">Open document</a>
  371. <?php else: ?>
  372. <span class="text-muted">No document link</span>
  373. <?php endif; ?>
  374. </div>
  375. </div>
  376. <?php
  377. $refKey = (string)$r['council_reference'];
  378. $cKey = (string)$r['council_key'];
  379. $hasStages = !empty($stagesByRef[$cKey][$refKey]);
  380. $stageRows = $hasStages ? $stagesByRef[$cKey][$refKey] : [];
  381. ?>
  382. <?php if ($hasStages): ?>
  383. <div class="col-12 mt-3">
  384. <h6 class="mb-2">Stages</h6>
  385. <div class="table-responsive">
  386. <table class="table table-sm table-bordered align-middle mb-0">
  387. <thead class="table-light">
  388. <tr>
  389. <th style="width:18%">Milestone</th>
  390. <th>Stage</th>
  391. <th style="width:12%">Opened</th>
  392. <th style="width:12%">Target</th>
  393. <th style="width:12%">Completed</th>
  394. <th style="width:14%">Status</th>
  395. </tr>
  396. </thead>
  397. <tbody>
  398. <?php foreach ($stageRows as $sr): ?>
  399. <tr>
  400. <td><?= h($sr['milestone'] ?? '') ?></td>
  401. <td><?= h($sr['stage'] ?? '') ?></td>
  402. <td class="nowrap"><?= h(fmt_date($sr['opened'] ?? null)) ?></td>
  403. <td class="nowrap"><?= h(fmt_date($sr['target'] ?? null)) ?></td>
  404. <td class="nowrap"><?= h(fmt_date($sr['completed'] ?? null)) ?></td>
  405. <td><?= h($sr['status'] ?? '') ?></td>
  406. </tr>
  407. <?php endforeach; ?>
  408. </tbody>
  409. </table>
  410. </div>
  411. </div>
  412. <?php endif; ?>
  413. </div>
  414. </div>
  415. </div>
  416. <?php endforeach; ?>
  417. </div>
  418. </div>
  419. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
  420. </body>
  421. </html>