Пример #1
0
 def setUp(self):
     Database.clear_db()
     self.processor = Processor()
     mapper = UserMapper()
     self.males = mapper.get_all_males()
     self.females = mapper.get_all_females()
     self.others = mapper.get_other_genders()
Пример #2
0
class TestOrderMapperRead(unittest.TestCase):
    def setUp(self):
        Database.clear_db()
        self.uMapper = UserMapper()
        self.u = self.uMapper.create_user("123")
        self.mapper = OrderMapper()
        self.o = self.mapper.create_order("123", "Flower", 2)

    def test_get_order_by_order_id(self):
        order = self.mapper.get_order_by_order_id(self.o.id)
        assert (order.user_id == self.u.id)

    def test_get_all_orders(self):
        orders = self.mapper.get_all_orders()
        assert (self.o in orders)

    def test_get_order_by_invalid_order_id(self):
        self.assertRaises(ValueError, self.mapper.get_order_by_order_id, 123)

    def test_get_order_by_fb_id(self):
        orders = self.mapper.get_orders_by_fb_id("123")
        assert (self.o in orders)

    def test_get_order_by_invalid_fb_id(self):
        self.assertRaises(ValueError, self.mapper.get_orders_by_fb_id, "233")

    def test_get_order_by_fb_id_no_order(self):
        self.uMapper.create_user("456")
        self.assertRaises(ValueError, self.mapper.get_orders_by_fb_id, "456")
Пример #3
0
 def setUp(self):
     Database.clear_db()
     self.mapper = UserMapper()
     self.male = self.mapper.create_user("123", "Max", "Kusnadi", "male")
     self.female = self.mapper.create_user("456", "Cindy", "Amelia",
                                           "female")
     self.other = self.mapper.create_user("789", "Bob", "Papatuli", "gay")
Пример #4
0
class TestUserMapperRead(unittest.TestCase):
    def setUp(self):
        Database.clear_db()
        self.mapper = UserMapper()
        self.u = self.mapper.create_user("123456", "Max", "Kusnadi")

    def test_read_fb_id_valid(self):
        u = self.mapper.get_user_by_fb_id("123456")
        assert (u.first_name == "Max")

    def test_read_fb_id_invalid(self):
        self.assertRaises(ValueError, self.mapper.get_user_by_fb_id, "@34")

    def test_read_fb_id_not_found(self):
        self.assertRaises(ValueError, self.mapper.get_user_by_fb_id, "abc")

    def test_read_name_valid(self):
        u = self.mapper.get_user_by_name("Max")
        assert (u.fb_id == "123456")

    def test_read_full_name_valid(self):
        u = self.mapper.get_user_by_name("Max", "Kusnadi")
        assert (u.fb_id == "123456")

    def test_read_name_invalid(self):
        self.assertRaises(ValueError, self.mapper.get_user_by_name, "@34")

    def test_read_name_not_found(self):
        self.assertRaises(ValueError, self.mapper.get_user_by_name, "Marc")

    def test_read_all_user(self):
        u_list = self.mapper.get_all_users()
        assert (self.u in u_list)
Пример #5
0
    def test_create_user(self):
        mapper = UserMapper()
        u = mapper.create_user("123", "Max", "Kusnadi", "Male")

        assert (u.fb_id == "123")
        assert (u.first_name == "Max")
        assert (u.last_name == "Kusnadi")
        assert (u.gender == "Male")
Пример #6
0
class OrderMapper(object):
    def __init__(self):
        self.userMapper = UserMapper()

    # CREATE
    def create_order(self, fb_id, description, quantity):
        try:
            user = self.userMapper.get_user_by_fb_id(fb_id)
        except ValueError as err:
            logging.error(err)
            logging.error(err.args)
            raise ValueError(UNABLE_TO_CREATE.format("Order"), fb_id)
        else:
            order = Order(user, description, quantity)
            order.set_time_auto()
            Database.add_to_db(order)
            return order

    # READ
    def get_order_by_order_id(self, order_id):
        order = Order.query.filter(Order.id == order_id).first()
        if order:
            return order
        else:
            raise ValueError(NOT_FOUND.format("Order"), order_id)

    def get_orders_by_fb_id(self, fb_id):
        try:
            user = self.userMapper.get_user_by_fb_id(fb_id)
        except ValueError as err:
            logging.error(err)
            logging.error(err.args)
            raise err

        user_id = user.id
        order = Order.query.filter(Order.user_id == user_id)
        if order.count() > 0:
            return order
        else:
            raise ValueError(NOT_FOUND.format("Orders"), fb_id)

    def get_all_orders(self):
        o = Order.query.all()
        return o

    # UPDATE
    def update_order_status_by_order_id(self, order_id, status):
        try:
            order = self.get_order_by_order_id(order_id)
        except ValueError as err:
            logging.error(err)
            logging.error(err.args)
            raise err

        order.set_status(status)
        order.set_time_auto()
        Database.commit_db()
        return order
Пример #7
0
class TestUserMapperUpdate(unittest.TestCase):
    def setUp(self):
        Database.clear_db()
        self.mapper = UserMapper()
        self.u = self.mapper.create_user("123", "Max", "Kusnadi", "Male")

    def test_update_user_by_fb_id(self):
        u = self.mapper.update_user_authorization("123", True)

        assert (u.is_authorized == True)

    def test_update_user_by_invalid_fb_id(self):
        self.assertRaises(ValueError, self.mapper.update_user_authorization,
                          "2225", True)
Пример #8
0
class TestUserMapperRead(unittest.TestCase):
    def setUp(self):
        Database.clear_db()
        self.mapper = UserMapper()
        self.u = self.mapper.create_user("123", "Max", "Kusnadi", "Male")

    def test_get_user_by_fb_id(self):
        u = self.mapper.get_user_by_fb_id("123")

        assert (u.fb_id == "123")
        assert (u.first_name == "Max")
        assert (u.last_name == "Kusnadi")
        assert (u.gender == "Male")

    def test_get_user_by_invalid_fb_id(self):
        self.assertRaises(ValueError, self.mapper.get_user_by_fb_id, "222")

    def test_get_all_users(self):
        users = self.mapper.get_all_users()
        self.assertTrue(self.u in users)
Пример #9
0
class TestUserMapperUpdate(unittest.TestCase):
    def setUp(self):
        Database.clear_db()
        self.mapper = UserMapper()
        self.u = self.mapper.create_user("123", "Max", "Kusnadi")

    def test_set_first_name(self):
        u = self.mapper.set_first_name("123", "Cindy")
        assert (u.first_name == "Cindy")

    def test_set_first_name_invalid_fb_id(self):
        self.assertRaises(ValueError, self.mapper.set_first_name, "#$%",
                          "Cindy")

    def test_set_last_name(self):
        u = self.mapper.set_last_name("123", "Cipu")
        assert (u.last_name == "Cipu")

    def test_set_last_name_invalid_fb_id(self):
        self.assertRaises(ValueError, self.mapper.set_last_name, "#$%",
                          "Cindy")
Пример #10
0
class TestUserMapperReadGender(unittest.TestCase):
    def setUp(self):
        Database.clear_db()
        self.mapper = UserMapper()
        self.male = self.mapper.create_user("123", "Max", "Kusnadi", "male")
        self.female = self.mapper.create_user("456", "Cindy", "Amelia",
                                              "female")
        self.other = self.mapper.create_user("789", "Bob", "Papatuli", "gay")

    def test_all_males(self):
        males = self.mapper.get_all_males()
        self.assertTrue(self.male in males)
        self.assertFalse(self.female in males)
        self.assertFalse(self.other in males)

    def test_all_females(self):
        females = self.mapper.get_all_females()
        self.assertTrue(self.female in females)
        self.assertFalse(self.male in females)
        self.assertFalse(self.other in females)

    def test_all_others(self):
        males = self.mapper.get_other_genders()
        self.assertTrue(self.other in males)
        self.assertFalse(self.female in males)
        self.assertFalse(self.male in males)
Пример #11
0
class TestUserMapperCreate(unittest.TestCase):
    def setUp(self):
        Database.clear_db()
        self.mapper = UserMapper()

    def test_create_user(self):
        u = self.mapper.create_user("abc123", "Max", "Kusnadi")
        assert (u.fb_id == "abc123")
        assert (u.first_name == "Max")
        assert (u.last_name == "Kusnadi")

    def test_invalid_fb_id(self):
        self.assertRaises(ValueError, self.mapper.create_user, "@#`")

    def test_invalid_name(self):
        self.assertRaises(ValueError, self.mapper.create_user, "1234", "@#`")
Пример #12
0
class Processor(object):
    def __init__(self):
        self.mapper = UserMapper()

    def get_match_for_male(self):
        females = self.mapper.get_all_females()
        others = self.mapper.get_other_genders()
        combined = list(females) + list(others)
        try:
            choice = random.choice(combined)
        except IndexError as err:
            logging.error(err)
            raise err
        else:
            return choice

    def get_match_for_female(self):
        males = self.mapper.get_all_males()
        others = self.mapper.get_other_genders()
        combined = list(males) + list(others)
        try:
            choice = random.choice(combined)
        except IndexError as err:
            logging.error(err)
            raise err
        else:
            return choice

    def get_match_for_others(self):
        females = self.mapper.get_all_females()
        males = self.mapper.get_all_males()
        combined = list(females) + list(males)
        try:
            choice = random.choice(combined)
        except IndexError as err:
            logging.error(err)
            raise err
        else:
            return choice
Пример #13
0
 def setUp(self):
     Database.clear_db()
     self.mapper = UserMapper()
     self.u = self.mapper.create_user("123", "Max", "Kusnadi")
Пример #14
0
 def __init__(self):
     self.userMapper = UserMapper()
Пример #15
0
 def setUp(self):
     Database.clear_db()
     uMapper = UserMapper()
     u = uMapper.create_user("123")
     self.mapper = OrderMapper()
     self.o = self.mapper.create_order("123", "Flower", 2)
Пример #16
0
 def __init__(self):
     self.user = UserMapper()
     self.order = OrderMapper()
Пример #17
0
class ShopLogic(object):

    def __init__(self):
        self.user = UserMapper()
        self.order = OrderMapper()

    def store_user(self, user):
        try:
            u = self.user.get_user_by_fb_id(user['fb_id'])
        except ValueError as err:
            logging.error(err)
            try:
                u = self.user.create_user(
                    user['fb_id'], user['first_name'], user['last_name'])
            except Exception as err:
                logging.error(err)
                u = None
        return u

    def get_all_users(self):
        users = self.user.get_all_users()
        return users

    def get_all_orders(self):
        orders = self.order.get_all_orders()
        return orders

    def generate_payload_start_order(self, recipient_id):
        data = json.dumps({
            "recipient": {
                "id": recipient_id
            },
            "message": {
                "text": "Which flower do you want?",
                "quick_replies": [
                    {
                        "content_type": "text",
                        "title": "Packet A",
                        "payload": "Packet A"
                    },
                    {
                        "content_type": "text",
                        "title": "Packet B",
                        "payload": "Packet B"
                    },
                    {
                        "content_type": "text",
                        "title": "Packet C",
                        "payload": "Packet C"
                    },
                    {
                        "content_type": "text",
                        "title": "Packet D",
                        "payload": "Packet D"
                    }
                ]
            }
        })
        return data

    def process_quick_reply(self, sender_id, payload):
        if payload in ["Packet A", "Packet B", "Packet C", "Packet D"]:
            logging.info("processing quantity for {recipient}".format(
                recipient=sender_id))
            data = self._process_quantity(sender_id, payload)
        elif payload == "No":
            logging.info("Canceling order for {}".format(sender_id))
            data = self._process_text(
                sender_id, "You can always order flower again by typing 'shop'! ")
        elif self._check_confirmation(payload):
            logging.info("Storing order for {}".format(sender_id))
            self._store_order(sender_id, payload)
            data = self._process_text(
                sender_id, "Your order has been confirmed. Transfer to POSB Savings 249256455 and message proof to Steven Nilam (8138 6940). Thanks for ordering! :)")
        elif self._check_quantity(payload):
            logging.info("Confirming order for {recipient}".format(
                recipient=sender_id))
            data = self._confirm_order(sender_id, payload)
        else:
            data = self._process_text(
                sender_id, "Sorry an error occured! It should'nt be happening. Please try again or order here bit.ly/PINUSFlowers")
        return data

    def _store_order(self, sender_id, payload):
        payload = eval(payload)
        order = self.order.create_order(
            sender_id, payload['description'], payload['quantity'])

    def _check_confirmation(self, payload):
        return "confirmed" in payload

    def _check_quantity(self, payload):
        lst = ["1", "2", "3", "4", "5"]
        result = False
        for num in lst:
            if num in payload:
                result = True
        return result

    def _process_text(self, sender_id, message_text):
        data = json.dumps({
            "recipient": {
                "id": sender_id
            },
            "message": {
                "text": message_text
            }
        })
        return data

    def _process_quantity(self, sender_id, payload):
        data = json.dumps({
            "recipient": {
                "id": sender_id
            },
            "message": {
                "text": "How many {} do you want?".format(payload),
                "quick_replies": [
                    {
                        "content_type": "text",
                        "title": "1",
                        "payload": str({
                            "description": payload,
                            "quantity": 1
                        })
                    },
                    {
                        "content_type": "text",
                        "title": "2",
                        "payload": str({
                            "description": payload,
                            "quantity": 2
                        })
                    },
                    {
                        "content_type": "text",
                        "title": "3",
                        "payload": str({
                            "description": payload,
                            "quantity": 3
                        })
                    },
                    {
                        "content_type": "text",
                        "title": "4",
                        "payload": str({
                            "description": payload,
                            "quantity": 4
                        })
                    },
                    {
                        "content_type": "text",
                        "title": "5",
                        "payload": str({
                            "description": payload,
                            "quantity": 5
                        })
                    }
                ]
            }
        })
        return data

    def _confirm_order(self, sender_id, payload):
        payload = eval(payload)
        payload["confirmed"] = True
        data = json.dumps({
            "recipient": {
                "id": sender_id
            },
            "message": {
                "text": "Confirm order? This is final and will be recorded",
                "quick_replies": [
                    {
                        "content_type": "text",
                        "title": "Yes",
                        "payload": str(payload)
                    },
                    {
                        "content_type": "text",
                        "title": "No",
                        "payload": "No",
                    }
                ]
            }
        })
        return data
Пример #18
0
 def setUp(self):
     Database.clear_db()
     self.mapper = UserMapper()
Пример #19
0
class Logic(object):
    def __init__(self):
        self.user = UserMapper()
        self.processor = Processor()
        self.wit = client
        self.response = ResponseGenerator()

    def get_all_users(self):
        u = self.user.get_all_users()
        return u

    def parse_messaging_event(self, messaging_event):
        sender_id = messaging_event["sender"]["id"]
        recipient_id = messaging_event["recipient"]["id"]
        user = self.find_user(sender_id)
        if messaging_event.get("message"):  # someone sent us a message
            self.parse_message(user, messaging_event)

        # user clicked/tapped "postback" button in earlier message
        if messaging_event.get("postback"):
            self.response.welcome_message(user)

    def parse_message(self, user, messaging_event):
        if "quick_reply" in messaging_event["message"].keys():
            self.process_quick_reply(
                user, messaging_event["message"]["quick_reply"]["payload"])
        else:
            try:
                message_text = messaging_event["message"]["text"]
            except KeyError:
                self.response.send_like(user)
            else:
                if message_text.lower() == "anti jones":
                    self.check_user_authorization(user)
                else:
                    fn = self.process_with_wit(message_text)
                    fn(user)

    def check_user_authorization(self, user):
        if user.is_authorized:
            self.find_match(user)
        else:
            self.response.send_authorization(user)

    def find_match(self, user):
        gender = user.gender

        if gender == "male":
            u = self.generate_match(self.processor.get_match_for_male)
        elif gender == "female":
            u = self.generate_match(self.processor.get_match_for_female)
        else:
            u = self.generate_match(self.processor.get_match_for_others)

        if u:
            self.response.send_match(user, u)
        else:
            self.response.match_not_found(user)

    def generate_match(self, fn):
        try:
            u = fn()
        except IndexError as err:
            u = None
        return u

    def process_quick_reply(self, user, payload):
        if payload == "Yes":
            self.response.send_match_again(user)
            self.find_match(user)
        elif payload == "No":
            self.response.stop_send_match(user)
        elif payload == "Authorized":
            self.user.update_user_authorization(user.fb_id, True)
            self.response.send_match_again(user)
            self.find_match(user)
        elif payload == "gombal_lagi":
            self.response.gombal(user)
        elif payload == "gombal_stop":
            self.response.farewell(user)
        else:
            self.response.not_authorized(user)

    def find_user(self, fb_id):
        try:
            u = self.user.get_user_by_fb_id(fb_id)
        except ValueError as err:
            logging.error(err)
            first_name, last_name, gender, pic = self.response.get_user_data(
                fb_id)
            u = self.user.create_user(fb_id, first_name, last_name, gender)
        return u

    def process_with_wit(self, message):
        resp = self.wit.message(message)
        entity, value = self.parse_wit(resp)

        if entity == 'laugh':
            return self.response.laugh
        elif entity == 'thank':
            return self.response.thank
        elif entity == 'gombal':
            return self.response.gombal
        elif entity == 'intent':
            if value == "greeting":
                return self.response.greeting
            else:
                return self.response.farewell
        else:
            return self.response.command_not_found

    def parse_wit(self, resp):
        resp_entity = resp['entities']
        entities = ['thank', 'intent', 'gombal', 'laugh']
        best_entity = None
        best_accuracy = 0
        best_value = None
        for en in entities:
            if en in resp_entity:
                accuracy = resp_entity[en][0]['confidence']
                if accuracy >= 0.8 and accuracy >= best_accuracy:
                    best_entity = en
                    best_accuracy = accuracy
                    best_value = resp_entity[en][0]['value']
        return (best_entity, best_value)
Пример #20
0
 def __init__(self):
     self.user = UserMapper()
     self.processor = Processor()
     self.wit = client
     self.response = ResponseGenerator()
Пример #21
0
 def setUp(self):
     Database.clear_db()
     uMapper = UserMapper()
     self.u = uMapper.create_user("123")
     self.mapper = OrderMapper()
Пример #22
0
    def setUp(self):
        Database.clear_db()
        self.processor = Processor()

        mapper = UserMapper()
        male1 = mapper.create_user("123", "M", "K", "male")
        male2 = mapper.create_user("123", "M", "K", "male")
        male3 = mapper.create_user("123", "M", "K", "male")

        female1 = mapper.create_user("123", "M", "K", "female")
        female2 = mapper.create_user("123", "M", "K", "female")
        female3 = mapper.create_user("123", "M", "K", "female")

        other1 = mapper.create_user("123", "M", "K", "gay")
        other2 = mapper.create_user("123", "M", "K", "gay")
        other3 = mapper.create_user("123", "M", "K", "gay")

        self.males = mapper.get_all_males()
        self.females = mapper.get_all_females()
        self.others = mapper.get_other_genders()