Fakultas Ilmu Komputer UI

views.py 22.5 KB
Newer Older
1
from django.core.exceptions import PermissionDenied
2
from django.contrib.auth.hashers import make_password
3
from django.db.models import Count
4
from django.http import HttpResponseRedirect, JsonResponse
5
from django.shortcuts import get_object_or_404
6
from django.views.generic import TemplateView, View
7
from django.contrib import messages
8
from django.utils import timezone
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
9
from administration.models import VerificationReport, VerificationSetting, DeletionHistory
Rizkhi PH's avatar
Rizkhi PH committed
10
from administration.forms import CategoryForm, VerificationSettingForm, RegistrasiAdminForm, PeriodForm, EditAdminStatusForm
11
12
from administration.services import StatisticService, DetailVerificationService, LaporanMateriService
from app.models import Category, Materi, ViewStatistics, DownloadStatistics, Comment, Like, LaporanMateri
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
13
from authentication.models import User
14
from datetime import datetime
15

16
17
from administration.utils import generate_time_step

18
19
from django.core import management

Rizkhi PH's avatar
Rizkhi PH committed
20
ADMINISTRATION_MANAGEMENT = "/administration/kelola-admin/"
21
ADMINISTRATION_REPORT = "/administration/laporan-materi/"
22

23

24
25
26
class VerificationView(TemplateView):
    template_name = "verif.html"

27
28
29
30
31
32
33
    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)
34
35
36
37
        context["materi_list_pending"] = Materi.objects.filter(
            status='PENDING')
        context["materi_list_history"] = Materi.objects.exclude(
            status='PENDING')
38
39
        return context

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

44

45
46
47
48
49
50
51
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)
52

53
54
55
    def get_context_data(self, **kwargs):
        context = super(DetailVerificationView,
                        self).get_context_data(**kwargs)
56
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
57
        DetailVerificationService.init_data(context, materi)
58
59
        return context

60

61
62
    def post(self, request, *args, **kwargs):
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
63
64
65
66
        feedback = request.POST.get("feedback", "")
        action = request.POST.get("action", None)

        report = {}
67
68
69
        items = request.POST.items()

        report["kriteria"] = DetailVerificationService.initilize_kriteria(items)
70
71
72
        report["feedback"] = feedback

        if action == "approve" and feedback != "":
73
            DetailVerificationService.action_approve(materi)
74
        elif action == "disapprove" and feedback != "":
75
            DetailVerificationService.action_disapprove(materi)
76
77
78
79
        else:
            context = self.get_context_data(**kwargs)
            context["error"] = True
            return self.render_to_response(context=context)
80
81
82
        verif_report = VerificationReport(
            report=report, materi=materi, user=self.request.user, status=materi.get_status_display())
        verif_report.save()
83
        return HttpResponseRedirect("/administration/")
84

85

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

90
91

class VerificationSettingView(TemplateView):
92
93
94
95
96
97
    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)
98
99

    def get_context_data(self, **kwargs):
100
101
        context = super(VerificationSettingView,
                        self).get_context_data(**kwargs)
102
        context["items"] = VerificationSetting.objects.filter(
103
            archived=False)
104
105
        context["items_archived"] = VerificationSetting.objects.filter(
            archived=True)
106
        context["page_title"] = "Point Verifikasi Materi"
107
108
109
        return context

    def get(self, request, *args, **kwargs):
110
111
112
        context = self.get_context_data(**kwargs)
        context["form"] = VerificationSettingForm()
        return self.render_to_response(context=context)
113
114

    def post(self, request, *args, **kwargs):
115
116
117
118
        form = VerificationSettingForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/administration/setting/verification/")
119
        else:
120
121
122
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
123

124

125
class CategorySettingView(TemplateView):
126
127
128
129
130
131
    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)
132
133

    def get_context_data(self, **kwargs):
134
        context = super(CategorySettingView, self).get_context_data(**kwargs)
135
136
        context["items"] = Category.objects.filter(archived=False)
        context["items_archived"] = Category.objects.filter(archived=True)
137
        context["page_title"] = "Kategori Materi"
138
139
140
        return context

    def get(self, request, *args, **kwargs):
141
142
143
        context = self.get_context_data(**kwargs)
        context["form"] = CategoryForm()
        return self.render_to_response(context=context)
144
145

    def post(self, request, *args, **kwargs):
146
147
148
149
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/administration/setting/category/")
150
        else:
151
152
153
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
154

155

156
157
class KelolaKontributorView(TemplateView):
    template_name = "kelola_kontributor.html"
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
158
159
160
161
162

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

163
        return super(KelolaKontributorView, self).dispatch(request, *args, **kwargs)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
164
165

    def get_context_data(self, **kwargs):
166
        context = super(KelolaKontributorView, self).get_context_data(**kwargs)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
167
        context["users"] = User.objects.filter(is_contributor=True)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
168
        context["deletion_history"] = DeletionHistory.objects.filter(deleted_user_role="Kontributor")
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
169
170
171
172
173
174
        return context

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

175

176
177
178
179
180
181
182
183
184
185
186
187
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
188
        context["deletion_history"] = DeletionHistory.objects.filter(deleted_user_role="Admin")
189
190
191
192
193
        return context

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

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
195
196
197
198
class ProfileContributorAdminView(TemplateView):
    template_name = "detail_kontri_admin.html"

    def dispatch(self, request, *args, **kwargs):
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
199
        if not request.user.is_authenticated:
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
200
201
202
203
204
205
206
207
208
209
            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"])
210
        return self.render_to_response(context=context)
211

212
213
214
class StatisticsView(TemplateView):
    template_name = "administration/data_statistik.html"

215
216
217
218
219
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            raise PermissionDenied(request)
        return super(StatisticsView, self).dispatch(request, *args, **kwargs)

220
221
222
223
224
225
    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

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241




    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"))

242
        StatisticService.generate_view_stat(chart_data, colors, data_sets, label, time_step)
243
244
        return chart_data

245

246
247
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
248
249
250
251
252
253
254
255
256
        filter_set = StatisticService.get_filter_set(self.request.GET,**kwargs)
        view_set = StatisticService.get_query_set(self.request.user,ViewStatistics, **kwargs)
        view_set = StatisticService.filter_qs(view_set, filter_set)
        download_set = StatisticService.get_query_set(self.request.user, DownloadStatistics, **kwargs)
        download_set = StatisticService.filter_qs(download_set, filter_set)
        like_set = StatisticService.get_query_set(self.request.user, Like, **kwargs)
        like_set = StatisticService.filter_qs(like_set, filter_set)
        comment_set = StatisticService.get_query_set(self.request.user, Comment, **kwargs)
        comment_set = StatisticService.filter_qs(comment_set, filter_set)
257
258
259
260
261

        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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277

        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)


278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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
293
        context["deletion_history"] = DeletionHistory.objects.filter(deletor_admin=get_object_or_404(User, pk=kwargs["pk"]))
294
295
        return self.render_to_response(context=context)

296

297
298
299
300
301
302
303
304
305
306
307
308
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
309

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

314
315
316
317
318
319
320
321
    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
322
            return HttpResponseRedirect(ADMINISTRATION_MANAGEMENT)
323
324
325
326
327
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)

328
329

class EditVerificationView(TemplateView):
330
    template_name = "edit_settings.html"
331
332
333
334
335
336
337
338

    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)
339
        context["page_title"] = "Verifikasi Materi"
340
341
        context["item"] = VerificationSetting.objects.get(id=kwargs["pk"])
        context["form"] = VerificationSettingForm(instance=context["item"])
342
343
344
345
346
347
        return context

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

348
349
350
351
352
353
354
355
356
357
358
359
    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)

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
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
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
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)
419

420
def delete_admin(request, *args, **kwargs):
421
422
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
423
424

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

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
428
429
430
431
432
433
    DeletionHistory.objects.create(
        deleted_user_name=user_to_be_deleted.name, 
        deleted_user_role="Admin",
        deletor_admin=request.user    
    )

434
    User.objects.filter(pk=kwargs["pk"]).delete()
Rizkhi PH's avatar
Rizkhi PH committed
435
    return HttpResponseRedirect(ADMINISTRATION_MANAGEMENT)
436

437

438
def delete_contributor(request, *args, **kwargs):
439
440
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
441
442
443
444
445
446
447
448
    
    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    
    )

449
    User.objects.filter(pk=kwargs["pk"]).delete()
450
    return HttpResponseRedirect("/administration/kelola-kontributor/")
451
452
453


def delete_verification(request, *args, **kwargs):
454
455
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
456
457
458
    queryObject = get_object_or_404(VerificationSetting,
                                    pk=kwargs["pk_verification"])
    queryObject.archived = True
459
460
461
    queryObject.description = "Telah dihapus pada " + \
        str(datetime.now().strftime("%m/%d/%Y, %H:%M:%S")) + " WIB"
    queryObject.archived_by = request.user
462
    queryObject.save()
463
    messages.success(request, "Point verifikasi berhasil dihapus")
464
    return HttpResponseRedirect("/administration/setting/verification/")
465
466
467
468
469
470
471


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
472
473
474
    queryObject = get_object_or_404(Category,
                                    pk=kwargs["pk_category"])
    queryObject.archived = True
475
476
477
    queryObject.description = "Telah dihapus pada " + \
        str(datetime.now().strftime("%m/%d/%Y, %H:%M:%S")) + " WIB"
    queryObject.archived_by = request.user
478
479
    queryObject.save()
    messages.success(request, "Kategori " +
480
481
                     category_name + " berhasil dihapus")
    return HttpResponseRedirect("/administration/setting/category/")
482
483
484
485
486
487
488
489
490
491
492
493
494

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)
495
496
497
498
499
500
501
502
503
504
505
506
507
    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)
508
        context['materi_list'] = Materi.all_objects.all()
509
510
511
512
513
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)
514
515
516
517
518
519
520
521
522
523
524

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)
525
526
527
528
529
        laporan_materi, materi_dilaporkan, \
        materi_diblokir = LaporanMateriService.initilize_report()
        context["laporan_materi"] = laporan_materi
        context["materi_dilaporkan"] = materi_dilaporkan
        context["materi_diblokir"] = materi_diblokir
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
        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))