accountant/src/api/controller/accounts.py

92 lines
2.6 KiB
Python
Raw Normal View History

from app import app
from app import db
from app import session
from api.model.accounts import Account
from api.model.entries import Entry
from flask import json, request
from sqlalchemy import func, case, cast, extract, distinct
@app.route("/api/accounts", methods=["GET"])
def get_accounts():
"""
Returns accounts with their solds.
"""
query=session.query(
Account.id.label("id"),
Account.name.label("name"),
func.sum(Entry.value).label("future"),
func.sum(case([(Entry.operation_date != None, Entry.value,)], else_=cast(0, db.Numeric(15, 2)))).label("pointed"),
func.sum(case([(Entry.value_date < func.now(), Entry.value,)], else_=cast(0, db.Numeric(15, 2)))).label("current")
).outerjoin(Entry).group_by(Account.id).order_by(Account.id)
return json.dumps([{
"id": i.id,
"name": i.name,
"current": str(i.current),
"pointed": str(i.pointed),
"future": str(i.future)
} for i in query.all()])
@app.route("/api/accounts/<account_id>/months")
def get_months(account_id):
query=session.query(
distinct(extract("year", Entry.value_date)).label("year"),
extract("month", Entry.value_date).label("month")
).filter(Entry.account_id == account_id).order_by("year", "month")
return json.dumps([{
"year": i.year,
"month": i.month
} for i in query.all()])
@app.route("/api/accounts", methods=["PUT"])
def add_account():
with session.begin():
try:
account = Account(request.json['name'])
session.add(account)
session.commit()
return json.dumps("Account added.")
except:
session.rollback()
raise
@app.route("/api/accounts/<account_id>", methods=["PUT"])
def update_account(account_id):
with session.begin():
try:
account = session.query(Account).filter(Account.id == account_id).first()
account.name = request.json['name']
session.merge(account)
session.commit()
return json.dumps("Account #%s updated." % account_id)
except:
session.rollback()
raise
@app.route("/api/accounts/<account_id>", methods=["DELETE"])
def delete_account(account_id):
with session.begin():
try:
account = session.query(Account).filter(Account.id == account_id).first()
session.delete(account)
session.commit()
return json.dumps("Account #%s deleted." % account_id)
except:
session.rollback()
raise