2021-10-05 14:17:18 +03:00
|
|
|
const labs = require('../../../shared/labs');
|
|
|
|
const events = require('../../lib/common/events');
|
|
|
|
|
|
|
|
const DynamicRedirectManager = require('@tryghost/express-dynamic-redirects');
|
|
|
|
const OffersModule = require('@tryghost/members-offers');
|
|
|
|
|
|
|
|
const stripeService = require('../stripe');
|
|
|
|
|
|
|
|
const config = require('../../../shared/config');
|
|
|
|
const urlUtils = require('../../../shared/url-utils');
|
|
|
|
const models = require('../../models');
|
|
|
|
|
|
|
|
const redirectManager = new DynamicRedirectManager({
|
|
|
|
permanentMaxAge: config.get('caching:customRedirects:maxAge')
|
|
|
|
}, urlUtils);
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
async init() {
|
|
|
|
const offersModule = OffersModule.create({
|
|
|
|
OfferModel: models.Offer,
|
|
|
|
redirectManager: redirectManager,
|
|
|
|
stripeAPIService: stripeService.api
|
|
|
|
});
|
|
|
|
|
|
|
|
this.api = offersModule.api;
|
2021-10-06 16:21:19 +03:00
|
|
|
this.repository = offersModule.repository;
|
2021-10-05 14:17:18 +03:00
|
|
|
|
2021-10-12 15:13:47 +03:00
|
|
|
let initCalled = false;
|
2021-10-05 14:17:18 +03:00
|
|
|
if (labs.isSet('offers')) {
|
|
|
|
// handles setting up redirects
|
2021-10-12 15:13:47 +03:00
|
|
|
const promise = offersModule.init();
|
|
|
|
initCalled = true;
|
|
|
|
await promise;
|
2021-10-05 14:17:18 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Delete after GA
|
|
|
|
let offersEnabled = labs.isSet('offers');
|
|
|
|
events.on('settings.labs.edited', async () => {
|
2021-10-12 15:13:47 +03:00
|
|
|
if (labs.isSet('offers') && !initCalled) {
|
|
|
|
const promise = offersModule.init();
|
|
|
|
initCalled = true;
|
|
|
|
await promise;
|
|
|
|
} else if (labs.isSet('offers') !== offersEnabled) {
|
2021-10-05 14:17:18 +03:00
|
|
|
offersEnabled = labs.isSet('offers');
|
|
|
|
|
|
|
|
if (offersEnabled) {
|
|
|
|
const offers = await this.api.listOffers();
|
|
|
|
for (const offer of offers) {
|
|
|
|
redirectManager.addRedirect(`/${offer.code}`, `/#/portal/offers/${offer.id}`, {permanent: false});
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
redirectManager.removeAllRedirects();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
api: null,
|
|
|
|
|
|
|
|
middleware: redirectManager.handleRequest
|
|
|
|
};
|