Example #1
0
def get_customer_subscription_length(customer_id):
    customer = Customer.get_by_id(customer_id)
    if not customer.subscription_order_number:
        raise NoSubscriptionFoundException(customer)
    months_till_charge, _ = get_subscription_order_remaining_length(
        customer_id, customer.subscription_order_number)
    return months_till_charge
Example #2
0
def set_service_disabled(customer_or_id, disabled_reason_int):
    """
    Disables the customer his service, disconnects all users and sets the service invisible.

    Args:
        customer_or_id (int, long, Customer): customer or id
        disabled_reason_int (int, long): reason why the service has been disabled

    Raises:
        NoSubscriptionException
        BusinessException
    """
    if isinstance(customer_or_id, Customer):
        customer = customer_or_id
    else:
        customer = Customer.get_by_id(customer_or_id)

    if not customer.service_email:
        raise NoSubscriptionException(customer)
    if disabled_reason_int not in Customer.DISABLED_REASONS:
        raise BusinessException('Invalid disable service reason')

    service_user = users.User(customer.service_email)
    sln_settings = get_solution_settings(service_user)
    customer.default_app_id = None
    customer.app_ids = []
    customer.service_disabled_at = now()
    customer.disabled_reason_int = disabled_reason_int
    customer.subscription_cancel_pending_date = 0
    sln_settings.search_enabled = False
    sln_settings.service_disabled = True
    db.put([customer, sln_settings])

    rogerthat_set_service_disabled(service_user)
Example #3
0
def create_task_if_not_order(customer_id):
    customer = Customer.get_by_id(customer_id)
    # Check if the customer has linked his credit card after he clicked the 'pay' button
    # If he didn't (one hour after the last time he tried to pay), create a new ShopTask to call this customer.
    if not customer.stripe_valid and customer.team_id:
        if customer.prospect_id:
            rmt, prospect = db.get([
                RegioManagerTeam.create_key(customer.team_id),
                Prospect.create_key(customer.prospect_id)
            ])
        else:
            prospect = create_prospect_from_customer(customer)
            rmt = RegioManagerTeam.get(
                RegioManagerTeam.create_key(customer.team_id))
        azzert(rmt.support_manager,
               'No support manager found for team %s' % rmt.name)
        task = create_task(
            prospect_or_key=prospect,
            status=ShopTask.STATUS_NEW,
            task_type=ShopTask.TYPE_SUPPORT_NEEDED,
            address=None,
            created_by=STORE_MANAGER.email(),
            assignee=rmt.support_manager,
            execution_time=today() + 86400 + 11 * 3600,  # tomorrow, 11:00,
            app_id=prospect.app_id,
            comment=u"Customer wanted to pay an order in the customer store, "
            "but didn't succeed because he did not link his creditcard.",
            notify_by_email=True)
        task.put()
Example #4
0
def link_stripe_to_customer(customer_id_or_service_email, stripe_token,
                            stripe_token_created, contact_id):
    solution_server_settings = get_solution_server_settings()
    stripe.api_key = solution_server_settings.stripe_secret_key
    if isinstance(customer_id_or_service_email, unicode):
        customer = Customer.get_by_service_email(customer_id_or_service_email)
    else:
        customer = Customer.get_by_id(customer_id_or_service_email)

    # Resellers and their customers should not be able to do this
    google_user = gusers.get_current_user()
    if not customer.team.legal_entity.is_mobicage:
        logging.error(
            "user %s tried to access function 'link_stripe_to_customer'",
            google_user.email())
        raise NoPermissionException()
    if google_user:
        azzert(user_has_permissions_to_team(google_user, customer.team_id))

    if customer.stripe_id:
        stripe_customer = stripe.Customer.retrieve(customer.stripe_id)
        card = stripe_customer.cards.create(card=stripe_token)
        stripe_customer.default_card = card.id
        stripe_customer.save()
    else:
        stripe_customer = stripe.Customer.create(
            card=stripe_token,
            description=u"%s %s -- %s, %s, %s, %s, %s, %s" %
            (customer.id, customer.vat, customer.name, customer.address1,
             customer.address2, customer.zip_code, customer.city,
             customer.country))
        card = stripe_customer.cards.data[0]
    try_or_defer(store_stripe_link_to_datastore, customer.key(),
                 stripe_customer.id, card.id, stripe_token_created, contact_id)
Example #5
0
    def get(self):
        customer_id = int(self.request.get("customer_id"))
        try:
            customer = Customer.get_by_id(customer_id)
        except CustomerNotFoundException:
            self.abort(404)

        current_user = users.get_current_user()
        current_customer = get_customer(current_user)
        sln_settings = get_solution_settings(current_user)
        if not sln_settings.can_edit_services(
                current_customer) or not current_customer.can_edit_service(
                    customer):
            logging.warn(
                'Service or user %s is trying to login to the dashboard of %s',
                current_user.email(), customer.name)
            self.abort(401)

        service_identity_user = create_service_identity_user(
            users.User(customer.service_email))
        current_session = users.get_current_session()
        new_secret, new_session = create_session(service_identity_user,
                                                 ignore_expiration=True)
        set_cookie(self.response,
                   get_server_settings().cookieSessionName, new_secret)
        new_session = switch_to_service_identity(new_session,
                                                 service_identity_user,
                                                 read_only=False,
                                                 shop=current_session.shop,
                                                 layout_only=True)
        new_session.parent_session_secret = current_session.secret
        new_session.put()
        self.redirect("/")
Example #6
0
def get_subscription_order(customer_id):
    customer = Customer.get_by_id(customer_id)
    if not customer.subscription_order_number:
        raise NoSubscriptionException(customer)
    order = Order.get_by_order_number(customer.id,
                                      customer.subscription_order_number)
    if not order.status == Order.STATUS_SIGNED:
        raise BusinessException(
            'The customer his subscription order has not been signed yet.')
    return order
Example #7
0
def set_next_charge_date(customer_id, next_charge_date):
    customer = Customer.get_by_id(customer_id)
    if not customer.subscription_order_number:
        raise NoSubscriptionException(customer)
    order = Order.get_by_order_number(customer_id,
                                      customer.subscription_order_number)
    if not order.status == Order.STATUS_SIGNED:
        raise BusinessException(
            'The customer his subscription order has not been signed yet.')
    order.next_charge_date = next_charge_date
    order.put()
Example #8
0
def customer_get_editable_organization_types(customer_id):
    request = GenericRESTRequestHandler.getCurrentRequest()
    language = get_languages_from_request(request)[0]
    try:
        customer = Customer.get_by_id(customer_id)

        if not language:
            language = customer.language

        return dict(get_organization_types(customer, language))
    except CustomerNotFoundException:
        return {}
Example #9
0
def cancel_subscription(customer_id, cancel_reason, immediately=False):
    """
    Marks the customer his subscription as disabled.
    Recurrent billing will disable the service and disconnect all users after the subscription has ended.
    When the 'immediately' parameter is set, the service will be disabled immediately.

    Args:
        customer_id (int, long): Customer id
        cancel_reason (unicode): Reason why the subscription has been canceled.
        immediately (bool): Set to True to disable the service immediately

    Returns: None

    Raises:
        EmptyValueException
        CustomerNotFoundException
        NoSubscriptionException
    """
    if not cancel_reason:
        raise EmptyValueException('cancel_reason')

    customer = Customer.get_by_id(customer_id)

    if not customer.subscription_order_number:
        raise NoSubscriptionException(customer)

    order = Order.get_by_order_number(customer_id,
                                      customer.subscription_order_number)
    if immediately or order.status != Order.STATUS_SIGNED:

        def trans():
            try:
                cancel_order(customer, customer.subscription_order_number)
            except OrderAlreadyCanceledException as exception:
                logging.info('Order %s already canceled, continueing...' %
                             exception.order.order_number)

            customer.disabled_reason = cancel_reason
            set_service_disabled(customer, Customer.DISABLED_OTHER)

        run_in_xg_transaction(trans)
    else:
        customer.disabled_reason = cancel_reason
        customer.subscription_cancel_pending_date = now()
        customer.put()
Example #10
0
def set_service_enabled(customer_id):
    customer = Customer.get_by_id(customer_id)
    if not customer.service_email:
        raise NoSubscriptionException(customer)

    service_user = users.User(customer.service_email)
    service_identity_user = create_service_identity_user(service_user)
    si = get_service_identity(service_identity_user)
    sln_settings = get_solution_settings(service_user)
    sln_settings.service_disabled = False
    customer.service_disabled_at = 0
    customer.disabled_reason = u''
    customer.disabled_reason_int = 0
    customer.subscription_cancel_pending_date = 0
    # restore app ids
    customer.app_ids = si.sorted_app_ids
    customer.default_app_id = si.app_id
    db.put([customer, sln_settings])

    rogerthat_re_enable_service(service_user)
Example #11
0
    def get(self):
        from shop.models import Customer, Invoice
        service_user = users.get_current_user()

        customer_id = long(self.request.get("customer_id"))
        order_number = self.request.get("order_number")
        charge_id = long(self.request.get("charge_id"))
        invoice_number = self.request.get("invoice_number")
        download = self.request.get("download", "false") == "true"

        self.response.headers['Content-Type'] = 'application/pdf'
        self.response.headers['Content-Disposition'] = str(
            '%s; filename=invoice_%s.pdf' %
            ("attachment" if download else "inline", invoice_number))

        try:
            customer = Customer.get_by_id(customer_id)
        except CustomerNotFoundException, exception:
            logging.exception(exception)
            self.abort(500)
            return
    def test_customer_store(self):
        xcty_product = ShopProductTO.create(u'be-berlare', u'XCTY', 1)
        posm_product = ShopProductTO.create(MISSING, u'POSM', 250)
        _, customer = self._create_customer_and_subscription_order(
            [u'MSUP', u'BEAC', u'KSUP', u'ILOS'])
        self._create_service(customer)
        customer = Customer.get_by_id(customer.id)
        self.current_user = users.User(customer.service_email)
        set_current_user(self.current_user)
        product_xcty, product_posm = db.get(
            [Product.create_key(u'XCTY'),
             Product.create_key(u'POSM')])

        xcty_order_item = add_item_to_order(xcty_product).order_item
        remaining_subscription_length = get_subscription_order_remaining_length(
            customer.id, customer.subscription_order_number)[0]
        price_xcty = remaining_subscription_length * product_xcty.price
        temp_order = Order.get_by_order_number(customer.id, '-1')
        self.assertEqual(temp_order.is_subscription_order, False)
        self.assertEqual(temp_order.amount, price_xcty)
        self.assertEqual(temp_order.is_subscription_extension_order,
                         False)  # Is set when paying the order

        add_item_to_order(posm_product).order_item
        temp_order = Order.get_by_order_number(customer.id, '-1')
        self.assertEqual(temp_order.amount,
                         price_xcty + product_posm.price * 250)

        # test removing an order item
        remove_from_order(xcty_order_item.id)
        temp_order = Order.get_by_order_number(customer.id, '-1')
        self.assertEqual(temp_order.amount, product_posm.price * 250)

        xcty_order_item = add_item_to_order(xcty_product).order_item
        temp_order = Order.get_by_order_number(customer.id, '-1')
        self.assertEqual(temp_order.amount,
                         price_xcty + product_posm.price * 250)
        self.assertEqual(
            pay_order().success,
            False)  # should be false since we have no credit card linked
Example #13
0
    def trans():
        from_profile = _get_profile_not_cached(from_user)
        if from_profile:
            bizz_check(
                isinstance(from_profile, UserProfile),
                'Profile %s is not of expected type UserProfile, but of type %s'
                % (from_user, from_profile.kind()))
        else:
            logging.warn('UserProfile for %s not found! Weird...',
                         from_user.email())

        to_put = set()
        to_profile = _get_profile_not_cached(to_user)
        if to_profile:
            bizz_check(
                isinstance(to_profile, UserProfile),
                'Profile %s is not of expected type UserProfile, but of type %s'
                % (to_user, to_profile.kind()))

            if service_email not in to_profile.owningServiceEmails:
                to_profile.owningServiceEmails.append(service_email)
            to_put.add(to_profile)
        else:
            if from_profile:
                language = from_profile.language
                password_hash = from_profile.passwordHash
            else:
                service_profile = get_service_profile(
                    users.User(service_email))
                language = service_profile.defaultLanguage
                password_hash = service_profile.passwordHash
            to_profile = create_user_profile(to_user, to_user.email(),
                                             language)
            to_profile.isCreatedForService = True
            to_profile.owningServiceEmails = [service_email]
            update_password_hash(to_profile, password_hash, now())

        if from_profile:
            if service_email in from_profile.owningServiceEmails:
                from_profile.owningServiceEmails.remove(service_email)
                to_put.add(from_profile)

            if not from_profile.owningServiceEmails:

                @db.non_transactional
                def has_mobiles():
                    return bool(
                        list(get_user_active_mobiles(from_profile.user)))

                if has_mobiles():
                    from_profile.isCreatedForService = False
                    to_put.add(from_profile)
                else:
                    delete_account(from_user)

        si = get_default_service_identity_not_cached(users.User(service_email))
        si.qualifiedIdentifier = to_user.email()
        to_put.add(si)
        sln_settings = get_solution_settings(users.User(service_email))
        sln_settings.login = to_user
        sln_settings.qualified_identifier = to_user.email()
        to_put.add(sln_settings)

        if customer_id is not None:
            customer = Customer.get_by_id(customer_id)
            customer.user_email = to_user.email()
            to_put.add(customer)

        put_and_invalidate_cache(*to_put)
Example #14
0
def rest_put_service(name, address1, address2, zip_code, city, user_email, telephone, language, modules,
                     broadcast_types, customer_id=None, organization_type=OrganizationType.PROFIT, vat=None,
                     website=None, facebook_page=None, force=False):
    city_service_user = users.get_current_user()
    city_customer = get_customer(city_service_user)
    city_sln_settings = get_solution_settings(city_service_user)
    lang = city_sln_settings.main_language
    customer = Customer.get_by_id(customer_id) if customer_id else None
    # check if the current user is in fact a city app
    if customer and not city_customer.can_edit_service(customer):
        logging.warn(u'Service %s tried to save service information for customer %d', city_service_user, customer.id)
        return CreateServiceStatusTO.create(False, translate(lang, SOLUTION_COMMON, 'no_permission'))

    error_msg = warning_msg = None
    email_changed = False
    is_new_service = False

    try:
        modules = filter_modules(city_customer, modules, broadcast_types)
        service = create_customer_service_to(name, address1, address2, city, zip_code, user_email, language, city_sln_settings.currency,
                                             telephone, organization_type, city_customer.app_id, broadcast_types, modules)
        (customer, email_changed, is_new_service) \
            = create_customer_with_service(city_customer, customer, service, name, address1, address2, zip_code, city,
                                           language, organization_type, vat, website, facebook_page, force=force)
    except EmptyValueException as ex:
        val_name = translate(lang, SOLUTION_COMMON, ex.value_name)
        error_msg = translate(lang, SOLUTION_COMMON, 'empty_field_error', field_name=val_name)
    except ServiceNameTooBigException:
        error_msg = translate(lang, SOLUTION_COMMON, 'name_cannot_be_bigger_than_n_characters', n=50)
    except DuplicateCustomerNameException as ex:
        warning_msg = translate(lang, SOLUTION_COMMON, 'duplicate_customer', customer_name=ex.name)
    except NoPermissionException:
        error_msg = translate(lang, SOLUTION_COMMON, 'no_permission')
    except InvalidEmailFormatException as ex:
        error_msg = translate(lang, SOLUTION_COMMON, 'invalid_email_format', email=ex.email)
    except NotOperatingInCountryException as ex:
        error_msg = translate(lang, SOLUTION_COMMON, 'not_operating_in_country', country=ex.country)
    except BusinessException as ex:
        logging.debug('Failed to create service, BusinessException', exc_info=True)
        error_msg = ex.message
    except:
        logging.exception('Failed to create service')
        error_msg = translate(lang, SOLUTION_COMMON, 'failed_to_create_service')
    finally:
        if error_msg:
            return CreateServiceStatusTO.create(False, error_msg)
        elif warning_msg:
            return CreateServiceStatusTO.create(False, warningmsg=warning_msg)

    try:
        put_customer_service(customer, service, skip_module_check=True, search_enabled=False,
                             skip_email_check=True, rollback=is_new_service)
    except EmptyValueException as ex:
        val_name = translate(lang, SOLUTION_COMMON, ex.value_name)
        error_msg = translate(lang, SOLUTION_COMMON, 'empty_field_error', field_name=val_name)
    except:
        logging.exception('Could not save service service information')
        error_msg = translate(lang, SOLUTION_COMMON, 'failed_to_create_service')
    finally:
        if error_msg:
            if is_new_service:
                logging.warn('Failed to save new service service information, changes would be reverted...')
            return CreateServiceStatusTO.create(False, error_msg)
        else:
            if email_changed:
                migrate_user(users.User(customer.user_email), users.User(customer.user_email), users.User(user_email),
                             customer.service_email)
                customer.user_email = user_email
                customer.put()
            variables = dict_str_for_audit_log({
                'user_email': user_email,
                'modules': modules,
            })
            audit_log(customer_id, 'put_service', variables, city_service_user)
            return CreateServiceStatusTO.create()