Fakultas Ilmu Komputer UI

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

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

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

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

19

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


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

Saul Andre's avatar
Saul Andre committed
27
28
29

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

    def __str__(self):
        return self.name

37

38
39
40
41
42
43
44
45
46
47
48
49
50
51
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


52
class Materi(models.Model):
igor lestin sianipar's avatar
igor lestin sianipar committed
53
54
    cover = models.ImageField()
    content = models.FileField()
55
56
    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
57
    uploader = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
58
    publisher = models.CharField(max_length=30, default="Penerbit")
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
59
    pages = models.IntegerField(default=0)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
60
    descriptions = models.TextField(default="Deskripsi")
61
    status = models.CharField(max_length=30, choices=VERIFICATION_STATUS, default=VERIFICATION_STATUS[0][0])
Saul Andre's avatar
Saul Andre committed
62
    categories = models.ManyToManyField(Category)
63
64
65
    date_created = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(auto_now=True)

66
67
68
69
70
71
72
73
74
75
76
    _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"])

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

    @property
    def published_date(self):
        published_date = None
        if self.verificationreport_set.exists():
89
90
            report = self.verificationreport_set.latest("timestamp")
            if report.status == "Diterima":
91
92
                published_date = report.timestamp
        return published_date
93

94
95
96
97
    @property
    def like_count(self):
        count = Like.objects.filter(materi=self).count()
        return count
98

99

100
class Comment(models.Model):
101
102
    username = models.CharField(max_length=100)
    profile = models.CharField(max_length=100, default=getRandomColor)
103
    comment = models.CharField(max_length=240, default="comments")
104
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True)
105
    user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
106
    timestamp = models.DateTimeField(default=timezone.now)
107
108

    def __str__(self):
109
        return self.username
110
111
112
113
114
115
116


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)

117

118
119
120
121
class ReqMaterial(models.Model):
    title = models.CharField(max_length=100)
    timestamp = models.DateTimeField(default=timezone.now)

122
123

class ViewStatistics(models.Model):
124
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True, related_name="baca")
125
126
127
128
    timestamp = models.DateTimeField(default=timezone.now)


class DownloadStatistics(models.Model):
129
130
    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")
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    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)
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166


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"]
167
168
169
170
171
172
173
174
175
176
177


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:
178
179
            raise ValidationError("Rating score must be integer between 1-5")

180

181
182
183
184
185
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)
186
    is_rejected = models.BooleanField(default=False)