Example #1
0
def put_loyalty_user(service_user, url, email):
    su = None  # ShortURL
    m = re.match("(HTTPS?://)(.*)/(M|S)/(.*)", url.upper())
    if m:
        from rogerthat.pages.shortner import get_short_url_by_code
        code = m.group(4)
        su = get_short_url_by_code(code)
        if su and not su.full.startswith("/q/i"):
            su = None

    if su:
        si = None
    else:
        logging.debug('Create new unassigned short url, because the provided loyalty user URL is unkown (%s)', url)
        si = get_default_service_identity(service_user)
        su = generate_unassigned_short_urls(si.app_id, 1)[0]
        url = su.full

    user_code = su.full[4:]
    pp = ProfilePointer.get(user_code)
    if pp:
        app_user = pp.user
    else:
        service_profile = get_service_profile(service_user)
        si = si or get_default_service_identity(service_user)
        app_id = si.app_id
        app_user = put_loyalty_user_profile(email.strip(), app_id, user_code, su.key().id(),
                                            service_profile.defaultLanguage)

    return url, app_user
    def testServiceIdentityCacheSerialization(self):
        svc_user = users.User(u'*****@*****.**')
        _, svc_identity = create_service_profile(svc_user, 'Serviceke')
        self.assert_(isinstance(svc_identity, ServiceIdentity))

        svc_id2 = get_default_service_identity(svc_user)
        self.assert_(isinstance(svc_id2, ServiceIdentity))
        self.assert_(svc_id2.name == svc_identity.name)
        self.assert_(svc_id2.name == 'Serviceke')

        svc_id3 = get_profile_info(svc_user)
        self.assert_(isinstance(svc_id3, ServiceIdentity))

        rpc.wait_for_rpcs()
        flush_request_cache()

        svc_id4 = get_profile_info(svc_user)
        self.assert_(isinstance(svc_id4, ServiceIdentity))

        rpc.wait_for_rpcs()
        flush_request_cache()

        svc_id5 = get_default_service_identity(svc_user)
        self.assert_(svc_user == svc_id5.service_user)
        self.assert_('Serviceke' == svc_id5.name)
Example #3
0
    def testSearchResults(self):
        self.set_datastore_hr_probability(1)

        # Prepare services
        service_profile = self._prepareService('*****@*****.**')[1]
        si = get_default_service_identity(service_profile.user)

        # Check FindServiceItemTO
        for lang in ['en', 'fr', 'nl', 'ar']:
            if lang == service_profile.defaultLanguage or lang not in service_profile.supportedLanguages:
                prefix = ""
            else:
                prefix = "%s_" % lang

            itemTO = FindServiceItemTO.fromServiceIdentity(si, lang)

            for to_attr, si_attr in {
                    "name": "name",
                    "description": "description",
                    "description_branding": "descriptionBranding",
                    "qualified_identifier": "qualifiedIdentifier"
            }.iteritems():
                expected = prefix + si_attr
                self.assertEqual(
                    getattr(itemTO, to_attr), expected,
                    "itemTO.%s != '%s' (language: %s)" %
                    (to_attr, expected, lang))
Example #4
0
def create_news_item(sln_settings, broadcast_type, message, title, permalink):
    service_user = sln_settings.service_user
    logging.info('Creating news item:\n- %s\n- %s\n- %s\n- %s\n- %s', service_user, message, title, broadcast_type,
                 permalink)

    with users.set_user(service_user):
        sticky = False
        sticky_until = 0
        image = None
        news_type = NewsItem.TYPE_NORMAL
        link_caption = transl(u'More info', sln_settings.main_language)
        action_button = NewsActionButtonTO(u'url', link_caption, permalink)
        qr_code_content = None
        qr_code_caption = None
        si = get_default_service_identity(service_user)
        app_ids = si.appIds

        title = limit_string(title, NewsItem.MAX_TITLE_LENGTH)
        news.publish(sticky=sticky,
                     sticky_until=sticky_until,
                     title=title,
                     message=message,
                     image=image,
                     news_type=news_type,
                     flags=NewsItem.DEFAULT_FLAGS | NewsItem.FLAG_SILENT,
                     broadcast_type=broadcast_type,
                     action_buttons=[action_button],
                     qr_code_content=qr_code_content,
                     qr_code_caption=qr_code_caption,
                     scheduled_at=0,
                     app_ids=app_ids)
Example #5
0
def put_settings(settings, app_id=None):
    service_user = users.get_current_user()
    if not app_id:
        app_id = get_default_service_identity(service_user).app_id

    validate_app_admin(service_user, [app_id])
    bizz_app.put_settings(service_user, app_id, settings)
def get_profile_info(user, cached=True, skip_warning=False):
    '''Returns a ProfileInfo (UserProfile or ServiceIdentity)'''
    if "/" in user.email():
        return get_service_identity(user) if cached else get_service_identity_not_cached(user)
    profile = _get_profile(user) if cached else _get_profile_not_cached(user)
    if not profile or isinstance(profile, UserProfile):
        return profile
    if not skip_warning:
        logging.warn("Implicit retrieving default ServiceIdentity for %s\n%s" % (user.email(), get_python_stack_trace(short=True)))
    return get_default_service_identity(user) if cached else get_default_service_identity_not_cached(user)
    def test_menu_items(self):
        user_profile, service_profile = self._prepare_users()

        friend_user = user_profile.user
        service_user = service_profile.user
        service_identity = get_default_service_identity(service_profile.user)
        makeFriends(friend_user, service_identity.user, service_identity.user, None, origin=ORIGIN_USER_INVITE)

        helper = FriendHelper.from_data_store(service_identity.user, FRIEND_TYPE_SERVICE)
        helper.get_service_profile()
        helper._service_profile = service_profile  # because we modify the service_profile which is cached by the helper

        menu = ServiceMenuTO.from_model(helper, user_profile.language, user_profile)
        self.assertEqual(0, len(menu.items))

        # No broadcast types --> error
        self.assertRaises(BusinessException, create_menu_item, service_user, "3d", "000000", "label", "tag", [1, 1, 1],
                          None, None, False, False, [], is_broadcast_settings=True, broadcast_branding=None)

        service_profile.broadcastTypes = ['Apes', 'Birds', 'Cats', 'Dogs']
        service_profile.put()

        friend_service_identity_connection = get_friend_serviceidentity_connection(friend_user, service_identity.user)
        friend_service_identity_connection.enabled_broadcast_types = service_profile.broadcastTypes
        friend_service_identity_connection.put()

        create_menu_item(service_user, "3d", "000000", "label", "tag", [1, 1, 1], None, None, False, False, [],
                         is_broadcast_settings=True, broadcast_branding=None)

        def _test_1_bc_settings_item():
            menu = ServiceMenuTO.from_model(helper, user_profile.language, user_profile)
            self.assertEqual(1, len(menu.items))
            smi = menu.items[0]
            self.assertTrue(smi.staticFlowHash)

            request = GetStaticFlowRequestTO()
            request.service = service_user.email()
            request.staticFlowHash = smi.staticFlowHash
            request.coords = smi.coords

            response = getStaticFlow(request)
            self.assertTrue(response)
            self.assertTrue(response.staticFlow)

        _test_1_bc_settings_item()

        move_menu_item(service_user, [1, 1, 1], [2, 2, 2])

        _test_1_bc_settings_item()

        # test Web-version of menu TO
        WebServiceMenuTO.from_model(helper, user_profile.language, user_profile)
def get_settings(app_id=None):
    """
    Args:
        app_id (unicode)
    Returns:
        AppSettingsTO
    """
    service_user = users.get_current_user()
    if not app_id:
        app_id = get_default_service_identity(service_user).app_id

    validate_app_admin(service_user, [app_id])
    return AppSettingsTO.from_model(bizz_app.get_app_settings(app_id))
Example #9
0
def _create_news_item(message,
                      service_identity,
                      service_user,
                      broadcast_type,
                      urls=None):
    if service_identity:
        service_identity_user = create_service_identity_user(
            service_user, service_identity)
        si = get_service_identity(service_identity_user)
    else:
        si = get_default_service_identity(service_user)
        service_identity_user = si.service_identity_user
    if '\n' in message:
        split = message.splitlines()
        title = limit_string(split[0], NewsItem.MAX_TITLE_LENGTH)
        message = '\n'.join(split[1:])
    else:
        title = limit_string(message, NewsItem.MAX_TITLE_LENGTH)
    news_buttons = []
    if urls:
        for url in urls:
            if url.get('url') and url.get('name'):
                id_ = u'url'
                caption = u'%s' % url['name']
                action = u'%s' % url['url']
                if len(caption) > NewsItem.MAX_BUTTON_CAPTION_LENGTH:
                    sln_settings = get_solution_settings(service_user)
                    caption = translate(sln_settings.main_language,
                                        SOLUTION_COMMON, u'read_more')
                news_buttons.append(NewsActionButtonTO(id_, caption, action))
                break

    app_ids = [
        app_id for app_id in si.appIds if app_id != App.APP_ID_OSA_LOYALTY
    ]
    return put_news(service_identity_user,
                    sticky=False,
                    sticky_until=0,
                    title=title,
                    message=message,
                    image=None,
                    news_type=NewsItem.TYPE_NORMAL,
                    broadcast_type=broadcast_type,
                    news_buttons=news_buttons,
                    qr_code_content=None,
                    qr_code_caption=None,
                    app_ids=app_ids,
                    news_id=None,
                    accept_missing=True)
    def testServiceIdentitySerializer(self):
        name = u'name %s' % uuid.uuid4()
        svc_email = u'*****@*****.**' % uuid.uuid4()
        svc_user = users.User(svc_email)
        create_service_profile(svc_user, name)

        svc_identity_original = get_default_service_identity(users.User(svc_email))
        stream = StringIO.StringIO()
        s_service_identity(stream, svc_identity_original)
        stream_str = stream.getvalue()

        svc_identity_deserialized = ds_service_identity(StringIO.StringIO(stream_str))

        self.assert_(svc_identity_original.user == svc_identity_deserialized.user)
        self.assert_(svc_identity_original.name == svc_identity_deserialized.name)
Example #11
0
def create_prospect_from_customer(customer):
    azzert(customer.prospect_id is None and customer.service_email)

    contact = Contact.get_one(customer.key())
    azzert(contact)

    si = get_default_service_identity(users.User(customer.service_email))

    prospect = Prospect(key_name=str(uuid.uuid4()) + str(uuid.uuid4()))
    prospect.name = customer.name
    prospect.address = ', '.join(filter(None, [customer.address1 + ((' ' + customer.address2) if customer.address2 else ''),
                                               customer.zip_code,
                                               customer.city,
                                               OFFICIALLY_SUPPORTED_COUNTRIES.get(customer.country, customer.country)]))
    prospect.phone = contact.phone_number
    prospect.email = contact.email
    prospect.type = ['establishment']
    if customer.organization_type == OrganizationType.EMERGENCY:
        prospect.type.append('health')
    prospect.customer_id = customer.id
    prospect.status = Prospect.STATUS_CUSTOMER
    prospect.app_id = si.app_id
    
    solution_server_settings = get_solution_server_settings()
    prospect.add_comment(u'Converted customer to prospect', users.User(solution_server_settings.shop_no_reply_email)) 
    try:
        result = geo_code(prospect.address)
    except GeoCodeZeroResultsException:
        try:
            result = geo_code(' '.join(filter(None, [customer.zip_code,
                                                     customer.city,
                                                     OFFICIALLY_SUPPORTED_COUNTRIES.get(customer.country,
                                                                                        customer.country)])))
        except GeoCodeZeroResultsException:
            logging.warn('Could not geo_code customer: %s', db.to_dict(customer))
            return

    prospect.geo_point = db.GeoPt(result['geometry']['location']['lat'],
                                  result['geometry']['location']['lng'])

    customer.prospect_id = prospect.id
    prospect.customer_id = customer.id

    logging.info('Creating prospect: %s', db.to_dict(prospect, dict(prospect_id=prospect.id)))
    put_and_invalidate_cache(customer, prospect)
    return prospect
def _get_profile_infos_not_cached(users_):
    keys = list()
    for user in users_:
        if "/" in user.email():
            keys.append(ServiceIdentity.keyFromUser(user))
        else:  # Could be human or service users
            keys.append(get_user_profile_key(user))

    result = db.get(keys)
    for i in xrange(len(result)):
        r = result[i]
        if "/" not in users_[i].email() and (r is None or isinstance(r, ServiceProfile)):
            # profile did not exist or was a default identity.
            result[i] = get_default_service_identity(users_[i])  # XXX: we could make this smarter

    # XXX: populate cache
    return result
Example #13
0
    def get(self, the_hash, page):
        self.response.headers['Cache-Control'] = "public, max-age=31536000"  # Cache forever (1 year)
        branding = Branding.get_by_key_name(the_hash)
        if not branding:
            self.error(404)
            return

        zipStream = get_branding_blob_stream(branding)
        if not zipStream:
            return self.error(404)

        with closing(zipStream):
            the_zip = ZipFile(zipStream)
            files = [fi.filename for fi in the_zip.filelist]
            if page == "branding_web.html" and page not in files:
                page = "branding.html"
            if not page in files:
                logging.warning("%s not found in branding zip" % page)
                self.error(404)
                return
            _, extension = os.path.splitext(page.lower())
            if extension in (".jpg", ".jpeg"):
                self.response.headers['Content-Type'] = "image/jpeg"
            elif extension == ".png":
                self.response.headers['Content-Type'] = "image/png"
            elif extension == ".css":
                self.response.headers['Content-Type'] = "text/css"
            content = the_zip.read(page)
        if self.request.get('xrender', 'false') == 'true':
            from lxml import html, etree
            doc = html.fromstring(content)
            elements = doc.xpath("//nuntiuz_identity_name")
            if elements:
                if branding.user:
                    si = get_default_service_identity(branding.user)
                    name = si.name
                else:
                    name = get_app_name_by_id(App.APP_ID_ROGERTHAT)
                elem = elements[0]
                parent = elem.getparent()
                elem.drop_tree()
                parent.text = name
            self.response.out.write(etree.tostring(doc))  # @UndefinedVariable
        else:
            self.response.out.write(content)
    def get(self, version, page):
        if int(version) > 0:
            self.response.headers['Cache-Control'] = "public, max-age=31536000"  # Cache forever (1 year)
        if page not in ('branding.html', 'logo.jpg', 'frame.png'):
            logging.warning("%s not found in branding editor" % page)
            self.error(404)
            return
        _, extension = os.path.splitext(page.lower())
        if extension in (".jpg", ".jpeg"):
            self.response.headers['Content-Type'] = "image/jpeg"
        elif extension == ".png":
            self.response.headers['Content-Type'] = "image/png"
        elif extension == ".css":
            self.response.headers['Content-Type'] = "text/css"

        if page == "branding.html":
            content, _ = render_branding_html(self.request.get("color_scheme", Branding.COLOR_SCHEME_DARK),
                                              self.request.get("background_color", "000000"),
                                              self.request.get("text_color", "FFFFFF"),
                                              self.request.get("menu_item_color", "FFFFFF"),
                                              self.request.get("show_header", "false") == "true")
            logging.debug("branding.html: %s" % content)
        else:
            with open(os.path.join(os.path.dirname(__file__), page)) as f:
                content = f.read()
            target_color = self.request.get("color")
            if target_color and target_color != COLOR_BLACK:
                logging.debug("Re-coloring PNG to %s" % str(webcolor_to_color_tuple(target_color)))
                content = recolor_png(content, webcolor_to_color_tuple(COLOR_BLACK), webcolor_to_color_tuple(target_color))

        if self.request.get('xrender', 'false') == 'true':
            from lxml import html, etree
            doc = html.fromstring(content)
            service_identity = None
            for elem in doc.xpath("//nuntiuz_identity_name"):
                service_identity = service_identity or get_default_service_identity(users.get_current_user())
                parent = elem.getparent()
                elem.drop_tree()
                parent.text = service_identity.name
            self.response.out.write(etree.tostring(doc))  # @UndefinedVariable
        else:
            self.response.out.write(content)
 def trans():
     to_put = list()
     customer = Customer.get(customer_key)
     if App.APP_ID_ROGERTHAT not in customer.app_ids and customer.service_email:
         customer.app_ids.append(App.APP_ID_ROGERTHAT)
         to_put.append(customer)
         service_identity = get_default_service_identity(
             customer.service_user)
         if App.APP_ID_ROGERTHAT not in service_identity.appIds:
             service_identity.appIds.append(App.APP_ID_ROGERTHAT)
             deferred.defer(re_index,
                            service_identity.service_identity_user,
                            _queue=MIGRATION_QUEUE,
                            _transactional=True)
             to_put.append(service_identity)
         deferred.defer(re_index_customer,
                        customer.key(),
                        _queue=MIGRATION_QUEUE,
                        _transactional=True)
         put_and_invalidate_cache(*to_put)
Example #16
0
def put_loyalty_user(url, email):
    service_user = users.get_current_user()
    url = url.upper()
    m = re.match("(HTTPS?://)(.*)/(M|S)/(.*)", url)
    if m:
        from rogerthat.pages.shortner import get_short_url_by_code
        code = m.group(4)
        su = get_short_url_by_code(code)

        if su.full.startswith("/q/i"):
            user_code = su.full[4:]
            pp = ProfilePointer.get(user_code)
            if not pp:
                service_profile = get_service_profile(service_user)
                si = get_default_service_identity(service_user)
                put_loyalty_user_profile(email.strip(), si.app_id, user_code, su.key().id(),
                                         service_profile.defaultLanguage)
        else:
            raise AppFailedToResovelUrlException(url)
    else:
        raise AppFailedToResovelUrlException(url)
    def testSignup(self):
        self.set_datastore_hr_probability(1)

        owner_user = users.get_current_user()
        name = u"service_name"
        description = u"service_description"
        trial_service_to = signup(owner_user, name, description, True)
        assert is_trial_service(users.User(trial_service_to.account))

        ts = get_trial_service_by_owner(owner_user)
        assert ts
        si = get_default_service_identity(ts.service)
        assert si.name == name
        assert si.description == description

        svc_profile = get_service_profile(si.service_user)
        assert svc_profile.avatarId > 0
        assert svc_profile.passwordHash

        qr_codes = get_service_interaction_defs(si.service_user, si.identifier, None, True)['defs']
        assert len(qr_codes) > 0
        assert ServiceInteractionDef.TAG_INVITE in [qr.tag for qr in qr_codes]
    def testSearchResults(self):
        self.set_datastore_hr_probability(1)

        # Prepare services
        service_profile = self._prepareService('*****@*****.**')[1]
        si = get_default_service_identity(service_profile.user)

        # Check FindServiceItemTO
        for lang in ['en', 'fr', 'nl', 'ar']:
            if lang == service_profile.defaultLanguage or lang not in service_profile.supportedLanguages:
                prefix = ""
            else:
                prefix = "%s_" % lang

            itemTO = FindServiceItemTO.fromServiceIdentity(si, lang)

            for to_attr, si_attr in {"name": "name",
                                     "description": "description",
                                     "description_branding": "descriptionBranding",
                                     "qualified_identifier": "qualifiedIdentifier"}.iteritems():
                expected = prefix + si_attr
                self.assertEqual(getattr(itemTO, to_attr), expected,
                                 "itemTO.%s != '%s' (language: %s)" % (to_attr, expected, lang))
    def testServiceProfileCacheSerialization(self):
        svc_user = users.User(u'*****@*****.**')
        _, svc_identity = create_service_profile(svc_user, 'Service')

        self.assert_(isinstance(svc_identity, ServiceIdentity))

        profile2 = get_service_profile(svc_user)
        self.assert_(isinstance(profile2, ServiceProfile))
        service_identity2 = get_profile_info(svc_user)
        self.assert_(isinstance(service_identity2, ServiceIdentity))

        rpc.wait_for_rpcs()
        flush_request_cache()

        profile3 = get_profile_info(svc_user)
        self.assert_(isinstance(profile3, ServiceIdentity))

        rpc.wait_for_rpcs()
        flush_request_cache()

        service_identity4 = get_default_service_identity(svc_user)
        self.assert_(service_identity2.user, service_identity4.user)
        self.assert_(service_identity2.name, service_identity4.name)
Example #20
0
def create_and_pay_news_order(service_user, news_item_id, order_items_to):
    """
    Creates an order, orderitems, charge and executes the charge. Should be executed in a transaction.
    Args:
        service_user (users.User)
        news_item_id (long)
        order_items_to (ist of OrderItemTO)

    Raises:
        NoCreditCardException
        ProductNotFoundException
    """
    @db.non_transactional
    def _get_customer():
        return get_customer(service_user)

    @db.non_transactional
    def _get_contact():
        return Contact.get_one(customer)

    customer = _get_customer()
    azzert(customer)
    contact = _get_contact()
    azzert(contact)
    if not customer.stripe_valid:
        raise NoCreditCardException(customer)
    extra_city_product_key = Product.create_key(Product.PRODUCT_EXTRA_CITY)
    news_product_key = Product.create_key(Product.PRODUCT_NEWS_PROMOTION)
    rmt_key = RegioManagerTeam.create_key(customer.team_id)
    extra_city_product, news_promotion_product, team = db.get(
        (extra_city_product_key, news_product_key, rmt_key))
    azzert(extra_city_product)
    azzert(news_promotion_product)
    azzert(team)
    new_order_key = Order.create_key(customer.id,
                                     OrderNumber.next(team.legal_entity_key))
    vat_pct = get_vat_pct(customer, team)

    total_amount = 0
    added_app_ids = []
    for order_item in order_items_to:
        if order_item.product == Product.PRODUCT_EXTRA_CITY:
            total_amount += extra_city_product.price * order_item.count
            added_app_ids.append(order_item.app_id)
            order_item.price = extra_city_product.price
        elif order_item.product == Product.PRODUCT_NEWS_PROMOTION:
            total_amount += news_promotion_product.price * order_item.count
            order_item.price = news_promotion_product.price
        else:
            raise BusinessException('Invalid product \'%s\'' %
                                    order_item.product)
    si = get_default_service_identity(users.User(customer.service_email))
    if added_app_ids:
        keys = [App.create_key(app_id) for app_id in added_app_ids]
        apps = db.get(keys)
        for app_id, app in zip(added_app_ids, apps):
            if not app:
                raise AppNotFoundException(app_id)
            if app_id in si.appIds:
                raise BusinessException('Customer %s already has app_id %s' %
                                        (customer.id, app_id))

    vat = int(round(vat_pct * total_amount / 100))
    total_amount_vat_incl = int(round(total_amount + vat))
    now_ = now()
    to_put = []
    order = Order(key=new_order_key,
                  date=now_,
                  amount=total_amount,
                  vat_pct=vat_pct,
                  vat=vat,
                  total_amount=total_amount_vat_incl,
                  contact_id=contact.id,
                  status=Order.STATUS_SIGNED,
                  is_subscription_order=False,
                  is_subscription_extension_order=False,
                  date_signed=now_,
                  manager=STORE_MANAGER,
                  team_id=team.id)
    to_put.append(order)
    azzert(order.total_amount >= 0)

    for item in order_items_to:
        order_item = OrderItem(parent=new_order_key,
                               number=item.number,
                               product_code=item.product,
                               count=item.count,
                               comment=item.comment,
                               price=item.price)
        order_item.app_id = item.app_id
        if order_item.product_code == Product.PRODUCT_NEWS_PROMOTION:
            order_item.news_item_id = news_item_id
        to_put.append(order_item)

    db.put(to_put)

    # Not sure if this is necessary
    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.
    to_put = []
    charge = Charge(parent=new_order_key)
    charge.date = now()
    charge.type = Charge.TYPE_ORDER_DELIVERY
    charge.amount = order.amount
    charge.vat_pct = order.vat_pct
    charge.vat = order.vat
    charge.total_amount = order.total_amount
    charge.manager = order.manager
    charge.team_id = order.team_id
    charge.status = Charge.STATUS_PENDING
    charge.date_executed = now()
    charge.currency_code = team.legal_entity.currency_code
    to_put.append(charge)

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

    # Update the customer service
    si.appIds.extend(added_app_ids)
    to_put.append(si)

    # Update the customer object so the newly added apps are added.
    customer.app_ids.extend(added_app_ids)
    customer.extra_apps_count += len(added_app_ids)
    to_put.append(customer)
    db.put(to_put)
    deferred.defer(re_index, si.user)

    # charge the credit card
    if charge.total_amount > 0:
        get_payed(customer.id, order, charge)
        server_settings = get_server_settings()
        send_to = server_settings.supportWorkers
        send_to.append(MC_DASHBOARD.email())
        channel_data = {
            'customer': customer.name,
            'no_manager': True,
            'amount': charge.amount / 100,
            'currency': charge.currency
        }
        channel.send_message(map(users.User, send_to),
                             'shop.monitoring.signed_order',
                             info=channel_data)
    else:
        charge.status = Charge.STATUS_EXECUTED
        charge.date_executed = now()
        charge.put()
    channel.send_message(service_user, 'common.billing.orders.update')
def getUserInfo(request):
    from rogerthat.bizz.friends import get_profile_info_via_user_code
    from rogerthat.pages.profile import get_avatar_cached
    from rogerthat.rpc import users
    current_app_id = users.get_current_app_id()
    user_code = request.code
    if '@' in user_code:
        if "/" in user_code:
            profile_info = get_profile_info(users.User(user_code))
        else:
            profile_info = get_profile_info(create_app_user(users.User(user_code), current_app_id))
            if not profile_info:
                profile_info = get_default_service_identity(users.User(user_code))

        if not profile_info:
            raise ApiWarning("User with userCode or email '%s' not found!" % request.code)
    else:
        if "?" in user_code:
            user_code = user_code[:user_code.index("?")]
        profile_info = get_profile_info_via_user_code(user_code)

        if not profile_info:
            loglevel = logging.DEBUG if current_app_id == App.APP_ID_OSA_LOYALTY else logging.WARNING
            logging.log(loglevel, "User with userCode or email '%s' not found!" % request.code)
            response = GetUserInfoResponseTO()
            response.avatar = None
            response.avatar_id = 0
            response.description = None
            response.descriptionBranding = None
            response.app_id = response.email = response.name = response.qualifiedIdentifier = u"dummy"
            response.type = FRIEND_TYPE_PERSON
            response.profileData = None

            if current_app_id == App.APP_ID_OSA_LOYALTY:
                response.error = None
            else:
                response.error = ErrorTO()
                target_language = get_user_profile(users.get_current_user()).language
                response.error.title = localize(target_language, "Error")
                response.error.message = localize(target_language,
                                                  "The scanned QR code is not supported by the %(app_name)s app",
                                                  app_name=get_app_name_by_id(current_app_id))
                response.error.caption = response.error.action = None
            return response


    response = GetUserInfoResponseTO()
    response.avatar = unicode(base64.b64encode(get_avatar_cached(profile_info.avatarId)))
    response.avatar_id = profile_info.avatarId
    response.description = None
    response.descriptionBranding = None
    response.app_id = current_app_id if profile_info.isServiceIdentity else profile_info.app_id
    response.email = (remove_slash_default(profile_info.user) if profile_info.isServiceIdentity else get_human_user_from_app_user(profile_info.user)).email()
    response.name = profile_info.name
    response.qualifiedIdentifier = profile_info.qualifiedIdentifier
    response.type = FRIEND_TYPE_SERVICE if profile_info.isServiceIdentity else FRIEND_TYPE_PERSON
    response.profileData = None if profile_info.isServiceIdentity else profile_info.profileData

    if request.allow_cross_app == MISSING:
        request.allow_cross_app = False

    if request.allow_cross_app or current_app_id == profile_info.app_id:
        response.error = None
    else:
        response.error = ErrorTO()
        target_language = get_user_profile(users.get_current_user()).language
        response.error.title = localize(target_language, "Error")
        response.error.message = localize(target_language,
                                          "The scanned QR code is not supported by the %(app_name)s app",
                                          app_name=get_app_name_by_id(current_app_id))
        response.error.caption = response.error.action = None
    return response
Example #22
0
    def trans():
        service_profile = get_service_profile(service_user, False)
        bizz_check(service_profile,
                   "Service %s does not exist" % service_user.email())
        bizz_check(
            not service_profile.solution
            or service_profile.solution == solution,
            u"Cannot change solution from %s to %s" %
            (service_profile.solution, solution))
        service_profile.solution = solution

        default_si = None
        if apps is not None:
            azzert(apps)
            default_si = get_default_service_identity(service_user)
            default_si.appIds = apps
            default_si.defaultAppId = apps[0]
            default_si.put()

        if organization_type is not None:
            service_profile.organizationType = organization_type

        solution_settings = get_solution_settings(service_user)
        solution_settings_changed = False
        if not solution_settings:
            default_si = default_si or get_default_service_identity(
                service_user)
            solution_settings = SolutionSettings(
                key=SolutionSettings.create_key(service_user),
                name=default_si.name)
            solution_settings_changed = True

        if solution_settings.solution != solution:
            solution_settings.solution = solution
            solution_settings_changed = True

        if languages:
            service_profile.supportedLanguages = languages
            solution_settings.main_language = languages[0]
            solution_settings_changed = True

        if menu_item_color == u"branding":
            solution_settings.menu_item_color = None
            solution_settings_changed = True
        elif menu_item_color:
            try:
                parse_color(menu_item_color)
            except ValueError:
                raise InvalidMenuItemColorException()

            solution_settings.menu_item_color = menu_item_color
            solution_settings_changed = True

        if currency:
            solution_settings.currency = currency
            solution_settings_changed = True

        if modules is not None:
            solution_settings.modules = modules
            solution_settings_changed = True

        if broadcast_types is not None:
            solution_settings.broadcast_types = broadcast_types
            solution_settings_changed = True

        main_branding, branding_settings = db.get([
            SolutionMainBranding.create_key(service_user),
            SolutionBrandingSettings.create_key(service_user)
        ])
        if not main_branding:
            main_branding = SolutionMainBranding(
                key=SolutionMainBranding.create_key(service_user))
            if not branding_url:
                main_branding.put()
        if branding_url:
            main_branding.blob = db.Blob(resp.content)
            main_branding.branding_creation_time = 0
            main_branding.put()

        if not branding_settings:
            branding_settings = _get_default_branding_settings(service_user)
            branding_settings.put()

        if solution_settings.name != name and name is not None:
            solution_settings.name = name
            solution_settings_changed = True
        if solution_settings.address != address and address is not None:
            solution_settings.address = address
            solution_settings_changed = True
        if solution_settings.phone_number != phone_number and phone_number is not None:
            solution_settings.phone_number = phone_number
            solution_settings_changed = True
        if solution_settings.qualified_identifier != qualified_identifier and qualified_identifier is not None:
            solution_settings.qualified_identifier = qualified_identifier
            solution_settings_changed = True
        service_profile.put()
        if solution_settings_changed:
            solution_settings.put()
        return solution_settings
Example #23
0
    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)
 def trans():
     si = get_default_service_identity(service_user)
     si.description = u"Test Description"
     si.put()
     return si
    def test_put_translations(self):
        service_user = self._prepare_svc()
        service_profile = get_service_profile(service_user)

        service_profile.supportedLanguages.extend([u'nl'])
        service_profile.put()

        si = get_default_service_identity(service_user)
        si.description = u"Test Description"
        si.put()

        put_flow(VALID_XML1)
        put_menu_item("3d", "label", "tag", [1, 1, 0], "999999")

        translation_set = get_translations()
        assert translation_set.export_id
        assert service_user.email() == translation_set.email

        print
        print 'TranslationSet in datastore:'
        print get_all_translations(get_editable_translation_set(service_user))
        print
        print 'TranslationSet transfer object:'
        print serialize_complex_value(translation_set, TranslationSetTO, False)

        # Name and description are the only properties that are filled in
        # Let's translate them in Dutch

        NL_NAME = u'Test Naam'
        NL_DESCR = u'Test Beschrijving'

        name_found = description_found = False
        for translation in translation_set.translations:
            if translation.type == ServiceTranslation.IDENTITY_TEXT:
                if translation.key == si.name:
                    name_found = True
                    assert not translation.values
                    nl_value = TranslationValueTO()
                    nl_value.language = u'nl'
                    nl_value.value = NL_NAME
                    translation.values = [ nl_value ]
                if translation.key == si.description:
                    description_found = True
                    assert not translation.values
                    nl_value = TranslationValueTO()
                    nl_value.language = u'nl'
                    nl_value.value = NL_DESCR
                    translation.values = [ nl_value ]

        print
        print 'Updated TranslationSet transfer object:'
        print serialize_complex_value(translation_set, TranslationSetTO, False)

        assert name_found
        assert description_found

        put_translations(translation_set)

        print
        print 'Updated TranslationSet in datastore:'
        print get_all_translations(get_editable_translation_set(service_user))

        # Test that nl name and description are in FriendTO
        human_user = users.User(u'*****@*****.**')
        create_user_profile(human_user, human_user.email(), language=u'nl')
        makeFriends(human_user, service_user, None, None, None)

        friendTO = FriendTO.fromDBFriendMap(get_friends_map(human_user), service_user, includeServiceDetails=True,
                                            targetUser=human_user)
        assert friendTO.name == NL_NAME
        assert friendTO.description == NL_DESCR

        # Test protection against overwriting
        time.sleep(1)  # making sure export_id is unique, since it's the current epoch in seconds
        get_translations()  # will save new export_id
        self.assertRaises(Exception, put_translations, translation_set)  # translation_set still has old export_id

        translations = get_translations()
        translations.email = u"*****@*****.**"
        self.assertRaises(Exception, put_translations, translation_set)
    def test_friends(self):
        non_nuntiuz_user = users.User(u'*****@*****.**')
        # setup env
        invitor = users.get_current_user()
        invitee = users.User(u'*****@*****.**')
        create_user_profile(invitee, invitee.email())
        register_tst_mobile(invitee.email())
        service_user = users.User(u'*****@*****.**')
        create_user_profile(service_user, u"Mobicage NV")
        convert_user_to_service(service_user)
        svc_identity = get_default_service_identity(service_user)
        svc_identity_user = svc_identity.user
        service_profile = get_service_profile(service_user)
        service_profile.callBackJid = "*****@*****.**"
        service_profile.sik = "test"
        service_profile.put()

        # assert invitee and invitor are not friends
        myFriendMap = get_friends_map(invitor)
        hisFriendMap = get_friends_map(invitee)
        assert not invitee in myFriendMap.friends
        assert not invitor in hisFriendMap.friends

        # assert friend generation
        assert myFriendMap.generation == 0
        assert hisFriendMap.generation == 0

        # invite, sending email
        invite(invitor, non_nuntiuz_user.email(), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT)
        set_current_user(non_nuntiuz_user, skip_create_session=True)
        messages = getMessages(None).messages
        assert not messages  # email was sent

        # trigger to much invites this week
        self.assertRaises(PersonAlreadyInvitedThisWeekException, lambda: invite(invitor, non_nuntiuz_user.email(), None, None, \
                                                                                None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT))
        get_friend_invitation_history(invitor, non_nuntiuz_user).delete()

        # trigger too much invites
        original_now = utils._now_impl
        utils._now_impl = lambda: original_now() - WEEK - WEEK - WEEK
        invite(invitor, invitee.email(), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT)
        utils._now_impl = lambda: original_now() - WEEK - WEEK
        invite(invitor, invitee.email(), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT)
        utils._now_impl = lambda: original_now() - WEEK
        invite(invitor, invitee.email(), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT)
        utils._now_impl = original_now
        self.assertRaises(PersonInvitationOverloadException, lambda: invite(invitor, invitee.email(), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT))
        get_friend_invitation_history(invitor, invitee).delete()

        # invite two nuntiuz users
        invite(invitor, invitee.email(), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT)
        set_current_user(invitee)
        messages = getMessages(None).messages
        assert messages
        invitation = messages[0]
        myFriendMap = get_friends_map(invitor)
        hisFriendMap = get_friends_map(invitee)
        assert myFriendMap.generation == 0
        assert hisFriendMap.generation == 0
        request = AckMessageRequestTO()
        request.button_id = ACCEPT_ID
        request.message_key = invitation.key
        request.custom_reply = None
        request.parent_message_key = None
        request.timestamp = now()
        ackMessage(request)
        myFriendMap = get_friends_map(invitor)
        hisFriendMap = get_friends_map(invitee)
        assert myFriendMap.generation == 1
        assert hisFriendMap.generation == 1

        # assert invitee and invitor are friends
        assert invitee in myFriendMap.friends
        assert invitor in hisFriendMap.friends

        # assert svc_identity_user and invitee are not friends
        assert remove_slash_default(svc_identity_user) not in hisFriendMap.friends
        assert not get_friend_serviceidentity_connection(invitee, svc_identity_user)

        # Cleanup previously sent messages
        db.delete(Message.all())

        # svc_identity_user invites friend
        set_current_user(service_user)
        service_invite(invitee.email(), None, "Ghellooooo", "fr", "tzal wezen bakske frezen",
                       service_identity=svc_identity.identifier)

        # assert svc_identity_user and invitee are not friends
        hisFriendMap = get_friends_map(invitee)
        assert remove_slash_default(svc_identity_user) not in hisFriendMap.friends
        assert not get_friend_serviceidentity_connection(invitee, svc_identity_user)

        # accept message and verify
        set_current_user(invitee)
        messages = getMessages(None).messages
        assert messages
        invitation = messages[0]
        request = AckMessageRequestTO()
        request.button_id = ACCEPT_ID
        request.message_key = invitation.key
        request.custom_reply = None
        request.parent_message_key = None
        request.timestamp = now()
        ackMessage(request)
        hisFriendMap = get_friends_map(invitee)
        assert remove_slash_default(svc_identity_user) in hisFriendMap.friends
        assert get_friend_serviceidentity_connection(invitee, svc_identity_user)

        # breakup friends invitor & invitee
        breakFriendShip(invitor, invitee)
        myFriendMap = get_friends_map(invitor)
        hisFriendMap = get_friends_map(invitee)
        assert myFriendMap.generation == 2
        assert hisFriendMap.generation == 3

        # assert invitee and invitor are not friends
        assert not invitee in myFriendMap.friends
        assert not invitor in hisFriendMap.friends

        # breakup friends svc_identity_user & invitee
        breakFriendShip(svc_identity_user, invitee)
        hisFriendMap = get_friends_map(invitee)
        assert hisFriendMap.generation == 4

        # assert invitee and svc_identity_user are not friends
        assert remove_slash_default(svc_identity_user) not in hisFriendMap.friends
        assert not get_friend_serviceidentity_connection(invitee, svc_identity_user)

        # Cleanup previously sent messages
        db.delete(Message.all())

        # friend invites svc_identity_user
        set_current_user(invitor)
        invite(invitor, remove_slash_default(svc_identity_user).email(), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT)
        myFriendMap = get_friends_map(invitor)
        print myFriendMap.generation
        invited_response_receiver(UNIT_TEST_REFS["invited"], ACCEPT_ID)
        myFriendMap = get_friends_map(invitor)
        assert remove_slash_default(svc_identity_user) in myFriendMap.friends
        print myFriendMap.generation
        assert myFriendMap.generation == 3
        assert get_friend_serviceidentity_connection(invitor, svc_identity_user)
        assert not myFriendMap.friendDetails[remove_slash_default(svc_identity_user).email()].hasUserData

        # Cleanup previously sent messages
        db.delete(Message.all())

        # invite two nuntiuz users via user code
        invite(invitor, unicode(userCode(users.User(invitee.email()))), None, None, None, None, origin=ORIGIN_USER_INVITE, app_id=App.APP_ID_ROGERTHAT)
        set_current_user(invitee)
        messages = getMessages(None).messages
        assert messages
        invitation = messages[0]
        myFriendMap = get_friends_map(invitor)
        hisFriendMap = get_friends_map(invitee)
        assert myFriendMap.generation == 3
        assert hisFriendMap.generation == 4
        request = AckMessageRequestTO()
        request.button_id = ACCEPT_ID
        request.message_key = invitation.key
        request.custom_reply = None
        request.parent_message_key = None
        request.timestamp = now()
        ackMessage(request)
        myFriendMap = get_friends_map(invitor)
        hisFriendMap = get_friends_map(invitee)
        assert myFriendMap.generation == 4
        assert hisFriendMap.generation == 5

        # assert invitee and invitor are friends
        assert invitee in myFriendMap.friends
        assert invitor in hisFriendMap.friends

        assert not myFriendMap.friendDetails[invitee.email()].hasUserData
        assert not hisFriendMap.friendDetails[invitor.email()].hasUserData
 def _create_service_identity(self):
     service_user = users.get_current_user()
     convert_user_to_service(service_user)
     si = get_default_service_identity(service_user)
     return si