import {jarvisRequestDomain} from './jarvis-request-domains.mjs'; import {automatedMailTemplate} from './automated-mail-templates.mjs'; import {ensureStaffMailbox} from './internal-mail-staff.mjs'; import {closeFilledJarvisListings} from './jarvis-clan-requests.mjs'; export async function runJarvisApplicationNotifications(central,store,{broker,eligible,clock=Date.now,sender=ensureStaffMailbox,kind='clan'}={}){ const domain=jarvisRequestDomain(kind);await closeFilledJarvisListings(central,store,{clock,kind}); const {results:events}=await central.prepare("SELECT e.*,c.name clan_name FROM "+domain.events+" e LEFT JOIN "+domain.organisations+" c ON c.id=e."+domain.column+" WHERE e.state='queued' AND e.next_attempt<=? ORDER BY e.created_at,e.id LIMIT 10").bind(clock()).all();if(!events.length)return {sent:0,failed:0}; const mailbox=await sender(broker);let sent=0,failed=0; for(const event of events)try{ const user=await central.prepare("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'").bind(event.user_id).first(); if(!user||!await eligible(central,user)){await central.prepare("UPDATE "+domain.events+" SET state='cancelled' WHERE id=?").bind(event.id).run();continue;} const target=await broker({action:'internal_ensure',userId:user.id,eligible:true}),name=event.clan_name||'the organisation',subject='Recruitment · '+(event.decision==='accepted'?'Application accepted':event.decision==='filled'?'Position filled':'Application declined'); const message=event.decision==='accepted'?'Your application to '+name+' was accepted. The membership decision is recorded in the '+kind+' register.':event.decision==='filled'?'The advertised place at '+name+' has been filled. Your application for this listing is closed.':'Your application to '+name+' was declined.'; const mail=automatedMailTemplate('jarvis-application',{recipientName:user.username,subject,message,url:'https://cp.dunerealms.com/jarvis-application?listing='+encodeURIComponent(event.listing_id)}); const result=await broker({action:'internal_send',userId:mailbox.userId,requestId:event.id,to:[target.address],cc:[],bcc:[],senderName:'DuneRealms · J.A.R.V.I.S. Recruitment',...mail,subject});if(!result.accepted)throw Error('Delivery not accepted'); await central.prepare("UPDATE "+domain.events+" SET state='sent',attempts=attempts+1 WHERE id=?").bind(event.id).run();sent++; }catch{failed++;await central.prepare('UPDATE '+domain.events+' SET attempts=attempts+1,next_attempt=? WHERE id=?').bind(clock()+Math.min(3600000,60000*2**Math.min(Number(event.attempts),6)),event.id).run();} return {sent,failed}; }