@chevre/domain 24.0.0-alpha.30 → 24.0.0-alpha.31

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.
@@ -91,7 +91,6 @@ import type { SettingRepo } from './repo/setting';
91
91
  import type { JWTSettingRepo } from './repo/setting/jwt';
92
92
  import type { StockHolderRepo } from './repo/stockHolder';
93
93
  import type { TaskRepo } from './repo/task';
94
- import type { TelemetryRepo } from './repo/telemetry';
95
94
  import type { TicketRepo } from './repo/ticket';
96
95
  import type { TransactionRepo } from './repo/transaction';
97
96
  import type { PlaceOrderRepo } from './repo/transaction/placeOrder';
@@ -509,10 +508,6 @@ export type Task = TaskRepo;
509
508
  export declare namespace Task {
510
509
  function createInstance(...params: ConstructorParameters<typeof TaskRepo>): Promise<TaskRepo>;
511
510
  }
512
- export type Telemetry = TelemetryRepo;
513
- export declare namespace Telemetry {
514
- function createInstance(...params: ConstructorParameters<typeof TelemetryRepo>): Promise<TelemetryRepo>;
515
- }
516
511
  export type Ticket = TicketRepo;
517
512
  export declare namespace Ticket {
518
513
  function createInstance(...params: ConstructorParameters<typeof TicketRepo>): Promise<TicketRepo>;
@@ -24,7 +24,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.PaymentServiceChannel = exports.PaymentService = exports.Passport = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.NoteAboutOrder = exports.Note = exports.MovieTicketType = exports.Message = exports.MerchantReturnPolicy = exports.MemberProgram = exports.Member = exports.Issuer = exports.IdentityProvider = exports.Identity = exports.EventSeries = exports.EventSellerMakesOffer = exports.EventOffer = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.Credentials = exports.CreativeWork = exports.ConfirmationNumber = exports.Comment = exports.Authorization = exports.CategoryCode = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOrder = exports.AggregateOffer = exports.AggregateAction = exports.AdvanceBookingRequirement = exports.AdditionalProperty = exports.action = exports.Action = exports.AccountTransaction = exports.AccountTitle = exports.AccountingReport = exports.Account = exports.AcceptedPaymentMethod = exports.AcceptedOffer = void 0;
27
- exports.WebSite = exports.rateLimit = exports.Trip = exports.TransactionProcess = exports.TransactionNumber = exports.transaction = exports.Transaction = exports.Ticket = exports.Telemetry = exports.Task = exports.StockHolder = exports.setting = exports.Setting = exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.ServiceAvailableHour = exports.SellerReturnPolicy = exports.SellerPaymentAccepted = exports.SellerMakesOffer = exports.Seller = exports.Schedule = exports.Role = exports.ReserveInterface = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.ProductModel = exports.ProductHasOfferCatalog = exports.Product = exports.PriceSpecification = exports.PotentialAction = exports.place = exports.Permit = exports.Person = exports.paymentMethod = exports.PendingReservation = exports.PaymentServiceProvider = void 0;
27
+ exports.WebSite = exports.rateLimit = exports.Trip = exports.TransactionProcess = exports.TransactionNumber = exports.transaction = exports.Transaction = exports.Ticket = exports.Task = exports.StockHolder = exports.setting = exports.Setting = exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.ServiceAvailableHour = exports.SellerReturnPolicy = exports.SellerPaymentAccepted = exports.SellerMakesOffer = exports.Seller = exports.Schedule = exports.Role = exports.ReserveInterface = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.ProductModel = exports.ProductHasOfferCatalog = exports.Product = exports.PriceSpecification = exports.PotentialAction = exports.place = exports.Permit = exports.Person = exports.paymentMethod = exports.PendingReservation = exports.PaymentServiceProvider = void 0;
28
28
  var AcceptedOffer;
29
29
  (function (AcceptedOffer) {
30
30
  let repo;
@@ -1081,17 +1081,6 @@ var Task;
1081
1081
  }
1082
1082
  Task.createInstance = createInstance;
1083
1083
  })(Task || (exports.Task = Task = {}));
1084
- var Telemetry;
1085
- (function (Telemetry) {
1086
- let repo;
1087
- async function createInstance(...params) {
1088
- if (repo === undefined) {
1089
- repo = (await Promise.resolve().then(() => __importStar(require('./repo/telemetry')))).TelemetryRepo;
1090
- }
1091
- return new repo(...params);
1092
- }
1093
- Telemetry.createInstance = createInstance;
1094
- })(Telemetry || (exports.Telemetry = Telemetry = {}));
1095
1084
  var Ticket;
1096
1085
  (function (Ticket) {
1097
1086
  let repo;
@@ -1,6 +1,5 @@
1
1
  import * as factory from '../../../../factory';
2
2
  import { Settings } from '../../../../settings';
3
- import type { ActionRepo } from '../../../../repo/action';
4
3
  import type { AdvanceBookingRequirementRepo } from '../../../../repo/advanceBookingRequirement';
5
4
  import type { AssetTransactionRepo } from '../../../../repo/assetTransaction';
6
5
  import type { AuthorizationRepo } from '../../../../repo/authorization';
@@ -51,7 +50,6 @@ declare function processStartReserve4chevre(params: {
51
50
  */
52
51
  maxReservationGracePeriodInDays: number;
53
52
  }): (repos: {
54
- action: ActionRepo;
55
53
  advanceBookingRequirement: AdvanceBookingRequirementRepo;
56
54
  authorization: AuthorizationRepo;
57
55
  stockHolder: StockHolderRepo;
@@ -1,6 +1,6 @@
1
1
  import * as factory from '../../../factory';
2
2
  import { Settings } from '../../../settings';
3
- import type { ActionRepo } from '../../../repo/action';
3
+ import type { AuthorizeOfferActionRepo } from '../../../repo/action/authorizeOffer';
4
4
  import type { AdvanceBookingRequirementRepo } from '../../../repo/advanceBookingRequirement';
5
5
  import type { AssetTransactionRepo } from '../../../repo/assetTransaction';
6
6
  import type { AuthorizationRepo } from '../../../repo/authorization';
@@ -29,7 +29,8 @@ import type { TicketRepo } from '../../../repo/ticket';
29
29
  import type { PlaceOrderRepo } from '../../../repo/transaction/placeOrder';
30
30
  import type { TransactionNumberRepo } from '../../../repo/transactionNumber';
31
31
  interface IAuthorizeRepos {
32
- action: ActionRepo;
32
+ action?: never;
33
+ authorizeOfferAction: AuthorizeOfferActionRepo;
33
34
  advanceBookingRequirement: AdvanceBookingRequirementRepo;
34
35
  assetTransaction: AssetTransactionRepo;
35
36
  authorization: AuthorizationRepo;
@@ -98,4 +99,4 @@ declare function authorize(params: {
98
99
  }, options: IAuthorizeOptions): IAuthorizeOperation<Pick<IAuthorizeOfferAction, 'id'> & {
99
100
  result: IAuthorizeOfferAction['result'];
100
101
  }>;
101
- export { authorize };
102
+ export { IAuthorizeRepos, authorize };
@@ -63,7 +63,7 @@ function authorize(params, options) {
63
63
  event, transaction,
64
64
  instrument: { transactionNumber }
65
65
  });
66
- const action = await repos.action.start(actionAttributes);
66
+ const action = await repos.authorizeOfferAction.start(actionAttributes);
67
67
  try {
68
68
  const processStartReserveResult = await (0, processStartReserve4chevre_1.processStartReserve4chevre)({
69
69
  acceptedOffers, event,
@@ -92,7 +92,7 @@ function authorize(params, options) {
92
92
  }
93
93
  catch (error) {
94
94
  try {
95
- await repos.action.giveUp({ typeOf: action.typeOf, id: action.id, error });
95
+ await repos.authorizeOfferAction.giveUp({ typeOf: action.typeOf, id: action.id, error });
96
96
  }
97
97
  catch (__) {
98
98
  // no op
@@ -100,7 +100,7 @@ function authorize(params, options) {
100
100
  throw error;
101
101
  }
102
102
  const result = (0, factory_1.acceptedOffers2authorizeResult)({ acceptedOffers, acceptedOffers4result, noOfferSpecified, ticketOffers });
103
- await repos.action.completeWithVoid({ typeOf: action.typeOf, id: action.id, result: result });
103
+ await repos.authorizeOfferAction.completeWithVoid({ typeOf: action.typeOf, id: action.id, result: result });
104
104
  return { id: action.id, result };
105
105
  };
106
106
  }
@@ -3,6 +3,7 @@ import * as factory from '../../../factory';
3
3
  import { Settings } from '../../../settings';
4
4
  import type { ActionRepo } from '../../../repo/action';
5
5
  import type { AcceptCOAOfferActionRepo } from '../../../repo/action/acceptCOAOffer';
6
+ import type { AuthorizeOfferActionRepo } from '../../../repo/action/authorizeOffer';
6
7
  import type { AssetTransactionRepo } from '../../../repo/assetTransaction';
7
8
  import type { OrderInTransactionRepo } from '../../../repo/orderInTransaction';
8
9
  import type { OfferRateLimitRepo } from '../../../repo/rateLimit/offer';
@@ -14,6 +15,7 @@ import type { PlaceOrderRepo } from '../../../repo/transaction/placeOrder';
14
15
  interface IVoidTransactionRepos {
15
16
  action: ActionRepo;
16
17
  acceptCOAOfferAction: AcceptCOAOfferActionRepo;
18
+ authorizeOfferAction: AuthorizeOfferActionRepo;
17
19
  assetTransaction: AssetTransactionRepo;
18
20
  stockHolder: StockHolderRepo;
19
21
  offerRateLimit: OfferRateLimitRepo;
@@ -2,6 +2,7 @@ import type * as COA from '@motionpicture/coa-service';
2
2
  import * as factory from '../../../factory';
3
3
  import { Settings } from '../../../settings';
4
4
  import type { ActionRepo } from '../../../repo/action';
5
+ import type { AuthorizeOfferActionRepo } from '../../../repo/action/authorizeOffer';
5
6
  import type { AssetTransactionRepo } from '../../../repo/assetTransaction';
6
7
  import type { OrderInTransactionRepo } from '../../../repo/orderInTransaction';
7
8
  import type { OfferRateLimitRepo } from '../../../repo/rateLimit/offer';
@@ -11,7 +12,11 @@ import type { StockHolderRepo } from '../../../repo/stockHolder';
11
12
  import type { TaskRepo } from '../../../repo/task';
12
13
  import type { PlaceOrderRepo } from '../../../repo/transaction/placeOrder';
13
14
  interface IVoidTransactionByActionIdRepos {
15
+ /**
16
+ * CancelAction開始で使用される
17
+ */
14
18
  action: ActionRepo;
19
+ authorizeOfferAction: AuthorizeOfferActionRepo;
15
20
  assetTransaction: AssetTransactionRepo;
16
21
  stockHolder: StockHolderRepo;
17
22
  offerRateLimit: OfferRateLimitRepo;
@@ -50,13 +50,13 @@ function voidTransactionByActionId(params) {
50
50
  // throw new factory.errors.Forbidden('Transaction not yours');
51
51
  // }
52
52
  const orderNumber = await repos.placeOrder.findInProgressOrderNumberById({ id: params.purpose.id });
53
- const action = await repos.action.findById({ typeOf: factory.actionType.AuthorizeAction, id: params.id });
53
+ const action = await repos.authorizeOfferAction.findById({ typeOf: factory.actionType.AuthorizeAction, id: params.id });
54
54
  if (action.purpose.typeOf !== transaction.typeOf || action.purpose.id !== transaction.id) {
55
55
  throw new factory.errors.Argument('Transaction', 'Action not found in the transaction');
56
56
  }
57
57
  // MongoDBでcompleteステータスであるにも関わらず、Chevreでは削除されている、というのが最悪の状況
58
58
  // それだけは回避するためにMongoDBを先に変更
59
- await repos.action.cancelWithVoid({ typeOf: factory.actionType.AuthorizeAction, id: params.id, cancelAction });
59
+ await repos.authorizeOfferAction.cancelWithVoid({ typeOf: factory.actionType.AuthorizeAction, id: params.id, cancelAction });
60
60
  // add orderInTransaction(2024-01-15~)
61
61
  // USE_CREATE_ORDER_ON_OFFER_ACCEPTEDの場合、orderNumber発行済のはず
62
62
  // const orderNumberByTransaction = transaction.object.orderNumber;
@@ -3,19 +3,20 @@ import type { IPlacingOrder, OrderInTransactionRepo } from '../../../repo/orderI
3
3
  import type { PlaceOrderRepo } from '../../../repo/transaction/placeOrder';
4
4
  import * as factory from '../../../factory';
5
5
  type IPlaceOrderTransaction = Pick<factory.transaction.placeOrder.ITransaction, 'id' | 'project' | 'typeOf' | 'result' | 'object' | 'seller'>;
6
+ interface ICreatePlacingOrderFromExistingTransactionRepos {
7
+ action: ActionRepo;
8
+ orderInTransaction: OrderInTransactionRepo;
9
+ placeOrder: PlaceOrderRepo;
10
+ }
6
11
  declare function createPlacingOrderFromExistingTransaction(params: {
7
12
  project: {
8
13
  id: string;
9
14
  };
10
15
  confirmationNumber: string;
11
16
  orderNumber: string;
12
- }): (repos: {
13
- action: ActionRepo;
14
- orderInTransaction: OrderInTransactionRepo;
15
- placeOrder: PlaceOrderRepo;
16
- }) => Promise<{
17
+ }): (repos: ICreatePlacingOrderFromExistingTransactionRepos) => Promise<{
17
18
  order: IPlacingOrder;
18
19
  placeOrderTransaction: IPlaceOrderTransaction;
19
20
  serialNumbers: string[];
20
21
  }>;
21
- export { createPlacingOrderFromExistingTransaction };
22
+ export { ICreatePlacingOrderFromExistingTransactionRepos, createPlacingOrderFromExistingTransaction };
@@ -2,5 +2,4 @@
2
2
  * レポートサービス
3
3
  */
4
4
  import * as OwnershipInfoService from './report/ownershipInfo';
5
- import * as TelemetryService from './report/telemetry';
6
- export { OwnershipInfoService as ownershipInfo, TelemetryService as telemetry };
5
+ export { OwnershipInfoService as ownershipInfo };
@@ -23,11 +23,9 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.telemetry = exports.ownershipInfo = void 0;
26
+ exports.ownershipInfo = void 0;
27
27
  /**
28
28
  * レポートサービス
29
29
  */
30
30
  const OwnershipInfoService = __importStar(require("./report/ownershipInfo"));
31
31
  exports.ownershipInfo = OwnershipInfoService;
32
- const TelemetryService = __importStar(require("./report/telemetry"));
33
- exports.telemetry = TelemetryService;
@@ -29,6 +29,7 @@ const factory = __importStar(require("../../factory"));
29
29
  const voidTransaction_1 = require("../offer/event/voidTransaction");
30
30
  const action_1 = require("../../repo/action");
31
31
  const acceptCOAOffer_1 = require("../../repo/action/acceptCOAOffer");
32
+ const authorizeOffer_1 = require("../../repo/action/authorizeOffer");
32
33
  const assetTransaction_1 = require("../../repo/assetTransaction");
33
34
  const orderInTransaction_1 = require("../../repo/orderInTransaction");
34
35
  const offer_1 = require("../../repo/rateLimit/offer");
@@ -82,6 +83,7 @@ function call(params) {
82
83
  })({
83
84
  action: new action_1.ActionRepo(connection),
84
85
  acceptCOAOfferAction: new acceptCOAOffer_1.AcceptCOAOfferActionRepo(connection),
86
+ authorizeOfferAction: new authorizeOffer_1.AuthorizeOfferActionRepo(connection),
85
87
  assetTransaction: new assetTransaction_1.AssetTransactionRepo(connection),
86
88
  stockHolder: new stockHolder_1.StockHolderRepo({ connection }),
87
89
  offerRateLimit: new offer_1.OfferRateLimitRepo(redisClient),
package/package.json CHANGED
@@ -99,5 +99,5 @@
99
99
  "postversion": "git push origin --tags",
100
100
  "prepublishOnly": "npm run clean && npm run build"
101
101
  },
102
- "version": "24.0.0-alpha.30"
102
+ "version": "24.0.0-alpha.31"
103
103
  }
@@ -1,10 +0,0 @@
1
- import { IndexDefinition, IndexOptions, Model, Schema, SchemaDefinition } from 'mongoose';
2
- import { IVirtuals } from '../virtuals';
3
- type IDocType = any;
4
- type IModel = Model<IDocType, {}, {}, IVirtuals>;
5
- type ISchemaDefinition = SchemaDefinition<IDocType>;
6
- type ISchema = Schema<IDocType, IModel, {}, {}, IVirtuals, {}, ISchemaDefinition, IDocType>;
7
- declare const modelName = "Telemetry";
8
- declare function createSchema(): ISchema;
9
- declare const indexes: [d: IndexDefinition, o: IndexOptions][];
10
- export { createSchema, IDocType, IModel, indexes, modelName };
@@ -1,80 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.modelName = exports.indexes = void 0;
4
- exports.createSchema = createSchema;
5
- const mongoose_1 = require("mongoose");
6
- const writeConcern_1 = require("../writeConcern");
7
- // import * as factory from '../../../factory';
8
- const settings_1 = require("../../../settings");
9
- const modelName = 'Telemetry';
10
- exports.modelName = modelName;
11
- const schemaDefinition = {
12
- project: mongoose_1.SchemaTypes.Mixed,
13
- result: mongoose_1.SchemaTypes.Mixed,
14
- error: mongoose_1.SchemaTypes.Mixed,
15
- object: mongoose_1.SchemaTypes.Mixed,
16
- startDate: Date,
17
- endDate: Date,
18
- purpose: mongoose_1.SchemaTypes.Mixed
19
- };
20
- const schemaOptions = {
21
- autoIndex: settings_1.MONGO_AUTO_INDEX,
22
- autoCreate: false,
23
- collection: 'telemetries',
24
- id: true,
25
- read: settings_1.MONGO_READ_PREFERENCE,
26
- writeConcern: writeConcern_1.writeConcern,
27
- strict: true,
28
- strictQuery: false,
29
- timestamps: false, // 2024-08-07~
30
- versionKey: false, // 2024-08-07~
31
- toJSON: {
32
- getters: false,
33
- virtuals: false,
34
- minimize: false,
35
- versionKey: false
36
- },
37
- toObject: {
38
- getters: false,
39
- virtuals: true,
40
- minimize: false,
41
- versionKey: false
42
- }
43
- };
44
- /**
45
- * 測定スキーマ
46
- */
47
- let schema;
48
- function createSchema() {
49
- if (schema === undefined) {
50
- schema = new mongoose_1.Schema(schemaDefinition, schemaOptions);
51
- }
52
- return schema;
53
- }
54
- const indexes = [
55
- [
56
- { 'project.id': 1 },
57
- {
58
- name: 'searchByProjectId-v20220721'
59
- }
60
- ],
61
- [
62
- { 'object.measuredAt': 1 },
63
- {
64
- partialFilterExpression: {
65
- 'object.measuredAt': { $exists: true }
66
- }
67
- }
68
- ],
69
- [
70
- { 'purpose.typeOf': 1, 'object.scope': 1, 'object.measuredAt': 1 },
71
- {
72
- partialFilterExpression: {
73
- 'purpose.typeOf': { $exists: true },
74
- 'object.scope': { $exists: true },
75
- 'object.measuredAt': { $exists: true }
76
- }
77
- }
78
- ]
79
- ];
80
- exports.indexes = indexes;
@@ -1,9 +0,0 @@
1
- import type { Connection } from 'mongoose';
2
- import { IModel } from './mongoose/schemas/telemetry';
3
- /**
4
- * 測定リポジトリ
5
- */
6
- export declare class TelemetryRepo {
7
- readonly telemetryModel: IModel;
8
- constructor(connection: Connection);
9
- }
@@ -1,14 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TelemetryRepo = void 0;
4
- const telemetry_1 = require("./mongoose/schemas/telemetry");
5
- /**
6
- * 測定リポジトリ
7
- */
8
- class TelemetryRepo {
9
- telemetryModel;
10
- constructor(connection) {
11
- this.telemetryModel = connection.model(telemetry_1.modelName, (0, telemetry_1.createSchema)());
12
- }
13
- }
14
- exports.TelemetryRepo = TelemetryRepo;
@@ -1,313 +0,0 @@
1
- /**
2
- * データ測定サービス
3
- * 実験的実装中
4
- */
5
- import type { ActionRepo } from '../../repo/action';
6
- import type { TaskRepo } from '../../repo/task';
7
- import type { TelemetryRepo } from '../../repo/telemetry';
8
- import type { TransactionRepo } from '../../repo/transaction';
9
- import type { PlaceOrderRepo } from '../../repo/transaction/placeOrder';
10
- import * as factory from '../../factory';
11
- export type TelemetryOperation<T> = (repos: {
12
- telemetry: TelemetryRepo;
13
- }) => Promise<T>;
14
- export type TaskOperation<T> = (repos: {
15
- task: TaskRepo;
16
- }) => Promise<T>;
17
- export type TransactionOperation<T> = (repos: {
18
- transaction: TransactionRepo;
19
- placeOrder: PlaceOrderRepo;
20
- }) => Promise<T>;
21
- export type TaskAndTransactionOperation<T> = (repos: {
22
- task: TaskRepo;
23
- transaction: TransactionRepo;
24
- }) => Promise<T>;
25
- export type TaskAndTransactionAndActionOperation<T> = (repos: {
26
- task: TaskRepo;
27
- transaction: TransactionRepo;
28
- action: ActionRepo;
29
- }) => Promise<T>;
30
- export type TransactionAndActionOperation<T> = (repos: {
31
- transaction: TransactionRepo;
32
- placeOrder: PlaceOrderRepo;
33
- action: ActionRepo;
34
- }) => Promise<T>;
35
- export type TaskAndTelemetryAndTransactionOperation<T> = (repos: {
36
- task: TaskRepo;
37
- telemetry: TelemetryRepo;
38
- transaction: TransactionRepo;
39
- placeOrder: PlaceOrderRepo;
40
- action: ActionRepo;
41
- }) => Promise<T>;
42
- export interface IGlobalFlowTaskResultByName {
43
- name: factory.taskName;
44
- /**
45
- * 集計期間中に作成されたタスク数
46
- */
47
- numberOfCreated: number;
48
- /**
49
- * 集計期間中に実行されたタスク数
50
- */
51
- numberOfExecuted: number;
52
- /**
53
- * 集計期間中に中止されたタスク数
54
- */
55
- numberOfAborted: number;
56
- /**
57
- * 合計待ち時間
58
- */
59
- totalLatencyInMilliseconds: number;
60
- /**
61
- * 最大待ち時間
62
- */
63
- maxLatencyInMilliseconds: number;
64
- /**
65
- * 最小待ち時間
66
- */
67
- minLatencyInMilliseconds: number;
68
- /**
69
- * 合計試行回数
70
- */
71
- totalNumberOfTrials: number;
72
- /**
73
- * 最大試行回数
74
- */
75
- maxNumberOfTrials: number;
76
- /**
77
- * 最小試行回数
78
- */
79
- minNumberOfTrials: number;
80
- }
81
- /**
82
- * フローデータ
83
- * https://en.wikipedia.org/wiki/Stock_and_flow
84
- */
85
- export interface IGlobalFlowResult {
86
- tasks: IGlobalFlowTaskResultByName[];
87
- measuredFrom: Date;
88
- measuredThrough: Date;
89
- }
90
- /**
91
- * ストックデータ
92
- * https://en.wikipedia.org/wiki/Stock_and_flow
93
- */
94
- export interface IGlobalStockResult {
95
- tasks: {
96
- numberOfUnexecuted: number;
97
- };
98
- measuredAt: Date;
99
- }
100
- export interface ISellerFlowTransactionResultByAction {
101
- /**
102
- * アクション数合計値(期限切れ取引)
103
- */
104
- totalNumberOfActionsOnExpired: number;
105
- /**
106
- * 最大アクション数(期限切れ取引)
107
- */
108
- maxNumberOfActionsOnExpired: number;
109
- /**
110
- * 最小アクション数(期限切れ取引)
111
- */
112
- minNumberOfActionsOnExpired: number;
113
- /**
114
- * 平均アクション数(期限切れ取引)
115
- */
116
- averageNumberOfActionsOnExpired: number;
117
- }
118
- export interface ISellerFlowTransactionResult {
119
- /**
120
- * 集計期間中に開始された取引数
121
- */
122
- numberOfStarted: number;
123
- /**
124
- * 集計期間中に開始されてその後成立した取引数
125
- */
126
- numberOfStartedAndConfirmed: number;
127
- /**
128
- * 集計期間中に開始されてその後期限切れになった取引数
129
- */
130
- numberOfStartedAndExpired: number;
131
- /**
132
- * 集計期間中に成立した取引数
133
- */
134
- numberOfConfirmed: number;
135
- /**
136
- * 集計期間中に期限切れになった取引数
137
- */
138
- numberOfExpired: number;
139
- /**
140
- * 取引の合計所要時間(ミリ秒)
141
- */
142
- totalRequiredTimeInMilliseconds: number;
143
- /**
144
- * 取引の最大所要時間(ミリ秒)
145
- */
146
- maxRequiredTimeInMilliseconds: number;
147
- /**
148
- * 取引の最小所要時間(ミリ秒)
149
- */
150
- minRequiredTimeInMilliseconds: number;
151
- /**
152
- * 取引の平均所要時間(ミリ秒)
153
- */
154
- averageRequiredTimeInMilliseconds: number;
155
- /**
156
- * イベントまでの合計残り時間(ミリ秒)
157
- */
158
- /**
159
- * イベントまでの最大残り時間(ミリ秒)
160
- */
161
- /**
162
- * イベントまでの最小残り時間(ミリ秒)
163
- */
164
- /**
165
- * イベントまでの平均残り時間(ミリ秒)
166
- */
167
- /**
168
- * 取引の合計金額(yen)
169
- */
170
- totalAmount: number;
171
- /**
172
- * 最大金額
173
- */
174
- maxAmount: number;
175
- /**
176
- * 最小金額
177
- */
178
- minAmount: number;
179
- /**
180
- * 平均金額
181
- */
182
- averageAmount: number;
183
- /**
184
- * アクション数合計値(成立取引)
185
- */
186
- /**
187
- * 最大アクション数(成立取引)
188
- */
189
- /**
190
- * 最小アクション数(成立取引)
191
- */
192
- /**
193
- * 注文アイテム数合計値
194
- */
195
- totalNumberOfOrderItems: number;
196
- /**
197
- * 最大注文アイテム数
198
- */
199
- maxNumberOfOrderItems: number;
200
- /**
201
- * 最小注文アイテム数
202
- */
203
- minNumberOfOrderItems: number;
204
- /**
205
- * 平均注文アイテム数
206
- */
207
- averageNumberOfOrderItems: number;
208
- }
209
- /**
210
- * 販売者が対象のフローデータ
211
- */
212
- export interface ISellerFlowResult {
213
- transactions: ISellerFlowTransactionResult & ISellerFlowTransactionResultByAction;
214
- measuredFrom: Date;
215
- measuredThrough: Date;
216
- }
217
- /**
218
- * 販売者が対象のストックデータ
219
- */
220
- export interface ISellerStockResult {
221
- transactions: {
222
- numberOfUnderway: number;
223
- };
224
- measuredAt: Date;
225
- }
226
- export declare enum TelemetryScope {
227
- Global = "Global",
228
- Seller = "Seller"
229
- }
230
- export declare enum TelemetryPurposeType {
231
- Flow = "Flow",
232
- Stock = "Stock"
233
- }
234
- export interface IGlobalObect {
235
- scope: TelemetryScope;
236
- measuredAt: Date;
237
- }
238
- export interface ISellerObect {
239
- scope: TelemetryScope;
240
- measuredAt: Date;
241
- sellerId: string;
242
- }
243
- /**
244
- * 測定データインターフェース
245
- */
246
- export interface ITelemetry {
247
- object: any;
248
- result: any;
249
- startDate: Date;
250
- endDate: Date;
251
- purpose: {
252
- typeOf: TelemetryPurposeType;
253
- };
254
- }
255
- export interface IGlobalStockTelemetry extends ITelemetry {
256
- object: IGlobalObect;
257
- result: IGlobalStockResult;
258
- }
259
- export interface IGlobalFlowTelemetry extends ITelemetry {
260
- object: IGlobalObect;
261
- result: IGlobalFlowResult;
262
- }
263
- export interface ISellerStockTelemetry extends ITelemetry {
264
- object: ISellerObect;
265
- result: ISellerStockResult;
266
- }
267
- export interface ISellerFlowTelemetry extends ITelemetry {
268
- object: ISellerObect;
269
- result: ISellerFlowResult;
270
- }
271
- export declare function searchGlobalFlow(searchConditions: {
272
- measuredFrom: Date;
273
- measuredThrough: Date;
274
- }): TelemetryOperation<IGlobalFlowTelemetry[]>;
275
- export declare function searchGlobalStock(searchConditions: {
276
- measuredFrom: Date;
277
- measuredThrough: Date;
278
- }): TelemetryOperation<IGlobalStockTelemetry[]>;
279
- export declare function searchSellerFlow(searchConditions: {
280
- measuredFrom: Date;
281
- measuredThrough: Date;
282
- }): TelemetryOperation<ISellerFlowTelemetry[]>;
283
- export declare function searchSellerStock(searchConditions: {
284
- measuredFrom: Date;
285
- measuredThrough: Date;
286
- }): TelemetryOperation<ISellerStockTelemetry[]>;
287
- /**
288
- * 計測データを検索する
289
- * @param searchConditions.measuredFrom 計測日時from
290
- * @param searchConditions.measuredThrough 計測日時through
291
- */
292
- export declare function search(searchConditions: {
293
- measuredFrom: Date;
294
- measuredThrough: Date;
295
- scope: TelemetryScope;
296
- purpose: TelemetryPurposeType;
297
- }): (repos: {
298
- telemetry: TelemetryRepo;
299
- }) => Promise<ITelemetry[]>;
300
- /**
301
- * フロー測定データを作成する
302
- */
303
- export declare function createFlow(target: {
304
- measuredAt: Date;
305
- sellerId?: string;
306
- }): TaskAndTelemetryAndTransactionOperation<void>;
307
- /**
308
- * ストック測定データを作成する
309
- */
310
- export declare function createStock(target: {
311
- measuredAt: Date;
312
- sellerId?: string;
313
- }): TaskAndTelemetryAndTransactionOperation<void>;
@@ -1,444 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.TelemetryPurposeType = exports.TelemetryScope = void 0;
30
- exports.searchGlobalFlow = searchGlobalFlow;
31
- exports.searchGlobalStock = searchGlobalStock;
32
- exports.searchSellerFlow = searchSellerFlow;
33
- exports.searchSellerStock = searchSellerStock;
34
- exports.search = search;
35
- exports.createFlow = createFlow;
36
- exports.createStock = createStock;
37
- const debug_1 = __importDefault(require("debug"));
38
- const moment_1 = __importDefault(require("moment"));
39
- const factory = __importStar(require("../../factory"));
40
- const debug = (0, debug_1.default)('chevre-domain:service');
41
- const TELEMETRY_UNIT_OF_MEASUREMENT_IN_SECONDS = 60; // 測定単位時間(秒)
42
- var TelemetryScope;
43
- (function (TelemetryScope) {
44
- TelemetryScope["Global"] = "Global";
45
- TelemetryScope["Seller"] = "Seller";
46
- })(TelemetryScope || (exports.TelemetryScope = TelemetryScope = {}));
47
- var TelemetryPurposeType;
48
- (function (TelemetryPurposeType) {
49
- TelemetryPurposeType["Flow"] = "Flow";
50
- TelemetryPurposeType["Stock"] = "Stock";
51
- })(TelemetryPurposeType || (exports.TelemetryPurposeType = TelemetryPurposeType = {}));
52
- function searchGlobalFlow(searchConditions) {
53
- return search({ ...searchConditions, ...{ scope: TelemetryScope.Global, purpose: TelemetryPurposeType.Flow } });
54
- }
55
- function searchGlobalStock(searchConditions) {
56
- return search({ ...searchConditions, ...{ scope: TelemetryScope.Global, purpose: TelemetryPurposeType.Stock } });
57
- }
58
- function searchSellerFlow(searchConditions) {
59
- return search({ ...searchConditions, ...{ scope: TelemetryScope.Seller, purpose: TelemetryPurposeType.Flow } });
60
- }
61
- function searchSellerStock(searchConditions) {
62
- return search({ ...searchConditions, ...{ scope: TelemetryScope.Seller, purpose: TelemetryPurposeType.Stock } });
63
- }
64
- /**
65
- * 計測データを検索する
66
- * @param searchConditions.measuredFrom 計測日時from
67
- * @param searchConditions.measuredThrough 計測日時through
68
- */
69
- function search(searchConditions) {
70
- return async (repos) => {
71
- return repos.telemetry.telemetryModel.find({
72
- 'object.scope': {
73
- $exists: true,
74
- $eq: searchConditions.scope
75
- },
76
- 'object.measuredAt': {
77
- $exists: true,
78
- $gte: searchConditions.measuredFrom,
79
- $lt: searchConditions.measuredThrough
80
- },
81
- 'purpose.typeOf': {
82
- $exists: true,
83
- $eq: searchConditions.purpose
84
- }
85
- })
86
- .sort({ 'object.measuredAt': 1 })
87
- .lean()
88
- .exec();
89
- };
90
- }
91
- /**
92
- * フロー測定データを作成する
93
- */
94
- /* istanbul ignore next */
95
- function createFlow(target) {
96
- return async (repos) => {
97
- const startDate = new Date();
98
- const measuredThrough = (0, moment_1.default)(target.measuredAt);
99
- const measuredFrom = (0, moment_1.default)(measuredThrough)
100
- .add(-TELEMETRY_UNIT_OF_MEASUREMENT_IN_SECONDS, 'seconds');
101
- let telemetry;
102
- if (target.sellerId !== undefined) {
103
- const flowData = await createSellerFlow(measuredFrom.toDate(), measuredThrough.toDate(), target.sellerId)(repos);
104
- debug('flowData created.');
105
- telemetry = {
106
- purpose: { typeOf: TelemetryPurposeType.Flow },
107
- object: {
108
- scope: TelemetryScope.Seller,
109
- measuredAt: target.measuredAt,
110
- sellerId: target.sellerId
111
- },
112
- result: flowData,
113
- startDate: startDate,
114
- endDate: new Date()
115
- };
116
- }
117
- else {
118
- const flowData = await createGlobalFlow(measuredFrom.toDate(), measuredThrough.toDate())({
119
- task: repos.task
120
- });
121
- debug('flowData created.');
122
- telemetry = {
123
- purpose: { typeOf: TelemetryPurposeType.Flow },
124
- object: {
125
- scope: TelemetryScope.Global,
126
- measuredAt: target.measuredAt
127
- },
128
- result: flowData,
129
- startDate: startDate,
130
- endDate: new Date()
131
- };
132
- }
133
- await repos.telemetry.telemetryModel.create(telemetry);
134
- debug('telemetry saved.');
135
- };
136
- }
137
- /**
138
- * ストック測定データを作成する
139
- */
140
- /* istanbul ignore next */
141
- function createStock(target) {
142
- return async (repos) => {
143
- const startDate = new Date();
144
- let telemetry;
145
- if (target.sellerId !== undefined) {
146
- const stockData = await createSellerStock(target.measuredAt, target.sellerId)(repos);
147
- debug('stockData created.');
148
- telemetry = {
149
- purpose: { typeOf: TelemetryPurposeType.Stock },
150
- object: {
151
- scope: TelemetryScope.Seller,
152
- measuredAt: target.measuredAt,
153
- sellerId: target.sellerId
154
- },
155
- result: stockData,
156
- startDate: startDate,
157
- endDate: new Date()
158
- };
159
- }
160
- else {
161
- const stockData = await createGlobalStock(target.measuredAt)({ task: repos.task });
162
- debug('stockData created.');
163
- telemetry = {
164
- purpose: { typeOf: TelemetryPurposeType.Stock },
165
- object: {
166
- scope: TelemetryScope.Global,
167
- measuredAt: target.measuredAt
168
- },
169
- result: stockData,
170
- startDate: startDate,
171
- endDate: new Date()
172
- };
173
- }
174
- await repos.telemetry.telemetryModel.create(telemetry);
175
- debug('telemetry saved.');
176
- };
177
- }
178
- /**
179
- * フロー計測データーを作成する
180
- * @param measuredFrom 計測開始日時
181
- * @param measuredThrough 計測終了日時
182
- */
183
- /* istanbul ignore next */
184
- function createSellerFlow(measuredFrom, measuredThrough, sellerId) {
185
- return async (repos) => {
186
- const { sellerFlowTransactionResult, expiredTransactionIds } = await createSellerFlowTransactionResult(measuredFrom, measuredThrough, sellerId)(repos);
187
- // 期限切れ取引数
188
- const numberOfTransactionsExpired = sellerFlowTransactionResult.numberOfExpired;
189
- // 期限切れ取引に対して作成されたアクションを取得
190
- const actionsOnExpiredTransactions = await repos.action.search({
191
- typeOf: { $eq: factory.actionType.AuthorizeAction },
192
- purpose: { id: { $in: expiredTransactionIds } }
193
- }, []);
194
- debug(actionsOnExpiredTransactions.length, 'actionsOnExpiredTransactions found.');
195
- const numbersOfActionsOnExpired = expiredTransactionIds.map((transactionId) => {
196
- return actionsOnExpiredTransactions.filter((action) => action.purpose?.id === transactionId).length;
197
- });
198
- const totalNumberOfActionsOnExpired = numbersOfActionsOnExpired.reduce((a, b) => a + b, 0);
199
- const maxNumberOfActionsOnExpired = numbersOfActionsOnExpired.reduce((a, b) => Math.max(a, b), 0);
200
- const minNumberOfActionsOnExpired = numbersOfActionsOnExpired.reduce((a, b) => Math.min(a, b), (numberOfTransactionsExpired > 0) ? numbersOfActionsOnExpired[0] : 0);
201
- const averageNumberOfActionsOnExpired = (numberOfTransactionsExpired > 0) ? totalNumberOfActionsOnExpired / numberOfTransactionsExpired : 0;
202
- return {
203
- transactions: {
204
- ...sellerFlowTransactionResult,
205
- totalNumberOfActionsOnExpired: totalNumberOfActionsOnExpired,
206
- maxNumberOfActionsOnExpired: maxNumberOfActionsOnExpired,
207
- minNumberOfActionsOnExpired: minNumberOfActionsOnExpired,
208
- averageNumberOfActionsOnExpired: parseFloat(averageNumberOfActionsOnExpired.toFixed(1)),
209
- totalNumberOfOrderItems: 0, // TODO 実装
210
- maxNumberOfOrderItems: 0, // TODO 実装
211
- minNumberOfOrderItems: 0, // TODO 実装
212
- averageNumberOfOrderItems: 0 // TODO 実装
213
- },
214
- measuredFrom: measuredFrom,
215
- measuredThrough: measuredThrough
216
- };
217
- };
218
- }
219
- function createSellerFlowTransactionResult(measuredFrom, measuredThrough, sellerId) {
220
- return async (repos) => {
221
- // 計測期間内に開始された取引数を算出する
222
- const { count } = await repos.placeOrder.countPlaceOrder({
223
- typeOf: factory.transactionType.PlaceOrder,
224
- seller: { ids: [sellerId] },
225
- startFrom: measuredFrom,
226
- startThrough: measuredThrough
227
- });
228
- const numberOfTransactionsStarted = count;
229
- // 計測期間内に開始され、かつ、すでに終了している取引を検索
230
- const startedAndEndedTransactions = await repos.placeOrder.findPlaceOrderTransactions({
231
- typeOf: factory.transactionType.PlaceOrder,
232
- seller: { ids: [sellerId] },
233
- startFrom: measuredFrom,
234
- startThrough: measuredThrough,
235
- endThrough: new Date(),
236
- inclusion: ['status']
237
- });
238
- const numberOfStartedAndConfirmed = startedAndEndedTransactions.filter((transaction) => transaction.status === factory.transactionStatusType.Confirmed).length;
239
- const numberOfStartedAndExpired = startedAndEndedTransactions.filter((transaction) => transaction.status === factory.transactionStatusType.Expired).length;
240
- const endedTransactions = await repos.placeOrder.findPlaceOrderTransactions({
241
- typeOf: factory.transactionType.PlaceOrder,
242
- seller: { ids: [sellerId] },
243
- endFrom: measuredFrom,
244
- endThrough: measuredThrough,
245
- inclusion: ['status', 'endDate', 'startDate', 'result']
246
- });
247
- debug(endedTransactions.length, 'endedTransactions found.');
248
- const confirmedTransactions = endedTransactions.filter((transaction) => transaction.status === factory.transactionStatusType.Confirmed);
249
- const expiredTransactions = endedTransactions.filter((transaction) => transaction.status === factory.transactionStatusType.Expired);
250
- const numberOfTransactionsConfirmed = confirmedTransactions.length;
251
- // 所要時間算出(期間の成立取引リストを取得し、開始時刻と成立時刻の差を所要時間とする)
252
- const requiredTimesConfirmed = confirmedTransactions.map((transaction) => (0, moment_1.default)(transaction.endDate)
253
- .diff((0, moment_1.default)(transaction.startDate, 'milliseconds')));
254
- const totalRequiredTimeInMilliseconds = requiredTimesConfirmed.reduce((a, b) => a + b, 0);
255
- const maxRequiredTimeInMilliseconds = requiredTimesConfirmed.reduce((a, b) => Math.max(a, b), 0);
256
- const minRequiredTimeInMilliseconds = requiredTimesConfirmed.reduce((a, b) => Math.min(a, b), (numberOfTransactionsConfirmed > 0) ? requiredTimesConfirmed[0] : 0);
257
- const averageRequiredTimeInMilliseconds = (numberOfTransactionsConfirmed > 0) ? totalRequiredTimeInMilliseconds / numberOfTransactionsConfirmed : 0;
258
- // const totalTimeLeftUntilEventInMilliseconds = timesLeftUntilEvent.reduce((a, b) => a + b, 0);
259
- // const maxTimeLeftUntilEventInMilliseconds = timesLeftUntilEvent.reduce((a, b) => Math.max(a, b), 0);
260
- // const minTimeLeftUntilEventInMilliseconds =
261
- // timesLeftUntilEvent.reduce((a, b) => Math.min(a, b), (numberOfTransactionsConfirmed > 0) ? timesLeftUntilEvent[0] : 0);
262
- // const averageTimeLeftUntilEventInMilliseconds =
263
- // (numberOfTransactionsConfirmed > 0) ? totalTimeLeftUntilEventInMilliseconds / numberOfTransactionsConfirmed : 0;
264
- // 金額算出
265
- const amounts = confirmedTransactions.map((transaction) => transaction.result.order.price);
266
- const totalAmount = amounts.reduce((a, b) => a + b, 0);
267
- const maxAmount = amounts.reduce((a, b) => Math.max(a, b), 0);
268
- const minAmount = amounts.reduce((a, b) => Math.min(a, b), (numberOfTransactionsConfirmed > 0) ? amounts[0] : 0);
269
- const averageAmount = (numberOfTransactionsConfirmed > 0) ? totalAmount / numberOfTransactionsConfirmed : 0;
270
- // アクション数集計
271
- // const numbersOfActions = confirmedTransactions.map((t) => t.object.authorizeActions.length);
272
- // const totalNumberOfActions = numbersOfActions.reduce((a, b) => a + b, 0);
273
- // const maxNumberOfActions = numbersOfActions.reduce((a, b) => Math.max(a, b), 0);
274
- // const minNumberOfActions = numbersOfActions.reduce(
275
- // (a, b) => Math.min(a, b), (numberOfTransactionsConfirmed > 0) ? numbersOfActions[0] : 0
276
- // );
277
- // const averageNumberOfActions = (numberOfTransactionsConfirmed > 0) ? totalNumberOfActions / numberOfTransactionsConfirmed : 0;
278
- // 期限切れ取引数
279
- const numberOfTransactionsExpired = expiredTransactions.length;
280
- const expiredTransactionIds = expiredTransactions.map((transaction) => transaction.id);
281
- return {
282
- sellerFlowTransactionResult: {
283
- numberOfStarted: numberOfTransactionsStarted,
284
- numberOfStartedAndConfirmed: numberOfStartedAndConfirmed,
285
- numberOfStartedAndExpired: numberOfStartedAndExpired,
286
- numberOfConfirmed: numberOfTransactionsConfirmed,
287
- numberOfExpired: numberOfTransactionsExpired,
288
- totalRequiredTimeInMilliseconds: totalRequiredTimeInMilliseconds,
289
- maxRequiredTimeInMilliseconds: maxRequiredTimeInMilliseconds,
290
- minRequiredTimeInMilliseconds: minRequiredTimeInMilliseconds,
291
- averageRequiredTimeInMilliseconds: parseFloat(averageRequiredTimeInMilliseconds.toFixed(1)),
292
- // totalTimeLeftUntilEventInMilliseconds: totalTimeLeftUntilEventInMilliseconds,
293
- // maxTimeLeftUntilEventInMilliseconds: maxTimeLeftUntilEventInMilliseconds,
294
- // minTimeLeftUntilEventInMilliseconds: minTimeLeftUntilEventInMilliseconds,
295
- // averageTimeLeftUntilEventInMilliseconds: averageTimeLeftUntilEventInMilliseconds,
296
- totalAmount: totalAmount,
297
- maxAmount: maxAmount,
298
- minAmount: minAmount,
299
- averageAmount: parseFloat(averageAmount.toFixed(1)),
300
- // totalNumberOfActionsOnConfirmed: totalNumberOfActions,
301
- // maxNumberOfActionsOnConfirmed: maxNumberOfActions,
302
- // minNumberOfActionsOnConfirmed: minNumberOfActions,
303
- // averageNumberOfActionsOnConfirmed: parseFloat(averageNumberOfActions.toFixed(1)),
304
- totalNumberOfOrderItems: 0, // TODO 実装
305
- maxNumberOfOrderItems: 0, // TODO 実装
306
- minNumberOfOrderItems: 0, // TODO 実装
307
- averageNumberOfOrderItems: 0 // TODO 実装
308
- },
309
- expiredTransactionIds
310
- };
311
- };
312
- }
313
- /**
314
- * ストック計測データを作成する
315
- * @param measuredAt 計測日時
316
- */
317
- /* istanbul ignore next */
318
- function createSellerStock(measuredAt, sellerId) {
319
- return async (repos) => {
320
- // {measuredAt}以前に開始し、{measuredAt}以後に成立あるいは期限切れした取引
321
- const { count } = await repos.placeOrder.countPlaceOrder({
322
- typeOf: factory.transactionType.PlaceOrder,
323
- seller: { ids: [sellerId] },
324
- startThrough: measuredAt,
325
- endFrom: measuredAt
326
- });
327
- const numTransactionsUnderway1 = count;
328
- // {measuredAt}以前に開始し、いまだに進行中の取引
329
- const count2Result = await repos.placeOrder.countPlaceOrder({
330
- typeOf: factory.transactionType.PlaceOrder,
331
- seller: { ids: [sellerId] },
332
- startThrough: measuredAt,
333
- statuses: [factory.transactionStatusType.InProgress]
334
- });
335
- const numTransactionsUnderway2 = count2Result.count;
336
- const numberOfTransactionsUnderway = numTransactionsUnderway1 + numTransactionsUnderway2;
337
- debug('numberOfTransactionsUnderway:', numberOfTransactionsUnderway);
338
- return {
339
- transactions: {
340
- numberOfUnderway: numberOfTransactionsUnderway
341
- },
342
- measuredAt: measuredAt
343
- };
344
- };
345
- }
346
- /**
347
- * フロー計測データーを作成する
348
- * @param measuredFrom 計測開始日時
349
- * @param measuredThrough 計測終了日時
350
- */
351
- /* istanbul ignore next */
352
- function createGlobalFlow(measuredFrom, measuredThrough) {
353
- return async (repos) => {
354
- // 全タスク名リスト
355
- const targetTaskNames = Object.keys(factory.taskName)
356
- .map((k) => factory.taskName[k]);
357
- const taskResults = await Promise.all(targetTaskNames.map(async (taskName) => {
358
- const numberOfTasksCreated = await repos.task.taskModel.countDocuments({
359
- name: taskName,
360
- createdAt: {
361
- $gte: measuredFrom,
362
- $lt: measuredThrough
363
- }
364
- })
365
- .exec();
366
- debug('numberOfTasksCreated:', numberOfTasksCreated);
367
- // 実行中止ステータスで、最終試行日時が範囲にあるものを実行タスク数とする
368
- const numberOfTasksAborted = await repos.task.taskModel.countDocuments({
369
- name: taskName,
370
- lastTriedAt: {
371
- $type: 'date',
372
- $gte: measuredFrom,
373
- $lt: measuredThrough
374
- },
375
- status: factory.taskStatus.Aborted
376
- })
377
- .exec();
378
- debug('numberOfTasksAborted:', numberOfTasksAborted);
379
- // 実行済みステータスで、最終試行日時が範囲にあるものを実行タスク数とする
380
- const executedTasks = await repos.task.taskModel.find({
381
- name: taskName,
382
- lastTriedAt: {
383
- $type: 'date',
384
- $gte: measuredFrom,
385
- $lt: measuredThrough
386
- },
387
- status: factory.taskStatus.Executed
388
- }, 'runsAt lastTriedAt numberOfTried')
389
- .exec()
390
- .then((docs) => docs.map((doc) => doc.toObject()));
391
- debug(executedTasks.length, 'executedTasks found.');
392
- const numberOfTasksExecuted = executedTasks.length;
393
- const latencies = executedTasks.map((task) => (0, moment_1.default)(task.lastTriedAt)
394
- .diff((0, moment_1.default)(task.runsAt, 'milliseconds')));
395
- const totalLatency = latencies.reduce((a, b) => a + b, 0);
396
- const maxLatency = latencies.reduce((a, b) => Math.max(a, b), 0);
397
- const minLatency = latencies.reduce((a, b) => Math.min(a, b), (numberOfTasksExecuted > 0) ? latencies[0] : 0);
398
- const numbersOfTrials = await Promise.all(executedTasks.map((task) => task.numberOfTried));
399
- const totalNumberOfTrials = numbersOfTrials.reduce((a, b) => a + b, 0);
400
- const maxNumberOfTrials = numbersOfTrials.reduce((a, b) => Math.max(a, b), 0);
401
- const minNumberOfTrials = numbersOfTrials.reduce((a, b) => Math.min(a, b), (numberOfTasksExecuted > 0) ? numbersOfTrials[0] : 0);
402
- return {
403
- name: taskName,
404
- numberOfCreated: numberOfTasksCreated,
405
- numberOfExecuted: numberOfTasksExecuted,
406
- numberOfAborted: numberOfTasksAborted,
407
- totalLatencyInMilliseconds: totalLatency,
408
- maxLatencyInMilliseconds: maxLatency,
409
- minLatencyInMilliseconds: minLatency,
410
- totalNumberOfTrials: totalNumberOfTrials,
411
- maxNumberOfTrials: maxNumberOfTrials,
412
- minNumberOfTrials: minNumberOfTrials
413
- };
414
- }));
415
- return {
416
- tasks: taskResults,
417
- measuredFrom: measuredFrom,
418
- measuredThrough: measuredThrough
419
- };
420
- };
421
- }
422
- /**
423
- * ストック計測データを作成する
424
- * @param measuredAt 計測日時
425
- */
426
- /* istanbul ignore next */
427
- function createGlobalStock(measuredAt) {
428
- return async (repos) => {
429
- // 待機状態のタスク数を算出
430
- debug('counting waiting tasks globally...');
431
- const numberOfTasksUnexecuted = await repos.task.taskModel.countDocuments({
432
- runsAt: { $lt: measuredAt }, // 実行日時を超過している
433
- status: { $in: [factory.taskStatus.Ready, factory.taskStatus.Running] }
434
- })
435
- .exec();
436
- debug('global waiting tasks count', numberOfTasksUnexecuted);
437
- return {
438
- tasks: {
439
- numberOfUnexecuted: numberOfTasksUnexecuted
440
- },
441
- measuredAt: measuredAt
442
- };
443
- };
444
- }