def handle(self, *args, **options):
        num_sms = 0

        start_datetime = datetime.datetime(*str_to_int_tuple(args[0:6]))
        end_datetime = datetime.datetime(*str_to_int_tuple(args[6:12]))

        for domain in Domain.get_all():
            key = [domain.name, 'SMSLog']
            sms_docs = SMSLog.get_db().view('sms/by_domain',
                                            reduce=False,
                                            startkey=key + [start_datetime.isoformat()],
                                            endkey=key + [end_datetime.isoformat(), {}],
            )

            for sms_doc in sms_docs:
                sms_log = SMSLog.get(sms_doc['id'])
                if options.get('create', False):
                    SmsBillable.create(sms_log)
                    print 'Created billable for SMSLog %s in domain %s from %s' \
                          % (sms_doc['id'], domain.name, sms_log.date)
                else:
                    print 'Found SMSLog %s in domain %s from %s' \
                          % (sms_doc['id'], domain.name, sms_log.date)
                num_sms += 1

        print 'Number of SMSs in datetime range: %d' % num_sms
Esempio n. 2
0
    def handle(self, *args, **options):
        if options.get('domain'):
            domains = [Domain.get_by_name(options.get('domain'))]
        else:
            domains = Domain.get_all()

        since = options.get('since')
        seen_since = False
        for d in domains:
            if since and not seen_since:
                if d.name == since:
                    seen_since = True
                else:
                    continue

            if d.name in DOMS_TO_IGNORE:
                continue
            try:
                for app in d.full_applications():
                    try:
                        if app.is_remote_app():
                            continue
                        for _, m in app.get_media_objects():
                            if app.domain not in m.valid_domains:
                                m.valid_domains.append(app.domain)
                                self.stdout.write(
                                    "adding domain %s to media file %s" %
                                    (app.domain, m._id))
                                m.save()
                    except Exception as e:
                        self.stdout.write("Error in app %s-%s: %s" %
                                          (app.domain, app._id, e))
            except Exception as e:
                self.stdout.write("Error in domain %s: %s" % (d.name, e))
    def handle(self, *args, **options):
        if options.get("domain"):
            domains = [Domain.get_by_name(options.get("domain"))]
        else:
            domains = Domain.get_all()

        since = options.get("since")
        seen_since = False
        for d in domains:
            if since and not seen_since:
                if d.name == since:
                    seen_since = True
                else:
                    continue

            if d.name in DOMS_TO_IGNORE:
                continue
            try:
                for app in d.full_applications():
                    try:
                        if app.is_remote_app():
                            continue
                        for _, m in app.get_media_objects():
                            if app.domain not in m.valid_domains:
                                m.valid_domains.append(app.domain)
                                self.stdout.write("adding domain %s to media file %s" % (app.domain, m._id))
                                m.save()
                    except Exception as e:
                        self.stdout.write("Error in app %s-%s: %s" % (app.domain, app._id, e))
            except Exception as e:
                self.stdout.write("Error in domain %s: %s" % (d.name, e))
Esempio n. 4
0
 def handle(self, *args, **options):
     billables_created = 0
     for domain in Domain.get_all():
         key = [domain.name, 'SMSLog']
         start_date = [datetime.datetime(2014, 1, 1).isoformat()]
         end_date = [datetime.datetime(2014, 1, 24).isoformat()]
         sms_docs = SMSLog.get_db().view('sms/by_domain',
                                         reduce=False,
                                         startkey=key + start_date,
                                         endkey=key + end_date + [{}])
         for sms_doc in sms_docs:
             sms_log = SMSLog.get(sms_doc['id'])
             try:
                 if sms_log.phone_number is not None:
                     parse_phone_number(sms_log.phone_number)
             except PhoneNumberParseException:
                 billables = SmsBillable.objects.filter(log_id=sms_log._id)
                 if len(billables) == 0:
                     SmsBillable.create(sms_log)
                     billables_created += 1
                     print 'created SmsBillable for invalid number %s in domain %s, id=%s'\
                           % (sms_log.phone_number, domain.name, sms_log._id)
                 elif len(billables) > 1:
                     print "Warning: >1 SmsBillable exists for SMSLog with id=%" % sms_log._id
     print 'Number of SmsBillables created: %d' % billables_created
     print 'Completed retrobilling.'
Esempio n. 5
0
 def options(self):
     return clean_options(
         [
             (domain.name, domain.name)
             for domain in Domain.get_all()
         ]
     )
Esempio n. 6
0
 def domain_response(self):
     domain_names = [
         domain['key'] for domain in Domain.get_all(include_docs=False)
     ]
     if self.search_string:
         domain_names = filter(
             lambda x: x.lower().startswith(self.search_string.lower()),
             domain_names)
     return [(d, d) for d in domain_names]
Esempio n. 7
0
def check_requisition_updates():
    projects = Domain.get_all()
    for project in projects:
        if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:
            endpoint = OpenLMISEndpoint.from_config(project.commtrack_settings.openlmis_config)
            requisitions = endpoint.get_all_requisition_statuses()
            for requisition in requisitions:
                cases, send_notification = sync_requisition_from_openlmis(project.name, requisition.requisition_id, endpoint)
                if cases and send_notification:
                    send_notifications(xform=None, cases=cases)
Esempio n. 8
0
def check_requisition_updates():
    projects = Domain.get_all()
    for project in projects:
        if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled:
            endpoint = OpenLMISEndpoint.from_config(project.commtrack_settings.openlmis_config)
            requisitions = endpoint.get_all_requisition_statuses()
            for requisition in requisitions:
                cases, send_notification = sync_requisition_from_openlmis(project.name, requisition.requisition_id, endpoint)
                if cases and send_notification:
                    send_notifications(xform=None, cases=cases)
Esempio n. 9
0
 def domain_response(self):
     domain_names = [
         domain['key'] for domain in Domain.get_all(include_docs=False)
     ]
     domain_names = filter(lambda x: toggles.ACCOUNTING_PREVIEW.enabled(x),
                           domain_names)
     if self.search_string:
         domain_names = filter(
             lambda x: x.lower().startswith(self.search_string.lower()),
             domain_names)
     return [(d, d) for d in domain_names]
 def handle(self, *args, **options):
     if len(args) != 1:
         print 'usage is ./manage.py list_dynamic_reports filename'
         sys.exit(1)
     filename = args[0]
     with open(filename, 'wb') as f:
         writer = csv.writer(f)
         writer.writerow(['domain', 'section', 'type', 'report'])
         for domain in Domain.get_all():
             for report_config in domain.dynamic_reports:
                 for report in report_config.reports:
                     writer.writerow([domain.name, report_config.section_title, report.report, report.name])
Esempio n. 11
0
 def page_context(self):
     toggle_meta = self.toggle_meta()
     context = {
         'toggle_meta': toggle_meta,
         'toggle': self.get_toggle(),
         'expanded': self.expanded,
     }
     if self.expanded:
         context['domain_toggle_list'] = sorted(
             [(row['key'], toggle_meta.enabled(row['key'])) for row in Domain.get_all(include_docs=False)],
             key=lambda domain_tup: (not domain_tup[1], domain_tup[0])
         )
     return context
Esempio n. 12
0
 def obj_get_list(self, bundle, **kwargs):
     if kwargs.get('domain'):
         return [self.obj_get(bundle, **kwargs)]
     else:
         filters = {}
         if hasattr(bundle.request, 'GET'):
             filters = bundle.request.GET
         domains = list(Domain.get_all())
         if filters:
             for key, value in filters.iteritems():
                 args = key.split('__')
                 if args and args[0] == 'last_modified':
                     domains = [domain for domain in domains if get_truth(domain.last_modified, args[1], value)]
         return domains
Esempio n. 13
0
 def page_context(self):
     toggle_meta = self.toggle_meta()
     context = {
         'toggle_meta': toggle_meta,
         'toggle': self.get_toggle(),
         'expanded': self.expanded,
         'namespaces': [NAMESPACE_USER if n is None else n for n in toggle_meta.namespaces],
     }
     if self.expanded:
         context['domain_toggle_list'] = sorted(
             [(row['key'], toggle_meta.enabled(row['key'])) for row in Domain.get_all(include_docs=False)],
             key=lambda domain_tup: (not domain_tup[1], domain_tup[0])
         )
     return context
Esempio n. 14
0
 def handle(self, *args, **options):
     if len(args) != 1:
         print 'usage is ./manage.py list_dynamic_reports filename'
         sys.exit(1)
     filename = args[0]
     with open(filename, 'wb') as f:
         writer = csv.writer(f)
         writer.writerow(['domain', 'section', 'type', 'report'])
         for domain in Domain.get_all():
             for report_config in domain.dynamic_reports:
                 for report in report_config.reports:
                     writer.writerow([
                         domain.name, report_config.section_title,
                         report.report, report.name
                     ])
Esempio n. 15
0
def sync_cases():
    """
    Create new child cases in CommCare for nutrition tracking, and associate
    CommCare child cases with DHIS2 child entities and enroll them in the
    Pediatric Nutrition Assessment and Underlying Risk Assessment programs.
    """
    for domain in Domain.get_all():
        settings = Dhis2Settings.for_domain(domain.name)
        if settings is None or not settings.is_enabled():
            continue

        children = get_children_only_theirs(settings)
        pull_child_entities(settings, children)

        children = gen_children_only_ours(domain.name)
        push_child_entities(settings, children)
Esempio n. 16
0
 def obj_get_list(self, bundle, **kwargs):
     if kwargs.get('domain'):
         return [self.obj_get(bundle, **kwargs)]
     else:
         filters = {}
         if hasattr(bundle.request, 'GET'):
             filters = bundle.request.GET
         domains = list(Domain.get_all())
         if filters:
             for key, value in filters.iteritems():
                 args = key.split('__')
                 if args and args[0] == 'last_modified':
                     domains = [
                         domain for domain in domains
                         if get_truth(domain.last_modified, args[1], value)
                     ]
         return domains
Esempio n. 17
0
 def page_context(self):
     toggle_meta = self.toggle_meta()
     context = {
         'toggle_meta':
         toggle_meta,
         'toggle':
         self.get_toggle(),
         'expanded':
         self.expanded,
         'namespaces': [
             NAMESPACE_USER if n is None else n
             for n in toggle_meta.namespaces
         ],
     }
     if self.expanded:
         context['domain_toggle_list'] = sorted(
             [(row['key'], toggle_meta.enabled(row['key']))
              for row in Domain.get_all(include_docs=False)],
             key=lambda domain_tup: (not domain_tup[1], domain_tup[0]))
     return context
    def handle(self, *args, **options):
        if len(args) != 1:
            print 'usage is ./manage.py delete_dynamic_reports report_type'
            sys.exit(1)

        report_type = args[0]
        if raw_input(
                'Really delete all reports of type {}? (y/n)\n'.format(report_type)).lower() == 'y':
            for domain in Domain.get_all():
                save_domain = False
                for report_config in domain.dynamic_reports:
                    old_report_count = len(report_config.reports)
                    report_config.reports = [r for r in report_config.reports if r.report != report_type]
                    if len(report_config.reports) != old_report_count:
                        save_domain = True
                if save_domain:
                    print 'removing reports from {}'.format(domain.name)
                    domain.save()
        else:
            print 'aborted'
    def handle(self, *args, **options):
        def settify(entity):
            entity = [entity] if not isinstance(entity, list) else entity
            return set(filter(None, entity))

        domains = Domain.get_all()
        for d in domains:
            for m in d.all_media():
                owners, valid_domains, sharers = \
                    settify(m.owners), settify(m.valid_domains), settify(m.shared_by)
                new_valid_domains = valid_domains.copy()

                if not new_valid_domains >= owners:
                    new_valid_domains |= owners
                if not new_valid_domains >= sharers:
                    new_valid_domains |= sharers

                if valid_domains != new_valid_domains:
                    m.valid_domains = list(new_valid_domains)
                    self.stdout.write("updating media %s: %s => %s" %
                                      (m._id, list(valid_domains), m.valid_domains))
                    m.save()
Esempio n. 20
0
    def handle(self, *args, **options):
        if len(args) != 1:
            print 'usage is ./manage.py delete_dynamic_reports report_type'
            sys.exit(1)

        report_type = args[0]
        if raw_input('Really delete all reports of type {}? (y/n)\n'.format(
                report_type)).lower() == 'y':
            for domain in Domain.get_all():
                save_domain = False
                for report_config in domain.dynamic_reports:
                    old_report_count = len(report_config.reports)
                    report_config.reports = [
                        r for r in report_config.reports
                        if r.report != report_type
                    ]
                    if len(report_config.reports) != old_report_count:
                        save_domain = True
                if save_domain:
                    print 'removing reports from {}'.format(domain.name)
                    domain.save()
        else:
            print 'aborted'
Esempio n. 21
0
def generate_invoices(based_on_date=None):
    """
    Generates all invoices for the past month.
    """
    today = based_on_date or datetime.date.today()
    invoice_start, invoice_end = utils.get_previous_month_date_range(today)
    invoiceable_subscriptions = Subscription.objects.filter(date_start__lt=invoice_end,
                                                            date_end__gt=invoice_start).all()

    def _create_invoice(sub):
        invoice_factory = SubscriptionInvoiceFactory(invoice_start, invoice_end, sub)
        invoice_factory.create()

    invoiced_orgs = []
    orgs = Organization.get_db().view('orgs/by_name', group=True, group_level=1).all()
    org_names = [o['key'] for o in orgs]
    for org_name in org_names:
        try:
            subscription = invoiceable_subscriptions.get(subscriber__organization=org_name)
        except ObjectDoesNotExist:
            continue
        _create_invoice(subscription)
        invoiced_orgs.append(org_name)

    all_domain_ids = [d['id'] for d in Domain.get_all(include_docs=False)]
    for domain_doc in iter_docs(Domain.get_db(), all_domain_ids):
        domain_name = domain_doc['name']
        domain_org = domain_doc['organization']
        try:
            subscription = invoiceable_subscriptions.get(subscriber__domain=domain_name)
        except ObjectDoesNotExist:
            if domain_org not in invoiced_orgs:
                domain = Domain.wrap(domain_doc)
                invoice_factory = CommunityInvoiceFactory(invoice_start, invoice_end, domain)
                invoice_factory.create()
            continue
        _create_invoice(subscription)
Esempio n. 22
0
def sync_org_units():
    """
    Synchronize DHIS2 Organization Units with local data.

    This data is used to fulfill the first requirement of
    `DHIS2 Integration`_: Allow mobile users in CommCareHQ to be
    associated with a particular DHIS2 Organisation Unit, so that when
    they create cases their new cases can be associated with that area
    or facility.


    .. _DHIS2 Integration: https://www.dropbox.com/s/8djk1vh797t6cmt/WV Sri Lanka Detailed Requirements.docx

    """
    # Loop through all enabled domains
    for domain in Domain.get_all():
        settings = Dhis2Settings.for_domain(domain.name)
        if settings is None or not settings.is_enabled():
            continue

        dhis2_api = Dhis2Api(settings.dhis2.host, settings.dhis2.username, settings.dhis2.password,
                             settings.dhis2.top_org_unit_name)
        # Is it a bad idea to read all org units into dictionaries and sync them ...
        their_org_units = {ou['id']: ou for ou in dhis2_api.gen_org_units_with_parents()}
        # ... or should we rather just drop all ours and import all theirs every time?
        org_unit_objects = FixtureManager(Dhis2OrgUnit, domain, ORG_UNIT_FIXTURES)
        our_org_units = {ou.id: ou for ou in org_unit_objects.all()}
        # Add new org units
        for id_, ou in their_org_units.iteritems():
            if id_ not in our_org_units:
                org_unit = Dhis2OrgUnit(id=id_, name=ou['name'], parent_id=ou['parent_id'])
                org_unit.save()
        # Delete former org units
        for id_, ou in our_org_units.iteritems():
            if id_ not in their_org_units:
                ou.delete()
Esempio n. 23
0
 def domain_response(self):
     domain_names = [domain['key'] for domain in Domain.get_all(include_docs=False)]
     domain_names = filter(lambda x: toggles.ACCOUNTING_PREVIEW.enabled(x), domain_names)
     if self.search_string:
         domain_names = filter(lambda x: x.lower().startswith(self.search_string.lower()), domain_names)
     return [(d, d) for d in domain_names]
Esempio n. 24
0
 def options(self):
     return clean_options([(domain.name, domain.name)
                           for domain in Domain.get_all()])
Esempio n. 25
0
 def obj_get_list(self, bundle, **kwargs):
     if kwargs.get('domain'):
         return [self.obj_get(bundle, **kwargs)]
     else:
         return list(Domain.get_all())
Esempio n. 26
0
 def domain_response(self):
     domain_names = [domain['key'] for domain in Domain.get_all(include_docs=False)]
     if self.search_string:
         domain_names = filter(lambda x: x.lower().startswith(self.search_string.lower()), domain_names)
     return [(name, name) for name in domain_names]