@chevre/domain 21.18.0-alpha.28 → 21.18.0-alpha.29

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,94 @@
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
+ // tslint:disable-next-line:max-func-body-length
9
+ async function main() {
10
+ await mongoose.connect(<string>process.env.MONGOLAB_URI, { autoIndex: false });
11
+
12
+ const offerRepo = await chevre.repository.Offer.createInstance(mongoose.connection);
13
+
14
+ const result = await offerRepo.upsertByIdentifier(
15
+ [
16
+ {
17
+ additionalProperty: [],
18
+ addOn: [],
19
+ alternateName: { en: '', ja: '20231213' },
20
+ availability: chevre.factory.itemAvailability.InStock,
21
+ availableAtOrFrom: [],
22
+ itemOffered: {
23
+ typeOf: chevre.factory.product.ProductType.EventService,
24
+ serviceOutput: {}
25
+ },
26
+ name: { ja: '20231213', en: '20231213' },
27
+ priceCurrency: chevre.factory.priceCurrency.JPY,
28
+ priceSpecification: {
29
+ name: { en: '20231213', ja: '20231213' },
30
+ price: 20231213,
31
+ priceCurrency: chevre.factory.priceCurrency.JPY,
32
+ referenceQuantity: {
33
+ typeOf: 'QuantitativeValue',
34
+ value: 1,
35
+ unitCode: chevre.factory.unitCode.C62
36
+ },
37
+ typeOf: chevre.factory.priceSpecificationType.UnitPriceSpecification,
38
+ valueAddedTaxIncluded: true,
39
+ accounting: {
40
+ typeOf: 'Accounting',
41
+ accountsReceivable: 20231213
42
+ }
43
+ },
44
+ settings: { ignoreCategoryCodeChargeSpec: false },
45
+ description: { en: '', ja: '' },
46
+ hasMerchantReturnPolicy: [],
47
+ identifier: '20231213',
48
+ project: { typeOf: chevre.factory.organizationType.Project, id: PROJECT_ID },
49
+ typeOf: chevre.factory.offerType.Offer
50
+ },
51
+ {
52
+ additionalProperty: [],
53
+ addOn: [],
54
+ alternateName: { en: '', ja: '2023121302' },
55
+ availability: chevre.factory.itemAvailability.InStock,
56
+ availableAtOrFrom: [],
57
+ itemOffered: {
58
+ typeOf: chevre.factory.product.ProductType.EventService,
59
+ serviceOutput: {}
60
+ },
61
+ name: { ja: '2023121302', en: '2023121302' },
62
+ priceCurrency: chevre.factory.priceCurrency.JPY,
63
+ priceSpecification: {
64
+ name: { en: '2023121302', ja: '2023121302' },
65
+ price: 20231213,
66
+ priceCurrency: chevre.factory.priceCurrency.JPY,
67
+ referenceQuantity: {
68
+ typeOf: 'QuantitativeValue',
69
+ value: 1,
70
+ unitCode: chevre.factory.unitCode.C62
71
+ },
72
+ typeOf: chevre.factory.priceSpecificationType.UnitPriceSpecification,
73
+ valueAddedTaxIncluded: true,
74
+ accounting: {
75
+ typeOf: 'Accounting',
76
+ accountsReceivable: 20231213
77
+ }
78
+ },
79
+ settings: { ignoreCategoryCodeChargeSpec: false },
80
+ description: { en: '', ja: '' },
81
+ hasMerchantReturnPolicy: [],
82
+ identifier: '2023121302',
83
+ project: { typeOf: chevre.factory.organizationType.Project, id: PROJECT_ID },
84
+ typeOf: chevre.factory.offerType.Offer
85
+ }
86
+ ]
87
+ // { replace: true }
88
+ );
89
+ console.log('result:', result);
90
+ }
91
+
92
+ main()
93
+ .then(console.log)
94
+ .catch(console.error);
@@ -1,3 +1,4 @@
1
+ import type { BulkWriteResult } from 'mongodb';
1
2
  import { AnyExpression, Connection, PipelineStage } from 'mongoose';
2
3
  import * as factory from '../factory';
3
4
  type IMatchStage = PipelineStage.Match;
@@ -152,6 +153,16 @@ export declare class MongoRepository {
152
153
  count(params: Omit<factory.unitPriceOffer.ISearchConditions, 'limit' | 'page' | 'sort'>): Promise<number>;
153
154
  search(params: factory.unitPriceOffer.ISearchConditions, projection?: IProjection): Promise<IUnitPriceOfferFromAggregateOffer[]>;
154
155
  save(params: factory.unitPriceOffer.IUnitPriceOffer & {}): Promise<factory.unitPriceOffer.IUnitPriceOffer>;
156
+ /**
157
+ * コードをキーにして冪等置換(2023-12-13~)
158
+ */
159
+ upsertByIdentifier(params: Omit<factory.unitPriceOffer.IUnitPriceOffer, 'id'>[]): Promise<{
160
+ bulkWriteResult4insert: BulkWriteResult;
161
+ bulkWriteResult: BulkWriteResult;
162
+ modifiedOffers: {
163
+ id: string;
164
+ }[];
165
+ } | void>;
155
166
  /**
156
167
  * sskts専用オファー保管
157
168
  */
@@ -804,6 +804,82 @@ class MongoRepository {
804
804
  return savedUnitPriceOffer;
805
805
  });
806
806
  }
807
+ /**
808
+ * コードをキーにして冪等置換(2023-12-13~)
809
+ */
810
+ upsertByIdentifier(params
811
+ // options?: {
812
+ // replace?: boolean;
813
+ // }
814
+ ) {
815
+ return __awaiter(this, void 0, void 0, function* () {
816
+ const uniqid = yield Promise.resolve().then(() => require('uniqid'));
817
+ const insertBulkWriteOps = [];
818
+ const updateBulkWriteOps = [];
819
+ const queryFilters = [];
820
+ if (Array.isArray(params)) {
821
+ params.forEach((p) => {
822
+ // リソースのユニークネスを保証するfilter
823
+ const filter = {
824
+ 'project.id': { $eq: p.project.id },
825
+ 'offers.identifier': { $exists: true, $eq: p.identifier }
826
+ };
827
+ queryFilters.push({
828
+ 'project.id': { $eq: p.project.id },
829
+ 'offers.identifier': { $exists: true, $eq: p.identifier }
830
+ });
831
+ const newOfferId = uniqid(); // setOnInsert時のみに利用する新ID
832
+ const unitPriceOffer = Object.assign(Object.assign({}, p), { id: newOfferId });
833
+ const aggregateOffer = {
834
+ project: p.project,
835
+ typeOf: factory.offerType.AggregateOffer,
836
+ offers: [unitPriceOffer]
837
+ };
838
+ const setOnInsert = Object.assign(Object.assign({}, aggregateOffer), { _id: newOfferId });
839
+ const updateFilter = { $setOnInsert: setOnInsert };
840
+ const updateOneOnInsert = {
841
+ filter,
842
+ update: updateFilter,
843
+ upsert: true
844
+ };
845
+ insertBulkWriteOps.push({ updateOne: updateOneOnInsert });
846
+ });
847
+ }
848
+ if (insertBulkWriteOps.length > 0) {
849
+ const bulkWriteResult4insert = yield this.aggregateOfferModel.bulkWrite(insertBulkWriteOps, { ordered: false });
850
+ // modifiedの場合upsertedIdsに含まれないので、idを検索する
851
+ const modifiedOffers = yield this.aggregateOfferModel.find({ $or: queryFilters }, { _id: 1, 'offers.identifier': 1 })
852
+ .exec()
853
+ .then((docs) => docs.map((doc) => doc.toObject()));
854
+ params.forEach((p) => {
855
+ const originalAggregateOffer = modifiedOffers.find(((offer) => { var _a; return ((_a = offer.offers[0]) === null || _a === void 0 ? void 0 : _a.identifier) === p.identifier; }));
856
+ if (originalAggregateOffer === undefined) {
857
+ // upsert後なので、必ず存在するはず
858
+ throw new factory.errors.NotFound(`${factory.offerType.AggregateOffer} [${p.identifier}]`);
859
+ }
860
+ // リソースのユニークネスを保証するfilter
861
+ const filter = {
862
+ 'project.id': { $eq: p.project.id },
863
+ 'offers.identifier': { $exists: true, $eq: p.identifier }
864
+ };
865
+ const unitPriceOffer = Object.assign(Object.assign({}, p), { id: originalAggregateOffer.id });
866
+ const setOnUpdate = {
867
+ 'offers.0': unitPriceOffer
868
+ };
869
+ const updateOne = {
870
+ filter,
871
+ update: { $set: setOnUpdate },
872
+ upsert: false
873
+ };
874
+ updateBulkWriteOps.push({ updateOne });
875
+ });
876
+ if (updateBulkWriteOps.length > 0) {
877
+ const bulkWriteResult = yield this.aggregateOfferModel.bulkWrite(updateBulkWriteOps, { ordered: false });
878
+ return { bulkWriteResult4insert, bulkWriteResult, modifiedOffers };
879
+ }
880
+ }
881
+ });
882
+ }
807
883
  /**
808
884
  * sskts専用オファー保管
809
885
  */
package/package.json CHANGED
@@ -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": "21.18.0-alpha.28"
118
+ "version": "21.18.0-alpha.29"
119
119
  }