generate_planning_report.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php declare(strict_types=1);
  2. require_once __DIR__ . '/_bootstrap.php';
  3. ini_set('display_errors', '0');
  4. ini_set('log_errors', '1');
  5. error_reporting(E_ALL);
  6. /**
  7. * Planning Report Generator (MVP)
  8. * Input: JSON payload (see schema below)
  9. * Output: { ok: true, markdown: "...", html: "...", meta: {...} }
  10. *
  11. * Place at: /internal/classes/generate_planning_report.php
  12. * Test: curl -s -X POST -H "Content-Type: application/json" \
  13. * --data @sample.json http://localhost/internal/classes/generate_planning_report.php | jq
  14. */
  15. $corsEnv = getenv('CORS_ORIGINS') ?: 'https://tasplanning.report';
  16. $allowedOrigins = array_filter(array_map('trim', explode(',', $corsEnv)));
  17. $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
  18. if ($origin && in_array($origin, $allowedOrigins, true)) {
  19. header("Access-Control-Allow-Origin: $origin");
  20. header("Vary: Origin"); // prevent cache mixups
  21. }
  22. // If you need credentials/cookies later, also set:
  23. // header('Access-Control-Allow-Credentials: true');
  24. header('Access-Control-Allow-Methods: POST, OPTIONS');
  25. header('Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With');
  26. // Preflight short-circuit
  27. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
  28. http_response_code(204);
  29. exit; // stop here, no body required
  30. }
  31. header('Content-Type: application/json; charset=UTF-8');
  32. try {
  33. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  34. http_response_code(405);
  35. echo json_encode(['ok' => false, 'error' => 'Use POST with application/json']);
  36. exit;
  37. }
  38. // Reject non-JSON content types early — prevents json_decode silently
  39. // returning null on form-encoded or multipart bodies.
  40. $ct = $_SERVER['CONTENT_TYPE'] ?? '';
  41. if (strpos($ct, 'application/json') === false) {
  42. http_response_code(415);
  43. echo json_encode(['ok' => false, 'error' => 'Content-Type must be application/json']);
  44. exit;
  45. }
  46. $raw = file_get_contents('php://input') ?: '';
  47. $in = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
  48. // --------- Schema (minimum viable) ----------
  49. $d = [
  50. // site
  51. 'address' => trim((string)($in['address'] ?? '')),
  52. 'lat' => floatval($in['lat'] ?? 0),
  53. 'lng' => floatval($in['lng'] ?? 0),
  54. 'pid' => trim((string)($in['pid'] ?? '')),
  55. 'title_id' => trim((string)($in['title_id'] ?? '')),
  56. 'total_area' => $in['total_area'] ?? null, // e.g. {sqm_label:"1,652 m²", ha_label:"0.1652 ha"} or string
  57. 'area_sqm' => $in['area_sqm'] ?? '',
  58. 'area_ha' => $in['area_ha'] ?? '',
  59. 'tenure' => trim((string)($in['tenure'] ?? '')),
  60. 'lpi' => trim((string)($in['lpi'] ?? '')),
  61. 'list_guid' => trim((string)($in['list_guid'] ?? '')),
  62. 'locality' => trim((string)($in['locality'] ?? '')),
  63. 'council' => trim((string)($in['council'] ?? '')),
  64. 'planning_scheme' => trim((string)($in['planning_scheme'] ?? 'Tasmanian Planning Scheme')),
  65. 'planning_zones' => array_values(array_filter((array)($in['planning_zones'] ?? []))),
  66. 'planning_codes' => array_values(array_filter((array)($in['planning_codes'] ?? []))),
  67. // proposal
  68. 'use_class' => trim((string)($in['use_class'] ?? 'Educational and Occasional Care')),
  69. 'proposal_summary' => trim((string)($in['proposal_summary'] ?? '')), // 1–3 paras freeform
  70. 'operations' => (array)($in['operations'] ?? []), // ['hours','staff','children']
  71. 'parking' => (array)($in['parking'] ?? []), // ['cars','bikes','accessible','motorcycle']
  72. 'signage' => (array)($in['signage'] ?? []), // [{type,desc}, ...]
  73. 'consultants' => (array)($in['consultants'] ?? []), // ['TIA'=>'…','Acoustic'=>'…','Bushfire'=>'…']
  74. // overlays
  75. 'overlays' => (array)($in['overlays'] ?? []), // ['bushfire'=>bool, 'airport_noise'=>bool, ...]
  76. // assessments matrix (zone + codes)
  77. 'standards' => (array)($in['standards'] ?? []), // [{clause, standard, acceptable, relies_on_pc:[], notes}]
  78. // assets (optional)
  79. 'map_png' => (string)($in['map_png'] ?? ''), // data:image/png;base64,...
  80. 'appendices' => array_values(array_filter((array)($in['appendices'] ?? []))),
  81. // meta
  82. 'prepared_for' => trim((string)($in['prepared_for'] ?? '')),
  83. 'prepared_by' => trim((string)($in['prepared_by'] ?? 'Modulos Design')),
  84. 'author' => trim((string)($in['author'] ?? '')),
  85. 'job_number' => trim((string)($in['job_number'] ?? '')),
  86. 'version' => trim((string)($in['version'] ?? 'Draft')),
  87. 'prepared_date' => trim((string)($in['prepared_date'] ?? date('j F Y'))),
  88. ];
  89. // Minimal required fields
  90. foreach (['address','planning_scheme'] as $k) {
  91. if ($d[$k] === '' || $d[$k] === null) {
  92. throw new RuntimeException("Missing required field: {$k}");
  93. }
  94. }
  95. // Helpers -----------------------------------------------------------
  96. $join = fn(array $arr, string $sep=', ') => implode($sep, array_values(array_filter($arr, fn($x)=>$x!=='' && $x!==null)));
  97. $fmt_area = function($d) {
  98. if (is_array($d['total_area'] ?? null)) {
  99. return $d['total_area']['ha_label'] ?? $d['total_area']['sqm_label'] ?? '';
  100. }
  101. return $d['area_ha'] ?: $d['area_sqm'];
  102. };
  103. $md_table_row = fn(array $cols) => '| ' . implode(' | ', array_map(fn($c)=>trim((string)$c) ?: '–', $cols)) . ' |';
  104. $render_standards = function(array $rows) use ($md_table_row) {
  105. if (!$rows) return "_No specific standards provided in this draft._\n";
  106. $out = [];
  107. $out[] = $md_table_row(['Clause','Standard','AS','PC','Notes']);
  108. $out[] = $md_table_row(['---','---','---','---','---']);
  109. foreach ($rows as $r) {
  110. $out[] = $md_table_row([
  111. $r['clause'] ?? '',
  112. $r['standard'] ?? '',
  113. $r['acceptable'] ?? '',
  114. $r['relies_on_pc'] ? implode(', ', (array)$r['relies_on_pc']) : '',
  115. $r['notes'] ?? ''
  116. ]);
  117. }
  118. return implode("\n", $out)."\n";
  119. };
  120. // Markdown builder --------------------------------------------------
  121. $md = [];
  122. $md[] = '# Supporting Planning Report';
  123. $md[] = '';
  124. $md[] = "Prepared for: **" . ($d['prepared_for'] ?: '—') . "**";
  125. $md[] = "Prepared by: **" . ($d['prepared_by'] ?: '—') . "**" . ($d['author'] ? " ({$d['author']})" : "");
  126. $md[] = "Job No.: **" . ($d['job_number'] ?: '—') . "**";
  127. $md[] = "Version: **" . ($d['version'] ?: '—') . "**";
  128. $md[] = "Date: **" . ($d['prepared_date'] ?: '—') . "**";
  129. $md[] = '';
  130. $md[] = '> ' . $d['acknowledgement'];
  131. $md[] = '';
  132. // Permit overview
  133. $md[] = '## Permit overview';
  134. $md[] = '### Permit application details';
  135. $md[] = $md_table_row(['Applicant','Owner','Address','Title']);
  136. $md[] = $md_table_row(['---','---','---','---']);
  137. $md[] = $md_table_row([
  138. $d['prepared_for'] ?: '—',
  139. '—',
  140. $d['address'],
  141. ($d['title_id'] ?: '—')
  142. ]);
  143. $md[] = '';
  144. $md[] = '### Relevant Planning Provisions';
  145. $md[] = "- Applicable planning scheme: **{$d['planning_scheme']}**";
  146. if ($d['planning_zones']) $md[] = '- Zone(s): **' . $join($d['planning_zones']) . '**';
  147. if ($d['planning_codes']) $md[] = '- Codes: **' . $join($d['planning_codes']) . '**';
  148. $md[] = '';
  149. // Proposal
  150. $md[] = '## 1. Introduction';
  151. $md[] = '**Purpose of the report.** This report seeks planning approval for the proposed use and development described below and assesses the application against the relevant provisions of the Tasmanian Planning Scheme.';
  152. $md[] = '';
  153. $md[] = '## 2. Proposal';
  154. if ($d['proposal_summary']) $md[] = $d['proposal_summary'];
  155. $ops = [];
  156. if (!empty($d['operations']['hours'])) $ops[] = "**Hours:** {$d['operations']['hours']}";
  157. if (!empty($d['operations']['staff'])) $ops[] = "**Staff:** {$d['operations']['staff']}";
  158. if (!empty($d['operations']['children'])) $ops[] = "**Children capacity:** {$d['operations']['children']}";
  159. if ($ops) $md[] = implode(' \n', $ops);
  160. if ($d['parking']) {
  161. $pbits = [];
  162. if (isset($d['parking']['cars'])) $pbits[] = "{$d['parking']['cars']} car spaces";
  163. if (isset($d['parking']['accessible'])) $pbits[] = "{$d['parking']['accessible']} accessible";
  164. if (isset($d['parking']['bikes'])) $pbits[] = "{$d['parking']['bikes']} bicycle spaces";
  165. if (isset($d['parking']['motorcycle'])) $pbits[] = "{$d['parking']['motorcycle']} motorcycle spaces";
  166. if ($pbits) $md[] = '**Parking:** ' . implode(', ', $pbits) . '.';
  167. }
  168. if ($d['signage']) {
  169. $md[] = '**Signage:**';
  170. foreach ($d['signage'] as $s) {
  171. $md[] = "- " . trim(is_array($s) ? (($s['type'] ?? 'Sign') . ': ' . ($s['desc'] ?? '')) : (string)$s);
  172. }
  173. }
  174. if (!empty($d['map_png'])) {
  175. $md[] = '';
  176. $md[] = '![Site and surrounds map]('.$d['map_png'].')';
  177. $md[] = '_Figure: Site context (auto-captured from map)._';
  178. }
  179. $md[] = '';
  180. // Site
  181. $md[] = '## 3. Site description';
  182. $md[] = $md_table_row(['Property ID','Title ID','Locality','Area','Tenure','LIST GUID']);
  183. $md[] = $md_table_row(['---','---','---','---','---','---']);
  184. $md[] = $md_table_row([
  185. $d['pid'] ?: '—',
  186. $d['title_id'] ?: '—',
  187. $d['locality'] ?: '—',
  188. $fmt_area($d) ?: '—',
  189. $d['tenure'] ?: '—',
  190. $d['list_guid'] ?: '—'
  191. ]);
  192. $md[] = '';
  193. // Zoning
  194. $md[] = '## 4. Zoning assessment';
  195. $md[] = "**Zone:** " . ($d['planning_zones'] ? $join($d['planning_zones']) : '—');
  196. $md[] = "**Use class:** {$d['use_class']} (assessment against applicable use and development standards).";
  197. $md[] = '';
  198. // Standards matrix
  199. $md[] = '### 4.x Applicable standards (zone + codes overview)';
  200. $md[] = $render_standards($d['standards']);
  201. // Codes — notes (driven by the standards rows)
  202. $md[] = '## 5. Code assessment';
  203. if (in_array('Signs', $d['planning_codes'])) $md[] = '- **Signs Code** – see relevant rows above.';
  204. if (in_array('Parking and Sustainable Transport', $d['planning_codes'])) $md[] = '- **Parking and Sustainable Transport Code** – see relevant rows above.';
  205. if (in_array('Road and Railway Assets', $d['planning_codes'])) $md[] = '- **Road and Railway Assets Code** – see relevant rows above.';
  206. if (!empty($d['overlays']['bushfire'])) $md[] = '- **Bushfire-Prone Areas Code** – see relevant rows above.';
  207. if (!empty($d['overlays']['airport_noise'])) $md[] = '- **Safeguarding of Airports Code** – see relevant rows above.';
  208. $md[] = '';
  209. // Consultants
  210. if ($d['consultants']) {
  211. $md[] = '### Supporting technical reports';
  212. foreach ($d['consultants'] as $k => $v) {
  213. $md[] = "- **{$k}:** {$v}";
  214. }
  215. $md[] = '';
  216. }
  217. // Conclusion (quick tally)
  218. $t_as = 0; $t_pc = 0;
  219. foreach ($d['standards'] as $r) {
  220. if (!empty($r['acceptable'])) $t_as++;
  221. if (!empty($r['relies_on_pc'])) $t_pc++;
  222. }
  223. $md[] = '## 6. Conclusion';
  224. $md[] = "This application has been assessed against the Tasmanian Planning Scheme provisions relevant to the site and proposal. Based on the information provided and the supporting technical assessments, the proposal **complies with acceptable solutions for ~{$t_as} standards** and **relies on performance criteria for ~{$t_pc} standards**. Approval is therefore requested subject to any reasonable conditions.";
  225. $md[] = '';
  226. // Appendices (labels only)
  227. if ($d['appendices']) {
  228. $md[] = '## Appendices';
  229. foreach ($d['appendices'] as $i => $label) {
  230. $md[] = ($i+1) . ". " . trim((string)$label);
  231. }
  232. $md[] = '';
  233. }
  234. $markdown = implode("\n", $md);
  235. // Minimal Markdown → HTML
  236. $html = md_to_html_min($markdown);
  237. // Optional: save a .md copy (ensure directory exists & is writable)
  238. $SAVE_DIR = __DIR__ . '/../../reports';
  239. if (is_dir($SAVE_DIR) && is_writable($SAVE_DIR)) {
  240. $fname = sanitize_filename("Planning Report - {$d['address']} - " . date('Ymd_His')) . ".md";
  241. @file_put_contents($SAVE_DIR . '/' . $fname, $markdown);
  242. }
  243. echo json_encode([
  244. 'ok' => true,
  245. 'markdown' => $markdown,
  246. 'html' => $html,
  247. 'meta' => [
  248. 'address' => $d['address'],
  249. 'scheme' => $d['planning_scheme'],
  250. 'zones' => $d['planning_zones'],
  251. 'codes' => $d['planning_codes'],
  252. ],
  253. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  254. exit;
  255. } catch (Throwable $e) {
  256. http_response_code(400);
  257. echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
  258. exit;
  259. }
  260. /** -------- Helpers -------- */
  261. function sanitize_filename(string $s): string {
  262. $s = preg_replace('~[^\w\-. ]+~u', '', $s);
  263. $s = preg_replace('~\s+~', ' ', $s);
  264. return trim($s) ?: 'report';
  265. }
  266. function esc_html(string $s): string {
  267. return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  268. }
  269. function md_to_html_min(string $md): string {
  270. // Extremely small converter: headers, bold/italics, lists, images, tables, paragraphs.
  271. $h = esc_html($md);
  272. // Images ![alt](src)
  273. $h = preg_replace('~!\[([^\]]*)\]\(([^)]+)\)~', '<img alt="$1" src="$2" style="max-width:100%;height:auto;border-radius:8px;" />', $h);
  274. // Bold / italic
  275. $h = preg_replace('~\*\*([^*]+)\*\*~', '<strong>$1</strong>', $h);
  276. $h = preg_replace('~\*([^*]+)\*~', '<em>$1</em>', $h);
  277. // Headers
  278. foreach ([6,5,4,3,2,1] as $n) {
  279. $re = '~^' . str_repeat('#', $n) . '\s*(.+)$~m';
  280. $h = preg_replace($re, "<h{$n}>$1</h{$n}>", $h);
  281. }
  282. // Tables (GitHub-style)
  283. if (preg_match('~^\|.+\|$~m', $h)) {
  284. $lines = explode("\n", $h);
  285. $out = [];
  286. $inTable = false;
  287. foreach ($lines as $line) {
  288. if (preg_match('~^\|(.+)\|$~', $line)) {
  289. if (!$inTable) { $out[] = '<table class="table table-sm"><tbody>'; $inTable = true; }
  290. if (preg_match('~^\|\s*-+(\s*\|\s*-+)+\s*\|$~', $line)) continue; // separator
  291. $cells = array_map('trim', explode('|', trim($line, '|')));
  292. $out[] = '<tr>' . implode('', array_map(fn($c)=>'<td>'.esc_html($c ?: '–').'</td>', $cells)) . '</tr>';
  293. } else {
  294. if ($inTable) { $out[] = '</tbody></table>'; $inTable = false; }
  295. $out[] = $line;
  296. }
  297. }
  298. if ($inTable) $out[] = '</tbody></table>';
  299. $h = implode("\n", $out);
  300. }
  301. // Lists
  302. $h = preg_replace_callback('~(?:^|\n)([-*]\s.+(?:\n[-*]\s.+)*)~m', function($m){
  303. $items = preg_split('~\n~', trim($m[1]));
  304. $lis = '';
  305. foreach ($items as $li) {
  306. $txt = preg_replace('~^[-*]\s~', '', $li);
  307. $lis .= '<li>'. $txt .'</li>';
  308. }
  309. return "\n<ul>{$lis}</ul>";
  310. }, $h);
  311. // Line breaks " \n" → <br>
  312. $h = str_replace(" \n", "<br>\n", $h);
  313. // Paragraphs
  314. $parts = preg_split('~\n{2,}~', $h);
  315. foreach ($parts as &$p) {
  316. if (!preg_match('~^\s*<(h\d|ul|ol|table|img|blockquote)~', $p)) {
  317. $p = '<p>'.$p.'</p>';
  318. }
  319. }
  320. $h = implode("\n", $parts);
  321. return '<article class="report-body" style="max-width:900px;margin:0 auto;">'.$h.'</article>';
  322. }