aboutsummaryrefslogtreecommitdiffstats
path: root/server/views.py
blob: 0954a1f0926f2d56069b802c07f66627fdd6d29a (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
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
from django.shortcuts import render
from client.models import UserCode, Keys, DocumentType, Document, KeyVal
from django.contrib.auth.models import Group, Permission, User
from django.db.models import Q
from django.http import HttpResponseRedirect, FileResponse
from django.db.models.deletion import ProtectedError
from django.template.loader import get_template
from django.conf import settings

import dateparser
from datetime import datetime
from datetime import timedelta
import pytz
import pdfkit
from io import BytesIO

# Create your views here.


def index(request):
    context = {}
    if (request.user.is_staff):
        parent_group = request.user.groups.values_list('name', flat=True)[
            0]
        users = User.objects.filter(groups__name=parent_group)
        users_out = []
        for user in users:
            code = ""
            if len(UserCode.objects.filter(user=user)) > 0:
                code = 'U' + str(UserCode.objects.filter(user=user)[0].code)
            status = ""
            if user.is_staff:
                status = "Staff"
            elif user.has_perm("client.approved"):
                status = "Attivo"
            else:
                status = "In attesa"
            users_out.append([user.username, user.first_name,
                        user.last_name, code, status])

        parent_group = request.user.groups.values_list('name', flat=True)[
            0]
        group = Group.objects.get(name=parent_group)
        public_types = DocumentType.objects.filter(
            Q(group_private=False) | Q(group=group) & Q(enabled=True))
        docs = []
        for doc in public_types:
            ref_docs = Document.objects.filter(document_type=doc)
            docs.append([doc, len(ref_docs)])

        context = {
            'docs': docs,
            'users': users_out,
            }
        return render(request, 'server/index.html', context)
    else:
        return render(request, 'client/index.html', context)


def uapprove(request):
    context = {}
    if (request.user.is_staff):
        data = []
        if request.method == "POST":
            parent_group = request.user.groups.values_list('name', flat=True)[
                0]
            group = Group.objects.get(name=parent_group)
            permission = Permission.objects.get(codename='approved')
            data = request.POST["codes"]
            data.replace("\r", "")
            data = data.split("\n")
            for i in range(len(data)):
                if not data[i].startswith("U"):
                    data[i] = data[i] + " - Formato errato"
                elif not data[i][1:].isdigit():
                    data[i] = data[i] + " - Formato errato"
                elif int(data[i][1:]) < 100000 or int(data[i][1:]) > 999999:
                    data[i] = data[i] + " - Formato errato"
                elif len(UserCode.objects.filter(code=data[i][1:])) == 0:
                    data[i] = data[i] + " - Invalido"
                else:
                    user = UserCode.objects.filter(code=data[i][1:])[0].user
                    if len(user.groups.values_list('name', flat=True)) == 0:
                        user.groups.add(group)
                        user.user_permissions.add(permission)
                        data[i] = data[i] + " - Ok"
                    else:
                        if user.groups.values_list('name', flat=True)[0] == parent_group:
                            user.user_permissions.add(permission)
                            data[i] = data[i] + " - Ok"
                        else:
                            user.groups.clear()
                            user.groups.add(group)
                            user.user_permissions.add(permission)
                            data[i] = data[i] + " - Ok, cambio branca"

        context = {
            'messages': data,
            'empty': len(data) == 0,
        }

        return render(request, 'server/approve_user.html', context)
    else:
        return render(request, 'client/index.html', context)


def docapprove(request):
    context = {}
    if (request.user.is_staff):
        data = []
        if request.method == "POST":
            data = request.POST["codes"]
            data.replace("\r", "")
            data = data.split("\n")
            for i in range(len(data)):
                if not data[i].isdigit():
                    data[i] = data[i] + " - Formato errato"
                elif int(data[i]) < 100000 or int(data[i]) > 999999:
                    data[i] = data[i] + " - Formato errato"
                elif len(Document.objects.filter(code=data[i])) == 0:
                    data[i] = data[i] + " - Invalido"
                else:
                    document = Document.objects.filter(code=data[i])[0]
                    if document.status == 'ok':
                        data[i] = data[i] + " - Già approvato"
                    else:
                        document.status = 'ok'
                        document.save()
                        data[i] = data[i] + " - Ok"

        context = {
            'messages': data,
            'empty': len(data) == 0,
        }

        return render(request, 'server/approve_doc.html', context)
    else:
        return render(request, 'client/index.html', context)


def ulist(request):
    context = {}
    if (request.user.is_staff):
        parent_group = request.user.groups.values_list('name', flat=True)[0]
        group = Group.objects.get(name=parent_group)
        if request.method == "POST":
            if request.POST["action"][0] == 'f':
                document = Document.objects.get(id=request.POST["action"][1:])
                if document.group == group:
                    template = get_template('server/download_doc.html')
                    doc = [document, KeyVal.objects.filter(container=document), document.personal_data, document.medical_data, parent_group]
                    context = {'doc': doc}
                    html = template.render(context)
                    pdf = pdfkit.from_string(html, False)
                    result = BytesIO(pdf)
                    result.seek(0)

                    return FileResponse(result, as_attachment=True, filename=document.user.username+"_"+document.document_type.name+".pdf")
        users = User.objects.filter(groups__name=parent_group).order_by("first_name")
        out = []
        for user in users:
            usercode = UserCode.objects.filter(user=user)[0]
            documents = Document.objects.filter(Q(user=user) & ~Q(status='archive'))
            out.append([user, usercode, parent_group, documents])
        context = {'users': out}
        return render(request, 'server/user_list.html', context)
    else:
        return render(request, 'client/index.html', context)


def doctype(request):
    context = {}
    if request.user.is_staff:
        error = False
        error_text = ""

        public = True
        selfsign = True
        hidden = False
        personal = True
        medic = True
        custom = True
        message = True
        group_bool = True
        public_check = 'checked="checked"'
        selfsign_check = 'checked="checked"'
        hidden_check = 'checked="checked"'
        personal_check = 'checked="checked"'
        medic_check = 'checked="checked"'
        custom_check = 'checked="checked"'
        message_check = 'checked="checked"'
        group_check = 'checked="checked"'
        if request.method == "POST":
            selected = []
            parent_groups = request.user.groups.values_list('name', flat=True)
            for i in request.POST.keys():
                if i.isdigit():
                    docc = DocumentType.objects.get(id=i)
                    if docc.group.name in parent_groups:
                        selected.append(docc)

            for i in selected:
                if request.POST["action"] == 'delete':
                    try:
                        i.delete()
                    except ProtectedError:
                        error = True
                        error_text = "Non puoi eliminare un tipo a cui é collegato uno o piú documenti"
                elif request.POST["action"] == 'hide':
                    i.enabled = False
                    i.save()
                elif request.POST["action"] == 'show':
                    i.enabled = True
                    i.save()

            public = "filter_public" in request.POST
            selfsign = "filter_selfsign" in request.POST
            hidden = "filter_hidden" in request.POST
            personal = "filter_personal" in request.POST
            medic = "filter_medic" in request.POST
            custom = "filter_custom" in request.POST
            message = "filter_message" in request.POST
            group_bool = "filter_group" in request.POST

            if request.POST["action"] == 'clear':
                public = True
                selfsign = True
                hidden = False
                personal = True
                medic = True
                custom = True
                message = True
                group_bool = True

        parent_group = request.user.groups.values_list('name', flat=True)[
            0]
        group = Group.objects.get(name=parent_group)
        public_types = DocumentType.objects.filter(
            Q(group_private=False) | Q(group=group))
        if not public:
            public_types = public_types.filter(group_private=True)
            public_check = ""
        if not selfsign:
            public_types = public_types.filter(auto_sign=False)
            selfsign_check = ""
        if not hidden:
            public_types = public_types.filter(enabled=True)
            hidden_check = ""
        if not personal:
            public_types = public_types.filter(personal_data=False)
            personal_check = ""
        if not medic:
            public_types = public_types.filter(medical_data=False)
            medic_check = ""
        if not custom:
            public_types = public_types.filter(custom_data=False)
            custom_check = ""
        if not message:
            public_types = public_types.filter(custom_message=False)
            message_check = ""
        if not group_bool:
            public_types = public_types.filter(custom_group=False)
            group_check = ""

        out = []
        for doc in public_types:
            custom_keys = Keys.objects.filter(container=doc)
            ref_docs = Document.objects.filter(document_type=doc)
            out.append([doc, custom_keys, len(ref_docs)])

        context = {
            'docs': out,
            'public_check': public_check,
            'selfsign_check': selfsign_check,
            'hidden_check': hidden_check,
            'personal_check': personal_check,
            'medic_check': medic_check,
            'custom_check': custom_check,
            'message_check': message_check,
            'group_check': group_check,
            'error': error,
            'error_text': error_text,
            }
        return render(request, 'server/doc_type.html', context)
    else:
        return render(request, 'client/index.html', context)


def doccreate(request):
    context = {}
    if request.user.is_staff:
        parent_group = request.user.groups.values_list('name', flat=True)[
            0]
        group = Group.objects.get(name=parent_group)
        enabled = False
        group_private = False
        personal_data = False
        medical_data = False
        custom_data = False
        custom_group_bool = False
        name = ""
        custom_group = ""

        enabled_check = 'checked="checked"'
        private_check = 'checked="checked"'
        personal_check = 'checked="checked"'
        sign_check = 'checked="checked"'
        medical_check = ""
        custom_check = ""
        custom_message_check = ""
        context = {
            "enabled_check": enabled_check,
            "private_check": private_check,
            "sign_check": sign_check,
            "personal_check": personal_check,
            "medical_check": medical_check,
            "custom_check": custom_check,
            "custom_message_check": custom_message_check,
        }
        if request.method == "POST":
            enabled = "enabled" in request.POST.keys()
            auto_sign = "sign" not in request.POST.keys()
            group_private = "group_private" in request.POST.keys()
            personal_data = "personal_data" in request.POST.keys()
            medical_data = "medical_data" in request.POST.keys()
            custom_data = "custom_data" in request.POST.keys()
            custom_message = "custom_message" in request.POST.keys()
            custom_message_text = request.POST["custom_message_text"]
            name = request.POST["name"]
            custom_group = request.POST["custom_group"]

            if custom_group != "":
                print("here")
                if custom_group not in request.user.groups.values_list('name', flat=True):
                    context["error"] = "true"
                    context["error_text"] = "Non puoi creare un tipo assegnato ad un gruppo di cui non fai parte"
                    return render(request, 'server/doc_create.html', context)
                else:
                    group = Group.objects.filter(name=custom_group)[0]
                    custom_group_bool = True

            doctype = DocumentType(
                custom_group=custom_group_bool, auto_sign=auto_sign, custom_message=custom_message, custom_message_text=custom_message_text, name=request.POST["name"], enabled=enabled, group_private=group_private, group=group, personal_data=personal_data, medical_data=medical_data, custom_data=custom_data)
            doctype.save()
            if custom_data:
                custom = request.POST["custom"]
                custom.replace("\r", "")
                custom = custom.split("\n")
                for i in custom:
                    key = Keys(key=i, container=doctype)
                    key.save()
            return HttpResponseRedirect('doctype')

        return render(request, 'server/doc_create.html', context)
    else:
        return render(request, 'client/index.html', context)


def doclist(request):
    context = {}
    if request.user.is_staff:
        parent_group = request.user.groups.values_list('name', flat=True)[
            0]
        group = Group.objects.get(name=parent_group)
        zurich = pytz.timezone('Europe/Zurich')
        error = False
        error_text = ""

        hidden = False
        wait = True
        selfsign = True
        ok = True

        hidden_check = 'checked="checked"'
        wait_check = 'checked="checked"'
        selfsign_check = 'checked="checked"'
        ok_check = 'checked="checked"'
        newer = zurich.localize(dateparser.parse("1970-01-01"))
        older = zurich.localize(datetime.now())
        owner = []
        types = []
        groups = []
        chips_owner = []
        chips_types = []
        chips_groups = []

        if request.method == "POST":
            if request.POST["action"][0] == 'k':
                document = Document.objects.get(id=request.POST["action"][1:])
                if document.group == group:
                    template = get_template('server/download_doc.html')
                    doc = [document, KeyVal.objects.filter(container=document), document.personal_data, document.medical_data, parent_group]
                    context = {'doc': doc}
                    html = template.render(context)
                    pdf = pdfkit.from_string(html, False)
                    result = BytesIO(pdf)
                    result.seek(0)

                    return FileResponse(result, as_attachment=True, filename=document.user.username+"_"+document.document_type.name+".pdf")

            selected = []
            parent_groups = request.user.groups.values_list('name', flat=True)
            for i in request.POST.keys():
                if i.isdigit():
                    docc = Document.objects.get(id=i)
                    if docc.group.name in parent_groups:
                        selected.append(docc)

            for i in selected:
                if request.POST["action"] == 'delete':
                    i.delete()
                elif request.POST["action"] == 'approve':
                    i.status = 'ok'
                    i.save()
                elif request.POST["action"] == 'archive':
                    if i.status == 'ok':
                        i.status = 'archive'
                        i.save()
                    else:
                        error = True
                        error_text = "Non puoi archiviare un documento non approvato"
                elif request.POST["action"] == 'unarchive':
                    if i.status == 'archive':
                        i.status = 'ok'
                        i.save()
                    else:
                        error = True
                        error_text = "Non puoi dearchiviare un documento non archiviato"
            
            hidden = "filter_hidden" in request.POST
            wait = "filter_wait" in request.POST
            selfsign = "filter_selfsign" in request.POST
            ok = "filter_ok" in request.POST
            newer = zurich.localize(dateparser.parse(request.POST["newer"]))
            older = zurich.localize(dateparser.parse(request.POST["older"]) + timedelta(days=1))
            owner = request.POST["owner"].split("^|")
            types = request.POST["type"].split("^|")
            groups = request.POST["groups"].split("^|")

            if request.POST["action"] == 'clear':
                hidden = False
                wait = True
                selfsign = True
                ok = True
                newer = zurich.localize(dateparser.parse("1970-01-01"))
                older = zurich.localize(datetime.now())
                owner = []
                types = []
                groups = []

        parent_groups = request.user.groups.values_list('name', flat=True)
        q_obj = Q()
        for i in parent_groups:
            q_obj |= Q(group__name=i)

        documents = Document.objects.filter(q_obj)

        if not hidden:
            documents = documents.filter(~Q(status="archive"))
            hidden_check = ""
        if not wait:
            documents = documents.filter(~Q(status="wait"))
            wait_check = ""
        if not selfsign:
            documents = documents.filter(~Q(status="autosign"))
            selfsign_check = ""
        if not ok:
            documents = documents.filter(~Q(status="ok"))
            ok_check = ""

        documents = documents.filter(compilation_date__range=[newer, older])

        if len(types) > 0:
            if types[0] != "":
                q_obj = Q()
                for t in types:
                    q_obj |= Q(document_type__name=t)
                    chips_types.append(t)

                documents = documents.filter(q_obj)

        if len(owner) > 0:
            if owner[0] != "":
                q_obj = Q()
                for u in owner:
                    user = u.split("(")[0][:-1]
                    q_obj |= Q(user__username=user)
                    chips_owner.append(u)

                documents = documents.filter(q_obj)

        if len(groups) > 0:
            if groups[0] != "":
                q_obj = Q()
                for g in groups:
                    q_obj |= Q(group__name=g)
                    chips_groups.append(g)

                documents = documents.filter(q_obj)

        out = []
        for i in documents:
            personal = None
            medical = None
            if i.document_type.personal_data:
                personal = i.personal_data
            if i.document_type.medical_data:
                medical = i.medical_data

            doc_group = i.user.groups.values_list('name', flat=True)[0]

            out.append([i, KeyVal.objects.filter(container=i), personal, medical, doc_group])

        auto_types = DocumentType.objects.filter(Q(group_private=False) | Q(group=group))
        users = User.objects.filter(groups__name=parent_group)
        context = {
            "types": auto_types,
            "users": users,
            "groups": parent_groups,
            "docs": out,
            "hidden_check": hidden_check,
            "wait_check": wait_check,
            "selfsign_check": selfsign_check,
            "ok_check": ok_check,
            "newer": newer,
            "older": older,
            "chips_owner": chips_owner,
            "chips_type": chips_types,
            "chips_groups": chips_groups,
            'error': error,
            'error_text': error_text,
            'settings': settings,
            }
        return render(request, 'server/doc_list.html', context)
    else:
        return render(request, 'client/index.html', context)