'use strict'; /* POST /diplomacy/proposals/:proposalId/accept | /decline. Needs `diplomacy` in the receiving alliance. The move is * validated again against the CURRENT relation (it may have changed since the proposal was made). */ const R = require('../../public/js/rules.js'); const { GameError } = require('../errors'); const A = require('../alliances'); const Dip = require('../diplomacy'); module.exports = function diploAnswer(ctx, { userId, proposalId, accept }) { const { db, now } = ctx; const p = db.get('SELECT * FROM alliance_proposals WHERE id = ?', proposalId); if (!p) throw new GameError('not_found', { what: 'proposal' }); const { op, alliance } = A.requireRole(db, userId, p.to_id, 'diplomacy'); // forbidden/not_found for outsiders if (p.status !== 'pending') { if ((accept && p.status === 'accepted') || (!accept && p.status === 'declined')) return { changed: false }; throw new GameError(p.status === 'expired' ? 'proposal_expired' : 'conflict', { what: 'proposal is ' + p.status }); } if (p.expires_at <= now) throw new GameError('proposal_expired', { expiresAt: p.expires_at }); const proposer = A.getAlliance(db, p.from_id); if (!proposer) throw new GameError('not_found', { what: 'alliance' }); if (!accept) { db.run("UPDATE alliance_proposals SET status = 'declined', answered_at = ? WHERE id = ?", now, p.id); A.notifyAlliance(ctx, proposer.id, 'diplomacy_declined', { proposalId: p.id, by: Dip.brief(alliance), state: p.state }, { roles: ['leader', 'diplomat'] }); return { changed: true }; } const rel = A.getRelation(db, alliance.id, proposer.id); const from = rel ? rel.state : 'neutral'; if (rel && rel.pending_to) throw new GameError('diplomacy_pending', { from, to: rel.pending_to, effectiveAt: rel.pending_at }); if (R.diplomacyMove(from, p.state) !== 'proposal') throw new GameError('diplomacy_invalid', { from, to: p.state }); db.run("UPDATE alliance_proposals SET status = 'accepted', answered_at = ? WHERE id = ?", now, p.id); Dip.applyChange(ctx, alliance, proposer, p.state, { by: op.name, proposalId: p.id }); return { changed: true, from, state: p.state }; };