summaryrefslogtreecommitdiffstats
path: root/app/Import/Ing/CurrentAccountCsv.hs
blob: bf287302c8fae321dbaa98e4adfeb1dbfa1b0809 (about) (plain) (blame)
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
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}

module Import.Ing.CurrentAccountCsv where

import Control.Applicative ((<|>))
import Data.ByteString.Lazy qualified as BS
import Data.Csv ((.:))
import Data.Csv qualified as C
import Data.Decimal (Decimal)
import Data.Functor ((<&>))
import Data.Iban (Iban)
import Data.Text qualified as T
import Data.Time.Calendar (Day)
import Data.Time.Clock (UTCTime)
import Data.Time.Zones (TZ, loadTZFromDB)
import Data.Vector qualified as V
import Import.Ing.Shared
  ( DebitCredit (Credit, Debit),
    dateCP,
    decimalCP,
    ibanCP,
    maybeCP,
    scsvOptions,
    timestampCP,
  )
import System.IO (Handle)
import Text.Regex.TDFA ((=~~))

data TransactionType
  = AcceptGiro -- AC (acceptgiro)
  | AtmWithdrawal -- GM (geldautomaat, Giromaat)
  | BatchPayment -- VZ (verzamelbetaling); 'Batch payment'
  | BranchPosting -- FL (filiaalboeking)
  | Deposit -- ST (storting)
  | DirectDebit -- IC (incasso); 'SEPA direct debit'
  | Ideal -- ID (iDEAL); 'iDEAL'
  | OnlineBanking -- GT (internetbankieren, Girotel); 'Online Banking'
  | OfficeWithdrawal -- PK (opname kantoor, postkantoor)
  | PaymentTerminal -- BA (betaalautomaat); 'Payment terminal'
  | PeriodicTransfer -- PO (periodieke overschrijving)
  | PhoneBanking -- GF (telefonisch bankieren, Girofoon)
  | Transfer -- OV (overboeking); 'Transfer'
  | Various -- DV (diversen)
  deriving (Eq, Show)

parseCode :: T.Text -> C.Parser TransactionType
parseCode "AC" = return AcceptGiro
parseCode "GM" = return AtmWithdrawal
parseCode "VZ" = return BatchPayment
parseCode "FL" = return BranchPosting
parseCode "ST" = return Deposit
parseCode "IC" = return DirectDebit
parseCode "ID" = return Ideal
parseCode "GT" = return OnlineBanking
parseCode "PK" = return OfficeWithdrawal
parseCode "BA" = return PaymentTerminal
parseCode "PO" = return PeriodicTransfer
parseCode "GF" = return PhoneBanking
parseCode "OV" = return Transfer
parseCode "DV" = return Various
parseCode t = fail $ "Unknown transaction code '" ++ T.unpack t ++ "'"

parseType :: T.Text -> C.Parser TransactionType
parseType "SEPA direct debit" = return DirectDebit
parseType "Batch payment" = return BatchPayment
parseType "Online Banking" = return OnlineBanking
parseType "Payment terminal" = return PaymentTerminal
parseType "Transfer" = return Transfer
parseType "iDEAL" = return Ideal
parseType t = fail $ "Unknown transaction type '" ++ T.unpack t ++ "'"

data PrimTx = PrimTx
  { ptDate :: !Day,
    ptDesc :: !(Maybe T.Text),
    ptAccount :: !Iban,
    ptCounterparty :: !(Maybe Iban),
    ptDebitCredit :: !DebitCredit,
    ptAmount :: !Decimal,
    ptResBal :: !Decimal,
    ptTag :: !T.Text,
    ptMoreData :: !MoreData
  }
  deriving (Show)

data MoreData
  = PaymentTerminalData
      { ptCardSequenceNo :: !T.Text,
        ptTimestamp :: !UTCTime,
        ptTransaction :: !T.Text,
        ptTerminal :: !T.Text,
        ptValueDate :: !Day,
        ptGooglePay :: !Bool
      }
  | DepositTransferData
      { dtName :: !T.Text,
        dtDescription :: !T.Text,
        dtIban :: !Iban,
        dtReference :: !T.Text,
        dtValueDate :: !Day
      }
  | RoundingSavingsDeposit
      { rsdSavingsAccount :: !T.Text,
        rsdValueDate :: !Day
      }
  | OnlineBankingCredit
      { obcName :: !T.Text,
        obcDescription :: !T.Text,
        obcIban :: !Iban,
        obcTimestamp :: !UTCTime,
        obcValueDate :: !Day
      }
  | OnlineBankingDebit
      { obdName :: !T.Text,
        obdDescription :: !T.Text,
        obdIban :: !Iban,
        obdTimestamp :: !(Maybe UTCTime),
        obdValueDate :: !Day
      }
  | RecurrentDirectDebitData
      { rddName :: !T.Text,
        rddDescription :: !T.Text,
        rddIban :: !Iban,
        rddReference :: !T.Text,
        rddMandateId :: !T.Text,
        rddCreditorId :: !T.Text,
        rddOtherParty :: !(Maybe T.Text),
        rddValueDate :: !Day
      }
  | IdealDebitData
      { idName :: !T.Text,
        idDescription :: !T.Text,
        idIban :: !Iban,
        idTimestamp :: !UTCTime,
        idReference :: !T.Text,
        idValueDate :: !Day
      }
  | PaymentTerminalCashbackData
      { ptcCardSequenceNo :: !T.Text,
        ptcTimestamp :: !UTCTime,
        ptcTransaction :: !T.Text,
        ptcTerminal :: !T.Text,
        ptcValueDate :: !Day
      }
  | BatchPaymentData
      { bpName :: !T.Text,
        bpDescription :: !T.Text,
        bpIban :: !Iban,
        bpReference :: !T.Text,
        bpValueDate :: !Day
      }
  deriving (Show)

maybeNotProvided :: T.Text -> Maybe T.Text
maybeNotProvided t = if t == "NOTPROVIDED" then Nothing else Just t

valueDateCP :: T.Text -> C.Parser Day
valueDateCP = dateCP "%d/%m/%Y"

data PartTx = PartTx !Day !TransactionType !DebitCredit

notificationsCP :: TZ -> PartTx -> T.Text -> C.Parser MoreData
notificationsCP _ (PartTx _ Transfer Credit) t = do
  let regex = "^Name: (.*) Description: (.*) IBAN: ([A-Z0-9]+) Reference: (.*) Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [name, desc, ibanTxt, ref, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  iban <- ibanCP ibanTxt
  valDate <- valueDateCP valDateTxt
  return $
    DepositTransferData
      { dtName = name,
        dtDescription = desc,
        dtIban = iban,
        dtReference = ref,
        dtValueDate = valDate
      }
notificationsCP _ (PartTx _ Transfer Debit) t = do
  let regex = "^To Oranje spaarrekening ([A-Z0-9]+) Afronding Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [savingsAccount, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  valDate <- valueDateCP valDateTxt
  return $
    RoundingSavingsDeposit
      { rsdSavingsAccount = savingsAccount,
        rsdValueDate = valDate
      }
notificationsCP amsTz (PartTx _ PaymentTerminal Debit) t = do
  let regex = "^Card sequence no.: ([0-9]+) ? ([0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2}) Transaction: (.*) Term: ((.+) Google Pay|(.+)) Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [cardSeqNo, timestampTxt, transaction, _, gpayTerm, noGpayTerm, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  timestamp <- timestampCP "%d/%m/%Y %H:%M" amsTz timestampTxt
  valDate <- valueDateCP valDateTxt
  return $
    PaymentTerminalData
      { ptCardSequenceNo = cardSeqNo,
        ptTimestamp = timestamp,
        ptTransaction = transaction,
        ptTerminal = if T.null gpayTerm then noGpayTerm else gpayTerm,
        ptValueDate = valDate,
        ptGooglePay = T.null noGpayTerm
      }
notificationsCP amsTz (PartTx _ PaymentTerminal Credit) t = do
  let regex = "^Card sequence no.: ([0-9]+) ? ([0-9]{2}/[0-9]{2}/[0-9]{4} [0-9]{2}:[0-9]{2}) Transaction: (.*) Term: (.*) Cashback transaction Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [cardSeqNo, timestampTxt, transaction, term, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  timestamp <- timestampCP "%d/%m/%Y %H:%M" amsTz timestampTxt
  valDate <- valueDateCP valDateTxt
  return $
    PaymentTerminalCashbackData
      { ptcCardSequenceNo = cardSeqNo,
        ptcTimestamp = timestamp,
        ptcTransaction = transaction,
        ptcTerminal = term,
        ptcValueDate = valDate
      }
notificationsCP amsTz (PartTx _ OnlineBanking Credit) t = do
  let regex = "^Name: (.*) Description: (.*) IBAN: ([A-Z0-9]+) Date/time: ([0-9]{2}-[0-9]{2}-[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}) Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [name, desc, ibanTxt, timestampTxt, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  iban <- ibanCP ibanTxt
  timestamp <- timestampCP "%d-%m-%Y %H:%M:%S" amsTz timestampTxt
  valDate <- valueDateCP valDateTxt
  return $
    OnlineBankingCredit
      { obcName = name,
        obcDescription = desc,
        obcIban = iban,
        obcTimestamp = timestamp,
        obcValueDate = valDate
      }
notificationsCP amsTz (PartTx _ OnlineBanking Debit) t = do
  let regex = "^Name: (.*) Description: (.*) IBAN: ([A-Z0-9]+) (Date/time: ([0-9]{2}-[0-9]{2}-[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}) )?Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [name, desc, ibanTxt, _, timestampTxt, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  iban <- ibanCP ibanTxt
  timestamp <-
    if T.null timestampTxt
      then pure Nothing
      else Just <$> timestampCP "%d-%m-%Y %H:%M:%S" amsTz timestampTxt
  valDate <- valueDateCP valDateTxt
  return $
    OnlineBankingDebit
      { obdName = name,
        obdDescription = desc,
        obdIban = iban,
        obdTimestamp = timestamp,
        obdValueDate = valDate
      }
notificationsCP _ (PartTx date DirectDebit Debit) t = normalRecurrentDirectDebit <|> ingInsurancePayment
  where
    normalRecurrentDirectDebit = do
      let regex = "^Name: (.*) Description: (.*) IBAN: ([A-Z0-9]+) Reference: (.*) Mandate ID: (.*) Creditor ID: (.*) Recurrent SEPA direct debit (Other party: (.*) )?Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
      (_, _, _, [name, desc, ibanTxt, ref, mandateId, creditorId, _, otherParty, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
      iban <- ibanCP ibanTxt
      valDate <- valueDateCP valDateTxt
      return $
        RecurrentDirectDebitData
          { rddName = name,
            rddDescription = desc,
            rddIban = iban,
            rddReference = ref,
            rddMandateId = mandateId,
            rddCreditorId = creditorId,
            rddOtherParty = if T.null otherParty then Nothing else Just otherParty,
            rddValueDate = valDate
          }
    ingInsurancePayment = do
      let regex = "^Name: (.* ING Verzekeren) Description: (.*) IBAN: ([A-Z0-9]+) Reference: (.*) Mandate ID: (.*) Creditor ID: (.*) Recurrent SEPA direct debit$" :: String
      (_, _, _, [name, desc, ibanTxt, ref, mandateId, creditorId]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
      iban <- ibanCP ibanTxt
      return $
        RecurrentDirectDebitData
          { rddName = name,
            rddDescription = desc,
            rddIban = iban,
            rddReference = ref,
            rddMandateId = mandateId,
            rddCreditorId = creditorId,
            rddOtherParty = Nothing,
            rddValueDate = date
          }
notificationsCP amsTz (PartTx _ Ideal Debit) t = do
  let regex = "^Name: (.*) Description: (.*) IBAN: ([A-Z0-9]+) Reference: ([0-9]{2}-[0-9]{2}-[0-9]{4} [0-9]{2}:[0-9]{2}) ([0-9]+) Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [name, desc, ibanTxt, timestampTxt, ref, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  iban <- ibanCP ibanTxt
  timestamp <- timestampCP "%d-%m-%Y %H:%M" amsTz timestampTxt
  valDate <- valueDateCP valDateTxt
  return $
    IdealDebitData
      { idName = name,
        idDescription = desc,
        idIban = iban,
        idTimestamp = timestamp,
        idReference = ref,
        idValueDate = valDate
      }
notificationsCP _ (PartTx _ BatchPayment Credit) t = do
  let regex = "^Name: (.*) Description: (.*) IBAN: ([A-Z0-9]+) Reference: (.*) Value date: ([0-9]{2}/[0-9]{2}/[0-9]{4})$" :: String
  (_, _, _, [name, desc, ibanTxt, ref, valDateTxt]) <- t =~~ regex :: C.Parser (T.Text, T.Text, T.Text, [T.Text])
  iban <- ibanCP ibanTxt
  valDate <- valueDateCP valDateTxt
  return $
    BatchPaymentData
      { bpName = name,
        bpDescription = desc,
        bpIban = iban,
        bpReference = ref,
        bpValueDate = valDate
      }
notificationsCP _ (PartTx _ ty cd) _ = fail $ "Unmatched type and debit/credit combination (" ++ show ty ++ ", " ++ show cd ++ ")"

debitCreditCP :: T.Text -> C.Parser DebitCredit
debitCreditCP "Debit" = return Debit
debitCreditCP "Credit" = return Credit
debitCreditCP t = fail ("Unknown debit/credit value '" ++ T.unpack t ++ "'")

parseNamedRecord :: TZ -> C.NamedRecord -> C.Parser PrimTx
parseNamedRecord amsTz m = do
  date <- m .: "Date" >>= dateCP "%0Y%m%d"
  debitCredit <- m .: "Debit/credit" >>= debitCreditCP
  codeText <- m .: "Code"
  tyText <- m .: "Transaction type"
  tyFromCode <- parseCode codeText
  ty <- parseType tyText
  if ty /= tyFromCode
    then
      fail $ "Code '" ++ T.unpack codeText ++ "' and transaction type '" ++ T.unpack tyText ++ "' do not agree"
    else
      PrimTx date
        <$> (m .: "Name / Description" <&> maybeNotProvided)
        <*> (m .: "Account" >>= ibanCP)
        <*> (m .: "Counterparty" >>= maybeCP ibanCP)
        <*> pure debitCredit
        <*> (m .: "Amount (EUR)" >>= decimalCP)
        <*> (m .: "Resulting balance" >>= decimalCP)
        <*> m .: "Tag"
        <*> (m .: "Notifications" >>= notificationsCP amsTz (PartTx date ty debitCredit))

readFile :: Handle -> IO (V.Vector PrimTx)
readFile h = do
  tz <- loadTZFromDB "Europe/Amsterdam"
  contents <- BS.hGetContents h
  case C.decodeByNameWithP (parseNamedRecord tz) scsvOptions contents of
    Left err -> fail err
    Right
      ( [ "Date",
          "Name / Description",
          "Account",
          "Counterparty",
          "Code",
          "Debit/credit",
          "Amount (EUR)",
          "Transaction type",
          "Notifications",
          "Resulting balance",
          "Tag"
          ],
        txs
        ) ->
        return txs
    Right _ ->
      fail "Headers do not match expected pattern"