示例#1
0
    def post(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=self.request.data)
        serializer.is_valid(raise_exception=True)

        user = self.get_user()
        token = default_token_generator.make_token(user)
        uid = urlsafe_base64_encode(force_bytes(user.pk))
        context = {
            'user': user,
            'token': token,
            'uid': uid,
            'reset_link': ForgotPasswordView.generate_reset_link(uid, token),
        }
        email_data = {
            'subject': 'Password Reset',
            'to': user.email,
            'context': context,
            'template_name': 'password_reset_email',
            'template_path': 'authentication/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        return Response('OK')
示例#2
0
    def post(self, request, *args, **kwargs):
        owner = self.request.user
        vm = self.get_object()

        opennebula_vm_id = self.kwargs.get('pk')

        manager = OpenNebulaManager(email=owner.email, password=owner.password)

        terminated = manager.delete_vm(vm.id)

        if not terminated:
            messages.error(request,
                           'Error terminating VM %s' % (opennebula_vm_id))
            return HttpResponseRedirect(self.get_success_url())

        context = {
            'vm':
            vm,
            'base_url':
            "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }
        email_data = {
            'subject': 'Virtual machine plan canceled',
            'to': self.request.user.email,
            'context': context,
            'template_name': 'vm_status_changed',
            'template_path': 'hosting/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.error(request,
                       'VM %s terminated successfully' % (opennebula_vm_id))

        return HttpResponseRedirect(self.get_success_url())
示例#3
0
    def post(self, request, *args, **kwargs):
        data = request.POST
        vms = BetaAccessVM.create(data)

        context = {
            'base_url':
            "{0}://{1}".format(self.request.scheme, self.request.get_host()),
            'email':
            data.get('email'),
            'name':
            data.get('name'),
            'vms':
            vms
        }

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'from_address':
            '(datacenterlight) datacenterlight Support <*****@*****.**>',
            'to': '*****@*****.**',
            'context': context,
            'template_name': 'request_beta_access_notification',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.add_message(self.request, messages.SUCCESS,
                             self.success_message)
        return HttpResponseRedirect(self.get_success_url())
示例#4
0
 def register(cls,
              name,
              password,
              email,
              app='digital_glarus',
              base_url=None,
              send_email=True,
              account_details=None):
     user = cls.objects.filter(email=email).first()
     if not user:
         user = cls.objects.create_user(name=name,
                                        email=email,
                                        password=password)
         if user:
             if app == 'digital_glarus':
                 dg = DigitalGlarusRegistrationMailer(user.validation_slug)
                 dg.send_mail(to=user.email)
             elif app == 'dcl':
                 dcl_text = settings.DCL_TEXT
                 user.is_active = False
                 if send_email is True:
                     email_data = {
                         'subject':
                         '{dcl_text} {account_activation}'.format(
                             dcl_text=dcl_text,
                             account_activation=_('Account Activation')),
                         'from_address':
                         settings.DCL_SUPPORT_FROM_ADDRESS,
                         'to':
                         user.email,
                         'context': {
                             'base_url':
                             base_url,
                             'activation_link':
                             reverse('hosting:validate',
                                     kwargs={
                                         'validate_slug':
                                         user.validation_slug
                                     }),
                             'dcl_text':
                             dcl_text
                         },
                         'template_name':
                         'user_activation',
                         'template_path':
                         'datacenterlight/emails/'
                     }
                     if account_details:
                         email_data['context'][
                             'account_details'] = account_details
                     email = BaseEmail(**email_data)
                     email.send()
             return user
         else:
             return None
     else:
         return None
示例#5
0
    def post(self, *args, **kwargs):
        vm = self.get_object()
        vm.cancel_plan()

        context = {
            'vm': vm,
            'base_url': "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }
        email_data = {
            'subject': 'Virtual machine plan canceled',
            'to': self.request.user.email,
            'context': context,
            'template_name': 'vm_status_changed',
            'template_path': 'hosting/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        return HttpResponseRedirect(self.get_success_url())
示例#6
0
    def post(self, request, *args, **kwargs):
        owner = self.request.user
        vm = self.get_object()

        opennebula_vm_id = self.kwargs.get('pk')

        manager = OpenNebulaManager(
            email=owner.email,
            password=owner.password
        )

        terminated = manager.delete_vm(
            vm.id
        )

        if not terminated:
            messages.error(
                request,
                'Error terminating VM %s' % (opennebula_vm_id)
            )
            return HttpResponseRedirect(self.get_success_url())

        context = {
            'vm': vm,
            'base_url': "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }
        email_data = {
            'subject': 'Virtual machine plan canceled',
            'to': self.request.user.email,
            'context': context,
            'template_name': 'vm_status_changed',
            'template_path': 'hosting/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.error(
            request,
            'VM %s terminated successfully' % (opennebula_vm_id)
        )

        return HttpResponseRedirect(self.get_success_url())
示例#7
0
 def register(cls,
              name,
              password,
              email,
              app='digital_glarus',
              base_url=None):
     user = cls.objects.filter(email=email).first()
     if not user:
         user = cls.objects.create_user(name=name,
                                        email=email,
                                        password=password)
         if user:
             if app == 'digital_glarus':
                 dg = DigitalGlarusRegistrationMailer(user.validation_slug)
                 dg.send_mail(to=user.email)
             elif app == 'dcl':
                 user.is_active = False
                 email_data = {
                     'subject':
                     _('Activate your Data Center Light account'),
                     'from_address':
                     '(Data Center Light) Data Center Light Support <*****@*****.**>',
                     'to': user.email,
                     'context': {
                         'base_url':
                         base_url,
                         'activation_link':
                         reverse(
                             'hosting:validate',
                             kwargs={'validate_slug': user.validation_slug})
                     },
                     'template_name': 'user_activation',
                     'template_path': 'datacenterlight/emails/'
                 }
                 email = BaseEmail(**email_data)
                 email.send()
             return user
         else:
             return None
     else:
         return None
示例#8
0
    def form_valid(self, form):

        context = {
            'base_url': "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'to': form.cleaned_data.get('email'),
            'context': context,
            'template_name': 'request_access_confirmation',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        context.update({
            'email': form.cleaned_data.get('email')
        })

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'to': '*****@*****.**',
            'context': context,
            'template_name': 'request_access_notification',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.add_message(self.request, messages.SUCCESS, self.success_message)
        return render(self.request, 'datacenterlight/beta_success.html', {})
示例#9
0
    def form_valid(self, form):

        context = {
            'base_url': "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'from_address': '(datacenterlight) datacenterlight Support <*****@*****.**>',
            'to': form.cleaned_data.get('email'),
            'from': '(datacenterlight) DatacenterLight Support [email protected]',
            'context': context,
            'template_name': 'request_access_confirmation',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        context.update({
            'email': form.cleaned_data.get('email')
        })

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'from_address': '(datacenterlight) datacenterlight Support <*****@*****.**>',
            'to': '*****@*****.**',
            'context': context,
            'template_name': 'request_access_notification',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.add_message(self.request, messages.SUCCESS, self.success_message)
        return super(IndexView, self).form_valid(form)
示例#10
0
    def post(self, request, *args, **kwargs):
        data = request.POST
        vms = BetaAccessVM.create(data)

        context = {
            'base_url': "{0}://{1}".format(self.request.scheme, self.request.get_host()),
            'email': data.get('email'),
            'name': data.get('name'),
            'vms': vms
        }

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'to': '*****@*****.**',
            'context': context,
            'template_name': 'request_beta_access_notification',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.add_message(self.request, messages.SUCCESS, self.success_message)
        return HttpResponseRedirect(self.get_success_url())
示例#11
0
    def form_valid(self, form):

        booking_order = self.get_object()
        booking_order.cancel()
        request = self.request

        BookingCancellation.create(booking_order)

        context = {
            'order': booking_order,
            'booking': booking_order.booking,
            'base_url': "{0}://{1}".format(request.scheme, request.get_host()),
            'user': request.user
        }

        email_data = {
            'subject': 'A cancellation has been requested',
            'to': '*****@*****.**',
            'context': context,
            'template_name': 'booking_cancellation_notification',
            'template_path': 'digitalglarus/emails/'
        }

        email = BaseEmail(**email_data)
        email.send()

        context = {
            'order': booking_order,
            'booking': booking_order.booking,
            'base_url': "{0}://{1}".format(request.scheme, request.get_host())
        }
        email_data = {
            'subject': 'Your booking has been cancelled',
            'to': request.user.email,
            'context': context,
            'template_name': 'booking_cancellation',
            'template_path': 'digitalglarus/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.add_message(self.request, messages.SUCCESS,
                             self.success_message)

        return HttpResponseRedirect(self.get_success_url())
示例#12
0
    def form_valid(self, form):

        context = {
            'base_url':
            "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'from_address':
            '(datacenterlight) datacenterlight Support <*****@*****.**>',
            'to': form.cleaned_data.get('email'),
            'from':
            '(datacenterlight) DatacenterLight Support [email protected]',
            'context': context,
            'template_name': 'request_access_confirmation',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        context.update({'email': form.cleaned_data.get('email')})

        email_data = {
            'subject': 'DatacenterLight Beta Access Request',
            'from_address':
            '(datacenterlight) datacenterlight Support <*****@*****.**>',
            'to': '*****@*****.**',
            'context': context,
            'template_name': 'request_access_notification',
            'template_path': 'datacenterlight/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.add_message(self.request, messages.SUCCESS,
                             self.success_message)
        return super(IndexView, self).form_valid(form)
示例#13
0
    def form_valid(self, form):

        booking_order = self.get_object()
        booking_order.cancel()
        request = self.request

        BookingCancellation.create(booking_order)

        context = {
            'order': booking_order,
            'booking': booking_order.booking,
            'base_url': "{0}://{1}".format(request.scheme, request.get_host()),
            'user': request.user

        }

        email_data = {
            'subject': 'A cancellation has been requested',
            'to': '*****@*****.**',
            'context': context,
            'template_name': 'booking_cancellation_notification',
            'template_path': 'digitalglarus/emails/'
        }

        email = BaseEmail(**email_data)
        email.send()

        context = {
            'order': booking_order,
            'booking': booking_order.booking,
            'base_url': "{0}://{1}".format(request.scheme, request.get_host())

        }
        email_data = {
            'subject': 'Your booking has been cancelled',
            'to': request.user.email,
            'context': context,
            'template_name': 'booking_cancellation',
            'template_path': 'digitalglarus/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        messages.add_message(self.request, messages.SUCCESS, self.success_message)

        return HttpResponseRedirect(self.get_success_url())
示例#14
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            context = self.get_context_data()
            token = form.cleaned_data.get('token')
            donation_amount = form.cleaned_data.get('donation_amount')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            stripe_utils.CURRENCY = 'usd'
            charge_response = stripe_utils.make_charge(amount=donation_amount,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            # Create a donation
            charge = charge_response.get('response_object')
            donation_data = request.POST.copy()
            donation_data.update({
                'cc_brand': charge.source.brand,
                'stripe_charge_id': charge.id,
                'last4': charge.source.last4,
                'billing_address': billing_address.id,
                'donator': customer.id,
                'donation': donation_amount
            })
            donation_form = DonationForm(donation_data)
            if donation_form.is_valid():

                # reactivate donation status
                donation = donation_form.save()

                try:
                    donator_status = DonatorStatus.objects.get(user=self.request.user)
                    donator_status.set_active()
                except DonatorStatus.DoesNotExist:
                    pass

                donation = donation_form.save()

                context = {
                    'donation': donation,
                    'base_url': "{0}://{1}".format(request.scheme, request.get_host())

                }
                email_data = {
                    'subject': 'Your donation have been charged',
                    'to': request.user.email,
                    'context': context,
                    'template_name': 'donation_charge',
                    'template_path': 'nosystemd/emails/'
                }
                email = BaseEmail(**email_data)
                email.send()

                return HttpResponseRedirect(reverse('nosystemd:donations',
                                                    kwargs={'pk': donation.id}))
            else:
                self.form_invalid(donation_form)

        else:
            return self.form_invalid(form)
示例#15
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():

            # Get billing address data
            billing_address_data = form.cleaned_data

            context = self.get_context_data()

            template = request.session.get('template')
            specs = request.session.get('specs')

            vm_template_id = template.get('id', 1)

            final_price = specs.get('price')

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

            owner = self.request.user

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=owner.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=final_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create OpenNebulaManager
            manager = OpenNebulaManager(email=owner.email,
                                        password=owner.password)
            # Get user ssh key
            if not UserHostingKey.objects.filter( user=self.request.user).exists():
                context.update({
                    'sshError': 'error',
                    'form': form
                })
                return render(request, self.template_name, context)
            # For now just get first one
            user_key = UserHostingKey.objects.filter(
                    user=self.request.user).first()
            
            # Create a vm using logged user
            vm_id = manager.create_vm(
                template_id=vm_template_id,
                # XXX: Confi
                specs=specs,
                ssh_key=user_key.public_key,
            )

            # Create a Hosting Order
            order = HostingOrder.create(
                price=final_price,
                vm_id=vm_id,
                customer=customer,
                billing_address=billing_address
            )

            # Create a Hosting Bill
            bill = HostingBill.create(
                customer=customer, billing_address=billing_address)

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                billing_address_data.update({
                    'user': customer.user.id
                })
                billing_address_user_form = UserBillingAddressForm(
                    billing_address_data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Associate an order with a stripe payment
            order.set_stripe_charge(charge)

            # If the Stripe payment was successed, set order status approved
            order.set_approved()

            vm = VirtualMachineSerializer(manager.get_vm(vm_id)).data

            # Send notification to ungleich as soon as VM has been booked
            context = {
                'vm': vm,
                'order': order,
                'base_url': "{0}://{1}".format(request.scheme, request.get_host())

            }
            email_data = {
                'subject': 'New VM request',
                'to': request.user.email,
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(reverse('hosting:orders', kwargs={'pk': order.id}))
        else:
            return self.form_invalid(form)
示例#16
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            data = form.cleaned_data
            context = self.get_context_data()
            token = data.get('token')
            membership_type = data.get('membership_type')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=membership_type.first_month_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create Billing Address
            billing_address = form.save()

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                data.update({
                    'user': customer.user.id
                })
                billing_address_user_form = UserBillingAddressForm(data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Get membership dates
            membership_start_date, membership_end_date = membership_type.first_month_range

            # Create membership plan
            membership_data = {
                'type': membership_type,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }
            membership = Membership.create(membership_data)

            # Create membership order
            order_data = {
                'membership': membership,
                'customer': customer,
                'billing_address': billing_address,
                'stripe_charge': charge,
                'amount': membership_type.first_month_price,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }

            membership_order = MembershipOrder.create(order_data)

            request.session.update({
                'membership_price': membership.type.first_month_price,
                'membership_dates': membership.type.first_month_formated_range
            })

            context = {
                'membership': membership,
                'order': membership_order,
                'membership_start_date': membership_start_date,
                'membership_end_date': membership_end_date,
                'base_url': "{0}://{1}".format(request.scheme, request.get_host())

            }
            email_data = {
                'subject': 'Your membership has been charged',
                'to': request.user.email,
                'context': context,
                'template_name': 'membership_charge',
                'template_path': 'digitalglarus/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(reverse('digitalglarus:membership_activated'))

        else:
            return self.form_invalid(form)
    def handle(self, *args, **options):
        translation.activate('en-us')
        memberships_orders = MembershipOrder.objects.filter(membership__active=True)
        current_month = datetime.now().month
        current_year = datetime.now().year

        print("--------- STARTING MEMBERSHIP CHARGING SCRIPT  ---------")
        print("Memberhips date: %s-%s" % (current_month, current_year))

        for membership_order in memberships_orders:
            member = membership_order.customer
            try:
                MembershipOrder.objects.get(created_at__month=current_month,
                                            created_at__year=current_year,
                                            customer=member)
            except MembershipOrder.DoesNotExist:
                try:
                    current_membership_price = membership_order.membership.type.price

                    last_membership_order = MembershipOrder.objects.filter(customer=member).last()

                    # Make stripe charge to a customer
                    stripe_utils = StripeUtils()
                    stripe_utils.CURRENCY = self.CURRENCY
                    charge_response = stripe_utils.make_charge(amount=current_membership_price,
                                                               customer=member.stripe_id)
                    charge = charge_response.get('response_object')
                    # Check if the payment was approved
                    if not charge:
                        # There is an error trying to creating the stripe charge
                        context = {
                            'paymentError': charge_response.get('error'),
                        }
                        print("--------- STRIPE PAYMENT ERROR ---------")
                        print(context)
                        print("-------------------------")
                        continue

                    # Create a donation
                    charge = charge_response.get('response_object')
                    membership_order_data = {
                        'cc_brand': charge.source.brand,
                        'stripe_charge_id': charge.id,
                        'last4': charge.source.last4,
                        'membership': last_membership_order.membership.id,
                        'billing_address': last_membership_order.billing_address.id,
                        'customer': member.id,
                        'amount': current_membership_price
                    }
                    membership_order_form = MembershipOrderForm(membership_order_data)
                    if membership_order_form.is_valid():
                        membership_order = membership_order_form.save()

                        context = {
                            'order': membership_order,
                            'base_url': "{0}://{1}".format('https', 'dynamicweb.ungleich.ch')

                        }
                        email_data = {
                            'subject': 'Your monthly membership has been charged',
                            'to': member.user.email,
                            'context': context,
                            'template_name': 'membership_monthly_charge',
                            'template_path': 'digitalglarus/emails/'
                        }
                        email = BaseEmail(**email_data)
                        email.send()

                        print("--------- PAYMENT DONATION SUCCESSFULL ---------")
                        print("Member: %s" % member.user.email)
                        print("Amount: %s %s" % (current_membership_price, self.CURRENCY))
                        print("-----------------------------------------------")

                except Exception as e:
                    print("--------- ERROR ---------")
                    print(e)
                    print("-------------------------")
                    continue
示例#18
0
def create_vm_task(self, vm_template_id, user, specs, template, order_id):
    logger.debug("Running create_vm_task on {}".format(
        current_task.request.hostname))
    vm_id = None
    try:
        final_price = (specs.get('total_price')
                       if 'total_price' in specs else specs.get('price'))

        if 'pass' in user:
            on_user = user.get('email')
            on_pass = user.get('pass')
            logger.debug("Using user {user} to create VM".format(user=on_user))
            vm_name = None
        else:
            on_user = settings.OPENNEBULA_USERNAME
            on_pass = settings.OPENNEBULA_PASSWORD
            logger.debug("Using OpenNebula admin user to create VM")
            vm_name = "{email}-{template_name}-{date}".format(
                email=user.get('email'),
                template_name=template.get('name'),
                date=int(datetime.now().strftime("%s")))

        # Create OpenNebulaManager
        manager = OpenNebulaManager(email=on_user, password=on_pass)

        vm_id = manager.create_vm(
            template_id=vm_template_id,
            specs=specs,
            ssh_key=settings.ONEADMIN_USER_SSH_PUBLIC_KEY,
            vm_name=vm_name)

        if vm_id is None:
            raise Exception("Could not create VM")

        # Update HostingOrder with the created vm_id
        hosting_order = HostingOrder.objects.filter(id=order_id).first()
        error_msg = None

        try:
            hosting_order.vm_id = vm_id
            hosting_order.save()
            logger.debug("Updated hosting_order {} with vm_id={}".format(
                hosting_order.id, vm_id))
        except Exception as ex:
            error_msg = (
                "HostingOrder with id {order_id} not found. This means that "
                "the hosting order was not created and/or it is/was not "
                "associated with VM with id {vm_id}. Details {details}".format(
                    order_id=order_id, vm_id=vm_id, details=str(ex)))
            logger.error(error_msg)

        stripe_utils = StripeUtils()
        result = stripe_utils.set_subscription_metadata(
            subscription_id=hosting_order.subscription_id,
            metadata={"VM_ID": str(vm_id)})

        if result.get('error') is not None:
            emsg = "Could not update subscription metadata for {sub}".format(
                sub=hosting_order.subscription_id)
            logger.error(emsg)
            if error_msg:
                error_msg += ". " + emsg
            else:
                error_msg = emsg

        vm = VirtualMachineSerializer(manager.get_vm(vm_id)).data

        context = {
            'name': user.get('name'),
            'email': user.get('email'),
            'cores': specs.get('cpu'),
            'memory': specs.get('memory'),
            'storage': specs.get('disk_size'),
            'price': final_price,
            'template': template.get('name'),
            'vm_name': vm.get('name'),
            'vm_id': vm['vm_id'],
            'order_id': order_id
        }

        if error_msg:
            context['errors'] = error_msg
        if 'pricing_name' in specs:
            context['pricing'] = str(
                VMPricing.get_vm_pricing_by_name(name=specs['pricing_name']))
        email_data = {
            'subject': settings.DCL_TEXT + " Order from %s" % context['email'],
            'from_email': settings.DCL_SUPPORT_FROM_ADDRESS,
            'to': ['*****@*****.**'],
            'body':
            "\n".join(["%s=%s" % (k, v) for (k, v) in context.items()]),
            'reply_to': [context['email']],
        }
        email = EmailMessage(**email_data)
        email.send()

        if 'pass' in user:
            lang = 'en-us'
            if user.get('language') is not None:
                logger.debug("Language is set to {}".format(
                    user.get('language')))
                lang = user.get('language')
            translation.activate(lang)
            # Send notification to the user as soon as VM has been booked
            context = {
                'base_url':
                "{0}://{1}".format(user.get('request_scheme'),
                                   user.get('request_host')),
                'order_url':
                reverse('hosting:orders', kwargs={'pk': order_id}),
                'page_header':
                _('Your New VM %(vm_name)s at Data Center Light') % {
                    'vm_name': vm.get('name')
                },
                'vm_name':
                vm.get('name')
            }
            email_data = {
                'subject': context.get('page_header'),
                'to': user.get('email'),
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/',
                'from_address': settings.DCL_SUPPORT_FROM_ADDRESS,
            }
            email = BaseEmail(**email_data)
            email.send()

            # try to see if we have the IPv6 of the new vm and that if the ssh
            # keys can be configured
            vm_ipv6 = manager.get_ipv6(vm_id)
            logger.debug("New VM ID is {vm_id}".format(vm_id=vm_id))
            if vm_ipv6 is not None:
                custom_user = CustomUser.objects.get(email=user.get('email'))
                get_or_create_vm_detail(custom_user, manager, vm_id)
                if custom_user is not None:
                    public_keys = get_all_public_keys(custom_user)
                    keys = [{
                        'value': key,
                        'state': True
                    } for key in public_keys]
                    if len(keys) > 0:
                        logger.debug("Calling configure on {host} for "
                                     "{num_keys} keys".format(
                                         host=vm_ipv6, num_keys=len(keys)))
                        # Let's wait until the IP responds to ping before we
                        # run the cdist configure on the host
                        did_manage_public_key = False
                        for i in range(0, 15):
                            if ping_ok(vm_ipv6):
                                logger.debug(
                                    "{} is pingable. Doing a "
                                    "manage_public_key".format(vm_ipv6))
                                sleep(10)
                                manager.manage_public_key(keys,
                                                          hosts=[vm_ipv6])
                                did_manage_public_key = True
                                break
                            else:
                                logger.debug(
                                    "Can't ping {}. Wait 5 secs".format(
                                        vm_ipv6))
                                sleep(5)
                        if not did_manage_public_key:
                            emsg = ("Waited for over 75 seconds for {} to be "
                                    "pingable. But the VM was not reachable. "
                                    "So, gave up manage_public_key. Please do "
                                    "this manually".format(vm_ipv6))
                            logger.error(emsg)
                            email_data = {
                                'subject':
                                '{} CELERY TASK INCOMPLETE: {} not '
                                'pingable for 75 seconds'.format(
                                    settings.DCL_TEXT, vm_ipv6),
                                'from_email':
                                current_task.request.hostname,
                                'to':
                                settings.DCL_ERROR_EMAILS_TO_LIST,
                                'body':
                                emsg
                            }
                            email = EmailMessage(**email_data)
                            email.send()
    except Exception as e:
        logger.error(str(e))
        try:
            retry_task(self)
        except MaxRetriesExceededError:
            msg_text = 'Finished {} retries for create_vm_task'.format(
                self.request.retries)
            logger.error(msg_text)
            # Try sending email and stop
            email_data = {
                'subject':
                '{} CELERY TASK ERROR: {}'.format(settings.DCL_TEXT, msg_text),
                'from_email':
                current_task.request.hostname,
                'to':
                settings.DCL_ERROR_EMAILS_TO_LIST,
                'body':
                ',\n'.join(str(i) for i in self.request.args)
            }
            email = EmailMessage(**email_data)
            email.send()
            return

    return vm_id
示例#19
0
    def form_valid(self, form):
        data = form.cleaned_data
        context = self.get_context_data()
        token = data.get('token')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        is_free = context.get('is_free')
        normal_price, final_price, free_days = Booking.\
            booking_price(self.request.user, start_date, end_date)
        charge = None

        # if not credit_card_needed:
        # Get or create stripe customer
        customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                token=token)
        if not customer:
            form.add_error("__all__", "Invalid credit card")
            return self.render_to_response(self.get_context_data(form=form))

        # If booking is not free, make the stripe charge
        if not is_free:
            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=final_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(self.request, self.template_name, context)

            charge = charge_response.get('response_object')

        # Create Billing Address for Membership Order
        billing_address = form.save()

        # Create Billing Address for User if he does not have one
        if not customer.user.billing_addresses.count():
            data.update({
                'user': customer.user.id
            })
            billing_address_user_form = UserBillingAddressForm(data)
            billing_address_user_form.is_valid()
            billing_address_user_form.save()

        # Create Booking
        booking_data = {
            'start_date': start_date,
            'end_date': end_date,
            'start_date': start_date,
            'free_days': free_days,
            'price': normal_price,
            'final_price': final_price,
        }
        booking = Booking.create(booking_data)

        # Create Booking order
        order_data = {
            'booking': booking,
            'customer': customer,
            'billing_address': billing_address,
            'stripe_charge': charge,
            'amount': final_price,
            'original_price': normal_price,
            'special_month_price': BookingPrice.objects.last().special_month_price,
        }
        order = BookingOrder.create(order_data)

        context = {
            'booking': booking,
            'order': order,
            'base_url': "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }

        email_data = {
            'subject': 'Your booking order has been placed',
            'to': self.request.user.email,
            'context': context,
            'template_name': 'booking_order_email',
            'template_path': 'digitalglarus/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        return HttpResponseRedirect(self.get_success_url(order.id))
示例#20
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():

            # Get billing address data
            billing_address_data = form.cleaned_data

            context = self.get_context_data()

            template = request.session.get('template')
            specs = request.session.get('specs')

            vm_template_id = template.get('id', 1)

            final_price = specs.get('price')

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

            owner = self.request.user

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=owner.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(
                    self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=final_price, customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create OpenNebulaManager
            manager = OpenNebulaManager(email=owner.email,
                                        password=owner.password)
            # Get user ssh key
            if not UserHostingKey.objects.filter(
                    user=self.request.user).exists():
                context.update({'sshError': 'error', 'form': form})
                return render(request, self.template_name, context)
            # For now just get first one
            user_key = UserHostingKey.objects.filter(
                user=self.request.user).first()

            # Create a vm using logged user
            vm_id = manager.create_vm(
                template_id=vm_template_id,
                # XXX: Confi
                specs=specs,
                ssh_key=user_key.public_key,
            )

            # Create a Hosting Order
            order = HostingOrder.create(price=final_price,
                                        vm_id=vm_id,
                                        customer=customer,
                                        billing_address=billing_address)

            # Create a Hosting Bill
            bill = HostingBill.create(customer=customer,
                                      billing_address=billing_address)

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                billing_address_data.update({'user': customer.user.id})
                billing_address_user_form = UserBillingAddressForm(
                    billing_address_data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Associate an order with a stripe payment
            order.set_stripe_charge(charge)

            # If the Stripe payment was successed, set order status approved
            order.set_approved()

            vm = VirtualMachineSerializer(manager.get_vm(vm_id)).data

            # Send notification to ungleich as soon as VM has been booked
            context = {
                'vm': vm,
                'order': order,
                'base_url': "{0}://{1}".format(request.scheme,
                                               request.get_host())
            }
            email_data = {
                'subject': 'New VM request',
                'to': request.user.email,
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(
                reverse('hosting:orders', kwargs={'pk': order.id}))
        else:
            return self.form_invalid(form)
示例#21
0
    def form_valid(self, form):
        data = form.cleaned_data
        context = self.get_context_data()
        token = data.get('token')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        is_free = context.get('is_free')
        normal_price, final_price, free_days = Booking.\
            booking_price(self.request.user, start_date, end_date)
        charge = None

        # if not credit_card_needed:
        # Get or create stripe customer
        customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                token=token)
        if not customer:
            form.add_error("__all__", "Invalid credit card")
            return self.render_to_response(self.get_context_data(form=form))

        # If booking is not free, make the stripe charge
        if not is_free:
            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=final_price, customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(self.request, self.template_name, context)

            charge = charge_response.get('response_object')

        # Create Billing Address for Membership Order
        billing_address = form.save()

        # Create Billing Address for User if he does not have one
        if not customer.user.billing_addresses.count():
            data.update({'user': customer.user.id})
            billing_address_user_form = UserBillingAddressForm(data)
            billing_address_user_form.is_valid()
            billing_address_user_form.save()

        # Create Booking
        booking_data = {
            'start_date': start_date,
            'end_date': end_date,
            'start_date': start_date,
            'free_days': free_days,
            'price': normal_price,
            'final_price': final_price,
        }
        booking = Booking.create(booking_data)

        # Create Booking order
        order_data = {
            'booking': booking,
            'customer': customer,
            'billing_address': billing_address,
            'stripe_charge': charge,
            'amount': final_price,
            'original_price': normal_price,
            'special_month_price':
            BookingPrice.objects.last().special_month_price,
        }
        order = BookingOrder.create(order_data)

        context = {
            'booking':
            booking,
            'order':
            order,
            'base_url':
            "{0}://{1}".format(self.request.scheme, self.request.get_host())
        }

        email_data = {
            'subject': 'Your booking order has been placed',
            'to': self.request.user.email,
            'context': context,
            'template_name': 'booking_order_email',
            'template_path': 'digitalglarus/emails/'
        }
        email = BaseEmail(**email_data)
        email.send()

        return HttpResponseRedirect(self.get_success_url(order.id))
示例#22
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            context = self.get_context_data()
            specifications = request.session.get('vm_specs')
            vm_type = specifications.get('hosting_company')
            vm = VirtualMachineType.objects.get(hosting_company=vm_type)
            final_price = vm.calculate_price(specifications)

            plan_data = {
                'vm_type': vm,
                'cores': specifications.get('cores'),
                'memory': specifications.get('memory'),
                'disk_size': specifications.get('disk_size'),
                'configuration': specifications.get('configuration'),
                'price': final_price
            }
            token = form.cleaned_data.get('token')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email,
                                                    token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Virtual Machine Plan
            plan = VirtualMachinePlan.create(plan_data, request.user)

            # Create Billing Address
            billing_address = form.save()

            # Create a Hosting Order
            order = HostingOrder.create(vm_plan=plan, customer=customer,
                                        billing_address=billing_address)

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(amount=final_price,
                                                       customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Associate an order with a stripe payment
            order.set_stripe_charge(charge)

            # If the Stripe payment was successed, set order status approved
            order.set_approved()

            # Send notification to ungleich as soon as VM has been booked
            context = {
                'vm': plan,
                'order': order,
                'base_url': "{0}://{1}".format(request.scheme, request.get_host())

            }
            email_data = {
                'subject': 'New VM request',
                'to': request.user.email,
                'context': context,
                'template_name': 'new_booked_vm',
                'template_path': 'hosting/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(reverse('hosting:orders', kwargs={'pk': order.id}))
        else:
            return self.form_invalid(form)
示例#23
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            data = form.cleaned_data
            context = self.get_context_data()
            token = data.get('token')
            membership_type = data.get('membership_type')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(
                email=self.request.user.email, token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(
                    self.get_context_data(form=form))

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=membership_type.first_month_price,
                customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                email_to_admin_data = {
                    'subject':
                    "Could not create charge for Digital Glarus "
                    "user: {user}".format(user=self.request.user.email),
                    'from_email':
                    '*****@*****.**',
                    'to': ['*****@*****.**'],
                    'body':
                    "\n".join([
                        "%s=%s" % (k, v) for (k, v) in charge_response.items()
                    ]),
                }
                send_plain_email_task.delay(email_to_admin_data)
                return render(request, self.template_name, context)

            # Subscribe the customer to dg plan from the next month onwards
            stripe_plan = stripe_utils.get_or_create_stripe_plan(
                amount=membership_type.price,
                name='Digital Glarus {sub_type_name} Subscription'.format(
                    sub_type_name=membership_type.name),
                stripe_plan_id='dg-{sub_type_name}'.format(
                    sub_type_name=membership_type.name))
            subscription_result = stripe_utils.subscribe_customer_to_plan(
                customer.stripe_id,
                [{
                    "plan": stripe_plan.get('response_object').stripe_plan_id
                }],
                trial_end=membership_type.next_month_in_sec_since_epoch)
            stripe_subscription_obj = subscription_result.get(
                'response_object')
            # Check if call to create subscription was ok
            if (stripe_subscription_obj is None
                    or (stripe_subscription_obj.status != 'active'
                        and stripe_subscription_obj.status != 'trialing')):
                context.update({
                    'paymentError': subscription_result.get('error'),
                    'form': form
                })
                email_to_admin_data = {
                    'subject':
                    "Could not create Stripe subscription for "
                    "Digital Glarus user: {user}".format(
                        user=self.request.user.email),
                    'from_email':
                    '*****@*****.**',
                    'to': ['*****@*****.**'],
                    'body':
                    "\n".join([
                        "%s=%s" % (k, v)
                        for (k, v) in subscription_result.items()
                    ]),
                }
                send_plain_email_task.delay(email_to_admin_data)
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')
            if 'source' in charge:
                cardholder_name = charge['source']['name']
            else:
                cardholder_name = customer.user.name

            # Create Billing Address
            billing_address = form.save()

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                data.update({
                    'user': customer.user.id,
                    'cardholder_name': cardholder_name
                })
                billing_address_user_form = UserBillingAddressForm(data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Get membership dates
            membership_start_date, membership_end_date = membership_type.first_month_range

            # Create or update membership plan
            membership_data = {
                'type': membership_type,
                'active': True,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }
            membership = Membership.activate_or_crete(membership_data,
                                                      self.request.user)

            # Create membership order
            order_data = {
                'membership': membership,
                'customer': customer,
                'billing_address': billing_address,
                'stripe_charge': charge,
                'stripe_subscription_id': stripe_subscription_obj.id,
                'amount': membership_type.first_month_price,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }

            membership_order = MembershipOrder.create(order_data)

            request.session.update({
                'membership_price':
                membership.type.first_month_price,
                'membership_dates':
                membership.type.first_month_formated_range
            })

            email_to_admin_data = {
                'subject':
                "New Digital Glarus subscription: {user}".format(
                    user=self.request.user.email),
                'from_email':
                '*****@*****.**',
                'to': ['*****@*****.**'],
                'body':
                "\n".join(["%s=%s" % (k, v) for (k, v) in order_data.items()]),
            }
            send_plain_email_task.delay(email_to_admin_data)

            context = {
                'membership': membership,
                'order': membership_order,
                'membership_start_date': membership_start_date,
                'membership_end_date': membership_end_date,
                'base_url': "{0}://{1}".format(request.scheme,
                                               request.get_host())
            }
            email_data = {
                'subject': 'Your membership has been charged',
                'to': request.user.email,
                'context': context,
                'template_name': 'membership_charge',
                'template_path': 'digitalglarus/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(
                reverse('digitalglarus:membership_activated'))

        else:
            return self.form_invalid(form)
示例#24
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            data = form.cleaned_data
            context = self.get_context_data()
            token = data.get('token')
            membership_type = data.get('membership_type')

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(
                email=self.request.user.email, token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(
                    self.get_context_data(form=form))

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            charge_response = stripe_utils.make_charge(
                amount=membership_type.first_month_price,
                customer=customer.stripe_id)
            charge = charge_response.get('response_object')

            # Check if the payment was approved
            if not charge:
                context.update({
                    'paymentError': charge_response.get('error'),
                    'form': form
                })
                return render(request, self.template_name, context)

            charge = charge_response.get('response_object')

            # Create Billing Address
            billing_address = form.save()

            # Create Billing Address for User if he does not have one
            if not customer.user.billing_addresses.count():
                data.update({'user': customer.user.id})
                billing_address_user_form = UserBillingAddressForm(data)
                billing_address_user_form.is_valid()
                billing_address_user_form.save()

            # Get membership dates
            membership_start_date, membership_end_date = membership_type.first_month_range

            # Create or update membership plan
            membership_data = {
                'type': membership_type,
                'active': True,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }
            membership = Membership.activate_or_crete(membership_data,
                                                      self.request.user)

            # Create membership order
            order_data = {
                'membership': membership,
                'customer': customer,
                'billing_address': billing_address,
                'stripe_charge': charge,
                'amount': membership_type.first_month_price,
                'start_date': membership_start_date,
                'end_date': membership_end_date
            }

            membership_order = MembershipOrder.create(order_data)

            request.session.update({
                'membership_price':
                membership.type.first_month_price,
                'membership_dates':
                membership.type.first_month_formated_range
            })

            context = {
                'membership': membership,
                'order': membership_order,
                'membership_start_date': membership_start_date,
                'membership_end_date': membership_end_date,
                'base_url': "{0}://{1}".format(request.scheme,
                                               request.get_host())
            }
            email_data = {
                'subject': 'Your membership has been charged',
                'to': request.user.email,
                'context': context,
                'template_name': 'membership_charge',
                'template_path': 'digitalglarus/emails/'
            }
            email = BaseEmail(**email_data)
            email.send()

            return HttpResponseRedirect(
                reverse('digitalglarus:membership_activated'))

        else:
            return self.form_invalid(form)
示例#25
0
    def post(self, request, *args, **kwargs):
        form = self.get_form()

        if form.is_valid():
            context = self.get_context_data()
            token = form.cleaned_data.get("token")
            donation_amount = form.cleaned_data.get("donation_amount")

            # Get or create stripe customer
            customer = StripeCustomer.get_or_create(email=self.request.user.email, token=token)
            if not customer:
                form.add_error("__all__", "Invalid credit card")
                return self.render_to_response(self.get_context_data(form=form))

            # Create Billing Address
            billing_address = form.save()

            # Make stripe charge to a customer
            stripe_utils = StripeUtils()
            stripe_utils.CURRENCY = "usd"
            charge_response = stripe_utils.make_charge(amount=donation_amount, customer=customer.stripe_id)
            charge = charge_response.get("response_object")

            # Check if the payment was approved
            if not charge:
                context.update({"paymentError": charge_response.get("error"), "form": form})
                return render(request, self.template_name, context)

            # Create a donation
            charge = charge_response.get("response_object")
            donation_data = request.POST.copy()
            donation_data.update(
                {
                    "cc_brand": charge.source.brand,
                    "stripe_charge_id": charge.id,
                    "last4": charge.source.last4,
                    "billing_address": billing_address.id,
                    "donator": customer.id,
                    "donation": donation_amount,
                }
            )
            donation_form = DonationForm(donation_data)
            if donation_form.is_valid():

                # reactivate donation status
                donation = donation_form.save()

                try:
                    donator_status = DonatorStatus.objects.get(user=self.request.user)
                    donator_status.set_active()
                except DonatorStatus.DoesNotExist:
                    pass

                donation = donation_form.save()

                context = {"donation": donation, "base_url": "{0}://{1}".format(request.scheme, request.get_host())}
                email_data = {
                    "subject": "Your donation have been charged",
                    "to": request.user.email,
                    "context": context,
                    "template_name": "donation_charge",
                    "template_path": "nosystemd/emails/",
                }
                email = BaseEmail(**email_data)
                email.send()

                return HttpResponseRedirect(reverse("nosystemd:donations", kwargs={"pk": donation.id}))
            else:
                self.form_invalid(donation_form)

        else:
            return self.form_invalid(form)
示例#26
0
    def handle(self, *args, **options):
        donators = DonatorStatus.objects.filter(status=DonatorStatus.ACTIVE)
        current_month = datetime.now().month
        current_year = datetime.now().year

        print("--------- STARTING DONATIONS SCRIPT  ---------")
        print("Donations date: %s-%s" % (current_month, current_year))

        for donator_status in donators:
            donator = donator_status.user.stripecustomer
            try:
                Donation.objects.get(created_at__month=current_month,
                                     created_at__year=current_year,
                                     donator=donator)
            except Donation.DoesNotExist:
                try:
                    # Get donator last donation amount
                    last_donation = Donation.objects.filter(
                        donator=donator).last()
                    donation_amount = last_donation.donation

                    # Make stripe charge to a customer
                    stripe_utils = StripeUtils()
                    stripe_utils.CURRENCY = self.CURRENCY
                    charge_response = stripe_utils.make_charge(
                        amount=donation_amount, customer=donator.stripe_id)
                    charge = charge_response.get('response_object')

                    # Check if the payment was approved
                    if not charge:
                        # There is an error trying to creating the stripe charge
                        context = {
                            'paymentError': charge_response.get('error'),
                        }
                        print("--------- STRIPE PAYMENT ERROR ---------")
                        print(context)
                        print("-------------------------")
                        continue
                    # Create a donation
                    charge = charge_response.get('response_object')
                    donation_data = {
                        'cc_brand': charge.source.brand,
                        'stripe_charge_id': charge.id,
                        'last4': charge.source.last4,
                        'billing_address': last_donation.billing_address.id,
                        'donator': donator.id,
                        'donation': donation_amount
                    }
                    donation_form = DonationForm(donation_data)
                    if donation_form.is_valid():
                        donation = donation_form.save()

                        context = {
                            'donation':
                            donation,
                            'base_url':
                            "{0}://{1}".format('https',
                                               'dynamicweb.ungleich.ch')
                        }
                        email_data = {
                            'subject': 'Your donation have been charged',
                            'to': donation.donator.user.email,
                            'context': context,
                            'template_name': 'donation_charge',
                            'template_path': 'nosystemd/emails/'
                        }
                        email = BaseEmail(**email_data)
                        email.send()

                        print(
                            "--------- PAYMENT DONATION SUCCESSFULL ---------")
                        print("Donator: %s" % donation.donator.user.email)
                        print("Amount: %s %s" %
                              (donation.donation, self.CURRENCY))
                        print(
                            "-----------------------------------------------")
                except Exception as e:
                    print("--------- ERROR ---------")
                    print(e)
                    print("-------------------------")
                    continue
示例#27
0
    def handle(self, *args, **options):
        donators = DonatorStatus.objects.filter(status=DonatorStatus.ACTIVE)
        current_month = datetime.now().month
        current_year = datetime.now().year

        print("--------- STARTING DONATIONS SCRIPT  ---------")
        print("Donations date: %s-%s" % (current_month, current_year))

        for donator_status in donators:
            donator = donator_status.user.stripecustomer
            try:
                Donation.objects.get(created_at__month=current_month,
                                     created_at__year=current_year,
                                     donator=donator)
            except Donation.DoesNotExist:
                try:
                    # Get donator last donation amount
                    last_donation = Donation.objects.filter(donator=donator).last()
                    donation_amount = last_donation.donation

                    # Make stripe charge to a customer
                    stripe_utils = StripeUtils()
                    stripe_utils.CURRENCY = self.CURRENCY
                    charge_response = stripe_utils.make_charge(amount=donation_amount,
                                                               customer=donator.stripe_id)
                    charge = charge_response.get('response_object')

                    # Check if the payment was approved
                    if not charge:
                        # There is an error trying to creating the stripe charge
                        context = {
                            'paymentError': charge_response.get('error'),
                        }
                        print("--------- STRIPE PAYMENT ERROR ---------")
                        print(context)
                        print("-------------------------")
                        continue
                    # Create a donation
                    charge = charge_response.get('response_object')
                    donation_data = {
                        'cc_brand': charge.source.brand,
                        'stripe_charge_id': charge.id,
                        'last4': charge.source.last4,
                        'billing_address': last_donation.billing_address.id,
                        'donator': donator.id,
                        'donation': donation_amount
                    }
                    donation_form = DonationForm(donation_data)
                    if donation_form.is_valid():
                        donation = donation_form.save()

                        context = {
                            'donation': donation,
                            'base_url': "{0}://{1}".format('https', 'dynamicweb.ungleich.ch')

                        }
                        email_data = {
                            'subject': 'Your donation have been charged',
                            'to': donation.donator.user.email,
                            'context': context,
                            'template_name': 'donation_charge',
                            'template_path': 'nosystemd/emails/'
                        }
                        email = BaseEmail(**email_data)
                        email.send()

                        print("--------- PAYMENT DONATION SUCCESSFULL ---------")
                        print("Donator: %s" % donation.donator.user.email)
                        print("Amount: %s %s" % (donation.donation, self.CURRENCY))
                        print("-----------------------------------------------")
                except Exception as e:
                    print("--------- ERROR ---------")
                    print(e)
                    print("-------------------------")
                    continue