Skip to content

Labels implementation #135

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

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
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
81 changes: 81 additions & 0 deletions src/backend/core/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.urls import path
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _

from core.services.import_service import ImportService
Expand Down Expand Up @@ -149,10 +151,72 @@ class ThreadAdmin(admin.ModelAdmin):
"id",
"subject",
"snippet",
"get_labels",
"messaged_at",
"created_at",
"updated_at",
)
search_fields = ("subject", "snippet", "labels__name")
list_filter = ("labels",)
fieldsets = (
(None, {"fields": ("subject", "snippet", "display_labels")}),
(
_("Statistics"),
{
"fields": (
"count_unread",
"count_trashed",
"count_draft",
"count_starred",
"count_sender",
"count_messages",
),
"classes": ("collapse",),
},
),
(
_("Metadata"),
{
"fields": ("sender_names", "created_at", "updated_at", "messaged_at"),
"classes": ("collapse",),
},
),
)
readonly_fields = (
"display_labels",
"count_unread",
"count_trashed",
"count_draft",
"count_starred",
"count_sender",
"count_messages",
"messaged_at",
"sender_names",
"created_at",
"updated_at",
)

def get_labels(self, obj):
"""Return a comma-separated list of labels for the thread."""
return ", ".join(label.name for label in obj.labels.all())

get_labels.short_description = _("Labels")
get_labels.admin_order_field = "labels__name"

def display_labels(self, obj):
"""Display labels with their colors in the detail view."""
if not obj.labels.exists():
return _("No labels")

labels_html = []
for label in obj.labels.all():
# Create a colored label display
label_html = f'<span style="display: inline-block; padding: 2px 8px; margin: 2px; border-radius: 3px; background-color: {label.color}; color: white;">{label.name}</span>'
labels_html.append(label_html)

return mark_safe(" ".join(labels_html))

display_labels.short_description = _("Labels")


class MessageRecipientInline(admin.TabularInline):
Expand Down Expand Up @@ -282,3 +346,20 @@ class MessageRecipientAdmin(admin.ModelAdmin):

list_display = ("id", "message", "contact", "type")
search_fields = ("message__subject", "contact__name", "contact__email")


@admin.register(models.Label)
class LabelAdmin(admin.ModelAdmin):
"""Admin class for the Label model"""

list_display = ("id", "name", "slug", "mailbox", "color")
search_fields = ("name", "mailbox__local_part", "mailbox__domain__name")
filter_horizontal = ("threads",)
list_filter = ("mailbox",)
readonly_fields = ("slug",)

def save_model(self, request, obj, form, change):
"""Generate slug from name before saving."""
if not obj.slug or (change and "name" in form.changed_data):
obj.slug = slugify(obj.name.replace("/", "-"))
super().save_model(request, obj, form, change)
48 changes: 47 additions & 1 deletion src/backend/core/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Client serializers for the messages core app."""

from django.db.models import Count, Q
from django.db.models import Count, Exists, OuterRef, Q

from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
Expand Down Expand Up @@ -141,6 +141,7 @@ class ThreadSerializer(serializers.ModelSerializer):
sender_names = serializers.ListField(child=serializers.CharField(), read_only=True)
user_role = serializers.SerializerMethodField()
accesses = serializers.SerializerMethodField()
labels = serializers.SerializerMethodField()

@extend_schema_field(ThreadAccessDetailSerializer(many=True))
def get_accesses(self, instance):
Expand Down Expand Up @@ -170,6 +171,22 @@ def get_user_role(self, instance):
return None
return None

def get_labels(self, instance):
"""Get labels for the thread, filtered by user's mailbox access."""
request = self.context.get("request")
if not request or not hasattr(request, "user"):
return []

labels = instance.labels.filter(
Exists(
models.MailboxAccess.objects.filter(
mailbox=OuterRef("mailbox"),
user=request.user,
)
)
).distinct()
return LabelSerializer(labels, many=True).data

class Meta:
model = models.Thread
fields = [
Expand All @@ -188,6 +205,7 @@ class Meta:
"updated_at",
"user_role",
"accesses",
"labels",
]
read_only_fields = fields # Mark all as read-only for safety

Expand Down Expand Up @@ -480,3 +498,31 @@ class ImportIMAPSerializer(ImportBaseSerializer):
default=0,
min_value=0,
)


class LabelSerializer(serializers.ModelSerializer):
"""Serializer for Label model."""

class Meta:
model = models.Label
fields = ["id", "name", "slug", "color", "mailbox", "threads"]
read_only_fields = ["id", "slug"]
extra_kwargs = {
"mailbox": {"required": True},
"name": {"required": True},
"color": {"required": False, "default": "#E3E3FD"},
"threads": {"required": False, "write_only": True},
}

def validate_name(self, value):
"""Validate label name format."""
if not value:
raise serializers.ValidationError("Label name is required")
return value

def validate_mailbox(self, value):
"""Validate that user has access to the mailbox."""
user = self.context["request"].user
if not value.accesses.filter(user=user).exists():
raise serializers.ValidationError("You don't have access to this mailbox")
return value
Loading
Loading