-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
458 lines (372 loc) · 15.6 KB
/
models.py
File metadata and controls
458 lines (372 loc) · 15.6 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
# pyright: reportUninitializedInstanceVariable=false
import typing
import ulid
from django.contrib.gis.db import models as gis_models
from django.db import models
from django.db.models import ExpressionWrapper, Q
from django.db.models.expressions import Value
from django.db.models.functions import Concat, Lower
from django.utils.translation import gettext_lazy
from django_choices_field import IntegerChoicesField
from apps.common.models import ArchivableResource, CommonAsset, FirebasePushStatusEnum, FirebaseResource, UserResource
from apps.contributor.models import ContributorTeam
from utils.fields import validate_percentage
if typing.TYPE_CHECKING:
from apps.tutorial.models import Tutorial
class ProjectTypeEnum(models.IntegerChoices):
FIND = 1, "Find"
""" Find project type. Previously known as Classification / Build Area. """
VALIDATE = 2, "Validate"
""" Validate project type. Previously known as Footprint """
VALIDATE_IMAGE = 10, "Validate Image"
""" Validate image project type. """
COMPARE = 3, "Compare"
""" Compare project type. Previously known as Change Detection. """
COMPLETENESS = 4, "Completeness"
""" Completeness project type. """
# MEDIA = 5, "Media"
# DIGITIZATION = 6, "Digitization"
# STREET = 7, "Street"
# TODO(thenav56): Confirm if we have more/less
@classmethod
def get_display(cls, value: typing.Self | int) -> str:
if value in cls:
return str(cls(value).label)
return "Unknown"
class ProjectStatusEnum(models.IntegerChoices):
DRAFT = 10, "Draft"
"""
Background processes and validations will not be triggered for a "Draft" project.
"""
MARKED_AS_READY = 20, "Marked as Ready"
"""
Background processes and validations will be triggered
once a project is "Marked as Ready".
"""
FAILED = 30, "Failed"
"""
If there are validation errors or issues with background processes,
then creation of project has "Failed"
"""
READY = 40, "Ready"
"""
If there are no validation errors or issues with background processes,
then the project is "Ready"
These projects are not be yet visible to the contributors.
"""
PUBLISHED = 50, "Published"
"""
"Published" projects is be visible to the contributors.
"""
PAUSED = 60, "Paused"
"""
"Paused" projects are visible to the contributors.
"Paused" projects can be "un-paused".
"""
ARCHIVED = 70, "Archived"
"""
"Archived" projects are not visible to the contributors.
"Archived" projects cannot be "un-archived".
"""
DISCARDED = 80, "Discarded"
"""
"Discarded" projects are not visible to the contributors.
"Discarded" projects cannot be "un-discarded".
"""
class ProjectProcessingStatusEnum(models.IntegerChoices):
PREPARING = 10, "Preparing"
VALIDATING_GEOMETRY = 20, "Validating Geometry"
GENERATING_GROUPS_AND_TASKS = 30, "Generating groups and tasks"
ANALYZING_GROUPS_AND_TASK = 40, "Analyzing groups and tasks"
GENERATING_TASKS_GEOJSON = 50, "Generating GeoJSON from tasks"
COMPLETED = 60, "Processing Completed"
class UploadHelper:
@staticmethod
def project_asset(instance: "ProjectAsset", filename: str):
return f"project/{instance.project_id}/asset/{instance.type}/{ulid.ULID()!s}/{filename}"
@staticmethod
# FIXME: This is not be used anymore
def project_image(instance: "Project", filename: str):
return f"project/{instance.pk}/image/{filename}"
class Organization(UserResource, ArchivableResource): # type: ignore[reportIncompatibleVariableOverride]
name = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
abbreviation = models.CharField(max_length=50, null=True, blank=True)
# TODO(Rup-Narayan-Rajbanshi): Add icon?
unique_name = models.GeneratedField( # type: ignore[reportAttributeAccessIssue]
expression=Lower("name"),
output_field=models.CharField(),
db_persist=True,
unique=True,
)
# FIREBASE FIELDS
firebase_push_status: int | None = IntegerChoicesField( # type: ignore[reportAssignmentType]
choices_enum=FirebasePushStatusEnum,
null=True,
blank=True,
)
firebase_last_pushed = models.DateTimeField(
null=True,
blank=True,
help_text=gettext_lazy("The latest time when organization was pushed to firebase"),
)
@typing.override
def __str__(self) -> str:
return self.name
def update_firebase_push_status(self, firebase_push_status: FirebasePushStatusEnum, *, commit: bool = True):
self.firebase_push_status = firebase_push_status
if commit:
self.save(update_fields=("firebase_push_status",))
class Project(UserResource, FirebaseResource): # type: ignore[reportIncompatibleVariableOverride]
Type = ProjectTypeEnum
Status = ProjectStatusEnum
ProcessingStatus = ProjectProcessingStatusEnum
project_type: int = IntegerChoicesField( # type: ignore[reportAssignmentType]
choices_enum=ProjectTypeEnum,
)
requesting_organization: Organization = models.ForeignKey( # type: ignore[reportAssignmentType]
Organization,
on_delete=models.PROTECT,
related_name="+",
help_text=gettext_lazy("Which group, institution or community is requesting this project?"),
)
# TODO(tnagorra): Do we also store project topic, region and number?
# TODO(tnagorra): Do we add uniqueness on project topic?
# Generate in manager dashboard based on topic, region, project number, requesting org
topic = models.CharField(max_length=255)
region = models.CharField(max_length=255)
project_number = models.PositiveIntegerField()
# TODO(tnagorra): Max length is 25 in manager dashboard.
# TODO(frozenhelium): We should discuss if we need this field.
look_for = models.CharField(
max_length=255,
help_text=gettext_lazy("What should the users look for (e.g. buildings, cars, trees)"),
)
additional_info_url = models.CharField(
null=True,
blank=True,
help_text=gettext_lazy("Provide an optional link to a resource with additional information on the project"),
) # NOTE: manual_url before
# TODO(tnagorra): Max length is 10000 in manager dashboard.
# TODO(tnagorra): This should be required.
# NOTE: Markdown syntax is supported.
description = models.TextField(
null=True,
blank=True,
) # NOTE: project_details before
# NOTE: JPG and PNG should be supported.
image: "ProjectAsset | None" = models.ForeignKey( # type: ignore[reportAssignmentType]
"project.ProjectAsset",
related_name="+",
blank=True,
null=True,
on_delete=models.SET_NULL,
)
# FIXME(tnagorra): We might need to rename this field
# NOTE: The tutorial should align with what we are looking for.
tutorial: "Tutorial" = models.ForeignKey( # type: ignore[reportAssignmentType]
"tutorial.Tutorial",
null=True, # NOTE: Validation makes sure active project have tutorial attached
blank=True,
on_delete=models.PROTECT,
related_name="+",
help_text=gettext_lazy("Tutorial used for this project."),
) # NOTE: tutorial_id before
# TODO(tnagorra): This should be an integer from 3 to 10000
verification_number = models.PositiveSmallIntegerField(
help_text=gettext_lazy("How many people do you want to see every tile before you consider it finished?"),
default=3,
)
# TODO(tnagorra): This should be an integer from 10 to 25
group_size = models.PositiveSmallIntegerField(
help_text=gettext_lazy(
"How big should a mapping session be? Group size refers to the number of tasks per mapping session.",
),
default=10,
)
# TODO(tnagorra): This should be an integer from 10 to 250
# TODO(tnagorra): Empty indicates that no limit is set. But, this field is required in manager dashboard.
max_tasks_per_user = models.PositiveSmallIntegerField(
help_text=gettext_lazy("How many tasks each user is allowed to work on for this project"),
null=True,
blank=True,
default=10,
)
# TODO(tnagorra): Currently this field collects any data not stored by another fields, pulled from firebase.
# Also, used in SQL queries
project_type_specifics = models.JSONField(blank=True, null=True)
project_type_specific_output: "ProjectAsset | None" = models.ForeignKey( # type: ignore[reportAssignmentType]
"project.ProjectAsset",
related_name="+",
blank=True,
null=True,
on_delete=models.SET_NULL,
)
# TODO(thenav56): Use srid=4326?
centroid = gis_models.PointField(blank=True, null=True)
# STATUS
is_featured = models.BooleanField(default=False)
status: int = IntegerChoicesField( # type: ignore[reportAssignmentType]
choices_enum=ProjectStatusEnum,
default=ProjectStatusEnum.DRAFT,
)
processing_status: int = IntegerChoicesField( # type: ignore[reportAssignmentType]
choices_enum=ProjectProcessingStatusEnum,
null=True,
blank=True,
)
# TEAM
# NOTE: If any team is attached to the project, then project should only visible to the team members.
team: ContributorTeam | None = models.OneToOneField( # type: ignore[reportAssignmentType]
ContributorTeam,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="+",
)
is_private = models.GeneratedField(
expression=ExpressionWrapper(
Q(team__isnull=False),
output_field=models.BooleanField(),
),
output_field=models.BooleanField(),
db_persist=True,
help_text=gettext_lazy(
"If the project is private, then it is only visible to the team members.",
),
)
# CALCULATED FIELDS
progress = models.PositiveSmallIntegerField(default=0, validators=[validate_percentage])
required_results = models.IntegerField(default=0)
result_count = models.IntegerField(default=0) # NOTE: All project have 0 in production database
# Type hints
requesting_organization_id: int
tutorial_id: int | None
image_id: int | None
team_id: int | None
project_type_specific_output_id: int | None
class Meta: # type: ignore[reportIncompatibleVariableOverride]
constraints = [
models.UniqueConstraint(
Lower("topic"),
Lower("region"),
"project_number",
"requesting_organization",
name="unique_project_name",
violation_error_message=gettext_lazy(
"A project with the same topic, region, project number and requesting organization already exists.",
),
),
]
@typing.override
def __str__(self) -> str:
return self.generate_name()
def generate_name(self) -> str:
"""
Returns a generated name for the project based on topic, region and project number.
Use select_related to avoid N+1 queries.
"""
# Format: "{topic} - {region} ({project_number}) {requesting_organization.name}"
return f"{self.topic} - {self.region} ({self.project_number}) {self.requesting_organization.name}"
@staticmethod
def generate_name_query(prefix: str = ""):
"""
Returns a Django QuerySet expression to generate the project name.
"""
return Concat(
models.F(f"{prefix}topic"),
Value(" - "),
models.F(f"{prefix}region"),
Value(" ("),
models.F(f"{prefix}project_number"),
Value(") "),
models.F(f"{prefix}requesting_organization__name"),
output_field=models.CharField(),
)
def update_status(self, status: ProjectStatusEnum, commit: bool = True):
self.status = status
if commit:
self.save(update_fields=("status",))
def update_processing_status(self, status: ProjectProcessingStatusEnum, commit: bool = True):
self.processing_status = status
if commit:
self.save(update_fields=("processing_status",))
@property
def project_type_enum(self):
return ProjectTypeEnum(self.project_type)
@property
def status_enum(self):
return ProjectStatusEnum(self.status)
@typing.override
def clean(self):
...
# if not self.teamId:
# self.status = "inactive" # this is a public project
# else:
# self.status = (
# "private_inactive" # private project visible only for team members
# )
#
# if max_tasks_per_user is not None:
# self.maxTasksPerUser = int(max_tasks_per_user)
# for group in self.groups.values():
# group.requiredCount = self.verificationNumber
# self.requiredResults += group.requiredCount * group.numberOfTasks
class ProjectAsset(UserResource, CommonAsset): # type: ignore[reportIncompatibleVariableOverride]
project: Project = models.ForeignKey( # type: ignore[reportAssignmentType]
Project,
on_delete=models.CASCADE,
related_name="+",
)
file = models.FileField(
upload_to=UploadHelper.project_asset,
help_text=gettext_lazy("The file associated with the asset"),
)
# Type hints
project_id: int
class ProjectTaskGroup(models.Model):
# FIXME(tnagorra): We might need to skip the indexing
old_id = models.CharField(max_length=30, db_index=True, null=True)
legacy_group_id = models.CharField(max_length=30, db_index=True)
project: Project = models.ForeignKey( # type: ignore[reportAssignmentType]
Project,
on_delete=models.CASCADE,
related_name="+",
)
number_of_tasks = models.IntegerField()
required_count = models.IntegerField()
finished_count = models.IntegerField(default=0)
progress = models.PositiveSmallIntegerField(default=0, validators=[validate_percentage])
# TODO(thenav56): Currently this field collects any data not stored by another fields, pulled from firebase.
# Also, used in SQL queries
# FIXME(thenav56): Refactor this
project_type_specifics = models.JSONField()
# NOTE: Used by Community Dashboard
total_area = models.FloatField(null=True, default=None)
time_spent_max_allowed = models.FloatField(null=True, default=None)
# Type hints
project_id: int
@typing.override
def __str__(self):
return f"(project={self.project_id}, id={self.pk})"
class ProjectTask(models.Model):
# FIXME(tnagorra): We might need to skip the indexing
old_id = models.CharField(max_length=30, db_index=True, null=True)
legacy_task_id = models.CharField(max_length=30, db_index=True)
task_group: ProjectTaskGroup = models.ForeignKey( # type: ignore[reportAssignmentType]
ProjectTaskGroup,
on_delete=models.CASCADE,
related_name="+",
)
# NOTE(tnagorra): The geometry is only necessary for validate project type
# FIXME(thenav56): Existing gid_models.MultiPolygonField(srid=4326, blank=True, null=True)
geometry = gis_models.GeometryField(null=True, blank=True, default=None, dim=2)
# TODO(thenav56): Currently this field collects any data not stored by another fields, pulled from firebase.
# Also, used in SQL queries
# FIXME(thenav56): Refactor this
project_type_specifics = models.JSONField()
# Type hints
task_group_id: int
@typing.override
def __str__(self):
return f"task_group_id={self.task_group_id}, id={self.pk}"