import bankAccounts from "./bank-accounts"; import { AuthedFetchType } from "../api/fake-fetch"; import { Account, Accounts } from "./models"; import { errorMessage } from "../utils"; import { MISSING_ACCOUNT_ERROR_MESSAGE, MISSING_ACCOUNT_ID_ERROR_MESSAGE, MISSING_ACCOUNT_OR_FOREIGN_ID_ERROR_MESSAGE, } from "../constants"; import representatives from "./representatives"; import paymentMethods from "./payment-methods"; import capabilities from "./capabilities"; import wallets from "./wallets"; import * as applePay from "./apple-pay"; export default function accounts(authedFetch: AuthedFetchType): Accounts { function getTermsOfServiceToken() { return authedFetch("/tos-token"); } function patchAccount(account: Partial) { let accountID, accountPatch; if (!account) return errorMessage(MISSING_ACCOUNT_ERROR_MESSAGE); try { ({accountID, ...accountPatch} = account); } catch { return errorMessage(MISSING_ACCOUNT_ERROR_MESSAGE); } if (!accountID) return errorMessage(MISSING_ACCOUNT_ID_ERROR_MESSAGE); return authedFetch(`/accounts/${accountID}`, { method: "PATCH", body: accountPatch, }); } return { create: (account: Account) => { if (!account) return errorMessage(MISSING_ACCOUNT_ERROR_MESSAGE); return authedFetch("/accounts", { method: "POST", body: account, headers: [ ["x-wait-for", "connection"] ] }); }, get: ({ accountID, foreignID }: { accountID?: string; foreignID?: string }) => { if (!accountID && !foreignID) return errorMessage(MISSING_ACCOUNT_OR_FOREIGN_ID_ERROR_MESSAGE); if (accountID) { return authedFetch(`/accounts/${accountID}`); } else { return authedFetch(`/accounts?foreignID=${foreignID}`); } }, update: (account: Account) => { if (!account) return errorMessage(MISSING_ACCOUNT_ERROR_MESSAGE); if (!account.accountID) return errorMessage(MISSING_ACCOUNT_ID_ERROR_MESSAGE); return authedFetch(`/accounts/${account.accountID}`, { method: "PUT", body: account, }); }, patch: patchAccount, getTermsOfServiceToken: getTermsOfServiceToken, acceptTermsOfService: ({ accountID }: { accountID: string }) => { if (!accountID) return errorMessage(MISSING_ACCOUNT_ID_ERROR_MESSAGE); return getTermsOfServiceToken() .then((tosToken) => { if (tosToken.error) return tosToken.error; return patchAccount({ accountID, termsOfService: { ...tosToken }, }); }); }, bankAccounts: { ...bankAccounts(authedFetch) }, wallets: { ...wallets(authedFetch) }, representatives: { ...representatives(authedFetch) }, paymentMethods: { ...paymentMethods(authedFetch) }, capabilities: { ...capabilities(authedFetch) }, applePay: { tokens: { ...applePay.tokens(authedFetch) }, sessions: { ...applePay.sessions(authedFetch) }, }, } as Accounts; }