Beispiel #1
0
def transactions_post(**kwargs):
    obj = json.loads(request.data.decode('utf-8', 'strict'))
    # try:
    i = Transaction(
        time=datetime.datetime.strptime(obj['time'], '%Y-%m-%d').date(),
        account_id=int(obj['account.id']),
        sum=decimal.Decimal(strip_numbers(obj['sum'])),
        transfer=int(obj['transfer']) if int(obj['transfer']) > 0 else None,
        income_id=int(obj['income.id']) if int(obj['income.id']) > 0 else None,
        comment=obj['comment']
    )
    DB.add(i)
    DB.flush()
    if 'new_account.id' in obj:
        transfer = Transaction(
          time=datetime.datetime.strptime(obj['time'], '%Y-%m-%d').date(),
          account_id=int(obj['new_account.id']),
          sum=decimal.Decimal(strip_numbers(obj['new_sum'])),
          transfer=int(obj['transfer']) if int(obj['transfer']) > 0 else None,
          comment=obj['comment'],
          income_id=int(obj['income.id']) if int(obj['income.id']) > 0 else None
        )
        DB.add(transfer)
        DB.flush()
        i.transfer = transfer.record_id
        transfer.transfer = i.record_id
    DB.commit()
    # except:
    #    abort(400)
    return i
Beispiel #2
0
 def setUp(self):
     testuser = User(username='******', email='*****@*****.**')
     testuser.save()
     self.testuser = testuser
     User(username='******', email='*****@*****.**', admin=True).save()
     testpayment = Transaction(diff=1000, user=testuser)
     testpayment.save()
     testexpense = Transaction(diff=-500)
     testexpense.save()
     testcons = Consumption(units=1, price_per_unit=50, user=testuser)
     testcons.save()
     self.app = coffee.app.test_client()
Beispiel #3
0
    def test_got_question_twice(self):
        transaction = Transaction(bid_id_old=42,
                                  bid_created_at=self.user.created_at,
                                  buyer_user_id=self.user.id,
                                  seller_user_id=self.another_user.id,
                                  value_satoshi=100,
                                  coinbase_order="unknown",
                                  status="wait_for_question")
        email = Email(to_user_id=self.user.id, purpose="ask")
        transaction.active_emails.append(email)
        db.session.add(transaction)
        db.session.commit()

        from_email = self.user.address_hash + "@example.com"
        self.responder.process_email(from_email,
                                     "Hash: %s ..." % (email.email_hash),
                                     "Some question?\n%s" % (from_email))

        db.session.refresh(transaction)
        db.session.refresh(self.user)

        self.assertEqual(len(self.user.active_emails),
                         1)  # We still have verification left
        self.trader.question_asked.assert_called_with(self.user, transaction,
                                                      "Some question?")
Beispiel #4
0
    def handle_all_callback(self, bot, update):
        print("1. Received: " + str(datetime.datetime.now().time()))
        counter.Counter.add_count()
        try:
            cbq = update.callback_query
            data = cbq.data

            if data is None:
                return cbq.answer()

            conn = self.db.get_connection()
            with Transaction(conn) as trans:
                user = update.callback_query.from_user
                trans.add_user(user.id, user.first_name, user.last_name,
                               user.username)
                payload = json.loads(data)
                action_type = payload.get(const.JSON_ACTION_TYPE)
                action_id = payload.get(const.JSON_ACTION_ID)

                if action_type is None:
                    return cbq.answer('nothing')
                print("1.1. Find handler: " +
                      str(datetime.datetime.now().time()))
                handler = self.get_action_handler(action_type)
                print("2. Dispatched: " + str(datetime.datetime.now().time()))
                return handler.execute(bot, update, trans, action_id, 0,
                                       payload)
        except Exception as e:
            logging.exception('handle_all_callback')
Beispiel #5
0
def submit_payment():
    pform = PaymentForm()
    pform.uid.choices = User.get_uids()
    if not pform.validate_on_submit():
        flash('Payment invalid.')
        return redirect(url_for('coffee.admin'))

    uid = pform.uid.data
    # prevent inaccurate input parsing (see
    # https://docs.python.org/3.6/tutorial/floatingpoint.html)
    amount = int(round(float(pform.amount.data) * 100))
    user = User.objects.get(id=uid)
    transaction = Transaction(user=user,
                              diff=amount,
                              description='{} payment from {}'.format(
                                  euros(amount), user.name))
    transaction.save()
    if user.email:
        msg = EmailMessage()
        msg['Subject'] = f'[Kaffeeministerium] Einzahlung von {euros(amount)}'
        msg['From'] = app.config['MAIL_DEFAULT_SENDER']
        msg['To'] = user.email
        msg.set_content(
            render_template('mail/payment',
                            amount=amount,
                            balance=user.balance,
                            minister_name=app.config['MAIL_MINISTER_NAME']))
        flash('Mail sent to user {}'.format(user.name))
        if not app.config['DEBUG']:
            s = getMailServer()
            s.send_message(msg)
        else:
            print(u'Sending mail \n{}'.format(msg.as_string()))

    return redirect(url_for('coffee.admin'))
Beispiel #6
0
 def new_transaction_db(self,
                        time_stamp,
                        product_serial_number,
                        product_name,
                        product_price,
                        tran_type,
                        manufacturer_seller_id,
                        manufacturer_seller_name,
                        manufacturer_seller_address,
                        manufacturer_seller_licence_number,
                        Status="Pending"):
     session = self.session_factory()
     tran = Transaction(
         time_stamp=time_stamp,
         product_serial_number=product_serial_number,
         product_name=product_name,
         product_price=product_price,
         type=tran_type,
         manufacturer_seller_id=manufacturer_seller_id,
         manufacturer_seller_name=manufacturer_seller_name,
         manufacturer_seller_address=manufacturer_seller_address,
         manufacturer_seller_licence_number=
         manufacturer_seller_licence_number,
         Status=Status)
     session.add(tran)
     session.commit()
     latest_tran_id = session.query(Transaction).order_by(
         Transaction.transaction_id.desc()).first()
     '''
     tran_alert = Transaction_Alert(transaction_id = latest_tran_id.transaction_id, status = "Active")
     session.add(tran_alert)
     session.commit()
     '''
     session.close()
     return latest_tran_id
Beispiel #7
0
def backlogs_put(**kwargs):
    """
    actually insert transaction
    """
    obj = json.loads(request.data.decode('utf-8', 'strict'))
    origin_time = datetime.datetime.strptime(
            obj['origin_time'], '%Y-%m-%d').date()
    operation_time = datetime.datetime.strptime(obj['time'], '%Y-%m-%d').date()

    transaction = Transaction(
        time=operation_time,
        account_id=int(obj['account.id']),
        sum=strip_numbers(obj['sum']),
        income_id=obj['income.id'],
        comment=obj['comment'])
    DB.add(transaction)
    DB.flush()
    if origin_time != operation_time:
        # payment before
        DB.add(
            Payforward(
                income_id=int(obj['income.id']),
                income_date=origin_time,
                payment_date=operation_time,
                transaction_id=transaction.record_id
            )
        )
    DB.commit()
    return transaction
Beispiel #8
0
def submit_payment():
    pform = PaymentForm()
    pform.uid.choices = User.get_uids()
    if not pform.validate_on_submit():
        flash('Payment invalid.')
        return redirect(url_for('coffee.admin'))

    uid = pform.uid.data
    amount = float(pform.amount.data) * 100
    user = User.objects.get(id=uid)
    transaction = Transaction(user=user,
                              diff=amount,
                              description='{} payment from {}'.format(
                                  euros(amount), user.name))
    transaction.save()
    if user.email:
        msg = Message('[Kaffeeministerium] Einzahlung von {}'.format(
            euros(amount)))
        msg.charset = 'utf-8'
        msg.add_recipient(user.email)
        msg.body = render_template('mail/payment',
                                   amount=amount,
                                   balance=user.balance)
        flash('Mail sent to user {}'.format(user.name))
        if not app.config['DEBUG']:
            mail.send(msg)
        else:
            print(u'Sending mail \n{}'.format(msg.as_string()))

    return redirect(url_for('coffee.admin'))
def store_plaid_transactions(transactionsResponse):
    for transactionResponse in transactionsResponse:
        transactionEntity = Transaction(
            id=transactionResponse['transaction_id'],
            account_id=transactionResponse['account_id'],
            account_owner='Caleb Kumar',
            name=str(transactionResponse['name']),
            amount=transactionResponse['amount'],
            date=datetime.strptime(transactionResponse['date'], '%Y-%m-%d'),
            default_transaction_type=transactionResponse['transaction_type'],
            # TODO: Iterate over list of categories
            default_category1=str(transactionResponse['category']))
Beispiel #10
0
 def new_bill(self, bot, update):
     # only allow private message
     try:
         conn = self.db.get_connection()
         handler = self.get_action_handler(const.TYPE_CREATE_BILL)
         with Transaction(conn) as trans:
             handler.execute(bot,
                             update,
                             trans,
                             action_id=create_bill_handler.ACTION_NEW_BILL)
     except Exception as e:
         logging.exception('new_bill')
Beispiel #11
0
def backlogs_delete(**kwargs):
    # just create transaction with sum zero
    obj = json.loads(request.data.decode('utf-8', 'strict'))
    t = Transaction(
        time=datetime.datetime.strptime(obj['origin_time'], '%Y-%m-%d').date(),
        account_id=0,
        sum=0,
        income_id=obj['income.id'],
        comment='cancelled')
    DB.add(t)
    DB.flush()
    DB.commit()
    return t
Beispiel #12
0
def accounts_put(**kwargs):
    a = DB.query(Account).get(kwargs['id'])
    obj = json.loads(request.data.decode('utf-8', 'strict'))
    a.title = obj['title']
    a.show = obj['show']
    a.currency_id = obj['currency.id']
    delta_sum = decimal.Decimal(strip_numbers(obj['sum'])) - a.sum()
    if delta_sum != 0:
        t = Transaction(time=datetime.date.today(), sum=delta_sum,
                        account_id=kwargs['id'], comment='fix account summ')
        DB.add(t)
    DB.commit()
    return {'updated': DB.query(Account).get(kwargs['id']), "previous": a}
Beispiel #13
0
 def handle_inline(self, bot, update):
     try:
         conn = self.db.get_connection()
         handler = self.get_action_handler(const.TYPE_SHARE_BILL)
         with Transaction(conn) as trans:
             user = update.inline_query.from_user
             trans.add_user(user.id, user.first_name, user.last_name,
                            user.username)
             handler.execute(bot,
                             update,
                             trans,
                             action_id=share_bill_handler.ACTION_FIND_BILLS)
     except Exception as e:
         logging.exception('handle_inline')
Beispiel #14
0
 def start(self, bot, update, args):
     # TODO: make command list screen
     if args is not None and len(args) == 1:
         handler = manage_bill_handler.BillManagementHandler()
         conn = self.db.get_connection()
         data = {const.JSON_BILL_ID: args[0]}
         with Transaction(conn) as trans:
             handler.execute(bot,
                             update,
                             trans,
                             action_id=manage_bill_handler.ACTION_SEND_BILL,
                             data=data)
         return
     bot.sendMessage(chat_id=update.message.chat_id, text="Start screen")
Beispiel #15
0
def accounts_post(**kwargs):
    """ add new account and set first transaction with rests of money """
    obj = json.loads(request.data.decode('utf-8', 'strict'))
    new_account = Account(
            title=obj['title'],
            currency_id=int(obj['currency.id']))
    DB.add(new_account)
    DB.flush()
    if float(strip_numbers(obj['sum'])) > 0:
        DB.add(Transaction(account_id=new_account.record_id,
                           show=obj['show'],
                           comment='initial summ',
                           time=datetime.date.today(),
                           sum=strip_numbers(obj['sum'])))
    DB.commit()
    return new_account
Beispiel #16
0
 def start(self, bot, update, args):
     # TODO: make command list screen
     if args is not None and len(args) == 1:
         handler = manage_bill_handler.BillManagementHandler()
         conn = self.db.get_connection()
         data = {const.JSON_BILL_ID: args[0]}
         with Transaction(conn) as trans:
             msg = update.message
             trans.reset_session(msg.chat_id, msg.from_user.id)
             handler.execute(bot,
                             update,
                             trans,
                             action_id=manage_bill_handler.ACTION_SEND_BILL,
                             data=data)
         return
     self.send_help_msg(bot, update)
Beispiel #17
0
def administrate_expenses():
    eform = ExpenseForm()
    if not eform.validate_on_submit():
        for field, errors in eform.errors.items():
            for error in errors:
                flash(u'Error in the %s field - %s' %
                      (getattr(eform, field).label.text, error))
        return redirect(url_for('coffee.admin'))

    description = eform.description.data
    amount = eform.amount.data
    date = (eform.date.data if eform.date.data != '' else datetime.utcnow())
    t = Transaction(diff=100 * amount, date=date, description=description)
    t.save()
    flash('Transaction stored.')
    return redirect(url_for('coffee.admin'))
Beispiel #18
0
 def test_result_email(self):
     transaction = Transaction(bid_id_old=42,
                               bid_created_at=self.user.created_at,
                               buyer_user_id=self.user.id,
                               seller_user_id=self.another_user.id,
                               value_satoshi=100,
                               coinbase_order="unknown",
                               status="success")
     db.session.add(transaction)
     db.session.commit()
     self.sender.send_result_email(transaction, "42")
     self.assertEqual(len(self.user.active_emails), 0)
     self.assertEqual(len(self.another_user.active_emails), 0)
     self.assertEqual(len(self.sender._send_email.call_args_list), 1)
     args, kwargs = self.sender._send_email.call_args
     self.assertIn("42", args[-1])
     self.assertEqual(args[0], self.user)
Beispiel #19
0
 def done(self, bot, update):
     try:
         conn = self.db.get_connection()
         with Transaction(conn) as trans:
             msg = update.message
             user = msg.from_user
             trans.add_user(user.id, user.first_name, user.last_name,
                            user.username)
             act_type, act_id, subact_id, data = trans.get_session(
                 msg.chat_id,
                 msg.from_user.id,
             )
             handler = self.get_action_handler(act_type)
             return handler.execute_done(bot, update, trans, act_id,
                                         subact_id, data)
     except Exception as e:
         logging.exception('done')
Beispiel #20
0
def administrate_expenses():
    eform = ExpenseForm()
    if not eform.validate_on_submit():
        for field, errors in eform.errors.items():
            for error in errors:
                flash(u'Error in the %s field - %s' %
                      (getattr(eform, field).label.text, error))
        return redirect(url_for('coffee.admin'))

    description = eform.description.data
    # prevent inaccurate input parsing (see
    # https://docs.python.org/3.6/tutorial/floatingpoint.html)
    amount = int(round(float(eform.amount.data * 100)))
    date = (eform.date.data if eform.date.data != '' else datetime.utcnow())
    t = Transaction(diff=amount, date=date, description=description)
    t.save()
    flash('Transaction stored.')
    return redirect(url_for('coffee.admin'))
Beispiel #21
0
 def test_question_email(self):
     transaction = Transaction(bid_id_old=42,
                               bid_created_at=self.user.created_at,
                               buyer_user_id=self.user.id,
                               seller_user_id=self.another_user.id,
                               value_satoshi=100,
                               coinbase_order="unknown",
                               status="wait_for_question")
     db.session.add(transaction)
     db.session.commit()
     self.sender.send_question_email(transaction)
     self.assertEqual(len(self.user.active_emails), 1)
     self.assertEqual(len(self.another_user.active_emails), 0)
     self.assertEqual(len(self.sender._send_email.call_args_list), 1)
     email = self.user.active_emails[0]
     args, kwargs = self.sender._send_email.call_args
     self.assertIn(email.email_hash, args[-1])
     self.assertEqual(args[0], self.user)
     self.assertEqual(email.transaction_id, transaction.id)
Beispiel #22
0
def create_transaction(db: Session, transaction: TransactionBase):

    from_acc = db.query(Account).filter(
        Account.id == transaction.from_account).first()
    to_acc = db.query(Account).filter(
        Account.id == transaction.to_account).first()

    from_acc.balance -= transaction.amount
    to_acc.balance += transaction.amount
    db_transaction = Transaction(
        from_user_id=from_acc.user_id,
        to_user_id=to_acc.user_id,
        from_account_id=transaction.from_account,
        to_account_id=transaction.to_account,
        amount=transaction.amount,
    )

    db.add(db_transaction)
    db.commit()
    db.refresh(db_transaction)
    return db_transaction
Beispiel #23
0
 def handle_all_msg(self, bot, update):
     try:
         if update.message.chat.type != PRIVATE_CHAT:
             return
         conn = self.db.get_connection()
         msg = update.message
         with Transaction(conn) as trans:
             try:
                 user = update.message.from_user
                 trans.add_user(user.id, user.first_name, user.last_name,
                                user.username)
                 act_type, act_id, subact_id, data = trans.get_session(
                     msg.chat_id,
                     msg.from_user.id,
                 )
                 handler = self.get_action_handler(act_type)
                 return handler.execute(bot, update, trans, act_id,
                                        subact_id, data)
             except Exception as e:
                 logging.exception('inner handle_all_msg')
     except Exception as e:
         logging.exception('handle_all_msg')
def deposit():
    email_id = request.json['email']
    amt = request.json['amt']
    acc = session.query(Account).filter(Account.user_id == email_id)
    count = acc.count()
    balance = 0
    acc_id = ""
    returnObj = {
        "status":
        "Failed. Transaction can't be made at this time. Please try again"
    }
    if count == 1:
        balance = acc.one().balance
        acc_id = acc.one().account_id
    if acc_id != "" and amt > 0:
        if balance + amt < 10000000:
            trans = Transaction(transaction_id=str(round(time.time())) +
                                "".join(random.choices(string.digits, k=6)),
                                account_id=acc_id,
                                amount=amt,
                                transaction_type="deposit")
            session.add(trans)
            session.commit()
            session.query(Account).filter(Account.account_id == acc_id).update(
                {"balance": balance + amt}, synchronize_session='evaluate')
            session.commit()
            returnObj = {"status": "Successfully deposited the amount"}
        else:
            returnObj = {
                "status":
                "Transaction unsuccessful. Balance exceeds $10million"
            }
    else:
        returnObj = {
            "status":
            "Failed. Account unavailable or Deposit amount is negative or zero. Expected positive value"
        }
    return jsonify(returnObj)
Beispiel #25
0
    def test_got_answer(self):
        transaction = Transaction(bid_id_old=42,
                                  bid_created_at=self.user.created_at,
                                  buyer_user_id=self.user.id,
                                  seller_user_id=self.another_user.id,
                                  value_satoshi=100,
                                  coinbase_order="unknown",
                                  status="wait_for_answer")
        email = Email(to_user_id=self.another_user.id, purpose="answer")
        transaction.active_emails.append(email)
        db.session.add(transaction)
        db.session.commit()

        self.responder.process_email(
            self.another_user.address_hash + "@example.com",
            "Hash: %s ..." % (email.email_hash), "Some answer")

        db.session.refresh(transaction)
        db.session.refresh(self.another_user)

        self.assertEqual(len(self.another_user.active_emails), 0)
        self.trader.question_answered.assert_called_with(
            self.another_user, transaction, "Some answer")
def store_transactions(transactionList):
    """

    :param transactionList: List of transactions where transactions are dictionary of item key to val
    :return: void
    """
    transactionEntities = []
    for transactionDict in transactionList:
        transactionEntity = Transaction(
            # Required Fields
            id=unicode(str(uuid4())),  # Generate this
            account_owner='Caleb Kumar',  # Hardcode
            name=str(transactionDict['name']),  # Required
            amount=transactionDict['amount'],  # Required
            date=datetime.strptime(transactionDict['date'], '%Y-%m-%d'),

            # Optional Fields
            transaction_type=str(transactionDict['transaction_type']),
            primary_category=str(transactionDict['primary_category']),
            secondary_category=str(transactionDict['secondary_category']))

        transactionEntities.append(transactionEntity)

    return transactionEntities
Beispiel #27
0
def generate_accounts_and_transactions():
    db = Session()
    list_of_users = get_users(db)

    for _ in range(20):
        from_user = random.choice(list_of_users).id
        to_user = random.choice(list_of_users).id
        db_account = Account(
            name=random.choice(names_pull),
            balance=random.randint(10000, 1000000000),
            currency=random.choice(currencies),
            user_id=from_user,
            type=random.randint(1, 3),
            interest=random.random() * 10,
        )

        db_account2 = Account(
            name=random.choice(names_pull),
            balance=random.randint(10000, 1000000000),
            currency=random.choice(currencies),
            user_id=to_user,
            type=random.randint(1, 3),
            interest=random.random() * 10,
        )

        db.add(db_account)
        db.add(db_account2)
        db.commit()
        db.refresh(db_account)
        db.refresh(db_account2)

        db_transaction = Transaction(
            from_user_id=from_user,
            to_user_id=to_user,
            from_account_id=db_account.id,
            to_account_id=db_account2.id,
            amount=random.randint(1, db_account.balance),
        )

        db.add(db_transaction)

    db.commit()

    for _ in range(2000):
        accounts = db.query(Account).all()

        first_acc = random.choice(accounts)
        second_acc = random.choice(accounts)

        from_user = first_acc.user_id
        to_user = second_acc.user_id

        db_transaction = Transaction(
            from_user_id=from_user,
            to_user_id=to_user,
            from_account_id=first_acc.id,
            to_account_id=second_acc.id,
            amount=random.randint(1, first_acc.balance),
            created_at=datetime.datetime(2019, random.randint(1, 12),
                                         random.randint(1, 27)),
        )
        db.add(db_transaction)
        db.commit()
        db.refresh(db_transaction)
Beispiel #28
0
            print "reading block at %d" % f.tell()
            magic, size = struct.unpack("<LL", f.read(8))
            blkdata = f.read(size)
            blkmsg = msgs.Blockmsg.frombinary(blkdata)[0]
            yield blkmsg
        except struct.error:
            return


if __name__ == "__main__":
    import sys
    import time
    logging.basicConfig(format='%(name)s - %(message)s', level=logging.INFO)
    cmd = sys.argv[1]
    if cmd == "loadblocks":
        import debug
        blkfile = open(sys.argv[2], "r")
        try:
            blkfile.seek(int(sys.argv[3]))
        except IndexError:
            pass
        for blkmsg in read_blocks(blkfile):
            process_blockmsg(blkmsg)
            eventlet.sleep(0)
    if cmd == "bestblock":
        with Transaction("bestblock", flags=[database.DB.DB_READ_UNCOMMITTED]):
            blk = get_bestblock()
        print blk
        print time.ctime(blk.block.time)
        print "%d days ago" % ((time.time() - blk.block.time) / 60 / 60 / 24)