import {createServerProjects} from './server-projects.mjs'; import {createProjectBanking} from './project-banking.mjs'; import {createGazettePublisher} from './jarvis-gazette.mjs'; import {can} from './permissions.mjs'; const first=async(db,sql,args=[])=>{const rows=await db.query(sql,args);return rows[0]||null;}; export function createServerProjectRuntime(central,bank,keys,{clock=Date.now}={}){ const fresh=id=>first(central,"SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]); const authorizePlayer=async actor=>(!actor.revalidate||(await actor.revalidate())?.id===actor.id)&&!!await fresh(actor.id); const authorizeReview=async actor=>{const current=await fresh(actor.id);return !!current&&await can(central,current,'web.projects.review');}; const banking=bank?createProjectBanking(bank,{clock,authorize:async(actor,input,tx)=>{ const project=await first(central,'SELECT * FROM jarvis_server_projects WHERE id=?',[input.projectId]);if(!project||actor.id!==project.reviewer_id)return false; const job=await first(central,"SELECT kind FROM jarvis_project_jobs WHERE id=? AND project_id=? AND state='queued'",[input.requestId,project.id]);if(!job)return false; if(input.action==='close')return ['close','close-empty'].includes(job.kind)&&['active','completion-pending','completed'].includes(project.state); if(input.action!=='fund'||job.kind!=='fund'||input.applicantId!==project.applicant_id||input.amountMinor!==Number(project.approved_minor)||input.title!==project.title||!['funding-pending','active'].includes(project.state))return false; // Reconciliation of an already posted payment does not confer new spending // rights when the original reviewer has since lost their staff permission. const previous=await tx.first('SELECT request_id FROM jarvis_project_banking WHERE project_id=?',[project.id]); return previous?.request_id===input.requestId||await authorizeReview(actor); }}):null; const publisherIdentity=Object.freeze({source:'approved-server-project'}),publisher=createGazettePublisher(central,keys,{clock,authorize:async actor=>actor===publisherIdentity,resolve:async(event,tx)=>{ const p=await tx.first("SELECT title,approved_minor,updated_at FROM jarvis_server_projects WHERE id=? AND state IN ('active','completion-pending','completed')",[event.sourceId]);if(!p)return null; return {title:'Project approved: '+p.title,body:'A server project has been accepted and funded: '+p.title+'.\n\nApproved budget: '+(Number(p.approved_minor)/100).toFixed(2)+' DM. Progress and spending remain in the project and bank records.',category:'community',occurredAt:Number(p.updated_at)}; }}); return createServerProjects(central,keys,{clock,authorizePlayer,authorizeReview,banking,announce:project=>publisher.publish(publisherIdentity,{type:'project-approved',sourceId:project.id,visibility:'public',confirmed:true})}); }