diff --git a/wwwroot/credit_limit/api/set_customer_credit.dspy b/wwwroot/credit_limit/api/set_customer_credit.dspy index 23e7c0d..f34bcc4 100644 --- a/wwwroot/credit_limit/api/set_customer_credit.dspy +++ b/wwwroot/credit_limit/api/set_customer_credit.dspy @@ -89,7 +89,32 @@ async with db.sqlorContext(dbname) as sor: } } - if record_id: + # Check if credit limit already exists for this account (UNIQUE on accountid) + exist_sql = "select id, used_credit from credit_limit where accountid = ${accountid}$" + exist_recs = await sor.sqlExe(exist_sql, {'accountid': accountid}) + + if exist_recs and len(exist_recs) > 0: + # Account already has a credit limit record — update it + existing = exist_recs[0] + sql = """ + UPDATE credit_limit + SET credit_limit = ${credit_limit}$, + available_credit = ${credit_limit}$ - used_credit, + valid_from = ${valid_from}$, + valid_to = ${valid_to}$, + remark = ${remark}$, + updated_at = CURRENT_TIMESTAMP + WHERE accountid = ${accountid}$ + """ + await sor.sqlExe(sql, { + 'credit_limit': credit_limit_amount, + 'valid_from': valid_from, + 'valid_to': valid_to, + 'remark': remark, + 'accountid': accountid + }) + debug(f'Updated credit limit for {customer.orgname}(accountid={accountid}): {credit_limit_amount}') + elif record_id: sql = """ UPDATE credit_limit SET credit_limit = ${credit_limit}$, @@ -110,7 +135,7 @@ async with db.sqlorContext(dbname) as sor: }) debug(f'Updated credit limit {record_id} to {credit_limit_amount}') else: - new_id = uuid() + new_id = getID() now = datetime.datetime.now() data = { 'id': new_id,