orgid = await get_userorgid() db = DBPools() dbname = get_module_dbname('accounting') async with db.sqlorContext(dbname) as sor: sql = """ SELECT COALESCE(SUM(credit_limit), 0) as total_credit, COALESCE(SUM(used_credit), 0) as total_used, COALESCE(SUM(available_credit), 0) as total_available, COUNT(*) as customer_count, COUNT(CASE WHEN status = 'active' THEN 1 END) as active_count, COUNT(CASE WHEN status = 'expired' THEN 1 END) as expired_count FROM credit_limit WHERE orgid = ${orgid}$ """ recs = await sor.sqlExe(sql, {'orgid': orgid}) if recs and len(recs) > 0: r = recs[0] total_credit = float(r.total_credit or 0) total_used = float(r.total_used or 0) total_available = float(r.total_available or 0) usage_pct = round((total_used / total_credit * 100), 1) if total_credit > 0 else 0 return json.dumps({ "status": "ok", "data": { "total_credit": total_credit, "total_used": total_used, "total_available": total_available, "usage_pct": usage_pct, "customer_count": int(r.customer_count or 0), "active_count": int(r.active_count or 0), "expired_count": int(r.expired_count or 0) } }) return json.dumps({ "status": "ok", "data": { "total_credit": 0, "total_used": 0, "total_available": 0, "usage_pct": 0, "customer_count": 0, "active_count": 0, "expired_count": 0 } })