@chevre/domain 27.1.0-alpha.6 → 27.1.0-alpha.7

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,19 @@
1
+ import type { RedisClientType } from '@redis/client';
2
+ import { factory } from '../../factory';
3
+ import type { IStartedTransaction } from './returnOrder';
4
+ /**
5
+ * 返品取引リポジトリ
6
+ */
7
+ export declare class ReturnOrderInProgressRepo {
8
+ private static readonly KEY_PREFIX;
9
+ private readonly redisClient;
10
+ constructor(redisClient: RedisClientType);
11
+ /**
12
+ * 取引を開始する
13
+ */
14
+ startReturnOrder(params: factory.transaction.IStartParams<factory.transactionType.ReturnOrder>): Promise<IStartedTransaction>;
15
+ findReturnOrderById(params: {
16
+ typeOf: factory.transactionType.ReturnOrder;
17
+ id: string;
18
+ }): Promise<factory.transaction.ITransaction<factory.transactionType.ReturnOrder>>;
19
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ReturnOrderInProgressRepo = void 0;
7
+ const moment_1 = __importDefault(require("moment"));
8
+ const factory_1 = require("../../factory");
9
+ /**
10
+ * 返品取引リポジトリ
11
+ */
12
+ class ReturnOrderInProgressRepo {
13
+ static KEY_PREFIX = `txn:${factory_1.factory.transaction.returnOrder}`;
14
+ redisClient;
15
+ constructor(redisClient) {
16
+ this.redisClient = redisClient;
17
+ }
18
+ /**
19
+ * 取引を開始する
20
+ */
21
+ async startReturnOrder(params) {
22
+ const status = factory_1.factory.transactionStatusType.InProgress;
23
+ const tasksExportAction = { actionStatus: factory_1.factory.actionStatusType.PotentialActionStatus };
24
+ const startDate = new Date();
25
+ let expires;
26
+ const { typeOf } = params;
27
+ // expiresInSecondsの指定があれば優先して適用する(2022-11-25~)
28
+ if (typeof params.expiresInSeconds === 'number' && params.expiresInSeconds > 0) {
29
+ expires = (0, moment_1.default)(startDate)
30
+ .add(params.expiresInSeconds, 'seconds')
31
+ .toDate();
32
+ }
33
+ else {
34
+ throw new factory_1.factory.errors.ArgumentNull('expiresInSeconds');
35
+ }
36
+ const { agent, project, object, seller } = params;
37
+ const creatingTransaction = {
38
+ status, startDate, expires, typeOf, tasksExportAction,
39
+ agent, project, seller, object
40
+ };
41
+ const id = `${ReturnOrderInProgressRepo.KEY_PREFIX}:${startDate.getTime()}`;
42
+ const result = await this.redisClient.set(id, JSON.stringify(creatingTransaction), {
43
+ expiration: { type: 'PXAT', value: expires.getTime() },
44
+ condition: 'NX'
45
+ });
46
+ // 成功時は 'OK' が返り、既に存在した場合は null が返る
47
+ if (result !== 'OK') {
48
+ throw new factory_1.factory.errors.AlreadyInUse(factory_1.factory.transactionType.ReturnOrder, []);
49
+ }
50
+ return { expires, id, startDate, status };
51
+ }
52
+ async findReturnOrderById(params) {
53
+ let transaction;
54
+ const transactionJson = await this.redisClient.get(params.id);
55
+ if (typeof transactionJson !== 'string') {
56
+ throw new factory_1.factory.errors.NotFound(factory_1.factory.transactionType.ReturnOrder);
57
+ }
58
+ try {
59
+ transaction = JSON.parse(transactionJson);
60
+ transaction = {
61
+ ...transaction,
62
+ startDate: (0, moment_1.default)(transaction.startDate)
63
+ .toDate(),
64
+ expires: (0, moment_1.default)(transaction.expires)
65
+ .toDate(),
66
+ id: params.id
67
+ };
68
+ }
69
+ catch (error) {
70
+ console.error('transaction parse error:', error);
71
+ throw error;
72
+ }
73
+ return transaction;
74
+ }
75
+ }
76
+ exports.ReturnOrderInProgressRepo = ReturnOrderInProgressRepo;
@@ -114,6 +114,7 @@ import type { TicketRepo } from './repo/ticket';
114
114
  import type { TransactionRepo } from './repo/transaction';
115
115
  import type { PlaceOrderRepo } from './repo/transaction/placeOrder';
116
116
  import type { ReturnOrderRepo } from './repo/transaction/returnOrder';
117
+ import type { ReturnOrderInProgressRepo } from './repo/transaction/returnOrderInProgress';
117
118
  import type { TransactionNumberRepo } from './repo/transactionNumber';
118
119
  import type { TransactionProcessRepo } from './repo/transactionProcess';
119
120
  import type { WebSiteRepo } from './repo/webSite';
@@ -607,6 +608,10 @@ export declare namespace transaction {
607
608
  namespace ReturnOrder {
608
609
  function createInstance(...params: ConstructorParameters<typeof ReturnOrderRepo>): Promise<ReturnOrderRepo>;
609
610
  }
611
+ type ReturnOrderInProgress = ReturnOrderInProgressRepo;
612
+ namespace ReturnOrderInProgress {
613
+ function createInstance(...params: ConstructorParameters<typeof ReturnOrderInProgressRepo>): Promise<ReturnOrderInProgressRepo>;
614
+ }
610
615
  }
611
616
  export type TransactionNumber = TransactionNumberRepo;
612
617
  export declare namespace TransactionNumber {
@@ -1299,6 +1299,17 @@ var transaction;
1299
1299
  }
1300
1300
  ReturnOrder.createInstance = createInstance;
1301
1301
  })(ReturnOrder = transaction.ReturnOrder || (transaction.ReturnOrder = {}));
1302
+ let ReturnOrderInProgress;
1303
+ (function (ReturnOrderInProgress) {
1304
+ let repo;
1305
+ async function createInstance(...params) {
1306
+ if (repo === undefined) {
1307
+ repo = (await import('./repo/transaction/returnOrderInProgress.js')).ReturnOrderInProgressRepo;
1308
+ }
1309
+ return new repo(...params);
1310
+ }
1311
+ ReturnOrderInProgress.createInstance = createInstance;
1312
+ })(ReturnOrderInProgress = transaction.ReturnOrderInProgress || (transaction.ReturnOrderInProgress = {}));
1302
1313
  })(transaction || (exports.transaction = transaction = {}));
1303
1314
  var TransactionNumber;
1304
1315
  (function (TransactionNumber) {
@@ -0,0 +1,6 @@
1
+ import { factory } from '../../factory';
2
+ import type { ICallResult, IExecutableTaskKeys, IOperationExecute } from '../taskHandler';
3
+ /**
4
+ * タスク実行関数
5
+ */
6
+ export declare function call(params: Pick<factory.task.confirmReturnOrder.ITask, IExecutableTaskKeys>): IOperationExecute<ICallResult>;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.call = call;
4
+ const factory_1 = require("../../factory");
5
+ const task_1 = require("../../repo/task");
6
+ /**
7
+ * タスク実行関数
8
+ */
9
+ function call(params) {
10
+ return async ({ connection }) => {
11
+ const { data } = params;
12
+ await exportTasksById({
13
+ transaction: data
14
+ })({
15
+ task: new task_1.TaskRepo(connection),
16
+ });
17
+ };
18
+ }
19
+ function exportTasksById(params) {
20
+ return async (repos) => {
21
+ const { transaction } = params;
22
+ const taskRunsAt = new Date();
23
+ await repos.task.saveMany(createImmediateTasks({ transaction, taskRunsAt }));
24
+ };
25
+ }
26
+ function createImmediateTasks(params) {
27
+ const taskAttributes = [];
28
+ const transaction = params.transaction;
29
+ const taskRunsAt = params.taskRunsAt;
30
+ const returnOrderPotentialActions = transaction.potentialActions?.returnOrder;
31
+ if (Array.isArray(returnOrderPotentialActions)) {
32
+ // 返品タスク
33
+ const returnOrderTask = returnOrderPotentialActions.map((r) => {
34
+ const { object, potentialActions, typeOf } = transaction;
35
+ const returnOrderTaskData = {
36
+ agent: r.agent,
37
+ object: r.object,
38
+ project: transaction.project,
39
+ typeOf: r.typeOf,
40
+ returnOrderTransaction: { object, potentialActions, typeOf } // add(2026-09-05~)
41
+ };
42
+ return {
43
+ project: transaction.project,
44
+ name: factory_1.factory.taskName.ReturnOrder,
45
+ status: factory_1.factory.taskStatus.Ready,
46
+ runsAt: taskRunsAt,
47
+ remainingNumberOfTries: 10,
48
+ numberOfTried: 0,
49
+ executionResults: [],
50
+ data: returnOrderTaskData
51
+ };
52
+ });
53
+ taskAttributes.push(...returnOrderTask);
54
+ }
55
+ return taskAttributes;
56
+ }
@@ -14,6 +14,7 @@ import type { SettingRepo } from '../../repo/setting';
14
14
  import type { ScheduledTaskRepo } from '../../repo/scheduledTask';
15
15
  import type { TaskRepo } from '../../repo/task';
16
16
  import type { IStartedTransaction, ReturnOrderRepo } from '../../repo/transaction/returnOrder';
17
+ import type { ReturnOrderInProgressRepo } from '../../repo/transaction/returnOrderInProgress';
17
18
  import { preStart } from './returnOrder/preStart';
18
19
  interface IStartOperationRepos {
19
20
  acceptedOffer: AcceptedOfferRepo;
@@ -27,6 +28,7 @@ interface IStartOperationRepos {
27
28
  seller: SellerRepo;
28
29
  sellerReturnPolicy: SellerReturnPolicyRepo;
29
30
  returnOrder: ReturnOrderRepo;
31
+ returnOrderInProgress: ReturnOrderInProgressRepo;
30
32
  }
31
33
  type IStartOperation<T> = (repos: IStartOperationRepos) => Promise<T>;
32
34
  interface IExportTasksByIdRepos {
@@ -39,13 +41,17 @@ type ITaskAndTransactionOperation<T> = (repos: IExportTasksByIdRepos) => Promise
39
41
  /**
40
42
  * 返品取引開始
41
43
  */
42
- declare function start(params: factory.transaction.returnOrder.IStartParamsWithoutDetail): IStartOperation<IStartedTransaction>;
44
+ declare function start(params: factory.transaction.returnOrder.IStartParamsWithoutDetail, options: {
45
+ useConfirmReturnOrderTask: boolean;
46
+ }): IStartOperation<IStartedTransaction>;
43
47
  interface IConfirmRepos {
44
48
  acceptedOffer: AcceptedOfferRepo;
45
49
  message: MessageRepo;
46
50
  order: OrderRepo;
47
51
  setting: SettingRepo;
48
52
  returnOrder: ReturnOrderRepo;
53
+ returnOrderInProgress: ReturnOrderInProgressRepo;
54
+ task: TaskRepo;
49
55
  }
50
56
  /**
51
57
  * 取引確定
@@ -56,6 +62,8 @@ declare function confirm(params: factory.transaction.returnOrder.IConfirmParams
56
62
  dateReturned: Date;
57
63
  };
58
64
  };
65
+ }, options: {
66
+ useConfirmReturnOrderTask: boolean;
59
67
  }): (repos: IConfirmRepos) => Promise<import("@chevre/factory/lib/chevre/transaction/returnOrder").IResult | undefined>;
60
68
  /**
61
69
  * 取引のタスクを出力します
@@ -20,8 +20,9 @@ const errorHandler_1 = require("../../errorHandler");
20
20
  /**
21
21
  * 返品取引開始
22
22
  */
23
- function start(params) {
23
+ function start(params, options) {
24
24
  return async (repos) => {
25
+ const { useConfirmReturnOrderTask } = options;
25
26
  const { transactionObject, expiresInSeconds, seller } = await (0, preStart_1.preStart)(params)(repos);
26
27
  const returnOrderAttributes = {
27
28
  project: params.project,
@@ -36,15 +37,20 @@ function start(params) {
36
37
  expiresInSeconds
37
38
  };
38
39
  let returnOrderTransaction;
39
- try {
40
- returnOrderTransaction = await repos.returnOrder.startReturnOrder(returnOrderAttributes);
40
+ if (useConfirmReturnOrderTask) {
41
+ returnOrderTransaction = await repos.returnOrderInProgress.startReturnOrder(returnOrderAttributes);
41
42
  }
42
- catch (error) {
43
- if (await (0, errorHandler_1.isMongoDuplicateError)(error)) {
44
- // 同一取引に対して返品取引を作成しようとすると、MongoDBでE11000 duplicate key errorが発生する
45
- throw new factory_1.factory.errors.Argument('orderNumber', 'Already returned');
43
+ else {
44
+ try {
45
+ returnOrderTransaction = await repos.returnOrder.startReturnOrder(returnOrderAttributes);
46
+ }
47
+ catch (error) {
48
+ if (await (0, errorHandler_1.isMongoDuplicateError)(error)) {
49
+ // 同一取引に対して返品取引を作成しようとすると、MongoDBでE11000 duplicate key errorが発生する
50
+ throw new factory_1.factory.errors.Argument('orderNumber', 'Already returned');
51
+ }
52
+ throw error;
46
53
  }
47
- throw error;
48
54
  }
49
55
  return returnOrderTransaction;
50
56
  };
@@ -78,18 +84,25 @@ function saveMessagesIfNeeded(params) {
78
84
  /**
79
85
  * 取引確定
80
86
  */
81
- function confirm(params) {
87
+ function confirm(params, options) {
82
88
  return async (repos) => {
83
- const transaction = await repos.returnOrder.findReturnOrderById({ typeOf: factory_1.factory.transactionType.ReturnOrder, id: params.id }, ['typeOf', 'status', 'project', 'agent', 'object', 'result']);
84
- if (transaction.status === factory_1.factory.transactionStatusType.Confirmed) {
85
- // すでに確定済の場合
86
- return transaction.result;
87
- }
88
- else if (transaction.status === factory_1.factory.transactionStatusType.Expired) {
89
- throw new factory_1.factory.errors.Argument('transaction', 'Transaction already expired');
89
+ const { useConfirmReturnOrderTask } = options;
90
+ let transaction;
91
+ if (useConfirmReturnOrderTask) {
92
+ transaction = await repos.returnOrderInProgress.findReturnOrderById({ typeOf: factory_1.factory.transactionType.ReturnOrder, id: params.id });
90
93
  }
91
- else if (transaction.status === factory_1.factory.transactionStatusType.Canceled) {
92
- throw new factory_1.factory.errors.Argument('transaction', 'Transaction already canceled');
94
+ else {
95
+ transaction = await repos.returnOrder.findReturnOrderById({ typeOf: factory_1.factory.transactionType.ReturnOrder, id: params.id }, ['typeOf', 'status', 'project', 'agent', 'object', 'result', 'startDate']);
96
+ if (transaction.status === factory_1.factory.transactionStatusType.Confirmed) {
97
+ // すでに確定済の場合
98
+ return transaction.result;
99
+ }
100
+ else if (transaction.status === factory_1.factory.transactionStatusType.Expired) {
101
+ throw new factory_1.factory.errors.Argument('transaction', 'Transaction already expired');
102
+ }
103
+ else if (transaction.status === factory_1.factory.transactionStatusType.Canceled) {
104
+ throw new factory_1.factory.errors.Argument('transaction', 'Transaction already canceled');
105
+ }
93
106
  }
94
107
  if (typeof params.agent?.id === 'string' && transaction.agent.id !== params.agent.id) {
95
108
  throw new factory_1.factory.errors.Forbidden('Transaction not yours');
@@ -110,18 +123,6 @@ function confirm(params) {
110
123
  'orderedItem', 'paymentMethods', 'price', 'priceCurrency', 'project', 'seller', 'typeOf'
111
124
  ]
112
125
  });
113
- // discontinue emailMessageRepo
114
- // // デフォルトEメールメッセージを検索
115
- // let emailMessageOnOrderReturned: factory.creativeWork.message.email.ICreativeWork | undefined;
116
- // if (repos.emailMessage !== undefined) {
117
- // const searchEmailMessagesResult = await repos.emailMessage.search({
118
- // limit: 1,
119
- // page: 1,
120
- // project: { id: { $eq: transaction.project.id } },
121
- // about: { identifier: { $eq: factory.creativeWork.message.email.AboutIdentifier.OnOrderReturned } }
122
- // });
123
- // emailMessageOnOrderReturned = searchEmailMessagesResult.shift();
124
- // }
125
126
  const setting = await repos.setting.findOne({ project: { id: { $eq: '*' } } }, ['defaultSenderEmail']);
126
127
  if (typeof setting?.defaultSenderEmail !== 'string') {
127
128
  throw new factory_1.factory.errors.NotFound('setting.defaultSenderEmail');
@@ -141,12 +142,38 @@ function confirm(params) {
141
142
  project: { id: transaction.project.id },
142
143
  order: { orderNumber: returningOrders[0].orderNumber }, seller: { id: returningOrders[0].seller.id }, emailMessages
143
144
  })(repos);
144
- // ステータス変更
145
- await repos.returnOrder.confirmReturnOrder({
146
- typeOf: transaction.typeOf,
147
- id: transaction.id,
148
- result, potentialActions
149
- });
145
+ if (useConfirmReturnOrderTask) {
146
+ // タスク作成
147
+ const endDate = new Date();
148
+ const task = {
149
+ project: transaction.project,
150
+ name: factory_1.factory.taskName.ConfirmReturnOrder,
151
+ status: factory_1.factory.taskStatus.Ready,
152
+ runsAt: endDate,
153
+ remainingNumberOfTries: 10,
154
+ numberOfTried: 0,
155
+ executionResults: [],
156
+ data: {
157
+ typeOf: transaction.typeOf,
158
+ id: transaction.id,
159
+ agent: transaction.agent,
160
+ startDate: transaction.startDate,
161
+ object: transaction.object,
162
+ project: transaction.project,
163
+ potentialActions,
164
+ endDate
165
+ }
166
+ };
167
+ await repos.task.saveMany([task]);
168
+ }
169
+ else {
170
+ // ステータス変更
171
+ await repos.returnOrder.confirmReturnOrder({
172
+ typeOf: transaction.typeOf,
173
+ id: transaction.id,
174
+ result, potentialActions
175
+ });
176
+ }
150
177
  return result;
151
178
  };
152
179
  }
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "dependencies": {
12
12
  "@aws-sdk/client-cognito-identity-provider": "3.1090.0",
13
13
  "@aws-sdk/credential-providers": "3.1090.0",
14
- "@chevre/factory": "10.5.0-alpha.6",
14
+ "@chevre/factory": "10.5.0-alpha.7",
15
15
  "@motionpicture/coa-service": "10.0.0",
16
16
  "@motionpicture/gmo-service": "6.1.0-alpha.0",
17
17
  "@sendgrid/client": "8.1.4",
@@ -88,5 +88,5 @@
88
88
  "postversion": "git push origin --tags",
89
89
  "prepublishOnly": "npm run clean && npm run build"
90
90
  },
91
- "version": "27.1.0-alpha.6"
91
+ "version": "27.1.0-alpha.7"
92
92
  }