myModel.py 5.76 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
from django.db import models
from django.contrib.auth.models import User
from rest_framework import serializers
from backend.signals import new_revision_saved
import reversion
from django.utils import timezone
from backend.models.tools import PendingModeration, PendingModerationSerializer
from django.conf import settings
from django.contrib.contenttypes.models import ContentType


class MyModel(models.Model):
    """
        All models in the app deppend of this one !
    """

    moderated_by = models.ForeignKey(
        User, null=True, on_delete=models.SET_NULL, related_name='moderated')
    moderated_on = models.DateTimeField(null=True)

    updated_on = models.DateTimeField(null=True)
    updated_by = models.ForeignKey(
        User, null=True, on_delete=models.SET_NULL, related_name='updated')

    class Meta:
        abstract = True


# class MyModelVersionned(MyModel):
#     class Meta:
#         abstract = True


def is_member(group_name, user):
    return user.groups.filter(name=group_name).exists()


def date_time_to_str(date):
    s = serializers.DateTimeField()


class MyModelSerializer(serializers.ModelSerializer):
    moderated_on = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_on = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", read_only=True)
    # moderated_by = serializers.ReadOnlyField()
    # updated_by = serializers.ReadOnlyField()
    # TODO Changed

    updated_by_username = serializers.SerializerMethodField(read_only=True)

    def get_updated_by_username(self, obj):
        if obj.updated_by:
            return obj.updated_by.username
        else:
            return None

    class Meta:
        model = MyModel

    def moderation_required(self):
        user = self.context['request'].user
        request = self.context['request']

        if user.is_staff:
            return False

        if settings.MODERATION_ACTIVATED:
            if request.method in ['POST', 'PUT']:  # should be always the case
                if is_member('Moderator', request.user):
                    return False
                else:
                    return True

        return False

    def set_model_attr_no_moder(self, moderated_and_updated):
        user = self.context['request'].user
        now = timezone.now()
        self.validated_data['moderated_by'] = user
        self.validated_data['moderated_on'] = now

        if moderated_and_updated:
            self.validated_data['updated_by'] = user
            self.validated_data['updated_on'] = now

    def set_model_attr_for_moder(self):
        user = self.context['request'].user
        self.validated_data['updated_by'] = user.pk
        self.validated_data['updated_on'] = timezone.now().strftime(
            "%Y-%m-%d %H:%M:%S")

        # also return the user because it's usefull...
        return user

    def clean_validated_data(self):
        self.validated_data['moderated_by'] = None
        self.validated_data['moderated_on'] = None
        self.validated_data['updated_by'] = None
        self.validated_data['updated_on'] = None

    def save(self, **kwargs):
        self.clean_validated_data()
        if self.moderation_required():
            print("Modération requise")
            user = self.set_model_attr_for_moder()

            if self.instance is None:  # we need to create the main model
                self.instance = super(
                    MyModelSerializer, self).save(**kwargs)

            ct = ContentType.objects.get_for_model(self.Meta.model)
            objs_pending_db = PendingModeration.objects.filter(
                content_type=ct, object_id=self.instance.pk)

            if len(objs_pending_db) > 0:
                pending_instance = objs_pending_db[0]
                pending_instance.new_object = self.validated_data
                pending_instance.save()
            else:
                pending_instance = PendingModeration(
                    referenced_object=self.instance,
                    author=user,
                    new_object=self.validated_data
                )
                pending_instance.save()

            return self.instance

        else:
            print("Pas besoin de modération")
            if self.instance is None:
                return super(MyModelSerializer, self).save(**kwargs)
            else:
                # We check if we don't have any moderation pending
                moderated_and_updated = True
                print(self.Meta.model)
                ct = ContentType.objects.get_for_model(self.Meta.model)
                objs_pending_db = PendingModeration.objects.filter(
                    content_type=ct, object_id=self.instance.pk)
                print(len(objs_pending_db))
                if len(objs_pending_db) > 0:
                    # obj_pending_db = objs_pending_db[0]
                    # there should be only one
                    # TODO add checks to know if moderator did some modifications or not
                    # Change updated_by and on accordingly
                    # if obj_pending_db.new_object == self.validated_date
                    #   moderated_and_updated = False
                    objs_pending_db.delete()

            self.set_model_attr_no_moder(moderated_and_updated)
            print('Pas besoin de modération')
            return super(MyModelSerializer, self).save(**kwargs)


# class MyModelVersionnedSerializer(MyModelSerializer):

#     def save(self, **kwargs):
#         user = self.set_model_attr()

#         # Create a revision for the update or creation
#         with reversion.create_revision():
#             super(MyModelVersionnedSerializer, self).save(**kwargs)
#             reversion.set_user(user)

#         # Signal save to perform concat of revisions
#         new_revision_saved.send(sender=self.__class__, obj=self.instance)