Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: differentiate attachment types refs #112519 #37

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 48 additions & 3 deletions ninetofiver/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,39 @@ class UserRelativeAdmin(admin.ModelAdmin):
autocomplete_fields = ('user',)


class AttachmentAdminForm(forms.ModelForm):
model = models.Attachment
def clean(self):
t = self.cleaned_data.get("type")
if t == "c" and not self.request.user.has_perm("ninetofiver.change_contract"):
raise forms.ValidationError("You are not allowed to create contract attachments")
elif t == "l" and not self.request.user.has_perm("ninetofiver.change_leave"):
raise forms.ValidationError("You are not allowed to create leave attachments")
return self.cleaned_data

@admin.register(models.Attachment)
class AttachmentAdmin(admin.ModelAdmin):
form = AttachmentAdminForm

def get_form(self, request, *args, **kwargs):
form = super(AttachmentAdmin, self).get_form(request, *args, **kwargs)
form.request = request
return form

def link(self, obj):
return format_html('<a href="%s">%s</a>' % (obj.get_file_url(), str(obj)))

list_display = ('__str__', 'user', 'name', 'description', 'file', 'slug', 'link')
def get_queryset(self, request):
qs = super(AttachmentAdmin, self).get_queryset(request)
if not request.user.has_perm("ninetofiver.change_leave"):
qs = qs.exclude(type="l")
if not request.user.has_perm("ninetofiver.change_contract"):
qs = qs.exclude(type="c")
return qs

list_display = ('__str__', 'user', 'name', 'description', 'file', 'slug', 'link', 'type')
list_filter = ["type"]
readonly_fields=('type',)


@admin.register(models.Holiday)
Expand Down Expand Up @@ -237,12 +264,22 @@ def formfield_for_foreignkey(self, db_field, request, **kwargs):

return formfield

class LeaveAdminForm(forms.ModelForm):
model = models.Leave

def clean(self):
if self.cleaned_data.get('attachments') is not None:
for att in self.cleaned_data.get('attachments'):
if att.type == "c":
raise forms.ValidationError("You cannot add a non-leave attachment to a leave!")
return self.cleaned_data

@admin.register(models.Leave)
class LeaveAdmin(admin.ModelAdmin):
"""Leave admin."""
change_form_template = "ninetofiver/admin/leave_changeform.html"

form = LeaveAdminForm

def get_queryset(self, request):
return (
super().get_queryset(request)
Expand Down Expand Up @@ -292,6 +329,7 @@ def attachment(self, obj):
return format_html('<br>'.join('<a href="%s">%s</a>'
% (x.get_file_url(), str(x)) for x in list(obj.attachments.all())))


def company(self, obj):
"""Company under which is user employed. If he is employed under more than one,
then the first one is shown in related column, but in filters, all his/her companies are used."""
Expand Down Expand Up @@ -464,7 +502,14 @@ def __init__(self, *args, **kwargs):
redmine_project_choices = cache.get_or_set('contract_admin_redmine_id_choices',
redmine.get_redmine_project_choices)
self.fields['redmine_id'].widget = select2_widgets.Select2Widget(choices=redmine_project_choices)


def clean(self):
if self.cleaned_data.get('attachments') is not None:
for att in self.cleaned_data.get('attachments'):
log.info(att.type)
if att.type == "l":
raise forms.ValidationError("You cannot add a non-contract attachment to a contract!")
return self.cleaned_data

class ContractResource(ModelResource):
"""Contract resource."""
Expand Down
18 changes: 18 additions & 0 deletions ninetofiver/migrations/0095_attachment_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.0 on 2023-09-14 10:33

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('ninetofiver', '0094_alter_userinfo_options'),
]

operations = [
migrations.AddField(
model_name='attachment',
name='type',
field=models.CharField(default='leave', max_length=15),
),
]
18 changes: 18 additions & 0 deletions ninetofiver/migrations/0096_alter_attachment_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.0 on 2023-09-14 12:05

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('ninetofiver', '0095_attachment_type'),
]

operations = [
migrations.AlterField(
model_name='attachment',
name='type',
field=models.CharField(choices=[('n', 'None'), ('l', 'Leave attachment'), ('c', 'Contract attachment')], default='leave', max_length=15),
),
]
18 changes: 18 additions & 0 deletions ninetofiver/migrations/0097_alter_attachment_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.0 on 2023-09-14 12:13

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('ninetofiver', '0096_alter_attachment_type'),
]

operations = [
migrations.AlterField(
model_name='attachment',
name='type',
field=models.CharField(choices=[('n', 'None'), ('l', 'Leave attachment'), ('c', 'Contract attachment')], default=('n', 'None'), max_length=15),
),
]
6 changes: 6 additions & 0 deletions ninetofiver/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,11 +498,17 @@ def generate_file_path(instance, filename):
"""Generate a file path."""
return 'attachments/user_%s/%s/%s' % (instance.user.id, instance.slug, filename)


TYPE_NONE = "n"
TYPE_LEAVE = "l"
TYPE_CONTRACT = "c"

user = models.ForeignKey(auth_models.User, on_delete=models.PROTECT)
name = models.CharField(max_length=255)
description = models.TextField(max_length=255, blank=True, null=True)
file = models.FileField(upload_to=generate_file_path)
slug = models.SlugField(default=uuid.uuid4, editable=False)
type = models.CharField(max_length=15,editable=False,default=(TYPE_NONE,_("No type")), choices=Choices((TYPE_NONE,_("No type")),(TYPE_LEAVE,_("Leave attachment")),(TYPE_CONTRACT,_("Contract attachment"))))

class Meta(BaseModel.Meta):
permissions = (
Expand Down
19 changes: 19 additions & 0 deletions ninetofiver/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,25 @@ def on_timesheet_pre_save(sender, instance, created=False, **kwargs):
}
)

@receiver(m2m_changed, sender=models.Leave.attachments.through)
@receiver(m2m_changed, sender=models.Contract.attachments.through)
def on_attachment_changed(sender, instance, action, pk_set, **kwargs):
"""Changes type of attachment based on where it is added/removed"""
if action == "pre_add":
for pk in pk_set:
att = models.Attachment.objects.get(pk=pk)
#* Set type based on instance
if isinstance(instance,models.Leave):
att.type = models.Attachment.TYPE_LEAVE
elif isinstance(instance,models.Contract):
att.type = models.Attachment.TYPE_CONTRACT
att.save()
elif action == "pre_remove":
for pk in pk_set:
att = models.Attachment.objects.get(pk=pk)
att.type = models.Attachment.TYPE_NONE
att.save()


@receiver(pre_save, sender=models.ContractUserGroup)
def on_contract_user_group_pre_save(sender, instance, created=False, **kwargs):
Expand Down