db_mgr.py 1.09 KB
from pprint import pprint

from app.models import db, Agent, Charge


def agents():
    sql_txt = """select a.id, a.firstname, a.secondname, sum(c.charge_rate) as total_charge
                from agent as a
                         inner join charge c on a.id = c.agent_id
                group by agent_id;"""
    all_agents = db.session.execute(sql_txt).fetchall()

    return all_agents


def charges_by_agent(agent_id):
    # all_charges = db.session.query(Charge).all()
    periods = db.session.execute("select name from period")
    sql_txt = "select p.name, sum(charge_rate)  from charge inner join period p on charge.period_id = p.id\
                where agent_id={} group by period_id order by p.name" \
        .format(agent_id)
    request = db.session.execute(sql_txt)
    all_charges = []
    charges_list = [(period, charge) for (period, charge) in request.fetchall()]
    charges_dict = dict(charges_list)
    for (p,) in periods:
        if p in charges_dict.keys():
            all_charges.append([p, charges_dict[p]])
        else:
            all_charges.append([p, 0])
    return all_charges