示例#1
0
文件: data.py 项目: yeleman/nut
def contact_for(entity, recursive=True):
    """ contact person for an entity. first found at level or sup levels """
    ct, oi = Access.target_data(entity)
    providers = Provider.objects\
                        .filter(access__in=Access.objects\
                                                 .filter(content_type=ct, \
                                                         object_id=oi))
    if providers.count() == 1:
            return providers.all()[0]
    if providers.count() > 0:
        return providers.all()[0]
    if entity.parent and recursive:
        return contact_for(entity.parent)
    return None
示例#2
0
文件: data.py 项目: yeleman/pnlp2011
def contact_for(entity, recursive=True):
    """ contact person for an entity. first found at level or sup levels """
    ct, oi = Access.target_data(entity)
    providers = Provider.active\
                        .filter(access__in=Access.objects\
                                                 .filter(content_type=ct, \
                                                         object_id=oi))
    if providers.count() == 1:
        return providers.all()[0]
    if providers.count() > 0:
        return providers.all()[0]
    if entity.parent and recursive:
        return contact_for(entity.parent)
    return None
示例#3
0
    def action(self):
        """ send SMS to district/region | email to PNLP for each new report """

        for report in MalariaReport.unvalidated\
                                   .filter(period=self.args.period):

            # entity has no parent. Either Mali or error
            if not report.entity.parent:
                # should never happen but we never know
                # drop if entity has no parent.
                if not report.entity.level == 0:
                    return

                # we now have a national report
                logger.info(u"Report %s found." % report)
                report._status = MalariaReport.STATUS_VALIDATED
                with reversion.create_revision():
                    report.save()
                    reversion.set_user(get_autobot().user)
                    #report.save()

                # send emails
                ct, oi = Access.target_data(Entity.objects.get(slug='mali'))
                nat_access = list(Access.objects.filter(content_type=ct, \
                                                        object_id=oi))
                providers = list(Provider.active\
                                    .select_related()\
                                    .filter(user__email__isnull=False, \
                                            access__in=nat_access)\
                                    .values_list('user__email', flat=True))

                rurl = full_url(path=reverse('raw_data', \
                                   kwargs={'entity_code': report.entity.slug, \
                       'period_str': report.period.middle().strftime('%m%Y')}))

                sent, sent_message = send_email(recipients=providers, \
                                        context={'report': report, \
                                                 'report_url': rurl, \
                                                 'url': full_url()},
                                 template='emails/mali_report_available.txt', \
                      title_template='emails/title.mali_report_available.txt')

                # the rest of the method is only for non-national
                return

            # we only send notifications for CSCom & District reports.
            if report.entity.type.slug not in ('cscom', 'district'):
                continue

            # we don't bug district if cscom period is over
            if report.entity.type.slug == 'cscom' \
               and time_cscom_over(period=self.args.period):
                continue

            # we don't bug region if district period is over
            if report.entity.type.slug == 'district' \
               and time_district_over(period=self.args.period):
                continue

            # create a dedicated alert so it can be tracked by report
            # then fire it.
            alert = IndividualMalariaReportCreated.create(report=report)
            if alert.can_trigger():
                alert.trigger()
示例#4
0
def import_users(csv_file):
    """ creates Provider object off a CSV filename

    CSV FORMAT:
    FIRST NAME, LAST NAME, EMAIL, PHONE, PHONE2, ROLE CODE, ENTITY CODE
    CSV file MUST include header row. """

    errors = []

    first = True
    f = open(csv_file)
    succ = open('success.csv', 'w')
    for line in f.readlines():
        if first:
            first = False
            continue
        # explode CSV line
        fname, lname, email, \
        phone_number, phone2, role_code, entity_code, area = line.strip().split(',')

        # convert name to unicode for django & .title()
        try:
            fname = unicode(fname.strip(), 'utf-8').title()
        except:
            pass

        try:
            lname = unicode(lname.strip(), 'utf-8').title()
        except:
            pass

        # retrieve parent object if address is provided
        try:
            entity = Entity.objects.get(slug=entity_code.lower())
        except:
            print("BAD ENTITY: %s" % entity_code)
            #raise
            errors.append(line)
            continue

        try:
            role = Role.objects.get(slug=role_code.lower())
        except:
            print("BAD ROLE: %s" % role_code)
            #raise
            errors.append(line)
            continue

        # build an Access based on Role and Entity selected
        # if a national role, force attachment to root entity
        if role.slug in ('antim', 'national'):
            entity = Entity.objects.filter(level=0)[0]
        elif role.slug != entity.type.slug:
            print("ROLE MISMATCH LOCATION TYPE: %s / %s (%s)" %
                  (role_code, entity_code, entity.type))
            errors.append(line)
            continue
        access = Access.find_by(role, entity)

        # forge username
        username = username_from_name(fname, lname)
        # generate password
        password = random_password()

        pcount = Provider.objects.filter(phone_number=phone_number).count()

        if phone_number and pcount > 0:
            print("PHONE NUMBER CONFLICT: %s" % phone_number)
            errors.append(line)
            continue

        # create Provider
        provider = Provider.create_provider(username, \
                                            'xx', access=[access])
        provider.set_password(password)

        # we have a valid provider whatever the case. update details
        provider.first_name = fname
        provider.last_name = lname
        provider.email = email
        # only update if not None to preserve uniqueness

        if phone_number and pcount == 0:
            provider.phone_number = phone_number

        if phone2:
            provider.phone_number_extra = phone2

        provider.save()

        line = u"%(ent)s,%(role)s,%(fname)s,%(lname)s,%(user)s,%(pass)s,%(passenc)s\n" % {
            'ent': entity,
            'role': role,
            'fname': provider.first_name,
            'lname': provider.last_name,
            'user': username,
            'pass': password,
            'passenc': provider.user.password
        }
        succ.write(line.encode('utf-8'))
        print(provider.name_access())
    f.close()
    succ.close()

    if errors:
        error_file = 'errors.csv'
        f = open(error_file, 'w')
        for line in errors:
            f.write(line)
        f.close()
        print("%d errors appended to file %s" % (errors.__len__(), error_file))
示例#5
0
def import_users(csv_file):
    """ creates Provider object off a CSV filename

    CSV FORMAT:
    FIRST NAME, LAST NAME, EMAIL, PHONE, PHONE2, ROLE CODE, ENTITY CODE
    CSV file MUST include header row. """

    errors = []

    first = True
    f = open(csv_file)
    succ = open('success.csv', 'w')
    for line in f.readlines():
        if first:
            first = False
            continue
        # explode CSV line
        fname, lname, email, \
        phone_number, phone2, role_code, entity_code, area = line.strip().split(',')

        # convert name to unicode for django & .title()
        try:
            fname = unicode(fname.strip(), 'utf-8').title()
        except:
            pass

        try:
            lname = unicode(lname.strip(), 'utf-8').title()
        except:
            pass

        # retrieve parent object if address is provided
        try:
            entity = Entity.objects.get(slug=entity_code.lower())
        except:
            print("BAD ENTITY: %s" % entity_code)
            #raise
            errors.append(line)
            continue

        try:
            role = Role.objects.get(slug=role_code.lower())
        except:
            print("BAD ROLE: %s" % role_code)
            #raise
            errors.append(line)
            continue


        # build an Access based on Role and Entity selected
        # if a national role, force attachment to root entity
        if role.slug in ('antim', 'national'):
            entity = Entity.objects.filter(level=0)[0]
        elif role.slug != entity.type.slug:
            print("ROLE MISMATCH LOCATION TYPE: %s / %s (%s)" % (role_code, entity_code, entity.type))
            errors.append(line)
            continue
        access = Access.find_by(role, entity)

        # forge username
        username = username_from_name(fname, lname)
        # generate password
        password = random_password()

        pcount = Provider.objects.filter(phone_number=phone_number).count()

        if phone_number and pcount > 0:
            print("PHONE NUMBER CONFLICT: %s" % phone_number)
            errors.append(line)
            continue

        # create Provider
        provider = Provider.create_provider(username, \
                                            'xx', access=[access])
        provider.set_password(password)

        # we have a valid provider whatever the case. update details
        provider.first_name = fname
        provider.last_name = lname
        provider.email = email
        # only update if not None to preserve uniqueness

        if phone_number and pcount == 0:
            provider.phone_number = phone_number

        if phone2:
            provider.phone_number_extra = phone2

        provider.save()

        line = u"%(ent)s,%(role)s,%(fname)s,%(lname)s,%(user)s,%(pass)s,%(passenc)s\n" % {'ent': entity, 'role': role, 'fname': provider.first_name, 'lname': provider.last_name, 'user': username, 'pass': password, 'passenc': provider.user.password}
        succ.write(line.encode('utf-8'))
        print(provider.name_access())
    f.close()
    succ.close()

    if errors:
        error_file = 'errors.csv'
        f = open(error_file, 'w')
        for line in errors:
            f.write(line)
        f.close()
        print("%d errors appended to file %s" % (errors.__len__(), error_file))