-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodels.py
More file actions
1705 lines (1509 loc) · 73.3 KB
/
Copy pathmodels.py
File metadata and controls
1705 lines (1509 loc) · 73.3 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 datetime import datetime, timezone
import json
from app import db
from services import owner_review
from services.advertiser import read_verdict as advertiser_verdict
from services.dossier import read_dossier
from services.listing_verification import read_verdict as listing_verdict
from services.search_subscription_identity import SEARCH_KEY_LENGTH
from sqlalchemy import CheckConstraint, func
from sqlalchemy.types import JSON
def utcnow():
return datetime.now(timezone.utc)
def investment_rating_badge_class(rating):
"""Bootstrap badge class for an AI investment rating.
Shared by `Property` and `Land`: both render the same "Inv. Metr." column
on the one listing page, and two copies of this mapping would eventually
colour the same rating differently depending on which table a row is in.
"""
text = (rating or "").upper()
if not text:
return None
if "EXCELLENT" in text or text == "HIGH":
return "bg-success"
if "GOOD" in text:
return "bg-primary"
if "MODERATE" in text or "MEDIUM" in text:
return "bg-warning text-dark"
if "BELOW" in text or "POOR" in text or "LOW" in text:
return "bg-danger"
return "bg-secondary"
class SearchProfile(db.Model):
"""Represents a saved search / client profile.
Each profile can have its own classification rules, travel targets, and UI/scoring config.
"""
__tablename__ = "search_profiles"
__table_args__ = (
db.Index("ix_search_profiles_name", "name"),
db.Index("ix_search_profiles_is_active", "is_active"),
db.Index("ix_search_profiles_is_default", "is_default"),
db.Index(
"ux_search_profiles_source_search_key", "source_search_key", unique=True
),
# Dropping the UNIQUE on `name` (migration 013) also removed what used
# to protect the check-then-insert in get_or_create_profile_by_name()
# and get_default_profile() from two overlapping ingestions. Identified
# subscriptions may share a label; unidentified ones may not, which
# restores exactly the old invariant without blocking the new case.
db.Index(
"ux_search_profiles_name_without_key",
"name",
unique=True,
postgresql_where=db.text("source_search_key IS NULL"),
sqlite_where=db.text("source_search_key IS NULL"),
),
# The catch-all must not be anybody's saved search. It receives every
# email that carries no search URL and matches no rule, so a default
# profile holding a search key would quietly make one subscription the
# recipient of all unrouted mail.
#
# Enforced here rather than in each reader on purpose: `is_default` is
# written from the profile editor, the create form, the merge and
# `get_default_profile()`, and five separate read-side filters were
# needed before this constraint existed. A route written next year
# cannot get around it.
CheckConstraint(
"source_search_key IS NULL OR is_default IS NOT TRUE",
name="ck_search_profiles_default_has_no_search_key",
),
# The catch-all cannot be hidden either (migration 028, #533): it
# receives every email that matches nothing else, so a hidden
# catch-all takes listings off the page as they arrive.
# `set_profile_hidden` and `edit_profile` refuse it first; this is
# what refuses it for the writers that never reach a route --
# curation SQL through `docker exec` is a supported workflow. The
# hiding half of 025's `ck_search_profiles_catch_all_never_routes`,
# on the same shape: `IS NOT TRUE` on both sides, because a NULL
# `is_default` is nobody's catch-all.
CheckConstraint(
"is_hidden IS NOT TRUE OR is_default IS NOT TRUE",
name="ck_search_profiles_catch_all_never_hidden",
),
)
id = db.Column(db.Integer, primary_key=True)
# Deliberately NOT unique (migration 013 drops the constraint): two saved
# searches may carry the same human label with a different `shape`, and
# before #102 that was impossible to represent.
name = db.Column(db.String(120), nullable=False)
description = db.Column(db.Text)
is_active = db.Column(db.Boolean, default=True)
is_default = db.Column(db.Boolean, default=False)
# Taken off the screen by the owner (2026-08-17), which is not the same
# question as `is_active`. An inactive subscription is *archived*: it is
# still offered, under `Archive`, because a saved search that stopped
# still holds listings worth reaching. A hidden one is not offered at all
# -- not as a chip, not in the menu, not in the archive -- and its
# listings are out of `profile_id=all` too, so the page it is hidden from
# does not show its rows either.
#
# It says nothing about ingestion: a hidden subscription keeps receiving
# its own alert emails, keeps its `email_matchers`, and keeps every
# listing it already holds. See services/search_profile_service.py for
# the one clause every surface reads. Never TRUE on the catch-all: the
# CHECK in `__table_args__` refuses the pair from either side.
is_hidden = db.Column(
db.Boolean, nullable=False, default=False, server_default=db.text("FALSE")
)
# Saved-search identity (#102). The key is the fingerprint of the search
# URL the alert email carries -- see services/search_subscription_identity
# -- and is what actually identifies a subscription; the name is a label.
# NULL until an email for this subscription arrives: nothing is
# backfilled, because no stored row records which search it came from.
source_search_key = db.Column(db.String(SEARCH_KEY_LENGTH))
# Diagnostics only: the last search URL seen for this profile. Never
# unique -- cosmetic variants of one link differ here but share the key.
source_search_url = db.Column(db.Text)
# Machine-readable "the ingester invented this label", so relabelling can
# never touch a profile the owner named. Existing rows stay False: the
# only evidence for them is a description string, which is exactly the
# signal #102 refuses to trust.
is_auto_created = db.Column(
db.Boolean, nullable=False, default=False, server_default=db.text("FALSE")
)
# Email routing for ingestion: list of regex patterns (configurable).
email_matchers = db.Column(JSON) # [{"pattern": "...", "priority": 10}, ...]
# This subscription's listings live on ANOTHER subscription (migration
# 025). The stub keeps its #102 saved-search identity; its rows land on
# the target — enforced by a BEFORE trigger on `properties` in
# PostgreSQL, so no writer (ORM, curation SQL, COPY) can land a row on a
# routed stub. Exactly one hop; `route_profile()` in
# services/search_profile_service.py is the one writer and refuses
# chains in both directions, self-routes and the catch-all. On SQLite
# (the test suite) only the Python boundary applies; the PostgreSQL
# trigger is pinned by tests/test_postgres_migrations.py.
routed_to = db.Column(db.Integer, db.ForeignKey("search_profiles.id"))
# On the TARGET: a profile auto-created by ingestion whose name matches
# this regex is born routed here and hidden — what keeps each of the six
# Galicia alerts from putting a chip back on screen at its first email.
auto_route_from_pattern = db.Column(db.String(120))
# The owner's app-side requirements the portals cannot encode, e.g.
# {"min_house_m2": 150, "min_plot_m2": 700}. Read by
# services/subscription_criteria.py; NULL means no criteria.
criteria = db.Column(JSON)
# Per-profile configuration (all optional; fall back to global defaults).
classification_rules = db.Column(
JSON
) # [{"category": "...", "subtype": "...", "pattern": "...", "priority": 50}, ...]
travel_targets = db.Column(
JSON
) # list of targets (schema in SettingsService/SearchProfileService)
ui_config = db.Column(JSON) # which columns/sections to show
scoring_config = db.Column(JSON) # future: per-profile scoring weights, etc.
ai_config = db.Column(
JSON
) # optional AI prompt/context overrides (e.g., market_context)
created_at = db.Column(db.DateTime, default=utcnow, nullable=False)
updated_at = db.Column(db.DateTime, default=utcnow, onupdate=utcnow, nullable=False)
def __repr__(self):
return f"<SearchProfile {self.id} {self.name}>"
class Property(db.Model):
"""Universal property model (venta-first, Spain-wide).
Introduced alongside the legacy Land model to enable an incremental migration.
"""
__tablename__ = "properties"
__table_args__ = (
db.Index("ix_properties_idealista_property_id", "idealista_property_id"),
db.Index("ix_properties_search_profile_id", "search_profile_id"),
db.Index("ix_properties_property_category", "property_category"),
db.Index("ix_properties_property_subtype", "property_subtype"),
db.Index("ix_properties_municipality", "municipality"),
db.Index("ix_properties_listing_status", "listing_status"),
db.Index("ix_properties_is_favorite", "is_favorite"),
db.Index("ix_properties_created_at", "created_at"),
db.Index("ix_properties_score_total", "score_total"),
db.Index("ix_properties_score_investment", "score_investment"),
db.Index("ix_properties_score_lifestyle", "score_lifestyle"),
db.Index("ix_properties_owner_verdict", "owner_verdict"),
db.Index("ix_properties_next_action_due_on", "next_action_due_on"),
db.Index("ix_properties_cadastral_reference", "cadastral_reference"),
# Data integrity constraints
CheckConstraint(
"price IS NULL OR price >= 0", name="ck_properties_price_non_negative"
),
CheckConstraint(
"area IS NULL OR area >= 0", name="ck_properties_area_non_negative"
),
CheckConstraint(
"location_lat IS NULL OR (location_lat >= -90 AND location_lat <= 90)",
name="ck_properties_lat_range",
),
CheckConstraint(
"location_lon IS NULL OR (location_lon >= -180 AND location_lon <= 180)",
name="ck_properties_lon_range",
),
CheckConstraint(
"score_total IS NULL OR (score_total >= 0 AND score_total <= 100)",
name="ck_properties_score_total_range",
),
CheckConstraint(
"score_investment IS NULL OR (score_investment >= 0 AND score_investment <= 100)",
name="ck_properties_score_investment_range",
),
CheckConstraint(
"score_lifestyle IS NULL OR (score_lifestyle >= 0 AND score_lifestyle <= 100)",
name="ck_properties_score_lifestyle_range",
),
CheckConstraint(
"listing_status IN ('active', 'removed', 'sold', 'unknown')",
name="ck_properties_listing_status_enum",
),
# The two review CHECKs -- `ck_properties_owner_verdict_enum` and
# `ck_properties_due_needs_action` -- live in migration 021 and
# deliberately NOT here, which is migration 015's precedent for the
# same situation. `tests/test_deployment_bootstrap.py` rebuilds the
# pre-ledger schema by running `create_all()` and dropping what later
# migrations added, and SQLite refuses to drop a column any CHECK
# mentions -- so declaring them on the model makes that baseline
# impossible to construct. They are exercised where they matter, on a
# real server, by `tests/test_postgres_migrations.py`; the reading in
# `services/owner_review.py` refuses an unknown verdict on every
# engine, towards `undecided` rather than towards a decision nobody
# made.
)
id = db.Column(db.Integer, primary_key=True)
source_email_id = db.Column(db.String(255), unique=True, nullable=False)
# Stable Idealista listing id extracted from URL (/inmueble/<id>/). Used for dedup/updates.
idealista_property_id = db.Column(db.BigInteger, nullable=True)
email_subject = db.Column(db.Text)
email_sender = db.Column(db.String(255))
search_profile_id = db.Column(
db.Integer,
db.ForeignKey("search_profiles.id", ondelete="SET NULL"),
nullable=True,
)
search_profile = db.relationship(
"SearchProfile", backref=db.backref("properties", lazy="dynamic")
)
title = db.Column(db.Text)
url = db.Column(db.Text)
# Deal & type classification (config-driven; no hard constraints here by design).
deal_type = db.Column(
db.String(16), default="sale"
) # 'sale' | 'rent' (rent not used initially)
property_category = db.Column(
db.String(32)
) # e.g. 'housing', 'land', 'garage', 'commercial', 'building'
property_subtype = db.Column(
db.String(64)
) # e.g. 'apartment', 'house', 'penthouse', 'plot', ...
price = db.Column(db.Numeric(10, 2))
currency = db.Column(db.String(3), default="EUR")
area = db.Column(db.Numeric(10, 2))
area_type = db.Column(
db.String(16), default="unknown"
) # 'built' | 'plot' | 'unknown'
municipality = db.Column(db.String(255))
location_lat = db.Column(db.Numeric(10, 7))
location_lon = db.Column(db.Numeric(10, 7))
location_accuracy = db.Column(
db.String(20), default="unknown"
) # 'precise', 'approximate', 'unknown'
description = db.Column(db.Text)
# Flexible JSON fields for extracted + enriched data.
attributes = db.Column(JSON) # rooms, bathrooms, floor, etc.
property_details = db.Column(
JSON
) # Raw/detail blocks (kept for compatibility patterns)
enrichment = db.Column(JSON) # Google/OSM derived info
travel = db.Column(JSON) # Dynamic travel times/distances per configured targets
scoring = db.Column(JSON) # Full scoring breakdown (per profile)
ai_analysis = db.Column(JSON)
enhanced_description = db.Column(JSON)
score_total = db.Column(db.Numeric(5, 2))
score_investment = db.Column(db.Numeric(5, 2))
score_lifestyle = db.Column(db.Numeric(5, 2))
# Price history (generic)
previous_price = db.Column(db.Numeric(10, 2))
price_change_amount = db.Column(db.Numeric(10, 2))
price_change_percentage = db.Column(db.Numeric(5, 2))
price_changed_date = db.Column(db.DateTime)
is_favorite = db.Column(db.Boolean, default=False)
listing_status = db.Column(
db.String(20), default="active"
) # 'active', 'removed', 'sold', 'unknown'
listing_removed_date = db.Column(db.DateTime)
listing_last_checked = db.Column(db.DateTime)
# How the status above was decided: 'ingest' (the default a new row carries,
# never verified), 'email' (idealista's own removal notice), 'check' (the
# scraper read the listing page) or 'manual' (the owner). NULL on rows that
# predate the column -- nothing was backfilled, because nothing recorded it.
listing_status_source = db.Column(db.String(16), default="ingest")
# What the OWNER concluded, which is a different question from whether the
# advert is still live -- writing one into `listing_status` is STATUS-002
# again (issue #430). NULL is not a fourth value: it means nobody has
# decided, and `services/owner_review.py` presents it as `undecided`,
# never as a rejection.
owner_verdict = db.Column(db.String(16))
owner_verdict_reason = db.Column(db.Text)
owner_verdict_at = db.Column(db.DateTime)
# What is still outstanding on this listing, and when it is due. Legal
# under any verdict, because "interested; call the architect on Friday" is
# an ordinary state. `overdue` is derived from the date and never stored.
next_action = db.Column(db.Text)
next_action_due_on = db.Column(db.Date)
# The parcel this listing sits on, as the cadastre names it (issue #430).
# Typed by a human off a document, so it is a column rather than a key
# inside `enrichment`: it is what every later check keys on, and it is
# looked up. The measurement it unlocks lives in `enrichment["cadastre"]`,
# written under the same lock (services/cadastre_service.py).
cadastral_reference = db.Column(db.String(20))
# How well this listing matches the owner's taste, scored by AI against
# the profile distilled from their own review comments (issue #498).
# NUMERIC like the three score columns above, because the list sorts on
# it; NULL means nobody scored the row — a bridge refusal writes nothing
# (services/taste_service.py), so the row stays in the backfill's scope.
# `taste` is the evidence beside the number: reasons, matched traits, the
# profile_version it was scored against, and a fingerprint of the facts.
taste_score = db.Column(db.Numeric(5, 2))
taste = db.Column(JSON)
# The parcel's surface in m², where the source portal states it
# (migration 025). A real column because the criteria verdict filters on
# it in SQL. NULL means nobody measured it (#98) — fotocasa's payload
# carries it (`surfaceLand`/`groundSurface`, 0-as-blank convention),
# yaencontre and idealista mostly cannot answer from this machine.
# Distinct from `area`, which is the BUILT surface for habitable
# listings and the plot only for bare land (`area_type` says which).
plot_area = db.Column(db.Numeric(10, 2))
created_at = db.Column(db.DateTime, default=utcnow)
email_date = db.Column(db.DateTime)
updated_at = db.Column(db.DateTime, default=utcnow, onupdate=utcnow)
def __repr__(self):
title = (self.title or "").strip()
snippet = (title[:50] + "...") if len(title) > 50 else title
return f"<Property {self.id}: {snippet}>"
def to_dict(self, review_today=None):
"""Serialize the row. `review_today` is the request's one Madrid date.
A collection endpoint MUST pass it: `overdue` is the comparison of a
due date against today, and a filter that selected rows against one
date while the payload describes them against another disagrees with
itself once a day, at the hour nobody is watching. `None` means
"compute it", which is right for a single-row caller and wrong for a
list -- `tests/test_owner_review_propagation.py` freezes the clock at
23:59 Madrid and asserts the filter and both serializers agree.
"""
review_action = owner_review.read_action(self, review_today)
return {
"id": self.id,
"source_email_id": self.source_email_id,
"idealista_property_id": self.idealista_property_id,
"email_subject": self.email_subject,
"email_sender": self.email_sender,
"search_profile_id": self.search_profile_id,
"title": self.title,
"url": self.url,
"deal_type": self.deal_type,
"property_category": self.property_category,
"property_subtype": self.property_subtype,
"price": float(self.price) if self.price else None,
"currency": self.currency,
"area": float(self.area) if self.area else None,
"area_type": self.area_type,
"municipality": self.municipality,
"location_lat": float(self.location_lat) if self.location_lat else None,
"location_lon": float(self.location_lon) if self.location_lon else None,
"location_accuracy": self.location_accuracy,
"description": self.description,
"attributes": self.attributes or {},
"property_details": self.property_details or {},
"enrichment": self.enrichment or {},
"travel": self.travel or {},
"scoring": self.scoring or {},
"ai_analysis": self.ai_analysis or {},
"enhanced_description": self.enhanced_description or {},
"score_total": float(self.score_total) if self.score_total else None,
"score_investment": float(self.score_investment)
if self.score_investment
else None,
"score_lifestyle": float(self.score_lifestyle)
if self.score_lifestyle
else None,
# `is not None`, not truthiness: a taste score of 0 is a measured
# answer ("nothing the owner values"), not an absence.
"taste_score": float(self.taste_score)
if self.taste_score is not None
else None,
"plot_area": float(self.plot_area) if self.plot_area is not None else None,
"taste": self.taste or {},
"previous_price": float(self.previous_price)
if self.previous_price
else None,
"price_change_amount": float(self.price_change_amount)
if self.price_change_amount
else None,
"price_change_percentage": float(self.price_change_percentage)
if self.price_change_percentage
else None,
"price_changed_date": self.price_changed_date.isoformat()
if self.price_changed_date
else None,
"is_favorite": bool(self.is_favorite),
"listing_status": self.listing_status or "active",
"listing_removed_date": self.listing_removed_date.isoformat()
if self.listing_removed_date
else None,
"listing_last_checked": self.listing_last_checked.isoformat()
if self.listing_last_checked
else None,
"listing_status_source": self.listing_status_source,
# The raw column above is 'active' by default and nobody verified
# that default, so a consumer reading it alone cannot tell a live
# listing from a never-checked one. This is the same verdict the
# pages render: 'active' only when a check or the owner established
# it, 'unchecked' otherwise (services/listing_verification.py).
"listing_status_verdict": listing_verdict(self)["state"],
# Who is selling. Most of the answer is derived from the listing
# URL rather than stored, so a consumer reading `enrichment` alone
# would see nothing for the 408 rows that answer for free
# (services/advertiser.py). 'unchecked' where nobody established
# it -- never 'agency' by default.
"advertiser_verdict": advertiser_verdict(self)["state"],
# The dossier written about this listing, if there is one. A
# pointer, not a measurement -- `None` means nobody wrote one, and
# the URL is the one the page would render, validated by the same
# function (services/dossier.py).
"dossier": read_dossier(self),
# What the owner decided, and what is still outstanding. Absent is
# `undecided`, never `rejected`: a report built off the raw column
# alone cannot tell "nobody looked" from "looked and said no"
# (services/owner_review.py).
"owner_verdict": owner_review.read_decision(self)["state"],
"owner_verdict_reason": self.owner_verdict_reason,
"owner_verdict_at": self.owner_verdict_at.isoformat()
if self.owner_verdict_at
else None,
"next_action": self.next_action,
"next_action_due_on": self.next_action_due_on.isoformat()
if self.next_action_due_on
else None,
"next_action_state": review_action["state"],
"cadastral_reference": self.cadastral_reference,
"email_date": self.email_date.isoformat() if self.email_date else None,
"created_at": self.created_at.isoformat() if self.created_at else None,
"updated_at": self.updated_at.isoformat() if self.updated_at else None,
}
def _get_enrichment_dict(self):
return self.enrichment if isinstance(self.enrichment, dict) else {}
def _get_legacy_land(self):
enrichment = self._get_enrichment_dict()
legacy = enrichment.get("legacy_land")
return legacy if isinstance(legacy, dict) else {}
def _get_enrichment_section(self, key):
enrichment = self._get_enrichment_dict()
section = enrichment.get(key)
if isinstance(section, dict):
return section
legacy = self._get_legacy_land()
section = legacy.get(key)
return section if isinstance(section, dict) else {}
def _get_enrichment_value(self, key):
enrichment = self._get_enrichment_dict()
if key in enrichment and enrichment.get(key) is not None:
return enrichment.get(key)
legacy = self._get_legacy_land()
if key in legacy and legacy.get(key) is not None:
return legacy.get(key)
return None
def _get_travel_targets(self):
travel = self.travel if isinstance(self.travel, dict) else {}
targets = travel.get("targets")
return targets if isinstance(targets, dict) else {}
def _travel_target_duration(self, key):
target = self._get_travel_targets().get(key)
if not isinstance(target, dict):
return None
duration_min = target.get("duration_min")
if duration_min is not None:
return duration_min
duration_s = target.get("duration_s")
if duration_s is None:
return None
return int(round(duration_s / 60.0))
def _travel_target_distance_km(self, key):
target = self._get_travel_targets().get(key)
if not isinstance(target, dict):
return None
distance_km = target.get("distance_km")
if distance_km is None:
distance_m = target.get("distance_m")
if distance_m is None:
return None
distance_km = float(distance_m) / 1000.0
return round(float(distance_km), 1)
@property
def geocoded_address(self):
"""The address the geocoder resolved, or `None` if it never resolved one.
A listing carries no street of its own -- the columns stop at
`municipality` -- so `enrichment.geocoding.formatted_address` is the
only human-readable location this app ever holds. It was written by
the enrichment pass and then read by nothing, which is why the page
could show a coordinate and no address at all. Absent means the
geocoder did not run or refused; nothing is reconstructed from the
coordinate to fill the gap.
"""
address = self._get_enrichment_section("geocoding").get("formatted_address")
if not isinstance(address, str):
return None
return address.strip() or None
def _measured_duration(self, target_key: str, legacy_key: str):
"""Minutes to a target, preferring the source that can be re-measured.
`travel["targets"]` is rewritten by every enrichment run;
`enrichment.legacy_land` is a frozen snapshot from the old `Land`
model that no recalculation touches. Reading legacy first made the
Transport card contradict Travel Times on all 168 mirrored rows --
41 minutes to Asturias Airport in one card, 35 to something unnamed
in the other. A target present in `travel` is authoritative even when
its value is `None`: "we looked and found nothing" outranks a
measurement nobody can reproduce.
"""
if target_key in self._get_travel_targets():
return self._travel_target_duration(target_key)
return self._get_enrichment_value(legacy_key)
def _measured_distance_km(self, target_key: str, legacy_key: str):
"""Kilometres to a target, with the same precedence as the duration."""
if target_key in self._get_travel_targets():
return self._travel_target_distance_km(target_key)
return self._get_enrichment_value(legacy_key)
@property
def infrastructure_basic(self):
return self._get_enrichment_section("infrastructure_basic")
@property
def infrastructure_extended(self):
return self._get_enrichment_section("infrastructure_extended")
@property
def transport(self):
return self._get_enrichment_section("transport")
@property
def environment(self):
return self._get_enrichment_section("environment")
@property
def services_quality(self):
return self._get_enrichment_section("services_quality")
@property
def travel_time_airport(self):
return self._measured_duration("airport", "travel_time_airport")
@property
def travel_time_train_station(self):
return self._measured_duration("train_station", "travel_time_train_station")
@property
def travel_time_hospital(self):
return self._measured_duration("hospital", "travel_time_hospital")
@property
def travel_time_police(self):
return self._measured_duration("police", "travel_time_police")
@property
def distance_airport(self):
return self._measured_distance_km("airport", "distance_airport")
@property
def distance_train_station(self):
return self._measured_distance_km("train_station", "distance_train_station")
@property
def distance_hospital(self):
return self._measured_distance_km("hospital", "distance_hospital")
@property
def distance_police(self):
return self._measured_distance_km("police", "distance_police")
def _ai_analysis_dict(self):
"""Return ai_analysis as a dict regardless of storage type."""
data = self.ai_analysis
if not data:
return {}
if isinstance(data, dict):
return data
if isinstance(data, str):
try:
parsed = json.loads(data)
return parsed if isinstance(parsed, dict) else {}
except Exception:
return {}
return {}
@staticmethod
def _humanize_rating_text(value):
text = str(value or "").strip()
if not text:
return None
text = text.replace("_", " ")
text = " ".join(text.split())
head, sep, tail = text.partition("-")
head = head.strip()
tail = tail.strip() if sep else ""
if head and head.upper() == head:
head = head.title()
if not sep:
return head
if not tail:
return head
return f"{head} - {tail}"
@property
def investment_metrics_rating_full(self):
"""Full investment rating text from structured rental market analysis (if present)."""
analysis = self._ai_analysis_dict()
rental = (
analysis.get("rental_market_analysis")
if isinstance(analysis, dict)
else None
)
if not isinstance(rental, dict):
return None
rating = rental.get("investment_rating")
if not rating:
return None
return self._humanize_rating_text(rating)
@property
def investment_metrics_rating(self):
"""Short investment rating label (e.g., GOOD/MODERATE/EXCELLENT)."""
full = self.investment_metrics_rating_full
if not full:
return None
short = full.split("-", 1)[0].strip()
return short if short else None
@property
def investment_metrics_badge_class(self):
"""Bootstrap badge class for the investment rating."""
return investment_rating_badge_class(
self.investment_metrics_rating_full or self.investment_metrics_rating
)
class Land(db.Model):
__tablename__ = "lands"
__table_args__ = (
db.Index("ix_lands_idealista_property_id", "idealista_property_id"),
db.Index("ix_lands_land_type", "land_type"),
db.Index("ix_lands_municipality", "municipality"),
db.Index("ix_lands_listing_status", "listing_status"),
db.Index("ix_lands_is_favorite", "is_favorite"),
db.Index("ix_lands_created_at", "created_at"),
db.Index("ix_lands_score_total", "score_total"),
db.Index("ix_lands_score_investment", "score_investment"),
db.Index("ix_lands_score_lifestyle", "score_lifestyle"),
# Data integrity constraints (matching Legacy)
CheckConstraint(
"price IS NULL OR price >= 0", name="ck_lands_price_non_negative"
),
CheckConstraint("area IS NULL OR area >= 0", name="ck_lands_area_non_negative"),
CheckConstraint(
"location_lat IS NULL OR (location_lat >= -90 AND location_lat <= 90)",
name="ck_lands_lat_range",
),
CheckConstraint(
"location_lon IS NULL OR (location_lon >= -180 AND location_lon <= 180)",
name="ck_lands_lon_range",
),
CheckConstraint(
"score_total IS NULL OR (score_total >= 0 AND score_total <= 100)",
name="ck_lands_score_total_range",
),
CheckConstraint(
"score_investment IS NULL OR (score_investment >= 0 AND score_investment <= 100)",
name="ck_lands_score_investment_range",
),
CheckConstraint(
"score_lifestyle IS NULL OR (score_lifestyle >= 0 AND score_lifestyle <= 100)",
name="ck_lands_score_lifestyle_range",
),
CheckConstraint(
"travel_time_oviedo IS NULL OR travel_time_oviedo >= 0",
name="ck_lands_tt_oviedo",
),
CheckConstraint(
"travel_time_gijon IS NULL OR travel_time_gijon >= 0",
name="ck_lands_tt_gijon",
),
CheckConstraint(
"travel_time_nearest_beach IS NULL OR travel_time_nearest_beach >= 0",
name="ck_lands_tt_beach",
),
CheckConstraint(
"travel_time_airport IS NULL OR travel_time_airport >= 0",
name="ck_lands_tt_airport",
),
CheckConstraint(
"travel_time_train_station IS NULL OR travel_time_train_station >= 0",
name="ck_lands_tt_train",
),
CheckConstraint(
"travel_time_hospital IS NULL OR travel_time_hospital >= 0",
name="ck_lands_tt_hospital",
),
CheckConstraint(
"travel_time_police IS NULL OR travel_time_police >= 0",
name="ck_lands_tt_police",
),
CheckConstraint(
"listing_status IN ('active', 'removed', 'sold', 'unknown')",
name="ck_lands_listing_status_enum",
),
)
id = db.Column(db.Integer, primary_key=True)
source_email_id = db.Column(db.String(255), unique=True, nullable=False)
# Stable Idealista listing id extracted from URL (/inmueble/<id>/). Used for dedup/updates.
idealista_property_id = db.Column(db.BigInteger, nullable=True)
email_subject = db.Column(db.Text) # Original email subject line
email_sender = db.Column(db.String(255)) # Email sender
title = db.Column(db.Text)
url = db.Column(db.Text)
price = db.Column(db.Numeric(10, 2))
area = db.Column(db.Numeric(10, 2))
municipality = db.Column(db.String(255))
location_lat = db.Column(db.Numeric(10, 7))
location_lon = db.Column(db.Numeric(10, 7))
location_accuracy = db.Column(
db.String(20), default="unknown"
) # 'precise', 'approximate', 'unknown'
land_type = db.Column(
db.String(20), CheckConstraint("land_type IN ('developed', 'buildable')")
)
description = db.Column(db.Text)
# JSON fields for complex data (works with both PostgreSQL and SQLite)
infrastructure_basic = db.Column(JSON) # electricity, water, internet, gas
infrastructure_extended = db.Column(
JSON
) # supermarket, school, restaurants, hospital
transport = db.Column(JSON) # train, airport, highway, bus
environment = db.Column(JSON) # sea_view, mountain_view, forest, orientation
neighborhood = db.Column(JSON) # new_houses, area_price_level, noise
services_quality = db.Column(
JSON
) # schools rating, restaurants rating, cafes rating
legal_status = db.Column(db.String(50))
property_details = db.Column(
JSON
) # AI analysis and property details in JSON format
ai_analysis = db.Column(JSON) # Structured AI analysis with 5 blocks
enhanced_description = db.Column(JSON) # AI-enhanced professional description data
# How the last travel run went, in the `Property.travel` shape: api_status
# plus a per-target `google` / `estimate` / `unavailable` (#225). The
# travel_time_* columns above hold measurements only; an estimate lives
# here, labelled, instead of impersonating one.
travel = db.Column(JSON)
score_total = db.Column(db.Numeric(5, 2))
score_investment = db.Column(db.Numeric(5, 2)) # Investment-focused score (0-100)
score_lifestyle = db.Column(db.Numeric(5, 2)) # Lifestyle-focused score (0-100)
# Travel times by car (in minutes)
# Reference city A/B are configured via SettingsService.get_reference_cities().
travel_time_oviedo = db.Column(db.Integer) # Travel time to reference city A
travel_time_gijon = db.Column(db.Integer) # Travel time to reference city B
travel_time_nearest_beach = db.Column(
db.Integer
) # Time to nearest beach in minutes
nearest_beach_name = db.Column(db.String(255)) # Name of nearest beach
# Priority infrastructure travel times (in minutes)
travel_time_airport = db.Column(db.Integer) # Time to nearest airport
travel_time_train_station = db.Column(db.Integer) # Time to nearest train station
travel_time_hospital = db.Column(db.Integer) # Time to nearest hospital
travel_time_police = db.Column(db.Integer) # Time to nearest police station
# Priority infrastructure distances (in kilometers)
distance_airport = db.Column(db.Integer) # Distance to nearest airport in km
distance_train_station = db.Column(
db.Integer
) # Distance to nearest train station in km
distance_hospital = db.Column(db.Integer) # Distance to nearest hospital in km
distance_police = db.Column(db.Integer) # Distance to nearest police station in km
# Price history tracking
previous_price = db.Column(db.Numeric(10, 2)) # Previous price before update
price_change_amount = db.Column(
db.Numeric(10, 2)
) # Amount of price change (negative for decrease)
price_change_percentage = db.Column(db.Numeric(5, 2)) # Percentage change
price_changed_date = db.Column(db.DateTime) # When price was last changed
# Favorites
is_favorite = db.Column(db.Boolean, default=False) # Mark property as favorite
# Listing status tracking
listing_status = db.Column(
db.String(20), default="active"
) # 'active', 'removed', 'sold', 'unknown'
listing_removed_date = db.Column(
db.DateTime
) # When listing was removed from Idealista
listing_last_checked = db.Column(
db.DateTime
) # Last time we checked the listing status
# Same four values as Property.listing_status_source, same NULL meaning.
listing_status_source = db.Column(db.String(16), default="ingest")
created_at = db.Column(db.DateTime, default=utcnow)
email_date = db.Column(db.DateTime) # Date when the email was received
updated_at = db.Column(
db.DateTime, default=utcnow, onupdate=utcnow
) # Last update time
def __repr__(self):
return f"<Land {self.id}: {self.title[:50]}...>"
def to_dict(self):
"""Convert land to dictionary for API responses"""
return {
"id": self.id,
"source_email_id": self.source_email_id,
"idealista_property_id": self.idealista_property_id,
"title": self.title,
"url": self.url,
"price": float(self.price) if self.price else None,
"area": float(self.area) if self.area else None,
"municipality": self.municipality,
"location_lat": float(self.location_lat) if self.location_lat else None,
"location_lon": float(self.location_lon) if self.location_lon else None,
"location_accuracy": self.location_accuracy,
"land_type": self.land_type,
"description": self.description,
"infrastructure_basic": self.infrastructure_basic or {},
"infrastructure_extended": self.infrastructure_extended or {},
"transport": self.transport or {},
"environment": self.environment or {},
"neighborhood": self.neighborhood or {},
"services_quality": self.services_quality or {},
"legal_status": self.legal_status,
"score_total": float(self.score_total) if self.score_total else None,
"score_investment": float(self.score_investment)
if self.score_investment
else None,
"score_lifestyle": float(self.score_lifestyle)
if self.score_lifestyle
else None,
"travel_time_oviedo": self.travel_time_oviedo,
"travel_time_gijon": self.travel_time_gijon,
"travel_time_nearest_beach": self.travel_time_nearest_beach,
"nearest_beach_name": self.nearest_beach_name,
"is_favorite": self.is_favorite or False,
"listing_status": self.listing_status or "active",
"listing_removed_date": self.listing_removed_date.isoformat()
if self.listing_removed_date
else None,
"listing_last_checked": self.listing_last_checked.isoformat()
if self.listing_last_checked
else None,
"listing_status_source": self.listing_status_source,
# The raw column above is 'active' by default and nobody verified
# that default, so a consumer reading it alone cannot tell a live
# listing from a never-checked one. This is the same verdict the
# pages render: 'active' only when a check or the owner established
# it, 'unchecked' otherwise (services/listing_verification.py).
"listing_status_verdict": listing_verdict(self)["state"],
"created_at": self.created_at.isoformat() if self.created_at else None,
}
def _ai_analysis_dict(self):
"""Return ai_analysis as a dict regardless of storage type."""
data = self.ai_analysis
if not data:
return {}
if isinstance(data, dict):
return data
if isinstance(data, str):
try:
parsed = json.loads(data)
return parsed if isinstance(parsed, dict) else {}
except Exception:
return {}
return {}
@property
def investment_metrics_rating_full(self):
"""Full investment rating text from structured rental market analysis (if present)."""
analysis = self._ai_analysis_dict()
rental = (
analysis.get("rental_market_analysis")
if isinstance(analysis, dict)
else None
)
if not isinstance(rental, dict):
return None
rating = rental.get("investment_rating")
if not rating:
return None
return self._humanize_rating_text(rating)
@property
def investment_metrics_rating(self):
"""Short investment rating label (e.g., GOOD/MODERATE/EXCELLENT)."""
full = self.investment_metrics_rating_full
if not full:
return None
short = full.split("-", 1)[0].strip()
return short if short else None
@staticmethod
def _humanize_rating_text(value):
text = str(value or "").strip()
if not text:
return None
text = text.replace("_", " ")
text = " ".join(text.split())
head, sep, tail = text.partition("-")
head = head.strip()
tail = tail.strip() if sep else ""
if head and head.upper() == head:
head = head.title()
if not sep:
return head
if not tail:
return head
return f"{head} - {tail}"
@property
def investment_metrics_badge_class(self):
"""Bootstrap badge class for investment rating."""
return investment_rating_badge_class(
self.investment_metrics_rating_full or self.investment_metrics_rating
)