index.php 21 KB

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