@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
@@ -4,14 +4,14 @@ import * as mongoose from 'mongoose';
4
4
  import { chevre } from '../../../lib/index';
5
5
 
6
6
  const project = { id: String(process.env.PROJECT_ID) };
7
- const IDENTIFIER = 'xxx';
7
+ const IDENTIFIER = 'sampleidentity20250528';
8
8
 
9
9
  async function main() {
10
10
  await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
11
11
 
12
12
  const identityRepo = await chevre.repository.Identity.createInstance(mongoose.connection);
13
13
 
14
- let docs = await identityRepo.projectFields(
14
+ let docs = await identityRepo.projectIdentityFields(
15
15
  {
16
16
  project: { id: { $eq: project.id } },
17
17
  about: { id: { $eq: IDENTIFIER } }
@@ -22,14 +22,14 @@ async function main() {
22
22
  console.log(docs.length, 'docs found');
23
23
 
24
24
  if (docs.length > 0) {
25
- await identityRepo.deleteById({
25
+ await identityRepo.deleteIdentityById({
26
26
  project: { id: docs[0].project.id },
27
27
  id: docs[0].id
28
28
  });
29
29
  console.log('deleted', docs[0].id);
30
30
  }
31
31
 
32
- await identityRepo.projectFields(
32
+ await identityRepo.projectIdentityFields(
33
33
  {
34
34
  project: { id: { $eq: project.id } },
35
35
  about: { id: { $eq: IDENTIFIER } }
@@ -39,7 +39,7 @@ async function main() {
39
39
  console.log('docs:', docs);
40
40
  console.log(docs.length, 'docs found');
41
41
 
42
- await identityRepo.save({
42
+ await identityRepo.saveIdentity({
43
43
  attributes: {
44
44
  project: { id: project.id, typeOf: chevre.factory.organizationType.Project },
45
45
  typeOf: chevre.factory.creativeWorkType.Certification,
@@ -47,15 +47,15 @@ async function main() {
47
47
  id: IDENTIFIER,
48
48
  typeOf: chevre.factory.creativeWorkType.WebApplication
49
49
  },
50
- issuedBy: {
50
+ issuedBy: [{
51
51
  identifier: 'https://example.com',
52
52
  typeOf: chevre.factory.organizationType.Organization
53
- }
53
+ }]
54
54
  }
55
55
  });
56
56
  console.log('created.');
57
57
 
58
- docs = await await identityRepo.projectFields(
58
+ docs = await await identityRepo.projectIdentityFields(
59
59
  {
60
60
  project: { id: { $eq: project.id } },
61
61
  about: { id: { $eq: IDENTIFIER } }
@@ -18,7 +18,10 @@ async function main() {
18
18
  await redisClient.connect();
19
19
  await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
20
20
 
21
- const transactionNumberRepo = await chevre.repository.TransactionNumber.createInstance(redisClient);
21
+ const transactionNumberRepo = await chevre.repository.TransactionNumber.createInstance({
22
+ redisClient,
23
+ connection: mongoose.connection
24
+ });
22
25
  const assetTransactionRepo = await chevre.repository.AssetTransaction.createInstance(mongoose.connection);
23
26
 
24
27
  const { transactionNumber } = await transactionNumberRepo.publishByTimestamp({ startDate: new Date() });
@@ -0,0 +1,64 @@
1
+ // tslint:disable:no-console
2
+ import * as redis from 'redis';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ const project = { id: String(process.env.PROJECT_ID) };
7
+
8
+ const client = redis.createClient<redis.RedisDefaultModules, Record<string, never>, Record<string, never>>({
9
+ socket: {
10
+ port: Number(<string>process.env.REDIS_PORT),
11
+ host: <string>process.env.REDIS_HOST
12
+ },
13
+ password: <string>process.env.REDIS_KEY
14
+ })
15
+ .on('error', (err) => {
16
+ // eslint-disable-next-line no-console
17
+ console.error('createDefaultRedisClient: client onError:', err);
18
+ // reject(err);
19
+ });
20
+ client.connect();
21
+
22
+ // tslint:disable-next-line:max-func-body-length
23
+ async function main() {
24
+ const rateLimitRepo = await chevre.repository.rateLimit.Offer.createInstance(
25
+ client
26
+ );
27
+
28
+ // await rateLimitRepo.unlock({
29
+ // project: { id: project.id },
30
+ // reservedTicket: {
31
+ // ticketType: {
32
+ // validRateLimit: {
33
+ // scope: 'scope2',
34
+ // unitInSeconds: 60
35
+ // }
36
+ // }
37
+ // },
38
+ // reservationFor: {
39
+ // startDate: new Date()
40
+ // },
41
+ // reservationNumber: 'xxx'
42
+ // });
43
+ // console.log('unlocked');
44
+ await rateLimitRepo.lock({
45
+ project: { id: project.id },
46
+ reservedTicket: {
47
+ ticketType: {
48
+ validRateLimit: {
49
+ scope: 'scope2',
50
+ unitInSeconds: 60
51
+ }
52
+ }
53
+ },
54
+ reservationFor: {
55
+ startDate: new Date()
56
+ },
57
+ reservationNumber: 'xxx'
58
+ });
59
+ console.log('locked');
60
+ }
61
+
62
+ main()
63
+ .then()
64
+ .catch(console.error);
@@ -0,0 +1,44 @@
1
+ // tslint:disable:no-console
2
+ import * as redis from 'redis';
3
+
4
+ import { chevre } from '../../../../lib/index';
5
+
6
+ const project = { id: String(process.env.PROJECT_ID) };
7
+
8
+ const client = redis.createClient<redis.RedisDefaultModules, Record<string, never>, Record<string, never>>({
9
+ socket: {
10
+ port: Number(<string>process.env.REDIS_PORT),
11
+ host: <string>process.env.REDIS_HOST
12
+ },
13
+ password: <string>process.env.REDIS_KEY
14
+ })
15
+ .on('error', (err) => {
16
+ // eslint-disable-next-line no-console
17
+ console.error('createDefaultRedisClient: client onError:', err);
18
+ // reject(err);
19
+ });
20
+ client.connect();
21
+
22
+ // tslint:disable-next-line:max-func-body-length
23
+ async function main() {
24
+ const processRepo = await chevre.repository.TransactionProcess.createInstance(
25
+ client,
26
+ { lockExpiresInSeconds: 60 }
27
+ );
28
+
29
+ // await processRepo.unlock({
30
+ // id: 'xxx',
31
+ // typeOf: chevre.factory.transactionType.PlaceOrder
32
+ // });
33
+ // console.log('unlocked');
34
+ await processRepo.lock({
35
+ id: 'xxx',
36
+ typeOf: chevre.factory.transactionType.PlaceOrder,
37
+ project: { id: project.id }
38
+ });
39
+ console.log('locked');
40
+ }
41
+
42
+ main()
43
+ .then()
44
+ .catch(console.error);
@@ -5,7 +5,7 @@ import { chevre } from '../../../lib/index';
5
5
 
6
6
  const project = { id: String(process.env.PROJECT_ID) };
7
7
 
8
- chevre.eventEmitter.task.onTaskStatusChanged((event) => {
8
+ chevre.eventEmitter.task.taskEventEmitter.onTaskStatusChanged((event) => {
9
9
  console.log('onTaskStatusChanged', event);
10
10
  });
11
11
 
@@ -17,17 +17,17 @@ async function main() {
17
17
  ['opens', 'typeOf']
18
18
  );
19
19
  console.log('setting:', setting);
20
- // const result = await availableHourRepo.saveOne(
21
- // {
22
- // // opens: '09:00:00',
23
- // validFrom: moment('2025-05-15T00:00:00Z')
24
- // .toDate(),
25
- // validThrough: moment('2025-05-15T01:00:00Z')
26
- // .toDate(),
27
- // typeOf: 'OpeningHoursSpecification'
28
- // }
29
- // );
30
- // console.log('saved', result);
20
+ const result = await availableHourRepo.saveOne(
21
+ {
22
+ // opens: '09:00:00',
23
+ validFrom: moment('2025-05-19T17:00:00Z')
24
+ .toDate(),
25
+ validThrough: moment('2025-05-19T20:00:00Z')
26
+ .toDate(),
27
+ typeOf: 'OpeningHoursSpecification'
28
+ }
29
+ );
30
+ console.log('saved', result);
31
31
  }
32
32
 
33
33
  main()
@@ -0,0 +1,126 @@
1
+ // tslint:disable:no-console
2
+ import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';
3
+ // tslint:disable-next-line:no-submodule-imports
4
+ import type { UserPoolClientType } from '@aws-sdk/client-cognito-identity-provider/dist-types/models/models_0';
5
+ import { fromEnv } from '@aws-sdk/credential-providers';
6
+ import * as fs from 'fs';
7
+ // tslint:disable-next-line:no-implicit-dependencies
8
+ import * as json2csv from 'json2csv';
9
+ import * as mongoose from 'mongoose';
10
+
11
+ import { chevre } from '../../../../lib/index';
12
+
13
+ // const project = { id: String(process.env.PROJECT_ID) };
14
+ // const excludedProject = { id: String(process.env.EXCLUDED_PROJECT_ID) };
15
+ const userPoolId = `${process.env.COGNITO_USER_POOL_ID}`;
16
+
17
+ // tslint:disable-next-line:max-func-body-length
18
+ async function main() {
19
+ const awsCredentials = fromEnv();
20
+ const cognitoIdentityServiceProvider = new CognitoIdentityProvider({
21
+ apiVersion: 'latest',
22
+ region: 'ap-northeast-1',
23
+ credentials: awsCredentials
24
+ });
25
+
26
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
27
+
28
+ const memberRepo = await chevre.repository.Member.createInstance(mongoose.connection);
29
+
30
+ const cursor = memberRepo.getCursor(
31
+ {
32
+ 'project.id': { $eq: '*' }
33
+ // _id: { $eq: '67de46777ec0510590b68922' }
34
+ },
35
+ {
36
+ _id: 1,
37
+ member: 1,
38
+ project: 1,
39
+ typeOf: 1
40
+ }
41
+ );
42
+ console.log('docs found');
43
+
44
+ let i = 0;
45
+ // let commonClients: {
46
+ // clientId?: string;
47
+ // clientSecret?: string;
48
+ // name?: string;
49
+ // }[] = [];
50
+ const commonClients: {
51
+ projectId: string;
52
+ clientId: string;
53
+ clientSecret: string;
54
+ name: string;
55
+ memberName: string;
56
+ }[] = [];
57
+ // tslint:disable-next-line:max-func-body-length
58
+ await cursor.eachAsync(async (doc) => {
59
+ i += 1;
60
+ const member: Pick<
61
+ chevre.factory.iam.IMember,
62
+ 'member' | 'project' | 'typeOf'
63
+ > = doc.toObject();
64
+
65
+ const client = await new Promise<UserPoolClientType>(async (resolve, reject) => {
66
+ cognitoIdentityServiceProvider.describeUserPoolClient(
67
+ {
68
+ ClientId: member.member.id,
69
+ UserPoolId: userPoolId
70
+ },
71
+ {},
72
+ (err, data) => {
73
+ if (err instanceof Error) {
74
+ reject(err);
75
+ } else {
76
+ if (data?.UserPoolClient === undefined) {
77
+ reject(new chevre.factory.errors.NotFound('UserPoolClient'));
78
+ } else {
79
+ resolve(data.UserPoolClient);
80
+ }
81
+ }
82
+ }
83
+ );
84
+ });
85
+
86
+ if (typeof client.ClientId !== 'string'
87
+ || typeof client.ClientSecret !== 'string'
88
+ || typeof client.ClientName !== 'string') {
89
+ throw new Error('invalid client');
90
+ }
91
+
92
+ const allowClientCredentials = client.AllowedOAuthFlows?.includes('client_credentials') === true;
93
+ if (allowClientCredentials) {
94
+ commonClients.push({
95
+ projectId: member.project.id,
96
+ clientId: client.ClientId,
97
+ clientSecret: client.ClientSecret,
98
+ name: client.ClientName,
99
+ memberName: String(member.member.name)
100
+ });
101
+ }
102
+ });
103
+
104
+ console.log(commonClients);
105
+
106
+ // tslint:disable-next-line:no-null-keyword
107
+ const json = JSON.stringify(commonClients, null, '');
108
+ // tslint:disable-next-line:non-literal-fs-path
109
+ fs.writeFileSync(`${__dirname}/../../../commonClients.json`, json);
110
+ console.log(i, 'docs checked');
111
+
112
+ const parser = new json2csv.Parser({
113
+ fields: ['projectId', 'clientId', 'clientSecret', 'name', 'memberName']
114
+ });
115
+ const csv = parser.parse(commonClients.sort(
116
+ (a, b) => {
117
+ return (String(a.name) > String(b.name)) ? 1 : -1;
118
+ }
119
+ ));
120
+ // tslint:disable-next-line:non-literal-fs-path
121
+ fs.writeFileSync(`${__dirname}/../../../commonClients.csv`, csv);
122
+ }
123
+
124
+ main()
125
+ .then()
126
+ .catch(console.error);
@@ -0,0 +1,200 @@
1
+ // tslint:disable:no-console
2
+ // tslint:disable:no-console
3
+ import { CognitoIdentityProvider } from '@aws-sdk/client-cognito-identity-provider';
4
+ // tslint:disable-next-line:no-submodule-imports
5
+ import type { UserPoolClientType } from '@aws-sdk/client-cognito-identity-provider/dist-types/models/models_0';
6
+ import { fromEnv } from '@aws-sdk/credential-providers';
7
+ import * as fs from 'fs';
8
+ // tslint:disable-next-line:no-implicit-dependencies
9
+ import * as json2csv from 'json2csv';
10
+ import * as mongoose from 'mongoose';
11
+
12
+ import { chevre } from '../../../../lib/index';
13
+
14
+ // const project = { id: String(process.env.PROJECT_ID) };
15
+ // const excludedProject = { id: String(process.env.EXCLUDED_PROJECT_ID) };
16
+ const userPoolId = `${process.env.COGNITO_USER_POOL_ID}`;
17
+ const oldProvider = `https://cognito-idp.ap-northeast-1.amazonaws.com/${userPoolId}`;
18
+ const NEW_ISS = process.env.NEW_ISS;
19
+
20
+ // tslint:disable-next-line:max-func-body-length
21
+ async function main() {
22
+ if (typeof NEW_ISS !== 'string') {
23
+ throw new Error('process.env.NEW_ISS undefined');
24
+ }
25
+
26
+ const awsCredentials = fromEnv();
27
+ const cognitoIdentityServiceProvider = new CognitoIdentityProvider({
28
+ apiVersion: 'latest',
29
+ region: 'ap-northeast-1',
30
+ credentials: awsCredentials
31
+ });
32
+
33
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
34
+
35
+ const identityRepo = await chevre.repository.Identity.createInstance(mongoose.connection);
36
+ const identityProviderRepo = await chevre.repository.IdentityProvider.createInstance(mongoose.connection);
37
+ const memberRepo = await chevre.repository.Member.createInstance(mongoose.connection);
38
+
39
+ const cursor = identityRepo.getCursor(
40
+ {
41
+ 'issuedBy.identifier': { $eq: oldProvider }
42
+ // _id: { $eq: '67de46777ec0510590b68922' }
43
+ },
44
+ {
45
+ _id: 1,
46
+ about: 1,
47
+ project: 1,
48
+ typeOf: 1,
49
+ issuedBy: 1
50
+ }
51
+ );
52
+ console.log('docs found');
53
+
54
+ let i = 0;
55
+ let updateCount = 0;
56
+ const creatingClients: {
57
+ projectId: string;
58
+ clientId: string;
59
+ clientSecret: string;
60
+ name: string;
61
+ memberName: string;
62
+ }[] = [];
63
+ // tslint:disable-next-line:max-func-body-length
64
+ await cursor.eachAsync(async (doc) => {
65
+ i += 1;
66
+ const identity: Pick<
67
+ chevre.factory.creativeWork.certification.webApplication.ICertification,
68
+ 'about' | 'project' | 'typeOf' | 'id' | 'issuedBy'
69
+ > = doc.toObject();
70
+
71
+ const iamMember = (await memberRepo.projectFieldsByProjectId(
72
+ { id: identity.project.id },
73
+ {
74
+ limit: 1,
75
+ member: {
76
+ id: { $eq: identity.about.id },
77
+ typeOf: { $eq: chevre.factory.creativeWorkType.WebApplication }
78
+ }
79
+ },
80
+ ['member']
81
+ )).shift();
82
+ if (iamMember === undefined) {
83
+ throw new Error(`iamMember not found ${identity.project.id} ${identity.about.id}`);
84
+ }
85
+
86
+ const client = await new Promise<UserPoolClientType>(async (resolve, reject) => {
87
+ cognitoIdentityServiceProvider.describeUserPoolClient(
88
+ {
89
+ ClientId: identity.about.id,
90
+ UserPoolId: userPoolId
91
+ },
92
+ {},
93
+ (err, data) => {
94
+ if (err instanceof Error) {
95
+ reject(err);
96
+ } else {
97
+ if (data?.UserPoolClient === undefined) {
98
+ reject(new chevre.factory.errors.NotFound('UserPoolClient'));
99
+ } else {
100
+ resolve(data.UserPoolClient);
101
+ }
102
+ }
103
+ }
104
+ );
105
+ });
106
+
107
+ if (typeof client.ClientId !== 'string'
108
+ || typeof client.ClientSecret !== 'string'
109
+ || typeof client.ClientName !== 'string') {
110
+ throw new Error('invalid client');
111
+ }
112
+
113
+ creatingClients.push({
114
+ projectId: identity.project.id,
115
+ clientId: client.ClientId,
116
+ clientSecret: client.ClientSecret,
117
+ name: client.ClientName,
118
+ memberName: String(iamMember.member.name)
119
+ });
120
+
121
+ const issuedBy = identity.issuedBy;
122
+ const numIssuedBy = (Array.isArray(identity.issuedBy)) ? identity.issuedBy.length : 1;
123
+
124
+ const alreadyMigrated = (Array.isArray(issuedBy))
125
+ // tslint:disable-next-line:no-magic-numbers
126
+ && issuedBy.length === 2
127
+ && issuedBy.some(({ identifier }) => identifier === NEW_ISS);
128
+
129
+ if (alreadyMigrated) {
130
+ console.log('already migrated.', identity.project.id, identity.about.id, identity.id, numIssuedBy, i);
131
+ } else {
132
+ if (typeof identity.id !== 'string') {
133
+ throw new Error(`id undefined ${identity.id}`);
134
+ }
135
+
136
+ // プロバイダー追加
137
+ const existingProvider = (await identityProviderRepo.projectFields(
138
+ {
139
+ limit: 1,
140
+ project: { id: { $eq: identity.project.id } },
141
+ identifier: { $eq: NEW_ISS }
142
+ },
143
+ ['identifier']
144
+ )).shift();
145
+ if (existingProvider === undefined) {
146
+ await identityProviderRepo.save({
147
+ attributes: {
148
+ identifier: NEW_ISS,
149
+ project: { id: identity.project.id, typeOf: chevre.factory.organizationType.Project },
150
+ typeOf: chevre.factory.organizationType.Organization
151
+ }
152
+ });
153
+ console.log('provider saved.', identity.project.id, identity.about.id, identity.id, numIssuedBy, i);
154
+ }
155
+
156
+ // identity更新
157
+ const newIssuedBy = (Array.isArray(issuedBy)) ? issuedBy : [issuedBy];
158
+ if (newIssuedBy.length !== 1) {
159
+ throw new Error('newIssuedBy.length must be 1');
160
+ }
161
+ newIssuedBy.push({
162
+ identifier: NEW_ISS,
163
+ typeOf: chevre.factory.organizationType.Organization
164
+ });
165
+ console.log(newIssuedBy);
166
+ await identityRepo.updateIssuedBy2array({
167
+ id: identity.id,
168
+ issuedBy: newIssuedBy
169
+ });
170
+ updateCount += 1;
171
+ console.log(
172
+ 'updated.', identity.project.id, identity.about.id, identity.id, numIssuedBy, i);
173
+ }
174
+ });
175
+
176
+ console.log(creatingClients.map(({ clientId }) => clientId));
177
+ // tslint:disable-next-line:non-literal-fs-path no-null-keyword
178
+ // fs.writeFileSync(`${__dirname}/../../../creatingClients.json`, JSON.stringify(creatingClients, null, ' '));
179
+ // tslint:disable-next-line:non-literal-fs-path no-null-keyword
180
+ const json = JSON.stringify(creatingClients, null, '');
181
+ // tslint:disable-next-line:non-literal-fs-path
182
+ fs.writeFileSync(`${__dirname}/../../../creatingClients.json`, json);
183
+ console.log(i, 'docs checked');
184
+ console.log(updateCount, 'docs updated');
185
+
186
+ const parser = new json2csv.Parser({
187
+ fields: ['projectId', 'clientId', 'clientSecret', 'name', 'memberName']
188
+ });
189
+ const csv = parser.parse(creatingClients.sort(
190
+ (a, b) => {
191
+ return (a.projectId > b.projectId) ? 1 : -1;
192
+ }
193
+ ));
194
+ // tslint:disable-next-line:non-literal-fs-path
195
+ fs.writeFileSync(`${__dirname}/../../../creatingClients.csv`, csv);
196
+ }
197
+
198
+ main()
199
+ .then()
200
+ .catch(console.error);
@@ -0,0 +1,55 @@
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 IDENTIFIER = 'DefaultMemberProgram';
8
+
9
+ async function main() {
10
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
11
+
12
+ const memberProgramRepo = await chevre.repository.MemberProgram.createInstance(mongoose.connection);
13
+
14
+ const memberPrograms = await memberProgramRepo.projectMemberPrograms(
15
+ {
16
+ project: { id: { $eq: project.id } },
17
+ identifier: { $eq: IDENTIFIER }
18
+ }
19
+ );
20
+ console.log('docs:', memberPrograms);
21
+ console.log(memberPrograms.length, 'docs found');
22
+
23
+ if (memberPrograms.length > 0) {
24
+ const memberProgram = memberPrograms[0];
25
+ await memberProgramRepo.updateOne({
26
+ project: { id: project.id },
27
+ identifier: memberProgram.identifier,
28
+ hostingOrganization: { id: 'xxx' },
29
+ hasTiers: [
30
+ { identifier: 'bronze' },
31
+ { identifier: 'silver' },
32
+ { identifier: 'gold' }
33
+ ]
34
+ });
35
+ console.log('updated.');
36
+
37
+ const tiers = await memberProgramRepo.projectMemberProgramTiers(
38
+ {
39
+ limit: 10,
40
+ page: 1,
41
+ project: { id: { $eq: project.id } },
42
+ isTierOf: {
43
+ identifier: { $eq: memberProgram.identifier }
44
+ }
45
+ }
46
+ );
47
+ // tslint:disable-next-line:no-null-keyword
48
+ console.dir(tiers, { depth: null });
49
+ console.log(tiers.length, 'tiers found');
50
+ }
51
+ }
52
+
53
+ main()
54
+ .then()
55
+ .catch(console.error);