brighton.rb 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. # Brighton Council — Advertised Development Applications (site page, not PlanBuild)
  2. require "date"
  3. require "nokogiri"
  4. require "cgi"
  5. require "fileutils"
  6. require_relative "../lib/http"
  7. require_relative "../lib/db"
  8. require_relative "../lib/util"
  9. require_relative "../lib/geocode"
  10. require_relative "../lib/enrich"
  11. TABLE = ENV.fetch("TABLE_NAME") # run_all.sh sets this from filename: da_brighton
  12. URL = "https://www.brighton.tas.gov.au/planning/advertised-development-applications/"
  13. DOWNLOAD_ATTACHMENTS = ENV["DOWNLOAD_ATTACHMENTS"] == "1"
  14. DOWNLOAD_DIR = ENV["DOWNLOAD_DIR"] || "/app/downloads"
  15. DB.ensure_table!(TABLE)
  16. # --- helpers ---------------------------------------------------------------
  17. # DA/APP refs like “DA2025-130”, “DA 2024/174”, etc → “DA YYYY / NNN…”
  18. REF_RX = %r{
  19. \b(?:DA|APP|APPLICATION)\s*
  20. (20\d{2})\s*[/\-]?\s*
  21. ([A-Za-z0-9\-_.]{2,})\b
  22. }ix
  23. def extract_ref_from(str)
  24. s = CGI.unescape(str.to_s)
  25. if (m = s.match(REF_RX))
  26. return "DA #{m[1]} / #{m[2]}"
  27. end
  28. # Compact like DA20250123
  29. if (m = s.match(/\bDA(20\d{2})(\d{3,})\b/i))
  30. return "DA #{m[1]} / #{m[2]}"
  31. end
  32. nil
  33. end
  34. def abs_url(base, href)
  35. return "" if href.to_s.strip.empty?
  36. URI.join(base, href).to_s
  37. rescue URI::InvalidURIError
  38. href.to_s
  39. end
  40. def safe_name(s) = s.to_s.gsub(/[^\w\-.]+/, "_")
  41. def strip_ordinals(s)
  42. s.to_s.gsub(/\b(\d{1,2})(st|nd|rd|th)\b/i, '\1')
  43. end
  44. def parse_close_date(s)
  45. Util.parse_aus_date(strip_ordinals(s.to_s))
  46. end
  47. def download_pdf(url, council_reference)
  48. return nil unless DOWNLOAD_ATTACHMENTS && !url.to_s.strip.empty?
  49. folder = File.join(DOWNLOAD_DIR, "brighton", safe_name(council_reference))
  50. FileUtils.mkdir_p(folder)
  51. begin
  52. res = Http.get_response(url) rescue Http.get(url)
  53. body = res.respond_to?(:body) ? res.body : res.to_s
  54. fname = safe_name(File.basename(URI.parse(url).path))
  55. fname += ".pdf" unless fname.downcase.end_with?(".pdf")
  56. path = File.join(folder, fname)
  57. File.binwrite(path, body)
  58. puts "Saved PDF #{path}"
  59. "/downloads/brighton/#{safe_name(council_reference)}/#{fname}"
  60. rescue StandardError => e
  61. warn "PDF download failed for #{url}: #{e.class} #{e.message}"
  62. nil
  63. end
  64. end
  65. # --- scrape ---------------------------------------------------------------
  66. html = Http.get(URL)
  67. doc = Nokogiri::HTML(html)
  68. # Find the advertised table by headers
  69. table = doc.css("table").find do |t|
  70. heads = t.css("thead th").map { |th| th.text.strip.downcase }
  71. heads.any? &&
  72. heads.any? { |h| h.include?("description") } &&
  73. heads.any? { |h| h.include?("address") } &&
  74. heads.any? { |h| h.include?("closing") || h.include?("closing date") } &&
  75. heads.any? { |h| h.include?("pdf") }
  76. end
  77. unless table
  78. puts "No advertised table found on #{URL}"
  79. exit 0
  80. end
  81. # Column indexes by header text (fallback to 0..3 if needed)
  82. heads = table.css("thead th").map { |th| th.text.strip.downcase }
  83. i_desc = heads.index { |h| h.include?("description") } || 0
  84. i_addr = heads.index { |h| h.include?("address") } || 1
  85. i_close= heads.index { |h| h.include?("closing") } || 2
  86. i_pdf = heads.index { |h| h.include?("pdf") } || 3
  87. rows = table.css("tbody tr")
  88. puts "Found #{rows.length} row(s) for #{TABLE}"
  89. saved = 0
  90. today = Date.today
  91. rows.each do |tr|
  92. tds = tr.css("td")
  93. next if tds.empty?
  94. description = tds[i_desc]&.text&.strip.to_s
  95. address = tds[i_addr]&.text&.strip.to_s
  96. close_raw = tds[i_close]&.text&.strip.to_s
  97. on_notice_to = parse_close_date(close_raw)
  98. date_received = on_notice_to && (on_notice_to - 14)
  99. # one or more PDF links
  100. pdf_links = tds[i_pdf]&.css('a[href]')&.map { |a| abs_url(URL, a["href"].to_s) } || []
  101. document_url = pdf_links.first.to_s
  102. # reference from link text or file name
  103. ref_texts = tds[i_pdf]&.css('a')&.map { |a| a.text.to_s } || []
  104. council_reference =
  105. ref_texts.map { |tx| extract_ref_from(tx) }.compact.first ||
  106. pdf_links.map { |u| extract_ref_from(File.basename(u)) }.compact.first
  107. # minimal keys
  108. next if address.empty? || council_reference.nil?
  109. DB.upsert(TABLE, {
  110. description: description.empty? ? "Development Application" : description,
  111. date_received: date_received,
  112. date_received_raw: today.strftime("%Y-%m-%d"),
  113. on_notice_to: on_notice_to, # store close date in DATE column
  114. on_notice_to_raw: strip_ordinals(close_raw),
  115. address: address,
  116. council_reference: council_reference,
  117. applicant: "",
  118. owner: ""
  119. })
  120. enrich_after_upsert!(
  121. table: TABLE,
  122. council_reference: council_reference,
  123. address: address
  124. )
  125. # remote URL
  126. begin
  127. upd = DB.client.prepare("UPDATE `#{DB.client.escape(TABLE)}` SET document_url = ? WHERE council_reference = ? AND address = ?")
  128. upd.execute(document_url, council_reference, address)
  129. rescue StandardError => e
  130. warn "document_url update skipped for #{council_reference}: #{e.class} #{e.message}"
  131. end
  132. # local copy
  133. local_doc_url = download_pdf(document_url, council_reference)
  134. if local_doc_url
  135. begin
  136. upd2 = DB.client.prepare("UPDATE `#{DB.client.escape(TABLE)}` SET local_document_url = ? WHERE council_reference = ? AND address = ?")
  137. upd2.execute(local_doc_url, council_reference, address)
  138. rescue StandardError => e
  139. warn "local_document_url update skipped for #{council_reference}: #{e.class} #{e.message}"
  140. end
  141. end
  142. puts "Upserted #{council_reference} -> #{address} (doc: #{document_url.empty? ? 0 : 1}, saved: #{local_doc_url ? 1 : 0})"
  143. saved += 1
  144. end
  145. puts "Done #{TABLE}. Saved #{saved} item(s)."