@chevre/domain 22.10.0-alpha.9 → 22.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/example/src/chevre/adminIdentities.ts +8 -8
  2. package/example/src/chevre/assetTransaction/processReserve.ts +4 -1
  3. package/example/src/chevre/concurrentLock/lockOfferRateLimit.ts +64 -0
  4. package/example/src/chevre/concurrentLock/lockTransactionProcess.ts +44 -0
  5. package/example/src/chevre/createTaskIfNotExistByAlternateName.ts +1 -1
  6. package/example/src/chevre/findOneAvailableHours.ts +11 -11
  7. package/example/src/chevre/identity/getCommonClients.ts +126 -0
  8. package/example/src/chevre/identity/migrateClients2oauth.ts +200 -0
  9. package/example/src/chevre/issuer/adminMemberProgramTiers.ts +55 -0
  10. package/example/src/chevre/maintenance/checkTransactionStatuses.ts +105 -0
  11. package/example/src/chevre/migrateIdentities.ts +24 -37
  12. package/example/src/chevre/reIndex.ts +1 -1
  13. package/example/src/chevre/roles/addPermissionIfNotExists.ts +27 -0
  14. package/example/src/chevre/roles/addRoleMembers.ts +75 -0
  15. package/example/src/chevre/saveWebSite.ts +14 -17
  16. package/example/src/chevre/stockHolder/checkRedisKeyCount.ts +43 -22
  17. package/example/src/chevre/transactionNumber/publishConfimationNumber.ts +37 -0
  18. package/example/src/chevre/transactionNumber/publishOrderNumber.ts +40 -0
  19. package/example/src/chevre/transactionNumber/setUseMongo4confirmationNumberFrom.ts +45 -0
  20. package/example/src/chevre/transactionNumber/setUseMongo4orderNumberFrom.ts +41 -0
  21. package/example/src/chevre/transactionNumber/setUseMongo4transactionNumberFrom.ts +41 -0
  22. package/example/src/redisMulti.ts +63 -0
  23. package/example/src/signPayload.ts +1 -1
  24. package/lib/chevre/eventEmitter/task.d.ts +36 -6
  25. package/lib/chevre/eventEmitter/task.js +5 -4
  26. package/lib/chevre/eventEmitter.d.ts +2 -2
  27. package/lib/chevre/eventEmitter.js +2 -2
  28. package/lib/chevre/repo/concurrentLock.d.ts +14 -0
  29. package/lib/chevre/repo/concurrentLock.js +48 -0
  30. package/lib/chevre/repo/concurrentLockAbstract.d.ts +42 -0
  31. package/lib/chevre/repo/concurrentLockAbstract.js +9 -0
  32. package/lib/chevre/repo/confirmationNumber.d.ts +17 -4
  33. package/lib/chevre/repo/confirmationNumber.js +89 -32
  34. package/lib/chevre/repo/identity.d.ts +42 -5
  35. package/lib/chevre/repo/identity.js +35 -4
  36. package/lib/chevre/repo/issuer.d.ts +10 -2
  37. package/lib/chevre/repo/member.js +2 -2
  38. package/lib/chevre/repo/memberProgram.d.ts +43 -2
  39. package/lib/chevre/repo/memberProgram.js +79 -8
  40. package/lib/chevre/repo/mongoose/schemas/issuer.d.ts +3 -1
  41. package/lib/chevre/repo/mongoose/schemas/issuer.js +10 -0
  42. package/lib/chevre/repo/mongoose/schemas/offer/event.js +30 -2
  43. package/lib/chevre/repo/mongoose/schemas/role.d.ts +2 -3
  44. package/lib/chevre/repo/mongoose/schemas/role.js +11 -1
  45. package/lib/chevre/repo/mongoose/schemas/setting.d.ts +3 -0
  46. package/lib/chevre/repo/mongoose/schemas/setting.js +4 -1
  47. package/lib/chevre/repo/mongoose/schemas/transactionNumber.d.ts +39 -0
  48. package/lib/chevre/repo/mongoose/schemas/transactionNumber.js +101 -0
  49. package/lib/chevre/repo/orderNumber.d.ts +15 -4
  50. package/lib/chevre/repo/orderNumber.js +71 -24
  51. package/lib/chevre/repo/passport.d.ts +1 -1
  52. package/lib/chevre/repo/passport.js +31 -13
  53. package/lib/chevre/repo/rateLimit/offer.d.ts +7 -2
  54. package/lib/chevre/repo/rateLimit/offer.js +41 -40
  55. package/lib/chevre/repo/role.d.ts +18 -4
  56. package/lib/chevre/repo/role.js +53 -4
  57. package/lib/chevre/repo/serviceOutputIdentifier.d.ts +8 -4
  58. package/lib/chevre/repo/serviceOutputIdentifier.js +54 -22
  59. package/lib/chevre/repo/stockHolder.d.ts +0 -2
  60. package/lib/chevre/repo/stockHolder.js +24 -31
  61. package/lib/chevre/repo/task.d.ts +10 -25
  62. package/lib/chevre/repo/task.js +65 -36
  63. package/lib/chevre/repo/transactionNumber.d.ts +15 -4
  64. package/lib/chevre/repo/transactionNumber.js +67 -22
  65. package/lib/chevre/repo/transactionNumberCounter.d.ts +28 -0
  66. package/lib/chevre/repo/transactionNumberCounter.js +128 -0
  67. package/lib/chevre/repo/transactionProcess.d.ts +7 -4
  68. package/lib/chevre/repo/transactionProcess.js +34 -13
  69. package/lib/chevre/service/aggregation/event/aggregateOffers.js +1 -0
  70. package/lib/chevre/service/assetTransaction/reserve/start.js +9 -1
  71. package/lib/chevre/service/assetTransaction/reserve/validateStartRequest.js +1 -1
  72. package/lib/chevre/service/code.js +1 -1
  73. package/lib/chevre/service/offer/event/checkAvailability.d.ts +1 -1
  74. package/lib/chevre/service/offer/event/checkAvailability.js +1 -0
  75. package/lib/chevre/service/offer/product.js +0 -40
  76. package/lib/chevre/service/payment/any.d.ts +0 -2
  77. package/lib/chevre/service/payment/any.js +1 -0
  78. package/lib/chevre/service/reserve/cancelReservation.d.ts +3 -0
  79. package/lib/chevre/service/reserve/cancelReservation.js +5 -1
  80. package/lib/chevre/service/task/acceptCOAOffer.js +2 -2
  81. package/lib/chevre/service/task/authorizePayment.js +4 -4
  82. package/lib/chevre/service/task/givePointAward.js +1 -1
  83. package/lib/chevre/service/task/moneyTransfer.js +1 -1
  84. package/lib/chevre/service/task/publishPaymentUrl.js +2 -2
  85. package/lib/chevre/service/task/refund.js +1 -1
  86. package/lib/chevre/service/task/returnMoneyTransfer.js +1 -1
  87. package/lib/chevre/service/task/returnPayTransaction.js +1 -1
  88. package/lib/chevre/service/task/returnPointAward.js +1 -1
  89. package/lib/chevre/service/task/returnReserveTransaction.js +1 -1
  90. package/lib/chevre/service/task.d.ts +8 -17
  91. package/lib/chevre/service/task.js +14 -5
  92. package/lib/chevre/service/transaction/placeOrder/start/validateStartRequest.js +2 -2
  93. package/lib/chevre/service/transaction/returnOrder/preStart/factory.d.ts +20 -0
  94. package/lib/chevre/service/transaction/returnOrder/preStart/factory.js +2 -0
  95. package/lib/chevre/service/transaction/returnOrder/preStart/findApplicableReturnPolicy.d.ts +23 -0
  96. package/lib/chevre/service/transaction/returnOrder/preStart/findApplicableReturnPolicy.js +323 -0
  97. package/lib/chevre/service/transaction/returnOrder/preStart/getReturnPolicyByProject.d.ts +13 -0
  98. package/lib/chevre/service/transaction/returnOrder/preStart/getReturnPolicyByProject.js +132 -0
  99. package/lib/chevre/service/transaction/returnOrder/preStart.js +2 -391
  100. package/package.json +3 -3
  101. package/example/src/chevre/migrateMembers2identities.ts +0 -109
  102. package/example/src/chevre/publishConfimationNumber.ts +0 -27
@@ -12,45 +12,66 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.OrderNumberRepo = void 0;
13
13
  const cdigit = require("cdigit");
14
14
  const moment = require("moment-timezone");
15
- const util = require("util");
16
15
  // tslint:disable-next-line:no-require-imports no-var-requires
17
16
  const fpe = require('node-fpe');
18
- const factory = require("../factory");
17
+ const setting_1 = require("./mongoose/schemas/setting");
18
+ const transactionNumber_1 = require("./mongoose/schemas/transactionNumber");
19
+ const transactionNumberCounter_1 = require("./transactionNumberCounter");
19
20
  const ORDER_NUMBER_SEPARATOR = '-';
20
21
  /**
21
22
  * 注文番号リポジトリ
22
23
  */
23
24
  class OrderNumberRepo {
24
- constructor(redisClient) {
25
- this.redisClient = redisClient;
26
- }
27
- static createKey(params) {
28
- return util.format('%s:%s:%s', OrderNumberRepo.REDIS_KEY_PREFIX, params.projectPrefix, params.timestamp);
25
+ constructor(params) {
26
+ const { connection } = params;
27
+ this.settingModel = connection.model(setting_1.modelName, (0, setting_1.createSchema)());
28
+ this.counterRepo = new transactionNumberCounter_1.TransactionNumberCounterRepo(params);
29
29
  }
30
+ // private static createKey(params: {
31
+ // orderDate: Date;
32
+ // projectPrefix: string;
33
+ // timestamp: string;
34
+ // }): string {
35
+ // return util.format(
36
+ // '%s:%s:%s',
37
+ // OrderNumberRepo.REDIS_KEY_PREFIX,
38
+ // params.projectPrefix,
39
+ // params.timestamp
40
+ // );
41
+ // }
30
42
  /**
31
43
  * タイムスタンプから発行する
32
44
  */
33
45
  publishByTimestamp(params) {
34
46
  return __awaiter(this, void 0, void 0, function* () {
35
- const projectPrefix = params.project.alternateName
36
- .toUpperCase();
37
47
  const timestamp = moment(params.orderDate)
38
48
  .valueOf()
39
49
  .toString();
40
- const now = moment();
41
- const TTL = moment(params.orderDate)
42
- .add(1, 'minute') // ミリ秒でカウントしていくので、注文日時後1分で十分
43
- .diff(now, 'seconds');
44
- const key = OrderNumberRepo.createKey({ orderDate: params.orderDate, projectPrefix, timestamp });
45
- const [incrReply] = yield this.redisClient.multi()
46
- .incr(key)
47
- .expire(key, TTL)
48
- .exec();
49
- // tslint:disable-next-line:no-single-line-block-comment
50
- /* istanbul ignore if */
51
- if (typeof incrReply !== 'number') {
52
- // 基本的にありえないフロー
53
- throw new factory.errors.Internal('order number not incremented unexpectedly');
50
+ const projectPrefix = params.project.alternateName
51
+ .toUpperCase();
52
+ let dataFeedExpires;
53
+ const dataFeedIdentifier = `${projectPrefix}:${timestamp}`;
54
+ let incrReply;
55
+ const useMongoBySettings = yield this.useMongoBySettings(params);
56
+ if (useMongoBySettings) {
57
+ dataFeedExpires = moment(params.orderDate)
58
+ .add(1, 'minute') // ミリ秒でカウントしていくので、注文日時後1分で十分
59
+ .toDate();
60
+ incrReply = yield this.counterRepo.incrementByMongo({
61
+ identifier: dataFeedIdentifier,
62
+ includedInDataCatalog: { identifier: transactionNumber_1.DataCatalogIdentifier.orderNumber },
63
+ expires: dataFeedExpires
64
+ });
65
+ }
66
+ else {
67
+ dataFeedExpires = moment(params.orderDate)
68
+ .add(1, 'minute') // ミリ秒でカウントしていくので、注文日時後1分で十分
69
+ .toDate();
70
+ incrReply = yield this.counterRepo.incrementByRedis({
71
+ identifier: dataFeedIdentifier,
72
+ includedInDataCatalog: { identifier: transactionNumber_1.DataCatalogIdentifier.orderNumber },
73
+ expires: dataFeedExpires
74
+ });
54
75
  }
55
76
  let orderNumber = `${timestamp}${incrReply}`;
56
77
  // checkdigit
@@ -69,6 +90,32 @@ class OrderNumberRepo {
69
90
  return orderNumber;
70
91
  });
71
92
  }
93
+ /**
94
+ * DB移行時のみに使用目的の設定更新
95
+ */
96
+ setUseMongo4orderNumberFrom(params) {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ const { useMongo4orderNumberFrom } = params;
99
+ return this.settingModel.findOneAndUpdate({ 'project.id': { $eq: '*' } }, {
100
+ $set: { useMongo4orderNumberFrom }
101
+ }, { projection: { _id: 0, useMongo4orderNumberFrom: 1 } })
102
+ .lean()
103
+ .exec();
104
+ });
105
+ }
106
+ useMongoBySettings(params) {
107
+ return __awaiter(this, void 0, void 0, function* () {
108
+ const setting = yield this.settingModel.findOne({ 'project.id': { $eq: '*' } }, {
109
+ _id: 0,
110
+ useMongo4orderNumberFrom: 1
111
+ })
112
+ .lean()
113
+ .exec();
114
+ const useMongo4orderNumberFrom = setting === null || setting === void 0 ? void 0 : setting.useMongo4orderNumberFrom;
115
+ return useMongo4orderNumberFrom instanceof Date
116
+ && moment(params.orderDate)
117
+ .isSameOrAfter(moment(useMongo4orderNumberFrom));
118
+ });
119
+ }
72
120
  }
73
121
  exports.OrderNumberRepo = OrderNumberRepo;
74
- OrderNumberRepo.REDIS_KEY_PREFIX = 'orderNumber';
@@ -25,7 +25,7 @@ type IStartParams = (factory.transaction.placeOrder.IStartParamsWithoutDetail |
25
25
  * 取引許可証リポジトリ
26
26
  */
27
27
  export declare class PassportRepo {
28
- private readonly redisClient;
28
+ private readonly concurrentLockRepo;
29
29
  private readonly options;
30
30
  constructor(redisClient: RedisClientType, options: IOptions);
31
31
  static CREATE_VERIFIED_PASSPORT(params: string | jwt.JwtPayload | undefined): IVerifiedPassport;
@@ -14,13 +14,15 @@ const createDebug = require("debug");
14
14
  const jwt = require("jsonwebtoken");
15
15
  const moment = require("moment");
16
16
  const factory = require("../factory");
17
+ const concurrentLock_1 = require("./concurrentLock");
17
18
  const debug = createDebug('chevre-domain:repo:passport');
18
19
  /**
19
20
  * 取引許可証リポジトリ
20
21
  */
21
22
  class PassportRepo {
22
23
  constructor(redisClient, options) {
23
- this.redisClient = redisClient;
24
+ this.concurrentLockRepo = new concurrentLock_1.ConcurrentLockRepo({ redisClient });
25
+ // this.redisClient = redisClient;
24
26
  this.options = options;
25
27
  }
26
28
  static CREATE_VERIFIED_PASSPORT(params) {
@@ -63,21 +65,37 @@ class PassportRepo {
63
65
  const now = moment();
64
66
  const passportExpires = moment.unix(params.exp);
65
67
  const key = PassportRepo.CREATE_REDIS_KEY(params);
66
- const ttl = (passportExpires.isAfter(now))
67
- ? moment.unix(params.exp)
68
- .diff(moment(), 'seconds')
69
- : 1;
70
- const results = yield this.redisClient.multi()
71
- .setNX(key, '1')
72
- .expire(key, ttl)
73
- .exec();
74
- debug('locked,', params.issueUnit.identifier, now, passportExpires, ttl, results);
75
- if (Array.isArray(results) && (results[0] === 1 || results[0] === true)) {
76
- return;
68
+ const expires = (passportExpires.isAfter(now))
69
+ ? passportExpires.toDate()
70
+ : now.add(1, 'second')
71
+ .toDate();
72
+ // reimplement using concurrentLockRepo(2025-05-27~)
73
+ try {
74
+ yield this.concurrentLockRepo.lock({
75
+ project: { id: params.project.id, typeOf: factory.organizationType.Project },
76
+ about: { identifier: key, typeOf: 'Thing' },
77
+ expires,
78
+ audience: { identifier: '1', typeOf: 'Audience' }
79
+ });
80
+ debug('locked,', params.issueUnit.identifier, passportExpires);
77
81
  }
78
- else {
82
+ catch (error) {
79
83
  throw new factory.errors.AlreadyInUse('passport', [], 'passport already in use');
80
84
  }
85
+ // const ttl = (passportExpires.isAfter(now))
86
+ // ? moment.unix(params.exp)
87
+ // .diff(moment(), 'seconds')
88
+ // : 1;
89
+ // const results = await this.redisClient.multi()
90
+ // .setNX(key, '1')
91
+ // .expire(key, ttl)
92
+ // .exec();
93
+ // debug('locked,', params.issueUnit.identifier, now, passportExpires, ttl, results);
94
+ // if (Array.isArray(results) && (results[0] === 1 || (<any>results)[0] === true)) {
95
+ // return;
96
+ // } else {
97
+ // throw new factory.errors.AlreadyInUse('passport', [], 'passport already in use');
98
+ // }
81
99
  });
82
100
  }
83
101
  /**
@@ -4,6 +4,9 @@ import * as factory from '../../factory';
4
4
  * レート制限キーインターフェース
5
5
  */
6
6
  export interface IRateLimitKey {
7
+ project: {
8
+ id: string;
9
+ };
7
10
  reservedTicket: {
8
11
  ticketType: {
9
12
  validRateLimit: factory.offer.IValidRateLimit;
@@ -19,13 +22,15 @@ export interface IRateLimitKey {
19
22
  */
20
23
  export declare class OfferRateLimitRepo {
21
24
  private static readonly KEY_PREFIX_NEW;
25
+ private readonly concurrentLockRepo;
22
26
  private readonly redisClient;
23
27
  constructor(redisClient: RedisClientType);
24
28
  private static createKey;
25
29
  /**
26
30
  * ロックする
31
+ * discontinue array params(2025-05-26~)
27
32
  */
28
- lock(ratelimitKeys: IRateLimitKey[]): Promise<void>;
29
- unlock(ratelimitKeys: IRateLimitKey[]): Promise<void>;
33
+ lock(params: IRateLimitKey): Promise<void>;
34
+ unlock(params: IRateLimitKey): Promise<void>;
30
35
  getHolder(ratelimitKey: IRateLimitKey): Promise<string | null>;
31
36
  }
@@ -12,11 +12,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.OfferRateLimitRepo = void 0;
13
13
  const moment = require("moment");
14
14
  const factory = require("../../factory");
15
+ const concurrentLock_1 = require("../concurrentLock");
15
16
  /**
16
17
  * オファーレート制限リポジトリ
17
18
  */
18
19
  class OfferRateLimitRepo {
19
20
  constructor(redisClient) {
21
+ this.concurrentLockRepo = new concurrentLock_1.ConcurrentLockRepo({ redisClient });
20
22
  this.redisClient = redisClient;
21
23
  }
22
24
  static createKey(ratelimitKey) {
@@ -28,54 +30,53 @@ class OfferRateLimitRepo {
28
30
  }
29
31
  /**
30
32
  * ロックする
33
+ * discontinue array params(2025-05-26~)
31
34
  */
32
- lock(ratelimitKeys) {
35
+ // public async lock(ratelimitKeys: IRateLimitKey[]): Promise<void> {
36
+ lock(params) {
33
37
  return __awaiter(this, void 0, void 0, function* () {
34
- const datasets = ratelimitKeys.map((ratelimitKey) => {
35
- return {
36
- key: OfferRateLimitRepo.createKey(ratelimitKey),
37
- value: ratelimitKey.reservationNumber,
38
- ttl: moment(ratelimitKey.reservationFor.startDate)
39
- .add(ratelimitKey.reservedTicket.ticketType.validRateLimit.unitInSeconds, 'seconds')
40
- .diff(moment(), 'seconds')
41
- };
42
- });
43
- let multi = this.redisClient.multi();
44
- datasets.forEach((dataset) => {
45
- multi.setNX(dataset.key, dataset.value)
46
- .expire(dataset.key, dataset.ttl);
47
- });
48
- const results = yield multi.exec();
49
- const lockedFields = [];
50
- results.forEach((r, index) => {
51
- // tslint:disable-next-line:no-magic-numbers
52
- if (index % 2 === 0 && (r === 1 || r === true)) {
53
- // tslint:disable-next-line:no-magic-numbers
54
- lockedFields.push(datasets[index / 2].key);
55
- }
56
- });
57
- const lockedAll = lockedFields.length === ratelimitKeys.length;
58
- if (!lockedAll) {
59
- if (lockedFields.length > 0) {
60
- // 全てロックできなければロックできたものは解除
61
- multi = this.redisClient.multi();
62
- lockedFields.forEach((key) => {
63
- multi.del(key);
64
- });
65
- yield multi.exec();
66
- }
38
+ const key = OfferRateLimitRepo.createKey(params);
39
+ const value = params.reservationNumber;
40
+ const ttl = moment(params.reservationFor.startDate)
41
+ .add(params.reservedTicket.ticketType.validRateLimit.unitInSeconds, 'seconds')
42
+ .diff(moment(), 'seconds');
43
+ const expires = moment()
44
+ .add(ttl, 'seconds')
45
+ .toDate();
46
+ // reimplement using concurrentLockRepo(2025-05-27~)
47
+ try {
48
+ yield this.concurrentLockRepo.lock({
49
+ project: { id: params.project.id, typeOf: factory.organizationType.Project },
50
+ about: { identifier: key, typeOf: 'Thing' },
51
+ expires,
52
+ audience: { identifier: value, typeOf: 'Audience' }
53
+ });
54
+ }
55
+ catch (error) {
67
56
  throw new factory.errors.RateLimitExceeded('Offer');
68
57
  }
58
+ // const multi = this.redisClient.multi();
59
+ // multi.setNX(key, value)
60
+ // .expire(key, ttl);
61
+ // const results = await multi.exec();
62
+ // if (Array.isArray(results) && (results[0] === 1 || (<any>results)[0] === true)) {
63
+ // return;
64
+ // } else {
65
+ // throw new factory.errors.RateLimitExceeded('Offer');
66
+ // }
69
67
  });
70
68
  }
71
- unlock(ratelimitKeys) {
69
+ // discontinue array params(2025-05-26~)
70
+ // public async unlock(ratelimitKeys: IRateLimitKey[]): Promise<void> {
71
+ unlock(params) {
72
72
  return __awaiter(this, void 0, void 0, function* () {
73
- const multi = this.redisClient.multi();
74
- ratelimitKeys.forEach((ratelimitKey) => {
75
- const key = OfferRateLimitRepo.createKey(ratelimitKey);
76
- multi.del(key);
73
+ const key = OfferRateLimitRepo.createKey(params);
74
+ // reimplement using concurrentLockRepo(2025-05-27~)
75
+ yield this.concurrentLockRepo.unlock({
76
+ about: { identifier: key, typeOf: 'Thing' },
77
+ audience: { identifier: params.reservationNumber, typeOf: 'Audience' }
77
78
  });
78
- yield multi.exec();
79
+ // await this.redisClient.del(key);
79
80
  });
80
81
  }
81
82
  getHolder(ratelimitKey) {
@@ -1,14 +1,16 @@
1
- import type { Connection } from 'mongoose';
1
+ import type { Connection, FilterQuery } from 'mongoose';
2
2
  import * as factory from '../factory';
3
- import { IRole } from './mongoose/schemas/role';
3
+ import { IDocType } from './mongoose/schemas/role';
4
+ type IRole = IDocType;
5
+ type IKeyOfProjection = keyof IDocType;
4
6
  /**
5
7
  * IAMロールリポジトリ
6
8
  */
7
9
  export declare class RoleRepo {
8
10
  private readonly roleModel;
9
11
  constructor(connection: Connection);
10
- static CREATE_MONGO_CONDITIONS(params: factory.iam.IRoleSearchConditions): any[];
11
- projectFields(params: factory.iam.IRoleSearchConditions): Promise<IRole[]>;
12
+ static CREATE_MONGO_CONDITIONS(params: factory.role.organizationRole.ISearchConditions): FilterQuery<IDocType>[];
13
+ projectFields(params: factory.role.organizationRole.ISearchConditions, inclusion: IKeyOfProjection[]): Promise<IRole[]>;
12
14
  aggregatePermissions(params: {
13
15
  roleName: {
14
16
  $in: string[];
@@ -16,4 +18,16 @@ export declare class RoleRepo {
16
18
  }): Promise<{
17
19
  _id: string;
18
20
  }[]>;
21
+ addPermissionIfNotExists(params: {
22
+ roleName: {
23
+ $eq: factory.role.organizationRole.RoleName;
24
+ };
25
+ permission: string;
26
+ }): Promise<(import("mongoose").FlattenMaps<IDocType> & {
27
+ _id: import("mongoose").Types.ObjectId;
28
+ }) | null>;
29
+ addMember(params: Pick<IRole, 'member' | 'memberOf' | 'roleName'>): Promise<(import("mongoose").FlattenMaps<IDocType> & {
30
+ _id: import("mongoose").Types.ObjectId;
31
+ }) | null>;
19
32
  }
33
+ export {};
@@ -15,7 +15,9 @@ const role_1 = require("./mongoose/schemas/role");
15
15
  const AVAILABLE_PROJECT_FIELDS = [
16
16
  'typeOf',
17
17
  'permissions',
18
- 'roleName'
18
+ 'roleName',
19
+ 'member',
20
+ 'memberOf'
19
21
  ];
20
22
  /**
21
23
  * IAMロールリポジトリ
@@ -25,7 +27,7 @@ class RoleRepo {
25
27
  this.roleModel = connection.model(role_1.modelName, (0, role_1.createSchema)());
26
28
  }
27
29
  static CREATE_MONGO_CONDITIONS(params) {
28
- var _a, _b, _c;
30
+ var _a, _b, _c, _d, _e, _f, _g;
29
31
  const andConditions = [];
30
32
  if (typeof ((_a = params.roleName) === null || _a === void 0 ? void 0 : _a.$eq) === 'string') {
31
33
  andConditions.push({ roleName: { $eq: params.roleName.$eq } });
@@ -38,12 +40,23 @@ class RoleRepo {
38
40
  if (typeof permissionsEq === 'string') {
39
41
  andConditions.push({ permissions: { $exists: true, $eq: permissionsEq } });
40
42
  }
43
+ const memberTypeOfEq = (_e = (_d = params.member) === null || _d === void 0 ? void 0 : _d.typeOf) === null || _e === void 0 ? void 0 : _e.$eq;
44
+ if (typeof memberTypeOfEq === 'string') {
45
+ andConditions.push({ 'member.typeOf': { $eq: memberTypeOfEq } });
46
+ }
47
+ const memberOfTypeOfEq = (_g = (_f = params.memberOf) === null || _f === void 0 ? void 0 : _f.typeOf) === null || _g === void 0 ? void 0 : _g.$eq;
48
+ if (typeof memberOfTypeOfEq === 'string') {
49
+ andConditions.push({ 'memberOf.typeOf': { $eq: memberOfTypeOfEq } });
50
+ }
41
51
  return andConditions;
42
52
  }
43
- projectFields(params) {
53
+ projectFields(params, inclusion) {
44
54
  return __awaiter(this, void 0, void 0, function* () {
45
55
  const conditions = RoleRepo.CREATE_MONGO_CONDITIONS(params);
46
- const positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
56
+ let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
57
+ if (Array.isArray(inclusion) && inclusion.length > 0) {
58
+ positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
59
+ }
47
60
  const projection = Object.assign({ _id: 0 }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
48
61
  const query = this.roleModel.find((conditions.length > 0) ? { $and: conditions } : {}, projection);
49
62
  if (typeof params.limit === 'number' && params.limit > 0) {
@@ -99,5 +112,41 @@ class RoleRepo {
99
112
  .exec();
100
113
  });
101
114
  }
115
+ addPermissionIfNotExists(params) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ return this.roleModel.findOneAndUpdate({
118
+ roleName: { $eq: params.roleName.$eq },
119
+ permissions: { $ne: params.permission }
120
+ }, {
121
+ $push: {
122
+ permissions: {
123
+ $each: [params.permission],
124
+ $sort: 1
125
+ }
126
+ }
127
+ }, {
128
+ new: true,
129
+ projection: { _id: 1 }
130
+ })
131
+ .lean()
132
+ .exec();
133
+ });
134
+ }
135
+ addMember(params) {
136
+ return __awaiter(this, void 0, void 0, function* () {
137
+ const { roleName, member, memberOf } = params;
138
+ return this.roleModel.findOneAndUpdate({
139
+ roleName: { $eq: roleName },
140
+ 'member.typeOf': { $ne: member.typeOf }
141
+ }, {
142
+ $set: { member, memberOf }
143
+ }, {
144
+ new: true,
145
+ projection: { _id: 1 }
146
+ })
147
+ .lean()
148
+ .exec();
149
+ });
150
+ }
102
151
  }
103
152
  exports.RoleRepo = RoleRepo;
@@ -1,16 +1,20 @@
1
+ import type { Connection } from 'mongoose';
1
2
  import { RedisClientType } from 'redis';
2
3
  /**
3
4
  * サービスアウトプット識別子リポジトリ
4
5
  */
5
6
  export declare class ServiceOutputIdentifierRepo {
6
- private static readonly REDIS_KEY_PREFIX;
7
- private readonly redisClient;
8
- constructor(redisClient: RedisClientType);
9
- private static createKey;
7
+ private readonly settingModel;
8
+ private readonly counterRepo;
9
+ constructor(params: {
10
+ redisClient: RedisClientType;
11
+ connection: Connection;
12
+ });
10
13
  /**
11
14
  * タイムスタンプから発行する
12
15
  */
13
16
  publishByTimestamp(params: {
14
17
  startDate: Date;
15
18
  }): Promise<string>;
19
+ private useMongoBySettings;
16
20
  }
@@ -12,20 +12,30 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ServiceOutputIdentifierRepo = void 0;
13
13
  const cdigit = require("cdigit");
14
14
  const moment = require("moment-timezone");
15
- const util = require("util");
16
15
  // tslint:disable-next-line:no-require-imports no-var-requires
17
16
  const fpe = require('node-fpe');
18
- const factory = require("../factory");
17
+ const setting_1 = require("./mongoose/schemas/setting");
18
+ const transactionNumber_1 = require("./mongoose/schemas/transactionNumber");
19
+ const transactionNumberCounter_1 = require("./transactionNumberCounter");
19
20
  /**
20
21
  * サービスアウトプット識別子リポジトリ
21
22
  */
22
23
  class ServiceOutputIdentifierRepo {
23
- constructor(redisClient) {
24
- this.redisClient = redisClient;
25
- }
26
- static createKey(params) {
27
- return util.format('%s:%s', ServiceOutputIdentifierRepo.REDIS_KEY_PREFIX, params.timestamp);
24
+ constructor(params) {
25
+ const { connection } = params;
26
+ this.settingModel = connection.model(setting_1.modelName, (0, setting_1.createSchema)());
27
+ this.counterRepo = new transactionNumberCounter_1.TransactionNumberCounterRepo(params);
28
28
  }
29
+ // private static createKey(params: {
30
+ // startDate: Date;
31
+ // timestamp: string;
32
+ // }): string {
33
+ // return util.format(
34
+ // '%s:%s',
35
+ // ServiceOutputIdentifierRepo.REDIS_KEY_PREFIX,
36
+ // params.timestamp
37
+ // );
38
+ // }
29
39
  /**
30
40
  * タイムスタンプから発行する
31
41
  */
@@ -34,20 +44,29 @@ class ServiceOutputIdentifierRepo {
34
44
  const timestamp = moment(params.startDate)
35
45
  .valueOf()
36
46
  .toString();
37
- const now = moment();
38
- const TTL = moment(params.startDate)
39
- .add(1, 'minute') // ミリ秒でカウントしていくので、予約日時後1分で十分
40
- .diff(now, 'seconds');
41
- const key = ServiceOutputIdentifierRepo.createKey({ startDate: params.startDate, timestamp });
42
- const [incrReply] = yield this.redisClient.multi()
43
- .incr(key)
44
- .expire(key, TTL)
45
- .exec();
46
- // tslint:disable-next-line:no-single-line-block-comment
47
- /* istanbul ignore else: please write tests */
48
- if (typeof incrReply !== 'number') {
49
- // 基本的にありえないフロー
50
- throw new factory.errors.Internal('serviceOutput identifier not incremented unexpectedly');
47
+ let dataFeedExpires;
48
+ const dataFeedIdentifier = timestamp;
49
+ let incrReply;
50
+ const useMongoBySettings = yield this.useMongoBySettings(params);
51
+ if (useMongoBySettings) {
52
+ dataFeedExpires = moment(params.startDate)
53
+ .add(1, 'minute') // ミリ秒でカウントしていくので、予約日時後1分で十分
54
+ .toDate();
55
+ incrReply = yield this.counterRepo.incrementByMongo({
56
+ identifier: dataFeedIdentifier,
57
+ includedInDataCatalog: { identifier: transactionNumber_1.DataCatalogIdentifier.serviceOutputIdentifier },
58
+ expires: dataFeedExpires
59
+ });
60
+ }
61
+ else {
62
+ dataFeedExpires = moment(params.startDate)
63
+ .add(1, 'minute') // ミリ秒でカウントしていくので、予約日時後1分で十分
64
+ .toDate();
65
+ incrReply = yield this.counterRepo.incrementByRedis({
66
+ identifier: dataFeedIdentifier,
67
+ includedInDataCatalog: { identifier: transactionNumber_1.DataCatalogIdentifier.serviceOutputIdentifier },
68
+ expires: dataFeedExpires
69
+ });
51
70
  }
52
71
  let identifier = `${timestamp}${incrReply}`;
53
72
  // checkdigit
@@ -58,6 +77,19 @@ class ServiceOutputIdentifierRepo {
58
77
  return identifier;
59
78
  });
60
79
  }
80
+ useMongoBySettings(params) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const setting = yield this.settingModel.findOne({ 'project.id': { $eq: '*' } }, {
83
+ _id: 0,
84
+ useMongo4transactionNumberFrom: 1
85
+ })
86
+ .lean()
87
+ .exec();
88
+ const useMongo4transactionNumberFrom = setting === null || setting === void 0 ? void 0 : setting.useMongo4transactionNumberFrom;
89
+ return useMongo4transactionNumberFrom instanceof Date
90
+ && moment(params.startDate)
91
+ .isSameOrAfter(moment(useMongo4transactionNumberFrom));
92
+ });
93
+ }
61
94
  }
62
95
  exports.ServiceOutputIdentifierRepo = ServiceOutputIdentifierRepo;
63
- ServiceOutputIdentifierRepo.REDIS_KEY_PREFIX = 'serviceOutputIdentifier';
@@ -8,7 +8,6 @@ export { ILockKey, IOffer, IUnlockKey };
8
8
  export declare class StockHolderRepo implements AbstractStockHolderRepo {
9
9
  static KEY_PREFIX_NEW: string;
10
10
  private readonly redisClient;
11
- private readonly settingModel;
12
11
  private readonly pendingReservationRepo;
13
12
  constructor(redisClient: RedisClientType, connection: Connection);
14
13
  private static offer2field;
@@ -75,5 +74,4 @@ export declare class StockHolderRepo implements AbstractStockHolderRepo {
75
74
  * 新リポジトリを使用するかどうか
76
75
  */
77
76
  private useMongoose;
78
- private useMongoAsStockHolderBySettings;
79
77
  }