Exemple #1
0
 def perform_destroy(self, instance):
     with transaction.atomic():
         if instance.services.count() > 0:
             raise APIConflict(_("Can't delete product in use by services"))
         try:
             instance.cycles.all().delete()
         except ProtectedError:
             # TODO: maybe return the objects which reference the cycles (exception.protected_objects)
             raise APIConflict(_("Can't delete product in use by services"))
         instance.delete()
Exemple #2
0
    def perform_destroy(self, instance: Configuration):
        if instance.is_default:
            raise APIConflict(
                'Unable to delete default configuration {}'.format(
                    instance.name))

        try:
            instance.delete()
        except ProtectedError:
            raise APIConflict(
                'Unable to delete configuration {} while it is assigned to one or more clients'
                .format(instance.name))
Exemple #3
0
 def perform_destroy(self, instance):
     try:
         instance.delete()
     except ProtectedError:
         # TODO(erno): maybe return the objects which reference the cycles (exception.protected_objects)
         raise APIConflict(
             _("Can't delete cycle. It is referenced by another object"))
Exemple #4
0
    def create(self, request):
        """Create a user in OpenStack either in a project and assign default role or standalone"""

        serializer = UserCreateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        os_user = None

        try:
            os_user = self.os_user_api.create_user(**serializer.validated_data)
            # only grant default role if it's assigned for somebody
            if getattr(os_user, 'default_project_id', None):
                self.os_user_api.grant_user_role(
                    project_id=os_user.default_project_id,
                    user=os_user.name,
                    role=plugin_settings.default_role)
        except Conflict:
            raise APIConflict(
                {'detail': _('Username taken. Choose a different name')})
        except ClientException as e:
            LOG.error('OpenStack user creation failed, reason: {0}'.format(e))
            if os_user is not None:
                self.os_user_api.delete_user(os_user)
            raise ValidationError({
                'detail':
                _('Unable to create the user in OpenStack. Check logs for more info'
                  )
            })
        else:
            serializer = UserSerializer(data=os_user.to_dict())
            serializer.is_valid(raise_exception=True)
        return Response(serializer.data, status=HTTP_201_CREATED)
Exemple #5
0
 def stop_impersonation(self, request):
     try:
         request.session.pop('impersonate')
         return Response({'detail': _('User is no longer impersonated')})
     except Exception as e:
         del e  # unused
         raise APIConflict(detail=_('No user is impersonated'))
Exemple #6
0
    def create(self, request, *args, **kwargs):
        if request.user.clients.count(
        ) > 0:  # NOTE(tomo): Removing this should also remove/change the below task
            raise APIConflict(detail=_('Client account already created'),
                              code=rest_status.HTTP_409_CONFLICT)
        resp = super(ClientViewSet, self).create(request=request,
                                                 *args,
                                                 **kwargs)
        # First client created. Execute signup task
        # NOTE(tomo): Change this when multi client support is added
        client = request.user.clients.first()
        order_metadata = OrderMetadata.from_request(request=request)
        if client.billing_settings.auto_create_order:
            product_id = client.billing_settings.auto_order_service
            if product_id:
                product = Product.objects.filter(id=product_id).first()
            else:
                product = None
            if product:
                if not validate_services_limit():
                    raise APIBadRequest(
                        _('Cannot create service, please contact support'), )
            transaction.on_commit(lambda: complete_signup_task.delay(
                user_id=request.user.pk,
                client_id=client.pk,
                product_id=product_id,
                order_metadata=order_metadata.to_json(),
            ))
        else:
            LOG.debug('Auto create order on signup disabled')

        return resp
Exemple #7
0
def fetch_project(request):
    """Returns openstack project for the first client of request.user or throws exceptions"""

    # TODO(Marius): as soon as a client supports multiple projects, implement a create options
    #  view which will return the available projects to select from and also a list of roles
    client = request.user.clients.filter(
        services__openstack_project__isnull=False).first()

    if client is None:
        raise APIConflict(_('No client with an OpenStack project found'))

    return client.first_project
Exemple #8
0
 def dissociate_configurable_option(self, request, pk):
     del pk  # unused
     product = self.get_object()
     option_id = request.data.get('option', None)
     if option_id is None:
         raise APIBadRequest(_('No option provided'))
     try:
         option_id = int(option_id)
     except ValueError:
         raise APIBadRequest(_('Option does not exist'))
     if product.configurable_options.filter(id=option_id).exists() == 0:
         raise APIConflict(_('Option not associated with product'))
     ProductConfigurableOption.objects.filter(
         product=product, configurable_option__id=option_id).delete()
     return Response({'detail': _('Option dissociated')})
Exemple #9
0
    def trigger_revenue_report_generation(self, request):
        month = request.data.get('month', None)
        year = request.data.get('year', None)
        if month is None or year is None:
            raise APIBadRequest(_('Missing year or month.'))
        try:
            month = int(month)
            year = int(year)
        except ValueError:
            raise APIBadRequest(_('Year and month should be integer values'))

        month_and_year = '{}/{}'.format(month, year)
        try:
            generate_revenue_report(month_and_year=month_and_year)
        except InvalidArgument as e:
            raise APIBadRequest(str(e))
        except ReportIsAlreadyGenerating as e:
            raise APIConflict(str(e))
        except RevenueReportTimezoneError as e:
            raise ConfigurationError(str(e))
        else:
            reports_under_generation = MonthlyRevenueReport.objects.filter(
                generating=True)
            if reports_under_generation:
                reports_under_generation_representation = MonthlyRevenueReportSerializer(
                    instance=reports_under_generation,
                    many=True,
                    read_only=True).data
            else:
                reports_under_generation_representation = []

        return Response({
            'detail':
            'OK',
            'reports_under_generation':
            reports_under_generation_representation
        })