File size: 10,339 Bytes
c09f67c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Providers } from "@engine/common/schema";
import type { AccountType } from "@engine/utils/account";
import { getFileExtension, getLogoURL } from "@engine/utils/logo";
import { capitalCase } from "change-case";
import { addDays } from "date-fns";
import type {
  Account as BaseAccount,
  Transaction as BaseTransaction,
  ConnectionStatus,
  GetAccountBalanceResponse,
} from "../types";
import type {
  GetRequisitionResponse,
  Institution,
  Transaction,
  TransactionDescription,
  TransformAccount,
  TransformAccountBalance,
  TransformAccountName,
  TransformInstitution,
} from "./types";
import { getAccessValidForDays } from "./utils";

/**
 * Maps GoCardless cashAccountType (ISO 20022) to Midday AccountType
 * - CACC: Current account β†’ depository
 * - CARD: Card account β†’ credit
 * - SVGS: Savings account β†’ depository
 * - TRAN: Transaction account β†’ depository
 * - LOAN: Loan account β†’ loan
 */
const getAccountType = (cashAccountType?: string): AccountType => {
  switch (cashAccountType) {
    case "CARD":
      return "credit";
    case "LOAN":
      return "loan";
    default:
      // CACC, SVGS, TRAN, CASH, and others default to depository
      return "depository";
  }
};

type MapTransactionCategory = {
  transaction: Transaction;
  accountType: AccountType;
};

export const mapTransactionCategory = ({
  transaction,
  accountType,
}: MapTransactionCategory) => {
  const amount = +transaction.transactionAmount.amount;

  if (amount > 0) {
    // For credit accounts, positive amount means money came IN (payment, refund, cashback)
    if (accountType === "credit") {
      // Check if it's a transfer/payment type
      const method = transaction.proprietaryBankTransactionCode;
      if (method === "Transfer" || method === "Payment") {
        return "credit-card-payment";
      }
      // Otherwise it's likely a refund - don't auto-categorize
      return null;
    }
    return "income";
  }

  return null;
};

export const mapTransactionMethod = (type?: string) => {
  switch (type) {
    case "Payment":
    case "Bankgiro payment":
    case "Incoming foreign payment":
      return "payment";
    case "Card purchase":
    case "Card foreign purchase":
      return "card_purchase";
    case "Card ATM":
      return "card_atm";
    case "Transfer":
      return "transfer";
    default:
      return "other";
  }
};

export const transformTransactionName = (transaction: Transaction) => {
  if (transaction?.creditorName) {
    return capitalCase(transaction.creditorName);
  }

  if (transaction?.debtorName) {
    return capitalCase(transaction?.debtorName);
  }

  if (transaction?.additionalInformation) {
    return capitalCase(transaction.additionalInformation);
  }

  if (transaction?.remittanceInformationStructured) {
    return capitalCase(transaction.remittanceInformationStructured);
  }

  if (transaction?.remittanceInformationUnstructured) {
    return capitalCase(transaction.remittanceInformationUnstructured);
  }

  const remittanceInformation =
    transaction?.remittanceInformationUnstructuredArray?.at(0);

  if (remittanceInformation) {
    return capitalCase(remittanceInformation);
  }

  console.log("No transaction name", transaction);

  // When there is no name, we use the proprietary bank transaction code (Service Fee)
  if (transaction.proprietaryBankTransactionCode) {
    return transaction.proprietaryBankTransactionCode;
  }

  return "No information";
};

const transformDescription = ({
  transaction,
  name,
}: TransactionDescription) => {
  if (transaction?.remittanceInformationUnstructuredArray?.length) {
    const text = transaction?.remittanceInformationUnstructuredArray.join(" ");
    const description = capitalCase(text);

    // NOTE: Sometimes the description is the same as name
    // Let's skip that and just save if they are not the same
    if (description !== name) {
      return description;
    }
  }

  const additionalInformation =
    transaction.additionalInformation &&
    capitalCase(transaction.additionalInformation);

  if (additionalInformation !== name) {
    return additionalInformation;
  }

  return null;
};

const transformCounterpartyName = (transaction: Transaction) => {
  if (transaction?.debtorName) {
    return capitalCase(transaction.debtorName);
  }

  if (transaction?.creditorName) {
    return capitalCase(transaction.creditorName);
  }

  return null;
};

type TransformTransactionPayload = {
  transaction: Transaction;
  accountType: AccountType;
};

export const transformTransaction = ({
  transaction,
  accountType,
}: TransformTransactionPayload): BaseTransaction => {
  const method = mapTransactionMethod(
    transaction?.proprietaryBankTransactionCode,
  );

  let currencyExchange: { rate: number; currency: string } | undefined;

  if (Array.isArray(transaction.currencyExchange)) {
    const rate = +(transaction.currencyExchange.at(0)?.exchangeRate ?? "");

    if (rate) {
      const currency = transaction?.currencyExchange?.at(0)?.sourceCurrency;

      if (currency) {
        currencyExchange = {
          rate,
          currency: currency.toUpperCase(),
        };
      }
    }
  }

  const name = transformTransactionName(transaction);
  const description = transformDescription({ transaction, name }) ?? null;
  const balance = transaction?.balanceAfterTransaction?.balanceAmount?.amount
    ? +transaction.balanceAfterTransaction.balanceAmount.amount
    : null;

  return {
    id: transaction.internalTransactionId,
    date: transaction.bookingDate,
    name,
    method,
    amount: +transaction.transactionAmount.amount,
    currency: transaction.transactionAmount.currency,
    category: mapTransactionCategory({ transaction, accountType }),
    currency_rate: currencyExchange?.rate || null,
    currency_source: currencyExchange?.currency?.toUpperCase() || null,
    balance,
    counterparty_name: transformCounterpartyName(transaction),
    merchant_name: null,
    description,
    status: "posted",
  };
};

const transformAccountName = (account: TransformAccountName) => {
  // First try to use the name from the account
  if (account?.name) {
    return capitalCase(account.name);
  }

  // Then try to use the product
  if (account?.product) {
    return account.product;
  }

  // Then try to use the institution name
  if (account?.institution?.name) {
    return `${account.institution.name} (${account.currency.toUpperCase()})`;
  }

  // Last use a default name
  return "No name";
};

/**
 * Extract available balance from GoCardless balances array.
 * Looks for interimAvailable balance type first, falls back to expected.
 */
const getAvailableBalance = (
  balances?: TransformAccount["balances"],
): number | null => {
  if (!balances?.length) return null;

  const interimAvailable = balances.find(
    (b) => b.balanceType === "interimAvailable",
  );
  if (interimAvailable) {
    return +interimAvailable.balanceAmount.amount;
  }

  // Fall back to expected balance if no interimAvailable
  const expected = balances.find((b) => b.balanceType === "expected");
  if (expected) {
    return +expected.balanceAmount.amount;
  }

  return null;
};

export const transformAccount = ({
  id,
  account,
  balance,
  balances,
  institution,
}: TransformAccount): BaseAccount => {
  const accountType = getAccountType(account.cashAccountType);

  return {
    id,
    type: accountType,
    name: transformAccountName({
      name: account.name,
      product: account.product,
      institution: institution,
      currency: account.currency.toUpperCase(),
    }),
    currency: account.currency.toUpperCase(),
    enrollment_id: null,
    balance: transformAccountBalance({ balance, accountType }),
    institution: transformInstitution(institution),
    resource_id: account.resourceId,
    expires_at: addDays(
      new Date(),
      getAccessValidForDays({ institutionId: institution.id }),
    ).toISOString(),
    iban: account.iban || null,
    subtype: null, // GoCardless uses cashAccountType for type, no additional subtype
    bic: institution.bic || null,
    // US bank details not available for GoCardless (EU/UK provider)
    routing_number: null,
    wire_routing_number: null,
    account_number: null,
    sort_code: null,
    // Credit account balances - GoCardless provides available via balance types
    available_balance: getAvailableBalance(balances),
    credit_limit: null, // GoCardless only has creditLimitIncluded boolean, not actual limit
  };
};

type TransformAccountBalanceParams = {
  balance?: TransformAccountBalance;
  balances?: TransformAccount["balances"];
  accountType?: string;
};

/**
 * Transform GoCardless balance to internal format.
 *
 * GoCardless stores credit card balances as NEGATIVE values (e.g., -1000 means $1000 owed).
 * We normalize to POSITIVE values for consistency with other providers (Plaid, Teller, Enable Banking).
 *
 * @param balance - The raw balance from GoCardless
 * @param balances - Full balances array for available_balance extraction
 * @param accountType - The account type (credit accounts get normalized)
 */
export const transformAccountBalance = ({
  balance,
  balances,
  accountType,
}: TransformAccountBalanceParams): GetAccountBalanceResponse => {
  const rawAmount = +(balance?.amount ?? 0);

  // GoCardless stores credit card debt as negative values (e.g., -1000 = $1000 owed)
  // Normalize to positive for consistency with other providers
  const amount =
    accountType === "credit" && rawAmount < 0 ? Math.abs(rawAmount) : rawAmount;

  return {
    currency: balance?.currency.toUpperCase() || "EUR",
    amount,
    available_balance: getAvailableBalance(balances),
    credit_limit: null, // GoCardless only has creditLimitIncluded boolean, not actual limit
  };
};

export const transformInstitution = (
  institution: Institution,
): TransformInstitution => ({
  id: institution.id,
  name: institution.name,
  logo: getLogoURL(institution.id, getFileExtension(institution.logo)),
  provider: Providers.enum.gocardless,
});

export const transformConnectionStatus = (
  requisition?: GetRequisitionResponse,
): ConnectionStatus => {
  // Expired or Rejected
  if (requisition?.status === "EX" || requisition?.status === "RJ") {
    return {
      status: "disconnected",
    };
  }

  return {
    status: "connected",
  };
};