Skip to content

Commit

Permalink
Merge pull request #109 from Elektordi/send_cdr
Browse files Browse the repository at this point in the history
Add feature to send cdr by email
  • Loading branch information
mwolff44 committed Feb 7, 2018
2 parents 1dcefc0 + b598ed9 commit f9e1b5e
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 19 deletions.
Empty file.
Empty file.
109 changes: 109 additions & 0 deletions pyfreebilling/cdr/management/commands/send_cdr_by_email.py
@@ -0,0 +1,109 @@
# Guillaume Genty, Waycom
# Dec. 2017

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from pyfreebilling.cdr.models import CDR, Company, RateCard
from datetime import date, time, timedelta, datetime
import calendar
from django.db import connection
from django.utils import timezone
from pprint import pprint
from dateutil.tz import tzlocal
from StringIO import StringIO
import csv
from django.core.mail import EmailMessage, mail_admins

TODAY = date.today()
MIDNIGHT = datetime.combine(TODAY, time.min)

CDR_PERIODS = {
'cdr_day': (MIDNIGHT - timedelta(days=1), MIDNIGHT),
'cdr_week': (MIDNIGHT - timedelta(days=TODAY.weekday()+7), MIDNIGHT - timedelta(days=TODAY.weekday())),
'cdr_month': (datetime.combine((TODAY.replace(day=1)-timedelta(days=1)).replace(day=1), time.min), MIDNIGHT - timedelta(days=TODAY.day-1))
}
#print CDR_PERIODS

class Command(BaseCommand):
help = 'Send all CDR exports by email.'

def add_arguments(self, parser):
parser.add_argument('period', nargs=1, type=str, choices=CDR_PERIODS.keys()+['all'])

def handle(self, *args, **options):

tz = tzlocal()
wantperiod = options['period'][0]

rc_didin = [x.id for x in RateCard.objects.all().filter(rctype='DIDIN')]
rc_emerg = [x.id for x in RateCard.objects.all().filter(rctype='EMERGENCY')]

customers = Company.objects.all().filter(customer_enabled=True)
for cust in customers:

emails = cust.email_address.all().filter(location__startswith='cdr_')
if not emails:
continue

targets = {}
for e in emails:
if not e.location in targets:
targets[e.location] = []
targets[e.location].append(e.email_address)

for period in CDR_PERIODS:
if wantperiod != 'all' and period != wantperiod:
continue
if not period in targets:
continue
#print CDR_PERIODS[period]
try:
p_start = CDR_PERIODS[period][0].replace(tzinfo=tz)
p_end = CDR_PERIODS[period][1].replace(tzinfo=tz)
#p_end = datetime.now().replace(tzinfo=tz) # DEBUG
list = CDR.objects.all().filter(end_stamp__gte=p_start, end_stamp__lt=p_end, customer_id=cust.id, billsec__gt=0)
csvfile = StringIO()
csvwriter = csv.writer(csvfile)
csvwriter.writerow(['direction', 'start', 'end', 'billed_sec', 'from', 'to', 'ip', 'destination', 'price', 'uuid'])
for l in list:
if l.ratecard_id_id in rc_emerg:
continue
if l.ratecard_id_id in rc_didin:
csvwriter.writerow(['IN',
timezone.localtime(l.start_stamp),
timezone.localtime(l.end_stamp),
l.billsec,
l.caller_id_number.lstrip("+"),
l.destination_number.lstrip("+"),
None,
l.sell_destination.encode('ascii',errors='ignore'),
l.total_sell,
l.bleg_uuid
])
else:
csvwriter.writerow(['OUT',
timezone.localtime(l.start_stamp),
timezone.localtime(l.end_stamp),
l.billsec,
l.caller_id_number.lstrip("+"),
l.destination_number.lstrip("+"),
l.customer_ip,
l.sell_destination.encode('ascii',errors='ignore'),
l.total_sell,
l.uuid
])

message = EmailMessage("%s - CDR for customer %s"%(settings.EMAIL_SIGNATURE, cust.name),
"Extract of call data records from %s to %s.\nCSV file attached."%(timezone.localtime(p_start), timezone.localtime(p_end)),
None,
targets[period])
message.attach('%s-%s-%s.csv'%(period.replace('_','-'), cust.slug, p_start.strftime('%Y%m%d')), csvfile.getvalue(), 'text/csv')
message.send()
self.stdout.write('CDRs for %s sent to %s'%(cust.name, ', '.join(targets[period])))
except Exception, e:
self.stderr.write(str(e))

self.stdout.write('OK')

#pprint(connection.queries)

32 changes: 13 additions & 19 deletions pyfreebilling/pyfreebill/models.py
Expand Up @@ -309,13 +309,13 @@ class Meta:
verbose_name = _(u'phone number')
verbose_name_plural = _(u'phone numbers')


LOCATION_CHOICES = (
EMAIL_LOCATION_CHOICES = (
('work', _(u'Work')),
('home', _(u'Home')),
('mobile', _(u'Mobile')),
('fax', _(u'Fax')),
('person', _(u'Personal')),
('billing', _(u'Billing')),
('cdr_month', _(u'CDR (Monthly)')),
('cdr_week', _(u'CDR (Weekly)')),
('cdr_day', _(u'CDR (Daily)')),
('other', _(u'Other'))
)

Expand All @@ -328,8 +328,8 @@ class EmailAddress(models.Model):
content_object = GenericForeignKey('content_type', 'object_id')
email_address = models.EmailField(_(u'email address'))
location = models.CharField(_(u'location'),
max_length=6,
choices=LOCATION_CHOICES,
max_length=10,
choices=EMAIL_LOCATION_CHOICES,
default='work')
date_added = models.DateTimeField(_(u'date added'),
auto_now_add=True)
Expand All @@ -346,18 +346,12 @@ class Meta:
verbose_name_plural = _(u'email addresses')


IM_SERVICE_CHOICES = (
('aim', 'AIM'),
('msn', 'MSN'),
('icq', 'ICQ'),
('jabber', 'Jabber'),
('yahoo', 'Yahoo'),
('skype', 'Skype'),
('qq', 'QQ'),
('sametime', 'Sametime'),
('gadu-gadu', 'Gadu-Gadu'),
('google-talk', 'Google Talk'),
('twitter', 'Twitter'),
LOCATION_CHOICES = (
('work', _(u'Work')),
('home', _(u'Home')),
('mobile', _(u'Mobile')),
('fax', _(u'Fax')),
('person', _(u'Personal')),
('other', _(u'Other'))
)

Expand Down

0 comments on commit f9e1b5e

Please sign in to comment.