def setUp(self):
        super().setUp()
        self.user1_id = 1
        self.user2_id = 2
        self.user3_id = 3
        trans1 = Transaction(
            user_id=self.user1_id,
            ticket_amount=500,
            activity="Transaction Test",
        )
        trans2 = Transaction(
            user_id=self.user2_id,
            ticket_amount=400,
            activity="Transaction Test",
        )
        with self.app.app_context():
            db.session.add(trans1)
            db.session.add(trans2)
            db.session.commit()

        self.blackjack_play_success = {
            KEY_SUCCESS: True,
            KEY_MESSAGE: "Welcome to Blackjack!",
        }
        self.blackjack_play_bad_user = {
            KEY_ERROR: "User not logged in",
        }
        self.blackjack_play_bad_funds = {
            KEY_SUCCESS: False,
            KEY_MESSAGE: "Client needs at least 500 tickets to play.",
        }
Beispiel #2
0
def transfer_tickets():
    try:
        current_user = get_current_user()

        balance = get_user_balance(current_user.id)

        data = json.loads(request.data)
        recipient_id = data["to"]
        amount = data["amount"]

        error = None

        recipient = User.query.filter_by(id=recipient_id).first()

        if amount <= 0:
            error = "You can't transfer non-positive number of tickets"

        if balance < amount:
            error = "Insufficient balance"

        if recipient_id == current_user.id:
            error = "You can't send points to yourself"

        if recipient is None:
            error = "Recipient does not exist"

        if error is not None:
            return {"error": error}, 400

        subtract_balance = Transaction(
            user_id=current_user.id,
            ticket_amount=-1 * amount,
            activity=f"Transfer to {recipient.name}",
        )
        add_balance = Transaction(
            user_id=recipient_id,
            ticket_amount=amount,
            activity=f"Transfer from {current_user.name}",
        )

        db.session.add(subtract_balance)
        db.session.add(add_balance)
        db.session.commit()

        return {"success": True, "user_id": recipient.id, "amount": amount}

    except json.decoder.JSONDecodeError:
        return {"error": "Malformed request"}, 400
Beispiel #3
0
 def setUp(self):
     super().setUp()
     self.user1_id = 1
     trans1 = Transaction(
         user_id=self.user1_id,
         ticket_amount=500,
         activity="Transaction Test",
     )
     blackjack1 = Blackjack(
         user_id=self.user1_id,
         deck="[1, 2, 3, 4, 5]",
         player_hand="[1, 2]",
         dealer_hand="[1, 2]",
     )
     with self.app.app_context():
         db.session.add(blackjack1)
         db.session.add(trans1)
         db.session.commit()
     self.blackjack_again_success = {
         KEY_SUCCESS: True,
         KEY_BLACKJACK: False,
         KEY_DEALER: ["2", "H"],
         KEY_PLAYER: ["3", "C", "5", "D"],
     }
     self.blackjack_again_error = {"error": "Malformed request"}
Beispiel #4
0
def payment_complete():
    payload = request.get_data()
    event_data = json.loads(request.data)
    sig_header = request.headers.get("STRIPE_SIGNATURE")

    data = event_data["data"]
    event_object = data["object"]
    amount = event_object["amount"]
    email = event_object["receipt_email"]

    item = list(filter(lambda item: round(item["price"] * 100) == amount, ITEMS))[0]
    tickets = item["tickets"]

    try:
        if (
            os.getenv("DEBUG", "").lower() != "true"
        ):  # Skip signiture check on debug mode
            stripe.Webhook.construct_event(payload, sig_header, STRIPE_ENDPOINT_SECRET)
    except ValueError:
        # invalid payload
        return "Invalid payload", 400
    except stripe.error.SignatureVerificationError:
        # invalid signature
        return "Invalid signature", 400

    user = User.query.filter_by(email=email).first()
    if user is not None:
        transaction = Transaction(
            user_id=user.id, ticket_amount=tickets, activity="Ticket purchase"
        )
        db.session.add(transaction)
        db.session.commit()

    return {"success": True}
Beispiel #5
0
def blackjack_transaction(amount):
    transaction = Transaction(
        user_id=session["user_id"],
        ticket_amount=amount,
        activity="blackjack",
    )
    db.session.add(transaction)
    db.session.commit()
    def test_non_empty_transaction_history(self):
        with self.app.app_context():
            transaction = Transaction(user_id=self.user_id,
                                      ticket_amount=1,
                                      activity="test")
            db.session.add(transaction)
            db.session.commit()

        with self.client.session_transaction() as sess:
            sess["user_id"] = "1"
        res = self.client.get("/api/ticket/history")
Beispiel #7
0
    def setUp(self):
        super().setUp()
        self.user_id = 1
        user = User(id=self.user_id, name="User", email="*****@*****.**")

        with self.app.app_context():
            db.session.add(user)
            transaction = Transaction(user=user,
                                      ticket_amount=1000,
                                      activity="Coinflip Test Initial Balance")
            db.session.add(transaction)
            db.session.commit()
    def setUp(self):
        super().setUp()
        self.user1_id = 1
        self.user2_id = 2
        self.user3_id = 3
        trans1 = Transaction(
            user_id=self.user1_id,
            ticket_amount=-500,
            activity="blackjack",
        )
        blackjack1 = Blackjack(
            user_id=self.user1_id,
            deck="[0, 1, 2]",
            player_hand="[0, 12]",
            dealer_hand="[9, 5]",
        )
        blackjack2 = Blackjack(
            user_id=self.user2_id,
            deck="[6, 2 , 3]",
            player_hand="[0, 12]",
            dealer_hand="[6, 6]",
        )
        blackjack3 = Blackjack(
            user_id=self.user3_id,
            deck="[6, 6]",
            player_hand="[12, 12]",
            dealer_hand="[6, 6]",
        )
        with self.app.app_context():
            db.session.add(trans1)
            db.session.add(blackjack1)
            db.session.add(blackjack2)
            db.session.add(blackjack3)
            db.session.commit()

        self.blackjack_stand_win = {
            KEY_SUCCESS: True,
            KEY_WINNER: KEY_PLAYER,
            KEY_DEALER: ["0", "H", "6", "H", "A", "D", "2", "H"],
            KEY_PLAYER: ["A", "D", "K", "D"],
        }
        self.blackjack_stand_tie = {
            KEY_SUCCESS: True,
            KEY_WINNER: KEY_NONE,
            KEY_DEALER: ["7", "C", "7", "C", "7", "C"],
            KEY_PLAYER: ["A", "D", "K", "D"],
        }
        self.blackjack_stand_lose = {
            KEY_SUCCESS: True,
            KEY_WINNER: KEY_DEALER,
            KEY_DEALER: ["7", "C", "7", "C", "7", "C"],
            KEY_PLAYER: ["K", "D", "K", "D"],
        }
Beispiel #9
0
    def test_fail_coinflip(self):
        with self.app.test_request_context():
            with self.client.session_transaction() as sess:
                sess["user_id"] = self.user_id

            user = get_user_by_id(self.user_id)

            transaction = Transaction(user=user,
                                      ticket_amount=-1000,
                                      activity="Make balance 0")
            db.session.add(transaction)
            db.session.commit()

            response = self.client.post(COINFLIP_ENDPOINT)

            self.assertIn("error", response.json)
Beispiel #10
0
def make_purchase(user_id, item_type, quantity):
    item_info = Store.query.filter_by(id=item_type).first()
    transaction = Transaction(
        user_id=user_id,
        ticket_amount=-item_info.price,
        activity="ticketstore",
    )
    db.session.add(transaction)
    item_query = Item.query.filter_by(user_id=user_id,
                                      item_type=item_type).first()
    if item_query is None:
        item = Item(
            item_type=item_type,
            item_group=item_info.item_group,
            user_id=user_id,
        )
        db.session.add(item)
    else:
        item_query.count = item_query.count + quantity
    db.session.commit()
    def setUp(self):
        super().setUp()
        self.sender_id = 1
        sender = User(id=self.sender_id,
                      name="Sender",
                      email="*****@*****.**")
        self.receiver_id = 2
        receiver = User(id=self.receiver_id,
                        name="Receiver",
                        email="*****@*****.**")

        with self.app.app_context():
            db.session.add(sender)
            db.session.add(receiver)
            transaction = Transaction(
                user=sender,
                ticket_amount=1000,
                activity="Transfer Test Initial Balance",
            )
            db.session.add(transaction)
            db.session.commit()
    def setUp(self):
        super().setUp()
        self.user1_id = 1
        trans1 = Transaction(
            user_id=self.user1_id,
            ticket_amount=KEY_TICKET_AMOUNT,
            activity="Transaction Test",
        )
        with self.app.app_context():
            db.session.add(trans1)
            db.session.commit()

        self.blackjack_checkfunds_success = {
            KEY_SUCCESS: True,
        }
        self.blackjack_checkfunds_bad = {
            KEY_SUCCESS: False,
            KEY_MESSAGE:
            "You are wagering more tickets than you currently have",
        }
        self.blackjack_checkfunds_error = {"error": "Malformed request"}
    def setUp(self):
        super().setUp()
        self.user1_id = 1
        self.user2_id = 2
        trans1 = Transaction(
            user_id=self.user1_id,
            ticket_amount=500,
            activity="Transaction Test",
        )
        blackjack1 = Blackjack(user_id=self.user1_id,
                               deck="[]",
                               player_hand="[]",
                               dealer_hand="[]")
        with self.app.app_context():
            db.session.add(blackjack1)
            db.session.add(trans1)
            db.session.commit()

        self.blackjack_start_old_success = {
            KEY_SUCCESS: True,
            KEY_BLACKJACK: False,
            KEY_DEALER: ["2", "H"],
            KEY_PLAYER: ["3", "C", "5", "D"],
        }
        self.blackjack_start_new_success = {
            KEY_SUCCESS: True,
            KEY_BLACKJACK: True,
            KEY_DEALER: ["2", "H"],
            KEY_PLAYER: ["A", "D", "Q", "S"],
        }
        self.blackjack_bad_api_success = {
            KEY_SUCCESS: True,
            KEY_BLACKJACK: False,
            KEY_DEALER: ["A", "D"],
            KEY_PLAYER: ["2", "H", "4", "S"],
        }
        self.blackjack_start_error = {"error": "Malformed request"}
Beispiel #14
0
def all_transactions():
    if request.method == 'POST':
        in_transaction = request.get_json()
        try:
            p = Product.query.get(in_transaction['product_id'])
            sl = StockLocation.query.get(in_transaction['stock_nr'])
        except KeyError:
            abort(500)

        if (p == None) or (sl == None):
            return jsonify({
                'code': 422,
                'text': 'Invalid data',
                'valid': {
                    'product_id': (p != None),
                    'stock_nr': (sl != None)
                }
            })

        try:
            t = Transaction(product=p,
                            stock_location=sl,
                            quantity=in_transaction['quantity'],
                            inbound=in_transaction['inbound'])
        except KeyError:
            abort(500)

        db.session.add(t)
        try:
            db.session.commit()
            return jsonify({'code': 200, 'text': 'OK', 'content': t.serialize})
        except IntegrityError:
            db.session.rollback()
            abort(500)
    else:
        ts = Transaction.query.all()
        return jsonify([t.serialize for t in ts])
Beispiel #15
0
def create_transaction(account_id, payment_id):
    """
        Add transaction to payment by ID

        :param account_id: Account id
        :type account_id: uuid
        :param payment_id: Id of the payment to be associated
        :type payment_id: uuid

        :rtype: dict | bytes (Transaction details)
    """

    code = HTTPStatus.CREATED
    msg = Message()

    account = Account.query.filter_by(id=account_id).first()

    if account:
        
        if account.state:
            try:
                amount = request.json.get('amount')
                reference = request.json.get('reference')

                # Check if missing arguments
                if not amount or not reference:
                    code = HTTPStatus.BAD_REQUEST
                    response = {
                        'status': 'fail',
                        'message': "The amount or reference values is missing"
                    }
                    return msg.message(code, response)

                payment = Payment.query.get(payment_id)

                # Check if payments exists
                if not payment:
                    code = HTTPStatus.NOT_FOUND
                    response = {
                        'status': 'fail',
                        'message': "Payment not found"
                    }
                    return msg.message(code, response)

            except Exception as excep:
                return msg.message(code, str(excep))

            # Create a transaction
            transaction = Transaction(amount, payment_id, reference)
            transaction.save_to_db()

            payment.amount += amount

            response = {
                'status': 'success',
                'id': transaction.id
            }                
        else:
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'Your number account is desactivated.'
            }  
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': 'Try Again.'
        }

    return msg.message(code, response)
Beispiel #16
0
    except User.DoesNotExist, Lock.DoesNotExist:
        try_compare = False

    if (try_compare):
        if str(requested_lock.id) in user.access_locks.split(","):
            # Only lock if door is unlocked
            if (requested_lock.state == Lock.UNLOCKED):
                lock_lock()
                requested_lock.state = Lock.LOCKED
                requested_lock.save()
            lock = True
        else:
            lock = False

    transaction = Transaction(user=user,
                              lock=requested_lock,
                              success=lock,
                              access_type="lock")
    transaction.save()

    return JsonResponse({
        'lock_id': response_lock_id,
        'lock_success': lock_success,
        'lock': lock,
        'user_id': response_user_id,
        'user_success': user_success,
        'username': username
    })


def unlock_door(response):
    response_user_id = response.GET['userid']
Beispiel #17
0
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)

sl1 = StockLocation(city="Cupertino")
sl2 = StockLocation(city="Norrköping")
sl3 = StockLocation(city="Frankurt")


db.session.add(sl1)
db.session.add(sl2)
db.session.add(sl3)

db.session.commit()

t1 = Transaction(quantity=10000,stock_location=sl3,product=p1, inbound=True)
t2 = Transaction(quantity=5000,stock_location=sl2,product=p3, inbound=True)
t3 = Transaction(product=p1,stock_location=sl2,quantity=5000, inbound=True)
t4 = Transaction(product=p2,stock_location=sl1,quantity=40000, inbound=True)
t5 = Transaction(product=p2,stock_location=sl1,quantity=25000, inbound=False)
t6 = Transaction(product=p1,stock_location=sl2,quantity=3000, inbound=False)
t7 = Transaction(product=p3,stock_location=sl3,quantity=20000, inbound=True)
t8 = Transaction(product=p1,stock_location=sl1,quantity=45000, inbound=True)

# t = Transaction(product_id=10,stock_nr=1,quantity=45000, inbound=True)


db.session.add(t1)
db.session.add(t2)
db.session.add(t3)
db.session.add(t4)
Beispiel #18
0
 def setUp(self):
     super().setUp()
     self.user1_id = 1
     self.user2_id = 2
     self.user3_id = 3
     trans1 = Transaction (
         user_id=self.user1_id,
         ticket_amount=1500,
         activity="Transaction Test",
     )
     trans2 = Transaction (
         user_id=self.user2_id,
         ticket_amount=500,
         activity="Transaction Test",
     )
     store_item1 = Store (
         name="test item1",
         item_group=1,
         price=1000,
         limit=5,
     )
     store_item2 = Store (
         name="test item2",
         item_group=2,
         price=500,
         limit=1,
     )
     item1 = Item (
         item_type=1,
         item_group=1,
         user_id=self.user1_id,
         count=1,
         active=False
     )
     item2 = Item (
         item_type=2,
         item_group=2,
         user_id=self.user2_id,
         count=1,
         active=False
     )
     with self.app.app_context():
         db.session.add(trans1)
         db.session.add(trans2)
         db.session.add(store_item1)
         db.session.add(store_item2)
         db.session.add(item1)
         db.session.add(item2)
         db.session.commit()
     self.params_item1 = {
         KEY_ID: 1,
         KEY_QUANTITY: 1
     }
     self.buy_item_bad_funds = {
         KEY_SUCCESS: False,
         KEY_MESSAGE: "Insufficient funds"
     }
     self.buy_item_bad_item = {
         KEY_SUCCESS: False,
         KEY_MESSAGE: "Reached purchase limit"
     }
     self.params_item2 = {
         KEY_ID: 2,
         KEY_QUANTITY: 1
     }
     self.buy_item_params = [
     {
         KEY_USER_ID: self.user1_id,
         KEY_PARAMS: self.params_item1,
         KEY_AMOUNT: 500,
         KEY_EXPECTED: { KEY_SUCCESS: True }
     },
     {
         KEY_USER_ID: self.user1_id,
         KEY_PARAMS: self.params_item2,
         KEY_AMOUNT: 0,
         KEY_EXPECTED: { KEY_SUCCESS: True }
     },
     {
         KEY_USER_ID: self.user2_id,
         KEY_PARAMS: self.params_item1,
         KEY_AMOUNT: 500,
         KEY_EXPECTED: self.buy_item_bad_funds
     },
     {
         KEY_USER_ID: self.user3_id,
         KEY_PARAMS: self.params_item1,
         KEY_AMOUNT: None,
         KEY_EXPECTED: self.buy_item_bad_funds
     },
     {
         KEY_USER_ID: self.user2_id,
         KEY_PARAMS: self.params_item2,
         KEY_AMOUNT: 500,
         KEY_EXPECTED: self.buy_item_bad_item
     }]
     self.buy_item_error = {
         KEY_ERROR: "Malformed request"
     }