import psycopg2.extras
import sys
+import argparse
create_temp_table = """
SELECT extract(year FROM date) AS annee,
+ %(select_month)s
CAST(sum(
- CASE WHEN emetteur = %(idbde)s THEN montant * quantite
+ CASE WHEN emetteur = %%(idbde)s THEN montant * quantite
ELSE 0
END
)/100.0 AS numeric(10,2)) AS depenses,
CAST(sum(
- CASE WHEN destinataire = %(idbde)s THEN montant * quantite
+ CASE WHEN destinataire = %%(idbde)s THEN montant * quantite
ELSE 0
END
)/100.0 AS numeric(10,2)) AS gains
INTO past
FROM transactions
- WHERE valide AND %(idbde)s in (emetteur, destinataire)
- GROUP BY annee
+ WHERE valide AND %%(idbde)s in (emetteur, destinataire)
+ GROUP BY annee%(groupby_month)s
;
"""
+select_month = """extract(month FROM date) AS mois,"""
+
+groupby_month = """, month"""
+
display_all = """ SELECT * FROM past
ORDER BY annee
;
cur = con.cursor(cursor_factory = psycopg2.extras.DictCursor)
return (con, cur)
-def get_depenses(idbde):
+def get_depenses(idbde, bymonth=False):
"""Récupère toutes les dépenses/gains du compte ``idbde``"""
con, cur = get_cursor()
- cur.execute(create_temp_table, {"idbde" : idbde})
+ modifiers = {"select_month" : "", "groupby_month" : ""}
+ params = {"idbde" : idbde}
+ if bymonth:
+ params["select_month"] = select_month
+ params["groupby_month"] = groupby_month
+ cur.execute(create_temp_table % modifiers, params)
cur.execute(display_all)
all = cur.fetchall()
cur.execute(display_sum)
tot = cur.fetchall()[0]
return (all, tot)
-def display_depenses(all, tot):
+def display_depenses(idbde, all, tot):
"""Pretty-printing des résultats."""
- print "annee\tdepenses\tgains"
+ print "Compte %s:\nannee\tdepenses\tgains" % (idbde,)
for li in all:
li = [int(li[0]), li[1], li[2]]
print "%s\t%s\t\t%s" % tuple(li)
print "\nTotal :\n\tdepenses\tgains"
- print "\t%s\t\t%s" % tuple(tot)
+ print "\t%s\t\t%s\n" % tuple(tot)
if __name__ == "__main__":
- idbde = int(sys.argv[1])
- all, tot = get_depenses(idbde)
- display_depenses(all, tot)
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("-m", "--months", help="Faire le calcul par mois", action="store_true")
+ parser.add_argument('idbdes', type=int, nargs=argparse.ONE_OR_MORE, help="Les idbde dont on veut connaître les dépenses.")
+
+ args = parser.parse_args()
+ for idbde in args.idbdes:
+ all, tot = get_depenses(idbde)
+ display_depenses(idbde, all, tot)