class BaseForm(forms.SelfHandlingForm, common.OrderFieldsMixin):
    type = forms.ChoiceField(label=_("Type"),
                             choices=(("flat", _("Flat")), ("rate",
                                                            _("Rate"))))
    cost = forms.DecimalField(label=_("Cost"))
    url = "horizon:admin:hashmap:group_create"
    group_id = forms.DynamicChoiceField(label=_("Group"),
                                        required=False,
                                        add_item_link=url)
    tenant_id = forms.ChoiceField(label=_("Project"), required=False)
    fields_order = ['type', 'cost', 'group_id']

    def __init__(self, request, *args, **kwargs):
        super(BaseForm, self).__init__(request, *args, **kwargs)
        self.order_fields()
        groups = api.cloudkittyclient(request).hashmap.groups.list()
        groups = api.identify(groups)
        choices = [(group.id, group.name) for group in groups]
        choices.insert(0, ('', ' '))
        self.fields['group_id'].choices = choices

        tenants, __ = api_keystone.keystone.tenant_list(request)
        choices_tenants = [(tenant.id, tenant.name) for tenant in tenants]
        choices_tenants.insert(0, (None, ' '))
        self.fields['tenant_id'].choices = choices_tenants
class BaseThresholdForm(BaseForm):
    level = forms.DecimalField(label=_("Level"))
    fields_order = ['level', 'type', 'cost', 'group_id', 'tenant_id']

    def handle(self, request, data):
        thresholds_mgr = api.cloudkittyclient(request).hashmap.thresholds
        threshold = {}
        for k, v in data.items():
            if v:
                threshold[k] = v
        return thresholds_mgr.create(**threshold)
Esempio n. 3
0
class GrantPromotionForm(forms.SelfHandlingForm):
    amount = forms.DecimalField(label='Amount')
    message = forms.CharField(label='Message to User')
    project_id = forms.CharField(label='project_id', widget=forms.HiddenInput)

    def handle(self, request, data):
        if not request.user.is_superuser:
            exceptions.handle(request, u'must be super user')
        try:
            transactions.UserTransactions().grant_user_promotion(
                data['project_id'], data['amount'], data['message'])
        except Exception:
            exceptions.handle(request, u'failed to grant project promotion')
        return True
Esempio n. 4
0
class CardPayForm(horizon_forms.SelfHandlingForm):

    amount = horizon_forms.DecimalField(label=_("Amount (In US Dollars)"),
                                        required=True,
                                        min_value=decimal.Decimal('15'))

    def clean(self):
        if not Card.objects.filter(
                tenant_id__exact=self.request.user.tenant_id,
                default=True).exists():
            raise ValidationError(
                _("Could not find default billing card. "
                  "Please select one of your cards as "
                  "the default for billing."))
        return super(CardPayForm, self).clean()

    def handle(self, request, data):
        try:
            # register charge on stripe
            stripe.Charge.create(
                amount=data['amount'] * 100,  # stripe expects amount in cents.
                currency="usd",
                customer=Card.objects.get(
                    tenant_id__exact=self.request.user.tenant_id,
                    default=True).stripe_customer_id)

            # credit user account
            transactions.UserTransactions().receive_user_payment(
                request.user.tenant_id, "STRIPE", data['amount'],
                "Received payment via Credit/Debit card")

            # profit!!!!
            messages.success(
                request,
                _('You have transferred %s USD to your account.') %
                data['amount'])
            return True
        except (stripe.error.CardError, stripe.error.InvalidRequestError,
                stripe.error.AuthenticationError,
                stripe.error.APIConnectionError,
                stripe.error.StripeError) as e:
            self.api_error(e.message)
            return False
        except django_forms.ValidationError as e:
            self.api_error(e.messages[0])
            return False
        except Exception:
            exceptions.handle(request, ignore=True)
            return False
Esempio n. 5
0
class UpdatePriceForm(forms.SelfHandlingForm):
    resource_price_id = forms.IntegerField(
        label='resource_price_id', widget=forms.HiddenInput)
    instance_type = forms.HiddenInput()
    price = forms.DecimalField(label='price')

    def __init__(self, request, *args, **kwargs):
        super(UpdatePriceForm, self).__init__(request, *args, **kwargs)

    def handle(self, request, data):
        try:
            price = Price.objects.get(id=data['resource_price_id'])
            price.price = data['price']
            price.save()
        except Exception:
            exceptions.handle(request, u'failed to update object')
        return True