from appPublic.log import debug, exception from sqlor.dbpools import DBPools from ahserver.serverenv import ServerEnv, get_serverenv from .const import * from accounting.accountingnode import get_parent_orgid async def get_account(sor, accounting_orgid, orgid, subjectid, org1id=None, update=False): ss = "a.org1id is NULL" if org1id: ss = "a.org1id = ${org1id}$" if update: ss += " for update" sql = """select a.* from account a where a.subjectid = ${subjectid}$ and a.accounting_orgid = ${accounting_orgid}$ and a.orgid = ${orgid}$ and """ + ss ns = { "accounting_orgid":accounting_orgid, "orgid":orgid, "org1id":org1id, "subjectid":subjectid } recs = await sor.sqlExe(sql, { "accounting_orgid":accounting_orgid, "orgid":orgid, "org1id":org1id, "subjectid":subjectid }) if len(recs) == 0: debug(f'{sql=}, {ns=}') return None return recs[0] async def getAccountByName(sor, accounting_orgid, orgid, name, org1id): sql = """select a.* from subject a where a.name = ${name}$""" recs = await sor.sqlExe(sql, { "name":name }); if len(recs) == 0: return None return await get_account(sor, accounting_orgid, orgid, recs[0].id, org1id=org1id) async def getCustomerBalance(sor, customerid): name = '客户资金账户' env = ServerEnv() get_owner_orgid = env.get_owner_orgid if get_owner_orgid is None: debug('get_owner_orgid function is not a serverenv function') return None orgid = await get_owner_orgid(sor, customerid) if orgid is None: debug(f"{customerid=}'s parent organization not found") return None balance = await getAccountBalance(sor, orgid, customerid, name, None) if balance is None: debug(f'accid is None, {orgid=}, {customerid=}, {name=}') return None return balance async def getAccountBalance(sor, accounting_orgid, orgid, subjectname, org1id): acc = await getAccountByName(sor, accounting_orgid, orgid, subjectname,org1id) if acc is None: debug(f'accid is None, {accounting_orgid=}, {orgid=}, {subjectname=}, {org1id=}') return None return acc.balance async def get_account_total_amount(sor, accid, accounting_dir, from_date, to_date): sql = """select sun(amount) as amount from acc_detail where accountid =${accountid}$ and acc_date >= ${from_date}$ and acc_date < ${to_date}$ and acc_dir = ${accounting_dir}$ """ ns = { 'accountid':accid, 'accounting_dir':accounting_dir, 'from_date':from_date, 'to_date':to_date } recs = await sor.sqlExe(sql, ns.copy()) if len(recs)==0: e = Exception(f'get_account_total_amount() error, {ns=}') exception('{e=}') raise e return recs[0].amount async def getAccountBalanceByAccid(sor, accid): balances = await sor.sqlExe("""select * from account where id=${accid}$""", {'accid':accid}) if len(balances) == 0: debug(f'acc_balance is None, {accid=}') return 0 return balances[0]['balance']