import asyncio import base64 import secrets import psycopg from argon2.low_level import Type, hash_secret_raw 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): value = f"{reading_id}|{secrets.randbelow(10000):04d}".encode("ascii") key = hash_secret_raw(value, bytes(16), time_cost=1, memory_cost=8192, parallelism=1, hash_len=32, type=Type.ID, version=19) return base64.b64encode(key).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 = await asyncio.to_thread(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 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), )