Beispiel #1
0
 def export(application):
     return (
         application.reference,
         application.lodgement_date,
         application.processing_status,
         render_user_name(application.proxy_applicant) if application.proxy_applicant else '',
         render_user_name(application.assigned_officer) if application.proxy_applicant else '',
     )
Beispiel #2
0
 def export(ret):
     return (
         ret.lodgement_number,
         ret.lodgement_date,
         ret.licence.reference,
         render_user_name(ret.licence.holder),
         ret.status,
         ret.due_date,
         render_user_name(ret.proxy_customer),
         'Yes' if ret.nil_return else 'No',
         ret.comments
     )
Beispiel #3
0
 def _build_data(self):
     data = super(DashboardTableOfficerView, self)._build_data()
     data['applications']['columnDefinitions'] = [
         {
             'title': 'Lodge No.'
         },
         {
             'title': 'Licence Type'
         },
         {
             'title': 'User'
         },
         {
             'title': 'Status',
         },
         {
             'title': 'Lodged on'
         },
         {
             'title': 'Assignee'
         },
         {
             'title': 'Action',
             'searchable': False,
             'orderable': False
         }
     ]
     data['applications']['filters']['status']['values'] = \
         [('all', 'All')] + _get_processing_statuses_but_draft()
     data['applications']['filters']['assignee'] = {
         'values': [('all', 'All')] + [(user.pk, render_user_name(user),) for user in get_all_officers()]
     }
     data['applications']['ajax']['url'] = reverse('dashboard:data_application_officer')
     return data
Beispiel #4
0
    def post(self, request, *args, **kwargs):
        try:
            application = utils.get_session_application(request.session)
        except Exception as e:
            messages.error(request, e.message)
            return redirect('wl_applications:new_application')

        if 'select' in request.POST:
            application.applicant = EmailUser.objects.get(id=request.POST.get('customer'))
            application.save()
        elif 'create' in request.POST:
            create_customer_form = EmailUserForm(request.POST, email_required=False)
            if create_customer_form.is_valid():
                customer = create_customer_form.save()
                application.applicant = customer
                application.save()
                application.log_user_action(
                    ApplicationUserAction.ACTION_CREATE_CUSTOMER_.format(render_user_name(customer)),
                    request
                )
            else:
                context = {'create_customer_form': create_customer_form}
                return render(request, self.template_name, context)

        return redirect('wl_applications:select_licence_type', *args, **kwargs)
Beispiel #5
0
    def post(self, request, *args, **kwargs):
        try:
            application = utils.get_session_application(request.session)
        except Exception as e:
            messages.error(request, str(e))
            return redirect('wl_applications:new_application')

        if 'select' in request.POST:
            application.applicant = EmailUser.objects.get(
                id=request.POST.get('customer'))
            application.save()
        elif 'create' in request.POST:
            create_customer_form = EmailUserForm(request.POST,
                                                 email_required=False)
            if create_customer_form.is_valid():
                customer = create_customer_form.save()
                application.applicant = customer
                application.save()
                application.log_user_action(
                    ApplicationUserAction.ACTION_CREATE_CUSTOMER_.format(
                        render_user_name(customer)), request)
            else:
                context = {'create_customer_form': create_customer_form}
                return render(request, self.template_name, context)

        return redirect('wl_applications:select_licence_type', *args, **kwargs)
Beispiel #6
0
    def post(self, request, *args, **kwargs):
        application = get_object_or_404(Application, pk=request.POST['applicationID'])

        try:
            application.assigned_officer = EmailUser.objects.get(pk=request.POST['userID'])
        except EmailUser.DoesNotExist:
            application.assigned_officer = None

        application.processing_status = determine_processing_status(application)
        application.save()

        if application.assigned_officer is not None:
            name = render_user_name(application.assigned_officer)
            assigned_officer = {'id': application.assigned_officer.id, 'text': name}
            application.log_user_action(
                ApplicationUserAction.ACTION_ASSIGN_TO_.format(name),
                request)
        else:
            assigned_officer = {'id': 0, 'text': 'Unassigned'}
            application.log_user_action(
                ApplicationUserAction.ACTION_UNASSIGN,
                request)

        return JsonResponse({'assigned_officer': assigned_officer,
                             'processing_status': PROCESSING_STATUSES[application.processing_status]},
                            safe=False, encoder=WildlifeLicensingJSONEncoder)
Beispiel #7
0
    def _build_data(self, request, application):
        with open('%s/json/%s.json' % (APPLICATION_SCHEMA_PATH, application.licence_type.code)) as data_file:
            form_structure = json.load(data_file)

        officers = [{'id': officer.id, 'text': render_user_name(officer)} for officer in get_all_officers()]
        officers.insert(0, {'id': 0, 'text': 'Unassigned'})

        current_ass_groups = [ass_request.assessor_group for ass_request in Assessment.objects.filter(application=application)]
        ass_groups = [{'id': ass_group.id, 'text': ass_group.name} for ass_group in
                     AssessorGroup.objects.all().exclude(id__in=[ass_group.pk for ass_group in current_ass_groups])]

        previous_application_data = []
        for revision in revisions.get_for_object(application).filter(revision__comment='Details Modified').order_by('-revision__date_created'):
            previous_application_data.append({'lodgement_number': revision.object_version.object.lodgement_number +
                                              '-' + str(revision.object_version.object.lodgement_sequence),
                                              'date': formats.date_format(revision.revision.date_created, 'd/m/Y', True),
                                              'data': revision.object_version.object.data})

        data = {
            'user': serialize(request.user),
            'application': serialize(application, posthook=format_application),
            'form_structure': form_structure,
            'officers': officers,
            'amendment_requests': serialize(AmendmentRequest.objects.filter(application=application), posthook=format_amendment_request),
            'assessor_groups': ass_groups,
            'assessments': serialize(Assessment.objects.filter(application=application),
                                     posthook=format_assessment),
            'previous_application_data': serialize(previous_application_data),
            'csrf_token': str(csrf(request).get('csrf_token'))
        }

        return data
Beispiel #8
0
    def post(self, request, *args, **kwargs):
        application = get_object_or_404(Application, pk=request.POST['applicationID'])

        try:
            application.assigned_officer = EmailUser.objects.get(pk=request.POST['userID'])
        except EmailUser.DoesNotExist:
            application.assigned_officer = None

        application.processing_status = determine_processing_status(application)
        application.save()

        if application.assigned_officer is not None:
            name = render_user_name(application.assigned_officer)
            assigned_officer = {'id': application.assigned_officer.id, 'text': name}
            application.log_user_action(
                ApplicationUserAction.ACTION_ASSIGN_TO_.format(name),
                request)
        else:
            assigned_officer = {'id': 0, 'text': 'Unassigned'}
            application.log_user_action(
                ApplicationUserAction.ACTION_UNASSIGN,
                request)

        return JsonResponse({'assigned_officer': assigned_officer,
                             'processing_status': PROCESSING_STATUSES[application.processing_status]},
                            safe=False, encoder=WildlifeLicensingJSONEncoder)
Beispiel #9
0
    def _build_data(self, request, application):
        officers = [{'id': officer.id, 'text': render_user_name(officer)} for officer in get_all_officers()]
        officers.insert(0, {'id': 0, 'text': 'Unassigned'})

        current_ass_groups = [ass_request.assessor_group for ass_request in
                              Assessment.objects.filter(application=application)]

        ass_groups = [{'id': ass_group.id, 'text': ass_group.name} for ass_group in
                      AssessorGroup.objects.all().exclude(id__in=[ass_group.pk for ass_group in current_ass_groups])]

        # extract and format the previous lodgements of the application
        previous_lodgements = []
        for revision in revisions.get_for_object(application).filter(revision__comment='Details Modified').order_by(
                '-revision__date_created'):
            previous_lodgement = revision.object_version.object

            if previous_lodgement.hard_copy is not None:
                previous_lodgement.licence_type.application_schema, previous_lodgement.data = \
                    append_app_document_to_schema_data(previous_lodgement.licence_type.application_schema, previous_lodgement.data,
                                                       previous_lodgement.hard_copy.file.url)

            # reversion won't reference the previous many-to-many sets, only the latest one, so need to get documents as per below
            previous_lodgement_documents = Document.objects.filter(pk__in=revision.field_dict['documents'])

            convert_documents_to_url(previous_lodgement.licence_type.application_schema, previous_lodgement.data,
                                     previous_lodgement_documents)
            previous_lodgements.append({'lodgement_number': '{}-{}'.format(previous_lodgement.lodgement_number,
                                                                           previous_lodgement.lodgement_sequence),
                                        'date': formats.date_format(revision.revision.date_created, 'd/m/Y', True),
                                        'data': previous_lodgement.data})

        previous_application_returns_outstanding = False
        if application.previous_application is not None:
            previous_application_returns_outstanding = Return.objects.filter(licence=application.previous_application.licence).\
                exclude(status='accepted').exclude(status='submitted').exists()

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.licence_type.application_schema, application.data, application.documents.all())

        data = {
            'user': serialize(request.user),
            'application': serialize(application, posthook=format_application),
            'form_structure': application.licence_type.application_schema,
            'officers': officers,
            'amendment_requests': serialize(AmendmentRequest.objects.filter(application=application),
                                            posthook=format_amendment_request),
            'assessor_groups': ass_groups,
            'assessments': serialize(Assessment.objects.filter(application=application),
                                     posthook=format_assessment),
            'previous_versions': serialize(previous_lodgements),
            'returns_outstanding': previous_application_returns_outstanding,
            'csrf_token': str(csrf(request).get('csrf_token'))
        }

        return data
Beispiel #10
0
 def export_profile(profile):
     return (
         render_user_name(profile.user),
         profile.name,
         to_string(profile.email),
         to_string(profile.postal_address),
         to_string(profile.institution)
     )
Beispiel #11
0
 def export(licence):
     application = Application.objects.filter(licence=licence).first()
     return (
         licence.reference,
         licence.issue_date,
         render_user_name(licence.issuer),
         licence.start_date,
         licence.end_date,
         ','.join([str(r) for r in licence.regions.all()]),
         to_string(licence.purpose),
         to_string(licence.locations),
         to_string(licence.additional_information),
         licence.previous_licence.reference if licence.previous_licence else '',
         application.reference if application else '',
     )
Beispiel #12
0
 def export(licence):
     application = Application.objects.filter(licence=licence).first()
     return (
         licence.reference,
         licence.issue_date,
         render_user_name(licence.issuer),
         licence.start_date,
         licence.end_date,
         ','.join([str(r) for r in licence.regions.all()]),
         to_string(licence.purpose),
         to_string(licence.locations),
         to_string(licence.additional_information),
         licence.replaced_by.reference if licence.replaced_by else '',
         application.reference if application else '',
         ','.join(licence.search_extracted_fields('species_estimated_number')),
         ','.join(licence.search_extracted_fields('authorised_persons'))
     )
Beispiel #13
0
class DataTableApplicationBaseView(DataTableBaseView):
    model = Application
    columns = [
        'licence_type', 'applicant', 'applicant_profile', 'processing_status'
    ]
    order_columns = [['licence_type.short_name', 'licence_type.name'],
                     'applicant', 'applicant_profile', 'processing_status']

    columns_helpers = dict(
        DataTableBaseView.columns_helpers.items(), **{
            'applicant': {
                'render':
                lambda self, instance: render_user_name(
                    instance.applicant, first_name_first=False),
                'search':
                lambda self, search: build_field_query([
                    'applicant_profile__user__last_name',
                    'applicant_profile__user__first_name'
                ], search)
            },
            'applicant_profile': {
                'render':
                lambda self, instance: '{}'.format(instance.applicant_profile),
                'search':
                lambda self, search: build_field_query([
                    'applicant_profile__email', 'applicant_profile__name'
                ], search)
            },
        })

    @staticmethod
    def filter_status(value):
        return Q(processing_status=value) if value.lower() != 'all' else None

    @staticmethod
    def filter_assignee(value):
        return Q(
            assigned_officer__pk=value) if value.lower() != 'all' else None

    @staticmethod
    def filter_licence_type(value):
        return Q(licence_type__pk=value) if value.lower() != 'all' else None

    def get_initial_queryset(self):
        return self.model.objects.all().exclude(processing_status='temp')
Beispiel #14
0
class DataTableApplicationAssessorView(OfficerOrAssessorRequiredMixin,
                                       base.DataTableBaseView):
    """
    The model of this table is not Application but Assessment.
    """
    APPLICATION_TYPES = dict(Application.APPLICATION_TYPE_CHOICES)
    model = Assessment
    columns = [
        'application.lodgement_number', 'licence_type',
        'application.applicant', 'application.application_type', 'status',
        'application.lodgement_date', 'application.assigned_officer',
        'assigned_assessor', 'application_pdf', 'action'
    ]
    order_columns = [
        'application.lodgement_number',
        [
            'application.licence_type.short_name',
            'application.licence_type.name'
        ],
        [
            'application.applicant.last_name',
            'application.applicant.first_name', 'application.applicant.email'
        ], 'application.application_type', 'status',
        'application.lodgement_date',
        [
            'application.assigned_officer.first_name',
            'application.assigned_officer.last_name',
            'application.assigned_officer.email'
        ],
        [
            'assigned_assessor.first_name', 'assigned_assessor.last_name',
            'assigned_assessor.email'
        ], ''
    ]

    columns_helpers = dict(
        **{
            'licence_type': {
                'render':
                lambda self, instance: instance.application.licence_type.
                display_name,
                'search':
                lambda self, search: base.build_field_query([
                    'application__licence_type__short_name',
                    'application__licence_type__name',
                    'application__licence_type__version'
                ], search)
            },
            'application.lodgement_number': {
                'search':
                lambda self, search: DataTableApplicationAssessorView.
                _search_lodgement_number(search),
                'render':
                lambda self, instance: base.render_lodgement_number(
                    instance.application)
            },
            'application.applicant': {
                'render':
                lambda self, instance: render_user_name(instance.application.
                                                        applicant),
                'search':
                lambda self, search: base.build_field_query([
                    'application__applicant_profile__user__last_name',
                    'application__applicant_profile__user__first_name'
                ], search),
            },
            'application.application_type': {
                'render':
                lambda self, instance: self.APPLICATION_TYPES[
                    instance.application.application_type]
            },
            'application.assigned_officer': {
                'render':
                lambda self, instance: render_user_name(instance.application.
                                                        assigned_officer),
                'search':
                lambda self, search: base.build_field_query([
                    'application__assigned_officer__last_name',
                    'application__assigned_officer__first_name',
                    'application__assigned_officer__email'
                ], search),
            },
            'assigned_assessor': {
                'render':
                lambda self, instance: render_user_name(instance.
                                                        assigned_assessor),
                'search':
                lambda self, search: base.build_field_query([
                    'assigned_assessor__last_name',
                    'assigned_assessor__first_name', 'assigned_assessor__email'
                ], search),
            },
            'application.lodgement_date': {
                'render':
                lambda self, instance: base.render_date(instance.application.
                                                        lodgement_date),
            },
            'application_pdf': {
                'render':
                lambda self, instance: base.render_application_document(
                    instance.application)
            },
            'action': {
                'render':
                lambda self, instance: DataTableApplicationAssessorView.
                render_action_column(instance),
            },
        })

    @staticmethod
    def render_action_column(obj):
        if obj.status == 'awaiting_assessment':
            return '<a href="{0}">Assess</a>'.format(
                reverse('wl_applications:enter_conditions_assessor',
                        args=[obj.application.pk, obj.pk]))
        else:
            return '<a href="{0}">View (read-only)</a>'.format(
                reverse('wl_applications:view_assessment',
                        args=[obj.application.pk, obj.pk]))

    @staticmethod
    def _search_lodgement_number(search):
        # testing to see if search term contains no spaces and two hyphens, meaning it's a lodgement number with a sequence
        if search and search.count(' ') == 0 and search.count('-') == 2:
            components = search.split('-')
            lodgement_number, lodgement_sequence = '-'.join(
                components[:2]), '-'.join(components[2:])

            return Q(application__lodgement_number__icontains=lodgement_number) & \
                   Q(application__lodgement_sequence__icontains=lodgement_sequence)
        else:
            return Q(application__lodgement_number__icontains=search)

    @staticmethod
    def filter_licence_type(value):
        return Q(application__licence_type__pk=value
                 ) if value.lower() != 'all' else None

    @staticmethod
    def filter_status(value):
        return Q(status=value) if value.lower() != 'all' else None

    def get_initial_queryset(self):
        groups = self.request.user.assessorgroup_set.all()
        assessments = self.model.objects.filter(
            assessor_group__in=groups).all()
        return assessments
Beispiel #15
0
def _create_licence(licence_buffer, licence, application, site_url, original_issue_date):
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160, id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages', frames=every_page_frame, onPage=_create_licence_header)

    doc = BaseDocTemplate(licence_buffer, pageTemplates=[every_page_template], pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.licence = licence
    doc.site_url = site_url

    licence_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []

    elements.append(Paragraph(licence.licence_type.act, styles['InfoTitleLargeCenter']))
    elements.append(Paragraph(licence.licence_type.code.upper(), styles['InfoTitleLargeCenter']))

    # cannot use licence get_title_with_variants because licence isn't saved yet so can't get variants
    if application.variants.exists:
        title = '{} ({})'.format(application.licence_type.name, ' / '.join(application.variants.all().
                                                                           values_list('name', flat=True)))
    else:
        title = licence.licence_type.name

    elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    elements.append(Paragraph(licence.licence_type.statement, styles['InfoTitleLargeLeft']))
    elements.append(Paragraph(licence.licence_type.authority, styles['InfoTitleLargeRight']))

    # licence conditions
    if application.conditions.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Conditions', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        conditionList = ListFlowable(
            [Paragraph(condition.text, styles['Left']) for condition in application.conditions.all()],
            bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE)
        elements.append(conditionList)

    # purpose
    if licence.purpose:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Purpose', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        for purpose in licence.purpose.split('\r\n'):
            if purpose:
                elements.append(Paragraph(purpose, styles['Left']))
            else:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # locations
    if licence.locations:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Locations', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        for location in licence.locations.split('\r\n'):
            if location:
                elements.append(Paragraph(location, styles['Left']))
            else:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # authorised persons
    authorised_persons = _get_authorised_person_names(application)
    if len(authorised_persons) > 0:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Authorised Persons', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        for ap in authorised_persons:
            elements.append(Paragraph(ap, styles['Left']))
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # species
    species = _get_species(application)
    if len(species) > 0:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        section_width = (PAGE_WIDTH - (2 * PAGE_MARGIN) - 100) / 2

        elements.append(Table([[Paragraph('Species', styles['BoldLeft']), Paragraph('Name', styles['BoldLeft']),
                                Paragraph('Count', styles['BoldLeft'])]],
                              colWidths=(100, section_width, section_width), style=licence_table_style))

        for s in species:
            elements.append(Table([['', Paragraph(s[0], styles['Left']), Paragraph(s[1], styles['Left'])]],
                                  colWidths=(100, section_width, section_width), style=licence_table_style))

    # additional information
    if licence.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information', styles['BoldLeft']))

        for paragraph in licence.additional_information.split('\r\n'):
            if paragraph:
                elements.append(Paragraph(paragraph, styles['Left']))
            else:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # delegation holds the dates, licencee and issuer details.
    delegation = []

    # dates and licensing officer
    dates_licensing_officer_table_style = TableStyle([('VALIGN', (0, 0), (-2, -1), 'TOP'),
                                                      ('VALIGN', (0, 0), (-1, -1), 'BOTTOM')])

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    date_headings = [Paragraph('Date of Issue', styles['BoldLeft']), Paragraph('Valid From', styles['BoldLeft']),
                     Paragraph('Date of Expiry', styles['BoldLeft'])]
    date_values = [Paragraph(licence.issue_date.strftime(DATE_FORMAT), styles['Left']),
                   Paragraph(licence.start_date.strftime(DATE_FORMAT), styles['Left']),
                   Paragraph(licence.end_date.strftime(DATE_FORMAT), styles['Left'])]

    if original_issue_date is not None:
        date_headings.insert(0, Paragraph('Original Date of Issue', styles['BoldLeft']))
        date_values.insert(0, Paragraph(original_issue_date.strftime(DATE_FORMAT), styles['Left']))

    delegation.append(Table([[date_headings, date_values]],
                            colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=dates_licensing_officer_table_style))

    # licensee details
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    address = application.applicant_profile.postal_address
    address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
                          Paragraph(address.line3, styles['Left']),
                          Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['Left']),
                          Paragraph(address.country.name, styles['Left'])]
    delegation.append(Table([[[Paragraph('Licensee:', styles['BoldLeft']), Paragraph('Address', styles['BoldLeft'])],
                              [Paragraph(render_user_name(application.applicant),
                                         styles['Left'])] + address_paragraphs]],
                            colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=licence_table_style))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Issued by a Wildlife Licensing Officer of the Department of Parks and Wildlife '
                                'under delegation from the Minister for Environment pursuant to section 133(1) '
                                'of the Conservation and Land Management Act 1984.', styles['Left']))

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return licence_buffer
Beispiel #16
0
def _create_licence(licence_buffer, licence, application, site_url,
                    original_issue_date):
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160,
                             id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=every_page_frame,
                                       onPage=_create_licence_header)

    doc = BaseDocTemplate(licence_buffer,
                          pageTemplates=[every_page_template],
                          pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.licence = licence
    doc.site_url = site_url

    licence_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []

    elements.append(
        Paragraph(licence.licence_type.act, styles['InfoTitleLargeCenter']))
    elements.append(
        Paragraph(licence.licence_type.code.upper(),
                  styles['InfoTitleLargeCenter']))

    # cannot use licence get_title_with_variants because licence isn't saved yet so can't get variants
    if application.variants.exists:
        title = '{} ({})'.format(
            application.licence_type.name,
            ' / '.join(application.variants.all().values_list('name',
                                                              flat=True)))
    else:
        title = licence.licence_type.name

    elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    elements.append(
        Paragraph(licence.licence_type.statement,
                  styles['InfoTitleLargeLeft']))
    elements.append(
        Paragraph(licence.licence_type.authority,
                  styles['InfoTitleLargeRight']))

    # licence conditions
    if application.conditions.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Conditions', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        conditionList = ListFlowable([
            Paragraph(condition.text, styles['Left'])
            for condition in application.conditions.all()
        ],
                                     bulletFontName=BOLD_FONTNAME,
                                     bulletFontSize=MEDIUM_FONTSIZE)
        elements.append(conditionList)

    # purpose
    if licence.purpose:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Purpose', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        for purpose in licence.purpose.split('\r\n'):
            if purpose:
                elements.append(Paragraph(purpose, styles['Left']))
            else:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # locations
    if licence.locations:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Locations', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        for location in licence.locations.split('\r\n'):
            if location:
                elements.append(Paragraph(location, styles['Left']))
            else:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # authorised persons
    authorised_persons = _get_authorised_person_names(application)
    if len(authorised_persons) > 0:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Authorised Persons', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        for ap in authorised_persons:
            elements.append(Paragraph(ap, styles['Left']))
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # species
    species = _get_species(application)
    if len(species) > 0:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        section_width = (PAGE_WIDTH - (2 * PAGE_MARGIN) - 100) / 2

        elements.append(
            Table([[
                Paragraph('Species', styles['BoldLeft']),
                Paragraph('Name', styles['BoldLeft']),
                Paragraph('Count', styles['BoldLeft'])
            ]],
                  colWidths=(100, section_width, section_width),
                  style=licence_table_style))

        for s in species:
            elements.append(
                Table([[
                    '',
                    Paragraph(s[0], styles['Left']),
                    Paragraph(s[1], styles['Left'])
                ]],
                      colWidths=(100, section_width, section_width),
                      style=licence_table_style))

    # additional information
    if licence.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information',
                                  styles['BoldLeft']))

        for paragraph in licence.additional_information.split('\r\n'):
            if paragraph:
                elements.append(Paragraph(paragraph, styles['Left']))
            else:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # delegation holds the dates, licencee and issuer details.
    delegation = []

    # dates and licensing officer
    dates_licensing_officer_table_style = TableStyle([
        ('VALIGN', (0, 0), (-2, -1), 'TOP'),
        ('VALIGN', (0, 0), (-1, -1), 'BOTTOM')
    ])

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    date_headings = [
        Paragraph('Date of Issue', styles['BoldLeft']),
        Paragraph('Valid From', styles['BoldLeft']),
        Paragraph('Date of Expiry', styles['BoldLeft'])
    ]
    date_values = [
        Paragraph(licence.issue_date.strftime(DATE_FORMAT), styles['Left']),
        Paragraph(licence.start_date.strftime(DATE_FORMAT), styles['Left']),
        Paragraph(licence.end_date.strftime(DATE_FORMAT), styles['Left'])
    ]

    if original_issue_date is not None:
        date_headings.insert(
            0, Paragraph('Original Date of Issue', styles['BoldLeft']))
        date_values.insert(
            0,
            Paragraph(original_issue_date.strftime(DATE_FORMAT),
                      styles['Left']))

    delegation.append(
        Table([[date_headings, date_values]],
              colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
              style=dates_licensing_officer_table_style))

    # licensee details
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    address = application.applicant_profile.postal_address
    address_paragraphs = [
        Paragraph(address.line1, styles['Left']),
        Paragraph(address.line2, styles['Left']),
        Paragraph(address.line3, styles['Left']),
        Paragraph(
            '%s %s %s' % (address.locality, address.state, address.postcode),
            styles['Left']),
        Paragraph(address.country.name, styles['Left'])
    ]
    delegation.append(
        Table([[[
            Paragraph('Licensee:', styles['BoldLeft']),
            Paragraph('Address', styles['BoldLeft'])
        ], [
            Paragraph(render_user_name(application.applicant), styles['Left'])
        ] + address_paragraphs]],
              colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
              style=licence_table_style))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(
            'Issued by a Wildlife Licensing Officer of the Department of Parks and Wildlife '
            'under delegation from the Minister for Environment pursuant to section 133(1) '
            'of the Conservation and Land Management Act 1984.',
            styles['Left']))

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return licence_buffer
Beispiel #17
0
 def _render_user_column(self, obj):
     return render_user_name(obj.applicant_profile.user, first_name_first=False)
Beispiel #18
0
    def _build_data(self, request, application):
        officers = [{'id': officer.id, 'text': render_user_name(officer)} for officer in get_all_officers()]
        officers.insert(0, {'id': 0, 'text': 'Unassigned'})

        current_ass_groups = [ass_request.assessor_group for ass_request in
                              Assessment.objects.filter(application=application)]

        ass_groups = [{'id': ass_group.id, 'text': ass_group.name} for ass_group in
                      AssessorGroup.objects.all().exclude(id__in=[ass_group.pk for ass_group in current_ass_groups]).
                          order_by('name')]

        # extract and format the previous lodgements of the application
        previous_lodgements = []
        for revision in revisions.get_for_object(application).filter(revision__comment='Details Modified').order_by(
                '-revision__date_created'):
            previous_lodgement = revision.object_version.object

            if previous_lodgement.hard_copy is not None:
                previous_lodgement.licence_type.application_schema, previous_lodgement.data = \
                    append_app_document_to_schema_data(previous_lodgement.licence_type.application_schema,
                                                       previous_lodgement.data,
                                                       previous_lodgement.hard_copy.file.url)

            # reversion won't reference the previous many-to-many sets, only the latest one, so need to get documents as per below
            previous_lodgement_documents = Document.objects.filter(pk__in=revision.field_dict['documents'])

            convert_documents_to_url(previous_lodgement.data, previous_lodgement_documents, '')
            previous_lodgements.append({'lodgement_number': '{}-{}'.format(previous_lodgement.lodgement_number,
                                                                           previous_lodgement.lodgement_sequence),
                                        'date': formats.date_format(revision.revision.date_created, 'd/m/Y', True),
                                        'data': previous_lodgement.data})

        previous_application_returns_outstanding = False
        if application.previous_application is not None:
            previous_application_returns_outstanding = Return.objects.filter(
                licence=application.previous_application.licence). \
                exclude(status='accepted').exclude(status='submitted').exists()

        if application.hard_copy is not None:
            application.licence_type.application_schema, application.data = \
                append_app_document_to_schema_data(application.licence_type.application_schema, application.data,
                                                   application.hard_copy.file.url)

        convert_documents_to_url(application.data, application.documents.all(), '')

        data = {
            'user': serialize(request.user),
            'application': serialize(application, posthook=format_application),
            'form_structure': application.licence_type.application_schema,
            'officers': officers,
            'amendment_requests': serialize(AmendmentRequest.objects.filter(application=application),
                                            posthook=format_amendment_request),
            'assessor_groups': ass_groups,
            'assessments': serialize(Assessment.objects.filter(application=application),
                                     posthook=format_assessment),
            'previous_versions': serialize(previous_lodgements),
            'returns_outstanding': previous_application_returns_outstanding,
            'payment_status': payment_utils.PAYMENT_STATUSES.get(payment_utils.
                                                                 get_application_payment_status(application)),
            'csrf_token': str(csrf(request).get('csrf_token'))
        }

        return data
Beispiel #19
0
 def _render_assignee_column(self, obj):
     return render_user_name(obj.application.assigned_officer)