in handlers/discount-api/src/discountEndpoint.ts [212:279]
async function getDiscountToApply(
logger: Logger,
stage: Stage,
subscription: ZuoraSubscription,
account: ZuoraAccount,
zuoraClient: ZuoraClient,
today: dayjs.Dayjs,
) {
const catalog = () => getZuoraCatalog(stage);
const eligibilityChecker = new EligibilityChecker(logger);
// don't get the billing preview until we know the subscription is not cancelled
const lazyBillingPreview = new Lazy(
() =>
getBillingPreview(
zuoraClient,
today.add(13, 'months'),
subscription.accountNumber,
),
'get billing preview for the subscription',
).then(billingPreviewToSimpleInvoiceItems);
await eligibilityChecker.assertGenerallyEligible(
subscription,
account.metrics.totalInvoiceBalance,
() => lazyBillingPreview.then(getNextInvoiceItems).get(),
);
// now we know the subscription is not cancelled we can force the billing preview
const billingPreview = await lazyBillingPreview.get();
logger.log('Working out the appropriate discount for the subscription');
const { discount, discountableProductRatePlanId } =
getDiscountFromSubscription(stage, subscription);
logger.log('Checking this subscription is eligible for the discount');
switch (discount.eligibilityCheckForRatePlan) {
case 'EligibleForFreePeriod':
eligibilityChecker.assertEligibleForFreePeriod(
discount.productRatePlanId,
subscription,
today,
);
break;
case 'AtCatalogPrice':
eligibilityChecker.assertNextPaymentIsAtCatalogPrice(
await catalog(),
billingPreview,
discountableProductRatePlanId,
account.metrics.currency,
);
break;
case 'NoRepeats':
eligibilityChecker.assertNoRepeats(
discount.productRatePlanId,
subscription,
);
break;
case 'NoCheck':
break;
}
const dateToApply = getNextInvoice(billingPreview).date;
const orderedInvoiceTotals = getOrderedInvoiceTotals(billingPreview);
return { discount, dateToApply, orderedInvoiceTotals };
}