@chevre/domain 22.11.0-alpha.1 → 22.11.0-alpha.11

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 (71) hide show
  1. package/example/src/chevre/assetTransaction/processReserve.ts +0 -1
  2. package/example/src/chevre/checkProjectMembers.ts +55 -0
  3. package/example/src/chevre/orders/searchWithUnwoundAcceptedOffers.ts +73 -0
  4. package/example/src/chevre/roles/addAdminPermissionIfNotExists.ts +132 -0
  5. package/example/src/chevre/roles/addDefaultPermissionIfNotExists.ts +37 -0
  6. package/example/src/chevre/roles/addEventOfferPermissionIfNotExists.ts +27 -0
  7. package/example/src/chevre/roles/addPermissionIfNotExists.ts +39 -6
  8. package/example/src/chevre/roles/addProjectCreatorRole.ts +48 -0
  9. package/example/src/chevre/roles/assignRoles.ts +71 -0
  10. package/example/src/chevre/roles/removeConsolePermissionIfExists.ts +38 -0
  11. package/example/src/chevre/roles/removePermissionFromAPIRoles.ts +46 -0
  12. package/example/src/chevre/roles/removePermissionIfExists.ts +39 -0
  13. package/example/src/chevre/settings/addSettings.ts +32 -0
  14. package/example/src/chevre/stockHolder/checkRedisKeyCount.ts +11 -20
  15. package/example/src/chevre/unsetUnnecessaryFields.ts +8 -5
  16. package/example/src/idaas/auth0/adminApplications.ts +183 -0
  17. package/example/src/idaas/auth0/getToken.ts +55 -0
  18. package/example/src/idaas/auth0/getTokenByPrivateKeyJWT.ts +84 -0
  19. package/lib/chevre/index.d.ts +0 -2
  20. package/lib/chevre/index.js +0 -10
  21. package/lib/chevre/repo/acceptedOffer.d.ts +3 -1
  22. package/lib/chevre/repo/acceptedOffer.js +11 -3
  23. package/lib/chevre/repo/confirmationNumber.d.ts +0 -11
  24. package/lib/chevre/repo/confirmationNumber.js +15 -54
  25. package/lib/chevre/repo/identity.d.ts +11 -33
  26. package/lib/chevre/repo/identity.js +10 -15
  27. package/lib/chevre/repo/member.d.ts +1 -0
  28. package/lib/chevre/repo/member.js +7 -2
  29. package/lib/chevre/repo/mongoose/schemas/identity.d.ts +1 -1
  30. package/lib/chevre/repo/orderNumber.d.ts +0 -11
  31. package/lib/chevre/repo/orderNumber.js +13 -51
  32. package/lib/chevre/repo/role.d.ts +11 -0
  33. package/lib/chevre/repo/role.js +36 -0
  34. package/lib/chevre/repo/serviceOutputIdentifier.d.ts +0 -4
  35. package/lib/chevre/repo/serviceOutputIdentifier.js +13 -38
  36. package/lib/chevre/repo/setting.d.ts +14 -1
  37. package/lib/chevre/repo/setting.js +15 -0
  38. package/lib/chevre/repo/stockHolder.js +0 -11
  39. package/lib/chevre/repo/transactionNumber.d.ts +0 -11
  40. package/lib/chevre/repo/transactionNumber.js +13 -51
  41. package/lib/chevre/repo/transactionNumberCounter.d.ts +0 -10
  42. package/lib/chevre/repo/transactionNumberCounter.js +34 -29
  43. package/lib/chevre/service/code.d.ts +5 -28
  44. package/lib/chevre/service/code.js +3 -79
  45. package/lib/chevre/service/order/onOrderStatusChanged/onOrderReturned/factory.js +22 -14
  46. package/lib/chevre/service/task/acceptCOAOffer.js +6 -5
  47. package/lib/chevre/service/task/authorizePayment.js +7 -6
  48. package/lib/chevre/service/task/checkMovieTicket.js +4 -3
  49. package/lib/chevre/service/task/givePointAward.js +1 -1
  50. package/lib/chevre/service/task/moneyTransfer.js +1 -1
  51. package/lib/chevre/service/task/publishPaymentUrl.js +6 -7
  52. package/lib/chevre/service/task/refund.js +1 -1
  53. package/lib/chevre/service/task/returnMoneyTransfer.js +1 -1
  54. package/lib/chevre/service/task/returnPayTransaction.js +1 -1
  55. package/lib/chevre/service/task/returnPointAward.js +1 -1
  56. package/lib/chevre/service/task/returnReserveTransaction.js +1 -1
  57. package/lib/chevre/service/task/voidReserveTransaction.js +4 -3
  58. package/lib/chevre/service/validation/validateOrder.js +55 -37
  59. package/lib/chevre/service.d.ts +0 -4
  60. package/lib/chevre/service.js +10 -14
  61. package/package.json +5 -3
  62. package/example/src/chevre/adminAuth/adminIdentity.ts +0 -38
  63. package/example/src/chevre/checkActions.ts +0 -65
  64. package/example/src/chevre/roles/addRoleMembers.ts +0 -75
  65. package/example/src/chevre/transactionNumber/publishConfimationNumber.ts +0 -37
  66. package/example/src/chevre/transactionNumber/publishOrderNumber.ts +0 -40
  67. package/example/src/chevre/transactionNumber/setUseMongo4confirmationNumberFrom.ts +0 -45
  68. package/example/src/chevre/transactionNumber/setUseMongo4orderNumberFrom.ts +0 -41
  69. package/example/src/chevre/transactionNumber/setUseMongo4transactionNumberFrom.ts +0 -41
  70. package/lib/chevre/adminAuth.d.ts +0 -2
  71. package/lib/chevre/adminAuth.js +0 -6
@@ -38,7 +38,6 @@ function countRedisKeyByProject(params: {
38
38
  {
39
39
  'project.id': {
40
40
  $eq: params.project.id
41
- // $in: useMongoAsStockHolderProjects
42
41
  },
43
42
  // startDate: {
44
43
  // $gte: params.now
@@ -93,30 +92,22 @@ function countRedisKeyByProject(params: {
93
92
  async function main() {
94
93
  const eventRepo = await chevre.repository.Event.createInstance(mongoose.connection);
95
94
  const projectRepo = await chevre.repository.Project.createInstance(mongoose.connection);
96
- const settingRepo = await chevre.repository.Setting.createInstance(mongoose.connection);
95
+ // const settingRepo = await chevre.repository.Setting.createInstance(mongoose.connection);
97
96
  const stockHolderRepo = await chevre.repository.StockHolder.createInstance(
98
97
  client,
99
98
  mongoose.connection
100
99
  );
101
100
 
102
- const setting = await settingRepo.findOne(
103
- { project: { id: { $eq: '*' } } },
104
- ['useMongoAsStockHolderProjects', 'useMongoAsStockHolder']
105
- );
106
- const useMongoAsStockHolder = setting?.useMongoAsStockHolder === true;
107
- let useMongoAsStockHolderProjects =
108
- (Array.isArray(setting?.useMongoAsStockHolderProjects)) ? setting?.useMongoAsStockHolderProjects : [];
109
- if (useMongoAsStockHolder) {
110
- // 全プロジェクト
111
- useMongoAsStockHolderProjects = (await projectRepo.projectFields(
112
- {
113
- // id: { $eq: 'xxx' }
114
- },
115
- ['id']
116
- )).map(({ id }) => id);
117
- }
101
+ let checkingProjects: string[] = [];
102
+ // 全プロジェクト
103
+ checkingProjects = (await projectRepo.projectFields(
104
+ {
105
+ // id: { $eq: 'xxx' }
106
+ },
107
+ ['id']
108
+ )).map(({ id }) => id);
118
109
 
119
- useMongoAsStockHolderProjects = useMongoAsStockHolderProjects.filter((id) => id.slice(0, 6) !== 'sskts-');
110
+ checkingProjects = checkingProjects.filter((id) => id.slice(0, 6) !== 'sskts-');
120
111
 
121
112
  const results: {
122
113
  project: { id: string };
@@ -127,7 +118,7 @@ async function main() {
127
118
  const now = moment()
128
119
  .add(0, 'days')
129
120
  .toDate();
130
- for (const projectId of useMongoAsStockHolderProjects) {
121
+ for (const projectId of checkingProjects) {
131
122
  const { checkedCount, redisKeyCount } = await countRedisKeyByProject({
132
123
  project: { id: projectId },
133
124
  now
@@ -9,17 +9,20 @@ import { chevre } from '../../../lib/index';
9
9
  async function main() {
10
10
  await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
11
11
 
12
- const aggregateOfferRepo = await chevre.repository.AggregateOffer.createInstance(mongoose.connection);
12
+ const settingRepo = await chevre.repository.Setting.createInstance(mongoose.connection);
13
13
 
14
14
  let updateResult: any;
15
15
 
16
- updateResult = await aggregateOfferRepo.unsetUnnecessaryFields({
16
+ updateResult = await settingRepo.unsetUnnecessaryFields({
17
17
  filter: {
18
- 'offers.includedInDataCatalog.id': { $exists: true }
19
- // _id: { $eq: 'blj55y1mo' }
18
+ 'project.id': { $eq: '*' }
20
19
  },
21
20
  $unset: {
22
- 'offers.0.includedInDataCatalog': 1
21
+ useMongoAsStockHolder: 1,
22
+ useMongoAsStockHolderProjects: 1
23
+ // useMongo4confirmationNumberFrom: 1,
24
+ // useMongo4orderNumberFrom: 1,
25
+ // useMongo4transactionNumberFrom: 1
23
26
  }
24
27
  });
25
28
  console.log(updateResult);
@@ -0,0 +1,183 @@
1
+ // tslint:disable:no-implicit-dependencies no-console no-magic-numbers
2
+ import { ManagementClient } from 'auth0';
3
+ import { readFileSync } from 'fs';
4
+ import * as moment from 'moment';
5
+ // import * as crypto from 'crypto'; // client_secret 生成用 (PKJWTなしの場合)
6
+ // import { JWK, importPKCS8, generateKeyPair, SignJWT } from 'jose'; // Private Key JWT 用
7
+
8
+ const PUBLIC_KEY_FILE_PATH = `${__dirname}/../../samplePublicKey.pem`;
9
+ const { AUTH0_DOMAIN, AUTH0_MGMT_CLIENT_ID, AUTH0_MGMT_CLIENT_SECRET, AUTH0_MGMT_API_AUDIENCE, AUTH0_AUDIENCE } = process.env;
10
+
11
+ if (typeof AUTH0_DOMAIN !== 'string'
12
+ || typeof AUTH0_MGMT_CLIENT_ID !== 'string'
13
+ || typeof AUTH0_MGMT_CLIENT_SECRET !== 'string'
14
+ || typeof AUTH0_MGMT_API_AUDIENCE !== 'string'
15
+ || typeof AUTH0_AUDIENCE !== 'string'
16
+ ) {
17
+ throw new Error('set envs!');
18
+ }
19
+
20
+ // --- Auth0 ManagementClient の初期化 ---
21
+ const management = new ManagementClient({
22
+ domain: AUTH0_DOMAIN,
23
+ clientId: AUTH0_MGMT_CLIENT_ID,
24
+ clientSecret: AUTH0_MGMT_CLIENT_SECRET,
25
+ audience: AUTH0_MGMT_API_AUDIENCE
26
+ // scope: 'read:clients create:clients' // 必要なスコープを明示
27
+ });
28
+
29
+ async function sleep(waitInSeconds: number) {
30
+ await new Promise<void>((resolve) => {
31
+ setTimeout(
32
+ () => {
33
+ resolve();
34
+ },
35
+ waitInSeconds
36
+ );
37
+ });
38
+ }
39
+
40
+ /**
41
+ * アプリケーションを検索し、存在しなければ作成します。
42
+ * Private Key JWT 認証を使用する前提。
43
+ */
44
+ async function findOrCreateServiceAccount(
45
+ appName: string,
46
+ projectId: string,
47
+ roles: string[],
48
+ audience: string
49
+ ) {
50
+ try {
51
+ console.log('getting organization...');
52
+ const getOrganizationResponse = await management.organizations.getByName({
53
+ name: projectId
54
+ });
55
+ const organization = getOrganizationResponse.data;
56
+ console.log('organization exists.', organization);
57
+
58
+ const newClient = (await management.clients.create({
59
+ name: appName,
60
+ app_type: 'non_interactive', // Machine to Machine アプリケーション
61
+ jwt_configuration: { // Private Key JWT の設定
62
+ alg: 'RS256' // 署名アルゴリズム
63
+ },
64
+ // token_endpoint_auth_method: 'client_secret_post',
65
+ client_authentication_methods: {
66
+ private_key_jwt: {
67
+ credentials: [{
68
+ alg: 'RS256',
69
+ /**
70
+ * Credential type. Supported types: public_key.
71
+ *
72
+ */
73
+ credential_type: 'public_key',
74
+ // name?: string;
75
+ pem: readFileSync(PUBLIC_KEY_FILE_PATH, 'utf8')
76
+
77
+ }]
78
+ }
79
+ },
80
+ grant_types: ['client_credentials'],
81
+ organization_usage: 'require', // 組織での利用を許可
82
+ default_organization: {
83
+ organization_id: organization.id,
84
+ flows: ['client_credentials']
85
+ },
86
+ oidc_conformant: true,
87
+ client_metadata: {
88
+ roles: JSON.stringify(roles)
89
+ }
90
+ })).data;
91
+ console.log(`Successfully created new application: ${newClient.client_id} (${newClient.name})`);
92
+
93
+ console.log(`checking clientGrant... ${newClient.client_id} (${newClient.name})`);
94
+ await sleep(3000);
95
+
96
+ let clientGrant = (await management.clientGrants.getAll({
97
+ audience,
98
+ client_id: newClient.client_id
99
+ })).data.shift();
100
+ if (clientGrant === undefined) {
101
+ clientGrant = (await management.clientGrants.create({
102
+ client_id: newClient.client_id,
103
+ audience,
104
+ organization_usage: 'require',
105
+ allow_any_organization: false,
106
+ scope: ['iam.members.me.read']
107
+ })).data;
108
+ console.log(`clientGrant created. ${newClient.client_id} (${newClient.name})`);
109
+ } else {
110
+ console.log(`clientGrant already exists. ${newClient.client_id} (${newClient.name})`);
111
+ }
112
+
113
+ console.log(`checking organizationClientGrant... ${newClient.client_id} (${newClient.name})`);
114
+ await sleep(3000);
115
+ const organizationClientGrant = (await management.organizations.getOrganizationClientGrants({
116
+ id: organization.id,
117
+ audience: 'https://development.apis.smart-theater.com',
118
+ client_id: newClient.client_id
119
+ })).data.shift();
120
+ if (organizationClientGrant === undefined) {
121
+ await management.organizations.postOrganizationClientGrants(
122
+ {
123
+ id: organization.id
124
+ },
125
+ {
126
+ grant_id: clientGrant.id
127
+ }
128
+ );
129
+ console.log(`organizationClientGrant created. ${newClient.client_id} (${newClient.name})`);
130
+ } else {
131
+ console.log(`organizationClientGrant already exists. ${newClient.client_id} (${newClient.name})`);
132
+ }
133
+
134
+ // 1. アプリケーションを検索 (名前で検索するのが一般的)
135
+ console.log('searching for applications...');
136
+ await sleep(3000);
137
+
138
+ await searchClients({ organization });
139
+ } catch (error) {
140
+ console.error(`Error finding or creating application: ${error.message}`);
141
+ throw error;
142
+ }
143
+ }
144
+
145
+ async function searchClients(params: {
146
+ organization: { id: string };
147
+ }) {
148
+ const existingApps = await management.clients.getAll({
149
+ include_totals: true,
150
+ // app_type: 'non_interactive',
151
+ // is_global: false,
152
+ // page: 0,
153
+ // per_page: 50,
154
+ // q: `name:"${appName}"`, // 名前で検索
155
+ q: `client_grant.organization_id:"${params.organization.id}"`,
156
+ // from: undefined,
157
+ take: 50
158
+ // is_client_credentials: true // Machine to Machine アプリケーションに絞る
159
+ });
160
+ const clients = existingApps.data.clients;
161
+ console.log(clients.length, 'existingApps exist.', clients);
162
+ console.log(clients.length, 'clients found.');
163
+ }
164
+
165
+ export async function run() {
166
+ if (typeof AUTH0_AUDIENCE !== 'string') {
167
+ throw new Error('set envs!');
168
+ }
169
+
170
+ try {
171
+ await findOrCreateServiceAccount(
172
+ `sampleServiceAccount-${moment()
173
+ .format('YYYY-MM-DDTHH:mm:ss')}`,
174
+ 'cinerino',
175
+ ['inventoryManager', 'user'],
176
+ AUTH0_AUDIENCE
177
+ );
178
+ } catch (error) {
179
+ console.error('Failed to run provisioning script:', error);
180
+ }
181
+ }
182
+
183
+ run();
@@ -0,0 +1,55 @@
1
+ // tslint:disable:no-implicit-dependencies no-console
2
+ interface IAuth0Config {
3
+ auth0Domain: string;
4
+ clientId: string;
5
+ clientSecret: string;
6
+ audience: string;
7
+ }
8
+
9
+ // 環境変数から機密情報を取得することを強く推奨します
10
+ const config: IAuth0Config = {
11
+ auth0Domain: String(process.env.AUTH0_DOMAIN),
12
+ clientId: String(process.env.AUTH0_CLIENT_ID),
13
+ clientSecret: String(process.env.AUTH0_CLIENT_SECRET),
14
+ audience: String(process.env.AUTH0_AUDIENCE)
15
+ // scopes: process.env.OKTA_SCOPES || 'api_access_scope openid', // 必要なスコープを指定
16
+ // authServerId: 'aussd9v86wlIar3cX697', // デフォルト承認サーバーを使用する場合はコメントアウトまたは指定しない
17
+ };
18
+
19
+ async function getToken() {
20
+ try {
21
+ const response = await fetch(
22
+ `https://${config.auth0Domain}/oauth/token`,
23
+ {
24
+ method: 'POST',
25
+ headers: { 'content-type': 'application/json' },
26
+ body: JSON.stringify({
27
+ client_id: config.clientId,
28
+ client_secret: config.clientSecret,
29
+ audience: config.audience,
30
+ grant_type: 'client_credentials'
31
+ // organization: 'org_zuMP9ng42QSgZ5Kn'
32
+ })
33
+ });
34
+
35
+ if (!response.ok) {
36
+ console.log(await response.json());
37
+ throw new Error('Network response was not ok');
38
+ }
39
+
40
+ const data = await response.json();
41
+ console.log(data);
42
+
43
+ return data;
44
+ } catch (error) {
45
+ console.error('Error fetching token:', error);
46
+ }
47
+ }
48
+
49
+ export async function main() {
50
+ const token = await getToken();
51
+ console.log(token);
52
+ }
53
+
54
+ main()
55
+ .catch(console.error);
@@ -0,0 +1,84 @@
1
+ // tslint:disable:no-implicit-dependencies no-console
2
+ import * as crypto from 'crypto';
3
+ import { readFileSync } from 'fs';
4
+ import { SignJWT } from 'jose';
5
+ import * as uuid from 'uuid';
6
+
7
+ const PRIVATE_KEY_FILE_PATH = `${__dirname}/../../samplePrivateKey.pem`;
8
+
9
+ interface IAuth0Config {
10
+ auth0Domain: string;
11
+ clientId: string;
12
+ privateKeyContent: string; // PEM形式の秘密鍵の内容 (例: fs.readFileSync('private_key.pem', 'utf8'))
13
+ audience: string;
14
+ }
15
+
16
+ // 環境変数から機密情報を取得することを強く推奨します
17
+ const auth0config: IAuth0Config = {
18
+ auth0Domain: String(process.env.AUTH0_DOMAIN),
19
+ clientId: String(process.env.AUTH0_CLIENT_ID),
20
+ // keyId: 'xxx',
21
+ privateKeyContent: readFileSync(PRIVATE_KEY_FILE_PATH, 'utf8'), // 秘密鍵の内容を読み込む
22
+ audience: String(process.env.AUTH0_AUDIENCE)
23
+ // scopes: process.env.OKTA_SCOPES || 'api_access_scope openid', // 必要なスコープを指定
24
+ // authServerId: 'aussd9v86wlIar3cX697', // デフォルト承認サーバーを使用する場合はコメントアウトまたは指定しない
25
+ };
26
+
27
+ async function generateJwtAssertion(config: IAuth0Config) {
28
+ const privateKeyPEM = crypto.createPrivateKey(readFileSync(PRIVATE_KEY_FILE_PATH, 'utf8'));
29
+
30
+ return new SignJWT({})
31
+ .setProtectedHeader({
32
+ alg: 'RS256' // or RS384 or PS256
33
+ // kid: '(OPTIONAL) KID_GENERATED_BY_AUTH0'
34
+ })
35
+ .setIssuedAt()
36
+ .setIssuer(config.clientId)
37
+ .setSubject(config.clientId)
38
+ .setAudience(`https://${config.auth0Domain}/`)
39
+ .setExpirationTime('1m')
40
+ .setJti(uuid.v4())
41
+ .sign(privateKeyPEM);
42
+ }
43
+
44
+ async function getToken() {
45
+ try {
46
+ const jwtAssertion = await generateJwtAssertion(auth0config);
47
+ console.log('jwtAssertion:', jwtAssertion);
48
+
49
+ const body = new URLSearchParams({
50
+ grant_type: 'client_credentials',
51
+ client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
52
+ client_assertion: jwtAssertion,
53
+ audience: auth0config.audience
54
+ // scope: config.scopes,
55
+ }).toString();
56
+ const response = await fetch(
57
+ `https://${auth0config.auth0Domain}/oauth/token`,
58
+ {
59
+ method: 'POST',
60
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
61
+ body: body
62
+ });
63
+
64
+ if (!response.ok) {
65
+ console.log(await response.json());
66
+ throw new Error('Network response was not ok');
67
+ }
68
+
69
+ const data = await response.json();
70
+ console.log(data);
71
+
72
+ return data;
73
+ } catch (error) {
74
+ console.error('Error fetching token:', error);
75
+ }
76
+ }
77
+
78
+ export async function main() {
79
+ const token = await getToken();
80
+ console.log(token);
81
+ }
82
+
83
+ main()
84
+ .catch(console.error);
@@ -3,7 +3,6 @@
3
3
  */
4
4
  import type * as COAService from '@motionpicture/coa-service';
5
5
  import type * as GMOService from '@motionpicture/gmo-service';
6
- import type * as AdminAuth from './adminAuth';
7
6
  import type * as Pecorinoapi from './pecorinoapi';
8
7
  import { credentials } from './credentials';
9
8
  import * as errorHandler from './errorHandler';
@@ -13,7 +12,6 @@ import * as repository from './repository';
13
12
  import * as service from './service';
14
13
  import * as settings from './settings';
15
14
  export { credentials, errorHandler, eventEmitter, factory, repository, service, settings };
16
- export declare function loadAdminAuth(): Promise<typeof AdminAuth>;
17
15
  export declare function loadPecorinoapi(): Promise<typeof Pecorinoapi>;
18
16
  export type COA = typeof COAService;
19
17
  export declare function loadCOA(): Promise<typeof COAService>;
@@ -10,7 +10,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.settings = exports.service = exports.repository = exports.factory = exports.eventEmitter = exports.errorHandler = exports.credentials = void 0;
13
- exports.loadAdminAuth = loadAdminAuth;
14
13
  exports.loadPecorinoapi = loadPecorinoapi;
15
14
  exports.loadCOA = loadCOA;
16
15
  exports.loadGMO = loadGMO;
@@ -28,15 +27,6 @@ const service = require("./service");
28
27
  exports.service = service;
29
28
  const settings = require("./settings");
30
29
  exports.settings = settings;
31
- let adminAuth;
32
- function loadAdminAuth() {
33
- return __awaiter(this, void 0, void 0, function* () {
34
- if (adminAuth === undefined) {
35
- adminAuth = yield Promise.resolve().then(() => require('./adminAuth'));
36
- }
37
- return adminAuth;
38
- });
39
- }
40
30
  let pecorinoapi;
41
31
  function loadPecorinoapi() {
42
32
  return __awaiter(this, void 0, void 0, function* () {
@@ -20,7 +20,9 @@ export declare class AcceptedOfferRepo {
20
20
  /**
21
21
  * オファー展開の注文検索
22
22
  */
23
- searchWithUnwoundAcceptedOffers(params: factory.order.ISearchConditions, projection?: IProjection4searchWithUnwoundAcceptedOffers): Promise<factory.order.IOrder[]>;
23
+ searchWithUnwoundAcceptedOffers(params: factory.order.ISearchConditions, projection: IProjection4searchWithUnwoundAcceptedOffers, options: {
24
+ useLimitAfterSkip: boolean;
25
+ }): Promise<factory.order.IOrder[]>;
24
26
  aggreateOwnershipInfosByOrder(filter: {
25
27
  orderNumber: {
26
28
  $eq: string;
@@ -24,9 +24,10 @@ class AcceptedOfferRepo {
24
24
  /**
25
25
  * オファー展開の注文検索
26
26
  */
27
- searchWithUnwoundAcceptedOffers(params, projection) {
27
+ searchWithUnwoundAcceptedOffers(params, projection, options) {
28
28
  return __awaiter(this, void 0, void 0, function* () {
29
29
  var _a;
30
+ const { useLimitAfterSkip } = options;
30
31
  const conditions = order_2.OrderRepo.CREATE_MONGO_CONDITIONS(params);
31
32
  const aggregate = this.orderModel.aggregate();
32
33
  // pipelineの順序に注意
@@ -43,8 +44,15 @@ class AcceptedOfferRepo {
43
44
  aggregate.project(Object.assign(Object.assign({}, projection), { acceptedOffers: ['$acceptedOffers'] }));
44
45
  if (typeof params.limit === 'number' && params.limit > 0) {
45
46
  const page = (typeof params.page === 'number' && params.page > 0) ? params.page : 1;
46
- aggregate.limit(params.limit * page)
47
- .skip(params.limit * (page - 1));
47
+ // support skip -> limit(2025-07-09~)
48
+ if (useLimitAfterSkip) {
49
+ aggregate.skip(params.limit * (page - 1))
50
+ .limit(params.limit);
51
+ }
52
+ else {
53
+ aggregate.limit(params.limit * page)
54
+ .skip(params.limit * (page - 1));
55
+ }
48
56
  }
49
57
  return aggregate
50
58
  // .allowDiskUse(true) // false化(2023-11-30~)
@@ -1,14 +1,10 @@
1
1
  import type { Connection } from 'mongoose';
2
- import { RedisClientType } from 'redis';
3
- import { ISetting } from './mongoose/schemas/setting';
4
2
  /**
5
3
  * 確認番号リポジトリ
6
4
  */
7
5
  export declare class ConfirmationNumberRepo {
8
- private readonly settingModel;
9
6
  private readonly counterRepo;
10
7
  constructor(params: {
11
- redisClient: RedisClientType;
12
8
  connection: Connection;
13
9
  });
14
10
  private static alignDigits;
@@ -20,11 +16,4 @@ export declare class ConfirmationNumberRepo {
20
16
  publish(params: {
21
17
  orderDate: Date;
22
18
  }): Promise<string>;
23
- /**
24
- * DB移行時のみに使用目的の設定更新
25
- */
26
- setUseMongo4confirmationNumberFrom(params: {
27
- useMongo4confirmationNumberFrom: Date;
28
- }): Promise<Pick<ISetting, "useMongo4confirmationNumberFrom"> | null>;
29
- private useMongoBySettings;
30
19
  }
@@ -12,9 +12,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ConfirmationNumberRepo = void 0;
13
13
  const cdigit = require("cdigit");
14
14
  const moment = require("moment-timezone");
15
+ // import { RedisClientType } from 'redis';
15
16
  // tslint:disable-next-line:no-require-imports no-var-requires
16
17
  const fpe = require('node-fpe');
17
- const setting_1 = require("./mongoose/schemas/setting");
18
+ // import { createSchema as createSettingSchema, modelName as settingModelName } from './mongoose/schemas/setting';
18
19
  const transactionNumber_1 = require("./mongoose/schemas/transactionNumber");
19
20
  const transactionNumberCounter_1 = require("./transactionNumberCounter");
20
21
  const CONFIRMATION_NUMBER_MIN_LENGH = 4;
@@ -24,8 +25,8 @@ const TIMEZONE = 'Asia/Tokyo';
24
25
  */
25
26
  class ConfirmationNumberRepo {
26
27
  constructor(params) {
27
- const { connection } = params;
28
- this.settingModel = connection.model(setting_1.modelName, (0, setting_1.createSchema)());
28
+ // const { connection } = params;
29
+ // this.settingModel = connection.model(settingModelName, createSettingSchema());
29
30
  this.counterRepo = new transactionNumberCounter_1.TransactionNumberCounterRepo(params);
30
31
  }
31
32
  static alignDigits(params) {
@@ -72,59 +73,19 @@ class ConfirmationNumberRepo {
72
73
  const dataFeedIdentifier = ConfirmationNumberRepo.createDataFeedIdentifier({ orderDate: params.orderDate });
73
74
  let incrReply;
74
75
  // support publishByMongo(2025-05-23~)
75
- const useMongoBySettings = yield this.useMongoBySettings(params);
76
- if (useMongoBySettings) {
77
- // データ保管期間はとりあえず2 months
78
- dataFeedExpires = moment(params.orderDate)
79
- // tslint:disable-next-line:no-magic-numbers
80
- .add(2, 'months')
81
- .toDate();
82
- incrReply = yield this.counterRepo.incrementByMongo({
83
- identifier: dataFeedIdentifier,
84
- includedInDataCatalog: { identifier: transactionNumber_1.DataCatalogIdentifier.confirmationNumber },
85
- expires: dataFeedExpires
86
- });
87
- }
88
- else {
89
- // データ保管期間はとりあえず一か月
90
- dataFeedExpires = moment(params.orderDate)
91
- .add(1, 'month')
92
- .toDate();
93
- incrReply = yield this.counterRepo.incrementByRedis({
94
- identifier: dataFeedIdentifier,
95
- includedInDataCatalog: { identifier: transactionNumber_1.DataCatalogIdentifier.confirmationNumber },
96
- expires: dataFeedExpires
97
- });
98
- }
76
+ // const useMongoBySettings = await this.useMongoBySettings(params);
77
+ // データ保管期間はとりあえず2 months
78
+ dataFeedExpires = moment(params.orderDate)
79
+ // tslint:disable-next-line:no-magic-numbers
80
+ .add(2, 'months')
81
+ .toDate();
82
+ incrReply = yield this.counterRepo.incrementByMongo({
83
+ identifier: dataFeedIdentifier,
84
+ includedInDataCatalog: { identifier: transactionNumber_1.DataCatalogIdentifier.confirmationNumber },
85
+ expires: dataFeedExpires
86
+ });
99
87
  return ConfirmationNumberRepo.count2confirmationNumber({ count: incrReply });
100
88
  });
101
89
  }
102
- /**
103
- * DB移行時のみに使用目的の設定更新
104
- */
105
- setUseMongo4confirmationNumberFrom(params) {
106
- return __awaiter(this, void 0, void 0, function* () {
107
- const { useMongo4confirmationNumberFrom } = params;
108
- return this.settingModel.findOneAndUpdate({ 'project.id': { $eq: '*' } }, {
109
- $set: { useMongo4confirmationNumberFrom }
110
- }, { projection: { _id: 0, useMongo4confirmationNumberFrom: 1 } })
111
- .lean()
112
- .exec();
113
- });
114
- }
115
- useMongoBySettings(params) {
116
- return __awaiter(this, void 0, void 0, function* () {
117
- const setting = yield this.settingModel.findOne({ 'project.id': { $eq: '*' } }, {
118
- _id: 0,
119
- useMongo4confirmationNumberFrom: 1
120
- })
121
- .lean()
122
- .exec();
123
- const useMongo4confirmationNumberFrom = setting === null || setting === void 0 ? void 0 : setting.useMongo4confirmationNumberFrom;
124
- return useMongo4confirmationNumberFrom instanceof Date
125
- && moment(params.orderDate)
126
- .isSameOrAfter(moment(useMongo4confirmationNumberFrom));
127
- });
128
- }
129
90
  }
130
91
  exports.ConfirmationNumberRepo = ConfirmationNumberRepo;