summaryrefslogtreecommitdiff
path: root/ishtar_common/tasks.py
blob: 631996684af8b4ebc576a2e30479a44601bb8602 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2013-2019 Étienne Loks  <etienne.loks_AT_peacefrogsDOTnet>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# See the file COPYING for details.

import datetime

import os
import sys

from django.conf import settings
from django.core.files import File
from django.db.models import Q

from ishtar_common.models import Town, Department
from ishtar_common.utils import task
from ishtar_common.serializers import full_serialization

from archaeological_operations.models import Operation, ArchaeologicalSite
from archaeological_context_records.models import ContextRecord
from archaeological_finds.models import Find
from archaeological_warehouse.models import Warehouse

from archaeological_operations.views import get_operation, get_site
from archaeological_context_records.views import get_contextrecord
from archaeological_finds.views import get_find
from archaeological_warehouse.views import get_warehouse


@task()
def launch_export(export_task):
    if export_task.state != 'S':
        return
    export_task.launch_date = datetime.datetime.now()
    export_task.state = 'P'
    export_task.save()

    kwargs = {}
    if export_task.filter_type and export_task.filter_text:
        query = {"search_vector": export_task.filter_text}
        kwargs["info"] = {"query": {"filter": export_task.filter_text}}
        if export_task.filter_type == "O":
            kwargs["info"]["query"]["model"] = "Operation"
            ids = list(
                get_operation(
                    None, query=query, return_query=True).values_list(
                    "id", flat=True))
            kwargs["operation_queryset"] = Operation.objects.filter(pk__in=ids)
        elif export_task.filter_type == "S":
            kwargs["info"]["query"]["model"] = "ArchaeologicalSite"
            ids = list(get_site(
                None, query=query, return_query=True).values_list(
                "id", flat=True))
            kwargs["site_queryset"] = ArchaeologicalSite.objects.filter(
                pk__in=ids)
        elif export_task.filter_type == "CR":
            kwargs["info"]["query"]["model"] = "ArchaeologicalSite"
            ids = list(get_contextrecord(
                None, query=query, return_query=True).values_list(
                "id", flat=True))
            kwargs["cr_queryset"] = ContextRecord.objects.filter(pk__in=ids)
        elif export_task.filter_type == "F":
            kwargs["info"]["query"]["model"] = "Find"
            ids = list(get_find(
                None, query=query, return_query=True
            ).values_list("id", flat=True))
            kwargs["find_queryset"] = Find.objects.filter(pk__in=ids)
        elif export_task.filter_type == "W":
            kwargs["info"]["query"]["model"] = "Warehouse"
            ids = list(get_warehouse(
                None, query=query, return_query=True
            ).values_list("id", flat=True))
            kwargs["warehouse_queryset"] = Warehouse.objects.filter(pk__in=ids)
    if not export_task.geo:
        kwargs["no_geo"] = True
    archive_name = full_serialization(**kwargs)
    result = open(archive_name, "rb")
    export_task.result.save(archive_name.split(os.sep)[-1], File(result))
    os.remove(archive_name)
    export_task.finished_date = datetime.datetime.now()
    export_task.state = 'F'
    export_task.save()


def load_towns():
    # TODO: remove?
    from geodjangofla.models import Commune
    q = None
    for dpt_number in settings.ISHTAR_DPTS:
        query = Q(insee_com__istartswith=dpt_number)
        if q:
            q = q | query
        else:
            q = query
    if q:
        q = Commune.objects.filter(q)
    else:
        q = Commune.objects
    nb, updated = 0, 0
    for town in q.all():
        surface = town.superficie or 0
        surface = surface * 10000
        defaults = {'name':town.nom_comm, 'surface':surface,
                    'center':town.centroid}
        town, created = Town.objects.get_or_create(numero_insee=town.insee_com,
                                   defaults=defaults)
        if created:
            nb += 1
        else:
            updated += 1
            for k in defaults:
                setattr(town, k, defaults[k])
            town.save()
    return nb, updated

def update_towns():
    # TODO: remove?
    nb, updated = 0, 0
    dpts = dict([(dpt.number, dpt) for dpt in Department.objects.all()])
    q = Town.objects.filter(numero_insee__isnull=False)
    total = q.count()
    for idx, town in enumerate(q.all()):
        sys.stdout.write('\rProcessing... %s/%d' % (
                                str(idx+1).zfill(len(str(total))), total))
        if len(town.numero_insee) < 2:
            continue
        dpt_code = town.numero_insee[:2]
        if dpt_code.startswith('9') and int(dpt_code) > 95:
            dpt_code = town.numero_insee[:3]
        if dpt_code not in dpts:
            sys.stdout.write('Missing department with INSEE code: %s' % dpt_code)
            continue
        if town.departement == dpts[dpt_code]:
            continue
        if town.departement:
            updated += 1
        else:
            nb += 1
        town.departement = dpts[dpt_code]
        town.save()
    sys.stdout.write('\n')
    return nb, updated