-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdiscountEndpoint.ts
168 lines (153 loc) · 4.76 KB
/
discountEndpoint.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import { sum } from '@modules/arrayFunctions';
import { ValidationError } from '@modules/errors';
import { checkDefined } from '@modules/nullAndUndefined';
import type { Stage } from '@modules/stage';
import { addDiscount, previewDiscount } from '@modules/zuora/addDiscount';
import { getBillingPreview } from '@modules/zuora/billingPreview';
import { getAccount } from '@modules/zuora/getAccount';
import { getSubscription } from '@modules/zuora/getSubscription';
import type { FetchInterface } from '@modules/zuora/requestLogger';
import { ZuoraClient } from '@modules/zuora/zuoraClient';
import type { ZuoraSubscription } from '@modules/zuora/zuoraSchemas';
import { getZuoraCatalog } from '@modules/zuora-catalog/S3';
import type { APIGatewayProxyEventHeaders } from 'aws-lambda';
import dayjs from 'dayjs';
import { EligibilityChecker } from './eligibilityChecker';
import type { Discount } from './productToDiscountMapping';
import { getDiscountFromSubscription } from './productToDiscountMapping';
import { applyDiscountSchema } from './requestSchema';
export const discountEndpoint = async (
stage: Stage,
preview: boolean,
headers: APIGatewayProxyEventHeaders,
body: string | null,
fetchInterface: FetchInterface,
) => {
const zuoraClient = await ZuoraClient.create(stage, fetchInterface);
const catalog = await getZuoraCatalog(stage);
const eligibilityChecker = new EligibilityChecker(catalog);
const identityId = checkDefined(
headers['x-identity-id'],
'Identity ID not found in request',
);
const requestBody = applyDiscountSchema.parse(
JSON.parse(checkDefined(body, 'No body was provided')),
);
console.log('Getting the subscription details from Zuora');
const subscription = await getSubscription(
zuoraClient,
requestBody.subscriptionNumber,
);
if (subscription.status !== 'Active') {
throw new ValidationError(
`Subscription ${subscription.subscriptionNumber} has status ${subscription.status}`,
);
}
console.log(
'Check sub is owned by user & get billing preview for the subscription',
);
const [, billingPreview] = await Promise.all([
checkSubscriptionBelongsToIdentityId(zuoraClient, subscription, identityId),
getBillingPreview(
zuoraClient,
dayjs().add(13, 'months'),
subscription.accountNumber,
),
]);
console.log('Working out the appropriate discount for the subscription');
const { discount, nonDiscountRatePlan } = getDiscountFromSubscription(
stage,
subscription,
);
console.log('Checking this subscription is eligible for the discount');
const dateToApply = eligibilityChecker.getNextBillingDateIfEligible(
billingPreview,
nonDiscountRatePlan,
);
if (preview) {
console.log('Preview the new price once the discount has been applied');
return getDiscountPreview(
zuoraClient,
requestBody.subscriptionNumber,
dateToApply,
discount,
);
} else {
return applyDiscount(
zuoraClient,
requestBody.subscriptionNumber,
subscription.termStartDate,
subscription.termEndDate,
dateToApply,
discount.productRatePlanId,
);
}
};
const getDiscountPreview = async (
zuoraClient: ZuoraClient,
subscriptionNumber: string,
nextBillingDate: Date,
discount: Discount,
) => {
const previewResponse = await previewDiscount(
zuoraClient,
subscriptionNumber,
dayjs(nextBillingDate),
discount.productRatePlanId,
);
if (!previewResponse.success || previewResponse.invoiceItems.length < 2) {
throw new Error(
'Unexpected data in preview response from Zuora. ' +
'We expected at least 2 invoice items, one for the discount and at least one for the main plan',
);
}
const discountedPrice = sum(
previewResponse.invoiceItems,
(item) => item.chargeAmount + item.taxAmount,
);
return {
body: JSON.stringify({
discountedPrice,
upToPeriods: discount.upToPeriods,
upToPeriodsType: discount.upToPeriodsType,
}),
statusCode: 200,
};
};
const applyDiscount = async (
zuoraClient: ZuoraClient,
subscriptionNumber: string,
termStartDate: Date,
termEndDate: Date,
nextBillingDate: Date,
discountProductRatePlanId: string,
) => {
console.log('Apply a discount to the subscription');
const discounted = await addDiscount(
zuoraClient,
subscriptionNumber,
dayjs(termStartDate),
dayjs(termEndDate),
dayjs(nextBillingDate),
discountProductRatePlanId,
);
if (discounted.success) {
console.log('Discount applied successfully');
}
return {
body: 'Success',
statusCode: 200,
};
};
const checkSubscriptionBelongsToIdentityId = async (
zuoraClient: ZuoraClient,
subscription: ZuoraSubscription,
identityId: string,
) => {
const account = await getAccount(zuoraClient, subscription.accountNumber);
if (account.basicInfo.identityId !== identityId) {
throw new ValidationError(
`Subscription ${subscription.subscriptionNumber} does not belong to identity ID ${identityId}`,
);
}
};