Ejemplo n.º 1
0
def configuration_duplicate(request, config_id=None):

    config = Configuration.get_or_none(config_id)
    if config is None:
        raise Http404("Configuration not found")

    if config.organization != request.user.profile.organization:
        raise HttpResponse("Unauthorized", status=401)

    try:
        nconfig = config.duplicate(by=request.user.profile)
        messages.success(
            request,
            "Successfuly duplicated Configuration <em>{}</em> into <em>{}</em>"
            .format(config, nconfig),
        )
    except Exception as exp:
        logger.error("Unable to duplicate configuration {id}: {exp}".format(
            id=config.id, exp=exp))
        messages.error(
            request,
            "Unable to duplicate Configuration <em>{config}</em>: -- ref {exp}"
            .format(config=config, exp=exp),
        )

    return redirect("configuration_list")
Ejemplo n.º 2
0
def configuration_duplicate(request, config_id=None):

    config = Configuration.get_or_none(config_id)
    if config is None:
        raise Http404(_("Configuration not found"))

    if config.organization != request.user.profile.organization:
        raise PermissionDenied()

    try:
        nconfig = config.duplicate(by=request.user.profile)
        messages.success(
            request,
            _("Successfuly duplicated Configuration <em>%(config)s</em> "
              "into <em>%(new_config)s</em>") % {
                  "config": config,
                  "new_config": nconfig
              },
        )
    except Exception as exp:
        logger.error("Unable to duplicate configuration {id}: {exp}".format(
            id=config.id, exp=exp))
        messages.error(
            request,
            _("Unable to duplicate Configuration <em>%(config)s</em>: -- ref %(err)s"
              ) % {
                  "config": config,
                  "err": exp
              },
        )

    return redirect("configuration_list")
Ejemplo n.º 3
0
def configuration_edit(request, config_id=None):
    context = {}

    if config_id:
        config = Configuration.get_or_none(config_id)
        if config is None:
            raise Http404(_("Configuration not found"))

        if config.organization != request.user.profile.organization:
            raise PermissionDenied()
    else:
        # new config
        config = Configuration(organization=request.user.profile.organization)

    # list of languages availables in all catalogs
    context["packages_langs"] = PACKAGES_LANGS

    if request.method == "POST":
        form = ConfigurationForm(request.POST, request.FILES, instance=config)
        if form.is_valid():
            try:
                instance = form.save(commit=False)
                instance.updated_by = request.user.profile
                instance.save()
            except Exception as exp:
                messages.error(
                    request,
                    _(
                        "Failed to save your configuration (although it looks good). "
                        "Try again and contact support "
                        "if it happens again (ref: $(err)s)"
                    )
                    % {"err": exp},
                )
            else:
                messages.success(request, _("Configuration Updated successfuly !"))
                return redirect("configuration_edit", config.id)
        else:
            pass
    else:
        form = ConfigurationForm(instance=config)

    context["form"] = form

    return render(request, "configuration_edit.html", context)
Ejemplo n.º 4
0
 def __init__(self, *args, **kwargs):
     client = kwargs.pop("client")
     super().__init__(*args, **kwargs)
     self.client = client
     self.organization = client.organization
     self.fields["config"].choices = Configuration.get_choices(
         self.organization)
     self.fields["address"].choices = Address.get_choices(self.organization)
     self.fields["media"].choices = Media.get_choices()
Ejemplo n.º 5
0
def media_choices_for_configuration(request, config_id):
    all_medias = Media.objects.all()

    config = Configuration.get_or_none(config_id)
    if config is not None and config.organization == request.user.profile.organization:
        medias = [m for m in all_medias if m.bytes >= config.size]
    if not medias:
        medias = all_medias.filter(size=all_medias.aggregate(Max("size"))["size__max"])
    return JsonResponse(Media.choices_for(medias), safe=False)
Ejemplo n.º 6
0
def configuration_list(request):

    page = request.GET.get("page")
    config_filter = bool(request.GET.get("all", False) == "yes")
    filtered_configurations = Configuration.objects.filter(
        organization=request.user.profile.organization
    )

    if not config_filter:
        filtered_configurations = filtered_configurations.filter(
            updated_by=request.user.profile
        )

    paginator = Paginator(filtered_configurations, NB_CONFIGURATIONS_PER_PAGE)
    configurations_page = paginator.get_page(page)

    context = {
        "configurations": configurations_page.object_list,
        "configurations_page": configurations_page,
        "config_filter": config_filter,
    }

    if request.method == "POST":
        form = JSONUploadForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                js_config = handle_uploaded_json(request.FILES["file"])
            except Exception:
                messages.error(
                    request, _("Your file is not a valid JSON. Can't import it.")
                )
            else:
                try:
                    config = Configuration.create_from(
                        config=js_config or {}, author=request.user.profile
                    )
                except Exception as exp:
                    messages.error(
                        request,
                        _(
                            "An error occured while trying to import your config file. "
                            "Please retry or contact support. (ref: %(err)s)"
                        )
                        % {"err": exp},
                    )
                else:
                    return redirect("configuration_edit", config.id)
        else:
            pass
    else:
        form = JSONUploadForm()

    context["form"] = form

    return render(request, "configuration_list.html", context)
Ejemplo n.º 7
0
def configuration_export(request, config_id=None):

    config = Configuration.get_or_none(config_id)
    if config is None:
        raise Http404(_("Configuration not found"))

    if config.organization != request.user.profile.organization:
        raise PermissionDenied()

    response = JsonResponse(config.to_dict(),
                            safe=False,
                            json_dumps_params={"indent": 4})
    response["Content-Disposition"] = 'attachment; filename="{}.json"'.format(
        config.display_name)
    return response
Ejemplo n.º 8
0
 def __init__(self, *args, **kwargs):
     request = kwargs.pop("request")
     super().__init__(*args, **kwargs)
     self.client = request.user.profile
     self.request_lang = get_language_from_request(request)
     self.organization = self.client.organization
     self.fields["config"].choices = Configuration.get_choices(
         self.organization)
     self.fields["address"].choices = [
         ("none", "Myself")
     ] + Address.get_choices(self.organization)
     self.fields["media"].choices = Media.get_choices(
         kind=None if self.client.can_order_physical else Media.VIRTUAL,
         display_units=self.client.is_limited,
     )
     self.fields["kind"].choices = filter(
         lambda item: self.client.can_order_physical or item[0] != Media.
         PHYSICAL,
         self.KIND_CHOICES.items(),
     )
Ejemplo n.º 9
0
 def __init__(self, *args, **kwargs):
     client = kwargs.pop("client")
     print(client, client.is_limited)
     super().__init__(*args, **kwargs)
     self.client = client
     self.organization = client.organization
     self.fields["config"].choices = Configuration.get_choices(
         self.organization)
     self.fields["address"].choices = [
         ("none", "Myself")
     ] + Address.get_choices(self.organization)
     self.fields["media"].choices = Media.get_choices(
         kind=None if client.can_order_physical else Media.VIRTUAL,
         display_units=client.is_limited,
     )
     self.fields["kind"].choices = filter(
         lambda item: client.can_order_physical or item[0] != Media.
         PHYSICAL,
         self.KIND_CHOICES.items(),
     )
Ejemplo n.º 10
0
 def clean_config(self):
     config = Configuration.get_or_none(self.cleaned_data.get("config"))
     if config is None or config.organization != self.organization:
         raise forms.ValidationError(_("Not your configuration"),
                                     code="invalid")
     return config
Ejemplo n.º 11
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields["config"].choices = Configuration.get_choices(
         self._client.organization
     )