def send_message_for_pharmacy_order(service_user, order_key, order_status, message): from solutions.common.bizz.messaging import send_inbox_forwarders_message azzert(order_status in SolutionPharmacyOrder.ORDER_STATUSES) def txn(): m = SolutionPharmacyOrder.get(order_key) azzert(service_user == m.service_user) if m.status == SolutionPharmacyOrder.STATUS_RECEIVED and m.status != order_status: m.status = order_status m.put() return m order = db.run_in_transaction(txn) sm_data = [] sm_data.append({u"type": u"solutions.common.pharmacy_orders.update"}) sln_settings = get_solution_settings(service_user) if message: if order.solution_inbox_message_key: sim_parent, _ = add_solution_inbox_message( service_user, order.solution_inbox_message_key, True, None, now(), message, mark_as_unread=False, mark_as_read=True) send_inbox_forwarders_message(service_user, sim_parent.service_identity, None, message, { 'if_name': sim_parent.sender.name, 'if_email': sim_parent.sender.email }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, order.service_identity) 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)}) else: sln_main_branding = get_solution_main_branding(service_user) branding = sln_main_branding.branding_key if sln_main_branding else None member = MemberTO() member.alert_flags = Message.ALERT_FLAG_VIBRATE member.member = order.sender.email member.app_id = order.sender.app_id messaging.send(parent_key=None, parent_message_key=None, message=message, answers=[], flags=Message.FLAG_ALLOW_DISMISS, members=[member], branding=branding, tag=None, service_identity=order.service_identity) elif order.solution_inbox_message_key: sim_parent = SolutionInboxMessage.get(order.solution_inbox_message_key) if not sim_parent.read: sim_parent.read = True sim_parent.put() deferred.defer(update_user_data_admins, service_user, order.service_identity) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, order.service_identity) 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)}) send_message(service_user, sm_data, service_identity=order.service_identity)
def delete_sandwich_order(service_user, service_identity, sandwich_id, message): from solutions.common.bizz.messaging import send_inbox_forwarders_message sln_settings = get_solution_settings(service_user) def txn(): m = SandwichOrder.get_by_order_id(service_user, service_identity, sln_settings.solution, sandwich_id) azzert(service_user == m.service_user) m.deleted = True m.put() return m xg_on = db.create_transaction_options(xg=True) sandwich_order = db.run_in_transaction_options(xg_on, txn) sm_data = [{u"type": u"solutions.common.sandwich.orders.deleted", u'sandwich_id': sandwich_id}] if message: if sandwich_order.solution_inbox_message_key: sim_parent, _ = add_solution_inbox_message(service_user, sandwich_order.solution_inbox_message_key, True, None, now(), message, mark_as_unread=False, mark_as_read=True, mark_as_trashed=True) send_inbox_forwarders_message(service_user, sim_parent.service_identity, None, message, { 'if_name': sim_parent.sender.name, 'if_email':sim_parent.sender.email }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, sandwich_order.service_identity) 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)}) else: branding = get_solution_main_branding(service_user).branding_key member = MemberTO() member.alert_flags = Message.ALERT_FLAG_VIBRATE member.member = sandwich_order.sender.email member.app_id = sandwich_order.sender.app_id messaging.send(parent_key=None, parent_message_key=None, message=message, answers=[], flags=Message.FLAG_ALLOW_DISMISS, members=[member], branding=branding, tag=None, service_identity=sandwich_order.service_identity) elif sandwich_order.solution_inbox_message_key: sim_parent = SolutionInboxMessage.get(sandwich_order.solution_inbox_message_key) if not sim_parent.trashed and not sim_parent.deleted: sim_parent.trashed = True sim_parent.put() deferred.defer(update_user_data_admins, service_user, sandwich_order.service_identity) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, sandwich_order.service_identity) 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)}) send_message(service_user, sm_data, service_identity=sandwich_order.service_identity)
def common_new_chat_message(parent_message_key, message_key, sender, message, answers, timestamp, tag, service_identity, attachments): if tag and tag.startswith(POKE_TAG_INBOX_FORWARDING_REPLY): info = json.loads(tag[len(POKE_TAG_INBOX_FORWARDING_REPLY):]) message_key = info['message_key'] sim_parent = SolutionInboxMessage.get(reconstruct_key(db.Key(message_key))) if sim_parent.awaiting_first_message: sim_parent.awaiting_first_message = False sim_parent.put() else: service_user = sim_parent.service_user sln_settings = get_solution_settings(service_user) sent_by_service = True if sim_parent.sender.email == sender.email and sim_parent.sender.app_id == sender.app_id: sent_by_service = False picture_attachments = [] video_attachments = [] for a in attachments: if a.content_type.startswith("image"): picture_attachments.append(a.download_url) if a.content_type.startswith("video"): video_attachments.append(a.download_url) if sent_by_service: sim_parent, _ = add_solution_inbox_message(service_user, message_key, sent_by_service, [sender], timestamp, message, picture_attachments, video_attachments, mark_as_unread=False, mark_as_read=True) else: sim_parent, _ = add_solution_inbox_message(service_user, message_key, sent_by_service, [sender], timestamp, message, picture_attachments, video_attachments) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity) send_message(service_user, u"solutions.common.messaging.update", service_identity=service_identity, message=serialize_complex_value(SolutionInboxMessageTO.fromModel(sim_parent, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)) member_sender_user = create_app_user_by_email(sim_parent.sender.email, sim_parent.sender.app_id) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity) members = [MemberTO.from_user(users.User(f)) for f in sln_i_settings.inbox_forwarders] if member_sender_user.email() not in sln_i_settings.inbox_forwarders: members.append(MemberTO.from_user(member_sender_user)) users.set_user(service_user) try: messaging.add_chat_members(sim_parent.message_key, members) finally: users.clear_user() else: raise NotImplementedError()
def try_to_set_location(settings_key): to_put = set() def set_location(settings): if settings.address and not settings.location: lines = settings.address.splitlines() if lines[0] == lines[1]: settings.address = '\n'.join(lines[1:]) to_put.add(settings) try: lat, lon = _get_location(settings.address) settings.location = db.GeoPt(lat, lon) to_put.add(settings) except: logging.warning("Failed to resolve address of %s: %s", settings.service_user.email(), settings.address, exc_info=1) sln_settings = db.get(settings_key) if sln_settings: if sln_settings.identities: for identity in sln_settings.identities: identity_settings = get_solution_settings_or_identity_settings( sln_settings, identity) set_location(identity_settings) else: set_location(sln_settings) if to_put: put_and_invalidate_cache(*to_put) service_user = sln_settings.service_user main_branding_key = get_solution_main_branding( service_user).branding_key populate_identity_and_publish(service_user, main_branding_key)
def trans(): sln_settings = get_solution_settings(service_user) sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) sln_i_settings.holiday_out_of_office_message = db.Text(message) sln_settings.updates_pending = True put_and_invalidate_cache(sln_settings, sln_i_settings) return sln_settings
def _repair_order_received(service_user, 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): from solutions.common.bizz.messaging import send_inbox_forwarders_message logging.info("_flow_member_result_repair_order: \n %s" % steps) remarks = _get_value(steps[0], u'message_remarks') if steps[1].answer_id == u"positive": picture_url = _get_value(steps[1], u'message_picture') else: picture_url = None sln_settings = get_solution_settings(service_user) logging.info("Saving repair order from %s" % user_details[0].email) service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) o = SolutionRepairOrder(parent=parent_key_unsafe(service_identity_user, sln_settings.solution)) o.description = remarks o.sender = SolutionUser.fromTO(user_details[0]) o.timestamp = steps[1].received_timestamp o.status = SolutionRepairOrder.STATUS_RECEIVED o.picture_url = picture_url o.user = user_details[0].toAppUser() if user_details else None msg = common_translate(sln_settings.main_language, SOLUTION_COMMON, 'if-repair-order-received', remarks=remarks) message = create_solution_inbox_message(service_user, service_identity, SolutionInboxMessage.CATEGORY_REPAIR, None, False, user_details, steps[1].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 = [] sm_data.append({u"type": u"solutions.common.repair_orders.update"}) sm_data.append({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) attachments = [] if picture_url: att = AttachmentTO() att.content_type = AttachmentTO.CONTENT_TYPE_IMG_JPG att.download_url = picture_url att.name = common_translate(sln_settings.main_language, SOLUTION_COMMON, u'picture') att.size = 0 attachments = [att] app_user = user_details[0].toAppUser() send_inbox_forwarders_message(service_user, service_identity, app_user, msg, { '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 _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 send_inbox_message_update(sln_settings, message, service_identity=None): service_user = sln_settings.service_user sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) message_to = SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True) data = serialize_complex_value(message_to, SolutionInboxMessageTO, False) channel.send_message(service_user, u'solutions.common.messaging.update', message=data, service_identity=service_identity)
def trans(): sln_settings = get_solution_settings(service_user) sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) for i in range(len(sln_i_settings.holidays) / 2): if sln_i_settings.holidays[2 * i] == holiday.start: del sln_i_settings.holidays[2 * i:2 * i + 2] break else: raise InvalidHolidayException('holiday-not-found') sln_settings.updates_pending = True put_and_invalidate_cache(sln_settings, sln_i_settings) return sln_settings
def trans(): sln_settings = get_solution_settings(service_user) sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) i = 0 while i < len(sln_i_settings.holidays) / 2: if holiday.start < sln_i_settings.holidays[2 * i]: break i += 1 sln_i_settings.holidays.insert(2 * i, holiday.start) sln_i_settings.holidays.insert(2 * i + 1, holiday.end) sln_settings.updates_pending = True put_and_invalidate_cache(sln_settings, sln_i_settings) return sln_settings
def bulk_invite_result(service_user, service_identity, tag, email, result, user_details): if not tag: logging.exception("Expected tag in bulk_invite_result") return if tag in (SERVICE_AUTOCONNECT_INVITE_TAG, APP_BROADCAST_TAG): return try: key = db.Key(tag) except db.BadKeyError: logging.info('Tag is no db.Key: %s. Ignoring...', tag) return def trans(): invite = db.get(reconstruct_key(key)) if not invite: logging.error("Invite object not found in datastore") return save_message = False if "accepted" == result: invite.status = RestaurantInvite.STATUS_ACCEPTED save_message = True else: invite.status = RestaurantInvite.STATUS_REJECTED invite.put() return save_message save_message = run_in_xg_transaction(trans) if save_message: now_ = now() sln_settings = get_solution_settings(service_user) msg = common_translate(sln_settings.main_language, SOLUTION_COMMON, 'if-accepted-invitation', if_name=user_details[0].name, if_email=user_details[0].email) message = create_solution_inbox_message( service_user, service_identity, SolutionInboxMessage.CATEGORY_BULK_INVITE, None, False, user_details, now_, msg, False) app_user = create_app_user_by_email(user_details[0].email, user_details[0].app_id) send_inbox_forwarders_message(service_user, service_identity, app_user, msg, { '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) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity) send_message(service_user, u"solutions.common.messaging.update", service_identity=service_identity, message=serialize_complex_value(SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False))
def send_signup_update_messages(sln_settings, *messages): service_identity = ServiceIdentity.DEFAULT sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) sm_data = [{u'type': u'solutions.common.customer.signup.update'}] for message in messages: message_to = SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True) sm_data.append({ u'type': u'solutions.common.messaging.update', u'message': serialize_complex_value(message_to, SolutionInboxMessageTO, False) }) channel.send_message(sln_settings.service_user, sm_data, service_identity=service_identity)
def reply_sandwich_order(service_user, service_identity, sandwich_id, message=unicode): from solutions.common.bizz.messaging import send_inbox_forwarders_message sln_settings = get_solution_settings(service_user) sandwich_order = SandwichOrder.get_by_order_id(service_user, service_identity, sln_settings.solution, sandwich_id) azzert(service_user == sandwich_order.service_user) sandwich_order.status = SandwichOrder.STATUS_REPLIED sandwich_order.put() sm_data = [] sm_data.append({u"type": u"solutions.common.sandwich.orders.update"}) if sandwich_order.solution_inbox_message_key: sim_parent, _ = add_solution_inbox_message(service_user, sandwich_order.solution_inbox_message_key, True, None, now(), message, mark_as_unread=False, mark_as_read=True) send_inbox_forwarders_message(service_user, sim_parent.service_identity, None, message, { 'if_name': sim_parent.sender.name, 'if_email':sim_parent.sender.email }, message_key=sim_parent.solution_inbox_message_key, reply_enabled=sim_parent.reply_enabled) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, sandwich_order.service_identity) 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)}) else: sln_main_branding = get_solution_main_branding(service_user) branding = sln_main_branding.branding_key if sln_main_branding else None member = MemberTO() member.alert_flags = Message.ALERT_FLAG_VIBRATE member.member = sandwich_order.sender.email member.app_id = sandwich_order.sender.app_id messaging.send(parent_key=None, parent_message_key=None, message=message, answers=[], flags=Message.FLAG_ALLOW_DISMISS, members=[member], branding=branding, tag=None, service_identity=sandwich_order.service_identity) send_message(service_user, sm_data, service_identity=sandwich_order.service_identity)
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 process_sandwich_order(service_user, service_identity, user_details, type_, topping, customizations, remark, takeaway_time, parent_message_key): from solutions.common.bizz.messaging import send_inbox_forwarders_message # Calculate price type_id = int(type_.split('_')[-1]) topping_id = int(topping.split('_')[-1]) if topping else None option_ids = [int(c.split('_')[-1]) for c in customizations] if customizations else [] logging.info("type: %s", type_id) logging.info("topping: %s", topping_id) logging.info("options: %s", option_ids) sandwich_type = SandwichType.get_by_type_id(service_user, SOLUTION_FLEX, type_id) sandwich_topping = SandwichTopping.get_by_topping_id(service_user, SOLUTION_FLEX, topping_id) if topping_id else None sandwich_customizations = SandwichOption.get_by_option_ids(service_user, SOLUTION_FLEX, option_ids) logging.info("type: %s", sandwich_type) logging.info("topping: %s", sandwich_topping) logging.info("options: %s", sandwich_customizations) total_price = sum([sandwich_type.price, sandwich_topping.price if sandwich_topping else 0] + [sc.price for sc in sandwich_customizations]) # Save order to datastore now_ = now() sln_settings = get_solution_settings(service_user) timezone_offset = datetime.now(pytz.timezone(sln_settings.timezone)).utcoffset().total_seconds() lang = sln_settings.main_language customizations = [''] customizations.extend([sw.description for sw in sandwich_customizations]) msg = common_translate(lang, SOLUTION_COMMON, 'if-sandwich-order-received', sandwich_type=sandwich_type.description, topping=sandwich_topping.description if sandwich_topping else u"", customizations=u"\n - ".join(customizations), remarks=remark or "") if takeaway_time: takeaway_time = long(takeaway_time - timezone_offset) takeaway_time_str = format_datetime( datetime.fromtimestamp(takeaway_time, tz=get_timezone(sln_settings.timezone)), format='short', locale=lang) msg = '%s\n%s: %s' % (msg, common_translate(lang, SOLUTION_COMMON, 'takeaway_time'), takeaway_time_str) create_inbox_message = True service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) order = SandwichOrder.get_or_insert(key_name=parent_message_key, parent=parent_key_unsafe(service_identity_user, SOLUTION_FLEX)) if order.solution_inbox_message_key: create_inbox_message = False order.sender = SolutionUser.fromTO(user_details[0]) order.order_time = now_ order.price = total_price order.type_id = type_id order.topping_id = topping_id order.option_ids = option_ids order.remark = remark order.status = SandwichOrder.STATUS_RECEIVED order.takeaway_time = takeaway_time sm_data = [{u"type": u"solutions.common.sandwich.orders.update"}] if create_inbox_message: message = create_solution_inbox_message(service_user, service_identity, SolutionInboxMessage.CATEGORY_SANDWICH_BAR, None, False, user_details, now_, msg, True) order.solution_inbox_message_key = message.solution_inbox_message_key order.put() message.category_key = unicode(order.key()) message.put() sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity) sm_data.append({u"type": u"solutions.common.messaging.update", u"message": serialize_complex_value(SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)}) app_user = create_app_user_by_email(user_details[0].email, user_details[0].app_id) send_inbox_forwarders_message(service_user, service_identity, app_user, msg, { '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_message(service_user, sm_data, service_identity=service_identity) if SolutionModule.LOYALTY in sln_settings.modules: deferred.defer(update_user_data_admins, service_user, service_identity)
def appointment_asked(service_user, 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): from solutions.common.bizz.messaging import _get_step_with_id, send_inbox_forwarders_message logging.info("_flow_member_result_appointment: \n %s" % steps) day = _get_step_with_id(steps, 'message_day') if not day: logging.error("Did not find step with id 'day'. Can not process message_flow_member_result with tag %s" % tag) return None phone = _get_step_with_id(steps, 'message_phone') if not phone: logging.error("Did not find step with id 'phone'. Can not process message_flow_member_result with tag %s" % tag) return None reason = _get_step_with_id(steps, 'message_reason') if not reason: logging.error("Did not find step with id 'reason'. Can not process message_flow_member_result with tag %s" % tag) return None logging.info("Saving appointment from %s" % user_details[0].email) sln_settings = get_solution_settings(service_user) days_str = [] language = sln_settings.main_language or DEFAULT_LANGUAGE for timeframe_id in day.form_result.result.values: sawt = SolutionAppointmentWeekdayTimeframe.get_by_id(int(timeframe_id), parent_key(service_user, sln_settings.solution)) if sawt: days_str.append(sawt.label(language)) msg_appointment = """%s: %s %s: %s %s: %s""" % (common_translate(language, SOLUTION_COMMON , 'days'), "\n".join(days_str), common_translate(language, SOLUTION_COMMON , 'phone'), phone.form_result.result.value, common_translate(language, SOLUTION_COMMON , 'reason'), reason.form_result.result.value) msg = common_translate(language, SOLUTION_COMMON, 'if-appointment-received', appointment=msg_appointment) message = create_solution_inbox_message(service_user, service_identity, SolutionInboxMessage.CATEGORY_APPOINTMENT, None, False, user_details, reason.acknowledged_timestamp, msg, True) app_user = create_app_user_by_email(user_details[0].email, user_details[0].app_id) send_inbox_forwarders_message(service_user, service_identity, app_user, msg, { 'if_name': user_details[0].name, 'if_email':user_details[0].email }, message_key=message.solution_inbox_message_key, reply_enabled=message.reply_enabled) sln_i_settings = get_solution_settings_or_identity_settings(sln_settings, service_identity) send_message(service_user, u"solutions.common.messaging.update", service_identity=service_identity, message=serialize_complex_value(SolutionInboxMessageTO.fromModel(message, sln_settings, sln_i_settings, True), SolutionInboxMessageTO, False)) return None
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 save_settings(service_user, service_identity, name, description=None, opening_hours=None, address=None, phone_number=None, facebook_page=None, facebook_name=None, facebook_action=None, currency=None, search_enabled=True, search_keywords=None, timezone=None, events_visible=None, email_address=None, inbox_email_reminders=None, iban=None, bic=None, search_enabled_check=False): address_geocoded = True sln_settings = get_solution_settings(service_user) sln_i_settings = get_solution_settings_or_identity_settings( sln_settings, service_identity) sln_i_settings.name = name sln_i_settings.description = description sln_i_settings.opening_hours = opening_hours sln_i_settings.phone_number = phone_number if email_address and email_address != service_user.email(): sln_i_settings.qualified_identifier = email_address else: sln_i_settings.qualified_identifier = None if facebook_page is not None: if sln_settings.facebook_page != facebook_page: send_message(service_user, u"solutions.common.settings.facebookPageChanged", facebook_page=facebook_page) sln_settings.facebook_page = facebook_page sln_settings.facebook_name = facebook_name if facebook_page else "" sln_settings.facebook_action = facebook_action if currency is not None: sln_settings.currency = currency sln_settings.search_enabled = search_enabled sln_settings.search_enabled_check = search_enabled_check sln_i_settings.search_keywords = search_keywords if address and (sln_i_settings.address != address or not sln_i_settings.location): sln_i_settings.address = address try: lat, lon = _get_location(address) sln_i_settings.location = db.GeoPt(lat, lon) except: address_geocoded = False logging.warning("Failed to resolve address: %s" % sln_i_settings.address, exc_info=1) if timezone is not None: if sln_settings.timezone != timezone: send_message(service_user, u"solutions.common.settings.timezoneChanged") sln_settings.timezone = timezone if events_visible is not None: sln_settings.events_visible = events_visible if inbox_email_reminders is not None: sln_i_settings.inbox_email_reminders_enabled = inbox_email_reminders sln_settings.iban = iban sln_settings.bic = bic sln_settings.updates_pending = True if not is_default_service_identity(service_identity): sln_i_settings.put() sln_settings.put() broadcast_updates_pending(sln_settings) return address_geocoded
def pharmacy_order_received(service_user, 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): from solutions.common.bizz.messaging import send_inbox_forwarders_message sln_settings = get_solution_settings(service_user) logging.info("_flow_member_result_pharmacy_order: \n %s" % steps) if "button_button_yes" == steps[0].answer_id: picture_url = _get_value(steps[1], u'message_photo_upload_prescription') description = None if u"positive" == steps[2].answer_id: remarks = _get_value(steps[2], u'message_remarks_box') else: remarks = "" else: if u"positive" == steps[1].answer_id: picture_url = _get_value(steps[1], u'message_photo_upload_box') description = None if u"positive" == steps[2].answer_id: remarks = _get_value(steps[2], u'message_remarks_box') else: remarks = "" else: picture_url = None description = _get_value(steps[2], u'message_describe_box') if u"positive" == steps[3].answer_id: remarks = _get_value(steps[3], u'message_remarks_box') else: remarks = "" logging.info("Saving pharmacy order from %s" % user_details[0].email) app_user = create_app_user_by_email(user_details[0].email, user_details[0].app_id) service_identity_user = create_service_identity_user_wo_default(service_user, service_identity) o = SolutionPharmacyOrder(parent=parent_key_unsafe(service_identity_user, SOLUTION_COMMON)) o.description = description o.remarks = remarks o.sender = SolutionUser.fromTO(user_details[0]) o.timestamp = steps[2].received_timestamp o.status = SolutionPharmacyOrder.STATUS_RECEIVED o.picture_url = picture_url o.user = app_user msg = translate(sln_settings.main_language, SOLUTION_COMMON, 'if-order-received', remarks=remarks, phone_number="") message = create_solution_inbox_message(service_user, service_identity, SolutionInboxMessage.CATEGORY_PHARMACY_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 = [] sm_data.append({u"type": u"solutions.common.pharmacy_orders.update"}) sm_data.append({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) if picture_url: att = AttachmentTO() att.content_type = AttachmentTO.CONTENT_TYPE_IMG_JPG att.download_url = picture_url att.name = translate(sln_settings.main_language, SOLUTION_COMMON, u'picture') att.size = 0 send_inbox_forwarders_message(service_user, service_identity, app_user, msg, { 'if_name': user_details[0].name, 'if_email': user_details[0].email }, message_key=message.solution_inbox_message_key, attachments=[att], reply_enabled=message.reply_enabled) else: send_inbox_forwarders_message(service_user, service_identity, app_user, msg, { 'if_name': user_details[0].name, 'if_email': user_details[0].email }, message_key=message.solution_inbox_message_key, reply_enabled=message.reply_enabled) return None
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()