@chevre/domain 22.11.0-alpha.9 → 22.12.0-alpha.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.
Files changed (156) hide show
  1. package/example/src/chevre/aggregation/aggregateOrderOfCustomer.ts +25 -11
  2. package/example/src/chevre/aggregation/aggregateOrderOfCustomerGlobally.ts +34 -0
  3. package/example/src/chevre/aggregation/aggregateTasks.ts +41 -0
  4. package/example/src/chevre/checkCustomerAttributesLength.ts +109 -0
  5. package/example/src/chevre/notifyAbortedTasksByEmail.ts +1 -1
  6. package/example/src/chevre/reIndex.ts +1 -1
  7. package/example/src/chevre/roles/addEventOfferPermissionIfNotExists.ts +27 -0
  8. package/example/src/chevre/roles/{addAdminInventoryManagerRole.ts → addProjectCreatorRole.ts} +6 -8
  9. package/example/src/chevre/roles/assignGlobalRoles.ts +72 -0
  10. package/example/src/chevre/roles/findPermissions.ts +84 -0
  11. package/example/src/chevre/roles/findRoleNames.ts +117 -0
  12. package/example/src/chevre/roles/removeConsolePermissionIfExists.ts +38 -0
  13. package/example/src/chevre/searchEventSeats.ts +1 -1
  14. package/example/src/chevre/searchProducts.ts +28 -0
  15. package/example/src/chevre/settings/addSettings.ts +31 -17
  16. package/example/src/chevre/task/countPotentiallyRunning.ts +41 -0
  17. package/example/src/chevre/task/countTasks.ts +51 -0
  18. package/example/src/chevre/{deleteRunsAtPassedCertainPeriod.ts → task/deleteRunsAtPassedCertainPeriod.ts} +4 -3
  19. package/example/src/chevre/task/deleteUnexpectedTasks.ts +23 -0
  20. package/example/src/chevre/task/emitRunning.ts +89 -0
  21. package/example/src/idaas/auth0/adminApplications.ts +183 -0
  22. package/example/src/idaas/auth0/getToken.ts +55 -0
  23. package/example/src/idaas/auth0/getTokenByPrivateKeyJWT.ts +84 -0
  24. package/example/src/regex.ts +31 -0
  25. package/lib/chevre/eventEmitter/task.d.ts +29 -6
  26. package/lib/chevre/factory/event.d.ts +1 -1
  27. package/lib/chevre/index.d.ts +0 -2
  28. package/lib/chevre/index.js +0 -10
  29. package/lib/chevre/repo/event.js +1 -1
  30. package/lib/chevre/repo/member.d.ts +22 -4
  31. package/lib/chevre/repo/member.js +81 -27
  32. package/lib/chevre/repo/mongoose/schemas/aggregateOrder.js +9 -0
  33. package/lib/chevre/repo/mongoose/schemas/event.js +1 -0
  34. package/lib/chevre/repo/mongoose/schemas/member/global.d.ts +14 -0
  35. package/lib/chevre/repo/mongoose/schemas/member/global.js +82 -0
  36. package/lib/chevre/repo/mongoose/schemas/product.js +9 -0
  37. package/lib/chevre/repo/mongoose/schemas/setting.d.ts +15 -0
  38. package/lib/chevre/repo/mongoose/schemas/setting.js +1 -0
  39. package/lib/chevre/repo/mongoose/schemas/task.js +9 -0
  40. package/lib/chevre/repo/order.d.ts +23 -2
  41. package/lib/chevre/repo/order.js +70 -8
  42. package/lib/chevre/repo/pendingReservation.js +1 -0
  43. package/lib/chevre/repo/product.js +12 -17
  44. package/lib/chevre/repo/role.d.ts +5 -4
  45. package/lib/chevre/repo/role.js +35 -32
  46. package/lib/chevre/repo/setting.d.ts +1 -10
  47. package/lib/chevre/repo/setting.js +2 -11
  48. package/lib/chevre/repo/stockHolder.d.ts +4 -27
  49. package/lib/chevre/repo/stockHolder.js +163 -175
  50. package/lib/chevre/repo/task.d.ts +58 -38
  51. package/lib/chevre/repo/task.js +126 -296
  52. package/lib/chevre/repo/transaction.js +10 -10
  53. package/lib/chevre/service/aggregation/event/aggregateScreeningEvent.js +7 -4
  54. package/lib/chevre/service/assetTransaction/cancelReservation/start.d.ts +1 -1
  55. package/lib/chevre/service/assetTransaction/registerService.js +4 -0
  56. package/lib/chevre/service/assetTransaction/reserve/start/createSubReservations.js +19 -16
  57. package/lib/chevre/service/assetTransaction/reserve/start.js +5 -1
  58. package/lib/chevre/service/code.d.ts +5 -28
  59. package/lib/chevre/service/code.js +3 -79
  60. package/lib/chevre/service/iam.d.ts +17 -7
  61. package/lib/chevre/service/iam.js +26 -6
  62. package/lib/chevre/service/notification/notifyAbortedTasksByEmail.d.ts +15 -0
  63. package/lib/chevre/service/notification/notifyAbortedTasksByEmail.js +38 -0
  64. package/lib/chevre/service/notification.d.ts +2 -1
  65. package/lib/chevre/service/notification.js +3 -1
  66. package/lib/chevre/service/offer/product.js +4 -0
  67. package/lib/chevre/service/order/confirmPayTransaction.d.ts +6 -1
  68. package/lib/chevre/service/order/onOrderStatusChanged/onOrderProcessing/processOrder.js +3 -3
  69. package/lib/chevre/service/task/acceptCOAOffer.d.ts +1 -1
  70. package/lib/chevre/service/task/aggregateOffers.d.ts +1 -1
  71. package/lib/chevre/service/task/aggregateOffers.js +1 -1
  72. package/lib/chevre/service/task/aggregateOnSystem.d.ts +4 -2
  73. package/lib/chevre/service/task/aggregateScreeningEvent.d.ts +1 -1
  74. package/lib/chevre/service/task/aggregateScreeningEvent.js +1 -1
  75. package/lib/chevre/service/task/authorizePayment.d.ts +1 -1
  76. package/lib/chevre/service/task/cancelMoneyTransfer.d.ts +1 -1
  77. package/lib/chevre/service/task/cancelPendingReservation.d.ts +1 -1
  78. package/lib/chevre/service/task/cancelPendingReservation.js +1 -1
  79. package/lib/chevre/service/task/cancelReservation.d.ts +1 -1
  80. package/lib/chevre/service/task/cancelReservation.js +1 -1
  81. package/lib/chevre/service/task/checkMovieTicket.d.ts +1 -1
  82. package/lib/chevre/service/task/checkResource.d.ts +1 -1
  83. package/lib/chevre/service/task/checkResource.js +1 -1
  84. package/lib/chevre/service/task/confirmMoneyTransfer.d.ts +1 -1
  85. package/lib/chevre/service/task/confirmPayTransaction.d.ts +2 -2
  86. package/lib/chevre/service/task/confirmPayTransaction.js +3 -2
  87. package/lib/chevre/service/task/confirmRegisterService.d.ts +1 -1
  88. package/lib/chevre/service/task/confirmRegisterServiceTransaction.d.ts +1 -1
  89. package/lib/chevre/service/task/confirmReserveTransaction.d.ts +6 -2
  90. package/lib/chevre/service/task/confirmReserveTransaction.js +3 -3
  91. package/lib/chevre/service/task/createAccountingReport.d.ts +1 -1
  92. package/lib/chevre/service/task/createEvent.d.ts +1 -1
  93. package/lib/chevre/service/task/deletePerson.d.ts +1 -1
  94. package/lib/chevre/service/task/deleteTransaction.d.ts +1 -1
  95. package/lib/chevre/service/task/givePointAward.d.ts +1 -1
  96. package/lib/chevre/service/task/handleNotification.d.ts +4 -2
  97. package/lib/chevre/service/task/importEventCapacitiesFromCOA.d.ts +1 -1
  98. package/lib/chevre/service/task/importEventsFromCOA.d.ts +1 -1
  99. package/lib/chevre/service/task/importOffersFromCOA.d.ts +1 -1
  100. package/lib/chevre/service/task/invalidatePaymentUrl.d.ts +1 -1
  101. package/lib/chevre/service/task/moneyTransfer.d.ts +1 -1
  102. package/lib/chevre/service/task/onAssetTransactionStatusChanged.d.ts +1 -1
  103. package/lib/chevre/service/task/onAuthorizationCreated.d.ts +1 -1
  104. package/lib/chevre/service/task/onEventChanged.d.ts +1 -1
  105. package/lib/chevre/service/task/onOrderPaymentCompleted.d.ts +1 -1
  106. package/lib/chevre/service/task/onResourceUpdated.d.ts +1 -1
  107. package/lib/chevre/service/task/pay.d.ts +1 -1
  108. package/lib/chevre/service/task/placeOrder.d.ts +1 -1
  109. package/lib/chevre/service/task/publishPaymentUrl.d.ts +1 -1
  110. package/lib/chevre/service/task/refund.d.ts +1 -1
  111. package/lib/chevre/service/task/registerService.d.ts +1 -1
  112. package/lib/chevre/service/task/reserve.d.ts +1 -1
  113. package/lib/chevre/service/task/returnMoneyTransfer.d.ts +1 -1
  114. package/lib/chevre/service/task/returnOrder.d.ts +1 -1
  115. package/lib/chevre/service/task/returnPayTransaction.d.ts +1 -1
  116. package/lib/chevre/service/task/returnPointAward.d.ts +1 -1
  117. package/lib/chevre/service/task/returnReserveTransaction.d.ts +1 -1
  118. package/lib/chevre/service/task/sendEmailMessage.d.ts +1 -1
  119. package/lib/chevre/service/task/sendOrder.d.ts +1 -1
  120. package/lib/chevre/service/task/triggerWebhook.d.ts +1 -1
  121. package/lib/chevre/service/task/useReservation.d.ts +1 -1
  122. package/lib/chevre/service/task/voidMoneyTransferTransaction.d.ts +1 -1
  123. package/lib/chevre/service/task/voidPayTransaction.d.ts +1 -1
  124. package/lib/chevre/service/task/voidPayment.d.ts +1 -1
  125. package/lib/chevre/service/task/voidRegisterServiceTransaction.d.ts +1 -1
  126. package/lib/chevre/service/task/voidReserveTransaction.d.ts +1 -1
  127. package/lib/chevre/service/task/voidReserveTransaction.js +1 -1
  128. package/lib/chevre/service/task.d.ts +7 -29
  129. package/lib/chevre/service/task.js +9 -114
  130. package/lib/chevre/service/taskHandler/onOperationFailed/informTaskIfNeeded.d.ts +11 -0
  131. package/lib/chevre/service/taskHandler/onOperationFailed/informTaskIfNeeded.js +105 -0
  132. package/lib/chevre/service/taskHandler/onOperationFailed.d.ts +17 -0
  133. package/lib/chevre/service/taskHandler/onOperationFailed.js +70 -0
  134. package/lib/chevre/service/taskHandler.d.ts +26 -0
  135. package/lib/chevre/service/taskHandler.js +97 -0
  136. package/lib/chevre/service/validation/validateEvent.d.ts +2 -2
  137. package/lib/chevre/service/validation/validateEvent.js +16 -10
  138. package/lib/chevre/service.d.ts +0 -4
  139. package/lib/chevre/service.js +10 -14
  140. package/lib/chevre/settings/aggregation.d.ts +6 -1
  141. package/lib/chevre/settings/aggregation.js +2 -1
  142. package/package.json +6 -4
  143. package/example/src/chevre/adminAuth/adminIdentity.ts +0 -38
  144. package/example/src/chevre/executeOneTask.ts +0 -41
  145. package/example/src/chevre/executeTaskIfExists.ts +0 -80
  146. package/example/src/chevre/findExecutableTask.ts +0 -50
  147. package/example/src/chevre/findSetting.ts +0 -79
  148. package/example/src/chevre/searchPermissions.ts +0 -46
  149. package/example/src/chevre/searchProductOffers.ts +0 -29
  150. package/example/src/chevre/stockHolder/checkIfConflicted.ts +0 -76
  151. package/example/src/chevre/stockHolder/checkRedisKeyCount.ts +0 -186
  152. package/example/src/chevre/stockHolder/migratePendingReservations.ts +0 -96
  153. package/example/src/chevre/stockHolder/playAroundStockHolder.ts +0 -256
  154. package/example/src/chevre/upsertProductsByProductId.ts +0 -100
  155. package/lib/chevre/adminAuth.d.ts +0 -2
  156. package/lib/chevre/adminAuth.js +0 -6
@@ -30,10 +30,10 @@ const task_2 = require("./mongoose/schemas/task");
30
30
  /**
31
31
  * タスク実行時のソート条件
32
32
  */
33
- const sortOrder4executionOfTasks = {
34
- numberOfTried: factory.sortType.Ascending, // トライ回数の少なさ優先
35
- runsAt: factory.sortType.Ascending // 実行予定日時の早さ優先
36
- };
33
+ // const sortOrder4executionOfTasks: { [key in keyof factory.task.IAttributes<factory.taskName>]?: factory.sortType } = {
34
+ // numberOfTried: factory.sortType.Ascending, // トライ回数の少なさ優先
35
+ // runsAt: factory.sortType.Ascending // 実行予定日時の早さ優先
36
+ // };
37
37
  const executableTaskProjection = {
38
38
  _id: 0,
39
39
  id: { $toString: '$_id' },
@@ -242,48 +242,6 @@ class TaskRepo {
242
242
  return { id, status };
243
243
  });
244
244
  }
245
- // public async createIfNotExistByIdentifier(
246
- // params: factory.task.IAttributes<factory.taskName> & {
247
- // // resolve uniqueness of identifier(2025-03-27~)
248
- // identifier: string;
249
- // },
250
- // options: IOptionOnCreate
251
- // ): Promise<void> {
252
- // if (typeof params.identifier !== 'string' || params.identifier.length === 0) {
253
- // throw new factory.errors.ArgumentNull('identifier');
254
- // }
255
- // try {
256
- // const createdTask = await this.taskModel.findOneAndUpdate(
257
- // {
258
- // 'project.id': { $eq: params.project.id },
259
- // name: { $eq: params.name },
260
- // identifier: { $exists: true, $eq: params.identifier }
261
- // },
262
- // { $setOnInsert: params },
263
- // { new: true, upsert: true }
264
- // )
265
- // .select({ _id: 1 })
266
- // .exec();
267
- // if (options.emitImmediately) {
268
- // taskEventEmitter.emitTaskStatusChanged({
269
- // id: createdTask.id,
270
- // name: params.name,
271
- // status: factory.taskStatus.Ready
272
- // });
273
- // }
274
- // } catch (error) {
275
- // let throwsError = true;
276
- // if (await isMongoError(error)) {
277
- // // すでにidentifierが存在する場合ok
278
- // if (error.code === MongoErrorCode.DuplicateKey) {
279
- // throwsError = false;
280
- // }
281
- // }
282
- // if (throwsError) {
283
- // throw error;
284
- // }
285
- // }
286
- // }
287
245
  /**
288
246
  * タスク識別子から冪等作成する
289
247
  * reimplement createIfNotExistByIdentifier(2025-03-28~)
@@ -341,40 +299,6 @@ class TaskRepo {
341
299
  }
342
300
  });
343
301
  }
344
- // public async createInformTaskIfNotExist(
345
- // // resolve uniqueness of identifier(2025-03-27~)
346
- // params: Pick<
347
- // factory.task.IAttributes<factory.taskName.TriggerWebhook>,
348
- // 'data' | 'executionResults' | 'name' | 'numberOfTried' | 'project' | 'remainingNumberOfTries' | 'runsAt' | 'status'
349
- // > & {
350
- // data: factory.task.triggerWebhook.IInformAnyResourceAction & {
351
- // object: factory.notification.person.IPersonAsNotification;
352
- // };
353
- // },
354
- // options: IOptionOnCreate
355
- // ): Promise<void> {
356
- // const createdTask = await this.taskModel.findOneAndUpdate(
357
- // {
358
- // 'project.id': { $eq: params.project.id },
359
- // name: params.name,
360
- // 'data.object.id': {
361
- // $exists: true,
362
- // $eq: String(params.data.object.id)
363
- // }
364
- // },
365
- // { $setOnInsert: params },
366
- // { new: true, upsert: true }
367
- // )
368
- // .select({ _id: 1 })
369
- // .exec();
370
- // if (options.emitImmediately) {
371
- // taskEventEmitter.emitTaskStatusChanged({
372
- // id: createdTask.id,
373
- // name: params.name,
374
- // status: factory.taskStatus.Ready
375
- // });
376
- // }
377
- // }
378
302
  /**
379
303
  * 取引削除タスク冪等作成
380
304
  */
@@ -401,36 +325,6 @@ class TaskRepo {
401
325
  }
402
326
  });
403
327
  }
404
- // public async createConfirmReserveTransactionTaskIfNotExist(
405
- // params: factory.task.IAttributes<factory.taskName.ConfirmReserveTransaction>,
406
- // options: IOptionOnCreate
407
- // ): Promise<void> {
408
- // const createdTask = await this.taskModel.findOneAndUpdate(
409
- // {
410
- // 'project.id': { $eq: params.project.id },
411
- // name: { $eq: params.name },
412
- // 'data.object.transactionNumber': {
413
- // $exists: true,
414
- // $eq: String(params.data.object.transactionNumber)
415
- // },
416
- // 'data.purpose.orderNumber': {
417
- // $exists: true,
418
- // $eq: String(params.data.purpose.orderNumber)
419
- // }
420
- // },
421
- // { $setOnInsert: params },
422
- // { new: true, upsert: true }
423
- // )
424
- // .select({ _id: 1 })
425
- // .exec();
426
- // if (options.emitImmediately) {
427
- // taskEventEmitter.emitTaskStatusChanged({
428
- // id: createdTask.id,
429
- // name: params.name,
430
- // status: factory.taskStatus.Ready
431
- // });
432
- // }
433
- // }
434
328
  createOnAssetTransactionStatusChangedTaskIfNotExist(
435
329
  // resolve uniqueness of identifier(2025-03-27~)
436
330
  params, options) {
@@ -458,6 +352,10 @@ class TaskRepo {
458
352
  }
459
353
  });
460
354
  }
355
+ /**
356
+ * Ready -> remainingNumberOfTriesが1減る
357
+ * Running -> findOneするだけ
358
+ */
461
359
  executeOneById(params) {
462
360
  return __awaiter(this, void 0, void 0, function* () {
463
361
  const now = new Date();
@@ -492,19 +390,21 @@ class TaskRepo {
492
390
  });
493
391
  }
494
392
  /**
495
- * support no name(2025-03-04~)
393
+ * Readyのタスクをname指定でひとつRunningに変更する
496
394
  */
497
395
  executeOneIfExists(params) {
498
396
  return __awaiter(this, void 0, void 0, function* () {
499
- var _a, _b;
397
+ var _a;
500
398
  if (!(params.runsAt.$lt instanceof Date)) {
501
399
  throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
502
400
  }
503
401
  const nameEq = (_a = params.name) === null || _a === void 0 ? void 0 : _a.$eq;
504
- const nameNin = (_b = params.name) === null || _b === void 0 ? void 0 : _b.$nin;
505
- const doc = yield this.taskModel.findOneAndUpdate(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameNin))
402
+ // const nameNin = params.name?.$nin;
403
+ const doc = yield this.taskModel.findOneAndUpdate(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string')
506
404
  ? {
507
- name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameNin)) ? { $nin: nameNin } : undefined)
405
+ name: Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined
406
+ // ...(Array.isArray(nameNin)) ? { $nin: nameNin } : undefined
407
+ )
508
408
  }
509
409
  : undefined), {
510
410
  $set: {
@@ -516,8 +416,9 @@ class TaskRepo {
516
416
  remainingNumberOfTries: -1, // 残りトライ可能回数減らす
517
417
  numberOfTried: 1 // トライ回数増やす
518
418
  }
519
- }, { new: true, projection: executableTaskProjection })
520
- .sort(sortOrder4executionOfTasks)
419
+ }, Object.assign({ new: true, projection: executableTaskProjection }, (typeof params.sort.numberOfTried === 'number' || typeof params.sort.runsAt === 'number')
420
+ ? { sort: params.sort }
421
+ : undefined))
521
422
  .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
522
423
  .lean() // lean(2024-09-26~)
523
424
  .exec();
@@ -535,13 +436,14 @@ class TaskRepo {
535
436
  return __awaiter(this, void 0, void 0, function* () {
536
437
  const { runsAt, limit, name } = params;
537
438
  const nameEq = name === null || name === void 0 ? void 0 : name.$eq;
538
- const nameNin = name === null || name === void 0 ? void 0 : name.$nin;
439
+ // const nameNin = name?.$nin;
440
+ const nameIn = name === null || name === void 0 ? void 0 : name.$in;
539
441
  if (!(runsAt.$lt instanceof Date)) {
540
442
  throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
541
443
  }
542
- const query = this.taskModel.countDocuments(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameNin))
444
+ const query = this.taskModel.countDocuments(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameIn))
543
445
  ? {
544
- name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameNin)) ? { $nin: nameNin } : undefined)
446
+ name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameIn)) ? { $in: nameIn } : undefined)
545
447
  }
546
448
  : undefined));
547
449
  if (typeof limit === 'number' && limit >= 0) {
@@ -552,9 +454,13 @@ class TaskRepo {
552
454
  return { count };
553
455
  });
554
456
  }
555
- emitRunningIfExists(params) {
457
+ /**
458
+ * 実行日時を一定期間過ぎたReadyタスクについて、Runningスタータスに変更した上で、Runningイベントを発生させる
459
+ */
460
+ emitRunningIfExists(params, next // support next function(2025-08-02~)
461
+ ) {
556
462
  return __awaiter(this, void 0, void 0, function* () {
557
- var _a, _b;
463
+ var _a;
558
464
  if (!(params.runsAt.$lt instanceof Date)) {
559
465
  throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
560
466
  }
@@ -564,12 +470,21 @@ class TaskRepo {
564
470
  name: 1
565
471
  };
566
472
  const nameEq = (_a = params.name) === null || _a === void 0 ? void 0 : _a.$eq;
567
- const nameNin = (_b = params.name) === null || _b === void 0 ? void 0 : _b.$nin;
568
- const doc = yield this.taskModel.findOneAndUpdate(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameNin))
569
- ? {
570
- name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameNin)) ? { $nin: nameNin } : undefined)
571
- }
572
- : undefined), {
473
+ // const nameNin = params.name?.$nin;
474
+ // const nameIn = params.name?.$in;
475
+ const { nameFilterBeforeRunsAt } = params;
476
+ const filter = Object.assign(Object.assign(Object.assign({ status: { $eq: factory.taskStatus.Ready } }, (nameFilterBeforeRunsAt) ? { name: params.name } : undefined), { runsAt: { $lt: params.runsAt.$lt } }), (!nameFilterBeforeRunsAt) ? { name: params.name } : undefined
477
+ // ...(typeof nameEq === 'string' || Array.isArray(nameIn))
478
+ // ? {
479
+ // name: {
480
+ // ...(typeof nameEq === 'string') ? { $eq: nameEq } : undefined,
481
+ // // ...(Array.isArray(nameNin)) ? { $nin: nameNin } : undefined
482
+ // ...(Array.isArray(nameIn)) ? { $in: nameIn } : undefined
483
+ // }
484
+ // }
485
+ // : undefined
486
+ );
487
+ const doc = yield this.taskModel.findOneAndUpdate(filter, {
573
488
  $set: {
574
489
  status: factory.taskStatus.Running, // 実行中に変更
575
490
  lastTriedAt: new Date(),
@@ -579,8 +494,9 @@ class TaskRepo {
579
494
  remainingNumberOfTries: -1, // 残りトライ可能回数減らす
580
495
  numberOfTried: 1 // トライ回数増やす
581
496
  }
582
- }, { new: true, projection })
583
- .sort(params.sort)
497
+ }, Object.assign({ new: true, projection }, (typeof params.sort.numberOfTried === 'number' || typeof params.sort.runsAt === 'number')
498
+ ? { sort: params.sort }
499
+ : undefined))
584
500
  .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
585
501
  .lean()
586
502
  .exec();
@@ -588,101 +504,26 @@ class TaskRepo {
588
504
  // tslint:disable-next-line:no-null-keyword
589
505
  return null;
590
506
  }
591
- task_1.taskEventEmitter.emitTaskStatusChanged({
592
- id: doc.id,
593
- status: factory.taskStatus.Running
594
- });
595
- return doc;
596
- });
597
- }
598
- findExecutableOne(params) {
599
- return __awaiter(this, void 0, void 0, function* () {
600
- var _a, _b;
601
- if (!(params.runsAt.$lt instanceof Date)) {
602
- throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
507
+ let changedTask;
508
+ if (typeof nameEq === 'string') {
509
+ changedTask = {
510
+ id: doc.id,
511
+ status: factory.taskStatus.Running,
512
+ name: nameEq
513
+ };
603
514
  }
604
- const nameEq = (_a = params.name) === null || _a === void 0 ? void 0 : _a.$eq;
605
- const nameNin = (_b = params.name) === null || _b === void 0 ? void 0 : _b.$nin;
606
- const query = this.taskModel.findOne(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameNin))
607
- ? {
608
- name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameNin)) ? { $nin: nameNin } : undefined)
609
- }
610
- : undefined), executableTaskProjection)
611
- .sort({
612
- runsAt: factory.sortType.Ascending
613
- });
614
- // .hint('executeOneByName');
615
- // const explainResult = await query.explain();
616
- // console.dir(explainResult, { depth: null });
617
- // console.log(explainResult[0].executionStats.allPlansExecution.map((e: any) => e.executionStages.inputStage));
618
- const doc = yield query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
619
- .lean()
620
- .exec();
621
- if (doc === null) {
622
- // tslint:disable-next-line:no-null-keyword
623
- return null;
515
+ else {
516
+ changedTask = {
517
+ id: doc.id,
518
+ status: factory.taskStatus.Running
519
+ };
624
520
  }
521
+ task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, (typeof next === 'function') ? next : undefined);
625
522
  return doc;
626
523
  });
627
524
  }
628
- // discontinue(2025-05-26~)
629
- /**
630
- * emit OnTaskStatusChanged on delayed tasks
631
- */
632
- // public async emitDelayedTasksEvent(params: {
633
- // now: Date;
634
- // /**
635
- // * 指定期間遅延しているタスクを実行する
636
- // */
637
- // delayInSeconds: number;
638
- // limit: number;
639
- // name: {
640
- // /**
641
- // * 指定タスクのみ実行する
642
- // */
643
- // $in?: factory.taskName[];
644
- // /**
645
- // * 指定タスク以外のみ実行する
646
- // */
647
- // $nin?: factory.taskName[];
648
- // };
649
- // }) {
650
- // const runsAtLt = moment(params.now)
651
- // .add(-params.delayInSeconds, 'seconds')
652
- // .toDate();
653
- // const projection: ProjectionType<factory.task.ITask<factory.taskName>> = {
654
- // _id: 0,
655
- // id: { $toString: '$_id' },
656
- // name: 1,
657
- // status: 1
658
- // };
659
- // const delayedTasks = await this.taskModel.find(
660
- // {
661
- // status: { $eq: factory.taskStatus.Ready },
662
- // runsAt: { $lt: runsAtLt },
663
- // ...(Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined,
664
- // ...(Array.isArray(params.name.$nin)) ? { name: { $nin: params.name.$nin } } : undefined
665
- // },
666
- // projection
667
- // )
668
- // .limit(params.limit)
669
- // .sort(sortOrder4executionOfTasks) // sort(2025-03-03~)
670
- // .setOptions({ maxTimeMS: MONGO_MAX_TIME_MS })
671
- // .lean<IDelayedTask[]>() // lean(2024-09-26~)
672
- // .exec();
673
- // if (delayedTasks.length > 0) {
674
- // delayedTasks.forEach((delayedTask) => {
675
- // taskEventEmitter.emitTaskStatusChanged({
676
- // id: delayedTask.id,
677
- // name: delayedTask.name,
678
- // status: factory.taskStatus.Ready
679
- // });
680
- // });
681
- // }
682
- // return delayedTasks;
683
- // }
684
525
  /**
685
- * make tasks expired
526
+ * Readyのままで期限切れのタスクをExpiredに変更する
686
527
  */
687
528
  makeExpiredMany(params) {
688
529
  return __awaiter(this, void 0, void 0, function* () {
@@ -702,21 +543,23 @@ class TaskRepo {
702
543
  });
703
544
  }
704
545
  /**
705
- * 実行中ステータスのままになっているタスクをリトライする
546
+ * Runningのまま一定期間超過し、かつ、remainingNumberOfTries>0のタスクをReadyに変更する
706
547
  */
707
- retry(params) {
548
+ retryMany(params) {
708
549
  return __awaiter(this, void 0, void 0, function* () {
709
550
  const lastTriedAtShoudBeLessThan = moment()
710
551
  .add(-params.intervalInMinutes, 'minutes')
711
552
  .toDate();
712
- return this.taskModel.updateMany({
713
- status: { $eq: factory.taskStatus.Running },
714
- lastTriedAt: {
553
+ const remainingNumberOfTriesGte = params.remainingNumberOfTries.$gte;
554
+ const remainingNumberOfTriesLte = params.remainingNumberOfTries.$lte;
555
+ return this.taskModel.updateMany(Object.assign(Object.assign(Object.assign({ status: { $eq: factory.taskStatus.Running }, lastTriedAt: {
715
556
  $type: 'date',
716
557
  $lt: lastTriedAtShoudBeLessThan
717
- },
718
- remainingNumberOfTries: { $gt: 0 }
719
- }, {
558
+ } }, (typeof remainingNumberOfTriesGte === 'number')
559
+ ? { remainingNumberOfTries: { $gte: remainingNumberOfTriesGte } }
560
+ : undefined), (typeof remainingNumberOfTriesLte === 'number')
561
+ ? { remainingNumberOfTries: { $lte: remainingNumberOfTriesLte } }
562
+ : undefined), (Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined), {
720
563
  $set: {
721
564
  status: factory.taskStatus.Ready // 実行前に変更
722
565
  }
@@ -744,47 +587,51 @@ class TaskRepo {
744
587
  .exec();
745
588
  });
746
589
  }
747
- abortOne(params) {
748
- return __awaiter(this, void 0, void 0, function* () {
749
- const lastTriedAtShoudBeLessThan = moment()
750
- .add(-params.intervalInMinutes, 'minutes')
751
- .toDate();
752
- const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(AVAILABLE_PROJECT_FIELDS.map((key) => ([key, 1]))));
753
- const doc = yield this.taskModel.findOneAndUpdate({
754
- status: { $eq: factory.taskStatus.Running },
755
- lastTriedAt: {
756
- $type: 'date',
757
- $lt: lastTriedAtShoudBeLessThan
758
- },
759
- remainingNumberOfTries: { $eq: 0 }
760
- }, {
761
- $set: {
762
- status: factory.taskStatus.Aborted,
763
- dateAborted: new Date()
764
- }
765
- }, { new: true, projection })
766
- .lean() // lean(2024-09-26~)
767
- .exec();
768
- if (doc === null) {
769
- // tslint:disable-next-line:no-null-keyword
770
- return null;
771
- }
772
- return doc;
773
- });
774
- }
590
+ // public async abortOne(params: {
591
+ // intervalInMinutes: number;
592
+ // }): Promise<factory.task.ITask<factory.taskName> | null> {
593
+ // const lastTriedAtShoudBeLessThan = moment()
594
+ // .add(-params.intervalInMinutes, 'minutes')
595
+ // .toDate();
596
+ // const projection: ProjectionType<factory.task.ITask<factory.taskName>> = {
597
+ // _id: 0,
598
+ // id: { $toString: '$_id' },
599
+ // ...Object.fromEntries<1>(AVAILABLE_PROJECT_FIELDS.map((key) => ([key, 1])))
600
+ // };
601
+ // const doc = await this.taskModel.findOneAndUpdate(
602
+ // {
603
+ // status: { $eq: factory.taskStatus.Running },
604
+ // lastTriedAt: {
605
+ // $type: 'date',
606
+ // $lt: lastTriedAtShoudBeLessThan
607
+ // },
608
+ // remainingNumberOfTries: { $eq: 0 }
609
+ // },
610
+ // {
611
+ // $set: {
612
+ // status: factory.taskStatus.Aborted,
613
+ // dateAborted: new Date()
614
+ // }
615
+ // },
616
+ // { new: true, projection }
617
+ // )
618
+ // .lean<factory.task.ITask<factory.taskName>>() // lean(2024-09-26~)
619
+ // .exec();
620
+ // if (doc === null) {
621
+ // // tslint:disable-next-line:no-null-keyword
622
+ // return null;
623
+ // }
624
+ // return doc;
625
+ // }
775
626
  abortMany(params) {
776
627
  return __awaiter(this, void 0, void 0, function* () {
777
628
  const lastTriedAtShoudBeLessThan = moment()
778
629
  .add(-params.intervalInMinutes, 'minutes')
779
630
  .toDate();
780
- return this.taskModel.updateMany({
781
- status: { $eq: factory.taskStatus.Running },
782
- lastTriedAt: {
631
+ return this.taskModel.updateMany(Object.assign({ status: { $eq: factory.taskStatus.Running }, lastTriedAt: {
783
632
  $type: 'date',
784
633
  $lt: lastTriedAtShoudBeLessThan
785
- },
786
- remainingNumberOfTries: { $eq: 0 }
787
- }, {
634
+ }, remainingNumberOfTries: { $eq: 0 } }, (Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined), {
788
635
  $set: {
789
636
  status: factory.taskStatus.Aborted,
790
637
  dateAborted: new Date()
@@ -794,48 +641,28 @@ class TaskRepo {
794
641
  });
795
642
  }
796
643
  /**
797
- * 実行結果を保管する
644
+ * タスクIDから実行結果とステータスを保管する
645
+ * Abortedの場合、dateAbortedもセットする
798
646
  */
799
- pushExecutionResultById(params, executionResult,
647
+ setExecutionResultAndStatus(params, update,
800
648
  // support customr function(2025-05-25~)
801
649
  next) {
802
650
  return __awaiter(this, void 0, void 0, function* () {
803
- const { id, status } = params;
651
+ const { id, remainingNumberOfTries, name } = params;
652
+ const { status, executionResult } = update;
804
653
  yield this.taskModel.updateOne({ _id: { $eq: id } }, {
805
- $set: { status },
654
+ $set: Object.assign({ status }, (status === factory.taskStatus.Aborted) ? { dateAborted: executionResult.endDate } : undefined // 2025-08-04~
655
+ ),
806
656
  $push: { executionResults: executionResult }
807
657
  })
808
658
  .exec();
809
659
  // emit event(2025-05-26~)
810
660
  if (typeof next === 'function') {
811
- task_1.taskEventEmitter.emitTaskStatusChanged({ id, status, executionResult }, next);
661
+ const changedTask = { id, name, status, remainingNumberOfTries, executionResult };
662
+ task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, next);
812
663
  }
813
664
  });
814
665
  }
815
- /**
816
- * 特定タスク検索
817
- */
818
- // public async findById<T extends factory.taskName>(params: {
819
- // name: T;
820
- // id: string;
821
- // }): Promise<factory.task.ITask<T>> {
822
- // const doc = await this.taskModel.findOne(
823
- // {
824
- // name: { $eq: params.name },
825
- // _id: { $eq: params.id }
826
- // },
827
- // {
828
- // __v: 0,
829
- // createdAt: 0,
830
- // updatedAt: 0
831
- // }
832
- // )
833
- // .exec();
834
- // if (doc === null) {
835
- // throw new factory.errors.NotFound('Task');
836
- // }
837
- // return doc.toObject();
838
- // }
839
666
  count(params) {
840
667
  return __awaiter(this, void 0, void 0, function* () {
841
668
  const { limit } = params;
@@ -970,7 +797,7 @@ class TaskRepo {
970
797
  return __awaiter(this, void 0, void 0, function* () {
971
798
  const matchConditions = params.matchConditions;
972
799
  const taskStatus = params.status;
973
- const aggregations = yield this.taskModel.aggregate([
800
+ const aggregate1 = this.taskModel.aggregate([
974
801
  {
975
802
  $match: matchConditions
976
803
  },
@@ -1000,8 +827,11 @@ class TaskRepo {
1000
827
  minLatency: '$minLatency'
1001
828
  }
1002
829
  }
1003
- ])
1004
- .exec();
830
+ ]);
831
+ // const explainResult = await aggregate1.explain();
832
+ // console.dir(explainResult, { depth: null });
833
+ // return;
834
+ const aggregations = yield aggregate1.exec();
1005
835
  // tslint:disable-next-line:no-magic-numbers
1006
836
  const percents = [50, 95, 99];
1007
837
  if (aggregations.length === 0) {
@@ -1028,7 +858,7 @@ class TaskRepo {
1028
858
  rank: Math.floor(aggregations[0].taskCount * percentile / 100)
1029
859
  };
1030
860
  });
1031
- const aggregations2 = yield this.taskModel.aggregate([
861
+ const aggregate2 = this.taskModel.aggregate([
1032
862
  {
1033
863
  $match: matchConditions
1034
864
  },
@@ -1058,8 +888,8 @@ class TaskRepo {
1058
888
  })
1059
889
  }
1060
890
  }
1061
- ])
1062
- .exec();
891
+ ]);
892
+ const aggregations2 = yield aggregate2.exec();
1063
893
  return {
1064
894
  status: taskStatus,
1065
895
  aggregation: Object.assign(Object.assign({}, aggregations[0]), aggregations2[0])