Ejemplo n.º 1
0
    def handle_query_products(self, request, range, form):
        products = form.get_products()
        if not products:
            return

        for product in products:
            range.add_product(product)

        num_products = len(products)
        messages.success(request, ungettext("%d product added to range",
                                            "%d products added to range",
                                            num_products) % num_products)
        dupe_skus = form.get_duplicate_skus()
        if dupe_skus:
            messages.warning(
                request,
                _("The products with SKUs or UPCs matching %s are already "
                  "in this range") % ", ".join(dupe_skus))

        missing_skus = form.get_missing_skus()
        if missing_skus:
            messages.warning(
                request,
                _("No product(s) were found with SKU or UPC matching %s") %
                ", ".join(missing_skus))
Ejemplo n.º 2
0
    def borrar_tipotelefonos(self, request, queryset):
        """
        borra los tipos de telefonos seleccionados solo si no estan
        asociados a un telefono
        """
        deleted=''
        nonDeleted=''
        for f in queryset:
            if not f.telefono_set.all():
                f.delete()
                deleted+=f.nombre+', '
            else:
                nonDeleted+=f.nombre+', '
        if deleted:
            deleted = deleted[:-2]
            msg1 = u'Se eliminaron los siguientes tipo de teléfono: %s.' %\
                   deleted
            self.message_user(request, msg1)
        if nonDeleted:
            msg2 = u'Recuerde que sólo se pueden eliminar los tipos de teléfono \
que no estén asociados a ningún número telefónico.'
            messages.warning(request,msg2)
            nonDeleted = nonDeleted[:-2]
            msg3 = u'Los siguientes tipos de teléfono no fueron eliminados: %s.'\
            % nonDeleted
            messages.error(request,msg3)
Ejemplo n.º 3
0
def TaskInstanceValidate(request, task_instance_id):
    task_instance = get_object_or_404(TaskInstance, pk=task_instance_id, task__owner=request.user)
    if request.POST:

        form = ValidationForm(request.POST)
        if form.is_valid():
            if 'validation' not in task_instance.parameters:
        # TODO: unify with the api, now the code is copied
                value = form.cleaned_data['validation']
                task_instance.quality = value
                pars = task_instance.parameters
                if pars is None:
                    pars = {}
                pars['validation'] = value
                task_instance.save()
                # if ("process_tactics_id" in task_instance.parameters):
                #     signal(task_instance.parameters['process_tactics_id'], task_instance.task.id, task_instance.id)
                messages.info(request, 'Validation made')
            else:
                messages.warning(request, 'Validation was already set')
            return redirect(reverse('r-taskinstances',args={task_instance.task.process.id,task_instance.task.id,}))
        else:
            return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
    else:
        form = ValidationForm()
        return render_to_response('requester/form.html', {'form': form}, context_instance=RequestContext(request))
Ejemplo n.º 4
0
def apply_messages(offers_before, request, default_msg=None):
    """
    Set flash messages triggered by changes to the basket
    """
    # Re-apply offers to see if any new ones are now available
    Applicator().apply(request, request.basket)
    offers_after = request.basket.get_discount_offers()

    # Look for changes in offers
    offers_lost = set(offers_before.keys()).difference(
        set(offers_after.keys()))
    offers_gained = set(offers_after.keys()).difference(
        set(offers_before.keys()))
    for offer_id in offers_lost:
        offer = offers_before[offer_id]
        messages.warning(
            request,
            _("Your basket no longer qualifies for the '%s' offer") % offer)
    for offer_id in offers_gained:
        offer = offers_after[offer_id]
        messages.success(
            request,
            _("Your basket now qualifies for the '%s' offer") % offer)
    if not offers_lost and not offers_gained:
        messages.info(request, default_msg)
Ejemplo n.º 5
0
def new_module(request, domain, app_id):
    "Adds a module to an app"
    app = get_app(domain, app_id)
    lang = request.COOKIES.get('lang', app.langs[0])
    name = request.POST.get('name')
    module_type = request.POST.get('module_type', 'case')
    if module_type == 'case':
        module = app.add_module(Module.new_module(name, lang))
        module_id = module.id
        app.new_form(module_id, "Untitled Form", lang)
        app.save()
        response = back_to_main(request, domain, app_id=app_id, module_id=module_id)
        response.set_cookie('suppress_build_errors', 'yes')
        return response
    elif module_type in MODULE_TYPE_MAP:
        fn = MODULE_TYPE_MAP[module_type][FN]
        validations = MODULE_TYPE_MAP[module_type][VALIDATIONS]
        error = next((v[1] for v in validations if v[0](app)), None)
        if error:
            messages.warning(request, error)
            return back_to_main(request, domain, app_id=app.id)
        else:
            return fn(request, domain, app, name, lang)
    else:
        logger.error('Unexpected module type for new module: "%s"' % module_type)
        return back_to_main(request, domain, app_id=app_id)
Ejemplo n.º 6
0
def chargedashboard(request):
	if not request.user.is_superuser:
		raise Http404

	talks = Talk.objects.filter(completed=True,paid_at=None)
	if request.method == "POST":
		talk_id = request.POST.get('talk_id','')  
		# error handling here
		talk = talks.get(id=talk_id)
		cost_in_cents = talk.cost() * 100

		customer_id = talk.user.userprofile.stripe_id
		card_id = talk.card.stripe_id

		# https://stripe.com/docs/api#create_charge
		stripe.api_key= settings.STRIPE_API_KEY 

		try:
			charge = stripe.Charge.create(
				amount=int(cost_in_cents), # amount in cents
				currency="usd",
				customer=customer_id,
				card=card_id,
				description= talk.expert.get_full_name()
			)
		except stripe.CardError, e:
			messages.warning(request,'The card is not valid')
			return HttpResponseRedirect(reverse('apps.main.views.chargedashboard', args=()))

		talk.paid_at = timezone.now()
		talk.save()
Ejemplo n.º 7
0
Archivo: views.py Proyecto: grv07/clat
def teacher_login(request):
	if request.user.is_authenticated():
		messages.info(request,'Please logout first and then re-login with a different account.')
		return HttpResponseRedirect('/home/')
	if request.method == 'POST':
		t_username = request.POST.get('username')
		t_password = request.POST.get('password')
		try:
			t_user = authenticate(username=t_username, password=t_password)
			teacher = Teacher.objects.get(pk=t_user.id)
		except Exception as e:
			t_user = None
			teacher = None
		if teacher is not None:
			if t_user.is_active:
				login(request, t_user)
				messages.success(request,'You logged in successfully.')
				return HttpResponseRedirect('/teacher/')
			else:
				messages.warning(request,'Your account is not yet active.')
				return render(request, 'teacher/login_teacher.html', {'t_not_active': True, 'next': request.POST.get('next')})
		else:
			course_list = CourseDetail.objects.all()
			course_list = pagination.get_paginated_list(obj_list=course_list,page = request.GET.get('page'))
			messages.error(request,'Please enter valid credentials.')
			return render(request, 'teacher/login_teacher.html', {'t_login_error': True, 'next': request.POST.get('next')})
	else:
		return render(request,'teacher/login_teacher.html',{})
Ejemplo n.º 8
0
    def form_valid(self, form):
        ticketed_event = form.save()
        messages.success(
            self.request, mark_safe('Event <strong> {}</strong> has been '
                                    'created!'.format(ticketed_event.name))
        )
        ActivityLog.objects.create(
            log='Ticketed Event {} (id {}) created by admin user {}'.format(
                ticketed_event, ticketed_event.id, self.request.user.username
            )
        )

        if ticketed_event.paypal_email != settings.DEFAULT_PAYPAL_EMAIL:
            messages.warning(
                self.request,
                mark_safe(
                    "You have changed the paypal receiver email from the "
                    "default value. If you haven't used this email before, "
                    "it is strongly recommended that you test the email "
                    "address "
                    "<a href='/studioadmin/test-paypal-email?email={}'>"
                    "here</a>".format(ticketed_event.paypal_email)
                )
            )

        return HttpResponseRedirect(self.get_success_url())
Ejemplo n.º 9
0
Archivo: cart.py Proyecto: rixx/pretix
    def _items_from_post_data(self):
        """
        Parses the POST data and returns a list of tuples in the
        form (item id, variation id or None, number)
        """

        # Compatibility patch that makes the frontend code a lot easier
        req_items = list(self.request.POST.lists())
        if '_voucher_item' in self.request.POST and '_voucher_code' in self.request.POST:
            req_items.append((
                '%s_voucher' % self.request.POST['_voucher_item'], (self.request.POST['_voucher_code'],)
            ))
            pass

        items = []
        for key, values in req_items:
            for value in values:
                try:
                    item = self._item_from_post_value(key, value)
                except CartError as e:
                    messages.error(self.request, str(e))
                    return
                if item:
                    items.append(item)

        if len(items) == 0:
            messages.warning(self.request, _('You did not select any products.'))
            return []
        return items
Ejemplo n.º 10
0
def versions(request):
    """
    Show all Versions for an Image according to ADMIN_VERSIONS.
    """
    
    # QUERY / PATH CHECK
    query = request.GET
    path = get_path(query.get('dir', ''))

    if 'pop' in query:
        is_popup = True
    else:
        is_popup = False

    filename = get_file(query.get('dir', ''), query.get('filename', ''))
    if path is None or filename is None:
        if path is None:
            msg = _('The requested Folder does not exist.')
        else:
            msg = _('The requested File does not exist.')
        messages.warning(request,message=msg)
        return HttpResponseRedirect(reverse("fb_browse"))
    abs_path = _check_access(request, path)
    
    return render_to_response(_template() + 'versions.html', {
        'original': path_to_url(os.path.join(fb_settings.DIRECTORY, path, filename)),
        'query': query,
        'title': _(u'Versions for "%s"') % filename,
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': _(u'Versions for "%s"') % filename,
        'is_popup': is_popup
    }, context_instance=Context(request))
Ejemplo n.º 11
0
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = request.POST.get('subject', '')
            message = request.POST.get('message', '')
            name = request.POST.get('name', '')
            from_email = '%s <%s>' % (name,
                                      request.POST.get('from_email', ''))
            recipient_list = [mail_tuple[1] for mail_tuple in settings.ADMINS]
            try:
                t = loader.get_template('reviewapp/email_contact.txt')
                c = Context({
                            'name': name,
                            'message': message,
                            'site_domain': Site.objects.get_current().domain,
                            'site_name': Site.objects.get_current().name, })
                send_mail(subject, t.render(c), from_email, recipient_list,
                          fail_silently=False)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')

            messages.success(request, _('Message sent successfully.'))
            return HttpResponseRedirect('/contact/')
        else:
            messages.warning(request, _('Please fill out all fields correctly.'))
    else:
        if request.user.is_authenticated():
            form = ContactForm(user=request.user)
        else:
            form = ContactForm()

    return render_to_response('reviewapp/contact.html', {
                              'form': form, },
                              context_instance=RequestContext(request))
Ejemplo n.º 12
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            form.save()
            if form.has_changed():
                self.request.event.log_action(
                    'pretix.event.settings', user=self.request.user, data={
                        k: form.cleaned_data.get(k) for k in form.changed_data
                        }
                )

            if request.POST.get('test', '0').strip() == '1':
                backend = self.request.event.get_mail_backend(force_custom=True)
                try:
                    backend.test(self.request.event.settings.mail_from)
                except Exception as e:
                    messages.warning(self.request, _('An error occured while contacting the SMTP server: %s') % str(e))
                else:
                    if form.cleaned_data.get('smtp_use_custom'):
                        messages.success(self.request, _('Your changes have been saved and the connection attempt to '
                                                         'your SMTP server was successful.'))
                    else:
                        messages.success(self.request, _('We\'ve been able to contact the SMTP server you configured. '
                                                         'Remember to check the "use custom SMTP server" checkbox, '
                                                         'otherwise your SMTP server will not be used.'))
            else:
                messages.success(self.request, _('Your changes have been saved.'))
            return redirect(self.get_success_url())
        else:
            messages.error(self.request, _('We could not save your changes. See below for details.'))
            return self.get(request)
Ejemplo n.º 13
0
def upload(request):
    """
    Multipe File Upload.
    """
    
    from django.http import parse_cookie
    
    # QUERY / PATH CHECK
    query = request.GET
    path = get_path(query.get('dir', ''))

    if 'pop' in query:
        is_popup = True
    else:
        is_popup = False

    if path is None:
        msg = _('The requested Folder does not exist.')
        messages.warning(request,message=msg)
        return HttpResponseRedirect(reverse("fb_browse"))
    abs_path = _check_access(request, path)
    
    # SESSION (used for flash-uploading)
    session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
    
    return render_to_response(_template() + 'upload.html', {
        'query': query,
        'title': _(u'Select files to upload'),
        'settings_var': get_settings_var(),
        'session_key': session_key,
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': _(u'Upload'),
        'is_popup': is_popup
    }, context_instance=Context(request))
Ejemplo n.º 14
0
def request_membership(request, slug):
    """
    Creates a JoinRequest for the initiative, provides the user
    with a message and redirects to the initiative's detail page.
    :param request: HTTPRequest
    :param slug: The initiative's slug
    :return: HTTPResponse
    """
    if not request.user.is_authenticated():
        messages.warning(
            request, 'Please Log In or Sign Up before joining an initiative.')
        return redirect(reverse("index_view"))

    # Make sure the Request doesnt exist yet.
    ini = get_object_or_404(models.Initiative, slug=slug)
    found = models.JoinRequest.objects.filter(
        initiative=ini, user=request.user.pk)
    if found.count() > 0:
        messages.warning(request, 'A request to join has already been made.')
        return redirect(reverse("initiatives:detail", kwargs={'slug': slug}))

    if request.POST:
        # Generate a new JoinRequest
        request_to_join = models.JoinRequest()
        request_to_join.user_id = request.user.pk
        request_to_join.is_open = True
        request_to_join.initiative = get_object_or_404(
            models.Initiative, slug=slug)
        request_to_join.save()
        messages.success(request, 'A request to join has been made')

    return redirect(reverse("initiatives:detail", kwargs={'slug': slug}))
Ejemplo n.º 15
0
def loginView(request):
    if request.user.is_authenticated():
         return redirect('website:catalogue')
    if request.method == 'POST':
        name = request.POST.get('login','')
        pw = request.POST.get('password','')

        #check if either is only whitespace
        if isNoneOrEmptyOrBlankString(name) or isNoneOrEmptyOrBlankString(pw):
            return HttpResponseBadRequest('username and/or password is empty')
        user = authenticate(username=name,password=pw)

        if user is not None:
            if user.is_active:
                login(request, user)
                #go to next or url root(index)
                return redirect(request.REQUEST.get('next','/'))
                
        else:
            messages.error(request, 'User not found')
            return redirect('website:index')

    elif request.method == 'GET':
        nextPage = request.REQUEST.get('next','/')
        if nextPage != '/':
            messages.warning(request,"You need to be logged in to view this page")
        return render(request, 'authenticate/login.html',{'next':nextPage})
Ejemplo n.º 16
0
def genome_get_form(wiz, form):
    """Genome, TF, TF_family, tf instance, .. selection form"""

    c = sutils.sget(wiz.request.session, "previously_curated_paper")
    # If selected publication is the one most recently curated, the related curation
    # should be in object c. Otherwise, c = None.  If so, populate "Genome and TF
    # information" form fields from the previously submitted curation to make things
    # easier for curator.
    if c:
        form.initial["TF"] = c.TF
        form.initial["TF_type"] = c.TF_type
        form.initial["TF_function"] = c.TF_function
        if c.site_instances.all():
            form.initial["genome_accession"] = c.site_instances.all()[0].genome.genome_accession
        form.initial["TF_accession"] = c.TF_instance.protein_accession
        
        form.initial["TF_species"] = c.TF_species
        form.initial["site_species"] = c.site_species

        msg = """
        <h4>Warning!</h4> It seems that the paper you selected is previously
        curated. For convenience, fields in this form are automatically filled based on
        the previous curation of the paper. They may differ in this curation, so it is
        best to check that they are correct before proceeding to the next step."""
        
        messages.warning(wiz.request, mark_safe(msg))        

    return form
Ejemplo n.º 17
0
    def process_request(self, request):
        user = request.user

        if user.is_authenticated():
            try:
                complete = user.profile.is_complete
            except UserProfile.DoesNotExist:
                complete = False

            try:
                loc = resolve(request.path_info)
            except Resolver404:
                return

            if not complete and not request.path_info.startswith('/static') and not request.path_info.startswith('/media'):
                # don't redirect if we're already on the profile page, or are logging out
                if loc.url_name in ['profile', 'logout'] or loc.app_name == 'admin':
                    if loc.url_name == 'profile':
                        messages.info(request, settings.COMPLETE_PROFILE_MESSAGE)
                    if loc.app_name == 'admin':
                        messages.warning(request, settings.ADMIN_COMPLETE_PROFILE_MESSAGE)

                    return

                #no exemptions matched, head to the profile page
                request.session['next'] = request.path_info
                request.session['was_redirected_from_completed_profile_middleware'] = True
                return redirect('profile')
Ejemplo n.º 18
0
def transfer_pool(request):
    try:
        pool_id = int(request.POST["pool_id"])
        user_id = int(request.POST["user_id"])
        with transaction.atomic():
            pool = AppliancePool.objects.get(id=pool_id)
            if not request.user.is_superuser:
                if pool.owner != request.user:
                    raise Exception("User does not have the right to change this pool's owner!")
            user = User.objects.get(id=user_id)
            if user == request.user:
                raise Exception("Why changing owner back to yourself? That does not make sense!")
            # original_owner = pool.owner
            pool.owner = user
            pool.save()
        # Rename appliances
        # for appliance in pool.appliances:
        #     if appliance.name.startswith("{}_".format(original_owner.username)):
        #         # Change name
        #         appliance_rename.delay(
        #             appliance.id, user.username + appliance.name[len(original_owner.username):])
    except Exception as e:
        messages.warning(request, "Exception {} happened: {}".format(type(e).__name__, str(e)))
    else:
        messages.success(request, "Success!")
    finally:
        return go_back_or_home(request)
Ejemplo n.º 19
0
def providers(request, provider_id=None):
    if request.user.is_staff or request.user.is_superuser:
        user_filter = {}
    else:
        user_filter = {'user_groups__in': request.user.groups.all()}
    if provider_id is None:
        try:
            provider = Provider.objects.filter(hidden=False, **user_filter).order_by("id")[0]
            return redirect(
                "specific_provider",
                provider_id=provider.id)
        except IndexError:
            # No Provider
            messages.info(request, "No provider present, redirected to the homepage.")
            return go_home(request)
    else:
        try:
            provider = Provider.objects.filter(id=provider_id, **user_filter).distinct().first()
            if provider is None:
                messages.error(
                    request,
                    'Could not find a provider with name {} that you would have access to.'.format(
                        provider_id))
                return go_home(request)
            if provider.hidden:
                messages.warning(request, 'Provider {} is hidden.'.format(provider_id))
                return redirect('providers')
        except ObjectDoesNotExist:
            messages.warning(request, "Provider '{}' does not exist.".format(provider_id))
            return redirect("providers")
    providers = Provider.objects.filter(hidden=False, **user_filter).order_by("id").distinct()
    return render(request, 'appliances/providers.html', locals())
Ejemplo n.º 20
0
    def get_redirect_url(self, **kwargs):
        try:
            basket = self.build_submission()['basket']
            url = self._get_redirect_url(basket, **kwargs)
        except PayPalError as ppe:
            messages.error(
                self.request, ppe.message)
            if self.as_payment_method:
                url = reverse('checkout:payment-details')
            else:
                url = reverse('basket:summary')
            return url
        except InvalidBasket as e:
            messages.warning(self.request, six.text_type(e))
            return reverse('basket:summary')
        except EmptyBasketException:
            messages.error(self.request, _("Your basket is empty"))
            return reverse('basket:summary')
        except MissingShippingAddressException:
            messages.error(
                self.request, _("A shipping address must be specified"))
            return reverse('checkout:shipping-address')
        except MissingShippingMethodException:
            messages.error(
                self.request, _("A shipping method must be specified"))
            return reverse('checkout:shipping-method')
        else:
            # Transaction successfully registered with PayPal.  Now freeze the
            # basket so it can't be edited while the customer is on the PayPal
            # site.
            basket.freeze()

            logger.info("Basket #%s - redirecting to %s", basket.id, url)

            return url
Ejemplo n.º 21
0
def tag_edit(request, id):
    tag = get_object_or_404(Tag, id=id)
    if request.method == 'POST':
        form = forms.TagEditForm(request.POST, instance=tag)
        if form.is_valid():
            tag = form.save()
            if Tag.objects.filter(name__iexact=tag.name).exclude(pk=tag.pk):
                messages.warning(
                    request,
                    "The tag you edited already exists with that same case "
                    "insensitive spelling."
                )
                return redirect('manage:tag_edit', tag.pk)
            else:
                edit_url = reverse('manage:tag_edit', args=(tag.pk,))
                messages.info(
                    request,
                    'Tag "%s" saved. [Edit again](%s)' % (tag, edit_url)
                )
                return redirect('manage:tags')
    else:
        form = forms.TagEditForm(instance=tag)
    repeated = Tag.objects.filter(name__iexact=tag.name).count()
    context = {
        'form': form,
        'tag': tag,
        'repeated': repeated,
        'is_repeated': repeated > 1
    }
    if repeated:
        context['repeated_form'] = forms.TagMergeForm(name=tag.name)
    return render(request, 'manage/tag_edit.html', context)
Ejemplo n.º 22
0
def search_view(request):
    query_str = request.GET.get('query_str')
    instance = None

    ## search for singel cell samples
    qs = cm.Sample.objects.filter(sample_id=query_str)
    if qs:
        instance = qs[0]
        return HttpResponseRedirect(instance.get_absolute_url())

    ## search for singel libraries
    qs = cm.Library.objects.filter(pool_id=query_str)
    if qs:
        instance = qs[0]
        return HttpResponseRedirect(instance.get_absolute_url())

    ## search for runs
    qs = Run.objects.filter(run_id=query_str)
    if qs:
        instance = qs[0]
        return HttpResponseRedirect(instance.get_absolute_url())

    ## no match found message
    msg = "Sorry, no match found."
    messages.warning(request, msg)
    return HttpResponseRedirect(reverse('index'))
Ejemplo n.º 23
0
def submissions(request):
    """Administrative list of bags in the bag directory"""
    if not request.user.is_authenticated():
        messages.warning(request, "You must log in to view this page.")
        return redirect('/login')
    if not request.user.is_staff:
        messages.warning(request, "Forbidden.")
        raise PermissionDenied

    submissions = []
    storage_path = os.path.abspath(settings.ETD_STORAGE_DIRECTORY)
    for subdir in os.listdir(storage_path):
        # Quickly check if this is a bag
        if True:  # TODO
            # Add to submissions
            submissions.append({
                'identifier': subdir,
                'username': subdir.split('-', 2)[-1]
            })
    submissions.sort(key=lambda x: x['identifier'], reverse=True)

    context = DefaultContext(request)
    context['title'] = "Submissions"
    context['submissions'] = submissions
    return render(request, 'etd_drop_app/submissions.html', context)
Ejemplo n.º 24
0
def submission_contents(request, id, path):
    """Download a file from the submission directory under the given
    path"""
    if not request.user.is_authenticated():
        messages.warning(request, "You must log in to view this page.")
        return redirect('/login')
    if not request.user.is_staff:
        messages.warning(request, "Forbidden.")
        raise PermissionDenied

    if '..' in path:
        raise Http404

    storage_path = os.path.abspath(settings.ETD_STORAGE_DIRECTORY)
    file_path = os.path.join(storage_path, id, path)
    if os.path.isfile(file_path):
        # Serve the file
        wrapper = FileWrapper(file(file_path))
        content_type = 'application/octet-stream'
        lowerpath = path.lower()
        if lowerpath.endswith('.pdf'):
            content_type = 'application/pdf'
        elif lowerpath.endswith('.json'):
            content_type = 'application/json'
        response = HttpResponse(wrapper, content_type=content_type)
        response['Content-Length'] = os.path.getsize(file_path)
        return response

    raise Http404
Ejemplo n.º 25
0
def submit(request):
    """Submit page, with submission form"""
    if not request.user.is_authenticated():
        messages.warning(request, "You must log in before submitting.")
        return redirect('/login')

    if request.method == 'POST':
        virus_found = False
        form = NewSubmissionForm(request.POST, request.FILES)
        result = None
        if form.is_valid():
            try:
                result = form.save(request.user)
            except ScanException, s:
                virus_found = True
            if result:
                messages.success(request, "Your submission was successfully uploaded.")
                context = DefaultContext(request)
                context['title'] = "Submission Receipt"
                context['submission_id'] = result
                return render(request, 'etd_drop_app/receipt.html', context)
            elif virus_found:
                messages.error(request, "A virus was detected in the ETD you have attempted to upload. We cannot accept this submission.")
            else:
                messages.error(request, "Your submission failed to process for an unknown reason. Contact the help desk or try again.")
        else:
            messages.error(request, "There were errors in your submission. Correct them and try again.")
Ejemplo n.º 26
0
def extra(request, provider):
    """
        Handle registration of new user with extra data for profile
    """
    identity = request.session.get('identity', None)
    if not identity:
        raise Http404

    if request.method == "POST":
        form = str_to_class(netauth_settings.EXTRA_FORM)(request.POST)
        if form.is_valid():
            user = form.save(request, identity, provider)
            del request.session['identity']
            if not netauth_settings.ACTIVATION_REQUIRED:
                user = auth.authenticate(identity=identity, provider=provider)
                if user:
                    auth.login(request, user)
                    return redirect(request.session.pop('next_url', netauth_settings.LOGIN_REDIRECT_URL))
            else:
                messages.warning(request, lang.ACTIVATION_REQUIRED_TEXT)
                return redirect(netauth_settings.ACTIVATION_REDIRECT_URL)
    else:
        initial = request.session['extra']
        form = str_to_class(netauth_settings.EXTRA_FORM)(initial=initial)

    return render_to_response('netauth/extra.html', {'form': form }, context_instance=RequestContext(request))
Ejemplo n.º 27
0
def submission_detail(request, id):
    """Details for a single submission."""
    if not request.user.is_authenticated():
        messages.warning(request, "You must log in to view this page.")
        return redirect('/login')
    if not request.user.is_staff:
        messages.warning(request, "Forbidden.")
        raise PermissionDenied

    storage_path = os.path.abspath(settings.ETD_STORAGE_DIRECTORY)
    json_path = os.path.join(storage_path, id, 'data', 'form.json')
    if os.path.isfile(json_path):
        # Load JSON
        with open(json_path, 'r') as json_file:
            json_dict = json.load(json_file)

        # Get bag tag files
        info_path = os.path.join(storage_path, id, 'bag-info.txt')
        with open(info_path, 'r') as info_file:
            info_string = info_file.read()
        manifest_path = os.path.join(storage_path, id, 'manifest-md5.txt')
        with open(manifest_path, 'r') as manifest_file:
            manifest_string = manifest_file.read()

        context = DefaultContext(request)
        context['title'] = "Submission Details"
        context['submission_id'] = id
        context['submission'] = json_dict
        context['bag_info'] = info_string
        context['bag_manifest'] = manifest_string
        return render(request, 'etd_drop_app/submission_detail.html', context)
    else:
        raise Http404
Ejemplo n.º 28
0
 def form_invalid(self, forms):
     """Method to display a message on invalid form submissions"""
     messages.warning(
         self.request,
         'Please check that required fields are filled out correctly.'
     )
     return super(GroupCreateView, self).form_invalid(forms)
Ejemplo n.º 29
0
    def f(*args, **kwargs):
        request = args[0]
        if request.user.is_staff:
            return view(*args, **kwargs)

        if require is None:
            # if no requirements, then limit to staff
            if request.user.is_staff:
                return view(*args, **kwargs)
        else:
            # check for anon users:
            # this hsould not be neccessary, but it works...
            if not request.user.is_authenticated:
                redirect_url = settings.LOGIN_URL + '?next=' + quote(request.get_full_path())
                return redirect(redirect_url)
            # check approval status:
            if not request.user.profile.approved:
                return redirect(reverse('not_approved'))
            # check user has required permissions
            tested_perms = [request.user.profile.__getattribute__(x) for x in require]
            if all(tested_perms):
                return view(*args, **kwargs)

        messages.warning(request, settings.NO_ACCESS_WARNING)
        return redirect('/')
Ejemplo n.º 30
0
def add_slack_btn(request):
    code = request.GET.get("code", "")
    if len(code) < 8:
        return HttpResponseBadRequest()

    result = requests.post("https://slack.com/api/oauth.access", {
        "client_id": settings.SLACK_CLIENT_ID,
        "client_secret": settings.SLACK_CLIENT_SECRET,
        "code": code
    })

    doc = result.json()
    if doc.get("ok"):
        channel = Channel()
        channel.user = request.team.user
        channel.kind = "slack"
        channel.value = result.text
        channel.save()
        channel.assign_all_checks()
        messages.success(request, "The Slack integration has been added!")
    else:
        s = doc.get("error")
        messages.warning(request, "Error message from slack: %s" % s)

    return redirect("hc-channels")
def listar(request, hash):
    for_print = 0
    db_slug = 'default'
    try:
        usuario_id = request.session['usuario_id']
        dict_hash = get_hash_url(hash)
        #retorno_pagina = dict_hash['retorno_pagina']
        #retorno_hash = dict_hash['retorno_hash']
        #s1060_alteracao_novavalidade_id = int(dict_hash['id'])
        for_print = int(dict_hash['print'])
    except:
        usuario_id = False
        return redirect('login')
    usuario = get_object_or_404(Usuarios.objects.using(db_slug),
                                excluido=False,
                                id=usuario_id)
    pagina = ConfigPaginas.objects.using(db_slug).get(
        excluido=False, endereco='s1060_alteracao_novavalidade')
    permissao = ConfigPermissoes.objects.using(db_slug).get(
        excluido=False,
        config_paginas=pagina,
        config_perfis=usuario.config_perfis)
    dict_permissoes = json_to_dict(usuario.config_perfis.permissoes)
    paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas
    modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos

    if permissao.permite_listar:
        filtrar = False
        dict_fields = {}
        show_fields = {
            'show_excluido': 0,
            'show_modificado_por': 0,
            'show_modificado_em': 0,
            'show_criado_por': 0,
            'show_criado_em': 0,
            'show_fimvalid': 0,
            'show_inivalid': 1,
            'show_s1060_alteracao': 1,
        }
        post = False
        if request.method == 'POST':
            post = True
            dict_fields = {
                'fimvalid__icontains': 'fimvalid__icontains',
                'inivalid__icontains': 'inivalid__icontains',
                's1060_alteracao': 's1060_alteracao',
            }
            for a in dict_fields:
                dict_fields[a] = request.POST.get(a or None)
            for a in show_fields:
                show_fields[a] = request.POST.get(a or None)
            if request.method == 'POST':
                dict_fields = {
                    'fimvalid__icontains': 'fimvalid__icontains',
                    'inivalid__icontains': 'inivalid__icontains',
                    's1060_alteracao': 's1060_alteracao',
                }
                for a in dict_fields:
                    dict_fields[a] = request.POST.get(dict_fields[a] or None)
        dict_qs = clear_dict_fields(dict_fields)
        s1060_alteracao_novavalidade_lista = s1060alteracaonovaValidade.objects.using(
            db_slug).filter(**dict_qs).filter(excluido=False).exclude(
                id=0).all()
        if not post and len(s1060_alteracao_novavalidade_lista) > 100:
            filtrar = True
            s1060_alteracao_novavalidade_lista = None
            messages.warning(
                request,
                'Listagem com mais de 100 resultados! Filtre os resultados um melhor desempenho!'
            )

        #s1060_alteracao_novavalidade_listar_custom
        request.session["retorno_hash"] = hash
        request.session["retorno_pagina"] = 's1060_alteracao_novavalidade'
        context = {
            's1060_alteracao_novavalidade_lista':
            s1060_alteracao_novavalidade_lista,
            'usuario': usuario,
            'modulos_permitidos_lista': modulos_permitidos_lista,
            'paginas_permitidas_lista': paginas_permitidas_lista,
            'permissao': permissao,
            'dict_fields': dict_fields,
            'data': datetime.datetime.now(),
            'pagina': pagina,
            'dict_permissoes': dict_permissoes,
            'show_fields': show_fields,
            'for_print': for_print,
            'hash': hash,
            'filtrar': filtrar,
        }
        return render(request, 's1060_alteracao_novavalidade_listar.html',
                      context)
    else:
        context = {
            'usuario': usuario,
            'modulos_permitidos_lista': modulos_permitidos_lista,
            'paginas_permitidas_lista': paginas_permitidas_lista,
            'permissao': permissao,
            'data': datetime.datetime.now(),
            'pagina': pagina,
            'dict_permissoes': dict_permissoes,
        }
        return render(request, 'permissao_negada.html', context)
Ejemplo n.º 32
0
def listar(request, hash):
    for_print = 0
    db_slug = 'default'
    try:
        usuario_id = request.user.id
        dict_hash = get_hash_url(hash)
        #retorno_pagina = dict_hash['retorno_pagina']
        #retorno_hash = dict_hash['retorno_hash']
        #s1030_inclusao_id = int(dict_hash['id'])
        for_print = int(dict_hash['print'])
    except:
        usuario_id = False
        return redirect('login')
    usuario = get_object_or_404(Usuarios.objects.using(db_slug),
                                excluido=False,
                                id=usuario_id)
    pagina = ConfigPaginas.objects.using(db_slug).get(
        excluido=False, endereco='s1030_inclusao')
    permissao = ConfigPermissoes.objects.using(db_slug).get(
        excluido=False,
        config_paginas=pagina,
        config_perfis=usuario.config_perfis)
    dict_permissoes = json_to_dict(usuario.config_perfis.permissoes)
    paginas_permitidas_lista = usuario.config_perfis.paginas_permitidas
    modulos_permitidos_lista = usuario.config_perfis.modulos_permitidos

    if permissao.permite_listar:
        filtrar = False
        dict_fields = {}
        show_fields = {
            'show_codcargo': 1,
            'show_codcbo': 1,
            'show_dadoscargo': 0,
            'show_fimvalid': 0,
            'show_idecargo': 0,
            'show_inivalid': 1,
            'show_nmcargo': 1,
            'show_s1030_evttabcargo': 1,
        }
        post = False
        if request.method == 'POST':
            post = True
            dict_fields = {
                'codcargo__icontains': 'codcargo__icontains',
                'codcbo__icontains': 'codcbo__icontains',
                'dadoscargo': 'dadoscargo',
                'fimvalid__icontains': 'fimvalid__icontains',
                'idecargo': 'idecargo',
                'inivalid__icontains': 'inivalid__icontains',
                'nmcargo__icontains': 'nmcargo__icontains',
                's1030_evttabcargo': 's1030_evttabcargo',
            }
            for a in dict_fields:
                dict_fields[a] = request.POST.get(a or None)
            for a in show_fields:
                show_fields[a] = request.POST.get(a or None)
            if request.method == 'POST':
                dict_fields = {
                    'codcargo__icontains': 'codcargo__icontains',
                    'codcbo__icontains': 'codcbo__icontains',
                    'dadoscargo': 'dadoscargo',
                    'fimvalid__icontains': 'fimvalid__icontains',
                    'idecargo': 'idecargo',
                    'inivalid__icontains': 'inivalid__icontains',
                    'nmcargo__icontains': 'nmcargo__icontains',
                    's1030_evttabcargo': 's1030_evttabcargo',
                }
                for a in dict_fields:
                    dict_fields[a] = request.POST.get(dict_fields[a] or None)
        dict_qs = clear_dict_fields(dict_fields)
        s1030_inclusao_lista = s1030inclusao.objects.using(db_slug).filter(
            **dict_qs).filter(excluido=False).exclude(id=0).all()
        if not post and len(s1030_inclusao_lista) > 100:
            filtrar = True
            s1030_inclusao_lista = None
            messages.warning(
                request,
                'Listagem com mais de 100 resultados! Filtre os resultados um melhor desempenho!'
            )

        #s1030_inclusao_listar_custom
        request.session["retorno_hash"] = hash
        request.session["retorno_pagina"] = 's1030_inclusao'
        context = {
            's1030_inclusao_lista': s1030_inclusao_lista,
            'usuario': usuario,
            'modulos_permitidos_lista': modulos_permitidos_lista,
            'paginas_permitidas_lista': paginas_permitidas_lista,
            'permissao': permissao,
            'dict_fields': dict_fields,
            'data': datetime.datetime.now(),
            'pagina': pagina,
            'dict_permissoes': dict_permissoes,
            'show_fields': show_fields,
            'for_print': for_print,
            'hash': hash,
            'filtrar': filtrar,
        }
        if for_print in (0, 1):
            return render(request, 's1030_inclusao_listar.html', context)
        elif for_print == 2:
            #return render_to_pdf('tables/s1000_evtinfoempregador_pdf_xls.html', context)
            from wkhtmltopdf.views import PDFTemplateResponse
            response = PDFTemplateResponse(
                request=request,
                template='s1030_inclusao_listar.html',
                filename="s1030_inclusao.pdf",
                context=context,
                show_content_in_browser=True,
                cmd_options={
                    'margin-top': 10,
                    'margin-bottom': 10,
                    'margin-right': 10,
                    'margin-left': 10,
                    'zoom': 1,
                    'dpi': 72,
                    'orientation': 'Landscape',
                    "viewport-size": "1366 x 513",
                    'javascript-delay': 1000,
                    'footer-center': '[page]/[topage]',
                    "no-stop-slow-scripts": True
                },
            )
            return response
        elif for_print == 3:
            from django.shortcuts import render_to_response
            response = render_to_response('s1030_inclusao_listar.html',
                                          context)
            filename = "s1030_inclusao.xls"
            response[
                'Content-Disposition'] = 'attachment; filename=' + filename
            response[
                'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8'
            return response
        elif for_print == 4:
            from django.shortcuts import render_to_response
            response = render_to_response('tables/s1030_inclusao_csv.html',
                                          context)
            filename = "s1030_inclusao.csv"
            response[
                'Content-Disposition'] = 'attachment; filename=' + filename
            response['Content-Type'] = 'text/csv; charset=UTF-8'
            return response
    else:
        context = {
            'usuario': usuario,
            'modulos_permitidos_lista': modulos_permitidos_lista,
            'paginas_permitidas_lista': paginas_permitidas_lista,
            'permissao': permissao,
            'data': datetime.datetime.now(),
            'pagina': pagina,
            'dict_permissoes': dict_permissoes,
        }
        return render(request, 'permissao_negada.html', context)
Ejemplo n.º 33
0
def send_xml(request, transmissor_id, service):

    import os
    from datetime import datetime
    from emensageriapro.settings import BASE_DIR
    from emensageriapro.mensageiro.functions.funcoes import ler_arquivo, \
        get_transmissor_name, create_pem_files, send, gravar_nome_arquivo, create_folders

    CA_CERT_PEM_FILE = config.EFDREINF_CA_CERT_PEM_FILE
    TP_AMB = config.EFDREINF_TP_AMB

    create_folders()

    data_atual = str(datetime.now()).replace(':', '-').replace(' ',
                                                               '-').replace(
                                                                   '.', '-')

    if TP_AMB == '1':  # Produção

        if service == 'RecepcaoLoteReinf':

            URL = "https://reinf.receita.fazenda.gov.br/WsREINF/RecepcaoLoteReinf.svc"
            ACTION = "http://sped.fazenda.gov.br/RecepcaoLoteReinf/ReceberLoteEventos"

        elif service == 'ConsultasReinf':

            URL = "https://reinf.receita.fazenda.gov.br/WsReinfConsultas/ConsultasReinf.svc"
            ACTION = "http://sped.fazenda.gov.br/ConsultasReinf/ConsultaInformacoesConsolidadas"

    elif TP_AMB == '2':  # Produção-Restrita

        if service == 'RecepcaoLoteReinf':

            URL = "https://preprodefdreinf.receita.fazenda.gov.br/wsreinf/RecepcaoLoteReinf.svc"
            ACTION = "http://sped.fazenda.gov.br/RecepcaoLoteReinf/ReceberLoteEventos"

        elif service == 'ConsultasReinf':

            URL = "https://preprodefdreinf.receita.fazenda.gov.br/WsReinfConsultas/ConsultasReinf.svc"
            ACTION = "http://sped.fazenda.gov.br/ConsultasReinf/ConsultaReciboEvento1000"

    tra = TransmissorLoteEfdreinf.objects.\
            get(id=transmissor_id)

    if tra.transmissor:

        if tra.transmissor.certificado:

            cert_host = '%s/certificado/%s' % (
                BASE_DIR, tra.transmissor.certificado.certificado)
            cert_pass = tra.transmissor.certificado.senha
            cert_pem_file = '/certificado/cert_%s.pem' % tra.transmissor.certificado.id
            key_pem_file = '/certificado/key_%s.pem' % tra.transmissor.certificado.id

            create_pem_files(cert_host, cert_pass, cert_pem_file, key_pem_file)

        else:

            messages.error(
                request,
                'O certificado não está configurado ou não possuem eventos validados para envio neste lote!'
            )

            return None

    else:

        messages.error(request, 'O Transmissor não está configurado!')
        return None

    dados = {}
    dados['contribuinte_tpinsc'] = tra.contribuinte_tpinsc
    dados['contribuinte_nrinsc'] = retirar_pontuacao_cpf_cnpj(
        tra.contribuinte_nrinsc)
    dados['transmissor_id'] = transmissor_id
    dados['efdreinf_lote_min'] = config.EFDREINF_LOTE_MIN
    dados['efdreinf_lote_max'] = config.EFDREINF_LOTE_MIN
    dados['efdreinf_timeout'] = int(config.EFDREINF_TIMEOUT)

    name = get_transmissor_name(transmissor_id)

    dados['transmissor_id'] = transmissor_id
    dados['header'] = '/arquivos/Comunicacao/%s/header/%s_%s.txt' % (
        service, name, data_atual)
    dados['request'] = '/arquivos/Comunicacao/%s/request/%s_%s.xml' % (
        service, name, data_atual)
    dados['response'] = '/arquivos/Comunicacao/%s/response/%s_%s.xml' % (
        service, name, data_atual)
    dados[
        'header_completo'] = '%s/arquivos/Comunicacao/%s/header/%s_%s.txt' % (
            BASE_DIR, service, name, data_atual)
    dados[
        'request_completo'] = '%s/arquivos/Comunicacao/%s/request/%s_%s.xml' % (
            BASE_DIR, service, name, data_atual)
    dados[
        'response_completo'] = '%s/arquivos/Comunicacao/%s/response/%s_%s.xml' % (
            BASE_DIR, service, name, data_atual)
    dados['service'] = service
    dados['url'] = URL
    dados['cert'] = BASE_DIR + cert_pem_file
    dados['cacert'] = BASE_DIR + CA_CERT_PEM_FILE
    dados['key'] = BASE_DIR + key_pem_file
    dados['action'] = ACTION
    dados['timeout'] = dados['efdreinf_timeout']

    quant_eventos = TransmissorEventosEfdreinf.objects. \
        filter(transmissor_lote_efdreinf_id=transmissor_id,
               status=STATUS_EVENTO_AGUARD_ENVIO).count()

    if tra.transmissor.certificado and (quant_eventos
                                        or service == 'ConsultasReinf'):

        if (quant_eventos >= dados['efdreinf_lote_min'] and \
                quant_eventos <= dados['efdreinf_lote_max'] and \
                service == 'RecepcaoLoteReinf') or service == 'ConsultasReinf':

            create_request(dados)
            send(dados)
            gravar_nome_arquivo(dados['header'], 0)
            gravar_nome_arquivo(dados['request'], 0)
            gravar_nome_arquivo(dados['response'], 0)

            if not os.path.isfile(BASE_DIR + dados['response']):

                messages.error(
                    request, '''O servidor demorou mais que o esperado 
                    para efetuar a conexão! Caso necessário solicite ao 
                    administrador do sistema para que aumente o tempo do 
                    Timeout. Timeout atual %(timeout)s''' % dados)

                return None

            elif 'HTTP/1.1 200 OK' not in ler_arquivo(dados['header']):

                messages.warning(
                    request,
                    'Retorno do servidor: ' + ler_arquivo(dados['header']))

            elif service == 'RecepcaoLoteReinf':

                from emensageriapro.mensageiro.functions.funcoes_efdreinf_comunicacao import read_envioLoteEventos

                retorno = read_envioLoteEventos(request, dados['response'],
                                                transmissor_id)
                messages.success(request, 'Lote enviado com sucesso!')

            elif service == 'ConsultasReinf':

                from emensageriapro.mensageiro.functions.funcoes_efdreinf_comunicacao import read_consultaLoteEventos

                retorno = read_consultaLoteEventos(request, dados['response'],
                                                   transmissor_id)
                messages.success(request, 'Lote consultado com sucesso!')

        elif quant_eventos < dados[
                'efdreinf_lote_min'] and service == 'RecepcaoLoteReinf':

            messages.error(request,
                           'Lote com quantidade inferior a mínima permitida!')

            TransmissorLoteEfdreinf.objects.\
                filter(id=transmissor_id).\
                update(status=TRANSMISSOR_STATUS_CADASTRADO)

        elif quant_eventos > dados[
                'efdreinf_lote_max'] and service == 'RecepcaoLoteReinf':

            messages.error(
                request,
                'Lote com quantidade de eventos superior a máxima permitida!')

            TransmissorLoteEfdreinf.objects.\
                filter(id=transmissor_id).\
                update(status=TRANSMISSOR_STATUS_CADASTRADO)

        else:

            messages.error(request, 'Erro ao enviar o lote!')

            if service == 'RecepcaoLoteReinf':

                TransmissorLoteEfdreinf.objects.\
                    filter(id=transmissor_id).\
                    update(status=TRANSMISSOR_STATUS_ENVIADO_ERRO)

            elif service == 'ConsultasReinf':

                TransmissorLoteEfdreinf.objects.\
                    filter(id=transmissor_id).\
                    update(status=TRANSMISSOR_STATUS_CONSULTADO_ERRO)

    else:

        messages.error(
            request,
            'O certificado não está configurado ou não possuem eventos validados para envio neste lote!'
        )
Ejemplo n.º 34
0
def listar(request, output=None):

    if request.user.has_perm('esocial.can_see_s1210evtPgtos'):

        filtrar = False
        dict_fields = {}
        show_fields = {
            'show_esocial': 0,
            'show_evtpgtos': 0,
            'show_identidade': 1,
            'show_ideevento': 0,
            'show_indretif': 1,
            'show_nrrecibo': 0,
            'show_indapuracao': 1,
            'show_perapur': 0,
            'show_tpamb': 0,
            'show_procemi': 0,
            'show_verproc': 0,
            'show_ideempregador': 0,
            'show_tpinsc': 0,
            'show_nrinsc': 0,
            'show_idebenef': 0,
            'show_cpfbenef': 0,
            'show_versao': 0,
            'show_transmissor_lote_esocial': 0,
            'show_retornos_eventos': 0,
            'show_ocorrencias': 0,
            'show_validacao_precedencia': 0,
            'show_validacoes': 0,
            'show_arquivo_original': 0,
            'show_arquivo': 0,
            'show_status': 1,
            'show_retornos_s5002': 0,
            'show_transmissor_lote_esocial_error': 0,
        }

        post = False

        if request.method == 'POST':

            post = True
            dict_fields = {
                'esocial': 'esocial',
                'evtpgtos': 'evtpgtos',
                'identidade__icontains': 'identidade__icontains',
                'ideevento': 'ideevento',
                'indretif__icontains': 'indretif__icontains',
                'nrrecibo__icontains': 'nrrecibo__icontains',
                'indapuracao__icontains': 'indapuracao__icontains',
                'perapur__icontains': 'perapur__icontains',
                'tpamb__icontains': 'tpamb__icontains',
                'procemi__icontains': 'procemi__icontains',
                'verproc__icontains': 'verproc__icontains',
                'ideempregador': 'ideempregador',
                'tpinsc__icontains': 'tpinsc__icontains',
                'nrinsc__icontains': 'nrinsc__icontains',
                'idebenef': 'idebenef',
                'cpfbenef__icontains': 'cpfbenef__icontains',
                'versao__icontains': 'versao__icontains',
                'transmissor_lote_esocial__icontains':
                'transmissor_lote_esocial__icontains',
                'status__icontains': 'status__icontains',
            }

            for a in dict_fields:
                dict_fields[a] = request.POST.get(a or None)

            for a in show_fields:
                show_fields[a] = request.POST.get(a or None)

            if request.method == 'POST':
                dict_fields = {
                    'esocial': 'esocial',
                    'evtpgtos': 'evtpgtos',
                    'identidade__icontains': 'identidade__icontains',
                    'ideevento': 'ideevento',
                    'indretif__icontains': 'indretif__icontains',
                    'nrrecibo__icontains': 'nrrecibo__icontains',
                    'indapuracao__icontains': 'indapuracao__icontains',
                    'perapur__icontains': 'perapur__icontains',
                    'tpamb__icontains': 'tpamb__icontains',
                    'procemi__icontains': 'procemi__icontains',
                    'verproc__icontains': 'verproc__icontains',
                    'ideempregador': 'ideempregador',
                    'tpinsc__icontains': 'tpinsc__icontains',
                    'nrinsc__icontains': 'nrinsc__icontains',
                    'idebenef': 'idebenef',
                    'cpfbenef__icontains': 'cpfbenef__icontains',
                    'versao__icontains': 'versao__icontains',
                    'transmissor_lote_esocial__icontains':
                    'transmissor_lote_esocial__icontains',
                    'status__icontains': 'status__icontains',
                }
                for a in dict_fields:
                    dict_fields[a] = request.POST.get(dict_fields[a] or None)

        dict_qs = clear_dict_fields(dict_fields)
        s1210_evtpgtos_lista = s1210evtPgtos.objects.filter(
            **dict_qs).filter().exclude(id=0).all()

        if not post and len(s1210_evtpgtos_lista) > 100:
            filtrar = True
            s1210_evtpgtos_lista = None
            messages.warning(
                request,
                u'Listagem com mais de 100 resultados! Filtre os resultados um melhor desempenho!'
            )

        #[VARIAVEIS_LISTA_FILTRO_RELATORIO]
        #s1210_evtpgtos_listar_custom

        request.session['return'] = request.META.get('HTTP_REFERER')

        context = {
            'usuario': Usuarios.objects.get(user_id=request.user.id),
            'output': output,
            's1210_evtpgtos_lista': s1210_evtpgtos_lista,
            'dict_fields': dict_fields,
            'data': datetime.datetime.now(),
            'modulos': [
                'esocial',
            ],
            'paginas': [
                's1210_evtpgtos',
            ],
            'show_fields': show_fields,
            'filtrar': filtrar,
            #[VARIAVEIS_FILTRO_RELATORIO]
        }

        if output == 'pdf':

            from emensageriapro.functions import render_to_pdf
            from wkhtmltopdf.views import PDFTemplateResponse

            response = PDFTemplateResponse(
                request=request,
                template='s1210_evtpgtos_listar.html',
                filename="s1210_evtpgtos.pdf",
                context=context,
                show_content_in_browser=True,
                cmd_options={
                    'margin-top': 10,
                    'margin-bottom': 10,
                    'margin-right': 10,
                    'margin-left': 10,
                    'zoom': 1,
                    'dpi': 72,
                    'orientation': 'Landscape',
                    'viewport-size': "1366 x 513",
                    'javascript-delay': 1000,
                    'footer-center': '[page]/[topage]',
                    "no-stop-slow-scripts": True
                },
            )
            return response

        elif output == 'xls':

            response = render_to_response('s1210_evtpgtos_listar.html',
                                          context)
            filename = "s1210_evtpgtos.xls"
            response[
                'Content-Disposition'] = 'attachment; filename=' + filename
            response[
                'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8'

            return response

        elif output == 'csv':

            response = render_to_response('csv/s1210_evtpgtos.csv', context)
            filename = "s1210_evtpgtos.csv"
            response[
                'Content-Disposition'] = 'attachment; filename=' + filename
            response['Content-Type'] = 'text/csv; charset=UTF-8'

            return response

        else:

            return render(request, 's1210_evtpgtos_listar.html', context)

    else:

        context = {
            'usuario': Usuarios.objects.get(user_id=request.user.id),
            'data': datetime.datetime.now(),
            'modulos': [
                'esocial',
            ],
            'paginas': [
                's1210_evtpgtos',
            ],
        }
        return render(request, 'permissao_negada.html', context)
def listar(request, output=None):

    if request.user.has_perm('s2200.can_see_s2200horContratual'):

        filtrar = False

        dict_fields = {}
        show_fields = {
            'show_s2200_evtadmissao': 1,
            'show_qtdhrssem': 0,
            'show_tpjornada': 1,
            'show_dsctpjorn': 0,
            'show_tmpparc': 1,
        }

        post = False

        if request.method == 'POST':

            post = True
            dict_fields = {
                's2200_evtadmissao__icontains': 's2200_evtadmissao__icontains',
                'qtdhrssem__icontains': 'qtdhrssem__icontains',
                'tpjornada__icontains': 'tpjornada__icontains',
                'dsctpjorn__icontains': 'dsctpjorn__icontains',
                'tmpparc__icontains': 'tmpparc__icontains',
            }

            for a in dict_fields:

                dict_fields[a] = request.POST.get(a or None)

            for a in show_fields:

                show_fields[a] = request.POST.get(a or None)

            if request.method == 'POST':

                dict_fields = {
                    's2200_evtadmissao__icontains':
                    's2200_evtadmissao__icontains',
                    'qtdhrssem__icontains': 'qtdhrssem__icontains',
                    'tpjornada__icontains': 'tpjornada__icontains',
                    'dsctpjorn__icontains': 'dsctpjorn__icontains',
                    'tmpparc__icontains': 'tmpparc__icontains',
                }

                for a in dict_fields:
                    dict_fields[a] = request.POST.get(dict_fields[a] or None)

        dict_qs = clear_dict_fields(dict_fields)
        s2200_horcontratual_lista = s2200horContratual.objects.filter(
            **dict_qs).filter().exclude(id=0).all()

        if not post and len(s2200_horcontratual_lista) > 100:

            filtrar = True
            s2200_horcontratual_lista = None
            messages.warning(
                request,
                u'Listagem com mais de 100 resultados! Filtre os resultados um melhor desempenho!'
            )

        s2200_evtadmissao_lista = s2200evtAdmissao.objects.all()
        #s2200_horcontratual_listar_custom

        request.session['return'] = request.META.get('HTTP_REFERER')

        context = {
            'usuario': Usuarios.objects.get(user_id=request.user.id),
            'output': output,
            's2200_horcontratual_lista': s2200_horcontratual_lista,
            'modulos': [
                's2200',
            ],
            'paginas': [
                's2200_horcontratual',
            ],
            'dict_fields': dict_fields,
            'data': datetime.datetime.now(),
            'show_fields': show_fields,
            'filtrar': filtrar,
            's2200_evtadmissao_lista': s2200_evtadmissao_lista,
        }

        if output == 'pdf':

            from wkhtmltopdf.views import PDFTemplateResponse

            response = PDFTemplateResponse(
                request=request,
                template='s2200_horcontratual_listar.html',
                filename="s2200_horcontratual.pdf",
                context=context,
                show_content_in_browser=True,
                cmd_options={
                    'margin-top': 10,
                    'margin-bottom': 10,
                    'margin-right': 10,
                    'margin-left': 10,
                    'zoom': 1,
                    'dpi': 72,
                    'orientation': 'Landscape',
                    "viewport-size": "1366 x 513",
                    'javascript-delay': 1000,
                    'footer-center': '[page]/[topage]',
                    "no-stop-slow-scripts": True
                },
            )

            return response

        elif output == 'xls':

            from django.shortcuts import render_to_response
            response = render_to_response('s2200_horcontratual_listar.html',
                                          context)
            filename = "s2200_horcontratual.xls"
            response[
                'Content-Disposition'] = 'attachment; filename=' + filename
            response[
                'Content-Type'] = 'application/vnd.ms-excel; charset=UTF-8'
            return response

        elif output == 'csv':

            from django.shortcuts import render_to_response
            response = render_to_response('csv/s2200_horcontratual.csv',
                                          context)
            filename = "s2200_horcontratual.csv"
            response[
                'Content-Disposition'] = 'attachment; filename=' + filename
            response['Content-Type'] = 'text/csv; charset=UTF-8'
            return response

        else:

            return render(request, 's2200_horcontratual_listar.html', context)

    else:

        context = {
            'usuario': Usuarios.objects.get(user_id=request.user.id),
            'output': output,
            'data': datetime.datetime.now(),
            'modulos': [
                's2200',
            ],
            'paginas': [
                's2200_horcontratual',
            ],
        }

        return render(request, 'permissao_negada.html', context)
Ejemplo n.º 36
0
def last_changed_incident(request):
    last_incident = Incident.objects.all().order_by('-updated').first()
    if last_incident:
        return redirect(reverse('incident', args=[last_incident.pk]))
    messages.warning(request, 'Инцидентов еще нет')
    return redirect(reverse('ins'))
Ejemplo n.º 37
0
def incident_view(request, incident_id):
    context = {'app': 'ins'}
    incident = get_object_or_404(Incident, pk=incident_id)
    context['incident'] = incident

    impact_time, text_parsed = incident.parse_intervals(incident.fiber)
    context['impact_time'] = impact_time
    context['text_parsed'] = text_parsed

    tab = request.GET.get('tab', 'services')
    context['tab'] = tab

    notifications = Notification.objects.filter(
        incident=incident).order_by('-date_added')
    notification_form = NotificationForm(incident=incident)
    context['notifications'] = notifications
    context['notification_form'] = notification_form

    context['warnings'] = incident.warnings()

    if request.POST:
        action = request.POST.get('action')

        if action == 'delete_service':
            service_id = request.POST.get('service_id')
            service = common_models.Service.objects.get(pk=service_id)
            incident.services.remove(service)
            url = reverse(incident_view, args=[incident.pk])
            url += '?tab=%s' % tab
            return redirect(url)

        if action == 'delete_subservice':
            subservice_id = request.POST.get('subservice_id')
            subservice = get_object_or_404(incident.subservices,
                                           pk=subservice_id)
            incident.subservices.remove(subservice)
            url = reverse(incident_view, args=[incident.pk])
            url += '?tab=%s' % tab
            return redirect(url)

        if action == 'copy_ins':

            copy_clients = request.POST.get('copy_clients')
            copy_services = request.POST.get('copy_services')
            copy_subservices = request.POST.get('copy_subservices')
            copy_leases = request.POST.get('copy_leases')

            clients = incident.clients.all()
            services = incident.services.all()
            subservices = incident.subservices.all()
            leases = incident.leases.all()

            incident.pk = None
            incident.creator = request.user.profile
            incident.save()

            if copy_clients:
                for client in clients:
                    incident.clients.add(client)

            if copy_services:
                for service in services:
                    incident.services.add(service)

            if copy_subservices:
                for subservice in subservices:
                    incident.subservices.add(subservice)

            if copy_leases:
                for lease in leases:
                    incident.leases.add(lease)

            messages.add_message(request, messages.SUCCESS,
                                 'Инцидент скопирован')
            return redirect(incident_view, incident_id=incident.pk)

        if action == 'delete_client':
            client_id = request.POST.get('client_id')
            client = get_object_or_404(Client, pk=client_id)
            incident.clients.remove(client)
            url = reverse(incident_view, args=[incident.pk])
            url += '?tab=%s' % tab
            return redirect(url)

        if action == 'delete_lease':
            lease_id = request.POST.get('lease_id')
            lease = get_object_or_404(common_models.Lease, pk=lease_id)
            incident.leases.remove(lease)
            url = reverse(incident_view, args=[incident.pk])
            url += '?tab=%s' % tab
            return redirect(url)

        if action == 'delete_incident':
            Spy().log(object=incident,
                      form=None,
                      user=request.user,
                      action=Spy.DELETE)
            incident.delete()
            messages.add_message(request, messages.SUCCESS, 'INS удален')
            return redirect(reverse('ins'))

        if action == 'get_services_from_leases':
            services = Service.objects \
                .filter(lease__in=incident.leases.all()) \
                .exclude(pk__in=incident.services.all()) \
                .distinct()
            if services:
                for service in services:
                    incident.services.add(service)
                messages.success(
                    request,
                    'Услуги успешно добавлены [%s]' % services.count())
            else:
                if incident.services.count():
                    messages.success(
                        request, 'Услуг, кроме уже добалвенных, не обнаружено')
                else:
                    messages.warning(request, 'Услуг не обнаружено')
            url = reverse(incident_view, args=[incident.pk])
            url += '?tab=%s' % tab
            return redirect(url)

        if action == 'get_subservices_from_leases':
            subservices = common_models.SubService.objects.filter(
                leases__in=incident.leases.all()).exclude(
                    pk__in=incident.subservices.all()).distinct()

            if subservices:
                for subservice in subservices:
                    incident.subservices.add(subservice)
                messages.success(
                    request,
                    'Услуги успешно добавлены [%s]' % subservices.count())
            else:
                messages.warning(request, 'Услуг не обнаружено')

            url = reverse(incident_view, args=[incident.pk])
            url += '?tab=%s' % tab
            return redirect(url)

        if action == 'disturb_provider':
            subject = request.POST.get('subject')
            message = request.POST.get('message')
            email = request.POST.get('email')

            try:
                tracker = Rt()
            except Rt.LoginError as e:
                messages.add_message(request, messages.ERROR, e)
                return redirect(incident_view, incident_id=incident.pk)

            ticket_id = tracker.create_ticket(Subject=subject,
                                              Requestors=email)
            if request.user.profile.email:
                tracker.edit_ticket(ticket_id,
                                    AdminCc=request.user.profile.email,
                                    CF_ins=str(incident.pk))

            if message:
                tracker.reply(ticket_id, text=message)

            incident.ticket = ticket_id
            incident.save()
            messages.add_message(
                request, messages.SUCCESS,
                'Тикет RT#%s успешно создан и привязан к инциденту' %
                ticket_id)
            return redirect(incident_view, incident_id=incident.pk)

        if action == 'rt_fill_ins':

            if not incident.ticket:
                messages.warning(request, '#RT не указан в INS')
                return redirect(incident_view, incident_id=incident.pk)

            try:
                tracker = Rt()
            except Rt.LoginError as e:
                messages.add_message(request, messages.ERROR, e)
                return redirect(incident_view, incident_id=incident.pk)

            ticket = tracker.tracker.get_ticket(incident.ticket)

            ticket_changes = {}

            rt_ins = ticket.get('CF.{INS}')
            ins_id = str(incident.pk)

            rt_start = ticket.get('CF.{maintenance_start}')
            ins_start = incident.time_start.strftime('%Y-%m-%d %H:%M:%S')

            rt_end = ticket.get('CF.{maintenance_start}')
            ins_end = incident.time_end.strftime('%Y-%m-%d %H:%M:%S')

            # CF_ins
            if rt_ins:
                if ins_id != rt_ins:
                    ticket_changes['CF_ins'] = ins_id
            else:
                ticket_changes['CF_ins'] = ins_id

            # CF_maintenance_start
            ticket_changes['CF_maintenance_start'] = ins_start

            # CF_maintenance_end
            ticket_changes['CF_maintenance_end'] = ins_end

            tracker.edit_ticket(incident.ticket, **ticket_changes)
            messages.success(request, 'Тикет RT обновлен')
            return redirect(incident_view, incident_id=incident.pk)

        if action == 'add_notification':
            notification_form = NotificationForm(request.POST,
                                                 incident=incident)
            context['notification_form'] = notification_form
            if notification_form.is_valid():

                clients_count = incident.clients.count()
                services_count = incident.services.count()
                subservices_count = incident.subservices.count()
                message_text = notification_form.cleaned_data['text']

                # if no clients or services
                if not any([clients_count, services_count, subservices_count]):
                    messages.error(request, 'Не указаны клиенты или услуги')

                # clients and '%services%' in text
                if clients_count > 0 and Notification.SERVICES_TEMPLATE in message_text:
                    error_text = 'Нельзя отправить письма по клиентам: "%s" в тексте' % Notification.SERVICES_TEMPLATE
                    messages.error(request, error_text)
                    url = reverse(incident_view, args=[incident.pk])
                    url += '?tab=messages'
                    return redirect(url)

                notification_form.instance.who_added = request.user.profile
                notification = notification_form.save()
                notification.email_all()

                if incident.rt:
                    comment_text = 'Отправлено оповещение:\r\n\r\n--\r\n'
                    comment_text += notification.text
                    tracker = Rt()
                    tracker.comment(incident.rt, text=comment_text)

                messages.success(request, 'Уведомление добавлено')
                url = reverse(incident_view, args=[incident.pk])
                url += '?tab=messages'
                return redirect(url)

    logs = Spy.objects.filter(object_name='incident',
                              object_id=incident.pk).order_by('-time')
    context['logs'] = logs

    return render(request, 'bs3/ins/incident.html', context)
Ejemplo n.º 38
0
def parse_and_save_activity(req,
                            user,
                            section,
                            act,
                            new_course,
                            process_quiz_locally,
                            is_baseline=False):
    """
    Parses an Activity XML and saves it to the DB
    :param section: section the activity belongs to
    :param act: a XML DOM element containing a single activity
    :param new_course: boolean indicating if it is a new course or existed previously
    :param process_quiz_locally: should the quiz be created based on the JSON contents?
    :param is_baseline: is the activity part of the baseline?
    :return: None
    """
    temp_title = {}
    for t in act.getElementsByTagName("title"):
        temp_title[t.getAttribute('lang')] = t.firstChild.nodeValue
    title = json.dumps(temp_title)

    content = ""
    act_type = act.getAttribute("type")
    if act_type == "page" or act_type == "url":
        temp_content = {}
        for t in act.getElementsByTagName("location"):
            if t.firstChild and t.getAttribute('lang'):
                temp_content[t.getAttribute('lang')] = t.firstChild.nodeValue
        content = json.dumps(temp_content)
    elif act_type == "quiz" or act_type == "feedback":
        for c in act.getElementsByTagName("content"):
            content = c.firstChild.nodeValue
    elif act_type == "resource":
        for c in act.getElementsByTagName("location"):
            content = c.firstChild.nodeValue
    else:
        content = None

    image = None
    if act.getElementsByTagName("image"):
        for i in act.getElementsByTagName("image"):
            image = i.getAttribute('filename')

    if act.getElementsByTagName("description"):
        description = {}
        for d in act.getElementsByTagName("description"):
            if d.firstChild and d.getAttribute('lang'):
                description[d.getAttribute('lang')] = d.firstChild.nodeValue
        description = json.dumps(description)
    else:
        description = None

    digest = act.getAttribute("digest")
    existed = False
    try:
        activity = Activity.objects.get(digest=digest)
        existed = True
    except Activity.DoesNotExist:
        activity = Activity()

    activity.section = section
    activity.title = title
    activity.type = act_type
    activity.order = act.getAttribute("order")
    activity.digest = act.getAttribute("digest")
    activity.baseline = is_baseline
    activity.image = image
    activity.content = content
    activity.description = description

    if not existed and not new_course:
        messages.warning(
            req,
            _('Activity "%(act)s"(%(digest)s) did not exist previously.') % {
                'act': activity,
                'digest': activity.digest
            })
    '''
    If we also want to show the activities that previously existed, uncomment this block
    else:
        messages.info(req, _('Activity "%(act)s"(%(digest)s) previously existed. Updated with new information') % {'act': activity, 'digest':activity.digest})
    '''

    if (act_type == "quiz") and process_quiz_locally:
        updated_json = parse_and_save_quiz(req, user, activity, act)
        # we need to update the JSON contents both in the XML and in the activity data
        act.getElementsByTagName(
            "content")[0].firstChild.nodeValue = updated_json
        activity.content = updated_json

    activity.save()

    # save gamification events
    if act.getElementsByTagName('gamification')[:1]:
        events = parse_gamification_events(
            act.getElementsByTagName('gamification')[0])
        # remove anything existing for this course
        ActivityGamificationEvent.objects.filter(activity=activity).delete()
        # add new
        for event in events:
            e = ActivityGamificationEvent(user=user,
                                          activity=activity,
                                          event=event['name'],
                                          points=event['points'])
            e.save()
Ejemplo n.º 39
0
def register(request):

    if request.method == 'POST':
        # first_name = request.POST['first_name']
        # last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        # gender = request.POST['exampleRadios']
        # dateofbirth = request.POST['dob']
        password1 = request.POST['password1']
        password2 = request.POST['password2']
        # print(len(password1))

        if password1 == password2:
            if User.objects.filter(username=username).exists():
                messages.warning(request, 'USERNAME TAKEN')
                return redirect('register')

            elif User.objects.filter(email=email).exists():
                messages.warning(request, 'EMAIL TAKEN')
                return redirect('register')

            elif len(email) == 0:
                messages.warning(request, 'EMAIL MISSING')
                return redirect('register')

            # elif len(first_name) == 0:
            #     messages.warning(request,'FIRST NAME MISSING')
            #     return redirect('register')

            # elif len(last_name) == 0:
            #     messages.warning(request,'LAST NAME MISSING')
            #     return redirect('register')

            elif len(username) == 0:
                messages.warning(request, 'USER NAME MISSING')
                return redirect('register')

            elif len(password1) == 0:
                messages.warning(request, 'PASSWORD CANNOT BE EMPTY!!')
                return redirect('register')

            elif len(password1) < 6:
                messages.warning(request, 'PASSWORD IS lESS THAN 6 CHARACTERS')
                return redirect('register')

            else:
                user = User.objects.create_user(username=username,
                                                password=password1,
                                                email=email)
                # newextended = extended(name=username, dateofbirth=dateofbirth, gender=gender, user=user)
                # newextended.save()
                # obj = KirrURL(user = user)
                # obj.save()
                user.is_active = False
                user.save()

                #email sending
                uidb64 = urlsafe_base64_encode(force_bytes(user.pk))

                domain = get_current_site(request).domain
                link = reverse('activate',
                               kwargs={
                                   'uidb64': uidb64,
                                   'token': token_generator.make_token(user)
                               })

                activate_url = 'http://' + domain + link
                email_body = 'Hi ' + user.username + \
                    ' Please use this link to verfiy your account\n' + activate_url

                email_subject = 'Activate your account Kirr.co'

                email = EmailMessage(
                    email_subject,
                    email_body,
                    '*****@*****.**',
                    [email],
                )
                EmailThreading(email).start()
                messages.success(request, 'USER CREATED')
                return redirect('login')

        else:
            messages.warning(request, 'PASSWORD NOT MATCHING!!')
            return redirect('register')

        return redirect('/')

    else:
        return render(request, 'register.html')
Ejemplo n.º 40
0
def validar_evento_funcao(request, pk):

    from emensageriapro.padrao import executar_sql
    from emensageriapro.functions import get_versao_evento
    from emensageriapro.settings import BASE_DIR
    from emensageriapro.mensageiro.functions.funcoes_validacoes_precedencia import validar_precedencia
    from emensageriapro.mensageiro.functions.funcoes_validacoes import get_schema_name, validar_schema
    from emensageriapro.esocial.views.s1200_evtremun_gerar_xml import gerar_xml_assinado

    VERIFICAR_PREDECESSAO_ANTES_ENVIO = config.ESOCIAL_VERIFICAR_PREDECESSAO_ANTES_ENVIO

    lista_validacoes = []
    s1200_evtremun = get_object_or_404(s1200evtRemun, id=pk)

    if not s1200_evtremun.identidade:
        from emensageriapro.functions import identidade_evento
        ident = identidade_evento(s1200_evtremun, 'esocial')
        s1200_evtremun = get_object_or_404(s1200evtRemun, id=pk)

    #
    # Validações internas
    #

    arquivo = '/arquivos/Eventos/s1200_evtremun/%s.xml' % (
        s1200_evtremun.identidade)

    os.system('mkdir -p %s/arquivos/Eventos/s1200_evtremun/' % BASE_DIR)
    lista = []
    tipo = 'esocial'

    if not os.path.exists(BASE_DIR + arquivo):

        gerar_xml_assinado(request, pk)

    if os.path.exists(BASE_DIR + arquivo):

        from emensageriapro.esocial.views.s1200_evtremun_validar import validacoes_s1200_evtremun

        texto_xml = ler_arquivo(arquivo).replace("s:", "")
        versao = get_versao_evento(texto_xml)
        lista = validacoes_s1200_evtremun(arquivo)

    for a in lista:

        if a:

            lista_validacoes.append(a)

    #
    # validando schema
    #

    schema_filename = get_schema_name(arquivo)
    quant_erros, error_list = validar_schema(request,
                                             schema_filename,
                                             arquivo,
                                             lang='pt')

    for a in error_list:

        if a:

            lista_validacoes.append(a)

    #
    #
    #

    if lista_validacoes:

        validacoes = '<br>'.join(lista_validacoes).replace("'", "''")

        s1200evtRemun.objects.\
            filter(id=pk).\
            update(validacoes=validacoes,
                   status=STATUS_EVENTO_VALIDADO_ERRO)

        messages.error(
            request,
            u'Validações foram processadas, porém foram encontrados erros!')

    else:

        from emensageriapro.mensageiro.functions.funcoes_validacoes_precedencia import EVENTOS_SEM_PREDECESSAO, validar_precedencia

        if VERIFICAR_PREDECESSAO_ANTES_ENVIO and 's1200_evtremun' not in EVENTOS_SEM_PREDECESSAO:

            quant = validar_precedencia('s1200_evtremun', pk)

            if quant <= 0:

                s1200evtRemun.objects.\
                    filter(id=pk).\
                    update(validacoes=None,
                           status=STATUS_EVENTO_AGUARD_PRECEDENCIA)

                messages.warning(
                    request,
                    u'Validações foram processadas com sucesso, porém o evento está aguardando envio de sua precedência!'
                )

            else:

                s1200evtRemun.objects.\
                    filter(id=pk).\
                    update(validacoes=None,
                           status=STATUS_EVENTO_AGUARD_ENVIO)

                messages.success(
                    request,
                    u'Validações foram processadas com sucesso, evento está aguardandando envio!'
                )

        else:

            s1200evtRemun.objects. \
                filter(id=pk).\
                update(validacoes=None,
                       status=STATUS_EVENTO_AGUARD_ENVIO)

            messages.success(
                request,
                u'Validações foram processadas com sucesso, evento está aguardandando envio!'
            )

    return lista_validacoes
Ejemplo n.º 41
0
    def _charge_source(self, request, source, order):
        try:
            charge = stripe.Charge.create(
                amount=int(order.total * 100),
                currency=self.event.currency.lower(),
                source=source,
                metadata={
                    'order': str(order.id),
                    'event': self.event.id,
                    'code': order.code
                },
                # TODO: Is this sufficient?
                idempotency_key=str(self.event.id) + order.code + source
            )
        except stripe.error.CardError as e:
            if e.json_body:
                err = e.json_body['error']
                logger.exception('Stripe error: %s' % str(err))
            else:
                err = {'message': str(e)}
                logger.exception('Stripe error: %s' % str(e))
            logger.info('Stripe card error: %s' % str(err))
            order.payment_info = json.dumps({
                'error': True,
                'message': err['message'],
            })
            order.save(update_fields=['payment_info'])
            raise PaymentException(_('Stripe reported an error with your card: %s') % err['message'])

        except stripe.error.StripeError as e:
            if e.json_body:
                err = e.json_body['error']
                logger.exception('Stripe error: %s' % str(err))
            else:
                err = {'message': str(e)}
                logger.exception('Stripe error: %s' % str(e))
            order.payment_info = json.dumps({
                'error': True,
                'message': err['message'],
            })
            order.save(update_fields=['payment_info'])
            raise PaymentException(_('We had trouble communicating with Stripe. Please try again and get in touch '
                                     'with us if this problem persists.'))
        else:
            ReferencedStripeObject.objects.get_or_create(order=order, reference=charge.id)
            if charge.status == 'succeeded' and charge.paid:
                try:
                    mark_order_paid(order, self.identifier, str(charge))
                except Quota.QuotaExceededException as e:
                    RequiredAction.objects.create(
                        event=self.event, action_type='pretix.plugins.stripe.overpaid', data=json.dumps({
                            'order': order.code,
                            'charge': charge.id
                        })
                    )
                    raise PaymentException(str(e))

                except SendMailException:
                    raise PaymentException(_('There was an error sending the confirmation mail.'))
            elif charge.status == 'pending':
                if request:
                    messages.warning(request, _('Your payment is pending completion. We will inform you as soon as the '
                                                'payment completed.'))
                order.payment_info = str(charge)
                order.save(update_fields=['payment_info'])
                return
            else:
                logger.info('Charge failed: %s' % str(charge))
                order.payment_info = str(charge)
                order.save(update_fields=['payment_info'])
                raise PaymentException(_('Stripe reported an error: %s') % charge.failure_message)
Ejemplo n.º 42
0
def invited_user(request, uuid):
    """The view for an invited user to set their password and enable account.
    """
    if request.method == "POST":
        email = request.POST.get("email")
        group = request.POST.get("group")
        password = request.POST.get("password")
        password1 = request.POST.get("password1")
        password2 = request.POST.get("password2")

        if not email or not password or not password1 or not password2 or not group:
            messages.warning(request, "Please fill in all fields.")
        elif password1 != password2:
            messages.warning(request, "Passwords do not match.")
        else:
            try:
                user = User.objects.get(username=email, email=email)
            except User.DoesNotExist:
                messages.warning(request, "%s does not exist." % email)
                return render(request, "users/invited_user.html")

            # Get the group
            try:
                group = Group.objects.get(id=group)
            except Group.DoesNotExist:
                messages.warning(request, "This group does not exist.")
                return render(request, "users/invited_user.html")

            # Verify the unique id
            if uuid != user.uuid:
                messages.warning(request, "This link is no longer valid.")
                return render(request, "users/invited_user.html")

            # Now authenticate with previous password
            user = authenticate(username=email, password=password)
            if user is None:
                messages.warning(request, "Invalid user email or password.")
                return render(request, "users/invited_user.html")

            # Update user password, and activate
            user.set_password(password1)
            user.uuid = uuid4()
            user.active = True
            user.save()
            auth_login(request, user)
            messages.info(request, f"You are now logged in as {user.username}")
            return redirect("/")

    return render(request, "users/invited_user.html",
                  {"groups": Group.objects.all()})
Ejemplo n.º 43
0
    def get_context(self, request):
        def django_fmt(y):
            return y.upper().replace("-", "_")

        def http_fmt(y):
            return y.upper().replace("_", "-")

        context = {
            "remote_user": None,
            "remote_address": request.META["REMOTE_ADDR"],
            "use_x_forwarded_for": None,
            "secure_proxy_ssl_header": None,
        }
        header = settings.DF_REMOTE_USER_HEADER
        if header:
            context["remote_user"] = (
                http_fmt(header),
                request.META.get(django_fmt(header)),
            )
        header = settings.USE_X_FORWARDED_FOR and "HTTP_X_FORWARDED_FOR"
        if header:
            context["use_x_forwarded_for"] = (
                http_fmt(header),
                request.META.get(django_fmt(header)),
            )
        context["secure_proxy_ssl_header"] = None
        if settings.SECURE_PROXY_SSL_HEADER:
            header, value = settings.SECURE_PROXY_SSL_HEADER
            context["secure_proxy_ssl_header"] = (
                http_fmt(header),
                request.META.get(django_fmt(header)),
                request.META.get(django_fmt(header)) == value,
            )
        host, sep, port = request.get_host().partition(":")
        context["allowed_hosts"] = settings.ALLOWED_HOSTS
        context["allowed_host"] = host in settings.ALLOWED_HOSTS
        context["request_host"] = host
        context["request_site"] = None
        context["cache_redis"] = settings.USE_REDIS_CACHE
        context["use_ssl"] = settings.USE_SSL
        context["session_redis"] = settings.USE_REDIS_SESSIONS
        context["websockets_required"] = settings.WEBSOCKET_URL is not None
        context["celery_required"] = settings.USE_CELERY
        # noinspection PyTypeChecker
        context["fake_username"] = getattr(
            settings, "DF_FAKE_AUTHENTICATION_USERNAME", None
        )
        # noinspection PyTypeChecker
        if hasattr(request, "site"):
            context["request_site"] = request.site
            context["request_site_valid"] = request.site == host
        context["server_name"] = settings.SERVER_NAME
        context["server_name_valid"] = settings.SERVER_NAME == host
        context["debug"] = settings.DEBUG
        context["request_headers"] = [
            (x, y, self.common_headers.get(x))
            for (x, y) in sorted(request.META.items())
        ]
        if settings.DEBUG:
            messages.warning(
                request,
                _(
                    "The DEBUG mode is activated. You should disable it for a production website."
                ),
            )
        if context["fake_username"]:
            messages.warning(
                request,
                _(
                    "DF_FAKE_AUTHENTICATION_USERNAME is set. "
                    "You should disable it for a production website."
                ),
            )
        context["settings_providers"] = [p for p in merger.providers]
        return context
Ejemplo n.º 44
0
def finanz_auto_matching(request: WSGIRequest) -> HttpResponse:
    semester: Semester = get_object_or_404(Semester, pk=get_semester(request))
    participants: QuerySet[Participant] = Participant.objects.filter(
        semester=semester, status="confirmed")

    # mypy is weird for this one. equivalent [but not Typechecking]:  participants.values_list("id", flat=True)
    participants_ids_pre_mypy: list[Optional[UUID]] = [
        element["id"] for element in participants.values("id")
    ]
    participants_ids: list[UUID] = [
        uuid for uuid in participants_ids_pre_mypy if uuid
    ]

    transactions: list[Entry] = [
        Entry.from_json(entry) for entry in request.session["results"]
    ]

    error, matched_transactions, unmatched_transactions = match_transactions_participant_ids(
        participants_ids,
        request,
        transactions,
    )
    if error:
        return redirect("fahrt:finanz_automated")

    # genrerate selection boxes
    unmatched_trans_form_set = formset_factory(
        ParticipantSelectForm, extra=len(unmatched_transactions))
    forms_unmatched = unmatched_trans_form_set(
        request.POST or None, form_kwargs={"semester": semester})
    forms_unmatched_trans = list(zip(forms_unmatched, unmatched_transactions))
    matched_trans_form_set = formset_factory(ParticipantSelectForm, extra=0)
    forms_matched = matched_trans_form_set(
        request.POST or None,
        initial=[{
            "selected": p_uuid
        } for (p_uuid, _) in matched_transactions],
        form_kwargs={"semester": semester},
    )
    forms_matched_trans = []
    for p_uuid, transaction in matched_transactions:
        for p_form in forms_matched:
            if p_form.initial["selected"] == p_uuid:
                forms_matched_trans.append((p_form, transaction))
                break

    # parse forms and redirect to confirmation page
    if forms_unmatched.is_valid() and forms_matched.is_valid():
        # hs notation: fst(unzip xs)++fst(unzip ys)
        selection_forms = []
        if forms_matched_trans:
            selection_forms += list(zip(*forms_matched_trans))[0]
        if forms_unmatched_trans:
            selection_forms += list(zip(*forms_unmatched_trans))[0]
        new_paid_participants = set()
        for form in selection_forms:
            if form.cleaned_data:
                selected_part: Participant = form.cleaned_data["selected"]
                if selected_part and Participant.objects.get(
                        id=selected_part.id).paid is None:
                    new_paid_participants.add(selected_part.id)

        if new_paid_participants:
            request.session["new_paid_participants"] = list(
                new_paid_participants)
            request.session["new_unpaid_participants"] = []
            return redirect("fahrt:finanz_confirm")
        messages.warning(request, _("No Changes to Payment-state detected"))
        return redirect("fahrt:finanz_automated")

    context = {
        "matched_transactions": forms_matched_trans,
        "unmatched_transactions": forms_unmatched_trans,
        "forms_matched": forms_matched,
        "forms_unmatched": forms_unmatched,
    }
    return render(request, "fahrt/finanz/automated_finanz_matching.html",
                  context)
Ejemplo n.º 45
0
def delete_category(request, pk):
    category = get_object_or_404(Category, id=pk)
    category.delete()
    messages.warning(request, 'The category has deleted')
    return redirect(reverse('dashboard:categories'))
Ejemplo n.º 46
0
    def get(self, *args, **kwargs):
        # TODO: Remover linhas a baixo
        # if self.request.session.get('carrinho'):
        #    del self.request.session['carrinho']
        #    self.request.session.save()

        http_referer = self.request.META.get(
            'HTTP_REFERER',
            reverse('produto:lista')
        )
        variacao_id = self.request.GET.get('vid')

        if not variacao_id:
            messages.error(
                self.request,
                'Produto não existe'
            )
            return redirect(http_referer)

        variacao = get_object_or_404(models.Variacao, id=variacao_id)
        variacao_estoque = variacao.estoque
        produto = variacao.produto

        produto_id = produto.id
        produto_nome = produto.nome
        variacao_nome = variacao.nome or ''
        preco_unitario = variacao.preco
        preco_unitario_promocional = variacao.preco_promocional
        quantidade = 1
        slug = produto.slug
        imagem = produto.imagem

        if imagem:
            imagem = imagem.name
        else:
            imagem = ''

        if variacao.estoque < 1:
            messages.error(
                self.request,
                'Estoque insuficiente'
            )
            return redirect(http_referer)

        if not self.request.session.get('carrinho'):
            self.request.session['carrinho'] = {}
            self.request.session.save()

        carrinho = self.request.session['carrinho']

        if variacao_id in carrinho:
            quantidade_carrinho = carrinho[variacao_id]['quantidade']
            quantidade_carrinho = quantidade_carrinho + 1

            if variacao_estoque < quantidade_carrinho:
                messages.warning(
                    self.request,
                    f'Estoque insuficiente para {quantidade_carrinho}x no'
                    f'produto "{produto_nome}". Adicionamos {variacao_estoque}x'
                    f'no seu carrinho.'
                )
                quantidade_carrinho = variacao_estoque

            carrinho[variacao_id]['quantidade'] = quantidade_carrinho
            carrinho[variacao_id]['preco_quantitativo'] = preco_unitario * \
                quantidade_carrinho
            carrinho[variacao_id]['preco_quantitativo_promocional'] = preco_unitario_promocional * \
                quantidade_carrinho

        else:
            carrinho[variacao_id] = {
                'produto_id': produto_id,
                'produto_nome': produto_nome,
                'variacao_nome': variacao_nome,
                'variacao_id': variacao_id,
                'preco_unitario': preco_unitario,
                'preco_unitario_promocional': preco_unitario_promocional,
                'preco_quantitativo': preco_unitario,
                'preco_quantitativo_promocional': preco_unitario_promocional,
                'quantidade': 1,
                'slug': slug,
                'imagem': imagem,
            }

        self.request.session.save()
        # pprint(carrinho)

        messages.success(
            self.request,
            f'Produto {produto_nome} {variacao_nome} adicionado ao seu '
            f'carrinho {carrinho[variacao_id]["quantidade"]}x'
        )
        return redirect(http_referer)
Ejemplo n.º 47
0
def delete_brand(request, pk):
    instance = get_object_or_404(Brands, id=pk)
    instance.delete()
    messages.warning(request, 'The brand %s has deleted' % instance.title)
    return redirect(reverse('dashboard:brands'))
Ejemplo n.º 48
0
 def get(self, request: HttpRequest):
     messages.warning(
         request, "La page demandée n'existe pas, vous avez été redirigé.")
     return redirect("welcome")
Ejemplo n.º 49
0
def eliminar_cuenta(request,pk,empresa):
    cuenta = Cuenta.objects.get(idCuenta=pk)
    cuenta.delete()
    messages.warning(request,'La cuenta a sido eliminada')
    return redirect('Empresa:cuentas',empresa)
Ejemplo n.º 50
0
def delete_color(request, pk):
    instance = get_object_or_404(Color, id=pk)
    instance.delete()
    messages.warning(request, 'The color %s deleted' % instance.title)
    return redirect(reverse('dashboard:colors'))
Ejemplo n.º 51
0
def index(request):
    """
    main view
    """
    warning_msg_same = "A quiz with the same name already exists, please change the name of the quiz or delete the existing one"
    import_form = forms.ImportForm()
    if request.method == 'POST':
        import_form = forms.ImportForm(request.POST)
        file = request.FILES['file']
        if file.name.endswith('.csv'):
            decoded_file = file.read().decode('UTF-8').splitlines()
            reader = csv.reader(decoded_file)
            try:
                the_quiz = list(reader)
                n_desc = ""
                is_random = False
                if len(the_quiz[0]) >= 3:
                    n_desc = the_quiz[0][2]

                if len(the_quiz[0]) >= 4:
                    if the_quiz[0][3] == "1":
                        is_random = True

                if Quiz.objects.filter(quiz_name=the_quiz[0][1]).exists():
                    messages.warning(request, warning_msg_same)

                    return redirect(index)
                n_quiz = Quiz.objects.create(quiz_name=the_quiz[0][1],
                                             quiz_category=the_quiz[0][0],
                                             quiz_description=n_desc,
                                             quiz_randomizable=is_random,
                                             quiz_allowed_users=request.user)

                n_quiz.save()
                bulk_questions = []
                bulk_answers = []
                for question in range(1, len(the_quiz)):
                    print(question)
                    n_question = Question()
                    n_question.question_text = the_quiz[question][0]
                    n_question.question_quiz = n_quiz
                    bulk_questions.append(n_question)
                Question.objects.bulk_create(bulk_questions)
                new_questions = Question.objects.filter(question_quiz=n_quiz)
                n_q = -1
                for question in range(1, len(the_quiz)):
                    n_q += 1
                    print("INSERTED QUESTION", )
                    for answer in range(1, len(the_quiz[question])):
                        print("1    =========>", the_quiz[question][answer])
                        if the_quiz[question][answer] != '0' and the_quiz[
                                question][answer] != '1' and the_quiz[
                                    question][answer] != "":
                            print("==========>", the_quiz[question][answer])
                            n_answer = Answer()
                            n_answer.answer_text = the_quiz[question][answer]
                            n_answer.correct_answer = the_quiz[question][answer
                                                                         + 1]
                            n_answer.answer_question = new_questions[n_q]
                            bulk_answers.append(n_answer)

                        else:
                            continue
                Answer.objects.bulk_create(bulk_answers)
            except:
                pass
        elif file.name.endswith('.json'):

            json_data = json.load(file)
            if Quiz.objects.filter(quiz_name=json_data['quiz_name']).exists():
                messages.warning(request, warning_msg_same)
            try:

                if json_data['random'] == "1":
                    is_random = True
                else:
                    is_random = False

                n_quiz = Quiz.objects.create(
                    quiz_name=json_data['quiz_name'],
                    quiz_category=json_data['category'],
                    quiz_description=json_data['quiz_description'],
                    quiz_randomizable=is_random,
                    quiz_allowed_users=request.user)

                n_quiz.save()
                #bulk_questions = []

                for question in json_data['questions']:
                    bulk_answers = []
                    n_question = Question()
                    n_question.question_text = question['question_text']
                    n_question.question_quiz = n_quiz
                    n_question.save()

                    for answer in question['answers']:

                        n_answer = Answer()
                        n_answer.answer_text = answer['answer_text']
                        n_answer.correct_answer = answer['answer_value']
                        n_answer.answer_question = n_question
                        bulk_answers.append(n_answer)
                #Question.objects.bulk_create(bulk_questions)
                    Answer.objects.bulk_create(bulk_answers)
            except:
                pass

            pass
        return redirect('index')

    else:
        try:
            ordered_quizs = {}
            available_quizs = Quiz.objects.all().values(
                'id',
                'quiz_category',
                'quiz_name',
                'quiz_description',
            ).order_by('-quiz_name')

            for quiz in available_quizs:
                if quiz['quiz_category'] in ordered_quizs:
                    ordered_quizs[quiz['quiz_category']].append(quiz)
                else:
                    ordered_quizs[quiz['quiz_category']] = []

                    ordered_quizs[quiz['quiz_category']].append(quiz)

            json_available_quizs = json.dumps(ordered_quizs)

        except Quiz.DoesNotExist:
            print("NO quizS")
            available_quizs = {}

        return render(request, 'quizz_app/home.html', {
            'available_quizs': json_available_quizs,
            'import_form': import_form,
        })
Ejemplo n.º 52
0
def delete_category_site(request, pk):
    instance = get_object_or_404(CategorySite, id=pk)
    instance.delete()
    messages.warning(request, f'The category {instance.title} is deleted')
    return HttpResponseRedirect(reverse('dashboard:categories_site'))
Ejemplo n.º 53
0
def rename(request):
    """
    Rename existing File/Directory.

    Includes renaming existing Image Versions/Thumbnails.
    """

    from djlime_filebrowser.forms import RenameForm

    # QUERY / PATH CHECK
    query = request.GET
    path = get_path(query.get('dir', ''))
    filename = get_file(query.get('dir', ''), query.get('filename', ''))
    if path is None or filename is None:
        if path is None:
            msg = _('The requested Folder does not exist.')
        else:
            msg = _('The requested File does not exist.')
        messages.warning(request, message=msg)
        return HttpResponseRedirect(reverse("fb_browse"))
    abs_path = _check_access(request, path)
    file_extension = os.path.splitext(filename)[1].lower()

    if request.method == 'POST':
        form = RenameForm(abs_path, file_extension, request.POST)
        if form.is_valid():
            relative_server_path = os.path.join(fb_settings.DIRECTORY, path,
                                                filename)
            new_filename = form.cleaned_data['name'] + file_extension
            new_relative_server_path = os.path.join(fb_settings.DIRECTORY,
                                                    path, new_filename)
            try:
                # PRE RENAME SIGNAL
                filebrowser_pre_rename.send(sender=request,
                                            path=path,
                                            filename=filename,
                                            new_filename=new_filename)
                # DELETE IMAGE VERSIONS/THUMBNAILS
                # regenerating versions/thumbs will be done automatically
                for version in VERSIONS:
                    try:
                        os.unlink(
                            os.path.join(
                                fb_settings.MEDIA_ROOT,
                                get_version_path(relative_server_path,
                                                 version)))
                    except:
                        pass
                # RENAME ORIGINAL
                os.rename(
                    os.path.join(fb_settings.MEDIA_ROOT, relative_server_path),
                    os.path.join(fb_settings.MEDIA_ROOT,
                                 new_relative_server_path))
                # POST RENAME SIGNAL
                filebrowser_post_rename.send(sender=request,
                                             path=path,
                                             filename=filename,
                                             new_filename=new_filename)
                # MESSAGE & REDIRECT
                msg = _('Renaming was successful.')
                messages.success(request, message=msg)
                redirect_url = reverse("fb_browse") + query_helper(
                    query, "", "filename")
                return HttpResponseRedirect(redirect_url)
            except OSError, (errno, strerror):
                form.errors['name'] = forms.util.ErrorList([_('Error.')])
Ejemplo n.º 54
0
def delete_a_post(request, pk):
    NewPost_Likes_Dislikes.objects.filter(pk=pk).delete()
    messages.warning(request, 'Your comment has been deleted')
    return redirect('my_posts')
Ejemplo n.º 55
0
def remove_order(request, slug):
    order_qs = get_object_or_404(Order, slug=slug)
    order_qs.delete()
    messages.warning(request, "این آیتم از لیست سفارشات شما حذف شد")
    return redirect("/order/")
Ejemplo n.º 56
0
def browse(request):
    """
    Browse Files/Directories.
    """
    # QUERY / PATH CHECK
    query = request.GET.copy()
    path = get_path(query.get('dir', ''))
    directory = get_path('')

    if path is not None:
        abs_path = _check_access(request, path)

    if path is None:
        msg = _('The requested Folder does not exist.')
        messages.warning(request, message=msg)
        if directory is None:
            # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
            raise ImproperlyConfigured, _(
                "Error finding Upload-Folder. Maybe it does not exist?")
        redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
        return HttpResponseRedirect(redirect_url)

    # INITIAL VARIABLES
    results_var = {
        'results_total': 0,
        'results_current': 0,
        'delete_total': 0,
        'images_total': 0,
        'select_total': 0
    }
    counter = {}
    for k, v in EXTENSIONS.iteritems():
        counter[k] = 0

    dir_list = os.listdir(abs_path)
    files = []
    for file in dir_list:

        # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
        filtered = file.startswith('.')
        for re_prefix in filter_re:
            if re_prefix.search(file):
                filtered = True
        if filtered:
            continue
        results_var['results_total'] += 1

        # CREATE FILEOBJECT
        fileobject = FileObject(os.path.join(fb_settings.DIRECTORY, path,
                                             file))

        # FILTER / SEARCH
        append = False
        if fileobject.filetype == request.GET.get(
                'filter_type', fileobject.filetype) and get_filterdate(
                    request.GET.get('filter_date', ''), fileobject.date):
            append = True
        if request.GET.get('q') and not re.compile(
                request.GET.get('q').lower(), re.M).search(file.lower()):
            append = False

        # APPEND FILE_LIST
        if append:
            _type = query.get('type')
            try:
                # COUNTER/RESULTS
                if fileobject.filetype == 'Image':
                    results_var['images_total'] += 1
                if fileobject.filetype != 'Folder':
                    results_var['delete_total'] += 1
                elif fileobject.filetype == 'Folder' and fileobject.is_empty:
                    results_var['delete_total'] += 1
                if _type and _type in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[
                        _type]:
                    results_var['select_total'] += 1
                elif not _type:
                    results_var['select_total'] += 1
            except OSError:
                # Ignore items that have problems
                continue
            else:
                files.append(fileobject)
                results_var['results_current'] += 1

        # COUNTER/RESULTS
        if fileobject.filetype:
            counter[fileobject.filetype] += 1

    # SORTING
    query['o'] = request.GET.get('o', DEFAULT_SORTING_BY)
    query['ot'] = request.GET.get('ot', DEFAULT_SORTING_ORDER)
    files = sort_by_attr(files, request.GET.get('o', DEFAULT_SORTING_BY))
    if not request.GET.get(
            'ot') and DEFAULT_SORTING_ORDER == "desc" or request.GET.get(
                'ot') == "desc":
        files.reverse()

    p = Paginator(files, LIST_PER_PAGE)
    try:
        page_nr = request.GET.get('p', '1')
    except:
        page_nr = 1
    try:
        page = p.page(page_nr)
    except (EmptyPage, InvalidPage):
        page = p.page(p.num_pages)

    return render_to_response('djlime_filebrowser/index.html', {
        'dir': path,
        'p': p,
        'page': page,
        'results_var': results_var,
        'counter': counter,
        'query': query,
        'title': _(u'FileBrowser'),
        'settings_var': get_settings_var(),
        'breadcrumbs': get_breadcrumbs(query, path),
        'breadcrumbs_title': ""
    },
                              context_instance=Context(request))
Ejemplo n.º 57
0
def checkout(request):
    stripe_public_key = settings.STRIPE_PUBLIC_KEY
    stripe_secret_key = settings.STRIPE_SECRET_KEY

    if request.method == 'POST':
        bag = request.session.get('bag', {})

        form_data = {
            'full_name': request.POST['full_name'],
            'email': request.POST['email'],
            'phone_number': request.POST['phone_number'],
            'country': request.POST['country'],
            'postcode': request.POST['postcode'],
            'town_or_city': request.POST['town_or_city'],
            'street_address1': request.POST['street_address1'],
            'street_address2': request.POST['street_address2'],
            'county': request.POST['county'],
        }
        order_form = OrderForm(form_data)
        if order_form.is_valid():
            order = order_form.save(commit=False)
            pid = request.POST.get('client_secret').split('_secret')[0]
            order.stripe_pid = pid
            order.original_bag = json.dumps(bag)
            order.save()
            for item_id, item_data in bag.items():
                try:
                    product = Product.objects.get(id=item_id)
                    if isinstance(item_data, int):
                        order_line_item = OrderLineItem(
                            order=order,
                            product=product,
                            quantity=item_data,
                        )
                        order_line_item.save()
                    else:
                        for size, quantity in item_data['items_by_size'].items(
                        ):
                            order_line_item = OrderLineItem(
                                order=order,
                                product=product,
                                quantity=quantity,
                                product_size=size,
                            )
                            order_line_item.save()
                except Product.DoesNotExist:
                    messages.error(request, (
                        "One of the products in your bag wasn't found in our database."
                        "Please call us for assistance!"))
                    order.delete()
                    return redirect(reverse('view_bag'))

            request.session['save_info'] = 'save-info' in request.POST
            return redirect(
                reverse('checkout_success', args=[order.order_number]))
        else:
            messages.error(
                request, 'There was an error with your form. \
                Please double check your information.')
    else:
        bag = request.session.get('bag', {})
        if not bag:
            messages.error(request,
                           "There's nothing in your bag at the moment")
            return redirect(reverse('products'))

        current_bag = bag_contents(request)
        total = current_bag['grand_total']
        stripe_total = round(total * 100)
        stripe.api_key = stripe_secret_key
        intent = stripe.PaymentIntent.create(
            amount=stripe_total,
            currency=settings.STRIPE_CURRENCY,
        )

        if request.user.is_authenticated:
            try:
                profile = UserProfile.objects.get(user=request.user)
                order_form = OrderForm(
                    initial={
                        'full_name': profile.user.get_full_name(),
                        'phone_number': profile.default_phone_number,
                        'country': profile.default_country,
                        'postcode': profile.default_postcode,
                        'town_or_city': profile.default_town_or_city,
                        'street_address1': profile.default_street_address1,
                        'street_address2': profile.default_street_address2,
                        'county': profile.default_county,
                    })

            except UserProfile.DoesNotExist:
                order_form = OrderForm()
        else:
            order_form = OrderForm()

    if not stripe_public_key:
        messages.warning(
            request, 'Stripe public key is missing. \
            Did you forget to set it in your environment?')

    template = 'checkout/checkout.html'
    context = {
        'order_form': order_form,
        'stripe_public_key': stripe_public_key,
        'client_secret': intent.client_secret,
    }

    return render(request, template, context)
Ejemplo n.º 58
0
def delete(request):
    """
    Delete existing File/Directory.

    When trying to delete a Directory, the Directory has to be empty.
    """

    # QUERY / PATH CHECK
    query = request.GET
    path = get_path(query.get('dir', ''))
    filename = get_file(query.get('dir', ''), query.get('filename', ''))
    if path is None or filename is None:
        if path is None:
            msg = _('The requested Folder does not exist.')
        else:
            msg = _('The requested File does not exist.')
        messages.warning(request, message=msg)
        return HttpResponseRedirect(reverse("fb_browse"))
    abs_path = _check_access(request, path)

    msg = ""
    if request.GET:
        if request.GET.get('filetype') != "Folder":
            relative_server_path = os.path.join(fb_settings.DIRECTORY, path,
                                                filename)
            try:
                # PRE DELETE SIGNAL
                filebrowser_pre_delete.send(sender=request,
                                            path=path,
                                            filename=filename)

                # DELETE FILE
                os.unlink(smart_str(_check_access(request, path, filename)))
                # DELETE IMAGE VERSIONS/THUMBNAILS
                for version in VERSIONS:
                    try:
                        os.unlink(
                            os.path.join(
                                fb_settings.MEDIA_ROOT,
                                get_version_path(relative_server_path,
                                                 version)))
                    except:
                        pass

                # POST DELETE SIGNAL
                filebrowser_post_delete.send(sender=request,
                                             path=path,
                                             filename=filename)
                # MESSAGE & REDIRECT
                msg = _('The file %s was successfully deleted.') % (
                    filename.lower())
                messages.success(request, message=msg)
                redirect_url = reverse("fb_browse") + query_helper(
                    query, "", "filename,filetype")
                return HttpResponseRedirect(redirect_url)
            except OSError, e:
                # todo: define error message
                msg = unicode(e)
        else:
            try:
                # PRE DELETE SIGNAL
                filebrowser_pre_delete.send(sender=request,
                                            path=path,
                                            filename=filename)
                # DELETE FOLDER
                os.rmdir(_check_access(request, path, filename))
                # POST DELETE SIGNAL
                filebrowser_post_delete.send(sender=request,
                                             path=path,
                                             filename=filename)
                # MESSAGE & REDIRECT
                msg = _('The folder %s was successfully deleted.') % (
                    filename.lower())
                messages.success(request, message=msg)
                redirect_url = reverse("fb_browse") + query_helper(
                    query, "", "filename,filetype")
                return HttpResponseRedirect(redirect_url)
            except OSError, e:
                # todo: define error message
                msg = unicode(e)
Ejemplo n.º 59
0
    def post(self, *args, **kwargs):
        form = CheckoutForm(self.request.POST or None)
        try:
            order = Order.objects.get(user=self.request.user, ordered=False)
            if form.is_valid():

                use_default_shipping = form.cleaned_data.get(
                    'use_default_shipping')
                if use_default_shipping:

                    address_qs = Address.objects.filter(user=self.request.user,
                                                        address_type='S',
                                                        default=True)
                    if address_qs.exists():
                        shipping_address = address_qs[0]
                        order.shipping_address = shipping_address
                        order.save()
                    else:
                        messages.info(
                            self.request,
                            " No default shipping address available")
                        return redirect('core:checkout')
                else:
                    shipping_address1 = form.cleaned_data.get(
                        'shipping_address')
                    shipping_address2 = form.cleaned_data.get(
                        'shipping_address2')
                    shipping_country = form.cleaned_data.get(
                        'shipping_country')
                    # state = form.cleaned_data.get('state')
                    shipping_zip = form.cleaned_data.get('shipping_zip')

                    if is_valid_form(
                        [shipping_address1, shipping_country, shipping_zip]):

                        shipping_address = Address(
                            user=self.request.user,
                            street_address=shipping_address1,
                            apartment_address=shipping_address2,
                            country=shipping_country,
                            # state=state,
                            zip=shipping_zip,
                            address_type='S')
                        shipping_address.save()

                        order.shipping_address = shipping_address
                        order.save()

                        set_default_shipping = form.cleaned_data.get(
                            'set_default_shipping')
                        if set_default_shipping:
                            shipping_address.default = True
                            shipping_address.save()

                    else:
                        messages.info(
                            self.request,
                            "please enter the shipping address fields.")

                use_default_billing = form.cleaned_data.get(
                    'use_default_billing')
                same_billing_address = form.cleaned_data.get(
                    'same_billing_address')

                if same_billing_address:
                    billing_address = shipping_address
                    billing_address.pk = None
                    billing_address.save()
                    billing_address.address_type = 'B'
                    billing_address.save()
                    order.billing_address = billing_address
                    order.save()

                elif use_default_billing:

                    address_qs = Address.objects.filter(user=self.request.user,
                                                        address_type='B',
                                                        default=True)
                    if address_qs.exists():
                        billing_address = address_qs[0]
                        order.billing_address = billing_address
                        order.save()
                    else:
                        messages.info(self.request,
                                      " No default billing address available")
                        return redirect('core:checkout')
                else:

                    billing_address1 = form.cleaned_data.get('billing_address')
                    billing_address2 = form.cleaned_data.get(
                        'billing_address2')
                    billing_country = form.cleaned_data.get('billing_country')
                    # state = form.cleaned_data.get('state')
                    billing_zip = form.cleaned_data.get('billing_zip')

                    if is_valid_form(
                        [billing_address1, billing_address2, billing_zip]):

                        billing_address = Address(
                            user=self.request.user,
                            street_address=billing_address1,
                            apartment_address=billing_address2,
                            country=billing_country,
                            # state=state,
                            zip=billing_zip,
                            address_type='B')
                        billing_address.save()

                        order.billing_address = billing_address
                        order.save()

                        set_default_billing = form.cleaned_data.get(
                            'set_default_billing')
                        if set_default_billing:
                            billing_address.default = True
                            billing_address.save()

                    else:
                        messages.info(
                            self.request,
                            "please enter the billing address fields.")

                payment_option = form.cleaned_data.get('payment_option')

                if payment_option == 'S':
                    return redirect('core:payment', payment_option='stripe')
                elif payment_option == 'P':
                    return redirect('core:payment', payment_option='paypal')
                else:
                    messages.warning(self.request, "Invalid payment option")
                    return redirect("core:checkout")

        except ObjectDoesNotExist:
            messages.warning(self.request, "Your Cart is Empty")
            return redirect("core:order-summary")
Ejemplo n.º 60
0
def wishlist(request):
    user = request.user
    try:
        member_connected = Member.objects.get(email=user.email)
    except Member.DoesNotExist :
        member_connected = None
    

    wishlist_member = Wishlist.objects.filter(member=member_connected).values('order', 'item', 'item__name', 'item__media')
    TEMPLATE_URL = 'accounts/wishlist.html'
    if 'looking_for_item' in request.POST :
        item_name = request.POST.get('item_name')
        if item_name:
            token = create_access_token(settings.CLIENT_ID, settings.CLIENT_SECRET)
            token = token['access_token']
            r = requests.get(f'{settings.API_URL}{item_name}{settings.TOKEN_URL}{token}', params=request.GET)

            if r.status_code == 200: 
                data = r.json()
                datas = data['results']
                context = {'datas': datas, 'item_name': item_name, 'wishlist_member': wishlist_member}

                return render(request, TEMPLATE_URL, context)
            else:
                messages.warning(request, "Merci de vérifier l'ortographe de l'item")
                context = {'wishlist_member': wishlist_member}
                return render(request, TEMPLATE_URL, context)

    if 'add_wishlist' in request.POST:
        order_max = Wishlist.objects.filter(member=member_connected).aggregate(Max('order'))
        order_max = order_max['order__max']
        item_name = request.POST.get('item')
        order = request.POST.get('order')
        media = request.POST.get('media')
        item_exist = Wishlist.objects.filter(member=member_connected, item__name=item_name)
        if order == "":
            messages.warning(request, "Merci de renseigner la position de l'item")
        elif order_max is not None and int(order) <= int(order_max):
            messages.warning(request, "Merci de choisir une position supérieur à la position de votre dernier item")
        elif item_exist:
            messages.warning(request, "L'item est déjà présent dans votre wishlist")
        elif Council.objects.filter(item__name=item_name, is_council=True).exists():
            messages.warning(request, "L'item est en loot council")
        else:
            messages.success(request, "Item ajouté à ta wishlist")
            try:
                item = Item.objects.get(name=item_name)
            except Item.DoesNotExist:
                item = None

            if item is None:
                item = Item(name=item_name, media=media)
                item.save()

            w = Wishlist(order=order, item=item, member=member_connected)
            w.save()
        
        context = {'wishlist_member': wishlist_member}
        return render(request, TEMPLATE_URL, context)
        
    context = {'wishlist_member': wishlist_member}
    return render(request, TEMPLATE_URL, context)