@chevre/domain 22.14.0-alpha.16 → 22.14.0-alpha.17

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,36 @@
1
+ import { IndexDefinition, IndexOptions, Model, Schema, SchemaDefinition } from 'mongoose';
2
+ import * as factory from '../../../factory';
3
+ interface IProductOffer {
4
+ project: {
5
+ id: string;
6
+ typeOf: factory.organizationType.Project;
7
+ };
8
+ typeOf: factory.offerType.Offer;
9
+ /**
10
+ * プロダクトオファーコード
11
+ */
12
+ identifier: string;
13
+ itemOffered: {
14
+ typeOf: factory.offerType.AggregateOffer;
15
+ /**
16
+ * プロダクトオファーコレクションコード
17
+ */
18
+ identifier: string;
19
+ };
20
+ availability: factory.itemAvailability.InStock | factory.itemAvailability.OutOfStock;
21
+ validFrom: Date;
22
+ validThrough: Date;
23
+ acceptedPaymentMethod?: {
24
+ typeOf: 'PaymentMethod';
25
+ identifier: string;
26
+ };
27
+ validForMemberTier?: Pick<factory.issuer.IMemberProgramTier, 'identifier' | 'typeOf'>;
28
+ }
29
+ type IDocType = IProductOffer;
30
+ type IModel = Model<IDocType>;
31
+ type ISchemaDefinition = SchemaDefinition<IDocType>;
32
+ type ISchema = Schema<IDocType, IModel, {}, {}, {}, {}, ISchemaDefinition, IDocType>;
33
+ declare const modelName = "ProductOffer";
34
+ declare const indexes: [d: IndexDefinition, o: IndexOptions][];
35
+ declare function createSchema(): ISchema;
36
+ export { createSchema, IDocType, IModel, indexes, modelName };
@@ -3,25 +3,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.modelName = exports.indexes = void 0;
4
4
  exports.createSchema = createSchema;
5
5
  const mongoose_1 = require("mongoose");
6
- const settings_1 = require("../../../../settings");
7
- const writeConcern_1 = require("../../writeConcern");
8
- const modelName = 'Offer.Event';
6
+ const settings_1 = require("../../../settings");
7
+ const writeConcern_1 = require("../writeConcern");
8
+ const modelName = 'ProductOffer';
9
9
  exports.modelName = modelName;
10
10
  const schemaDefinition = {
11
11
  project: { type: mongoose_1.SchemaTypes.Mixed, required: true },
12
- seller: { type: mongoose_1.SchemaTypes.Mixed, required: true },
13
12
  typeOf: { type: String, required: true },
14
13
  identifier: { type: String, required: true },
15
14
  itemOffered: { type: mongoose_1.SchemaTypes.Mixed, required: true },
16
- availableAtOrFrom: { type: mongoose_1.SchemaTypes.Mixed, required: true },
15
+ availability: { type: String, required: true },
17
16
  validFrom: { type: Date, required: true },
18
17
  validThrough: { type: Date, required: true },
19
- validForMemberTier: { type: mongoose_1.SchemaTypes.Mixed, required: true }
18
+ // availableAtOrFrom: { type: SchemaTypes.Mixed, required: false },
19
+ validForMemberTier: { type: mongoose_1.SchemaTypes.Mixed, required: false },
20
+ acceptedPaymentMethod: { type: mongoose_1.SchemaTypes.Mixed, required: false }
20
21
  };
21
22
  const schemaOptions = {
22
23
  autoIndex: settings_1.MONGO_AUTO_INDEX,
23
24
  autoCreate: false,
24
- collection: 'offers.event',
25
+ collection: 'productOffers',
25
26
  id: true,
26
27
  read: settings_1.MONGO_READ_PREFERENCE,
27
28
  writeConcern: writeConcern_1.writeConcern,
@@ -46,56 +47,11 @@ const indexes = [
46
47
  [
47
48
  { validFrom: 1 },
48
49
  { name: 'validFrom' }
49
- ],
50
- [
51
- {
52
- 'itemOffered.id': 1,
53
- identifier: 1
54
- },
55
- {
56
- name: 'uniqueByItemOfferedAndIdentifier',
57
- unique: true
58
- }
59
- ],
60
- [
61
- {
62
- 'itemOffered.id': 1,
63
- 'availableAtOrFrom.id': 1,
64
- 'validForMemberTier.identifier': 1
65
- },
66
- {
67
- name: 'uniqueByItemOfferedAndAvailableAt',
68
- unique: true
69
- }
70
- ],
71
- [
72
- { 'project.id': 1, validFrom: 1 },
73
- { name: 'projectId' }
74
- ],
75
- [
76
- { 'seller.id': 1, validFrom: 1 },
77
- { name: 'sellerId' }
78
- ],
79
- [
80
- { identifier: 1, validFrom: 1 },
81
- { name: 'identifier' }
82
- ],
83
- [
84
- { 'itemOffered.id': 1, validFrom: 1 },
85
- { name: 'itemOfferedId' }
86
- ],
87
- [
88
- { 'availableAtOrFrom.id': 1, validFrom: 1 },
89
- { name: 'availableAtOrFromId' }
90
- ],
91
- [
92
- { 'validForMemberTier.identifier': 1, validFrom: 1 },
93
- { name: 'validForMemberTierIdentifier' }
94
50
  ]
95
51
  ];
96
52
  exports.indexes = indexes;
97
53
  /**
98
- * イベントオファー(クライアントごとの有効期間)スキーマ
54
+ * プロダクトオファー(汎用的なオファー設定)スキーマ
99
55
  */
100
56
  let schema;
101
57
  function createSchema() {
@@ -1,7 +1,72 @@
1
- import { Connection } from 'mongoose';
1
+ import type { BulkWriteResult } from 'mongodb';
2
+ import { Connection, FilterQuery } from 'mongoose';
3
+ import * as factory from '../factory';
4
+ import { IDocType } from './mongoose/schemas/productOffer';
5
+ export { IDocType as IProductOffer };
6
+ interface ISearchConditions {
7
+ limit?: number;
8
+ page?: number;
9
+ sort?: {
10
+ validFrom?: factory.sortType;
11
+ };
12
+ project?: {
13
+ id?: {
14
+ $eq?: string;
15
+ };
16
+ };
17
+ itemOffered?: {
18
+ identifier?: {
19
+ $eq?: string;
20
+ };
21
+ };
22
+ validForMemberTier?: {
23
+ identifier?: {
24
+ $eq?: string;
25
+ };
26
+ };
27
+ validFrom?: {
28
+ $lte?: Date;
29
+ };
30
+ validThrough?: {
31
+ $gte?: Date;
32
+ };
33
+ }
34
+ export type ISavingOffer = Pick<IDocType, 'identifier' | 'itemOffered' | 'project' | 'typeOf' | 'validFrom' | 'validThrough' | 'availability' | 'validForMemberTier' | 'acceptedPaymentMethod'> & {
35
+ id?: never;
36
+ };
37
+ type IUnset = {
38
+ [key in keyof IDocType]?: 1;
39
+ };
40
+ type IDocWithId = IDocType & {
41
+ id: string;
42
+ };
43
+ type IKeyOfProjection = keyof IDocType;
2
44
  /**
3
45
  * プロダクトオファーリポジトリ
4
46
  */
5
47
  export declare class ProductOfferRepo {
6
- constructor(__: Connection);
48
+ private readonly productOfferModel;
49
+ constructor(connection: Connection);
50
+ static CREATE_MONGO_CONDITIONS(params: ISearchConditions): FilterQuery<IDocType>[];
51
+ findProductOffers(params: ISearchConditions, inclusion: IKeyOfProjection[]): Promise<IDocWithId[]>;
52
+ /**
53
+ * オファーコードとオファーコレクションコードをキーにして冪等置換
54
+ */
55
+ upsertOffersByIdentifier(params: {
56
+ $set: Pick<IDocType, 'acceptedPaymentMethod' | 'availability' | 'identifier' | 'itemOffered' | 'project' | 'typeOf' | 'validForMemberTier' | 'validFrom' | 'validThrough'> & {
57
+ id?: never;
58
+ };
59
+ $unset: IUnset;
60
+ }[], options: {
61
+ /**
62
+ * falseの場合setOnInsertのみ
63
+ * trueの場合setのみ
64
+ */
65
+ update: boolean;
66
+ }): Promise<{
67
+ bulkWriteResult: BulkWriteResult;
68
+ modifiedNotes: {
69
+ id: string;
70
+ }[];
71
+ } | void>;
7
72
  }
@@ -1,18 +1,159 @@
1
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
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.ProductOfferRepo = void 0;
4
- // import * as factory from '../factory';
5
- // import { MONGO_MAX_TIME_MS } from '../settings';
6
- // import { createSchema, IModel, modelName } from './mongoose/schemas/product';
7
- // type IMatchStage = PipelineStage.Match;
13
+ const factory = require("../factory");
14
+ const settings_1 = require("../settings");
15
+ const productOffer_1 = require("./mongoose/schemas/productOffer");
16
+ const AVAILABLE_PROJECT_FIELDS = [
17
+ 'identifier',
18
+ 'project',
19
+ 'itemOffered',
20
+ 'typeOf',
21
+ 'validFrom',
22
+ 'validThrough',
23
+ 'availability',
24
+ 'acceptedPaymentMethod',
25
+ 'validForMemberTier'
26
+ ];
8
27
  /**
9
28
  * プロダクトオファーリポジトリ
10
29
  */
11
- // tslint:disable-next-line:no-unnecessary-class
12
30
  class ProductOfferRepo {
13
- // private readonly productModel: IModel;
14
- constructor(__) {
15
- // this.productModel = connection.model(modelName, createSchema());
31
+ constructor(connection) {
32
+ this.productOfferModel = connection.model(productOffer_1.modelName, (0, productOffer_1.createSchema)());
33
+ }
34
+ static CREATE_MONGO_CONDITIONS(params) {
35
+ var _a, _b, _c, _d, _e, _f, _g, _h;
36
+ const andConditions = [];
37
+ // const idIn = params.id?.$in;
38
+ // if (Array.isArray(idIn)) {
39
+ // andConditions.push({ _id: { $in: idIn } });
40
+ // }
41
+ const projectIdEq = (_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$eq;
42
+ if (typeof projectIdEq === 'string') {
43
+ andConditions.push({ 'project.id': { $eq: projectIdEq } });
44
+ }
45
+ const itemOfferedIdentifierEq = (_d = (_c = params.itemOffered) === null || _c === void 0 ? void 0 : _c.identifier) === null || _d === void 0 ? void 0 : _d.$eq;
46
+ if (typeof itemOfferedIdentifierEq === 'string') {
47
+ andConditions.push({ 'itemOffered.identifier': { $eq: itemOfferedIdentifierEq } });
48
+ }
49
+ const validForMemberTierIdentifierEq = (_f = (_e = params.validForMemberTier) === null || _e === void 0 ? void 0 : _e.identifier) === null || _f === void 0 ? void 0 : _f.$eq;
50
+ if (typeof validForMemberTierIdentifierEq === 'string') {
51
+ andConditions.push({ 'validForMemberTier.identifier': { $exists: true, $eq: validForMemberTierIdentifierEq } });
52
+ }
53
+ const validFromLte = (_g = params.validFrom) === null || _g === void 0 ? void 0 : _g.$lte;
54
+ if (validFromLte instanceof Date) {
55
+ andConditions.push({ validFrom: { $lte: validFromLte } });
56
+ }
57
+ const validThroughGte = (_h = params.validThrough) === null || _h === void 0 ? void 0 : _h.$gte;
58
+ if (validThroughGte instanceof Date) {
59
+ andConditions.push({ validThrough: { $gte: validThroughGte } });
60
+ }
61
+ return andConditions;
62
+ }
63
+ findProductOffers(params, inclusion) {
64
+ return __awaiter(this, void 0, void 0, function* () {
65
+ var _a;
66
+ const conditions = ProductOfferRepo.CREATE_MONGO_CONDITIONS(params);
67
+ let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
68
+ if (Array.isArray(inclusion) && inclusion.length > 0) {
69
+ positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
70
+ }
71
+ else {
72
+ throw new factory.errors.ArgumentNull('inclusion', 'inclusion must be specified');
73
+ }
74
+ const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
75
+ const query = this.productOfferModel.find((conditions.length > 0) ? { $and: conditions } : {}, projection);
76
+ if (typeof ((_a = params.sort) === null || _a === void 0 ? void 0 : _a.validFrom) === 'number') {
77
+ query.sort({ validFrom: params.sort.validFrom });
78
+ }
79
+ if (typeof params.limit === 'number' && params.limit > 0) {
80
+ const page = (typeof params.page === 'number' && params.page > 0) ? params.page : 1;
81
+ query.limit(params.limit)
82
+ .skip(params.limit * (page - 1));
83
+ }
84
+ return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
85
+ .lean()
86
+ .exec();
87
+ });
88
+ }
89
+ /**
90
+ * オファーコードとオファーコレクションコードをキーにして冪等置換
91
+ */
92
+ upsertOffersByIdentifier(params, options) {
93
+ return __awaiter(this, void 0, void 0, function* () {
94
+ const { update } = options;
95
+ const bulkWriteOps = [];
96
+ const queryFilters = [];
97
+ if (Array.isArray(params)) {
98
+ params.forEach(({ $set, $unset }) => {
99
+ const { availability, identifier, itemOffered, project, validFrom, validThrough, acceptedPaymentMethod, validForMemberTier } = $set;
100
+ if (typeof identifier !== 'string' || identifier === '') {
101
+ throw new factory.errors.ArgumentNull('identifier');
102
+ }
103
+ if (typeof itemOffered.identifier !== 'string' || itemOffered.identifier === '') {
104
+ throw new factory.errors.ArgumentNull('itemOffered.identifier');
105
+ }
106
+ // リソースのユニークネスを保証するfilter
107
+ const filter = {
108
+ 'project.id': { $eq: project.id },
109
+ 'itemOffered.identifier': { $eq: itemOffered.identifier },
110
+ identifier: { $eq: identifier }
111
+ };
112
+ queryFilters.push({
113
+ 'project.id': { $eq: project.id },
114
+ 'itemOffered.identifier': { $eq: itemOffered.identifier },
115
+ identifier: { $eq: identifier }
116
+ });
117
+ if (update === true) {
118
+ const setFields = Object.assign(Object.assign({ availability,
119
+ validFrom,
120
+ validThrough }, (typeof (acceptedPaymentMethod === null || acceptedPaymentMethod === void 0 ? void 0 : acceptedPaymentMethod.typeOf) === 'string') ? { acceptedPaymentMethod } : undefined), (typeof (validForMemberTier === null || validForMemberTier === void 0 ? void 0 : validForMemberTier.typeOf) === 'string') ? { validForMemberTier } : undefined);
121
+ const updateFilter = Object.assign({ $set: setFields }, ($unset !== undefined) ? { $unset } : undefined);
122
+ const updateOne = {
123
+ filter,
124
+ update: updateFilter,
125
+ upsert: false
126
+ };
127
+ bulkWriteOps.push({ updateOne });
128
+ }
129
+ else {
130
+ const setOnInsert = Object.assign(Object.assign({ itemOffered, identifier, project, typeOf: factory.offerType.Offer, availability,
131
+ validFrom,
132
+ validThrough }, (typeof (acceptedPaymentMethod === null || acceptedPaymentMethod === void 0 ? void 0 : acceptedPaymentMethod.typeOf) === 'string') ? { acceptedPaymentMethod } : undefined), (typeof (validForMemberTier === null || validForMemberTier === void 0 ? void 0 : validForMemberTier.typeOf) === 'string') ? { validForMemberTier } : undefined);
133
+ const updateFilter = {
134
+ $setOnInsert: setOnInsert
135
+ };
136
+ const updateOne = {
137
+ filter,
138
+ update: updateFilter,
139
+ upsert: true
140
+ };
141
+ bulkWriteOps.push({ updateOne });
142
+ }
143
+ });
144
+ }
145
+ if (bulkWriteOps.length > 0) {
146
+ const bulkWriteResult = yield this.productOfferModel.bulkWrite(bulkWriteOps, { ordered: false });
147
+ // modifiedの場合upsertedIdsに含まれないので、idを検索する
148
+ const modifiedNotes = yield this.productOfferModel.find({ $or: queryFilters }, {
149
+ _id: 0,
150
+ id: { $toString: '$_id' }
151
+ })
152
+ .lean()
153
+ .exec();
154
+ return { bulkWriteResult, modifiedNotes };
155
+ }
156
+ });
16
157
  }
17
158
  }
18
159
  exports.ProductOfferRepo = ProductOfferRepo;
@@ -34,7 +34,6 @@ import type { MerchantReturnPolicyRepo } from './repo/merchantReturnPolicy';
34
34
  import type { MessageRepo } from './repo/message';
35
35
  import type { NoteRepo } from './repo/note';
36
36
  import type { NoteAboutOrderRepo } from './repo/noteAboutOrder';
37
- import type { EventOfferRepo } from './repo/offer/event';
38
37
  import type { OfferRepo } from './repo/offer/unitPriceInCatalog';
39
38
  import type { OfferCatalogRepo } from './repo/offerCatalog';
40
39
  import type { OfferCatalogItemRepo } from './repo/offerCatalogItem';
@@ -180,10 +179,6 @@ export type Event = EventRepo;
180
179
  export declare namespace Event {
181
180
  function createInstance(...params: ConstructorParameters<typeof EventRepo>): Promise<EventRepo>;
182
181
  }
183
- export type EventOffer = EventOfferRepo;
184
- export declare namespace EventOffer {
185
- function createInstance(...params: ConstructorParameters<typeof EventOfferRepo>): Promise<EventOfferRepo>;
186
- }
187
182
  export type EventSellerMakesOffer = EventSellerMakesOfferRepo;
188
183
  export declare namespace EventSellerMakesOffer {
189
184
  function createInstance(...params: ConstructorParameters<typeof EventSellerMakesOfferRepo>): Promise<EventSellerMakesOfferRepo>;
@@ -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.Person = exports.paymentMethod = exports.PendingReservation = exports.PaymentServiceProvider = exports.PaymentServiceChannel = exports.PaymentService = exports.Passport = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.NoteAboutOrder = exports.Note = exports.Message = exports.MerchantReturnPolicy = exports.MemberProgram = exports.Member = exports.Issuer = exports.IdentityProvider = exports.Identity = exports.EventSeries = exports.EventSellerMakesOffer = exports.EventOffer = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.Credentials = exports.CreativeWork = exports.ConfirmationNumber = exports.Comment = exports.Authorization = exports.CategoryCode = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOrder = exports.AggregateOffer = exports.AdvanceBookingRequirement = exports.AdditionalProperty = exports.Action = exports.AccountTransaction = exports.AccountTitle = exports.AccountingReport = exports.Account = exports.AcceptedOffer = void 0;
13
- exports.WebSite = exports.rateLimit = exports.Trip = exports.TransactionProcess = exports.TransactionNumber = exports.Transaction = exports.Ticket = exports.Telemetry = exports.Task = exports.StockHolder = exports.setting = exports.Setting = exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.ServiceAvailableHour = exports.SellerReturnPolicy = exports.SellerPaymentAccepted = exports.SellerMakesOffer = exports.Seller = exports.Schedule = exports.Role = exports.ReserveInterface = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.ProductModel = exports.Product = exports.PriceSpecification = exports.PotentialAction = exports.place = exports.Permit = void 0;
12
+ exports.Permit = exports.Person = exports.paymentMethod = exports.PendingReservation = exports.PaymentServiceProvider = exports.PaymentServiceChannel = exports.PaymentService = exports.Passport = exports.OwnershipInfo = exports.OrderNumber = exports.OrderInTransaction = exports.Order = exports.Offer = exports.OfferItemCondition = exports.OfferCatalogItem = exports.OfferCatalog = exports.NoteAboutOrder = exports.Note = exports.Message = exports.MerchantReturnPolicy = exports.MemberProgram = exports.Member = exports.Issuer = exports.IdentityProvider = exports.Identity = exports.EventSeries = exports.EventSellerMakesOffer = exports.Event = exports.EmailMessage = exports.CustomerType = exports.Customer = exports.Credentials = exports.CreativeWork = exports.ConfirmationNumber = exports.Comment = exports.Authorization = exports.CategoryCode = exports.AssetTransaction = exports.Aggregation = exports.AggregateReservation = exports.AggregateOrder = exports.AggregateOffer = exports.AdvanceBookingRequirement = exports.AdditionalProperty = exports.Action = exports.AccountTransaction = exports.AccountTitle = exports.AccountingReport = exports.Account = exports.AcceptedOffer = void 0;
13
+ exports.WebSite = exports.rateLimit = exports.Trip = exports.TransactionProcess = exports.TransactionNumber = exports.Transaction = exports.Ticket = exports.Telemetry = exports.Task = exports.StockHolder = exports.setting = exports.Setting = exports.ServiceOutputIdentifier = exports.ServiceOutput = exports.ServiceAvailableHour = exports.SellerReturnPolicy = exports.SellerPaymentAccepted = exports.SellerMakesOffer = exports.Seller = exports.Schedule = exports.Role = exports.ReserveInterface = exports.Reservation = exports.ProjectMakesOffer = exports.Project = exports.ProductOffer = exports.ProductModel = exports.Product = exports.PriceSpecification = exports.PotentialAction = exports.place = void 0;
14
14
  var AcceptedOffer;
15
15
  (function (AcceptedOffer) {
16
16
  let repo;
@@ -310,19 +310,6 @@ var Event;
310
310
  }
311
311
  Event.createInstance = createInstance;
312
312
  })(Event || (exports.Event = Event = {}));
313
- var EventOffer;
314
- (function (EventOffer) {
315
- let repo;
316
- function createInstance(...params) {
317
- return __awaiter(this, void 0, void 0, function* () {
318
- if (repo === undefined) {
319
- repo = (yield Promise.resolve().then(() => require('./repo/offer/event'))).EventOfferRepo;
320
- }
321
- return new repo(...params);
322
- });
323
- }
324
- EventOffer.createInstance = createInstance;
325
- })(EventOffer || (exports.EventOffer = EventOffer = {}));
326
313
  var EventSellerMakesOffer;
327
314
  (function (EventSellerMakesOffer) {
328
315
  let repo;
@@ -6,7 +6,6 @@ import type { EventRepo } from '../../../repo/event';
6
6
  import type { EventSeriesRepo } from '../../../repo/eventSeries';
7
7
  import type { IssuerRepo } from '../../../repo/issuer';
8
8
  import type { MemberProgramRepo } from '../../../repo/memberProgram';
9
- import type { EventOfferRepo } from '../../../repo/offer/event';
10
9
  import type { OfferRepo } from '../../../repo/offer/unitPriceInCatalog';
11
10
  import type { OfferCatalogRepo } from '../../../repo/offerCatalog';
12
11
  import type { OfferCatalogItemRepo } from '../../../repo/offerCatalogItem';
@@ -14,6 +13,7 @@ import type { PaymentServiceRepo } from '../../../repo/paymentService';
14
13
  import { SeatRepo } from '../../../repo/place/seat';
15
14
  import type { PriceSpecificationRepo } from '../../../repo/priceSpecification';
16
15
  import type { ProductRepo } from '../../../repo/product';
16
+ import type { ProductOfferRepo } from '../../../repo/productOffer';
17
17
  import type { ProjectRepo } from '../../../repo/project';
18
18
  import type { OfferRateLimitRepo } from '../../../repo/rateLimit/offer';
19
19
  import type { SettingRepo } from '../../../repo/setting';
@@ -23,7 +23,6 @@ interface IStartOperationRepos {
23
23
  advanceBookingRequirement: AdvanceBookingRequirementRepo;
24
24
  stockHolder: StockHolderRepo;
25
25
  event: EventRepo;
26
- eventOffer: EventOfferRepo;
27
26
  eventSeries: EventSeriesRepo;
28
27
  issuer: IssuerRepo;
29
28
  memberProgram: MemberProgramRepo;
@@ -33,6 +32,7 @@ interface IStartOperationRepos {
33
32
  offerRateLimit: OfferRateLimitRepo;
34
33
  paymentService: PaymentServiceRepo;
35
34
  product: ProductRepo;
35
+ productOffer: ProductOfferRepo;
36
36
  priceSpecification: PriceSpecificationRepo;
37
37
  project: ProjectRepo;
38
38
  seat: SeatRepo;
@@ -47,9 +47,9 @@ function start(params, options) {
47
47
  now,
48
48
  store: { id: (_a = params.availableAtOrFrom) === null || _a === void 0 ? void 0 : _a.id }
49
49
  })({
50
- eventOffer: repos.eventOffer,
51
50
  issuer: repos.issuer,
52
- memberProgram: repos.memberProgram
51
+ memberProgram: repos.memberProgram,
52
+ productOffer: repos.productOffer
53
53
  });
54
54
  // objectに必要な情報をそろえる
55
55
  const { acceptedOffers4transactionObject, objectSubReservations } = yield createObjectAttributes({
@@ -2,7 +2,7 @@ import * as factory from '../../../factory';
2
2
  import { IMinimizedIndividualEvent } from '../../../factory/event';
3
3
  import type { IssuerRepo } from '../../../repo/issuer';
4
4
  import type { MemberProgramRepo } from '../../../repo/memberProgram';
5
- import type { EventOfferRepo } from '../../../repo/offer/event';
5
+ import type { ProductOfferRepo } from '../../../repo/productOffer';
6
6
  declare function validateStartRequest(params: {
7
7
  object: factory.assetTransaction.reserve.IObjectWithoutDetail;
8
8
  event: Pick<IMinimizedIndividualEvent<factory.eventType.Event | factory.eventType.ScreeningEvent>, 'offers' | 'id' | 'project'>;
@@ -16,8 +16,8 @@ declare function validateStartRequest(params: {
16
16
  id?: string;
17
17
  };
18
18
  }): (repos: {
19
- eventOffer: EventOfferRepo;
20
19
  issuer: IssuerRepo;
21
20
  memberProgram: MemberProgramRepo;
21
+ productOffer: ProductOfferRepo;
22
22
  }) => Promise<void>;
23
23
  export { validateStartRequest };
@@ -13,7 +13,6 @@ exports.validateStartRequest = validateStartRequest;
13
13
  const jwt = require("jsonwebtoken");
14
14
  const moment = require("moment");
15
15
  const factory = require("../../../factory");
16
- const ROLE_DATE_FORMAT = 'YYYY-MM-DDTHH:mm:ssZ';
17
16
  function verifyOfferedByToken(params) {
18
17
  return __awaiter(this, void 0, void 0, function* () {
19
18
  let result;
@@ -67,7 +66,7 @@ function validateStartRequest(params) {
67
66
  function validateMemberTier(params) {
68
67
  return (repos) => __awaiter(this, void 0, void 0, function* () {
69
68
  var _a, _b, _c, _d, _e;
70
- const { acceptedDate, event, availableAt, verifiedValidForMemberTier, memberProgramIdentifierMustBe } = params;
69
+ const { acceptedDate, event, verifiedValidForMemberTier, memberProgramIdentifierMustBe, aggregateOfferIdentifier } = params;
71
70
  const tierIdentifier = (_b = (_a = verifiedValidForMemberTier.member) === null || _a === void 0 ? void 0 : _a.memberOf) === null || _b === void 0 ? void 0 : _b.identifier;
72
71
  const memberProgramIdentifier = (_e = (_d = (_c = verifiedValidForMemberTier.member) === null || _c === void 0 ? void 0 : _c.memberOf) === null || _d === void 0 ? void 0 : _d.isTierOf) === null || _e === void 0 ? void 0 : _e.identifier;
73
72
  if (typeof tierIdentifier !== 'string') {
@@ -79,28 +78,36 @@ function validateMemberTier(params) {
79
78
  if (memberProgramIdentifier !== memberProgramIdentifierMustBe) {
80
79
  throw new factory.errors.Argument('reservationFor.offers.validForMemberTier', 'member program not matched');
81
80
  }
82
- // イベントオファーを検索して有効期間検証
83
- const eventOfferForMemberTier = (yield repos.eventOffer.projectFields({
81
+ // 有効なプロダクトオファーを検証
82
+ const productOfferForMemberTier = (yield repos.productOffer.findProductOffers({
84
83
  limit: 1,
85
84
  page: 1,
86
85
  project: { id: { $eq: event.project.id } },
87
- availableAtOrFrom: { id: { $eq: availableAt.id } },
88
- itemOffered: { id: { $eq: event.id } },
89
- validForMemberTier: { identifier: { $eq: tierIdentifier } }
90
- }, ['validFrom', 'validThrough'])).shift();
91
- if (eventOfferForMemberTier === undefined) {
92
- throw new factory.errors.NotFound(factory.offerType.Offer, 'event offer for member tier not found');
93
- }
94
- let validThroughMoment;
95
- let validFromMoment;
96
- validThroughMoment = moment(eventOfferForMemberTier.validThrough, ROLE_DATE_FORMAT, true);
97
- validFromMoment = moment(eventOfferForMemberTier.validFrom, ROLE_DATE_FORMAT, true);
98
- if (acceptedDate.isBefore(validFromMoment)) {
99
- throw new factory.errors.Argument('reservationFor.offers.validForMemberTier', `the offer id valid from ${validFromMoment}`);
100
- }
101
- if (acceptedDate.isAfter(validThroughMoment)) {
102
- throw new factory.errors.Argument('reservationFor.offers.validForMemberTier', `the offer id valid through ${validThroughMoment}`);
86
+ // availableAtOrFrom: { id: { $eq: availableAt.id } },
87
+ itemOffered: { identifier: { $eq: aggregateOfferIdentifier } }, // オファーコレクションコード
88
+ validForMemberTier: { identifier: { $eq: tierIdentifier } },
89
+ validFrom: { $lte: acceptedDate.toDate() },
90
+ validThrough: { $gte: acceptedDate.toDate() }
91
+ }, ['identifier'])).shift();
92
+ if (productOfferForMemberTier === undefined) {
93
+ throw new factory.errors.NotFound(factory.offerType.Offer, 'product offer for member tier not found');
103
94
  }
95
+ // let validThroughMoment: moment.Moment;
96
+ // let validFromMoment: moment.Moment;
97
+ // validThroughMoment = moment(productOfferForMemberTier.validThrough, ROLE_DATE_FORMAT, true);
98
+ // validFromMoment = moment(productOfferForMemberTier.validFrom, ROLE_DATE_FORMAT, true);
99
+ // if (acceptedDate.isBefore(validFromMoment)) {
100
+ // throw new factory.errors.Argument(
101
+ // 'reservationFor.offers.validForMemberTier',
102
+ // `the offer id valid from ${validFromMoment}`
103
+ // );
104
+ // }
105
+ // if (acceptedDate.isAfter(validThroughMoment)) {
106
+ // throw new factory.errors.Argument(
107
+ // 'reservationFor.offers.validForMemberTier',
108
+ // `the offer id valid through ${validThroughMoment}`
109
+ // );
110
+ // }
104
111
  });
105
112
  }
106
113
  /**
@@ -116,11 +123,11 @@ function validateEventOfferPeriod(params) {
116
123
  const makesOfferOnApplication = eventOffers === null || eventOffers === void 0 ? void 0 : eventOffers.seller.makesOffer.find((offer) => {
117
124
  var _a, _b;
118
125
  // support non-array(2024-10-11~)
119
- return (Array.isArray(offer.availableAtOrFrom) && ((_a = offer.availableAtOrFrom.at(0)) === null || _a === void 0 ? void 0 : _a.id) === params.availableAt.id)
120
- || (!Array.isArray(offer.availableAtOrFrom) && ((_b = offer.availableAtOrFrom) === null || _b === void 0 ? void 0 : _b.id) === params.availableAt.id);
126
+ return (Array.isArray(offer.availableAtOrFrom) && ((_a = offer.availableAtOrFrom.at(0)) === null || _a === void 0 ? void 0 : _a.id) === availableAt.id)
127
+ || (!Array.isArray(offer.availableAtOrFrom) && ((_b = offer.availableAtOrFrom) === null || _b === void 0 ? void 0 : _b.id) === availableAt.id);
121
128
  });
122
129
  if (makesOfferOnApplication === undefined) {
123
- throw new factory.errors.Argument('reservationFor.id', `seller makes no available offer at ${params.availableAt.id}`);
130
+ throw new factory.errors.Argument('reservationFor.id', `seller makes no available offer at ${availableAt.id}`);
124
131
  }
125
132
  const validFrom = makesOfferOnApplication.validFrom;
126
133
  const validThrough = makesOfferOnApplication.validThrough;
@@ -137,37 +144,45 @@ function validateEventOfferPeriod(params) {
137
144
  }
138
145
  }
139
146
  // support validForMemberTier(2025-05-14~)
140
- const memberProgramIdentifierMustBe = (_b = (_a = makesOfferOnApplication.validForMemberTier) === null || _a === void 0 ? void 0 : _a.isTierOf) === null || _b === void 0 ? void 0 : _b.identifier;
141
- if (typeof memberProgramIdentifierMustBe === 'string') {
142
- if (typeof validForMemberTierToken !== 'string' || validForMemberTierToken === '') {
143
- throw new factory.errors.ArgumentNull('reservationFor.offers.validForMemberTier');
144
- }
145
- // トークン検証
146
- const memberProgram = (yield repos.memberProgram.projectMemberPrograms({
147
- limit: 1,
148
- page: 1,
149
- project: { id: { $eq: params.event.project.id } },
150
- identifier: { $eq: memberProgramIdentifierMustBe }
151
- })).shift();
152
- if (memberProgram === undefined) {
153
- throw new factory.errors.NotFound('MemberProgram');
154
- }
155
- const issuer = yield repos.issuer.findByIdentifier({
156
- project: { id: params.event.project.id },
157
- identifier: memberProgram.hostingOrganization.identifier
158
- });
159
- if (typeof issuer.tokenSecret !== 'string' || issuer.tokenSecret === '') {
160
- throw new factory.errors.NotFound('issuer.tokenSecret');
147
+ if (makesOfferOnApplication.typeOf === factory.offerType.AggregateOffer) {
148
+ const memberProgramIdentifierMustBe = (_b = (_a = makesOfferOnApplication.validForMemberTier) === null || _a === void 0 ? void 0 : _a.isTierOf) === null || _b === void 0 ? void 0 : _b.identifier;
149
+ if (typeof memberProgramIdentifierMustBe === 'string') {
150
+ // 有効メンバープログラムティアが存在する場合、ティアトークンが必須
151
+ if (typeof validForMemberTierToken !== 'string' || validForMemberTierToken === '') {
152
+ throw new factory.errors.ArgumentNull('reservationFor.offers.validForMemberTier');
153
+ }
154
+ // 有効メンバープログラムティアが存在する場合、オファーコレクションコードが必須
155
+ const aggregateOfferIdentifier = makesOfferOnApplication.identifier;
156
+ if (typeof aggregateOfferIdentifier !== 'string' || aggregateOfferIdentifier === '') {
157
+ throw new factory.errors.NotFound('makesOfferOnApplication.identifier');
158
+ }
159
+ // トークン検証
160
+ const memberProgram = (yield repos.memberProgram.projectMemberPrograms({
161
+ limit: 1,
162
+ page: 1,
163
+ project: { id: { $eq: params.event.project.id } },
164
+ identifier: { $eq: memberProgramIdentifierMustBe }
165
+ })).shift();
166
+ if (memberProgram === undefined) {
167
+ throw new factory.errors.NotFound('MemberProgram');
168
+ }
169
+ const issuer = yield repos.issuer.findByIdentifier({
170
+ project: { id: params.event.project.id },
171
+ identifier: memberProgram.hostingOrganization.identifier
172
+ });
173
+ if (typeof issuer.tokenSecret !== 'string' || issuer.tokenSecret === '') {
174
+ throw new factory.errors.NotFound('issuer.tokenSecret');
175
+ }
176
+ const verifiedValidForMemberTier = yield verifyOfferedByToken({
177
+ secret: issuer.tokenSecret,
178
+ issuer: issuer.url,
179
+ token: validForMemberTierToken
180
+ });
181
+ yield validateMemberTier({
182
+ event, acceptedDate, verifiedValidForMemberTier,
183
+ memberProgramIdentifierMustBe, aggregateOfferIdentifier
184
+ })(repos);
161
185
  }
162
- const verifiedValidForMemberTier = yield verifyOfferedByToken({
163
- secret: issuer.tokenSecret,
164
- issuer: issuer.url,
165
- token: validForMemberTierToken
166
- });
167
- yield validateMemberTier({
168
- event, availableAt, acceptedDate, verifiedValidForMemberTier,
169
- memberProgramIdentifierMustBe
170
- })(repos);
171
186
  }
172
187
  });
173
188
  }
@@ -8,7 +8,6 @@ import type { EventRepo, IMinimizedIndividualEvent } from '../../../../repo/even
8
8
  import { EventSeriesRepo } from '../../../../repo/eventSeries';
9
9
  import type { IssuerRepo } from '../../../../repo/issuer';
10
10
  import type { MemberProgramRepo } from '../../../../repo/memberProgram';
11
- import type { EventOfferRepo } from '../../../../repo/offer/event';
12
11
  import type { OfferRepo } from '../../../../repo/offer/unitPriceInCatalog';
13
12
  import type { OfferCatalogRepo } from '../../../../repo/offerCatalog';
14
13
  import type { OfferCatalogItemRepo } from '../../../../repo/offerCatalogItem';
@@ -16,6 +15,7 @@ import type { PaymentServiceRepo } from '../../../../repo/paymentService';
16
15
  import type { SeatRepo } from '../../../../repo/place/seat';
17
16
  import type { PriceSpecificationRepo } from '../../../../repo/priceSpecification';
18
17
  import type { ProductRepo } from '../../../../repo/product';
18
+ import type { ProductOfferRepo } from '../../../../repo/productOffer';
19
19
  import type { ProjectRepo } from '../../../../repo/project';
20
20
  import type { OfferRateLimitRepo } from '../../../../repo/rateLimit/offer';
21
21
  import type { SettingRepo } from '../../../../repo/setting';
@@ -52,7 +52,6 @@ declare function processStartReserve4chevre(params: {
52
52
  authorization: AuthorizationRepo;
53
53
  stockHolder: StockHolderRepo;
54
54
  event: EventRepo;
55
- eventOffer: EventOfferRepo;
56
55
  eventSeries: EventSeriesRepo;
57
56
  issuer: IssuerRepo;
58
57
  memberProgram: MemberProgramRepo;
@@ -62,6 +61,7 @@ declare function processStartReserve4chevre(params: {
62
61
  offerRateLimit: OfferRateLimitRepo;
63
62
  paymentService: PaymentServiceRepo;
64
63
  product: ProductRepo;
64
+ productOffer: ProductOfferRepo;
65
65
  priceSpecification: PriceSpecificationRepo;
66
66
  project: ProjectRepo;
67
67
  seat: SeatRepo;
@@ -8,7 +8,6 @@ import type { EventRepo } from '../../../repo/event';
8
8
  import { EventSeriesRepo } from '../../../repo/eventSeries';
9
9
  import type { IssuerRepo } from '../../../repo/issuer';
10
10
  import type { MemberProgramRepo } from '../../../repo/memberProgram';
11
- import type { EventOfferRepo } from '../../../repo/offer/event';
12
11
  import type { OfferRepo } from '../../../repo/offer/unitPriceInCatalog';
13
12
  import type { OfferCatalogRepo } from '../../../repo/offerCatalog';
14
13
  import type { OfferCatalogItemRepo } from '../../../repo/offerCatalogItem';
@@ -18,6 +17,7 @@ import type { PaymentServiceRepo } from '../../../repo/paymentService';
18
17
  import type { SeatRepo } from '../../../repo/place/seat';
19
18
  import type { PriceSpecificationRepo } from '../../../repo/priceSpecification';
20
19
  import type { ProductRepo } from '../../../repo/product';
20
+ import type { ProductOfferRepo } from '../../../repo/productOffer';
21
21
  import type { ProjectRepo } from '../../../repo/project';
22
22
  import type { OfferRateLimitRepo } from '../../../repo/rateLimit/offer';
23
23
  import type { SettingRepo } from '../../../repo/setting';
@@ -32,7 +32,6 @@ interface IAuthorizeRepos {
32
32
  assetTransaction: AssetTransactionRepo;
33
33
  authorization: AuthorizationRepo;
34
34
  event: EventRepo;
35
- eventOffer: EventOfferRepo;
36
35
  eventSeries: EventSeriesRepo;
37
36
  issuer: IssuerRepo;
38
37
  memberProgram: MemberProgramRepo;
@@ -46,6 +45,7 @@ interface IAuthorizeRepos {
46
45
  paymentService: PaymentServiceRepo;
47
46
  priceSpecification: PriceSpecificationRepo;
48
47
  product: ProductRepo;
48
+ productOffer: ProductOfferRepo;
49
49
  project: ProjectRepo;
50
50
  seat: SeatRepo;
51
51
  setting: SettingRepo;
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "dependencies": {
12
12
  "@aws-sdk/client-cognito-identity-provider": "3.600.0",
13
13
  "@aws-sdk/credential-providers": "3.600.0",
14
- "@chevre/factory": "4.399.0-alpha.16",
14
+ "@chevre/factory": "4.399.0-alpha.17",
15
15
  "@cinerino/sdk": "12.2.0",
16
16
  "@motionpicture/coa-service": "9.6.0",
17
17
  "@motionpicture/gmo-service": "5.4.0-alpha.1",
@@ -115,5 +115,5 @@
115
115
  "postversion": "git push origin --tags",
116
116
  "prepublishOnly": "npm run clean && npm run build && npm test && npm run doc"
117
117
  },
118
- "version": "22.14.0-alpha.16"
118
+ "version": "22.14.0-alpha.17"
119
119
  }
@@ -1,67 +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
- const IDENTIFIER = 'xxx';
8
-
9
- async function main() {
10
- await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
11
-
12
- // const eventRepo = await chevre.repository.Event.createInstance(mongoose.connection);
13
- const eventOfferRepo = await chevre.repository.EventOffer.createInstance(mongoose.connection);
14
-
15
- let docs = await eventOfferRepo.projectFields(
16
- {
17
- project: { id: { $eq: project.id } },
18
- identifier: { $eq: IDENTIFIER }
19
- },
20
- ['availableAtOrFrom', 'identifier', 'itemOffered', 'project', 'validFrom']
21
- );
22
- console.log('docs:', docs);
23
- console.log(docs.length, 'docs found');
24
-
25
- if (docs.length > 0) {
26
- await eventOfferRepo.deleteById({
27
- project: { id: docs[0].project.id },
28
- id: docs[0].id
29
- });
30
- console.log('deleted', docs[0].id);
31
- }
32
-
33
- await eventOfferRepo.save({
34
- attributes: {
35
- identifier: IDENTIFIER,
36
- project: { id: project.id, typeOf: chevre.factory.organizationType.Project },
37
- typeOf: chevre.factory.offerType.Offer,
38
- itemOffered: {
39
- id: 'xxxxx',
40
- typeOf: chevre.factory.eventType.ScreeningEvent
41
- },
42
- seller: {
43
- id: 'xxxxx',
44
- typeOf: chevre.factory.organizationType.Organization
45
- },
46
- availableAtOrFrom: { id: 'xxx' },
47
- validFrom: new Date(),
48
- validThrough: new Date(),
49
- validForMemberTier: { identifier: 'xxx', typeOf: 'MemberProgramTier' }
50
- }
51
- });
52
- console.log('created.');
53
-
54
- docs = await await eventOfferRepo.projectFields(
55
- {
56
- project: { id: { $eq: project.id } },
57
- identifier: { $eq: IDENTIFIER }
58
- },
59
- ['availableAtOrFrom', 'identifier', 'itemOffered', 'project', 'validFrom']
60
- );
61
- console.log('docs:', docs);
62
- console.log(docs.length, 'docs found');
63
- }
64
-
65
- main()
66
- .then()
67
- .catch(console.error);
@@ -1,10 +0,0 @@
1
- import { IndexDefinition, IndexOptions, Model, Schema, SchemaDefinition } from 'mongoose';
2
- import * as factory from '../../../../factory';
3
- type IDocType = factory.eventOffer.IEventOfferForMemberTier;
4
- type IModel = Model<IDocType>;
5
- type ISchemaDefinition = SchemaDefinition<IDocType>;
6
- type ISchema = Schema<IDocType, IModel, {}, {}, {}, {}, ISchemaDefinition, IDocType>;
7
- declare const modelName = "Offer.Event";
8
- declare const indexes: [d: IndexDefinition, o: IndexOptions][];
9
- declare function createSchema(): ISchema;
10
- export { createSchema, IDocType, IModel, indexes, modelName };
@@ -1,38 +0,0 @@
1
- import { Connection, FilterQuery } from 'mongoose';
2
- import * as factory from '../../factory';
3
- import { IDocType } from '../mongoose/schemas/offer/event';
4
- type ISearchConditions = factory.eventOffer.ISearchConditions;
5
- export type ISavingOffer = Pick<IDocType, 'availableAtOrFrom' | 'identifier' | 'itemOffered' | 'project' | 'seller' | 'typeOf' | 'validForMemberTier' | 'validFrom' | 'validThrough'> & {
6
- id?: never;
7
- };
8
- interface IUnset {
9
- $unset?: {
10
- [key: string]: 1;
11
- };
12
- }
13
- type IDocWithId = IDocType & {
14
- id: string;
15
- };
16
- type IKeyOfProjection = keyof IDocType;
17
- /**
18
- * イベントオファーリポジトリ
19
- */
20
- export declare class EventOfferRepo {
21
- private readonly eventOfferModel;
22
- constructor(connection: Connection);
23
- static CREATE_FILTER_QUERY(params: ISearchConditions): FilterQuery<IDocType>[];
24
- save(params: {
25
- id?: string;
26
- attributes: ISavingOffer & IUnset;
27
- }): Promise<{
28
- id: string;
29
- }>;
30
- projectFields(conditions: ISearchConditions, inclusion: IKeyOfProjection[]): Promise<IDocWithId[]>;
31
- deleteById(params: {
32
- id: string;
33
- project: {
34
- id: string;
35
- };
36
- }): Promise<void>;
37
- }
38
- export {};
@@ -1,142 +0,0 @@
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
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.EventOfferRepo = void 0;
24
- const factory = require("../../factory");
25
- const settings_1 = require("../../settings");
26
- const event_1 = require("../mongoose/schemas/offer/event");
27
- /**
28
- * イベントオファーリポジトリ
29
- */
30
- class EventOfferRepo {
31
- constructor(connection) {
32
- this.eventOfferModel = connection.model(event_1.modelName, (0, event_1.createSchema)());
33
- }
34
- // tslint:disable-next-line:max-func-body-length
35
- static CREATE_FILTER_QUERY(params) {
36
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
37
- const andConditions = [];
38
- const projectIdEq = (_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$eq;
39
- if (typeof projectIdEq === 'string') {
40
- andConditions.push({ 'project.id': { $eq: projectIdEq } });
41
- }
42
- const idEq = (_c = params.id) === null || _c === void 0 ? void 0 : _c.$eq;
43
- if (typeof idEq === 'string') {
44
- andConditions.push({ _id: { $eq: idEq } });
45
- }
46
- const idIn = (_d = params.id) === null || _d === void 0 ? void 0 : _d.$in;
47
- if (Array.isArray(idIn)) {
48
- andConditions.push({ _id: { $in: idIn } });
49
- }
50
- const identifierEq = (_e = params.identifier) === null || _e === void 0 ? void 0 : _e.$eq;
51
- if (typeof identifierEq === 'string') {
52
- andConditions.push({ identifier: { $eq: identifierEq } });
53
- }
54
- const sellerIdEq = (_g = (_f = params.seller) === null || _f === void 0 ? void 0 : _f.id) === null || _g === void 0 ? void 0 : _g.$eq;
55
- if (typeof sellerIdEq === 'string') {
56
- andConditions.push({ 'seller.id': { $eq: sellerIdEq } });
57
- }
58
- const itemOfferedIdEq = (_j = (_h = params.itemOffered) === null || _h === void 0 ? void 0 : _h.id) === null || _j === void 0 ? void 0 : _j.$eq;
59
- if (typeof itemOfferedIdEq === 'string') {
60
- andConditions.push({ 'itemOffered.id': { $eq: itemOfferedIdEq } });
61
- }
62
- const availableAtOrFromIdEq = (_l = (_k = params.availableAtOrFrom) === null || _k === void 0 ? void 0 : _k.id) === null || _l === void 0 ? void 0 : _l.$eq;
63
- if (typeof availableAtOrFromIdEq === 'string') {
64
- andConditions.push({ 'availableAtOrFrom.id': { $eq: availableAtOrFromIdEq } });
65
- }
66
- const validForMemberTierIdentifierEq = (_o = (_m = params.validForMemberTier) === null || _m === void 0 ? void 0 : _m.identifier) === null || _o === void 0 ? void 0 : _o.$eq;
67
- if (typeof validForMemberTierIdentifierEq === 'string') {
68
- andConditions.push({ 'validForMemberTier.identifier': { $exists: true, $eq: validForMemberTierIdentifierEq } });
69
- }
70
- return andConditions;
71
- }
72
- save(params) {
73
- return __awaiter(this, void 0, void 0, function* () {
74
- var _a, _b;
75
- let doc;
76
- let savedId;
77
- const savingId = params.id;
78
- if (typeof savingId === 'string') {
79
- if (savingId === '') {
80
- throw new factory.errors.ArgumentNull('id');
81
- }
82
- const _c = params.attributes, { id, identifier, itemOffered, project, seller, typeOf, availableAtOrFrom, validForMemberTier, $unset } = _c, updateFields = __rest(_c, ["id", "identifier", "itemOffered", "project", "seller", "typeOf", "availableAtOrFrom", "validForMemberTier", "$unset"]);
83
- const filter = {
84
- _id: { $eq: savingId },
85
- 'project.id': { $eq: project.id }
86
- };
87
- const update = Object.assign({ $set: Object.assign({}, updateFields) }, ($unset !== undefined && $unset !== null) ? { $unset } : undefined);
88
- const options = {
89
- upsert: false,
90
- new: true,
91
- projection: { _id: 1, id: { $toString: '$_id' } }
92
- };
93
- doc = yield this.eventOfferModel.findOneAndUpdate(filter, update, options)
94
- .lean()
95
- .exec();
96
- if (doc === null) {
97
- throw new factory.errors.NotFound(this.eventOfferModel.modelName);
98
- }
99
- savedId = savingId;
100
- }
101
- else {
102
- const _d = params.attributes, { $unset, id } = _d, createParams = __rest(_d, ["$unset", "id"]);
103
- const result = yield this.eventOfferModel.insertMany(Object.assign({}, createParams), { rawResult: true });
104
- const insertedId = (_b = (_a = result.insertedIds) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.toHexString();
105
- if (typeof insertedId !== 'string') {
106
- throw new factory.errors.Internal(`seller not saved unexpectedly. result:${JSON.stringify(result)}`);
107
- }
108
- savedId = insertedId;
109
- }
110
- return { id: savedId };
111
- });
112
- }
113
- projectFields(conditions, inclusion) {
114
- return __awaiter(this, void 0, void 0, function* () {
115
- var _a;
116
- const andConditions = EventOfferRepo.CREATE_FILTER_QUERY(conditions);
117
- const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(inclusion.map((key) => ([key, 1]))));
118
- const query = this.eventOfferModel.find((andConditions.length > 0) ? { $and: andConditions } : {}, projection);
119
- if (typeof conditions.limit === 'number' && conditions.limit > 0) {
120
- const page = (typeof conditions.page === 'number' && conditions.page > 0) ? conditions.page : 1;
121
- query.limit(conditions.limit)
122
- .skip(conditions.limit * (page - 1));
123
- }
124
- if (typeof ((_a = conditions.sort) === null || _a === void 0 ? void 0 : _a.validFrom) === 'number') {
125
- query.sort({ validFrom: conditions.sort.validFrom });
126
- }
127
- return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
128
- .lean()
129
- .exec();
130
- });
131
- }
132
- deleteById(params) {
133
- return __awaiter(this, void 0, void 0, function* () {
134
- yield this.eventOfferModel.findOneAndDelete({
135
- _id: { $eq: params.id },
136
- 'project.id': { $eq: params.project.id }
137
- }, { projection: { _id: 1 } })
138
- .exec();
139
- });
140
- }
141
- }
142
- exports.EventOfferRepo = EventOfferRepo;