Exemplo n.º 1
0
    def form_valid(self, form):
        form.save()
        action = form.cleaned_data

        if action == 'cancel_selected':
            # django forms don't support "getlist"
            job_ids = self.request.POST.getlist('_selected_action')
            for job_id in job_ids:
                cancel_job(job_id, self.connection)

            # this has the side effect of flushing the canceled jobs,
            # otherwise on redirect you may get an empty list..
            form.queue.get_jobs(0, len(job_ids))
        elif action == 'requeue_selected':
            job_ids = self.request.POST.getlist('_selected_action')
            for job_id in job_ids:
                requeue_job(job_id, self.connection)
            form.queue.get_jobs(0, len(job_ids))

        msgs = {
            'compact': __('Queue compacted'),
            'empty': __('Queue emptied'),
            'requeue': __('Jobs requeued'),
            'cancel_selected': __('Selected jobs canceled'),
            'requeue_selected': __('Selected jobs requeued'),
        }
        messages.success(self.request, msgs[action])
        return super(QueueDetails, self).form_valid(form)
Exemplo n.º 2
0
def validate_registration(request):
    """validate registration data"""
    # step1 - email and password and captcha
    if email_errors(request):
        return email_errors(request, return_values = 3)

    # Password is generated by us

    # Captcha
    if not (settings.DEBUG and request.POST.get("ignorecaptcha", False)):
        if not captcha_valid(request, "register"):
            return (__('Captcha'), '1', __('Captcha challenge failed'))
        invalidate_captcha(request, "register")

    # step2 - languages
    if language_errors(request):
        return language_errors(request, return_values = 3)

    # step3 - location
    if location_errors(request):
        return location_errors(request, return_values = 3)

    # step4 - about me
    if contactinfo_errors(request):
        return contactinfo_errors(request, return_values = 3)
    if aboutme_errors(request):
        return aboutme_errors(request, return_values = 3)

    return (None, None, None)
Exemplo n.º 3
0
def contact_admin(request):
    # check if form was posted
    if request.method == 'POST':

        # create a form instance and populate it with data from request:
        form = ContactForm(request.POST)

        # check whether user data is valid:
        if form.is_valid():
            # send email
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            from_email = form.cleaned_data['from_email']

            try:
                send_mail(subject,message,from_email, [ADMIN_EMAIL])
            except Exception:
                message = __(u"While sending this letter unexpected error occured." \
                          u"Please try again later.")
                logger = logging.getLogger(__name__)
                logger.exception(message)
                messages.warning(request,message)
            else:
                message = __(u"Message has been sent successfully!")
                messages.success(request,message)

            # redirect to same contact page with  message
            return HttpResponseRedirect(reverse('contact_admin'))

        # if there was not POST render blank form
    else:
        form = ContactForm()
    return render(request, 'contact_admin/form.html', {'form': form})
Exemplo n.º 4
0
def add_doctor(request, form_class=AddDoctorForm, template="add_doctor.html"):

    context = {"title": "Parceiro"}
    if request.method == "POST":
        form = form_class(request.POST)

        if form.is_valid():
            company_admin = request.user.companyadmin_set.all()[0]
            user, password = form.save(company_admin)
            form = form_class()

            vars_dict = {"first_name": user.first_name, "username": user.username, "password": password}
            html_email(
                "Cadastro no Sisquiropraxia", "add_doctor_email.html", vars_dict, "*****@*****.**", user.email
            )

            messages.success(request, __("Médico criado com sucesso!"))
            context["css_message"] = "message success"
        else:
            messages.error(request, __(u"Ocorreu um erro ao tentar salvar o perfil. Verifique os campos!"))
            context["css_message"] = "message error"
    else:
        form = form_class
    context["form"] = form
    return render_to_response(template, context, context_instance=RequestContext(request))
Exemplo n.º 5
0
	def clean(self):
		"""
		Verifiy that the values entered into the two password fields
		match. Note that an error here will end up in
		``non_field_errors()`` because it doesn't apply to a single
		field.
		
		"""
		if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
			if self.cleaned_data['password1'] != self.cleaned_data['password2']:
				raise forms.ValidationError(__(u'You must type the same password each time'))
				
		if 'username' in self.cleaned_data and 'password1' in self.cleaned_data and 'password2' in self.cleaned_data and 'email' in self.cleaned_data:
			temp_username = self.cleaned_data['username'] #'memento85'
			temp_password = self.cleaned_data['password1'] #'ont9oth1ag6foc'
			res = urlfetch.fetch('https://api.del.icio.us/v1/posts/update', 
 						 headers={'Authorization': 'Basic ' + base64.b64encode(temp_username+ ":" + temp_password)},
 						 allow_truncated=True)
			dom = parseString(res.content.partition('<!--')[0])
			nodes = dom.getElementsByTagName('update')
			if nodes.length > 0:
				self.last_updated = datetime.strptime(nodes[0].getAttribute('time'), "%Y-%m-%dT%H:%M:%SZ")
			else:
				raise forms.ValidationError(__(res.content))
		#https://memento85:[email protected]/v1/posts/update
		#https://memento85:[email protected]/v1/posts/all
		return self.cleaned_data
Exemplo n.º 6
0
Arquivo: forms.py Projeto: basa/charge
 def __init__(self, *args, **kwargs):
     """ Generate legend text automatically. """
     super(BaseForm, self).__init__(*args, **kwargs)
     legend = (__('Create {model_name}') if self.instance._state.adding
             else __('Update {model_name}'))
     model_name = self.Meta.model._meta.verbose_name
     self.Meta.layout[0].legend = legend.format(model_name=model_name)
Exemplo n.º 7
0
    def clone(self, user):
        """
        Returns a clone of the workflow. The clone will be in the DEFINITION
        state whereas the source workflow *must* be ACTIVE or RETIRED (so we
        know it *must* be valid).
        """

        # TODO: A target for refactoring so calling this method doesn't hit the
        # database so hard. Would welcome ideas..?

        if self.status >= self.ACTIVE:
            # Clone this workflow
            clone_workflow = Workflow()
            clone_workflow.name = self.name
            clone_workflow.slug = self.slug+'_clone'
            clone_workflow.description = self.description
            clone_workflow.status = self.DEFINITION
            clone_workflow.created_by = user
            clone_workflow.cloned_from = self
            clone_workflow.save()
            # Clone the states
            state_dict = dict() # key = old pk of state, val = new clone state
            for s in self.states.all():
                clone_state = State()
                clone_state.name = s.name
                clone_state.description = s.description
                clone_state.is_start_state = s.is_start_state
                clone_state.is_end_state = s.is_end_state
                clone_state.workflow = clone_workflow
                clone_state.estimation_value = s.estimation_value
                clone_state.estimation_unit = s.estimation_unit
                clone_state.save()
                for r in s.roles.all():
                    clone_state.roles.add(r)
                state_dict[s.id] = clone_state
            # Clone the transitions
            for tr in self.transitions.all():
                clone_trans = Transition()
                clone_trans.name = tr.name
                clone_trans.workflow = clone_workflow
                clone_trans.from_state = state_dict[tr.from_state.id]
                clone_trans.to_state = state_dict[tr.to_state.id]
                clone_trans.save()
                for r in tr.roles.all():
                    clone_trans.roles.add(r)
            # Clone the events
            for ev in self.events.all():
                clone_event = Event()
                clone_event.name = ev.name
                clone_event.description = ev.description
                clone_event.workflow = clone_workflow
                clone_event.state = state_dict[ev.state.id]
                clone_event.is_mandatory = ev.is_mandatory
                clone_event.save()
                for r in ev.roles.all():
                    clone_event.roles.add(r)
            return clone_workflow
        else:
            raise UnableToCloneWorkflow, __('Only active or retired workflows'\
                    ' may be cloned')
Exemplo n.º 8
0
def add_service(request, form_class=AddServiceForm, template="add_service.html"):
    if not request.user.get_profile().user_type in ['0','4','5']:
        context = {'title': 'Acesso Negado'}
        template = '403.html'
        return render_to_response(template,
                              context,
                              context_instance=RequestContext(request))
        
    context = {'title': 'Paciente', 'active_service_sidemenu': 'current'}
    if request.method == 'POST':
        form = form_class(request.POST)

        if form.is_valid():
            try:
                service = form.save()
                messages.success(request,
                    __(u'Serviço \'%s\' criado com sucesso!') % (form.cleaned_data['description'],))
                form = form_class()
                context['css_message'] = 'message success'
            except:
                messages.success(request,__('Erro ao tentar salvar serviço!'))
                form = form_class()
                context['css_message'] = 'message error'
        else:
            messages.error(request,
                __(u'Ocorreu um erro ao tentar salvar o perfil. Verifique os campos!'))
            context['css_message'] = 'message error'
    else:
        form = form_class()
    context['form'] = form
    return render_to_response(template,
                                context,
                                context_instance=RequestContext(request))
Exemplo n.º 9
0
def make_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                # Redirect to a success page.
                if request.POST['next']:
                    return HttpResponseRedirect(request.POST['next'])
                else:
                    return HttpResponseRedirect('/office')
                # return render_to_response('index.html')
            else:
                # Return a 'disabled account' error message
                messages.error(request, 
                    __(u'Conta desativada. Por favor, contacte o adminstrador'))
        else:
            # Return an 'invalid login' error message.
            messages.error(request, 
                    __(u'Usuario ou senha invalidos. Por favor, tente novamente'))
        
    form = LoginForm()
    return render_to_response('login/login.html',
                                {'form': form},
                                context_instance=RequestContext(request))
Exemplo n.º 10
0
    def vote_for(cls, user, obj, vote):
        if user.pk == obj.pk:
            raise PermissionCheckFailed(__("You can't vote for yourself"))

        if not obj.profile.can_be_voted_by(user):
            raise PermissionCheckFailed(__("You can't vote for this user"))

        super(Karma, cls).vote_for(user, obj, vote)
Exemplo n.º 11
0
 def _get_used(self):
     try:
         return self._get_used_bytes()
     except:
         if self.is_decrypted():
             return __(u"Error getting used space")
         else:
             return __("Locked")
Exemplo n.º 12
0
	def __unicode__(self):
		parts = [self.full]
		if self.is_multi:
			if self.major < 3:
				parts.append(__("MU"))
			else:
				parts.append(__("multisite"))
		return " ".join(parts)
Exemplo n.º 13
0
 def _get_avail(self):
     try:
         return self._zplist['free']
     except:
         if self.is_decrypted():
             return __("Error getting available space")
         else:
             return __("Locked")
Exemplo n.º 14
0
 def get_context_data(self, **kwargs):
     context = super(PackageDetailView, self).get_context_data(**kwargs)
     if self.object:
         context['app'] = self.object.application
     context['metadiff'] = list(unified_diff(
         self.object.application.metadata.splitlines(1),
         self.object.metadata.splitlines(1), fromfile=__("Application"),
         tofile=__("Package")))
     return context
Exemplo n.º 15
0
 def form_valid(self, form):
     queue = 'failed' if form.job.is_failed else form.job.origin
     form.save()
     msgs = {
         'requeue': __('Job requeued'),
         'cancel': __('Job canceled'),
     }
     messages.success(self.request, msgs[form.cleaned_data])
     return redirect(reverse('rq_queue', args=[queue]))
Exemplo n.º 16
0
 def form_valid(self, form):
     form.save()
     msgs = {
         'compact': __('Queue compacted'),
         'empty': __('Queue emptied'),
         'requeue': __('Jobs requeued'),
     }
     messages.success(self.request, msgs[form.cleaned_data])
     return super(QueueDetails, self).form_valid(form)
Exemplo n.º 17
0
 def email_message(self):
     """ compose complete email message text """
     site = Site.objects.get(pk=settings.SITE_ID)
     action_url = self.get_action()
     if action_url != '' and not action_url.startswith('http'):
         action_url = "%s://%s%s" % (getattr(settings, 'PROTOCOL', 'http'), site.domain, action_url)
     hello_text = __("""Hi %s,""" % self.to_user.get_full_name())
     action_text = __("""\n\nMore details here: %s""") % action_url if action_url != "" else ""
     explain_text = __("""This is an automatic notification sent from from %s.\nIf you want to stop receiving this notification edit your email notification settings here: %s""") % (site.name, 'TODO')
     
     return "%s\n\n%s%s\n\n%s" % (hello_text, self.text, action_text, explain_text)
Exemplo n.º 18
0
    def email_message(self):
        """ compose complete email message text """
        url = settings.SITE_URL
        hello_text = __("Hi %s," % self.to_user.get_full_name())
        action_text = __("\n\nMore details here: %s") % url
        explain_text = __(
            "This is an automatic notification sent from from %s.\n"
            "If you want to stop receiving this notification edit your"
            "email notification settings here: %s") % (settings.SITE_NAME, 'TODO')

        return "%s\n\n%s%s\n\n%s" % (hello_text, self.text, action_text, explain_text)
Exemplo n.º 19
0
 def _get_avail(self):
     try:
         if self.mp_volume.vol_fstype == "ZFS":
             return self._zplist["free"]
         else:
             return self._vfs.f_bavail * self._vfs.f_frsize
     except:
         if self.mp_volume.is_decrypted():
             return __(u"Error getting available space")
         else:
             return __("Locked")
Exemplo n.º 20
0
 def _get_avail(self):
     try:
         if self.vol_fstype == 'ZFS':
             return self._zplist['free']
         else:
             return self._vfs.f_bavail * self._vfs.f_frsize
     except:
         if self.is_decrypted():
             return __(u"Error getting available space")
         else:
             return __("Locked")
Exemplo n.º 21
0
    def switch_is_active(self, moderator):
        """Block or unblock user if the moderator have proper permissions"""
        if self.user.pk == moderator.pk:
            raise PermissionCheckFailed(__("You can't use this action "
                                           "on yourself."))
        if not self.can_be_moderated_by(moderator):
            raise PermissionCheckFailed(__("Sorry, you have no permissions "
                                           "to edit this profile."))

        self.user.is_active = not self.user.is_active
        self.user.save()
Exemplo n.º 22
0
 def email_message(self):
     """ compose complete email message text """
     site = Site.objects.get(pk=settings.SITE_ID)
     url = "%s://%s/" % (getattr(settings, 'PROTOCOL', 'http'), site.domain)
     hello_text = __("Hi %s," % self.to_user.get_full_name())
     action_text = __("\n\nMore details here: %s") % url
     explain_text = __(
         "This is an automatic notification sent from from %s.\n"
         "If you want to stop receiving this notification edit your"
         "email notification settings here: %s") % (site.name, 'TODO')
     
     return "%s\n\n%s%s\n\n%s" % (hello_text, self.text, action_text, explain_text)
Exemplo n.º 23
0
    def payment_prepare(self, request, payment_obj):
        self.init_api()

        if request.event.settings.payment_paypal_connect_user_id:
            userinfo = Tokeninfo.create_with_refresh_token(request.event.settings.payment_paypal_connect_refresh_token).userinfo()
            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'intent': 'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url": build_absolute_uri(request.event, 'plugins:paypal:return'),
                "cancel_url": build_absolute_uri(request.event, 'plugins:paypal:abort'),
            },
            "transactions": [
                {
                    "item_list": {
                        "items": [
                            {
                                "name": __('Order {slug}-{code}').format(slug=self.event.slug.upper(),
                                                                         code=payment_obj.order.code),
                                "quantity": 1,
                                "price": self.format_price(payment_obj.amount),
                                "currency": payment_obj.order.event.currency
                            }
                        ]
                    },
                    "amount": {
                        "currency": request.event.currency,
                        "total": self.format_price(payment_obj.amount)
                    },
                    "description": __('Order {order} for {event}').format(
                        event=request.event.name,
                        order=payment_obj.order.code
                    ),
                    "payee": payee
                }
            ]
        })
        request.session['payment_paypal_order'] = payment_obj.order.pk
        request.session['payment_paypal_payment'] = payment_obj.pk
        return self._create_payment(request, payment)
Exemplo n.º 24
0
    def vote_for(cls, user, obj, vote):
        if user.pk == obj.author.pk:
            raise PermissionCheckFailed(__("You can't vote for your own post"))

        if obj.blog is not None:
            membership = obj.blog.check_membership(user)
        else:
            membership = None

        if obj.can_be_voted_by(user, membership):
            super(PostVote, cls).vote_for(user, obj, vote)
        else:
            raise PermissionCheckFailed(__("You can't vote for this post"))
Exemplo n.º 25
0
 def delete(self, request, *args, **kwargs):
     if self.model._meta.get_all_related_objects():            
         for related_object in self.model._meta.get_all_related_objects():
             related = related_object.model.objects
             campo   = related_object.field.get_attname().replace('_id','')
             if related.get_query_set().filter(**{campo.lower():id}):
                 messages.error(self.request,__(u"O Registro contêm outros registros que dependem dele."))
                 return False
         messages.success(self.request,__(u"Deletado com sucesso."))
         return super(DeleteVerificaMixin, self).delete(self, request, *args, **kwarg)
     else:                   
         messages.success(self.request,__(u"Deletado com sucesso."))    
         return super(DeleteVerificaMixin, self).delete(self, request, *args, **kwarg)
Exemplo n.º 26
0
def add_client(request):
    context = {}
    if request.POST:
        form = AddClientForm(request.POST)
        
        if form.is_valid():
            # Address
            address = Address()
            address.street = request.POST['street']
            address.complement = request.POST['complement']
            address.neighborhood = request.POST['neighborhood']
            address.zip = request.POST['zip']
            address.save()
            
            # Phone
            phone = Phone()
            phone.number = request.POST['phone']
            phone.save()
            
            # Car
            car = Car()
            car.model = request.POST['model']
            car.license_plate = request.POST['license_plate'].upper()
            car.year = request.POST['year']
            car.save()
            
            # Client
            client = Client()
            client.car = car
            client.name = request.POST['name']
            client.email = request.POST['email']
            client.address = address
            client.phone = phone
            client.save()
            
            messages.success(request,
                __('Cliente \'%s\' criado com sucesso.' % client.name))
            
            form = AddClientForm()
            context['class_message'] = 'green'
        else:
            context['class_message'] = 'red'
            messages.error(request,
                __(u'Ocorreu um erro ao tentar salvar o perfil. Verifique os campos!'))
    else:
        form = AddClientForm()

    context['form'] = form
    return render_to_response('order/add_client.html',
                                context,
                                context_instance=RequestContext(request))
Exemplo n.º 27
0
    def submit_deposit(self, pdf, form):
        result = {}
        if self.user is None or self.password is None:
            raise DepositError(__("No HAL user credentials provided."))

        deposit_result = DepositResult()

        try:
            # Creating the metadata
            self.log("### Generating metadata")
            metadata = self.createMetadata(form)
            print metadata
            # TODO dump XML

            # Check that there is an abstract
            #if data['metadata'].get('description','') == '':
            #    self.log('No abstract found, aborting.')
            #    raise DepositError(__('No abstract is available for this paper but '+
            #            'Zenodo requires to attach one. Please use the metadata panel to provide one.'))

            # Bundling the metadata and the PDF
            self.log("### Creating ZIP file")
            zipFile = self.create_zip(pdf, metadata)

            # Creating a new deposition
            self.log("### Creating a new deposition")
            files = {'file':('deposit.zip',zipFile,'application/zip')}
            headers = {"X-Packaging":"http://purl.org/net/sword-types/AOfr"}
            r = requests.post(self.api_url,
                    headers=headers,
                    files=files,
                    auth=(self.user,self.password))
            self.log_request(r, 201, __('Unable to create a new deposition on HAL.'))
            print r
            deposition_id = r.headers['Location']
            deposit_result.identifier = deposition_id
            self.log("Deposition id: %d" % deposition_id)

            deposit_result.splash_url = deposition_id
            deposit_result.pdf_url = deposit_result.splash_url + '/document'

        except DepositError as e:
            raise e
        except Exception as e:
            self.log("Caught exception:")
            self.log(str(type(e))+': '+str(e)+'')
            self.log(traceback.format_exc())
            raise DepositError('Connection to HAL failed. Please try again later.')

        return deposit_result
Exemplo n.º 28
0
    def checkout_prepare(self, request, cart):
        self.init_api()
        kwargs = {}
        if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
            kwargs['cart_namespace'] = request.resolver_match.kwargs['cart_namespace']

        if request.event.settings.payment_paypal_connect_user_id:
            userinfo = Tokeninfo.create_with_refresh_token(request.event.settings.payment_paypal_connect_refresh_token).userinfo()
            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'intent': 'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url": build_absolute_uri(request.event, 'plugins:paypal:return', kwargs=kwargs),
                "cancel_url": build_absolute_uri(request.event, 'plugins:paypal:abort', kwargs=kwargs),
            },
            "transactions": [
                {
                    "item_list": {
                        "items": [
                            {
                                "name": __('Order for %s') % str(request.event),
                                "quantity": 1,
                                "price": self.format_price(cart['total']),
                                "currency": request.event.currency
                            }
                        ]
                    },
                    "amount": {
                        "currency": request.event.currency,
                        "total": self.format_price(cart['total'])
                    },
                    "description": __('Event tickets for {event}').format(event=request.event.name),
                    "payee": payee
                }
            ]
        })
        request.session['payment_paypal_order'] = None
        return self._create_payment(request, payment)
Exemplo n.º 29
0
    def clean_username(self):
        data = self.cleaned_data['username']
        
        if len(data) < 4:
            raise forms.ValidationError(
                __(u'O usuario precisa ser maior que 3 caracteres')
            )

        try:
            user = User.objects.get(username=data)
        except:
            return data
        else:
            raise forms.ValidationError(__(u'Este usuario ja existe'))
Exemplo n.º 30
0
    def test_visible_email(self):
        """Test that private emails are displayed correctly"""

        moderator_with_perms = User.objects.get(username='******')
        moderator_with_perms2 = User.objects.get(
            username='******')
        moderator_without_perms = User.objects.get(
            username='******')
        user_with_perms = User.objects.get(username='******')
        user_with_perms2 = User.objects.get(username='******')
        superuser = User.objects.get(username='******')
        disabled_superuser = User.objects.get(username='******')
        disabled_superuser2 = User.objects.get(username='******')
        ordinary_user = User.objects.get(username='******')

        user = User.objects.get(username="******")
        profile = user.profile
        user2 = User.objects.get(username="******")

        self.assertEqual(profile.email_as_seen_by(moderator_with_perms), "[email protected] (%s)" % __('Only you can see the email'))
        self.assertEqual(profile.email_as_seen_by(moderator_with_perms2), "[email protected] (%s)" % __('Only you can see the email'))
        self.assertEqual(profile.email_as_seen_by(moderator_without_perms), '')
        self.assertEqual(profile.email_as_seen_by(user_with_perms), '')
        self.assertEqual(profile.email_as_seen_by(user_with_perms2), '')
        self.assertEqual(profile.email_as_seen_by(superuser), "[email protected] (%s)" % __('Only you can see the email'))
        self.assertEqual(profile.email_as_seen_by(disabled_superuser), '')
        self.assertEqual(profile.email_as_seen_by(disabled_superuser2), '')
        self.assertEqual(profile.email_as_seen_by(ordinary_user), '')
        self.assertEqual(profile.email_as_seen_by(user), "[email protected] (%s)" % __('Only you can see the email'))
        self.assertEqual(profile.email_as_seen_by(user2), "[email protected] (%s)" % __('Only you can see the email'))

        user.profile.email_is_public = True
        user.profile.save()

        user = User.objects.get(username="******")
        profile = user.profile
        user2 = User.objects.get(username="******")

        self.assertEqual(profile.email_as_seen_by(moderator_with_perms), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(moderator_with_perms2), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(moderator_without_perms), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(user_with_perms), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(user_with_perms2), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(superuser), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(disabled_superuser), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(disabled_superuser2), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(ordinary_user), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(user), "*****@*****.**")
        self.assertEqual(profile.email_as_seen_by(user2), "*****@*****.**")
Exemplo n.º 31
0
    def checkout_prepare(self, request, cart):
        self.init_api()
        kwargs = {}
        if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
            kwargs['cart_namespace'] = request.resolver_match.kwargs[
                'cart_namespace']

        if request.event.settings.payment_paypal_connect_user_id:
            try:
                userinfo = Tokeninfo.create_with_refresh_token(
                    request.event.settings.payment_paypal_connect_refresh_token
                ).userinfo()
            except BadRequest as ex:
                ex = json.loads(ex.content)
                messages.error(
                    request, '{}: {} ({})'.format(
                        _('We had trouble communicating with PayPal'),
                        ex['error_description'], ex['correlation_id']))
                return

            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'header': {
                'PayPal-Partner-Attribution-Id': 'ramiioSoftwareentwicklung_SP'
            },
            'intent':
            'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url":
                build_absolute_uri(request.event,
                                   'plugins:paypal:return',
                                   kwargs=kwargs),
                "cancel_url":
                build_absolute_uri(request.event,
                                   'plugins:paypal:abort',
                                   kwargs=kwargs),
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": __('Order for %s') % str(request.event),
                        "quantity": 1,
                        "price": self.format_price(cart['total']),
                        "currency": request.event.currency
                    }]
                },
                "amount": {
                    "currency": request.event.currency,
                    "total": self.format_price(cart['total'])
                },
                "description":
                __('Event tickets for {event}').format(
                    event=request.event.name),
                "payee":
                payee
            }]
        })
        request.session['payment_paypal_order'] = None
        return self._create_payment(request, payment)
Exemplo n.º 32
0
 def __str__(self):
     return __('{name}\'s profile').format(name=self.user.name)
Exemplo n.º 33
0
 def __str__(self):
     return __('Settings')
Exemplo n.º 34
0
    def submit_deposit(self, pdf, form, dry_run=False):
        if self.username is None or self.password is None:
            raise DepositError(__("No HAL user credentials provided."))

        deposit_result = DepositResult()

        try:
            # Creating the metadata
            self.log("### Generating metadata")
            metadata = self.create_metadata(form)

            # Bundling the metadata and the PDF
            self.log("### Creating ZIP file")
            zipFile = self.create_zip(pdf, metadata)

            # Build the list of users who should own this deposit
            on_behalf_of = [self.username]
            if self.hal_preferences.on_behalf_of:
                on_behalf_of.append(self.hal_preferences.on_behalf_of)

            # Creating a new deposition
            self.log("### Creating a new deposition")

            parsed_endpoint = urlparse(self.api_url)
            host = parsed_endpoint.netloc
            path = parsed_endpoint.path + 'hal'

            conn = http_client.HTTPConnection(host)
            conn.putrequest('POST', path, True, True)
            zipContent = zipFile.getvalue()
            headers = {
                'Authorization': self.encodeUserData(),
                'Host': host,
                'X-Packaging': 'http://purl.org/net/sword-types/AOfr',
                'Content-Type': 'application/zip',
                'Content-Disposition': 'attachment; filename=meta.xml',
                'Content-Length': len(zipContent),
                'On-Behalf-Of': ';'.join(on_behalf_of),
            }
            for header, value in headers.items():
                conn.putheader(header, value)
            conn.endheaders()
            conn.send(zipContent)
            resp = conn.getresponse()

            xml_response = resp.read()
            conn.close()
            try:
                parser = etree.XMLParser(encoding='utf-8')
                receipt = etree.parse(BytesIO(xml_response), parser)
                if resp.status != 201:
                    self.log('Deposit response status: HTTP %d' % resp.status)
                    self.log(xml_response.decode('utf-8'))
                    # Get the verbose description of the error to output it as well
                    root = receipt.getroot()
                    verboseDescription = (next(
                        root.iter(
                            "{http://purl.org/net/sword/error/}verboseDescription"
                        )).text)
                    try:
                        # Give a better error message to the user if the document
                        # already exists in HAL. See #356.
                        assert "duplicate-entry" in json.loads(
                            verboseDescription)
                        raise DepositError(
                            __('This document is already in HAL. '
                               'HAL refused the deposit.'))
                    except (ValueError, AssertionError):
                        raise DepositError(
                            __('HAL refused the deposit (HTTP error %d): %s') %
                            (resp.status, verboseDescription))
            except etree.XMLSyntaxError:
                self.log('Invalid XML response from HAL:')
                self.log(xml_response.decode('utf-8'))
                self.log('(end of the response)')
                raise DepositError(__('HAL returned an invalid XML response'))

            receipt = receipt.getroot()
            if receipt.tag == '{http://purl.org/net/sword/error/}error':
                self.log('Error while depositing the content.')
                verbosedesc = receipt.find(
                    '{http://purl.org/net/sword/error/}verboseDescription')

                # this will happen if a paper has not made its way via
                # OAI to us, so we could not detect that earlier in the
                # submission
                if verbosedesc is not None and 'duplicate-entry' in verbosedesc.text:
                    raise DepositError(__('This paper already exists in HAL.'))

                # Otherwise this error should not happen: let's dump
                # everything to check later
                self.log('Here is the XML response:{}'.format(
                    xml_response.decode('utf-8')))
                self.log('Here is the metadata:{}'.format(
                    metadata.decode('utf-8')))
                raise DepositError(__('HAL rejected the submission.'))
            else:
                self.log(xml_response)

            deposition_id = receipt.find(
                '{http://www.w3.org/2005/Atom}id').text
            password = receipt.find(
                '{http://hal.archives-ouvertes.fr/}password').text
            document_url = resp.getheader('location')

            if not deposition_id:
                raise DepositError(__('HAL rejected the submission'))

            self.log("Deposition id: %s" % deposition_id)

            deposit_result.identifier = deposition_id
            deposit_result.splash_url = document_url
            deposit_result.pdf_url = None
            deposit_result.status = 'pending'  # HAL moderates submissions
            deposit_result.additional_info = [
                {
                    'label': __('Password'),
                    'value': password
                },
            ]

            if dry_run:
                conn = http_client.HTTPConnection(host)
                conn.putrequest('DELETE', '/sword/' + deposition_id)
                headers = {
                    'Authorization': self.encodeUserData(),
                    # 'Host': host,
                    'Accept': '*/*',
                    'User-Agent': 'dissemin',
                }
                for header, value in headers.items():
                    conn.putheader(header, value)
                conn.endheaders()
                resp = conn.getresponse()
                self.log(resp.read())
                conn.close()
                deposit_result.status = 'faked'

        except DepositError as e:
            raise e
        except Exception as e:
            self.log("Caught exception:")
            self.log(str(type(e)) + ': ' + str(e) + '')
            self.log(traceback.format_exc())
            raise DepositError(
                __('Connection to HAL failed. Please try again later.'))

        return deposit_result
Exemplo n.º 35
0
class ZenodoForm(FormWithAbstract):
    license = forms.ChoiceField(
        label=__('License'),
        choices=ZENODO_LICENSES_CHOICES,
        initial='other-open',
        widget=forms.RadioSelect(attrs={'class': 'radio-margin'}))
Exemplo n.º 36
0
                                             params):
        """Update the case when migration is reviewed.

        :param case: case object
        :type case: core.models.Case
        :param fb: fogbugz api client object
        :param case_info: case information dictionary
        :type case_info: dict
        :param params: optional case edit params
        :type params: dict

        :return: fogbugz api response object
        """
        if 'migration-reviewed' not in case_info['tags']:
            response = fb.edit(ixbug=case.id,
                               sEvent=__('Migration was marked as reviewed'),
                               sTags=','.join(case_info['tags'].union(
                                   {'migration-reviewed'})))
            return response

    def update_to_fogbugz_migration_unreviewed(self, case, fb, case_info,
                                               params):
        """Update the case when migration is unreviewed.

        :param case: case object
        :type case: core.models.Case
        :param fb: fogbugz api client object
        :param case_info: case information dictionary
        :type case_info: dict
        :param params: optional case edit params
        :type params: dict
Exemplo n.º 37
0
 def choices(cls):
     return [(item.value, __(item.name.replace("_", " ").capitalize())) for item in cls]
Exemplo n.º 38
0
    def _execute_payment(self, payment, request, payment_obj):
        if payment.state == 'created':
            payment.replace([{
                "op": "replace",
                "path": "/transactions/0/item_list",
                "value": {
                    "items": [{
                        "name":
                        __('Order {slug}-{code}').format(
                            slug=self.event.slug.upper(),
                            code=payment_obj.order.code),
                        "quantity":
                        1,
                        "price":
                        self.format_price(payment_obj.amount),
                        "currency":
                        payment_obj.order.event.currency
                    }]
                }
            }, {
                "op":
                "replace",
                "path":
                "/transactions/0/description",
                "value":
                __('Order {order} for {event}').format(
                    event=request.event.name, order=payment_obj.order.code)
            }])
            try:
                payment.execute(
                    {"payer_id": request.session.get('payment_paypal_payer')})
            except Exception as e:
                messages.error(request,
                               _('We had trouble communicating with PayPal'))
                logger.exception('Error on creating payment: ' + str(e))

        for trans in payment.transactions:
            for rr in trans.related_resources:
                if hasattr(rr, 'sale') and rr.sale:
                    if rr.sale.state == 'pending':
                        messages.warning(
                            request,
                            _('PayPal has not yet approved the payment. We will inform you as '
                              'soon as the payment completed.'))
                        payment_obj.info = json.dumps(payment.to_dict())
                        payment_obj.state = OrderPayment.PAYMENT_STATE_PENDING
                        payment_obj.save()
                        return

        payment_obj.refresh_from_db()
        if payment.state == 'pending':
            messages.warning(
                request,
                _('PayPal has not yet approved the payment. We will inform you as soon as the '
                  'payment completed.'))
            payment_obj.info = json.dumps(payment.to_dict())
            payment_obj.state = OrderPayment.PAYMENT_STATE_PENDING
            payment_obj.save()
            return

        if payment.state != 'approved':
            payment_obj.fail(info=payment.to_dict())
            logger.error('Invalid state: %s' % str(payment))
            raise PaymentException(
                _('We were unable to process your payment. See below for details on how to '
                  'proceed.'))

        if payment_obj.state == OrderPayment.PAYMENT_STATE_CONFIRMED:
            logger.warning(
                'PayPal success event even though order is already marked as paid'
            )
            return

        try:
            payment_obj.info = json.dumps(payment.to_dict())
            payment_obj.save(update_fields=['info'])
            payment_obj.confirm()
        except Quota.QuotaExceededException as e:
            raise PaymentException(str(e))

        except SendMailException:
            messages.warning(
                request,
                _('There was an error sending the confirmation mail.'))
        return None
Exemplo n.º 39
0
 class Meta:
     verbose_name = __("commercial meaning", "Order")
     verbose_name_plural = __("commercial meaning", "Orders")
     ordering = ("-id", )
Exemplo n.º 40
0
    def payment_prepare(self, request, payment_obj):
        self.init_api()

        try:
            if request.event.settings.payment_paypal_connect_user_id:
                try:
                    tokeninfo = Tokeninfo.create_with_refresh_token(
                        request.event.settings.
                        payment_paypal_connect_refresh_token)
                except BadRequest as ex:
                    ex = json.loads(ex.content)
                    messages.error(
                        request, '{}: {} ({})'.format(
                            _('We had trouble communicating with PayPal'),
                            ex['error_description'], ex['correlation_id']))
                    return

                # Even if the token has been refreshed, calling userinfo() can fail. In this case we just don't
                # get the userinfo again and use the payment_paypal_connect_user_id that we already have on file
                try:
                    userinfo = tokeninfo.userinfo()
                    request.event.settings.payment_paypal_connect_user_id = userinfo.email
                except UnauthorizedAccess:
                    pass

                payee = {
                    "email":
                    request.event.settings.payment_paypal_connect_user_id,
                    # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                    # we should use it instead of the merchant's eMail-address
                    # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
                }
            else:
                payee = {}

            payment = paypalrestsdk.Payment({
                'header': {
                    'PayPal-Partner-Attribution-Id':
                    'ramiioSoftwareentwicklung_SP'
                },
                'intent':
                'sale',
                'payer': {
                    "payment_method": "paypal",
                },
                "redirect_urls": {
                    "return_url":
                    build_absolute_uri(request.event, 'plugins:paypal:return'),
                    "cancel_url":
                    build_absolute_uri(request.event, 'plugins:paypal:abort'),
                },
                "transactions": [{
                    "item_list": {
                        "items": [{
                            "name": ('{} '.format(self.settings.prefix)
                                     if self.settings.prefix else '') +
                            __('Order {slug}-{code}').format(
                                slug=self.event.slug.upper(),
                                code=payment_obj.order.code),
                            "quantity":
                            1,
                            "price":
                            self.format_price(payment_obj.amount),
                            "currency":
                            payment_obj.order.event.currency
                        }]
                    },
                    "amount": {
                        "currency": request.event.currency,
                        "total": self.format_price(payment_obj.amount)
                    },
                    "description":
                    ('{} '.format(self.settings.prefix) if self.settings.prefix
                     else '') + __('Order {order} for {event}').format(
                         event=request.event.name,
                         order=payment_obj.order.code),
                    "payee":
                    payee
                }]
            })
            request.session['payment_paypal_payment'] = payment_obj.pk
            return self._create_payment(request, payment)
        except paypalrestsdk.exceptions.ConnectionError as e:
            messages.error(request,
                           _('We had trouble communicating with PayPal'))
            logger.exception('Error on creating payment: ' + str(e))
Exemplo n.º 41
0
    def render_js(self):
        return mark_safe(render_to_string(self.js_template, {
            'self': self,
            'can_order': self.formset.can_order,
        }))


def InlinePanel(base_model, relation_name, panels=None, label='', help_text=''):
    rel = getattr(base_model, relation_name).related
    return type('_InlinePanel', (BaseInlinePanel,), {
        'relation_name': relation_name,
        'related': rel,
        'panels': panels,
        'heading': label,
        'help_text': help_text,  # TODO: can we pick this out of the foreign key definition as an alternative? (with a bit of help from the inlineformset object, as we do for label/heading)
    })


# Now that we've defined EditHandlers, we can set up wagtailcore.Page to have some.
Page.content_panels = [
    FieldPanel('title', classname="full title"),
]
Page.promote_panels = [
    MultiFieldPanel([
        FieldPanel('slug'),
        FieldPanel('seo_title'),
        FieldPanel('show_in_menus'),
        FieldPanel('search_description'),
    ], __('Common page configuration')),
]
Exemplo n.º 42
0
    def payment_prepare(self, request, payment_obj):
        self.init_api()

        if request.event.settings.payment_paypal_connect_user_id:
            userinfo = Tokeninfo.create_with_refresh_token(
                request.event.settings.payment_paypal_connect_refresh_token
            ).userinfo()
            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'header': {
                'PayPal-Partner-Attribution-Id': 'ramiioSoftwareentwicklung_SP'
            },
            'intent':
            'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url":
                build_absolute_uri(request.event, 'plugins:paypal:return'),
                "cancel_url":
                build_absolute_uri(request.event, 'plugins:paypal:abort'),
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name":
                        __('Order {slug}-{code}').format(
                            slug=self.event.slug.upper(),
                            code=payment_obj.order.code),
                        "quantity":
                        1,
                        "price":
                        self.format_price(payment_obj.amount),
                        "currency":
                        payment_obj.order.event.currency
                    }]
                },
                "amount": {
                    "currency": request.event.currency,
                    "total": self.format_price(payment_obj.amount)
                },
                "description":
                __('Order {order} for {event}').format(
                    event=request.event.name, order=payment_obj.order.code),
                "payee":
                payee
            }]
        })
        request.session['payment_paypal_order'] = payment_obj.order.pk
        request.session['payment_paypal_payment'] = payment_obj.pk
        return self._create_payment(request, payment)
Exemplo n.º 43
0
    def save(self, *args, **kwargs):
        if self.cleaned_data.get('copy_from'):
            self.instance.description = self.cleaned_data[
                'copy_from'].description
            self.instance.active = self.cleaned_data['copy_from'].active
            self.instance.available_from = self.cleaned_data[
                'copy_from'].available_from
            self.instance.available_until = self.cleaned_data[
                'copy_from'].available_until
            self.instance.require_voucher = self.cleaned_data[
                'copy_from'].require_voucher
            self.instance.hide_without_voucher = self.cleaned_data[
                'copy_from'].hide_without_voucher
            self.instance.allow_cancel = self.cleaned_data[
                'copy_from'].allow_cancel
            self.instance.min_per_order = self.cleaned_data[
                'copy_from'].min_per_order
            self.instance.max_per_order = self.cleaned_data[
                'copy_from'].max_per_order
            self.instance.checkin_attention = self.cleaned_data[
                'copy_from'].checkin_attention

        self.instance.position = (
            self.event.items.aggregate(p=Max('position'))['p'] or 0) + 1
        instance = super().save(*args, **kwargs)

        if not self.event.has_subevents and not self.cleaned_data.get(
                'has_variations'):
            if self.cleaned_data.get(
                    'quota_option') == self.EXISTING and self.cleaned_data.get(
                        'quota_add_existing') is not None:
                quota = self.cleaned_data.get('quota_add_existing')
                quota.items.add(self.instance)
            elif self.cleaned_data.get('quota_option') == self.NEW:
                quota_name = self.cleaned_data.get('quota_add_new_name')
                quota_size = self.cleaned_data.get('quota_add_new_size')

                quota = Quota.objects.create(event=self.event,
                                             name=quota_name,
                                             size=quota_size)
                quota.items.add(self.instance)

        if self.cleaned_data.get('has_variations'):
            if self.cleaned_data.get('copy_from') and self.cleaned_data.get(
                    'copy_from').has_variations:
                for variation in self.cleaned_data['copy_from'].variations.all(
                ):
                    ItemVariation.objects.create(
                        item=instance,
                        value=variation.value,
                        active=variation.active,
                        position=variation.position,
                        default_price=variation.default_price)
            else:
                ItemVariation.objects.create(item=instance,
                                             value=__('Standard'))

        if self.cleaned_data.get('copy_from'):
            for question in self.cleaned_data['copy_from'].questions.all():
                question.items.add(instance)

        return instance
Exemplo n.º 44
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     helper = FormHelper()
     helper.layout = Layout(
         Div(
             Field(
                 "gm",
                 template="crispy/floating-labels.html",
                 wrapper_class="col-12 col-md-6 col-lg px-1 mb-lg-0",
                 title=__("GM") + " (" + __("active") + ")"
                 if "gm" in self.active_filters
                 else __("GM"),
                 css_class="filter-active" if "gm" in self.active_filters else "",
             ),
             Field(
                 "workweek",
                 template="crispy/floating-labels.html",
                 wrapper_class="col-12 col-md-6 col-lg px-1 mb-lg-0",
                 title=__("Workweek") + " (" + __("active") + ")"
                 if "workweek" in self.active_filters
                 else __("Workweek"),
                 css_class="filter-active"
                 if "workweek" in self.active_filters
                 else "",
             ),
             Field(
                 "categories",
                 template="crispy/floating-labels.html",
                 wrapper_class="col-12 col-md-6 col-lg px-1 mb-lg-0",
                 title=__("Categories") + " (" + __("active") + ")"
                 if "categories" in self.active_filters
                 else __("Categories"),
                 css_class="filter-active"
                 if "categories" in self.active_filters
                 else "",
             ),
             Field(
                 "is_custom_material",
                 template="crispy/floating-labels.html",
                 wrapper_class="col-12 col-md-6 col-lg px-1 mb-lg-0",
                 title=__("Custom material") + " (" + __("active") + ")"
                 if "is_custom_material" in self.active_filters
                 else __("Custom material"),
                 css_class="filter-active"
                 if "is_custom_material" in self.active_filters
                 else "",
             ),
             Div(
                 Submit(
                     "filter",
                     _("Apply filters"),
                     css_class="btn-secondary",
                 ),
                 HTML(
                     '<a href="?" class="btn btn-outline-secondary">{}</a>'.format(
                         _("Clear")
                     )
                 ),
                 css_class="col-12 col-lg-auto px-1 mb-xl-0 form-label-group mb-md-0",
             ),
             css_class="row mx-0",
         ),
     )
     helper.form_class = "form-inline"
     helper.disable_csrf = True
     self.helper = helper
Exemplo n.º 45
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

from __future__ import unicode_literals

from deposit.forms import FormWithAbstract
from django import forms
from django.utils.translation import ugettext as __

ZENODO_LICENSES_CHOICES = [
    ('cc-zero', __('Creative Commons CCZero (CC0)')),
    ('cc-by', __('Creative Commons Attribution (CC-BY)')),
    ('cc-by-sa', __('Creative Commons Attribution-ShareAlike (CC-BY-SA)')),
    ('cc-by-nc-4.0',
     __('Creative Commons Attribution-NonCommercial (CC-BY-NC)')),
    ('cc-by-nd-4.0',
     __('Creative Commons Attribution-NoDerivatives (CC-BY-ND)')),
    ('other-open', __('Other open license')),
]


class ZenodoForm(FormWithAbstract):
    license = forms.ChoiceField(
        label=__('License'),
        choices=ZENODO_LICENSES_CHOICES,
        initial='other-open',
Exemplo n.º 46
0
 def nav_subtitle(self):
     return __("%d query in %.2fms", "%d queries in %.2fms",
               self._num_queries) % (self._num_queries, self._sql_time)
Exemplo n.º 47
0
 def get_display(cls, value):
     return ", ".join((__(ChoicesIntEnum.capitalize(item)) for item in cls
                       if item.value & value))
Exemplo n.º 48
0
 def title(self):
     count = len(self._databases)
     return __('SQL Queries from %(count)d connection',
               'SQL Queries from %(count)d connections',
               count) % dict(count=count)
Exemplo n.º 49
0
 class Meta:
     verbose_name = __('Pad Etherpad')
     verbose_name_plural = __('Pads Etherpad')
Exemplo n.º 50
0
class Registration(models.Model):
    import re
    alpha = RegexValidator(regex=re.compile(r'^[\w\s]*$', flags=re.UNICODE),
                           message=_('Only letters are allowed.'))

    first_name = models.CharField(max_length=20,
                                  validators=[alpha],
                                  verbose_name=_('first name'))
    last_name = models.CharField(max_length=20,
                                 validators=[alpha],
                                 verbose_name=_('last name'))
    GENDER_CHOICES = (
        ('M', _('Male')),
        ('F', _('Female')),
        # Translators: Gender information
        ('N', _('Other / I prefer not to disclose')),
    )
    gender = models.CharField(
        max_length=20,
        choices=GENDER_CHOICES,
        # default=GENDER_CHOICES[0][0],
        verbose_name=_('gender'))

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    # student-specific
    is_student = models.BooleanField(default=False,
                                     verbose_name=_("Are you a student?"))
    school = models.CharField(max_length=100,
                              blank=True,
                              verbose_name=_("Where do/did you go to school?"),
                              validators=[alpha])

    # contact
    email = models.EmailField(verbose_name=_('email'))
    github = models.URLField(max_length=100, blank=True)
    linkedin = models.URLField(max_length=100, blank=True)

    # misc
    food_restrictions = models.TextField(
        max_length=100,
        default="None",
        verbose_name=_("Do you have any allergies or food restrictions?"))
    TSHIRT_SIZE_CHOICES = (
        # Translators: T-shirt sizes
        ('S', _('Small')),
        ('M', _('Medium')),
        ('L', _('Large')),
        ('XL', _('X-Large')),
    )
    tshirt_size = models.CharField(max_length=20,
                                   choices=TSHIRT_SIZE_CHOICES,
                                   verbose_name=_('T-Shirt size'))
    is_waitlisted = models.BooleanField(default=False,
                                        verbose_name=_("Waitlisted?"))
    is_returning = models.BooleanField(
        default=False, verbose_name=_("Did you attend last year's event?"))
    is_first_time_hacker = models.BooleanField(
        default=False, verbose_name=_("Is this your first hackathon?"))
    preferred_language = models.CharField(max_length=2,
                                          choices=settings.LANGUAGES,
                                          default=settings.LANGUAGE_CODE)
    # files
    RESUME_HELP_TEXT = "Not required but this might reach our sponsors for targeted employment opportunities."
    MAX_UPLOAD_SIZE = 2621440  # 2.5MB
    resume = models.FileField(
        upload_to=get_resume_filename,
        blank=True,
        verbose_name=_('resume'),
        help_text=__("Help text for resume field", RESUME_HELP_TEXT),
    )
    # has_read_code_of_conduct = models.BooleanField(default=False,
    #     verbose_name = _('I have read the <a href="#" target="_blank">Code of Conduct.</a>'),
    #     validators = [validate_true])
    # WAIVER_HELP_TEXT = "Not required but it will save us some time during registration."
    # waiver = models.FileField(upload_to=get_waiver_filename, blank=True,
    #     help_text = __("Help text for waiver field", WAIVER_HELP_TEXT),
    #     verbose_name = _('waiver'),
    # )
    # has_read_waiver = models.BooleanField(default=False,
    #     verbose_name = _('I have read the <a href="#" target="_blank">Waiver.</a>'),
    #     validators = [validate_true])
    has_read_conditions = models.BooleanField(default=False,
                                              validators=[validate_true])

    is_email_sent = models.BooleanField(
        default=False,
        verbose_name='Was the confirmation email sent?',
    )

    # Ticket Info
    charge = models.ForeignKey('ChargeAttempt', blank=True,
                               null=True)  #default=1)

    is_early_bird = models.BooleanField(default=False)

    TICKET_FULL_PRICE = 2000  # in cents
    TICKET_STUDENT_PRICE = 1500  # in cents
    ticket_price = models.SmallIntegerField(default=0)
    TICKET_DESCRIPTION_CHOICES = (
        # Translators: Ticket descriptions
        ('N', _('No ticket yet')),
        ('CR', _('Turing Ticket')),
        ('CS', _('Turing Student Ticket')),
        ('R', _('Regular Ticket')),
        ('S', _('Student Ticket')),
        ('ER', _('Early Bird Ticket')),
        ('ES', _('Early Bird Student Ticket')),
    )
    ticket_description = models.CharField(
        default=TICKET_DESCRIPTION_CHOICES[0][0],
        choices=TICKET_DESCRIPTION_CHOICES,
        max_length=2)
    ticket_file = models.FileField(upload_to=get_ticket_filename, blank=True)
    qrcode_file = models.FileField(upload_to=get_qrcode_filename,
                                   blank=True,
                                   storage=OverwriteStorage())
    discount_code = models.ForeignKey('DiscountCode', null=True, blank=True)

    # Logistics
    ORDER_ID_MAX_LENGTH = 6
    order_id = models.CharField(default='xxx', max_length=ORDER_ID_MAX_LENGTH)

    has_attended = models.BooleanField(default=False)
    staff_comments = models.TextField(
        max_length=100,
        default="No comments",
        help_text='Log anything to do with this registration here.',
        blank=True)

    # Challenge
    has_solved_challenge = models.BooleanField(default=False)
    solved_challenge = models.ForeignKey('Challenge', null=True, blank=True)

    @property
    def has_submitted_waiver(self):
        print "waiver", self.waiver
        print bool(self.waiver)
        print 'name', self.waiver.name
        return bool(self.waiver)

    def has_submitted_resume(self):
        return bool(self.resume)

    def has_discount(self):
        return bool(self.discount_code)

    def full_name(self):
        return '%s %s' % (self.first_name.encode('utf-8'),
                          self.last_name.encode('utf-8'))

    full_name.admin_order_field = 'last_name'

    def needs_to_be_checked(self):
        result = False
        if self.is_email_sent and self.charge and \
            not self.charge.is_captured:
            result = True
        return result

    def is_charged(self):
        return bool(self.charge) and self.charge.is_captured

    @staticmethod
    def get_ticket_info(registration=None,
                        is_early_bird=False,
                        is_student=False,
                        has_solved_challenge=False,
                        discount_code=None):
        from datetime import datetime

        if registration:
            is_early_bird = registration.is_early_bird
            is_student = registration.is_student
            has_solved_challenge = registration.has_solved_challenge

        # ticket price
        # full_price = Registration.TICKET_FULL_PRICE
        # ratio_to_pay = 0.5 if is_early_bird else 1
        # ratio_to_pay = ratio_to_pay * 0.5 if is_student else ratio_to_pay
        # price = full_price * ratio_to_pay

        if has_solved_challenge:
            price = 0
        else:
            price = Registration.TICKET_STUDENT_PRICE if is_student else Registration.TICKET_FULL_PRICE

        # discount info
        if not discount_code and registration and registration.discount_code:
            discount_code = registration.discount_code

        if discount_code:
            if discount_code.is_fixed_discount:
                price = discount_code.amount
            elif discount_code.is_percentage:
                price = price * (100 - discount_code.amount) / 100.0
            else:
                price = price - discount_code.amount
            price = 0 if price < 0 else price

        discount_percentage = (
            1 - price / float(Registration.TICKET_FULL_PRICE)) * 100
        discount_amount = Registration.TICKET_FULL_PRICE - price
        discount = {
            'percentage': discount_percentage,
            'amount': discount_amount
        }
        # ticket description
        choices = dict(Registration.TICKET_DESCRIPTION_CHOICES)
        description = ''  #'E' if is_early_bird else ''
        description += 'C' if has_solved_challenge else ''
        description += 'S' if is_student else 'R'
        return (description, price, discount)

    @staticmethod
    def generate_order_id():
        from random import randint
        n, generated, order_id = Registration.ORDER_ID_MAX_LENGTH, False, 'xxx'
        while not generated:
            order_id = ''.join(["%s" % randint(0, 9) for num in range(0, n)])
            if not Registration.objects.filter(order_id=order_id).exists():
                generated = True
        return order_id

    def get_confirmation_url(self):
        """
        Staff-only url to confirm registration
        """
        url = reverse("confirm-registration",
                      kwargs={'order_id': str(self.order_id)})
        full_url = ''.join([settings.HTTP_PREFIX, settings.HOSTS[0], url])
        return full_url

    def get_qrcode_url(self):
        """
        Access hacker mobile ticket
        """
        url = reverse("qrcode", kwargs={'order_id': str(self.order_id)})
        full_url = ''.join([settings.HTTP_PREFIX, settings.HOSTS[0], url])
        return full_url

    def get_absolute_url(self):
        return reverse("confirmation_email",
                       kwargs={'order_id': str(self.order_id)})

    class Meta:
        ordering = (
            '-updated_at',
            'last_name',
            'first_name',
        )

    def __unicode__(self):
        if self.pk:
            return '{0}'.format(
                self.pk)  # '{0} (#{1})'.format(self.full_name(), self.pk)
        else:
            return '{0} (Not saved)'.format(self.full_name())
Exemplo n.º 51
0
 def save(self, *args, **kwargs):
     instance = super().save(*args, **kwargs)
     if self.cleaned_data.get('has_variations'):
         ItemVariation.objects.create(item=instance, value=__('Standard'))
     return instance
Exemplo n.º 52
0
    def save(self, *args, **kwargs):
        if self.cleaned_data.get('copy_from'):
            self.instance.description = self.cleaned_data[
                'copy_from'].description
            self.instance.active = self.cleaned_data['copy_from'].active
            self.instance.available_from = self.cleaned_data[
                'copy_from'].available_from
            self.instance.available_until = self.cleaned_data[
                'copy_from'].available_until
            self.instance.require_voucher = self.cleaned_data[
                'copy_from'].require_voucher
            self.instance.hide_without_voucher = self.cleaned_data[
                'copy_from'].hide_without_voucher
            self.instance.allow_cancel = self.cleaned_data[
                'copy_from'].allow_cancel
            self.instance.min_per_order = self.cleaned_data[
                'copy_from'].min_per_order
            self.instance.max_per_order = self.cleaned_data[
                'copy_from'].max_per_order
            self.instance.checkin_attention = self.cleaned_data[
                'copy_from'].checkin_attention
            self.instance.free_price = self.cleaned_data[
                'copy_from'].free_price
            self.instance.original_price = self.cleaned_data[
                'copy_from'].original_price
            self.instance.sales_channels = self.cleaned_data[
                'copy_from'].sales_channels
        else:
            # Add to all sales channels by default
            self.instance.sales_channels = [
                k for k in get_all_sales_channels().keys()
            ]

        self.instance.position = (
            self.event.items.aggregate(p=Max('position'))['p'] or 0) + 1
        instance = super().save(*args, **kwargs)

        if not self.event.has_subevents and not self.cleaned_data.get(
                'has_variations'):
            if self.cleaned_data.get(
                    'quota_option') == self.EXISTING and self.cleaned_data.get(
                        'quota_add_existing') is not None:
                quota = self.cleaned_data.get('quota_add_existing')
                quota.items.add(self.instance)
                quota.log_action('pretix.event.quota.changed',
                                 user=self.user,
                                 data={'item_added': self.instance.pk})
            elif self.cleaned_data.get('quota_option') == self.NEW:
                quota_name = self.cleaned_data.get('quota_add_new_name')
                quota_size = self.cleaned_data.get('quota_add_new_size')

                quota = Quota.objects.create(event=self.event,
                                             name=quota_name,
                                             size=quota_size)
                quota.items.add(self.instance)
                quota.log_action('pretix.event.quota.added',
                                 user=self.user,
                                 data={
                                     'name': quota_name,
                                     'size': quota_size,
                                     'items': [self.instance.pk]
                                 })

        if self.cleaned_data.get('has_variations'):
            if self.cleaned_data.get('copy_from') and self.cleaned_data.get(
                    'copy_from').has_variations:
                for variation in self.cleaned_data['copy_from'].variations.all(
                ):
                    ItemVariation.objects.create(
                        item=instance,
                        value=variation.value,
                        active=variation.active,
                        position=variation.position,
                        default_price=variation.default_price)
            else:
                ItemVariation.objects.create(item=instance,
                                             value=__('Standard'))

        if self.cleaned_data.get('copy_from'):
            for question in self.cleaned_data['copy_from'].questions.all():
                question.items.add(instance)
            for a in self.cleaned_data['copy_from'].addons.all():
                instance.addons.create(addon_category=a.addon_category,
                                       min_count=a.min_count,
                                       max_count=a.max_count,
                                       price_included=a.price_included,
                                       position=a.position)
            for b in self.cleaned_data['copy_from'].bundles.all():
                instance.bundles.create(bundled_item=b.bundled_item,
                                        bundled_variation=b.bundled_variation,
                                        count=b.count,
                                        designated_price=b.designated_price)

            item_copy_data.send(sender=self.event,
                                source=self.cleaned_data['copy_from'],
                                target=instance)

        return instance
Exemplo n.º 53
0
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from django.utils.translation import gettext as __

from .models import User

admin.site.empty_value_display = __('(None)')
admin.site.site_header = 'mosh_template'

admin.site.unregister(Group)


@admin.register(User)
class MyUser(UserAdmin):
    fieldsets = (
        (None, {
            'classes': ('extrapretty',),
            'fields': ('username', 'profile_pic', 'date_joined', 'last_login', 'is_active', 'is_staff', 'is_superuser',)
        }),
        ('Additional Information', {
            'classes': ('extrapretty', 'collapse',),
            'fields': ('password', 'email', 'first_name', 'last_name',)
        }),
    )
    add_fieldsets = (
        (None, {
            'classes': ('extrapretty',),
            'fields': ('username', 'password1', 'password2', 'first_name', 'last_name', 'profile_pic',)
        }),
    )
Exemplo n.º 54
0
    def submit_deposit(self, pdf, form):
        result = {}

        if self.repository.api_key is None:
            raise DepositError(__("No Zenodo API key provided."))
        api_key = self.repository.api_key
        api_url_with_key = self.api_url+'?access_token='+api_key

        deposit_result = DepositResult()

        # Checking the access token
        self.log("### Checking the access token")
        r = requests.get(api_url_with_key)
        self.log_request(r, 200, __('Unable to authenticate to Zenodo.'))
           
        # Creating a new deposition
        self.log("### Creating a new deposition")
        headers = {"Content-Type": "application/json"}
        r = requests.post(api_url_with_key, data=str("{}"), headers=headers)
        self.log_request(r, 201, __('Unable to create a new deposition on Zenodo.'))
        deposition_id = r.json()['id']
        deposit_result.identifier = deposition_id
        self.log("Deposition id: %d" % deposition_id)

        # Uploading the PDF
        self.log("### Uploading the PDF")
        data = {'filename':'article.pdf'}
        files = {'file': open(pdf, 'rb')}
        r = requests.post(self.api_url+"/%s/files?access_token=%s" % (deposition_id,api_key),
                data=data, files=files)
        self.log_request(r, 201, __('Unable to transfer the document to Zenodo.'))

        # Creating the metadata
        self.log("### Generating the metadata")
        data = self.createMetadata(form)
        self.log(json.dumps(data, indent=4)+'')

        # Check that there is an abstract
        if data['metadata'].get('description','') == '':
            self.log('No abstract found, aborting.')
            raise DepositError(__('No abstract is available for this paper but '+
                    'Zenodo requires to attach one. Please use the metadata panel to provide one.'))

        # Submitting the metadata
        self.log("### Submitting the metadata")
        r = requests.put(self.api_url+"/%s?access_token=%s" % ( deposition_id, api_key),
                data=json.dumps(data), headers=headers)
        self.log_request(r, 200, __('Unable to submit paper metadata to Zenodo.'))
        
        # Deleting the deposition
        #self.log("### Deleting the deposition")
        #r = requests.delete(self.api_url+"/%s?access_token=%s" % ( deposition_id, api_key) )
        self.log("### Publishing the deposition")
        r = requests.post(self.api_url+"/%s/actions/publish?access_token=%s" % (deposition_id, api_key))
        self.log_request(r, 202, __('Unable to publish the deposition on Zenodo.'))
        self.log(r.text)
        deposition_object = r.json()
        deposit_result.splash_url = deposition_object['record_url'] 
        deposit_result.pdf_url = deposit_result.splash_url + '/files/article.pdf'

        return deposit_result
Exemplo n.º 55
0
def humanize_list(lst):
    if not lst:
        return ""
    lst = lst.copy()
    last = lst.pop()
    return __("{} and {}").format(", ".join(map(str, lst)), last)
Exemplo n.º 56
0
def map_to_table(data):
    array = np.array(list(data.items())).T
    cols, body = array
    return html_table([body], columns=[__(col) for col in cols], class_='ReportTable')
Exemplo n.º 57
0
 def get_conn(self):
     if self.repository.endpoint is None:
         raise DepositError(__("No servicedocument provided."))
     return sword2.Connection(self.repository.endpoint,
                              user_name=self.repository.username,
                              user_pass=self.repository.password)
Exemplo n.º 58
0
    def save(self, *args, **kwargs):
        if self.cleaned_data.get('copy_from'):
            src = self.cleaned_data['copy_from']
            fields = (
                'description',
                'active',
                'available_from',
                'available_until',
                'require_voucher',
                'hide_without_voucher',
                'allow_cancel',
                'min_per_order',
                'max_per_order',
                'generate_tickets',
                'checkin_attention',
                'free_price',
                'original_price',
                'sales_channels',
                'issue_giftcard',
                'require_approval',
                'allow_waitinglist',
                'show_quota_left',
                'hidden_if_available',
                'require_bundling',
                'checkin_attention',
                'require_membership',
                'grant_membership_type',
                'grant_membership_duration_like_event',
                'grant_membership_duration_days',
                'grant_membership_duration_months',
            )
            for f in fields:
                setattr(self.instance, f, getattr(src, f))

            if src.picture:
                self.instance.picture.save(os.path.basename(src.picture.name),
                                           src.picture)
        else:
            # Add to all sales channels by default
            self.instance.sales_channels = list(
                get_all_sales_channels().keys())

        self.instance.position = (
            self.event.items.aggregate(p=Max('position'))['p'] or 0) + 1
        instance = super().save(*args, **kwargs)

        if not self.event.has_subevents and not self.cleaned_data.get(
                'has_variations'):
            if self.cleaned_data.get(
                    'quota_option') == self.EXISTING and self.cleaned_data.get(
                        'quota_add_existing') is not None:
                quota = self.cleaned_data.get('quota_add_existing')
                quota.items.add(self.instance)
                quota.log_action('pretix.event.quota.changed',
                                 user=self.user,
                                 data={'item_added': self.instance.pk})
            elif self.cleaned_data.get('quota_option') == self.NEW:
                quota_name = self.cleaned_data.get('quota_add_new_name')
                quota_size = self.cleaned_data.get('quota_add_new_size')

                quota = Quota.objects.create(event=self.event,
                                             name=quota_name,
                                             size=quota_size)
                quota.items.add(self.instance)
                quota.log_action('pretix.event.quota.added',
                                 user=self.user,
                                 data={
                                     'name': quota_name,
                                     'size': quota_size,
                                     'items': [self.instance.pk]
                                 })

        if self.cleaned_data.get('copy_from'):
            self.instance.require_membership_types.set(
                self.cleaned_data['copy_from'].require_membership_types.all())
        if self.cleaned_data.get('has_variations'):
            if self.cleaned_data.get('copy_from') and self.cleaned_data.get(
                    'copy_from').has_variations:
                for variation in self.cleaned_data['copy_from'].variations.all(
                ):
                    ItemVariation.objects.create(
                        item=instance,
                        value=variation.value,
                        active=variation.active,
                        position=variation.position,
                        default_price=variation.default_price,
                        description=variation.description,
                        original_price=variation.original_price)
            else:
                ItemVariation.objects.create(item=instance,
                                             value=__('Standard'))

        if self.cleaned_data.get('copy_from'):
            for question in self.cleaned_data['copy_from'].questions.all():
                question.items.add(instance)
            for a in self.cleaned_data['copy_from'].addons.all():
                instance.addons.create(addon_category=a.addon_category,
                                       min_count=a.min_count,
                                       max_count=a.max_count,
                                       price_included=a.price_included,
                                       position=a.position,
                                       multi_allowed=a.multi_allowed)
            for b in self.cleaned_data['copy_from'].bundles.all():
                instance.bundles.create(bundled_item=b.bundled_item,
                                        bundled_variation=b.bundled_variation,
                                        count=b.count,
                                        designated_price=b.designated_price)

            item_copy_data.send(sender=self.event,
                                source=self.cleaned_data['copy_from'],
                                target=instance)

        return instance
Exemplo n.º 59
0
 def _get_used_pct(self):
     try:
         return "%d%%" % self._zplist['capacity']
     except:
         return __("Error")
Exemplo n.º 60
0
 def __str__(self):
     if self.user is None:
         return __('unbound profile')
     return __('%(name)s\'s profile') % {'name': self.user.get_full_name()}