import {pathToFileURL} from 'node:url'; import {randomUUID} from 'node:crypto'; import {openDatabase} from '../node/mysql.mjs'; import {openPostbankDatabase} from '../node/postbank-db.mjs'; import {canRunScheduler} from '../node/scheduler-authority.mjs'; import {PostbankCreditSupport} from '../node/postbank-credit-support.mjs'; export async function linkPendingCreditSupport(central,bank,{apply=false,actorId}={}){ const actor=actorId?await central.prepare("SELECT id FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(actorId).first():null; if(!actor||!await canRunScheduler(central,actor))throw Error('A current Big Four or Dev control identity is required.'); const count=await bank.first("SELECT COUNT(*) AS n FROM pb_credit_loans l LEFT JOIN pb_credit_support_jobs j ON j.loan_id=l.id WHERE l.state='submitted' AND l.product_key NOT LIKE 'grant_%' AND j.loan_id IS NULL"); if(!apply)return{plan:true,pendingApplications:Number(count.n)}; const created=await bank.transaction(async tx=>{ const result=await tx.query("INSERT INTO pb_credit_support_jobs(loan_id) SELECT l.id FROM pb_credit_loans l LEFT JOIN pb_credit_support_jobs j ON j.loan_id=l.id WHERE l.state='submitted' AND l.product_key NOT LIKE 'grant_%' AND j.loan_id IS NULL ON DUPLICATE KEY UPDATE loan_id=VALUES(loan_id)"); await tx.query('INSERT INTO pb_audit(id,actor_id,action,entity_id,details,created_at) VALUES(?,?,?,?,?,?)',[randomUUID(),actor.id,'credit_support_backfill',null,JSON.stringify({jobs:Number(result.affectedRows)}),Date.now()]);return Number(result.affectedRows); }); return{applied:true,created,...await new PostbankCreditSupport(bank,central).process({limit:25})}; } if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){ const central=await openDatabase(process.env),bank=await openPostbankDatabase(process.env); try{if(!bank)throw Error('Bank database unavailable');console.log(JSON.stringify(await linkPendingCreditSupport(central,bank,{apply:process.argv.includes('--apply'),actorId:process.argv.find(v=>v.startsWith('--actor='))?.slice(8)})));} finally{await central.close();if(bank)await bank.close();} }