models.py 43.6 KB
Newer Older
1
import datetime
Hypsug0's avatar
Hypsug0 committed
2
import logging
JB's avatar
JB committed
3
import os.path
Hypsug0's avatar
Uuid    
Hypsug0 committed
4
import uuid
Hypsug0's avatar
Hypsug0 committed
5

6
7
from django.conf import settings
from django.contrib.gis.db import models as gismodels
8
9
from django.contrib.gis.db.models import Union
from django.contrib.gis.geos import GEOSGeometry
Hypsug0's avatar
Hypsug0 committed
10
from django.contrib.postgres.fields import JSONField
11
from django.core.files.storage import FileSystemStorage
12
from django.core.validators import MaxValueValidator, MinValueValidator
Hypsug0's avatar
Hypsug0 committed
13
from django.db import models
Hypsug0's avatar
Hypsug0 committed
14
from django.db.models import Sum
15
from django.db.models.deletion import DO_NOTHING
Hypsug0's avatar
Hypsug0 committed
16
from django.db.models.signals import post_delete, post_save
Hypsug0's avatar
Hypsug0 committed
17
from django.dispatch import receiver
18
from django.urls import reverse
19
20
from django.utils.translation import ugettext_lazy as _

Hypsug0's avatar
Hypsug0 committed
21
from core.functions import get_sight_period
Hypsug0's avatar
Hypsug0 committed
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
from dicts.models import (
    Age,
    BiomChinspot,
    BiomDent,
    BiomEpiphyse,
    BiomEpipidyme,
    BiomGestation,
    BiomGlandCoul,
    BiomGlandTaille,
    BiomMamelle,
    BiomTesticule,
    BiomTuniqVag,
    BuildCover,
    Contact,
    CountPrecision,
    CountUnit,
    GiteBatAccess,
    Interest,
    MetaPlaceType,
    Method,
    PlaceManagementAction,
    PlacePrecision,
    PropertyDomain,
    Sex,
    Specie,
    TreeCircumstance,
    TreeContext,
    TreeForestStands,
    TreeGiteOrigin,
    TreeGitePlace,
    TreeGiteType,
    TreeHealth,
    TreeSpecies,
    TypeDevice,
    TypePlace,
)
Hypsug0's avatar
Hypsug0 committed
58
from geodata.models import LandCover, Municipality, Territory
59
from management.models import Study, Transmitter
Hypsug0's avatar
Hypsug0 committed
60

Hypsug0's avatar
Hypsug0 committed
61
62
63
logger = logging.getLogger(__name__)


Hypsug0's avatar
Hypsug0 committed
64
65
fs = FileSystemStorage()

66

67
def update_metaplace_autogeom(id_metaplace):
Hypsug0's avatar
Hypsug0 committed
68
    """Update metaplace geom when autogeom is checked
69
70
71
72
73

    :param id_metaplace:
    :return:
    """
    metaplace = MetaPlace.objects.get(id_metaplace=id_metaplace)
Hypsug0's avatar
Hypsug0 committed
74
    logger.debug("metaplace", metaplace)
75
    places = Place.objects.filter(metaplace_id=id_metaplace)
Hypsug0's avatar
Hypsug0 committed
76
    logger.debug("places {} : {}".format(len(places), places))
77
78
79
80
81
    if metaplace.autogeom:
        if len(places) == 1:
            place_geom = places.first().geom
            metaplace.geom = place_geom.buffer(0.0005)
        elif len(places) > 1:
Hypsug0's avatar
Hypsug0 committed
82
83
84
            places_collection = Place.objects.filter(metaplace_id=id_metaplace).aggregate(
                union=Union("geom")
            )
85
86
87
88
89
90
91
            if len(places) == 2:
                metaplace.geom = GEOSGeometry(places_collection["union"]).envelope
            elif len(places) > 2:
                metaplace.geom = GEOSGeometry(places_collection["union"]).convex_hull
        metaplace.save()


92
class MetaPlace(gismodels.Model):
Hypsug0's avatar
Hypsug0 committed
93
    id_metaplace = models.AutoField(primary_key=True, db_index=True)
Hypsug0's avatar
Hypsug0 committed
94
    name = models.CharField(max_length=255, db_index=True, verbose_name=_("nom du métasite"))
95
96
97
98
99
100
    type = models.ForeignKey(
        MetaPlaceType,
        db_index=True,
        blank=True,
        null=True,
        verbose_name=_("Type de métasite"),
Hypsug0's avatar
Hypsug0 committed
101
        on_delete=models.SET_NULL,
102
103
104
105
106
107
    )
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
    geom = gismodels.PolygonField(
        srid=settings.GEODATA_SRID,
        null=True,
        blank=True,
Hypsug0's avatar
Hypsug0 committed
108
        verbose_name="Enveloppe du métasite",
109
110
    )
    autogeom = models.BooleanField(
Hypsug0's avatar
Hypsug0 committed
111
112
113
114
        db_index=True,
        verbose_name="Géométrie automatiquement générée",
        default=True,
        help_text=_(
Hypsug0's avatar
Hypsug0 committed
115
116
            "La géométrie sera automatiquement générée selon les localités associés au métasite."
            " Décocher l'option pour dessiner un polygone à main levée."
Hypsug0's avatar
Hypsug0 committed
117
        ),
118
    )
Hypsug0's avatar
Hypsug0 committed
119
    extra_data = JSONField(blank=True, null=True)
120
121
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
122
    created_by = models.ForeignKey(
123
124
125
126
127
        settings.AUTH_USER_MODEL,
        null=True,
        db_index=True,
        editable=False,
        related_name="metaplace_creator",
Hypsug0's avatar
Hypsug0 committed
128
        on_delete=models.SET_NULL,
129
    )
Hypsug0's avatar
Hypsug0 committed
130
    updated_by = models.ForeignKey(
131
132
133
134
135
        settings.AUTH_USER_MODEL,
        null=True,
        db_index=True,
        editable=False,
        related_name="metaplace_modifier",
Hypsug0's avatar
Hypsug0 committed
136
        on_delete=models.SET_NULL,
137
138
139
140
141
    )

    def __str__(self):
        return "%s ∙ %s" % (self.name, self.type)

Rémy Lebrun's avatar
Rémy Lebrun committed
142
    def save(self, *args, **kwargs):
143
        # Regenerate autogeom if checked after update
Rémy Lebrun's avatar
Rémy Lebrun committed
144
        id_metaplace = self.id_metaplace
Hypsug0's avatar
Hypsug0 committed
145
        if id_metaplace is not None:
146
            places = Place.objects.filter(metaplace_id=id_metaplace)
Hypsug0's avatar
Hypsug0 committed
147
            logger.debug("places {} : {}".format(len(places), places))
148
149
150
151
152
            if self.autogeom:
                if len(places) == 1:
                    place_geom = places.first().geom
                    self.geom = place_geom.buffer(0.0005)
                elif len(places) > 1:
Hypsug0's avatar
Hypsug0 committed
153
154
155
                    places_collection = Place.objects.filter(metaplace_id=id_metaplace).aggregate(
                        union=Union("geom")
                    )
156
157
158
159
                    if len(places) == 2:
                        self.geom = GEOSGeometry(places_collection["union"]).envelope
                    elif len(places) > 2:
                        self.geom = GEOSGeometry(places_collection["union"]).convex_hull
Rémy Lebrun's avatar
Rémy Lebrun committed
160
        super(MetaPlace, self).save(*args, **kwargs)
Rémy Lebrun's avatar
Rémy Lebrun committed
161

162
163
164
    def get_absolute_url(self):
        return reverse("sights:metaplace_detail", kwargs={"pk": self.id_metaplace})

165
166
167
    # Calculate polygon centroid on the fly
    def get_centroid(self):
        c = str(self.geom.centroid)
Hypsug0's avatar
Hypsug0 committed
168
169
        c = c[c.find("(") + 1 : c.find(")")].split(" ")
        return c[1] + ";" + c[0]
170

171
172
173
    class Meta:
        verbose_name = _("Métasite")
        verbose_name_plural = _("Métasites")
174

Hypsug0's avatar
Hypsug0 committed
175

Hypsug0's avatar
Hypsug0 committed
176
class Place(models.Model):
177
    id_place = models.AutoField(primary_key=True, db_index=True)
Hypsug0's avatar
Uuid    
Hypsug0 committed
178
    uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
179
    name = models.CharField(max_length=255, db_index=True, verbose_name=_("nom du lieu"))
180
181
182
183
184
185
    metaplace = models.ForeignKey(
        MetaPlace,
        db_index=True,
        blank=True,
        null=True,
        verbose_name=_("Métasite associé"),
Hypsug0's avatar
Hypsug0 committed
186
        on_delete=models.SET_NULL,
187
    )
Hypsug0's avatar
Hypsug0 committed
188
    is_hidden = models.BooleanField(db_index=True, default=False, verbose_name="Site sensible")
189
    authorized_user = models.ManyToManyField(
190
191
192
193
194
        settings.AUTH_USER_MODEL,
        blank=True,
        related_name="hiddenplaceauthuser",
        verbose_name=_("Personnes authorisées si site sensible"),
    )
195
    type = models.ForeignKey(
Hypsug0's avatar
Hypsug0 committed
196
197
198
199
200
201
        TypePlace,
        db_index=True,
        blank=True,
        null=True,
        verbose_name=_("Type de gîte"),
        on_delete=models.SET_NULL,
202
    )
Hypsug0's avatar
Hypsug0 committed
203
204
    is_gite = models.BooleanField(db_index=True, verbose_name="Est un gîte", default=False)
    is_managed = models.BooleanField(db_index=True, default=False, verbose_name="Site géré")
Hypsug0's avatar
Hypsug0 committed
205
    proprietary = models.CharField(
206
207
208
209
210
211
212
        max_length=100,
        db_index=True,
        blank=True,
        null=True,
        verbose_name="Nom du propriétaire",
    )
    convention = models.BooleanField(verbose_name="Convention refuge", default=False)
Hypsug0's avatar
Hypsug0 committed
213
    convention_file = models.FileField(
214
215
216
217
218
        upload_to="place/convention/",
        blank=True,
        null=True,
        verbose_name="Exemplaire de la convention",
    )
219
    map_file = models.FileField(
220
221
222
223
224
        upload_to="place/map/",
        blank=True,
        null=True,
        verbose_name="Carte détaillée, topo, etc.",
    )
225
    photo_file = models.ImageField(
226
227
        upload_to="photo/", blank=True, null=True, verbose_name="Photo de la localité"
    )
Hypsug0's avatar
Hypsug0 committed
228
    habitat = models.CharField(max_length=255, blank=True, null=True, verbose_name=_("Habitat"))
229
230
231
232
233
234
235
236
237
    altitude = models.PositiveIntegerField(
        blank=True,
        null=True,
        verbose_name=_("Altitude"),
        validators=[
            MaxValueValidator(settings.GEODATA_ALTI_MAX),
            MinValueValidator(settings.GEODATA_ALTI_MIN),
        ],
    )
Hypsug0's avatar
Hypsug0 committed
238
    domain = models.ForeignKey(
239
240
        PropertyDomain,
        max_length=100,
Hypsug0's avatar
Hypsug0 committed
241
242
        on_delete=DO_NOTHING,
        null=True,
243
244
245
        blank=True,
        verbose_name=_("Domaine"),
    )
Hypsug0's avatar
Hypsug0 committed
246
    municipality = models.ForeignKey(
247
248
249
250
251
252
253
        Municipality,
        models.DO_NOTHING,
        db_index=True,
        blank=True,
        null=True,
        verbose_name=_("Commune"),
    )
Hypsug0's avatar
Hypsug0 committed
254
    territory = models.ForeignKey(
255
256
257
258
259
260
261
262
263
264
265
266
267
        Territory,
        models.SET_NULL,
        db_index=True,
        blank=True,
        null=True,
        verbose_name=_("Territoire"),
    )
    landcover = models.ForeignKey(
        LandCover,
        db_index=True,
        blank=True,
        null=True,
        verbose_name=_("Occupation du sol"),
Hypsug0's avatar
Hypsug0 committed
268
        on_delete=models.SET_NULL,
269
    )
270
    id_bdcavite = models.CharField(max_length=15, blank=True, null=True)
271
272
273
274
275
276
277
278
279
280
281
282
283
    plan_localite = models.FileField(
        upload_to="place/plan_localite/",
        blank=True,
        null=True,
        verbose_name="Plan du site et/ou topo de la cavité",
    )
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
    other_imported_data = models.TextField(
        blank=True, null=True, verbose_name=_("Autres données importées")
    )
    telemetric_crossaz = models.BooleanField(
        default=False, verbose_name=_("Croisement d 'azimuth télémétrique")
    )
284
    bdsource = models.CharField(max_length=100, blank=True, null=True)
285
    id_bdsource = models.CharField(max_length=100, blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
286
    extra_data = JSONField(blank=True, null=True)
287
288
289
    precision = models.ForeignKey(
        PlacePrecision, models.DO_NOTHING, verbose_name="Précision géographique"
    )
290
    x = models.FloatField(
291
292
293
294
295
        blank=True,
        null=True,
        verbose_name="Longitude",
        help_text=_("Coordonnées est-ouest en WGS84 (projection habituelle des gps)"),
    )
296
    y = models.FloatField(
297
298
299
300
301
302
303
304
305
306
307
308
        blank=True,
        null=True,
        verbose_name="Latitude",
        help_text=_("Coordonnées nord-sud en WGS84 (projection habituelle des gps)"),
    )
    geom = gismodels.PointField(
        srid=settings.GEODATA_SRID,
        null=True,
        blank=True,
        verbose_name="Localisation géographique",
    )
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
309
    timestamp_update = models.DateTimeField(auto_now=True, db_index=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
310
    created_by = models.ForeignKey(
311
312
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
313
        blank=True,
314
315
316
        db_index=True,
        editable=False,
        related_name="place_creator",
Hypsug0's avatar
Hypsug0 committed
317
        on_delete=models.SET_NULL,
318
    )
Hypsug0's avatar
Hypsug0 committed
319
    updated_by = models.ForeignKey(
320
321
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
322
        blank=True,
323
324
325
        db_index=True,
        editable=False,
        related_name="place_modifier",
Hypsug0's avatar
Hypsug0 committed
326
        on_delete=models.SET_NULL,
327
    )
Hypsug0's avatar
Hypsug0 committed
328
329

    def __str__(self):
Hypsug0's avatar
Hypsug0 committed
330
        return "%s (%s)" % (self.name, self.municipality)
Hypsug0's avatar
Hypsug0 committed
331

332
    def get_absolute_url(self):
333
        return reverse("sights:place_detail", kwargs={"pk": self.id_place})
Hypsug0's avatar
Hypsug0 committed
334
335

    def save(self, *args, **kwargs):
Hypsug0's avatar
Hypsug0 committed
336
337
        self.y = self.geom.x
        self.x = self.geom.y
338
        try:
339
            self.territory = Territory.objects.get(geom__contains=self.geom)
Hypsug0's avatar
Hypsug0 committed
340
341
        except Exception as e:
            logger.debug(str(e))
342
343
            pass
        try:
344
            self.municipality = Municipality.objects.get(geom__contains=self.geom)
Hypsug0's avatar
Hypsug0 committed
345
346
        except Exception as e:
            logger.debug(str(e))
347
            pass
Hypsug0's avatar
Hypsug0 committed
348
        # self.creator = current_user()
Hypsug0's avatar
Hypsug0 committed
349
350
        super(Place, self).save(*args, **kwargs)

351
    class Meta:
Hypsug0's avatar
Hypsug0 committed
352
353
        verbose_name = "Localité"
        verbose_name_plural = "Localités"
354
        unique_together = ["name", "municipality", "type"]
355

Hypsug0's avatar
Hypsug0 committed
356

357
358
class PlaceManagement(models.Model):
    id_placemanagement = models.AutoField(primary_key=True)
Hypsug0's avatar
Hypsug0 committed
359
360
361
    place = models.ForeignKey(
        Place, editable=False, related_name="management", on_delete=models.CASCADE
    )
362
    date = models.DateField(verbose_name=_("Date"))
Hypsug0's avatar
Hypsug0 committed
363
364
365
366
367
368
369
    action = models.ForeignKey(
        PlaceManagementAction,
        null=True,
        blank=True,
        verbose_name=_("Action"),
        on_delete=models.SET_NULL,
    )
370
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
371
    referent = models.ForeignKey(
Hypsug0's avatar
Hypsug0 committed
372
373
374
375
376
        settings.AUTH_USER_MODEL,
        verbose_name=_("Référent de l'action"),
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
377
378
379
380
381
382
383
    )
    file = models.FileField(
        upload_to="place/management/",
        blank=True,
        null=True,
        verbose_name=_("Fichier"),
        help_text=_(
Hypsug0's avatar
Hypsug0 committed
384
385
            "Si vous voulez charger plusieurs fichiers, créez une archive avec un logiciel de "
            "compression comme 7zip"
386
387
        ),
    )
Hypsug0's avatar
Hypsug0 committed
388
389
    bdsource = models.CharField(max_length=100, blank=True, null=True)
    id_bdsource = models.CharField(max_length=100, blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
390
    extra_data = JSONField(blank=True, null=True)
391
392
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
393
    created_by = models.ForeignKey(
394
395
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
396
        blank=True,
397
398
399
        db_index=True,
        editable=False,
        related_name="placemanagement_creator",
Hypsug0's avatar
Hypsug0 committed
400
        on_delete=models.SET_NULL,
401
    )
402
    updated_by = models.ForeignKey(
403
404
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
405
        blank=True,
406
407
408
        db_index=True,
        editable=False,
        related_name="placemanagement_modifier",
Hypsug0's avatar
Hypsug0 committed
409
        on_delete=models.SET_NULL,
410
    )
411
412
413
414
415

    def __str__(self):
        return "%s ∙ %s" % (self.date, self.action)

    def get_absolute_url(self):
416
        return reverse("sights:place_detail", kwargs={"pk": self.place_id})
417
418
419
420
421
422

    class Meta:
        verbose_name = _("Action de gestion")
        verbose_name_plural = _("Actions de gestion")


Hypsug0's avatar
Hypsug0 committed
423
424
class Bridge(models.Model):
    id_bridge = models.AutoField(primary_key=True)
Hypsug0's avatar
Hypsug0 committed
425
    place = models.ForeignKey(Place, on_delete=models.CASCADE)
Hypsug0's avatar
Hypsug0 committed
426
427
    visit_date = models.DateField()
    interest = models.ForeignKey(
Hypsug0's avatar
Hypsug0 committed
428
429
430
431
432
        Interest,
        null=True,
        blank=True,
        verbose_name="Intérêt pour les chiros",
        on_delete=models.SET_NULL,
433
434
    )
    renovated = models.NullBooleanField(verbose_name="Rénové")
Hypsug0's avatar
Hypsug0 committed
435
    renovated_date = models.DateField(null=True, blank=True, verbose_name="Date de rénovation")
436
437
438
439
440
441
442
    joint = models.NullBooleanField(verbose_name="Joints")
    rift = models.NullBooleanField(verbose_name="Fissures")
    expansion = models.NullBooleanField(verbose_name="Joints de dilatations")
    drain = models.NullBooleanField(verbose_name="Drains")
    cornice = models.NullBooleanField(verbose_name="Corniche")
    volume = models.NullBooleanField(verbose_name="Volume")
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
Hypsug0's avatar
Hypsug0 committed
443
444
    bdsource = models.CharField(max_length=100, blank=True, null=True)
    id_bdsource = models.CharField(max_length=100, blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
445
    extra_data = JSONField(blank=True, null=True)
446
447
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
448
    created_by = models.ForeignKey(
449
450
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
451
        blank=True,
452
453
454
        db_index=True,
        editable=False,
        related_name="bridge_creator",
Hypsug0's avatar
Hypsug0 committed
455
        on_delete=models.SET_NULL,
456
    )
Hypsug0's avatar
Hypsug0 committed
457
    updated_by = models.ForeignKey(
458
459
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
460
        blank=True,
461
462
463
        db_index=True,
        editable=False,
        related_name="bridge_modifier",
Hypsug0's avatar
Hypsug0 committed
464
        on_delete=models.SET_NULL,
465
    )
Hypsug0's avatar
Hypsug0 committed
466
467

    def __str__(self):
Hypsug0's avatar
Hypsug0 committed
468
        return "Pont : %s ∙ %s" % (self.place.name, self.visit_date)
Hypsug0's avatar
Hypsug0 committed
469

Hypsug0's avatar
Hypsug0 committed
470
    def get_absolute_url(self):
471
        return reverse("sights:place_detail", kwargs={"pk": self.place_id})
Hypsug0's avatar
Hypsug0 committed
472

473
    class Meta:
Hypsug0's avatar
Hypsug0 committed
474
475
        verbose_name = "Détails d'un pont"
        verbose_name_plural = "Détails des ponts"
476
        unique_together = ["visit_date", "place"]
Hypsug0's avatar
Hypsug0 committed
477
478


Hypsug0's avatar
Hypsug0 committed
479
480
class Build(models.Model):
    id_build = models.AutoField(primary_key=True)
481
    place = models.ForeignKey(Place, on_delete=models.CASCADE)
482
483
484
    visit_date = models.DateField(verbose_name="Date de visite")
    cavity_front = models.NullBooleanField(verbose_name="Cavité en façade")
    attic = models.NullBooleanField(verbose_name="Combles présents")
485
486
487
488
489
    attic_access = models.ForeignKey(
        GiteBatAccess,
        models.DO_NOTHING,
        blank=True,
        null=True,
490
491
492
493
494
        verbose_name="Accessibilité aux chiroptères",
        related_name="attic",
    )
    bell_tower = models.NullBooleanField(verbose_name="Clocher présent")
    bell_tower_screen = models.NullBooleanField(verbose_name="Clocher grillagé")
495
496
497
498
499
    bell_tower_access = models.ForeignKey(
        GiteBatAccess,
        models.DO_NOTHING,
        blank=True,
        null=True,
500
501
502
503
504
505
506
507
508
509
510
        verbose_name="Accessibilité aux chiroptères",
        related_name="belltower",
    )
    cover = models.ForeignKey(
        BuildCover,
        models.DO_NOTHING,
        blank=True,
        null=True,
        verbose_name="Type de couverture",
    )
    cellar = models.NullBooleanField(verbose_name="Cave présente")
511
512
513
514
515
    cellar_access = models.ForeignKey(
        GiteBatAccess,
        models.DO_NOTHING,
        blank=True,
        null=True,
516
517
518
519
520
521
        verbose_name="Accessibilité aux chiroptères",
        related_name="cellar",
    )
    ext_light = models.NullBooleanField(verbose_name="Eclairage extérieur")
    access_light = models.NullBooleanField(verbose_name="Entrées éclairées")
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
Hypsug0's avatar
Hypsug0 committed
522
523
    bdsource = models.CharField(max_length=100, blank=True, null=True)
    id_bdsource = models.CharField(max_length=100, blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
524
    extra_data = JSONField(blank=True, null=True)
525
526
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
527
    created_by = models.ForeignKey(
528
529
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
530
        blank=True,
531
532
533
        db_index=True,
        editable=False,
        related_name="build_creator",
Hypsug0's avatar
Hypsug0 committed
534
        on_delete=models.SET_NULL,
535
    )
Hypsug0's avatar
Hypsug0 committed
536
    updated_by = models.ForeignKey(
537
538
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
539
        blank=True,
540
541
542
        db_index=True,
        editable=False,
        related_name="build_modifier",
Hypsug0's avatar
Hypsug0 committed
543
        on_delete=models.SET_NULL,
544
    )
Hypsug0's avatar
Hypsug0 committed
545
546
547
548

    def __str__(self):
        return "Pont : %s ∙ %s" % (self.place.name, self.visit_date)

Hypsug0's avatar
Hypsug0 committed
549
    def get_absolute_url(self):
550
        return reverse("sights:place_detail", kwargs={"pk": self.place_id})
Hypsug0's avatar
Hypsug0 committed
551

Hypsug0's avatar
Hypsug0 committed
552
553
554
    class Meta:
        verbose_name = "Détails d'un pont"
        verbose_name_plural = "Détails des ponts"
555
        unique_together = ["visit_date", "place"]
Hypsug0's avatar
Hypsug0 committed
556

557

Hypsug0's avatar
Hypsug0 committed
558
class Tree(models.Model):
Hypsug0's avatar
Hypsug0 committed
559
560
561
562
563
    """

    # SubModel of place model for tree bat gites.

    """
564

Hypsug0's avatar
Hypsug0 committed
565
    id_tree = models.AutoField(primary_key=True)
566
    place = models.ForeignKey(Place, on_delete=models.CASCADE)
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
    visit_date = models.DateField(verbose_name="Date", help_text="Date de visite")
    context = models.ForeignKey(
        TreeContext,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name=_("Contexte"),
    )
    forest_stands = models.ForeignKey(
        TreeForestStands,
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        verbose_name=_("Peuplement"),
        help_text=_("Peuplement forestier"),
    )
    situation = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        verbose_name=_("Situation"),
        help_text=_("... dans le milieu (dans le bois, en lisière, etc.)"),
    )
    circumstance = models.ForeignKey(
        TreeCircumstance,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
595
596
        verbose_name=_("Circonstance"),
        help_text=_("Circonstance de la découverte"),
597
    )
Hypsug0's avatar
Hypsug0 committed
598
    tree_specie = models.ForeignKey(
599
600
601
602
603
        TreeSpecies,
        null=True,
        blank=True,
        verbose_name=_("Espèce"),
        help_text=_("Espèce de l'arbre"),
Hypsug0's avatar
Hypsug0 committed
604
        on_delete=models.SET_NULL,
605
606
607
608
609
610
611
    )
    health = models.ForeignKey(
        TreeHealth,
        null=True,
        blank=True,
        verbose_name=_("Etat"),
        help_text=_("Etat sanitaire"),
Hypsug0's avatar
Hypsug0 committed
612
        on_delete=models.SET_NULL,
613
614
615
616
617
618
619
620
621
622
    )
    tree_diameter = models.PositiveIntegerField(
        null=True,
        blank=True,
        verbose_name=_("Diamètre"),
        help_text=_("à 1.30m du sol, en cm"),
        validators=[MaxValueValidator(500)],
    )
    standing = models.NullBooleanField(verbose_name=_("Arbre debout"))
    protected = models.NullBooleanField(verbose_name=_("Arbre protégé"))
623
    bat_specie = models.ManyToManyField(
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
        Specie,
        blank=True,
        related_name="treebatspecie",
        verbose_name=_("Espèces observées"),
    )
    gite_type = models.ManyToManyField(
        TreeGiteType, blank=True, verbose_name=_("Types de gîte(s)")
    )
    gite_origin = models.ManyToManyField(
        TreeGiteOrigin, blank=True, verbose_name=_("Origines du/des gîte(s)")
    )
    gite_localisation = models.ManyToManyField(
        TreeGitePlace, blank=True, verbose_name=_("Emplacement du/des gîte(s)")
    )
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
Hypsug0's avatar
Hypsug0 committed
639
640
    bdsource = models.CharField(max_length=100, blank=True, null=True)
    id_bdsource = models.CharField(max_length=100, blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
641
    extra_data = JSONField(blank=True, null=True)
642
643
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
644
    created_by = models.ForeignKey(
645
646
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
647
        blank=True,
648
649
650
        db_index=True,
        editable=False,
        related_name="tree_creator",
Hypsug0's avatar
Hypsug0 committed
651
        on_delete=models.SET_NULL,
652
    )
Hypsug0's avatar
Hypsug0 committed
653
    updated_by = models.ForeignKey(
654
655
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
656
        blank=True,
657
658
659
        db_index=True,
        editable=False,
        related_name="tree_modifier",
Hypsug0's avatar
Hypsug0 committed
660
        on_delete=models.SET_NULL,
661
    )
662

Hypsug0's avatar
Hypsug0 committed
663
664
    def __str__(self):
        return "Arbre : %s ∙ %s" % (self.place.name, self.visit_date)
665

Hypsug0's avatar
Hypsug0 committed
666
    def get_absolute_url(self):
667
        return reverse("sights:tree_detail", kwargs={"pk": self.id_tree})
668

Hypsug0's avatar
Hypsug0 committed
669
670
671
672
    class Meta:
        verbose_name = "Détail d'un arbre"
        verbose_name_plural = "Détails des arbres"
        unique_together = ["visit_date", "place"]
673
674


Hypsug0's avatar
Hypsug0 committed
675
676
677
class TreeGite(models.Model):
    id_treegite = models.AutoField(primary_key=True)
    tree = models.ForeignKey(Tree, on_delete=models.CASCADE)
678
    bat_specie = models.ManyToManyField(
679
680
681
682
683
684
        Specie,
        blank=True,
        related_name="treegitebatspecie",
        verbose_name=_("Espèces observées"),
    )
    gite_type = models.ForeignKey(
Hypsug0's avatar
Hypsug0 committed
685
686
687
688
689
        TreeGiteType,
        null=True,
        blank=True,
        verbose_name=_("Type de gîte"),
        on_delete=models.SET_NULL,
690
691
    )
    gite_origin = models.ForeignKey(
Hypsug0's avatar
Hypsug0 committed
692
693
694
695
696
        TreeGiteOrigin,
        null=True,
        blank=True,
        verbose_name=_("Origine du gîte"),
        on_delete=models.SET_NULL,
697
698
    )
    gite_localisation = models.ForeignKey(
Hypsug0's avatar
Hypsug0 committed
699
700
701
702
703
        TreeGitePlace,
        null=True,
        blank=True,
        verbose_name=_("Emplacement du gîte"),
        on_delete=models.SET_NULL,
704
    )
705
    gite_high = models.PositiveIntegerField(
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
        null=True,
        blank=True,
        verbose_name=_("Hauteur gîte (au plus haut point d’accès)"),
    )
    gite_tree_diameter = models.DecimalField(
        max_digits=3,
        decimal_places=1,
        null=True,
        blank=True,
        verbose_name=_("Diamètre (branche, tronc) à hauteur du gîte"),
        help_text=_("en cm"),
    )
    gite_access_orientation = models.CharField(
        max_length=50,
        blank=True,
        null=True,
        verbose_name=_("Orientation du ou des accès"),
    )
    gite_access_size = models.FloatField(
        blank=True,
        null=True,
        verbose_name=_("largeur ou diamètre de l'ouverture en cm"),
    )
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
Hypsug0's avatar
Hypsug0 committed
730
731
    bdsource = models.CharField(max_length=100, blank=True, null=True)
    id_bdsource = models.CharField(max_length=100, blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
732
    extra_data = JSONField(blank=True, null=True)
733
734
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
735
    created_by = models.ForeignKey(
736
737
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
738
        blank=True,
739
740
741
        db_index=True,
        editable=False,
        related_name="treegite_creator",
Hypsug0's avatar
Hypsug0 committed
742
        on_delete=models.SET_NULL,
743
    )
Hypsug0's avatar
Hypsug0 committed
744
    updated_by = models.ForeignKey(
745
746
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
747
        blank=True,
748
749
750
        db_index=True,
        editable=False,
        related_name="treegite_modifier",
Hypsug0's avatar
Hypsug0 committed
751
        on_delete=models.SET_NULL,
752
    )
753
754

    def get_absolute_url(self):
755
        return reverse("sights:tree_detail", kwargs={"pk": self.tree_id})
756
757
758
759
760
761

    class Meta:
        verbose_name = "Détail des gîtes d'un arbre"
        verbose_name_plural = "Détails des gîtes d'un arbre"


Hypsug0's avatar
Hypsug0 committed
762
763
class Cave(models.Model):
    id_cave = models.AutoField(primary_key=True)
764
    place = models.ForeignKey(Place, on_delete=models.CASCADE)
Hypsug0's avatar
Hypsug0 committed
765
    bd_cavite = models.CharField(
766
767
768
769
770
        max_length=20,
        blank=True,
        null=True,
        verbose_name="Identifiant de la BD Cavités du BRGM",
    )
771
    visit_date = models.DateField()
772
    interest = models.ForeignKey(
Hypsug0's avatar
Hypsug0 committed
773
774
775
776
777
        Interest,
        null=True,
        blank=True,
        verbose_name="Intérêt pour les chiros",
        on_delete=models.SET_NULL,
778
    )
Hypsug0's avatar
Hypsug0 committed
779
780
781
    length = models.PositiveIntegerField(blank=True, null=True, verbose_name="Développement")
    altdiff = models.IntegerField(blank=True, null=True, verbose_name="Dénivellé vers la cavité")
    n_entry = models.PositiveIntegerField(blank=True, null=True, verbose_name="Nombre d" "entrées")
782
    equip_req = models.NullBooleanField(verbose_name="Equipement requis?")
Hypsug0's avatar
Hypsug0 committed
783
    equipment = models.TextField(blank=True, null=True, verbose_name=_("Equipement nécessaire"))
784
    access_walk_duration = models.TimeField(
785
786
787
        blank=True, null=True, verbose_name=_("Durée de la marche d'accès")
    )
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
Hypsug0's avatar
Hypsug0 committed
788
789
    bdsource = models.CharField(max_length=100, blank=True, null=True)
    id_bdsource = models.CharField(max_length=100, blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
790
    extra_data = JSONField(blank=True, null=True)
791
792
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
793
    created_by = models.ForeignKey(
794
795
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
796
        blank=True,
797
798
799
        db_index=True,
        editable=False,
        related_name="cave_creator",
Hypsug0's avatar
Hypsug0 committed
800
        on_delete=models.SET_NULL,
801
    )
Hypsug0's avatar
Hypsug0 committed
802
    updated_by = models.ForeignKey(
803
804
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
805
        blank=True,
806
807
808
        db_index=True,
        editable=False,
        related_name="cave_modifier",
Hypsug0's avatar
Hypsug0 committed
809
        on_delete=models.SET_NULL,
810
    )
811
812

    def __str__(self):
Hypsug0's avatar
Hypsug0 committed
813
        return _("Cavité : {} ∙ {}").format(self.place.name, self.visit_date)
814

Hypsug0's avatar
Hypsug0 committed
815
    def get_absolute_url(self):
816
        return reverse("sights:place_detail", kwargs={"pk": self.place_id})
Hypsug0's avatar
Hypsug0 committed
817

818
819
820
    class Meta:
        verbose_name = "Détail d'une cavité"
        verbose_name_plural = "Détails des cavités"
821
        unique_together = ["visit_date", "place"]
Hypsug0's avatar
Hypsug0 committed
822

Hypsug0's avatar
Hypsug0 committed
823

824
825
class Session(models.Model):
    id_session = models.AutoField(primary_key=True)
Hypsug0's avatar
Uuid    
Hypsug0 committed
826
    uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
827
    name = models.CharField(max_length=150, blank=True, verbose_name="Intitulé de la session")
828
    contact = models.ForeignKey(
829
830
        Contact, models.DO_NOTHING, default=10, verbose_name=_("Type de contact")
    )
Hypsug0's avatar
Hypsug0 committed
831
    place = models.ForeignKey(Place, on_delete=models.CASCADE, verbose_name=_("Localité associée"))
832
    date_start = models.DateField(
Hypsug0's avatar
Hypsug0 committed
833
        verbose_name=_("Date de début"),
834
835
        help_text=_("Format de date: <em>01/01/2017</em>."),
    )
836
    time_start = models.TimeField(
837
838
839
840
841
        blank=True,
        null=True,
        verbose_name=_("Heure de début"),
        help_text=_("Format d'heure: <em>02:15</em>."),
    )
842
    date_end = models.DateField(
843
844
845
846
847
        blank=True,
        null=True,
        verbose_name=_("Date de fin"),
        help_text=_("Format de date: <em>01/01/2017</em>."),
    )
848
    time_end = models.TimeField(
849
850
851
852
853
        blank=True,
        null=True,
        verbose_name=_("Heure de fin"),
        help_text=_("Format d'heure: <em>02:15</em>."),
    )
Hypsug0's avatar
Hypsug0 committed
854
    data_file = models.FileField(
855
856
857
        upload_to="session/file/",
        blank=True,
        null=True,
Hypsug0's avatar
Hypsug0 committed
858
859
860
        verbose_name=_(
            "Fichier de données (tableur d'analyse acoustique, fiche de terrain, etc.)"
        ),
861
    )
862
    main_observer = models.ForeignKey(
863
864
        settings.AUTH_USER_MODEL, on_delete=DO_NOTHING, related_name="mainobs"
    )
865
    other_observer = models.ManyToManyField(
866
867
        settings.AUTH_USER_MODEL, blank=True, related_name="otherobs"
    )
Hypsug0's avatar
Hypsug0 committed
868
    is_confidential = models.BooleanField(default=False, verbose_name=_("Données confidentielles"))
869
870
871
    study = models.ForeignKey(
        Study,
        models.DO_NOTHING,
872
873
        verbose_name="Etude",
        related_name="study",
874
        blank=True,
875
876
        null=True,
    )
Hypsug0's avatar
Hypsug0 committed
877
878
879
880
881
882
883
884
    # dataset = models.ForeignKey(
    #     "metadata.Dataset",
    #     models.DO_NOTHING,
    #     verbose_name="Jeu de données",
    #     related_name="dataset",
    #     blank=True,
    #     null=True,
    # )
885
    comment = models.TextField(blank=True, null=True, verbose_name=_("Commentaire"))
Hypsug0's avatar
Hypsug0 committed
886
887
    bdsource = models.CharField(max_length=100, blank=True, null=True)
    id_bdsource = models.TextField(blank=True, null=True)
Hypsug0's avatar
Hypsug0 committed
888
    extra_data = JSONField(blank=True, null=True)
889
890
    timestamp_create = models.DateTimeField(auto_now_add=True, editable=False)
    timestamp_update = models.DateTimeField(auto_now=True, editable=False)
Hypsug0's avatar
Hypsug0 committed
891
    created_by = models.ForeignKey(
892
893
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
894
        blank=True,
895
896
897
        db_index=True,
        editable=False,
        related_name="session_creator",
Hypsug0's avatar
Hypsug0 committed
898
        on_delete=models.SET_NULL,
899
    )
Hypsug0's avatar
Hypsug0 committed
900
    updated_by = models.ForeignKey(
901
902
        settings.AUTH_USER_MODEL,
        null=True,
Hypsug0's avatar
Hypsug0 committed
903
        blank=True,
904
905
906
        db_index=True,
        editable=False,
        related_name="session_modifier",
Hypsug0's avatar
Hypsug0 committed
907
        on_delete=models.SET_NULL,
908
    )
909

JB's avatar
JB committed
910
    @property
JB's avatar
JB committed
911
    def data_filename(self):
JB's avatar
JB committed
912
913
        return os.path.basename(self.data_file.name)

914
    def __str__(self):
915
        return "%s ∙ %s ∙ %s" % (
916
            self.place,
Hypsug0's avatar
Hypsug0 committed
917
            datetime.date(self.date_start.year, self.date_start.month, self.date_start.day),
918
919
            self.contact,
        )
Hypsug0's avatar
Hypsug0 committed
920
921

    def save(self, *args, **kwargs):
922
923
        self.name = "loc%s %s %s %s" % (
            self.place_id,
Hypsug0's avatar
Hypsug0 committed
924
            datetime.date(self.date_start.year, self.date_start.month, self.date_start.day),
925
926
927
            self.contact.code,
            self.main_observer.username,
        )
Hypsug0's avatar
Hypsug0 committed
928
929
        super(Session, self).save(*args, **kwargs)

930
    def get_absolute_url(self):
931
        return reverse("sights:session_detail", kwargs={"pk": self.id_session})
932

933
    class Meta:
Hypsug0's avatar
Hypsug0 committed
934
935
        verbose_name = "Session d'inventaire/observations"
        verbose_name_plural = "Sessions d'inventaire/observations"
936
        unique_together = ["place", "contact", "date_start"]
937

Hypsug0's avatar
Hypsug0 committed
938

Hypsug0's avatar
Hypsug0 committed
939
940
941
942
943
class SessionLink(models.Model):
    id_session_link = models.AutoField(verbose_name=_("id unique"), primary_key=True)
    type_link = models.ForeignKey(
        "dicts.LinkType", on_delete=models.DO_NOTHING, verbose_name=_("Type de lien")
    )
Hypsug0's avatar
Hypsug0 committed
944
    link = models.URLField(null=False, verbose_name=_("Hyperlien"), help_text=_("http(s)://..."))
Hypsug0's avatar
Hypsug0 committed
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
    comment = models.CharField(
        max_length=500, null=True, blank=True, verbose_name=_("Commentaire")
    )
    session = models.ForeignKey(
        Session,
        on_delete=models.CASCADE,
        related_name="session_link_related",
        related_query_name="session_links",
    )

    class Meta:
        unique_together = [["link", "session"]]

    def __str__(self):
        return f"{self.type_link.label}{self.link}"

    def get_absolute_url(self):
        return reverse("sights:session_detail", kwargs={"pk": self.session.pk})


Hypsug0's avatar
Hypsug0 committed
965
class Sighting(models.Model):
966
    id_sighting = models.AutoField(_("id unique"), primary_key=True)
Hypsug0's avatar
Uuid    
Hypsug0 committed
967
    uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
968
    session = models.ForeignKey(
969
970
971
972
973
        Session, on_delete=models.CASCADE, verbose_name=_("Session associée")
    )
    period = models.CharField(
        max_length=50, blank=True, null=True, verbose_name=_("Période d'observation")
    )
974
    codesp = models.ForeignKey(
975
976
977
978
979
980
981
982
983
        Specie, on_delete=DO_NOTHING, verbose_name=_("Espèce ou groupe d'espèce")
    )
    total_count = models.PositiveIntegerField(
        "Nombre total",
        blank=True,
        null=True,
        help_text=_("Désactivé pour les données acoustiques et en main"),
    )
    breed_colo = models.NullBooleanField(verbose_name="Colonie de reproduction")
984
    observer = models.ForeignKey(
985
        settings.AUTH_USER_MODEL,
Hypsug0's avatar
Hypsug0 committed
986
987
        blank=True,
        null=True,
988
989
        related_name="sightingobs",
        verbose_name=_("Observateur"),