コード例 #1
0
ファイル: group.py プロジェクト: manastech/de-bee
 def getTransactionHistory(self, transactionCount, userMembership, lang):
     transactions_query_from = Transaction.gql("WHERE group = :1 AND fromMember = :2 ORDER BY date DESC", userMembership.group, userMembership)
     transactions_from = transactions_query_from.fetch(transactionCount)
     
     transactions_query_to = Transaction.gql("WHERE group = :1 AND toMember = :2 ORDER BY date DESC", userMembership.group, userMembership)
     transactions_to = transactions_query_to.fetch(transactionCount)
     
     transactions = transactions_from + transactions_to
     transactions.sort(cmp = compareTransactionsByDateDesc)
     
     transactions = transactions[0:transactionCount]
     
     messages = []
     for tr in transactions:
         if not tr.fromUser or not tr.toUser or not tr.creator:
             continue
         
         message = descriptionOfTransaction(tr, userMembership.user, lang)
         message = '%s %s' % (niceDate(tr.date, lang), message)
         messages.append({
             'message': message, 
             'benefical': transactionIsBenefical(tr, userMembership.user),
             'isRejectable': tr.isRejectable,
             'rejectUrl': '/reject?key=' + str(tr.key()) + '&h=' + tr.hash +'&cancel=1&trcount=' + str(transactionCount)
             })
          
     return messages
コード例 #2
0
ファイル: server.py プロジェクト: rayhanaziai/Good-Cheddar
def process_acceptance(user_id):
    """Change status of transaction depending on seller acceptance"""

    acceptance = request.form.get("agree_or_disagree")

    transaction_id = session["transaction"]
    current_transaction = Transaction.fetch(transaction_id)
    seller_user = User.fetch(user_id)
    payer_user = User.fetch(current_transaction.payer_id)

    if acceptance == "agree":
        current_transaction.status = "awaiting payment from payer"
        html = "<html><h2>Good Cheddar</h2><br><p>Hi " + payer_user.fullname \
               + ",</p><br>" + seller_user.fullname + " has approved your contract." \
               + "Please<a href='http://*****:*****@hotmail.com",
                "to": '*****@*****.**',
                "subject": "Contract approved!",
                "html": html
            })

    else:
        Transaction.new_status(transaction_id, "declined by seller")
    db.session.commit()

    # At this stage an email is sent to the buyer with prompt to pay.
    return redirect("/dashboard")
コード例 #3
0
def viewUpload():
    if request.method == 'GET':
        return render_template('upload.html')

    elif request.method == 'POST':
        # get file
        file = request.files['transactions_file']
        content = file.read()

        for line in content.splitlines():
            transaction = Transaction()
            for index, item in enumerate(str(line)[2:].split(',')):

                # Date
                if index == 0:
                    transaction.date = item
                elif index == 1:
                    transaction.amount = float(item[1:-1])
                elif index == 2:
                    transaction.name = item[:-1]

            # add transaction
            model.AddTransaction(transaction)

        # complete redirect to upload page
        return render_template('upload.html')
コード例 #4
0
ファイル: server.py プロジェクト: rayhanaziai/Good-Cheddar
def payment_process(transaction_id):

    token = request.form.get("stripeToken")

    transfer = Transaction.fetch(transaction_id)
    payer_id = transfer.payer_id
    seller_id = transfer.seller_id
    seller_email = transfer.seller.email
    amount = transfer.amount * 100
    currency = transfer.currency
    date = transfer.date
    description = "payment from %d to %d" % (payer_id, seller_id)

    # Any way to check if this payment causes error?
    charge = create_charge(amount, token, description)

    if charge.to_dict()['paid'] is not True:
        flash("Your payment has not gone through. Please try again.")
    else:
        Transaction.new_status(transaction_id, "payment from payer received")

        # As soon as payment is successfull, stripe account set up for seller.
        try:
            new_account = create_seller_account(currency, seller_email)

            account_id = new_account.to_dict()['id']
            s_key = new_account.to_dict()['keys']['secret']

            # Add account_id and s_key to database
            User.fetch(seller_id).account_id = account_id
            User.fetch(seller_id).secret_key = s_key
            db.session.commit()

            #Send prompt email to seller for him to put in account details.
            html = "<html><h2>Good Cheddar</h2><br><p>Hi " + transfer.seller.fullname \
                + ",</p><br>" + transfer.payer.fullname + " has transfered the \
                agreed amount of funds to Good Cheddar. \
                <br> To get paid on the scheduled date, please log in to your \
                Good Cheddar account and enter your account details.\
                <br><br> From the Good Cheddar team!</html>"

            # for test purposes, the same seller email will be used. when live, use '"to": seller_email'
            requests.post(
                "https://api.mailgun.net/v3/sandbox9ba71cb39eb046f798ee4676ad972946.mailgun.org/messages",
                auth=('api', mailgun_key),
                data={
                    "from": "*****@*****.**",
                    "to": seller_email,
                    "subject": "Log in to Good Cheddar",
                    "html": html
                })

        except stripe.InvalidRequestError as e:
            flash(e.message)
            # send email to seller telling them to put their details in stripe

    print("***the token is", token)
    return redirect("/dashboard")
コード例 #5
0
ファイル: cow.py プロジェクト: manastech/de-bee
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		rejectPath = UrlBuilder(self.request).buildUrl('/reject')
		
		user = users.get_current_user()
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("cow")
		members = group.memberships
		
		parser = CowParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
		
		result = transaction.getResult()
		
		# Update balance and send mails
		for member, balance in result.balanceChange.iteritems():
			balanceBefore = member.balance
			balanceNow = member.balance + balance
			
			# Balance
			member.balance += balance
			member.put()
			
			# Send mail, but not to the creator of this mail
			if member.user != creatorMember.user:
				message = createCowMail(creatorMember, transaction, result, member, balanceBefore, balanceNow, lang)
				sendEmail(message)
			
		# Create transactions
		for debt in result.debts:
			for singleDebt in debt.singleDebts:
				tr = Transaction(
					group = group,
					creatorMember = creatorMember, 
					fromMember = debt.fromMember,
					toMember = singleDebt.toMember,
					type = 'debt',
					amount = singleDebt.money, 
					reason = transaction.reason,
					isRejected = False
				)
				tr.put()
				
		location = '/group?group=%s&msg=%s' % (group.key(), _('Debts saved!', lang))
		redirectPage(self,location)
コード例 #6
0
ファイル: encas.py プロジェクト: hugoatease/encas
def createAccount():
    form = forms.AccountCreationForm()
    if form.validate_on_submit():
        account = Account.create(form.firstname.data, form.lastname.data, form.promo.data, form.number.data)

        if form.balance.data is not None and form.balance.data != 0:
            Transaction.add(account.id, form.balance.data)

        return account.serialize()
    else:
        raise MissingFieldsError(form.errors.keys())
コード例 #7
0
 def post(self):
     # We set the same parent key on the 'Greeting' to ensure each Greeting
     # is in the same entity group. Queries across the single entity group
     # will be consistent. However, the write rate to a single entity group
     # should be limited to ~1/second.
     current_user = users.get_current_user()
     description = self.request.get('description')
     total = float(self.request.get('total'))
     time = datetime.strptime(self.request.get('date'),"%m/%d/%Y")
     transaction_id = self.request.get('transaction_id')
     if not transaction_id:
       transaction = Transaction(owner_user_id=current_user.user_id(), description=description, total=total, date=time)
     else:
       transaction_key = ndb.Key(Transaction, int(transaction_id))
       transaction = transaction_key.get()
       transaction.description = description
       transaction.total = total
       transaction.date = time
     shares = []
     transaction.share = []
     for user_id in self.request.get_all('user_id'):
         shares.append(Share(target=user_id, share=1)) 
     transaction.share = shares
     transaction.put()
     self.response.write(json.dumps({}))
コード例 #8
0
ファイル: tests.py プロジェクト: rayhanaziai/Good-Cheddar
def example_data():
    """Create example data to test the database"""

    password = password_hash('0000')

    u1 = User(fullname="Test Person",
              email="*****@*****.**",
              password=password,
              payer_seller="Payer")

    u2 = User(fullname="Test Person2",
              email="*****@*****.**",
              password=password,
              account_id='acct_19rvdXFByeZDKBFc',
              secret_key='sk_test_FMu4VqVNvb1oqZAWYTBh3kvj',
              payer_seller="Seller")

    u3 = User(fullname="Test Person3",
              email="*****@*****.**",
              password=password,
              payer_seller="Payer")

    u4 = User(fullname="Test Person4",
              email="*****@*****.**",
              account_id='acct_19rvdXFByeZDKBFc',
              secret_key='sk_test_FMu4VqVNvb1oqZAWYTBh3kvj',
              password=password,
              payer_seller="Seller")

    new_trans1 = Transaction(payer_id=1,
                             seller_id=2,
                             is_signed=False,
                             payment_received=False,
                             date=datetime(2017, 06, 06, 0, 0),
                             amount=1000,
                             currency='usd',
                             status='pending approval from seller')

    new_trans2 = Transaction(payer_id=3,
                             seller_id=4,
                             is_signed=False,
                             payment_received=False,
                             date=datetime(2017, 11, 11, 0, 0),
                             amount=1000,
                             currency='usd',
                             status='pending approval from seller')

    db.session.add_all([u1, u2, u3, u4, new_trans1, new_trans2])
    db.session.commit()
コード例 #9
0
def confirm():
    """Check a transaction confirmation status"""
    gopay = Gopay.load(TOKEN)
    transaction_id = int(request.form["id"])
    limit = int(request.form["limit"])

    try:
        transaction = Transaction.get(Transaction.id == transaction_id,
                                      Transaction.created_at == date.today())
    except:
        return jsonify({"status": "error", "detail": "transaction not found"})

    if transaction.status is True:
        # Already confirmed
        return jsonify({"status": "success", "confirmed": True})

    history = gopay.history(limit)
    found = False
    i = 0

    while not found and i < len(history):
        trx = history[i]
        if (trx["amount"] == (transaction.amount)) and (trx["type"]
                                                        == "credit"):
            found = True

        i += 1

    if not found:
        return jsonify({"status": "fail", "confirmed": False})

    transaction.status = True
    transaction.save()

    return jsonify({"status": "success", "confirmed": True})
コード例 #10
0
ファイル: what.py プロジェクト: manastech/de-bee
	def get(self):
		page = self.request.get('p');
		if page is None or page == '':
			page = 1
		else:
			page = int(page)
			
		offset = (page - 1) * 20
		
		if page != 1:
			self.response.out.write("<a href=\"?p=%s\">Previous</a> | " % (page - 1))
			
		self.response.out.write(" &nbsp; %s &nbsp; " % page)
			
		self.response.out.write(" | <a href=\"?p=%s\">Next</a>" % (page + 1))
		
		self.response.out.write("<br/><br/>")
		
		self.response.out.write("<ul>")
		for tr in Transaction.gql("ORDER BY date DESC LIMIT %s, %s" % (offset, 20)):
			try:
				self.response.out.write("<li>In %s: %s <b>%s</b> %s ($%s due to \"%s\", %s)</li>" % (
											tr.group.name, 
											tr.fromMember.userNick, 
											tr.type, 
											tr.toMember.userNick, 
											tr.amount, 
											tr.reason, 
											tr.date))
			except:
				self.response.out.write("<li style=\"color:blue\">Group must have been deleted...</li>")
		self.response.out.write("</ul>")
コード例 #11
0
ファイル: view_store.py プロジェクト: ilhamwk/accounting
def store_detail(id):
    store = get_object_or_404(Store, Store.id == id)
    trans = Transaction.listStoreTransactions(id)
    if request.args.get('page'):
        trans.paginate(request.args['page'], 
                       app.config['ITEMS_PER_PAGE'])
    return render_template('transaction.html', store=store, trans=trans)
コード例 #12
0
ファイル: app.py プロジェクト: andihaki/gopay-payment-gateway
def confirm():
    '''Check a transaction confirmation status'''
    gopay = Gopay.load(TOKEN)
    transaction_id = int(request.form['id'])
    limit = int(request.form['limit'])

    try:
        transaction = Transaction.get(Transaction.id == transaction_id , \
             Transaction.created_at == date.today())
    except:
        return jsonify({'status': 'error', 'detail': 'transaction not found'})

    if transaction.status is True:
        #Already confirmed
        return jsonify({'status': 'success', 'confirmed': True})

    history = gopay.history(limit)
    found = False
    i = 0

    while not found and i < len(history):
        trx = history[i]
        if (trx['amount'] == (transaction.amount)) and (trx['type']
                                                        == 'credit'):
            found = True

        i += 1

    if not found:
        return jsonify({'status': 'fail', 'confirmed': False})

    transaction.status = True
    transaction.save()

    return jsonify({'status': 'success', 'confirmed': True})
コード例 #13
0
    def add_split_transactions(cls, trx_date: date, budget_names: list,
                               thing: str, income: int, outcome: int):
        budgets = cls._get_budgets_by_names(budget_names, trx_date)
        total_left = sum(map(lambda x: x.left, budgets))
        cur_outcome = outcome - income
        if cur_outcome > total_left:
            raise BudgetAmountExceedLimitError(total_left)

        trxs = []
        for budget in budgets:
            if cur_outcome == 0:
                break

            left = budget.left
            if left == 0:
                continue

            trx_outcome = cur_outcome
            if trx_outcome > left:
                trx_outcome = left
                cur_outcome -= left
            else:
                cur_outcome = 0
            trx = Transaction(date=trx_date,
                              budget_id=budget.id,
                              thing=thing,
                              income=0,
                              outcome=trx_outcome)
            cls.save(trx)
            trxs.append(trx)
        return trxs
コード例 #14
0
def nova_transakcija(user):
    #pridobi podatke za transakcijo in jo izvede
    placilo = placilo_ali_priliv()
    amount = pridobi_amount(user, placilo)
    note = pridobi_note()
    transakcija = Transaction(amount, note, expense=placilo)
    user.izvedi_transakcijo(transakcija)
    print('Uspešno ste izvedli transakcijo!')
コード例 #15
0
def order():
    data = request.json
    user = BaseAPI.get_session().user
    trx = Transaction(
        user=user,
        buyer_name=data["name"],
        address=data["address"],
        total_price=data["price"],
        status="Paid",
    )
    trx.save()
    item = Item.get(Item.sku == data["sku"])
    item.stock -= 1
    item.save()
    trx_item = TransactionItem(item=item, transaction=trx, qty=1)
    trx_item.save()
    return BaseAPI(None).respond(trx.to_dict())
コード例 #16
0
ファイル: transactions.py プロジェクト: manastech/de-bee
    def get(self):
        groupKey = self.request.get("key")
        group = Group.get(groupKey)

        self.response.out.write("<h1>Transactions in %s</h1>" % group.name)

        balances = {}

        transactions = Transaction.gql("WHERE group = :1 ORDER BY date ASC", group)

        self.response.out.write("<ul>")
        for tr in transactions:
            try:
                self.response.out.write("<li>")
                self.response.out.write(
                    "Creator: %s, From: <b>%s</b>, To: <b>%s</b>, Type: <b>%s</b>, Amount: %s, Reason: %s, Date: %s"
                    % (
                        tr.creatorMember.user.nickname(),
                        tr.fromMember.user.nickname(),
                        tr.toMember.user.nickname(),
                        tr.type,
                        tr.amount,
                        tr.reason,
                        tr.date,
                    )
                )

                if tr.type == "debt":
                    fromBalance = -tr.amount
                    toBalance = tr.amount
                else:
                    fromBalance = tr.amount
                    toBalance = -tr.amount

                if not tr.fromMember.user in balances:
                    balances[tr.fromMember.user] = fromBalance
                else:
                    balances[tr.fromMember.user] += fromBalance

                if not tr.toMember.user in balances:
                    balances[tr.toMember.user] = toBalance
                else:
                    balances[tr.toMember.user] += toBalance

                totalBalance = 0.0

                self.response.out.write("<ul>")
                for member, balance in balances.items():
                    totalBalance += balance
                    self.response.out.write("<li>%s: %s</li>" % (member, balance))
                if abs(totalBalance - 0) > 1e7:
                    self.response.out.write('<li style="color:red">Total Balance: %s</li>' % totalBalance)
                self.response.out.write("</ul>")

                self.response.out.write("</li>")
            except:
                foo = True
        self.response.out.write("</ul>")
コード例 #17
0
def send_payments():
    """Send todays payments that are due."""

    today = datetime.today()
    today = today.strftime("%Y-%m-%d")
    today = datetime.strptime(today, "%Y-%m-%d")

    due_list = Transaction.query.filter_by(date=today).all()

    for item in due_list:
        if item.status == 'payment to seller scheduled':
            account_id = item.seller.account_id
            amount = item.amount
            currency = item.currency
            create_transfer(amount, currency, account_id)

            Transaction.new_status(item.transaction_id, "completed")
            db.session.commit()
コード例 #18
0
def preveri_priv():
    priliv = bottle.request.forms['priliv']
    opomba = bottle.request.forms['opomba1']
    if model.je_stevilka(priliv):
        transakcija = Transaction(float(priliv), opomba, False)
        prijavljen.izvedi_transakcijo(transakcija)
        return bottle.redirect('/osnovna_stran/')
    else:
        return bottle.template('narobe.tpl', link='/priliv/')
コード例 #19
0
ファイル: server.py プロジェクト: rayhanaziai/Good-Cheddar
def show_approved_form(transaction_id):

    transaction = Transaction.fetch(transaction_id)
    user_id = session["user_id"]
    payer_seller = session["payer_seller"]
    session["transaction"] = transaction_id
    return render_template('approved-contract.html',
                           transaction=transaction,
                           user_id=user_id,
                           payer_seller=payer_seller)
コード例 #20
0
def preveri_nak():
    nakazilo = bottle.request.forms['nakazilo']
    opomba = bottle.request.forms['opomba']
    if model.je_stevilka(nakazilo):
        if prijavljen.account.stanje < float(nakazilo):
            return bottle.template('premalo_denarja.tpl')
        else:
            transakcija = Transaction(float(nakazilo), opomba, True)
            prijavljen.izvedi_transakcijo(transakcija)
            return bottle.redirect('/osnovna_stran/')
    else:
        return bottle.template('narobe.tpl', link='/placilo/')
コード例 #21
0
ファイル: nurdbar.py プロジェクト: NURDspace/nurdbar
 def addTransaction(self,item,member,transaction_price,number=0):
     self.log.debug('Adding transaction with item %s, transaction_price %s for member %s'%(item.item_id,transaction_price,member.member_id))
     trans=Transaction()
     self.session.add(trans)
     running_total=member.balance
     trans.item=item
     trans.member=member
     try:
         self.session.commit()
         self.session.flush()
     except Exception:
         self.log.error("Exception occured during commit:\n%s"%traceback.format_exc())
         self.session.rollback()
         raise
     self.log.debug("Price: %s"%transaction_price)
     trans.transaction_price=transaction_price
     self.log.debug("Current balance: %s"%running_total)
     trans.running_total=running_total+transaction_price
     self.log.debug("Count: %s"%number)
     trans.item_amount=number
     try:
         self.session.commit()
         self.session.flush()
     except Exception:
         self.log.error("Exception occured during commit:\n%s"%traceback.format_exc())
         self.session.rollback()
         raise
     return trans
コード例 #22
0
 def add_transaction(cls, trx_date: date, budget_name: str, thing: str,
                     income: int, outcome: int):
     budget = budget_service.BudgetService.find_by_name(
         budget_name, trx_date)
     if outcome > budget.left + income:
         raise BudgetAmountExceedLimitError(budget.left)
     trx = Transaction(date=trx_date,
                       budget_id=budget.id,
                       thing=thing,
                       income=income,
                       outcome=outcome)
     cls.save(trx)
     return trx
コード例 #23
0
ファイル: server.py プロジェクト: rayhanaziai/Good-Cheddar
def account_process(transaction_id):

    name = request.form.get("name")
    routing_number = request.form.get("routing-number")
    account_number = request.form.get("account-number")

    response = create_seller_token(name, routing_number, account_number)

    user_id = session['user_id']
    user = User.fetch(user_id)

    seller_email = user.email
    s_key = user.secret_key
    account_token = response.to_dict()['id']
    amount = Transaction.fetch(transaction_id).amount
    currency = Transaction.fetch(transaction_id).currency
    account_id = user.account_id
    create_customer(seller_email, s_key)

    Transaction.new_status(transaction_id, "payment to seller scheduled")

    return redirect("/dashboard")
コード例 #24
0
ファイル: crud.py プロジェクト: LadanShaie/quickstart
def create_transaction(amount, date, merchant_name, user, account_id):
    """Create and return a new transaction."""

    transaction = Transaction(amount=amount,
                              date=date,
                              merchant_name=merchant_name,
                              user=user,
                              account_id=account_id)

    db.session.add(transaction)
    db.session.commit()

    return transaction
コード例 #25
0
ファイル: crud.py プロジェクト: yvonneyeh/photo-shopping-app
def create_transactions(photo_id, user_id, purchased=True):
    """Creates new transaction"""

    purchase_date = datetime.today()
    trans = Transaction(photo_id=photo_id,
                        user_id=user_id,
                        purchase_date=purchase_date,
                        buy_price=buy_price,
                        purchased=purchased)

    db.session.add(trans)
    db.session.commit()

    return trans
コード例 #26
0
ファイル: app.py プロジェクト: andihaki/gopay-payment-gateway
def generate():
    '''Generate a transaction from value'''
    value = int(request.form['amount'])
    today = date.today().strftime('%Y-%m-%d')
    not_assigned = True

    while not_assigned:
        #Making sure there isn't any duplicate value
        add_value = randint(0, 999)  #Random 3 digit number for verification
        not_assigned = Transaction.select()\
              .where(Transaction.created_at == date.today()\
                  , Transaction.amount == value+add_value)\
              .exists()

    transaction = Transaction(amount=value + add_value)
    transaction.save()
    print(transaction.created_at)

    return jsonify({
        'transaction_id': transaction.id,
        'amount': value + add_value,
        'status': 'success'
    })
コード例 #27
0
def generate():
    """Generate a transaction from value"""
    value = int(request.form["amount"])
    today = date.today().strftime("%Y-%m-%d")
    not_assigned = True

    while not_assigned:
        # Making sure there isn't any duplicate value
        add_value = randint(0, 999)  # Random 3 digit number for verification
        not_assigned = (Transaction.select().where(
            Transaction.created_at == date.today(),
            Transaction.amount == value + add_value,
        ).exists())

    transaction = Transaction(amount=value + add_value)
    transaction.save()
    print(transaction.created_at)

    return jsonify({
        "transaction_id": transaction.id,
        "amount": value + add_value,
        "status": "success",
    })
コード例 #28
0
def convertAmount():
    # convert amount
    usAmount = request.json.get('usamount', '')
    #rate = float(request.json.get('rateSet'))
    rate = session.query(Rate).first()
    # add a if to check rate
    # calculate gd amount
    gdAmount = float(usAmount) * rate.convertRate
    transaction = Transaction(usAmount=usAmount,
                              gdAmount=gdAmount,
                              rate=rate.convertRate,
                              user_id=current_user.id)
    session.add(transaction)
    session.commit()
    return jsonify({'message': 'successfully added', 'gdAmount': gdAmount})
コード例 #29
0
def create_investment():
    """API endpoint to create new investment transactions.
       Note: A company/investment must be created on the investments 
       table before recording a transaction."""

    data = request.get_json()

    new_investment = Transaction(company_id=data["company_id"],
                                 asset=data["asset"],
                                 date=datetime.datetime.utcnow(),
                                 cost_per_share=data["cost_per_share"],
                                 num_shares=data["num_shares"])
    db.session.add(new_investment)
    db.session.commit()

    return jsonify({"message": "New investment transaction."})
コード例 #30
0
ファイル: reject.py プロジェクト: manastech/de-bee
def isValidTransaction(key, hash, user):
    # Check that the parameters exist
        if not key or not hash:
            return False
        
        # Check that the transaction exists
        tr = Transaction.get(key)
        if not tr:
            return False
        
        # Check that the current user is involved in the transaction
        if user != tr.fromUser and user != tr.toUser:
            return False
        
        # Check that the hash if valid
        if not tr.isValidHash(hash):
            return
        
        return tr
コード例 #31
0
def deserializer(csv_iterable):
    """
    Generator for converting csv to python
    Handle sparse data and yield
    Transaction model field order (same as csv)
    'id',
    'ts',
    'price',
    'amount',
    'sell',
    'asks',
    'bids',
    'd_high',
    'd_low',
    'd_vwap',
    'd_volume'
    """
    previous_transaction = None

    while True:
        identifier, ts, price, amount, sell, asks, bids, d_high, d_low, d_vwap, d_volume = next(
            csv_iterable)

        if not d_high or not d_low or not d_vwap or not d_volume:
            # Sparse data, set current daily values to previous one
            # Since it does not change that much
            d_high = previous_transaction.d_high
            d_low = previous_transaction.d_low
            d_vwap = previous_transaction.d_vwap
            d_volume = previous_transaction.d_volume

        if not ts or not sell:
            # Cannot do anything for this, passing
            yield None
        else:
            transaction = Transaction(identifier, ts, price, amount, sell,
                                      asks, bids, d_high, d_low, d_vwap,
                                      d_volume)

            yield transaction
            previous_transaction = transaction
コード例 #32
0
def logout():
    """Allows the user to log out, ends the session."""

    # Provides a random number of transactions with random data, stores in db as uncategorized for use upon next login
    if session.get('user_id'):
        for i in range(random.randint(1, 10)):
            fin_transaction_id = ''.join(
                ["%s" % random.randint(0, 9) for num in range(0, 10)])
            # print(fin_transaction_id)
            amount = -float(("{0:.2f}".format(random.random() * 10)))
            # print(amount)
            account = random.choice(session.get('account_choices'))
            # print(account)
            fin_description = random.choice([
                'target', 'chick-fil-a', 'starbucks', 'amazon', 'safeway',
                'petco', 'chevron', 'home depot', 'blue bottle'
            ])
            # print(fin_description)
            transaction_date = random.randint(int(session.get('from_date')),
                                              int(round(time.time())))
            # print(transaction_date)

            # Add transactions to db, do inside for loop for each transaction
            newest_transactions = Transaction(
                fin_transaction_id=str(fin_transaction_id),
                user_id=session.get('user_id'),
                amount=amount,
                account=account,
                fin_description=fin_description,
                user_description=None,
                transaction_date=str(transaction_date),
                is_sorted=False)

            db.session.add(newest_transactions)

        # Commits info for all accounts at once to db
        db.session.commit()

        del session['user_id']

    return redirect('/')
コード例 #33
0
ファイル: logic.py プロジェクト: haojiliu/cmpe273-spring18
def create_transaction(form):
    try:
        with create_session() as s:
            t = Transaction(form)

            entities = _get_legal_entities(
                [t.from_legal_entity, t.to_legal_entity], s)
            if len(entities) != 2:
                return 'Invalid entity ids'
            products = _get_products([t.product_sku], s)
            if len(products) != 1:
                return 'Invalid product sku'

            if _get_txns([t.id], s):
                return 'Existed'
            else:
                s.add(t)
                return t.id
    except:
        raise
        return 'Failed'
コード例 #34
0
 def post(self):
     summaries = []
     months = util.getMonths()
     transactions_query = Transaction.query()
     transactions = transactions_query.fetch(50)
     
     for month in months:
         month_begin = datetime.strptime(month['id'],"%m/%d/%Y")
         month_end = datetime(month_begin.year + (month_begin.month / 12), ((month_begin.month % 12) + 1), 1)
         num_inhabitants = util.getNumInhabitants(month)
         
         sum_food_cost = 0
         for transaction in transactions:
             if transaction.type == TransactionType.COMMON_FOOD and transaction.date >= month_begin and transaction.date < month_end:
                 sum_food_cost += transaction.total
         sum_utility_cost = 0
         for transaction in transactions:
             if transaction.type == TransactionType.COMMON_CLEANING and transaction.date >= month_begin and transaction.date < month_end:
                 sum_utility_cost += transaction.total
         summaries.append({'month' : month['text'],
                           'food_cost_per_person' : sum_food_cost / num_inhabitants if num_inhabitants > 0 else 0,
                           'utility_cost_per_person' : sum_utility_cost / num_inhabitants if num_inhabitants > 0 else 0})
     
     self.response.write(json.dumps(summaries))
コード例 #35
0
ファイル: bulk.py プロジェクト: manastech/de-bee
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		rejectPath = UrlBuilder(self.request).buildUrl('/reject')
		
		user = users.get_current_user()
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("command")
		members = group.memberships
		
		parser = OrderParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
			
		payersBalanceBefore = transaction.payer.balance
		
		for debt in transaction.debts:
		    debtor = debt.member
		    payer = transaction.payer
		    debtorLang = getLanguage(self, debtor.user)
			
		    if debtor.user.email().lower() == payer.user.email().lower():
		        continue
			
		    debtorsBalanceBefore = debtor.balance
		    
		    # Adjust balance
		    debtor.balance -= debt.money
		    debtor.put()
		    
		    payer.balance += debt.money
		    
		    debtorsBalanceNow = debtor.balance
		    
		    # Create transaction
		    tr = Transaction(
		        group = group,
		        creatorMember = creatorMember, 
		        fromMember = debtor,
		        toMember = payer,
		        type = 'debt',
		        amount = debt.money, 
		        reason = debt.reason,
		        isRejected = False
		        )
		    tr.put()
			
		    # If the one that created this transaction is the one that owes,
		    # don't sent a mail to him/her
		    if creatorMember.user == debtor.user:
		    	continue
		    
		    # Build the reject url
		    rejectUrl = UrlBuilder(self.request).buildUrl('/reject')
		    rejectUrl += "?key=%s&h=%s" % (str(tr.key()), tr.hash)
		    
		    # Try send email to the debtor
		    if creatorMember.user == transaction.payer.user:
		    	message = createActionMail(payer, debtor, debt.money, debt.reason, debtorsBalanceBefore, debtorsBalanceNow, rejectUrl, youOwedSomeone(debtorLang), debtorLang) 
		    else:
		    	message = createThirdPartyActionMail(creatorMember, payer, debtor, debt.money, debt.reason, debtorsBalanceBefore, debtorsBalanceNow, rejectUrl, creatorSaysYouOwedSomeone(debtorLang), debtorLang)
		    
		    sendEmail(message)
				
		transaction.payer.put()
		
		payersBalanceNow = transaction.payer.balance
		
		# Now try send email to the payer with a summary
		if not creatorMember.user == transaction.payer.user:
			payerLang = getLanguage(self, transaction.payer.user)
			message = createBulkMail(transaction, creatorMember, payersBalanceBefore, payersBalanceNow, payerLang)
			sendEmail(message)
				
		location = '/group?group=%s&msg=%s' % (group.key(), _('Debts saved!', lang))
		redirectPage(self,location)
コード例 #36
0
ファイル: encas.py プロジェクト: hugoatease/encas
def addTransaction():
    form = forms.TransactionAddForm()
    if form.validate_on_submit():
        return Transaction.add(form.account_id.data, form.cash.data).serialize()
    else:
        raise MissingFieldsError(form.errors.keys())
コード例 #37
0
ファイル: server.py プロジェクト: rayhanaziai/Good-Cheddar
def process_new_transaction(user_id):
    """Persist a new transaction into the DB"""

    # Get form variables
    seller_email = request.form.get("seller_email")
    seller_fullname = request.form.get("seller_fullname")
    payment_date = request.form.get("payment_date")
    payment_amount = request.form.get("payment_amount")
    product_details = request.form.get("product_details")
    date = datetime.datetime.strptime(payment_date, "%Y-%m-%d")

    # The recipient is added to the database
    # password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
    original_password = '******'
    password = password_hash(original_password)
    if User.fetch_by_email(seller_email) is None:
        User.add(
            fullname=seller_fullname,
            email=seller_email,
            phone_number='',
            password=password,
        )
    db.session.commit()

    seller = User.fetch_by_email(seller_email)
    seller_id = seller.user_id
    payer_id = session['user_id']
    payer = User.fetch(payer_id)
    payer_fullname = payer.fullname
    # An email is sent to the seller to log in and view the contract
    html = "<html><h2>Good Cheddar</h2><br><p>Hi " + seller_fullname \
        + ",</p><br>" + payer_fullname + " would like to send you money via Good Cheddar. \
        <br> Please<a href='http://*****:*****@gmail.com",
            "to": seller_email,
            "subject": "You have a payment pending",
            "html": html
        })

    status_history = {"status": ["waiting from approval from seller"]}
    # The new transaction is created in the database
    new_transaction = Transaction.add(
        payer_id=payer_id,
        seller_id=seller_id,
        payment_amount=float(payment_amount),
        payment_currency="USD",
        payment_date=date,
        payment_is_approved=False,
        product_images='',
        product_details=product_details,
        payment_is_made=False,
        is_disputed=False,
        dispute_images='',
        dispute_details='',
        status_history=json.dumps(status_history),
        status="pending approval from recipient",
        is_completed=False,
    )
    date = date.strftime('%Y-%m-%d')

    flash("Approval prompt sent to the recipient")
    # return redirect("/dashboard")

    return jsonify({
        'new_transaction_id': new_transaction.transaction_id,
        'new_recipient': new_transaction.seller.fullname,
        'new_date': date,
        'new_amount': payment_amount,
        'new_status': "pending approval from recipient",
        'new_action': 'No action'
    })
コード例 #38
0
ファイル: encas.py プロジェクト: hugoatease/encas
def getBalance(id):
    id = convert(int, id)
    return {'balance' : str(Transaction.getBalance(id))}
コード例 #39
0
ファイル: encas.py プロジェクト: hugoatease/encas
def getAllTransactions(account_id):
    transactions = Transaction.getByAccount(account_id, None)
    return [tr.serialize() for tr in transactions]
コード例 #40
0
def get_transactions():
    """Collects new transactions for a specific customer."""

    user_id = session.get('user_id')
    # print(user_id)
    user_object = User.query.filter(User.user_id == user_id).first()
    # print(user_object)
    customer_id = user_object.fin_id
    # print(customer_id)

    # Non-interactive refresh of customer transactions from all activated accounts
    refresh_customer_accounts(str(customer_id))

    # Set from_date as the timestamp of the last recieved transaction stored in the db
    recent_transact_object = Transaction.query.filter(
        Transaction.user_id == user_id).order_by(
            Transaction.transaction_date.desc()).first()
    # print(recent_transact_object)
    from_date = str(recent_transact_object.transaction_date)
    # print(from_date)
    session['from_date'] = from_date

    # Get new transactions from Finicity
    new_transactions = get_customer_transactions(str(customer_id), from_date)

    user_account_choice = UserBankAccount.query.filter(
        UserBankAccount.user_id == user_id).all()
    # print(user_account_choice)

    account_choices = []

    for account in user_account_choice:
        added_account = account.fin_account_id
        account_choices.append(added_account)

    session['account_choices'] = account_choices

    # print(account_choices)

    # Loop through transactions to pick out the info that I want to store in the db
    for transaction in new_transactions['transactions']:
        if str(transaction['accountId']) in account_choices:
            fin_transaction_id = transaction['id']
            amount = transaction['amount']
            account = transaction['accountId']
            fin_description = random.choice([
                'target', 'chick-fil-a', 'starbucks', 'amazon', 'safeway',
                'petco', 'chevron', 'home depot', 'blue bottle'
            ])
            transaction_date = transaction['postedDate']

            # Add transactions to db, do inside for loop for each transaction
            newest_transactions = Transaction(
                fin_transaction_id=str(fin_transaction_id),
                user_id=session.get('user_id'),
                amount=amount,
                account=account,
                fin_description=fin_description,
                user_description=None,
                transaction_date=str(transaction_date),
                is_sorted=False)

            db.session.add(newest_transactions)

    # Commits info for all accounts at once to db
    db.session.commit()
コード例 #41
0
ファイル: encas.py プロジェクト: hugoatease/encas
def listTransaction():
    return [tr.serialize() for tr in Transaction.list()]
コード例 #42
0
def show_accounts():
    """Allows users to select and add accounts from their chosen institution."""

    customer_id = session.get('fin_id')
    # print(type(customer_id))
    institution_id = session.get('bank_id')

    # Gets info on ALL (getlist) checkboxed accounts
    # account_choice = request.form['']
    account_choice = request.args.getlist('select_accounts')
    # print(account_choice)

    # Save account_choice in session for use in getting transactions
    session['account_choice'] = account_choice

    # Gets previous account info for all accounts that has been saved in session
    all_accounts_info = session.get('account_choices')
    # print(all_accounts_info)
    # print(all_accounts_info['accounts'])

    # Stores info in db and activates only selected accounts
    for account in all_accounts_info['accounts']:
        # print(account['id'])
        # print(type(account['id']))
        if str(account['id']) in account_choice:
            account_id = str(account['id'])
            account_num = account['number']
            account_name = account['name']
            account_type = account['type']

            # Activate user accounts for daily transaction aggregation
            activate_customer_accounts(customer_id, institution_id, account_id,
                                       account_num, account_name, account_type)

            # Add new user's account info to db
            new_user_accounts = UserBankAccount(fin_account_id=int(account_id),
                                                user_id=session.get('user_id'),
                                                account_name=account_name,
                                                account_num=account_num,
                                                account_type=account_type)

            db.session.add(new_user_accounts)

            # Gets all transactions for the last 12 months for each account (so there is data to pull from for categorizing)
            # PREMIUM FINICITY SERVICE ONLY
            # get_historic_customer_transactions(customer_id, account_id)

    # Non-interactive refresh of customer transactions from all activated accounts
    refresh_customer_accounts(str(customer_id))

    # fromDate = January 10, 2000, gets all transactions Finicity has for a given user
    from_date = str(947462400)

    # Get all transactions for a certain customer within a given date range
    transactions = get_customer_transactions(customer_id, from_date)
    # print(transactions)

    # Loop through transactions to pick out the info that I want to store in the db
    for transaction in transactions['transactions']:
        if str(transaction['accountId']) in account_choice:
            fin_transaction_id = transaction['id']
            amount = transaction['amount']
            account = transaction['accountId']
            fin_description = transaction['memo']
            transaction_date = transaction['postedDate']

            # Add transactions to db, do inside for loop for each transaction
            new_user_transactions = Transaction(
                fin_transaction_id=fin_transaction_id,
                user_id=session.get('user_id'),
                amount=amount,
                account=account,
                fin_description=fin_description,
                user_description=None,
                transaction_date=str(transaction_date),
                is_sorted=False)
            db.session.add(new_user_transactions)

    # Commits info for all accounts at once to db
    db.session.commit()

    get_transactions()

    return redirect('/showunsortedtransactions')
コード例 #43
0
ファイル: encas.py プロジェクト: hugoatease/encas
def calculateBalance(id):
    id = convert(int, id)
    return {'balance' : str(Transaction.calculateBalance(id))}