77 lines
2.8 KiB
Python
Executable File
77 lines
2.8 KiB
Python
Executable File
import base64
|
|
import secrets
|
|
|
|
import psycopg
|
|
from psycopg.types.json import Jsonb
|
|
|
|
from backend.app.db import connection
|
|
from backend.app.db.connection import call
|
|
|
|
async def resources():
|
|
return await call("select billing.resource_types()")
|
|
|
|
async def readings():
|
|
return await call("select billing.reading_list()")
|
|
|
|
async def reading_public(reading_id):
|
|
return await call("select billing.reading_public(%s::bigint)", (reading_id,))
|
|
|
|
def calculation_key(reading_id):
|
|
return base64.b64encode(secrets.token_bytes(32)).decode("ascii")
|
|
|
|
async def add_reading(serial, kind, metrics):
|
|
try:
|
|
async with connection.pool.connection() as db:
|
|
async with db.transaction():
|
|
cursor = await db.execute(
|
|
"select billing.reading_add(%s::text, %s::text, %s::jsonb)",
|
|
(serial, kind, Jsonb(metrics)),
|
|
)
|
|
reading = (await cursor.fetchone())[0]
|
|
key = calculation_key(reading["id"])
|
|
cursor = await db.execute(
|
|
"select billing.receipt_issue(r, %s::text)"
|
|
" from billing.reading r where r.id = %s::bigint",
|
|
(key, reading["id"]),
|
|
)
|
|
return reading | (await cursor.fetchone())[0] | {"calculation_id": key}
|
|
except psycopg.Error as exc:
|
|
raise connection.query_error(exc) from None
|
|
|
|
async def ping():
|
|
return await call("select 1")
|
|
|
|
async def chat_greeting():
|
|
return await call("select chat.greeting()")
|
|
|
|
async def check_start(reading_id):
|
|
return await call("select chat.check_start(%s::bigint)", (reading_id,))
|
|
|
|
async def incomplete_checks(reading_id):
|
|
return await call(
|
|
"select count(*) from chat.check_session where reading_id = %s::bigint and not complete",
|
|
(reading_id,),
|
|
)
|
|
|
|
async def check_commit(check_id, round, values):
|
|
return await call("select chat.check_commit(%s::uuid, %s::int, %s::text[])", (check_id, round, values))
|
|
|
|
async def check_answer(check_id, round, data):
|
|
return await call("select chat.check_answer(%s::uuid, %s::int, %s::jsonb)", (check_id, round, Jsonb(data)))
|
|
|
|
async def receipts():
|
|
return await call("select billing.receipt_list()")
|
|
|
|
async def open_receipt(receipt_id, calculation_id):
|
|
return await call("select billing.receipt_open(%s::bigint, %s::text)", (receipt_id, calculation_id))
|
|
|
|
async def report_fields(report):
|
|
return await call("select billing.report_fields(%s::text)", (report,))
|
|
|
|
async def finance_report(period=None, fields=None, sort="", group_by="", filter="", having=""):
|
|
return await call(
|
|
"select jsonb_build_object('period', coalesce(%s::text, to_char(current_date, 'YYYY-MM')))"
|
|
" || billing.finance_report(%s::text, %s::text[], %s::text, %s::text, %s::text, %s::text)",
|
|
(period, period, fields or [], sort, group_by, filter, having),
|
|
)
|