Ejemplo n.º 1
0
    def test_create_service_with_existing_user(self):
        self.set_datastore_hr_probability(1)
        rogerthat_service_email = "*****@*****.**"
        rogerthat_email = "*****@*****.**"
        rogerthat_user = create_app_user_by_email(rogerthat_email, 'rogerthat')

        be_loc_email = "*****@*****.**"
        be_loc_user = create_app_user_by_email(be_loc_email, 'be-loc')

        for u in (rogerthat_user, be_loc_user):
            create_user_profile(u, u.email())

        with self.assertRaises(
                UserWithThisEmailAddressAlreadyExistsException) as cm:
            create_solution_service(rogerthat_email, 'name', solution='flex')
        self.assertEqual(rogerthat_email, cm.exception.fields['email'])

        _, new_service_sln_settings = create_solution_service(
            rogerthat_service_email,
            'name',
            solution='flex',
            owner_user_email=rogerthat_email)
        new_service_user = new_service_sln_settings.service_user
        self.assertEqual(rogerthat_service_email, new_service_user.email())
        self.assertTrue(rogerthat_service_email in get_user_profile(
            users.User(rogerthat_email), cached=False).owningServiceEmails)

        _, new_service_sln_settings = create_solution_service(be_loc_email,
                                                              'name',
                                                              solution='flex')
        new_service_user = new_service_sln_settings.service_user
        self.assertEqual(be_loc_email, new_service_user.email())
Ejemplo n.º 2
0
def solution_event_guest_status(service_user, email, method, params, tag,
                                service_identity, user_details):
    sln_settings = get_solution_settings(service_user)
    app_user = create_app_user_by_email(email, user_details[0].app_id)

    jsondata = json.loads(params)
    event_id = long(jsondata['eventId'])
    status = int(jsondata['status'])

    event = get_event_by_id(service_user, sln_settings.solution, event_id)
    r = SendApiCallCallbackResultTO()
    if event:
        eg_key = EventGuest.createKey(app_user, event.key())
        eg = EventGuest.get(eg_key)
        if not eg:
            eg = EventGuest(key=eg_key)
        eg.guest = SolutionUser.fromTO(user_details[0])
        eg.status = status
        eg.timestamp = now()
        eg.put()
        r.result = u"Succesfully update event status"

        if sln_settings.event_notifications_enabled and (
                eg.status == EventGuest.STATUS_GOING or eg.chat_key):
            _send_event_notification(sln_settings,
                                     service_user,
                                     service_identity,
                                     user_details,
                                     event=event,
                                     event_guest=eg)
    else:
        r.result = u"Event not found. Update status failed."
    r.error = None
    return r
Ejemplo n.º 3
0
def solution_remind_event(service_user, email, method, params, tag,
                          service_identity, user_details):
    settings = get_solution_settings(service_user)
    jsondata = json.loads(params)

    app_user = create_app_user_by_email(email, user_details[0].app_id)
    event_id = long(jsondata['eventId'])
    remind_before = int(jsondata['remindBefore'])
    if jsondata.get("eventStartEpoch", None):
        event_start_epoch = int(jsondata['eventStartEpoch'])
    else:
        event_start_epoch = get_event_by_id(service_user, settings.solution,
                                            event_id).start_dates[0]

    r = SendApiCallCallbackResultTO()
    if is_reminder_set(app_user, event_id, event_start_epoch,
                       remind_before) is False:
        er = EventReminder()
        er.service_identity_user = create_service_identity_user(
            users.get_current_user(), service_identity)
        er.human_user = app_user
        er.remind_before = remind_before
        er.event_id = event_id
        er.event_start_epoch = event_start_epoch
        er.put()
        r.result = u"successfully reminded"
    else:
        r.result = u"already reminded"
    r.error = None
    return r
Ejemplo n.º 4
0
def load_chance_user(email, app_id):
    service_user = users.get_current_user()
    session_ = users.get_current_session()
    service_identity = session_.service_identity
    app_user = create_app_user_by_email(email, app_id)
    r = LoyaltyLotteryChanceTO()
    r.total_visits, r.my_visits, r.chance = calculate_chance_for_user(service_user, service_identity, app_user)
    return r
Ejemplo n.º 5
0
def load_city_wide_lottery_detail_customer_points(city_app_id, email, app_id):
    app_user = create_app_user_by_email(email, app_id)
    visits = get_solution_city_wide_lottery_loyalty_visits_for_user(city_app_id, app_user)
    r = LoyaltyCustomerPointsTO()

    # XXX: don't use get_profile_infos
    profile_infos = get_profile_infos([app_user], allow_none_in_results=True)
    for app_user, profile_info in zip([app_user], profile_infos):
        if not profile_info or profile_info.isServiceIdentity:
            continue
        r.user_details = ExtendedUserDetailsTO.fromUserProfile(profile_info, None)
        app_info = get_app_info_cached(r.user_details.app_id)
        r.user_details.app_name = app_info.name
    r.visits = [SolutionLoyaltyVisitTO.fromModel(visit) for visit in visits]
    return r
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
0
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))
Ejemplo n.º 8
0
def solution_event_guests(service_user, email, method, params, tag,
                          service_identity, user_details):
    sln_settings = get_solution_settings(service_user)
    app_user = create_app_user_by_email(email, user_details[0].app_id)

    jsondata = json.loads(params)
    event_id = long(jsondata['eventId'])
    include_details = int(jsondata['includeDetails'])

    event = get_event_by_id(service_user, sln_settings.solution, event_id)
    r = SendApiCallCallbackResultTO()
    if event:
        your_status = None
        eg = db.get(EventGuest.createKey(app_user, event.key()))
        if eg:
            your_status = eg.status

        guests = []
        if include_details == 1:
            for guest in event.guests:
                guests.append(EventGuestTO.fromEventGuest(guest))

        r.result = json.dumps(
            dict(
                event_id=event_id,
                include_details=include_details,
                guests_count_going=event.guests_count(EventGuest.STATUS_GOING),
                guests_count_maybe=event.guests_count(EventGuest.STATUS_MAYBE),
                guests_count_not_going=event.guests_count(
                    EventGuest.STATUS_NOT_GOING),
                guests=serialize_complex_value(guests, EventGuestTO, True),
                your_status=your_status)).decode('utf8')
        r.error = None
    else:
        r.result = None
        r.error = u"Event not found"
    return r
Ejemplo n.º 9
0
def load_detail_customer_points(loyalty_type, email, app_id):
    service_user = users.get_current_user()
    session_ = users.get_current_session()
    service_identity = session_.service_identity
    app_user = create_app_user_by_email(email, app_id)
    if loyalty_type == SolutionLoyaltySettings.LOYALTY_TYPE_REVENUE_DISCOUNT:
        visits = get_solution_loyalty_visits_for_revenue_discount(service_user, service_identity, app_user)
    elif loyalty_type == SolutionLoyaltySettings.LOYALTY_TYPE_LOTTERY:
        visits = get_solution_loyalty_visits_for_lottery(service_user, service_identity, app_user)
    else:
        visits = get_solution_loyalty_visits_for_stamps(service_user, service_identity, app_user)

    r = LoyaltyCustomerPointsTO()

    # XXX: don't use get_profile_infos
    profile_infos = get_profile_infos([app_user], allow_none_in_results=True)
    for app_user, profile_info in zip([app_user], profile_infos):
        if not profile_info or profile_info.isServiceIdentity:
            continue
        r.user_details = ExtendedUserDetailsTO.fromUserProfile(profile_info, None)
        app_info = get_app_info_cached(r.user_details.app_id)
        r.user_details.app_name = app_info.name
    r.visits = [SolutionLoyaltyVisitTO.fromModel(visit) for visit in visits]
    return r
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
 def admin_user(self):
     return create_app_user_by_email(self.tablet_email, self.tablet_app_id)
Ejemplo n.º 12
0
def load_city_wide_lottery_chance_user(city_app_id, email, app_id):
    app_user = create_app_user_by_email(email, app_id)
    r = LoyaltyLotteryChanceTO()
    r.total_visits, r.my_visits, r.chance = calculate_city_wide_lottery_chance_for_user(city_app_id, app_user)
    return r
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
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