def uitdatabank_check_cityapp_settings(): service_user = users.get_current_user() cap = get_cityapp_profile(service_user) sln_settings = get_solution_settings(service_user) try: success, result = get_uitdatabank_events(cap, 1, 50) if not success: try: result = translate(sln_settings.main_language, SOLUTION_COMMON, result) except ValueError: pass except Exception: logging.debug('Failed to check uitdatabank.be settings: %s', dict(key=cap.uitdatabank_key, regions=cap.uitdatabank_regions), exc_info=1) success, result = False, translate(sln_settings.main_language, SOLUTION_COMMON, 'error-occured-unknown-try-again') def trans(): cap = get_cityapp_profile(service_user) if success: cap.uitdatabank_enabled = True cap.put() return RETURNSTATUS_TO_SUCCESS cap.uitdatabank_enabled = False cap.put() return ReturnStatusTO.create(False, result) return db.run_in_transaction(trans)
def solution_group_purchcase_purchase(service_user, email, method, params, tag, service_identity, user_details): service_identity_user = create_service_identity_user_wo_default( service_user, service_identity) jsondata = json.loads(params) group_purchase_id = int(jsondata['groupPurchaseId']) units = int(jsondata['units']) r = SendApiCallCallbackResultTO() sln_settings = get_solution_settings(service_user) try: sgp = new_group_purchase_subscription(service_user, service_identity, group_purchase_id, user_details[0].name, user_details[0], units) r.result = u"Successfully purchased %s units" % units r.error = None message = translate(sln_settings.main_language, SOLUTION_COMMON, 'group-subscription-successful-title', units=units, title=sgp.title) except BusinessException, e: r.result = e.message r.error = None sgp = SolutionGroupPurchase.get_by_id( group_purchase_id, parent_key_unsafe(service_identity_user, sln_settings.solution)) message = translate(sln_settings.main_language, SOLUTION_COMMON, 'group-subscription-failure-title-reason', units=units, title=sgp.title, reason=e.message)
def _send_order_confirmation(service_user, lang, message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details, order_details): if now() - steps[-1].acknowledged_timestamp < 10: alert_flags = Message.ALERT_FLAG_SILENT else: alert_flags = Message.ALERT_FLAG_VIBRATE users.set_user(service_user) try: messaging.send( parent_key=parent_message_key, parent_message_key=parent_message_key, message=u'%s\n\n%s:\n%s' % (translate(lang, SOLUTION_COMMON, u'order_complete_will_notify'), translate(lang, SOLUTION_COMMON, u'usage-detail'), order_details), answers=list(), flags=Message.FLAG_ALLOW_DISMISS | Message.FLAG_AUTO_LOCK, members=[ MemberTO.from_user(user_details[0].toAppUser(), alert_flags) ], branding=get_solution_main_branding(service_user).branding_key, tag=None, service_identity=service_identity, alert_flags=alert_flags, step_id=u'order_complete') finally: users.clear_user()
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 _send_event_notification(sln_settings, service_user, service_identity, user_details, event, event_guest): from solutions.common.bizz.messaging import send_inbox_forwarders_message status = translate(sln_settings.main_language, SOLUTION_COMMON, event_guest.status_str) status_message = translate(sln_settings.main_language, SOLUTION_COMMON, u'events_status_notification', status=status, event=event.title) create_chat = True if event_guest.chat_key: create_chat = SolutionInboxMessage.get(event_guest.chat_key) is None if create_chat: event_key = unicode(event.key()) message = create_solution_inbox_message( service_user, service_identity, SolutionInboxMessage.CATEGORY_AGENDA, event_key, False, user_details, now(), status_message, True) event_guest.chat_key = message.solution_inbox_message_key event_guest.put() app_user = user_details[0].toAppUser() else: message, _ = add_solution_inbox_message(service_user, event_guest.chat_key, False, user_details, now(), status_message) app_user = None send_inbox_forwarders_message( service_user, service_identity, app_user, status_message, { 'if_name': user_details[0].name, 'if_email': user_details[0].email }, message_key=message.solution_inbox_message_key, reply_enabled=message.reply_enabled, send_reminder=False) # show as last message sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) message_to = SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True) send_message(service_user, u'solutions.common.messaging.update', service_identity=service_identity, message=serialize_complex_value(message_to, SolutionInboxMessageTO, False))
def solution_calendar_broadcast(service_user, email, method, params, tag, service_identity, user_details): from solutions.common.bizz.messaging import broadcast_send sln_settings = get_solution_settings(service_user) jsondata = json.loads(params) calendar_id = long(jsondata['calendarId']) message = jsondata['message'] sc = SolutionCalendar.get_by_id( calendar_id, parent_key(service_user, sln_settings.solution)) r = SendApiCallCallbackResultTO() if sc: broadcast_type = translate(sln_settings.main_language, SOLUTION_COMMON, u'calendar-broadcast-type', name=sc.name) broadcast_send(service_user, service_identity, broadcast_type, message, broadcast_on_facebook=False, broadcast_on_twitter=False, broadcast_to_all_locations=True) r.result = u"successfully broadcast" else: r.result = u"Calendar not found. Broadcast failed." r.error = None return r
def combo(): p = solutions.shear(pts, -1.02, .5) p = solutions.translate(p, np.array([-2, .5])) p = solutions.reflect(p, np.array([-2, .5])) fig = plotOldNew(pts, p, "General Affine") fig.savefig("combo.pdf") plt.close(fig.number)
def post(self): max_upload_size_mb = 5 max_upload_size = max_upload_size_mb * 1048576 # 1 MB service_user = get_current_user() sln_settings = get_solution_settings(service_user) name = unicode(self.request.get("name")) logging.info('%s uploads an attachment for broadcasting', service_user.email()) uploaded_file = self.request.POST.get( 'attachment-files') # type: FieldStorage try: if not isinstance(uploaded_file, FieldStorage): raise BusinessException( translate(sln_settings.main_language, SOLUTION_COMMON, 'please_select_attachment')) file_content = uploaded_file.value if len(file_content) > max_upload_size: raise BusinessException( translate(sln_settings.main_language, SOLUTION_COMMON, 'attachment_too_big', max_size=max_upload_size_mb)) content_type = uploaded_file.type if content_type not in AttachmentTO.CONTENT_TYPES: raise BusinessException( translate(sln_settings.main_language, SOLUTION_COMMON, 'attachment_must_be_of_type')) date = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S') filename = '%s/news/%s/%s_%s' % (ROGERTHAT_ATTACHMENTS_BUCKET, service_user.email(), date, uploaded_file.filename) blob_key = upload_to_gcs(file_content, content_type, filename) logging.debug('blob key: %s', blob_key) filename = '/'.join(map(urllib.quote, filename.split('/'))) channel.send_message( service_user, 'solutions.common.broadcast.attachment.upload.success', url=get_serving_url(filename), name=name) except BusinessException as ex: channel.send_message( service_user, 'solutions.common.broadcast.attachment.upload.failed', message=ex.message)
def rest_link_stripe_to_customer(stripe_token, stripe_token_created, contact_id): service_user = users.get_current_user() try: link_stripe_to_customer(service_user.email(), stripe_token, stripe_token_created, contact_id) except NoPermissionException: sln_settings = get_solution_settings(service_user) return translate(sln_settings.main_language, SOLUTION_COMMON, 'no_permission') except BusinessException, exception: return exception.message
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)
def get_solution_order_settings(sln_settings): solution_order_settings_key = SolutionOrderSettings.create_key( sln_settings.service_user) solution_order_settings = SolutionOrderSettings.get( solution_order_settings_key) if not solution_order_settings: solution_order_settings = SolutionOrderSettings( key=solution_order_settings_key) solution_order_settings.text_1 = translate(sln_settings.main_language, SOLUTION_COMMON, 'order-flow-details') solution_order_settings.put() return solution_order_settings
def label(self, language): time_from_dt = datetime.utcfromtimestamp(self.time_from) time_until_dt = datetime.utcfromtimestamp(self.time_until) return translate(language, SOLUTION_COMMON, 'appointment-1-label', day=self.day_str(language), time_from=format_time(time_from_dt, format='short', locale=language), time_until=format_time(time_until_dt, format='short', locale=language))
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 []
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 trans(): service_identity_user = create_service_identity_user_wo_default( service_user, service_identity) sgp = SolutionGroupPurchase.get_by_id( group_purchase_id, parent_key_unsafe(service_identity_user, sln_settings.solution)) units_user = 0 if user_detail: for subscription in sgp.subscriptions_for_user(app_user): units_user += subscription.units if sgp.max_units_pp and units_user >= sgp.max_units_pp: raise BusinessException( translate(sln_settings.main_language, SOLUTION_COMMON, 'new-group-subscription-failure-reached-maximum')) if sgp.max_units_pp and (units_user + units) > sgp.max_units_pp: raise BusinessException( translate(sln_settings.main_language, SOLUTION_COMMON, 'new-group-subscription-failure-exceeded-maximum', max_units=sgp.max_units_pp - units_user)) if (sgp.units_available - units) >= 0: sgpe = SolutionGroupPurchaseSubscription(parent=sgp) sgpe.sender = SolutionUser.fromTO( user_detail) if user_detail else None sgpe.name = name sgpe.units = units sgpe.timestamp = now() sgpe.app_user = app_user sgpe.put() units_user += units else: raise BusinessException( translate(sln_settings.main_language, SOLUTION_COMMON, 'new-group-subscription-failure-insufficient-units')) return sln_settings, sgp, units_user
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)
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
def _provision_without_publish(sln_settings_key): service_user = users.User(sln_settings_key.parent().name()) service_profile = get_service_profile(service_user) if not service_profile or service_profile.solution != SOLUTION_FLEX: return with users.set_user(service_user): default_lang = get_default_language() sln_settings = get_and_complete_solution_settings( service_user, SOLUTION_FLEX) put_avatar_if_needed(service_user) # Force update branding settings branding_settings = SolutionBrandingSettings.get( SolutionBrandingSettings.create_key(service_user)) if not branding_settings: return if branding_settings.color_scheme == u'dark': branding_settings.menu_item_color = SolutionBrandingSettings.default_menu_item_color( u'light') branding_settings.modification_time = now() branding_settings.color_scheme = u'light' branding_settings.background_color = SolutionBrandingSettings.default_background_color( branding_settings.color_scheme) branding_settings.text_color = SolutionBrandingSettings.default_text_color( branding_settings.color_scheme) branding_settings.show_avatar = False branding_settings.put() main_branding = get_and_store_main_branding(service_user) populate_identity(sln_settings, main_branding.branding_key) for i, label in enumerate(['About', 'History', 'Call', 'Recommend']): system.put_reserved_menu_item_label( i, translate(sln_settings.main_language, SOLUTION_COMMON, label)) xg_on = db.create_transaction_options(xg=True) allow_transaction_propagation(db.run_in_transaction_options, xg_on, provision_all_modules, sln_settings, DEFAULT_COORDS, main_branding, default_lang)
def delete_discussion_group(service_user, discussion_group_id): key = SolutionDiscussionGroup.create_key(service_user, discussion_group_id) discussion_group = SolutionDiscussionGroup.get(key) if not discussion_group: raise HttpNotFoundException() if discussion_group.message_key: sln_settings = get_solution_settings(service_user) message = translate(sln_settings.main_language, SOLUTION_COMMON, 'discussion_group_stopped') messaging.send_chat_message(discussion_group.message_key, message) messaging.update_chat(discussion_group.message_key, flags=messaging.ChatFlags.READ_ONLY) def trans(): discussion_group = db.get(key) discussion_group.members.clear() # clears the buckets discussion_group.delete() db.run_in_transaction(trans)
def put_static_content(service_user, static_content): try: if static_content.sc_type == SolutionStaticContent.TYPE_OWN: branding_hash = store_static_content_branding( service_user, static_content.background_color, static_content.text_color, static_content.html_content, static_content.icon_label) elif static_content.sc_type != SolutionStaticContent.TYPE_WEBSITE: raise BusinessException('Invalid static content type') else: branding_hash = None except BrandingValidationException: raise except ServiceApiException: logging.exception('Failed to store static content branding', exc_info=True) raise BusinessException( translate( get_solution_settings(service_user).main_language, SOLUTION_COMMON, 'error-occured-unknown-try-again')) def trans(): sln_settings = get_solution_settings(service_user) new_coords = map(int, [ static_content.position.x, static_content.position.y, static_content.position.z ]) if static_content.id is MISSING or static_content.id is None: sc = SolutionStaticContent(parent=parent_key( service_user, SOLUTION_COMMON), deleted=False) sc.old_coords = new_coords else: sc = SolutionStaticContent.get( SolutionStaticContent.create_key(service_user, static_content.id)) if sc.old_coords != new_coords and sc.provisioned: sc.old_coords = sc.coords sc.icon_label = static_content.icon_label sc.icon_name = static_content.icon_name if static_content.sc_type == SolutionStaticContent.TYPE_OWN: sc.text_color = static_content.text_color sc.background_color = static_content.background_color sc.html_content = static_content.html_content sc.branding_hash = branding_hash elif static_content.sc_type == SolutionStaticContent.TYPE_WEBSITE: sc.website = static_content.website sc.sc_type = static_content.sc_type sc.visible = static_content.visible sc.provisioned = False sc.coords = new_coords sc.put() sln_settings.updates_pending = True put_and_invalidate_cache(sc, sln_settings) 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 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(): 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
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 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 post(self): service_user = users.get_current_user() sln_settings = get_solution_settings(service_user) try: position = self.request.POST.get('position') icon_label = self.request.POST.get('icon_label') icon_name = self.request.POST.get('icon_name') pdf_upload = self.request.POST.get('pdf_upload') static_content_id = self.request.POST.get('static_content_id') if static_content_id: static_content_id = int(static_content_id) visible = self.request.POST.get( 'static_content_visible_pdf') == 'on' coords = map(int, position.split(',')) if not static_content_id and pdf_upload == "": error = translate(sln_settings.main_language, SOLUTION_COMMON, 'PDF is required') self.response.out.write( broadcast_via_iframe_result( u'solutions.common.static_content.pdf.post_result', error=error)) return if pdf_upload == "": branding_hash = None else: if pdf_upload.type != "application/pdf": error = translate(sln_settings.main_language, SOLUTION_COMMON, 'PDF not of correct type.') self.response.out.write( broadcast_via_iframe_result( u'solutions.common.static_content.pdf.post_result', error=error)) return pdf_stream = pdf_upload.file pdf_stream.seek(0) # Test if the file is a valid PDF try: error_stream = StringIO( ) # get rid the of zero index warnings doc = PdfFileReader(pdf_stream, strict=False, warndest=error_stream) logging.debug("Uploaded pdf contains %s pages", doc.numPages) del doc except: error = translate(sln_settings.main_language, SOLUTION_COMMON, 'uploaded-file-not-a-pdf') self.response.out.write( broadcast_via_iframe_result( u'solutions.common.static_content.pdf.post_result', error=error)) return # Test if the file is not too large pdf_stream.seek(0) pdf_bytes = pdf_stream.getvalue() if len(pdf_bytes) > MAX_BRANDING_PDF_SIZE: error = translate(sln_settings.main_language, SOLUTION_COMMON, 'pdf-size-too-large') self.response.out.write( broadcast_via_iframe_result( u'solutions.common.static_content.pdf.post_result', error=error)) return branding_hash = put_pdf_branding( u"Static content pdf: %s" % icon_label, base64.b64encode(pdf_bytes)).id def trans(): if static_content_id: sc = SolutionStaticContent.get( SolutionStaticContent.create_key( service_user, static_content_id)) if not sc: logging.error( u"Failed to update static content with id '%s' for user %s", static_content_id, service_user) return sln_settings if sc.old_coords != coords and sc.provisioned: sc.old_coords = sc.coords else: sc = SolutionStaticContent(parent=parent_key( sln_settings.service_user, SOLUTION_COMMON)) sc.old_coords = coords sc.icon_label = icon_label sc.icon_name = icon_name sc.text_color = None sc.background_color = None sc.html_content = None sc.sc_type = SolutionStaticContent.TYPE_PDF sc.visible = visible sc.coords = coords sc.provisioned = False sc.deleted = False if branding_hash: sc.branding_hash = branding_hash sln_settings.updates_pending = True put_and_invalidate_cache(sc, sln_settings) return sln_settings xg_on = db.create_transaction_options(xg=True) sln_settings = db.run_in_transaction_options(xg_on, trans) send_message(service_user, "solutions.common.service_menu.updated") broadcast_updates_pending(sln_settings) self.response.out.write( broadcast_via_iframe_result( u'solutions.common.static_content.pdf.post_result', success=True)) except: logging.exception( 'Error while trying to save static content PDF for user %s' % sln_settings.service_user.email()) self.response.out.write( broadcast_via_iframe_result( u'solutions.common.static_content.pdf.post_result', error=translate(sln_settings.main_language, SOLUTION_COMMON, 'error-occured-unknown')))
def translate(): fig = plotOldNew(pts, solutions.translate(pts, np.array([2, 0])), "Translate") fig.savefig("translate.pdf") plt.close(fig.number)
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)
def trans(): sln_settings = get_solution_settings(service_user) order_settings = get_solution_order_settings(sln_settings) lang = sln_settings.main_language comment = None phone = None takeaway_time = None if order_type == ORDER_TYPE_SIMPLE: details = get_extended_details_from_tag( _get_value(steps[0], u'message_details')) if steps[1].answer_id == u"positive": picture_url = _get_value(steps[1], u'message_picture') att = AttachmentTO() att.content_type = AttachmentTO.CONTENT_TYPE_IMG_JPG att.download_url = picture_url att.name = translate(lang, SOLUTION_COMMON, u'picture') att.size = 0 attachments = [att] else: picture_url = None attachments = [] phone = _get_value(steps[2], u'message_phone') msg = common_translate(lang, SOLUTION_COMMON, 'if-order-received') % { 'remarks': details, 'phone_number': phone } elif order_type == ORDER_TYPE_ADVANCED: with closing(StringIO()) as order: timezone_offset = datetime.datetime.now( pytz.timezone( sln_settings.timezone)).utcoffset().total_seconds() has_order_items = False for step in steps: if step.step_id == u'message_phone': phone = step.get_value() elif step.step_id == u'message_comment': comment = step.get_value() elif step.step_id == u'message_advanced_order': step_value = step.display_value.encode('utf-8') if step_value: has_order_items = True order.write(step_value) elif step.step_id == u'message_takeaway_time': takeaway_time = int(step.get_value() - timezone_offset) picture_url = None attachments = [] if comment: if has_order_items: order.write('\n\n') c = '%s: %s' % (common_translate( lang, SOLUTION_COMMON, 'reservation-comment'), comment) order.write( c.encode('utf-8') if isinstance(c, unicode) else c) details = get_extended_details_from_tag( order.getvalue().decode('utf-8')) takeaway_datetime = datetime.datetime.fromtimestamp( takeaway_time, tz=get_timezone(sln_settings.timezone)) takeaway_time_str = format_datetime(takeaway_datetime, locale=lang, format='d/M/yyyy H:mm') msg = '%s:\n%s\n%s: %s\n%s: %s' % ( common_translate(lang, SOLUTION_COMMON, 'order_received'), details, common_translate(lang, SOLUTION_COMMON, 'phone_number'), phone, common_translate(lang, SOLUTION_COMMON, 'takeaway_time'), takeaway_time_str) else: raise BusinessException('Unsupported order type %s', order_type) if not order_settings.manual_confirmation: # Waiting for follow-up message deferred.defer(_send_order_confirmation, service_user, lang, message_flow_run_id, member, steps, end_id, end_message_flow_id, parent_message_key, tag, result_key, flush_id, flush_message_flow_id, service_identity, user_details, details, _transactional=db.is_in_transaction()) service_identity_user = create_service_identity_user_wo_default( service_user, service_identity) o = SolutionOrder( parent=parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) o.description = details o.phone_number = phone o.sender = SolutionUser.fromTO(user_details[0]) o.timestamp = now() o.status = SolutionOrder.STATUS_RECEIVED o.picture_url = picture_url o.takeaway_time = takeaway_time o.user = user_details[0].toAppUser() if user_details else None message = create_solution_inbox_message( service_user, service_identity, SolutionInboxMessage.CATEGORY_ORDER, None, False, user_details, steps[2].received_timestamp, msg, True, [picture_url] if picture_url else []) o.solution_inbox_message_key = message.solution_inbox_message_key o.put() message.category_key = unicode(o.key()) message.put() sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) sm_data = [{ u"type": u"solutions.common.orders.update" }, { u"type": u"solutions.common.messaging.update", u"message": serialize_complex_value( SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False) }] send_message(service_user, sm_data, service_identity=service_identity) app_user = user_details[0].toAppUser() send_inbox_forwarders_message( service_user, service_identity, app_user, msg, dict(if_name=user_details[0].name, if_email=user_details[0].email), message_key=message.solution_inbox_message_key, attachments=attachments, reply_enabled=message.reply_enabled)
def _broadcast(sln_settings_key, sandwich_settings_key): sln_settings, sandwich_settings = db.get( [sln_settings_key, sandwich_settings_key]) if not sln_settings: logging.info("Service has been deleted in the meantime") return solution_datetime = datetime.now(pytz.timezone(sln_settings.timezone)) if not sandwich_settings.can_order_sandwiches_on(solution_datetime): logging.info("No email_reminders anymore today for %s", sln_settings.service_user.email()) return broadcast_type = get_sandwich_reminder_broadcast_type( sln_settings.main_language or DEFAULT_LANGUAGE, SandwichSettings.DAYS[solution_datetime.weekday()]) message = sandwich_settings.reminder_broadcast_message order_sandwich_answer = AnswerTO() order_sandwich_answer.action = None order_sandwich_answer.caption = translate(sln_settings.main_language, SOLUTION_COMMON, u'order') order_sandwich_answer.type = u'button' order_sandwich_answer.id = u'order' order_sandwich_answer.ui_flags = 1 no_sandwich_today_answer = AnswerTO() no_sandwich_today_answer.action = None no_sandwich_today_answer.caption = translate( sln_settings.main_language, SOLUTION_COMMON, u'order-sandwiches-not-today') no_sandwich_today_answer.type = u'button' no_sandwich_today_answer.id = u'Not now' no_sandwich_today_answer.ui_flags = 0 answers = list() answers.append(order_sandwich_answer) answers.append(no_sandwich_today_answer) flags = 0 branding = db.get( SolutionMainBranding.create_key( sln_settings.service_user)).branding_key tag = MESSAGE_TAG_SANDWICH_ORDER_NOW alert_flags = 0 timeout = sandwich_settings.get_reminder_broadcast_timeout( solution_datetime) users.set_user(sln_settings.service_user) try: identities = [None] if sln_settings.identities: identities.extend(sln_settings.identities) for service_identity in identities: sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) if sln_i_settings.is_in_holiday_for_date(now()): logging.info( "Not sending out sandwich broadcast '%s'. %s is in holiday.", broadcast_type, sln_i_settings.service_user) else: logging.info( "Sending broadcast to users of %s with broadcast type %s", sln_i_settings.service_user, broadcast_type) messaging.broadcast(broadcast_type, message, answers, flags, branding, tag, service_identity, alert_flags, timeout=timeout) finally: users.clear_user()
def get_exported_filename(language, year, month): name = translate(language, SOLUTION_COMMON, 'Vouchers') return '%s %s-%s.xls' % (name, year, month)
def transl(key): return translate(lang, SOLUTION_COMMON, key)