members_email.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import datetime
  4. from django.core.management.base import BaseCommand, CommandError
  5. from django.db.models import Q
  6. from coin.members.models import Member
  7. from coin.offers.models import Offer
  8. from coin.offers.models import OfferSubscription
  9. class Command(BaseCommand):
  10. help = """Returns email addresses of members in a format suitable for bulk importing in Sympa."""
  11. def add_arguments(self, parser):
  12. parser.add_argument('--subscribers', action='store_true',
  13. help='Return only the email addresses of subscribers to any offers.')
  14. parser.add_argument('--offer', metavar='OFFER-ID or OFFER-REF',
  15. help='Return only the email addresses of subscribers to the specified offer')
  16. def handle(self, *args, **options):
  17. if options['subscribers']:
  18. today = datetime.date.today()
  19. offer_subscriptions = OfferSubscription.objects.filter(
  20. Q(resign_date__gt=today)
  21. | Q(resign_date__isnull=True)
  22. )
  23. members = [s.member for s in offer_subscriptions]
  24. elif options['offer']:
  25. try:
  26. # Try to find the offer by its reference
  27. offer = Offer.objects.get(reference=options['offer'])
  28. except Offer.DoesNotExist:
  29. try:
  30. # No reference found, maybe it's an offer_id
  31. offer_id = int(options['offer'])
  32. offer = Offer.objects.get(pk=offer_id)
  33. except Offer.DoesNotExist:
  34. raise CommandError('Offer "%s" does not exist' % options['offer'])
  35. except (IndexError, ValueError):
  36. raise CommandError('Please enter a valid offer reference or id')
  37. today = datetime.date.today()
  38. offer_subscriptions = OfferSubscription.objects.filter(
  39. # Fetch all OfferSubscription to the given Offer
  40. Q(offer=offer)
  41. # Check if OfferSubscription isn't resigned
  42. & (Q(resign_date__isnull=True) | Q(resign_date__gt=today))
  43. ).select_related('member')
  44. members = [s.member for s in offer_subscriptions]
  45. else:
  46. members = Member.objects.filter(status='member')
  47. emails = list(set([m.email for m in members if m.status == 'member']))
  48. for email in emails:
  49. self.stdout.write(email)