コード例 #1
0
ファイル: views.py プロジェクト: gaiaresources/ledger
    def get_context_data(self, **kwargs):
        ret = get_object_or_404(Return, pk=self.args[0])

        kwargs['return'] = ret

        kwargs['tables'] = []

        for resource in ret.return_type.resources:
            resource_name = resource.get('name')
            schema = Schema(resource.get('schema'))
            headers = []
            for f in schema.fields:
                header = {
                    "title": f.name,
                    "required": f.required
                }
                if f.is_species:
                    header["species"] = f.species_type
                headers.append(header)
            table = {
                'name': resource_name,
                'title': resource.get('title', resource.get('name')),
                'headers': headers
            }
            try:
                return_table = ret.returntable_set.get(name=resource_name)
                rows = [return_row.data for return_row in return_table.returnrow_set.all()]
                validated_rows = list(schema.rows_validator(rows))
                table['data'] = validated_rows
            except ReturnTable.DoesNotExist:
                pass

            kwargs['tables'].append(table)

        if 'upload_spreadsheet_form' not in kwargs:
            kwargs['upload_spreadsheet_form'] = UploadSpreadsheetForm()
        kwargs['nil_return_form'] = NilReturnForm()

        pending_amendments = ret.pending_amendments_qs
        if pending_amendments:
            kwargs['amendments'] = pending_amendments

        return super(EnterReturnView, self).get_context_data(**kwargs)
コード例 #2
0
ファイル: views.py プロジェクト: scottp-dpaw/ledger
    def get_context_data(self, **kwargs):
        ret = get_object_or_404(Return, pk=self.args[0])

        kwargs['return'] = serialize(ret, posthook=format_return)

        kwargs['tables'] = []

        for resource in ret.return_type.resources:
            resource_name = resource.get('name')
            schema = Schema(resource.get('schema'))
            table = {
                'name': resource_name,
                'title': resource.get('title', resource.get('name')),
                'headers': schema.headers
            }

            try:
                return_table = ret.returntable_set.get(name=resource_name)
                rows = [
                    return_row.data
                    for return_row in return_table.returnrow_set.all()
                ]
                validated_rows = list(schema.rows_validator(rows))
                table['data'] = validated_rows
            except ReturnTable.DoesNotExist:
                pass

            kwargs['tables'].append(table)

        kwargs['upload_spreadsheet_form'] = UploadSpreadsheetForm()

        if ret.proxy_customer is None:
            to = ret.licence.holder
        else:
            to = ret.proxy_customer

        kwargs['log_entry_form'] = ReturnsLogEntryForm(
            to=to.get_full_name(),
            fromm=self.request.user.get_full_name(),
        )

        return super(CurateReturnView, self).get_context_data(**kwargs)
コード例 #3
0
ファイル: views.py プロジェクト: gaiaresources/ledger
    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        ret = context['return']

        if 'upload' in request.POST:
            form = UploadSpreadsheetForm(request.POST, request.FILES)

            if form.is_valid():
                temp_file_dir = tempfile.mkdtemp(dir=settings.MEDIA_ROOT)
                try:
                    data = form.cleaned_data.get('spreadsheet_file')
                    path = default_storage.save(os.path.join(temp_file_dir, str(data)), ContentFile(data.read()))

                    workbook = excel.load_workbook_content(path)

                    for table in context['tables']:
                        worksheet = excel.get_sheet(workbook, table.get('title')) \
                            or excel.get_sheet(workbook, table.get('name'))
                        if worksheet is not None:
                            table_data = excel.TableData(worksheet)
                            schema = Schema(ret.return_type.get_schema_by_name(table.get('name')))
                            excel_rows = list(table_data.rows_by_col_header_it())
                            has_errors = not schema.is_all_valid(excel_rows)
                            if has_errors:
                                messages.error(request, "Your return contains some errors. See below.")
                            validated_rows = list(schema.rows_validator(excel_rows))
                            # We want to stringify the datetime/date that might have been created by the excel parser
                            for vr in validated_rows:
                                for col, validation in vr.items():
                                    value = validation.get('value')
                                    if isinstance(value, datetime.datetime) or isinstance(value, datetime.date):
                                        validation['value'] = value.strftime(DATE_FORMAT)
                            table['data'] = validated_rows
                        else:
                            messages.warning(request, 'Missing worksheet ' + table.get('name'))
                finally:
                    shutil.rmtree(temp_file_dir)
            else:
                context['upload_spreadsheet_form'] = form

        elif 'draft' in request.POST or 'draft_continue' in request.POST:
            _create_return_data_from_post_data(ret, context['tables'], request.POST)

            if is_officer(request.user):
                ret.proxy_customer = request.user

            ret.status = 'draft'
            ret.save()

            messages.warning(request, 'Return saved as draft.')

            # redirect or reshow page depending on whether save or save/continue was clicked
            if 'draft' in request.POST:
                return redirect('home')
            else:
                for table in context['tables']:
                    table['data'] = _get_validated_rows_from_post(ret, table.get('name'), request.POST)
        elif 'lodge' in request.POST:
            if _is_post_data_valid(ret, context['tables'], request.POST):

                _create_return_data_from_post_data(ret, context['tables'], request.POST)

                self._set_submitted(ret)
                return redirect('home')
            else:
                for table in context['tables']:
                    table['data'] = _get_validated_rows_from_post(ret, table.get('name'), request.POST)
                    if len(table['data']) == 0:
                        messages.warning(request,
                                         "You must enter data for {} or submit a Nil Return".format(table.get('name')))
                    else:
                        messages.error(request,
                                       "Your return contains some errors. See below.")

        elif 'nil' in request.POST:
            form = NilReturnForm(request.POST)
            if form.is_valid():
                ret.nil_return = True
                ret.comments = form.cleaned_data['comments']
                self._set_submitted(ret)
                return redirect('home')

        return render(request, self.template_name, context)
コード例 #4
0
ファイル: views.py プロジェクト: parksandwildlife/ledger
    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        ret = context["return"]

        if "upload" in request.POST:
            form = UploadSpreadsheetForm(request.POST, request.FILES)

            if form.is_valid():
                temp_file_dir = tempfile.mkdtemp(dir=settings.MEDIA_ROOT)
                try:
                    data = form.cleaned_data.get("spreadsheet_file")
                    path = default_storage.save(os.path.join(temp_file_dir, str(data)), ContentFile(data.read()))

                    workbook = excel.load_workbook_content(path)

                    for table in context["tables"]:
                        worksheet = excel.get_sheet(workbook, table.get("title")) or excel.get_sheet(
                            workbook, table.get("name")
                        )
                        if worksheet is not None:
                            table_data = excel.TableData(worksheet)
                            schema = Schema(ret.return_type.get_schema_by_name(table.get("name")))
                            excel_rows = list(table_data.rows_by_col_header_it())
                            validated_rows = list(schema.rows_validator(excel_rows))
                            # We want to stringify the datetime/date that might have been created by the excel parser
                            for vr in validated_rows:
                                for col, validation in vr.items():
                                    value = validation.get("value")
                                    if isinstance(value, datetime.datetime) or isinstance(value, datetime.date):
                                        validation["value"] = value.strftime(DATE_FORMAT)
                            table["data"] = validated_rows
                        else:
                            messages.warning(request, "Missing worksheet " + table.get("name"))
                finally:
                    shutil.rmtree(temp_file_dir)
            else:
                context["upload_spreadsheet_form"] = form

        elif "draft" in request.POST or "draft_continue" in request.POST:
            _create_return_data_from_post_data(ret, context["tables"], request.POST)

            if is_officer(request.user):
                ret.proxy_customer = request.user

            ret.status = "draft"
            ret.save()

            messages.warning(request, "Return saved as draft.")

            # redirect or reshow page depending on whether save or save/continue was clicked
            if "draft" in request.POST:
                return redirect("home")
            else:
                for table in context["tables"]:
                    table["data"] = _get_validated_rows_from_post(ret, table.get("name"), request.POST)
        elif "lodge" in request.POST:
            if _is_post_data_valid(ret, context["tables"], request.POST):

                _create_return_data_from_post_data(ret, context["tables"], request.POST)

                self._set_submitted(ret)
                return redirect("home")
            else:
                for table in context["tables"]:
                    table["data"] = _get_validated_rows_from_post(ret, table.get("name"), request.POST)
                    if len(table["data"]) == 0:
                        messages.warning(
                            request, "You must enter data for {} or submit a Nil Return".format(table.get("name"))
                        )
        elif "nil" in request.POST:
            form = NilReturnForm(request.POST)
            if form.is_valid():
                ret.nil_return = True
                ret.comments = form.cleaned_data["comments"]
                self._set_submitted(ret)
                return redirect("home")

        return render(request, self.template_name, context)
コード例 #5
0
ファイル: views.py プロジェクト: serge-gaia/ledger
    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        ret = context['return']

        if 'upload' in request.POST:
            form = UploadSpreadsheetForm(request.POST, request.FILES)

            if form.is_valid():
                temp_file_dir = tempfile.mkdtemp(dir=settings.MEDIA_ROOT)
                try:
                    data = form.cleaned_data.get('spreadsheet_file')
                    path = default_storage.save(os.path.join(temp_file_dir, str(data)), ContentFile(data.read()))

                    workbook = excel.load_workbook_content(path)

                    for table in context['tables']:
                        worksheet = excel.get_sheet(workbook, table.get('title')) \
                                    or excel.get_sheet(workbook, table.get('name'))
                        if worksheet is not None:
                            table_data = excel.TableData(worksheet)
                            schema = Schema(ret.return_type.get_schema_by_name(table.get('name')))
                            validated_rows = list(schema.rows_validator(table_data.rows_by_col_header_it()))
                            table['data'] = validated_rows
                        else:
                            messages.warning(request, 'Missing worksheet ' + table.get('name'))
                finally:
                    shutil.rmtree(temp_file_dir)
        elif 'draft' in request.POST or 'draft_continue' in request.POST:
            _create_return_data_from_post_data(ret, context['tables'], request.POST)

            if is_officer(request.user):
                ret.proxy_customer = request.user

            ret.status = 'draft'
            ret.save()

            messages.warning(request, 'Return saved as draft.')

            # redirect or reshow page depending on whether save or save/continue was clicked
            if 'draft' in request.POST:
                return redirect('home')
            else:
                for table in context['tables']:
                    table['data'] = _get_validated_rows_from_post(ret, table.get('name'), request.POST)
        elif 'lodge' in request.POST:
            if _is_post_data_valid(ret, context['tables'], request.POST):

                _create_return_data_from_post_data(ret, context['tables'], request.POST)

                ret.lodgement_number = '%s-%s' % (str(ret.licence.licence_type.pk).zfill(LICENCE_TYPE_NUM_CHARS),
                                                  str(ret.pk).zfill(LODGEMENT_NUMBER_NUM_CHARS))

                ret.lodgement_date = date.today()

                if is_officer(request.user):
                    ret.proxy_customer = request.user

                ret.status = 'submitted'
                ret.save()

                message = 'Return successfully submitted.'

                # update next return in line's status to become the new current return
                next_ret = Return.objects.filter(licence=ret.licence, status='future').order_by('due_date').first()

                if next_ret is not None:
                    next_ret.status = 'current'
                    next_ret.save()

                    message += ' The next return for this licence can now be entered and is due on {}.'.\
                        format(next_ret.due_date.strftime(DATE_FORMAT))

                return_submitted.send(sender=self.__class__, ret=ret)

                messages.success(request, message)

                return redirect('home')
            else:
                for table in context['tables']:
                    table['data'] = _get_validated_rows_from_post(ret, table.get('name'), request.POST)
                    if len(table['data']) == 0:
                        messages.warning(request, "You must enter data for {}".format(table.get('name')))

        return render(request, self.template_name, context)
コード例 #6
0
ファイル: views.py プロジェクト: brendanc-dpaw/ledger
    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        ret = context['return']

        if 'upload' in request.POST:
            form = UploadSpreadsheetForm(request.POST, request.FILES)

            if form.is_valid():
                temp_file_dir = tempfile.mkdtemp(dir=settings.MEDIA_ROOT)
                try:
                    data = form.cleaned_data.get('spreadsheet_file')
                    path = default_storage.save(os.path.join(temp_file_dir, str(data)), ContentFile(data.read()))

                    workbook = excel.load_workbook_content(path)

                    for table in context['tables']:
                        worksheet = excel.get_sheet(workbook, table.get('title')) \
                                    or excel.get_sheet(workbook, table.get('name'))
                        if worksheet is not None:
                            table_data = excel.TableData(worksheet)
                            schema = Schema(ret.return_type.get_schema_by_name(table.get('name')))
                            validated_rows = list(schema.rows_validator(table_data.rows_by_col_header_it()))
                            table['data'] = validated_rows
                        else:
                            messages.warning(request, 'Missing worksheet ' + table.get('name'))
                finally:
                    shutil.rmtree(temp_file_dir)
        elif 'draft' in request.POST or 'draft_continue' in request.POST:
            _create_return_data_from_post_data(ret, context['tables'], request.POST)

            if is_officer(request.user):
                ret.proxy_customer = request.user

            ret.status = 'draft'
            ret.save()

            messages.warning(request, 'Return saved as draft.')

            # redirect or reshow page depending on whether save or save/continue was clicked
            if 'draft' in request.POST:
                return redirect('home')
            else:
                for table in context['tables']:
                    table['data'] = _get_validated_rows_from_post(ret, table.get('name'), request.POST)
        elif 'lodge' in request.POST:
            if _is_post_data_valid(ret, context['tables'], request.POST):

                _create_return_data_from_post_data(ret, context['tables'], request.POST)

                self._set_submitted(ret)
                return redirect('home')
            else:
                for table in context['tables']:
                    table['data'] = _get_validated_rows_from_post(ret, table.get('name'), request.POST)
                    if len(table['data']) == 0:
                        messages.warning(request,
                                         "You must enter data for {} or submit a Nil Return".format(table.get('name')))
        elif 'nil' in request.POST:
            form = NilReturnForm(request.POST)
            if form.is_valid():
                ret.nil_return = True
                ret.comments = form.cleaned_data['comments']
                self._set_submitted(ret)
                return redirect('home')

        return render(request, self.template_name, context)