@chevre/domain
Version:
Chevre Domain Library for Node.js
454 lines (453 loc) • 22 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PaymentServiceRepo = void 0;
const factory = require("../factory");
const settings_1 = require("../settings");
const paymentService_1 = require("./mongoose/schemas/paymentService");
const paymentServiceChannel_1 = require("./mongoose/schemas/paymentServiceChannel");
const AVAILABLE_PROJECT_FIELDS = [
'project',
'typeOf',
'additionalProperty',
'availableChannel',
'description',
'name',
'productID',
'serviceOutput',
'serviceType',
'potentialAction'
];
/**
* 決済サービスリポジトリ
*/
class PaymentServiceRepo {
constructor(connection) {
this.paymentServiceModel = connection.model(paymentService_1.modelName, (0, paymentService_1.createSchema)());
this.paymentServiceChannelModel = connection.model(paymentServiceChannel_1.modelName, (0, paymentServiceChannel_1.createSchema)());
}
// tslint:disable-next-line:max-func-body-length
static CREATE_MONGO_CONDITIONS(params) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
const andConditions = [];
const projectIdEq = (_b = (_a = params.project) === null || _a === void 0 ? void 0 : _a.id) === null || _b === void 0 ? void 0 : _b.$eq;
if (typeof projectIdEq === 'string') {
andConditions.push({
'project.id': { $eq: projectIdEq }
});
}
const typeOfEq = (_c = params.typeOf) === null || _c === void 0 ? void 0 : _c.$eq;
if (typeof typeOfEq === 'string') {
andConditions.push({
typeOf: { $eq: typeOfEq }
});
}
const typeOfIn = (_d = params.typeOf) === null || _d === void 0 ? void 0 : _d.$in;
if (Array.isArray(typeOfIn)) {
andConditions.push({
typeOf: { $in: typeOfIn }
});
}
const idEq = (_e = params.id) === null || _e === void 0 ? void 0 : _e.$eq;
if (typeof idEq === 'string') {
andConditions.push({ _id: { $eq: idEq } });
}
const idIn = (_f = params.id) === null || _f === void 0 ? void 0 : _f.$in;
if (Array.isArray(idIn)) {
andConditions.push({ _id: { $in: idIn } });
}
const productIDEq = (_g = params.productID) === null || _g === void 0 ? void 0 : _g.$eq;
if (typeof productIDEq === 'string') {
andConditions.push({
productID: { $eq: productIDEq }
});
}
const productIDIn = (_h = params.productID) === null || _h === void 0 ? void 0 : _h.$in;
if (Array.isArray(productIDIn)) {
andConditions.push({
productID: { $in: productIDIn }
});
}
const productIDRegex = (_j = params.productID) === null || _j === void 0 ? void 0 : _j.$regex;
if (typeof productIDRegex === 'string' && productIDRegex.length > 0) {
andConditions.push({
productID: { $regex: new RegExp(productIDRegex) }
});
}
// discontinue(2024-08-20~)
// const offersElemMatch = params.offers?.$elemMatch;
// if (offersElemMatch !== undefined && offersElemMatch !== null) {
// andConditions.push({
// offers: {
// $elemMatch: offersElemMatch
// }
// });
// }
const serviceOutputTypeOfEq = (_l = (_k = params.serviceOutput) === null || _k === void 0 ? void 0 : _k.typeOf) === null || _l === void 0 ? void 0 : _l.$eq;
if (typeof serviceOutputTypeOfEq === 'string') {
andConditions.push({
'serviceOutput.typeOf': {
$exists: true,
$eq: serviceOutputTypeOfEq
}
});
}
const serviceOutputPaymentMethodAmountCurrencyEq = (_q = (_p = (_o = (_m = params.serviceOutput) === null || _m === void 0 ? void 0 : _m.paymentMethod) === null || _o === void 0 ? void 0 : _o.amount) === null || _p === void 0 ? void 0 : _p.currency) === null || _q === void 0 ? void 0 : _q.$eq;
if (typeof serviceOutputPaymentMethodAmountCurrencyEq === 'string') {
andConditions.push({
'serviceOutput.paymentMethod.amount.currency': {
$exists: true,
$eq: serviceOutputPaymentMethodAmountCurrencyEq
}
});
}
// extend(2024-08-20~)
const serviceOutputIssuedThroughServiceTypeCodeValueEq = (_u = (_t = (_s = (_r = params.serviceOutput) === null || _r === void 0 ? void 0 : _r.issuedThrough) === null || _s === void 0 ? void 0 : _s.serviceType) === null || _t === void 0 ? void 0 : _t.codeValue) === null || _u === void 0 ? void 0 : _u.$eq;
if (typeof serviceOutputIssuedThroughServiceTypeCodeValueEq === 'string') {
andConditions.push({
'serviceOutput.issuedThrough.serviceType.codeValue': {
$exists: true,
$eq: serviceOutputIssuedThroughServiceTypeCodeValueEq
}
});
}
const serviceTypeCodeValueEq = (_w = (_v = params.serviceType) === null || _v === void 0 ? void 0 : _v.codeValue) === null || _w === void 0 ? void 0 : _w.$eq;
if (typeof serviceTypeCodeValueEq === 'string') {
andConditions.push({
'serviceType.codeValue': {
$exists: true,
$eq: serviceTypeCodeValueEq
}
});
}
const nameRegex = (_x = params.name) === null || _x === void 0 ? void 0 : _x.$regex;
if (typeof nameRegex === 'string' && nameRegex.length > 0) {
const nameRegexExp = new RegExp(nameRegex);
andConditions.push({
$or: [
{
'name.ja': {
$exists: true,
$regex: nameRegexExp
}
},
{
'name.en': {
$exists: true,
$regex: nameRegexExp
}
}
]
});
}
// プロバイダー条件を追加(2023-06-21~)
const providerIdEq = (_z = (_y = params.provider) === null || _y === void 0 ? void 0 : _y.id) === null || _z === void 0 ? void 0 : _z.$eq;
if (typeof providerIdEq === 'string') {
andConditions.push({ 'provider.id': { $exists: true, $eq: providerIdEq } });
}
const availableChannelIdEq = (_1 = (_0 = params.availableChannel) === null || _0 === void 0 ? void 0 : _0.id) === null || _1 === void 0 ? void 0 : _1.$eq;
if (typeof availableChannelIdEq === 'string') {
andConditions.push({ 'availableChannel.id': { $exists: true, $eq: availableChannelIdEq } });
}
// discontinue(2025-03-25~)
// const availableChannelServiceUrlEq = params.availableChannel?.serviceUrl?.$eq;
// if (typeof availableChannelServiceUrlEq === 'string') {
// andConditions.push({ 'availableChannel.serviceUrl': { $exists: true, $eq: availableChannelServiceUrlEq } });
// }
return andConditions;
}
/**
* 決済サービスを保管する
*/
savePaymentService(params) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
let doc;
let savedId;
if (typeof params.id === 'string') {
// 上書き禁止属性を除外
const _c = params.$set, { id, productID, project, typeOf, provider, serviceType } = _c, setFields = __rest(_c, ["id", "productID", "project", "typeOf", "provider", "serviceType"]);
switch (typeOf) {
case factory.service.paymentService.PaymentServiceType.CreditCard:
case factory.service.paymentService.PaymentServiceType.MovieTicket:
doc = yield this.paymentServiceModel.findOneAndUpdate({
_id: { $eq: params.id },
typeOf: { $eq: typeOf }
}, {
$set: setFields,
$unset: params.$unset
}, { upsert: false, new: true, projection: { _id: 1, id: { $toString: '$_id' } } })
.lean()
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.paymentServiceModel.modelName);
}
break;
default:
throw new factory.errors.NotImplemented(`${typeOf} not implemented`);
}
savedId = params.id;
}
else {
const _d = params.$set, { id, provider } = _d, createParams = __rest(_d, ["id", "provider"]);
if (params.createIfNotExist === true) {
doc = yield this.paymentServiceModel.findOneAndUpdate({
'project.id': { $eq: createParams.project.id },
typeOf: { $eq: createParams.typeOf }
}, { $setOnInsert: createParams }, { new: true, upsert: true, projection: { _id: 1, id: { $toString: '$_id' } } })
.lean()
.exec();
if (doc === null) {
throw new factory.errors.NotFound(this.paymentServiceModel.modelName);
}
savedId = doc.id;
}
else {
const result = yield this.paymentServiceModel.insertMany(createParams, { rawResult: true });
const insertedId = (_b = (_a = result.insertedIds) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.toHexString();
if (typeof insertedId !== 'string') {
throw new factory.errors.Internal(`paymentService not saved unexpectedly. result:${JSON.stringify(result)}`);
}
savedId = insertedId;
}
}
return { id: savedId };
});
}
/**
* 決済サービスを検索する
*/
projectFields(conditions, inclusion
// exclusion: IKeyOfProjection4paymentService[] // discontinue(2025-02-05~)
) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
const andConditions = PaymentServiceRepo.CREATE_MONGO_CONDITIONS(conditions);
let positiveProjectionFields = AVAILABLE_PROJECT_FIELDS;
if (Array.isArray(inclusion) && inclusion.length > 0) {
positiveProjectionFields = inclusion.filter((key) => AVAILABLE_PROJECT_FIELDS.includes(key));
}
else {
// if (Array.isArray(exclusion) && exclusion.length > 0) {
// positiveProjectionFields = positiveProjectionFields.filter((key) => !exclusion.includes(key));
// }
}
const projection = Object.assign({ _id: 0, id: { $toString: '$_id' } }, Object.fromEntries(positiveProjectionFields.map((key) => ([key, 1]))));
const query = this.paymentServiceModel.find((andConditions.length > 0) ? { $and: andConditions } : {}, projection);
if (typeof conditions.limit === 'number' && conditions.limit > 0) {
const page = (typeof conditions.page === 'number' && conditions.page > 0) ? conditions.page : 1;
query.limit(conditions.limit)
.skip(conditions.limit * (page - 1));
}
// tslint:disable-next-line:no-single-line-block-comment
/* istanbul ignore else */
if (((_a = conditions.sort) === null || _a === void 0 ? void 0 : _a.productID) !== undefined) {
query.sort({ productID: conditions.sort.productID });
}
return query.setOptions({ maxTimeMS: settings_1.MONGO_MAX_TIME_MS })
.lean() // 2024-08-20~
.exec();
});
}
deletePaymentServiceById(params) {
return __awaiter(this, void 0, void 0, function* () {
yield this.paymentServiceModel.findOneAndDelete({ _id: { $eq: params.id } }, { projection: { _id: 1 } })
.exec();
});
}
// public async findAvailableChannel(params: {
// project: { id: string };
// typeOf: factory.service.paymentService.PaymentServiceType.CreditCard;
// id: string;
// }): Promise<factory.service.paymentService.IAvailableChannel> {
// let paymentService: Pick<factory.service.paymentService.IService, 'availableChannel'> | undefined;
// paymentService = (await this.projectFields(
// {
// limit: 1,
// page: 1,
// project: { id: { $eq: params.project.id } },
// typeOf: { $eq: params.typeOf },
// id: { $eq: params.id }
// },
// ['availableChannel'],
// []
// )).shift();
// if (paymentService === undefined) {
// throw new factory.errors.NotFound('PaymentService');
// }
// const availableChannel = paymentService.availableChannel;
// if (availableChannel === undefined) {
// throw new factory.errors.NotFound('paymentService.availableChannel');
// }
// return availableChannel;
// }
findAvailableChannelCreditCard(params) {
return __awaiter(this, void 0, void 0, function* () {
const paymentService = (yield this.projectFields({
limit: 1,
page: 1,
project: { id: { $eq: params.project.id } },
typeOf: { $eq: factory.service.paymentService.PaymentServiceType.CreditCard },
id: { $eq: params.id }
}, ['availableChannel']
// []
)).shift();
if (paymentService === undefined) {
throw new factory.errors.NotFound(factory.service.paymentService.PaymentServiceType.CreditCard);
}
const availableChannel = paymentService.availableChannel;
if (availableChannel === undefined) {
throw new factory.errors.NotFound('paymentService.availableChannel');
}
if (typeof availableChannel.id !== 'string' || availableChannel.id === '') {
throw new factory.errors.NotFound('paymentService.availableChannel.id');
}
const serviceChannel = yield this.paymentServiceChannelModel.findOne({
'project.id': { $eq: params.project.id },
_id: { $eq: availableChannel.id },
// serviceUrl: { $eq: availableChannel.serviceUrl },
'providesService.typeOf': { $eq: factory.service.paymentService.PaymentServiceType.CreditCard }
}, {
credentials: 1,
_id: 0,
id: { $toString: '$_id' },
serviceUrl: 1
})
.lean()
.exec();
if (serviceChannel === null) {
throw new factory.errors.NotFound('ServiceChannel');
}
return Object.assign(Object.assign({}, availableChannel), { id: serviceChannel.id, serviceUrl: serviceChannel.serviceUrl, credentials: serviceChannel.credentials });
});
}
findAvailableChannelMovieTicket(params) {
return __awaiter(this, void 0, void 0, function* () {
const paymentService = (yield this.projectFields({
limit: 1,
page: 1,
project: { id: { $eq: params.project.id } },
typeOf: { $eq: factory.service.paymentService.PaymentServiceType.MovieTicket },
id: { $eq: params.id }
}, ['availableChannel']
// []
)).shift();
if (paymentService === undefined) {
throw new factory.errors.NotFound(factory.service.paymentService.PaymentServiceType.MovieTicket);
}
const availableChannel = paymentService.availableChannel;
if (availableChannel === undefined) {
throw new factory.errors.NotFound('paymentService.availableChannel');
}
if (typeof availableChannel.id !== 'string' || availableChannel.id === '') {
throw new factory.errors.NotFound('paymentService.availableChannel.id');
}
const serviceChannel = yield this.paymentServiceChannelModel.findOne({
'project.id': { $eq: '*' },
_id: { $eq: availableChannel.id },
// serviceUrl: { $eq: availableChannel.serviceUrl },
'providesService.typeOf': { $eq: factory.service.paymentService.PaymentServiceType.MovieTicket }
}, {
credentials: 1,
_id: 0,
id: { $toString: '$_id' },
serviceUrl: 1
})
.lean()
.exec();
if (serviceChannel === null) {
throw new factory.errors.NotFound('ServiceChannel');
}
return Object.assign(Object.assign({}, availableChannel), { id: serviceChannel.id, serviceUrl: serviceChannel.serviceUrl, credentials: serviceChannel.credentials });
});
}
// public async saveChannelByServiceUrl(
// params: Omit<factory.serviceChannel.IServiceChannel, 'id'>
// ): Promise<void> {
// await this.paymentServiceChannelModel.findOneAndUpdate(
// {
// 'project.id': { $eq: params.project.id },
// serviceUrl: { $eq: params.serviceUrl }
// },
// {
// $setOnInsert: params
// },
// { upsert: true }
// )
// .exec();
// }
// public async migrateChannelId(params: {
// project: { id: string };
// /**
// * payment service ID
// */
// id: string;
// typeOf: factory.service.paymentService.PaymentServiceType.CreditCard
// | factory.service.paymentService.PaymentServiceType.MovieTicket;
// }): Promise<void> {
// let existingChannel: Pick<
// factory.service.paymentService.IAvailableChannel,
// 'serviceUrl' | 'typeOf' | 'id'
// >;
// if (params.typeOf === factory.service.paymentService.PaymentServiceType.CreditCard) {
// existingChannel = await this.findAvailableChannelCreditCard(params);
// } else if (params.typeOf === factory.service.paymentService.PaymentServiceType.MovieTicket) {
// existingChannel = await this.findAvailableChannelMovieTicket(params);
// } else {
// throw new factory.errors.Argument('typeOf', `not implemented`);
// }
// if (typeof existingChannel.id !== 'string' || existingChannel.id === '') {
// throw new factory.errors.NotFound('existingChannel.id');
// }
// // tslint:disable-next-line:no-console
// console.log('updating paymentService...', existingChannel.id, existingChannel.serviceUrl, params.project.id, params.id);
// const doc = await this.paymentServiceModel.findOneAndUpdate(
// { _id: { $eq: params.id } },
// {
// $set: {
// 'availableChannel.id': existingChannel.id
// }
// },
// { upsert: false, new: true, projection: { _id: 1, id: { $toString: '$_id' } } }
// )
// .lean<{ id: string }>()
// .exec();
// if (doc === null) {
// throw new factory.errors.NotFound(this.paymentServiceModel.modelName);
// }
// }
unsetUnnecessaryFields(params) {
return __awaiter(this, void 0, void 0, function* () {
return this.paymentServiceModel.updateMany(params.filter, { $unset: params.$unset }, { timestamps: false })
.exec();
});
}
getCursor(conditions, projection) {
return this.paymentServiceModel.find(conditions, projection)
.sort({ productID: factory.sortType.Ascending })
.cursor();
}
getModel() {
return this.paymentServiceModel;
}
}
exports.PaymentServiceRepo = PaymentServiceRepo;