def update_mach_billables(): """ Goes through all billable items tied to mach (SMS records) and tries to make sure that they are properly associated with rates from mach. """ mach_data = get_mach_data(days=3) try: # rateless billables are Mach Billables that do not have a delivered date rateless_billables = MachSMSBillable.get_rateless() for billable in rateless_billables: billable.sync_attempts.append(datetime.datetime.utcnow()) for data in mach_data: phone_number = data[3] if phone_number == billable.phone_number: mach_number = MachPhoneNumber.get_by_number(phone_number, data) rate_item = MachSMSRate.get_by_number(billable.direction, mach_number) billable.calculate_rate(rate_item) billable.save() billable.update_mach_delivery_status(data) billable.save() if billable.rate_id and billable.mach_delivered_date: break deal_with_delinquent_mach_billable(billable) except Exception as e: logging.error("There was an error updating mach billables: %s" % e)
def handle_api_response(cls, message, **kwargs): response = kwargs.get('response', None) logging.info("[Billing] Mach API Response %s" % response) # temporary measure, charge all messages rate_item = MachSMSRate.get_default(direction=OUTGOING, country="USA", network="dimagi") billable = cls.new_billable(rate_item, message) if billable: now = datetime.datetime.now(tz=pytz.utc) billable.contacted_mach_api = now billable.mach_id = "dimagi-retro" billable.mach_delivery_status = "delivered" billable.mach_delivered_date = now return if isinstance(response, str) or isinstance(response, unicode): api_success = bool("+OK" in response) if api_success: test_mach_data = kwargs.get('_test_scrape') mach_data = test_mach_data if test_mach_data else get_mach_data() for mach_row in mach_data: phone_number = mach_row[3] if phone_number != message.phone_number: continue mach_number = MachPhoneNumber.get_by_number(message.phone_number, mach_row) rate_item = MachSMSRate.get_by_number(message.direction, mach_number) if mach_number else None billable = cls.new_billable(rate_item, message) if billable: billable.contacted_mach_api = datetime.datetime.now(tz=pytz.utc) billable.update_mach_delivery_status(mach_row) billable.save() return logging.error("[Billing] MACH API Response was successful, but creating the MACH " "billable was not. SMSLog # %s" % message.get_id) else: logging.error("[Billing] There was an error retrieving message delivery information from MACH.") else: logging.error("[Billing] There was an error accessing the MACHI API.") else: logging.error("[Billing] There was an error while trying to send an SMS via MACH.")