ability to cancel construction and have a portion of the funds returned
[browser-rts.git] / src / api.ts
index 50d4f06d014eeb92b75c7bc8df2a63b665d4795b..4509bec431ad8d616bc0946d2fa2c0933268b2da 100644 (file)
@@ -1,7 +1,7 @@
 import { HttpServer } from './lib/server';
 import * as config from './config';
 import { AccountRepository } from './repository/accounts';
-import { CityRepository } from './repository/city';
+import { City, CityRepository } from './repository/city';
 import { MailRepository } from './repository/mail';
 import {BadInputError, ERROR_CODE, NotFoundError} from './errors';
 import { renderKingomOverview } from './render/kingdom-overview';
@@ -19,6 +19,7 @@ import { renderCost } from './render/costs';
 import {renderMailroom, renderMessage} from './render/mail';
 import {topbar} from './render/topbar';
 import {renderPublicChatMessage} from './render/chat-message';
+import validator from 'validator';
 
 
 const server = new HttpServer(config.API_PORT);
@@ -379,6 +380,49 @@ server.post<{body: {message: string}}, void>('/chat', async req => {
   return;
 });
 
+server.post<{params: {queueId: string}}, void>('/construction/:queueId/cancel', async req => {
+       const acct = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
+       const city = await cityRepo.getUsersCity(acct.id);
+
+  if(!validator.isUUID(req.params.queueId)) {
+    throw new BadInputError('Invalid queue ID', ERROR_CODE.INVALID_BUILD_QUEUE);
+  }
+
+  // validate that this is an actual queue
+  const queue = await cityRepo.buildQueue.FindOne({owner: city.owner, id: req.params.queueId});
+
+  if(!queue) {
+    throw new NotFoundError('That queue does not exist', ERROR_CODE.INVALID_BUILD_QUEUE);
+  }
+
+  const [, building] = await Promise.all([
+    cityRepo.buildQueue.Delete({
+      owner: city.owner,
+      id: req.params.queueId
+    }),
+    cityRepo.buildingRepository.findBySlug(queue.building_type)
+  ]);
+
+  // now that it's deleted we can give the player back some percentage 
+  // of resources based on how close they are to completion.
+  const diff = (queue.due - Date.now()) / (queue.due - queue.created);
+  // force a 20% loss minimum
+  const finalDiff = diff < 0.2 ? 0.2 : diff;
+
+  const costReturn: Partial<City> = {
+    id: city.id,
+    credits: city.credits + Math.floor(building.credits * queue.amount * diff),
+    alloys: city.alloys + Math.floor(building.alloys * queue.amount * diff),
+    energy: city.energy + Math.floor(building.energy * queue.amount * diff),
+    usedSpace: city.usedSpace - (building.land * queue.amount)
+  };
+
+  console.log('update', costReturn)
+
+  await cityRepo.save(costReturn);
+
+}, 'reload-construction-queue');
+
 server.get<void, string>('/server-stats', async req => {
   const date = new Date();
   return `