def get_solution_settings(service_user): """ Args: service_user (users.User) Returns: SolutionSettings """ return SolutionSettings.get(SolutionSettings.create_key(service_user))
def job(): countdown = 0 for old_export in SolutionLoyaltyExport.all(): date_int = old_export.year_month year = date_int / 100 month = date_int % 100 first_day_of_month = int(time.mktime(date(year, month, day=1).timetuple())) first_day_of_next_month = int(time.mktime(get_next_month(year, month).timetuple())) service_user_email = old_export.parent_key().name() sln_settings = SolutionSettings.get(SolutionSettings.create_key(users.User(service_user_email))) deferred.defer(create_loyalty_statistics_for_service, sln_settings, first_day_of_month, first_day_of_next_month, _countdown=countdown) countdown += 15
def load_loyalty_export_list(cursor=None): service_user = users.get_current_user() session_ = users.get_current_session() service_identity = session_.service_identity sln_settings = SolutionSettings.get(SolutionSettings.create_key(service_user)) exports_q = SolutionLoyaltyExport.list_by_service_user(service_user, service_identity) exports_q.with_cursor(cursor) exports_list = exports_q.fetch(10) cursor = unicode(exports_q.cursor()) to = SolutionLoyaltyExportListTO.create(cursor, [SolutionLoyaltyExportTO.from_model(e, sln_settings.main_language) for e in exports_list]) return to
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)
def poke_discussion_groups(service_user, email, tag, result_key, context, service_identity, user_details): from solutions.common.bizz.messaging import POKE_TAG_DISCUSSION_GROUPS result = PokeCallbackResultTO() widget = MultiSelectTO() widget.choices = list() widget.values = list() app_user_email = user_details[0].toAppUser().email() for discussion_group in SolutionDiscussionGroup.list(service_user): widget.choices.append( ChoiceTO(label=discussion_group.topic, value=unicode(discussion_group.id))) if app_user_email in discussion_group.members['members']: widget.values.append(unicode(discussion_group.id)) sln_settings, sln_main_branding = db.get([ SolutionSettings.create_key(service_user), SolutionMainBranding.create_key(service_user) ]) if widget.choices: form = MultiSelectFormTO() form.javascript_validation = None form.negative_button = translate(sln_settings.main_language, SOLUTION_COMMON, u'Cancel') form.negative_button_ui_flags = 0 form.negative_confirmation = None form.positive_button = translate(sln_settings.main_language, SOLUTION_COMMON, u'Save') form.positive_button_ui_flags = Message.UI_FLAG_EXPECT_NEXT_WAIT_5 form.positive_confirmation = None form.type = MultiSelectTO.TYPE form.widget = widget result.type = TYPE_FORM result.value = FormCallbackResultTypeTO() result.value.form = form result.value.message = translate(sln_settings.main_language, SOLUTION_COMMON, u'discussion_group_choices') result.value.tag = POKE_TAG_DISCUSSION_GROUPS else: result.type = TYPE_MESSAGE result.value = MessageCallbackResultTypeTO() result.value.answers = list() result.value.dismiss_button_ui_flags = 0 result.value.message = translate(sln_settings.main_language, SOLUTION_COMMON, u'no_discussion_groups_yet') result.value.tag = None result.value.alert_flags = Message.ALERT_FLAG_SILENT result.value.attachments = list() result.value.branding = sln_main_branding.branding_key result.value.flags = Message.FLAG_AUTO_LOCK | Message.FLAG_ALLOW_DISMISS result.value.step_id = None return result
def trans(): sln_cwl = db.get(sln_cwl_lottery_key) logging.info("city wide lottery loot: %s", sln_cwl.app_id) sln_settings = db.get(SolutionSettings.create_key(service_user)) if SolutionModule.HIDDEN_CITY_WIDE_LOTTERY in sln_settings.modules: now_tz = int( time.mktime( datetime.fromtimestamp( now(), pytz.timezone(sln_settings.timezone)).timetuple())) logging.debug("sln_cwl.end_timestamp: %s", sln_cwl.end_timestamp) logging.debug("end: %s", now_tz) seconds_before = sln_cwl.end_timestamp - now_tz if seconds_before < 0: seconds_before = 0 logging.debug( "_schedule_loot_city_wide_lottery seconds_before: %s", seconds_before) deferred.defer(_pick_city_wide_lottery_winner, service_user, sln_cwl_lottery_key, _countdown=seconds_before, _queue=SCHEDULED_QUEUE, _transactional=True) else: sln_cwl.deleted = True sln_cwl.schedule_loot_time = sln_cwl.schedule_loot_time * -1 sln_cwl.put()
def _re_provision(sln_settings_key): sln_settings = SolutionSettings.get(sln_settings_key) if 'order' in sln_settings.modules and not sln_settings.updates_pending: menu = RestaurantMenu.get( RestaurantMenu.create_key(sln_settings.service_user, sln_settings.solution)) if menu: for category in menu.categories: for item in category.items: if not item.has_price: common_provision(sln_settings.service_user) return
def remind_user_with_expired_vouchers(sln_settings_key, today_timestamp): """Remind voucher owners (users) before the expiration date by n days""" sln_settings = SolutionSettings.get(sln_settings_key) if not sln_settings: return customer = Customer.get_by_service_email(sln_settings.service_user.email()) if not customer: return for days in EXPIRED_VOUCHERS_REMINDER: run_job(expired_vouchers_qry, [customer.app_id, today_timestamp + days], send_expired_voucher_message, [sln_settings, days / DAY])
def _delete_static_content(service_user, static_content_id): sln_settings, sc = db.get( (SolutionSettings.create_key(service_user), SolutionStaticContent.create_key(service_user, static_content_id))) def trans(): sc.provisioned = False sc.deleted = True sln_settings.updates_pending = True db.put([sln_settings, sc]) return sln_settings sln_settings = run_in_transaction(trans, True) send_message(service_user, u"solutions.common.service_menu.updated") broadcast_updates_pending(sln_settings)
def create_voucher_export_pdfs(): def get_last_month(): today = date.today() d = today - relativedelta(months=1) return date(d.year, d.month, 1) first_day_of_last_month = int(time.mktime(get_last_month().timetuple())) first_day_of_current_month = int( time.mktime(date.today().replace(day=1).timetuple())) for sln_settings in SolutionSettings.all().filter( 'modules =', SolutionModule.CITY_VOUCHERS): deferred.defer(create_voucher_statistics_for_city_service, sln_settings.service_user, sln_settings.main_language, first_day_of_last_month, first_day_of_current_month)
def get_menu_item_qr_url(service_user, category_index, item_index): from solutions.common.bizz.messaging import POKE_TAG_MENU_ITEM_IMAGE_UPLOAD from solutions.common.bizz.provisioning import put_menu_item_image_upload_flow menu = get_restaurant_menu(service_user) for category in menu.categories: if category.index == category_index: item = category.items[item_index] if item.qr_url: return item.qr_url qr_templates = qr.list_templates().templates qr_template_id = qr_templates[0].id if qr_templates else None tag = { u'__rt__.tag': POKE_TAG_MENU_ITEM_IMAGE_UPLOAD, u'category_name': category.name, u'item_name': item.name, u'category_id': category.id, u'item_id': item.id } def create_qr(): return qr.create(common_translate( get_solution_settings(service_user).main_language, SOLUTION_COMMON, u'upload_menu_item_image', item_name=item.name), json.dumps(tag), qr_template_id, flow=u'Upload image') try: qr_code = create_qr() except MessageFlowNotFoundException: sln_setting, main_branding = db.get([ SolutionSettings.create_key(service_user), SolutionMainBranding.create_key(service_user) ]) put_menu_item_image_upload_flow(main_branding.branding_key, sln_setting.main_language) qr_code = create_qr() item.qr_url = qr_code.image_uri menu.put() return item.qr_url azzert(False)
def trans(): avatar_key = SolutionAvatar.create_key(service_user) avatar, branding_settings, sln_settings = db.get( (avatar_key, SolutionBrandingSettings.create_key(service_user), SolutionSettings.create_key(service_user))) avatar = avatar or SolutionAvatar(key=avatar_key) avatar.picture = db.Blob(jpg_bytes) avatar.published = False avatar.is_default = False to_put = [avatar, sln_settings] sln_settings.updates_pending = True if branding_settings: branding_settings.modification_time = now() to_put.append(branding_settings) put_and_invalidate_cache(*to_put) return sln_settings
def trans(): branding_settings, sln_settings, loyalty_settings = db.get( (SolutionBrandingSettings.create_key(service_user), SolutionSettings.create_key(service_user), SolutionLoyaltySettings.create_key(service_user))) if not branding_settings: branding_settings = SolutionBrandingSettings( key=SolutionBrandingSettings.create_key(service_user)) branding_settings_to.color_scheme = u'light' branding_settings_to.background_color = SolutionBrandingSettings.default_background_color( branding_settings_to.color_scheme) branding_settings_to.text_color = SolutionBrandingSettings.default_text_color( branding_settings_to.color_scheme) branding_settings.background_color = branding_settings_to.background_color branding_settings.color_scheme = branding_settings_to.color_scheme branding_settings.menu_item_color = branding_settings_to.menu_item_color branding_settings.text_color = branding_settings_to.text_color branding_settings.show_identity_name = branding_settings_to.show_identity_name branding_settings.show_avatar = branding_settings_to.show_avatar branding_settings.modification_time = now() sln_settings.events_branding_hash = None sln_settings.updates_pending = True to_be_put = [branding_settings, sln_settings] if loyalty_settings: loyalty_settings.loyalty_branding_hash = None to_be_put.append(loyalty_settings) sgps = SolutionGroupPurchaseSettings.get( SolutionGroupPurchaseSettings.create_key(service_user, sln_settings.solution)) if sgps: sgps.branding_hash = None to_be_put.append(sgps) put_and_invalidate_cache(*to_be_put) on_trans_committed(broadcast_updates_pending, sln_settings)
def create_loyalty_export_pdfs(): def get_last_month(): today = date.today() d = today - relativedelta(months=1) return date(d.year, d.month, 1) first_day_of_last_month = int(time.mktime(get_last_month().timetuple())) first_day_of_current_month = int( time.mktime(date.today().replace(day=1).timetuple())) countdown = 0 for sln_settings in SolutionSettings.all().filter('modules =', 'loyalty'): identities = [None] if sln_settings.identities: identities.extend(sln_settings.identities) for service_identity in identities: deferred.defer(create_loyalty_statistics_for_service, sln_settings.service_user, service_identity, first_day_of_last_month, first_day_of_current_month, _countdown=countdown) countdown += 2
def trans(): sln_loyalty_lottery = db.get(sln_loyalty_lottery_key) service_user = sln_loyalty_lottery.service_user logging.info("loyalty lottery loot: %s", service_user) sls_key = SolutionLoyaltySettings.create_key(service_user) sln_settings_key = SolutionSettings.create_key(service_user) sln_loyalty_settings, sln_settings = db.get( [sls_key, sln_settings_key]) if SolutionModule.LOYALTY in sln_settings.modules: if sln_loyalty_settings.loyalty_type != SolutionLoyaltySettings.LOYALTY_TYPE_LOTTERY: sln_loyalty_lottery.deleted = True else: now_tz = int( time.mktime( datetime.fromtimestamp( now(), pytz.timezone(sln_settings.timezone)).timetuple())) logging.debug("sln_loyalty_lottery.end_timestamp: %s", sln_loyalty_lottery.end_timestamp) logging.debug("end: %s", now_tz) seconds_before = sln_loyalty_lottery.end_timestamp - now_tz if seconds_before < 0: seconds_before = 0 logging.debug("_schedule_loot_lottery seconds_before: %s", seconds_before) deferred.defer(_pick_winner, service_user, sln_loyalty_lottery_key, _countdown=seconds_before, _queue=SCHEDULED_QUEUE, _transactional=True) else: sln_loyalty_lottery.deleted = True sln_loyalty_lottery.schedule_loot_time = sln_loyalty_lottery.schedule_loot_time * -1 sln_loyalty_lottery.put()
def _publish_events_app_data(sln_settings_key): sln_settings = SolutionSettings.get(sln_settings_key) _publish_app_data(sln_settings)
def _get_solution_settings_keys(): return SolutionSettings.all(keys_only=True)
def _pick_winner(service_user, sln_loyalty_lottery_key): now_ = now() sln_loyalty_lottery = db.get(sln_loyalty_lottery_key) if sln_loyalty_lottery.claimed or sln_loyalty_lottery.redeemed or sln_loyalty_lottery.deleted: return if sln_loyalty_lottery.schedule_loot_time > 0: return service_identity = sln_loyalty_lottery.service_identity service_identity_user = create_service_identity_user_wo_default( service_user, service_identity) sls_key = SolutionLoyaltySettings.create_key(service_user) slls_key = SolutionLoyaltyLotteryStatistics.create_key( service_user, service_identity) sln_settings_key = SolutionSettings.create_key(service_user) sln_loyalty_settings, slls, sln_settings = db.get( [sls_key, slls_key, sln_settings_key]) if sln_loyalty_settings.loyalty_type != SolutionLoyaltySettings.LOYALTY_TYPE_LOTTERY: sln_loyalty_lottery.deleted = True sln_loyalty_lottery.put() return logging.info("loyalty lottery loot: %s", service_user) possible_winners = [] if slls: for i, app_user in enumerate(slls.app_users): if app_user not in sln_loyalty_lottery.skip_winners and app_user != sln_loyalty_lottery.winner: for i in xrange(slls.count[i]): possible_winners.append(app_user) logging.debug("possible winners count: %s", len(possible_winners)) if len(possible_winners) == 0: if sln_loyalty_lottery.winner: logging.debug("can not assign winner, keep old") else: logging.debug("can not assign winner, delete lottery") sln_loyalty_lottery.deleted = True sln_loyalty_lottery.put() return else: winner = random.choice(possible_winners) logging.debug("new winner: %s", winner) slvl = SolutionLoyaltyVisitLottery.all() \ .ancestor(parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) \ .filter('redeemed =', False) \ .filter('app_user ='******'t use get_profile_infos profile_info = get_profile_infos([slvl.app_user], allow_none_in_results=True)[0] if not profile_info or profile_info.isServiceIdentity: azzert(False, "profile_info for app_user %s not found!" % winner) else: user_detail = UserDetailsTO.fromUserProfile(profile_info) loot_datetime_tz = datetime.fromtimestamp( sln_loyalty_lottery.end_timestamp, pytz.timezone(sln_settings.timezone)) loot_date_str = format_datetime(loot_datetime_tz, format='medium', locale=sln_settings.main_language or DEFAULT_LANGUAGE) next_datetime_tz = datetime.fromtimestamp( now() + 24 * 3600, pytz.timezone(sln_settings.timezone)) next_date_str = format_datetime(next_datetime_tz, format='medium', locale=sln_settings.main_language or DEFAULT_LANGUAGE) msg_ok = translate(sln_settings.main_language, SOLUTION_COMMON, 'loyalty-lottery-loot-ok', name=user_detail.name, date_loot=loot_date_str, price=sln_loyalty_lottery.winnings, date=next_date_str) msg_sorry = translate(sln_settings.main_language, SOLUTION_COMMON, 'loyalty-lottery-loot-nok') btn = AnswerTO() btn.id = u'%s' % json.dumps({"key": unicode(sln_loyalty_lottery_key)}) btn.type = u'button' btn.caption = translate(sln_settings.main_language, SOLUTION_COMMON, 'Confirm') btn.action = None btn.ui_flags = 0 message_flags = Message.FLAG_ALLOW_DISMISS sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) def trans(): sm_data = [] if sln_loyalty_lottery.winner_timestamp != 0: logging.debug("loyalty lottery loot: update winner %s", sln_loyalty_lottery.winner) sim_parent, _ = add_solution_inbox_message( service_user, sln_loyalty_lottery.solution_inbox_message_key, True, None, now_, msg_sorry, mark_as_read=True) if sim_parent.message_key_by_tag: message_key_by_tag = json.loads(sim_parent.message_key_by_tag) if message_key_by_tag.get(u"loyalty_lottery_loot", None): deferred.defer(_messaging_seal, service_user, message_key_by_tag[u"loyalty_lottery_loot"], sim_parent.message_key, sim_parent.message_key, 1, _transactional=True) send_inbox_forwarders_message( service_user, service_identity, None, msg_sorry, { 'if_name': user_detail.name, 'if_email': user_detail.email }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled, send_reminder=False) deferred.defer(send_email_to_user_for_loyalty_update, service_user, service_identity, sln_loyalty_lottery.winner, msg_sorry, False) sm_data.append({ u"type": u"solutions.common.messaging.update", u"message": serialize_complex_value( SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False) }) logging.debug("loyalty lottery loot: new winner %s", winner) sim_parent = create_solution_inbox_message( service_user, service_identity, SolutionInboxMessage.CATEGORY_LOYALTY, unicode(sln_loyalty_lottery_key), True, [user_detail], now_, msg_ok, True, mark_as_read=True) sln_loyalty_lottery.solution_inbox_message_key = sim_parent.solution_inbox_message_key if sln_loyalty_lottery.winner: if not sln_loyalty_lottery.skip_winners: sln_loyalty_lottery.skip_winners = [] sln_loyalty_lottery.skip_winners.append(sln_loyalty_lottery.winner) sln_loyalty_lottery.pending = False sln_loyalty_lottery.winner = winner sln_loyalty_lottery.winner_info = SolutionUser.fromTO( user_detail) if user_detail else None sln_loyalty_lottery.winner_timestamp = now_ sln_loyalty_lottery.put() send_inbox_forwarders_message( service_user, service_identity, None, msg_ok, { 'if_name': user_detail.name, 'if_email': user_detail.email }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled, send_reminder=False, answers=[btn], store_tag=u"loyalty_lottery_loot", flags=message_flags) deferred.defer(send_email_to_user_for_loyalty_update, service_user, service_identity, sln_loyalty_lottery.winner, msg_ok, False, sim_parent.solution_inbox_message_key) sm_data.append({ u"type": u"solutions.common.messaging.update", u"message": serialize_complex_value( SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False) }) sm_data.append({u"type": u"solutions.common.loyalty.lottery.update"}) send_message(service_user, sm_data, service_identity=service_identity) deferred.defer(_continue, service_user, service_identity, sln_loyalty_lottery_key, _transactional=True) xg_on = db.create_transaction_options(xg=True) db.run_in_transaction_options(xg_on, trans)
def _get_order_solution_settings(): return SolutionSettings.all().filter("modules =", SolutionModule.ORDER)
def _get_agenda_solution_settings(): return SolutionSettings.all().filter("modules =", SolutionModule.AGENDA)
def _re_provision(sln_settings_key): sln_settings = SolutionSettings.get(sln_settings_key) if sln_settings.updates_pending == False: logging.info('Provisioning %s', sln_settings.name) allow_transaction_propagation(run_in_xg_transaction, common_provision, sln_settings.service_user, sln_settings)
def get_all_solution_settings_keys(module): return SolutionSettings.all(keys_only=True).filter('modules', module)
def _qry(): return SolutionSettings.all(keys_only=True).filter( "modules =", SolutionModule.SANDWICH_BAR)
def create_solution_service(email, name, branding_url=None, menu_item_color=None, address=None, phone_number=None, solution=None, languages=None, currency=u"€", category_id=None, organization_type=1, fail_if_exists=True, modules=None, broadcast_types=None, apps=None, owner_user_email=None, search_enabled=False): password = unicode(generate_random_key()[:8]) if languages is None: languages = [DEFAULT_LANGUAGE] if menu_item_color == "branding": menu_item_color = None elif menu_item_color: try: parse_color(menu_item_color) except ValueError: raise InvalidMenuItemColorException() if branding_url: # Already download branding to validate url resp = urlfetch.fetch(branding_url, deadline=60) if resp.status_code != 200: raise BrandingNotFoundException() if not is_branding(resp.content, Branding.TYPE_NORMAL): raise BrandingValidationException( "Content of branding download could not be identified as a branding" ) # Raises if service already existed # If a solution is provided, bypass the service creator validation by calling create_service directly. if not solution: solution = validate_and_get_solution(users.get_current_user()) create_service(email, name, password, languages, solution, category_id, organization_type, fail_if_exists, supported_app_ids=apps, owner_user_email=owner_user_email) new_service_user = users.User(email) to_be_put = list() settings = get_solution_settings(new_service_user) if not settings: settings = SolutionSettings( key=SolutionSettings.create_key(new_service_user), name=name, menu_item_color=menu_item_color, address=address, phone_number=phone_number, currency=currency, main_language=languages[0], solution=solution, search_enabled=search_enabled, modules=modules or list(), broadcast_types=broadcast_types or list()) if owner_user_email: settings.qualified_identifier = owner_user_email if settings.uses_inbox(): settings.inbox_email_reminders_enabled = True settings.inbox_mail_forwarders.append( settings.qualified_identifier) settings.login = users.User( owner_user_email) if owner_user_email else None settings.holidays = [] settings.holiday_out_of_office_message = common_translate( settings.main_language, SOLUTION_COMMON, 'holiday-out-of-office') to_be_put.append(settings) main_branding = SolutionMainBranding( key=SolutionMainBranding.create_key(new_service_user)) to_be_put.append(main_branding) main_branding.branding_key = None if branding_url: main_branding.blob = db.Blob(resp.content) else: # Branding will be generated during provisioning bs = _get_default_branding_settings(new_service_user) with open( os.path.join(os.path.dirname(__file__), '..', 'templates', 'main_branding', 'logo.jpg'), 'r') as f: sl = SolutionLogo(key=SolutionLogo.create_key(new_service_user), picture=db.Blob(f.read()), is_default=True) to_be_put.extend([bs, sl]) put_and_invalidate_cache(*to_be_put) if solution == SOLUTION_FLEX: deferred.defer(service_auto_connect, new_service_user, _transactional=db.is_in_transaction()) return password, settings
def _all_solution_settings(): return SolutionSettings.all(keys_only=True)
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
def test_create_restaurant_identity(self): self.set_datastore_hr_probability(1) root_proj = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..', '..') branding_url = os.path.join(root_proj, 'rogerthat-backend', 'src-test', 'rogerthat_tests', 'mobicage', 'bizz', 'nuntiuz.zip') email = u"*****@*****.**" name = u"resto_soluton" service_user = users.User(email) create_service(email=email, name=name, password=u"test1", languages=[u"en"], solution=SOLUTION_FLEX, category_id=None, organization_type=ServiceProfile.ORGANIZATION_TYPE_PROFIT, fail_if_exists=False) solutionSettings = SolutionSettings(key=SolutionSettings.create_key(service_user), name=name, menu_item_color=None, address=u"lochristi", phone_number=None, currency=u"€", main_language=DEFAULT_LANGUAGE, solution=SOLUTION_FLEX) solutionSettings.holidays = [] solutionSettings.holiday_out_of_office_message = u'holiday-out-of-office' settings = RestaurantSettings(key=RestaurantSettings.create_key(service_user)) settings.language = DEFAULT_LANGUAGE stream = StringIO() stream.write(open(branding_url).read()) stream.seek(0) main_branding = SolutionMainBranding(key=SolutionMainBranding.create_key(service_user)) main_branding.blob = db.Blob(stream.read()) main_branding.branding_key = None settings.shifts = Shifts() shift = Shift() shift.name = u'shift-lunch' shift.capacity = 50 shift.max_group_size = 6 shift.leap_time = 30 shift.threshold = 70 shift.start = 12 * 60 * 60 shift.end = 14 * 60 * 60 shift.days = [1, 2, 3, 4, 5, 6, 7] shift.comment = u'shift-comment0' settings.shifts.add(shift) shift = Shift() shift.name = u'shift-dinner' shift.capacity = 50 shift.max_group_size = 6 shift.leap_time = 30 shift.threshold = 70 shift.start = 18 * 60 * 60 shift.end = 21 * 60 * 60 shift.days = [1, 2, 3, 4, 5, 6, 7] shift.comment = u'shift-comment1' settings.shifts.add(shift) put_and_invalidate_cache(solutionSettings, settings, main_branding) date_ = datetime.datetime.combine(datetime.date.today() + datetime.timedelta(days=10), datetime.datetime.min.time()) date_ = date_ + datetime.timedelta(hours=19) today_ = get_epoch_from_datetime(date_) service_identity = None user_detail = UserDetailsTO.fromUserProfile(get_user_profile(users.get_current_user())) reservationOkKey, reservationOk = \ self._test_reserve_table(service_user, service_identity, user_details=[user_detail], date=today_, people=3, name=u"text Name", phone=None, comment=u"comment", force=False) reservationTooMany = self._test_reserve_table(service_user, service_identity, user_details=[user_detail], date=today_, people=50, name=u"text Name", phone=None, comment=u"comment", force=False) self.assertEqual(STATUS_AVAILABLE, reservationOk) self.assertEqual(STATUS_TOO_MANY_PEOPLE, reservationTooMany) editReservationOk = edit_reservation(service_user, reservationOkKey, people=4, comment=None, force=False) self.assertEqual(STATUS_AVAILABLE, editReservationOk) cancel_reservation(service_user, reservationOkKey, notified=False) move_reservation(service_user, None, reservationOkKey, u'shift-lunch')
def follow_discussion_groups(service_user, status, form_result, answer_id, member, message_key, tag, received_timestamp, acked_timestamp, parent_message_key, result_key, service_identity, user_details): if answer_id != FormTO.POSITIVE or form_result in ( None, MISSING) or form_result.result in (None, MISSING): return None app_user = user_details[0].toAppUser() app_user_email = app_user.email() selected_ids = map(long, form_result.result.values) def rm_from_chat(parent_message_key): messaging.delete_chat_members(parent_message_key, [MemberTO.from_user(app_user)]) def add_to_chat(parent_message_key): messaging.add_chat_members(parent_message_key, [MemberTO.from_user(app_user)]) def trans(): followed_new_group = False to_put = list() for discussion_group in SolutionDiscussionGroup.list(service_user): kv_store_dict = discussion_group.members.to_json_dict() was_following = app_user_email in kv_store_dict['members'] now_following = discussion_group.id in selected_ids if was_following != now_following: if now_following: followed_new_group = True logging.debug('Adding %s to discussion group "%s"', app_user_email, discussion_group.topic) kv_store_dict['members'].append(app_user_email) on_trans_committed(add_to_chat, discussion_group.message_key) else: logging.debug('Removing %s from discussion group "%s"', app_user_email, discussion_group.topic) kv_store_dict['members'].remove(app_user_email) on_trans_committed(rm_from_chat, discussion_group.message_key) to_put.append(discussion_group) # We need to set members again to force the KVStore to be put discussion_group.members.from_json_dict(kv_store_dict) if to_put: put_and_invalidate_cache(*to_put) return followed_new_group followed_new_group = run_in_xg_transaction(trans) sln_settings, sln_main_branding = db.get([ SolutionSettings.create_key(service_user), SolutionMainBranding.create_key(service_user) ]) result = FormAcknowledgedCallbackResultTO() result.type = TYPE_MESSAGE result.value = MessageCallbackResultTypeTO() result.value.alert_flags = Message.ALERT_FLAG_VIBRATE result.value.answers = list() result.value.attachments = list() result.value.branding = sln_main_branding.branding_key result.value.dismiss_button_ui_flags = 0 result.value.flags = Message.FLAG_AUTO_LOCK | Message.FLAG_ALLOW_DISMISS result.value.message = translate(sln_settings.main_language, SOLUTION_COMMON, u'Your changes have been saved.') if followed_new_group: result.value.message += u'\n\n%s' % translate( sln_settings.main_language, SOLUTION_COMMON, u'you_can_find_discussion_groups_on_homescreen') result.value.step_id = None result.value.tag = None return result
def _process_cityapp_uitdatabank_events(cap_key, page): try: uitdatabank_actors = defaultdict(list) for sln_settings in SolutionSettings.all().filter( "uitdatabank_actor_id !=", None): uitdatabank_actors[sln_settings.uitdatabank_actor_id].append( sln_settings) pagelength = 50 cap = CityAppProfile.get(cap_key) if page == 1: run_time = now() services_to_update = set() else: run_time = cap.run_time services_to_update = set(cap.services_to_update) logging.info("process_cityapp_uitdatabank_events for %s page %s", cap.service_user, page) success, result = get_uitdatabank_events( cap, page, pagelength, cap.uitdatabank_last_query or None) if not success: logging.exception(result, _suppress=False) return sln_settings = get_solution_settings(cap.service_user) to_put = list() should_update_service = page != 1 result_count = 0 updated_events_count = 0 for r in result: result_count += 1 updated_events = _populate_uit_events( sln_settings, cap.uitdatabank_secret, cap.uitdatabank_key, r['cdbid'], uitdatabank_actors, cap.uitdatabank_last_query or None) if updated_events: services_to_update.update( (event.service_user for event in updated_events)) updated_events_count += 1 should_update_service = True to_put.extend(updated_events) def trans_update_cap(): cap = db.get(cap_key) cap.run_time = run_time cap.services_to_update = list(services_to_update) cap.put() return cap cap = db.run_in_transaction(trans_update_cap) logging.debug("Added/updated %s/%s events", updated_events_count, result_count) if to_put: put_and_invalidate_cache(*to_put) if result_count != 0: deferred.defer(_process_cityapp_uitdatabank_events, cap_key, page + 1) else: def trans_set_last_query(): cap = db.get(cap_key) cap.uitdatabank_last_query = cap.run_time cap.put() return cap cap = db.run_in_transaction(trans_set_last_query) if should_update_service: for service_user in cap.services_to_update: if service_user != sln_settings.service_user: settings_to_put = get_solution_settings(service_user) else: settings_to_put = sln_settings settings_to_put.put_identity_pending = True settings_to_put.put() except Exception, e: logging.exception(str(e), _suppress=False)
def _qry(): return SolutionSettings.all().filter('modules =', 'loyalty')