Fakultas Ilmu Komputer UI

models.py 7.58 KB
Newer Older
Saul Andre's avatar
Saul Andre committed
1
import random
2
import datetime
3

4
from django.contrib.postgres import search
5
from django.core.exceptions import ValidationError
6
from django.core.validators import MinValueValidator, MaxValueValidator
7
from django.db import models
8
from django.utils import timezone
9

igor lestin sianipar's avatar
igor lestin sianipar committed
10
11
12
from authentication.models import User

VERIFICATION_STATUS = [
13
14
    ("PENDING", "Diproses"),
    ("APPROVE", "Diterima"),
15
    ("DISAPPROVE", "Ditolak"),
16
    ("REVISION", "Perbaikan"),
17
    ("BLOCKED", "Diblokir"),
igor lestin sianipar's avatar
igor lestin sianipar committed
18
]
Samuel Dimas's avatar
Samuel Dimas committed
19

20

Samuel Dimas's avatar
Samuel Dimas committed
21
# Create your models here.
22
23


Saul Andre's avatar
Saul Andre committed
24
25
def getRandomColor():
    color = "%06x" % random.randint(0, 0xFFFFFF)
26
27
    return color

28
29
def current_year():
    return datetime.date.today().year
Saul Andre's avatar
Saul Andre committed
30
31
32

class Category(models.Model):
    name = models.CharField(max_length=20)
33
34
    description = models.TextField(blank=False, default="")
    archived = models.BooleanField(default=False, blank=False)
35
    archived_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Saul Andre's avatar
Saul Andre committed
36
37
38
39

    def __str__(self):
        return self.name

40

41
42
43
44
45
46
47
48
49
50
51
52
53
54
class MateriManager(models.Manager):
    def search(self, search_text):
        search_vector = search.SearchVector("title", weight="A")
        search_query = search.SearchQuery(search_text)

        search_rank = search.SearchRank(search_vector, search_query)

        search_result = (
            self.get_queryset().filter(_search_vector=search_query).annotate(rank=search_rank).order_by("-rank")
        )

        return search_result


55
class Materi(models.Model):
igor lestin sianipar's avatar
igor lestin sianipar committed
56
57
    cover = models.ImageField()
    content = models.FileField()
58
59
    title = models.CharField(max_length=50, default="Judul")
    author = models.CharField(max_length=30, default="Penyusun")
igor lestin sianipar's avatar
igor lestin sianipar committed
60
    uploader = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
61
    publisher = models.CharField(max_length=30, default="Penerbit")
62
    release_year = models.IntegerField(default=current_year)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
63
    pages = models.IntegerField(default=0)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
64
    descriptions = models.TextField(default="Deskripsi")
65
    status = models.CharField(max_length=30, choices=VERIFICATION_STATUS, default=VERIFICATION_STATUS[0][0])
Saul Andre's avatar
Saul Andre committed
66
    categories = models.ManyToManyField(Category)
67
68
69
    date_created = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(auto_now=True)

70
71
72
73
74
75
76
77
78
79
80
    _search_vector = search.SearchVectorField(null=True, editable=False)

    objects = MateriManager()

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        if "update_fields" not in kwargs or "_search_vector" not in kwargs["update_fields"]:
            self._search_vector = search.SearchVector("title", weight="A")
            self.save(update_fields=["_search_vector"])

81
82
83
84
    @property
    def is_published(self):
        published = False
        if self.verificationreport_set.exists():
85
86
            report = self.verificationreport_set.latest("timestamp")
            published = True if report.status == "Diterima" else False
87
88
89
90
91
92
        return published

    @property
    def published_date(self):
        published_date = None
        if self.verificationreport_set.exists():
93
94
            report = self.verificationreport_set.latest("timestamp")
            if report.status == "Diterima":
95
96
                published_date = report.timestamp
        return published_date
97

98
99
100
101
    @property
    def like_count(self):
        count = Like.objects.filter(materi=self).count()
        return count
102
103
104
105
106
    
    @property
    def comment_count(self):
        count = Comment.objects.filter(materi=self).count()
        return count
107

108
109
110
111
112
113
    @property
    def is_like(self):
        like = False
        if Like.objects.filter(materi=self).exists():
            like = True

114

115
class Comment(models.Model):
116
117
    username = models.CharField(max_length=100)
    profile = models.CharField(max_length=100, default=getRandomColor)
118
    comment = models.CharField(max_length=240, default="comments")
119
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True)
120
    user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
121
    timestamp = models.DateTimeField(default=timezone.now)
122
123

    def __str__(self):
124
        return self.username
125

126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    @property
    def like_count(self):
        count = LikeComment.objects.filter(comment=self).count()
        return count
    
    @property
    def dislike_count(self):
        count = DislikeComment.objects.filter(comment=self).count()
        return count


class LikeComment(models.Model):
    comment = models.ForeignKey(Comment, models.SET_NULL, null=True)
    timestamp = models.DateTimeField(default=timezone.now)
    session_id = models.CharField(max_length=32, blank=False)


class DislikeComment(models.Model):
    comment = models.ForeignKey(Comment, models.SET_NULL, null=True)
    timestamp = models.DateTimeField(default=timezone.now)
    session_id = models.CharField(max_length=32, blank=False)

148
149
150
151
152
153

class Like(models.Model):
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True)
    timestamp = models.DateTimeField(default=timezone.now)
    session_id = models.CharField(max_length=32, blank=False)

154

155
156
157
158
class ReqMaterial(models.Model):
    title = models.CharField(max_length=100)
    timestamp = models.DateTimeField(default=timezone.now)

159
160

class ViewStatistics(models.Model):
161
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True, related_name="baca")
162
163
164
165
    timestamp = models.DateTimeField(default=timezone.now)


class DownloadStatistics(models.Model):
166
167
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True, related_name="unduh")
    downloader = models.ForeignKey(User, models.SET_NULL, blank=True, null=True, related_name="riwayat_unduh")
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    timestamp = models.DateTimeField(default=timezone.now)


class DummyLike(models.Model):
    item = models.ForeignKey(Like, on_delete=models.CASCADE)


class DummyViewStatistics(models.Model):
    item = models.ForeignKey(ViewStatistics, on_delete=models.CASCADE)


class DummyDownloadStatistics(models.Model):
    item = models.ForeignKey(DownloadStatistics, on_delete=models.CASCADE)


class DummyComment(models.Model):
    item = models.ForeignKey(Comment, on_delete=models.CASCADE)
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203


class Rating(models.Model):
    materi = models.ForeignKey(Materi, models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    timestamp = models.DateTimeField(default=timezone.now)
    score = models.IntegerField()

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if 1 <= self.score <= 5:
            super().save(force_insert, force_update, using, update_fields)
        else:
            raise ValidationError("Rating score must be integer between 1-5")

    def __str__(self):
        return "Material:{} | User:{} | Rating:{}".format(self.materi.title, self.user.name, self.score)

    class Meta:
        unique_together = ["materi", "user"]
204
205
206
207
208
209
210
211
212
213
214


class RatingContributor(models.Model):
    timestamp = models.DateTimeField(auto_now=True)
    score = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if 1 <= self.score <= 5:
            super().save(force_insert, force_update, using, update_fields)
        else:
215
216
            raise ValidationError("Rating score must be integer between 1-5")

217

218
219
220
221
222
class LaporanMateri(models.Model):
    materi = models.ForeignKey(Materi, on_delete=models.CASCADE, max_length=120)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    laporan = models.TextField(validators=[MinValueValidator(30), MaxValueValidator(120)], default="")
    timestamp = models.DateTimeField(default=timezone.now)
223
    is_rejected = models.BooleanField(default=False)