def create_30_day_trial(domain_obj): from corehq.apps.accounting.models import ( DefaultProductPlan, SoftwarePlanEdition, BillingAccount, Currency, BillingAccountType, Subscription, SubscriptionAdjustmentMethod, ) # Create a 30 Day Trial subscription to the Advanced Plan advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain( domain_obj, edition=SoftwarePlanEdition.ADVANCED, is_trial=True ) expiration_date = date.today() + timedelta(days=30) trial_account = BillingAccount.objects.get_or_create( name="Trial Account for %s" % domain_obj.name, currency=Currency.get_default(), created_by_domain=domain_obj.name, account_type=BillingAccountType.TRIAL, )[0] trial_subscription = Subscription.new_domain_subscription( trial_account, domain_obj.name, advanced_plan_version, date_end=expiration_date, adjustment_method=SubscriptionAdjustmentMethod.TRIAL, is_trial=True, ) trial_subscription.is_active = True trial_subscription.save()
def create_new(cls, backend_api_id, direction, amount, currency=None, backend_instance=None, country_code=None, prefix=None, save=True, fee_class=None, criteria_class=None): fee_class = fee_class or cls criteria_class = criteria_class or SmsGatewayFeeCriteria currency = currency or Currency.get_default() # caller's responsibility to pass the right combination of criteria_class and prefix # will error if bad combination is passed if prefix: criteria, _ = criteria_class.objects.get_or_create( backend_api_id=backend_api_id, direction=direction, backend_instance=backend_instance, country_code=country_code, prefix=prefix, ) else: criteria, _ = criteria_class.objects.get_or_create( backend_api_id=backend_api_id, direction=direction, backend_instance=backend_instance, country_code=country_code, ) new_fee = fee_class( currency=currency, amount=amount, criteria=criteria ) if save: new_fee.save() return new_fee
def create_new(cls, backend_api_id, direction, amount, currency=None, backend_instance=None, country_code=None, prefix=None, save=True, fee_class=None, criteria_class=None): fee_class = fee_class or cls criteria_class = criteria_class or SmsGatewayFeeCriteria currency = currency or Currency.get_default() if 'prefix' in [ field.name for field in criteria_class._meta.get_fields() ]: prefix = prefix or '' criteria, _ = criteria_class.objects.get_or_create( backend_api_id=backend_api_id, direction=direction, backend_instance=backend_instance, country_code=country_code, prefix=prefix, ) else: criteria, _ = criteria_class.objects.get_or_create( backend_api_id=backend_api_id, direction=direction, backend_instance=backend_instance, country_code=country_code, ) new_fee = fee_class( currency=currency, amount=amount, criteria=criteria ) if save: new_fee.save() return new_fee
def create_30_day_trial(domain_obj): from corehq.apps.accounting.models import ( DefaultProductPlan, SoftwarePlanEdition, BillingAccount, Currency, BillingAccountType, Subscription, SubscriptionAdjustmentMethod, ) # Create a 30 Day Trial subscription to the Advanced Plan advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain( domain_obj, edition=SoftwarePlanEdition.ADVANCED, is_trial=True) expiration_date = date.today() + timedelta(days=30) trial_account = BillingAccount.objects.get_or_create( name="Trial Account for %s" % domain_obj.name, currency=Currency.get_default(), created_by_domain=domain_obj.name, account_type=BillingAccountType.TRIAL, )[0] trial_subscription = Subscription.new_domain_subscription( trial_account, domain_obj.name, advanced_plan_version, date_end=expiration_date, adjustment_method=SubscriptionAdjustmentMethod.TRIAL, is_trial=True, ) trial_subscription.is_active = True trial_subscription.save()
def __init__(self, account, *args, **kwargs): if account is not None: contact_info, _ = BillingContactInfo.objects.get_or_create(account=account) kwargs["initial"] = { "name": account.name, "salesforce_account_id": account.salesforce_account_id, "currency": account.currency.code, "contact_emails": contact_info.emails, "first_name": contact_info.first_name, "last_name": contact_info.last_name, "company_name": contact_info.company_name, "phone_number": contact_info.phone_number, "address_line_1": contact_info.first_line, "address_line_2": contact_info.second_line, "city": contact_info.city, "region": contact_info.state_province_region, "postal_code": contact_info.postal_code, "country": contact_info.country, } else: kwargs["initial"] = {"currency": Currency.get_default().code} super(BillingAccountForm, self).__init__(*args, **kwargs) if account is None: self.fields["address_line_1"].required = False self.fields["city"].required = False self.fields["region"].required = False self.fields["postal_code"].required = False self.fields["country"].required = False self.fields["currency"].choices = [(cur.code, cur.code) for cur in Currency.objects.order_by("code")] self.helper = FormHelper() self.helper.layout = crispy.Layout( crispy.Fieldset("Basic Information", "name", "contact_emails", "salesforce_account_id", "currency"), crispy.Fieldset( "Contact Information", "first_name", "last_name", "company_name", "phone_number", "address_line_1", "address_line_2", "city", "region", "postal_code", crispy.Field( "country", css_class="input-xlarge", data_countryname=dict(COUNTRIES).get( args[0].get("country") if len(args) > 0 else account.billingcontactinfo.country, "" ), ), ) if account is not None else None, FormActions( crispy.ButtonHolder( crispy.Submit("account", "Update Account" if account is not None else "Add New Account") ) ), )
def update_exchange_rates(app_id=settings.OPEN_EXCHANGE_RATES_ID): try: update_logger.info("Updating exchange rates...") rates = json.load(urllib2.urlopen( 'https://openexchangerates.org/api/latest.json?app_id=%s' % app_id))['rates'] default_rate = float(rates[Currency.get_default().code]) for code, rate in rates.items(): currency, _ = Currency.objects.get_or_create(code=code) currency.rate_to_default = float(rate) / default_rate currency.save() update_logger.info("Exchange rates updated.") except Exception as e: smsbillables_logger.error(e.message)
def _get_cost_string(cost, currency_code): cost_template = '%.2f %s' cost_string_in_original_currency = cost_template % (cost, currency_code) default_code = Currency.get_default().code if currency_code == default_code: return cost_string_in_original_currency else: cost_string_in_default_currency = cost_template % ( cost / Currency.objects.get( code=currency_code).rate_to_default, default_code) return '%s (%s)' % (cost_string_in_original_currency, cost_string_in_default_currency)
def update_exchange_rates(app_id=settings.OPEN_EXCHANGE_RATES_API_ID): try: logger.info("Updating exchange rates...") rates = json.load(urllib2.urlopen("https://openexchangerates.org/api/latest.json?app_id=%s" % app_id))["rates"] default_rate = float(rates[Currency.get_default().code]) for code, rate in rates.items(): currency, _ = Currency.objects.get_or_create(code=code) currency.rate_to_default = float(rate) / default_rate currency.save() logger.info( "Exchange rate for %(code)s updated %(rate)f." % {"code": currency.code, "rate": currency.rate_to_default} ) except Exception as e: logger.error(e.message)
def _get_cost_string(cost, currency_code): cost_template = '%.2f %s' cost_string_in_original_currency = cost_template % (cost, currency_code) default_code = Currency.get_default().code if currency_code == default_code: return cost_string_in_original_currency else: cost_string_in_default_currency = cost_template % ( cost / Currency.objects.get(code=currency_code).rate_to_default, default_code ) return '%s (%s)' % ( cost_string_in_original_currency, cost_string_in_default_currency )
def create_new(cls, backend_api_id, direction, amount, currency=None, backend_instance=None, country_code=None, save=True): currency = currency or Currency.get_default() criteria, _ = SmsGatewayFeeCriteria.objects.get_or_create( backend_api_id=backend_api_id, direction=direction, backend_instance=backend_instance, country_code=country_code ) new_fee = SmsGatewayFee( currency=currency, amount=amount, criteria=criteria ) if save: new_fee.save() return new_fee
def update_exchange_rates(app_id=settings.OPEN_EXCHANGE_RATES_ID): try: logger.info("Updating exchange rates...") rates = json.load( urllib2.urlopen( 'https://openexchangerates.org/api/latest.json?app_id=%s' % app_id))['rates'] default_rate = float(rates[Currency.get_default().code]) for code, rate in rates.items(): currency, _ = Currency.objects.get_or_create(code=code) currency.rate_to_default = float(rate) / default_rate currency.save() logger.info("Exchange rate for %(code)s updated %(rate)f." % { 'code': currency.code, 'rate': currency.rate_to_default, }) except Exception as e: logger.error(e.message)
def update_exchange_rates(app_id=settings.OPEN_EXCHANGE_RATES_API_ID): if app_id: try: log_accounting_info("Updating exchange rates...") rates = json.load(urllib2.urlopen( 'https://openexchangerates.org/api/latest.json?app_id=%s' % app_id))['rates'] default_rate = float(rates[Currency.get_default().code]) for code, rate in rates.items(): currency, _ = Currency.objects.get_or_create(code=code) currency.rate_to_default = float(rate) / default_rate currency.save() log_accounting_info("Exchange rate for %(code)s updated %(rate)f." % { 'code': currency.code, 'rate': currency.rate_to_default, }) except Exception as e: log_accounting_error( "Error updating exchange rates: %s" % e.message, show_stack_trace=True, )
def update_exchange_rates(app_id=settings.OPEN_EXCHANGE_RATES_API_ID): if app_id: try: log_accounting_info("Updating exchange rates...") rates = json.load(six.moves.urllib.request.urlopen( 'https://openexchangerates.org/api/latest.json?app_id=%s' % app_id))['rates'] default_rate = float(rates[Currency.get_default().code]) for code, rate in rates.items(): currency, _ = Currency.objects.get_or_create(code=code) currency.rate_to_default = float(rate) / default_rate currency.save() log_accounting_info("Exchange rate for %(code)s updated %(rate)f." % { 'code': currency.code, 'rate': currency.rate_to_default, }) except Exception as e: log_accounting_error( "Error updating exchange rates: %s" % e.message, show_stack_trace=True, )
def create_30_day_advanced_trial(domain_obj): # Create a 30 Day Trial subscription to the Advanced Plan advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain( domain_obj, edition=SoftwarePlanEdition.ADVANCED, is_trial=True ) expiration_date = date.today() + timedelta(days=30) trial_account = BillingAccount.objects.get_or_create( name="Trial Account for %s" % domain_obj.name, currency=Currency.get_default(), created_by_domain=domain_obj.name, account_type=BillingAccountType.TRIAL, pre_or_post_pay=PreOrPostPay.POSTPAY, )[0] trial_subscription = Subscription.new_domain_subscription( trial_account, domain_obj.name, advanced_plan_version, date_end=expiration_date, adjustment_method=SubscriptionAdjustmentMethod.TRIAL, is_trial=True, service_type=SubscriptionType.TRIAL ) trial_subscription.is_active = True trial_subscription.save()
def create_30_day_advanced_trial(domain_obj): # Create a 30 Day Trial subscription to the Advanced Plan advanced_plan_version = DefaultProductPlan.get_default_plan( edition=SoftwarePlanEdition.ADVANCED, is_trial=True) expiration_date = date.today() + timedelta(days=30) trial_account = BillingAccount.objects.get_or_create( name="Trial Account for %s" % domain_obj.name, currency=Currency.get_default(), created_by_domain=domain_obj.name, account_type=BillingAccountType.TRIAL, pre_or_post_pay=PreOrPostPay.POSTPAY, )[0] trial_subscription = Subscription.new_domain_subscription( trial_account, domain_obj.name, advanced_plan_version, date_end=expiration_date, adjustment_method=SubscriptionAdjustmentMethod.TRIAL, is_trial=True, service_type=SubscriptionType.TRIAL) trial_subscription.is_active = True trial_subscription.save()
def request_new_domain(request, form, org, domain_type=None, new_user=True): now = datetime.utcnow() current_user = CouchUser.from_django_user(request.user) commtrack_enabled = domain_type == 'commtrack' dom_req = RegistrationRequest() if new_user: dom_req.request_time = now dom_req.request_ip = get_ip(request) dom_req.activation_guid = uuid.uuid1().hex new_domain = Domain( name=form.cleaned_data['domain_name'], is_active=False, date_created=datetime.utcnow(), commtrack_enabled=commtrack_enabled, creating_user=current_user.username, secure_submissions=True, ) if form.cleaned_data.get('domain_timezone'): new_domain.default_timezone = form.cleaned_data['domain_timezone'] if org: new_domain.organization = org new_domain.hr_name = request.POST.get('domain_hrname', None) or new_domain.name if not new_user: new_domain.is_active = True # ensure no duplicate domain documents get created on cloudant new_domain.save(**get_safe_write_kwargs()) if not new_domain.name: new_domain.name = new_domain._id new_domain.save() # we need to get the name from the _id # Create a 30 Day Trial subscription to the Advanced Plan advanced_plan_version = DefaultProductPlan.get_default_plan_by_domain( new_domain, edition=SoftwarePlanEdition.ADVANCED, is_trial=True ) expiration_date = date.today() + timedelta(days=30) trial_account = BillingAccount.objects.get_or_create( name="Trial Account for %s" % new_domain.name, currency=Currency.get_default(), created_by_domain=new_domain.name, account_type=BillingAccountType.TRIAL, )[0] trial_subscription = Subscription.new_domain_subscription( trial_account, new_domain.name, advanced_plan_version, date_end=expiration_date, adjustment_method=SubscriptionAdjustmentMethod.TRIAL, is_trial=True, ) trial_subscription.is_active = True trial_subscription.save() dom_req.domain = new_domain.name if request.user.is_authenticated(): if not current_user: current_user = WebUser() current_user.sync_from_django_user(request.user) current_user.save() current_user.add_domain_membership(new_domain.name, is_admin=True) current_user.save() dom_req.requesting_user_username = request.user.username dom_req.new_user_username = request.user.username if new_user: dom_req.save() send_domain_registration_email(request.user.email, dom_req.domain, dom_req.activation_guid) else: send_global_domain_registration_email(request.user, new_domain.name) send_new_request_update_email(request.user, get_ip(request), new_domain.name, is_new_user=new_user)
def __init__(self, account, *args, **kwargs): if account is not None: contact_info, _ = BillingContactInfo.objects.get_or_create(account=account) kwargs['initial'] = { 'name': account.name, 'salesforce_account_id': account.salesforce_account_id, 'currency': account.currency.code, 'billing_account_admins': ', '.join([admin.web_user for admin in account.billing_admins.all()]), 'first_name': contact_info.first_name, 'last_name': contact_info.last_name, 'company_name': contact_info.company_name, 'phone_number': contact_info.phone_number, 'address_line_1': contact_info.first_line, 'address_line_2': contact_info.second_line, 'city': contact_info.city, 'region': contact_info.state_province_region, 'postal_code': contact_info.postal_code, 'country': contact_info.country, } else: kwargs['initial'] = { 'currency': Currency.get_default().code, } super(BillingAccountForm, self).__init__(*args, **kwargs) if account is None: self.fields['address_line_1'].required = False self.fields['city'].required = False self.fields['region'].required = False self.fields['postal_code'].required = False self.fields['country'].required = False self.fields['currency'].choices =\ [(cur.code, cur.code) for cur in Currency.objects.order_by('code')] self.helper = FormHelper() self.helper.layout = crispy.Layout( crispy.Fieldset( 'Basic Information', 'name', 'salesforce_account_id', 'currency', ), crispy.Fieldset( 'Contact Information', 'billing_account_admins', 'first_name', 'last_name', 'company_name', 'phone_number', 'address_line_1', 'address_line_2', 'city', 'region', 'postal_code', 'country', ) if account is not None else None, FormActions( crispy.ButtonHolder( crispy.Submit('account', 'Update Account' if account is not None else 'Add New Account') ) ) )