Fakultas Ilmu Komputer UI

services.py 7.34 KB
Newer Older
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
from dateutil.relativedelta import relativedelta
from django.db.models import Count
from django.utils import timezone
from datetime import datetime

from administration.forms import PeriodForm
from administration.models import VerificationSetting
from app.models import LaporanMateri, Materi


class DateHelperService:

    @staticmethod
    def get_start_end_date(period):
        if period == 'ALL_TIME':
            return (None, None)
        elif period.split("_")[0] == "LAST":
            end, start = DateHelperService.handle_last(period)
            return (start, end)
        elif period.split("_")[0] == "CURRENT":
            end, start = DateHelperService.handle_current(period)
            return (start, end)
        elif period.split("_")[0] == "MINUS":
            end, start = DateHelperService.handle_minus(period)
            return (start, end)
        else:
            return (None, None)

    @staticmethod
    def handle_minus(period):
        start = timezone.now()
        end = None
        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)
        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 end, start

    @staticmethod
    def handle_current(period):
        start = timezone.now()
        end = None
        if period.split("_")[1] == "MONTH":
            start = start.replace(day=1, hour=0, minute=0,
                                  second=0, microsecond=0)
            end = start + relativedelta(months=1)
        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 end, start

    @staticmethod
    def handle_last(period):
        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 end, start

class DetailVerificationService:

    @staticmethod
    def init_data(context, materi):
        context["materi_data"] = materi
        context["kriteria_list"] = VerificationSetting.objects.filter(
            archived=False)
        if materi.status == "PENDING" or materi.status == "REVISION":
            riwayat = False
        else:
            riwayat = True
        context["riwayat"] = riwayat
        context["verification_report"] = materi.verificationreport_set.first()

    @staticmethod
    def initilize_kriteria(items) -> list:
        kriteria = []
        for item in 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)
        return kriteria

    @staticmethod
    def action_approve(materi):
        DetailVerificationService.save_materi_status(materi, "APPROVE")

    @staticmethod
    def action_disapprove(materi):
        DetailVerificationService.save_materi_status(materi, "DISAPPROVE")

    @staticmethod
    def save_materi_status(materi, status: str):
        materi.status = status
        materi.save()

class StatisticService:

    @staticmethod
    def get_filter_set(period, kwargs):
        filter_set = {}
        form = PeriodForm()
        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
            end, start = StatisticService.init_date(DEFAULT_PERIOD, form_data)
            filter_set["start"] = start
            filter_set["end"] = end
            filter_set["categories"] = form_data["categories"]
        return filter_set

    @staticmethod
    def init_date(default_period, form_data):
        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 = DateHelperService.get_start_end_date(form_data["period"])
        else:
            start, end = DateHelperService.get_start_end_date(default_period)
        return end, start

    @staticmethod
    def generate_view_stat(chart_data, colors, data_sets, label, time_step):
        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)


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


    @staticmethod
    def filter_qs(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()

class LaporanMateriService:

    @staticmethod
    def initilize_report():
        laporan_materi = LaporanMateri.objects.filter(is_rejected=False)
        materi_dilaporkan = Materi.objects \
            .filter(laporanmateri__id__in=laporan_materi, status="APPROVE") \
            .annotate(jumlah_laporan=Count('laporanmateri__materi_id')) \
            .order_by('-jumlah_laporan') \
            .distinct()
        materi_diblokir = Materi.objects.filter(status="BLOCKED")
        return laporan_materi, materi_dilaporkan, materi_diblokir