-
Notifications
You must be signed in to change notification settings - Fork 0
/
RogersAccount.swift
285 lines (262 loc) · 11 KB
/
RogersAccount.swift
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
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/// A credit card account
public protocol Account {
/// Customer
var customer: Customer { get }
/// Internal ID
var accountId: String { get }
/// Account type, e.g. Personal
var accountType: String { get }
/// Payment status, e.g. Paid
var paymentStatus: String { get }
/// Product Name, e.g. World Elite
var productName: String { get }
/// Code for product
var productExternalCode: String { get }
/// ISO symbol of account currency
var accountCurrency: String { get }
/// Brand name, e.g. ROGERSBRAND
var brandId: String { get }
/// Date the Account was opend
var openedDate: Date { get }
/// Date of the last statement
var previousStatementDate: Date { get }
/// Date the payment of the current statement is due (might be in the past)
var paymentDueDate: Date { get }
/// Date of the last payment
var lastPaymentDate: Date { get }
/// List of past statement dates
var cycleDates: [Date] { get }
/// Current balance
var currentBalance: Amount { get }
/// Balance on the last Statement
var statementBalance: Amount { get }
/// Amount which is still due for the statement
var statementDueAmount: Amount { get }
/// Credit limit
var creditLimit: Amount { get }
/// Amount charged since the last statement
var purchasesSinceLastCycle: Amount? { get }
/// Amount of the last payment
var lastPayment: Amount { get }
/// Remaining credit limit
var realtimeBalance: Amount { get }
/// Cash Advance available
var cashAvailable: Amount { get }
/// Cash Advance limit
var cashLimit: Amount { get }
/// Multi Card
var multiCard: Bool { get }
/// Download a statement
/// - Parameters:
/// - statement: the statement to download
/// - completion: completion handler, called with either a temporary URL to the downloaded file or a DownloadError
func downloadStatement(statement: Statement, completion: @escaping (Result<URL, DownloadError>) -> Void)
/// Search Statements
/// - Parameters:
/// - completion: completion handler, called with either the Statements or a DownloadError
func searchStatements(completion: @escaping (Result<[Statement], DownloadError>) -> Void)
/// Downloads the transactions
/// - Parameters:
/// - statementNumber: number of the statement for which the transactions should be downloaded, with 0 mean current period, 1 means last statement, ...
/// - completion: completion handler, called with either the Transactions or a DownloadError
func downloadActivities(statementNumber: Int, completion: @escaping (Result<[Activity], DownloadError>) -> Void)
}
public struct RogersAccount: Account, Codable {
enum CodingKeys: String, CodingKey {
case accountId
case accountType
case paymentStatus
case productName
case productExternalCode
case accountCurrency
case brandId
case openedDate
case previousStatementDate
case paymentDueDate
case lastPaymentDate
case cycleDates
case multiCard
case rogersCurrentBalance = "currentBalance"
case rogersStatementBalance = "statementBalance"
case rogersStatementDueAmount = "statementDueAmount"
case rogersCreditLimit = "creditLimit"
case rogersPurchasesSinceLastCycle = "purchasesSinceLastCycle"
case rogersLastPayment = "lastPayment"
case rogersRealtimeBalance = "realtimeBalance"
case rogersCashAvailable = "cashAvailable"
case rogersCashLimit = "cashLimit"
case rogersCustomer = "customer"
}
private static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
private static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Self.dateFormatter)
return decoder
}()
public let accountId: String
public let accountType: String
public let paymentStatus: String
public let productName: String
public let productExternalCode: String
public let accountCurrency: String
public let brandId: String
public let openedDate: Date
public let previousStatementDate: Date
public let paymentDueDate: Date
public let lastPaymentDate: Date
public let cycleDates: [Date]
public let multiCard: Bool
private let rogersStatementBalance: RogersAmount
private let rogersCurrentBalance: RogersAmount
private let rogersStatementDueAmount: RogersAmount
private let rogersCreditLimit: RogersAmount
private let rogersPurchasesSinceLastCycle: RogersAmount?
private let rogersLastPayment: RogersAmount
private let rogersRealtimeBalance: RogersAmount
private let rogersCashAvailable: RogersAmount
private let rogersCashLimit: RogersAmount
private let rogersCustomer: RogersCustomer
public var customer: Customer {
rogersCustomer
}
public var statementBalance: Amount {
rogersStatementBalance
}
public var currentBalance: Amount {
rogersCurrentBalance
}
public var statementDueAmount: Amount {
rogersStatementDueAmount
}
public var creditLimit: Amount {
rogersCreditLimit
}
public var purchasesSinceLastCycle: Amount? {
rogersPurchasesSinceLastCycle
}
public var lastPayment: Amount {
rogersLastPayment
}
public var realtimeBalance: Amount {
rogersRealtimeBalance
}
public var cashLimit: Amount {
rogersCashLimit
}
public var cashAvailable: Amount {
rogersCashAvailable
}
private var activityURLComponents: URLComponents {
URLComponents(string: "https://rbaccess.rogersbank.com/issuing/digital/account/\(accountId)/customer/\(customer.customerId)/activity")!
}
private var statementSearchURL: URL {
URL(string: "https://rbaccess.rogersbank.com/issuing/digital/account/\(accountId)/customer/\(customer.customerId)/estatement/search")!
}
private func statementDownloadURL(statement: Statement) -> URL {
URL(string: "https://rbaccess.rogersbank.com/issuing/digital/account/\(accountId)/customer/\(customer.customerId)/estatement/\(statement.statementId)/view")!
}
public func downloadStatement(statement: Statement, completion: @escaping (Result<URL, DownloadError>) -> Void) {
var request = URLRequest(url: statementDownloadURL(statement: statement))
request.httpMethod = "GET"
let task = URLSession.shared.downloadTask(with: request) { url, response, error in
guard let url else {
if let error {
completion(.failure(DownloadError.httpError(error: error.localizedDescription)))
} else {
completion(.failure(DownloadError.noDataReceived))
}
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(DownloadError.httpError(error: "No HTTPURLResponse")))
return
}
guard httpResponse.statusCode == 200 else {
completion(.failure(DownloadError.httpError(error: "Status code \(httpResponse.statusCode)")))
return
}
completion(.success(url))
}
task.resume()
}
public func searchStatements(completion: @escaping (Result<[Statement], DownloadError>) -> Void) {
var request = URLRequest(url: statementSearchURL)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data else {
if let error {
completion(.failure(DownloadError.httpError(error: error.localizedDescription)))
} else {
completion(.failure(DownloadError.noDataReceived))
}
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(.failure(DownloadError.httpError(error: "No HTTPURLResponse")))
return
}
guard httpResponse.statusCode == 200 else {
completion(.failure(DownloadError.httpError(error: "Status code \(httpResponse.statusCode)")))
return
}
do {
let statements = try Self.decoder.decode(Statements.self, from: data)
completion(.success(statements.monthlyStatements))
} catch {
completion(.failure(DownloadError.invalidJson(error: String(describing: error))))
return
}
}
task.resume()
}
public func downloadActivities(statementNumber: Int, completion: @escaping (Result<[Activity], DownloadError>) -> Void) {
downloadActivities(statementNumber: statementNumber, retryAttempt: 0, completion: completion)
}
public func downloadActivities(statementNumber: Int, retryAttempt: Int, completion: @escaping (Result<[Activity], DownloadError>) -> Void) {
guard statementNumber >= 0 && cycleDates.count >= statementNumber else {
completion(.failure(DownloadError.invalidStatementNumber(statementNumber)))
return
}
var urlComponents = activityURLComponents
if statementNumber > 0 {
urlComponents.queryItems = [URLQueryItem(name: "cycleStartDate", value: Self.dateFormatter.string(from: cycleDates[statementNumber - 1]))]
}
var request = URLRequest(url: urlComponents.url!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
let processedResponse = URLTaskHelper.processResponse(data: data, response: response, error: error)
guard case let .success((data, httpResponse)) = processedResponse else {
if case let .failure(error) = processedResponse {
completion(.failure(error))
}
return
}
guard httpResponse.statusCode == 200 else {
if retryAttempt < 2 {
downloadActivities(statementNumber: statementNumber, retryAttempt: retryAttempt + 1, completion: completion)
} else {
completion(.failure(DownloadError.httpError(error: "Status code \(httpResponse.statusCode)")))
}
return
}
completion(parseData(data))
}
task.resume()
}
private func parseData(_ data: Data) -> Result<[Activity], DownloadError> {
do {
let activities = try Self.decoder.decode(Activities.self, from: data)
return .success(activities.activities ?? [])
} catch {
return .failure(DownloadError.invalidJson(error: String(describing: error)))
}
}
}