def unpaid_transaction_notification():
    today = datetime.now(pytz.timezone('US/Eastern'))
    for transaction in Transaction.objects.exclude(autorefill=None)\
            .filter(paid=False,
                    status='S',
                    state='C',
                    autorefill__customer__charge_getaway='CP',
                    autorefill__refill_type='MN',
                    started__range=(today - timedelta(days=1),
                                    today - timedelta(hours=2))):
        try:
            message = "HI %s, the plan for %s%s expires on %s," \
                      "to avoid interruption of your cellphone service" \
                      " Please make a  payment of %s  before expire date," \
                      " Regards, %s" % \
                      (
                          transaction.customer.first_name,
                          PhoneNumber.objects.filter(company=transaction.company,
                                                     customer=transaction.autorefill.customer,
                                                     number=transaction.phone_number_str)[0].title,
                          ' (' + transaction.phone_number_str + ')',
                          transaction.autorefill.renewal_date.strftime("%m/%d/%y"),
                          search_unused_charges(transaction.autorefill, transaction.cost),
                          transaction.company.company_name
                      )
            Notification.objects.create(
                company=transaction.company,
                customer=transaction.customer,
                email=transaction.customer.primary_email,
                phone_number=transaction.autorefill.phone_number,
                subject='Unpaid refill notification',
                body=message,
                send_with=transaction.customer.send_status)
        except Exception, e:
            logger.error("Exception: %s. Trace: %s." % (e, traceback.format_exc(limit=10)))
def cash_prepayment_notification():
    today = datetime.now(pytz.timezone('US/Eastern')).date()
    for day, message in [[3, 'SECOND REMINDER'], [6, '']]:
        payment_day = today + timedelta(days=day)
        for autorefill in AutoRefill.objects.filter(
                renewal_date=payment_day,
                trigger=AutoRefill.TRIGGER_SC,
                enabled=True,
                customer__charge_getaway=Customer.CASH_PREPAYMENT):
            amount, tax = autorefill.calculate_cost_and_tax()
            need_paid = search_unused_charges(autorefill, amount)
            if need_paid:
                prepayment_customer_notification(autorefill, need_paid, message)
def precharge_job():
    today = datetime.now(pytz.timezone('US/Eastern')).date()
    for company in CompanyProfile.objects.filter(superuser_profile=False):
        if not company.authorize_precharge_days:
            continue
        precharge_today = []
        t = 0
        d = 1
        payment_day = today + timedelta(days=company.authorize_precharge_days)
        for autorefill in AutoRefill.objects.filter(
                company=company,
                renewal_date=payment_day,
                trigger=AutoRefill.TRIGGER_SC,
                enabled=True,
        ).exclude(
                    Q(customer__charge_getaway=Customer.CASH) |
                    Q(customer__charge_getaway=Customer.CASH_PREPAYMENT)):
            if (autorefill.customer.charge_getaway == Customer.DOLLARPHONE and
                        autorefill.plan.plan_type == Plan.DOMESTIC_TOPUP):
                continue
            if not autorefill.check_renewal_end_date(today=payment_day):
                # return self.enabled
                # if False == not enabled then skip precharge
                continue
            check_twilio_confirm_sms, confirm_log = autorefill.check_twilio_confirm_sms()
            if autorefill.pre_refill_sms and not check_twilio_confirm_sms:
                continue

            amount, tax = autorefill.calculate_cost_and_tax()
            need_paid = search_unused_charges(autorefill, amount)
            if need_paid:
                if Charge.DOLLARPHONE == autorefill.customer.charge_getaway:
                    need_paid = autorefill.plan.plan_cost
                charge = autorefill.create_charge(need_paid, tax)
                if Charge.DOLLARPHONE == charge.payment_getaway:
                    queue_precharge.apply_async(args=[charge], countdown=60*d)
                    d += 1
                elif charge.customer.id in precharge_today:
                    t += 1
                    queue_precharge.apply_async(args=[charge], countdown=200*t)
                else:
                    precharge_today.append(charge.customer.id)
                    queue_precharge.delay(charge)
def insufficient_funds():
    today = datetime.now(pytz.timezone('US/Eastern')).date()
    payment_day = today + timedelta(days=1)
    i = 1
    for company in CompanyProfile.objects.filter(superuser_profile=False, insufficient_funds_notification=True):
        unpaid_autorefills = []
        for autorefill in AutoRefill.objects.filter(
                trigger=AutoRefill.TRIGGER_SC,
                enabled=True,
                company=company,
                renewal_date=payment_day,
                customer__charge_getaway=Customer.CASH_PREPAYMENT,
        ):
            amount, tax = autorefill.calculate_cost_and_tax()
            need_paid = search_unused_charges(autorefill, amount)
            if need_paid:
                unpaid_autorefills.append('<br/>%s needs $%s for <a href="%s">%s</a>' %
                                          (autorefill.customer,
                                           need_paid,
                                           reverse('autorefill_update', args=[autorefill.id]),
                                           autorefill.phone_number))
        if unpaid_autorefills:
            subject = "[%s] Unpaid scheduled refills at %s " % (company.company_name, payment_day)
            body = 'Unpaid scheduled refills:%s<br/><br/>Regards, %s' % (
                ','.join(unpaid_autorefills), company.company_name)
            notification = Notification.objects.create(
                company=CompanyProfile.objects.get(superuser_profile=True),
                email=company.email_id,
                subject=subject,
                body=body,
                send_with=Notification.MAIL)
            try:
                if notification.send_with == notification.GV_SMS:
                    notification.send_notification(i=i)
                    i += 1
                else:
                    notification.send_notification()
            except Exception, e:
                logger.error("Exception: %s. Trace: %s." % (e, traceback.format_exc(limit=10)))