Skip to content

Commit

Permalink
Feat: Add Mixin to add created_by and updated_by for configuration mo…
Browse files Browse the repository at this point in the history
…dels
  • Loading branch information
Ashutosh619-sudo committed Dec 24, 2024
1 parent 29fc361 commit 7bae7c8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
55 changes: 55 additions & 0 deletions fyle_accounting_mappings/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -888,3 +888,58 @@ def bulk_create_ccc_category_mappings(workspace_id: int):
CategoryMapping.objects.bulk_update(
mapping_updation_batch, fields=['destination_account'], batch_size=50
)


class AutoUserTrackManager(models.Manager):
def update_or_create(self, defaults=None, **kwargs):
"""
Overrides the default update_or_create to handle 'user' keyword argument.
"""
user = kwargs.pop('user', None)
defaults = defaults or {}

if user and hasattr(user, 'email'):
defaults['updated_by'] = user.email

instance, created = super().update_or_create(defaults=defaults, **kwargs)

if created and user and hasattr(user, 'email'):
instance.created_by = user.email
instance.save(user=user)

return instance, created

class AutoUserTrackModelMixin(models.Model):
"""
Mixin to automatically set created_by and updated_by fields.
Stores only the user's email.
"""
created_by = models.CharField(
max_length=255,
null=True,
blank=True,
help_text="Email of the user who created this record"
)
updated_by = models.CharField(
max_length=255,
null=True,
blank=True,
help_text="Email of the user who last updated this record"
)

objects = AutoUserTrackManager()

class Meta:
abstract = True

def save(self, *args, **kwargs):
"""
Override the save method to set created_by and updated_by fields.
Expects a 'user' keyword argument containing the user instance.
"""
user = kwargs.pop('user', None)
if user and hasattr(user, 'email'):
if not self.pk:
self.created_by = user.email
self.updated_by = user.email
super().save(*args, **kwargs)
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

setuptools.setup(
name='fyle-accounting-mappings',
version='1.35.0',
version='1.36.0',
author='Shwetabh Kumar',
author_email='[email protected]',
description='Django application to store the fyle accounting mappings in a generic manner',
Expand Down

0 comments on commit 7bae7c8

Please sign in to comment.