in handlers/dev-env-cleaner/src/main/scala/com/gu/cleaner/Handler.scala [130:190]
def steps(
aquaQuerier: AquaQueryRequest => ClientFailableOp[String],
getJobResult: JobResultRequest => ClientFailableOp[JobResult],
downloadRequests: RestRequestMaker.Requests,
cancelSub: CancelSub,
cancelAccount: CancelAccount,
removeAccountCrm: RemoveAccountCrm,
deleteAccount: DeleteAccount,
today: () => LocalDate,
): Either[Throwable, Unit] = {
val subs_to_cancel = "subs_to_cancel"
val subsQuery = AquaQuery(
subs_to_cancel,
"""select Id, TermEndDate
|from Subscription
|where (billtocontact.WorkEmail LIKE '%@thegulocal.com' OR (billtocontact.WorkEmail LIKE 'test%' AND billtocontact.WorkEmail LIKE '%@theguardian.com')) and Status = 'Active' and account.Status = 'Active'
|""".stripMargin,
)
val accounts_to_cancel = "accounts_to_cancel"
val accountsQuery = AquaQuery(
accounts_to_cancel,
"""select Id, CreditBalance
|from Account
|where (billtocontact.WorkEmail LIKE '%@thegulocal.com' OR (billtocontact.WorkEmail LIKE 'test%' AND billtocontact.WorkEmail LIKE '%@theguardian.com')) and Status = 'Active'
|""".stripMargin,
)
val request = AquaQueryRequest(
name = "test_accounts_and_subs",
queries = List(subsQuery, accountsQuery),
)
val zRes = for {
jobId <- aquaQuerier(request)
batches <- waitForResult(jobId, getJobResult)
streams <- batches.toList.traverse { batch =>
downloadRequests
.getDownloadStream(s"batch-query/file/${batch.fileId}")
.map(stream => (batch.name, stream.stream))
}
queryResults = streams.map { case (name, stream) =>
val csvLines = Source.fromInputStream(stream).getLines()
val values = csvLines.drop(1).map(_.split(',').toList) // first line is a header
(name, values)
}.toMap
_ <- queryResults(subs_to_cancel)
.map { case id :: termEndDate :: Nil => cancelSub.run(id, dateToCancel(LocalDate.parse(termEndDate), today())) }
.toList
.sequence
_ <- queryResults(accounts_to_cancel)
.map { case id :: creditBalance :: Nil =>
for {
_ <- creditBalance.toDouble match {
case 0 => cancelAccount.run(id)
case _ =>
removeAccountCrm.run(id) // can't cancel an account with a credit balance, so just remove the CRMId
}
_ <- deleteAccount.run(id)
} yield ()
}
.toList
.sequence
} yield ()