2023-04-25 02:28:19 +00:00
|
|
|
from rest_framework import serializers
|
2023-04-19 02:18:13 +00:00
|
|
|
|
2023-04-12 09:59:13 +00:00
|
|
|
from accounts.models import AccountTemplate, Account
|
2023-01-16 11:02:09 +00:00
|
|
|
from common.serializers import SecretReadableMixin
|
2022-09-23 10:59:19 +00:00
|
|
|
from .base import BaseAccountSerializer
|
2022-08-24 08:36:42 +00:00
|
|
|
|
|
|
|
|
2022-09-23 10:59:19 +00:00
|
|
|
class AccountTemplateSerializer(BaseAccountSerializer):
|
2023-04-25 02:28:19 +00:00
|
|
|
is_sync_account = serializers.BooleanField(default=False, write_only=True)
|
|
|
|
_is_sync_account = False
|
|
|
|
|
2022-09-23 10:59:19 +00:00
|
|
|
class Meta(BaseAccountSerializer.Meta):
|
2022-08-24 08:36:42 +00:00
|
|
|
model = AccountTemplate
|
2023-04-25 02:28:19 +00:00
|
|
|
fields = BaseAccountSerializer.Meta.fields + ['is_sync_account']
|
2022-08-24 08:36:42 +00:00
|
|
|
|
2023-04-25 02:28:19 +00:00
|
|
|
def sync_accounts_secret(self, instance, diff):
|
|
|
|
if not self._is_sync_account or 'secret' not in diff:
|
2023-04-12 09:59:13 +00:00
|
|
|
return
|
|
|
|
|
2023-04-25 02:28:19 +00:00
|
|
|
accounts = Account.objects.filter(source_id=instance.id)
|
|
|
|
instance.bulk_sync_account_secret(accounts, self.context['request'].user.id)
|
2023-04-19 02:18:13 +00:00
|
|
|
|
2023-04-25 02:28:19 +00:00
|
|
|
def validate(self, attrs):
|
|
|
|
self._is_sync_account = attrs.pop('is_sync_account', None)
|
|
|
|
attrs = super().validate(attrs)
|
|
|
|
return attrs
|
2023-04-12 09:59:13 +00:00
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
2023-04-25 02:28:19 +00:00
|
|
|
diff = {
|
|
|
|
k: v for k, v in validated_data.items()
|
|
|
|
if getattr(instance, k) != v
|
|
|
|
}
|
2023-04-12 09:59:13 +00:00
|
|
|
instance = super().update(instance, validated_data)
|
2023-04-25 02:28:19 +00:00
|
|
|
self.sync_accounts_secret(instance, diff)
|
2023-04-12 09:59:13 +00:00
|
|
|
return instance
|
2022-11-28 07:54:16 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AccountTemplateSecretSerializer(SecretReadableMixin, AccountTemplateSerializer):
|
|
|
|
class Meta(AccountTemplateSerializer.Meta):
|
|
|
|
extra_kwargs = {
|
|
|
|
'secret': {'write_only': False},
|
|
|
|
}
|