@chevre/domain 21.30.0-alpha.17 → 21.30.0-alpha.18

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.
@@ -0,0 +1,73 @@
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
+ // tslint:disable-next-line:max-func-body-length
10
+ async function main() {
11
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
12
+
13
+ // const actionRepo = await chevre.repository.Action.createInstance(mongoose.connection);
14
+ // const orderRepo = await chevre.repository.Order.createInstance(mongoose.connection);
15
+ const transactionRepo = await chevre.repository.Transaction.createInstance(mongoose.connection);
16
+
17
+ const cursor = transactionRepo.getCursor(
18
+ {
19
+ startDate: {
20
+ $gte: moment()
21
+ // tslint:disable-next-line:no-magic-numbers
22
+ .add(-30, 'days')
23
+ .toDate()
24
+ },
25
+ typeOf: { $eq: chevre.factory.transactionType.PlaceOrder },
26
+ status: { $eq: chevre.factory.transactionStatusType.Confirmed }
27
+ // orderStatus: { $nin: [chevre.factory.orderStatus.OrderReturned] }
28
+ },
29
+ {
30
+ // orderNumber: 1,
31
+ // orderDate: 1,
32
+ // project: 1
33
+ }
34
+ );
35
+ console.log('transactions found');
36
+
37
+ let i = 0;
38
+ await cursor.eachAsync(async (doc) => {
39
+ i += 1;
40
+ const transaction = <Pick<
41
+ chevre.factory.transaction.placeOrder.ITransaction,
42
+ 'object' | 'result' | 'potentialActions' | 'project' | 'startDate'
43
+ >>doc.toObject();
44
+
45
+ // console.log('searching actions...', order, order.project, order.orderNumber, order.orderDate, i);
46
+ // const actions = await actionRepo.search(
47
+ // {
48
+ // typeOf: { $eq: chevre.factory.actionType.SendAction },
49
+ // purpose: { orderNumber: { $in: [order.orderNumber] } }
50
+ // },
51
+ // ['_id', 'object'],
52
+ // []);
53
+ // const onOrderSentMessageCount: number = actions.filter(
54
+ // ({ object }) => object.about.identifier === chevre.factory.creativeWork.message.email.AboutIdentifier.OnOrderSent
55
+ // ).length;
56
+ let onOrderSentMessageCount: number | undefined =
57
+ transaction.potentialActions?.order.potentialActions?.sendOrder?.potentialActions?.sendEmailMessage?.length;
58
+ if (onOrderSentMessageCount === undefined) {
59
+ onOrderSentMessageCount = 0;
60
+ }
61
+ console.log(
62
+ onOrderSentMessageCount, 'messages found', transaction.project, transaction.object.orderNumber, transaction.startDate, i);
63
+ if (onOrderSentMessageCount > 1) {
64
+ throw new Error(transaction.object.orderNumber);
65
+ }
66
+ });
67
+
68
+ console.log(i, 'orders checked');
69
+ }
70
+
71
+ main()
72
+ .then()
73
+ .catch(console.error);
@@ -0,0 +1,49 @@
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
+
8
+ async function main() {
9
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
10
+
11
+ const messageRepo = await chevre.repository.Message.createInstance(mongoose.connection);
12
+ const createResult = await messageRepo.upsertByIdentifier(
13
+ [
14
+ {
15
+ project: { id: project.id, typeOf: chevre.factory.organizationType.Project },
16
+ identifier: 'SendOrder-TTT5-8982603-9533198',
17
+ name: 'SendOrder-TTT5-8982603-9533198',
18
+ sender: {
19
+ typeOf: 'Corporation',
20
+ name: 'sample sender name',
21
+ email: 'text@example.com'
22
+ },
23
+ toRecipient: [
24
+ {
25
+ typeOf: 'WebApplication',
26
+ name: 'sample toRecipient',
27
+ email: 'text@example.com'
28
+ }
29
+ ],
30
+ about: {
31
+ typeOf: 'Thing',
32
+ identifier: chevre.factory.creativeWork.message.email.AboutIdentifier.OnOrderSent,
33
+ name: 'sample about name'
34
+ },
35
+ text: 'sample text',
36
+ mainEntity: {
37
+ typeOf: chevre.factory.order.OrderType.Order,
38
+ orderNumber: 'TTT5-8982603-9533198'
39
+ }
40
+ }
41
+ ]
42
+ );
43
+ console.log('createResult:', createResult);
44
+
45
+ }
46
+
47
+ main()
48
+ .then(console.log)
49
+ .catch(console.error);
@@ -0,0 +1,23 @@
1
+ import type { BulkWriteResult } from 'mongodb';
2
+ import type { Connection } from 'mongoose';
3
+ import * as factory from '../factory';
4
+ type IEmailMessage = factory.creativeWork.message.email.ICreativeWork & {
5
+ datePublished: Date;
6
+ mainEntity: Pick<factory.order.ISimpleOrder, 'orderNumber' | 'typeOf'>;
7
+ project: {
8
+ id: string;
9
+ typeOf: factory.organizationType.Project;
10
+ };
11
+ };
12
+ /**
13
+ * メッセージリポジトリ
14
+ */
15
+ export declare class MessageRepo {
16
+ private readonly messageModel;
17
+ constructor(connection: Connection);
18
+ /**
19
+ * コードをキーにしてなければ作成する(複数対応)
20
+ */
21
+ upsertByIdentifier(params: Pick<IEmailMessage, 'about' | 'identifier' | 'mainEntity' | 'name' | 'project' | 'sender' | 'text' | 'toRecipient'>[]): Promise<BulkWriteResult | void>;
22
+ }
23
+ export {};
@@ -0,0 +1,74 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MessageRepo = void 0;
13
+ const message_1 = require("./mongoose/schemas/message");
14
+ const factory = require("../factory");
15
+ /**
16
+ * メッセージリポジトリ
17
+ */
18
+ class MessageRepo {
19
+ constructor(connection) {
20
+ this.messageModel = connection.model(message_1.modelName, (0, message_1.createSchema)());
21
+ }
22
+ /**
23
+ * コードをキーにしてなければ作成する(複数対応)
24
+ */
25
+ upsertByIdentifier(params) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ const now = new Date();
28
+ const bulkWriteOps = [];
29
+ if (Array.isArray(params)) {
30
+ params.forEach((creatingNoteParams) => {
31
+ const { about, identifier, project, text, mainEntity, name, sender, toRecipient } = creatingNoteParams;
32
+ if (typeof identifier !== 'string' || identifier.length === 0) {
33
+ throw new factory.errors.ArgumentNull('identifier');
34
+ }
35
+ if (typeof text !== 'string') {
36
+ throw new factory.errors.ArgumentNull('text');
37
+ }
38
+ // リソースのユニークネスを保証するfilter
39
+ const filter = {
40
+ typeOf: { $eq: factory.creativeWorkType.EmailMessage },
41
+ 'project.id': { $eq: project.id },
42
+ identifier: { $eq: identifier }
43
+ };
44
+ const setOnInsert = {
45
+ identifier,
46
+ project,
47
+ datePublished: now,
48
+ typeOf: factory.creativeWorkType.EmailMessage
49
+ };
50
+ // 変更可能な属性のみ上書き
51
+ const setFields = Object.assign({ mainEntity,
52
+ about,
53
+ sender,
54
+ text,
55
+ toRecipient }, (typeof name === 'string') ? { name } : undefined);
56
+ const updateFilter = {
57
+ $setOnInsert: setOnInsert,
58
+ $set: setFields
59
+ };
60
+ const updateOne = {
61
+ filter,
62
+ update: updateFilter,
63
+ upsert: true
64
+ };
65
+ bulkWriteOps.push({ updateOne });
66
+ });
67
+ }
68
+ if (bulkWriteOps.length > 0) {
69
+ return this.messageModel.bulkWrite(bulkWriteOps, { ordered: false });
70
+ }
71
+ });
72
+ }
73
+ }
74
+ exports.MessageRepo = MessageRepo;
@@ -15,7 +15,15 @@ const schemaDefinition = {
15
15
  type: String,
16
16
  required: true
17
17
  },
18
- identifier: String,
18
+ datePublished: {
19
+ type: Date,
20
+ required: true
21
+ },
22
+ identifier: {
23
+ type: String,
24
+ required: true
25
+ },
26
+ mainEntity: mongoose_1.SchemaTypes.Mixed,
19
27
  name: mongoose_1.SchemaTypes.Mixed,
20
28
  about: mongoose_1.SchemaTypes.Mixed,
21
29
  sender: mongoose_1.SchemaTypes.Mixed,
@@ -22,6 +22,7 @@ import type { MongoRepository as EmailMessageRepo } from './repo/emailMessage';
22
22
  import type { MongoRepository as EventRepo } from './repo/event';
23
23
  import type { MongoRepository as MemberRepo } from './repo/member';
24
24
  import type { MongoRepository as MerchantReturnPolicyRepo } from './repo/merchantReturnPolicy';
25
+ import type { MessageRepo } from './repo/message';
25
26
  import type { MongoRepository as NoteRepo } from './repo/note';
26
27
  import type { MongoRepository as OfferRepo } from './repo/offer';
27
28
  import type { MongoRepository as OfferCatalogRepo } from './repo/offerCatalog';
@@ -151,6 +152,10 @@ export type MerchantReturnPolicy = MerchantReturnPolicyRepo;
151
152
  export declare namespace MerchantReturnPolicy {
152
153
  function createInstance(...params: ConstructorParameters<typeof MerchantReturnPolicyRepo>): Promise<MerchantReturnPolicyRepo>;
153
154
  }
155
+ export type Message = MessageRepo;
156
+ export declare namespace Message {
157
+ function createInstance(...params: ConstructorParameters<typeof MessageRepo>): Promise<MessageRepo>;
158
+ }
154
159
  export type Note = NoteRepo;
155
160
  export declare namespace Note {
156
161
  function createInstance(...params: ConstructorParameters<typeof NoteRepo>): Promise<NoteRepo>;
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.StockHolder = exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.SellerPaymentAccepted = exports.Seller = exports.Role = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.ProductModel = exports.Product = exports.PriceSpecification = exports.place = exports.Permit = exports.Person = exports.paymentMethod = exports.PaymentServiceProvider = exports.PaymentService = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.Note = exports.MerchantReturnPolicy = exports.Member = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.CreativeWork = exports.ConfirmationNumber = exports.Comment = exports.Code = exports.CategoryCode = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOffer = exports.AdditionalProperty = exports.Action = exports.AccountTransaction = exports.AccountTitle = exports.AccountingReport = exports.Account = exports.AcceptedOffer = void 0;
13
- exports.rateLimit = exports.Trip = exports.TransactionProcess = exports.TransactionNumber = exports.Transaction = exports.Telemetry = exports.Task = void 0;
12
+ exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.SellerPaymentAccepted = exports.Seller = exports.Role = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.ProductModel = exports.Product = exports.PriceSpecification = exports.place = exports.Permit = exports.Person = exports.paymentMethod = exports.PaymentServiceProvider = exports.PaymentService = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.Note = exports.Message = exports.MerchantReturnPolicy = exports.Member = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.CreativeWork = exports.ConfirmationNumber = exports.Comment = exports.Code = exports.CategoryCode = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOffer = exports.AdditionalProperty = exports.Action = exports.AccountTransaction = exports.AccountTitle = exports.AccountingReport = exports.Account = exports.AcceptedOffer = void 0;
13
+ exports.rateLimit = exports.Trip = exports.TransactionProcess = exports.TransactionNumber = exports.Transaction = exports.Telemetry = exports.Task = exports.StockHolder = void 0;
14
14
  var AcceptedOffer;
15
15
  (function (AcceptedOffer) {
16
16
  let repo;
@@ -297,6 +297,19 @@ var MerchantReturnPolicy;
297
297
  }
298
298
  MerchantReturnPolicy.createInstance = createInstance;
299
299
  })(MerchantReturnPolicy = exports.MerchantReturnPolicy || (exports.MerchantReturnPolicy = {}));
300
+ var Message;
301
+ (function (Message) {
302
+ let repo;
303
+ function createInstance(...params) {
304
+ return __awaiter(this, void 0, void 0, function* () {
305
+ if (repo === undefined) {
306
+ repo = (yield Promise.resolve().then(() => require('./repo/message'))).MessageRepo;
307
+ }
308
+ return new repo(...params);
309
+ });
310
+ }
311
+ Message.createInstance = createInstance;
312
+ })(Message = exports.Message || (exports.Message = {}));
300
313
  var Note;
301
314
  (function (Note) {
302
315
  let repo;
@@ -2,6 +2,7 @@ import type { MongoRepository as ActionRepo } from '../../../repo/action';
2
2
  import type { MongoRepository as CodeRepo } from '../../../repo/code';
3
3
  import type { RedisRepository as ConfirmationNumberRepo } from '../../../repo/confirmationNumber';
4
4
  import type { MongoRepository as EmailMessageRepo } from '../../../repo/emailMessage';
5
+ import type { MessageRepo } from '../../../repo/message';
5
6
  import type { MongoRepository as OrderInTransactionRepo } from '../../../repo/orderInTransaction';
6
7
  import type { RedisRepository as OrderNumberRepo } from '../../../repo/orderNumber';
7
8
  import type { MongoRepository as ProjectRepo } from '../../../repo/project';
@@ -12,6 +13,7 @@ interface IConfirmOperationRepos {
12
13
  action: ActionRepo;
13
14
  authorization: CodeRepo;
14
15
  emailMessage?: EmailMessageRepo;
16
+ message: MessageRepo;
15
17
  project: ProjectRepo;
16
18
  transaction: TransactionRepo;
17
19
  orderInTransaction: OrderInTransactionRepo;
@@ -101,9 +101,7 @@ function confirm(params) {
101
101
  // order: orderWithAcceptedOffers, // 現時点でcreateEmailMessageでorder.acceptedOffersを使用している(2024-02-06~)
102
102
  transaction: transaction }, (params.potentialActions !== undefined) ? { potentialActions: params.potentialActions } : undefined), (emailMessageOnOrderSent !== undefined) ? { emailMessage: emailMessageOnOrderSent } : undefined));
103
103
  // メッセージ保管(2024-04-28~)
104
- if (params.options.useSaveMessages) {
105
- debug('saving', emailMessages.length, 'emailMessages...', emailMessages);
106
- }
104
+ yield saveMessagesIfNeeded({ options: params.options }, result.order, emailMessages)(repos);
107
105
  // ステータス変更
108
106
  try {
109
107
  yield repos.transaction.confirm({
@@ -128,6 +126,24 @@ function confirm(params) {
128
126
  });
129
127
  }
130
128
  exports.confirm = confirm;
129
+ function saveMessagesIfNeeded(params, order, emailMessages) {
130
+ return (repos) => __awaiter(this, void 0, void 0, function* () {
131
+ if (params.options.useSaveMessages) {
132
+ if (emailMessages.length > 0) {
133
+ const { orderNumber, typeOf, project } = order;
134
+ debug('saving', emailMessages.length, 'messages...', emailMessages);
135
+ const saveMessageResult = yield repos.message.upsertByIdentifier(emailMessages.map(({ identifier, name, about, text, toRecipient, sender }) => {
136
+ return {
137
+ identifier, name, about, text, toRecipient, sender,
138
+ project,
139
+ mainEntity: { orderNumber, typeOf }
140
+ };
141
+ }));
142
+ debug(emailMessages.length, 'messages saved.', saveMessageResult);
143
+ }
144
+ }
145
+ });
146
+ }
131
147
  /**
132
148
  * 全承認アクションを分解する
133
149
  */
package/package.json CHANGED
@@ -110,5 +110,5 @@
110
110
  "postversion": "git push origin --tags",
111
111
  "prepublishOnly": "npm run clean && npm run build && npm test && npm run doc"
112
112
  },
113
- "version": "21.30.0-alpha.17"
113
+ "version": "21.30.0-alpha.18"
114
114
  }
@@ -1,83 +0,0 @@
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
-
8
- async function main() {
9
- await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
10
-
11
- const noteRepo = await chevre.repository.Note.createInstance(mongoose.connection);
12
- const result = await noteRepo.search({
13
- limit: 1,
14
- page: 1,
15
- inclusion: ['text', 'about', 'identifier'],
16
- exclusion: []
17
- });
18
- console.log('result:', result);
19
-
20
- // let createResult = await noteRepo.upsertByIdentifier(
21
- // [{
22
- // about: {
23
- // id: '65c41ca61898c4feba427e4f',
24
- // orderNumber: 'CIN2-8393218-6955938',
25
- // typeOf: chevre.factory.order.OrderType.Order
26
- // },
27
- // creator: {
28
- // id: '582ee997-86ac-43e4-90c2-213a10c3282f',
29
- // typeOf: chevre.factory.personType.Person
30
- // },
31
- // identifier: '20240213OrderNote',
32
- // project: { id: project.id, typeOf: chevre.factory.organizationType.Project },
33
- // text: 'note text',
34
- // version: '1'
35
- // }],
36
- // { overwrite: false }
37
- // );
38
- // console.log('createResult:', createResult);
39
-
40
- // createResult = await noteRepo.upsertByIdentifier(
41
- // [{
42
- // about: {
43
- // id: '65c41ca61898c4feba427e4f',
44
- // orderNumber: 'CIN2-8393218-6955938',
45
- // typeOf: chevre.factory.order.OrderType.Order
46
- // },
47
- // creator: {
48
- // id: '582ee997-86ac-43e4-90c2-213a10c3282f',
49
- // typeOf: chevre.factory.personType.Person
50
- // },
51
- // identifier: '20240213OrderNote',
52
- // project: { id: project.id, typeOf: chevre.factory.organizationType.Project },
53
- // text: 'note text updated',
54
- // version: '1'
55
- // }],
56
- // { overwrite: false }
57
- // );
58
- // console.log('createResult:', createResult);
59
-
60
- // createResult = await noteRepo.upsertByIdentifier(
61
- // [{
62
- // about: {
63
- // id: '65c41ca61898c4feba427e4f',
64
- // orderNumber: 'CIN2-8393218-6955938',
65
- // typeOf: chevre.factory.order.OrderType.Order
66
- // },
67
- // creator: {
68
- // id: '582ee997-86ac-43e4-90c2-213a10c3282f',
69
- // typeOf: chevre.factory.personType.Person
70
- // },
71
- // identifier: '20240213OrderNote',
72
- // project: { id: project.id, typeOf: chevre.factory.organizationType.Project },
73
- // text: '',
74
- // version: '1'
75
- // }],
76
- // { overwrite: false }
77
- // );
78
- // console.log('createResult:', createResult);
79
- }
80
-
81
- main()
82
- .then(console.log)
83
- .catch(console.error);