progress.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. <?php
  2. error_reporting(E_ALL);
  3. ini_set("display_errors", 1);
  4. date_default_timezone_set("Australia/Hobart");
  5. // Adjust path if your contracts live elsewhere.
  6. if (!defined('CONTRACTS_DIR')) {
  7. define('CONTRACTS_DIR', realpath(__DIR__ . '/contracts'));
  8. }
  9. function contract_path_for_client(string $clientid): string {
  10. $id = preg_replace('/[^A-Za-z0-9_-]/', '', $clientid);
  11. return rtrim(CONTRACTS_DIR, '/\\') . DIRECTORY_SEPARATOR . $id . '.md';
  12. }
  13. /** Very small front-matter puller; same idea as contracts admin */
  14. function extract_front_matter_fields_progress(string $file): array {
  15. $out = [];
  16. $txt = @file_get_contents($file);
  17. if (!$txt) return $out;
  18. if (!preg_match('/^---\s*\R(.*?)\R---/s', $txt, $m)) return $out;
  19. $fm = $m[1];
  20. // admin.secret or admin_secret
  21. if (preg_match('/^\s*admin\s*:\s*$(.*?)^(?=\S)/ms', $fm."\nX", $block)) {
  22. $adminBlock = $block[1];
  23. if (preg_match('/^\s*secret\s*:\s*["\']?([^"\']+)["\']?/mi', $adminBlock, $mm)) {
  24. $out['admin_secret'] = trim($mm[1]);
  25. }
  26. }
  27. if (empty($out['admin_secret']) && preg_match('/^\s*admin_secret\s*:\s*["\']?([^"\']+)["\']?/mi', $fm, $mm)) {
  28. $out['admin_secret'] = trim($mm[1]);
  29. }
  30. return $out;
  31. }
  32. /** Build the exact token we expect for the public progress page */
  33. function progress_expected_token(string $clientid, $appId): ?string {
  34. $path = contract_path_for_client($clientid);
  35. $fm = extract_front_matter_fields_progress($path);
  36. $secret = $fm['admin_secret'] ?? '';
  37. if ($secret === '') return null;
  38. return hash_hmac('sha256', 'progress|' . (string)$appId, $secret);
  39. }
  40. $cfg = require __DIR__ . '/config.php';
  41. $dsn = 'mysql:host=' . $cfg['db_host'] . ';dbname=' . $cfg['db_name'] . ';charset=utf8mb4';
  42. $options = [
  43. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  44. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  45. ];
  46. try {
  47. $pdo = new PDO($dsn, $cfg['db_username'], $cfg['db_password'], $options);
  48. } catch (PDOException $e) {
  49. exit('Database connection failed: ' . $e->getMessage());
  50. }
  51. $app_id_raw = $_GET['id'] ?? '';
  52. $token = $_GET['token'] ?? '';
  53. $app_id = preg_match('/^\d+$/', $app_id_raw) ? $app_id_raw : '0';
  54. // Verify token (optional: match your token logic)
  55. $stmt = $pdo->prepare("SELECT client_email, reference, created_at, submission_date, required_by, clock_paused, clock_paused_at, clock_pause_reason FROM applications WHERE id = ?");
  56. $stmt->execute([$app_id]);
  57. $app = $stmt->fetch(PDO::FETCH_ASSOC);
  58. if (!$app) {
  59. http_response_code(404);
  60. exit("Application not found.");
  61. }
  62. // Fetch stages
  63. $stmt = $pdo->prepare("SELECT * FROM application_stages WHERE application_id = ? ORDER BY position ASC");
  64. $stmt->execute([$app_id]);
  65. $stages = $stmt->fetchAll(PDO::FETCH_ASSOC);
  66. $totalStages = 7;
  67. $currentStage = count(array_filter($stages, function ($s) {
  68. return strtolower(trim($s['status'] ?? '')) === 'complete';
  69. }));
  70. $progress = round(($currentStage / $totalStages) * 100);
  71. $isPaused = (int)($app['clock_paused'] ?? 0) === 1;
  72. $pauseReason = trim((string)($app['clock_pause_reason'] ?? ''));
  73. $decisionDate = null;
  74. // 1) Look for an explicit 'Council Decision Due' stage date
  75. $decisionStage = null;
  76. foreach ($stages as $s) {
  77. if (stripos($s['title'] ?? '', 'decision') !== false && !empty($s['stage_date'])) {
  78. $decisionStage = $s;
  79. break;
  80. }
  81. }
  82. if ($decisionStage) {
  83. $decisionDate = new DateTime($decisionStage['stage_date'], new DateTimeZone('Australia/Hobart'));
  84. } elseif (!empty($app['required_by'])) {
  85. $decisionDate = new DateTime($app['required_by'], new DateTimeZone('Australia/Hobart'));
  86. } elseif (!empty($app['submission_date'])) {
  87. $decisionDate = (new DateTime($app['submission_date'], new DateTimeZone('Australia/Hobart')))->modify('+42 days');
  88. }
  89. // set a friendly “end of business day” time so the countdown isn’t midnight-awkward
  90. if ($decisionDate) { $decisionDate->setTime(17, 0, 0); }
  91. $decisionIso = $decisionDate ? $decisionDate->format('c') : '';
  92. // --- Create correspondence entry ---
  93. if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_correspondence') {
  94. $tz = new DateTimeZone('Australia/Hobart');
  95. $typeAllow = ['incoming','outgoing','note'];
  96. $channelAllow = ['email','phone','portal','letter','meeting','other'];
  97. $visibilityAllow= ['client','internal'];
  98. $type = in_array($_POST['type'] ?? 'note', $typeAllow, true) ? $_POST['type'] : 'note';
  99. $channel = in_array($_POST['channel'] ?? 'other', $channelAllow, true) ? $_POST['channel'] : 'other';
  100. $visibility = in_array($_POST['visibility'] ?? 'client', $visibilityAllow, true) ? $_POST['visibility'] : 'client';
  101. $subject = trim($_POST['subject'] ?? '') ?: null;
  102. $author = trim($_POST['author'] ?? '') ?: null;
  103. $pin = isset($_POST['pin']) ? 1 : 0;
  104. $bodyRaw = trim($_POST['body'] ?? '');
  105. if ($bodyRaw === '') { $bodyRaw = '(no content)'; }
  106. // event_at: prefer user input, else "now"
  107. $eventAtRaw = trim($_POST['event_at'] ?? '');
  108. try {
  109. $eventAt = $eventAtRaw ? new DateTime($eventAtRaw, $tz) : new DateTime('now', $tz);
  110. } catch (Exception $e) {
  111. $eventAt = new DateTime('now', $tz);
  112. }
  113. $stmt = $pdo->prepare("
  114. INSERT INTO application_correspondence
  115. (application_id, event_at, type, channel, subject, body, author, visibility, pin)
  116. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
  117. ");
  118. $stmt->execute([
  119. $app_id,
  120. $eventAt->format('Y-m-d H:i:s'),
  121. $type,
  122. $channel,
  123. $subject,
  124. $bodyRaw,
  125. $author,
  126. $visibility,
  127. $pin
  128. ]);
  129. // Redirect to avoid resubmission and jump to the timeline section
  130. header("Location: ".$_SERVER['REQUEST_URI']."#correspondence");
  131. exit;
  132. }
  133. // Fetch timeline (newest first; pinned first)
  134. $stmt = $pdo->prepare("
  135. SELECT id, event_at, type, channel, subject, body, author, visibility, pin, created_at
  136. FROM application_correspondence
  137. WHERE application_id = ?
  138. ORDER BY pin DESC, event_at DESC, id DESC
  139. LIMIT 200
  140. ");
  141. $stmt->execute([$app_id]);
  142. $correspondence = $stmt->fetchAll(PDO::FETCH_ASSOC);
  143. /* NEW: attachment counts (and optional details) */
  144. $fileCounts = [];
  145. $filesByCorr = []; // if you also want to list the files
  146. if (!empty($correspondence)) {
  147. $ids = array_column($correspondence, 'id');
  148. $ph = implode(',', array_fill(0, count($ids), '?'));
  149. // Count files per correspondence
  150. $qc = $pdo->prepare("
  151. SELECT correspondence_id, COUNT(*) AS n
  152. FROM application_correspondence_files
  153. WHERE correspondence_id IN ($ph)
  154. GROUP BY correspondence_id
  155. ");
  156. $qc->execute($ids);
  157. foreach ($qc->fetchAll(PDO::FETCH_ASSOC) as $r) {
  158. $fileCounts[(int)$r['correspondence_id']] = (int)$r['n'];
  159. }
  160. // OPTIONAL: load file details if you want links
  161. $qd = $pdo->prepare("
  162. SELECT correspondence_id, original_name, file_url
  163. FROM application_correspondence_files
  164. WHERE correspondence_id IN ($ph)
  165. ORDER BY id ASC
  166. ");
  167. $qd->execute($ids);
  168. foreach ($qd->fetchAll(PDO::FETCH_ASSOC) as $f) {
  169. $cid = (int)$f['correspondence_id'];
  170. if (!isset($filesByCorr[$cid])) $filesByCorr[$cid] = [];
  171. $filesByCorr[$cid][] = $f;
  172. }
  173. }
  174. // ------------------ HELPERS ------------------
  175. function render_body_html(string $text): string {
  176. // escape first
  177. $s = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
  178. // linkify http(s)
  179. $s = preg_replace('~(https?://[^\s<]+)~i', '<a href="$1" target="_blank" rel="noopener">$1</a>', $s);
  180. // newlines to <br>
  181. return nl2br($s);
  182. }
  183. function stage_icon_for(string $title): string {
  184. $t = strtolower($title);
  185. if (str_contains($t,'submit')) return 'bi-upload';
  186. if (str_contains($t,'ack')) return 'bi-inbox';
  187. if (str_contains($t,'fee') || str_contains($t,'paid')) return 'bi-cash-coin';
  188. if (str_contains($t,'valid') || str_contains($t,'confirm')) return 'bi-check2-circle';
  189. if (str_contains($t,'advert')) return 'bi-megaphone';
  190. if (str_contains($t,'decision')) return 'bi-check-circle-fill';
  191. return 'bi-flag';
  192. }
  193. // --- Require signed token from Contracts Admin link ---
  194. $clientid = $_GET['clientid'] ?? '';
  195. $token = $_GET['token'] ?? '';
  196. if (!preg_match('/^[A-Za-z0-9_-]+$/', $clientid)) {
  197. http_response_code(400);
  198. exit('Bad link (clientid).');
  199. }
  200. if ($token === '') {
  201. http_response_code(403);
  202. exit('Missing token.');
  203. }
  204. // Build expected token from the .md front matter secret
  205. $expected = progress_expected_token($clientid, $app_id);
  206. if (!$expected || !hash_equals($expected, $token)) {
  207. http_response_code(403);
  208. exit('Invalid or expired link.');
  209. }
  210. ?>
  211. <!doctype html>
  212. <html lang="en">
  213. <head>
  214. <meta charset="utf-8">
  215. <meta name="viewport" content="width=device-width, initial-scale=1">
  216. <title> <?= htmlspecialchars($app['reference']) ?> – Application Progress</title>
  217. <link rel="shortcut icon" href="../../internal/images/blueprint.ico" type="image/x-icon">
  218. <meta name="robots" content="noindex">
  219. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous">
  220. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js" integrity="sha384-ndDqU0Gzau9qJ1lfW4pNLlhNTkCfHzAVBReH9diLvGRem5+R9g2FzA8ZGN954O5Q" crossorigin="anonymous"></script>
  221. <link href="../../internal/css/blueprint.css" rel="stylesheet">
  222. <link href="../../internal/css/print.css" rel="stylesheet" media="print">
  223. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
  224. <link href="progress.css" rel="stylesheet">
  225. <style>
  226. .popover-attachments {
  227. max-width: 360px;
  228. }
  229. .popover-attachments .popover-body {
  230. padding: .5rem .75rem;
  231. }
  232. /* wrapper so lots of steps can scroll horizontally on small screens */
  233. .timeline-wrap {
  234. overflow-x: auto;
  235. -webkit-overflow-scrolling: touch;
  236. padding-bottom: .25rem;
  237. /* keep scrollbar off arrows */
  238. }
  239. /* your snippet */
  240. #timeline {
  241. list-style: none;
  242. display: flex;
  243. width: 100%;
  244. margin: 0;
  245. }
  246. #timeline .icon {
  247. font-size: 14px;
  248. }
  249. #timeline li {
  250. flex: 1 1 0;
  251. min-width: 0;
  252. }
  253. #timeline li a {
  254. color: #FFF;
  255. display: block;
  256. background: #3498db;
  257. text-decoration: none;
  258. position: relative;
  259. height: 40px;
  260. line-height: 40px;
  261. padding: 0 12px 0 8px;
  262. text-align: center;
  263. margin-right: 23px;
  264. white-space: nowrap;
  265. }
  266. #timeline li:nth-child(even) a {
  267. background-color: #2980b9;
  268. }
  269. #timeline li:nth-child(even) a:before {
  270. border-color: #2980b9;
  271. border-left-color: transparent;
  272. }
  273. #timeline li:nth-child(even) a:after {
  274. border-left-color: #2980b9;
  275. }
  276. #timeline li:first-child a {
  277. padding-left: 15px;
  278. border-radius: 0;
  279. }
  280. #timeline li:first-child a:before {
  281. border: none;
  282. }
  283. #timeline li:last-child a {
  284. padding-right: 15px;
  285. border-radius: 0;
  286. }
  287. #timeline li:last-child a:after {
  288. border: none;
  289. }
  290. #timeline li a:before,
  291. #timeline li a:after {
  292. content: "";
  293. position: absolute;
  294. top: 0;
  295. border: 0 solid #3498db;
  296. border-width: 20px 10px;
  297. width: 0;
  298. height: 0;
  299. }
  300. #timeline li a:before {
  301. left: -20px;
  302. border-left-color: transparent;
  303. }
  304. #timeline li a:after {
  305. left: 100%;
  306. border-color: transparent;
  307. border-left-color: #3498db;
  308. }
  309. #timeline li a:hover {
  310. background-color: #1abc9c;
  311. }
  312. #timeline li a:hover:before {
  313. border-color: #1abc9c;
  314. border-left-color: transparent;
  315. }
  316. #timeline li a:hover:after {
  317. border-left-color: #1abc9c;
  318. }
  319. #timeline li a:active {
  320. background-color: #16a085;
  321. }
  322. #timeline li a:active:before {
  323. border-color: #16a085;
  324. border-left-color: transparent;
  325. }
  326. #timeline li a:active:after {
  327. border-left-color: #16a085;
  328. }
  329. /* Icon tweaks inside the pill */
  330. #timeline li a .bi {
  331. font-size: 1rem;
  332. vertical-align: -1px;
  333. margin-right: .35rem;
  334. }
  335. #timeline li a small {
  336. opacity: .9;
  337. margin-left: .35rem;
  338. }
  339. /* Stack on small screens (match original breakpoint) */
  340. @media (max-width: 1399px) {
  341. #timeline {
  342. display: block;
  343. }
  344. /* stop flex row */
  345. #timeline li {
  346. flex: 0 0 100%;
  347. max-width: 100%;
  348. margin: .5rem 0;
  349. }
  350. #timeline li a {
  351. height: auto;
  352. line-height: 1.3;
  353. padding: .65rem .9rem;
  354. /* comfy pill */
  355. border-radius: .25rem;
  356. }
  357. /* remove arrow heads when stacked */
  358. #timeline li a:before,
  359. #timeline li a:after {
  360. content: none !important;
  361. border: 0 !important;
  362. }
  363. }
  364. /* ---- STATE COLOURS (match original) ---- */
  365. #timeline li.is-current a {
  366. background: #97846E;
  367. /* brown */
  368. color: #EADFD7;
  369. /* cream text */
  370. }
  371. #timeline li.is-current a:before {
  372. border-color: #97846E;
  373. border-left-color: transparent;
  374. }
  375. #timeline li.is-current a:after {
  376. border-left-color: #97846E;
  377. }
  378. /* “Complete” = green pill + dark green text */
  379. #timeline li.is-complete a {
  380. background: #d1e7dd;
  381. color: #0f5132;
  382. }
  383. #timeline li.is-complete a:before {
  384. border-color: #d1e7dd;
  385. border-left-color: transparent;
  386. }
  387. #timeline li.is-complete a:after {
  388. border-left-color: #d1e7dd;
  389. }
  390. /* “Pending / Upcoming” greys */
  391. #timeline li.is-pending a {
  392. background: #e9ecef;
  393. color: #055160;
  394. /* same as original */
  395. }
  396. #timeline li.is-pending a:before {
  397. border-color: #e9ecef;
  398. border-left-color: transparent;
  399. }
  400. #timeline li.is-pending a:after {
  401. border-left-color: #e9ecef;
  402. }
  403. /* optional alias if you ever emit `is-upcoming` */
  404. #timeline li.is-upcoming a {
  405. background: #dee2e6;
  406. color: #495057;
  407. }
  408. #timeline li.is-upcoming a:before {
  409. border-color: #dee2e6;
  410. border-left-color: transparent;
  411. }
  412. #timeline li.is-upcoming a:after {
  413. border-left-color: #dee2e6;
  414. }
  415. /* Ensure state colours don’t change on hover */
  416. #timeline li.is-current a:hover,
  417. #timeline li.is-complete a:hover,
  418. #timeline li.is-pending a:hover,
  419. #timeline li.is-upcoming a:hover {
  420. background: inherit;
  421. color: inherit;
  422. }
  423. #timeline li.is-current a:hover:before,
  424. #timeline li.is-complete a:hover:before,
  425. #timeline li.is-pending a:hover:before,
  426. #timeline li.is-upcoming a:hover:before {
  427. border-color: inherit;
  428. border-left-color: transparent;
  429. }
  430. #timeline li.is-current a:hover:after,
  431. #timeline li.is-complete a:hover:after,
  432. #timeline li.is-pending a:hover:after,
  433. #timeline li.is-upcoming a:hover:after {
  434. border-left-color: currentColor;
  435. /* overridden below for exact bg match */
  436. }
  437. /* Keep triangle colour exactly the same as the pill bg */
  438. #timeline li.is-current a:hover:after {
  439. border-left-color: #97846E;
  440. }
  441. #timeline li.is-complete a:hover:after {
  442. border-left-color: #d1e7dd;
  443. }
  444. #timeline li.is-pending a:hover:after {
  445. border-left-color: #e9ecef;
  446. }
  447. #timeline li.is-upcoming a:hover:after {
  448. border-left-color: #dee2e6;
  449. }
  450. /* Dates row colours (xxl-only row in your markup) */
  451. .step-dates li.is-complete {
  452. color: #0f5132;
  453. }
  454. .step-dates li.is-current {
  455. color: #7c6a57;
  456. font-weight: 600;
  457. }
  458. .step-dates li.is-pending,
  459. .step-dates li.is-upcoming {
  460. color: #6c757d;
  461. }
  462. /* Stack rules you already added still apply */
  463. @media (max-width: 1399px) {
  464. #timeline {
  465. display: block;
  466. }
  467. #timeline li {
  468. flex: 0 0 100%;
  469. max-width: 100%;
  470. margin: .5rem 0;
  471. }
  472. #timeline li a {
  473. height: auto;
  474. line-height: 1.3;
  475. padding: .65rem .9rem;
  476. border-radius: .25rem;
  477. }
  478. #timeline li a:before,
  479. #timeline li a:after {
  480. content: none !important;
  481. border: 0 !important;
  482. }
  483. }
  484. </style>
  485. </head>
  486. <body>
  487. <!--
  488. <nav class="navbar bg-dark border-bottom border-body d-print-none" data-bs-theme="dark"><div class="container"><a class="navbar-brand text-white" href="#"><img src="../internal/images/blueprint-logo-light.png" width="30" height="24" class="d-inline-block align-text-top" alt="Modulos">
  489. Modulos Design
  490. </a></div></nav>
  491. -->
  492. <main class="container my-4">
  493. <div class="bg-white p-4 p-md-5 rounded-0 shadow-sm">
  494. <div class="row align-items-center page-header">
  495. <div class="col-12 col-md-6 text-start">
  496. <!-- CUSTOMER DETAILS HERE -->
  497. </div>
  498. <div class="col-12 col-md-6 text-end pt-2">
  499. <h3 class="fw-bold mb-1 text-dark">Development Application</h3>
  500. <h3 class="fw-bold mb-1 text-dark">Application No: <?= htmlspecialchars($app['reference']) ?> </h3>
  501. <h5 class="mb-0 text-muted">Started: <?= date("d M Y", strtotime($app['created_at'])) ?> </h5>
  502. </div>
  503. </div>
  504. <hr class="my-4">
  505. <div class="row my-4">
  506. <div class="col-12 align-self-center">
  507. <div class="steps"> <?php
  508. // Build a flexible steps array straight from DB rows (ordered by position)
  509. $steps = [];
  510. foreach ($stages as $row) {
  511. $steps[] = [
  512. 'title' => trim($row['title'] ?? '') ?: ('Stage ' . (string)($row['position'] + 1)),
  513. 'status' => in_array(strtolower($row['status'] ?? ''), ['complete','current','pending'], true)
  514. ? strtolower($row['status'])
  515. : 'pending',
  516. 'date' => $row['stage_date'] ?: ($row['updated_at'] ?: ($row['created_at'] ?? null)),
  517. ];
  518. }
  519. // Ensure we always have a “current”
  520. $hasCurrent = false;
  521. foreach ($steps as $s) { if (($s['status'] ?? '') === 'current') { $hasCurrent = true; break; } }
  522. if (!$hasCurrent && !empty($steps)) {
  523. $lastComplete = -1;
  524. foreach ($steps as $i => $s) if (($s['status'] ?? '') === 'complete') $lastComplete = $i;
  525. if ($lastComplete >= 0) $steps[$lastComplete]['status'] = 'current';
  526. else $steps[0]['status'] = 'current';
  527. }
  528. // formatter
  529. $fmtDate = function ($v) {
  530. $t = $v ? strtotime($v) : 0;
  531. return $t ? date('D d M y', $t) : '';
  532. };
  533. ?> <div class="timeline-wrap text-center my-4">
  534. <ul id="timeline" class="mb-0 w-100 "> <?php foreach ($steps as $s):
  535. $state = 'is-' . ($s['status'] ?? 'pending');
  536. $titleSafe = htmlspecialchars($s['title'], ENT_QUOTES, 'UTF-8');
  537. $dateText = $fmtDate($s['date']);
  538. $iconClass = stage_icon_for($s['title']);
  539. $isComplete = ($s['status'] === 'complete');
  540. $isCurrent = ($s['status'] === 'current');
  541. $prefix = (!$isComplete && !$isCurrent && $dateText) ? 'Due ' : '';
  542. $tooltip = $titleSafe . ($dateText ? ' — ' . $prefix . $dateText : '');
  543. ?>
  544. <li class="
  545. <?= $state ?>">
  546. <a href="#" title="
  547. <?= $tooltip ?>">
  548. <span class="bi
  549. <?= $iconClass ?>">
  550. </span> <?= $titleSafe ?> <?php if ($dateText): ?> <small class="d-block d-xxl-none opacity-75 ms-4"> <?= htmlspecialchars($prefix . $dateText, ENT_QUOTES, 'UTF-8') ?> </small> <?php endif; ?> </a>
  551. </li> <?php endforeach; ?> </ul>
  552. <ul class="step-dates d-none d-xxl-flex"> <?php foreach ($steps as $s):
  553. $state = 'is-' . ($s['status'] ?? 'pending');
  554. $dateText = $fmtDate($s['date']);
  555. $isComplete = ($s['status'] === 'complete');
  556. $isCurrent = ($s['status'] === 'current');
  557. $prefix = (!$isComplete && !$isCurrent && $dateText) ? 'Due ' : '';
  558. ?>
  559. <li class="
  560. <?= htmlspecialchars($state, ENT_QUOTES, 'UTF-8') ?>"> <?= $dateText ? htmlspecialchars($prefix . $dateText, ENT_QUOTES, 'UTF-8') : '&nbsp;' ?> </li> <?php endforeach; ?> </ul>
  561. </div>
  562. <div class="row px-5">
  563. <div class="col-12"> <?php if (!empty($decisionIso)): ?> <?php if ($isPaused): ?> <div class="alert alert-warning d-flex align-items-center" role="alert">
  564. <i class="bi bi-pause-circle me-2"></i>
  565. <div> Statutory clock paused by council request. <?php if ($pauseReason !== ''): ?> <span class="text-muted">Reason: <?= htmlspecialchars($pauseReason) ?> </span> <?php endif; ?> </div>
  566. </div>
  567. <!-- No ticking countdown shown while paused --> <?php else: ?> <div class="countdown" data-target-date="
  568. <?= htmlspecialchars($decisionIso) ?>">
  569. </div> <?php endif; ?> <?php endif; ?> </div>
  570. </div>
  571. <div class="row"> <?php if (empty($stages)): ?> <div class="col-12">
  572. <div class="alert alert-warning">This application has not started yet.</div>
  573. </div> <?php endif; ?> </div>
  574. <hr class="my-4">
  575. <div class="row">
  576. <div class="col-12 text-center">
  577. <h4>Timeline of Correspondence</h4>
  578. </div>
  579. </div>
  580. <div class="row py-3">
  581. <div class="col">
  582. <div class="timeline"> <?php
  583. $badgeMap = [
  584. 'email_incoming' => 'bi-envelope-arrow-up',
  585. 'email_outgoing' => 'bi-send-check',
  586. 'phone_incoming' => 'bi-telephone-inbound',
  587. 'phone_outgoing' => 'bi-telephone-outbound',
  588. 'note' => 'bi-journal-text'
  589. ];
  590. $fallbackByChannel = [
  591. 'email' => 'bi-envelope',
  592. 'phone' => 'bi-telephone',
  593. 'meeting' => 'bi-people',
  594. 'other' => 'bi-chat-dots'
  595. ];
  596. $typeLabel = ['incoming'=>'Incoming','outgoing'=>'Outgoing','note'=>'Note'];
  597. $chLabel = ['email'=>'Email','phone'=>'Phone','meeting'=>'Meeting','other'=>'Other'];
  598. foreach ($correspondence as $row):
  599. $id = (int)$row['id'];
  600. $typeVal = strtolower(trim($row['type'] ?? 'note'));
  601. $channelVal = strtolower(trim($row['channel'] ?? 'other'));
  602. $key = ($typeVal === 'note') ? 'note' : "{$channelVal}_{$typeVal}";
  603. $icon = $badgeMap[$key] ?? ($fallbackByChannel[$channelVal] ?? 'bi-journal-text');
  604. $when = (new DateTime($row['event_at'], new DateTimeZone('Australia/Hobart')))->format('d M Y, h:ia');
  605. $visBadge = $row['visibility']==='internal' ? '
  606. <span class="badge rounded-pill text-bg-secondary ms-2">Internal</span>' : '';
  607. $typeClass = 'type-'.preg_replace('/[^a-z]/','', $typeVal);
  608. $numFiles = $fileCounts[$id] ?? 0; // <- NEW
  609. $hasFiles = $numFiles > 0; // <- NEW
  610. ?> <div class="timeline-item
  611. <?= $row['pin'] ? 'pinned' : '' ?>">
  612. <div class="timeline-badge">
  613. <i class="bi
  614. <?= $icon ?>">
  615. </i>
  616. </div>
  617. <div class="timeline-panel
  618. <?= $typeClass ?>">
  619. <div class="timeline-heading d-flex justify-content-between align-items-start">
  620. <div>
  621. <h6 class="mb-1"> <?= $when ?> • <?= $typeLabel[$typeVal] ?? ucfirst($typeVal) ?> via <?= $chLabel[$channelVal] ?? ucfirst($channelVal) ?> <?= $visBadge ?> <?php if ($row['pin']): ?> <i class="bi bi-pin-angle-fill text-warning ms-1" title="Pinned"></i> <?php endif; ?> <?php if (!empty($filesByCorr[$id])): ?> <span class="ms-2 att-pop" role="button" tabindex="0" data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-placement="top" data-bs-custom-class="popover-attachments" data-content-id="att-popover-
  622. <?= $id ?>" title="Attachments (
  623. <?= (int)$numFiles ?>)">
  624. <i class="bi bi-paperclip"></i>
  625. </span> <?php endif; ?> </h6>
  626. <small class="text-muted"> <?= htmlspecialchars($row['subject'] ?: ucfirst($typeVal)) ?> <?= $row['author'] ? ' • by: '.htmlspecialchars($row['author']) : '' ?> </small>
  627. </div>
  628. </div>
  629. <div class="timeline-body mt-2 small"> <?= render_body_html($row['body']) ?> </div>
  630. </div>
  631. </div> <?php endforeach; ?> <?php if (empty($correspondence)): ?> <div class="text-muted">No correspondence recorded yet.</div> <?php endif; ?> </div>
  632. </div>
  633. </div>
  634. </div> <?php foreach ($filesByCorr as $cid => $files): ?> <div id="att-popover-
  635. <?= (int)$cid ?>" class="d-none"> <?php foreach ($files as $f): ?> <div class="py-1">
  636. <a href="
  637. <?= htmlspecialchars($f['file_url'], ENT_QUOTES) ?>" target="_blank" rel="noopener">
  638. <i class="bi bi-file-earmark-pdf"></i> <?= htmlspecialchars($f['original_name'], ENT_QUOTES) ?> </a>
  639. </div> <?php endforeach; ?> </div> <?php endforeach; ?>
  640. </main>
  641. <script>
  642. const countdownEls = document.querySelectorAll(".countdown")
  643. countdownEls.forEach(countdownEl => createCountdown(countdownEl))
  644. function createCountdown(countdownEl) {
  645. const target = new Date(countdownEl.dataset.targetDate);
  646. const parts = {
  647. days: {
  648. text: ["days", "day"],
  649. dots: 30
  650. },
  651. hours: {
  652. text: ["hours", "hour"],
  653. dots: 24
  654. },
  655. minutes: {
  656. text: ["minutes", "minute"],
  657. dots: 60
  658. },
  659. seconds: {
  660. text: ["seconds", "second"],
  661. dots: 60
  662. },
  663. }
  664. Object.entries(parts).forEach(([key, value]) => {
  665. const partEl = document.createElement("div");
  666. partEl.classList.add("part", key);
  667. partEl.style.setProperty("--dots", value.dots);
  668. value.element = partEl;
  669. const remainingEl = document.createElement("div");
  670. remainingEl.classList.add("remaining");
  671. remainingEl.innerHTML = `
  672. <span class="number"></span>
  673. <span class="text"></span>`
  674. partEl.append(remainingEl);
  675. for (let i = 0; i < value.dots; i++) {
  676. const dotContainerEl = document.createElement("div");
  677. dotContainerEl.style.setProperty("--dot-idx", i);
  678. dotContainerEl.classList.add("dot-container")
  679. const dotEl = document.createElement("div");
  680. dotEl.classList.add("dot")
  681. dotContainerEl.append(dotEl);
  682. partEl.append(dotContainerEl);
  683. }
  684. countdownEl.append(partEl);
  685. })
  686. getRemainingTime(target, parts)
  687. }
  688. function getRemainingTime(target, parts, first = true) {
  689. const now = new Date()
  690. if (first) console.log({
  691. target,
  692. now
  693. })
  694. const remaining = {}
  695. let seconds = Math.floor((target - (now)) / 1000);
  696. let minutes = Math.floor(seconds / 60);
  697. let hours = Math.floor(minutes / 60);
  698. let days = Math.floor(hours / 24);
  699. hours = hours - (days * 24);
  700. minutes = minutes - (days * 24 * 60) - (hours * 60);
  701. seconds = seconds - (days * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);
  702. Object.entries({
  703. days,
  704. hours,
  705. minutes,
  706. seconds
  707. }).forEach(([key, value]) => {
  708. const remaining = parts[key].element.querySelector(".number");
  709. const text = parts[key].element.querySelector(".text");
  710. remaining.innerText = value;
  711. text.innerText = parts[key].text[Number(value == 1)]
  712. const dots = parts[key].element.querySelectorAll(".dot")
  713. dots.forEach((dot, idx) => {
  714. dot.dataset.active = idx <= value;
  715. dot.dataset.lastactive = idx == value;
  716. })
  717. })
  718. if (now <= target) {
  719. window.requestAnimationFrame(() => {
  720. getRemainingTime(target, parts, false)
  721. });
  722. }
  723. }
  724. document.getElementById('tryParse')?.addEventListener('click', function(e) {
  725. e.preventDefault();
  726. const body = document.getElementById('corrBody').value || '';
  727. const subj = /(?:^|\n)Subject:\s*(.+)/i.exec(body);
  728. const from = /(?:^|\n)From:\s*(.+)/i.exec(body);
  729. const date = /(?:^|\n)Date:\s*(.+)/i.exec(body);
  730. if (subj) document.getElementById('corrSubject').value = subj[1].trim();
  731. if (from) document.getElementById('corrAuthor').value = from[1].trim();
  732. if (date) {
  733. const guess = new Date(date[1]);
  734. if (!isNaN(guess.getTime())) {
  735. // to local datetime-local string
  736. const pad = n => String(n).padStart(2, '0');
  737. const v = guess.getFullYear() + '-' + pad(guess.getMonth() + 1) + '-' + pad(guess.getDate()) + 'T' + pad(guess.getHours()) + ':' + pad(guess.getMinutes());
  738. const el = document.querySelector('input[name="event_at"]');
  739. if (el) el.value = v;
  740. }
  741. }
  742. });
  743. document.addEventListener('DOMContentLoaded', () => {
  744. document.querySelectorAll('[data-bs-toggle="popover"][data-content-id]').forEach(el => {
  745. const id = el.getAttribute('data-content-id');
  746. const tpl = document.getElementById(id);
  747. const content = tpl ? tpl.innerHTML : '';
  748. new bootstrap.Popover(el, {
  749. html: true,
  750. content,
  751. container: 'body',
  752. sanitize: true, // keep Bootstrap’s sanitizer on
  753. trigger: 'hover focus' // hover on desktop, tap/focus on mobile
  754. });
  755. });
  756. });
  757. </script>
  758. </body>
  759. </html>