from django.apps import AppConfig
from django.urls import reverse
from django.db import models
from django.utils.translation import ugettext_lazy as _


class TeamConfig(AppConfig):
    name = 'froide.team'
    verbose_name = _('Teams')

    def ready(self):
        from froide.account.menu import menu_registry, MenuItem
        from froide.account import account_canceled

        from .services import can_use_team

        def get_account_menu_item(request):
            if not can_use_team(request.user):
                return None

            return MenuItem(
                section='before_settings', order=0,
                url=reverse('team-list'),
                label=_('Your teams')
            )

        menu_registry.register(get_account_menu_item)

        account_canceled.connect(cancel_user)


def cancel_user(sender, user=None, **kwargs):
    from .models import Team

    if user is None:
        return

    # FIXME: teams may become owner-less
    user.teammembership_set.all().delete()

    # Remove teams with no members
    Team.objects.all().annotate(
        num_members=models.Count('members', distinct=True)
    ).filter(num_members=0).delete()

@@ -1,20 +1,33 @@
+import json%0A%0A
 from django.apps imp
@@ -380,16 +380,67 @@
 canceled
+%0A        from froide.account.export import registry
 %0A%0A      
@@ -826,16 +826,60 @@
 nu_item)
+%0A        registry.register(export_user_data)
 %0A%0A      
@@ -1245,16 +1245,16 @@
 t=True)%0A
-
     ).fi
@@ -1274,16 +1274,682 @@
 ers=0).delete()%0A
+%0A%0Adef export_user_data(user):%0A    from .models import TeamMembership%0A%0A    memberships = TeamMembership.objects.filter(%0A        user=user%0A    ).select_related('team')%0A    if not memberships:%0A        return%0A    yield ('teams.json', json.dumps(%5B%0A        %7B%0A            'created': member.created.isoformat() if member.created else None,%0A            'updated': member.updated.isoformat() if member.created else None,%0A            'status': member.status,%0A            'email': member.email,%0A            'role': member.role,%0A            'team_name': member.team.name,%0A            'team_id': member.team_id,%0A        %7D%0A        for member in memberships%5D).encode('utf-8')%0A    )%0A

Add user data export for teams