Example #1
0
def show(message, *args):
    if args[0] == "all":
        return join_columns(Transaction.select())

    usernames = [ _ for _ in args if _.startswith('@')]
    numbers = [_ for _ in args if is_int(_)]

    if not numbers and not usernames:
        return "See /usage for the help"

    query = Chat.id == message.chat.id

    if usernames:
        for username in usernames:
            username = username.upper()

            try:
                user = User.get(User.username == username)
            except:
                return "No such user %s" % username

            query &= (Transaction.creditor == user) | (Transaction.debtor == user)

    if numbers:
        N = int(numbers[0])
    else:
        N = 10

    return join_columns(Transaction.select().join(Chat).where(query).limit(N))
Example #2
0
def authenticate():
    GESTURES = ['FIST', 'LEFT', 'OPEN', 'RIGHT']

    gesture_one = None
    gesture_two = None
    gesture_three = None

    query = Transaction.delete()
    query.execute()

    secure_random = random.SystemRandom()

    while (gesture_one == gesture_two or gesture_two == gesture_three):
        gesture_one = secure_random.choice(GESTURES)
        gesture_two = secure_random.choice(GESTURES)
        gesture_three = secure_random.choice(GESTURES)

    transaction_id = 0
    transaction = Transaction.create(gesture_one=gesture_one,
                                     gesture_two=gesture_two,
                                     gesture_three=gesture_three,
                                     transaction_id=transaction_id)

    return jsonify(gesture_one=gesture_one,
                   gesture_two=gesture_two,
                   gesture_three=gesture_three,
                   transaction_id=transaction_id)
Example #3
0
def add_transaction():
    transaction_name = request.form.get('transaction_name')
    if transaction_name == 'Transaction Name':
        return redirect('/new_transaction')
    fields = [
        Field('field_0', 'name', 'string', False),
        Field('field_1', 'date', 'date', False),
        Field('field_2', 'cost', 'number', False)
    ]

    for k, v in request.form.items():
        try:
            if int(k.split('_')[-1]) > 2 and k.split('_')[0] != 'type':
                if v == '':
                    v = 'enter name'
                new_field = Field(k, v, request.form['type_{}'.format(k)],
                                  True)
                fields.append(new_field)
        except ValueError:
            pass
    payload = Transaction(transaction_name)
    for field in fields:
        payload.add_property(field.name, field.type)
    db.put('transaction_types', payload.to_json())
    return redirect('/types')
def scrub():
    if request.method == "POST":
        file = request.files["file"]
        if file:
            transactions = Transaction.from_csv_file(file)
            report = Transaction.transaction_report(transactions)
            return jsonify(**report)
Example #5
0
def create_transaction():
    ''' Creates a transaction for the user's shopping cart. Apparently, adding
    relations to transient transactions somehow automatically adds them to the
    current session. As we usually don't want to commit semi-complete
    transactions, DB modifications are prepent with session.rollback(). '''

    ta = Transaction()

    lending = session_or_empty('lend')
    buying = session_or_empty('buy')

    ta.group = session_or_empty('group')
    if ta.group == []:
        ta.group = 'int'

    for id in lending:
        item = Item.query.get(id)
        ta.lend[id] = Lend(item, lending[id])

    for id in buying:
        item = Item.query.get(id)
        ta.buy[id] = Buy(item, buying[id])

    ta.date_start = session_or_empty('date_start')
    ta.date_end = session_or_empty('date_end')
    ta.name = session_or_empty('name')
    ta.email = session_or_empty('email')
    ta.tel = session_or_empty('tel')

    g.ta = ta
Example #6
0
 def create(attributes_transaction: dict):
     try:
         new_transaction = Transaction(**attributes_transaction)
         new_transaction.save()
         return View.get_response(new_transaction)
     except BaseException:
         return None
Example #7
0
    def upload(self, name, file, source):
        try:
            acc = Account.get(name=name)
            balance_to_add = 0
            with open(file) as f:
                csv_f = xl.reader(f)
                next(csv_f)  # Skip filename line
                next(csv_f)  # Skip column headers
                for row in csv_f:
                    cleaned = lambda s: float(s[1:len(s)-4])
                    date = datetime.datetime.strptime(row[0], '%d/%m/%Y').strftime('%Y/%m/%d')
                    trans = Transaction(date=date,
                                        amount_in=cleaned(row[1]),
                                        fees=cleaned(row[2]),
                                        amount_out=cleaned(row[4]),
                                        source=source,
                                        account=acc)
                    trans.save()
                    balance_to_add += cleaned(row[4])
            acc.balance += balance_to_add
            acc.last_updated = datetime.datetime.now()
            acc.save()

            print('Successfully uploaded', file, 'to account', name)
            print('Added', '$' + str(balance_to_add), 'to account', name)
            print('New balance for account', name, 'is', '$' + str(acc.balance))
        except IOError as e:
            print('Error uploading', e)
Example #8
0
def pay(line):
    """Logic new payment"""
    msg = 0
    if len(line) > 4:
        actor = User.get_by_name(line[1])
        target = User.get_by_name(line[2])
        amount = line[3]
        note = ' '.join(line[4:])
        actor_card = CreditCard.get_by_user(actor)
        if actor_card:  # actor has a card
            if actor and target:  #both existed
                if actor != target:  #not paying self
                    amount = clean_amount(amount)
                    if amount:  #valid amount
                        t = Transaction(actor, target, amount, note)
                        t.save()
                    else:
                        msg = ERROR_MSG['INVLIAD_AMOUNT']
                else:
                    msg = ERROR_MSG['PAY_SELF']
            else:
                msg = ERROR_MSG['U_NOT_EXISTED']
        else:
            msg = ERROR_MSG['U_HAS_NO_CARD']

    else:
        msg = ERROR_MSG['INVALID_ARS']

    return msg
Example #9
0
    def post(self, id=None):
        '''
        Endpoint for creating a new transaction

        Creates a new Transaction record and updates the associated User
        record's balance
        '''
        parser = reqparse.RequestParser()
        parser.add_argument('netid',
                            location='json',
                            required=True,
                            type=validate_netid)
        parser.add_argument('amount', location='json', required=True, type=int)
        parser.add_argument('description', location='json', default='')

        args = parser.parse_args()

        transaction = Transaction(netid=args.netid,
                                  amount=args.amount,
                                  description=args.description)
        user = get_user(args.netid)
        user.balance += args.amount

        db.session.add(user)
        db.session.add(transaction)
        db.session.commit()
        return jsonify(transaction.serialize())
Example #10
0
def withdraw(acc_id):
    form = WithdrawForm()
    if request.method == 'POST':
        if form.validate_on_submit:
            amt = form.amt.data
            account = Account.query.filter_by(ws_acc_id=acc_id).first()
            x = int(account.ws_acct_balance)
            if (x < int(amt)):
                flash("Your Balance is not sufficient to withdraw !", "danger")
            else:
                account.ws_acct_balance = x - int(amt)
                db.session.commit()
                flash("Amount withdrawed successfully .", "success")

                transaction = Transaction(ws_acc_id=account.ws_acc_id,
                                          ws_cust_id=account.ws_cust_id,
                                          ws_amt=amt,
                                          ws_acct_type=account.ws_acct_type,
                                          ws_src_typ=None,
                                          ws_tgt_typ=None,
                                          cr_or_db='Debit')
                transaction.ws_trxn_date = datetime.now()
                transaction.description = '' + str(
                    amt) + ' debited from ' + str(
                        account.ws_acc_id) + ' account'
                db.session.add(transaction)
                db.session.commit()

                return render_template("withdraw.html",
                                       account=account,
                                       old_balance=x,
                                       get_accounts=True)

    return render_template("withdraw.html", title='Withdraw Amount', form=form)
Example #11
0
def add(message, creditor, debtor, amount, currency=None):
    chat, _ = Chat.get_or_create(id=message.chat.id)
    creditor, _ = User.get_or_create(username=creditor.upper())
    debtor, _ = User.get_or_create(username=debtor.upper())
    amount = Decimal(amount)
    original_amount = amount

    currency = check_currency(currency, chat.currency)

    if currency != chat.currency:
        amount = cr.convert(currency, chat.currency, amount)
    transaction = Transaction(
        chat=chat,
        transaction_id=uuid4(),
        transaction_type=TransactionType.DEBT.value,
        date=datetime.now(),
        debtor=debtor,
        creditor=creditor,
        amount=amount,
        currency=chat.currency,
        original_amount=original_amount,
        original_currency=currency
    )
    transaction.save()

    debt_graph = DebtGraph.load_graph(chat)
    debt_graph.add_debt(transaction)
    DebtGraph.save_graph(chat, debt_graph)

    return str(transaction)
Example #12
0
def transaction(request, start=False):
    """
        Start a transaction with Fermi
        @param request: request object
        @param start: if True, a new transaction will be started if we didn't already have one
    """
    if start is not True:
        transID = request.session.get('fermi_transID', None)
        if transID is not None:
            transactions = Transaction.objects.filter(trans_id=transID)
            if len(transactions)>0:
                return transactions[0]
    try:
        conn = httplib.HTTPSConnection(settings.FERMI_HOST, timeout=0.5)
        conn.request('GET', settings.FERMI_BASE_URL+'transaction?Action=Start',
                            headers={'Cookie':request.session.get('fermi', '')})
        r = conn.getresponse()
        if not r.status == 200:
            logging.error("Fermi transaction call failed: %s" % r.status)
        info = json.loads(r.read())
        if "Err_Msg" in info:
            logging.error("MantidRemote: %s" % info["Err_Msg"])

        request.session['fermi_transID'] = info["TransID"]
        transaction_obj = Transaction(trans_id = info["TransID"],
                                  directory = info["Directory"],
                                  owner = request.user)
        transaction_obj.save()
        return transaction_obj
    except:
        logging.error("Could not get new transaction ID: %s" % sys.exc_value)
    return None
Example #13
0
def run_sim(d, scrip, a, amount, ledger):
    net_buys = 0
    for i in a:
        f = d.get_first(i)
        s = d.stocks.get(f)
        qty = int(float(amount) / float(s.high))
        net_buys += qty
        t0 = Transaction(scrip, BUY, s.date, s.high, qty)
        ledger.append(t0)
    a0 = d.get_last(a[-1])
    s0 = d.stocks.get(a0)
    t1 = Transaction(scrip, SELL, s0.date, s0.high, net_buys)
    ledger.append(t1)
    # for i in ledger:
    #     print( i.to_str(), i.tx_value())
    investment = sum(
        [float(x.price) * x.qty for x in ledger if x.action == BUY])

    sale = 0
    profit = 0
    roi = 0
    if not investment == 0:
        sale = sum(
            [float(x.price) * x.qty for x in ledger if x.action == SELL])
        profit = (sale - investment)
        roi = round((profit * 100) / investment, 2)
    #print( "Roi for {} months starting {} is {}".format( len(a) , a[0], round( roi,2)))
    scenario = Scenario(a[0], len(a), amount, profit, investment, ledger, roi)
    return scenario
Example #14
0
def add_transaction(user):
    wallets = user.wallets
    for wallet in wallets:
        print(wallet.id, wallet.name, wallet.balance)

    ch = int(input("Choose a Wallet ID: "))

    wallet = Wallet.get(Wallet.id == ch)
    is_expense = int(input("Choose Type:\n0. Income\n1.Expense"))

    if not is_expense:
        from_person = input("From Who: ")
    else:
        from_person = "None"

    tranx_name = input("Enter Purpose: ")
    amount = float(input("Enter Amount: "))
    comment = input("Any comments? \n")

    Transaction.create(owner=user,
                       wallet=wallet,
                       name=tranx_name,
                       amount=amount,
                       comment=comment,
                       from_person=from_person,
                       timestamp=datetime.now(),
                       is_expense=bool(is_expense))
Example #15
0
def dept_to_emp(plan_id):
    conn = mysql.connect()
    cursor = conn.cursor()
    query = 'SELECT * FROM plan WHERE id = %s'
    cursor.execute(query, plan_id)
    records = cursor.fetchall()
    funding_amount = records[0][2]
    source_fund_FK = records[0][7]

    query = 'SELECT token FROM department_lookup WHERE id = %s'
    cursor.execute(query, source_fund_FK)
    source_token = cursor.fetchall()[0][0]

    query = 'SELECT * FROM employee_plan WHERE ep_plan_FK = %s'
    cursor.execute(query, plan_id)
    records = cursor.fetchall()

    t = Transaction(cursor, conn)

    for row in records:
        query = 'SELECT token FROM employee WHERE id = %s'
        cursor.execute(query, row[0])
        dest_token = cursor.fetchall()[0][0]
        transfer = client.transfer(funding_amount, source_token, dest_token, dest_token_is_user=True)
        t.insert(source_token, dest_token, Transaction.current_time(transfer.created_time), funding_amount)

    conn.commit()
    conn.close()

    complete_employee_plan(plan_id)
    simulate_employee_plan(plan_id)
Example #16
0
def save_reset_pass():
    from lib.email2 import send_email
    from models import User
    from models import Transaction
    from models import TransactionType
    from sbb import application, db
    form = ResetPassordForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=request.form['email']).first()
        if user:
            user.password = User.hash_password(form.password.data)
            db.session.add(user)
            tr = Transaction(datetime.now(), None, 1)
            tr.transactionTypeId = TransactionType.query.filter_by(
                id=6).first().id
            db.session.add(tr)
            db.session.commit()
            html = 'Thank you! You have successfully reset your password.'
            subject = "Reset password"
            send_email(request.form['email'], subject, html,
                       application.config)
            flash('Thank you! You have successfully reset your password.')
        else:
            flash('No user found with specified email.', 'warning')
            return redirect(request.referrer)
    else:
        flash_errors(form)
        return redirect(request.referrer)
    return redirect('login')
    def add_transaction():
        body = request.get_json()
        item = body.get('item', None)
        price = body.get('price', None)
        buyer_id = body.get('buyer_id', None)
        borrower_id = body.get('borrower_id', None)
        group_id = body.get('group_id', None)

        # try:
        new_transaction = Transaction(item=item,
                                      price=price,
                                      buyer_id=buyer_id,
                                      borrower_id=borrower_id,
                                      group_id=group_id)
        new_transaction.insert()

        # except:
        #     abort(422)

        buyer = User.query.filter_by(id=buyer_id).one()

        #Updates the user debts
        if not group_id:
            price = (price / 2)
            update_individual_transaction(buyer_id, borrower_id, price)

        else:
            update_group_transaction(buyer_id, group_id, price)

        return jsonify({
            'success': True,
            'transaction': new_transaction.format()
        })
Example #18
0
    def save_all_mutations(self):
        mutations = self.mutations

        update = Update.get_or_none(Update.id == 1)
        last_asked_transaction_timestamp = update.last_transaction if update is not None else 0
        print(last_asked_transaction_timestamp)
        last_timestamp = last_asked_transaction_timestamp

        for mutation in mutations['mutationsList']['mutations'][::-1]:
            mutation = mutation['mutation']

            # Trim the mutation time so we won't bother with microsecond comparisons
            mutation_time = datetime.strptime(
                mutation['transactionTimestamp'],
                '%Y%m%d%H%M%S%f').replace(microsecond=0)
            timestamp = mutation_time.timestamp()

            if timestamp > last_asked_transaction_timestamp:

                last_timestamp = last_timestamp if last_timestamp > timestamp else timestamp
                is_debit = mutation['amount'] < 0
                amount = "{0:.2f}".format(
                    mutation['amount'] *
                    -1 if is_debit else mutation['amount'])

                Transaction.insert(
                    amount=amount,
                    is_debit=is_debit,
                    description=mutation['counterAccountName'],
                    time=mutation_time).on_conflict('ignore').execute()

        if update is not None:
            update.update(last_transaction=last_timestamp).execute()
        else:
            Update.create(last_transaction=last_timestamp)
Example #19
0
def deposite(acc_id):
    form = DepositeForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            amt = form.amt.data
            account = Account.query.filter_by(ws_acc_id=acc_id).first()
            x = int(account.ws_acct_balance)
            account.ws_acct_balance = x + int(amt)
            db.session.commit()
            flash("Amount deposited successfully", "success")

            transaction = Transaction(ws_acc_id=account.ws_acc_id,
                                      ws_cust_id=account.ws_cust_id,
                                      ws_amt=amt,
                                      ws_acct_type=account.ws_acct_type,
                                      ws_src_typ=None,
                                      ws_tgt_typ=None,
                                      cr_or_db='Credit')
            transaction.ws_trxn_date = datetime.now()
            transaction.description = '' + str(amt) + ' credited in ' + str(
                account.ws_acc_id) + ' account'
            db.session.add(transaction)
            db.session.commit()

            return render_template("deposite.html",
                                   account=account,
                                   old_balance=x,
                                   get_accounts=True)

    return render_template("deposite.html",
                           title='Deposite Amount',
                           form=form,
                           get_accounts=True)
Example #20
0
    def transaction_create(payload):
        body = request.get_json()
        new_drink_id = body.get('drink_id')
        new_quantity = body.get('quantity')
        new_created_at = body.get('created_at')

        # check input
        if new_drink_id is None or new_quantity is None or new_created_at is None:
            abort(400)
        drink = Drink.query.get(new_drink_id)
        if drink is None or drink.quantity < new_quantity:
            abort(400)

        t = datetime.datetime.strptime(new_created_at, "%Y-%m-%d")
        trans = Transaction(new_drink_id, new_quantity, t)
        trans.insert()

        drink.quantity -= new_quantity
        drink.update()

        return jsonify({
            'success': True,
            'transaction': trans.format(),
            'drink': drink.name
        })
Example #21
0
 def _fill_trans(self, line):
     trans = Transaction()
     trans.trans_counter = self._strip_zeroes(line, conf.TRANS_COUNTER.POS)
     trans.trans_sum = self._format_decimal(
         self._strip_zeroes(line, conf.TRANS_SUM.POS))
     trans.currency_code = self._strip_zeroes(line, conf.CURRENCY_CODE.POS)
     self.trans_list.append(trans)
Example #22
0
    def test_model_transaction(self):
        "Test transaction model"
        contact_type = ContactType(name='test')
        contact_type.save()

        contact = Contact(name='test', contact_type=contact_type)
        contact.save()

        currency = Currency(code="GBP",
                            name="Pounds",
                            symbol="L",
                            is_default=True)
        currency.save()

        account = Account(
            name='test', owner=contact, balance_currency=currency)
        account.save()

        obj = Transaction(name='test',
                          account=account,
                          source=contact,
                          target=contact,
                          value=10,
                          value_currency=currency)
        obj.save()
        self.assertEquals('test', obj.name)
        self.assertNotEquals(obj.id, None)
        obj.delete()
Example #23
0
	def ask(self, transaction: Transaction):
		keyboard = []

		categories = self.expense_categories if transaction.is_debit else self.income_categories

		for category_row in categories:
			row = []

			if isinstance(category_row, list):
				for category in category_row:
					category_name = category_short = category

					if isinstance(category, dict):
						category_name = list(category.keys())[0]
						category_short = list(category.values())[0]['short_name']

					row.append(InlineKeyboardButton(
						text=category_short,
						callback_data=category_name
					))

			else:
				row.append(InlineKeyboardButton(
					text=category_row,
					callback_data=category_row
				))
			keyboard.append(row)

		# Check if the last keyboard row has more than 4 buttons
		#  if it is, add a new keyboard row.
		if len(keyboard[-1]) >= 4:
			keyboard.append([])

		# Add the stop emoji button to the last row
		keyboard[-1].append(InlineKeyboardButton(
			"❌",
			callback_data=self.keywords['ignore']
		))

		reply_markup = InlineKeyboardMarkup(keyboard)

		try:
			telegram_message = self.bot.bot.send_message(
				chat_id=self.chat_id,
				text=transaction.message_text,
				reply_markup=reply_markup,
				parse_mode='Markdown'
			)

			Message.insert(
				id=telegram_message.message_id,
				transaction_id=transaction.id
			).on_conflict('replace').execute()

			transaction.asked = True
			transaction.save()
		except TelegramError:
			traceback.print_exc()
			print('Something went wrong!')
def scrapeCard(br, session, cardID, cardSerial):
    #follows link to View Card Summary page for a particular card
    response1 = br.follow_link(url_regex=r"CardSummary.aspx\?card_id=" + cardID).read()
    #follows link to View Usage History page for a particular card
    response1 = br.follow_link(text_regex=r"View Usage History").read()
    br.select_form(name="aspnetForm")
    response1 = br.submit().read()
    br.select_form(name="aspnetForm")
    
    #transaction status either 'All' or 'Successful' or 'Failed Autoloads';
    #'All' includes every succesful transaction including failed (card didn't swipe or error)  
    br["ctl00$MainContent$ddlTransactionStatus"] = ["All"]

    br.submit()
    
    #wmata only started posting data in 2010, pulls all available months
    for year in xrange(2010, 2011+1):
        for month in xrange(1, 12+1):
            time_period = ("%d%02d" % (year, month))
            print "\t", time_period

            #opens link to 'print' version of usage page for easier extraction 
            br.open("https://smartrip.wmata.com/Card/CardUsageReport2.aspx?card_id=" +
                    cardID + "&period=M&month=" + time_period)
            response1 = br.follow_link(text_regex=r"Print Version").read()
           
            #extracts data from html table, writes to csv
            soup = BeautifulSoup.BeautifulSoup(response1)
            table = soup.find('table', {'class': 'reportTable'})
            if table is None:
                continue
            rows = table.findAll('tr')
            it = iter(rows)    
            try:
                while True:
                    cols = it.next().findAll('td')
                    if len(cols) == 0:
                        continue #ignore blank rows
                    rowspan = int(cols[0].get('rowspan', '1'))

                    parsedCols = [td.find(text=True) for td in cols]
                    (sequence, timestamp, description, operator, entry, exit) = parsedCols[0:6]

                    purses = []
                    purses.append(parsedCols[6:9])

                    if rowspan > 1:
                        for i in xrange(1, rowspan):
                            cols = it.next().findAll('td')
                            purses.append([td.find(text=True) for td in cols])

                    txn = Transaction(sequence, timestamp, description, operator, entry, exit, purses)
                    txn.card_id = cardID
                    txn.card_serial = cardSerial
                    session.add(txn)
            except StopIteration:
                pass

            session.commit()
Example #25
0
 def logout(self, **kwargs):
     if 'transaction_key' in self.session:
         try:
             Transaction2.get(Key(encoded=self.session['transaction_key'])).delete()
         except:
             Transaction.get(Key(encoded=self.session['transaction_key'])).delete()
     self.users.logout()
     self.redirect('/')
Example #26
0
 def get_balance(self, user_id):
     if current_user.status == 'ADVERTISER':
         Transaction.query(func.sum(adv_amount).label('adv_sum')).filter(advId=user_id)
         return adv_sum
     elif current_user.status == 'AFFILIATE':
         Transaction.query(func.sum(aff_amount).label('aff_sum')).filter(affId=user_id)
         return aff_sum
     return 0
Example #27
0
def purchase_product(product_id, buyer_id, quantity, price):
    Transaction.create(
        user_id=buyer_id,
        product_id=product_id,
        number=quantity,
        sell_date=datetime.now(),
        sell_price=price,
    )
Example #28
0
    def make_guess(self, request):
        """Guess a letter. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        if game.game_over:
            raise endpoints.BadRequestException(
                    'Game already over!')

        if game.game_cancelled:
            raise endpoints.BadRequestException(
                    'Game has been cancelled!')

        if len(request.guess) > 1:
            raise endpoints.BadRequestException(
                    'You can only guess one letter!')

        if not request.guess.isalpha():
            raise endpoints.BadRequestException(
                    'The guess must be a letter!')

        # Determine if guess is correct.  If so, update score
        score = Score.query(ancestor=game.key).get()
        if request.guess in game.game_word:
            msg = 'You guessed right. The game word does contain the letter '\
              + request.guess + '.'
            # find all correctly guess letters in the game word and
            # set those letters in the guess string
            for index, char in enumerate(game.game_word):
                if char == request.guess:
                    game.correct_guesses[index] = char
                    score.points += 1
        else:
            msg = 'Sorry, the game word does not contain the letter '\
              + request.guess + '.'
            game.hangman.append(STICK_MAN_PARTS[game.attempts_remaining-1])
            game.attempts_remaining -= 1
            game.incorrect_guesses.append(request.guess)

        if ''.join(game.correct_guesses) == game.game_word:
            game.game_over = True
            score.points += 30
            score.won = True
            msg = 'You win!'
        elif game.attempts_remaining < 1:
            game.game_over = True
            msg = msg + 'Sorry, Game over!'

        game.put()
        score.put()

        # Record the transaction
        trans = Transaction(date=datetime.today(),
                            game=game.key,
                            guess=request.guess,
                            result=msg)
        trans.put()

        return game.to_form(msg)
Example #29
0
    def get(self, client):
        # Get the transaction id, tx=blahblahblah
        trans_id = self.request.get("tx")

        # Confgure POST args
        args = {}
        # Specify the paypal command
        args["cmd"] ="_notify-synch"
        args["tx"] = trans_id
        args["at"] = settings.PAYPAL_PDT_KEY

        args = urllib.urlencode(args)

        try:
            # Do a post back to validate
            # the transaction data
            status = urlfetch.fetch(url = settings.PAYPAL_URL,
                                    method = urlfetch.POST,
                                    payload = args).content
        except:
          self.response.out.write("POST Failed")

        # Check for SUCCESS at the start of the response
        lines = status.split(' ')
        if lines[0] == 'SUCCESS':
            lines = line[1:]
            props = {}
            for line in lines:
                (key, value) = line.split('=')
                props[key] = value
            # Check other transaction details here like
            # payment_status etc..

            # TODO Update donation transaction in streetcodes

            client = Client.all().filter('shortCode =', props['item_number']).get()

            donor = Donor.all().filter('email =', props['email']).get()
            if donor is None:
                donor = Donor()
                donor.name = "%s %s" % (props['first'], props['last'])
                donor.email = props['email']
                donor.put()

            tx = Transaction(method='PayPal',
                             donor=donor,
                             client=client,
                             amount=props['amount'])
            tx.put()

            # redirect user to thank you screen "/client_short_code#thanks"
            self.response.out.write('<script> window.location = "/'+ client + '#thanks"; </script>')

            # DEBUG code
            # self.response.out.write("OK<br>")
            # self.response.out.write(urllib.unquote(status))
        else:
            self.response.out.write("Failed")
Example #30
0
def get_post_function(request,t_id,rf_id,amt=0.0,l_or_s_or_c=None,date_time=None):
	loan_balance = 0.0
	savings_balance = 0.0
	try:
		customer = Customer.objects.get(RfCard_id=rf_id)
		if int(l_or_s_or_c) == 0: #i.e loan

			loan_amt = float(customer.loanAmount) - float(amt)
			trans_type = 'Loan'
			customer.loanAmount = loan_amt
			customer.save()
			
		elif int(l_or_s_or_c) == 1: #i.e savings
			savings_balance = float(customer.savingsAmount) + float(amt)
			trans_type = 'Savings'
			customer.savingsAmount = savings_balance
			customer.save()
		
		elif int(l_or_s_or_c) == 2: #i.e collections
			collection_amt = float(customer.collectionAmount) - float(amt)
			trans_type = 'Collections'
			customer.collectionAmount = collection_amt
			customer.save()

		else:
			return HttpResponseForbidden("You do not have permission!!")
          
               
   		#random codes from online
		#random_number = User.objects.make_random_password(length=20, allowed_chars='123456789')

		#while User.objects.filter(userprofile__temp_password=random_number):
    		#	random_number = User.objects.make_random_password(length=10, allowed_chars='123456789')
		
			
		
               # key = hashlib.new(str(random.random()))
		trans_id_gen = random.randint(1,1000000000000)
            	#trans_id_gen = hashlib.new('TRANS'+str(key)).hexdigest()

               

		trans = Transaction(transaction_type=trans_type,paymentAmount = float(amt),terminal_id = t_id,transaction_id = trans_id_gen,RfCard_id =  rf_id,status=l_or_s_or_c, company=customer.company, customer_name=customer.name, collector_id = str(request.user.username))
		trans.save()
		#return HttpResponse('Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Loan Balance: GHS '+ str(customer.loanAmount)+'<br/>'+'Transaction Type: '+ trans_type+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>')
		#print 'blupay1'
                pwdBy = PoweredBy.objects.get(pk=1)
		if trans_type == 'Loan':
			return HttpResponse('<b>'+str(customer.company)+'</b></br></br>LOAN REPAYMENT RECEIPT<br/>***************************</br>'+'Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Loan Balance: GHS '+ str(customer.loanAmount)+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>'+'Timestamp: '+str(trans.date_created)+'<br/>***************************</br>Powered by <b>'+pwdBy.poweredByName+'&#0174;</b>')
			#return HttpResponseRedirect('https://dev.jallohenterprise.co.uk/visiontekconnect.php?userid=visiontek&password=12345&amount='+str(customer.loanAmount))
		elif trans_type == 'Savings':
			return HttpResponse('<b>'+str(customer.company)+'</b></br></br>SAVINGS RECEIPT<br/>***************************</br>'+'Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Savings Balance: GHS '+ str(customer.savingsAmount)+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>'+'Timestamp: '+str(trans.date_created)+'<br/>***************************</br>Powered by <b>'+pwdBy.poweredByName+'&#0174;</b>')
			#return HttpResponseRedirect('https://dev.jallohenterprise.co.uk/visiontekconnect.php?userid=visiontek&password=12345&amount='+str(customer.savingsAmount))
		else:
			return HttpResponse('<b>'+str(customer.company)+'</b></br></br>COLLECTION REPAYMENT RECEIPT<br/>***************************</br>'+'Name: '+str(customer.name)+'<br/>'+ 'Amount Paid: GHS '+str(trans.paymentAmount)+'<br/>'+ 'Collection Balance: GHS '+ str(customer.collectionAmount)+'<br/>'+'Transaction Id: '+str(trans_id_gen)+'<br/>'+'Timestamp: '+str(trans.date_created)+'<br/>***************************</br>Powered by <b>'+pwdBy.poweredByName+'&#0174;</b>')

	except Customer.DoesNotExist:	
		return HttpResponseForbidden("Forbidden!!, Customer does not exist!!")
Example #31
0
def create_transaction(client_id, recipient_number, amount):
    try:
        recipient = Bill.objects.get(number=recipient_number)
    except:
        return [recipient_number, amount]
    trans = Transaction()
    trans.create(client_id, recipient, amount)
    
    return trans.code
 def post(self):
     self.response.headers['Content-Type'] = 'application/json'
     jsonString = self.request.body          
     data = simplejson.loads(jsonString) #Decoding JSON
     transaction = Transaction()
     transaction.processTransaction(data)
     response = {'payRentSuccessNotice':'Congratulations, you have paid the rent!'}
     json_response= simplejson.dumps(response)
     return self.response.out.write(json_response)
Example #33
0
def create_transactions(db, source_wallet, target_wallet, amount, host):
    source_transaction = Transaction(wallet_id=source_wallet.id,
                                     amount=(-amount),
                                     ip=host)
    db.add(source_transaction)
    target_transaction = Transaction(wallet_id=target_wallet.id,
                                     amount=amount,
                                     ip=host)
    db.add(target_transaction)
Example #34
0
    def test_transaction_value_buy(self):
        t = Transaction(units=10, price=5, date=None)

        self.assertEqual(t.value(), 50)

        self.assertEqual(t.value(transaction_cost_base=5), 55)

        self.assertAlmostEqual(t.value(transaction_cost_base=5, transaction_cost_perc=0.10), 60)

        self.assertAlmostEqual(t.value(transaction_cost_perc=0.15), 57.5)
Example #35
0
    def test_transaction_value_sell(self):
        t = Transaction(units=-10, price=5, date=None)

        self.assertEqual(t.value(), -50)

        self.assertEqual(t.value(transaction_cost_base=5), -45)

        self.assertAlmostEqual(t.value(transaction_cost_base=5, transaction_cost_perc=0.10), -40)

        self.assertAlmostEqual(t.value(transaction_cost_perc=0.15), -42.5)
Example #36
0
def emit_create_transaction(task_id, user_tg_id, transactionType, actionType, transactionStatus, price):
    try:
        task = Task.query.filter_by(id=task_id).first()
        Transaction.create_transaction(task, user_tg_id, transactionType, actionType, transactionStatus, price)

        app.logger.info("emit_create_transaction")
    except Exception as e:
        app.logger.info("emit_create_transaction EXCEPTION traceback: {0}".format(traceback.format_exc()))

    return True
Example #37
0
    def post(self, request, format=None):
        data = json.loads(request.body)
        print('--------------------')
        print(data['fromAccountNumber'])
        print(data['toAccountNumber'])
        print(data['owner'])
        print(data['amount'])
        print(data['date'])
        print(data['pending'])
        print('--------------------')
        fromAccountNumber = data.get('fromAccountNumber', None)
        toAccountNumber = data.get('toAccountNumber', None)
        owner = data.get('owner', None)
        amount = data.get('amount', None)
        date = data.get('date', None)
        pending = data.get('pending', None)

        headers = {'Content-Type': 'application/json'}
        if (fromAccountNumber == None or toAccountNumber == None or owner == None \
                or amount == None or date == None or pending == None):
            return Response(
                {
                    'status': 'Not acceptable',
                    'message': 'Cannot find request parameters!'
                },
                headers=headers,
                status=status.HTTP_406_NOT_ACCEPTABLE)

        # validate the account information
        try:
            toAcct = AccountInfo.objects.get(owner=owner,
                                             accountNumber=toAccountNumber)
            # increase the amount in to-account
            toAcct.balance = toAcct.balance + amount
            toAcct.save()
            # generate one transaction record in the database
            trans = Transaction(fromAccountNumber=toAccountNumber, \
                                toAccountNumber=fromAccountNumber, owner=owner, date=date, \
                                pending=pending, amount=amount)
            trans.save()
            return Response(
                {
                    'status': 'Success',
                    'message': 'Your check has been deposited successfully!'
                },
                headers=headers,
                status=status.HTTP_200_OK)
        except AccountInfo.DoesNotExist:
            return Response(
                {
                    'status': 'Precondition invalid',
                    'message': 'Internal Error: cannot find to account!'
                },
                headers=headers,
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    def post(self):
        data = flatten_arguments(self.request.arguments)
        from models import Transaction, Invoice
        from pprint import pformat

        invoice_id = data.get('invoice')
        if invoice_id:
            invoice = Invoice.get_by_id(int(invoice_id, 10))

            txn = Transaction(invoice=invoice)
            txn.identifier = data.get('txn_id')
            txn.subscription_id = data.get("subscr_id")
            txn.transaction_type = data.get('txn_type')
            txn.currency = data.get('mc_currency')
            txn.amount = data.get('mc_gross', data.get('mc_amount3'))
            txn.data = pformat(data)
            txn.put()

            if self.verify(data):
                r = self.process(data, txn=txn, invoice=invoice)
            else:
                r = self.process_invalid(data, txn=txn, invoice=invoice)
            if r:
                self.write(r)
            else:
                self.write('Nothing to see here.')
        else:
            # error.  invoice id was not found.
            pass
Example #39
0
def close_order(request, pk):
    order = Kvant.objects.get(pk=pk)
    income = Transaction.objects.all()
    balances = Balance.objects.all()

    if request.method == "POST":

        if request.POST.get('save_button') is not None:

            errors = {}

            ord = Kvant.objects.get(pk=pk)

            balance = request.POST.get('balance_name', '')
            is_money = request.POST.get('is_money', None)

            if not balance:
                errors['balance'] = u"Оберіть касу"
            else:
                balance = Balance.objects.get(pk=balance)

            try:
                cost_repair = Decimal(
                    request.POST.get('cost_repair', '').strip())
            except:
                ValueError

            if ord.status != 'closed':
                ord.close_order()
                ord.save()
                if cost_repair != 0:
                    income = Transaction(balance=balance,
                                         debit=cost_repair,
                                         order_number=Kvant.objects.get(pk=pk),
                                         agent=ord.customer)
                    income.save()
                    balance.balance_debit(debit=income.debit)

            else:
                return HttpResponse('Замовлення вже закрите')

            return HttpResponse(
                '<script type="text/javascript">window.close(); window.parent.location.href = "/";</script>'
            )

        elif request.POST.get('cancel_button') is not None:
            return HttpResponse(
                '<script type="text/javascript">window.close(); window.parent.location.href = "/";</script>'
            )

    return render(request, 'close_order.html', {
        'order': order,
        'income': income,
        'balances': balances
    })
Example #40
0
    def make_guess(self, request):
        """Guess a letter. Returns a game state with message"""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)

        if game.game_over:
            raise endpoints.BadRequestException('Game already over!')

        if game.game_cancelled:
            raise endpoints.BadRequestException('Game has been cancelled!')

        if len(request.guess) > 1:
            raise endpoints.BadRequestException(
                'You can only guess one letter!')

        if not request.guess.isalpha():
            raise endpoints.BadRequestException('The guess must be a letter!')

        # Determine if guess is correct.  If so, update score
        score = Score.query(ancestor=game.key).get()
        if request.guess in game.game_word:
            msg = 'You guessed right. The game word does contain the letter '\
              + request.guess + '.'
            # find all correctly guess letters in the game word and
            # set those letters in the guess string
            for index, char in enumerate(game.game_word):
                if char == request.guess:
                    game.correct_guesses[index] = char
                    score.points += 1
        else:
            msg = 'Sorry, the game word does not contain the letter '\
              + request.guess + '.'
            game.hangman.append(STICK_MAN_PARTS[game.attempts_remaining - 1])
            game.attempts_remaining -= 1
            game.incorrect_guesses.append(request.guess)

        if ''.join(game.correct_guesses) == game.game_word:
            game.game_over = True
            score.points += 30
            score.won = True
            msg = 'You win!'
        elif game.attempts_remaining < 1:
            game.game_over = True
            msg = msg + 'Sorry, Game over!'

        game.put()
        score.put()

        # Record the transaction
        trans = Transaction(date=datetime.today(),
                            game=game.key,
                            guess=request.guess,
                            result=msg)
        trans.put()

        return game.to_form(msg)
Example #41
0
    def doWithdrawal(self):
        user = get_or_create_user()
        amount = float(self.request.get("withdraw_amount"))

        new_transaction = Transaction(type="withdraw", amount=amount)
        new_transaction.put()

        user.balance -= amount
        user.put()

        self.redirect('/')
Example #42
0
    def doDeposit(self):
        user = get_or_create_user()
        amount = float(self.request.get("deposit_amount"))

        new_transaction = Transaction(type="deposit", amount=amount)
        new_transaction.put()

        user.balance += amount
        user.put()

        self.redirect('/')
Example #43
0
def init_data():
    """
    Método para iniciar/resetear todos los ficheros
    """
    if(request_confirm(message = "Do you want to reset all the tables to the inital state [Y/N]?")):
        Account.init_table()
        Transaction.init_table()
        Category.init_table()
        Tag.init_table()
        print("-"*20,">>>  Todas las tablas han sido inicializadas", "-"*20, sep="\n")
    else:
        print("The tables initialization has been canceld")
Example #44
0
 def post(self):
    company = Company.query.get(request.form['company_id'])
    if company is None:
       return jsonify(message='Company does not exists')
    transaction = Transaction()
    transaction.company_id  = company.id
    transaction.type = request.form['type']
    transaction.amount = request.form['amount']
    transaction.date = request.form['date']
    db.session.add(transaction)
    db.session.commit()
    return jsonify(transaction.serialize)
Example #45
0
def deser_tx(f):
    if type(f) is not io.BytesIO:
        f = io.BytesIO(f)

    from models import Transaction, TxIn, TxOut

    tx = Transaction()
    tx.version = deser_uint32(f.read(4))
    tx.inputs = deser_vector(f, TxIn)
    tx.outputs = deser_vector(f, TxOut)
    tx.locktime = deser_uint32(f)
    return tx
Example #46
0
def logout():
    from sbb import db
    from models import Transaction
    from models import TransactionType
    trType = TransactionType.query.filter_by(id=2).first()
    logout_act = Transaction(date=datetime.now(), amount=None, status=1)
    logout_act.account = current_user.account
    logout_act.transactionType = trType
    db.session.add(logout_act)
    db.session.commit()
    logout_user()
    return redirect(url_for('home.index'))
Example #47
0
    def post(self):
        trans = Transaction(id=self.request.get("trans_code"))
        trans.trans_code = self.request.get("trans_code")

        sender = User.get_by_id(self.request.get("sender_code"))
        trans.sender = sender.key.urlsafe()
        
        receiver = User.get_by_id(self.request.get("receiver_code"))
        trans.receiver = receiver.key.urlsafe()

        trans.description = self.request.get("description")
        logging.critical(self.request.get("eda"))
        date = datetime.datetime.strptime(self.request.get("eda"), '%m/%d/%Y')
        logging.critical(date)
        trans.eda = date
        p_code = ""
        r_code = ""
        while True:
            p_code = parser_code()
            parcel = P.get_by_id(p_code)    
            if not parcel:
                break;

        while True:
            r_code = receiver_code()
            receiver = R.get_by_id(r_code)
            if not receiver:
                break;

        logging.critical(p_code)
        logging.critical(r_code)

        trans.parser_code = hash_code(p_code, "PARSER")
        trans.receiver_code = hash_code(r_code, "RECEIVER")

        trans.put()

        """ save transaction for PARSEL code """
        p = P(id=p_code)
        p.codes = p_code
        p.trans_key = trans.key.urlsafe()
        p.put()
        """ ---------------------------------- """

        """ save transaction for RECEIVER code """
        r = R(id=r_code)
        r.codes = r_code
        r.trans_key = trans.key.urlsafe()
        r.put()
        """ ---------------------------------- """

        self.redirect(self.uri_for('www-login', success="Added!."))
Example #48
0
 def createTransaction(self, props): 
     tx = Transaction( method = 'PayPal',
                   donor = props['donor'],
                   client = props['client'],
                   txID = props['txn_id'],
                   paymentDate = urllib.unquote(props['payment_date']).replace('+', ' '),
                   amount = float(props['mc_gross']),
                   fee = float(props['mc_fee']) ,
                   paymentStatus = props['payment_status'],
                   note = urllib.unquote(props['item_name']).replace('+', ' '),
                   fulfilled = False
                 )
     tx.put() 
     return tx
Example #49
0
def init(amount, currency=None, email="", description="", language=None):
    """
    Init payment

    Params:
    * amount - Amount to pay
    * currency - Suggested currency (can be changed by user)
    * email - User's email (can be changed by user)
    * description - Transaction description
    * language - "en" or "ru"

    Return tuple (rk.models.Transaction instance, robokassa redirect URL)
    """

    from models import Transaction

    if amount is None:
        return None

    currency = currency or lib.conf("RK_DEFAULT_CURRENCY")
    language = language or lib.conf("RK_DEFAULT_LANGUAGE")

    login = lib.conf("RK_MERCHANT_LOGIN")
    pass1 = lib.conf("RK_MERCHANT_PASS1")

    # 2. Create transaction in DB
    tr = Transaction(amount=amount, currency=currency, description=description)
    tr.save()
    _id = tr.id

    signature = lib.sign([login, amount, str(_id), pass1])

    # 3. Redirect to robokassa
    params = {"MrchLogin": login,
              "OutSum": amount,
              "InvId": _id,
              "Desc": description,
              "SignatureValue": signature,
              "IncCurrLabel": currency,
              "Email": email,
              "Culture": language}

    if lib.conf("RK_USE_TEST_SERVER"):
        rk_url = lib.conf("RK_TEST_URL")
    else:
        rk_url = lib.conf("RK_URL")

    url = rk_url + "?%s" % urllib.urlencode(params)

    return (tr, url)
Example #50
0
 def get_game_history(self, request):
     """Returns the a listing of all guesses made in the given game"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     tx = Transaction.query(Transaction.game == game.key)
     tx = tx.order(Transaction.date)
     return TransactionForms(transactions=[trans.to_form()
                             for trans in tx])
Example #51
0
 def get_transactions(self, account_number):
   db_account_id = self.get_accountid(account_number)
   trans = Transaction.select().where(Transaction.ACCOUNTID==db_account_id)
   results = []
   for row in trans:
     results.append(row)
   return results
Example #52
0
    def setUp(self):
        self.group, created = Group.objects.get_or_create(name='test')
        self.user, created = DjangoUser.objects.get_or_create(username=self.username)
        self.user.set_password(self.password)
        self.user.save()
        perspective, created = Perspective.objects.get_or_create(name='default')
        perspective.set_default_user()
        perspective.save()
        ModuleSetting.set('default_perspective', perspective.id)

        self.contact_type = ContactType(name='test')
        self.contact_type.set_default_user()
        self.contact_type.save()

        self.contact = Contact(name='test', contact_type=self.contact_type)
        self.contact.set_default_user()
        self.contact.save()

        self.category = Category(name='test')
        self.category.set_default_user()
        self.category.save()

        self.equity = Equity(
            issue_price=10, sell_price=10, issuer=self.contact, owner=self.contact)
        self.equity.set_default_user()
        self.equity.save()

        self.asset = Asset(name='test', owner=self.contact)
        self.asset.set_default_user()
        self.asset.save()

        self.tax = Tax(name='test', rate=10)
        self.tax.set_default_user()
        self.tax.save()

        self.currency = Currency(code="GBP",
                                 name="Pounds",
                                 symbol="L",
                                 is_default=True)
        self.currency.set_default_user()
        self.currency.save()

        self.account = Account(
            name='test', owner=self.contact, balance_currency=self.currency)
        self.account.set_default_user()
        self.account.save()

        self.liability = Liability(name='test',
                                   source=self.contact,
                                   target=self.contact,
                                   account=self.account,
                                   value=10,
                                   value_currency=self.currency)
        self.liability.set_default_user()
        self.liability.save()

        self.transaction = Transaction(name='test', account=self.account, source=self.contact,
                                       target=self.contact, value=10, value_currency=self.currency)
        self.transaction.set_default_user()
        self.transaction.save()
Example #53
0
    def _handler(self, expense_key, post=False):
        user = users.get_current_user()

        if user:
            instance = Transaction.get(expense_key)
            if instance.user != user:
                self.redirect(users.create_login_url(self.request.uri))

            if post:
                form = IncomeForm(user, instance=instance, data=self.request.POST)
                if form.is_valid():
                    transaction = form.save(commit=False)
                    transaction.account = transaction.customer.account
                    transaction.put()
                    self.redirect("/receitas/")

            form = IncomeForm(user, instance=instance)
            path = os.path.join(os.path.dirname(__file__), 'templates/income.html')
            self.response.out.write(template.render(path, {
                'form': form,
                'user': user,
                'logout_url': users.create_logout_url("/")
            }))
        else:
            self.redirect(users.create_login_url(self.request.uri))
Example #54
0
def parser_code():
    while True:
        code_id = ''.join(random.choice(string.digits) for x in range(6))
        trans = Transaction.query(Transaction.parser_code == code_id).fetch(100)
        if not trans:
            break

    return code_id
Example #55
0
def get_trans_id():
    while True:
        code_id = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(5))
        trans = Transaction.get_by_id(code_id)
        if not trans:
            break

    return code_id
Example #56
0
def add_balance():
    """For GET requests, display the login form. For POSTS, login the current user
    by processing the form."""

    form = BalanceForm()
    if form.validate_on_submit():
        user = User.query.get(form.email.data)
        if user:
            if user.balance is None:
                user.balance = UserBalance()
                user.balance.amount = 0.0
            user.balance.amount += form.amount.data

            txn_id = str(uuid.uuid4())[:8]
            reason = "ABU - Admin Balance update"

            credit_transaction = Transaction()
            credit_transaction.txn_id =  txn_id
            credit_transaction.party =  form.email.data
            credit_transaction.counter_party =  "Admin"
            credit_transaction.amount =  form.amount.data
            credit_transaction.type =  'Cr'
            credit_transaction.reason =  reason

            db.session.add(user.balance)
            db.session.add(credit_transaction)
            db.session.commit()
            return redirect(url_for("user_page"))
        else:
            flash('Invalid User Id')
    return render_template("add_balance.html", form=form)
Example #57
0
def route_webhook():
    data = json.loads(request.data.decode('utf8'))

    if data['type'] == 'transaction.created':
        transaction = Transaction(data['data'])
        transaction.save()

        if transaction.visited_count > settings.mondo_visit_count:
            suggestion = transaction.find_suggestion()

            if suggestion:
                suggestion.save()
                suggestion.post_to_feed()

    else:
        log.warning('Unsupported webhook type: %s' % data['type'])

    return ''
Example #58
0
 def post(self, user_id):
     auth_key = request.args.get('key')
     user = User.authenticate(user_id, auth_key)
     if user:
         supposed_transaction = request.get_json(force=True)
         transaction = Transaction()
         transaction.user_id = user_id
         transaction.category_id = supposed_transaction['category_id']
         transaction.person_id = supposed_transaction['person_id']
         transaction.transaction_date = supposed_transaction['transaction_date']
         transaction.value = supposed_transaction['value']
         transaction.notes = supposed_transaction['notes']
         transaction.type = supposed_transaction['type']
         transaction.done = supposed_transaction['done']
         db.session.add(transaction)
         db.session.commit()
         if transaction.transaction_id:
             return json.jsonify(transaction.as_dict())
     return json.jsonify({})
Example #59
0
    def get(self, expense_key):
        user = users.get_current_user()

        if user:
            instance = Transaction.get(expense_key)
            if instance.user == user:
                instance.delete()
            self.redirect("/receitas/")
        else:
            self.redirect(users.create_login_url(self.request.uri))
Example #60
0
File: api.py Project: MBloom/OneDir
 def decorator(*args, **kwargs):
     res = func(*args, **kwargs)
     if type(res) == dict or 200 <= res[1] <= 210:
         LOG = True
         # Successful txn, log it.
         print "yes"
         _type='DIR'
         path = request.args.get('path', None)
         if 'file' in request.args:
             p = request.args['path']
             f = request.args['file']
             _type = 'FILE'
             path = os.path.join(p, f)
         action = ''
         if 'move' in request.path:
             action = 'MOVE'
             path  = request.args['from']
             if 'file' in request.path:
                 _type = 'FILE'
         elif request.method == 'POST':
             action ='CREATE'
         elif request.method == 'PUT':
             action ='UPDATE'
         elif request.method == 'DELETE':
             action = 'DELETE'
         else:
             LOG = False
         try:
             if LOG: 
                 tx = Transaction(user=kwargs['username'],
                                  type=_type,
                                  action=action,
                                  pathname=path,
                                  ip_address=request.remote_addr  
                                  )
                 g.db.add(tx)
                 print "yes"
                 txid = tx.hash()
                 res[0]['txid'] = txid
         except Exception as e:
             print e
     return res