generate_planning_report.php 16 KB

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