def remove_temp_applications_for_user(user): if is_customer(user): Application.objects.filter(applicant=user, customer_status='temp').delete() elif is_officer(user): Application.objects.filter(proxy_applicant=user, customer_status='temp').delete()
def _set_submitted(self, ret): 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 = datetime.date.today() if is_officer(self.request.user): ret.proxy_customer = self.request.user # assume that all the amendment requests has been solved. pending_amendments = ret.pending_amendments_qs if pending_amendments: pending_amendments.update(status='amended') ret.status = 'amended' else: 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(self.request, message)
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[1]) if len(self.args) > 1 else None licence_type = WildlifeLicenceType.objects.get(code=self.args[0]) if is_app_session_data_set(self.request.session, 'profile_pk'): profile = get_object_or_404(Profile, pk=get_app_session_data(self.request.session, 'profile_pk')) else: profile = application.applicant_profile with open('%s/json/%s.json' % (APPLICATION_SCHEMA_PATH, self.args[0])) as data_file: form_structure = json.load(data_file) kwargs['licence_type'] = licence_type kwargs['profile'] = profile kwargs['structure'] = form_structure kwargs['is_proxy_applicant'] = is_officer(self.request.user) if application is not None: kwargs['application_pk'] = application.pk if application.review_status == 'awaiting_amendments': amendments = AmendmentRequest.objects.filter(application=application).filter(status='requested') kwargs['amendments'] = amendments if is_app_session_data_set(self.request.session, 'data'): data = get_app_session_data(self.request.session, 'data') temp_files_dir = get_app_session_data(self.request.session, 'temp_files_dir') if temp_files_dir is not None: temp_files_url = settings.MEDIA_URL + os.path.basename(os.path.normpath(temp_files_dir)) prepend_url_to_application_data_files(form_structure, data, temp_files_url) kwargs['data'] = data return super(EnterDetailsView, self).get_context_data(**kwargs)
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[0]) 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(), '') kwargs['application'] = serialize(application, posthook=format_application) if is_officer(self.request.user): kwargs['customer'] = application.applicant kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application), fromm=self.request.user.get_full_name()) else: kwargs['payment_status'] = payment_utils.PAYMENT_STATUSES.get(payment_utils. get_application_payment_status(application)) if application.processing_status == 'declined': message = "This application has been declined." details = ApplicationDeclinedDetails.objects.filter(application=application).first() if details and details.reason: message += "<br/>Reason:<br/>{}".format(details.reason.replace('\n', '<br/>')) kwargs['application']['declined_reason'] = details.reason messages.error(self.request, message) return super(ViewReadonlyView, self).get_context_data(**kwargs)
def _set_submitted(self, ret): 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 = datetime.date.today() if is_officer(self.request.user): ret.proxy_customer = self.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(self.request, message)
def get(self, request, *args, **kwargs): utils.remove_temp_applications_for_user(request.user) previous_application = get_object_or_404(Application, licence=args[0]) # check if there is already a renewal or amendment, otherwise create one try: application = Application.objects.get( previous_application=previous_application) if application.customer_status == 'under_review': messages.warning( request, 'An amendment for this licence has already been lodged and is awaiting review.' ) return redirect('wl_dashboard:home') except Application.DoesNotExist: application = utils.clone_application_with_status_reset( previous_application, is_licence_amendment=True) application.application_type = 'amendment' if is_officer(request.user): application.proxy_applicant = request.user application.save() utils.set_session_application(request.session, application) return redirect('wl_applications:enter_details')
def get_user_home_url(user): if accounts_helpers.is_officer(user): return '/dashboard/officer' elif accounts_helpers.is_assessor(user): return '/dashboard/tables/assessor' return '/dashboard/tables/customer'
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[0]) 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() ) kwargs["application"] = application if is_officer(self.request.user): kwargs["customer"] = application.applicant_profile.user if application.proxy_applicant is None: to = application.applicant_profile.user.email else: to = application.proxy_applicant.email kwargs["log_entry_form"] = CommunicationsLogEntryForm(to=to, fromm=self.request.user.email) return super(ViewReadonlyView, self).get_context_data(**kwargs)
def get_context_data(self, **kwargs): with open('%s/json/%s.json' % (APPLICATION_SCHEMA_PATH, self.args[0])) as data_file: form_structure = json.load(data_file) licence_type = WildlifeLicenceType.objects.get(code=self.args[0]) application = get_object_or_404(Application, pk=self.args[1]) if len(self.args) > 1 else None if is_app_session_data_set(self.request.session, 'profile_pk'): profile = get_object_or_404(Profile, pk=get_app_session_data(self.request.session, 'profile_pk')) else: profile = application.applicant_profile kwargs['licence_type'] = licence_type kwargs['profile'] = profile kwargs['structure'] = form_structure kwargs['is_proxy_applicant'] = is_officer(self.request.user) if len(self.args) > 1: kwargs['application_pk'] = self.args[1] if is_app_session_data_set(self.request.session, 'data'): data = get_app_session_data(self.request.session, 'data') temp_files_url = settings.MEDIA_URL + \ os.path.basename(os.path.normpath(get_app_session_data(self.request.session, 'temp_files_dir'))) prepend_url_to_application_data_files(form_structure, data, temp_files_url) kwargs['data'] = data return super(PreviewView, self).get_context_data(**kwargs)
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[0]) 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(), '') kwargs['application'] = serialize(application, posthook=format_application) if is_officer(self.request.user): kwargs['customer'] = application.applicant kwargs['log_entry_form'] = ApplicationLogEntryForm( to=get_log_entry_to(application), fromm=self.request.user.get_full_name()) else: kwargs['payment_status'] = payment_utils.PAYMENT_STATUSES.get( payment_utils.get_application_payment_status(application)) return super(ViewReadonlyView, self).get_context_data(**kwargs)
def setUp(self): self.customer = helpers.get_or_create_default_customer() self.assertTrue(is_customer(self.customer)) self.officer = helpers.get_or_create_default_officer() self.assertTrue(is_officer(self.officer)) self.assessor = helpers.get_or_create_default_assessor() self.assertTrue(is_assessor(self.assessor)) self.client = helpers.SocialClient()
def test_create_default_officer(self): user = get_or_create_default_officer() self.assertIsNotNone(user) self.assertTrue(isinstance(user, EmailUser)) self.assertEqual(TestData.DEFAULT_OFFICER['email'], user.email) self.assertTrue(accounts_helpers.is_officer(user)) # test that we can login self.client.login(user.email) is_client_authenticated(self.client)
def get(self, *args, **kwargs): if self.request.user.is_authenticated(): if is_officer(self.request.user): return redirect('wl_dashboard:tree_officer') elif is_assessor(self.request.user): return redirect('wl_dashboard:tables_assessor') return redirect('wl_dashboard:tables_customer') else: kwargs['form'] = LoginForm return super(DashBoardRoutingView, self).get(*args, **kwargs)
def test_func(self): """ implementation of the UserPassesTestMixin test_func """ user = self.request.user if is_officer(user): return True ret = self.get_return() if ret is not None: return ret.licence.holder == user else: return True
def test_func(self): """ implementation of the UserPassesTestMixin test_func """ user = self.request.user if not user.is_authenticated(): self.raise_exception = False return False self.raise_exception = True if is_customer(user) or is_officer(user): return False assessment = self.get_assessment() return assessment is not None and assessment.assessor_group in get_user_assessor_groups(user)
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[0]) with open('%s/json/%s.json' % (APPLICATION_SCHEMA_PATH, application.licence_type.code)) as data_file: form_structure = json.load(data_file) kwargs['licence_type'] = application.licence_type kwargs['structure'] = form_structure kwargs['data'] = application.data if is_officer(self.request.user): kwargs['customer'] = application.applicant_profile.user return super(ViewReadonlyView, self).get_context_data(**kwargs)
def test_func(self): """ implementation of the UserCanEditApplicationMixin test_func """ user = self.request.user if not user.is_authenticated(): return False if is_officer(user): return True application = self.get_application() if application is not None: return application.applicant == user and application.can_user_edit else: return True
def test_func(self): """ implementation of the UserPassesTestMixin test_func """ user = self.request.user if not user.is_authenticated(): self.raise_exception = False return False self.raise_exception = True if is_customer(user) or is_officer(user): return False assessment = self.get_assessment() return assessment is not None and assessment.assessor_group in get_user_assessor_groups( user)
def get(self, *args, **kwargs): if self.request.user.is_authenticated(): if (not self.request.user.first_name) or (not self.request.user.last_name) or (not self.request.user.dob): messages.info(self.request, 'Welcome! As this is your first time using the website, please enter your full name and date of birth.') return redirect('wl_main:edit_account') if is_officer(self.request.user): return redirect('wl_dashboard:tree_officer') elif is_assessor(self.request.user): return redirect('wl_dashboard:tables_assessor') return redirect('wl_dashboard:tables_customer') else: kwargs['form'] = LoginForm return super(DashBoardRoutingView, self).get(*args, **kwargs)
def get_context_data(self, **kwargs): kwargs['licence_type'] = get_object_or_404(WildlifeLicenceType, code_slug=self.args[0]) if is_officer(self.request.user) and utils.is_app_session_data_set(self.request.session, 'customer_pk'): kwargs['customer'] = EmailUser.objects.get(pk=utils.get_app_session_data(self.request.session, 'customer_pk')) kwargs['is_renewal'] = False if len(self.args) > 1: try: application = Application.objects.get(pk=self.args[1]) if application.processing_status == 'renewal': kwargs['is_renewal'] = True except Exception: pass return super(ApplicationEntryBaseView, self).get_context_data(**kwargs)
def test_func(self): """ implementation of the UserCanAmendApplicationMixin test_func """ user = self.request.user if not user.is_authenticated(): return False if is_officer(user): return True application = self.get_application() if application is not None: if application.applicant != user: return False return application.licence.end_date >= datetime.date.today() else: return False
def test_func(self): """ implementation of the UserPassesTestMixin test_func """ user = self.request.user if not user.is_authenticated(): self.raise_exception = False return False if is_officer(user): return True self.raise_exception = True ret = self.get_return() if ret is not None: return ret.licence.holder == user and ret.can_user_edit else: return True
def test_func(self): """ implementation of the UserPassesTestMixin test_func """ user = self.request.user if not user.is_authenticated(): self.raise_exception = False return False if is_officer(user): return True self.raise_exception = True application = self.get_application() if application is not None: return application.applicant == user and application.can_user_view else: return True
def test_func(self): """ implementation of the UserPassesTestMixin test_func """ user = self.request.user if not user.is_authenticated(): self.raise_exception = False return False if is_officer(user): return True self.raise_exception = True application = self.get_application() if application is not None: return application.applicant_profile.user == user and application.can_user_view else: return True
def test_func(self): """ implementation of the UserCanRenewApplicationMixin test_func """ user = self.request.user if not user.is_authenticated(): return False if is_officer(user): return True application = self.get_application() if application is not None: if application.applicant != user: return False expiry_days = (application.licence.end_date - datetime.date.today()).days return expiry_days <= 30 and application.licence.is_renewable else: return False
def get(self, request, *args, **kwargs): application = get_object_or_404(Application, pk=args[0]) product = get_product(generate_product_title(application)) user = application.applicant.id error_url = request.build_absolute_uri( reverse('wl_applications:preview')) success_url = request.build_absolute_uri( reverse('wl_applications:complete')) parameters = { 'system': PAYMENT_SYSTEM_ID, 'basket_owner': user, 'associateInvoiceWithToken': True, 'checkoutWithToken': True, 'fallback_url': error_url, 'return_url': success_url, 'forceRedirect': True, 'template': 'wl/payment_information.html', 'proxy': is_officer(request.user), "products": [{ "id": product.id if product is not None else None }], "vouchers": [] } headers = { 'X-CSRFToken': request.COOKIES.get('csrftoken'), 'Referer': request.META.get('HTTP_REFERER'), } headers.update(JSON_REQUEST_HEADER_PARAMS) # senior discount if application.is_senior_offer_applicable: parameters['vouchers'].append({'code': SENIOR_VOUCHER_CODE}) url = request.build_absolute_uri( reverse('payments:ledger-initial-checkout')) response = requests.post(url, headers=headers, cookies=request.COOKIES, data=json.dumps(parameters)) return HttpResponse(response.content)
def test_func(self): """ implementation of the UserCanAmendApplicationMixin test_func """ user = self.request.user if not user.is_authenticated(): self.raise_exception = False return False if is_officer(user): return True self.raise_exception = True application = self.get_application() if application is not None: if application.applicant != user: return False return application.licence.end_date >= datetime.date.today() else: return False
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[1]) if len(self.args) > 1 else None licence_type = WildlifeLicenceType.objects.get(code_slug=self.args[0]) if utils.is_app_session_data_set(self.request.session, 'profile_pk'): profile = get_object_or_404(Profile, pk=utils.get_app_session_data(self.request.session, 'profile_pk')) else: profile = application.applicant_profile kwargs['licence_type'] = licence_type kwargs['profile'] = profile kwargs['structure'] = licence_type.application_schema kwargs['is_proxy_applicant'] = is_officer(self.request.user) if application is not None: kwargs['application_pk'] = application.pk if application.review_status == 'awaiting_amendments': amendments = AmendmentRequest.objects.filter(application=application).filter(status='requested') kwargs['amendments'] = amendments temp_files_dir = utils.get_app_session_data(self.request.session, 'temp_files_dir') if temp_files_dir is not None: temp_files_url = settings.MEDIA_URL + os.path.basename(os.path.normpath(temp_files_dir)) if utils.is_app_session_data_set(self.request.session, 'data'): data = utils.get_app_session_data(self.request.session, 'data') if temp_files_dir is not None: utils.prepend_url_to_files(licence_type.application_schema, data, temp_files_url) kwargs['data'] = data if utils.is_app_session_data_set(self.request.session, 'application_document'): application_document = utils.get_app_session_data(self.request.session, 'application_document') if temp_files_dir is not None: application_document = os.path.join(temp_files_url, application_document) kwargs['application_document'] = application_document return super(EnterDetailsView, self).get_context_data(**kwargs)
def get_context_data(self, **kwargs): licence_type = WildlifeLicenceType.objects.get(code_slug=self.args[0]) application = get_object_or_404(Application, pk=self.args[1]) if len(self.args) > 1 else None if utils.is_app_session_data_set(self.request.session, 'profile_pk'): profile = get_object_or_404(Profile, pk=utils.get_app_session_data(self.request.session, 'profile_pk')) else: profile = application.applicant_profile kwargs['licence_type'] = licence_type kwargs['profile'] = profile kwargs['structure'] = licence_type.application_schema kwargs['is_proxy_applicant'] = is_officer(self.request.user) if len(self.args) > 1: kwargs['application_pk'] = self.args[1] temp_files_dir = utils.get_app_session_data(self.request.session, 'temp_files_dir') if temp_files_dir is not None: temp_files_url = settings.MEDIA_URL + os.path.basename(os.path.normpath(temp_files_dir)) if utils.is_app_session_data_set(self.request.session, 'data'): data = utils.get_app_session_data(self.request.session, 'data') if temp_files_dir is not None: utils.prepend_url_to_files(licence_type.application_schema, data, temp_files_url) kwargs['data'] = data if utils.is_app_session_data_set(self.request.session, 'application_document'): application_document = utils.get_app_session_data(self.request.session, 'application_document') if temp_files_dir is not None: application_document = os.path.join(temp_files_url, application_document) kwargs['structure'], kwargs['data'] = utils.append_app_document_to_schema_data(kwargs['structure'], kwargs['data'], application_document) return super(PreviewView, self).get_context_data(**kwargs)
def test_func(self): """ implementation of the UserCanRenewApplicationMixin test_func """ user = self.request.user if not user.is_authenticated(): self.raise_exception = False return False if is_officer(user): return True self.raise_exception = True application = self.get_application() if application is not None: if application.applicant != user: return False expiry_days = (application.licence.end_date - datetime.date.today()).days return expiry_days <= 30 and application.licence.is_renewable else: return False
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[0]) 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(), '') kwargs['application'] = serialize(application, posthook=format_application) if is_officer(self.request.user): kwargs['customer'] = application.applicant kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application), fromm=self.request.user.get_full_name()) else: kwargs['payment_status'] = payment_utils.PAYMENT_STATUSES.get(payment_utils. get_application_payment_status(application)) return super(ViewReadonlyView, self).get_context_data(**kwargs)
def get(self, request, *args, **kwargs): utils.remove_temp_applications_for_user(request.user) previous_application = get_object_or_404(Application, licence=args[0]) # check if there is already a renewal, otherwise create one try: application = Application.objects.get(previous_application=previous_application) if application.customer_status == 'under_review': messages.warning(request, 'A renewal for this licence has already been lodged and is awaiting review.') return redirect('wl_dashboard:home') except Application.DoesNotExist: application = utils.clone_application_with_status_reset(previous_application) application.application_type = 'renewal' if is_officer(request.user): application.proxy_applicant = request.user application.save() utils.set_session_application(request.session, application) return redirect('wl_applications:enter_details')
def get_context_data(self, **kwargs): application = get_object_or_404(Application, pk=self.args[0]) 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(), '') kwargs['application'] = serialize(application,posthook=format_application, related={ 'applicant': {'exclude': ['residential_address','postal_address','billing_address']}, 'applicant_profile':{'fields':['email','id','institution','name']}, 'previous_application':{'exclude':['applicant','applicant_profile','previous_application','licence']}, 'licence':{'related':{ 'holder':{'exclude': ['residential_address','postal_address','billing_address']}, 'issuer':{'exclude': ['residential_address','postal_address','billing_address']}, 'profile':{'related': {'user': {'exclude': ['residential_address','postal_address','billing_address']}}, 'exclude': ['postal_address']} },'exclude':['holder','issuer','profile','licence_ptr']} }) if is_officer(self.request.user): kwargs['customer'] = application.applicant kwargs['log_entry_form'] = ApplicationLogEntryForm(to=get_log_entry_to(application), fromm=self.request.user.get_full_name()) else: kwargs['payment_status'] = payment_utils.PAYMENT_STATUSES.get(payment_utils. get_application_payment_status(application)) if application.processing_status == 'declined': message = "This application has been declined." details = ApplicationDeclinedDetails.objects.filter(application=application).first() if details and details.reason: message += "<br/>Reason:<br/>{}".format(details.reason.replace('\n', '<br/>')) kwargs['application']['declined_reason'] = details.reason messages.error(self.request, message) return super(ViewReadonlyView, self).get_context_data(**kwargs)
def get(self, request, *args, **kwargs): application = get_object_or_404(Application, pk=args[0]) product = get_product(generate_product_title(application)) user = application.applicant.id error_url = request.build_absolute_uri( reverse('wl_applications:preview')) success_url = request.build_absolute_uri( reverse('wl_applications:complete')) basket_params = { 'products': [{ 'id': product.id if product is not None else None }], 'vouchers': [], 'system': PAYMENT_SYSTEM_ID } # senior discount if application.is_senior_offer_applicable: basket_params['vouchers'].append({'code': SENIOR_VOUCHER_CODE}) basket, basket_hash = create_basket_session(request, basket_params) checkout_params = { 'system': PAYMENT_SYSTEM_ID, 'basket_owner': user, 'associate_invoice_with_token': True, 'fallback_url': error_url, 'return_url': success_url, 'force_redirect': True, 'template': 'wl/payment_information.html', 'proxy': is_officer(request.user), } create_checkout_session(request, checkout_params) if checkout_params['proxy']: response = place_order_submission(request) else: response = HttpResponseRedirect(reverse('checkout:index')) return response
def get(self, request, *args, **kwargs): application = get_object_or_404(Application, pk=args[0]) product = get_product(generate_product_title(application)) user = application.applicant.id error_url = request.build_absolute_uri(reverse('wl_applications:preview')) success_url = request.build_absolute_uri(reverse('wl_applications:complete')) basket_params = { 'products': [ {'id': product.id if product is not None else None} ], 'vouchers': [], 'system': PAYMENT_SYSTEM_ID } # senior discount if application.is_senior_offer_applicable: basket_params['vouchers'].append({'code': SENIOR_VOUCHER_CODE}) basket, basket_hash = create_basket_session(request, basket_params) checkout_params = { 'system': PAYMENT_SYSTEM_ID, 'basket_owner': user, 'associate_invoice_with_token': True, 'fallback_url': error_url, 'return_url': success_url, 'force_redirect': True, 'template': 'wl/payment_information.html', 'proxy': is_officer(request.user), } create_checkout_session(request, checkout_params) if checkout_params['proxy']: response = place_order_submission(request) else: response = HttpResponseRedirect(reverse('checkout:index')) return response
def get(self, request, *args, **kwargs): application = get_object_or_404(Application, pk=args[0]) product = get_product(generate_product_code(application)) user = application.applicant.id error_url = request.build_absolute_uri(reverse('wl_applications:preview')) success_url = request.build_absolute_uri(reverse('wl_applications:complete')) parameters = { 'system': PAYMENT_SYSTEM_ID, 'basket_owner': user, 'associateInvoiceWithToken': True, 'checkoutWithToken': True, 'fallback_url': error_url, 'return_url': success_url, 'forceRedirect': True, 'template': 'wl/payment_information.html', 'proxy': is_officer(request.user), "products": [ {"id": product.id if product is not None else None} ], "vouchers": [] } # senior discount if application.is_senior_offer_applicable: parameters['vouchers'].append({'code': SENIOR_VOUCHER_CODE}) url = request.build_absolute_uri( reverse('payments:ledger-initial-checkout') ) response = requests.post(url, headers=JSON_REQUEST_HEADER_PARAMS, cookies=request.COOKIES, data=json.dumps(parameters)) return HttpResponse(response.content)
def test_func(self): user = self.request.user return is_officer(user) or is_customer(user)
def test_func(self): """ implementation of the UserPassesTestMixin test_func """ user = self.request.user return is_officer(user)
def remove_temp_applications_for_user(user): if is_customer(user): Application.objects.filter(applicant=user, customer_status="temp").delete() elif is_officer(user): Application.objects.filter(proxy_applicant=user, customer_status="temp").delete()
def post(self, request, *args, **kwargs): licence_type = WildlifeLicenceType.objects.get(code_slug=self.args[0]) utils.rename_filename_doubleups(request.POST, request.FILES) utils.set_app_session_data(request.session, 'data', utils.create_data_from_form(licence_type.application_schema, request.POST, request.FILES)) temp_files_dir = utils.get_app_session_data(request.session, 'temp_files_dir') if 'draft' in request.POST or 'draft_continue' in request.POST: if len(args) > 1: application = get_object_or_404(Application, pk=args[1]) else: application = Application() if is_officer(request.user): application.proxy_applicant = request.user application.data = utils.get_app_session_data(request.session, 'data') application.licence_type = WildlifeLicenceType.objects.get(code_slug=args[0]) application.applicant_profile = get_object_or_404(Profile, pk=utils.get_app_session_data(request.session, 'profile_pk')) application.customer_status = 'draft' if application.processing_status != 'renewal': application.processing_status = 'draft' application.save(version_user=application.applicant_profile.user) application.documents.clear() # need to create documents from all the existing files that haven't been replaced # (saved in temp_files_dir) as well as any new ones try: for filename in utils.get_all_filenames_from_application_data(licence_type.application_schema, utils.get_app_session_data(request.session, 'data')): # need to be sure file is in tmp directory (as it could be a freshly attached file) if os.path.exists(os.path.join(temp_files_dir, filename)): document = Document.objects.create(name=filename) with open(os.path.join(temp_files_dir, filename), 'rb') as doc_file: document.file.save(filename, File(doc_file), save=True) application.documents.add(document) except Exception as e: messages.error(request, 'There was a problem appending applications files: %s' % e) for f in request.FILES: if f == 'application_document': application.hard_copy = Document.objects.create(name=str(request.FILES[f]), file=request.FILES[f]) else: application.documents.add(Document.objects.create(name=str(request.FILES[f]), file=request.FILES[f])) application.save(no_revision=True) messages.warning(request, 'The application was saved to draft.') if 'draft' in request.POST: try: utils.delete_app_session_data(request.session) except Exception as e: messages.warning(request, 'There was a problem deleting session data: %s' % e) return redirect('wl_dashboard:home') else: # if continuing, need to save new files in temp so they can be previewed on enter details screen if len(request.FILES) > 0: temp_files_dir = utils.get_app_session_data(request.session, 'temp_files_dir') for f in request.FILES: if f == 'application_document': utils.set_app_session_data(request.session, 'application_document', str(request.FILES[f])) with open(os.path.join(temp_files_dir, str(request.FILES[f])), 'wb+') as destination: for chunk in request.FILES[f].chunks(): destination.write(chunk) return redirect('wl_applications:enter_details', args[0], application.pk) else: if len(request.FILES) > 0: temp_files_dir = utils.get_app_session_data(request.session, 'temp_files_dir') for f in request.FILES: if f == 'application_document': utils.set_app_session_data(request.session, 'application_document', str(request.FILES[f])) with open(os.path.join(temp_files_dir, str(request.FILES[f])), 'wb+') as destination: for chunk in request.FILES[f].chunks(): destination.write(chunk) return redirect('wl_applications:preview', *args)
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)
def test_func(self): user = self.request.user return is_officer(user) or is_assessor(user)
def post(self, request, *args, **kwargs): if len(args) > 1: application = get_object_or_404(Application, pk=args[1]) else: application = Application() if is_officer(request.user): application.proxy_applicant = request.user application.data = utils.get_app_session_data(self.request.session, 'data') application.licence_type = get_object_or_404(WildlifeLicenceType, code_slug=args[0]) application.correctness_disclaimer = request.POST.get('correctnessDisclaimer', '') == 'on' application.further_information_disclaimer = request.POST.get('furtherInfoDisclaimer', '') == 'on' application.applicant_profile = get_object_or_404(Profile, pk=utils.get_app_session_data(request.session, 'profile_pk')) application.lodgement_sequence += 1 application.lodgement_date = datetime.now().date() if application.customer_status == 'amendment_required': # this is a 're-lodged' application after some amendment were required. # from this point we assume that all the amendments have been amended. AmendmentRequest.objects.filter(application=application).filter(status='requested').update(status='amended') application.review_status = 'amended' application.processing_status = 'ready_for_action' else: if application.processing_status != 'renewal': application.processing_status = 'new' application.customer_status = 'under_review' # need to save application in order to get its pk if not application.lodgement_number: application.save(no_revision=True) application.lodgement_number = '%s-%s' % (str(application.licence_type.pk).zfill(LICENCE_TYPE_NUM_CHARS), str(application.pk).zfill(LODGEMENT_NUMBER_NUM_CHARS)) application.documents.clear() # if attached files were saved temporarily, add each to application as part of a Document temp_files_dir = utils.get_app_session_data(request.session, 'temp_files_dir') try: for filename in utils.get_all_filenames_from_application_data(application.licence_type.application_schema, utils.get_app_session_data(request.session, 'data')): document = Document.objects.create(name=filename) with open(os.path.join(temp_files_dir, filename), 'rb') as doc_file: document.file.save(filename, File(doc_file), save=True) application.documents.add(document) if utils.is_app_session_data_set(request.session, 'application_document'): filename = utils.get_app_session_data(request.session, 'application_document') document = Document.objects.create(name=filename) with open(os.path.join(utils.get_app_session_data(request.session, 'temp_files_dir'), filename), 'rb') as doc_file: document.file.save(filename, File(doc_file), save=True) application.hard_copy = document messages.success(request, 'The application was successfully lodged.') except Exception as e: messages.error(request, 'There was a problem creating the application: %s' % e) application.save(version_user=application.applicant_profile.user, version_comment='Details Modified') try: utils.delete_app_session_data(request.session) except Exception as e: messages.warning(request, 'There was a problem deleting session data: %s' % e) return redirect('wl_dashboard:home')
def is_officer(user): return helpers.is_officer(user)
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)
def test_func(self): return is_officer(self.request.user)