@chevre/domain 20.2.0-alpha.2 → 20.2.0-alpha.21

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 (67) hide show
  1. package/example/src/chevre/aggregateEventReservation.ts +37 -0
  2. package/example/src/chevre/aggregation/aggregateSystem.ts +82 -0
  3. package/example/src/chevre/importEventsFromCOA.ts +8 -1
  4. package/example/src/chevre/migrateEventOffersItemOfferedAvailableChannel.ts +90 -0
  5. package/example/src/chevre/migrateEventOffersItemOfferedTypeOf.ts +0 -5
  6. package/example/src/chevre/migratePaymentServicePaymentUrlExpiresInSeconds.ts +77 -0
  7. package/lib/chevre/repo/action.d.ts +58 -0
  8. package/lib/chevre/repo/action.js +187 -0
  9. package/lib/chevre/repo/aggregation.d.ts +34 -0
  10. package/lib/chevre/repo/aggregation.js +64 -0
  11. package/lib/chevre/repo/event.d.ts +0 -1
  12. package/lib/chevre/repo/event.js +124 -105
  13. package/lib/chevre/repo/mongoose/model/aggregation.d.ts +7 -0
  14. package/lib/chevre/repo/mongoose/model/aggregation.js +47 -0
  15. package/lib/chevre/repo/mongoose/model/event.js +2 -2
  16. package/lib/chevre/repo/mongoose/model/telemetry.js +4 -28
  17. package/lib/chevre/repo/order.d.ts +9 -0
  18. package/lib/chevre/repo/order.js +49 -0
  19. package/lib/chevre/repo/place.d.ts +15 -1
  20. package/lib/chevre/repo/place.js +205 -52
  21. package/lib/chevre/repo/product.d.ts +1 -0
  22. package/lib/chevre/repo/product.js +5 -0
  23. package/lib/chevre/repo/reservation.d.ts +0 -6
  24. package/lib/chevre/repo/reservation.js +106 -66
  25. package/lib/chevre/repo/transaction.d.ts +29 -0
  26. package/lib/chevre/repo/transaction.js +133 -0
  27. package/lib/chevre/repo/trip.js +33 -27
  28. package/lib/chevre/repository.d.ts +3 -0
  29. package/lib/chevre/repository.js +5 -1
  30. package/lib/chevre/service/aggregation/event/aggregateScreeningEvent.d.ts +1 -1
  31. package/lib/chevre/service/aggregation/event/aggregateScreeningEvent.js +34 -13
  32. package/lib/chevre/service/aggregation/system.d.ts +74 -0
  33. package/lib/chevre/service/aggregation/system.js +266 -0
  34. package/lib/chevre/service/aggregation.d.ts +2 -0
  35. package/lib/chevre/service/aggregation.js +3 -1
  36. package/lib/chevre/service/assetTransaction/pay/potentialActions.js +2 -4
  37. package/lib/chevre/service/assetTransaction/pay.d.ts +19 -4
  38. package/lib/chevre/service/assetTransaction/pay.js +65 -32
  39. package/lib/chevre/service/assetTransaction/reserve/factory.d.ts +3 -0
  40. package/lib/chevre/service/assetTransaction/reserve/factory.js +33 -2
  41. package/lib/chevre/service/assetTransaction/reserve.d.ts +7 -2
  42. package/lib/chevre/service/assetTransaction/reserve.js +33 -51
  43. package/lib/chevre/service/delivery/factory.js +1 -0
  44. package/lib/chevre/service/event.d.ts +2 -4
  45. package/lib/chevre/service/event.js +21 -10
  46. package/lib/chevre/service/offer/event/cancel.js +0 -1
  47. package/lib/chevre/service/offer/event/factory.js +25 -5
  48. package/lib/chevre/service/offer/event/searchEventTicketOffers.js +116 -4
  49. package/lib/chevre/service/offer/event/voidTransaction.js +0 -2
  50. package/lib/chevre/service/offer.js +28 -20
  51. package/lib/chevre/service/order/onOrderStatusChanged/factory.js +2 -1
  52. package/lib/chevre/service/order/onOrderStatusChanged.js +2 -1
  53. package/lib/chevre/service/order/placeOrder.js +16 -0
  54. package/lib/chevre/service/payment/any.d.ts +5 -0
  55. package/lib/chevre/service/reserve/confirmReservation.js +7 -10
  56. package/lib/chevre/service/reserve/useReservation.js +2 -1
  57. package/lib/chevre/service/task/confirmPayTransaction.js +20 -1
  58. package/lib/chevre/service/task/confirmReserveTransaction.d.ts +4 -0
  59. package/lib/chevre/service/task/confirmReserveTransaction.js +5 -5
  60. package/lib/chevre/service/task/importEventsFromCOA.js +3 -1
  61. package/lib/chevre/service/transaction/placeOrderInProgress/result/acceptedOffers.js +42 -27
  62. package/lib/chevre/settings.d.ts +2 -0
  63. package/lib/chevre/settings.js +7 -2
  64. package/package.json +3 -3
  65. package/example/src/chevre/aggregateReservationOnProject.ts +0 -32
  66. package/example/src/chevre/migrateEventProjectAttributes.ts +0 -57
  67. package/example/src/chevre/migratePlaceAdditionalProperties.ts +0 -162
@@ -0,0 +1,37 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+ import * as redis from 'redis';
4
+
5
+ import { chevre } from '../../../lib/index';
6
+
7
+ // const project = { id: <string>process.env.PROJECT_ID };
8
+
9
+ async function main() {
10
+ await mongoose.connect(<string>process.env.MONGOLAB_URI);
11
+ const client = redis.createClient({
12
+ host: process.env.REDIS_HOST,
13
+ port: Number(process.env.REDIS_PORT),
14
+ password: process.env.REDIS_KEY
15
+ });
16
+
17
+ // const now = new Date();
18
+ await chevre.service.aggregation.event.aggregateScreeningEvent({
19
+ id: 'alb35u7m4'
20
+ })({
21
+ event: new chevre.repository.Event(mongoose.connection),
22
+ eventAvailability: new chevre.repository.itemAvailability.ScreeningEvent(client),
23
+ offer: new chevre.repository.Offer(mongoose.connection),
24
+ offerRateLimit: new chevre.repository.rateLimit.Offer(client),
25
+ place: new chevre.repository.Place(mongoose.connection),
26
+ product: new chevre.repository.Product(mongoose.connection),
27
+ project: new chevre.repository.Project(mongoose.connection),
28
+ reservation: new chevre.repository.Reservation(mongoose.connection),
29
+ task: new chevre.repository.Task(mongoose.connection)
30
+ });
31
+ }
32
+
33
+ main()
34
+ .then(() => {
35
+ console.log('success!');
36
+ })
37
+ .catch(console.error);
@@ -0,0 +1,82 @@
1
+ // tslint:disable:no-console
2
+ import * as mongoose from 'mongoose';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ // const project = { id: <string>process.env.PROJECT_ID };
7
+ const EXCLUDED_PROJECT_ID = process.env.EXCLUDED_PROJECT_ID;
8
+ const AGGREGATE_DAYS = Number(process.env.AGGREGATE_DAYS);
9
+ const AGGREGATE_CLIENT_IDS = (typeof process.env.AGGREGATE_CLIENT_IDS === 'string') ? process.env.AGGREGATE_CLIENT_IDS.split(',') : [];
10
+
11
+ async function main() {
12
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
13
+
14
+ const aggregationRepo = new chevre.repository.Aggregation(mongoose.connection);
15
+ const transactionRepo = new chevre.repository.Transaction(mongoose.connection);
16
+ const reservationRepo = new chevre.repository.Reservation(mongoose.connection);
17
+ const orderRepo = new chevre.repository.Order(mongoose.connection);
18
+ const actionRepo = new chevre.repository.Action(mongoose.connection);
19
+
20
+ await chevre.service.aggregation.system.aggregatePlaceOrder({
21
+ aggregationDays: AGGREGATE_DAYS,
22
+ excludedProjectId: EXCLUDED_PROJECT_ID,
23
+ clientIds: AGGREGATE_CLIENT_IDS
24
+ })({
25
+ agregation: aggregationRepo,
26
+ transaction: transactionRepo
27
+ });
28
+
29
+ await chevre.service.aggregation.system.aggregateAuthorizeOrderAction({
30
+ aggregationDays: AGGREGATE_DAYS,
31
+ excludedProjectId: EXCLUDED_PROJECT_ID
32
+ })({
33
+ agregation: aggregationRepo,
34
+ action: actionRepo
35
+ });
36
+
37
+ await chevre.service.aggregation.system.aggregateAuthorizeEventServiceOfferAction({
38
+ aggregationDays: AGGREGATE_DAYS,
39
+ excludedProjectId: EXCLUDED_PROJECT_ID
40
+ })({
41
+ agregation: aggregationRepo,
42
+ action: actionRepo
43
+ });
44
+
45
+ await chevre.service.aggregation.system.aggregateAuthorizePaymentAction({
46
+ aggregationDays: AGGREGATE_DAYS,
47
+ excludedProjectId: EXCLUDED_PROJECT_ID
48
+ })({
49
+ agregation: aggregationRepo,
50
+ action: actionRepo
51
+ });
52
+
53
+ await chevre.service.aggregation.system.aggregateUseAction({
54
+ aggregationDays: AGGREGATE_DAYS,
55
+ excludedProjectId: EXCLUDED_PROJECT_ID
56
+ })({
57
+ agregation: aggregationRepo,
58
+ action: actionRepo
59
+ });
60
+
61
+ await chevre.service.aggregation.system.aggregateOrder({
62
+ aggregationDays: AGGREGATE_DAYS,
63
+ excludedProjectId: EXCLUDED_PROJECT_ID
64
+ })({
65
+ agregation: aggregationRepo,
66
+ order: orderRepo
67
+ });
68
+
69
+ await chevre.service.aggregation.system.aggregateReservation({
70
+ aggregationDays: AGGREGATE_DAYS,
71
+ excludedProjectId: EXCLUDED_PROJECT_ID
72
+ })({
73
+ agregation: aggregationRepo,
74
+ reservation: reservationRepo
75
+ });
76
+ }
77
+
78
+ main()
79
+ .then(() => {
80
+ console.log('success!');
81
+ })
82
+ .catch(console.error);
@@ -14,6 +14,7 @@ async function main() {
14
14
  const categoryCodeRepo = new chevre.repository.CategoryCode(mongoose.connection);
15
15
  const eventRepo = new chevre.repository.Event(mongoose.connection);
16
16
  const placeRepo = new chevre.repository.Place(mongoose.connection);
17
+ const sellerRepo = new chevre.repository.Seller(mongoose.connection);
17
18
 
18
19
  await chevre.service.event.importFromCOA({
19
20
  project: {
@@ -28,7 +29,13 @@ async function main() {
28
29
  .toDate(),
29
30
  saveMovieTheater: false,
30
31
  saveScreeningEventSeries: false
31
- })({ action: actionRepo, categoryCode: categoryCodeRepo, event: eventRepo, place: placeRepo });
32
+ })({
33
+ action: actionRepo,
34
+ categoryCode: categoryCodeRepo,
35
+ event: eventRepo,
36
+ place: placeRepo,
37
+ seller: sellerRepo
38
+ });
32
39
  console.log('imported');
33
40
  }
34
41
 
@@ -0,0 +1,90 @@
1
+ // tslint:disable:no-console
2
+ import * as moment from 'moment';
3
+ import * as mongoose from 'mongoose';
4
+
5
+ import { chevre } from '../../../lib/index';
6
+
7
+ // const project = { id: String(process.env.PROJECT_ID) };
8
+
9
+ const EXCLUDED_PROJECT_ID = process.env.EXCLUDED_PROJECT_ID;
10
+
11
+ // tslint:disable-next-line:max-func-body-length
12
+ async function main() {
13
+ await mongoose.connect(<string>process.env.MONGOLAB_URI);
14
+
15
+ const eventRepo = new chevre.repository.Event(mongoose.connection);
16
+
17
+ const cursor = eventRepo.getCursor(
18
+ {
19
+ // 'project.id': { $eq: project.id },
20
+ 'project.id': { $ne: EXCLUDED_PROJECT_ID },
21
+ typeOf: { $eq: chevre.factory.eventType.ScreeningEvent },
22
+ startDate: {
23
+ $gte: moment()
24
+ // tslint:disable-next-line:no-magic-numbers
25
+ .add(-6, 'months')
26
+ .toDate()
27
+ }
28
+ // _id: { $eq: 'al6aff83w' }
29
+ },
30
+ {
31
+ // _id: 1,
32
+ }
33
+ );
34
+ console.log('events found');
35
+
36
+ let i = 0;
37
+ let updateCount = 0;
38
+ await cursor.eachAsync(async (doc) => {
39
+ i += 1;
40
+ const event: chevre.factory.event.screeningEvent.IEvent = doc.toObject();
41
+
42
+ const eventOffers = <chevre.factory.event.screeningEvent.IOffer | undefined>event.offers;
43
+ if (eventOffers === undefined) {
44
+ throw new Error('event.offers undefined');
45
+ }
46
+
47
+ const availableChannel = eventOffers.itemOffered.availableChannel;
48
+
49
+ const alreadyMigrated = availableChannel?.typeOf === 'ServiceChannel';
50
+
51
+ if (alreadyMigrated) {
52
+ console.log(
53
+ 'already exist...', event.project.id, event.id, event.startDate, availableChannel.serviceLocation.branchCode, i);
54
+ } else {
55
+ const newAvailableChannel: chevre.factory.reservation.IServiceChannel = {
56
+ typeOf: 'ServiceChannel',
57
+ serviceLocation: {
58
+ typeOf: event.location.typeOf,
59
+ branchCode: event.location.branchCode,
60
+ name: event.location.name,
61
+ containedInPlace: {
62
+ typeOf: event.superEvent.location.typeOf,
63
+ id: event.superEvent.location.id,
64
+ branchCode: event.superEvent.location.branchCode,
65
+ name: event.superEvent.location.name
66
+ }
67
+ }
68
+ };
69
+ console.log(
70
+ 'updating seller...', event.project.id, event.id, event.startDate, newAvailableChannel.serviceLocation.branchCode, i);
71
+ await eventRepo.updatePartiallyById({
72
+ id: event.id,
73
+ attributes: <any>{
74
+ typeOf: event.typeOf,
75
+ 'offers.itemOffered.availableChannel': newAvailableChannel
76
+ }
77
+ });
78
+ updateCount += 1;
79
+ console.log(
80
+ 'updated...', event.project.id, event.id, event.startDate, i);
81
+ }
82
+ });
83
+
84
+ console.log(i, 'events checked');
85
+ console.log(updateCount, 'events updated');
86
+ }
87
+
88
+ main()
89
+ .then()
90
+ .catch(console.error);
@@ -5,11 +5,6 @@ import * as mongoose from 'mongoose';
5
5
  import { chevre } from '../../../lib/index';
6
6
 
7
7
  // const project = { id: String(process.env.PROJECT_ID) };
8
-
9
- const POS_CLIENT_ID = process.env.POS_CLIENT_ID;
10
- if (typeof POS_CLIENT_ID !== 'string') {
11
- throw new Error('set POS_CLIENT_ID');
12
- }
13
8
  const EXCLUDED_PROJECT_ID = process.env.EXCLUDED_PROJECT_ID;
14
9
 
15
10
  // tslint:disable-next-line:max-func-body-length
@@ -0,0 +1,77 @@
1
+ // tslint:disable:no-console
2
+ // import * as moment from 'moment';
3
+ import * as mongoose from 'mongoose';
4
+
5
+ import { chevre } from '../../../lib/index';
6
+
7
+ // const project = { id: String(process.env.PROJECT_ID) };
8
+ const EXCLUDED_PROJECT_ID = process.env.EXCLUDED_PROJECT_ID;
9
+
10
+ // tslint:disable-next-line:max-func-body-length
11
+ async function main() {
12
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
13
+
14
+ const productRepo = new chevre.repository.Product(mongoose.connection);
15
+
16
+ const cursor = productRepo.getCursor(
17
+ {
18
+ // 'project.id': { $eq: project.id },
19
+ 'project.id': { $ne: EXCLUDED_PROJECT_ID },
20
+ typeOf: { $eq: chevre.factory.service.paymentService.PaymentServiceType.CreditCard }
21
+ },
22
+ {
23
+ // _id: 1,
24
+ }
25
+ );
26
+ console.log('products found');
27
+
28
+ let i = 0;
29
+ let updateCount = 0;
30
+ // tslint:disable-next-line:max-func-body-length
31
+ await cursor.eachAsync(async (doc) => {
32
+ i += 1;
33
+ const paymentService: chevre.factory.service.paymentService.IService = doc.toObject();
34
+
35
+ const hasPaymentUrlExpiresInseconds = paymentService.provider?.some((provider) => {
36
+ return typeof (<any>provider).credentials?.paymentUrlExpiresInSeconds === 'number';
37
+ });
38
+
39
+ if (!hasPaymentUrlExpiresInseconds) {
40
+ console.log(
41
+ 'no expiresInSeconds', paymentService.project.id, paymentService.id, paymentService.productID, i);
42
+
43
+ return;
44
+ }
45
+
46
+ const alreadyMigrated = paymentService.provider?.filter((provider) => {
47
+ return typeof (<any>provider).credentials?.paymentUrlExpiresInSeconds === 'number';
48
+ })
49
+ .every((provider) => {
50
+ return typeof provider.credentials?.paymentUrl?.expiresInSeconds === 'number';
51
+ });
52
+
53
+ if (alreadyMigrated) {
54
+ console.log(
55
+ 'already exist...', paymentService.project.id, paymentService.id, paymentService.productID, i);
56
+ } else {
57
+ console.log(
58
+ 'updating product...', paymentService.project.id, paymentService.id, paymentService.productID, i);
59
+ // await eventRepo.updatePartiallyById({
60
+ // id: event.id,
61
+ // attributes: <any>{
62
+ // typeOf: event.typeOf,
63
+ // 'offers.itemOffered.availableChannel': newAvailableChannel
64
+ // }
65
+ // });
66
+ updateCount += 1;
67
+ console.log(
68
+ 'updated...', paymentService.project.id, paymentService.id, paymentService.productID, i);
69
+ }
70
+ });
71
+ console.log(i, 'products checked');
72
+ console.log(updateCount, 'products updated');
73
+ }
74
+
75
+ main()
76
+ .then()
77
+ .catch(console.error);
@@ -7,6 +7,23 @@ export interface IUseActionCountByOffer {
7
7
  _id: string[];
8
8
  useActionCount?: number;
9
9
  }
10
+ interface IAggregationByStatus {
11
+ actionCount: number;
12
+ avgDuration: number;
13
+ maxDuration: number;
14
+ minDuration: number;
15
+ percentilesDuration: {
16
+ name: string;
17
+ value: number;
18
+ }[];
19
+ }
20
+ interface IStatus {
21
+ status: factory.actionStatusType;
22
+ aggregation: IAggregationByStatus;
23
+ }
24
+ interface IAggregateAction {
25
+ statuses: IStatus[];
26
+ }
10
27
  export { modelName };
11
28
  /**
12
29
  * アクションリポジトリ
@@ -107,4 +124,45 @@ export declare class MongoRepository {
107
124
  deleteEndDatePassedCertainPeriod(params: {
108
125
  $lt: Date;
109
126
  }): Promise<void>;
127
+ aggregateAuthorizeEventServiceOfferAction(params: {
128
+ project?: {
129
+ id?: {
130
+ $ne?: string;
131
+ };
132
+ };
133
+ startFrom: Date;
134
+ startThrough: Date;
135
+ typeOf: factory.actionType;
136
+ }): Promise<IAggregateAction>;
137
+ aggregateAuthorizePaymentAction(params: {
138
+ project?: {
139
+ id?: {
140
+ $ne?: string;
141
+ };
142
+ };
143
+ startFrom: Date;
144
+ startThrough: Date;
145
+ typeOf: factory.actionType;
146
+ }): Promise<IAggregateAction>;
147
+ aggregateAuthorizeOrderAction(params: {
148
+ project?: {
149
+ id?: {
150
+ $ne?: string;
151
+ };
152
+ };
153
+ startFrom: Date;
154
+ startThrough: Date;
155
+ typeOf: factory.actionType;
156
+ }): Promise<IAggregateAction>;
157
+ aggregateUseAction(params: {
158
+ project?: {
159
+ id?: {
160
+ $ne?: string;
161
+ };
162
+ };
163
+ startFrom: Date;
164
+ startThrough: Date;
165
+ typeOf: factory.actionType;
166
+ }): Promise<IAggregateAction>;
167
+ private agggregateByStatus;
110
168
  }
@@ -677,5 +677,192 @@ class MongoRepository {
677
677
  .exec();
678
678
  });
679
679
  }
680
+ aggregateAuthorizeEventServiceOfferAction(params) {
681
+ return __awaiter(this, void 0, void 0, function* () {
682
+ const statuses = yield Promise.all([
683
+ factory.actionStatusType.CompletedActionStatus,
684
+ factory.actionStatusType.CanceledActionStatus,
685
+ factory.actionStatusType.FailedActionStatus
686
+ ].map((actionStatus) => __awaiter(this, void 0, void 0, function* () {
687
+ var _a, _b;
688
+ const matchConditions = Object.assign({ startDate: {
689
+ $gte: params.startFrom,
690
+ $lte: params.startThrough
691
+ }, typeOf: { $eq: params.typeOf }, actionStatus: { $eq: actionStatus }, 'object.typeOf': {
692
+ $exists: true,
693
+ $eq: factory.action.authorize.offer.seatReservation.ObjectType.SeatReservation
694
+ } }, (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$ne) === 'string')
695
+ ? { 'project.id': { $ne: params.project.id.$ne } }
696
+ : undefined);
697
+ return this.agggregateByStatus({ matchConditions, actionStatus });
698
+ })));
699
+ return { statuses };
700
+ });
701
+ }
702
+ aggregateAuthorizePaymentAction(params) {
703
+ return __awaiter(this, void 0, void 0, function* () {
704
+ const statuses = yield Promise.all([
705
+ factory.actionStatusType.CompletedActionStatus,
706
+ factory.actionStatusType.CanceledActionStatus,
707
+ factory.actionStatusType.FailedActionStatus
708
+ ].map((actionStatus) => __awaiter(this, void 0, void 0, function* () {
709
+ var _a, _b;
710
+ const matchConditions = Object.assign({ startDate: {
711
+ $gte: params.startFrom,
712
+ $lte: params.startThrough
713
+ }, typeOf: { $eq: params.typeOf }, actionStatus: { $eq: actionStatus }, 'object.typeOf': {
714
+ $exists: true,
715
+ $eq: factory.action.authorize.paymentMethod.any.ResultType.Payment
716
+ } }, (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$ne) === 'string')
717
+ ? { 'project.id': { $ne: params.project.id.$ne } }
718
+ : undefined);
719
+ return this.agggregateByStatus({ matchConditions, actionStatus });
720
+ })));
721
+ return { statuses };
722
+ });
723
+ }
724
+ aggregateAuthorizeOrderAction(params) {
725
+ return __awaiter(this, void 0, void 0, function* () {
726
+ const statuses = yield Promise.all([
727
+ factory.actionStatusType.CompletedActionStatus,
728
+ factory.actionStatusType.CanceledActionStatus,
729
+ factory.actionStatusType.FailedActionStatus
730
+ ].map((actionStatus) => __awaiter(this, void 0, void 0, function* () {
731
+ var _a, _b;
732
+ const matchConditions = Object.assign({ startDate: {
733
+ $gte: params.startFrom,
734
+ $lte: params.startThrough
735
+ }, typeOf: { $eq: params.typeOf }, actionStatus: { $eq: actionStatus }, 'object.typeOf': {
736
+ $exists: true,
737
+ $eq: factory.order.OrderType.Order
738
+ } }, (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$ne) === 'string')
739
+ ? { 'project.id': { $ne: params.project.id.$ne } }
740
+ : undefined);
741
+ return this.agggregateByStatus({ matchConditions, actionStatus });
742
+ })));
743
+ return { statuses };
744
+ });
745
+ }
746
+ aggregateUseAction(params) {
747
+ return __awaiter(this, void 0, void 0, function* () {
748
+ const statuses = yield Promise.all([
749
+ factory.actionStatusType.CompletedActionStatus,
750
+ factory.actionStatusType.CanceledActionStatus,
751
+ factory.actionStatusType.FailedActionStatus
752
+ ].map((actionStatus) => __awaiter(this, void 0, void 0, function* () {
753
+ var _a, _b;
754
+ const matchConditions = Object.assign({ startDate: {
755
+ $gte: params.startFrom,
756
+ $lte: params.startThrough
757
+ }, typeOf: { $eq: params.typeOf }, actionStatus: { $eq: actionStatus } }, (typeof ((_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$ne) === 'string')
758
+ ? { 'project.id': { $ne: params.project.id.$ne } }
759
+ : undefined);
760
+ return this.agggregateByStatus({ matchConditions, actionStatus });
761
+ })));
762
+ return { statuses };
763
+ });
764
+ }
765
+ // tslint:disable-next-line:max-func-body-length
766
+ agggregateByStatus(params) {
767
+ return __awaiter(this, void 0, void 0, function* () {
768
+ const aggregations = yield this.actionModel.aggregate([
769
+ { $match: params.matchConditions },
770
+ {
771
+ $project: {
772
+ duration: { $subtract: ['$endDate', '$startDate'] },
773
+ actionStatus: '$actionStatus',
774
+ startDate: '$startDate',
775
+ endDate: '$endDate',
776
+ typeOf: '$typeOf'
777
+ }
778
+ },
779
+ {
780
+ $group: {
781
+ _id: '$typeOf',
782
+ actionCount: { $sum: 1 },
783
+ maxDuration: { $max: '$duration' },
784
+ minDuration: { $min: '$duration' },
785
+ avgDuration: { $avg: '$duration' }
786
+ }
787
+ },
788
+ {
789
+ $project: {
790
+ _id: 0,
791
+ actionCount: '$actionCount',
792
+ avgDuration: '$avgDuration',
793
+ maxDuration: '$maxDuration',
794
+ minDuration: '$minDuration'
795
+ }
796
+ }
797
+ ])
798
+ .exec();
799
+ // tslint:disable-next-line:no-magic-numbers
800
+ const percents = [50, 95, 99];
801
+ if (aggregations.length === 0) {
802
+ return {
803
+ status: params.actionStatus,
804
+ aggregation: {
805
+ actionCount: 0,
806
+ avgDuration: 0,
807
+ maxDuration: 0,
808
+ minDuration: 0,
809
+ percentilesDuration: percents.map((percent) => {
810
+ return {
811
+ name: String(percent),
812
+ value: 0
813
+ };
814
+ })
815
+ }
816
+ };
817
+ }
818
+ const ranks4percentile = percents.map((percentile) => {
819
+ return {
820
+ percentile,
821
+ // tslint:disable-next-line:no-magic-numbers
822
+ rank: Math.floor(aggregations[0].actionCount * percentile / 100)
823
+ };
824
+ });
825
+ const aggregations2 = yield this.actionModel.aggregate([
826
+ {
827
+ $match: params.matchConditions
828
+ },
829
+ {
830
+ $project: {
831
+ duration: { $subtract: ['$endDate', '$startDate'] },
832
+ actionStatus: '$actionStatus',
833
+ startDate: '$startDate',
834
+ endDate: '$endDate',
835
+ typeOf: '$typeOf'
836
+ }
837
+ },
838
+ { $sort: { duration: 1 } },
839
+ {
840
+ $group: {
841
+ _id: '$typeOf',
842
+ durations: { $push: '$duration' }
843
+ }
844
+ },
845
+ {
846
+ $project: {
847
+ _id: 0,
848
+ avgSmallDuration: '$avgSmallDuration',
849
+ avgMediumDuration: '$avgMediumDuration',
850
+ avgLargeDuration: '$avgLargeDuration',
851
+ percentilesDuration: ranks4percentile.map((rank) => {
852
+ return {
853
+ name: String(rank.percentile),
854
+ value: { $arrayElemAt: ['$durations', rank.rank] }
855
+ };
856
+ })
857
+ }
858
+ }
859
+ ])
860
+ .exec();
861
+ return {
862
+ status: params.actionStatus,
863
+ aggregation: Object.assign(Object.assign({}, aggregations[0]), aggregations2[0])
864
+ };
865
+ });
866
+ }
680
867
  }
681
868
  exports.MongoRepository = MongoRepository;
@@ -0,0 +1,34 @@
1
+ import { Connection, Model } from 'mongoose';
2
+ import * as factory from '../factory';
3
+ export declare enum AggregationType {
4
+ AggregatePlaceOrder = "AggregatePlaceOrder",
5
+ AggregateAuthorizeEventServiceOfferAction = "AggregateAuthorizeEventServiceOfferAction",
6
+ AggregateAuthorizeOrderAction = "AggregateAuthorizeOrderAction",
7
+ AggregateAuthorizePaymentAction = "AggregateAuthorizePaymentAction",
8
+ AggregateOrder = "AggregateOrder",
9
+ AggregateReservation = "AggregateReservation",
10
+ AggregateUseAction = "AggregateUseAction"
11
+ }
12
+ export interface IAggregationByClient {
13
+ clientId: string;
14
+ aggregation: any;
15
+ }
16
+ export interface IAggregation {
17
+ typeOf: AggregationType;
18
+ project: {
19
+ id: string;
20
+ typeOf: factory.organizationType.Project;
21
+ };
22
+ aggregateDate: Date;
23
+ aggregateDuration: string;
24
+ aggregateStart: Date;
25
+ aggregationByClient?: IAggregationByClient[];
26
+ }
27
+ /**
28
+ * 集計リポジトリ
29
+ */
30
+ export declare class MongoRepository {
31
+ readonly aggregationModel: typeof Model;
32
+ constructor(connection: Connection);
33
+ saveAggregation(params: IAggregation): Promise<any>;
34
+ }
@@ -0,0 +1,64 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.MongoRepository = exports.AggregationType = void 0;
24
+ const aggregation_1 = require("./mongoose/model/aggregation");
25
+ var AggregationType;
26
+ (function (AggregationType) {
27
+ AggregationType["AggregatePlaceOrder"] = "AggregatePlaceOrder";
28
+ AggregationType["AggregateAuthorizeEventServiceOfferAction"] = "AggregateAuthorizeEventServiceOfferAction";
29
+ AggregationType["AggregateAuthorizeOrderAction"] = "AggregateAuthorizeOrderAction";
30
+ AggregationType["AggregateAuthorizePaymentAction"] = "AggregateAuthorizePaymentAction";
31
+ AggregationType["AggregateOrder"] = "AggregateOrder";
32
+ AggregationType["AggregateReservation"] = "AggregateReservation";
33
+ AggregationType["AggregateUseAction"] = "AggregateUseAction";
34
+ })(AggregationType = exports.AggregationType || (exports.AggregationType = {}));
35
+ /**
36
+ * 集計リポジトリ
37
+ */
38
+ class MongoRepository {
39
+ constructor(connection) {
40
+ this.aggregationModel = connection.model(aggregation_1.modelName);
41
+ }
42
+ saveAggregation(params) {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ const { typeOf, project, aggregateDuration, aggregateStart } = params, setFields = __rest(params, ["typeOf", "project", "aggregateDuration", "aggregateStart"]);
45
+ const doc = yield this.aggregationModel.findOneAndUpdate({
46
+ typeOf: { $eq: params.typeOf },
47
+ 'project.id': { $eq: params.project.id },
48
+ aggregateStart: { $eq: params.aggregateStart },
49
+ aggregateDuration: { $eq: params.aggregateDuration }
50
+ }, {
51
+ $setOnInsert: {
52
+ typeOf: params.typeOf,
53
+ project: params.project,
54
+ aggregateDuration: params.aggregateDuration,
55
+ aggregateStart: params.aggregateStart
56
+ },
57
+ $set: setFields
58
+ }, { upsert: true, new: true })
59
+ .exec();
60
+ return doc.toObject();
61
+ });
62
+ }
63
+ }
64
+ exports.MongoRepository = MongoRepository;