File size: 7,770 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
import { Providers } from "@engine/common/schema";
import { getType } from "@engine/utils/account";
import { getLogoURL } from "@engine/utils/logo";
import { capitalCase } from "change-case";
import type {
  Account as BaseAccount,
  Transaction as BaseTransaction,
  GetAccountBalanceResponse,
} from "../types";
import type {
  FormatAmount,
  Transaction,
  TransformAccount,
  TransformAccountBalance,
  TransformInstitution,
  TransformTransaction,
} from "./types";

export const mapTransactionMethod = (type?: string) => {
  switch (type) {
    case "payment":
    case "bill_payment":
    case "digital_payment":
      return "payment";
    case "card_payment":
      return "card_purchase";
    case "atm":
      return "card_atm";
    case "transfer":
      return "transfer";
    case "ach":
      return "ach";
    case "interest":
      return "interest";
    case "deposit":
      return "deposit";
    case "wire":
      return "wire";
    case "fee":
      return "fee";
    default:
      return "other";
  }
};

type MapTransactionCategory = {
  transaction: Transaction;
  amount: number;
  accountType: string;
};

export const mapTransactionCategory = ({
  transaction,
  amount,
  accountType,
}: MapTransactionCategory) => {
  if (transaction.type === "fee") {
    return "fees";
  }

  if (amount > 0) {
    // For credit accounts, positive amount after transformation means money came IN
    // (e.g., payment, refund, cashback). Determine category based on transaction type/category.
    if (accountType === "credit") {
      // If Teller categorizes it as income, it might be cashback/rewards
      if (transaction.details?.category === "income") {
        return "income";
      }
      // Payment types indicate a credit card payment
      if (
        transaction.type === "payment" ||
        transaction.type === "bill_payment" ||
        transaction.type === "digital_payment" ||
        transaction.type === "ach" ||
        transaction.type === "transfer"
      ) {
        return "credit-card-payment";
      }
      // Otherwise it's likely a refund - don't auto-categorize, let user decide
      return null;
    }
    return "income";
  }

  switch (transaction?.details.category) {
    case "bar":
    case "dining":
    case "groceries":
      return "meals";
    case "transport":
    case "transportation":
      return "travel";
    case "tax":
      return "taxes";
    case "office":
      return "office-supplies";
    case "phone":
      return "internet-and-telephone";
    case "software":
      return "software";
    case "entertainment":
    case "sport":
      return "activity";
    case "utilities":
      return "utilities"; // Updated to use new utilities category
    case "electronics":
      return "equipment";
    case "accommodation":
      return "travel"; // Hotel stays should be travel
    case "advertising":
      return "advertising"; // Use new advertising category
    case "charity":
      return "charitable-donations"; // Use new charitable donations category
    case "education":
      return "training"; // Use new training category
    case "health":
      return "benefits"; // Health-related could be benefits
    case "insurance":
      return "insurance"; // Use new insurance category
    case "fuel":
      return "travel"; // Business fuel is typically travel-related
    case "home":
      return "facilities-expenses"; // Home office expenses
    case "service":
      return "professional-services-fees"; // General services
    default:
      return null;
  }
};

export const transformDescription = (transaction: Transaction) => {
  const description =
    transaction?.details?.counterparty?.name &&
    capitalCase(transaction.details.counterparty.name);

  if (transaction.description !== description && description) {
    return capitalCase(description);
  }

  return null;
};

const formatAmout = ({ amount, accountType }: FormatAmount) => {
  // NOTE: For account credit positive values when money moves out of the account; negative values when money moves in.
  if (accountType === "credit") {
    return +(amount * -1);
  }

  return +amount;
};

export const transformTransaction = ({
  transaction,
  accountType,
}: TransformTransaction): BaseTransaction => {
  const method = mapTransactionMethod(transaction.type);
  const description = transformDescription(transaction);
  const amount = formatAmout({
    amount: +transaction.amount,
    accountType,
  });

  return {
    id: transaction.id,
    date: transaction.date,
    name: transaction.description && capitalCase(transaction.description),
    description: description ?? null,
    currency_rate: null,
    currency_source: null,
    method,
    amount,
    currency: "USD",
    category: mapTransactionCategory({ transaction, amount, accountType }),
    balance: transaction?.running_balance ? +transaction.running_balance : null,
    counterparty_name: transaction?.details?.counterparty?.name
      ? capitalCase(transaction.details.counterparty.name)
      : null,
    merchant_name: null,
    status: transaction?.status === "posted" ? "posted" : "pending",
  };
};

type TransformAccountParams = TransformAccount & {
  accountDetails?: {
    account_number: string;
    routing_numbers: {
      ach: string | null;
      wire: string | null;
      bacs: string | null;
    };
  } | null;
};

export const transformAccount = ({
  id,
  name,
  currency,
  enrollment_id,
  type,
  subtype,
  institution,
  balance,
  last_four,
  accountDetails,
}: TransformAccountParams): BaseAccount => {
  const accountType = getType(type);

  return {
    id,
    name,
    currency: currency.toUpperCase(),
    enrollment_id: enrollment_id,
    institution: transformInstitution(institution),
    type: accountType,
    balance: transformAccountBalance({ balance, accountType }),
    // Use last_four as stable identifier for account matching during reconnect
    resource_id: last_four,
    expires_at: null,
    iban: null, // Teller (US-only) doesn't have IBAN
    subtype: subtype || null, // checking, savings, money_market, credit_card, etc.
    bic: null, // Teller doesn't have BIC
    // US bank account details from /accounts/:id/details
    routing_number: accountDetails?.routing_numbers?.ach || null,
    wire_routing_number: accountDetails?.routing_numbers?.wire || null,
    account_number: accountDetails?.account_number || null,
    sort_code: accountDetails?.routing_numbers?.bacs || null,
    available_balance: null, // Not available without expensive /balances endpoint
    credit_limit: null, // Teller doesn't provide credit limit
  };
};

type TransformAccountBalanceParams = {
  balance: TransformAccountBalance;
  accountType?: string;
};

/**
 * Transform Teller balance to internal format.
 * Balance is derived from running_balance in transactions (free API call).
 *
 * Teller typically returns positive values for credit card debt.
 * Normalization is added for safety and consistency with other providers.
 */
export const transformAccountBalance = ({
  balance,
  accountType,
}: TransformAccountBalanceParams): GetAccountBalanceResponse => {
  const rawAmount = +balance.amount;

  // Normalize credit card balances to positive (amount owed) for consistency
  const amount =
    accountType === "credit" && rawAmount < 0 ? Math.abs(rawAmount) : rawAmount;

  return {
    currency: balance.currency.toUpperCase(),
    amount,
    available_balance: null, // Not available without paid /balances endpoint
    credit_limit: null, // Teller doesn't provide credit limit
  };
};

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