-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodes.py
More file actions
509 lines (393 loc) · 16.2 KB
/
Copy pathcodes.py
File metadata and controls
509 lines (393 loc) · 16.2 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
from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar, Self, TypeVar
from uuid import UUID # Sqlalchemy uses UUID type annotation runtime
from geoalchemy2 import Geometry, WKBElement
from sqlalchemy import Column, ForeignKey, Index, Table, Uuid
from sqlalchemy.orm import Mapped, Session, declared_attr, mapped_column, relationship
from sqlalchemy.sql import func
from database.base import Base, VersionedBase, language_str, unique_str
if TYPE_CHECKING:
from database.models import (
Document,
LandUseArea,
Line,
Organisation,
OtherArea,
Plan,
PlanMatter,
PlanProposition,
PlanRegulation,
PlanRegulationGroup,
Point,
SourceData,
)
allowed_events = Table(
"allowed_events",
Base.metadata,
Column("id", Uuid, primary_key=True, server_default=func.gen_random_uuid()),
Column(
"lifecycle_status_id",
ForeignKey(
"codes.lifecycle_status.id",
name="lifecycle_status_id_fkey",
ondelete="CASCADE",
),
index=True,
),
Column(
"name_of_plan_case_decision_id",
ForeignKey(
"codes.name_of_plan_case_decision.id",
name="name_of_plan_case_decision_id_fkey",
ondelete="CASCADE",
),
index=True,
),
Column(
"type_of_processing_event_id",
ForeignKey(
"codes.type_of_processing_event.id",
name="type_of_processing_event_id_fkey",
ondelete="CASCADE",
),
index=True,
),
Column(
"type_of_interaction_event_id",
ForeignKey(
"codes.type_of_interaction_event.id",
name="type_of_interaction_event_id_fkey",
ondelete="CASCADE",
),
index=True,
),
schema="codes",
)
class CodeBase(VersionedBase):
"""Code tables in Ryhti should refer to national Ryhti code table URIs. They may
have hierarchical structure.
"""
__abstract__ = True
__table_args__: Any = {"schema": "codes"} # noqa: RUF012 # No can do, sqlalchemy has Any annotation for this
code_list_uri = "" # the URI to use for looking for codes online
local_codes: ClassVar[
list[dict[str, Any]]
] = [] # local codes to add to the code list
value: Mapped[unique_str]
short_name: Mapped[str] = mapped_column(server_default="", index=True)
name: Mapped[language_str | None]
description: Mapped[language_str | None]
# Let's import code status too. This tells our importer if the koodisto is final,
# or if the code can be deleted and/or moved.
status: Mapped[str]
# For now, level can just be imported from RYTJ. Let's assume the level in RYTJ
# is correct, so we don't have to calculate and recalculate it ourselves.
level: Mapped[int] = mapped_column(server_default="1", index=True)
# self-reference in abstract base class:
@declared_attr
@classmethod
def parent_id(cls) -> Mapped[UUID | None]:
return mapped_column(
ForeignKey(cls.id, name=f"{cls.__tablename__}_parent_id_fkey"), index=True
)
@declared_attr
@classmethod
def parent(cls) -> Mapped[Self | None]:
return relationship(cls, remote_side=[cls.id], back_populates="children")
@declared_attr
@classmethod
def children(cls) -> Mapped[list[Self]]:
return relationship(cls, back_populates="parent")
@property
def uri(self) -> str:
return f"{self.code_list_uri}/code/{self.value}"
class LifeCycleStatus(CodeBase):
"""Elinkaaren vaihe"""
VALID_VALUE = "13" # Voimassa
VALID_BEFORE_LEGAL_VALIDITY_VALUE = "11" # Voimassa ennen kaavan lainvoimaisuutta
__tablename__ = "lifecycle_status"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/kaavaelinkaari"
allowed_interaction_events: Mapped[list[TypeOfInteractionEvent]] = relationship(
secondary="codes.allowed_events", back_populates="allowed_statuses"
)
allowed_decisions: Mapped[list[NameOfPlanCaseDecision]] = relationship(
secondary="codes.allowed_events",
back_populates="allowed_statuses",
overlaps="allowed_interaction_events",
)
allowed_processing_events: Mapped[list[TypeOfProcessingEvent]] = relationship(
secondary="codes.allowed_events",
back_populates="allowed_statuses",
overlaps="allowed_decisions,allowed_interaction_events",
)
plans: Mapped[list[Plan]] = relationship(back_populates="lifecycle_status")
land_use_areas: Mapped[list[LandUseArea]] = relationship(
back_populates="lifecycle_status"
)
other_areas: Mapped[list[OtherArea]] = relationship(
back_populates="lifecycle_status"
)
lines: Mapped[list[Line]] = relationship(back_populates="lifecycle_status")
points: Mapped[list[Point]] = relationship(back_populates="lifecycle_status")
plan_regulations: Mapped[list[PlanRegulation]] = relationship(
back_populates="lifecycle_status"
)
plan_propositions: Mapped[list[PlanProposition]] = relationship(
back_populates="lifecycle_status"
)
class PlanType(CodeBase):
"""Kaavalaji"""
REGIONAL_PLAN_VALUE = "1"
__tablename__ = "plan_type"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/RY_Kaavalaji"
plan_matters: Mapped[list[PlanMatter]] = relationship(back_populates="plan_type")
def is_regional_plan(self) -> bool:
if self.value == PlanType.REGIONAL_PLAN_VALUE:
return True
if self.parent:
return self.parent.is_regional_plan()
return False
class TypeOfPlanRegulation(CodeBase):
"""Kaavamääräyslaji"""
__tablename__ = "type_of_plan_regulation"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/RY_Kaavamaarayslaji"
plan_regulations: Mapped[list[PlanRegulation]] = relationship(
back_populates="type_of_plan_regulation"
)
class TypeOfAdditionalInformation(CodeBase):
"""Kaavamääräyksen lisätiedon laji"""
# Let's use a shortish table name, since the long name creates indexes that have
# names that are too long for PostgreSQL, hooray :D
__tablename__ = "type_of_additional_information"
code_list_uri = (
"http://uri.suomi.fi/codelist/rytj/RY_Kaavamaarayksen_Lisatiedonlaji"
)
class TypeOfVerbalPlanRegulation(CodeBase):
"""Sanallisen määräyksen laji
Epäselvää milloin tätä käytetään.
"""
__tablename__ = "type_of_verbal_plan_regulation"
code_list_uri = (
"http://uri.suomi.fi/codelist/rytj/RY_Sanallisen_Kaavamaarayksen_Laji"
)
plan_regulations: Mapped[list[PlanRegulation]] = relationship(
secondary="hame.type_of_verbal_regulation_association",
back_populates="types_of_verbal_plan_regulations",
)
class TypeOfSourceData(CodeBase):
"""Lähtöaineiston laji"""
__tablename__ = "type_of_source_data"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/RY_LahtotietoaineistonLaji"
source_data: Mapped[list[SourceData]] = relationship(
back_populates="type_of_source_data"
)
class TypeOfUnderground(CodeBase):
"""Maanalaisuuden laji"""
__tablename__ = "type_of_underground"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/RY_MaanalaisuudenLaji"
land_use_areas: Mapped[list[LandUseArea]] = relationship(
back_populates="type_of_underground"
)
other_areas: Mapped[list[OtherArea]] = relationship(
back_populates="type_of_underground"
)
lines: Mapped[list[Line]] = relationship(back_populates="type_of_underground")
points: Mapped[list[Point]] = relationship(back_populates="type_of_underground")
class TypeOfDocument(CodeBase):
"""Asiakirjatyyppi"""
__tablename__ = "type_of_document"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/RY_AsiakirjanLaji_YKAK"
documents: Mapped[list[Document]] = relationship(back_populates="type_of_document")
class Municipality(CodeBase):
"""Kunta"""
__tablename__ = "municipality"
code_list_uri = "http://uri.suomi.fi/codelist/jhs/kunta_1_20240101"
geom: Mapped[WKBElement] = mapped_column(
type_=Geometry(geometry_type="MULTIPOLYGON", srid=3067), nullable=True
)
organisations: Mapped[list[Organisation]] = relationship(
back_populates="municipality"
)
class AdministrativeRegion(CodeBase):
"""Maakunta"""
__tablename__ = "administrative_region"
code_list_uri = "http://uri.suomi.fi/codelist/jhs/maakunta_1_20240101"
geom: Mapped[WKBElement] = mapped_column(
type_=Geometry(geometry_type="MULTIPOLYGON", srid=3067), nullable=True
)
organisations: Mapped[list[Organisation]] = relationship(
back_populates="administrative_region"
)
class TypeOfPlanRegulationGroup(CodeBase):
"""Kaavamääräysryhmän tyyppi
This is our own code list. It does not exist in koodistot.suomi.fi.
"""
__tablename__ = "type_of_plan_regulation_group"
__table_args__ = (
Index("ix_type_of_plan_regulation_group_value", "value"),
CodeBase.__table_args__,
)
code_list_uri = ""
local_codes: ClassVar[list[dict[str, Any]]] = [
{"value": "generalRegulations", "name": {"fin": "Yleismääräykset"}},
{"value": "landUseRegulations", "name": {"fin": "Aluevaraus"}},
{"value": "otherAreaRegulations", "name": {"fin": "Osa-alue"}},
{"value": "lineRegulations", "name": {"fin": "Viiva"}},
{"value": "pointRegulations", "name": {"fin": "Piste"}},
]
plan_regulation_groups: Mapped[list[PlanRegulationGroup]] = relationship(
back_populates="type_of_plan_regulation_group"
)
class PlanTheme(CodeBase):
"""Kaavoitusteema"""
__tablename__ = "plan_theme"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/kaavoitusteema"
plan_propositions: Mapped[list[PlanProposition]] = relationship(
secondary="hame.plan_theme_association",
overlaps="plan_regulations",
back_populates="plan_themes",
)
plan_regulations: Mapped[list[PlanRegulation]] = relationship(
secondary="hame.plan_theme_association",
overlaps="plan_propositions",
back_populates="plan_themes",
)
class CategoryOfPublicity(CodeBase):
"""Asiakirjan julkisuusluokka"""
__tablename__ = "category_of_publicity"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/julkisuus"
documents: Mapped[list[Document]] = relationship(
back_populates="category_of_publicity"
)
class PersonalDataContent(CodeBase):
"""Asiakirjan henkilötietosisältö"""
__tablename__ = "personal_data_content"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/henkilotietosisalto"
documents: Mapped[list[Document]] = relationship(
back_populates="personal_data_content"
)
class RetentionTime(CodeBase):
"""Asiakirjan säilytysaika"""
__tablename__ = "retention_time"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/sailytysaika"
documents: Mapped[list[Document]] = relationship(back_populates="retention_time")
class Language(CodeBase):
"""Rakennetun ympäristön tietojärjestelmän tukemat kielet"""
__tablename__ = "language"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/ryhtikielet"
documents: Mapped[list[Document]] = relationship(back_populates="language")
class LegalEffectsOfMasterPlan(CodeBase):
"""Yleiskaavan oikeusvaikutukset"""
__tablename__ = "legal_effects_of_master_plan"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/oikeusvaik_YK"
plans: Mapped[list[Plan]] = relationship(
secondary="hame.legal_effects_association",
back_populates="legal_effects_of_master_plan",
)
decisions_by_status = {
# Some lifecycle statuses require decisions, some don't.
# Plan decision code depends on lifecycle status:
# https://ryhti.syke.fi/wp-content/uploads/sites/2/2023/11/Kaavatiedon-validointisaannot-ja-paluuarvot.pdf
"02": [
"01",
"02",
"03",
], # lifecycle/req-codelist-plandecision-name-codevalue-pending
"03": [
"04",
"05",
"06",
], # lifecycle/req-codelist-plandecision-name-codevalue-preparation
"04": [
"08"
], # lifecycle__req_codelist_plandecision_name_codevalue_changed_proposal_reversed
"05": ["07", "09"], # lifecycle/req-codelist-regionalplan-decisionname-lifecycle-05
"06": [
"11A"
], # lifecycle/req-codelist-plandecision-name-alternative-codevalues-approved-spatialplan # noqa: E501
"08": [
"12",
"13",
"15",
], # lifecycle/req-planmatterdecision-name-subject-appeal-lifecycle
}
processing_events_by_status = {
# Some lifecycle statuses require processing events, some don't.
# Processing event code depends on lifecycle status:
# https://ryhti.syke.fi/wp-content/uploads/sites/2/2023/11/Kaavatiedon-validointisaannot-ja-paluuarvot.pdf
"02": ["04"], # lifecycle/req-codelist-handlingeventtype-codevalue-lifecycle
"03": ["05", "06"], # lifecycle/req-codelist-handlingeventtype-codevalue-lifecycle
"04": ["07", "08"], # lifecycle/req-codelist-plandecision-name-codevalue-proposal
"05": [
"08",
"09",
], # lifecycle/req-codelist-regionalplan-handlingeventtype-lifecycle-05
"06": [
"11"
], # lifecycle/req-codelist-regionalplan-handlingevent-approved-spatialplan
"11": ["13"], # not allowed in regional plan!
"13": ["16"], # lifecycle/req-codelist-handlingeventtype-codevalue-lifecycle
}
interaction_events_by_status = {
# Some lifecycle statuses require interaction events, some don't
# Interaction event code depends on lifecycle status:
# https://ryhti.syke.fi/wp-content/uploads/sites/2/2023/11/Kaavatiedon-validointisaannot-ja-paluuarvot.pdf
"03": ["01"], # lifecycle/req-codelist-interactionevent-codevalue-lifecycle
"04": [
"01"
], # lifecycle/req-codelist-regionalplan-interactionevent-display-proposal
"05": [
"01",
"02",
], # lifecycle/req-codelist-regionalplan-iteractioneventtype-lifecycle-05
}
class TypeOfInteractionEvent(CodeBase):
"""Vuorovaikutustapahtuman laji (kaava)"""
__tablename__ = "type_of_interaction_event"
code_list_uri = (
"http://uri.suomi.fi/codelist/rytj/RY_KaavanVuorovaikutustapahtumanLaji"
)
allowed_status_dict = interaction_events_by_status
allowed_statuses: Mapped[list[LifeCycleStatus]] = relationship(
secondary="codes.allowed_events",
back_populates="allowed_interaction_events",
overlaps="allowed_decisions,allowed_processing_events",
)
class NameOfPlanCaseDecision(CodeBase):
"""Kaava-asian päätöksen nimi"""
__tablename__ = "name_of_plan_case_decision"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/kaavpaatnimi"
allowed_status_dict = decisions_by_status
allowed_statuses: Mapped[list[LifeCycleStatus]] = relationship(
secondary="codes.allowed_events",
back_populates="allowed_decisions",
overlaps="allowed_interaction_events,allowed_processing_events,allowed_statuses",
)
class TypeOfProcessingEvent(CodeBase):
"""Käsittelytapahtuman laji"""
__tablename__ = "type_of_processing_event"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/kaavakastap"
allowed_status_dict = processing_events_by_status
allowed_statuses: Mapped[list[LifeCycleStatus]] = relationship(
secondary="codes.allowed_events",
back_populates="allowed_processing_events",
overlaps="allowed_interaction_events,allowed_decisions,allowed_statuses",
)
class TypeOfDecisionMaker(CodeBase):
"""Päätöksentekijän laji"""
__tablename__ = "type_of_decision_maker"
code_list_uri = "http://uri.suomi.fi/codelist/rytj/PaatoksenTekija"
T = TypeVar("T", bound=CodeBase)
def get_code[T: CodeBase](
session: Session, code_class: type[T], value: str
) -> T | None:
"""Get code object by value."""
return session.query(code_class).filter_by(value=value).first()
def get_code_uri(code_class: type[CodeBase], value: str) -> str:
"""Get code URI by value, without querying the database."""
return code_class(value=value).uri
decisionmaker_by_status = {
# TODO: Decisionmaker may depend on lifecycle status.
str(i).zfill(2): "01"
for i in range(1, 16)
}