'use strict'; /* * POST /backbone/:id/build: start the next Backbone node level on a landing site your alliance holds. The level's cost comes out * of the site's stockpile (shipped in by the holders, see backboneShip) at once; one level at a time; the level lands when the * `backboneDone` event runs. Needs the `backboneBuild` permission. */ const R = require('../../public/js/rules.js'); const { GameError } = require('../errors'); const { loadWorld } = require('../state'); const A = require('../alliances'); const E = require('../endgame'); const ctxOf = require('../military/ctx'); // The site, the caller's operator in its world, and proof that the caller's alliance holds it. Shared with backboneShip. function holderContext(db, userId, siteId, now) { const site = E.siteRow(db, siteId); if (!site) throw new GameError('not_found', { what: 'landing site' }); const world = loadWorld(db, site.world_id); const op = db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, site.world_id); if (!op) throw new GameError('not_found', { what: 'landing site' }); if (!E.isOpen(world, now)) throw new GameError('backbone_closed', { opensAtDay: require('../../public/js/data.js').ENDGAME.openDay }); const m = A.membership(db, op.id); if (!site.holder_alliance_id || !m || m.alliance_id !== site.holder_alliance_id) throw new GameError('forbidden', { need: 'holder' }); return { site, world, op, member: m }; } module.exports = function backboneBuild(ctx0, { userId, siteId }) { const ctx = ctxOf(ctx0); const { db, now } = ctx; const { site, world, op, member } = holderContext(db, userId, siteId, now); if (!R.allianceCan(member.role, 'backboneBuild')) throw new GameError('forbidden', { need: 'backboneBuild', role: member.role }); const plan = R.backbonePlan({ level: site.level, build: site.build_to ? { to: site.build_to } : null, pool: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } }, world.speed); if (!plan.ok) throw new GameError(plan.code, { siteId: site.id, toLevel: plan.toLevel, cost: plan.cost, have: { fiber: site.fiber, hardware: site.hardware, capital: site.capital } }); const dueAt = now + plan.durationMs; const ev = ctx.enqueue({ worldId: site.world_id, dueAt, type: 'backboneDone', payload: { siteId: site.id, toLevel: plan.toLevel, by: op.id } }); db.run(`UPDATE landing_sites SET fiber = fiber - ?, hardware = hardware - ?, capital = capital - ?, build_to = ?, build_event_id = ?, build_started_at = ?, build_due_at = ?, build_cost = ? WHERE id = ?`, plan.cost.fiber, plan.cost.hardware, plan.cost.capital, plan.toLevel, ev, now, dueAt, JSON.stringify(plan.cost), site.id); return { siteId: site.id, eventId: ev, toLevel: plan.toLevel, startedAt: now, dueAt, cost: plan.cost }; }; module.exports.holderContext = holderContext;