@terreno/admin-backend 0.3.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,113 @@
1
- import type express from "express";
1
+ import { type ScriptRunner } from "@terreno/api";
2
+ import express from "express";
2
3
  import type { Model } from "mongoose";
4
+ /**
5
+ * Configuration for a single model in the admin panel.
6
+ */
7
+ export interface AdminFieldOverride {
8
+ /** Widget to use for this field in the admin form (e.g., "markdown") */
9
+ widget?: string;
10
+ }
3
11
  export interface AdminModelConfig {
12
+ /** The Mongoose model to expose in the admin panel */
4
13
  model: Model<any>;
14
+ /** Route path for this model's endpoints, relative to basePath (e.g., "/users") */
5
15
  routePath: string;
16
+ /** Human-readable name shown in the admin UI (e.g., "Users") */
6
17
  displayName: string;
18
+ /** Field names to display in the list view table */
7
19
  listFields: string[];
20
+ /** Default sort order for list queries (e.g., "-created"). Defaults to "-created" if not provided. */
8
21
  defaultSort?: string;
22
+ /** Per-field overrides for widget type and other display options */
23
+ fieldOverrides?: Record<string, AdminFieldOverride>;
24
+ }
25
+ /**
26
+ * Configuration for a script that can be run from the admin panel.
27
+ */
28
+ export interface AdminScriptConfig {
29
+ /** Unique name for this script (used as route key) */
30
+ name: string;
31
+ /** Human-readable description shown in the admin UI */
32
+ description: string;
33
+ /** The function that executes the script. Must return string[] results. */
34
+ runner: ScriptRunner;
9
35
  }
36
+ /**
37
+ * Configuration options for the AdminApp plugin.
38
+ */
10
39
  export interface AdminOptions {
40
+ /** Array of model configurations to expose in the admin panel */
11
41
  models: AdminModelConfig[];
42
+ /** Array of scripts that can be run from the admin panel */
43
+ scripts?: AdminScriptConfig[];
44
+ /** Base path for all admin routes. Defaults to "/admin". */
12
45
  basePath?: string;
13
46
  }
47
+ /**
48
+ * TerrenoPlugin that auto-generates admin CRUD endpoints for Mongoose models.
49
+ *
50
+ * Creates a metadata endpoint (`GET {basePath}/config`) and full CRUD routes for each
51
+ * configured model. All routes require `Permissions.IsAdmin`.
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * import {AdminApp} from "@terreno/admin-backend";
56
+ * import {User, Todo} from "./models";
57
+ *
58
+ * const admin = new AdminApp({
59
+ * basePath: "/admin",
60
+ * models: [
61
+ * {
62
+ * model: User,
63
+ * routePath: "/users",
64
+ * displayName: "Users",
65
+ * listFields: ["email", "name", "admin"],
66
+ * defaultSort: "-created",
67
+ * },
68
+ * {
69
+ * model: Todo,
70
+ * routePath: "/todos",
71
+ * displayName: "Todos",
72
+ * listFields: ["title", "completed", "ownerId"],
73
+ * },
74
+ * ],
75
+ * });
76
+ *
77
+ * // Register with TerrenoApp
78
+ * new TerrenoApp({ userModel: User })
79
+ * .register(admin)
80
+ * .start();
81
+ * ```
82
+ *
83
+ * @see AdminOptions for configuration options
84
+ * @see AdminModelConfig for model configuration
85
+ * @see TerrenoPlugin for the plugin interface
86
+ */
14
87
  export declare class AdminApp {
15
88
  private options;
89
+ /**
90
+ * Create a new AdminApp plugin.
91
+ *
92
+ * @param options - Admin panel configuration including models and base path
93
+ */
16
94
  constructor(options: AdminOptions);
95
+ /**
96
+ * Register admin routes with the Express application.
97
+ *
98
+ * Creates:
99
+ * - `GET {basePath}/config` - Returns metadata for all configured models
100
+ * - CRUD endpoints for each model at `{basePath}{model.routePath}`:
101
+ * - `GET /` - List with pagination
102
+ * - `POST /` - Create
103
+ * - `GET /:id` - Read single item
104
+ * - `PATCH /:id` - Update
105
+ * - `DELETE /:id` - Delete
106
+ *
107
+ * All endpoints require `Permissions.IsAdmin` authentication.
108
+ *
109
+ * @param app - The Express application instance to register with
110
+ */
17
111
  register(app: express.Application): void;
112
+ private mountScriptRoutes;
18
113
  }
package/dist/adminApp.js CHANGED
@@ -1,4 +1,40 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
2
38
  var __values = (this && this.__values) || function(o) {
3
39
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
40
  if (m) return m.call(o);
@@ -26,9 +62,14 @@ var __read = (this && this.__read) || function (o, n) {
26
62
  }
27
63
  return ar;
28
64
  };
65
+ var __importDefault = (this && this.__importDefault) || function (mod) {
66
+ return (mod && mod.__esModule) ? mod : { "default": mod };
67
+ };
29
68
  Object.defineProperty(exports, "__esModule", { value: true });
30
69
  exports.AdminApp = void 0;
31
70
  var api_1 = require("@terreno/api");
71
+ var express_1 = __importDefault(require("express"));
72
+ var luxon_1 = require("luxon");
32
73
  var extractFieldMeta = function (properties, required) {
33
74
  var e_1, _a;
34
75
  var _b;
@@ -59,25 +100,86 @@ var extractFieldMeta = function (properties, required) {
59
100
  }
60
101
  return fields;
61
102
  };
103
+ /**
104
+ * TerrenoPlugin that auto-generates admin CRUD endpoints for Mongoose models.
105
+ *
106
+ * Creates a metadata endpoint (`GET {basePath}/config`) and full CRUD routes for each
107
+ * configured model. All routes require `Permissions.IsAdmin`.
108
+ *
109
+ * @example
110
+ * ```typescript
111
+ * import {AdminApp} from "@terreno/admin-backend";
112
+ * import {User, Todo} from "./models";
113
+ *
114
+ * const admin = new AdminApp({
115
+ * basePath: "/admin",
116
+ * models: [
117
+ * {
118
+ * model: User,
119
+ * routePath: "/users",
120
+ * displayName: "Users",
121
+ * listFields: ["email", "name", "admin"],
122
+ * defaultSort: "-created",
123
+ * },
124
+ * {
125
+ * model: Todo,
126
+ * routePath: "/todos",
127
+ * displayName: "Todos",
128
+ * listFields: ["title", "completed", "ownerId"],
129
+ * },
130
+ * ],
131
+ * });
132
+ *
133
+ * // Register with TerrenoApp
134
+ * new TerrenoApp({ userModel: User })
135
+ * .register(admin)
136
+ * .start();
137
+ * ```
138
+ *
139
+ * @see AdminOptions for configuration options
140
+ * @see AdminModelConfig for model configuration
141
+ * @see TerrenoPlugin for the plugin interface
142
+ */
62
143
  var AdminApp = /** @class */ (function () {
144
+ /**
145
+ * Create a new AdminApp plugin.
146
+ *
147
+ * @param options - Admin panel configuration including models and base path
148
+ */
63
149
  function AdminApp(options) {
64
150
  this.options = options;
65
151
  }
152
+ /**
153
+ * Register admin routes with the Express application.
154
+ *
155
+ * Creates:
156
+ * - `GET {basePath}/config` - Returns metadata for all configured models
157
+ * - CRUD endpoints for each model at `{basePath}{model.routePath}`:
158
+ * - `GET /` - List with pagination
159
+ * - `POST /` - Create
160
+ * - `GET /:id` - Read single item
161
+ * - `PATCH /:id` - Update
162
+ * - `DELETE /:id` - Delete
163
+ *
164
+ * All endpoints require `Permissions.IsAdmin` authentication.
165
+ *
166
+ * @param app - The Express application instance to register with
167
+ */
66
168
  AdminApp.prototype.register = function (app) {
67
169
  var e_2, _a;
68
- var _b, _c;
170
+ var _b, _c, _d;
69
171
  var basePath = (_b = this.options.basePath) !== null && _b !== void 0 ? _b : "/admin";
70
172
  var modelConfigs = this.options.models;
71
173
  // Build config response with field metadata from Mongoose schemas
72
174
  var configModels = modelConfigs.map(function (config) {
73
- var e_3, _a;
74
- var _b, _c;
75
- var _d = (0, api_1.getOpenApiSpecForModel)(config.model), properties = _d.properties, required = _d.required;
175
+ var e_3, _a, e_4, _b;
176
+ var _c, _d;
177
+ var _e = (0, api_1.getOpenApiSpecForModel)(config.model), properties = _e.properties, required = _e.required;
76
178
  // Extract ref information directly from the Mongoose schema
77
179
  var fields = extractFieldMeta(properties, required);
78
180
  try {
79
- for (var _e = __values(Object.entries(fields)), _f = _e.next(); !_f.done; _f = _e.next()) {
80
- var _g = __read(_f.value, 2), key = _g[0], field = _g[1];
181
+ for (var _f = __values(Object.entries(fields)), _g = _f.next(); !_g.done; _g = _f.next()) {
182
+ var _h = __read(_g.value, 2), key = _h[0], field = _h[1];
81
183
  var schemaPath = config.model.schema.path(key);
82
184
  if (schemaPath) {
83
185
  var pathOptions = schemaPath.options;
@@ -85,7 +187,7 @@ var AdminApp = /** @class */ (function () {
85
187
  field.ref = pathOptions.ref;
86
188
  }
87
189
  // Handle array of refs
88
- if (Array.isArray(pathOptions === null || pathOptions === void 0 ? void 0 : pathOptions.type) && ((_b = pathOptions.type[0]) === null || _b === void 0 ? void 0 : _b.ref)) {
190
+ if (Array.isArray(pathOptions === null || pathOptions === void 0 ? void 0 : pathOptions.type) && ((_c = pathOptions.type[0]) === null || _c === void 0 ? void 0 : _c.ref)) {
89
191
  field.ref = pathOptions.type[0].ref;
90
192
  }
91
193
  }
@@ -94,12 +196,30 @@ var AdminApp = /** @class */ (function () {
94
196
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
95
197
  finally {
96
198
  try {
97
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
199
+ if (_g && !_g.done && (_a = _f.return)) _a.call(_f);
98
200
  }
99
201
  finally { if (e_3) throw e_3.error; }
100
202
  }
203
+ // Apply field overrides (e.g., widget: "markdown")
204
+ if (config.fieldOverrides) {
205
+ try {
206
+ for (var _j = __values(Object.entries(config.fieldOverrides)), _k = _j.next(); !_k.done; _k = _j.next()) {
207
+ var _l = __read(_k.value, 2), key = _l[0], override = _l[1];
208
+ if (fields[key] && override.widget) {
209
+ fields[key].widget = override.widget;
210
+ }
211
+ }
212
+ }
213
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
214
+ finally {
215
+ try {
216
+ if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
217
+ }
218
+ finally { if (e_4) throw e_4.error; }
219
+ }
220
+ }
101
221
  return {
102
- defaultSort: (_c = config.defaultSort) !== null && _c !== void 0 ? _c : "-created",
222
+ defaultSort: (_d = config.defaultSort) !== null && _d !== void 0 ? _d : "-created",
103
223
  displayName: config.displayName,
104
224
  fields: fields,
105
225
  listFields: config.listFields,
@@ -107,7 +227,13 @@ var AdminApp = /** @class */ (function () {
107
227
  routePath: "".concat(basePath).concat(config.routePath),
108
228
  };
109
229
  });
110
- var configResponse = { models: configModels };
230
+ // Build script metadata for config response
231
+ var scriptConfigs = (_c = this.options.scripts) !== null && _c !== void 0 ? _c : [];
232
+ var configScripts = scriptConfigs.map(function (script) { return ({
233
+ description: script.description,
234
+ name: script.name,
235
+ }); });
236
+ var configResponse = { models: configModels, scripts: configScripts };
111
237
  // GET /admin/config
112
238
  app.get("".concat(basePath, "/config"), function (_req, res) {
113
239
  return res.json(configResponse);
@@ -124,7 +250,7 @@ var AdminApp = /** @class */ (function () {
124
250
  read: [api_1.Permissions.IsAdmin],
125
251
  update: [api_1.Permissions.IsAdmin],
126
252
  },
127
- sort: (_c = config.defaultSort) !== null && _c !== void 0 ? _c : "-created",
253
+ sort: (_d = config.defaultSort) !== null && _d !== void 0 ? _d : "-created",
128
254
  };
129
255
  app.use("".concat(basePath).concat(config.routePath), (0, api_1.modelRouter)(config.model, routerOptions));
130
256
  }
@@ -136,6 +262,244 @@ var AdminApp = /** @class */ (function () {
136
262
  }
137
263
  finally { if (e_2) throw e_2.error; }
138
264
  }
265
+ // Mount script routes
266
+ if (scriptConfigs.length > 0) {
267
+ var scriptsRouter = express_1.default.Router();
268
+ scriptsRouter.use((0, api_1.authenticateMiddleware)());
269
+ this.mountScriptRoutes(scriptsRouter, scriptConfigs);
270
+ app.use("".concat(basePath, "/scripts"), scriptsRouter);
271
+ }
272
+ };
273
+ AdminApp.prototype.mountScriptRoutes = function (router, scripts) {
274
+ var _this = this;
275
+ var scriptsByName = new Map(scripts.map(function (s) { return [s.name, s]; }));
276
+ // POST /admin/scripts/:name/run — Execute a script
277
+ router.post("/:name/run", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
278
+ var user, script, isWetRun, now, task, err_1, detail, ctx;
279
+ var _this = this;
280
+ var _a;
281
+ return __generator(this, function (_b) {
282
+ switch (_b.label) {
283
+ case 0:
284
+ user = req.user;
285
+ if (!(user === null || user === void 0 ? void 0 : user.admin)) {
286
+ throw new api_1.APIError({ status: 403, title: "Only admins can run scripts" });
287
+ }
288
+ script = scriptsByName.get(req.params.name);
289
+ if (!script) {
290
+ throw new api_1.APIError({ status: 404, title: "Script not found: ".concat(req.params.name) });
291
+ }
292
+ isWetRun = req.query.wetRun === "true";
293
+ now = luxon_1.DateTime.now().toJSDate();
294
+ _b.label = 1;
295
+ case 1:
296
+ _b.trys.push([1, 3, , 4]);
297
+ return [4 /*yield*/, api_1.BackgroundTask.create({
298
+ createdBy: user._id,
299
+ isDryRun: !isWetRun,
300
+ logs: [
301
+ { level: "info", message: "Script started by ".concat((_a = user.name) !== null && _a !== void 0 ? _a : "admin"), timestamp: now },
302
+ ],
303
+ progress: { message: "Starting...", percentage: 0, stage: "Queued" },
304
+ startedAt: now,
305
+ status: "running",
306
+ taskType: script.name,
307
+ })];
308
+ case 2:
309
+ task = (_b.sent());
310
+ return [3 /*break*/, 4];
311
+ case 3:
312
+ err_1 = _b.sent();
313
+ detail = err_1 instanceof Error ? err_1.message : String(err_1);
314
+ api_1.logger.error("Failed to create background task for ".concat(script.name, ": ").concat(detail));
315
+ throw new api_1.APIError({
316
+ detail: detail,
317
+ status: 500,
318
+ title: "Failed to create background task for script: ".concat(script.name),
319
+ });
320
+ case 4:
321
+ ctx = {
322
+ addLog: function (level, message) { return __awaiter(_this, void 0, void 0, function () {
323
+ var current;
324
+ return __generator(this, function (_a) {
325
+ switch (_a.label) {
326
+ case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
327
+ case 1:
328
+ current = _a.sent();
329
+ if (!current) return [3 /*break*/, 3];
330
+ return [4 /*yield*/, current.addLog(level, message)];
331
+ case 2:
332
+ _a.sent();
333
+ _a.label = 3;
334
+ case 3: return [2 /*return*/];
335
+ }
336
+ });
337
+ }); },
338
+ checkCancellation: function () { return __awaiter(_this, void 0, void 0, function () {
339
+ return __generator(this, function (_a) {
340
+ switch (_a.label) {
341
+ case 0: return [4 /*yield*/, api_1.BackgroundTask.checkCancellation(task._id.toString())];
342
+ case 1:
343
+ _a.sent();
344
+ return [2 /*return*/];
345
+ }
346
+ });
347
+ }); },
348
+ updateProgress: function (percentage, stage, message) { return __awaiter(_this, void 0, void 0, function () {
349
+ var current;
350
+ return __generator(this, function (_a) {
351
+ switch (_a.label) {
352
+ case 0: return [4 /*yield*/, api_1.BackgroundTask.findById(task._id)];
353
+ case 1:
354
+ current = _a.sent();
355
+ if (!current) return [3 /*break*/, 3];
356
+ return [4 /*yield*/, current.updateProgress(percentage, stage, message)];
357
+ case 2:
358
+ _a.sent();
359
+ _a.label = 3;
360
+ case 3: return [2 /*return*/];
361
+ }
362
+ });
363
+ }); },
364
+ };
365
+ // Run the script asynchronously — use atomic updates to avoid overwriting
366
+ // cancellation or other intermediate state changes.
367
+ void (function () { return __awaiter(_this, void 0, void 0, function () {
368
+ var result, err_2, message;
369
+ return __generator(this, function (_a) {
370
+ switch (_a.label) {
371
+ case 0:
372
+ _a.trys.push([0, 3, , 5]);
373
+ return [4 /*yield*/, script.runner(isWetRun, ctx)];
374
+ case 1:
375
+ result = _a.sent();
376
+ // Atomically update only if still running (don't overwrite cancellation)
377
+ return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
378
+ $set: {
379
+ completedAt: luxon_1.DateTime.now().toJSDate(),
380
+ progress: { message: "Done", percentage: 100, stage: "Complete" },
381
+ result: result.results,
382
+ status: result.success ? "completed" : "failed",
383
+ },
384
+ })];
385
+ case 2:
386
+ // Atomically update only if still running (don't overwrite cancellation)
387
+ _a.sent();
388
+ return [3 /*break*/, 5];
389
+ case 3:
390
+ err_2 = _a.sent();
391
+ if (err_2 instanceof api_1.TaskCancelledError) {
392
+ return [2 /*return*/];
393
+ }
394
+ message = err_2 instanceof Error ? err_2.message : String(err_2);
395
+ api_1.logger.error("Script ".concat(script.name, " failed: ").concat(message));
396
+ // Atomically update only if still running
397
+ return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: "running" }, {
398
+ $set: {
399
+ completedAt: luxon_1.DateTime.now().toJSDate(),
400
+ error: message,
401
+ result: [message],
402
+ status: "failed",
403
+ },
404
+ })];
405
+ case 4:
406
+ // Atomically update only if still running
407
+ _a.sent();
408
+ return [3 /*break*/, 5];
409
+ case 5: return [2 /*return*/];
410
+ }
411
+ });
412
+ }); })();
413
+ return [2 /*return*/, res.status(201).json({ taskId: task._id.toString() })];
414
+ }
415
+ });
416
+ }); }));
417
+ // GET /admin/scripts/tasks/:id — Poll task status
418
+ router.get("/tasks/:id", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
419
+ var user, task, err_3, detail;
420
+ return __generator(this, function (_a) {
421
+ switch (_a.label) {
422
+ case 0:
423
+ user = req.user;
424
+ if (!(user === null || user === void 0 ? void 0 : user.admin)) {
425
+ throw new api_1.APIError({ status: 403, title: "Only admins can view tasks" });
426
+ }
427
+ _a.label = 1;
428
+ case 1:
429
+ _a.trys.push([1, 3, , 4]);
430
+ return [4 /*yield*/, api_1.BackgroundTask.findById(req.params.id)];
431
+ case 2:
432
+ task = _a.sent();
433
+ return [3 /*break*/, 4];
434
+ case 3:
435
+ err_3 = _a.sent();
436
+ detail = err_3 instanceof Error ? err_3.message : String(err_3);
437
+ throw new api_1.APIError({ detail: detail, status: 400, title: "Invalid task ID" });
438
+ case 4:
439
+ if (!task) {
440
+ throw new api_1.APIError({ status: 404, title: "Task not found" });
441
+ }
442
+ return [2 /*return*/, res.json({ task: task.toObject() })];
443
+ }
444
+ });
445
+ }); }));
446
+ // DELETE /admin/scripts/tasks/:id — Cancel a running task
447
+ router.delete("/tasks/:id", (0, api_1.asyncHandler)(function (req, res) { return __awaiter(_this, void 0, void 0, function () {
448
+ var user, task, err_4, detail, cancelled;
449
+ var _a;
450
+ return __generator(this, function (_b) {
451
+ switch (_b.label) {
452
+ case 0:
453
+ user = req.user;
454
+ if (!(user === null || user === void 0 ? void 0 : user.admin)) {
455
+ throw new api_1.APIError({ status: 403, title: "Only admins can cancel tasks" });
456
+ }
457
+ _b.label = 1;
458
+ case 1:
459
+ _b.trys.push([1, 3, , 4]);
460
+ return [4 /*yield*/, api_1.BackgroundTask.findById(req.params.id)];
461
+ case 2:
462
+ task = _b.sent();
463
+ return [3 /*break*/, 4];
464
+ case 3:
465
+ err_4 = _b.sent();
466
+ detail = err_4 instanceof Error ? err_4.message : String(err_4);
467
+ throw new api_1.APIError({ detail: detail, status: 400, title: "Invalid task ID" });
468
+ case 4:
469
+ if (!task) {
470
+ throw new api_1.APIError({ status: 404, title: "Task not found" });
471
+ }
472
+ if (task.status !== "pending" && task.status !== "running") {
473
+ throw new api_1.APIError({
474
+ status: 400,
475
+ title: "Cannot cancel task with status: ".concat(task.status),
476
+ });
477
+ }
478
+ return [4 /*yield*/, api_1.BackgroundTask.findOneAndUpdate({ _id: task._id, status: { $in: ["pending", "running"] } }, {
479
+ $push: {
480
+ logs: {
481
+ level: "info",
482
+ message: "Task cancelled by ".concat((_a = user.name) !== null && _a !== void 0 ? _a : "admin"),
483
+ timestamp: luxon_1.DateTime.now().toJSDate(),
484
+ },
485
+ },
486
+ $set: {
487
+ completedAt: luxon_1.DateTime.now().toJSDate(),
488
+ status: "cancelled",
489
+ },
490
+ }, { new: true })];
491
+ case 5:
492
+ cancelled = _b.sent();
493
+ if (!cancelled) {
494
+ throw new api_1.APIError({
495
+ status: 409,
496
+ title: "Task already completed or cancelled",
497
+ });
498
+ }
499
+ return [2 /*return*/, res.json({ message: "Task cancelled", task: cancelled.toObject() })];
500
+ }
501
+ });
502
+ }); }));
139
503
  };
140
504
  return AdminApp;
141
505
  }());
@@ -0,0 +1 @@
1
+ export {};