@chevre/domain 23.2.0-alpha.61 → 23.2.0-alpha.63

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 (481) hide show
  1. package/lib/chevre/credentials/customSearch.js +2 -0
  2. package/lib/chevre/credentials/lineNotify.js +4 -0
  3. package/lib/chevre/credentials/sendGrid.js +2 -0
  4. package/lib/chevre/credentials.js +15 -30
  5. package/lib/chevre/emailMessageBuilder.js +225 -250
  6. package/lib/chevre/errorHandler.js +38 -59
  7. package/lib/chevre/eventEmitter/assetTransaction.js +0 -1
  8. package/lib/chevre/eventEmitter/task.js +0 -1
  9. package/lib/chevre/eventEmitter/transaction.js +0 -1
  10. package/lib/chevre/factory/event.js +69 -42
  11. package/lib/chevre/factory/transactionNumber.js +2 -2
  12. package/lib/chevre/index.js +15 -30
  13. package/lib/chevre/repo/acceptedOffer.js +177 -197
  14. package/lib/chevre/repo/acceptedPaymentMethod.js +131 -144
  15. package/lib/chevre/repo/account.js +194 -238
  16. package/lib/chevre/repo/accountTitle.js +9 -21
  17. package/lib/chevre/repo/accountTransaction.js +186 -193
  18. package/lib/chevre/repo/accountingReport.js +88 -107
  19. package/lib/chevre/repo/action.js +849 -883
  20. package/lib/chevre/repo/additionalProperty.js +64 -92
  21. package/lib/chevre/repo/advanceBookingRequirement.js +69 -91
  22. package/lib/chevre/repo/aggregateOffer.js +392 -430
  23. package/lib/chevre/repo/aggregateOrder.js +50 -62
  24. package/lib/chevre/repo/aggregateReservation.js +76 -89
  25. package/lib/chevre/repo/aggregation.js +42 -63
  26. package/lib/chevre/repo/assetTransaction.js +692 -729
  27. package/lib/chevre/repo/authorization.js +115 -134
  28. package/lib/chevre/repo/categoryCode.js +114 -147
  29. package/lib/chevre/repo/comment.js +73 -82
  30. package/lib/chevre/repo/concurrentLock.js +17 -29
  31. package/lib/chevre/repo/confirmationNumber.js +19 -35
  32. package/lib/chevre/repo/creativeWork.js +152 -180
  33. package/lib/chevre/repo/credentials.js +39 -51
  34. package/lib/chevre/repo/customer.js +64 -88
  35. package/lib/chevre/repo/customerType.js +52 -62
  36. package/lib/chevre/repo/emailMessage.js +51 -80
  37. package/lib/chevre/repo/event.js +640 -684
  38. package/lib/chevre/repo/eventOffer.js +122 -125
  39. package/lib/chevre/repo/eventSellerMakesOffer.js +64 -76
  40. package/lib/chevre/repo/eventSeries.js +207 -244
  41. package/lib/chevre/repo/identity.js +94 -107
  42. package/lib/chevre/repo/identityProvider.js +72 -96
  43. package/lib/chevre/repo/issuer.js +102 -135
  44. package/lib/chevre/repo/member.js +238 -259
  45. package/lib/chevre/repo/memberProgram.js +157 -177
  46. package/lib/chevre/repo/merchantReturnPolicy.js +61 -94
  47. package/lib/chevre/repo/message.js +122 -135
  48. package/lib/chevre/repo/mongoose/onIndexCreated.js +0 -1
  49. package/lib/chevre/repo/mongoose/schemas/acceptedPaymentMethod.js +1 -1
  50. package/lib/chevre/repo/mongoose/schemas/account.js +1 -1
  51. package/lib/chevre/repo/mongoose/schemas/accountTitle.js +1 -1
  52. package/lib/chevre/repo/mongoose/schemas/accountTransaction.js +1 -1
  53. package/lib/chevre/repo/mongoose/schemas/accountingReport.js +1 -1
  54. package/lib/chevre/repo/mongoose/schemas/action.js +1 -1
  55. package/lib/chevre/repo/mongoose/schemas/actionRecipe.js +1 -1
  56. package/lib/chevre/repo/mongoose/schemas/additionalProperty.js +1 -1
  57. package/lib/chevre/repo/mongoose/schemas/advanceBookingRequirement.js +1 -1
  58. package/lib/chevre/repo/mongoose/schemas/aggregateOffer.js +1 -1
  59. package/lib/chevre/repo/mongoose/schemas/aggregateOrder.js +1 -1
  60. package/lib/chevre/repo/mongoose/schemas/aggregateReservation.js +1 -1
  61. package/lib/chevre/repo/mongoose/schemas/aggregation.js +1 -1
  62. package/lib/chevre/repo/mongoose/schemas/assetTransaction.js +1 -1
  63. package/lib/chevre/repo/mongoose/schemas/authorization.js +1 -1
  64. package/lib/chevre/repo/mongoose/schemas/categoryCode.js +1 -1
  65. package/lib/chevre/repo/mongoose/schemas/civicStructure.js +1 -1
  66. package/lib/chevre/repo/mongoose/schemas/creativeWork.js +1 -1
  67. package/lib/chevre/repo/mongoose/schemas/customer.js +1 -1
  68. package/lib/chevre/repo/mongoose/schemas/customerType.js +1 -1
  69. package/lib/chevre/repo/mongoose/schemas/event.js +1 -1
  70. package/lib/chevre/repo/mongoose/schemas/eventOffer.js +1 -1
  71. package/lib/chevre/repo/mongoose/schemas/eventSeries.js +1 -1
  72. package/lib/chevre/repo/mongoose/schemas/identity.js +1 -1
  73. package/lib/chevre/repo/mongoose/schemas/identityProvider.js +1 -1
  74. package/lib/chevre/repo/mongoose/schemas/issuer.js +1 -1
  75. package/lib/chevre/repo/mongoose/schemas/member/global.js +1 -1
  76. package/lib/chevre/repo/mongoose/schemas/member.js +1 -1
  77. package/lib/chevre/repo/mongoose/schemas/merchantReturnPolicy.js +1 -1
  78. package/lib/chevre/repo/mongoose/schemas/message.js +1 -1
  79. package/lib/chevre/repo/mongoose/schemas/movieTicketTypes.js +1 -1
  80. package/lib/chevre/repo/mongoose/schemas/note.js +1 -1
  81. package/lib/chevre/repo/mongoose/schemas/offerCatalog.js +1 -1
  82. package/lib/chevre/repo/mongoose/schemas/offerCatalogItem.js +1 -1
  83. package/lib/chevre/repo/mongoose/schemas/offerItemCondition.js +1 -1
  84. package/lib/chevre/repo/mongoose/schemas/order.js +1 -1
  85. package/lib/chevre/repo/mongoose/schemas/paymentService.js +1 -1
  86. package/lib/chevre/repo/mongoose/schemas/paymentServiceChannel.js +1 -1
  87. package/lib/chevre/repo/mongoose/schemas/pendingReservation.js +1 -1
  88. package/lib/chevre/repo/mongoose/schemas/pendingReservationAggregate.js +1 -1
  89. package/lib/chevre/repo/mongoose/schemas/place.js +1 -1
  90. package/lib/chevre/repo/mongoose/schemas/potentialAction.js +1 -1
  91. package/lib/chevre/repo/mongoose/schemas/product.js +1 -1
  92. package/lib/chevre/repo/mongoose/schemas/productModel.js +1 -1
  93. package/lib/chevre/repo/mongoose/schemas/productOffer.js +1 -1
  94. package/lib/chevre/repo/mongoose/schemas/reservation.js +1 -1
  95. package/lib/chevre/repo/mongoose/schemas/reserveInterface.js +1 -1
  96. package/lib/chevre/repo/mongoose/schemas/role.js +1 -1
  97. package/lib/chevre/repo/mongoose/schemas/schedule.js +1 -1
  98. package/lib/chevre/repo/mongoose/schemas/seller.js +1 -1
  99. package/lib/chevre/repo/mongoose/schemas/sellerReturnPolicy.js +1 -1
  100. package/lib/chevre/repo/mongoose/schemas/service/availableHour.js +1 -1
  101. package/lib/chevre/repo/mongoose/schemas/setting.js +1 -1
  102. package/lib/chevre/repo/mongoose/schemas/task.js +1 -2
  103. package/lib/chevre/repo/mongoose/schemas/ticket.js +1 -1
  104. package/lib/chevre/repo/mongoose/schemas/transaction.js +1 -1
  105. package/lib/chevre/repo/mongoose/schemas/transactionNumber.js +1 -1
  106. package/lib/chevre/repo/mongoose/schemas/trip.js +1 -1
  107. package/lib/chevre/repo/mongoose/schemas/webSite.js +1 -1
  108. package/lib/chevre/repo/movieTicketType.js +67 -94
  109. package/lib/chevre/repo/note.js +143 -147
  110. package/lib/chevre/repo/noteAboutOrder.js +112 -113
  111. package/lib/chevre/repo/offer/unitPriceInCatalog.js +330 -314
  112. package/lib/chevre/repo/offerCatalog.js +302 -334
  113. package/lib/chevre/repo/offerCatalogItem.js +289 -317
  114. package/lib/chevre/repo/offerItemCondition.js +60 -85
  115. package/lib/chevre/repo/order.js +559 -607
  116. package/lib/chevre/repo/orderInTransaction.js +113 -136
  117. package/lib/chevre/repo/orderNumber.js +95 -112
  118. package/lib/chevre/repo/ownershipInfo.js +212 -240
  119. package/lib/chevre/repo/passport.js +93 -102
  120. package/lib/chevre/repo/paymentMethod/creditCard.js +151 -169
  121. package/lib/chevre/repo/paymentService.js +179 -200
  122. package/lib/chevre/repo/paymentServiceChannel.js +76 -100
  123. package/lib/chevre/repo/paymentServiceProvider.js +186 -201
  124. package/lib/chevre/repo/pendingReservation.js +272 -305
  125. package/lib/chevre/repo/permit.js +47 -42
  126. package/lib/chevre/repo/person.js +217 -256
  127. package/lib/chevre/repo/place/busStop.js +76 -106
  128. package/lib/chevre/repo/place/entranceGate.js +123 -128
  129. package/lib/chevre/repo/place/hasPOS.js +108 -120
  130. package/lib/chevre/repo/place/movieTheater.js +185 -220
  131. package/lib/chevre/repo/place/screeningRoom.js +339 -325
  132. package/lib/chevre/repo/place/seat.js +538 -481
  133. package/lib/chevre/repo/place/section.js +328 -296
  134. package/lib/chevre/repo/potentialAction.js +67 -87
  135. package/lib/chevre/repo/priceSpecification.js +102 -146
  136. package/lib/chevre/repo/product.js +203 -239
  137. package/lib/chevre/repo/productHasOfferCatalog.js +39 -50
  138. package/lib/chevre/repo/productModel.js +94 -127
  139. package/lib/chevre/repo/productOffer.js +119 -118
  140. package/lib/chevre/repo/project.js +123 -141
  141. package/lib/chevre/repo/projectMakesOffer.js +96 -108
  142. package/lib/chevre/repo/rateLimit/offer.js +43 -57
  143. package/lib/chevre/repo/reservation.js +369 -398
  144. package/lib/chevre/repo/reserveInterface.js +31 -42
  145. package/lib/chevre/repo/role.js +93 -112
  146. package/lib/chevre/repo/schedule.js +25 -36
  147. package/lib/chevre/repo/seller.js +114 -147
  148. package/lib/chevre/repo/sellerMakesOffer.js +95 -110
  149. package/lib/chevre/repo/sellerPaymentAccepted.js +92 -109
  150. package/lib/chevre/repo/sellerReturnPolicy.js +74 -97
  151. package/lib/chevre/repo/service/availableHour.js +27 -38
  152. package/lib/chevre/repo/serviceOutput.js +54 -67
  153. package/lib/chevre/repo/serviceOutputIdentifier.js +46 -58
  154. package/lib/chevre/repo/setting/jwt.js +40 -50
  155. package/lib/chevre/repo/setting.js +48 -48
  156. package/lib/chevre/repo/stockHolder.js +179 -199
  157. package/lib/chevre/repo/task.js +610 -619
  158. package/lib/chevre/repo/telemetry.js +1 -0
  159. package/lib/chevre/repo/ticket.js +52 -65
  160. package/lib/chevre/repo/transaction.js +754 -815
  161. package/lib/chevre/repo/transactionNumber.js +67 -80
  162. package/lib/chevre/repo/transactionNumberCounter.js +68 -79
  163. package/lib/chevre/repo/transactionProcess.js +36 -47
  164. package/lib/chevre/repo/trip.js +144 -164
  165. package/lib/chevre/repo/webSite.js +90 -106
  166. package/lib/chevre/repository.js +455 -647
  167. package/lib/chevre/service/account.js +9 -21
  168. package/lib/chevre/service/accountTransaction/deposit.js +16 -17
  169. package/lib/chevre/service/accountTransaction/transfer.js +18 -22
  170. package/lib/chevre/service/accountTransaction/withdraw.js +16 -17
  171. package/lib/chevre/service/accountTransaction.js +4 -16
  172. package/lib/chevre/service/aggregation/event/aggregateOffers.js +63 -60
  173. package/lib/chevre/service/aggregation/event/aggregateScreeningEvent.js +52 -55
  174. package/lib/chevre/service/aggregation/event/findEventOffers.js +7 -17
  175. package/lib/chevre/service/aggregation/event/importFromCOA.js +4 -14
  176. package/lib/chevre/service/aggregation/project.js +10 -19
  177. package/lib/chevre/service/aggregation/system.js +182 -99
  178. package/lib/chevre/service/assetTransaction/cancelReservation/factory.js +31 -17
  179. package/lib/chevre/service/assetTransaction/cancelReservation/start.js +17 -24
  180. package/lib/chevre/service/assetTransaction/cancelReservation/startAndConfirm.js +17 -15
  181. package/lib/chevre/service/assetTransaction/cancelReservation.js +7 -18
  182. package/lib/chevre/service/assetTransaction/cancelReservationCOA/factory.js +11 -4
  183. package/lib/chevre/service/assetTransaction/cancelReservationCOA.js +4 -13
  184. package/lib/chevre/service/assetTransaction/fixInformAction.js +6 -16
  185. package/lib/chevre/service/assetTransaction/moneyTransfer/potentialActions.js +13 -25
  186. package/lib/chevre/service/assetTransaction/moneyTransfer.js +101 -90
  187. package/lib/chevre/service/assetTransaction/pay/cancel.js +3 -12
  188. package/lib/chevre/service/assetTransaction/pay/check.js +4 -14
  189. package/lib/chevre/service/assetTransaction/pay/confirm.js +18 -21
  190. package/lib/chevre/service/assetTransaction/pay/exportTasksById.js +4 -14
  191. package/lib/chevre/service/assetTransaction/pay/publishPaymentUrl.js +33 -34
  192. package/lib/chevre/service/assetTransaction/pay/searchGMOTrade.js +7 -17
  193. package/lib/chevre/service/assetTransaction/pay/start/account/validation.js +6 -16
  194. package/lib/chevre/service/assetTransaction/pay/start/factory.js +64 -37
  195. package/lib/chevre/service/assetTransaction/pay/start/preStart/validateAcceptedPaymentMethodIfNeeded.js +7 -19
  196. package/lib/chevre/service/assetTransaction/pay/start/preStart/validateSeller.js +6 -16
  197. package/lib/chevre/service/assetTransaction/pay/start/processAuthorizeAccount.js +7 -17
  198. package/lib/chevre/service/assetTransaction/pay/start/processAuthorizeCreditCard.js +9 -15
  199. package/lib/chevre/service/assetTransaction/pay/start/processAuthorizeMovieTicket.js +3 -12
  200. package/lib/chevre/service/assetTransaction/pay/start.js +29 -35
  201. package/lib/chevre/service/assetTransaction/refund/factory.js +36 -16
  202. package/lib/chevre/service/assetTransaction/refund/potentialActions.js +12 -21
  203. package/lib/chevre/service/assetTransaction/refund.js +35 -41
  204. package/lib/chevre/service/assetTransaction/registerService/factory.js +65 -28
  205. package/lib/chevre/service/assetTransaction/registerService/potentialActions.js +50 -43
  206. package/lib/chevre/service/assetTransaction/registerService.js +45 -56
  207. package/lib/chevre/service/assetTransaction/reserve/cancel.js +5 -14
  208. package/lib/chevre/service/assetTransaction/reserve/confirm/factory.js +15 -4
  209. package/lib/chevre/service/assetTransaction/reserve/confirm.js +21 -26
  210. package/lib/chevre/service/assetTransaction/reserve/exportTasksById.js +3 -13
  211. package/lib/chevre/service/assetTransaction/reserve/start/createSubReservations.js +99 -83
  212. package/lib/chevre/service/assetTransaction/reserve/start/factory/createPointAward.js +17 -12
  213. package/lib/chevre/service/assetTransaction/reserve/start/factory/createReservation.js +108 -72
  214. package/lib/chevre/service/assetTransaction/reserve/start/factory/createStartParams.js +69 -30
  215. package/lib/chevre/service/assetTransaction/reserve/start/factory/price.js +29 -20
  216. package/lib/chevre/service/assetTransaction/reserve/start.js +91 -108
  217. package/lib/chevre/service/assetTransaction/reserve/validateStartRequest/fixExtendedEventOffer.js +5 -15
  218. package/lib/chevre/service/assetTransaction/reserve/validateStartRequest/validateIssuedOfferIfExists.js +41 -54
  219. package/lib/chevre/service/assetTransaction/reserve/validateStartRequest/validateMemberTierIfExists.js +42 -56
  220. package/lib/chevre/service/assetTransaction/reserve/validateStartRequest/verifyTicketTokenAsNeeded.js +7 -19
  221. package/lib/chevre/service/assetTransaction/reserve/validateStartRequest.js +15 -27
  222. package/lib/chevre/service/assetTransaction/reserveCOA/cancel.js +24 -24
  223. package/lib/chevre/service/assetTransaction/reserveCOA/factory.js +12 -4
  224. package/lib/chevre/service/assetTransaction/reserveCOA.js +4 -13
  225. package/lib/chevre/service/assetTransaction.js +17 -21
  226. package/lib/chevre/service/delivery/factory.js +3 -4
  227. package/lib/chevre/service/delivery/product/factory.js +16 -7
  228. package/lib/chevre/service/delivery/reservation/factory.js +14 -3
  229. package/lib/chevre/service/delivery.js +48 -52
  230. package/lib/chevre/service/event/processUpdateMovieTheater.js +21 -26
  231. package/lib/chevre/service/event/saveScreeningEventSeries.js +56 -41
  232. package/lib/chevre/service/event/saveScreeningEvents.js +14 -29
  233. package/lib/chevre/service/event.js +34 -30
  234. package/lib/chevre/service/iam.js +8 -17
  235. package/lib/chevre/service/moneyTransfer.js +128 -112
  236. package/lib/chevre/service/notification/factory.js +11 -10
  237. package/lib/chevre/service/notification/notifyAbortedTasksByEmail.js +11 -15
  238. package/lib/chevre/service/notification/notifyByEmail.js +7 -19
  239. package/lib/chevre/service/notification/sendEmailMessage.js +23 -26
  240. package/lib/chevre/service/notification/triggerWebhook.js +58 -56
  241. package/lib/chevre/service/offer/any.js +6 -15
  242. package/lib/chevre/service/offer/event/authorize/factory.js +139 -63
  243. package/lib/chevre/service/offer/event/authorize/processStartReserve4chevre/requestedProgramMembershipUsed2permit.js +8 -19
  244. package/lib/chevre/service/offer/event/authorize/processStartReserve4chevre.js +43 -27
  245. package/lib/chevre/service/offer/event/authorize.js +114 -71
  246. package/lib/chevre/service/offer/event/checkAvailability.js +5 -15
  247. package/lib/chevre/service/offer/event/importFromCOA/factory.js +9 -3
  248. package/lib/chevre/service/offer/event/importFromCOA.js +13 -19
  249. package/lib/chevre/service/offer/event/issueEventOfferTicket.js +38 -39
  250. package/lib/chevre/service/offer/event/searchEventTicketOffers.js +26 -41
  251. package/lib/chevre/service/offer/event/searchOfferAppliesToMovieTicket.js +11 -22
  252. package/lib/chevre/service/offer/event/searchOfferCatalogItemAvailability.js +13 -26
  253. package/lib/chevre/service/offer/event/searchOfferCatalogItems.js +15 -23
  254. package/lib/chevre/service/offer/event/searchOffersByIds.js +24 -39
  255. package/lib/chevre/service/offer/event/searchPriceSpecs4event.js +5 -14
  256. package/lib/chevre/service/offer/event/voidTransaction/processVoidTransaction4chevre.js +4 -13
  257. package/lib/chevre/service/offer/event/voidTransaction/processVoidTransaction4coa.js +6 -15
  258. package/lib/chevre/service/offer/event/voidTransaction.js +35 -41
  259. package/lib/chevre/service/offer/event/voidTransactionByActionId.js +14 -20
  260. package/lib/chevre/service/offer/eventServiceByCOA/acceptOffer/authorize.js +52 -42
  261. package/lib/chevre/service/offer/eventServiceByCOA/acceptOffer/factory.js +5 -1
  262. package/lib/chevre/service/offer/eventServiceByCOA/acceptOffer.js +34 -37
  263. package/lib/chevre/service/offer/eventServiceByCOA/authorize/factory.js +45 -26
  264. package/lib/chevre/service/offer/eventServiceByCOA/authorize/validateAcceptedOffers.js +67 -62
  265. package/lib/chevre/service/offer/eventServiceByCOA/authorize.js +16 -27
  266. package/lib/chevre/service/offer/eventServiceByCOA/authorizeByAcceptAction.js +8 -18
  267. package/lib/chevre/service/offer/eventServiceByCOA/changeOffers.js +42 -43
  268. package/lib/chevre/service/offer/eventServiceByCOA/findAcceptAction.js +22 -25
  269. package/lib/chevre/service/offer/factory.js +18 -8
  270. package/lib/chevre/service/offer/moneyTransfer/authorize.js +31 -36
  271. package/lib/chevre/service/offer/moneyTransfer/returnMoneyTransfer.js +9 -18
  272. package/lib/chevre/service/offer/moneyTransfer/settleTransaction.js +10 -19
  273. package/lib/chevre/service/offer/moneyTransfer/voidTransaction.js +14 -24
  274. package/lib/chevre/service/offer/onEventChanged.js +69 -65
  275. package/lib/chevre/service/offer/product/factory.js +54 -32
  276. package/lib/chevre/service/offer/product/searchProductOffers.js +30 -24
  277. package/lib/chevre/service/offer/product.js +106 -82
  278. package/lib/chevre/service/offer.js +48 -45
  279. package/lib/chevre/service/order/confirmPayTransaction.js +28 -27
  280. package/lib/chevre/service/order/createAccountingReportIfNotExist.js +54 -41
  281. package/lib/chevre/service/order/deleteOrder.js +28 -36
  282. package/lib/chevre/service/order/findPlaceOrderTransaction.js +3 -12
  283. package/lib/chevre/service/order/onAssetTransactionStatusChanged.js +64 -70
  284. package/lib/chevre/service/order/onOrderStatusChanged/onOrderCancelled/factory.js +1 -2
  285. package/lib/chevre/service/order/onOrderStatusChanged/onOrderCancelled.js +3 -12
  286. package/lib/chevre/service/order/onOrderStatusChanged/onOrderDelivered/factory.js +11 -6
  287. package/lib/chevre/service/order/onOrderStatusChanged/onOrderDelivered.js +5 -14
  288. package/lib/chevre/service/order/onOrderStatusChanged/onOrderDeliveredPartially/factory.js +22 -9
  289. package/lib/chevre/service/order/onOrderStatusChanged/onOrderDeliveredPartially.js +5 -14
  290. package/lib/chevre/service/order/onOrderStatusChanged/onOrderInTransit.js +23 -26
  291. package/lib/chevre/service/order/onOrderStatusChanged/onOrderPaymentDue.js +13 -19
  292. package/lib/chevre/service/order/onOrderStatusChanged/onOrderProcessing/createSendEmailMessageTaskIfNotExist.js +5 -14
  293. package/lib/chevre/service/order/onOrderStatusChanged/onOrderProcessing/factory.js +24 -14
  294. package/lib/chevre/service/order/onOrderStatusChanged/onOrderProcessing/processOrder.js +23 -32
  295. package/lib/chevre/service/order/onOrderStatusChanged/onOrderProcessing.js +8 -18
  296. package/lib/chevre/service/order/onOrderStatusChanged/onOrderReturned/factory.js +10 -9
  297. package/lib/chevre/service/order/onOrderStatusChanged/onOrderReturned.js +23 -28
  298. package/lib/chevre/service/order/onOrderUpdated/factory.js +3 -5
  299. package/lib/chevre/service/order/onOrderUpdated.js +13 -15
  300. package/lib/chevre/service/order/payOrder.js +3 -12
  301. package/lib/chevre/service/order/placeOrder/createPlacingOrderFromExistingTransaction.js +9 -20
  302. package/lib/chevre/service/order/placeOrder/factory/orderedItem.js +31 -15
  303. package/lib/chevre/service/order/placeOrder/factory.js +35 -22
  304. package/lib/chevre/service/order/placeOrder/voidAcceptedOfferIfNecessary.js +3 -12
  305. package/lib/chevre/service/order/placeOrder.js +12 -23
  306. package/lib/chevre/service/order/placeOrderWithoutTransaction.js +10 -18
  307. package/lib/chevre/service/order/returnOrder.js +27 -30
  308. package/lib/chevre/service/order/sendOrder.js +37 -37
  309. package/lib/chevre/service/payment/any/authorize/fixTransactionNumber.js +19 -25
  310. package/lib/chevre/service/payment/any/authorize/handlePrePublishedPaymentMethodIdOnAuthorizing.js +24 -39
  311. package/lib/chevre/service/payment/any/factory.js +106 -50
  312. package/lib/chevre/service/payment/any/fixOrderAsNeeded.js +4 -13
  313. package/lib/chevre/service/payment/any/onPayActionCompleted.js +13 -18
  314. package/lib/chevre/service/payment/any/onPaymentStatusChanged/onPaid.js +34 -37
  315. package/lib/chevre/service/payment/any/onPaymentStatusChanged/onRefunded.js +18 -24
  316. package/lib/chevre/service/payment/any/onPaymentStatusChanged.js +16 -16
  317. package/lib/chevre/service/payment/any/onRefundActionCompletedOrFailed.js +15 -21
  318. package/lib/chevre/service/payment/any/person2username.js +32 -45
  319. package/lib/chevre/service/payment/any/publishPaymentUrl/fixTransactionNumberOnPublishPaymentUrl.js +8 -18
  320. package/lib/chevre/service/payment/any/verifyTicketTokenAsNeeded.js +5 -17
  321. package/lib/chevre/service/payment/any.js +181 -142
  322. package/lib/chevre/service/payment/creditCard/authorize/handleAuthorizeError.js +2 -2
  323. package/lib/chevre/service/payment/creditCard/authorize/processAuthorizeCreditCard.js +44 -25
  324. package/lib/chevre/service/payment/creditCard/authorize/processAuthorizeCreditCard3ds.js +6 -15
  325. package/lib/chevre/service/payment/creditCard/authorize/processAuthorizeCreditCard3dsResult2recipe.js +5 -1
  326. package/lib/chevre/service/payment/creditCard/authorize/processAuthorizeCreditCardResult2recipe.js +10 -2
  327. package/lib/chevre/service/payment/creditCard/authorize.js +20 -22
  328. package/lib/chevre/service/payment/creditCard/factory.js +22 -4
  329. package/lib/chevre/service/payment/creditCard/getGMOInfoFromSeller.js +8 -18
  330. package/lib/chevre/service/payment/creditCard/payCreditCard.js +31 -36
  331. package/lib/chevre/service/payment/creditCard/refundCreditCard.js +40 -51
  332. package/lib/chevre/service/payment/creditCard/searchGMOTrade.js +33 -45
  333. package/lib/chevre/service/payment/creditCard/voidTransaction.js +15 -26
  334. package/lib/chevre/service/payment/faceToFace.js +14 -23
  335. package/lib/chevre/service/payment/factory/createPayObjectServiceOutput.js +44 -25
  336. package/lib/chevre/service/payment/factory.js +50 -24
  337. package/lib/chevre/service/payment/movieTicket/authorize.js +35 -30
  338. package/lib/chevre/service/payment/movieTicket/checkMovieTicket.js +22 -25
  339. package/lib/chevre/service/payment/movieTicket/factory.js +33 -10
  340. package/lib/chevre/service/payment/movieTicket/getCredentials.js +5 -15
  341. package/lib/chevre/service/payment/movieTicket/payMovieTicket.js +29 -40
  342. package/lib/chevre/service/payment/movieTicket/processPurchaseNumberAuth.js +8 -18
  343. package/lib/chevre/service/payment/movieTicket/refundMovieTicket.js +60 -60
  344. package/lib/chevre/service/payment/movieTicket/validation.js +41 -37
  345. package/lib/chevre/service/payment/movieTicket/voidTransaction.js +8 -18
  346. package/lib/chevre/service/payment/paymentCard.js +87 -104
  347. package/lib/chevre/service/permit.js +36 -35
  348. package/lib/chevre/service/product.js +23 -28
  349. package/lib/chevre/service/project.js +22 -31
  350. package/lib/chevre/service/report/ownershipInfo.js +3 -4
  351. package/lib/chevre/service/report/telemetry.js +51 -70
  352. package/lib/chevre/service/reserve/cancelReservation.js +92 -93
  353. package/lib/chevre/service/reserve/checkInReservation.js +24 -29
  354. package/lib/chevre/service/reserve/confirmReservation.js +33 -39
  355. package/lib/chevre/service/reserve/factory.js +42 -20
  356. package/lib/chevre/service/reserve/findByCode.js +13 -18
  357. package/lib/chevre/service/reserve/potentialActions/onPendingReservationCanceled.js +18 -24
  358. package/lib/chevre/service/reserve/potentialActions/onReservationCanceled.js +17 -25
  359. package/lib/chevre/service/reserve/potentialActions/onReservationCheckedIn.js +38 -30
  360. package/lib/chevre/service/reserve/potentialActions/onReservationConfirmed.js +45 -37
  361. package/lib/chevre/service/reserve/potentialActions/onReservationUsed.js +37 -33
  362. package/lib/chevre/service/reserve/potentialActions/onReservationsCreated.js +17 -23
  363. package/lib/chevre/service/reserve/searchByOrder.js +10 -20
  364. package/lib/chevre/service/reserve/useReservation.js +47 -34
  365. package/lib/chevre/service/reserve/verifyToken4reservation.js +7 -14
  366. package/lib/chevre/service/reserveCOA/cancelReservation.js +7 -17
  367. package/lib/chevre/service/reserveCOA/factory.js +5 -1
  368. package/lib/chevre/service/task/acceptCOAOffer.js +20 -25
  369. package/lib/chevre/service/task/aggregateOffers.js +3 -12
  370. package/lib/chevre/service/task/aggregateOnSystem.js +4 -14
  371. package/lib/chevre/service/task/aggregateScreeningEvent.js +3 -12
  372. package/lib/chevre/service/task/authorizePayment.js +9 -15
  373. package/lib/chevre/service/task/cancelMoneyTransfer.js +3 -12
  374. package/lib/chevre/service/task/cancelPendingReservation.js +10 -20
  375. package/lib/chevre/service/task/cancelReservation.js +3 -12
  376. package/lib/chevre/service/task/checkMovieTicket.js +16 -19
  377. package/lib/chevre/service/task/checkResource.js +7 -16
  378. package/lib/chevre/service/task/confirmMoneyTransfer.js +3 -12
  379. package/lib/chevre/service/task/confirmPayTransaction.js +6 -12
  380. package/lib/chevre/service/task/confirmRegisterService.js +3 -12
  381. package/lib/chevre/service/task/confirmRegisterServiceTransaction.js +24 -31
  382. package/lib/chevre/service/task/confirmReserveTransaction.js +48 -45
  383. package/lib/chevre/service/task/createAccountingReport.js +14 -20
  384. package/lib/chevre/service/task/deletePerson.js +48 -60
  385. package/lib/chevre/service/task/deleteTransaction.js +3 -12
  386. package/lib/chevre/service/task/givePointAward.js +3 -12
  387. package/lib/chevre/service/task/handleNotification.js +4 -14
  388. package/lib/chevre/service/task/importEventCapacitiesFromCOA.js +6 -16
  389. package/lib/chevre/service/task/importEventsFromCOA.js +6 -16
  390. package/lib/chevre/service/task/importOffersFromCOA.js +8 -18
  391. package/lib/chevre/service/task/invalidatePaymentUrl.js +6 -12
  392. package/lib/chevre/service/task/moneyTransfer.js +3 -12
  393. package/lib/chevre/service/task/onAssetTransactionStatusChanged.js +3 -12
  394. package/lib/chevre/service/task/onAuthorizationCreated.js +11 -19
  395. package/lib/chevre/service/task/onEventChanged.js +3 -12
  396. package/lib/chevre/service/task/onOrderPaymentCompleted.js +3 -12
  397. package/lib/chevre/service/task/onResourceDeleted/deleteResourcesByAggregateOffer.js +7 -16
  398. package/lib/chevre/service/task/onResourceDeleted/deleteResourcesByEventSeries.js +7 -16
  399. package/lib/chevre/service/task/onResourceDeleted/deleteResourcesByMovieTheater.js +8 -17
  400. package/lib/chevre/service/task/onResourceDeleted/deleteResourcesByOfferCatalog.js +10 -19
  401. package/lib/chevre/service/task/onResourceDeleted/deleteResourcesByProduct.js +8 -17
  402. package/lib/chevre/service/task/onResourceDeleted/deleteResourcesByRoom.js +6 -15
  403. package/lib/chevre/service/task/onResourceDeleted/deleteResourcesBySeller.js +14 -24
  404. package/lib/chevre/service/task/onResourceDeleted.js +17 -27
  405. package/lib/chevre/service/task/onResourceUpdated/onAggregateOfferUpdated.js +9 -21
  406. package/lib/chevre/service/task/onResourceUpdated/onCategoryCodeUpdated.js +3 -12
  407. package/lib/chevre/service/task/onResourceUpdated/onHasPOSUpdated.js +11 -23
  408. package/lib/chevre/service/task/onResourceUpdated/onOfferCatalogUpdated.js +13 -25
  409. package/lib/chevre/service/task/onResourceUpdated/syncCategoryCode.js +9 -15
  410. package/lib/chevre/service/task/onResourceUpdated/syncOfferCatalog.js +21 -27
  411. package/lib/chevre/service/task/onResourceUpdated.js +113 -158
  412. package/lib/chevre/service/task/pay.js +8 -16
  413. package/lib/chevre/service/task/payment/invalidatePaymentUrlByTask.js +4 -14
  414. package/lib/chevre/service/task/payment/payByTask.js +49 -38
  415. package/lib/chevre/service/task/payment/refundByTask.js +7 -17
  416. package/lib/chevre/service/task/payment/voidPaymentByTask.js +6 -15
  417. package/lib/chevre/service/task/placeOrder.js +6 -12
  418. package/lib/chevre/service/task/publishPaymentUrl.js +9 -14
  419. package/lib/chevre/service/task/refund.js +8 -16
  420. package/lib/chevre/service/task/registerService.js +3 -12
  421. package/lib/chevre/service/task/reserve.js +3 -12
  422. package/lib/chevre/service/task/returnMoneyTransfer.js +3 -12
  423. package/lib/chevre/service/task/returnOrder.js +6 -12
  424. package/lib/chevre/service/task/returnPayTransaction.js +54 -49
  425. package/lib/chevre/service/task/returnPointAward.js +3 -12
  426. package/lib/chevre/service/task/returnReserveTransaction.js +29 -30
  427. package/lib/chevre/service/task/sendEmailMessage.js +6 -13
  428. package/lib/chevre/service/task/sendOrder.js +12 -15
  429. package/lib/chevre/service/task/syncResourcesFromCOA.js +39 -45
  430. package/lib/chevre/service/task/triggerWebhook.js +6 -12
  431. package/lib/chevre/service/task/useReservation.js +11 -14
  432. package/lib/chevre/service/task/voidMoneyTransferTransaction.js +3 -12
  433. package/lib/chevre/service/task/voidPayTransaction.js +7 -12
  434. package/lib/chevre/service/task/voidPayment.js +3 -12
  435. package/lib/chevre/service/task/voidRegisterServiceTransaction.js +3 -12
  436. package/lib/chevre/service/task/voidReserveTransaction.js +10 -16
  437. package/lib/chevre/service/task.js +16 -26
  438. package/lib/chevre/service/taskHandler/onOperationFailed/informTaskIfNeeded.js +9 -20
  439. package/lib/chevre/service/taskHandler/onOperationFailed.js +20 -17
  440. package/lib/chevre/service/taskHandler.js +19 -22
  441. package/lib/chevre/service/transaction/deleteTransaction.js +104 -88
  442. package/lib/chevre/service/transaction/moneyTransfer/exportTasks/factory.js +15 -9
  443. package/lib/chevre/service/transaction/moneyTransfer/factory.js +13 -4
  444. package/lib/chevre/service/transaction/moneyTransfer/potentialActions.js +12 -24
  445. package/lib/chevre/service/transaction/moneyTransfer.js +119 -98
  446. package/lib/chevre/service/transaction/placeOrder/confirm/potentialActions/sendEmailMessage.js +49 -51
  447. package/lib/chevre/service/transaction/placeOrder/confirm/potentialActions.js +14 -25
  448. package/lib/chevre/service/transaction/placeOrder/confirm/publishCode.js +4 -14
  449. package/lib/chevre/service/transaction/placeOrder/confirm/validation/validateInvoiceReferencesOrder.js +3 -4
  450. package/lib/chevre/service/transaction/placeOrder/confirm/validation/validateMovieTicket.js +3 -6
  451. package/lib/chevre/service/transaction/placeOrder/confirm/validation/validatePrice.js +2 -3
  452. package/lib/chevre/service/transaction/placeOrder/confirm/validation.js +30 -47
  453. package/lib/chevre/service/transaction/placeOrder/confirm.js +75 -59
  454. package/lib/chevre/service/transaction/placeOrder/exportTasks/factory.js +31 -15
  455. package/lib/chevre/service/transaction/placeOrder/exportTasksById.js +6 -15
  456. package/lib/chevre/service/transaction/placeOrder/publishConfirmationNumberIfNotExist.js +6 -15
  457. package/lib/chevre/service/transaction/placeOrder/publishOrderNumberIfNotExist.js +7 -16
  458. package/lib/chevre/service/transaction/placeOrder/start/factory.js +27 -7
  459. package/lib/chevre/service/transaction/placeOrder/start/validateStartRequest.js +53 -60
  460. package/lib/chevre/service/transaction/placeOrder/start.js +14 -18
  461. package/lib/chevre/service/transaction/returnOrder/exportTasks/factory.js +13 -7
  462. package/lib/chevre/service/transaction/returnOrder/potentialActions/returnPaymentMethod.js +176 -190
  463. package/lib/chevre/service/transaction/returnOrder/potentialActions/returnPointAward.js +75 -89
  464. package/lib/chevre/service/transaction/returnOrder/potentialActions/sendEmailMessage.js +40 -48
  465. package/lib/chevre/service/transaction/returnOrder/potentialActions.js +52 -56
  466. package/lib/chevre/service/transaction/returnOrder/preStart/findApplicableReturnPolicy.js +100 -104
  467. package/lib/chevre/service/transaction/returnOrder/preStart/getReturnPolicyByProject.js +60 -80
  468. package/lib/chevre/service/transaction/returnOrder/preStart.js +42 -47
  469. package/lib/chevre/service/transaction/returnOrder.js +32 -37
  470. package/lib/chevre/service/transaction.js +75 -46
  471. package/lib/chevre/service/validation/validateEvent.js +2 -11
  472. package/lib/chevre/service/validation/validateOrder.js +7 -18
  473. package/lib/chevre/service.js +85 -131
  474. package/lib/chevre/settings/aggregation.js +4 -0
  475. package/lib/chevre/settings.js +7 -1
  476. package/lib/index.js +0 -1
  477. package/package.json +6 -11
  478. package/example/src/chevre/addEventBySchedule.ts +0 -46
  479. package/example/src/idaas/auth0/adminApplications.ts +0 -183
  480. package/example/src/idaas/auth0/getToken.ts +0 -55
  481. package/example/src/idaas/auth0/getTokenByPrivateKeyJWT.ts +0 -84
@@ -1,24 +1,4 @@
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 __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
2
  Object.defineProperty(exports, "__esModule", { value: true });
23
3
  exports.TaskRepo = void 0;
24
4
  const moment = require("moment");
@@ -69,18 +49,17 @@ const AVAILABLE_PROJECT_FIELDS = [
69
49
  * タスクリポジトリ
70
50
  */
71
51
  class TaskRepo {
52
+ taskModel;
72
53
  constructor(connection) {
73
54
  this.taskModel = connection.model(task_2.modelName, (0, task_2.createSchema)());
74
55
  }
75
- // tslint:disable-next-line:cyclomatic-complexity max-func-body-length
76
56
  static CREATE_MONGO_CONDITIONS(params) {
77
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
78
57
  const andConditions = [];
79
- const idEq = (_a = params.id) === null || _a === void 0 ? void 0 : _a.$eq;
58
+ const idEq = params.id?.$eq;
80
59
  if (typeof idEq === 'string') {
81
60
  andConditions.push({ _id: { $eq: idEq } });
82
61
  }
83
- const projectIdEq = (_c = (_b = params.project) === null || _b === void 0 ? void 0 : _b.id) === null || _c === void 0 ? void 0 : _c.$eq;
62
+ const projectIdEq = params.project?.id?.$eq;
84
63
  if (typeof projectIdEq === 'string') {
85
64
  andConditions.push({ 'project.id': { $eq: projectIdEq } });
86
65
  }
@@ -88,16 +67,16 @@ class TaskRepo {
88
67
  andConditions.push({ name: { $eq: params.name } });
89
68
  }
90
69
  else {
91
- const nameIn = (_d = params.name) === null || _d === void 0 ? void 0 : _d.$in;
70
+ const nameIn = params.name?.$in;
92
71
  if (Array.isArray(nameIn)) {
93
72
  andConditions.push({ name: { $in: nameIn } });
94
73
  }
95
- const nameNin = (_e = params.name) === null || _e === void 0 ? void 0 : _e.$nin;
74
+ const nameNin = params.name?.$nin;
96
75
  if (Array.isArray(nameNin)) {
97
76
  andConditions.push({ name: { $nin: nameNin } });
98
77
  }
99
78
  }
100
- const statusEq = (_f = params.status) === null || _f === void 0 ? void 0 : _f.$eq;
79
+ const statusEq = params.status?.$eq;
101
80
  if (typeof statusEq === 'string') {
102
81
  andConditions.push({ status: { $eq: statusEq } });
103
82
  }
@@ -116,206 +95,170 @@ class TaskRepo {
116
95
  if (params.lastTriedThrough instanceof Date) {
117
96
  andConditions.push({ lastTriedAt: { $type: 'date', $lte: params.lastTriedThrough } });
118
97
  }
119
- const dateAbortedGte = (_g = params.dateAborted) === null || _g === void 0 ? void 0 : _g.$gte;
98
+ const dateAbortedGte = params.dateAborted?.$gte;
120
99
  if (dateAbortedGte instanceof Date) {
121
100
  andConditions.push({ dateAborted: { $type: 'date', $gte: dateAbortedGte } });
122
101
  }
123
- const dateAbortedLte = (_h = params.dateAborted) === null || _h === void 0 ? void 0 : _h.$lte;
102
+ const dateAbortedLte = params.dateAborted?.$lte;
124
103
  if (dateAbortedLte instanceof Date) {
125
104
  andConditions.push({ dateAborted: { $type: 'date', $lte: dateAbortedLte } });
126
105
  }
127
- const objectIdEq = (_l = (_k = (_j = params.data) === null || _j === void 0 ? void 0 : _j.object) === null || _k === void 0 ? void 0 : _k.id) === null || _l === void 0 ? void 0 : _l.$eq;
106
+ const objectIdEq = params.data?.object?.id?.$eq;
128
107
  if (typeof objectIdEq === 'string') {
129
108
  andConditions.push({ 'data.object.id': { $exists: true, $eq: objectIdEq } });
130
109
  }
131
- const objectOrderNumberEq = (_p = (_o = (_m = params.data) === null || _m === void 0 ? void 0 : _m.object) === null || _o === void 0 ? void 0 : _o.orderNumber) === null || _p === void 0 ? void 0 : _p.$eq;
110
+ const objectOrderNumberEq = params.data?.object?.orderNumber?.$eq;
132
111
  if (typeof objectOrderNumberEq === 'string') {
133
112
  andConditions.push({ 'data.object.orderNumber': { $exists: true, $eq: objectOrderNumberEq } });
134
113
  }
135
- const objectTransactionNumberEq = (_s = (_r = (_q = params.data) === null || _q === void 0 ? void 0 : _q.object) === null || _r === void 0 ? void 0 : _r.transactionNumber) === null || _s === void 0 ? void 0 : _s.$eq;
114
+ const objectTransactionNumberEq = params.data?.object?.transactionNumber?.$eq;
136
115
  if (typeof objectTransactionNumberEq === 'string') {
137
116
  andConditions.push({ 'data.object.transactionNumber': { $exists: true, $eq: objectTransactionNumberEq } });
138
117
  }
139
- const objectPurposeIdEq = (_v = (_u = (_t = params.data) === null || _t === void 0 ? void 0 : _t.purpose) === null || _u === void 0 ? void 0 : _u.id) === null || _v === void 0 ? void 0 : _v.$eq;
118
+ const objectPurposeIdEq = params.data?.purpose?.id?.$eq;
140
119
  if (typeof objectPurposeIdEq === 'string') {
141
120
  andConditions.push({ 'data.purpose.id': { $exists: true, $eq: objectPurposeIdEq } });
142
121
  }
143
- const objectPurposeOrderNumberEq = (_y = (_x = (_w = params.data) === null || _w === void 0 ? void 0 : _w.purpose) === null || _x === void 0 ? void 0 : _x.orderNumber) === null || _y === void 0 ? void 0 : _y.$eq;
122
+ const objectPurposeOrderNumberEq = params.data?.purpose?.orderNumber?.$eq;
144
123
  if (typeof objectPurposeOrderNumberEq === 'string') {
145
124
  andConditions.push({ 'data.purpose.orderNumber': { $exists: true, $eq: objectPurposeOrderNumberEq } });
146
125
  }
147
- const alternateNameRegex = (_z = params.alternateName) === null || _z === void 0 ? void 0 : _z.$regex;
126
+ const alternateNameRegex = params.alternateName?.$regex;
148
127
  if (typeof alternateNameRegex === 'string' && alternateNameRegex.length > 0) {
149
128
  andConditions.push({ alternateName: { $exists: true, $regex: new RegExp(alternateNameRegex) } });
150
129
  }
151
- const identifierRegex = (_0 = params.identifier) === null || _0 === void 0 ? void 0 : _0.$regex;
130
+ const identifierRegex = params.identifier?.$regex;
152
131
  if (typeof identifierRegex === 'string' && identifierRegex.length > 0) {
153
132
  andConditions.push({ identifier: { $exists: true, $regex: new RegExp(identifierRegex) } });
154
133
  }
155
134
  return andConditions;
156
135
  }
157
- runImmediately(
136
+ async runImmediately(
158
137
  // resolve uniqueness of identifier(2025-03-27~)
159
138
  params,
160
139
  // support customr function(2025-05-25~)
161
140
  next) {
162
- return __awaiter(this, void 0, void 0, function* () {
163
- var _a, _b;
164
- const { expires } = params;
165
- if (!(expires instanceof Date)) {
166
- throw new factory.errors.Argument('expires', 'must be Date');
167
- }
168
- const savingTask = Object.assign(Object.assign({}, params), { status: factory.taskStatus.Ready, numberOfTried: 0, executionResults: [] });
169
- const result = yield this.taskModel.insertMany(savingTask, { rawResult: true });
170
- const id = (_b = (_a = result.insertedIds) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.toHexString();
171
- if (typeof id !== 'string') {
172
- throw new factory.errors.Internal('task not saved');
173
- }
174
- task_1.taskEventEmitter.emitTaskStatusChanged({
175
- id,
176
- status: factory.taskStatus.Ready,
177
- expires // emit expires(2025-03-31~)
178
- }, next);
179
- return { id };
180
- });
141
+ const { expires } = params;
142
+ if (!(expires instanceof Date)) {
143
+ throw new factory.errors.Argument('expires', 'must be Date');
144
+ }
145
+ const savingTask = {
146
+ ...params,
147
+ status: factory.taskStatus.Ready,
148
+ numberOfTried: 0,
149
+ executionResults: []
150
+ };
151
+ const result = await this.taskModel.insertMany(savingTask, { rawResult: true });
152
+ const id = result.insertedIds?.[0]?.toHexString();
153
+ if (typeof id !== 'string') {
154
+ throw new factory.errors.Internal('task not saved');
155
+ }
156
+ task_1.taskEventEmitter.emitTaskStatusChanged({
157
+ id,
158
+ status: factory.taskStatus.Ready,
159
+ expires // emit expires(2025-03-31~)
160
+ }, next);
161
+ return { id };
181
162
  }
182
- saveMany(taskAttributes, options) {
183
- return __awaiter(this, void 0, void 0, function* () {
184
- const emitImmediately = (options === null || options === void 0 ? void 0 : options.emitImmediately) === true;
185
- if (taskAttributes.length > 0) {
186
- // resolve uniqueness of identifier(2025-03-27~)
187
- const creatingTasks = taskAttributes.map((_a) => {
188
- var { identifier } = _a, creatingTask = __rest(_a, ["identifier"]);
189
- return creatingTask;
190
- });
191
- const result = yield this.taskModel.insertMany(creatingTasks, { ordered: false, rawResult: true });
192
- if (result.insertedCount !== taskAttributes.length) {
193
- throw new factory.errors.Internal('all tasks not saved');
194
- }
195
- const savedTasks = Object.values(result.insertedIds)
196
- .map((objectId) => {
197
- return { id: objectId.toHexString() };
198
- });
199
- if (emitImmediately) {
200
- savedTasks.forEach((savedTask) => {
201
- task_1.taskEventEmitter.emitTaskStatusChanged({
202
- id: savedTask.id,
203
- status: factory.taskStatus.Ready
204
- });
163
+ async saveMany(taskAttributes, options) {
164
+ const emitImmediately = options?.emitImmediately === true;
165
+ if (taskAttributes.length > 0) {
166
+ // resolve uniqueness of identifier(2025-03-27~)
167
+ const creatingTasks = taskAttributes.map(({ identifier, ...creatingTask }) => creatingTask);
168
+ const result = await this.taskModel.insertMany(creatingTasks, { ordered: false, rawResult: true });
169
+ if (result.insertedCount !== taskAttributes.length) {
170
+ throw new factory.errors.Internal('all tasks not saved');
171
+ }
172
+ const savedTasks = Object.values(result.insertedIds)
173
+ .map((objectId) => {
174
+ return { id: objectId.toHexString() };
175
+ });
176
+ if (emitImmediately) {
177
+ savedTasks.forEach((savedTask) => {
178
+ task_1.taskEventEmitter.emitTaskStatusChanged({
179
+ id: savedTask.id,
180
+ status: factory.taskStatus.Ready
205
181
  });
206
- // taskAttributes.forEach((savedTask) => {
207
- // taskEventEmitter.emitTaskStatusChanged({
208
- // name: savedTask.name,
209
- // status: factory.taskStatus.Ready
210
- // });
211
- // });
212
- }
213
- // return result.ops;
214
- return savedTasks;
215
- }
216
- else {
217
- return [];
218
- }
219
- });
182
+ });
183
+ // taskAttributes.forEach((savedTask) => {
184
+ // taskEventEmitter.emitTaskStatusChanged({
185
+ // name: savedTask.name,
186
+ // status: factory.taskStatus.Ready
187
+ // });
188
+ // });
189
+ }
190
+ // return result.ops;
191
+ return savedTasks;
192
+ }
193
+ else {
194
+ return [];
195
+ }
220
196
  }
221
197
  /**
222
198
  * タスク識別子から検索する
223
199
  */
224
- findByIdentifier(params) {
225
- return __awaiter(this, void 0, void 0, function* () {
226
- const projection = {
227
- _id: 0,
228
- id: { $toString: '$_id' },
229
- status: 1
230
- };
231
- const doc = yield this.taskModel.findOne({
232
- 'project.id': { $eq: params.project.id },
233
- name: { $eq: params.name },
234
- identifier: { $exists: true, $eq: params.identifier }
235
- }, projection)
236
- .lean() // lean(2024-09-26~)
237
- .exec();
238
- if (doc === null) {
239
- return;
240
- }
241
- const { id, status } = doc;
242
- return { id, status };
243
- });
200
+ async findByIdentifier(params) {
201
+ const projection = {
202
+ _id: 0,
203
+ id: { $toString: '$_id' },
204
+ status: 1
205
+ };
206
+ const doc = await this.taskModel.findOne({
207
+ 'project.id': { $eq: params.project.id },
208
+ name: { $eq: params.name },
209
+ identifier: { $exists: true, $eq: params.identifier }
210
+ }, projection)
211
+ .lean() // lean(2024-09-26~)
212
+ .exec();
213
+ if (doc === null) {
214
+ return;
215
+ }
216
+ const { id, status } = doc;
217
+ return { id, status };
244
218
  }
245
219
  /**
246
220
  * タスク識別子から冪等作成する
247
221
  * reimplement createIfNotExistByIdentifier(2025-03-28~)
248
222
  */
249
- createIfNotExistByAlternateName(params, options) {
250
- return __awaiter(this, void 0, void 0, function* () {
251
- if (typeof params.alternateName !== 'string' || params.alternateName.length === 0) {
252
- throw new factory.errors.ArgumentNull('alternateName');
253
- }
254
- let createdTask;
255
- const filterQuery = {
256
- 'project.id': { $eq: params.project.id },
257
- name: { $eq: params.name },
258
- alternateName: { $exists: true, $eq: params.alternateName }
259
- };
260
- const projection = {
261
- _id: 0,
262
- id: { $toString: '$_id' }
263
- };
264
- try {
265
- createdTask = yield this.taskModel.findOneAndUpdate(filterQuery, { $setOnInsert: params }, {
266
- new: true,
267
- upsert: true,
268
- projection
269
- })
270
- .lean()
271
- .exec();
272
- }
273
- catch (error) {
274
- let throwsError = true;
275
- if (yield (0, errorHandler_1.isMongoError)(error)) {
276
- // すでにalternateNameが存在する場合ok
277
- if (error.code === errorHandler_1.MongoErrorCode.DuplicateKey) {
278
- throwsError = false;
279
- createdTask = yield this.taskModel.findOne(filterQuery, projection)
280
- .lean()
281
- .exec();
282
- }
283
- }
284
- if (throwsError) {
285
- throw error;
286
- }
287
- }
288
- if (typeof (createdTask === null || createdTask === void 0 ? void 0 : createdTask.id) === 'string') {
289
- if (options.emitImmediately) {
290
- task_1.taskEventEmitter.emitTaskStatusChanged({
291
- id: createdTask.id,
292
- name: params.name,
293
- status: factory.taskStatus.Ready
294
- });
223
+ async createIfNotExistByAlternateName(params, options) {
224
+ if (typeof params.alternateName !== 'string' || params.alternateName.length === 0) {
225
+ throw new factory.errors.ArgumentNull('alternateName');
226
+ }
227
+ let createdTask;
228
+ const filterQuery = {
229
+ 'project.id': { $eq: params.project.id },
230
+ name: { $eq: params.name },
231
+ alternateName: { $exists: true, $eq: params.alternateName }
232
+ };
233
+ const projection = {
234
+ _id: 0,
235
+ id: { $toString: '$_id' }
236
+ };
237
+ try {
238
+ createdTask = await this.taskModel.findOneAndUpdate(filterQuery, { $setOnInsert: params }, {
239
+ new: true,
240
+ upsert: true,
241
+ projection
242
+ })
243
+ .lean()
244
+ .exec();
245
+ }
246
+ catch (error) {
247
+ let throwsError = true;
248
+ if (await (0, errorHandler_1.isMongoError)(error)) {
249
+ // すでにalternateNameが存在する場合ok
250
+ if (error.code === errorHandler_1.MongoErrorCode.DuplicateKey) {
251
+ throwsError = false;
252
+ createdTask = await this.taskModel.findOne(filterQuery, projection)
253
+ .lean()
254
+ .exec();
295
255
  }
296
256
  }
297
- else {
298
- throw new factory.errors.Internal(`falied in creating a task unexpectedly. ${params.alternateName}`);
299
- }
300
- });
301
- }
302
- /**
303
- * 取引削除タスク冪等作成
304
- */
305
- createDeleteTransactionTaskIfNotExist(
306
- // resolve uniqueness of identifier(2025-03-27~)
307
- params, options) {
308
- return __awaiter(this, void 0, void 0, function* () {
309
- if (params.data.object.specifyingMethod !== factory.action.update.deleteAction.ObjectAsTransactionSpecifyingMethod.Id) {
310
- throw new factory.errors.NotImplemented(`only ${factory.action.update.deleteAction.ObjectAsTransactionSpecifyingMethod.Id} implemented`);
257
+ if (throwsError) {
258
+ throw error;
311
259
  }
312
- const createdTask = yield this.taskModel.findOneAndUpdate({
313
- 'project.id': { $eq: params.project.id },
314
- name: { $eq: params.name },
315
- 'data.object.id': { $exists: true, $eq: params.data.object.id }
316
- }, { $setOnInsert: params }, { new: true, upsert: true })
317
- .select({ _id: 1 })
318
- .exec();
260
+ }
261
+ if (typeof createdTask?.id === 'string') {
319
262
  if (options.emitImmediately) {
320
263
  task_1.taskEventEmitter.emitTaskStatusChanged({
321
264
  id: createdTask.id,
@@ -323,157 +266,202 @@ class TaskRepo {
323
266
  status: factory.taskStatus.Ready
324
267
  });
325
268
  }
326
- });
269
+ }
270
+ else {
271
+ throw new factory.errors.Internal(`falied in creating a task unexpectedly. ${params.alternateName}`);
272
+ }
273
+ }
274
+ /**
275
+ * 取引削除タスク冪等作成
276
+ */
277
+ async createDeleteTransactionTaskIfNotExist(
278
+ // resolve uniqueness of identifier(2025-03-27~)
279
+ params, options) {
280
+ if (params.data.object.specifyingMethod !== factory.action.update.deleteAction.ObjectAsTransactionSpecifyingMethod.Id) {
281
+ throw new factory.errors.NotImplemented(`only ${factory.action.update.deleteAction.ObjectAsTransactionSpecifyingMethod.Id} implemented`);
282
+ }
283
+ const createdTask = await this.taskModel.findOneAndUpdate({
284
+ 'project.id': { $eq: params.project.id },
285
+ name: { $eq: params.name },
286
+ 'data.object.id': { $exists: true, $eq: params.data.object.id }
287
+ }, { $setOnInsert: params }, { new: true, upsert: true })
288
+ .select({ _id: 1 })
289
+ .exec();
290
+ if (options.emitImmediately) {
291
+ task_1.taskEventEmitter.emitTaskStatusChanged({
292
+ id: createdTask.id,
293
+ name: params.name,
294
+ status: factory.taskStatus.Ready
295
+ });
296
+ }
327
297
  }
328
- createOnAssetTransactionStatusChangedTaskIfNotExist(
298
+ async createOnAssetTransactionStatusChangedTaskIfNotExist(
329
299
  // resolve uniqueness of identifier(2025-03-27~)
330
300
  params, options) {
331
- return __awaiter(this, void 0, void 0, function* () {
332
- const createdTask = yield this.taskModel.findOneAndUpdate({
333
- 'project.id': { $eq: params.project.id },
334
- name: { $eq: params.name },
335
- 'data.object.transactionNumber': {
336
- $exists: true,
337
- $eq: String(params.data.object.transactionNumber)
338
- },
339
- 'data.purpose.orderNumber': {
340
- $exists: true,
341
- $eq: String(params.data.purpose.orderNumber)
342
- }
343
- }, { $setOnInsert: params }, { new: true, upsert: true })
344
- .select({ _id: 1 })
345
- .exec();
346
- if (options.emitImmediately) {
347
- task_1.taskEventEmitter.emitTaskStatusChanged({
348
- id: createdTask.id,
349
- name: params.name,
350
- status: factory.taskStatus.Ready
351
- });
352
- }
353
- });
301
+ const createdTask = await this.taskModel.findOneAndUpdate({
302
+ 'project.id': { $eq: params.project.id },
303
+ name: { $eq: params.name },
304
+ 'data.object.transactionNumber': {
305
+ $exists: true,
306
+ $eq: String(params.data.object.transactionNumber)
307
+ },
308
+ 'data.purpose.orderNumber': {
309
+ $exists: true,
310
+ $eq: String(params.data.purpose.orderNumber)
311
+ }
312
+ }, { $setOnInsert: params }, { new: true, upsert: true })
313
+ .select({ _id: 1 })
314
+ .exec();
315
+ if (options.emitImmediately) {
316
+ task_1.taskEventEmitter.emitTaskStatusChanged({
317
+ id: createdTask.id,
318
+ name: params.name,
319
+ status: factory.taskStatus.Ready
320
+ });
321
+ }
354
322
  }
355
323
  /**
356
324
  * Ready -> remainingNumberOfTriesが1減る
357
325
  * Running -> findOneするだけ
358
326
  */
359
- executeOneById(params) {
360
- return __awaiter(this, void 0, void 0, function* () {
361
- const now = new Date();
362
- let doc;
363
- if (params.status === factory.taskStatus.Running) {
364
- doc = yield this.taskModel.findOne(Object.assign({ _id: { $eq: params.id }, status: { $eq: params.status }, runsAt: { $lt: now } }, (params.expires instanceof Date) ? { expires: { $gt: now } } : undefined), executableTaskProjection)
365
- .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
366
- .lean()
367
- .exec();
368
- }
369
- else {
370
- doc = yield this.taskModel.findOneAndUpdate(Object.assign({ _id: { $eq: params.id }, status: { $eq: params.status }, runsAt: { $lt: now } }, (params.expires instanceof Date) ? { expires: { $gt: now } } : undefined), {
371
- $set: {
372
- status: factory.taskStatus.Running, // 実行中に変更
373
- lastTriedAt: now,
374
- executor: params.executor
375
- },
376
- $inc: {
377
- remainingNumberOfTries: -1, // 残りトライ可能回数減らす
378
- numberOfTried: 1 // トライ回数増やす
379
- }
380
- }, { new: true, projection: executableTaskProjection })
381
- .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
382
- .lean() // lean(2024-09-26~)
383
- .exec();
384
- }
385
- if (doc === null) {
386
- // tslint:disable-next-line:no-null-keyword
387
- return null;
388
- }
389
- return doc;
390
- });
391
- }
392
- /**
393
- * Readyのタスクをname指定でひとつRunningに変更する
394
- */
395
- executeOneIfExists(params) {
396
- return __awaiter(this, void 0, void 0, function* () {
397
- var _a;
398
- if (!(params.runsAt.$lt instanceof Date)) {
399
- throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
400
- }
401
- const nameEq = (_a = params.name) === null || _a === void 0 ? void 0 : _a.$eq;
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')
404
- ? {
405
- name: Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined
406
- // ...(Array.isArray(nameNin)) ? { $nin: nameNin } : undefined
407
- )
408
- }
409
- : undefined), {
327
+ async executeOneById(params) {
328
+ const now = new Date();
329
+ let doc;
330
+ if (params.status === factory.taskStatus.Running) {
331
+ doc = await this.taskModel.findOne({
332
+ _id: { $eq: params.id },
333
+ status: { $eq: params.status },
334
+ runsAt: { $lt: now },
335
+ ...(params.expires instanceof Date) ? { expires: { $gt: now } } : undefined
336
+ }, executableTaskProjection)
337
+ .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
338
+ .lean()
339
+ .exec();
340
+ }
341
+ else {
342
+ doc = await this.taskModel.findOneAndUpdate({
343
+ _id: { $eq: params.id },
344
+ status: { $eq: params.status },
345
+ runsAt: { $lt: now },
346
+ ...(params.expires instanceof Date) ? { expires: { $gt: now } } : undefined
347
+ }, {
410
348
  $set: {
411
349
  status: factory.taskStatus.Running, // 実行中に変更
412
- lastTriedAt: new Date(),
350
+ lastTriedAt: now,
413
351
  executor: params.executor
414
352
  },
415
353
  $inc: {
416
354
  remainingNumberOfTries: -1, // 残りトライ可能回数減らす
417
355
  numberOfTried: 1 // トライ回数増やす
418
356
  }
419
- }, Object.assign({ new: true, projection: executableTaskProjection }, (typeof params.sort.numberOfTried === 'number' || typeof params.sort.runsAt === 'number')
420
- ? { sort: params.sort }
421
- : undefined))
357
+ }, { new: true, projection: executableTaskProjection })
422
358
  .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
423
359
  .lean() // lean(2024-09-26~)
424
360
  .exec();
425
- if (doc === null) {
426
- // tslint:disable-next-line:no-null-keyword
427
- return null;
428
- }
429
- return doc;
430
- });
361
+ }
362
+ if (doc === null) {
363
+ return null;
364
+ }
365
+ return doc;
366
+ }
367
+ /**
368
+ * Readyのタスクをname指定でひとつRunningに変更する
369
+ */
370
+ async executeOneIfExists(params) {
371
+ if (!(params.runsAt.$lt instanceof Date)) {
372
+ throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
373
+ }
374
+ const nameEq = params.name?.$eq;
375
+ // const nameNin = params.name?.$nin;
376
+ const doc = await this.taskModel.findOneAndUpdate({
377
+ status: { $eq: factory.taskStatus.Ready },
378
+ runsAt: { $lt: params.runsAt.$lt },
379
+ ...(typeof nameEq === 'string')
380
+ ? {
381
+ name: {
382
+ ...(typeof nameEq === 'string') ? { $eq: nameEq } : undefined
383
+ // ...(Array.isArray(nameNin)) ? { $nin: nameNin } : undefined
384
+ }
385
+ }
386
+ : undefined
387
+ }, {
388
+ $set: {
389
+ status: factory.taskStatus.Running, // 実行中に変更
390
+ lastTriedAt: new Date(),
391
+ executor: params.executor
392
+ },
393
+ $inc: {
394
+ remainingNumberOfTries: -1, // 残りトライ可能回数減らす
395
+ numberOfTried: 1 // トライ回数増やす
396
+ }
397
+ }, {
398
+ new: true,
399
+ projection: executableTaskProjection,
400
+ ...(typeof params.sort.numberOfTried === 'number' || typeof params.sort.runsAt === 'number')
401
+ ? { sort: params.sort }
402
+ : undefined
403
+ })
404
+ .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
405
+ .lean() // lean(2024-09-26~)
406
+ .exec();
407
+ if (doc === null) {
408
+ return null;
409
+ }
410
+ return doc;
431
411
  }
432
412
  /**
433
413
  * add(2025-03-16~)
434
414
  */
435
- countPotentiallyRunning(params) {
436
- return __awaiter(this, void 0, void 0, function* () {
437
- const { runsAt, limit, name } = params;
438
- const nameEq = name === null || name === void 0 ? void 0 : name.$eq;
439
- // const nameNin = name?.$nin;
440
- const nameIn = name === null || name === void 0 ? void 0 : name.$in;
441
- if (!(runsAt.$lt instanceof Date)) {
442
- throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
443
- }
444
- const query = this.taskModel.countDocuments(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: params.runsAt.$lt } }, (typeof nameEq === 'string' || Array.isArray(nameIn))
415
+ async countPotentiallyRunning(params) {
416
+ const { runsAt, limit, name } = params;
417
+ const nameEq = name?.$eq;
418
+ // const nameNin = name?.$nin;
419
+ const nameIn = name?.$in;
420
+ if (!(runsAt.$lt instanceof Date)) {
421
+ throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
422
+ }
423
+ const query = this.taskModel.countDocuments({
424
+ status: { $eq: factory.taskStatus.Ready },
425
+ runsAt: { $lt: params.runsAt.$lt },
426
+ ...(typeof nameEq === 'string' || Array.isArray(nameIn))
445
427
  ? {
446
- name: Object.assign(Object.assign({}, (typeof nameEq === 'string') ? { $eq: nameEq } : undefined), (Array.isArray(nameIn)) ? { $in: nameIn } : undefined)
428
+ name: {
429
+ ...(typeof nameEq === 'string') ? { $eq: nameEq } : undefined,
430
+ // ...(Array.isArray(nameNin)) ? { $nin: nameNin } : undefined,
431
+ ...(Array.isArray(nameIn)) ? { $in: nameIn } : undefined
432
+ }
447
433
  }
448
- : undefined));
449
- if (typeof limit === 'number' && limit >= 0) {
450
- query.limit(limit);
451
- }
452
- const count = yield query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
453
- .exec();
454
- return { count };
434
+ : undefined
455
435
  });
436
+ if (typeof limit === 'number' && limit >= 0) {
437
+ query.limit(limit);
438
+ }
439
+ const count = await query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
440
+ .exec();
441
+ return { count };
456
442
  }
457
443
  /**
458
444
  * 実行日時を一定期間過ぎたReadyタスクについて、Runningスタータスに変更した上で、Runningイベントを発生させる
459
445
  */
460
- emitRunningIfExists(params, next // support next function(2025-08-02~)
446
+ async emitRunningIfExists(params, next // support next function(2025-08-02~)
461
447
  ) {
462
- return __awaiter(this, void 0, void 0, function* () {
463
- var _a;
464
- if (!(params.runsAt.$lt instanceof Date)) {
465
- throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
466
- }
467
- const projection = {
468
- _id: 0,
469
- id: { $toString: '$_id' },
470
- name: 1
471
- };
472
- const nameEq = (_a = params.name) === null || _a === void 0 ? void 0 : _a.$eq;
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
448
+ if (!(params.runsAt.$lt instanceof Date)) {
449
+ throw new factory.errors.Argument('runsAt.$lt', 'must be Date');
450
+ }
451
+ const projection = {
452
+ _id: 0,
453
+ id: { $toString: '$_id' },
454
+ name: 1
455
+ };
456
+ const nameEq = params.name?.$eq;
457
+ // const nameNin = params.name?.$nin;
458
+ // const nameIn = params.name?.$in;
459
+ const { nameFilterBeforeRunsAt } = params;
460
+ const filter = {
461
+ status: { $eq: factory.taskStatus.Ready },
462
+ ...(nameFilterBeforeRunsAt) ? { name: params.name } : undefined,
463
+ runsAt: { $lt: params.runsAt.$lt },
464
+ ...(!nameFilterBeforeRunsAt) ? { name: params.name } : undefined
477
465
  // ...(typeof nameEq === 'string' || Array.isArray(nameIn))
478
466
  // ? {
479
467
  // name: {
@@ -483,109 +471,114 @@ class TaskRepo {
483
471
  // }
484
472
  // }
485
473
  // : undefined
486
- );
487
- const doc = yield this.taskModel.findOneAndUpdate(filter, {
488
- $set: {
489
- status: factory.taskStatus.Running, // 実行中に変更
490
- lastTriedAt: new Date(),
491
- executor: params.executor
492
- },
493
- $inc: {
494
- remainingNumberOfTries: -1, // 残りトライ可能回数減らす
495
- numberOfTried: 1 // トライ回数増やす
496
- }
497
- }, Object.assign({ new: true, projection }, (typeof params.sort.numberOfTried === 'number' || typeof params.sort.runsAt === 'number')
474
+ };
475
+ const doc = await this.taskModel.findOneAndUpdate(filter, {
476
+ $set: {
477
+ status: factory.taskStatus.Running, // 実行中に変更
478
+ lastTriedAt: new Date(),
479
+ executor: params.executor
480
+ },
481
+ $inc: {
482
+ remainingNumberOfTries: -1, // 残りトライ可能回数減らす
483
+ numberOfTried: 1 // トライ回数増やす
484
+ }
485
+ }, {
486
+ new: true,
487
+ projection,
488
+ ...(typeof params.sort.numberOfTried === 'number' || typeof params.sort.runsAt === 'number')
498
489
  ? { sort: params.sort }
499
- : undefined))
500
- .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
501
- .lean()
502
- .exec();
503
- if (doc === null) {
504
- // tslint:disable-next-line:no-null-keyword
505
- return null;
506
- }
507
- let changedTask;
508
- if (typeof nameEq === 'string') {
509
- changedTask = {
510
- id: doc.id,
511
- status: factory.taskStatus.Running,
512
- name: nameEq
513
- };
514
- }
515
- else {
516
- changedTask = {
517
- id: doc.id,
518
- status: factory.taskStatus.Running
519
- };
520
- }
521
- task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, (typeof next === 'function') ? next : undefined);
522
- return doc;
523
- });
490
+ : undefined
491
+ })
492
+ .setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
493
+ .lean()
494
+ .exec();
495
+ if (doc === null) {
496
+ return null;
497
+ }
498
+ let changedTask;
499
+ if (typeof nameEq === 'string') {
500
+ changedTask = {
501
+ id: doc.id,
502
+ status: factory.taskStatus.Running,
503
+ name: nameEq
504
+ };
505
+ }
506
+ else {
507
+ changedTask = {
508
+ id: doc.id,
509
+ status: factory.taskStatus.Running
510
+ };
511
+ }
512
+ task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, (typeof next === 'function') ? next : undefined);
513
+ return doc;
524
514
  }
525
515
  /**
526
516
  * Readyのままで期限切れのタスクをExpiredに変更する
527
517
  */
528
- makeExpiredMany(params) {
529
- return __awaiter(this, void 0, void 0, function* () {
530
- const { expiresLt } = params;
531
- if (!(expiresLt instanceof Date)) {
532
- throw new factory.errors.Argument('expiresLt', 'must be Date');
533
- }
534
- return this.taskModel.updateMany({
535
- status: { $eq: factory.taskStatus.Ready },
536
- expires: { $exists: true, $lt: expiresLt }
537
- }, {
538
- $set: {
539
- status: factory.taskStatus.Expired
540
- }
541
- })
542
- .exec();
543
- });
518
+ async makeExpiredMany(params) {
519
+ const { expiresLt } = params;
520
+ if (!(expiresLt instanceof Date)) {
521
+ throw new factory.errors.Argument('expiresLt', 'must be Date');
522
+ }
523
+ return this.taskModel.updateMany({
524
+ status: { $eq: factory.taskStatus.Ready },
525
+ expires: { $exists: true, $lt: expiresLt }
526
+ }, {
527
+ $set: {
528
+ status: factory.taskStatus.Expired
529
+ }
530
+ })
531
+ .exec();
544
532
  }
545
533
  /**
546
534
  * Runningのまま一定期間超過し、かつ、remainingNumberOfTries>0のタスクをReadyに変更する
547
535
  */
548
- retryMany(params) {
549
- return __awaiter(this, void 0, void 0, function* () {
550
- const lastTriedAtShoudBeLessThan = moment()
551
- .add(-params.intervalInMinutes, 'minutes')
552
- .toDate();
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: {
556
- $type: 'date',
557
- $lt: lastTriedAtShoudBeLessThan
558
- } }, (typeof remainingNumberOfTriesGte === 'number')
536
+ async retryMany(params) {
537
+ const lastTriedAtShoudBeLessThan = moment()
538
+ .add(-params.intervalInMinutes, 'minutes')
539
+ .toDate();
540
+ const remainingNumberOfTriesGte = params.remainingNumberOfTries.$gte;
541
+ const remainingNumberOfTriesLte = params.remainingNumberOfTries.$lte;
542
+ return this.taskModel.updateMany(
543
+ // name: 'retry'のindexと連動しているので、条件の順序などには注意すること
544
+ // @see schemas/task
545
+ {
546
+ status: { $eq: factory.taskStatus.Running },
547
+ lastTriedAt: {
548
+ $type: 'date',
549
+ $lt: lastTriedAtShoudBeLessThan
550
+ },
551
+ ...(typeof remainingNumberOfTriesGte === 'number')
559
552
  ? { remainingNumberOfTries: { $gte: remainingNumberOfTriesGte } }
560
- : undefined), (typeof remainingNumberOfTriesLte === 'number')
553
+ : undefined,
554
+ ...(typeof remainingNumberOfTriesLte === 'number')
561
555
  ? { remainingNumberOfTries: { $lte: remainingNumberOfTriesLte } }
562
- : undefined), (Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined), {
563
- $set: {
564
- status: factory.taskStatus.Ready // 実行前に変更
565
- }
566
- })
567
- .exec();
568
- });
556
+ : undefined,
557
+ ...(Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined
558
+ }, {
559
+ $set: {
560
+ status: factory.taskStatus.Ready // 実行前に変更
561
+ }
562
+ })
563
+ .exec();
569
564
  }
570
565
  /**
571
566
  * 実行中止済タスクを強制的にリトライ
572
567
  * 中止済タスクでなければ何もしない
573
568
  */
574
- retryForciblyIfAborted(params) {
575
- return __awaiter(this, void 0, void 0, function* () {
576
- return this.taskModel.updateOne({
577
- _id: { $eq: params.id },
578
- status: { $eq: factory.taskStatus.Aborted }
579
- }, {
580
- $set: {
581
- status: factory.taskStatus.Ready
582
- },
583
- $inc: {
584
- remainingNumberOfTries: params.remainingNumberOfTries
585
- }
586
- })
587
- .exec();
588
- });
569
+ async retryForciblyIfAborted(params) {
570
+ return this.taskModel.updateOne({
571
+ _id: { $eq: params.id },
572
+ status: { $eq: factory.taskStatus.Aborted }
573
+ }, {
574
+ $set: {
575
+ status: factory.taskStatus.Ready
576
+ },
577
+ $inc: {
578
+ remainingNumberOfTries: params.remainingNumberOfTries
579
+ }
580
+ })
581
+ .exec();
589
582
  }
590
583
  // public async abortOne(params: {
591
584
  // intervalInMinutes: number;
@@ -623,278 +616,276 @@ class TaskRepo {
623
616
  // }
624
617
  // return doc;
625
618
  // }
626
- abortMany(params) {
627
- return __awaiter(this, void 0, void 0, function* () {
628
- const lastTriedAtShoudBeLessThan = moment()
629
- .add(-params.intervalInMinutes, 'minutes')
630
- .toDate();
631
- return this.taskModel.updateMany(Object.assign({ status: { $eq: factory.taskStatus.Running }, lastTriedAt: {
632
- $type: 'date',
633
- $lt: lastTriedAtShoudBeLessThan
634
- }, remainingNumberOfTries: { $eq: 0 } }, (Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined), {
635
- $set: {
636
- status: factory.taskStatus.Aborted,
637
- dateAborted: new Date()
638
- }
639
- })
640
- .exec();
641
- });
619
+ async abortMany(params) {
620
+ const lastTriedAtShoudBeLessThan = moment()
621
+ .add(-params.intervalInMinutes, 'minutes')
622
+ .toDate();
623
+ return this.taskModel.updateMany({
624
+ status: { $eq: factory.taskStatus.Running },
625
+ lastTriedAt: {
626
+ $type: 'date',
627
+ $lt: lastTriedAtShoudBeLessThan
628
+ },
629
+ remainingNumberOfTries: { $eq: 0 },
630
+ ...(Array.isArray(params.name.$in)) ? { name: { $in: params.name.$in } } : undefined
631
+ }, {
632
+ $set: {
633
+ status: factory.taskStatus.Aborted,
634
+ dateAborted: new Date()
635
+ }
636
+ })
637
+ .exec();
642
638
  }
643
639
  /**
644
640
  * タスクIDから実行結果とステータスを保管する
645
641
  * Abortedの場合、dateAbortedもセットする
646
642
  */
647
- setExecutionResultAndStatus(params, update,
643
+ async setExecutionResultAndStatus(params, update,
648
644
  // support customr function(2025-05-25~)
649
645
  next) {
650
- return __awaiter(this, void 0, void 0, function* () {
651
- const { id, remainingNumberOfTries, name } = params;
652
- const { status, executionResult } = update;
653
- yield this.taskModel.updateOne({ _id: { $eq: id } }, {
654
- $set: Object.assign({ status }, (status === factory.taskStatus.Aborted) ? { dateAborted: executionResult.endDate } : undefined // 2025-08-04~
655
- ),
656
- $push: { executionResults: executionResult }
657
- })
658
- .exec();
659
- // emit event(2025-05-26~)
660
- if (typeof next === 'function') {
661
- const changedTask = { id, name, status, remainingNumberOfTries, executionResult };
662
- task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, next);
663
- }
664
- });
646
+ const { id, remainingNumberOfTries, name } = params;
647
+ const { status, executionResult } = update;
648
+ await this.taskModel.updateOne({ _id: { $eq: id } }, {
649
+ $set: {
650
+ status,
651
+ ...(status === factory.taskStatus.Aborted) ? { dateAborted: executionResult.endDate } : undefined // 2025-08-04~
652
+ },
653
+ $push: { executionResults: executionResult }
654
+ })
655
+ .exec();
656
+ // emit event(2025-05-26~)
657
+ if (typeof next === 'function') {
658
+ const changedTask = { id, name, status, remainingNumberOfTries, executionResult };
659
+ task_1.taskEventEmitter.emitTaskStatusChanged(changedTask, next);
660
+ }
665
661
  }
666
- count(params) {
667
- return __awaiter(this, void 0, void 0, function* () {
668
- const { limit } = params;
669
- const conditions = TaskRepo.CREATE_MONGO_CONDITIONS(params);
670
- const query = this.taskModel.countDocuments((conditions.length > 0) ? { $and: conditions } : {});
671
- if (typeof limit === 'number' && limit >= 0) {
672
- query.limit(limit);
673
- }
674
- const count = yield query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
675
- .exec();
676
- return { count };
677
- });
662
+ async count(params) {
663
+ const { limit } = params;
664
+ const conditions = TaskRepo.CREATE_MONGO_CONDITIONS(params);
665
+ const query = this.taskModel.countDocuments((conditions.length > 0) ? { $and: conditions } : {});
666
+ if (typeof limit === 'number' && limit >= 0) {
667
+ query.limit(limit);
668
+ }
669
+ const count = await query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
670
+ .exec();
671
+ return { count };
678
672
  }
679
673
  /**
680
674
  * 検索する
681
675
  */
682
- projectFields(params,
676
+ async projectFields(params,
683
677
  // projection?: IProjection
684
678
  inclusion) {
685
- return __awaiter(this, void 0, void 0, function* () {
686
- var _a;
687
- const conditions = TaskRepo.CREATE_MONGO_CONDITIONS(params);
688
- // const positiveProjectionExists: boolean = (projection !== undefined && projection !== null)
689
- // ? Object.values(projection)
690
- // .some((value) => value !== 0)
691
- // : false;
692
- let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
693
- if (Array.isArray(inclusion) && inclusion.length > 0) {
694
- positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
695
- }
696
- else {
697
- // no op
698
- }
699
- const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
700
- const query = this.taskModel.find((conditions.length > 0) ? { $and: conditions } : {}, projection);
701
- if (typeof params.limit === 'number' && params.limit > 0) {
702
- const page = (typeof params.page === 'number' && params.page > 0) ? params.page : 1;
703
- query.limit(params.limit)
704
- .skip(params.limit * (page - 1));
705
- }
706
- if (((_a = params.sort) === null || _a === void 0 ? void 0 : _a.runsAt) !== undefined) {
707
- query.sort({ runsAt: params.sort.runsAt });
708
- }
709
- return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
710
- .lean() // lean(2024-09-26~)
711
- .exec();
712
- });
679
+ const conditions = TaskRepo.CREATE_MONGO_CONDITIONS(params);
680
+ // const positiveProjectionExists: boolean = (projection !== undefined && projection !== null)
681
+ // ? Object.values(projection)
682
+ // .some((value) => value !== 0)
683
+ // : false;
684
+ let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
685
+ if (Array.isArray(inclusion) && inclusion.length > 0) {
686
+ positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
687
+ }
688
+ else {
689
+ // no op
690
+ }
691
+ const projection = {
692
+ _id: 0,
693
+ id: { $toString: '$_id' },
694
+ ...Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1])))
695
+ };
696
+ const query = this.taskModel.find((conditions.length > 0) ? { $and: conditions } : {}, projection);
697
+ if (typeof params.limit === 'number' && params.limit > 0) {
698
+ const page = (typeof params.page === 'number' && params.page > 0) ? params.page : 1;
699
+ query.limit(params.limit)
700
+ .skip(params.limit * (page - 1));
701
+ }
702
+ if (params.sort?.runsAt !== undefined) {
703
+ query.sort({ runsAt: params.sort.runsAt });
704
+ }
705
+ return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
706
+ .lean() // lean(2024-09-26~)
707
+ .exec();
713
708
  }
714
- deleteByProject(params) {
715
- return __awaiter(this, void 0, void 0, function* () {
716
- yield this.taskModel.deleteMany({
717
- 'project.id': { $eq: params.project.id }
718
- })
719
- .exec();
720
- });
709
+ async deleteByProject(params) {
710
+ await this.taskModel.deleteMany({
711
+ 'project.id': { $eq: params.project.id }
712
+ })
713
+ .exec();
721
714
  }
722
- deleteByName(params) {
723
- return __awaiter(this, void 0, void 0, function* () {
724
- var _a, _b;
725
- return this.taskModel.deleteMany(Object.assign(Object.assign({ name: { $eq: params.name } }, (typeof ((_a = params.status) === null || _a === void 0 ? void 0 : _a.$eq) === 'string') ? { status: { $eq: params.status.$eq } } : undefined), (((_b = params.runsAt) === null || _b === void 0 ? void 0 : _b.$gte) instanceof Date)
715
+ async deleteByName(params) {
716
+ return this.taskModel.deleteMany({
717
+ name: { $eq: params.name },
718
+ ...(typeof params.status?.$eq === 'string') ? { status: { $eq: params.status.$eq } } : undefined,
719
+ ...(params.runsAt?.$gte instanceof Date)
726
720
  ? {
727
721
  runsAt: { $gte: params.runsAt.$gte, $lte: params.runsAt.$lte }
728
722
  }
729
- : undefined))
730
- .exec();
731
- });
723
+ : undefined
724
+ })
725
+ .exec();
732
726
  }
733
727
  /**
734
728
  * 不要なタスクを削除する
735
729
  */
736
- deleteRunsAtPassedCertainPeriod(params) {
737
- return __awaiter(this, void 0, void 0, function* () {
738
- return this.taskModel.deleteMany({
739
- runsAt: { $lt: params.runsAt.$lt },
740
- status: {
741
- $in: [
742
- factory.taskStatus.Aborted,
743
- factory.taskStatus.Executed,
744
- factory.taskStatus.Expired
745
- ]
746
- }
747
- })
748
- .exec();
749
- });
730
+ async deleteRunsAtPassedCertainPeriod(params) {
731
+ return this.taskModel.deleteMany({
732
+ runsAt: { $lt: params.runsAt.$lt },
733
+ status: {
734
+ $in: [
735
+ factory.taskStatus.Aborted,
736
+ factory.taskStatus.Executed,
737
+ factory.taskStatus.Expired
738
+ ]
739
+ }
740
+ })
741
+ .exec();
750
742
  }
751
- countDelayedTasks(params) {
752
- return __awaiter(this, void 0, void 0, function* () {
753
- const { limit } = params;
754
- const runsAtLt = moment()
755
- .add(-params.delayInSeconds, 'seconds')
756
- .toDate();
757
- const query = this.taskModel.countDocuments(Object.assign({ status: { $eq: factory.taskStatus.Ready }, runsAt: { $lt: runsAtLt } }, (Array.isArray(params.name.$nin)) ? { name: { $nin: params.name.$nin } } : undefined));
758
- if (typeof limit === 'number' && limit >= 0) {
759
- query.limit(limit);
760
- }
761
- const count = yield query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
762
- .exec();
763
- return { count };
743
+ async countDelayedTasks(params) {
744
+ const { limit } = params;
745
+ const runsAtLt = moment()
746
+ .add(-params.delayInSeconds, 'seconds')
747
+ .toDate();
748
+ const query = this.taskModel.countDocuments({
749
+ status: { $eq: factory.taskStatus.Ready },
750
+ runsAt: { $lt: runsAtLt },
751
+ ...(Array.isArray(params.name.$nin)) ? { name: { $nin: params.name.$nin } } : undefined
764
752
  });
753
+ if (typeof limit === 'number' && limit >= 0) {
754
+ query.limit(limit);
755
+ }
756
+ const count = await query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
757
+ .exec();
758
+ return { count };
765
759
  }
766
760
  getCursor(conditions, projection) {
767
761
  return this.taskModel.find(conditions, projection)
768
762
  .sort({ runsAt: factory.sortType.Ascending })
769
763
  .cursor();
770
764
  }
771
- unsetUnnecessaryFields(params) {
772
- return __awaiter(this, void 0, void 0, function* () {
773
- return this.taskModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
774
- .exec();
775
- });
765
+ async unsetUnnecessaryFields(params) {
766
+ return this.taskModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
767
+ .exec();
776
768
  }
777
- aggregateTask(params) {
778
- return __awaiter(this, void 0, void 0, function* () {
779
- const statuses = yield Promise.all([
780
- factory.taskStatus.Executed,
781
- factory.taskStatus.Aborted
782
- ].map((taskStatus) => __awaiter(this, void 0, void 0, function* () {
783
- var _a, _b;
784
- const matchConditions = Object.assign({ runsAt: {
785
- $gte: params.runsFrom,
786
- $lte: params.runsThrough
787
- }, status: { $eq: taskStatus } }, (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$ne) === 'string')
769
+ async aggregateTask(params) {
770
+ const statuses = await Promise.all([
771
+ factory.taskStatus.Executed,
772
+ factory.taskStatus.Aborted
773
+ ].map(async (taskStatus) => {
774
+ const matchConditions = {
775
+ runsAt: {
776
+ $gte: params.runsFrom,
777
+ $lte: params.runsThrough
778
+ },
779
+ status: { $eq: taskStatus },
780
+ ...(typeof params.project?.id?.$ne === 'string')
788
781
  ? { 'project.id': { $ne: params.project.id.$ne } }
789
- : undefined);
790
- return this.agggregateByStatus({ matchConditions, status: taskStatus });
791
- })));
792
- return { statuses };
793
- });
782
+ : undefined
783
+ };
784
+ return this.agggregateByStatus({ matchConditions, status: taskStatus });
785
+ }));
786
+ return { statuses };
794
787
  }
795
- // tslint:disable-next-line:max-func-body-length
796
- agggregateByStatus(params) {
797
- return __awaiter(this, void 0, void 0, function* () {
798
- const matchConditions = params.matchConditions;
799
- const taskStatus = params.status;
800
- const aggregate1 = this.taskModel.aggregate([
801
- {
802
- $match: matchConditions
803
- },
804
- {
805
- $project: {
806
- latency: { $subtract: ['$lastTriedAt', '$runsAt'] },
807
- status: '$status',
808
- runsAt: '$runsAt',
809
- lastTriedAt: '$lastTriedAt'
810
- }
811
- },
812
- {
813
- $group: {
814
- _id: '$status',
815
- taskCount: { $sum: 1 },
816
- maxLatency: { $max: '$latency' },
817
- minLatency: { $min: '$latency' },
818
- avgLatency: { $avg: '$latency' }
819
- }
820
- },
821
- {
822
- $project: {
823
- _id: 0,
824
- taskCount: '$taskCount',
825
- avgLatency: '$avgLatency',
826
- maxLatency: '$maxLatency',
827
- minLatency: '$minLatency'
828
- }
788
+ async agggregateByStatus(params) {
789
+ const matchConditions = params.matchConditions;
790
+ const taskStatus = params.status;
791
+ const aggregate1 = this.taskModel.aggregate([
792
+ {
793
+ $match: matchConditions
794
+ },
795
+ {
796
+ $project: {
797
+ latency: { $subtract: ['$lastTriedAt', '$runsAt'] },
798
+ status: '$status',
799
+ runsAt: '$runsAt',
800
+ lastTriedAt: '$lastTriedAt'
829
801
  }
830
- ]);
831
- // const explainResult = await aggregate1.explain();
832
- // console.dir(explainResult, { depth: null });
833
- // return;
834
- const aggregations = yield aggregate1.exec();
835
- // tslint:disable-next-line:no-magic-numbers
836
- const percents = [50, 95, 99];
837
- if (aggregations.length === 0) {
838
- return {
839
- status: taskStatus,
840
- aggregation: {
841
- taskCount: 0,
842
- avgLatency: 0,
843
- maxLatency: 0,
844
- minLatency: 0,
845
- percentilesLatency: percents.map((percent) => {
846
- return {
847
- name: String(percent),
848
- value: 0
849
- };
850
- })
851
- }
852
- };
853
- }
854
- const ranks4percentile = percents.map((percentile) => {
855
- return {
856
- percentile,
857
- // tslint:disable-next-line:no-magic-numbers
858
- rank: Math.floor(aggregations[0].taskCount * percentile / 100)
859
- };
860
- });
861
- const aggregate2 = this.taskModel.aggregate([
862
- {
863
- $match: matchConditions
864
- },
865
- {
866
- $project: {
867
- latency: { $subtract: ['$lastTriedAt', '$runsAt'] },
868
- status: '$status',
869
- runsAt: '$runsAt',
870
- lastTriedAt: '$lastTriedAt'
871
- }
872
- },
873
- { $sort: { latency: 1 } },
874
- {
875
- $group: {
876
- _id: '$status',
877
- latencies: { $push: '$latency' }
878
- }
879
- },
880
- {
881
- $project: {
882
- _id: 0,
883
- percentilesLatency: ranks4percentile.map((rank) => {
884
- return {
885
- name: String(rank.percentile),
886
- value: { $arrayElemAt: ['$latencies', rank.rank] }
887
- };
888
- })
889
- }
802
+ },
803
+ {
804
+ $group: {
805
+ _id: '$status',
806
+ taskCount: { $sum: 1 },
807
+ maxLatency: { $max: '$latency' },
808
+ minLatency: { $min: '$latency' },
809
+ avgLatency: { $avg: '$latency' }
810
+ }
811
+ },
812
+ {
813
+ $project: {
814
+ _id: 0,
815
+ taskCount: '$taskCount',
816
+ avgLatency: '$avgLatency',
817
+ maxLatency: '$maxLatency',
818
+ minLatency: '$minLatency'
890
819
  }
891
- ]);
892
- const aggregations2 = yield aggregate2.exec();
820
+ }
821
+ ]);
822
+ // const explainResult = await aggregate1.explain();
823
+ // console.dir(explainResult, { depth: null });
824
+ // return;
825
+ const aggregations = await aggregate1.exec();
826
+ const percents = [50, 95, 99];
827
+ if (aggregations.length === 0) {
893
828
  return {
894
829
  status: taskStatus,
895
- aggregation: Object.assign(Object.assign({}, aggregations[0]), aggregations2[0])
830
+ aggregation: {
831
+ taskCount: 0,
832
+ avgLatency: 0,
833
+ maxLatency: 0,
834
+ minLatency: 0,
835
+ percentilesLatency: percents.map((percent) => {
836
+ return {
837
+ name: String(percent),
838
+ value: 0
839
+ };
840
+ })
841
+ }
842
+ };
843
+ }
844
+ const ranks4percentile = percents.map((percentile) => {
845
+ return {
846
+ percentile,
847
+ rank: Math.floor(aggregations[0].taskCount * percentile / 100)
896
848
  };
897
849
  });
850
+ const aggregate2 = this.taskModel.aggregate([
851
+ {
852
+ $match: matchConditions
853
+ },
854
+ {
855
+ $project: {
856
+ latency: { $subtract: ['$lastTriedAt', '$runsAt'] },
857
+ status: '$status',
858
+ runsAt: '$runsAt',
859
+ lastTriedAt: '$lastTriedAt'
860
+ }
861
+ },
862
+ { $sort: { latency: 1 } },
863
+ {
864
+ $group: {
865
+ _id: '$status',
866
+ latencies: { $push: '$latency' }
867
+ }
868
+ },
869
+ {
870
+ $project: {
871
+ _id: 0,
872
+ percentilesLatency: ranks4percentile.map((rank) => {
873
+ return {
874
+ name: String(rank.percentile),
875
+ value: { $arrayElemAt: ['$latencies', rank.rank] }
876
+ };
877
+ })
878
+ }
879
+ }
880
+ ]);
881
+ const aggregations2 = await aggregate2.exec();
882
+ return {
883
+ status: taskStatus,
884
+ aggregation: {
885
+ ...aggregations[0],
886
+ ...aggregations2[0]
887
+ }
888
+ };
898
889
  }
899
890
  }
900
891
  exports.TaskRepo = TaskRepo;