index.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. $cols[] = tableHasColumn($pdo, $t, 'documents_json') ? "documents_json" : "NULL AS documents_json";
  176. validate_table_name($t);
  177. $selects[] = "SELECT ".implode(", ", $cols)." FROM `{$t}`";
  178. }
  179. $sql = "SELECT * FROM (".implode(" UNION ALL ", $selects).") AS x";
  180. // Where
  181. $where = [];
  182. $params = [];
  183. if (!$includeClosed) {
  184. // show items that are still open today or later, or unknown close date
  185. $where[] = "(x.on_notice_to IS NULL OR x.on_notice_to >= CURDATE())";
  186. }
  187. if ($q !== '') {
  188. $where[] = "(x.address LIKE ? OR x.description LIKE ? OR x.council_reference LIKE ? OR x.address_std LIKE ?)";
  189. $like = "%{$q}%";
  190. array_push($params, $like, $like, $like, $like);
  191. }
  192. if ($where) $sql .= " WHERE ".implode(" AND ", $where);
  193. // Sort
  194. // Sort
  195. $dir = strtolower((string)($_GET['dir'] ?? 'desc')) === 'asc' ? 'ASC' : 'DESC';
  196. switch ($sort) {
  197. case 'council':
  198. // within a council, order by date
  199. $order = "x.council_key ASC, x.date_received $dir, x.address ASC";
  200. break;
  201. case 'address':
  202. $order = "x.address $dir";
  203. break;
  204. case 'ref':
  205. $order = "x.council_reference $dir";
  206. break;
  207. case 'close':
  208. default:
  209. // primary sort by close date
  210. $order = "(x.on_notice_to IS NULL) ASC, x.on_notice_to $dir, x.council_key ASC, x.address ASC";
  211. }
  212. $sql .= " ORDER BY {$order}";
  213. // Query
  214. $st = $pdo->prepare($sql);
  215. $st->execute($params);
  216. $rows = $st->fetchAll();
  217. ?>
  218. <!doctype html>
  219. <html lang="en">
  220. <head>
  221. <meta charset="utf-8">
  222. <meta name="viewport" content="width=device-width, initial-scale=1">
  223. <title>Advertised DAs</title>
  224. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
  225. <style>
  226. body { padding: 24px; }
  227. header form .form-control, header form select { min-width: 220px; }
  228. .badge-council { background:#6c757d; }
  229. .badge-open { background:#198754; }
  230. .badge-today { background:#ffc107; }
  231. .badge-closed { background:#dc3545; }
  232. .badge-unknown { background:#ced4da; }
  233. .muted { color:#6c757d; }
  234. .accordion-button .meta { margin-left:auto; display:flex; gap:.5rem; align-items:center; }
  235. .nowrap { white-space:nowrap; }
  236. </style>
  237. </head>
  238. <body>
  239. <header class="container mb-3">
  240. <h1 class="h3 mb-3">Currently Advertised Applications</h1>
  241. <a class="btn btn-outline-secondary btn-sm" href="councils.php">Council status</a>
  242. <form method="get" class="row g-2 align-items-center">
  243. <div class="col-auto">
  244. <input type="text" name="q" class="form-control" placeholder="Search address, ref, description" value="<?=h($q)?>">
  245. </div>
  246. <div class="col-auto">
  247. <select name="council_key" class="form-select">
  248. <option value="">All councils</option>
  249. <?php foreach ($councilOptions as $opt): ?>
  250. <option value="<?= h($opt['key']) ?>" <?= $opt['key']===$councilKeySel ? 'selected' : '' ?>>
  251. <?= h($opt['label']) ?>
  252. </option>
  253. <?php endforeach; ?>
  254. </select>
  255. </div>
  256. <div class="col-auto form-check">
  257. <input class="form-check-input" type="checkbox" name="include_closed" value="1" id="incClosed" <?= $includeClosed ? 'checked' : '' ?>>
  258. <label class="form-check-label" for="incClosed">include closed</label>
  259. </div>
  260. <div class="col-auto">
  261. <select name="sort" class="form-select">
  262. <option value="close" <?= $sort==='close'?'selected':'' ?>>sort by close date</option>
  263. <option value="council" <?= $sort==='council'?'selected':'' ?>>sort by council</option>
  264. <option value="address" <?= $sort==='address'?'selected':'' ?>>sort by address</option>
  265. <option value="ref" <?= $sort==='ref'?'selected':'' ?>>sort by reference</option>
  266. </select>
  267. </div>
  268. <div class="col-auto">
  269. <select name="dir" class="form-select">
  270. <option value="desc" <?= (($_GET['dir'] ?? '')==='desc') ? 'selected' : '' ?>>newest first</option>
  271. <option value="asc" <?= (($_GET['dir'] ?? '')!=='desc') ? 'selected' : '' ?>>oldest first</option>
  272. </select>
  273. </div>
  274. <div class="col-auto">
  275. <button type="submit" class="btn btn-primary">Apply</button>
  276. </div>
  277. </form>
  278. <div class="muted mt-2"><?= count($rows) ?> item(s)</div>
  279. </header>
  280. <div class="container">
  281. <div class="accordion" id="advertisedDA">
  282. <?php foreach ($rows as $i => $r):
  283. $uid = 'acc' . $i;
  284. $cname = council_name_from_key($r['council_key']);
  285. $days = days_left($r['on_notice_to']);
  286. $closeLabel = $r['on_notice_to'] ? h($r['on_notice_to']) : h($r['on_notice_to_raw']);
  287. $statusBadge = '';
  288. if ($r['on_notice_to']) {
  289. if ($days !== null && $days < 0) {
  290. $statusBadge = '<span class="badge badge-closed">closed</span>';
  291. } elseif ($days === 0) {
  292. $statusBadge = '<span class="badge badge-today">today</span>';
  293. } elseif ($days > 0) {
  294. $statusBadge = '<span class="badge badge-open">due '.$days.'d</span>';
  295. }
  296. } else {
  297. $statusBadge = '<span class="badge badge-unknown">unknown</span>';
  298. }
  299. // prefer local file, fallback to council URL
  300. $docLocal = trim((string)($r['local_document_url'] ?? ''));
  301. $docWeb = trim((string)($r['document_url'] ?? ''));
  302. $docHref = $docLocal !== '' ? $docLocal : $docWeb;
  303. // multi-document list (e.g. Launceston)
  304. $docList = [];
  305. $rawJson = $r['documents_json'] ?? '';
  306. if ($rawJson !== '' && $rawJson !== null) {
  307. $decoded = json_decode($rawJson, true);
  308. if (is_array($decoded)) {
  309. foreach ($decoded as $d) {
  310. $href = trim((string)($d['local_url'] ?? ''));
  311. if ($href === '') $href = trim((string)($d['url'] ?? ''));
  312. $name = trim((string)($d['name'] ?? ''));
  313. if ($name === '') $name = 'Document';
  314. if ($href !== '') $docList[] = ['href' => $href, 'name' => $name];
  315. }
  316. }
  317. }
  318. ?>
  319. <div class="accordion-item">
  320. <h2 class="accordion-header" id="<?= $uid ?>-head">
  321. <button class="accordion-button collapsed py-2" type="button"
  322. data-bs-toggle="collapse"
  323. data-bs-target="#<?= $uid ?>-body"
  324. aria-expanded="false"
  325. aria-controls="<?= $uid ?>-body">
  326. <div class="col-2 align-self-start"><?= h($r['council_reference'] ?: '[no ref]') ?></div>
  327. <div class="col align-self-center"><?= h(($r['address_std'] ?: $r['address']) ?: '[no address]') ?></div>
  328. <div class="col align-self-emd meta ">
  329. <div class="col"><span class="badge badge-council"><?= h($cname) ?></span></div>
  330. <?php if ($closeLabel): ?>
  331. <div class="col"><span class="badge text-bg-light border nowrap">Close <?= $closeLabel ?></span></div>
  332. <?php endif; ?>
  333. <div class="col me-1"><?= $statusBadge ?></div>
  334. </div>
  335. </button>
  336. </h2>
  337. <div id="<?= $uid ?>-body" class="accordion-collapse collapse" aria-labelledby="<?= $uid ?>-head" data-bs-parent="#advertisedDA">
  338. <div class="accordion-body">
  339. <div class="row gy-2">
  340. <div class="col-md-3">
  341. <label class="form-label">Reference</label>
  342. <input type="text" class="form-control form-control-sm" value="<?= h($r['council_reference']) ?>" disabled readonly>
  343. </div>
  344. <div class="col-md-3">
  345. <label class="form-label">Title</label>
  346. <input type="text" class="form-control form-control-sm" value="<?= h($r['title_reference'] ?? '') ?>" disabled readonly>
  347. </div>
  348. <div class="col-md-3">
  349. <label class="form-label">Property ID</label>
  350. <input type="text" class="form-control form-control-sm" value="<?= h($r['property_id'] ?? '') ?>" disabled readonly>
  351. </div>
  352. <div class="col-md-3">
  353. <label class="form-label">Council</label>
  354. <input type="text" class="form-control form-control-sm" value="<?= h($cname) ?>" disabled readonly>
  355. </div>
  356. <div class="col-6">
  357. <label class="form-label">Owner</label>
  358. <input type="text" class="form-control form-control-sm" value="<?= h($r['owner'] ?? '') ?>" disabled readonly>
  359. </div>
  360. <div class="col-6">
  361. <label class="form-label">Applicant</label>
  362. <input type="text" class="form-control form-control-sm" value="<?= h($r['applicant'] ?? '') ?>" disabled readonly>
  363. </div>
  364. <div class="col-12">
  365. <label class="form-label">Address</label>
  366. <input type="text" class="form-control form-control-sm" value="<?= h(($r['address_std'] ?: $r['address']) ?? '') ?>" disabled readonly>
  367. </div>
  368. <div class="col-12">
  369. <label class="form-label">Description</label>
  370. <textarea class="form-control form-control-sm" rows="2" disabled readonly><?= h($r['description']) ?></textarea>
  371. </div>
  372. <div class="col-md-4">
  373. <label class="form-label">Received date</label>
  374. <input type="text" class="form-control form-control-sm" value="<?= h(fmt_date($r['date_received']) ?: ($r['date_received_raw'] ?? '')) ?>" disabled readonly>
  375. </div>
  376. <div class="col-md-4">
  377. <label class="form-label">Close date</label>
  378. <input type="text" class="form-control form-control-sm" value="<?= h(fmt_date($r['on_notice_to']) ?: ($r['on_notice_to_raw'] ?? '')) ?>" disabled readonly>
  379. </div>
  380. <div class="col-md-4">
  381. <label class="form-label">Days remaining</label>
  382. <input type="text" class="form-control form-control-sm" value="<?= is_null($days) ? '' : $days ?>" disabled readonly>
  383. </div>
  384. <div class="col-12">
  385. <?php if (!empty($docList)): ?>
  386. <div class="d-flex flex-wrap gap-2">
  387. <?php foreach ($docList as $doc): ?>
  388. <a class="btn btn-sm btn-outline-secondary" href="<?= h($doc['href']) ?>" target="_blank" rel="noopener"><?= h($doc['name']) ?></a>
  389. <?php endforeach; ?>
  390. </div>
  391. <?php elseif ($docHref !== ''): ?>
  392. <a class="btn btn-outline-secondary" href="<?= h($docHref) ?>" target="_blank" rel="noopener">Open document</a>
  393. <?php else: ?>
  394. <span class="text-muted">No document link</span>
  395. <?php endif; ?>
  396. </div>
  397. </div>
  398. <?php
  399. $refKey = (string)$r['council_reference'];
  400. $cKey = (string)$r['council_key'];
  401. $hasStages = !empty($stagesByRef[$cKey][$refKey]);
  402. $stageRows = $hasStages ? $stagesByRef[$cKey][$refKey] : [];
  403. ?>
  404. <?php if ($hasStages): ?>
  405. <div class="col-12 mt-3">
  406. <h6 class="mb-2">Stages</h6>
  407. <div class="table-responsive">
  408. <table class="table table-sm table-bordered align-middle mb-0">
  409. <thead class="table-light">
  410. <tr>
  411. <th style="width:18%">Milestone</th>
  412. <th>Stage</th>
  413. <th style="width:12%">Opened</th>
  414. <th style="width:12%">Target</th>
  415. <th style="width:12%">Completed</th>
  416. <th style="width:14%">Status</th>
  417. </tr>
  418. </thead>
  419. <tbody>
  420. <?php foreach ($stageRows as $sr): ?>
  421. <tr>
  422. <td><?= h($sr['milestone'] ?? '') ?></td>
  423. <td><?= h($sr['stage'] ?? '') ?></td>
  424. <td class="nowrap"><?= h(fmt_date($sr['opened'] ?? null)) ?></td>
  425. <td class="nowrap"><?= h(fmt_date($sr['target'] ?? null)) ?></td>
  426. <td class="nowrap"><?= h(fmt_date($sr['completed'] ?? null)) ?></td>
  427. <td><?= h($sr['status'] ?? '') ?></td>
  428. </tr>
  429. <?php endforeach; ?>
  430. </tbody>
  431. </table>
  432. </div>
  433. </div>
  434. <?php endif; ?>
  435. </div>
  436. </div>
  437. </div>
  438. <?php endforeach; ?>
  439. </div>
  440. </div>
  441. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
  442. </body>
  443. </html>