Пример #1
0
    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)
Пример #2
0
    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)
Пример #3
0
    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)
Пример #4
0
    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)