-
-
Notifications
You must be signed in to change notification settings - Fork 300
Expand file tree
/
Copy pathtask.py
More file actions
1927 lines (1733 loc) · 67.5 KB
/
task.py
File metadata and controls
1927 lines (1733 loc) · 67.5 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
import datetime
import json
from datetime import timezone
from enum import Enum
from typing import Any, Dict, List, Optional
import bleach
import geojson
from databases import Database
from geoalchemy2 import Geometry
from shapely.geometry import shape
from sqlalchemy import (
BigInteger,
Boolean,
Column,
DateTime,
ForeignKey,
ForeignKeyConstraint,
Index,
Integer,
String,
Unicode,
desc,
select,
)
from sqlalchemy.orm import relationship
from sqlalchemy.orm.exc import MultipleResultsFound
from backend.config import settings
from backend.db import Base
from backend.exceptions import NotFound
from backend.models.dtos.mapping_dto import TaskDTO, TaskHistoryDTO
from backend.models.dtos.mapping_issues_dto import TaskMappingIssueDTO
from backend.models.dtos.project_dto import (
LockedTasksForUser,
ProjectComment,
ProjectCommentsDTO,
)
from backend.models.dtos.task_annotation_dto import TaskAnnotationDTO
from backend.models.dtos.validator_dto import MappedTasks, MappedTasksByUser
from backend.models.postgis.mapping_level import MappingLevel
from backend.models.postgis.statuses import TaskStatus
from backend.models.postgis.task_annotation import TaskAnnotation
from backend.models.postgis.user import User
from backend.models.postgis.utils import (
InvalidData,
InvalidGeoJson,
parse_duration,
timestamp,
)
class TaskAction(Enum):
"""Describes the possible actions that can happen to to a task, that we'll record history for"""
LOCKED_FOR_MAPPING = 1
LOCKED_FOR_VALIDATION = 2
STATE_CHANGE = 3
COMMENT = 4
AUTO_UNLOCKED_FOR_MAPPING = 5
AUTO_UNLOCKED_FOR_VALIDATION = 6
EXTENDED_FOR_MAPPING = 7
EXTENDED_FOR_VALIDATION = 8
class TaskInvalidationHistory(Base):
"""Describes the most recent history of task invalidation and subsequent validation"""
__tablename__ = "task_invalidation_history"
id = Column(Integer, primary_key=True)
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
task_id = Column(Integer, nullable=False)
is_closed = Column(Boolean, default=False)
mapper_id = Column(BigInteger, ForeignKey("users.id", name="fk_mappers"))
mapped_date = Column(DateTime)
invalidator_id = Column(BigInteger, ForeignKey("users.id", name="fk_invalidators"))
invalidated_date = Column(DateTime)
invalidation_history_id = Column(
Integer, ForeignKey("task_history.id", name="fk_invalidation_history")
)
validator_id = Column(BigInteger, ForeignKey("users.id", name="fk_validators"))
validated_date = Column(DateTime)
updated_date = Column(DateTime, default=timestamp)
__table_args__ = (
ForeignKeyConstraint(
[task_id, project_id], ["tasks.id", "tasks.project_id"], name="fk_tasks"
),
Index("idx_task_validation_history_composite", "task_id", "project_id"),
Index(
"idx_task_validation_validator_status_composite",
"invalidator_id",
"is_closed",
),
Index("idx_task_validation_mapper_status_composite", "mapper_id", "is_closed"),
{},
)
def __init__(self, project_id, task_id):
self.project_id = project_id
self.task_id = task_id
self.is_closed = False
@staticmethod
async def get_open_for_task(project_id: int, task_id: int, db: Database):
"""
Retrieve the open TaskInvalidationHistory entry for the given project and task.
This method also handles a suspected concurrency issue by managing cases where multiple entries
are created when only one should exist. If multiple entries are found, it
recursively handles and closes duplicate entries to ensure only a single entry
remains open.
Args:
project_id (int): The ID of the project.
task_id (int): The ID of the task.
local_session (Session, optional): The SQLAlchemy session to use for the query.
If not provided, a default session is used.
Returns:
TaskInvalidationHistory or None: The open TaskInvalidationHistory entry, or
None if no open entry is found.
Raises:
None: This method handles the MultipleResultsFound exception internally.
"""
try:
# Fetch open entry
query = """
SELECT * FROM task_invalidation_history
WHERE task_id = :task_id
AND project_id = :project_id
AND is_closed = FALSE
"""
entry = await db.fetch_one(
query=query, values={"task_id": task_id, "project_id": project_id}
)
return entry
except MultipleResultsFound:
await TaskInvalidationHistory.close_duplicate_invalidation_history_rows(
project_id, task_id, db
)
return await TaskInvalidationHistory.get_open_for_task(
project_id, task_id, db
)
@staticmethod
async def close_duplicate_invalidation_history_rows(
project_id: int, task_id: int, db: Database
):
"""
Closes duplicate TaskInvalidationHistory entries except for the latest one for the given project and task.
"""
# Fetch the oldest duplicate
query = """
SELECT id FROM task_invalidation_history
WHERE task_id = :task_id
AND project_id = :project_id
AND is_closed = FALSE
ORDER BY id ASC
LIMIT 1
"""
oldest_dupe = await db.fetch_one(
query=query, values={"task_id": task_id, "project_id": project_id}
)
if oldest_dupe:
update_query = """
UPDATE task_invalidation_history
SET is_closed = TRUE
WHERE id = :id
"""
await db.execute(query=update_query, values={"id": oldest_dupe["id"]})
@staticmethod
async def close_all_for_task(project_id: int, task_id: int, db: Database):
"""
Closes all open invalidation history entries for the specified task.
"""
update_query = """
UPDATE task_invalidation_history
SET is_closed = TRUE, updated_date = :updated_date
WHERE project_id = :project_id AND task_id = :task_id AND is_closed = FALSE
"""
values = {
"project_id": project_id,
"task_id": task_id,
"updated_date": datetime.datetime.utcnow(),
}
await db.execute(query=update_query, values=values)
@staticmethod
async def record_invalidation(
project_id: int, task_id: int, invalidator_id: int, history, db: Database
):
# Invalidation always kicks off a new entry for a task, so close any existing ones.
await TaskInvalidationHistory.close_all_for_task(project_id, task_id, db)
last_mapped = await TaskHistory.get_last_mapped_action(project_id, task_id, db)
if not last_mapped:
return
# Insert a new TaskInvalidationHistory entry
insert_query = """
INSERT INTO task_invalidation_history (
project_id, task_id, invalidation_history_id, mapper_id, mapped_date,
invalidator_id, invalidated_date, updated_date
)
VALUES (
:project_id, :task_id, :invalidation_history_id, :mapper_id, :mapped_date,
:invalidator_id, :invalidated_date, :updated_date
)
"""
values = {
"project_id": project_id,
"task_id": task_id,
"invalidation_history_id": history.id,
"mapper_id": last_mapped["user_id"],
"mapped_date": last_mapped["action_date"],
"invalidator_id": invalidator_id,
"invalidated_date": history.action_date,
"updated_date": datetime.datetime.utcnow(),
}
await db.execute(query=insert_query, values=values)
@staticmethod
async def record_validation(
project_id: int,
task_id: int,
validator_id: int,
history: TaskHistoryDTO,
db: Database,
):
entry = await TaskInvalidationHistory.get_open_for_task(project_id, task_id, db)
# If no open invalidation to update, then nothing to do
if entry is None:
return
last_mapped = await TaskHistory.get_last_mapped_action(project_id, task_id, db)
# Update entry with validation details
update_query = """
UPDATE task_invalidation_history
SET mapper_id = :mapper_id,
mapped_date = :mapped_date,
validator_id = :validator_id,
validated_date = :validated_date,
is_closed = TRUE,
updated_date = :updated_date
WHERE id = :entry_id
"""
await db.execute(
query=update_query,
values={
"mapper_id": last_mapped["user_id"],
"mapped_date": last_mapped["action_date"],
"validator_id": validator_id,
"validated_date": history.action_date,
"updated_date": timestamp(),
"entry_id": entry["id"],
},
)
class TaskMappingIssue(Base):
"""Describes an issue (along with an occurrence count) with a
task mapping that contributed to invalidation of the task"""
__tablename__ = "task_mapping_issues"
id = Column(Integer, primary_key=True)
task_history_id = Column(
Integer, ForeignKey("task_history.id"), nullable=False, index=True
)
issue = Column(String, nullable=False)
mapping_issue_category_id = Column(
Integer,
ForeignKey("mapping_issue_categories.id", name="fk_issue_category"),
nullable=False,
)
count = Column(Integer, nullable=False)
def __init__(self, issue, count, mapping_issue_category_id, task_history_id=None):
self.task_history_id = task_history_id
self.issue = issue
self.count = count
self.mapping_issue_category_id = mapping_issue_category_id
def as_dto(self):
issue_dto = TaskMappingIssueDTO()
issue_dto.category_id = self.mapping_issue_category_id
issue_dto.name = self.issue
issue_dto.count = self.count
return issue_dto
def __repr__(self):
return "{0}: {1}".format(self.issue, self.count)
class TaskHistory(Base):
"""Describes the history associated with a task"""
__tablename__ = "task_history"
id = Column(Integer, primary_key=True)
project_id = Column(Integer, ForeignKey("projects.id"), index=True)
task_id = Column(Integer, nullable=False)
action = Column(String, nullable=False)
action_text = Column(String)
action_date = Column(DateTime, nullable=False, default=timestamp)
user_id = Column(
BigInteger,
ForeignKey("users.id", name="fk_users"),
index=True,
nullable=False,
)
invalidation_history = relationship(
TaskInvalidationHistory, lazy="dynamic", cascade="all"
)
actioned_by = relationship(User)
task_mapping_issues = relationship(TaskMappingIssue, cascade="all")
__table_args__ = (
ForeignKeyConstraint(
[task_id, project_id], ["tasks.id", "tasks.project_id"], name="fk_tasks"
),
Index("idx_task_history_composite", "task_id", "project_id"),
Index("idx_task_history_project_id_user_id", "user_id", "project_id"),
{},
)
def __init__(self, task_id, project_id, user_id):
self.task_id = task_id
self.project_id = project_id
self.user_id = user_id
def set_task_extend_action(task_action: TaskAction) -> str:
if task_action not in [
TaskAction.EXTENDED_FOR_MAPPING,
TaskAction.EXTENDED_FOR_VALIDATION,
]:
raise ValueError("Invalid Action")
return task_action.name, None
def set_task_locked_action(task_action: TaskAction) -> str:
if task_action not in [
TaskAction.LOCKED_FOR_MAPPING,
TaskAction.LOCKED_FOR_VALIDATION,
]:
raise ValueError("Invalid Action")
return task_action.name, None
def set_comment_action(comment: str) -> str:
clean_comment = bleach.clean(comment) # Ensure no harmful scripts or tags
return TaskAction.COMMENT.name, clean_comment
def set_state_change_action(new_state: TaskStatus) -> str:
return TaskAction.STATE_CHANGE.name, new_state.name
def set_auto_unlock_action(task_action: TaskAction) -> str:
return task_action.name, None
async def update_task_locked_with_duration(
task_id: int,
project_id: int,
lock_action: TaskAction,
user_id: int,
db: Database,
):
"""
Calculates the duration a task was locked for and sets it on the history record.
:param task_id: Task in scope
:param project_id: Project ID in scope
:param lock_action: The lock action, either Mapping or Validation
:param user_id: Logged-in user updating the task.
"""
try:
# Fetch the last locked task history entry with raw SQL
query = """
SELECT id, action_date
FROM task_history
WHERE task_id = :task_id
AND project_id = :project_id
AND action = :action
AND action_text IS NULL
AND user_id = :user_id
ORDER BY action_date DESC
LIMIT 1
"""
values = {
"task_id": task_id,
"project_id": project_id,
"action": lock_action.name,
"user_id": user_id,
}
last_locked = await db.fetch_one(query=query, values=values)
if last_locked is None:
# We suspect there's some kind or race condition that is occasionally deleting history records
# prior to user unlocking task. Most likely stemming from auto-unlock feature. However, given that
# we're trying to update a row that doesn't exist, it's better to return without doing anything
# rather than showing the user an error that they can't fix.
# No record found, possibly a race condition or auto-unlock scenario.
return
# Calculate the duration the task was locked for
duration_task_locked = (
datetime.datetime.utcnow() - last_locked["action_date"]
)
# Cast duration to ISO format
action_text = (
(datetime.datetime.min + duration_task_locked).time().isoformat()
)
# Update the task history with the duration
update_query = """
UPDATE task_history
SET action_text = :action_text
WHERE id = :id
"""
update_values = {
"action_text": action_text,
"id": last_locked["id"],
}
await db.execute(query=update_query, values=update_values)
except MultipleResultsFound:
# Again race conditions may mean we have multiple rows within the Task History. Here we attempt to
# remove the oldest duplicate rows, and update the newest on the basis that this was the last action
# the user was attempting to make.
# Handle race conditions by removing duplicates.
await TaskHistory.remove_duplicate_task_history_rows(
task_id, project_id, lock_action, user_id, db
)
# Recursively call the method to update the remaining row
await TaskHistory.update_task_locked_with_duration(
task_id, project_id, lock_action, user_id, db
)
async def remove_duplicate_task_history_rows(
task_id: int,
project_id: int,
lock_action: TaskAction,
user_id: int,
db: Database,
):
"""
Removes duplicate task history rows for the specified task, project, and action.
Keeps the most recent entry and deletes the older ones.
"""
duplicate_query = """
DELETE FROM task_history
WHERE id IN (
SELECT id
FROM task_history
WHERE task_id = :task_id
AND project_id = :project_id
AND action = :action
AND user_id = :user_id
ORDER BY action_date ASC
OFFSET 1
)
"""
values = {
"task_id": task_id,
"project_id": project_id,
"action": lock_action.name,
"user_id": user_id,
}
await db.execute(query=duplicate_query, values=values)
@staticmethod
async def update_expired_and_locked_actions(
task_id: int,
project_id: int,
expiry_date: datetime,
action_text: str,
db: Database,
):
"""Update expired actions with an auto-unlock state."""
query = """
UPDATE task_history
SET action = CASE
WHEN action IN ('LOCKED_FOR_MAPPING', 'EXTENDED_FOR_MAPPING')
THEN 'AUTO_UNLOCKED_FOR_MAPPING'
WHEN action IN ('LOCKED_FOR_VALIDATION', 'EXTENDED_FOR_VALIDATION')
THEN 'AUTO_UNLOCKED_FOR_VALIDATION'
END,
action_text = :action_text
WHERE task_id = :task_id
AND project_id = :project_id
AND action_text IS NULL
AND action IN (
'LOCKED_FOR_MAPPING', 'LOCKED_FOR_VALIDATION',
'EXTENDED_FOR_MAPPING', 'EXTENDED_FOR_VALIDATION'
)
AND action_date <= :expiry_date
"""
values = {
"action_text": action_text,
"task_id": task_id,
"project_id": project_id,
"expiry_date": expiry_date,
}
await db.execute(query=query, values=values)
@staticmethod
async def get_all_comments(project_id: int, db: Database) -> ProjectCommentsDTO:
"""Gets all comments for the supplied project_id"""
# Raw SQL query joining task_history and users tables
query = """
SELECT
th.task_id,
th.action_date,
th.action_text,
u.username
FROM
task_history th
JOIN
users u ON th.user_id = u.id
WHERE
th.project_id = :project_id
AND th.action = :action
"""
# Execute the query with parameters
comments = await db.fetch_all(
query=query,
values={
"project_id": project_id,
"action": "COMMENT", # Assuming TaskAction.COMMENT.name is "COMMENT"
},
)
# Transform database results into DTOs
comments_dto = ProjectCommentsDTO()
for comment in comments:
dto = ProjectComment(
comment=comment["action_text"],
comment_date=comment["action_date"],
user_name=comment["username"],
task_id=comment["task_id"],
)
comments_dto.comments.append(dto)
return comments_dto
@staticmethod
async def get_last_status(
project_id: int, task_id: int, db: Database, for_undo: bool = False
) -> TaskStatus:
"""Get the status the task was set to the last time the task had a STATUS_CHANGE."""
query = """
SELECT action_text
FROM task_history
WHERE project_id = :project_id
AND task_id = :task_id
AND action = 'STATE_CHANGE'
ORDER BY action_date DESC
"""
result = await db.fetch_all(
query, values={"project_id": project_id, "task_id": task_id}
)
# If no results, return READY status
if not result:
return TaskStatus.READY
# If we only have one result and for_undo is True, return READY
if len(result) == 1 and for_undo:
return TaskStatus.READY
# If the last status was MAPPED or BADIMAGERY and for_undo is True, return READY
if for_undo and result[0]["action_text"] in [
TaskStatus.MAPPED.name,
TaskStatus.BADIMAGERY.name,
]:
return TaskStatus.READY
# If for_undo is True, return the second last status
if for_undo:
return TaskStatus[result[1]["action_text"]]
# Otherwise, return the last status
return TaskStatus[result[0]["action_text"]]
@staticmethod
async def get_last_action(project_id: int, task_id: int, db: Database):
"""Gets the most recent task history record for the task"""
query = """
SELECT * FROM task_history
WHERE project_id = :project_id AND task_id = :task_id
ORDER BY action_date DESC
LIMIT 1
"""
return await db.fetch_one(query, {"project_id": project_id, "task_id": task_id})
@staticmethod
async def get_last_action_of_type(
project_id: int, task_id: int, allowed_task_actions: list, db: Database
):
"""Gets the most recent task history record having provided TaskAction"""
query = """
SELECT id, action, action_date
FROM task_history
WHERE project_id = :project_id
AND task_id = :task_id
AND action = ANY(:allowed_actions)
ORDER BY action_date DESC
LIMIT 1
"""
values = {
"project_id": project_id,
"task_id": task_id,
"allowed_actions": tuple(allowed_task_actions),
}
result = await db.fetch_one(query=query, values=values)
return result
@staticmethod
async def get_last_locked_action(project_id: int, task_id: int, db: Database):
"""Gets the most recent task history record with locked action for the task"""
return await TaskHistory.get_last_action_of_type(
project_id,
task_id,
[
TaskAction.LOCKED_FOR_MAPPING.name,
TaskAction.LOCKED_FOR_VALIDATION.name,
],
db,
)
@staticmethod
async def get_last_locked_or_auto_unlocked_action(
task_id: int, project_id: int, db: Database
):
"""Fetch the last locked or auto-unlocked action for a task."""
query = """
SELECT action
FROM task_history
WHERE task_id = :task_id
AND project_id = :project_id
AND action IN (
'LOCKED_FOR_MAPPING',
'LOCKED_FOR_VALIDATION',
'AUTO_UNLOCKED_FOR_MAPPING',
'AUTO_UNLOCKED_FOR_VALIDATION'
)
ORDER BY action_date DESC
LIMIT 1
"""
row = await db.fetch_one(
query=query, values={"task_id": task_id, "project_id": project_id}
)
return row["action"] if row else None
@staticmethod
async def get_last_mapped_action(project_id: int, task_id: int, db: Database):
"""
Gets the most recent mapped action, if any, in the task history.
"""
query = """
SELECT * FROM task_history
WHERE project_id = :project_id
AND task_id = :task_id
AND action = 'STATE_CHANGE'
AND action_text IN ('BADIMAGERY', 'MAPPED')
ORDER BY action_date DESC
LIMIT 1
"""
last_mapped = await db.fetch_one(
query=query, values={"project_id": project_id, "task_id": task_id}
)
return last_mapped
class Task(Base):
"""Describes an individual mapping Task"""
__tablename__ = "tasks"
# Table has composite PK on (id and project_id)
id = Column(Integer, primary_key=True)
project_id = Column(
Integer, ForeignKey("projects.id"), index=True, primary_key=True
)
x = Column(Integer)
y = Column(Integer)
zoom = Column(Integer)
extra_properties = Column(Unicode)
# Tasks need to be split differently if created from an arbitrary grid or were clipped to the edge of the AOI
is_square = Column(Boolean, default=True)
geometry = Column(Geometry("MULTIPOLYGON", srid=4326))
task_status = Column(Integer, default=TaskStatus.READY.value)
locked_by = Column(
BigInteger, ForeignKey("users.id", name="fk_users_locked"), index=True
)
mapped_by = Column(
BigInteger, ForeignKey("users.id", name="fk_users_mapper"), index=True
)
validated_by = Column(
BigInteger, ForeignKey("users.id", name="fk_users_validator"), index=True
)
# Mapped objects
task_history = relationship(
TaskHistory, cascade="all", order_by=desc(TaskHistory.action_date)
)
task_annotations = relationship(TaskAnnotation, cascade="all")
lock_holder = relationship(User, foreign_keys=[locked_by])
mapper = relationship(User, foreign_keys=[mapped_by])
@classmethod
def from_geojson_feature(cls, task_id, task_feature):
"""
Constructs and validates a task from a GeoJson feature object.
:param task_id: Unique ID for the task.
:param task_feature: A geojson feature object.
:raises InvalidGeoJson, InvalidData
"""
if type(task_feature) is not geojson.Feature:
raise InvalidGeoJson("MustBeFeature - Invalid GeoJson should be a feature")
task_geometry = task_feature.geometry
if type(task_geometry) is not geojson.MultiPolygon:
raise InvalidGeoJson("MustBeMultiPolygon - Geometry must be a MultiPolygon")
if not task_geometry.is_valid:
raise InvalidGeoJson(
"InvalidMultiPolygon - " + ", ".join(task_geometry.errors())
)
task = cls()
try:
task.x = task_feature.properties["x"]
task.y = task_feature.properties["y"]
task.zoom = task_feature.properties["zoom"]
task.is_square = task_feature.properties["isSquare"]
wkt = shape(task_feature.geometry).wkt
ewkt = f"SRID=4326;{wkt}"
task.geometry = ewkt
except KeyError as e:
raise InvalidData(
f"PropertyNotFound: Expected property not found: {str(e)}"
)
if "extra_properties" in task_feature.properties:
task.extra_properties = json.dumps(
task_feature.properties["extra_properties"]
)
task.id = task_id
return task
@staticmethod
async def get(task_id: int, project_id: int, db: Database) -> Optional[dict]:
"""
Gets the specified task.
:param db: The async database connection.
:param task_id: Task ID in scope.
:param project_id: Project ID in scope.
:return: A dictionary representing the Task if found, otherwise None.
"""
query = """
SELECT
id, project_id, x, y, zoom, is_square, task_status, locked_by, mapped_by, geometry
FROM
tasks
WHERE
id = :task_id AND project_id = :project_id
LIMIT 1
"""
task = await db.fetch_one(
query, values={"task_id": task_id, "project_id": project_id}
)
return task if task else None
@staticmethod
async def exists(task_id: int, project_id: int, db: Database) -> bool:
"""
Checks if the specified task exists.
:param db: The async database connection.
:param task_id: Task ID in scope.
:param project_id: Project ID in scope.
:return: True if the task exists, otherwise False.
"""
query = """
SELECT 1
FROM tasks
WHERE id = :task_id AND project_id = :project_id
LIMIT 1
"""
task = await db.fetch_one(
query, values={"task_id": task_id, "project_id": project_id}
)
return task is not None
@staticmethod
async def get_tasks(project_id: int, task_ids: List[int], db: Database):
"""
Get all tasks that match the supplied list of task_ids for a project.
"""
query = """
SELECT id, geometry
FROM tasks
WHERE project_id = :project_id
AND id = ANY(:task_ids)
"""
values = {"project_id": project_id, "task_ids": task_ids}
rows = await db.fetch_all(query=query, values=values)
return rows
@staticmethod
async def get_all_tasks(project_id: int, db: Database):
"""
Get all tasks for a given project.
"""
query = """
SELECT id, geometry
FROM tasks
WHERE project_id = :project_id
"""
values = {"project_id": project_id}
rows = await db.fetch_all(query=query, values=values)
return rows
@staticmethod
async def get_tasks_by_status(project_id: int, status: str, db: Database):
"""
Returns all tasks filtered by status in a project.
:param project_id: The ID of the project.
:param status: The status to filter tasks by.
:param db: The database connection.
:return: A list of tasks with the specified status in the given project.
"""
query = """
SELECT *
FROM tasks
WHERE project_id = :project_id
AND task_status = :task_status
"""
values = {
"project_id": project_id,
"task_status": TaskStatus[status].value,
}
tasks = await db.fetch_all(query=query, values=values)
return tasks
@staticmethod
async def auto_unlock_delta():
return parse_duration(settings.TASK_AUTOUNLOCK_AFTER)
@staticmethod
async def auto_unlock_tasks(project_id: int, db: Database):
"""Unlock all tasks locked for longer than the auto-unlock delta."""
expiry_delta = await Task.auto_unlock_delta()
expiry_date = datetime.datetime.utcnow() - expiry_delta
# Query for task IDs to unlock
query = """
SELECT tasks.id
FROM tasks
JOIN task_history
ON tasks.id = task_history.task_id
AND tasks.project_id = task_history.project_id
WHERE tasks.task_status IN (1, 3)
AND task_history.action IN (
'EXTENDED_FOR_MAPPING',
'EXTENDED_FOR_VALIDATION',
'LOCKED_FOR_VALIDATION',
'LOCKED_FOR_MAPPING'
)
AND task_history.action_text IS NULL
AND tasks.project_id = :project_id
AND task_history.action_date <= :expiry_date
"""
old_task_ids = await db.fetch_all(
query=query, values={"project_id": project_id, "expiry_date": expiry_date}
)
old_task_ids = [row["id"] for row in old_task_ids]
if not old_task_ids:
return # No tasks to unlock
for task_id in old_task_ids:
await Task.auto_unlock_expired_tasks(task_id, project_id, expiry_date, db)
@staticmethod
async def auto_unlock_expired_tasks(
task_id: int, project_id: int, expiry_date: datetime, db: Database
):
"""Unlock all tasks locked before expiry date. Clears task lock if needed."""
lock_duration = (
(datetime.datetime.min + await Task.auto_unlock_delta()).time().isoformat()
)
await TaskHistory.update_expired_and_locked_actions(
task_id, project_id, expiry_date, lock_duration, db
)
last_action = await TaskHistory.get_last_locked_or_auto_unlocked_action(
task_id, project_id, db
)
if last_action in ["AUTO_UNLOCKED_FOR_MAPPING", "AUTO_UNLOCKED_FOR_VALIDATION"]:
await Task.clear_lock(task_id, project_id, db)
@staticmethod
def is_mappable(task: dict) -> bool:
"""Determines if task in scope is in a suitable state for mapping."""
if TaskStatus(task.task_status) not in [
TaskStatus.READY,
TaskStatus.INVALIDATED,
]:
return False
return True
@staticmethod
async def set_task_history(
task_id: int,
project_id: int,
user_id: int,
action: TaskAction,
db: Database,
comment: Optional[str] = None,
new_state: Optional[TaskStatus] = None,
mapping_issues: Optional[
List[Dict[str, Any]]
] = None, # Updated to accept a list of dictionaries
):
"""Sets the task history for the action that the user has just performed."""
# Determine action and action_text based on the task action
if action in [TaskAction.LOCKED_FOR_MAPPING, TaskAction.LOCKED_FOR_VALIDATION]:
action_name, action_text = TaskHistory.set_task_locked_action(action)
elif action in [
TaskAction.EXTENDED_FOR_MAPPING,
TaskAction.EXTENDED_FOR_VALIDATION,
]:
action_name, action_text = TaskHistory.set_task_extend_action(action)
elif action == TaskAction.COMMENT:
action_name, action_text = TaskHistory.set_comment_action(comment)
elif action == TaskAction.STATE_CHANGE and new_state:
action_name, action_text = TaskHistory.set_state_change_action(new_state)
elif action in [
TaskAction.AUTO_UNLOCKED_FOR_MAPPING,
TaskAction.AUTO_UNLOCKED_FOR_VALIDATION,
]:
action_name, action_text = TaskHistory.set_auto_unlock_action(action)
else:
raise ValueError("Invalid Action")
# Insert the task history into the task_history table
query = """
INSERT INTO task_history (task_id, user_id, project_id, action, action_text, action_date)
VALUES (:task_id, :user_id, :project_id, :action, :action_text, :action_date)
RETURNING id, action, action_text, action_date
"""
values = {
"task_id": task_id,
"user_id": user_id,
"project_id": project_id,
"action": action_name,
"action_text": action_text,
"action_date": timestamp(),
}
task_history = await db.fetch_one(query=query, values=values)
# TODO Verify this.
# Insert any mapping issues into the task_mapping_issues table, building the query dynamically
if mapping_issues:
for issue in mapping_issues:
fields = {"task_history_id": task_history["id"]}
placeholders = [":task_history_id"]
if "issue" in issue:
fields["issue"] = issue["issue"]
placeholders.append(":issue")
if "mapping_issue_category_id" in issue:
fields["mapping_issue_category_id"] = issue[
"mapping_issue_category_id"
]
placeholders.append(":mapping_issue_category_id")
if "count" in issue:
fields["count"] = issue["count"]
placeholders.append(":count")
columns = ", ".join(fields.keys())