'use strict'; /* DELETE /towns/:id/queue/:eventId. Cancels a running build and refunds 80% (rounded down). */ const D = require('../../public/js/data.js'); const { GameError } = require('../errors'); const { settle } = require('../state'); const { ownedTown } = require('./build'); const REFUND = 0.8; module.exports = function cancelBuild(ctx, { userId, townId, eventId }) { const { db, now } = ctx; const town = ownedTown(db, userId, townId); const ev = db.get("SELECT id, payload FROM events WHERE id = ? AND town_id = ? AND type = 'buildDone' AND status = 'pending'", eventId, town.id); if (!ev) throw new GameError('not_found', { what: 'queue entry' }); settle(db, town, now); const cost = JSON.parse(ev.payload).cost || {}; const R = require('../../public/js/rules.js'); for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(R.storageCapOf(town, r), town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND)); db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id); db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ?", now, ev.id); return { cancelled: ev.id }; };