def test_0(self):
     """
     Request_redeem creates a new RedeemReward (reward)
     """
     if RedeemReward.objects().count(\
         PatronStore=self.patron_store.objectId) > 0:
         return "PatronStore exists. Test is invalid."
     
     self.request_redeem()
     
     return RedeemReward.objects().count(\
         PatronStore=self.patron_store.objectId) == 1
 def test_16(self):
     """
     RedeemReward is deleted
     """
     self.patron_store.fetch_all(clear_first=True, with_cache=False)
     return RedeemReward.objects().count(\
         objectId=self.redeem_reward.objectId) == 0
 def test_43(self):
     """
     The RedeemReward is then deleted 
     """
     return  RedeemReward.objects().count(\
         objectId=self.redeem_reward.objectId) == 0
         
 def test_1(self):
     """
     RedeemReward is added to Store's RedeemReward relation
     """
     self.redeem_reward = RedeemReward.objects().get(\
             PatronStore=self.patron_store.objectId)
     return self.store.get("redeemRewards", objectId=\
         self.redeem_reward.objectId, count=1, limit=0) == 1
 def test_19(self):
     """
     RedeemReward is added to Store's RedeemReward relation
     """
     self.redeem_reward = RedeemReward.objects().get(\
         MessageStatus=self.message_status.objectId,
         is_redeemed=False)
         
     self.store.redeemRewards = None
     return self.store.get("redeemRewards", objectId=\
         self.redeem_reward.objectId, count=1, limit=0) == 1
 def test_37(self):
     """
     Validate_redeem succeeds with insufficient if the
     PatronStore does not have enough punches
     """
     self.patron_store = self.add_patronstore(0)
     self.request_redeem()
     self.redeem_reward = RedeemReward.objects().get(\
         PatronStore=self.patron_store.objectId, is_redeemed=False)
         
     return cloud_call("validate_redeem", {
         "redeem_id": self.redeem_reward.objectId,
         "store_id": self.store.objectId,
         "reward_id": self.reward["reward_id"]
     })["result"]["code"] == "insufficient"
 def test_15(self):
     """
     Reject_redeem successful
     """
     # need a new redeem
     self.request_redeem()
     self.redeem_reward = RedeemReward.objects().get(\
         PatronStore=self.patron_store.objectId, is_redeemed=False)
         
     res = cloud_call("reject_redeem", {
         "redeem_id": self.redeem_reward.objectId,
         "store_id": self.store.objectId,
     })
     
     return "error" not in res
 def test_42(self):
     """
     Reject_redeem fails with PATRONSTORE_REMOVED if the
     PatronStore has been deleted
     """
     self.patron_store.pending = False
     self.patron_store.update()
     self.request_redeem()
     self.redeem_reward = RedeemReward.objects().get(\
         PatronStore=self.patron_store.objectId, is_redeemed=False)
     self.patron_store.delete()
     
     return cloud_call("reject_redeem", {
         "redeem_id": self.redeem_reward.objectId,
         "store_id": self.store.objectId,
     })["error"] == "PATRONSTORE_REMOVED"
 def test_41(self):
     """
     Reject_redeem fails with REDEEMREWARD_NOT_FOUND if the
     RedeemReward has been deleted 
     """
     self.patron_store.pending = False
     self.patron_store.update()
     self.request_redeem()
     self.redeem_reward = RedeemReward.objects().get(\
         PatronStore=self.patron_store.objectId, is_redeemed=False)
     self.redeem_reward.delete()
     
     return cloud_call("reject_redeem", {
         "redeem_id": self.redeem_reward.objectId,
         "store_id": self.store.objectId,
     })["error"] == "REDEEMREWARD_NOT_FOUND"
 def test_18(self):
     """
     Request_redeem creates a new RedeemReward (offer/gift)
     """
     # need to create an offer
     self.offer = self.create_offer()
     self.message_status =\
         self.patron.get("receivedMessages", limit=1)[0]
     self.patron.receivedMessages = None
     
     self.request_redeem(None, self.offer.offer_title,
         self.message_status.objectId)
     
     return RedeemReward.objects().count(\
         MessageStatus=self.message_status.objectId,
         is_redeemed=False) == 1
 def test_40(self):
     """
     Reject_redeem fails with REDEEMREWARD_VALIDATED
     if the RedeemReward has already been validated
     """
     self.patron_store.all_time_punches = 10
     self.patron_store.punch_count = 10
     self.patron_store.update()
     self.request_redeem()
     self.redeem_reward = RedeemReward.objects().get(\
         PatronStore=self.patron_store.objectId, is_redeemed=False)
     self.redeem_reward.is_redeemed = True
     self.redeem_reward.update()
     
     return cloud_call("reject_redeem", {
         "redeem_id": self.redeem_reward.objectId,
         "store_id": self.store.objectId,
     })["error"] == "REDEEMREWARD_VALIDATED"
 def test_34(self):
     """
     Validate_redeem succeeds with validated if the
     RedeemReward has already been redeemed
     """
     self.patron_store.pending_reward = False
     self.patron_store.update()
     self.request_redeem()
     self.redeem_reward = RedeemReward.objects().get(\
         PatronStore=self.patron_store.objectId, is_redeemed=False)
     self.redeem_reward.is_redeemed = True
     self.redeem_reward.update()
     
     return cloud_call("validate_redeem", {
         "redeem_id": self.redeem_reward.objectId,
         "store_id": self.store.objectId,
         "reward_id": self.reward["reward_id"]
     })["result"]["code"] == "validated"
 def test_30(self):
     """
     Reject_redeem successful
     """
     # create another redeem
     self.offer = self.create_offer()
     self.message_status = self.patron.get("receivedMessages",
         redeem_available="yes", limit=1)[0]
     self.patron.receivedMessages = None
     self.request_redeem(None, self.offer.offer_title,
         self.message_status.objectId)
     self.redeem_reward = RedeemReward.objects().get(\
             MessageStatus=self.message_status.objectId,
             is_redeemed=False)
         
     res = cloud_call("reject_redeem", {
         "redeem_id": self.redeem_reward.objectId,
         "store_id": self.store.objectId,
     })
     return "error" not in res
 def test_43(self):
     """
     The RedeemReward is then deleted 
     """
     return  RedeemReward.objects().count(\
         objectId=self.redeem_reward.objectId) == 0
 def test_31(self):
     """
     RedeemReward is deleted
     """
     return  RedeemReward.objects().count(\
         objectId=self.redeem_reward.objectId) == 0
Beispiel #16
0
def redeem(request):
    """ returns json object. result is 0 if fail, 1 if success,
    2 if insufficient punches, 3 if already validated, 
    4 if successfully deleted/denied, 5 has been deleted elsewhere and
    action is deny, 6 PatronStore has been removed,
    7 deleted elsewhere and action is approve.
    """
    if request.method == "GET":
        # approve or deny
        action = request.GET.get("action")
        redeemId = request.GET.get('redeemRewardId')
        # may come in as "None" or "null" or "undefined"
        rewardId = request.GET.get('rewardId')
        if str(rewardId).isdigit():
            rewardId = int(rewardId)
        else:
            rewardId = None

        store = SESSION.get_store(request.session)
        if action == "approve":
            res = cloud_call(
                "validate_redeem", {
                    "redeem_id": redeemId,
                    "store_id": store.get("objectId"),
                    "reward_id": rewardId,
                })
        elif action == "deny":
            res = cloud_call("reject_redeem", {
                "redeem_id": redeemId,
                "store_id": store.get("objectId"),
            })

        # retrieve latest session since user may click a bunch
        # of redemptions consecutively
        session = SessionStore(request.session.session_key)

        data = {"result": 0}

        # success result removed means patronstore is null!
        if 'error' not in res:
            redemptions_pending =\
                    SESSION.get_redemptions_pending(session)
            i_remove = -1
            if action == "approve":
                result = res.get("result").get("code")
                result_red =\
                    RedeemReward(**res.get("result").get("result"))
            else:
                result = res.get("result")

            # remove from redemptions_pending
            for i, red in enumerate(redemptions_pending):
                if red.objectId == redeemId:
                    i_remove = i
                    break

            # IMPORTANT! Since comet receive  immediately commits
            # changes to a session, i_remove will probably be -1

            if action == "approve":
                redemptions_past =\
                    SESSION.get_redemptions_past(session)

                if result and result in ("insufficient", "PATRONSTORE_REMOVED"
                                         ) and i_remove != -1:
                    redemptions_pending.pop(i_remove)

                elif i_remove != -1:  # success
                    redemption = redemptions_pending.pop(i_remove)
                    redemption.is_redeemed = True
                    redemption.updatedAt = result_red.updatedAt
                    redemptions_past.append(redemption)
                    session['redemptions_past'] =\
                        redemptions_past

                # session changed only if i_remove was not 1
                if i_remove != -1:
                    session['redemptions_pending'] =\
                        redemptions_pending

                if result and result == "insufficient":
                    data["result"] = 2
                elif result and result == "validated":
                    data["result"] = 3
                elif result and result == "PATRONSTORE_REMOVED":
                    data["result"] = 6
                else:
                    data["result"] = 1

                # request.session will be saved after return
                request.session.clear()
                request.session.update(session)
                return HttpResponse(json.dumps(data),
                                    content_type="application/json")

            elif action == "deny":
                if i_remove != -1:
                    del_red = redemptions_pending.pop(i_remove)
                    session['redemptions_pending'] =\
                        redemptions_pending

                data["result"] = 4

                request.session.clear()
                request.session.update(session)
                return HttpResponse(json.dumps(data),
                                    content_type="application/json")

        elif 'error' in res:
            if res['error'] == "REDEEMREWARD_NOT_FOUND":
                if action == "approve":
                    data["result"] = 7
                elif action == "deny":
                    data["result"] = 5
            elif res['error'] == "REDEEMREWARD_VALIDATED":
                data["result"] = 3
            elif res['error'] == "PATRONSTORE_REMOVED":
                data["result"] = 6

    # always make sure to get the latest session since the session
    # will be saved on return!!!
    request.session.clear()
    request.session.update(SessionStore(request.session.session_key))
    return HttpResponse(json.dumps(data), content_type="application/json")
Beispiel #17
0
    def processCometReceivedDict(session, postDict):
        employees_pending_list =\
            SESSION.get_employees_pending_list(session)
        employees_approved_list =\
            SESSION.get_employees_approved_list(session)
        messages_received_list =\
            SESSION.get_messages_received_list(session)
        redemptions_pending =\
            SESSION.get_redemptions_pending(session)
        redemptions_past =\
            SESSION.get_redemptions_past(session)

        #############################################################
        # FEEDBACKS_UNREAD ##################################
        newFeedback = postDict.get('newFeedback')
        if newFeedback:
            messages_received_ids =\
                [ fb.objectId for fb in messages_received_list ]
            m = Message(**newFeedback)
            if m.objectId not in messages_received_ids:
                messages_received_list.insert(0, m)

            session['messages_received_list'] =\
                messages_received_list

        #############################################################
        # FEEDBACK DELETED ##################################
        deletedFeedback = postDict.get("deletedFeedback")
        if deletedFeedback:
            fb = Message(**deletedFeedback)
            for i, mro in enumerate(messages_received_list):
                if fb.objectId == mro.objectId:
                    messages_received_list.pop(i)
                    break
            session['messages_received_list'] =\
                messages_received_list

        #############################################################
        # MESSAGE SENT ##################################
        # need to check if this new message is an original message
        # or a reply to a feedback (the message sent by the patron)!
        # also may increment the message count!
        newMessage = postDict.get("newMessage")
        if newMessage:
            messages_received_ids =\
                    [ fb.objectId for fb in messages_received_list ]
            messages_sent_list =\
                SESSION.get_messages_sent_list(session)
            messages_sent_ids =\
                [ msg.objectId for msg in messages_sent_list ]
            m = Message(**newMessage)
            if m.objectId not in messages_sent_ids and\
                m.message_type != FEEDBACK:
                messages_sent_list.insert(0, m)
                if 'message_count' in session:
                    session['message_count'] =\
                        int(session['message_count']) + 1
            # update an existing feedback
            if m.objectId in messages_received_ids and\
                m.message_type == FEEDBACK:
                for i, mrl in enumerate(messages_received_list):
                    if mrl.objectId == m.objectId:
                        messages_received_list.pop(i)
                        messages_received_list.insert(i, m)
                        break
            session['messages_received_list'] =\
                messages_received_list
            session['messages_sent_list'] = messages_sent_list

        #############################################################
        # EMPLOYEES_PENDING ##################################
        # must also check if employee is already approved!
        pendingEmployee = postDict.get("pendingEmployee")
        if pendingEmployee:
            employees_approved_ids =\
                [ emp.objectId for emp in employees_approved_list ]
            employees_pending_ids =\
                [ emp.objectId for emp in employees_pending_list ]
            e = Employee(**pendingEmployee)
            if e.objectId not in employees_pending_ids and\
                e.objectId not in employees_approved_ids:
                employees_pending_list.insert(0, e)

            session['employees_pending_list'] =\
                employees_pending_list

        #############################################################
        # EMPLOYEES APPROVED (pending to approved) #################
        approvedEmployee = postDict.get("approvedEmployee")
        if approvedEmployee:
            emp = Employee(**approvedEmployee)
            # first check if the employee is in the pending list
            # if not then check if it is already approved
            for i, emp_pending in\
                enumerate(employees_pending_list):
                if emp.objectId == emp_pending.objectId:
                    emp = employees_pending_list.pop(i)
                    emp.status = APPROVED
                    employees_approved_list.insert(0, emp)
                    break

            session['employees_pending_list'] =\
                employees_pending_list
            session['employees_approved_list'] =\
                employees_approved_list

        #############################################################
        # EMPLOYEES NEW (straight to approved) #################
        newEmployee = postDict.get("newEmployee")
        if newEmployee:
            employees_approved_ids =\
                [ emp.objectId for emp in employees_approved_list ]
            emp = Employee(**newEmployee)
            if emp.objectId not in employees_approved_ids:
                employees_approved_list.insert(0, emp)
                session['employees_approved_list'] =\
                    employees_approved_list

        #############################################################
        # EMPLOYEES DELETED/DENIED/REJECTED (pending/approved to pop)!
        deletedEmployee = postDict.get("deletedEmployee")
        if deletedEmployee:
            emp = Employee(**deletedEmployee)
            # check in approved emps
            for i, cop in enumerate(employees_approved_list):
                if cop.objectId == emp.objectId:
                    employees_approved_list.pop(i)
                    break

            # check in pending emps
            for i, cop in enumerate(employees_pending_list):
                if cop.objectId == emp.objectId:
                    employees_pending_list.pop(i)
                    break

            session['employees_approved_list'] =\
                employees_approved_list
            session['employees_pending_list'] =\
                employees_pending_list

        #############################################################
        # EMPLOYEE UPDATED PUNCHES
        updatedEmployeePunch = postDict.get("updatedEmployeePunch")
        if updatedEmployeePunch:
            u_emp = Employee(**updatedEmployeePunch)
            for emp in employees_approved_list:
                if u_emp.objectId == emp.objectId:
                    emp.set("lifetime_punches", u_emp.lifetime_punches)
                    break
            session['employees_approved_list'] =\
                employees_approved_list

        #############################################################
        # REDEMPTIONS PENDING
        ### Only added to cache if it has the store_location_id as
        ### active_store_location_id
        pendingRedemption = postDict.get("pendingRedemption")
        if pendingRedemption:
            rr = RedeemReward(**pendingRedemption)

            # store_location_id can be null for backwards compat
            if not rr.store_location_id or rr.store_location_id ==\
                session.get('active_store_location_id'):
                redemptions_pending_ids =\
                    [ red.objectId for red in redemptions_pending ]
                redemptions_past_ids =\
                    [ red.objectId for red in redemptions_past ]
                # need to check here if the redemption is new because
                # the dashboard that validated it will also receive
                # the validated redemption back.
                if rr.objectId not in redemptions_past_ids and\
                    rr.objectId not in redemptions_pending_ids:
                    redemptions_pending.insert(0, rr)

                session['redemptions_pending'] =\
                    redemptions_pending

        #############################################################
        # REDEMPTIONS APPROVED (pending to history)
        # Save cpu by skipping those that do not have the same
        # store_location_id as active_store_location_id
        approvedRedemption = postDict.get("approvedRedemption")
        if approvedRedemption:
            redemp = RedeemReward(**approvedRedemption)

            # store_location_id can be null for backwards compat
            if not redemp.store_location_id or redemp.store_location_id ==\
                session.get('active_store_location_id'):
                # check if redemp is still in pending
                for i, redem in enumerate(redemptions_pending):
                    if redem.objectId == redemp.objectId:
                        r = redemptions_pending.pop(i)
                        r.is_redeemed = True
                        r.updatedAt = redemp.updatedAt
                        redemptions_past.insert(0, r)
                        break
                # if not then check if it is in the history already
                # the above shouldn't happen!

                session['redemptions_pending'] =\
                    redemptions_pending
                session['redemptions_past'] =\
                    redemptions_past

        #############################################################
        # REDEMPTIONS DELETED ##############################
        # remove from pending (should not be in history!)
        # Save cpu by skipping those that do not have the same
        # store_location_id as active_store_location_id
        deletedRedemption = postDict.get("deletedRedemption")
        if deletedRedemption:
            redemp = RedeemReward(**deletedRedemption)

            # store_location_id can be null for backwards compat
            if not redemp.store_location_id or redemp.store_location_id ==\
                session.get('active_store_location_id'):
                # check if redemp is still in pending
                for i, redem in enumerate(redemptions_pending):
                    if redem.objectId == redemp.objectId:
                        redemptions_pending.pop(i)
                        break

                session['redemptions_pending'] =\
                    redemptions_pending

        #############################################################
        # STORE UPDATED ##############################
        updatedStore = postDict.get("updatedStore")
        if updatedStore:
            store = Store(**updatedStore)
            # have to add the image url manually
            store.thumbnail_image_url = updatedStore.get("thumbnail_image_url")
            store.cover_image_url = updatedStore.get("cover_image_url")
            # below here for backwards compat
            store.store_avatar_url = store.thumbnail_image_url
            session['store'] = store

        updatedStoreThumbnailName = postDict.get("updatedStoreThumbnailName")
        if updatedStoreThumbnailName:
            store = session['store']
            store.thumbnail_image = updatedStoreThumbnailName
            store.thumbnail_image_url = postDict.get(
                "updatedStoreThumbnailUrl")
            # below here for backwards compat
            store.store_avatar = store.thumbnail_image
            store.store_avatar_url = store.thumbnail_image_url
            session['store'] = store

        updatedStoreCoverName = postDict.get("updatedStoreCoverName")
        if updatedStoreCoverName:
            store = session['store']
            store.cover_image = updatedStoreCoverName
            store.cover_image_url = postDict.get("updatedStoreCoverUrl")
            session['store'] = store

        # this is in the settings tab in the dashboard but the field
        # is in the Store class
        updatedPunchesFacebook_int =\
            postDict.get("updatedPunchesFacebook_int")
        if updatedPunchesFacebook_int:
            store = session['store']
            store.punches_facebook = int(updatedPunchesFacebook_int)
            session['store'] = store

        #############################################################
        # STORE LOCATION UPDATED ##############################
        ### Note that this is also being used to insert new StoreLocations
        updatedStoreLocation = postDict.get("updatedStoreLocation")
        if updatedStoreLocation:
            store_location = StoreLocation(**updatedStoreLocation)
            session['store_locations'][store_location.objectId] =\
                store_location

            try:  # also update the store_timezone
                session['store_timezone'] =\
                    pytz.timezone(store_location.get('store_timezone'))
            except Exception:  # assign a default timezone
                session['store_timezone'] =\
                    pytz.timezone(TIME_ZONE)

        #############################################################
        # ACCOUNT UPDATED ##############################
        updatedAccount = postDict.get("updatedAccount")
        if updatedAccount:
            updatedAccountObject = Account(**updatedAccount)
            # need to make sure that these are the same accounts!
            if session['account'].objectId ==\
                updatedAccountObject.objectId:
                session['account'] = updatedAccountObject

        #############################################################
        # SUBSCRIPTION UPDATED ##############################
        updatedSubscription =\
            postDict.get("updatedSubscription")
        if updatedSubscription:
            subscription = Subscription(**updatedSubscription)
            store = session["store"]
            store.set('subscription', subscription)
            store.set('Subscription', subscription.objectId)
            session['subscription'] = subscription
            session['store'] = store

        #############################################################
        # SETTINGS UPDATED ##############################
        updatedSettings = postDict.get("updatedSettings")
        if updatedSettings:
            settings = Settings(**updatedSettings)
            store = session["store"]
            store.set('settings', settings)
            store.set("Settings", settings.objectId)
            session['settings'] = settings
            session['store'] = store

        #############################################################
        # REWARDS NEW ##############################
        newReward = postDict.get("newReward")
        if newReward:
            store = session['store']
            rewards = store.get("rewards")
            rewards_ids = [r['reward_id'] for r in rewards]
            if newReward['reward_id'] not in rewards_ids:
                rewards.append(newReward)
            store.rewards = rewards
            session['store'] = store

        #############################################################
        # REWARDS UPDATED ##############################
        updatedReward = postDict.get('updatedReward')
        if updatedReward:
            store = session['store']
            mod_rewards = store.get("rewards")
            for i, mreward in enumerate(mod_rewards):
                # [{"reward_name":"Free bottle of wine",
                # "description":"Must be under $25 in value",
                # "punches":10,"redemption_count":0,reward_id:0},]
                if updatedReward['reward_id'] == mreward['reward_id']:
                    if updatedReward.has_key("redemption_count"):
                        mod_rewards[i]['redemption_count'] =\
                            updatedReward['redemption_count']
                    if updatedReward.has_key("reward_name"):
                        mod_rewards[i]['reward_name'] =\
                            updatedReward['reward_name']
                    if updatedReward.has_key("punches"):
                        mod_rewards[i]['punches'] =\
                            updatedReward['punches']
                    if updatedReward.has_key("description"):
                        mod_rewards[i]['description'] =\
                            updatedReward['description']
                    break

            store.rewards = mod_rewards
            session['store'] = store

        #############################################################
        # REWARDS DELETED ##############################
        deletedReward = postDict.get("deletedReward")
        if deletedReward:
            store = session['store']
            rewards = store.get("rewards")
            rewards_ids = [r['reward_id'] for r in rewards]
            if deletedReward['reward_id'] in rewards_ids:
                for i, r in enumerate(rewards):
                    if r['reward_id'] == deletedReward['reward_id']:
                        rewards.pop(i)
                        break
            store.rewards = rewards
            session['store'] = store

        #############################################################
        # PATRONSTORE_COUNT ##################################
        patronStore_int = postDict.get('patronStore_int')
        if patronStore_int:
            patronStore_int = int(patronStore_int)
            session['patronStore_count'] = patronStore_int