def login_page(request): object = {} object['get_seo_title'] = Settings.get_seo_title_template("Вход на сайт") object['get_meta_description'] = Settings.get_meta_description() object['get_meta_keywords'] = Settings.get_meta_keywords() return render(request, 'lk/login.html', locals())
def result(request): if 'enrollment' not in request.session: return redirect('enrollment:registration') enrollment = get_or_create_enrollment(request) if enrollment.state == 'registration' and enrollment.result not in ['cancel', 'fail']: # Whoops, how did we get here without going through payment first? Redirect back. return redirect('enrollment:payment_method') elif enrollment.state == 'payment': # Not done with payments, why is the user here? Redirect back to payment processing if enrollment.payment_method == 'invoice': return redirect('enrollment:process_invoice') elif enrollment.payment_method == 'card': return redirect("%s?merchantId=%s&transactionId=%s" % ( settings.NETS_TERMINAL_URL, settings.NETS_MERCHANT_ID, enrollment.transactions.get(state='register', active=True).transaction_id, )) # Collect emails to a separate list for easier template formatting emails = [user.email for user in enrollment.users.all() if user.email != ''] skip_header = enrollment.result == 'success_invoice' or enrollment.result == 'success_card' proof_validity_end = datetime.now() + timedelta(days=settings.MEMBERSHIP['TEMPORARY_PROOF_VALIDITY']) context = { 'enrollment': enrollment, 'skip_header': skip_header, 'proof_validity_end': proof_validity_end, 'emails': emails, 'innmelding_aktivitet': request.session.get('innmelding.aktivitet'), 'settings': Settings.get_cached(), } context.update(current_template_layout(request)) return render(request, 'central/enrollment/result/%s.html' % enrollment.result, context)
def payment_method(request): enrollment = get_or_create_enrollment(request) if enrollment.state == 'payment': # Payment has been initiated but the user goes back here - why? # Reset the state and let them reinitiate payment when they're ready. enrollment.state = 'registration' enrollment.save() elif enrollment.state == 'complete': # A previous registration has been completed, so why would the user come directly here? # Just redirect them back to registration which will restart a new registration. return redirect("enrollment:registration") enrolling_through_aktivitet = 'innmelding.aktivitet' in request.session # Check conditions needed to enable invoice payment invoice_available = all([ # Invoice payment can be disabled by admin Settings.get_cached().enrollment_accept_invoice, # If enrolling through aktivitet, you need to pay with card so that the # membership is confirmed not enrolling_through_aktivitet, # Foreign members must pay with card enrollment.get_country().code == 'NO', ]) context = { 'enrollment': enrollment, 'enrolling_through_aktivitet': enrolling_through_aktivitet, 'invoice_available': invoice_available, } context.update(current_template_layout(request)) return render(request, 'central/enrollment/payment.html', context)
def get_invoice(self): """Returns the current invoice for this member. Raises DoesNotExist if there's no invoice generated for them this year.""" from core.models import Settings from core.util import membership_year_start invoices = self.invoices.filter( # Filter on invoices issued after previous årskrav invoice_date__gte=Settings.get_cached().arskrav_initiation_date_last_year, ).order_by( '-invoice_date' ) # Exclude invoices that aren't recorded in the reskontro, and exclude # completed reskontro entries; these are marked as 'open' account_invoices = [a.invoice_id for a in self.accounts.filter(open=False)] invoices = [i for i in invoices if i.invoice_number in account_invoices] if len(invoices) == 0: # No invoices generated for this member; they were likely not a # member last year raise InvoiceHead.DoesNotExist else: # Select only the newest invoice, regardless of whether there were # multiple matches. In such cases, typically only the newest one # is applicable. return invoices[0]
def sync(): profile = Profile.objects.filter(user__username='******').first() if profile is None: return last_tweet_id = Settings.last_tweet_id() timeline = t.get_timeline(since_id=last_tweet_id.value) timeline.reverse() count = 0 for tweet in timeline: weibo = tweet.to_weibo() if weibo is not None: result = oauth_weibo.post(profile, weibo) if result: last_tweet_id.value = weibo.tweet_id last_tweet_id.save() count += 1 seconds = random.randint(15, 45) time.sleep(seconds) logger.info(f'Tweets: Published. Sleep {seconds} seconds') logger.info(f'Cron job finished. Length: {len(timeline)}, sent: {count}')
def title_and_tagline(request): try: s = Settings.get_current() return { 'SITE_TITLE': s.title, 'SITE_TAGLINE': s.tagline } except: return {}
def status(request): if request.method == 'GET': return render(request, 'central/admin/enrollment/status.html') elif request.method == 'POST': settings = Settings.objects.get() settings.enrollment_is_active = request.POST.get('enrollment_is_active') == 'on' if 'enrollment_title' in request.POST: settings.enrollment_title = request.POST['enrollment_title'] settings.enrollment_accept_card = request.POST.get('enrollment_accept_card') == 'on' settings.enrollment_accept_invoice = request.POST.get('enrollment_accept_invoice') == 'on' settings.enrollment_message_show = request.POST.get('enrollment_message_show') == 'on' settings.renew_membership_foreign = request.POST.get('renew_membership_foreign') == 'on' settings.renew_membership_norwegian = request.POST.get('renew_membership_norwegian') == 'on' if 'enrollment_message' in request.POST: settings.enrollment_message = request.POST['enrollment_message'] settings.focus_writes = request.POST.get('focus_writes') == 'on' if 'focus_writes_message' in request.POST: settings.focus_writes_message = request.POST['focus_writes_message'] try: settings.arskrav_initiation_date_last_year = datetime.strptime( request.POST.get('arskrav_initiation_date_last_year'), "%Y-%m-%d", ).date() settings.arskrav_initiation_date = datetime.strptime( request.POST.get('arskrav_initiation_date'), "%Y-%m-%d", ).date() settings.arskrav_actual_date = datetime.strptime( request.POST.get('arskrav_actual_date'), "%Y-%m-%d", ).date() settings.arskrav_public_date = datetime.strptime( request.POST.get('arskrav_public_date'), "%Y-%m-%d", ).date() except ValueError: messages.error(request, 'invalid_date_format') settings.save() Settings.clear_cache() messages.success(request, 'enrollment_status_saved') return redirect('admin:enrollment.status') else: raise PermissionDenied
def show_defaults(self): settings = list(Settings.select()) vw = max([len(setting.value) for setting in settings]) kw = max([len(setting.key) for setting in settings]) sc_head = 'Setting'.ljust(kw) vc_head = 'Value'.ljust(vw) output = '\n%s\t%s' % (sc_head, vc_head) output += '\n%s\n' % ('-' * len(output)) for s in settings: output += '%s\t%s\n' % (s.key.ljust(kw), s.value.ljust(vw)) print output sys.exit(0)
def payment_method(request): enrollment = get_or_create_enrollment(request) if enrollment.state == 'payment': # Payment has been initiated but the user goes back here - why? # Reset the state and let them reinitiate payment when they're ready. enrollment.state = 'registration' enrollment.save() elif enrollment.state == 'complete': # A previous registration has been completed, so why would the user come directly here? # Just redirect them back to registration which will restart a new registration. return redirect("enrollment:registration") enrolling_through_aktivitet = 'innmelding.aktivitet' in request.session invoice_available = Settings.get_cached().enrollment_accept_invoice and not enrolling_through_aktivitet context = { 'settings': Settings.get_cached(), 'enrolling_through_aktivitet': enrolling_through_aktivitet, 'invoice_available': invoice_available, } context.update(current_template_layout(request)) return render(request, 'central/enrollment/payment.html', context)
def process_request(self, request): from core.models import Settings settings = Settings.get_cached() # The enrollment slug is duplicated and hardcoded here :( # However, it's not really likely to change often since it's an important URL. if request.path.startswith('/innmelding') and not settings.enrollment_is_active: context = current_template_layout(request) return render(request, 'central/enrollment/unavailable.html', context) # Another issue: If passing through DNT Connect, and card payment is deactivated, # there is no means for payment available. Inform them immediately if request.path.startswith('/innmelding') and 'dntconnect' in request.session \ and not settings.enrollment_accept_card: return render(request, 'central/connect/signon_enrollment_card_deactivated.html')
def get_invoice(self): """Returns the current invoice for this member. Raises DoesNotExist or MultipleObjectReturned if there isn't exactly one invoice - which is likely, and will need to be handled by callers. See the docstring on `focus.models.InvoiceHead` for what those cases mean.""" # We need to select invoices created after the initiation date for the *last membership # year*, because that was the date for which new memberships apply for the following year as # well. from core.models import Settings from core.util import membership_year_start if date.today() >= membership_year_start()['actual_date']: # New membership year has started! Use this year's membership date last_membership_year = date.today().year else: # New membership year not started yet, use last year's membership date last_membership_year = date.today().year - 1 return self.invoices.get(invoice_date__gte=Settings.get_cached().arskrav_initiation_date_last_year)
def membership_year_start(): """ Returns the date set for the membership year start. If the dates haven't been updated for this year then last year's dates are re-used. See relevant fields in `core.models.Settings`. """ from core.models import Settings this_year = date.today().year settings = Settings.get_cached() return { "initiation_date": date( year=this_year, month=settings.arskrav_initiation_date.month, day=settings.arskrav_initiation_date.day ), "actual_date": date( year=this_year, month=settings.arskrav_actual_date.month, day=settings.arskrav_actual_date.day ), "public_date": date( year=this_year, month=settings.arskrav_public_date.month, day=settings.arskrav_public_date.day ), }
def change_setting(self, settings): for s in settings: try: key, value = s.split('=') except ValueError: msg = '%s is not in the form of key=value.' % s[0] self.log.critical(msg) sys.exit(msg) else: try: so = list(Settings.select(Settings.q.key==key))[0] except IndexError: msg = "%s is not a valid key" % key self.log.critical(msg) sys.exit(msg) else: so.value = value msg = 'Changed key %s to %s' % (so.key, so.value) self.log.info(msg) print msg sys.exit(0)
def benefits(request, forening_id): if forening_id is None: # No forening-attachment provided, use default prices; those connected to the DNT central group forening = None forening_id = Forening.DNT_CENTRAL_ID forening = cache.get('forening.%s' % forening_id) if forening is None: forening = Forening.objects.get(id=forening_id) cache.set('forening.%s' % forening_id, forening, 60 * 60 * 24 * 7) try: price = forening.get_focus_price() except Price.DoesNotExist: # User either tampered with the forening id request parameter, or the requested forening actually misses prices # in Focus, in which case a warning has been logged. Either way, send the user to the generic benefits page. return redirect('membership:benefits') context = { 'forening': forening, 'price': price, 'enrollment_active': Settings.get_cached().enrollment_is_active, } return render(request, 'central/membership/benefits.html', context)
def edit(request, user_id): try: other_user = User.objects.filter(id=user_id).get() except User.DoesNotExist: messages.warning(request, 'no_such_user') return redirect('admin:users.index') if not other_user.is_member(): # Non-members if request.method == 'GET': initial = { 'name': other_user.get_full_name(), 'email': other_user.get_email(), 'phone_mobile': other_user.get_phone_mobile(), } if other_user.get_birth_date() is None: initial['birth_date'] = None else: initial['birth_date'] = ( other_user.get_birth_date().strftime('%d.%m.%Y')) form = NonmemberPersonalDetailsForm(initial=initial) elif request.method == 'POST': form = NonmemberPersonalDetailsForm(request.POST) if form.is_valid(): other_user.set_contact_info({ 'email': form.cleaned_data['email'], 'phone_mobile': form.cleaned_data['phone_mobile'], }) other_user.first_name, other_user.last_name = ( form.cleaned_data['name'].rsplit(maxsplit=1)) other_user.birth_date = form.cleaned_data['birth_date'] other_user.save() other_user.clear_cache() return redirect('admin:users.show', other_user.id) else: return redirect('admin:users.show', other_user.id) context = { 'form': form, 'other_user': other_user, } return render(request, 'central/admin/users/show/edit_nonmember.html', context) else: # Members if request.method == 'GET': form = MemberContactInfoForm(initial={ 'email': other_user.get_email(), 'phone_mobile': other_user.get_phone_mobile(), }) elif request.method == 'POST': if not Settings.get_cached().focus_writes: return redirect('admin:users.edit', user_id) form = MemberContactInfoForm(request.POST) if form.is_valid(): other_user.set_contact_info({ 'email': form.cleaned_data['email'], 'phone_mobile': form.cleaned_data['phone_mobile'], }) return redirect('admin:users.show', other_user.id) else: return redirect('admin:users.show', other_user.id) context = { 'form': form, 'other_user': other_user, } return render(request, 'central/admin/users/show/edit_member.html', context)
def wrapped(self, *args, **kwargs): if not Settings.get_cached().focus_writes: return redirect('user:focus_writes_disabled') return method(self, *args, **kwargs)
def sherpa_settings(request): return {'sherpa_settings': Settings.get_cached()}
def update_account(request): if not request.user.is_member(): if request.method == 'GET': context = { 'user_password_length': settings.USER_PASSWORD_LENGTH } return render(request, 'common/user/account/update_account_nonmember.html', context) elif request.method == 'POST': if not Settings.get_cached().focus_writes: return redirect('user:account') errors = False if not validator.email(request.POST['email']): messages.error(request, 'invalid_email_address') errors = True if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST and not validator.email(request.POST['sherpa-email'], req=False): messages.error(request, 'invalid_sherpa_email_address') errors = True if User.objects.filter(identifier=request.POST['email']).exclude(id=request.user.id).exists(): messages.error(request, 'duplicate_email_address') errors = True if errors: return redirect('user:update_account') if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST: user = request.user user.sherpa_email = request.POST['sherpa-email'] user.save() if 'phone_mobile' in request.POST: request.user.phone_mobile = request.POST['phone_mobile'] if all([key in request.POST for key in ['b_day', 'b_month', 'b_year']]): try: request.user.birth_date = datetime.strptime( "%s-%s-%s" % (request.POST['b_year'], request.POST['b_month'], request.POST['b_day']), "%Y-%m-%d", ).date() except ValueError: request.user.birth_date = None request.user.identifier = request.POST['email'] request.user.email = request.POST['email'] request.user.save() messages.info(request, 'update_success') return redirect('user:account') else: if request.method == 'GET': context = { 'address_field_max_length': ADDRESS_FIELD_MAX_LENGTH, 'settings': Settings.get_cached(), } return render(request, 'common/user/account/update_account.html', context) elif request.method == 'POST': errors = False if not validator.email(request.POST['email']): messages.error(request, 'invalid_email_address') errors = True if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST and not validator.email(request.POST['sherpa-email'], req=False): messages.error(request, 'invalid_sherpa_email_address') errors = True if not validator.phone(request.POST['phone_home'], req=False): messages.error(request, 'invalid_phone_home') errors = True if not validator.phone(request.POST['phone_mobile'], req=False): messages.error(request, 'invalid_phone_mobile') errors = True if request.user.address.country.code == 'NO' and not request.user.is_related_member(): if not validator.address(request.POST['address']): messages.error(request, 'invalid_address') errors = True if len(request.POST['address']) >= ADDRESS_FIELD_MAX_LENGTH: messages.error(request, 'too_long_address') errors = True try: zipcode = Zipcode.get_by_zipcode(zipcode=request.POST['zipcode']) except Zipcode.DoesNotExist: messages.error(request, 'invalid_zipcode') errors = True if errors: return redirect('user:update_account') if request.user.has_perm('sherpa') and 'sherpa-email' in request.POST: user = request.user user.sherpa_email = request.POST['sherpa-email'] user.save() attributes = { 'email': request.POST['email'], 'phone_home': request.POST['phone_home'], 'phone_mobile': request.POST['phone_mobile'] } address_attributes = None if request.user.address.country.code == 'NO' and not request.user.is_related_member(): address_attributes = {} address_attributes['a1'] = request.POST['address'] if 'address2' in request.POST: address_attributes['a2'] = request.POST['address2'] if 'address3' in request.POST: address_attributes['a3'] = request.POST['address3'] address_attributes['zipcode_id'] = zipcode.zipcode address_attributes['area'] = zipcode.area request.user.set_contact_info(attributes, address_attributes, update_changedby=True) messages.info(request, 'update_success') return redirect('user:account')
def process_card(request): if 'enrollment' not in request.session: return redirect('enrollment:registration') enrollment = get_or_create_enrollment(request) if enrollment.state == 'registration': # Whoops, how did we get here without going through payment first? Redirect back. # Note, *this* makes it impossible to use a previously verified transaction id # on a *second* registration by skipping the payment view and going straight to this check. return redirect('enrollment:payment_method') elif enrollment.state == 'payment': # Cool, this is where we want to be. pass elif enrollment.state == 'complete': # Registration has already been completed, redirect forwards to results page return redirect('enrollment:result') # The client's transaction id CAN differ from the one we think is active. Let them override it, # given that the transaction id is already registered. Note that the transaction id from the # GET parameter is obviously untrusted input. try: enrollment.transactions.update(active=False) active_transaction = enrollment.transactions.get(transaction_id=request.GET['transactionId']) active_transaction.active = True active_transaction.save() except Transaction.DoesNotExist: # They returned with a transaction id which we haven't registered on them - cannot see this happen # without them tampering with the GET parameter, we'll have to send them back with an error message. messages.error(request, 'invalid_transaction_id') enrollment.state = 'payment' enrollment.save() return redirect('enrollment:payment_method') if request.GET.get('responseCode') == 'OK': try: librato.increment('sherpa.requests.nets.process') r = requests.get(settings.NETS_PROCESS_URL, params={ 'merchantId': settings.NETS_MERCHANT_ID, 'token': settings.NETS_TOKEN, 'operation': 'SALE', 'transactionId': active_transaction.transaction_id }) response = r.text.encode('utf-8') dom = ET.fromstring(response) response_code = dom.find(".//ResponseCode") response_text = dom.find(".//ResponseText") payment_verified = False tx_already_processed_explicit = response_code.text == '98' tx_already_processed_general = ( response_code.text == '99' and response_text is not None and response_text.text == 'Transaction already processed' ) if response_code is None: # Crap, we didn't get the expected response from Nets. # This has happened a few times before. We'll have to handle it ourselves. logger.error( "Mangler 'ResponseCode' element fra Nets", extra={ 'request': request, 'nets_response': response, 'enrollment': enrollment, 'transaction_id': active_transaction.transaction_id } ) enrollment.state = 'payment' enrollment.save() context = current_template_layout(request) context['settings'] = Settings.get_cached() return render(request, 'central/enrollment/payment-process-error.html', context) elif tx_already_processed_explicit or tx_already_processed_general: # The transaction might have already been processed if the user resends the process_card # request - recheck nets with a Query request and verify those details sale_response = response librato.increment('sherpa.requests.nets.query') r = requests.get(settings.NETS_QUERY_URL, params={ 'merchantId': settings.NETS_MERCHANT_ID, 'token': settings.NETS_TOKEN, 'transactionId': active_transaction.transaction_id }) response = r.text.encode('utf-8') dom = ET.fromstring(response) order_amount = int(dom.find(".//OrderInformation/Amount").text) captured_amount = int(dom.find(".//Summary/AmountCaptured").text) credited_amount = int(dom.find(".//Summary/AmountCredited").text) if order_amount == (captured_amount - credited_amount) == enrollment.total_price() * 100: payment_verified = True else: logger.warning( "Nets: Prosessert transaksjon matcher ikke forventet beløp", extra={ 'request': request, 'enrollment': enrollment, 'nets_sale_response': sale_response, 'nets_query_response': response, 'transaction_id': active_transaction.transaction_id, 'payment_verified': payment_verified, 'order_amount': order_amount, 'captured_amount': captured_amount, 'credited_amount': credited_amount, 'total_price_100': enrollment.total_price() * 100 } ) elif response_code.text == 'OK': payment_verified = True if payment_verified: # Mark the transaction as successful active_transaction.state = 'success' active_transaction.save() # Register the payment in focus for user in enrollment.users.all(): focus_user = FocusEnrollment.objects.get(memberid=user.memberid) focus_user.paid = True focus_user.save() user.pending_user = User.create_pending_user(user.memberid) user.save() librato.increment('sherpa.medlemmer.innmeldinger') if enrollment.relation_type == 'family': librato.increment('sherpa.familiemedlemskap.innmelding.kort_betalt') prepare_and_send_email(request, enrollment) enrollment.save_prices() enrollment.state = 'complete' enrollment.result = 'success_card' enrollment.save() else: active_transaction.state = 'fail' active_transaction.save() enrollment.state = 'registration' enrollment.result = 'fail' enrollment.save() except requests.ConnectionError: logger.warning( "Nets `process` feil", exc_info=sys.exc_info(), extra={'request': request} ) enrollment.state = 'payment' enrollment.save() context = current_template_layout(request) context['settings'] = Settings.get_cached() return render(request, 'central/enrollment/payment-process-error.html', context) else: active_transaction.state = 'cancel' active_transaction.save() enrollment.state = 'registration' enrollment.result = 'cancel' enrollment.save() return redirect('enrollment:result')
def verification(request): enrollment = get_or_create_enrollment(request) if enrollment.state == 'payment': # Payment has been initiated but the user goes back here - why? # Reset the state and let them reinitiate payment when they're ready. enrollment.state = 'registration' enrollment.save() elif enrollment.state == 'complete': # A previous registration has been completed, so why would the user come directly here? # Just redirect them back to registration which will restart a new registration. return redirect("enrollment:registration") # If existing member is specified, save details and change to that address existing_name = '' if enrollment.existing_memberid != '': user = User.get_or_create_inactive(memberid=enrollment.existing_memberid) existing_name = user.get_full_name() enrollment.country = user.address.country.code if user.address.country.code == 'NO': enrollment.address1 = user.address.field1 elif user.address.country.code in ['DK', 'SE']: # Don't change the user-provided address. # The user might potentially provide a different address than the existing member, which isn't allowed, # but this is preferable to trying to parse the existing address into zipcode, area etc. In order to # enforce the same address, the address logic for DK and SE in enrollment.User.save_to_focus would have to # be rewritten. pass else: # Uppercase the country code as Focus doesn't use consistent casing enrollment.country = user.address.country.code enrollment.address1 = user.address.field1 enrollment.address2 = user.address.field2 enrollment.address3 = user.address.field3 # Get the area name for this zipcode if enrollment.country == 'NO': enrollment.area = Zipcode.get_by_zipcode(zipcode=enrollment.zipcode).area # Figure out which forening this member/these members will belong to if enrollment.existing_memberid != '': # Use main members' forening if applicable existing_user = User.get_or_create_inactive(memberid=enrollment.existing_memberid) forening = existing_user.main_forening(convert_dnt_oslo_for_youth=False) else: if enrollment.country == 'NO': focus_forening_id = cache.get('focus.zipcode_forening.%s' % enrollment.zipcode) if focus_forening_id is None: focus_forening_id = FocusZipcode.objects.get(zipcode=enrollment.zipcode).main_forening_id cache.set('focus.zipcode_forening.%s' % enrollment.zipcode, focus_forening_id, 60 * 60 * 24 * 7) forening = cache.get('forening.focus.%s' % focus_forening_id) if forening is None: forening = Forening.objects.get(focus_id=focus_forening_id) cache.set('forening.focus.%s' % focus_forening_id, forening, 60 * 60 * 24 * 7) else: # Foreign members are registered with DNT Oslo og Omegn forening = cache.get('forening.%s' % Forening.DNT_OSLO_ID) if forening is None: forening = Forening.objects.get(id=Forening.DNT_OSLO_ID) cache.set('forening.%s' % Forening.DNT_OSLO_ID, forening, 60 * 60 * 24 * 7) enrollment.forening = forening enrollment.save() context = { 'enrollment': enrollment, 'existing_name': existing_name, 'age_senior': settings.MEMBERSHIP['AGES']['SENIOR'], 'age_main': settings.MEMBERSHIP['AGES']['MAIN'], 'age_youth': settings.MEMBERSHIP['AGES']['YOUTH'], 'age_school': settings.MEMBERSHIP['AGES']['SCHOOL'], 'membership_type_names': { 'family_primary': get_membership_type_by_codename('family_primary')['name'], 'main': get_membership_type_by_codename('main')['name'], 'youth': get_membership_type_by_codename('youth')['name'], 'senior': get_membership_type_by_codename('senior')['name'], 'child': get_membership_type_by_codename('child')['name'], 'school': get_membership_type_by_codename('school')['name'], 'household': get_membership_type_by_codename('household')['name'], 'family_household': get_membership_type_by_codename('family_household')['name'], }, 'foreign_shipment_price': FOREIGN_SHIPMENT_PRICE, 'settings': Settings.get_cached(), } context.update(current_template_layout(request)) return render(request, 'central/enrollment/verification.html', context)
def household(request): enrollment = get_or_create_enrollment(request) if enrollment.state == 'payment': # Payment has been initiated but the user goes back here - why? # Reset the state and let them reinitiate payment when they're ready. enrollment.state = 'registration' enrollment.save() elif enrollment.state == 'complete': # A previous registration has been completed, so why would the user come directly here? # Just redirect them back to registration which will restart a new registration. return redirect("enrollment:registration") errors = invalid_location in request.GET if request.method == 'POST': enrollment.country = request.POST['country'] enrollment.address1 = polite_title(request.POST['address1']) enrollment.address2 = polite_title(request.POST['address2']) enrollment.address3 = polite_title(request.POST['address3']) enrollment.zipcode = request.POST['zipcode'] enrollment.area = request.POST.get('area', '') enrollment.existing_memberid = request.POST.get('existing', '')[:50] enrollment.wants_yearbook = enrollment.country != 'NO' and 'yearbook' in request.POST enrollment.attempted_yearbook = False if enrollment.wants_yearbook: if enrollment.existing_memberid != '' or not enrollment.has_potential_main_member(): enrollment.wants_yearbook = False enrollment.attempted_yearbook = True enrollment.save() if enrollment.validate_location(): if enrollment.country != 'NO': return redirect('enrollment:verification') else: try: focus_zipcode = FocusZipcode.objects.get(zipcode=enrollment.zipcode) Forening.objects.get(focus_id=focus_zipcode.main_forening_id) # Verify that the Forening exists return redirect('enrollment:verification') except FocusZipcode.DoesNotExist: # We know that this zipcode exists in Zipcode, because validate_location validated, and it checks # for that logger.warning( "Postnummer finnes i Zipcode, men ikke i Focus!", exc_info=sys.exc_info(), extra={ 'request': request, 'postnummer': enrollment.zipcode } ) messages.error(request, 'focus_zipcode_missing') except Forening.DoesNotExist: logger.warning( "Focus-postnummer mangler foreningstilknytning!", exc_info=sys.exc_info(), extra={'request': request} ) messages.error(request, 'focus_zipcode_missing') else: errors = True context = { 'enrollment': enrollment, 'invalid_existing': invalid_existing in request.GET, 'countries': FocusCountry.get_sorted(), 'foreign_shipment_price': FOREIGN_SHIPMENT_PRICE, 'errors': errors, 'settings': Settings.get_cached(), } context.update(current_template_layout(request)) return render(request, 'central/enrollment/household.html', context)
def get_settings(): return Settings.load()
def payment(request): enrollment = get_or_create_enrollment(request) if enrollment.state == 'registration': # All right, enter payment state enrollment.state = 'payment' enrollment.save() elif enrollment.state == 'payment': # Already in payment state, redirect them forwards to processing if enrollment.payment_method == 'invoice': return redirect('enrollment:process_invoice') elif enrollment.payment_method == 'card': # Let's check for an existing transaction first try: active_transaction = enrollment.transactions.get(state='register', active=True) # Yeah, it's there. Skip payment and redirect forwards to processing return redirect("%s?merchantId=%s&transactionId=%s" % ( settings.NETS_TERMINAL_URL, settings.NETS_MERCHANT_ID, active_transaction.transaction_id )) except Transaction.DoesNotExist: # No active transactions - maybe a problem occured during payment. # Assume payment failed and just redo it - if something failed, we'll know # through logs and hopefully discover any double-payments pass elif enrollment.state == 'complete': # Registration has already been completed, redirect forwards to results page return redirect('enrollment:result') enrollment.payment_method = request.POST.get('payment_method', '') # Validate chosen payment method if enrollment.payment_method not in ['card', 'invoice']: messages.error(request, 'invalid_payment_method') return redirect('enrollment:payment_method') # Ensure card payment is accepted if chosen if enrollment.payment_method == 'card' and not Settings.get_cached().enrollment_accept_card: messages.error(request, 'invalid_payment_method') return redirect('enrollment:payment_method') # Ensure invoice is accepted if chosen if enrollment.payment_method == 'invoice' and not Settings.get_cached().enrollment_accept_invoice: messages.error(request, 'invalid_payment_method') return redirect('enrollment:payment_method') # Ensure user is not enrolling through aktivitet if invoice is chosen if enrollment.payment_method == 'invoice' and 'innmelding.aktivitet' in request.session: messages.error(request, 'invalid_payment_method') return redirect('enrollment:payment_method') # Ok, we're good to go. Save all users to Focus enrollment.save() enrollment.save_users_to_focus() # If we're paying by invoice, skip ahead to invoice processing if enrollment.payment_method == 'invoice': return redirect('enrollment:process_invoice') # Paying with card, move on. order_number = Transaction.generate_order_number() # Choose a user as the Nets customer; preferably the main member try: nets_customer = enrollment.get_chosen_main_member() except EnrollmentUser.DoesNotExist: # There's no main member, so they're either all children or related to an existing member. We still need a # 'main' user though, for the customer data. Try to find the oldest one that *has* contact information. nets_customer = enrollment.users.exclude(email='').order_by('dob')[0] first_name, last_name = nets_customer.name.rsplit(maxsplit=1) description = render_to_string('central/enrollment/payment-terminal.html', request=request) # Send the transaction registration to Nets try: librato.increment('sherpa.requests.nets.register') r = requests.get(settings.NETS_REGISTER_URL, params={ 'merchantId': settings.NETS_MERCHANT_ID, 'token': settings.NETS_TOKEN, 'orderNumber': order_number, 'customerFirstName': first_name, 'customerLastName': last_name, 'customerEmail': nets_customer.email, 'currencyCode': 'NOK', 'amount': enrollment.total_price() * 100, 'orderDescription': description, 'redirectUrl': "http://%s%s" % (request.site.domain, reverse("enrollment:process_card")) }) # Sweet, almost done, now just send the user to complete the transaction # Consider handling errors here (unexpected XML response or connection error) # We recieved a random "Unable to create setup string" message once, ignoring it for now response = r.text.encode('utf-8') enrollment.transactions.update(active=False) transaction = Transaction( enrollment=enrollment, transaction_id=ET.fromstring(response).find("TransactionId").text, order_number=order_number, state='register', active=True, ) transaction.save() except Exception as e: # Handle any exception that might occur (requests.ConnectionError, invalid response from Nets, etc.) logger.warning( "Nets `register` feil", exc_info=sys.exc_info(), extra={'request': request} ) messages.error(request, 'nets_register_connection_error') return redirect('enrollment:payment_method') return redirect("%s?merchantId=%s&transactionId=%s" % ( settings.NETS_TERMINAL_URL, settings.NETS_MERCHANT_ID, transaction.transaction_id ))
def norway_bus_tickets_offer_has_expired(self): from core.models import Settings from core.util import membership_year_start last_year = date.today().year - 1 return self.get_membership_start_date() < Settings.get_cached().arskrav_initiation_date_last_year
def registration(request, user): enrollment = get_or_create_enrollment(request) if enrollment.state == 'payment': # Payment has been initiated but the user goes back to the registration page - why? # Maybe it failed, and they want to retry registration? # Reset the state and let them reinitiate payment when they're ready. enrollment.state = 'registration' enrollment.save() elif enrollment.state == 'complete': # A previous registration has been completed, but a new one has been initiated. # Remove the old one and start over. del request.session['enrollment'] enrollment = get_or_create_enrollment(request) if request.method == 'GET': if user is not None: try: user = enrollment.users.all().get(id=user) except EnrollmentUser.DoesNotExist: return redirect('enrollment:registration') # Display the registration form for the first registration, and when editing a user; hide otherwise show_registration_form = len(enrollment.users.all()) == 0 or user is not None context = { 'enrollment': enrollment, 'current_user': user, 'show_registration_form': show_registration_form, 'confirmation_age_min': min(settings.MEMBERSHIP['FAMILY']['YOUTH_CONFIRMATION_AGE_RANGE']), 'confirmation_age_max': max(settings.MEMBERSHIP['FAMILY']['YOUTH_CONFIRMATION_AGE_RANGE']), 'phone_required': json.dumps(len(enrollment.users.all()) == 0), 'email_required': json.dumps(True), 'settings': Settings.get_cached(), } context.update(current_template_layout(request)) return render(request, 'central/enrollment/registration.html', context) elif request.method == 'POST': # We want to check provided user details if: # - The user has explicitly clicked the save button # - They're not editing a user, but added a new member and clicked continue # - They're editing an existing user and clicked continue just_save = request.POST['button'] == 'save' continue_ = request.POST['button'] == 'continue' editing_user = '******' in request.POST name_defined = len(request.POST['name'].strip()) > 0 save_and_continue = continue_ and (name_defined or editing_user) # Save terms & conditions accepted enrollment.accepts_conditions = request.POST.get('conditions') == 'on' enrollment.save() # Save partneroffers optin enrollment.partneroffers_optin = 'partneroffers_optin' in request.POST enrollment.save() if just_save or save_and_continue: if editing_user: try: user = enrollment.users.all().get(id=request.POST['user']) except EnrollmentUser.DoesNotExist: # They're trying to save a non-existing user - maybe they deleted it in another tab? Just create a # new user user = EnrollmentUser(enrollment=enrollment) else: user = EnrollmentUser(enrollment=enrollment) # Titleize name and strip whitespace before/after dash user.name = re.sub('\s*-\s*', '-', polite_title(request.POST['name'].strip())) user.phone = request.POST['phone'].strip() user.email = request.POST['email'].lower().strip() user.gender = request.POST.get('gender', '') try: user.dob = datetime.strptime(request.POST['dob'], "%d.%m.%Y").date() except ValueError: user.dob = None user.save() if not user.is_valid(): messages.error(request, 'user_invalid') return redirect('enrollment:registration', user.id) elif user.requires_family_membership_confirmation() and not user.has_confirmation_info(): messages.error(request, 'user_requires_confirmation_info') return redirect('enrollment:registration', user.id) else: enrollment.users.add(user) # The user was saved successfully, so clear the form for the next user user = None if continue_: return redirect("enrollment:household") else: return redirect('enrollment:registration') else: raise PermissionDenied