web/website/node/war-native-relations.mjs

18 lines
1.5 KiB
JavaScript

import {createHash} from 'node:crypto';
import {campaignPhase} from './war-campaign-model.mjs';
const stableId=value=>{const h=createHash('sha256').update(value).digest('hex');return h.slice(0,8)+'-'+h.slice(8,12)+'-4'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);};
export function campaignWarRelations(campaigns,now=Date.now()){
const result=[];
for(const c of campaigns){
const phase=campaignPhase(c,now);if(c.mode!=='clan'||!['scheduled','active'].includes(phase))continue;const pairs=new Set(),roster=c.teams.flatMap(t=>t.roster.map(p=>p.uuid)).sort();
for(let i=0;i<c.teams.length;i++)for(const clan of c.teams[i].clanIds||[c.teams[i].id]){
const other=c.teams[1-i].id,pair=[clan,other].sort().join(':');if(clan===other||pairs.has(pair))continue;pairs.add(pair);
result.push({keyId:stableId('war-campaign:'+c.id+':'+pair),campaignId:c.id,source:'war-campaign',attackerId:clan,defenderId:other,declaredAt:c.startsAt,expiresAt:c.endsAt,active:phase==='active',reserved:phase==='scheduled',roster});
}
}
if(result.length>500)throw Error('Campaign native relations exceed the supported batch.');return result;
}
export async function readClanWarRelations(store,{clock=Date.now}={}){
const rows=await store.query('SELECT snapshot_json FROM jarvis_war_campaigns WHERE ends_at>? ORDER BY starts_at,id LIMIT 501',[clock()]);
if(rows.length>500)throw Error('Campaign native view requires review.');return campaignWarRelations(rows.map(r=>JSON.parse(r.snapshot_json)),clock());
}