def get_order_by(self):
     if self.order_by:
         order = to_camel(self.order_by).split(',')
         return [
             Sort(item[1:], 1) if item.startswith('-') else Sort(item, 0)
             for item in order
         ]
Exemplo n.º 2
0
 def get_attribute(self, instance):
     camel_case = to_camel(self.source)
     if getattr(instance,
                'properties') and camel_case in instance.properties:
         values = instance.properties[camel_case]
         if values:
             values = values.replace('; ', ';').split(';')
         return values
     return super().get_attribute(instance)
    def get_filter_querystring(self):
        filter_queries = []
        for filter_name, filter_value in self.filters.items():
            # operator
            querystring_operator = filter_name.split('__')[-1]
            operator = self.mapping_operator.get(querystring_operator, 'eq')
            # filter
            filter_name = to_camel(filter_name.split('__')[0])
            if operator in self.date_operators:
                values = [f"{filter_value}T00:00:00Z"]  # 2016-03-26
                query = ' or '.join([f"{filter_name} {operator} datetime'{value}'" for value in values])
            elif operator == 'substringof':
                values = filter_value.split(',')
                query = ' or '.join([f"{operator}('{value}', {filter_name})" for value in values])

            else:
                values = filter_value.split(',')
                query = ' or '.join([f"{filter_name} {operator} '{value}'" for value in values])
                if len(values) > 1:
                    query = f'({query})'
            filter_queries.append(query)
            logger.info(query)
        return str(" and ".join(filter_queries))
    def create_query(self):
        where_condition = ''

        if self.filters.keys():
            filter_queries = []
            for filter_name, filter_value in self.filters.items():
                querystring_operator = filter_name.split('__')[-1]
                operator = self.mapping_operator.get(querystring_operator,
                                                     'Eq')

                filter_name = to_camel(filter_name.split('__')[0])
                if operator in self.date_operators:
                    column_type, value = 'DateTime', f"{filter_value}T00:00:00Z"  # 2016-03-26
                    query = '<{}><FieldRef Name="{}" /><Value Type="{}">{}</Value></{}>'.format(
                        operator, filter_name, column_type, value, operator)
                elif operator == 'Contains':
                    column_type = 'Text'
                    query = '<{}><FieldRef Name="{}" /><Value Type="{}">{}</Value></{}>'.format(
                        operator, filter_name, column_type, filter_value,
                        operator)
                else:
                    column_type, values = 'Text', filter_value.split(',')
                    queries = [
                        '<{}><FieldRef Name="{}" /><Value Type="{}">{}</Value></{}>'
                        .format(operator, filter_name, column_type, value,
                                operator) for value in values
                    ]
                    query = recursive_builder(queries, 'Or')
                filter_queries.append(query)
            where_condition = recursive_builder(filter_queries)
            if len(filter_queries) > 1:
                where_condition = f"<And>{where_condition}</And>"

        scope = f' Scope="{self.scope}"' if self.scope else ''
        query = f'<View{scope}><Query><Where>{where_condition}</Where></Query></View>'
        return query
Exemplo n.º 5
0
 def get_attribute(self, instance):
     field_name = to_camel(self.source)
     items = [
         item['Value'] for item in instance if item['Key'] == field_name
     ]
     return items[0] if items else 'N/A'
Exemplo n.º 6
0
 def get_attribute(self, instance):
     camel_case = to_camel(self.source)
     if getattr(instance,
                'properties') and camel_case in instance.properties:
         return instance.properties[camel_case]
     return super().get_attribute(instance)
Exemplo n.º 7
0
def notify_donor(donor_code):

    document_type_filter = [
        'Certified Financial Statement - EC',
        'Certified Financial Statement - US Government',
        'Certified Statement of Account',
        'Certified Statement of Account EU',
        'Certified Statement of Account JPO',
        'Donor Statement CERF',
        'Certified Financial Report - Final',
        'Certified Financial Report - Interim',
        'Donor Statement Innovation',
        'Donor Statement Joint Programme',
        'Donor Statement Joint Programme PUNO',
        'Donor Statement JPO Summary',
        'Donor Statement Trust Fund',
        'Donor Statement UN',
        'Donor Statement UNICEF Hosted Funds',
        'FFR Form (SF-425)',
        'JPO Expenditure Summary',
        'Statement of Account Thematic Funds',
        'Donor Statement by Activity',
        'Interim Statement by Nature of expense',
        'Funds Request Report',
        'Non-Standard Statement',
        'Emergency Consolidated - Final',
        'Emergency  Consolidated - Interim',
        'Thematic Emergency Global - Final',
        'Thematic Emergency Global - Interim',
        'Emergency - Two Pager',
        'Emergency - Final',
        'Emergency - Interim',
        'Human Interest / Photos',
        'Narrative - Final',
        'Narrative - Interim',
        'Narrative Consolidated - Final',
        'Narrative Consolidated - Interim',
        'Thematic Consolidated - Final',
        'Thematic Consolidated - Interim',
        'Thematic Global - Final',
        'Thematic Global - Interim',
        'Thematic - Final',
        'Thematic - Interim',
        'Short Summary Update',
        'Official Receipts',
        'Quarterly Monitoring Report',
    ]

    donor = Donor.objects.get(code=donor_code)
    logger.info(f'Notifing {donor.name}')
    client = SharePointClient(
        url=
        f'{config.SHAREPOINT_TENANT}/{config.SHAREPOINT_SITE_TYPE}/{config.SHAREPOINT_SITE}'
    )

    notification_periods = [
        x for x in [
            (UserRole.EVERY_MONTH,
             today().replace(day=1) - relativedelta(months=1),
             today().day == 1),
            (UserRole.EVERY_MONDAY, today() - timedelta(7),
             today().weekday() == 0),
            (UserRole.EVERY_DAY, today() - timedelta(1), True),
        ] if x[2]
    ]

    for period, modified_date, _ in notification_periods:
        filters = {
            'DRPDonorCode': donor.code,
            'DRPDonorDocument': ','.join(document_type_filter),
            'DRPModified__gte': modified_date.strftime('%Y-%m-%d')
        }
        serializer_fields = DRPSharePointSearchSerializer._declared_fields.keys(
        )
        selected = ['DRP' + to_camel(x)
                    for x in serializer_fields] + ["Title", "Author", "Path"]

        page = 1
        exit_condition = True
        reports = []

        users = UserRole.objects.filter(donor=donor,
                                        notification_period=period).values(
                                            'user__first_name', 'user__email')

        if users:
            while exit_condition:
                response, total_rows = client.search(
                    filters=filters,
                    select=selected,
                    source_id=settings.DRP_SOURCE_IDS['external'],
                    page=page)
                exit_condition = page * SHAREPOINT_PAGE_SIZE < total_rows
                page += 1
                qs = DRPSharePointSearchSerializer(response, many=True)
                reports.extend(qs.data)

            if reports:
                context = {'reports': reports, 'donor': donor.name}
                recipients = list(
                    set([
                        str(user['user__email']) for user in users
                        if user['user__email']
                    ]))
                send_notification_with_template(recipients, 'notify_donor',
                                                context)
Exemplo n.º 8
0
 def get_attribute(self, instance):
     field_name = self.prefix + to_camel(self.source)
     return getvalue(instance, field_name)