-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3702 lines (3293 loc) · 157 KB
/
Copy pathapp.py
File metadata and controls
3702 lines (3293 loc) · 157 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, jsonify, Response, session, redirect, url_for
from flask_compress import Compress
import requests
import json
import csv
import io
import math
import re
import os
import sys
import subprocess
from pathlib import Path
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # dotenv not installed — env vars must be set manually
from datetime import datetime, timezone
from functools import wraps
app = Flask(__name__)
Compress(app) # gzip-compress all JSON/HTML responses automatically
# Secret key for session encryption — set FLASK_SECRET_KEY env var in Railway
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "vt-prop-dev-secret-change-in-prod")
from datetime import timedelta
# Session expires after 8 hours of inactivity.
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(hours=8)
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_SECURE"] = True
# ── Auth blueprint ────────────────────────────────────────────────────────────
from auth import auth_bp, init_db, db_fetchone, db_fetchall, db_execute, get_db, user_has_access, days_left_in_trial, _q, get_active_plans
app.register_blueprint(auth_bp)
init_db() # create users table if it doesn't exist
# ── Assessor links table ──────────────────────────────────────────────────────
def _init_assessor_links():
conn = get_db()
try:
cur = conn.cursor()
from auth import _using_postgres
if _using_postgres():
cur.execute("""
CREATE TABLE IF NOT EXISTS assessor_links (
town_name TEXT PRIMARY KEY,
url TEXT NOT NULL,
updated_at TEXT NOT NULL
)
""")
else:
cur.execute("""
CREATE TABLE IF NOT EXISTS assessor_links (
town_name TEXT PRIMARY KEY,
url TEXT NOT NULL,
updated_at TEXT NOT NULL
)
""")
conn.commit()
# Add url2 column if it doesn't exist yet
if _using_postgres():
cur.execute("ALTER TABLE assessor_links ADD COLUMN IF NOT EXISTS url2 TEXT;")
else:
try:
cur.execute("ALTER TABLE assessor_links ADD COLUMN url2 TEXT;")
except Exception:
pass # column already exists
conn.commit()
finally:
conn.close()
_init_assessor_links()
# ── Site content table (terms / privacy) ─────────────────────────────────────
def _init_site_content():
conn = get_db()
try:
cur = conn.cursor()
from auth import _using_postgres
if _using_postgres():
cur.execute("""
CREATE TABLE IF NOT EXISTS site_content (
key TEXT PRIMARY KEY,
content TEXT NOT NULL,
updated_at TIMESTAMP DEFAULT NOW()
)
""")
else:
cur.execute("""
CREATE TABLE IF NOT EXISTS site_content (
key TEXT PRIMARY KEY,
content TEXT NOT NULL,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
# Seed initial content from default content files if rows don't exist yet
for key, filename in [("terms", "templates/terms_default.html"), ("privacy", "templates/privacy_default.html")]:
row = None
if _using_postgres():
cur.execute("SELECT key FROM site_content WHERE key = %s", (key,))
else:
cur.execute("SELECT key FROM site_content WHERE key = ?", (key,))
row = cur.fetchone()
if row is None:
filepath = Path(__file__).parent / filename
if filepath.exists():
body_content = filepath.read_text(encoding="utf-8").strip()
if _using_postgres():
cur.execute(
"INSERT INTO site_content (key, content) VALUES (%s, %s) ON CONFLICT (key) DO NOTHING",
(key, body_content)
)
else:
cur.execute(
"INSERT INTO site_content (key, content) VALUES (?, ?) ON CONFLICT (key) DO NOTHING",
(key, body_content)
)
# Fix existing rows that were seeded with raw Jinja2 template tags
for key, filename in [("terms", "templates/terms_default.html"), ("privacy", "templates/privacy_default.html")]:
if _using_postgres():
cur.execute("SELECT content FROM site_content WHERE key = %s", (key,))
else:
cur.execute("SELECT content FROM site_content WHERE key = ?", (key,))
row = cur.fetchone()
if row and "{{ content" in (row["content"] if isinstance(row, dict) else row[0]):
filepath = Path(__file__).parent / filename
if filepath.exists():
body_content = filepath.read_text(encoding="utf-8").strip()
if _using_postgres():
cur.execute(
"UPDATE site_content SET content = %s WHERE key = %s",
(body_content, key)
)
else:
cur.execute(
"UPDATE site_content SET content = ? WHERE key = ?",
(body_content, key)
)
# Fix static "$19.95 per month" pricing in seeded terms content
if _using_postgres():
cur.execute("SELECT content FROM site_content WHERE key = %s", ("terms",))
else:
cur.execute("SELECT content FROM site_content WHERE key = ?", ("terms",))
row = cur.fetchone()
if row:
content = row["content"] if isinstance(row, dict) else row[0]
if "$19.95 per month" in content:
content = content.replace(
"at <strong>$19.95 per month</strong>",
"at the subscription rates listed above"
).replace(
"charged $19.95. Billing continues on a monthly basis on the same date each month unless you cancel.",
"charged at your selected plan rate. Billing continues on a recurring basis unless you cancel."
)
if _using_postgres():
cur.execute("UPDATE site_content SET content = %s WHERE key = %s", (content, "terms"))
else:
cur.execute("UPDATE site_content SET content = ? WHERE key = ?", (content, "terms"))
conn.commit()
finally:
conn.close()
_init_site_content()
# ── Geocoding runs table ──────────────────────────────────────────────────
def _init_geocoding_runs():
conn = get_db()
try:
cur = conn.cursor()
from auth import _using_postgres
if _using_postgres():
cur.execute("""
CREATE TABLE IF NOT EXISTS geocoding_runs (
id SERIAL PRIMARY KEY,
run_date TIMESTAMP DEFAULT NOW(),
date_from DATE NOT NULL,
records_found INTEGER DEFAULT 0,
records_added INTEGER DEFAULT 0,
status TEXT DEFAULT 'pending',
notes TEXT,
dry_run BOOLEAN DEFAULT FALSE
)
""")
else:
cur.execute("""
CREATE TABLE IF NOT EXISTS geocoding_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
date_from DATE NOT NULL,
records_found INTEGER DEFAULT 0,
records_added INTEGER DEFAULT 0,
status TEXT DEFAULT 'pending',
notes TEXT,
dry_run BOOLEAN DEFAULT 0
)
""")
conn.commit()
finally:
conn.close()
_init_geocoding_runs()
# ── Login required decorator ──────────────────────────────────────────────────
ADMIN_EMAIL_LOCAL = os.environ.get("ADMIN_EMAIL", "appraiservt@gmail.com").lower()
ADMIN_PASSWORD_SET = bool(os.environ.get("ADMIN_PASSWORD")) # True only when env var exists
def login_required(f):
@wraps(f)
def decorated(*args, **kwargs):
if "user_id" not in session:
return redirect(url_for("auth.login"))
# Admin bypass — only active when ADMIN_PASSWORD env var is set (local dev only)
if ADMIN_PASSWORD_SET and session.get("user_email", "").lower() == ADMIN_EMAIL_LOCAL:
return f(*args, **kwargs)
user = db_fetchone(_q("SELECT * FROM users WHERE id = ?"), (session["user_id"],))
if not user:
# Account deleted or session stale — go to login
session.clear()
return redirect(url_for("auth.login"))
# Session token check — prevents credential sharing
# If the token doesn't match, someone else logged in from another device
if session.get("session_token") and \
session["session_token"] != (user.get("session_token") or ""):
session.clear()
flash("Your account was signed in from another location. Please log in again.", "warning")
return redirect(url_for("auth.login"))
if not user_has_access(user):
# Trial expired or cancelled — go to subscribe
return redirect(url_for("auth.subscribe",
email=session.get("user_email", "")))
return f(*args, **kwargs)
return decorated
ARCGIS_URL = (
"https://services1.arcgis.com/"
"BkFxaEFNwHqX3tAw/arcgis/rest/services/"
"FS_VCGI_OPENDATA_Cadastral_PTTR_point_WM_v1_view/FeatureServer/0/query"
)
# -----------------------------
# Load Vermont code mappings
# -----------------------------
CODES_PATH = Path(__file__).with_name("vt_codes.json")
with CODES_PATH.open() as f:
VT_CODES = json.load(f)
COUNTY_CODE_TO_NAME = VT_CODES["counties"]
TOWN_TO_COUNTY = VT_CODES["town_to_county"]
SCHOOL_TO_TOWN = {int(k): v for k, v in VT_CODES["school_to_town"].items()}
SPAN_PREFIX_TO_TOWN = VT_CODES.get("span_prefix_to_town", {})
# Village/hamlet names filers write as propLocCty that are not official town names.
# Used to resolve centroid lookups and county derivation when propLocCty is a village.
VILLAGE_TO_TOWN = {
'BELLOWS FALLS': 'Rockingham',
'MORRISVILLE': 'Morristown',
'LYNDONVILLE': 'Lyndon',
'ISLAND POND': 'Brighton',
'PROCTORSVILLE': 'Cavendish',
'PERKINSVILLE': 'Weathersfield',
'NORTH SPRINGFIELD': 'Springfield',
'NORTH MONTPELIER': 'Calais',
'EAST MONTPELIER VILLAGE': 'East Montpelier',
'WEST BURKE': 'Burke',
'EAST BURKE': 'Burke',
'BARTON VILLAGE': 'Barton',
'ORLEANS VILLAGE': 'Barton',
'WEST PAWLET': 'Pawlet',
'NORTH BENNINGTON': 'Bennington',
'JACKSONVILLE': 'Whitingham',
'NORTH TROY': 'Troy',
'EAST HARDWICK': 'Hardwick',
'GREENSBORO BEND': 'Greensboro',
'CRAFTSBURY COMMON': 'Craftsbury',
'EAST CRAFTSBURY': 'Craftsbury',
'NORTH HYDE PARK': 'Hyde Park',
'JEFFERSONVILLE': 'Cambridge',
'WATERBURY CENTER': 'Waterbury',
'STOWE HOLLOW': 'Stowe',
'MOSCOW': 'Stowe',
'NORTH POMFRET': 'Pomfret',
'SOUTH POMFRET': 'Pomfret',
'TAFTSVILLE': 'Woodstock',
'QUECHEE': 'Hartford',
'WILDER': 'Hartford',
'WHITE RIVER JUNCTION': 'Hartford',
'ASCUTNEY': 'Weathersfield',
'BROWNSVILLE': 'West Windsor',
'NORTH HARTLAND': 'Hartland',
'NORTH THETFORD': 'Thetford',
'POST MILLS': 'Thetford',
'EAST THETFORD': 'Thetford',
'WELLS RIVER': 'Newbury',
'MARSHFIELD VILLAGE': 'Marshfield',
}
# Grand List Category lookup: numeric code → description text
GL_CATEGORY_LOOKUP = VT_CODES.get("grand_list_categories", {})
# Building type lookup: numeric code → description text
BUILDING_TYPE_LOOKUP = VT_CODES.get("building_types", {})
# Town centroid fallback: town name (UPPERCASE) → {lat, lon, county}
# Used when a record's ArcGIS coordinates fail the county bounds check.
TOWN_CENTROIDS = VT_CODES.get("town_centroids", {})
# Pre-geocoded approx records: OBJECTID (str) → {lat, lon}
# Built by geocode_approx.py, updated weekly.
# Records here get plotted as precise black dots instead of town centroid red circles.
_GEOCODED_APPROX_PATH = Path(__file__).with_name("geocoded_approx.json")
try:
with _GEOCODED_APPROX_PATH.open() as _f:
GEOCODED_APPROX = json.load(_f)
except (FileNotFoundError, json.JSONDecodeError):
GEOCODED_APPROX = {}
# Vermont state bounding box — outer limit for any coordinate check.
VT_LAT_MIN, VT_LAT_MAX = 42.7, 45.1
VT_LON_MIN, VT_LON_MAX = -73.5, -71.5
# Per-county bounding boxes keyed by zero-padded county code.
# Used to validate that a record’s ArcGIS coordinates land in the right county.
# The key insight: we check against the TRUSTED county (from schoolCode), not
# the self-reported countyCode on the form or the ArcGIS TOWNNAME field.
# A generous padding of ~0.15 degrees (~10 miles) handles records near county
# borders whose geocoded point lands just across the line.
COUNTY_BOUNDS = {
"01": (43.60, 44.55, -73.50, -72.60), # Addison
"02": (42.70, 43.50, -73.50, -72.70), # Bennington
"03": (44.10, 45.05, -72.55, -71.40), # Caledonia
"04": (44.10, 44.90, -73.50, -72.65), # Chittenden
"05": (44.20, 45.05, -72.35, -71.40), # Essex
"06": (44.45, 45.05, -73.40, -72.35), # Franklin
"07": (44.45, 45.05, -73.55, -72.95), # Grand Isle
"08": (44.25, 44.95, -73.15, -72.20), # Lamoille
"09": (43.60, 44.40, -72.90, -71.80), # Orange
"10": (44.40, 45.05, -72.75, -71.70), # Orleans
"11": (43.10, 44.10, -73.55, -72.35), # Rutland
"12": (43.85, 44.70, -73.10, -72.05), # Washington
"13": (42.65, 43.50, -73.05, -71.85), # Windham
"14": (43.10, 44.25, -72.95, -71.95), # Windsor
}
def coords_in_county(lat, lon, county_code):
"""Return True if (lat, lon) falls within the padded bbox of county_code."""
if lat is None or lon is None:
return False
code = str(county_code).strip().zfill(2)
bounds = COUNTY_BOUNDS.get(code)
if bounds is None:
return True # Unknown county — give it the benefit of the doubt
lat_min, lat_max, lon_min, lon_max = bounds
return lat_min <= lat <= lat_max and lon_min <= lon <= lon_max
def resolve_coordinates(raw_lat, raw_lon, trusted_town, object_id=None, match_method=None, prop_city_for_centroid=None, prop_loc_str=None):
"""Return (lat, lon, approx, is_centroid) for a record.
Uses MatchMthod as the primary signal for coordinate quality:
0. GEOCODED_APPROX lookup — manually/script geocoded coordinates
1. MatchMthod in _GOOD_MATCH_METHODS — reliable geocode, use as-is
2. MatchMthod in _APPROX_MATCH_METHODS — parcel centroid, approx but usable
3. MatchMthod = 'Unmatched' or null — fall back to town centroid
4. Sanity check: coords must be in Vermont
"""
# Tier 0: pre-geocoded lookup by OBJECTID
if object_id is not None:
entry = GEOCODED_APPROX.get(str(object_id))
if entry and entry.get("lat") and entry.get("lon"):
return entry["lat"], entry["lon"], False, False
mm = (match_method or "").strip().lower()
# Tier 1: good geocode — trust coordinates.
if mm in _GOOD_MATCH_METHODS:
if (raw_lat is not None and raw_lon is not None and
VT_LAT_MIN <= raw_lat <= VT_LAT_MAX and
VT_LON_MIN <= raw_lon <= VT_LON_MAX):
return raw_lat, raw_lon, False, False
# Good match method but coords out of VT — fall through to centroid
# Tier 2: parcel centroid match — approximate but usable coordinates
if mm in _APPROX_MATCH_METHODS:
if (raw_lat is not None and raw_lon is not None and
VT_LAT_MIN <= raw_lat <= VT_LAT_MAX and
VT_LON_MIN <= raw_lon <= VT_LON_MAX):
return raw_lat, raw_lon, True, False # approx, not centroid
# Coords out of VT — fall through to centroid
# Tier 3: unmatched or unknown method — town centroid fallback.
# Try in order:
# a) trusted_town from schoolCode (most reliable when schoolCode is correct)
# b) propLocCty direct match (filer-entered, sometimes a village name)
# c) propLocCty via VILLAGE_TO_TOWN mapping (resolves village to parent town)
# This prevents miscoded schoolCodes (e.g. 246->Winooski for a Wilmington property)
# from placing the centroid in the wrong county.
def _try_centroid(town_name):
key = (town_name or '').strip().upper()
if not key:
return None
c = TOWN_CENTROIDS.get(key)
if c:
return c
# Try village->town mapping
mapped = VILLAGE_TO_TOWN.get(key)
if mapped:
return TOWN_CENTROIDS.get(mapped.upper())
return None
# Try schoolCode-derived town first, but validate it's in the right county
centroid = _try_centroid(trusted_town)
prop_city_val = (prop_city_for_centroid or '').strip()
if centroid and prop_city_val:
# If we also have a propLocCty centroid and it's in a different county,
# prefer propLocCty — schoolCode is more likely to be miscoded than address
prop_centroid = _try_centroid(prop_city_val)
if prop_centroid and prop_centroid.get('county') != centroid.get('county'):
centroid = prop_centroid # propLocCty wins on county mismatch
elif not centroid:
centroid = _try_centroid(prop_city_val)
if centroid:
return centroid['lat'], centroid['lon'], True, True
return None, None, False, False
# MatchMthod values that indicate reliable geocoding
_GOOD_MATCH_METHODS = {
'property address (esite)',
'property address (composite)',
'span (esite)',
}
# MatchMthod values that indicate approximate (parcel centroid) geocoding
_APPROX_MATCH_METHODS = {
'span (parcel centroid)',
}
# 'unmatched' or anything else -> use town centroid fallback
def derive_trusted_location(attr):
"""Derive reliable town/county from TownSpan (primary) or schoolCode (fallback).
TownSpan is entered by the town clerk against the official grand list and
is the most reliable identifier. Its first 3 digits equal the town code.
schoolCode is the fallback when TownSpan is absent.
"""
raw_county = attr.get("countyCode")
school_code = attr.get("schoolCode")
town_code = attr.get("townCode")
span = attr.get("span")
town_span = attr.get("TownSpan") or attr.get("townSpan") or ""
prop_city = (
attr.get("propertyLocationCity")
or attr.get("propLocCty")
or attr.get("TownCityorTown")
)
trusted_town = None
trusted_county = None
# ── Step 1: SPAN prefix + schoolCode (most authoritative) ──────────────────
# Key = "{SPAN[:3]}-{schoolCode:03d}" e.g. '042-144' -> 'Barton'
# Handles school-choice towns where one town has multiple school codes.
sc_int = None
if school_code is not None:
try:
sc_int = int(float(str(school_code)))
except (TypeError, ValueError):
pass
if town_span and len(town_span.strip()) >= 3 and sc_int is not None:
span_key = f"{town_span.strip()[:3]}-{sc_int:03d}"
span_town = SPAN_PREFIX_TO_TOWN.get(span_key)
if span_town:
trusted_town = span_town
trusted_county = TOWN_TO_COUNTY.get(span_town)
# ── Step 2: schoolCode fallback (SPAN missing or not in table) ────────────
if trusted_town is None and sc_int is not None:
trusted_town = SCHOOL_TO_TOWN.get(sc_int)
if trusted_town:
trusted_county = TOWN_TO_COUNTY.get(trusted_town)
# ── Step 3: TOWNNAME confirmation ─────────────────────────────────────────
# Use TOWNNAME as canonical display name when it agrees with the county
# already derived from SPAN/schoolCode. Fixes display names like
# 'Barre City' vs 'Barre Town', 'East Montpelier' vs 'E Montpelier'.
town_name_field = (attr.get("TOWNNAME") or attr.get("townName") or "").strip()
if town_name_field:
tn_county = TOWN_TO_COUNTY.get(town_name_field)
if tn_county is not None:
if trusted_county is None:
trusted_town = town_name_field
trusted_county = tn_county
elif str(tn_county).zfill(2) == str(trusted_county).zfill(2):
trusted_town = town_name_field
# Use TOWNNAME as canonical town name when available.
# TOWNNAME contains official names like 'Barre City', 'Barre Town',
# 'East Montpelier', 'Essex Junction' that school codes sometimes
# fail to resolve correctly or produce inconsistent variants.
# Only override if TOWNNAME maps to the same county as schoolCode.
town_name_field = (attr.get("TOWNNAME") or attr.get("townName") or "").strip()
if town_name_field:
tn_county = TOWN_TO_COUNTY.get(town_name_field)
if tn_county is not None:
if trusted_county is None:
# No county yet — take TOWNNAME's county
trusted_town = town_name_field
trusted_county = tn_county
elif str(tn_county).zfill(2) == str(trusted_county).zfill(2):
# TOWNNAME agrees with schoolCode county — use canonical name
trusted_town = town_name_field
# Sanity check: if schoolCode resolves to a county but the actual geocoded
# coordinates land outside that county bbox, the schoolCode is miscoded.
# In that case, override with propLocCty-derived county if available.
if trusted_county is not None and prop_city:
lat_val = attr.get("Latitude") or attr.get("lat")
lon_val = attr.get("Longitude") or attr.get("lon")
try:
lat_f = float(lat_val) if lat_val is not None else None
lon_f = float(lon_val) if lon_val is not None else None
except (TypeError, ValueError):
lat_f = lon_f = None
if lat_f is not None and not coords_in_county(lat_f, lon_f, trusted_county):
# Coords are outside the schoolCode-derived county — try propLocCty
pc_key = prop_city.strip().upper()
pc_resolved = VILLAGE_TO_TOWN.get(pc_key, prop_city.strip().title())
pc_county = TOWN_TO_COUNTY.get(pc_resolved) or TOWN_TO_COUNTY.get(prop_city.strip().title())
if pc_county and coords_in_county(lat_f, lon_f, pc_county):
trusted_county = pc_county
trusted_town = pc_resolved
# Fallback 1: propLocCty town name lookup (with village -> town resolution)
if trusted_county is None:
prop_city = (prop_city or '').strip().title()
if prop_city:
# Try direct town name first, then village->town mapping
resolved = VILLAGE_TO_TOWN.get(prop_city.upper(), prop_city)
trusted_county = TOWN_TO_COUNTY.get(resolved) or TOWN_TO_COUNTY.get(prop_city)
if trusted_county:
trusted_town = trusted_town or resolved
# Fallback 2: self-reported countyCode (unreliable but better than nothing)
if trusted_county is None and raw_county is not None:
trusted_county = str(raw_county).zfill(2)
corrected = False
if raw_county is not None and trusted_county is not None:
corrected = str(raw_county).zfill(2) != str(trusted_county).zfill(2)
trusted_county_name = None
if trusted_county is not None:
trusted_county_name = COUNTY_CODE_TO_NAME.get(str(trusted_county).zfill(2))
return {
"rawCountyCode": raw_county,
"trustedCountyCode": trusted_county,
"trustedCountyName": trusted_county_name,
"trustedTown": trusted_town,
"schoolCode": school_code,
"townCode": town_code,
"span": span,
"displayCity": prop_city,
"correctedCounty": corrected,
}
def parse_filters(args):
"""Parse all filter query parameters into a dict."""
f = {}
# --- Location ---
f["counties"] = args.get("counties", "") # comma-separated codes
f["towns"] = args.get("towns", "") # comma-separated town names
# --- Date range ---
f["date_from"] = args.get("date_from", "") # ISO date string YYYY-MM-DD
f["date_to"] = args.get("date_to", "")
# --- Price range ---
f["price_low"] = args.get("price_low", "")
f["price_high"] = args.get("price_high", "")
# --- Land size range ---
f["land_low"] = args.get("land_low", "")
f["land_high"] = args.get("land_high", "")
f["no_land"] = args.get("no_land", "") # "1" = landSize=0 exact match
# --- Street address (contains) ---
f["street"] = args.get("street", "").strip()
# --- Interest type (multi, pipe-separated codes) ---
f["interest"] = args.get("interest", "") # e.g. "1|2"
# --- Building construction (multi, pipe-separated codes) ---
f["building"] = args.get("building", "") # e.g. "2|3"
# --- Seller use of property (multi, pipe-separated codes) ---
f["seller_use"] = args.get("seller_use", "")
# --- Buyer use of property (multi, pipe-separated codes) ---
f["buyer_use"] = args.get("buyer_use", "")
# --- PTT Exemption (multi, pipe-separated codes) ---
f["ptt_exemption"] = args.get("ptt_exemption", "")
# --- Grand List Category (multi, pipe-separated codes) ---
f["grand_list"] = args.get("grand_list", "")
# --- Seller name fields ---
f["seller_entity"] = args.get("seller_entity", "").strip()
f["seller_last"] = args.get("seller_last", "").strip()
f["seller_first"] = args.get("seller_first", "").strip()
# --- Buyer name fields ---
f["buyer_entity"] = args.get("buyer_entity", "").strip()
f["buyer_last"] = args.get("buyer_last", "").strip()
f["buyer_first"] = args.get("buyer_first", "").strip()
# --- SPAN ---
f["span"] = args.get("span", "").strip().replace("-", "")
# --- Boolean radio buttons ---
f["dev_prev_conv"] = args.get("dev_prev_conv", "") # "true"/"false"/""
f["buyer_adjoining"] = args.get("buyer_adjoining", "")
f["enrolled_current_use"] = args.get("enrolled_current_use", "") # "true"/"false"/""
f["current_use_continues"] = args.get("current_use_continues", "") # "true"/"false"/""
f["foreclosed"] = args.get("foreclosed", "") # "true"/"false"/""
f["rented_before"] = args.get("rented_before", "") # "true"/"false"/""
f["rented_after"] = args.get("rented_after", "") # "true"/"false"/""
return f
def build_where_clause(filters):
"""Build the ArcGIS WHERE clause from filters.
All filters are pushed to ArcGIS SQL so the server does the heavy
lifting across 218K+ records. Python post-filtering is only used for
the county-bounds coordinate validation (not a data filter).
"""
# Exclude $0 transfers (refinances, name changes, family transfers, etc.)
# unless user is searching by a specific SPAN or street address — then show all transfers.
# Base exclusions for map display:
# - Timeshares (intPrpType='05') go to the TS collector dot, never black dots
# - Unlanded mobile homes (TownGlCat='03' AND landSize=0) go to MH collector dot
clauses = [
# intPrpType=5 or 05 -> TS collector. Period. Nothing else.
"intPrpType NOT IN ('05','5')",
# Mobile home (blCn1/2/3=4 or 04) with no land -> MH collector.
# blCn2/blCn3 are often NULL — must guard with IS NOT NULL before IN
# or ArcGIS SQL treats NULL IN (...) unpredictably, excluding condos.
"NOT ((blCn1 IN ('4','04') OR (blCn2 IS NOT NULL AND blCn2 IN ('4','04')) OR (blCn3 IS NOT NULL AND blCn3 IN ('4','04'))) AND (landSize = 0 OR landSize IS NULL))",
]
if not filters.get('span') and not filters.get('street'):
clauses.append('ValPdOrTrn > 0')
# County filter
# ArcGIS has inconsistent countyCode padding — some records use '9', others '09'.
# Include both padded and unpadded forms to catch all records.
if filters["counties"]:
codes = filters["counties"].split(",")
all_codes = set()
for c in codes:
all_codes.add(c) # e.g. '09'
all_codes.add(str(int(c))) # e.g. '9'
codes_sql = ",".join([f"'{c}'" for c in sorted(all_codes)])
clauses.append(f"countyCode IN ({codes_sql})")
# Date range — ArcGIS requires DATE 'YYYY-MM-DD' format
if filters["date_from"]:
try:
datetime.strptime(filters["date_from"], "%Y-%m-%d")
clauses.append(f"closeDate >= DATE '{filters['date_from']}'")
except Exception:
pass
if filters["date_to"]:
try:
datetime.strptime(filters["date_to"], "%Y-%m-%d")
clauses.append(f"closeDate <= DATE '{filters['date_to']}'")
except Exception:
pass
# Price range — actual field name: ValPdOrTrn
if filters["price_low"]:
try:
clauses.append(f"ValPdOrTrn >= {float(filters['price_low'])}")
except Exception:
pass
if filters["price_high"]:
try:
clauses.append(f"ValPdOrTrn <= {float(filters['price_high'])}")
except Exception:
pass
# Land size range — actual field name: landSize
# no_land=1 means exact zero (sale did not involve land) — takes priority
# over land_low/land_high range since they are mutually exclusive.
if filters.get("no_land") == "1":
clauses.append("landSize = 0")
else:
if filters["land_low"]:
try:
clauses.append(f"landSize >= {float(filters['land_low'])}")
except Exception:
pass
if filters["land_high"]:
try:
clauses.append(f"landSize <= {float(filters['land_high'])}")
except Exception:
pass
# ----------------------------------------------------------------
# String field filters — ArcGIS stores these as zero-padded 2-digit
# strings ('01', '02', etc.). Codes from vt_codes.json are '1', '2'
# etc. We must zero-pad AND single-quote each value in the SQL.
# ----------------------------------------------------------------
def str_in_clause(field, raw_codes_str):
"""Build a quoted IN clause for a string field.
Includes both zero-padded ('05') and unpadded ('5') forms since
ArcGIS stores codes inconsistently across records.
"""
codes = [str(c).strip() for c in raw_codes_str.split('|') if c.strip()]
if not codes:
return None
# For each code include both the zero-padded and unpadded form
all_forms = set()
for c in codes:
padded = c.zfill(2)
unpadded = c.lstrip('0') or '0'
all_forms.add(padded)
all_forms.add(unpadded)
quoted = ','.join(f"'{v}'" for v in sorted(all_forms))
return f"{field} IN ({quoted})"
# Interest type — actual field name: intPrpType
if filters["interest"]:
clause = str_in_clause("intPrpType", filters["interest"])
if clause: clauses.append(clause)
# Building construction — check blCn1, blCn2, blCn3 (preparer can use any slot)
# Include both padded and unpadded forms for each code.
# Special codes: '4land' = MH with land, '4noland' = MH without land.
if filters["building"]:
raw_codes = [str(c).strip() for c in filters["building"].split('|') if c.strip()]
has_4land = '4land' in raw_codes
has_4noland = '4noland' in raw_codes
# Replace virtual MH codes with the real code '4' for the IN clause
normalised = []
for c in raw_codes:
if c in ('4land', '4noland'):
normalised.append('4')
else:
normalised.append(c)
all_forms = set()
for c in normalised:
all_forms.add(c.zfill(2))
all_forms.add(c.lstrip('0') or '0')
quoted = ','.join(f"'{v}'" for v in sorted(all_forms))
# When only ONE MH variant is selected, add a land-size sub-condition
# so that MH code 4 matches only the desired land/no-land subset.
mh_match = "(blCn1 IN ('4','04') OR (blCn2 IS NOT NULL AND blCn2 IN ('4','04')) OR (blCn3 IS NOT NULL AND blCn3 IN ('4','04')))"
if has_4land and not has_4noland:
# MH with land only — exclude MH rows that have no land
non_mh = f"(blCn1 IN ({quoted}) OR blCn2 IN ({quoted}) OR blCn3 IN ({quoted}))"
clauses.append(
f"(({non_mh}) AND NOT ({mh_match} AND (landSize = 0 OR landSize IS NULL)))"
)
elif has_4noland and not has_4land:
# MH without land only — exclude MH rows that have land
non_mh = f"(blCn1 IN ({quoted}) OR blCn2 IN ({quoted}) OR blCn3 IN ({quoted}))"
clauses.append(
f"(({non_mh}) AND NOT ({mh_match} AND landSize > 0))"
)
else:
# Both MH variants selected OR no MH at all — plain code match
clauses.append(
f"(blCn1 IN ({quoted}) OR blCn2 IN ({quoted}) OR blCn3 IN ({quoted}))"
)
# Seller use of property — actual field name: sUsePr
if filters["seller_use"]:
clause = str_in_clause("sUsePr", filters["seller_use"])
if clause: clauses.append(clause)
# Buyer use of property — actual field name: bUsePr
if filters["buyer_use"]:
clause = str_in_clause("bUsePr", filters["buyer_use"])
if clause: clauses.append(clause)
# PTT exemption — actual field name: prTxEx
if filters["ptt_exemption"]:
clause = str_in_clause("prTxEx", filters["ptt_exemption"])
if clause: clauses.append(clause)
# Grand list category — actual field name: TownGlCat
if filters["grand_list"]:
clause = str_in_clause("TownGlCat", filters["grand_list"])
if clause: clauses.append(clause)
# ---------------------------------------------------------------
# Name / SPAN / Street filters — pushed into SQL LIKE so ArcGIS
# searches all 218K+ records efficiently instead of relying on
# Python post-filtering across paginated statewide results.
# ---------------------------------------------------------------
# Helper: escape single-quotes in user input for SQL safety
def sql_like(val):
return val.replace("'", "''").upper()
seller_last = filters.get("seller_last", "").strip()
seller_first = filters.get("seller_first", "").strip()
seller_entity = filters.get("seller_entity", "").strip()
buyer_last = filters.get("buyer_last", "").strip()
buyer_first = filters.get("buyer_first", "").strip()
buyer_entity = filters.get("buyer_entity", "").strip()
has_seller_name = bool(seller_last or seller_first or seller_entity)
has_buyer_name = bool(buyer_last or buyer_first or buyer_entity)
if has_seller_name and has_buyer_name:
# Both sides filled — OR: match seller criteria OR buyer criteria
seller_parts = []
if seller_last: seller_parts.append(f"UPPER(sellLstNam) LIKE '%{sql_like(seller_last)}%'")
if seller_first: seller_parts.append(f"UPPER(sellFstNam) LIKE '%{sql_like(seller_first)}%'")
if seller_entity: seller_parts.append(f"UPPER(sellEntNam) LIKE '%{sql_like(seller_entity)}%'")
buyer_parts = []
if buyer_last: buyer_parts.append(f"UPPER(buyLstNam) LIKE '%{sql_like(buyer_last)}%'")
if buyer_first: buyer_parts.append(f"UPPER(buyFstNam) LIKE '%{sql_like(buyer_first)}%'")
if buyer_entity: buyer_parts.append(f"UPPER(buyEntNam) LIKE '%{sql_like(buyer_entity)}%'")
seller_sql = " AND ".join(seller_parts)
buyer_sql = " AND ".join(buyer_parts)
clauses.append(f"(({seller_sql}) OR ({buyer_sql}))")
elif has_seller_name:
if seller_last: clauses.append(f"UPPER(sellLstNam) LIKE '%{sql_like(seller_last)}%'")
if seller_first: clauses.append(f"UPPER(sellFstNam) LIKE '%{sql_like(seller_first)}%'")
if seller_entity: clauses.append(f"UPPER(sellEntNam) LIKE '%{sql_like(seller_entity)}%'")
elif has_buyer_name:
if buyer_last: clauses.append(f"UPPER(buyLstNam) LIKE '%{sql_like(buyer_last)}%'")
if buyer_first: clauses.append(f"UPPER(buyFstNam) LIKE '%{sql_like(buyer_first)}%'")
if buyer_entity: clauses.append(f"UPPER(buyEntNam) LIKE '%{sql_like(buyer_entity)}%'")
# Street address — pushed to SQL
if filters.get("street", "").strip():
clauses.append(f"UPPER(propLocStr) LIKE '%{sql_like(filters['street'].strip())}%'")
# SPAN — pushed to SQL (strip dashes before comparing)
span_val = filters.get("span", "").strip().replace("-", "")
if span_val:
clauses.append(f"CAST(span AS VARCHAR(20)) LIKE '%{sql_like(span_val)}%'")
# ---------------------------------------------------------------
# Town filter — use TOWNNAME for SQL IN() filter.
# TOWNNAME is the authoritative municipal name in ArcGIS and correctly
# handles school-choice towns where one town has multiple school codes
# (e.g. Barton has schoolCode 013 and 144 but TOWNNAME='Barton' for both).
# ---------------------------------------------------------------
if filters.get("towns", "").strip():
requested_towns = [t.strip() for t in filters["towns"].split(",") if t.strip()]
if requested_towns:
town_sql = ",".join(f"'{t.upper()}'" for t in requested_towns)
clauses.append(f"UPPER(TOWNNAME) IN ({town_sql})")
else:
# No towns specified — force zero results rather than
# returning unfiltered statewide data
clauses.append("1=0")
# ---------------------------------------------------------------
# Boolean / radio flag filters — all pushed to SQL
# Fields store uppercase strings 'TRUE' / 'FALSE'.
# ---------------------------------------------------------------
def bool_clause(field, value):
"""Return SQL clause for a boolean string field given 'true'/'false'."""
if value == "true":
return f"UPPER({field}) = 'TRUE'"
elif value == "false":
return f"UPPER({field}) = 'FALSE'"
return None
for flt_key, field in [
("dev_prev_conv", "devPrevCnv"),
("buyer_adjoining", "buyrAdjPrp"),
("enrolled_current_use", "enrCrntUse"),
("current_use_continues","cUseEnCont"),
("rented_before", "rntdBefore"),
("rented_after", "rntdAfter"),
]:
clause = bool_clause(field, filters.get(flt_key, ""))
if clause:
clauses.append(clause)
# Foreclosed — LGTEx code '6' means foreclosed sale
fc = filters.get("foreclosed", "")
if fc == "true":
clauses.append("LGTEx = '6'")
elif fc == "false":
clauses.append("LGTEx <> '6'")
return " AND ".join(clauses)
def apply_python_filters(record, filters):
"""All filters are now handled by ArcGIS SQL in build_where_clause.
This function is retained as a no-op stub so call sites don't need
to change. The only remaining Python-side logic is the county-bounds
coordinate validation in resolve_coordinates(), which is not a data
filter but a geocoding quality check.
"""
return True
# Only the ArcGIS fields actually used by app.py — omitting 41 unused fields
# cuts payload size by ~47% and speeds up ArcGIS response + JSON parsing.
# Slim map-tier fields — only what's needed to place dots, build badges,
# and show the hover popup preview (price, date, address, type, interest).
# Full PTT-172 detail is fetched on demand via /ptt172 when user clicks.
# Reduces /data payload from ~5.5 MB to ~600 KB for a typical county load.
_NEEDED_FIELDS = (
"OBJECTID,propLocStr,propLocCty,Latitude,Longitude,MatchMthod,"
"span,schoolCode,ValPdOrTrn,closeDate,"
"blCn1,blCn1Desc,blCn2,blCn3,TownGlCat,landSize,"
"intUDPdesc,intPrpType,"
"countyCode,TOWNNAME"
)
# Full field list — used only by /ptt172 and export endpoints where all
# fields are needed. Never used for the map /data endpoint.
_FULL_FIELDS = (
"LGTEx,LGTExDesc,Latitude,Longitude,MatchMthod,OBJECTID,PTT175Atch,"
"PrPrVlPdTr,RlPrVlPdTr,TOWNNAME,TownBkNum,TownCtyOrT,TownGlCat,"
"TownGlValu,TownGlYear,TownParcID,TownPgNum,TownSpan,TownSubdiv,"
"ValPdOrTrn,addBuyrNam,addSellNam,bCnDUs06,bUsePr,bUsePrDesc,bUsePrExpl,"
"blCn1,blCn1Desc,blCn2,blCn2Desc,blCn3,blCn3Desc,blCnUnts05,blConstr20,"
"buyEntNam,buyFstNam,buyLstNam,buyrAdjPrp,buyerStrt,buyerCity,buyerState,buyerZip,"
"cUseEnCont,closeDate,countyCode,devPrevCnv,enrCrntUse,"
"ex99Elig,ex99TxDue,famMem,famMemDesc,financing,"
"GenRtTxDue,intPrpType,intPrTypOt,intUDP,intUDPdesc,landSize,"
"prTxEx,prTxExDesc,prResSRVal,propLocCty,propLocStr,"
"rntdAfter,rntdBefore,schoolCode,"
"SellerAcq,sellAq,sellAqDesc,sellAqOthr,sellEntNam,sellFstNam,sellLstNam,"
"sellerStrt,sellerCity,sellerSt,sellerZip,"
"span,spRteTxDue,sUsePr,sUsePrDesc,sUsePrExpl,"
"tenantPrch,tlSpRteDue,townCode,TotlTaxDue,TownDteRec,"
"VlSbjGnRte"
)
def fetch_features(where, geometry_params=None, max_records=2000, fields=None):
"""Fetch features from ArcGIS. geometry_params is optional bbox dict."""
params = {
"where": where,
"outFields": fields or _NEEDED_FIELDS,
"f": "json",
"outSR": "4326",
"resultRecordCount": max_records,
}
if geometry_params:
params.update(geometry_params)
else:
params["inSR"] = "4326"
try:
# Use POST to avoid URL length limits with large WHERE clauses
# (e.g. OBJECTID IN (...) with 100+ IDs can exceed GET URL limits)
r = requests.post(ARCGIS_URL, data=params, timeout=30)
data = r.json()
if data.get("error"):
app.logger.warning(f"ArcGIS error in fetch_features: {data['error']}")
return []
return data.get("features", [])
except Exception as e:
app.logger.error(f"fetch_features failed: {e}")
return []
def fetch_all_features(where, geometry_params=None, fields=None):
"""
Page through ArcGIS results to get ALL matching records.
Optional geometry_params adds a bbox filter to constrain the result set
(e.g. for county-filtered map views). Without a bbox this fetches statewide.
Uses resultOffset pagination.
"""
all_features = []
offset = 0
page_size = 2000
while True:
params = {
"where": where,
"outFields": fields or _NEEDED_FIELDS,