Fakultas Ilmu Komputer UI

views.py 27.7 KB
Newer Older
1
import json
2
from datetime import datetime, date
3

4
from django.core.exceptions import PermissionDenied
5
from django.contrib.auth.hashers import make_password
6
from django.db.models import Count
7
from django.http import HttpResponseRedirect, JsonResponse
8
from django.shortcuts import get_object_or_404, render
9
from django.views.generic import TemplateView, View
10
from django.contrib import messages
11
12
from django.utils import timezone, lorem_ipsum
from dateutil.relativedelta import relativedelta
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
13
from administration.models import VerificationReport, VerificationSetting, DeletionHistory
Rizkhi PH's avatar
Rizkhi PH committed
14
from administration.forms import CategoryForm, VerificationSettingForm, RegistrasiAdminForm, PeriodForm, EditAdminStatusForm
15
from app.models import Category, Materi, ViewStatistics, DownloadStatistics, Comment, Like, getRandomColor, LaporanMateri
16
from app.views import permission_denied
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
17
from authentication.models import User
18
from datetime import datetime
19

20
21
from administration.utils import generate_time_step

22
23
from django.core import management

Rizkhi PH's avatar
Rizkhi PH committed
24
ADMINISTRATION_MANAGEMENT = "/administration/kelola-admin/"
25
ADMINISTRATION_REPORT = "/administration/laporan-materi/"
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

def get_start_end_date(period):
    if period == 'ALL_TIME':
        return (None, None)
    elif period.split("_")[0] == "LAST":
        end = timezone.now()
        delta = 7
        if period.split("_")[1] == "WEEK":
            delta = 7
        if period.split("_")[1] == "MONTH":
            delta = 30
        if period.split("_")[1] == "QUARTER":
            delta = 90
        if period.split("_")[1] == "YEAR":
            delta = 365
        start = end - relativedelta(days=delta)
        return (start, end)
    elif period.split("_")[0] == "CURRENT":
        start = timezone.now()
        if period.split("_")[1] == "MONTH":
            start = start.replace(day=1, hour=0, minute=0,
                                  second=0, microsecond=0)
            end = start + relativedelta(months=1)
            return (start, end)
        elif period.split("_")[1] == "YEAR":
            start = start.replace(month=1, day=1, hour=0,
                                  minute=0, second=0, microsecond=0)
            end = start + relativedelta(years=1)
            return (start, end)
    elif period.split("_")[0] == "MINUS":
        start = timezone.now()
        delta = int(period.split("_")[1])
        if period.split("_")[2] == "MONTH":
            start = start.replace(day=1, hour=0, minute=0,
                                  second=0, microsecond=0)
            start = start - relativedelta(months=delta)
            end = start + relativedelta(months=1)
            return (start, end)
        elif period.split("_")[2] == "YEAR":
            start = start.replace(month=1, day=1, hour=0,
                                  minute=0, second=0, microsecond=0)
            start = start - relativedelta(years=delta)
            end = start + relativedelta(years=1)
            return (start, end)
    else:
        return (None, None)

73

74
75
76
class VerificationView(TemplateView):
    template_name = "verif.html"

77
78
79
80
81
82
83
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(VerificationView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(VerificationView, self).get_context_data(**kwargs)
84
85
86
87
        context["materi_list_pending"] = Materi.objects.filter(
            status='PENDING')
        context["materi_list_history"] = Materi.objects.exclude(
            status='PENDING')
88
89
        return context

90
91
92
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)
93

94

95
96
97
98
99
100
101
class DetailVerificationView(TemplateView):
    template_name = "detail_verif.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(DetailVerificationView, self).dispatch(request, *args, **kwargs)
102

103
104
105
    def get_context_data(self, **kwargs):
        context = super(DetailVerificationView,
                        self).get_context_data(**kwargs)
106
107
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
        context["materi_data"] = materi
108
109
        context["kriteria_list"] = VerificationSetting.objects.filter(
            archived=False)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
110
111
112
113
        if materi.status == "PENDING" or materi.status == "REVISION":
            riwayat = False
        else:
            riwayat = True
114
115
        context["riwayat"] = riwayat
        context["verification_report"] = materi.verificationreport_set.first()
116
117
118
119
        return context

    def post(self, request, *args, **kwargs):
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        feedback = request.POST.get("feedback", "")
        action = request.POST.get("action", None)

        report = {}
        kriteria = []
        for item in request.POST.items():
            if "kriteria" in item[0]:
                verification_item_id = item[0].split("-")[1]
                verif_obj = VerificationSetting.objects.get(
                    id=int(verification_item_id))
                kriteria_value = {
                    "title": verif_obj.title,
                    "status": True if item[1] == "1" else False
                }
                kriteria.append(kriteria_value)

        report["kriteria"] = kriteria
        report["feedback"] = feedback

        if action == "approve" and feedback != "":
140
141
            materi.status = "APPROVE"
            materi.save()
142
        elif action == "disapprove" and feedback != "":
143
144
145
146
147
148
            materi.status = "DISAPPROVE"
            materi.save()
        else:
            context = self.get_context_data(**kwargs)
            context["error"] = True
            return self.render_to_response(context=context)
149
150
151
        verif_report = VerificationReport(
            report=report, materi=materi, user=self.request.user, status=materi.get_status_display())
        verif_report.save()
152
        return HttpResponseRedirect("/administration/")
153

154
155
156
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context=context)
157

158
159

class VerificationSettingView(TemplateView):
160
161
162
163
164
165
    template_name = "settings.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(VerificationSettingView, self).dispatch(request, *args, **kwargs)
166
167

    def get_context_data(self, **kwargs):
168
169
        context = super(VerificationSettingView,
                        self).get_context_data(**kwargs)
170
        context["items"] = VerificationSetting.objects.filter(
171
            archived=False)
172
173
        context["items_archived"] = VerificationSetting.objects.filter(
            archived=True)
174
        context["page_title"] = "Point Verifikasi Materi"
175
176
177
        return context

    def get(self, request, *args, **kwargs):
178
179
180
        context = self.get_context_data(**kwargs)
        context["form"] = VerificationSettingForm()
        return self.render_to_response(context=context)
181
182

    def post(self, request, *args, **kwargs):
183
184
185
186
        form = VerificationSettingForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/administration/setting/verification/")
187
        else:
188
189
190
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
191

192

193
class CategorySettingView(TemplateView):
194
195
196
197
198
199
    template_name = "settings.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(CategorySettingView, self).dispatch(request, *args, **kwargs)
200
201

    def get_context_data(self, **kwargs):
202
        context = super(CategorySettingView, self).get_context_data(**kwargs)
203
204
        context["items"] = Category.objects.filter(archived=False)
        context["items_archived"] = Category.objects.filter(archived=True)
205
        context["page_title"] = "Kategori Materi"
206
207
208
        return context

    def get(self, request, *args, **kwargs):
209
210
211
        context = self.get_context_data(**kwargs)
        context["form"] = CategoryForm()
        return self.render_to_response(context=context)
212
213

    def post(self, request, *args, **kwargs):
214
215
216
217
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/administration/setting/category/")
218
        else:
219
220
221
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
222

223

224
225
class KelolaKontributorView(TemplateView):
    template_name = "kelola_kontributor.html"
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
226
227
228
229
230

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)

231
        return super(KelolaKontributorView, self).dispatch(request, *args, **kwargs)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
232
233

    def get_context_data(self, **kwargs):
234
        context = super(KelolaKontributorView, self).get_context_data(**kwargs)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
235
        context["users"] = User.objects.filter(is_contributor=True)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
236
        context["deletion_history"] = DeletionHistory.objects.filter(deleted_user_role="Kontributor")
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
237
238
239
240
241
242
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

243

244
245
246
247
248
249
250
251
252
253
254
255
class KelolaAdminView(TemplateView):
    template_name = "kelola_admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)

        return super(KelolaAdminView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(KelolaAdminView, self).get_context_data(**kwargs)
        context['users_list'] = User.objects.filter(is_admin=True)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
256
        context["deletion_history"] = DeletionHistory.objects.filter(deleted_user_role="Admin")
257
258
259
260
261
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)
262

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
263
264
265
266
class ProfileContributorAdminView(TemplateView):
    template_name = "detail_kontri_admin.html"

    def dispatch(self, request, *args, **kwargs):
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
267
        if not request.user.is_authenticated:
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
268
269
270
271
272
273
274
275
276
277
            raise PermissionDenied(request)

        return super(ProfileContributorAdminView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        context["user"] = get_object_or_404(User, pk=kwargs["pk"])
278
        return self.render_to_response(context=context)
279

280
281
282
class StatisticsView(TemplateView):
    template_name = "administration/data_statistik.html"

283
284
285
286
287
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            raise PermissionDenied(request)
        return super(StatisticsView, self).dispatch(request, *args, **kwargs)

288
289
290
291
292
293
    def get_context_data(self, **kwargs):
        context = super(StatisticsView, self).get_context_data(**kwargs)
        context["page_title"] = "Statistik"
        context["periodForm"] = PeriodForm(self.request.GET)
        return context

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
    def get_filter_set(self, **kwargs):
        filter_set = {}
        form = PeriodForm(self.request.GET)
        DEFAULT_PERIOD = "LAST_MONTH"
        if form.is_valid():
            form_data = form.cleaned_data
            if len(form_data["categories"]) == 0:
                form_data["categories"] = None

            if form_data["period"] == "":
                form_data["period"] = DEFAULT_PERIOD

            # check if using custom date range
            if form_data["start_date"] is not None and form_data["end_date"] is not None:
                start = timezone.make_aware(datetime.combine(
                    form_data["start_date"], datetime.min.time()))
                end = timezone.make_aware(datetime.combine(
                    form_data["end_date"], datetime.min.time()))
            elif form_data["period"] is not None:
                start, end = get_start_end_date(form_data["period"])
            else:
                start, end = get_start_end_date(DEFAULT_PERIOD)
            filter_set["start"] = start
            filter_set["end"] = end
            filter_set["categories"] = form_data["categories"]
        return filter_set

    def get_query_set(self, object_statistic, **kwargs):
        if self.request.user.is_admin:
            return object_statistic.objects.filter(materi__status="APPROVE")
        else:
            return object_statistic.objects.filter(materi__status="APPROVE", materi__uploader=self.request.user.id)

    def filter_qs(self, qs, filter_set):
        if filter_set.get("categories", None) is not None:
            qs = qs.filter(materi__categories__in=filter_set.get("categories"))
        if filter_set.get("start") is not None and filter_set.get("end") is not None:
            s = filter_set.get("start")
            e = filter_set.get("end")
            qs = qs.filter(timestamp__gte=s, timestamp__lt=e)
        return qs.distinct()

    # def generate_table_data(self, data_sets):
    #     table_data = {}

    #     counter = 1
    #     row_materi_table = []
    #     for item in data_sets:

    #         # return res

    def generate_chart_data(self, start, end, data_sets):
        chart_data = {
            "charts": [],
            "total": [],
            "label": []
        }
        label = ["Dilihat", "Diunduh", "Komentar", "Disukai"]
        colors = ["#4e73df", "#e74a3b", "#1cc88a", "#f6c23e"]
        time_step = generate_time_step(start, end)
        for i in time_step:
            chart_data["label"].append(i.strftime("%d/%m/%Y"))

        # generate view stat
        for label, color, dataset in zip(label, colors, data_sets):
            result = {
                "label": label,
                "backgroundColor": color,
                "borderColor": color,
                "borderWidth": 1
            }
            data = []
            total = 0
            s = 0
            e = 1
            while e < len(time_step):
                todays = dataset.filter(
                    timestamp__gte=time_step[s], timestamp__lt=time_step[e]).count()
                data.append(todays)
                total += todays
                s += 1
                e += 1
            result["data"] = data
            chart_data["charts"].append(result)
            chart_data["total"].append(total)
        return chart_data

381
382
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
383
384
385
386
387
388
389
390
391
392
393
394
395
396
        filter_set = self.get_filter_set(**kwargs)
        view_set = self.get_query_set(ViewStatistics, **kwargs)
        view_set = self.filter_qs(view_set, filter_set)
        download_set = self.get_query_set(DownloadStatistics, **kwargs)
        download_set = self.filter_qs(download_set, filter_set)
        like_set = self.get_query_set(Like, **kwargs)
        like_set = self.filter_qs(like_set, filter_set)
        comment_set = self.get_query_set(Comment, **kwargs)
        comment_set = self.filter_qs(comment_set, filter_set)

        data_sets = [view_set, download_set, like_set, comment_set]
        chart_data = self.generate_chart_data(
            filter_set["start"], filter_set["end"], data_sets)
        context["chart_data"] = chart_data
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

        return self.render_to_response(context=context)


class StatisticApiView(View):
    def get_context_data(self, **kwargs):
        context = {}
        context["success"] = True
        context["period"] = self.request.GET.get("period", "default")
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return JsonResponse(context)


413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
class ProfileAdminAdministrationView(TemplateView):
    template_name = "detail_admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)

        return super(ProfileAdminAdministrationView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        context["user"] = get_object_or_404(User, pk=kwargs["pk"])
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
428
        context["deletion_history"] = DeletionHistory.objects.filter(deletor_admin=get_object_or_404(User, pk=kwargs["pk"]))
429
430
        return self.render_to_response(context=context)

431

432
433
434
435
436
437
438
439
440
441
442
443
class RegistrasiAdminView(TemplateView):
    template_name = "registrasi_admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(RegistrasiAdminView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(RegistrasiAdminView, self).get_context_data(**kwargs)
        context["form"] = RegistrasiAdminForm
        return context
444

445
446
447
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context=context)
448

449
450
451
452
453
454
455
456
    def post(self, request, *args, **kwargs):
        data = request.POST.copy()
        form = RegistrasiAdminForm(request.POST)
        if form.is_valid():
            new_user = form.save(commit=False)
            new_user.password = make_password(data["password"])
            new_user.is_admin = True
            new_user.save()
Rizkhi PH's avatar
Rizkhi PH committed
457
            return HttpResponseRedirect(ADMINISTRATION_MANAGEMENT)
458
459
460
461
462
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)

463
464

class EditVerificationView(TemplateView):
465
    template_name = "edit_settings.html"
466
467
468
469
470
471
472
473

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(EditVerificationView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(EditVerificationView, self).get_context_data(**kwargs)
474
        context["page_title"] = "Verifikasi Materi"
475
476
        context["item"] = VerificationSetting.objects.get(id=kwargs["pk"])
        context["form"] = VerificationSettingForm(instance=context["item"])
477
478
479
480
481
482
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context=context)

483
484
485
486
487
488
489
490
491
492
493
494
    def post(self, request, *args, **kwargs):
        verification_object = self.get_context_data(**kwargs)["item"]
        form = VerificationSettingForm(
            request.POST, instance=verification_object)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/administration/setting/verification/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)

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
class EditCategoryView(TemplateView):
    template_name = "edit_settings.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(EditCategoryView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(EditCategoryView, self).get_context_data(**kwargs)
        context["page_title"] = "Kategori Materi"
        context["item"] = Category.objects.get(id=kwargs["pk"])
        context["form"] = CategoryForm(instance=context["item"])
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context=context)

    def post(self, request, *args, **kwargs):
        category_object = self.get_context_data(**kwargs)["item"]
        form = CategoryForm(
            request.POST, instance=category_object)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/administration/setting/category/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)

Rizkhi PH's avatar
Rizkhi PH committed
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
class EditAdminStatusView(TemplateView):
    template_name = "edit_admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_superuser:
            raise PermissionDenied(request)
        return super(EditAdminStatusView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(EditAdminStatusView, self).get_context_data(**kwargs)
        context["page_title"] = "Admin Status"
        context["item"] = User.objects.get(id=kwargs["pk"])
        context["form"] = EditAdminStatusForm(instance=context["item"])
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context=context)

    def post(self, request, *args, **kwargs):
        user_object = self.get_context_data(**kwargs)["item"]
        if user_object.is_superuser:
            raise PermissionDenied(request)
        form = EditAdminStatusForm(
            request.POST, instance=user_object)
        form.save()
        return HttpResponseRedirect(ADMINISTRATION_MANAGEMENT)
554

555
def delete_admin(request, *args, **kwargs):
556
557
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
558
559

    user_to_be_deleted = User.objects.get(pk=kwargs["pk"])
Rizkhi PH's avatar
Rizkhi PH committed
560
561
562
    if (user_to_be_deleted.is_superuser):
        raise PermissionDenied(request)

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
563
564
565
566
567
568
    DeletionHistory.objects.create(
        deleted_user_name=user_to_be_deleted.name, 
        deleted_user_role="Admin",
        deletor_admin=request.user    
    )

569
    User.objects.filter(pk=kwargs["pk"]).delete()
Rizkhi PH's avatar
Rizkhi PH committed
570
    return HttpResponseRedirect(ADMINISTRATION_MANAGEMENT)
571

572

573
def delete_contributor(request, *args, **kwargs):
574
575
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
576
577
578
579
580
581
582
583
    
    user_to_be_deleted = User.objects.get(pk=kwargs["pk"])
    DeletionHistory.objects.create(
        deleted_user_name=user_to_be_deleted.name, 
        deleted_user_role="Kontributor",
        deletor_admin=request.user    
    )

584
    User.objects.filter(pk=kwargs["pk"]).delete()
585
    return HttpResponseRedirect("/administration/kelola-kontributor/")
586
587
588


def delete_verification(request, *args, **kwargs):
589
590
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
591
592
593
    queryObject = get_object_or_404(VerificationSetting,
                                    pk=kwargs["pk_verification"])
    queryObject.archived = True
594
595
596
    queryObject.description = "Telah dihapus pada " + \
        str(datetime.now().strftime("%m/%d/%Y, %H:%M:%S")) + " WIB"
    queryObject.archived_by = request.user
597
    queryObject.save()
598
    messages.success(request, "Point verifikasi berhasil dihapus")
599
    return HttpResponseRedirect("/administration/setting/verification/")
600
601
602
603
604
605
606


def delete_category(request, *args, **kwargs):
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
    category_name = get_object_or_404(Category,
                                      pk=kwargs["pk_category"]).name
607
608
609
    queryObject = get_object_or_404(Category,
                                    pk=kwargs["pk_category"])
    queryObject.archived = True
610
611
612
    queryObject.description = "Telah dihapus pada " + \
        str(datetime.now().strftime("%m/%d/%Y, %H:%M:%S")) + " WIB"
    queryObject.archived_by = request.user
613
614
    queryObject.save()
    messages.success(request, "Kategori " +
615
616
                     category_name + " berhasil dihapus")
    return HttpResponseRedirect("/administration/setting/category/")
617
618
619
620
621
622
623
624
625
626
627
628
629

def generatedummy(request):
    if request.user.is_authenticated is False or request.user.is_admin is False:
        return PermissionDenied(request)
    materi = request.GET.get("materi", None)
    visitor = request.GET.get("visitor", None)
    if materi is None or visitor is None:
        return JsonResponse({"success":False})
    materi = int(materi)
    visitor = int(visitor)
    # RUn management command
    management.call_command('generatedummy', materi)
    management.call_command('generatetraffic', visitor)
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
    return JsonResponse({"success":True,"materi":materi,"visitor":visitor})

class KelolaMateriView(TemplateView):
    template_name = "kelola_materi.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)

        return super(KelolaMateriView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(KelolaMateriView, self).get_context_data(**kwargs)
        context['materi_list'] = Materi.objects.all()
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)
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

class LaporanMateriView(TemplateView):
    template_name = "laporan_materi.html"
    
    def dispatch(self, request, *args, **kwargs):   
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(LaporanMateriView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        context = super(LaporanMateriView, self).get_context_data(**kwargs)
        context["laporan_materi"] = LaporanMateri.objects.filter(is_rejected=False)
        context["materi_dilaporkan"] = Materi.objects \
            .filter(laporanmateri__id__in=context["laporan_materi"], status="APPROVE") \
            .annotate(jumlah_laporan=Count('laporanmateri__materi_id')) \
            .order_by('-jumlah_laporan') \
            .distinct()
        context["materi_diblokir"] = Materi.objects.filter(status="BLOCKED")
        return self.render_to_response(context=context)

class LaporanMateriDetailView(TemplateView):
    template_name = "laporan_materi_detail.html"
    
    def dispatch(self, request, *args, **kwargs):   
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(LaporanMateriDetailView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        context = super(LaporanMateriDetailView, self).get_context_data(**kwargs)
        context["laporan_materi"] = LaporanMateri.objects.filter(materi_id=kwargs["pk"], is_rejected=False)
        context["materi"] = get_object_or_404(Materi, id=kwargs["pk"])
        return self.render_to_response(context=context)

def blok_materi(request, *args, **kwargs):
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
    
    materi = get_object_or_404(Materi, pk=kwargs["pk"])
    if materi.status == "APPROVE" and LaporanMateri.objects.filter(is_rejected=False, materi_id=materi.id):
        materi.status = "BLOCKED"
        materi.save()

    return HttpResponseRedirect(ADMINISTRATION_REPORT)

def tolak_laporan(request, *args, **kwargs):
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
    
    laporan = get_object_or_404(LaporanMateri, pk=kwargs["pk"])
    laporan.is_rejected = True
    laporan.save()

    return HttpResponseRedirect(ADMINISTRATION_REPORT + str(laporan.materi_id))