File size: 9,199 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
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 { Transaction, TransactionCode } from "plaid";
import type {
  Account as BaseAccount,
  Transaction as BaseTransaction,
  GetAccountBalanceResponse,
} from "../types";
import type {
  TransformAccount,
  TransformAccountBalance,
  TransformInstitution,
  TransformTransactionPayload,
} from "./types";

export const mapTransactionMethod = (type?: TransactionCode | null) => {
  switch (type) {
    case "bill payment":
      return "payment";
    case "purchase":
      return "card_purchase";
    case "atm":
      return "card_atm";
    case "transfer":
      return "transfer";
    case "interest":
      return "interest";
    case "bank charge":
      return "fee";
    default:
      return "other";
  }
};

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

export const mapTransactionCategory = ({
  transaction,
  amount,
  accountType,
}: MapTransactionCategory) => {
  // Check Plaid's category first - they have good categorization
  if (transaction.personal_finance_category?.primary === "INCOME") {
    return "income";
  }

  // Plaid categorizes credit card payments under the detailed category
  if (
    transaction.personal_finance_category?.detailed ===
    "LOAN_PAYMENTS_CREDIT_CARD_PAYMENT"
  ) {
    return "credit-card-payment";
  }

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

  if (
    transaction.transaction_code === "bank charge" ||
    transaction.personal_finance_category?.primary === "BANK_FEES"
  ) {
    return "fees";
  }

  if (transaction.personal_finance_category?.primary === "FOOD_AND_DRINK") {
    return "meals";
  }

  if (
    transaction.personal_finance_category?.primary === "TRANSPORTATION" ||
    transaction.personal_finance_category?.primary === "TRAVEL"
  ) {
    return "travel";
  }

  // Software and technology
  if (
    transaction.personal_finance_category?.detailed ===
    "GENERAL_SERVICES_OTHER_GENERAL_SERVICES"
  ) {
    return "software";
  }

  // Utilities - use new utilities category instead of facilities-expenses
  if (
    transaction.personal_finance_category?.detailed ===
      "RENT_AND_UTILITIES_GAS_AND_ELECTRICITY" ||
    transaction.personal_finance_category?.detailed ===
      "RENT_AND_UTILITIES_SEWAGE_AND_WASTE_MANAGEMENT" ||
    transaction.personal_finance_category?.detailed ===
      "RENT_AND_UTILITIES_WATER" ||
    transaction.personal_finance_category?.detailed ===
      "RENT_AND_UTILITIES_OTHER_UTILITIES"
  ) {
    return "utilities"; // Updated to use new utilities category
  }

  if (
    transaction.personal_finance_category?.detailed ===
    "RENT_AND_UTILITIES_RENT"
  ) {
    return "rent";
  }

  if (
    transaction.personal_finance_category?.detailed ===
      "RENT_AND_UTILITIES_INTERNET_AND_CABLE" ||
    transaction.personal_finance_category?.detailed ===
      "RENT_AND_UTILITIES_TELEPHONE"
  ) {
    return "internet-and-telephone";
  }

  // Professional services
  if (
    transaction.personal_finance_category?.primary === "PROFESSIONAL_SERVICES"
  ) {
    return "professional-services-fees";
  }

  // Insurance
  if (transaction.personal_finance_category?.primary === "INSURANCE") {
    return "insurance";
  }

  // Marketing and advertising
  if (transaction.personal_finance_category?.primary === "MARKETING") {
    return "marketing";
  }

  // Home improvement for office supplies
  if (transaction.personal_finance_category?.primary === "HOME_IMPROVEMENT") {
    return "office-supplies";
  }

  if (transaction.personal_finance_category?.primary === "ENTERTAINMENT") {
    return "activity";
  }

  // Tax payments
  if (transaction.personal_finance_category?.primary === "TAX") {
    return "taxes";
  }

  // Healthcare/medical - could be benefits
  if (transaction.personal_finance_category?.primary === "MEDICAL") {
    return "benefits";
  }

  // General merchandise - could be office supplies for small amounts
  if (
    transaction.personal_finance_category?.primary === "GENERAL_MERCHANDISE" &&
    Math.abs(amount) < 500 // Small amounts likely office supplies
  ) {
    return "office-supplies";
  }

  // Large general merchandise - likely equipment
  if (
    transaction.personal_finance_category?.primary === "GENERAL_MERCHANDISE" &&
    Math.abs(amount) >= 500 // Large amounts likely equipment
  ) {
    return "equipment";
  }

  return null;
};

const formatAmout = (amount: number) => {
  // Positive values when money moves out of the account; negative values when money moves in.
  // For example, debit card purchases are positive; credit card payments, direct deposits, and refunds are negative.
  return +(amount * -1);
};

const transformDescription = (transaction: Transaction) => {
  const name = capitalCase(transaction.name);

  if (
    transaction?.original_description &&
    transaction.original_description !== name
  ) {
    return capitalCase(transaction.original_description);
  }

  if (transaction?.merchant_name && transaction?.merchant_name !== name) {
    return transaction?.merchant_name;
  }

  return null;
};

export const transformTransaction = ({
  transaction,
  accountType,
}: TransformTransactionPayload): BaseTransaction => {
  const method = mapTransactionMethod(transaction?.transaction_code);
  const amount = formatAmout(transaction.amount);
  const description = transformDescription(transaction) ?? null;

  return {
    id: transaction.transaction_id,
    date: transaction.date,
    name: transaction.name,
    description,
    currency_rate: null,
    currency_source: null,
    method,
    amount,
    currency:
      transaction?.iso_currency_code?.toUpperCase() ||
      transaction?.unofficial_currency_code?.toUpperCase() ||
      "USD",
    category: mapTransactionCategory({ transaction, amount, accountType }),
    counterparty_name: transaction?.counterparties?.[0]?.name
      ? capitalCase(transaction.counterparties[0].name)
      : null,
    merchant_name: transaction?.merchant_name || null,
    balance: null,
    status: transaction.pending ? "pending" : "posted",
  };
};

export const transformAccount = ({
  account_id,
  name,
  balances,
  institution,
  type,
  subtype,
  mask,
  persistent_account_id,
}: TransformAccount): BaseAccount => {
  const accountType = getType(type);
  return {
    id: account_id,
    name,
    currency:
      balances?.iso_currency_code?.toUpperCase() ||
      balances?.unofficial_currency_code?.toUpperCase() ||
      "USD",
    type: accountType,
    enrollment_id: null,
    balance: transformAccountBalance({ balances, accountType }),
    institution: {
      id: institution.id,
      name: institution.name,
      logo: getLogoURL(institution.id),
      provider: Providers.enum.plaid,
    },
    // Use persistent_account_id (stable across Item resets for TAN institutions)
    // Fall back to mask (last 2-4 digits) for other institutions
    resource_id: persistent_account_id || mask || null,
    expires_at: null,
    iban: null, // Plaid (US-focused) doesn't typically provide IBAN
    subtype: subtype || null, // checking, savings, credit_card, mortgage, etc.
    bic: null, // Plaid doesn't have BIC
    // US bank details - requires Auth product, fetched separately
    routing_number: null,
    wire_routing_number: null,
    account_number: null,
    sort_code: null,
    // Credit account balances - Plaid provides both
    available_balance: balances?.available ?? null,
    credit_limit: balances?.limit ?? null,
  };
};

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

export const transformAccountBalance = ({
  balances,
  accountType,
}: TransformAccountBalanceParams): GetAccountBalanceResponse => {
  // For credit cards, use `current` (amount owed), not `available` (available credit)
  // Example: $5000 limit, $1000 owed → available=$4000, current=$1000
  // We want to show $1000 (current), not $4000 (available)
  const amount =
    accountType === "credit"
      ? (balances?.current ?? 0)
      : (balances?.available ?? balances?.current ?? 0);

  return {
    currency:
      balances?.iso_currency_code?.toUpperCase() ||
      balances?.unofficial_currency_code?.toUpperCase() ||
      "USD",
    amount,
    available_balance: balances?.available ?? null,
    credit_limit: balances?.limit ?? null,
  };
};

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