-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAmendmentHandler.scala
More file actions
398 lines (363 loc) · 13.9 KB
/
Copy pathAmendmentHandler.scala
File metadata and controls
398 lines (363 loc) · 13.9 KB
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package pricemigrationengine.handlers
import pricemigrationengine.model.{AmendmentHandlerHelper, ZuoraOrdersApiPrimitives}
import pricemigrationengine.model.CohortTableFilter.{
AmendmentComplete,
NotificationSendDateWrittenToSalesforce,
NotificationSendDateWrittenToSalesforceN4HOLD,
UserOptOut,
ZuoraCancellation
}
import pricemigrationengine.model._
import pricemigrationengine.migrations._
import pricemigrationengine.services._
import zio.{Clock, ZIO}
import java.time.LocalDate
import zio._
import ujson._
/** Carries out price-rise amendments in Zuora.
*/
object AmendmentHandler extends CohortHandler {
private val batchSize = 15
private def main(
cohortSpec: CohortSpec
): ZIO[Logging with CohortTable with Zuora with SalesforceClient, Failure, HandlerOutput] = {
for {
// The batch size of this lambda is particularly low (currently 15)
// which should be plenty of time (observations show that it runs in 4 minutes in average)
// but the refactoring we made here: https://github.com/guardian/price-migration-engine/pull/1221
// (retry of the invoice preview retrieval) means that we have much less control
// over the total time taken by the run.
// Specifically in one instance an item took 13 minutes to complete, which caused issues
// for the lambda itself. To address this problem we monitor the time since the start
// of the run, and exit after 10 minutes.
startingTime <- Clock.nanoTime
deadline = startingTime + 10.minutes.toNanos
_ <- performN4Unlock() // Remove this at the end of N4, in November 2026
catalogue <- Zuora.fetchProductCatalogue
count <- {
val items = cohortSpec.subscriptionNumber match {
case None =>
CohortTable
.fetch(NotificationSendDateWrittenToSalesforce, None)
.take(batchSize)
case Some(subscriptionNumber) =>
CohortTable
.fetch(NotificationSendDateWrittenToSalesforce, None)
.filter(item => item.subscriptionName == subscriptionNumber)
}
items
.takeWhileZIO(_ =>
// When we reach the deadline, we ignore later items from the array.
// They will be picked up by the next run of the lambda.
// If we reach the deadline, isComplete will be false.
Clock.nanoTime.map(_ < deadline)
)
.mapZIO(item =>
performAmendmentAttempt(cohortSpec, item)
.tapBoth(Logging.logFailure(item), Logging.logSuccess(item))
)
.runCount
}
now <- Clock.nanoTime
} yield {
val reachedDeadline = now >= deadline
val isComplete = (count < batchSize) && !reachedDeadline
HandlerOutput(isComplete = isComplete)
}
}
def performN4Unlock(): ZIO[CohortTable with Logging, Failure, Unit] = {
// This effect performs the monitoring of N4 items and unlock those for which delayN4AmendmentUntil
// has been reached. The unlocking corresponds to moving the items from
// NotificationSendDateWrittenToSalesforceN4HOLD to NotificationSendDateWrittenToSalesforce
// This function will be removed at the end of N4, in November 2026
for {
today <- Clock.currentDateTime.map(_.toLocalDate)
_ <- CohortTable
.fetch(NotificationSendDateWrittenToSalesforceN4HOLD, None)
.mapZIO(item =>
item.delayN4AmendmentUntil match {
case Some(unlockDate) if Date.equalOrInOrder(unlockDate, today) => {
CohortTable.update(
CohortItem(
item.subscriptionName,
processingStage = NotificationSendDateWrittenToSalesforce,
)
)
}
case _ => ZIO.unit
}
)
.runDrain
} yield ()
}
private def performAmendmentAttempt(
cohortSpec: CohortSpec,
item: CohortItem
): ZIO[CohortTable with Zuora with Logging with SalesforceClient, Failure, Unit] = {
// This function performs the amendment (through the migration dispatch)
// and updates the Cohort Item.
(for {
result <- performAmendmentAttemptWithResult(cohortSpec, item)
_ <- result match {
case r: AARSuccessfulAmendment => {
CohortTable.update(
CohortItem(
r.subscriptionNumber,
processingStage = AmendmentComplete,
amendmentEffectiveDate = Some(r.amendmentEffectiveDate),
newPrice = Some(r.newPrice),
newSubscriptionId = Some(r.newSubscriptionId),
whenAmendmentDone = Some(r.whenDone)
)
)
}
case r: AARUserOptOut => {
CohortTable
.update(
CohortItem(
r.subscriptionNumber,
processingStage = UserOptOut
)
)
}
case _ =>
ZIO
.fail(
AmendmentFailure(
s"[7f2bf362] unexpected amendment attempt result while processing subscription: ${item.subscriptionName}"
)
)
}
} yield ()).foldZIO(
failure = {
case e: SubscriptionCancelledInZuoraFailure => {
// This case happens when being thrown by
// AmendmentHandler.fetchSubscription
CohortTable
.update(
CohortItem(
item.subscriptionName,
processingStage = ZuoraCancellation
)
)
}
case e: ZuoraUpdateFailure => {
// If the failure was a lock competition, we do not want to alarm by reporting a
// ZIO.fail. Instead, we return a ZIO.succeed, and the item will be retried
// in the next run of the lambda.
if (e.reason.contains("lock competition")) {
ZIO.succeed(())
} else {
ZIO.fail(e)
}
}
case e => ZIO.fail(e)
},
success = { _ => ZIO.succeed(()) }
)
}
private def fetchSubscription(item: CohortItem): ZIO[Zuora, Failure, ZuoraSubscription] =
Zuora
.fetchSubscription(item.subscriptionName)
.filterOrFail(_.status != "Cancelled")(
SubscriptionCancelledInZuoraFailure(s"subscription ${item.subscriptionName} has been cancelled in Zuora")
)
private def renewSubscription(
subscription: ZuoraSubscription,
effectDate: LocalDate,
account: ZuoraAccount
): ZIO[Zuora with Logging, Failure, Unit] = {
val payload = ZuoraOrdersApiPrimitives.subscriptionRenewalPayload(
LocalDate.now().toString,
account.basicInfo.accountNumber,
subscription.subscriptionNumber,
effectDate.toString
)
for {
_ <- Logging.info(s"[cce20c51] Renewing subscription ${subscription.subscriptionNumber} with payload ${payload}")
_ <- Zuora.applyOrderAsynchronously(subscription.subscriptionNumber, payload, "subscription renewal")
} yield ()
}
private def doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec: CohortSpec,
item: CohortItem
): ZIO[Zuora with Logging, Failure, AARSuccessfulAmendment] = {
for {
subscriptionBeforeUpdate <- fetchSubscription(item)
amendmentEffectiveDate <- ZIO
.fromOption(item.amendmentEffectiveDate)
.orElseFail(DataExtractionFailure(s"No start date in $item"))
oldPrice <- ZIO.fromOption(item.oldPrice).orElseFail(DataExtractionFailure(s"No old price in $item"))
commsPrice <-
ZIO
.fromOption(item.commsPrice)
.orElseFail(DataExtractionFailure(s"No commsPrice in $item"))
invoicePreviewTargetDate = amendmentEffectiveDate.plusMonths(13)
account <- Zuora.fetchAccount(
subscriptionBeforeUpdate.accountNumber,
subscriptionBeforeUpdate.subscriptionNumber
)
_ <- renewSubscription(subscriptionBeforeUpdate, subscriptionBeforeUpdate.termEndDate, account)
order <- (for {
_ <- Logging.info(
s"[e0418da6] fetching invoice preview before update, accountId: ${subscriptionBeforeUpdate.accountId}, target date: ${invoicePreviewTargetDate}"
)
invoicePreviewBeforeUpdate <-
Zuora.fetchInvoicePreview(subscriptionBeforeUpdate.accountId, invoicePreviewTargetDate)
_ <- Logging.info(
s"[ec0e9b31] found invoice preview: ${invoicePreviewBeforeUpdate}"
)
_ <- Logging.info(
s"[11ebeaa4] building amendment payload"
)
order <- ZIO.fromEither(
AmendmentHandlerHelper.amendmentOrderPayload(
cohortSpec = cohortSpec,
cohortItem = item,
orderDate = LocalDate.now(),
accountNumber = account.basicInfo.accountNumber,
subscriptionNumber = subscriptionBeforeUpdate.subscriptionNumber,
effectDate = amendmentEffectiveDate,
zuora_subscription = subscriptionBeforeUpdate,
oldPrice = oldPrice,
commsPrice = commsPrice,
invoiceList = invoicePreviewBeforeUpdate
)
)
} yield order)
.retry(
// Values chosen to ensure that the operation doesn't last more than 5 minutes
// so that if an item was started just before the 10 minutes mark deadline of the handler,
// then the entire lambda will complete before 15 minutes (ish)
Schedule.spaced(1.minute) && Schedule.recurs(5)
)
.mapError(e =>
// Note that there are two reason why this would happen
// 1. MigrationRoutingFailure, or
// 2. The `retry` has exited
ZuoraUpdateFailure(
s"[2eecdf44] subscription: ${subscriptionBeforeUpdate.subscriptionNumber}, reason: ${e.reason}"
)
)
_ <- Logging.info(
s"[6e6da544] Amending subscription ${subscriptionBeforeUpdate.subscriptionNumber} with order ${order}"
)
_ <- Zuora.applyOrderAsynchronously(subscriptionBeforeUpdate.subscriptionNumber, order, "subscription amendment")
subscriptionAfterUpdate <- fetchSubscription(item)
invoicePreviewAfterUpdate <-
Zuora.fetchInvoicePreview(subscriptionAfterUpdate.accountId, invoicePreviewTargetDate)
newPrice <-
ZIO.fromEither(
AmendmentData.totalChargeAmount(
subscriptionAfterUpdate,
invoicePreviewAfterUpdate,
amendmentEffectiveDate
)
)
today <- Clock.currentDateTime.map(_.toLocalDate)
_ <- ZIO
.fromEither(
AmendmentHandlerHelper
.postAmendmentPriceCheck(cohortSpec, item, subscriptionAfterUpdate, commsPrice, newPrice, today)
)
.mapError(message => AmendmentFailure(message))
// Date: 29 October 2025
// Author: Pascal
// This check was introduced to add extra security to N4. To be decommissioned at the end of N4
// unless we decide to generalise it and absorb the price check and the billing period check in
// one single unit.
_ <- (MigrationType(cohortSpec) match {
case ProductMigration2025N4 =>
ZIO.fromEither(
ProductMigration2025N4Migration.postAmendmentStructureIntegrityCheck(
subscriptionBeforeUpdate,
subscriptionAfterUpdate,
today
)
)
case _ => ZIO.succeed(())
}).mapError(message => AmendmentFailure(message))
whenDone <- Clock.instant
} yield AARSuccessfulAmendment(
item.subscriptionName,
amendmentEffectiveDate,
newPrice,
subscriptionAfterUpdate.id,
whenDone
)
}
private def performAmendmentAttemptWithResult(
cohortSpec: CohortSpec,
item: CohortItem
): ZIO[Zuora with Logging with SalesforceClient, Failure, AmendmentAttemptResult] = {
MigrationType(cohortSpec) match {
case Test1 => ZIO.fail(ConfigFailure("Branch not supported"))
case GuardianWeekly2025 =>
doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec: CohortSpec,
item: CohortItem
)
case Newspaper2025P1 =>
doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec: CohortSpec,
item: CohortItem
)
case Newspaper2025P3 =>
doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec: CohortSpec,
item: CohortItem
)
case ProductMigration2025N4 => {
for {
salesforcePriceRiseId <- ZIO
.fromOption(item.salesforcePriceRiseId)
.orElseFail(AmendmentFailure(s"Missing salesforcePriceRiseId for ${item.subscriptionName}"))
priceRise <- SalesforceClient.getPriceRise(salesforcePriceRiseId)
optOutFlag <- ZIO
.fromOption(priceRise.Customer_Opt_Out__c)
.orElseFail(
AmendmentFailure(
s"Missing Customer_Opt_Out__c in price rise $salesforcePriceRiseId, subscription: ${item.subscriptionName}"
)
)
result <-
if (optOutFlag)
ZIO.succeed(AARUserOptOut(item.subscriptionName))
else
doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec,
item
)
} yield result
}
case Membership2025 =>
doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec: CohortSpec,
item: CohortItem
)
case DigiSubs2025 =>
doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec: CohortSpec,
item: CohortItem
)
case SupporterPlus2026 =>
doAmendmentUsingOrdersApiWithJsonValues(
cohortSpec: CohortSpec,
item: CohortItem
)
}
}
def handle(input: CohortSpec): ZIO[Logging, Failure, HandlerOutput] = {
main(input).provideSome[Logging](
EnvConfig.cohortTable.layer,
EnvConfig.zuora.layer,
EnvConfig.stage.layer,
DynamoDBZIOLive.impl,
DynamoDBClientLive.impl,
CohortTableLive.impl(input),
ZuoraLive.impl,
SalesforceClientLive.impl,
EnvConfig.salesforce.layer
)
}
}