示例#1
0
    def get(self):
        service_user = users.get_current_user()
        sln_settings = get_solution_settings(service_user)
        if SolutionModule.CITY_VOUCHERS not in sln_settings.modules:
            self.response.set_status(404)
            return

        app_id = self.request.get('a')
        customer = get_customer(service_user)
        if app_id != customer.app_id:
            self.response.set_status(404)
            return

        year = self.request.get('y')
        month = self.request.get('m')

        sln_city_voucher_export_key = SolutionCityVoucherExport.create_key(
            app_id, year, month)
        export = SolutionCityVoucherExport.get(sln_city_voucher_export_key)
        if export:
            self.response.headers['Content-Type'] = 'application/vnd.ms-excel'
            filename = get_exported_filename(sln_settings.main_language, year,
                                             month)
            self.response.headers['Content-Disposition'] = str(
                'attachment; filename=%s' % filename)
            self.response.write(export.xls)
        else:
            self.response.set_status(404)
示例#2
0
def load_orders():
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    if not customer:
        logging.error("Customer not found for %s", service_user)
        return []
    return [OrderTO.fromOrderModel(order) for order in Order.list_signed(customer)]
示例#3
0
def remove_from_order(item_id):
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    azzert(customer)
    customer_store_order_key = Order.create_key(
        customer.id, Order.CUSTOMER_STORE_ORDER_NUMBER)
    order_item_key = OrderItem.create_key(customer.id,
                                          Order.CUSTOMER_STORE_ORDER_NUMBER,
                                          item_id)
    order_item, order = db.get([order_item_key, customer_store_order_key])

    if not order_item:
        logging.warn(
            "Customer %s tried to delete an already deleted item (%s)",
            service_user.email(), item_id)
        return RETURNSTATUS_TO_SUCCESS
    azzert(order)

    # Subtract the price from this product, then remove the product.
    vat = order_item.count * order_item.price * order.vat_pct / 100
    total = order_item.count * order_item.price
    total_inc_vat = total + vat
    order.amount -= total
    order.total_amount -= total_inc_vat
    order.vat -= vat
    order_item.delete()
    order.put()
    return RETURNSTATUS_TO_SUCCESS
示例#4
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("/")
示例#5
0
def load_invoices():
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    if not customer:
        logging.error("Customer not found for %s", service_user)
        return []
    return [InvoiceTO.fromInvoiceModel(invoice) for invoice in get_invoices(customer)]
示例#6
0
def load_unsinged_orders():
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    if not customer:
        logging.error("Customer not found for %s", service_user)
        return []
    return [OrderTO.fromOrderModel(order) for order in Order.list_unsigned(customer) if order.order_number != Order.CUSTOMER_STORE_ORDER_NUMBER]
示例#7
0
def get_billing_contacts():
    from shop.models import Contact
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    if not customer:
        logging.error("Customer not found for %s", service_user)
        return []
    return [ContactTO.fromContactModel(c) for c in Contact.list(customer)]
示例#8
0
def get_modules_and_broadcast_types():
    city_service_user = users.get_current_user()
    city_customer = get_customer(city_service_user)
    lang = get_solution_settings(city_service_user).main_language
    modules = [ModuleTO.fromArray([k, SolutionModule.get_translated_description(lang, k)]) for k in
               get_allowed_modules(city_customer)]
    broadcast_types = [translate(lang, SOLUTION_COMMON, k) for k in get_allowed_broadcast_types(city_customer)]
    organization_types = [
        KeyValueTO(unicode(t), ServiceProfile.localized_singular_organization_type(t, lang, city_customer.app_id))
        for t in city_customer.editable_organization_types]
    return ModuleAndBroadcastTypesTO(modules, broadcast_types, organization_types)
示例#9
0
def get_app_statistics(service_identity):
    service_user = users.get_current_user()
    if not service_identity or service_identity == MISSING:
        service_identity = ServiceIdentity.DEFAULT
    service_identity_user = create_service_identity_user(service_user, service_identity)
    si = get_service_identity(service_identity_user)
    default_app = get_app(si.defaultAppId)
    customer = get_customer(service_user)
    available_apps = [a.app_id for a in get_available_apps_for_customer(customer, default_app.demo)]
    if not available_apps:
        # Customer does not exist or has no app ids
        available_apps = sorted(si.appIds)
    return app.get_app_statistics(available_apps)
示例#10
0
def get_order_items():
    # get the order items for this customer from the latest order that isn't signed yet
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    if not customer:
        return []
    order_key = Order.create_key(customer.id,
                                 Order.CUSTOMER_STORE_ORDER_NUMBER)
    order = Order.get(order_key)
    if order:
        sln_settings = get_solution_settings(service_user)
        lang = sln_settings.main_language
        remaining_length, sub_order = get_subscription_order_remaining_length(
            customer.id, customer.subscription_order_number)
        subscription_order_charge_date = format_date(
            datetime.datetime.utcfromtimestamp(sub_order.next_charge_date),
            locale=lang)
        order_items = list(OrderItem.list_by_order(order_key))
        order_items_updated = list()
        to_put = list()
        to_get = list(
            set([Product.create_key(o.product_code) for o in order_items] +
                [Product.create_key(Product.PRODUCT_EXTRA_CITY)]))
        products = {p.code: p for p in db.get(to_get)}
        # update the order items if necessary.
        for order_item in order_items:
            if products[
                    order_item.
                    product_code].is_subscription_extension and order_item.count != remaining_length:
                order_item.count = remaining_length
                to_put.append(order_item)
            order_items_updated.append(order_item)
        if to_put:
            db.put(to_put)
        extra_city_price = format_price(
            products[Product.PRODUCT_EXTRA_CITY].price, sln_settings.currency)
        service_visible_in_translation = translate(
            lang,
            SOLUTION_COMMON,
            'service_visible_in_app',
            subscription_expiration_date=subscription_order_charge_date,
            amount_of_months=remaining_length,
            extra_city_price=extra_city_price,
            app_name='%(app_name)s')
        return [
            OrderItemTO.create(i, service_visible_in_translation)
            for i in order_items_updated
        ]
    else:
        return []
示例#11
0
def get_services(organization_type, cursor=None, limit=50):
    city_service_user = users.get_current_user()
    si = system.get_identity()
    # get all the services in this city
    app_id = si.app_ids[0]
    city_customer = get_customer(city_service_user)
    azzert(organization_type in city_customer.editable_organization_types)
    service_customers_qry = Customer.list_enabled_by_organization_type_in_app(app_id, organization_type)
    service_customers_qry.with_cursor(cursor)
    service_customers = service_customers_qry.fetch(limit)
    new_cursor = unicode(service_customers_qry.cursor())

    services = []
    statistics = get_services_statistics(app_id)
    sln_settings_keys = [SolutionSettings.create_key(city_service_user)]
    for customer in service_customers:
        if not customer.service_email:
            logging.error('Customer %d (%s) has default_app_id, but has no service!', customer.id, customer.name)
        elif customer.app_id == app_id:
            sln_settings_keys.append(SolutionSettings.create_key(users.User(customer.service_email)))
    sln_settings_list = db.get(sln_settings_keys)
    city_sln_settings = sln_settings_list.pop(0)  # type: SolutionSettings
    azzert(city_sln_settings.can_edit_services(city_customer))
    city_service_email = city_sln_settings.service_user.email()
    for customer in service_customers:
        service_email = customer.service_email
        # Exclude the city app's own service
        if customer.app_id == app_id and service_email != city_service_email:
            future_events_count = 0
            broadcasts_last_month = 0
            static_content_count = 0
            last_unanswered_question_timestamp = 0
            modules = []
            for sln_settings in sln_settings_list:
                if sln_settings.key().name() == service_email:
                    modules = sln_settings.modules
            if statistics:
                for mail in statistics.customer_emails:
                    if mail == service_email:
                        index = statistics.customer_emails.index(mail)
                        future_events_count = statistics.future_events_count[index]
                        broadcasts_last_month = statistics.broadcasts_last_month[index]
                        static_content_count = statistics.static_content_count[index]
                        last_unanswered_question_timestamp = statistics.last_unanswered_questions_timestamps[index]

            statistic = ServiceStatisticTO.create(future_events_count, broadcasts_last_month, static_content_count,
                                                  last_unanswered_question_timestamp)
            services.append(ServiceListTO(service_email, customer.name, statistic, modules, customer.id))
    generated_on = statistics.generated_on if statistics else None
    return ServicesTO(sorted(services, key=lambda x: x.name.lower()), generated_on, new_cursor)
示例#12
0
def get_service(service_email):
    city_service_user = users.get_current_user()
    city_customer = get_customer(city_service_user)
    service_user = users.User(email=service_email)
    customer = Customer.get_by_service_email(service_email)
    if 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)
        lang = get_solution_settings(city_service_user).main_language
        return ReturnStatusTO.create(False, translate(lang, SOLUTION_COMMON, 'no_permission'))
    contact = Contact.get_one(customer.key())
    solution_settings = get_solution_settings(service_user)
    return ServiceTO(customer.id, customer.name, customer.address1, customer.address2, customer.zip_code, customer.city,
                     customer.user_email, contact.phone_number, solution_settings.main_language,
                     solution_settings.modules, solution_settings.broadcast_types, customer.organization_type,
                     customer.vat, customer.website, customer.facebook_page)
示例#13
0
def search_services(search_string):
    city_service_user = users.get_current_user()
    city_sln_settings = get_solution_settings(city_service_user)
    si = system.get_identity()
    app_id = si.app_ids[0]
    city_customer = get_customer(city_service_user)
    azzert(city_sln_settings.can_edit_services(city_customer))

    customers = []
    # if app id is set, the customer should have a service
    for c in search_customer(search_string, [app_id], None):
        # exclude own service and disabled services
        if c.service_email == city_service_user.email() or c.service_disabled_at:
            continue
        customers.append(CustomerTO.fromCustomerModel(c, False, False))

    return sorted(customers, key=lambda c: c.name.lower())
示例#14
0
def rest_delete_service(service_email):
    city_service_user = users.get_current_user()
    city_customer = get_customer(city_service_user)
    customer = Customer.get_by_service_email(service_email)
    if not city_customer.can_edit_service(customer):
        lang = get_solution_settings(city_service_user).main_language
        logging.warn(u'Service %s tried to save service information for customer %d', city_service_user, customer.id)
        return ReturnStatusTO.create(False, translate(lang, SOLUTION_COMMON, 'no_permission'))
    cancel_subscription(customer.id, Customer.DISABLED_REASONS[Customer.DISABLED_ASSOCIATION_BY_CITY], True)
    session = users.get_current_session()
    service_identity = session.service_identity
    send_message_to_session(city_service_user, session,
                            [{u"type": u"solutions.common.services.deleted",
                              u'service_email': service_email,
                              u'service_organization_type': customer.organization_type}],
                            si=service_identity)
    return RETURNSTATUS_TO_SUCCESS
示例#15
0
def get_billing_credit_card_info():
    service_user = users.get_current_user()
    try:
        customer = get_customer(service_user)
        if not customer:
            logging.error("Customer not found for %s", service_user)
            return None
        if not customer.stripe_id:
            logging.debug("No credit card coupled")
            return None

        solution_server_settings = get_solution_server_settings()
        stripe.api_key = solution_server_settings.stripe_secret_key
        stripe_customer = stripe.Customer.retrieve(customer.stripe_id)
        card = stripe_customer.cards.data[0]

        cc = CreditCardTO()
        cc.brand = card.brand
        cc.exp_month = card.exp_month
        cc.exp_year = card.exp_year
        cc.last4 = card.last4
        return cc
    except BusinessException:
        return None
示例#16
0
def rest_create_service_from_signup(signup_key, modules=None, broadcast_types=None, force=False):
    signup = db.get(signup_key)

    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

    azzert(city_sln_settings.can_edit_services(city_customer))
    if not signup:
        return CreateServiceStatusTO.create(False, translate(lang, SOLUTION_COMMON, 'signup_not_found'))

    error_msg = warning_msg = None
    try:
        if not modules:
            modules = signup.modules

        if not broadcast_types:
            broadcast_types = []

        _fill_signup_data(signup, 'email', 'telephone', 'website', 'facebook_page')
        modules = filter_modules(city_customer, modules, broadcast_types)
        service = create_customer_service_to(signup.company_name, signup.company_address1, None, signup.company_city,
                                             signup.company_zip_code, signup.company_email, lang, city_sln_settings.currency,
                                             signup.company_telephone, signup.company_organization_type, city_customer.app_id,
                                             broadcast_types, modules=modules)
        customer = create_customer_with_service(city_customer, None, service, signup.company_name,
                                                signup.customer_address1, None, signup.company_zip_code,
                                                signup.company_city, lang, signup.company_organization_type,
                                                signup.company_vat, signup.company_website,
                                                signup.company_facebook_page, force=force)[0]

        # update the contact, as it should be created by now
        _update_signup_contact(customer, signup)

    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)
        else:
            try:
                put_customer_service(customer, service, skip_module_check=True, search_enabled=False,
                                     skip_email_check=True, rollback=True)
            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:
                    return CreateServiceStatusTO.create(False, error_msg)
                else:
                    set_customer_signup_status(city_customer, signup, approved=True)
                    return CreateServiceStatusTO.create(success=True)
示例#17
0
 def _get_customer():
     return get_customer(service_user)
示例#18
0
def pay_order():
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    azzert(customer)

    if not customer.stripe_valid:
        # Create a shoptask after 1 hour
        deferred.defer(create_task_if_not_order, customer.id, _countdown=3600)
        return BoolReturnStatusTO.create(
            False,
            translate(
                get_solution_settings(service_user).main_language,
                SOLUTION_COMMON, u'no_credit_card_contact_support'), True)

    # create a new order with the exact same order items.
    old_order_key = Order.create_key(customer.id,
                                     Order.CUSTOMER_STORE_ORDER_NUMBER)

    def trans():
        old_order, team = db.get(
            (old_order_key, RegioManagerTeam.create_key(customer.team_id)))

        if not old_order:
            return BoolReturnStatusTO.create(
                False,
                translate(
                    get_solution_settings(service_user).main_language,
                    SOLUTION_COMMON, u'cart_empty'), False)

        # Duplicate the order
        to_put = list()
        to_delete = list()
        properties = copy_model_properties(old_order)
        properties['status'] = Order.STATUS_SIGNED
        properties['date_signed'] = now()
        new_order_key = Order.create_key(
            customer.id, OrderNumber.next(team.legal_entity_key))
        new_order = Order(key=new_order_key, **properties)
        new_order.team_id = team.id
        to_delete.append(old_order)

        # duplicate all of the order items
        old_order_items = OrderItem.list_by_order(old_order_key)
        all_products = db.get([
            Product.create_key(item.product_code) for item in old_order_items
        ])
        is_subscription_extension_order = False
        for product in all_products:
            if product.is_subscription_extension:
                is_subscription_extension_order = True
                break
        new_order.is_subscription_extension_order = is_subscription_extension_order
        if is_subscription_extension_order:
            subscription_order = Order.get_by_order_number(
                customer.id, customer.subscription_order_number)
            new_order.next_charge_date = subscription_order.next_charge_date
        added_apps = list()
        should_create_shoptask = False
        for old_item in old_order_items:
            properties = copy_model_properties(old_item)
            new_item = OrderItem(parent=new_order_key, **properties)
            to_put.append(new_item)
            to_delete.append(old_item)
            if hasattr(old_item, 'app_id'):
                added_apps.append(old_item.app_id)
            else:
                should_create_shoptask = True
        to_put.append(new_order)
        db.put(to_put)
        db.delete(to_delete)

        deferred.defer(generate_and_put_order_pdf_and_send_mail,
                       customer,
                       new_order_key,
                       service_user,
                       _transactional=True)

        # No need for signing here, immediately create a charge.
        azzert(new_order.total_amount > 0)
        charge = Charge(parent=new_order_key)
        charge.date = now()
        charge.type = Charge.TYPE_ORDER_DELIVERY
        charge.amount = new_order.amount
        charge.vat_pct = new_order.vat_pct
        charge.vat = new_order.vat
        charge.total_amount = new_order.total_amount
        charge.manager = new_order.manager
        charge.team_id = new_order.team_id
        charge.status = Charge.STATUS_PENDING
        charge.date_executed = now()
        charge.currency_code = team.legal_entity.currency_code
        charge.put()

        # Update the regiomanager statistics so these kind of orders show up in the monthly statistics
        deferred.defer(update_regiomanager_statistic,
                       gained_value=new_order.amount / 100,
                       manager=new_order.manager,
                       _transactional=True)

        # Update the customer service
        si = get_default_service_identity(users.User(customer.service_email))
        si.appIds.extend(added_apps)
        si.put()
        deferred.defer(re_index, si.user, _transactional=True)

        # Update the customer object so the newly added apps are added.
        customer.app_ids.extend(added_apps)
        customer.extra_apps_count += len(added_apps)
        customer.put()

        get_payed(customer.id, new_order, charge)
        # charge the credit card
        channel.send_message(service_user, 'common.billing.orders.update')
        channel_data = {
            'customer': customer.name,
            'no_manager': True,
            'amount': charge.amount / 100,
            'currency': charge.currency
        }
        server_settings = get_server_settings()
        send_to = server_settings.supportWorkers
        send_to.append(MC_DASHBOARD.email())
        channel.send_message(map(users.User, send_to),
                             'shop.monitoring.signed_order',
                             info=channel_data)
        if should_create_shoptask:
            prospect_id = customer.prospect_id
            if prospect_id is None:
                prospect = create_prospect_from_customer(customer)
                prospect_id = prospect.id
            deferred.defer(create_task_for_order,
                           customer.team_id,
                           prospect_id,
                           new_order.order_number,
                           _transactional=True)
        return BoolReturnStatusTO.create(True, None)

    xg_on = db.create_transaction_options(xg=True)
    return db.run_in_transaction_options(xg_on, trans)
示例#19
0
def add_item_to_order(item):
    service_user = users.get_current_user()
    customer = get_customer(service_user)
    azzert(customer)
    contact = Contact.get_one(customer)
    azzert(contact)
    sln_settings = get_solution_settings(service_user)
    lang = sln_settings.main_language

    # Check if the customer his service isn't already enabled in this city
    if item.app_id in customer.app_ids:
        raise BusinessException(
            translate(lang, SOLUTION_COMMON, u'service_already_active'))

    def trans():
        to_put = list()
        customer_store_order_key = Order.create_key(
            customer.id, Order.CUSTOMER_STORE_ORDER_NUMBER)
        subscription_order_key = Order.create_key(
            customer.id, customer.subscription_order_number)
        team_key = RegioManagerTeam.create_key(customer.team_id)
        product_key = Product.create_key(item.code)

        if item.app_id is not MISSING:
            app_key = App.create_key(item.app_id)
            product, customer_store_order, sub_order, app, team = db.get([
                product_key, customer_store_order_key, subscription_order_key,
                app_key, team_key
            ])
            if sub_order.status != Order.STATUS_SIGNED:
                raise BusinessException(
                    translate(lang, SOLUTION_COMMON, u'no_unsigned_order'))
            # check if the provided app does exist
            azzert(app)
        else:
            product, customer_store_order, team = db.get(
                [product_key, customer_store_order_key, team_key])

        # Check if the item has a correct count.
        # Should never happen unless the user manually recreates the ajax request..
        azzert(
            not product.possible_counts
            or item.count in product.possible_counts
            or item.code == Product.PRODUCT_EXTRA_CITY,
            u'Invalid amount of items supplied')
        number = 0
        existing_order_items = list()
        vat_pct = get_vat_pct(customer, team)
        item_already_added = False
        if not customer_store_order:
            # create new order
            customer_store_order = Order(key=customer_store_order_key)
            customer_store_order.contact_id = contact.key().id()
            customer_store_order.date = now()
            customer_store_order.vat_pct = 0
            customer_store_order.amount = 0
            customer_store_order.vat = 0
            customer_store_order.vat_pct = vat_pct
            customer_store_order.total_amount = 0
            customer_store_order.is_subscription_order = False
            customer_store_order.manager = STORE_MANAGER
            customer_store_order.team_id = None
        else:
            order_items = OrderItem.list_by_order(customer_store_order.key())
            for i in order_items:
                number = i.number if i.number > number else number
                existing_order_items.append(i)
                # Check if this city isn't already in the possible pending order.
                if hasattr(i, 'app_id') and (i.app_id == item.app_id or
                                             item.app_id in customer.app_ids):
                    raise BusinessException(
                        translate(lang, SOLUTION_COMMON,
                                  u'item_already_added'))
                else:
                    # Check if there already is an orderitem with the same product code.
                    # If so, add the count of this new item to the existing item.
                    for it in order_items:
                        if it.product_code == item.code and it.product_code not in (
                                Product.PRODUCT_EXTRA_CITY,
                                Product.PRODUCT_NEWS_PROMOTION):
                            if (
                                    it.count + item.count
                            ) in product.possible_counts or not product.possible_counts:
                                it.count += item.count
                                item_already_added = True
                                to_put.append(it)
                                order_item = it
                            elif len(product.possible_counts) != 0:
                                raise BusinessException(
                                    translate(
                                        lang,
                                        SOLUTION_COMMON,
                                        u'cant_order_more_than_specified',
                                        allowed_items=max(
                                            product.possible_counts)))

        if item.app_id is not MISSING:
            remaining_length, _ = get_subscription_order_remaining_length(
                customer.id, customer.subscription_order_number)
            subscription_order_charge_date = format_date(
                datetime.datetime.utcfromtimestamp(sub_order.next_charge_date),
                locale=lang)
            total = remaining_length * product.price
        else:
            total = product.price * item.count
        vat = total * vat_pct / 100
        total_price = total + vat
        customer_store_order.amount += total
        customer_store_order.vat += vat
        azzert(customer_store_order.total_amount >= 0)
        customer_store_order.total_amount += total_price
        service_visible_in_translation = None
        if not item_already_added:
            order_item = OrderItem(parent=customer_store_order.key())
            order_item.number = number
            order_item.comment = product.default_comment(customer.language)
            order_item.product_code = product.code
            if item.app_id is not MISSING:
                order_item.count = remaining_length
                service_visible_in_translation = translate(
                    lang,
                    SOLUTION_COMMON,
                    'service_visible_in_app',
                    subscription_expiration_date=subscription_order_charge_date,
                    amount_of_months=remaining_length,
                    extra_city_price=product.price_in_euro,
                    app_name=app.name)
            else:
                order_item.count = item.count
            order_item.price = product.price

            if item.app_id is not MISSING:
                order_item.app_id = item.app_id
            to_put.append(order_item)
        to_put.append(customer_store_order)
        db.put(to_put)
        return order_item, service_visible_in_translation

    try:
        order_item, service_visible_in_translation = run_in_xg_transaction(
            trans)
        return OrderItemReturnStatusTO.create(True, None, order_item,
                                              service_visible_in_translation)
    except BusinessException, exception:
        return OrderItemReturnStatusTO.create(False, exception.message, None)
示例#20
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()