import {z} from 'zod' export type GetApiBooksJournalEntryJournalEntryIdArgs = {journalEntryId: unknown, booksId?: string | undefined, expand?: ('lineEntries' | 'lineEntriesTransactions' | 'lineEntriesLedger' | 'lineEntriesOpposingLedgerIds' | 'lineEntriesPaymentApplications' | 'lineEntriesLinePaymentApplications' | 'accrualSource' | 'transfer' | 'autocatResult') | undefined}; export type GetApiBooksJournalEntryJournalEntryIdOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const booksCounterpartyId = z.string(); export const customerId = z.string(); export const booksAccrualSourceFile = z.object({fileName: z.string(), id: z.string()}); export const booksAccrualSourceLine = z.object({accountId: z.string(), accrualSourceId: z.string(), amount: z.number(), description: z.string(), externalId: z.string().nullable().optional(), id: z.string(), lineNumber: z.number().int().gte(-9223372036854776000).lte(9223372036854776000)}); export const booksPaymentApplicationAccrualAdjustment = z.object({accrualAdjustmentId: z.string(), amount: z.number(), creditAccountId: z.string(), debitAccountId: z.string()}); export const booksAccrualSourcePaymentApplication = z.object({adjustments: z.array(booksPaymentApplicationAccrualAdjustment), lineEntry: z.object({journalEntryDescription: z.string(), journalEntryId: z.string(), lineEntryAmount: z.number(), lineEntryDescription: z.string(), lineEntryId: z.string()}), matchedAmount: z.number(), paymentApplicationId: z.string(), sourceType: z.enum(["bankTransaction", "customerCredit", "manual"]), status: z.enum(["proposed", "confirmed", "rejected"])}); export const booksAccrualSourceUnappliedPayment = z.object({amount: z.number(), needsActionReason: z.enum(["transactionNotInTeal", "transactionAmountExceedsInvoiceBalance", "transactionAmountDoesNotCoverInvoices", "sourceAccountNotMapped", "transactionPredatesBooksStartDate", "transactionAppliedToOtherInvoices", "cardChargeStripeNotConnected", "cardChargeStripeSetupPending"])}); export const booksLineEntryLinePaymentApplication = z.object({accrualSource: z.object({accrualSourceId: z.string(), endDate: z.string(), startDate: z.string(), type: z.literal("payroll")}), linePaymentApplicationId: z.string(), matchedAmount: z.number(), sourceType: z.enum(["bankTransaction", "customerCredit", "manual"]), status: z.enum(["proposed", "confirmed", "rejected"])}); export const booksLineEntryPaymentApplicationSource = z.object({accrualSource: z.object({accrualSourceId: z.string(), effectiveDate: z.string(), externalId: z.string().nullable().optional(), externalPartyId: z.union([z.object({contents: booksCounterpartyId, tag: z.literal("counterpartyId")}).nullable(), z.object({contents: customerId, tag: z.literal("customerId")}).nullable()]).optional(), grossAmount: z.number(), referenceNumber: z.string().nullable().optional(), type: z.enum(["invoice", "bill", "payroll"])}).nullable().optional(), adjustments: z.array(booksPaymentApplicationAccrualAdjustment), matchedAmount: z.number(), paymentApplicationId: z.string(), sourceType: z.enum(["bankTransaction", "customerCredit", "manual"]), status: z.enum(["proposed", "confirmed", "rejected"])}); export const booksLineEntryPaymentApplication = z.union([booksLineEntryLinePaymentApplication, booksLineEntryPaymentApplicationSource]); export const booksTag = z.object({id: z.string(), name: z.string(), tagGroupId: z.string()}); export const booksTransactionAttachment = z.object({downloadUrl: z.string(), fileName: z.string(), id: z.string()}); export const booksLineEntry = z.object({accrualSource: z.object({amountOutstanding: z.number(), amountPaid: z.number(), displayStatus: z.enum(["open", "paid", "draft", "cancelled", "overdue", "partiallyPaid", "processing"]), dueDate: z.string().nullable().optional(), effectiveDate: z.string(), externalId: z.string().nullable().optional(), externalPartyId: z.union([z.object({contents: booksCounterpartyId, tag: z.literal("counterpartyId")}).nullable(), z.object({contents: customerId, tag: z.literal("customerId")}).nullable()]).optional(), grossAmount: z.number(), id: z.string(), lines: z.array(booksAccrualSourceLine).nullable().optional(), notes: z.string().nullable().optional(), referenceNumber: z.string().nullable().optional(), status: z.enum(["open", "paid", "draft", "cancelled", "processing"]), type: z.enum(["invoice", "bill", "payroll"])}).nullable().optional(), amount: z.number(), categorizationStatus: z.enum(["pending", "delayed", "completed", "notAttempted"]), datetime: z.string(), debitCredit: z.enum(["debit", "credit"]), description: z.string().nullable().optional(), editable: z.boolean(), id: z.string(), journalEntryDescription: z.string(), journalEntryId: z.string(), ledgerId: z.string(), ledgerName: z.string(), opposingLedgerIds: z.array(z.string()).nullable().optional(), paymentApplications: z.array(booksLineEntryPaymentApplication).nullable().optional(), relatedLineEntryId: z.string().nullable().optional(), sortOrder: z.number().int().gte(-9223372036854776000).lte(9223372036854776000).nullable().optional(), tags: z.array(booksTag).nullable().optional(), transaction: z.object({amount: z.number(), attachments: z.array(booksTransactionAttachment).nullable().optional(), cardLastFourDigits: z.string().nullable().optional(), categorizationMethod: z.enum(["aI", "rules", "similarity", "transferBetweenAccounts", "uncategorized", "user"]).nullable().optional(), counterpartyName: z.string().nullable().optional(), customCategoryId: z.string().nullable().optional(), customCategoryName: z.string().nullable().optional(), datetime: z.string(), description: z.string(), externalMetadataId: z.string().nullable().optional(), id: z.string(), journalEntryId: z.string().nullable().optional(), ledgerId: z.string().nullable().optional(), lineEntryId: z.string().nullable().optional(), merchantType: z.object({category: z.enum(["Other", "Advertising", "Airlines", "AlcoholAndBars", "BooksAndNewspaper", "CarRental", "Charity", "Clothing", "Conferences", "Education", "Electronics", "Entertainment", "FacilitiesExpenses", "Fees", "FoodDelivery", "FuelAndGas", "Gambling", "GovernmentServices", "Grocery", "GroundTransportation", "Insurance", "InternetAndTelephone", "Legal", "Lodging", "Medical", "Memberships", "OfficeSupplies", "OtherTravel", "Parking", "Political", "ProfessionalServices", "Restaurants", "Retail", "RideshareAndTaxis", "Shipping", "Software", "Taxes", "Utilities", "VehicleExpenses"]), display: z.string(), icon: z.enum(["arrowsLeftRightIcon", "arrowsRotateIcon", "atomSimpleIcon", "ballotCheckIcon", "bankIcon", "bellConciergeIcon", "boltIcon", "bookOpenCoverIcon", "booksIcon", "boxIcon", "buildingIcon", "burgerIcon", "carIcon", "cartShoppingFastIcon", "carWrenchIcon", "chartLineUpIcon", "circleParkingIcon", "computerIcon", "creditCardIcon", "crownIcon", "envelopeOpenTextIcon", "faucetIcon", "fileInvoiceIcon", "fileInvoiceDollarIcon", "fingerprintIcon", "gasPumpIcon", "gavelIcon", "gearIcon", "giftIcon", "globeIcon", "graduationCapIcon", "handHoldingDollarIcon", "handshakeIcon", "headSideMedicalIcon", "heartIcon", "homeIcon", "idBadgeIcon", "keyIcon", "keynoteIcon", "landmarkFlagIcon", "laptopIcon", "laptopMobileIcon", "listCheckIcon", "lockIcon", "lockOpenIcon", "martiniGlassIcon", "masksTheaterIcon", "messagesIcon", "mobileIcon", "moneyBillTransferIcon", "moneyBillWaveIcon", "moneyCheckIcon", "mugSaucerIcon", "planeIcon", "planetRingedIcon", "receiptIcon", "rectanglesMixedIcon", "seedlingIcon", "shieldCheckIcon", "shieldHavedIcon", "shirtIcon", "shopIcon", "shoppingCartIcon", "signInIcon", "signOutIcon", "slotMachineIcon", "staplerIcon", "starsIcon", "sunBrightIcon", "taxiBusIcon", "taxiIcon", "towerBroadcastIcon", "trainIcon", "tvIcon", "userIcon", "userPlusIcon", "usersIcon", "utensilsIcon", "warningIcon", "wifiIcon", "wineGlassIcon", "wrenchIcon"])}).nullable().optional(), note: z.string().nullable().optional(), opposingLineEntryIds: z.array(z.string()).nullable().optional(), personal: z.boolean(), postedStatus: z.enum(["notPosted", "posted", "deleted"]), reviewStatus: z.enum(["reviewed", "unreviewed"]), sourceAccountId: z.string(), teamMemberId: z.string().nullable().optional(), teamMemberName: z.string().nullable().optional(), transactionMethodKind: z.enum(["outgoingElectronicPayment", "outgoingCheckPayment", "endogenousOutgoingAchTransfer", "endogenousIncomingAchTransfer", "exogenousOutgoingAch", "exogenousIncomingAch", "incomingCredit", "outgoingCredit", "incomingDebit", "outgoingDebit", "internalTransfer", "incomingCheck", "outgoingInternationalWire", "incomingInternationalWire", "outgoingDomesticWire", "incomingDomesticWire", "wireFee", "conversionFee", "personalBankingSubscriptionFee", "billingEngineSubscriptionFee", "physicalCardUpgradeFee", "exogenousOutgoingCheck", "exogenousOutgoingWire", "treasuryTransfer", "investTransfer", "currencyCloudReturn", "internationalWirePartnerReturn", "internalCreditAccountPayment", "autoRoutingTransfer", "ventureDebtFunding", "ventureDebtRepayment", "creditCashbackRewardsDeposit", "externalCreditCashbackRewardsDeposit", "interestPayment", "outgoingProvisionalCredit", "incomingProvisionalCredit", "lineOfCreditFunding", "lineOfCreditRepayment", "lineOfCreditInterestRepayment", "atmFeeReimbursement", "atmFeeReimbursementReversal", "expenseReimbursement", "requestedPayment", "exogenousWireDrawdown", "incomingCreditAccountRepayment", "cardIntlTransactionFee", "cardIntlTransactionFeeRebate", "cardIntlTransactionFeeReversal", "cardIntlTransactionFeeRebateReversal", "externalCreditAccountPayment", "realtimePayment", "outgoingRealTimePayment", "balanceHold", "linkedMercuryAccountTransfer"]).nullable().optional()}).nullable().optional(), transactionId: z.string().nullable().optional()}); export const getBooksAPIJournalEntryResponse = z.object({journalEntry: z.object({accrualSource: z.object({amountOutstanding: z.number(), amountPaid: z.number(), billPayInvoiceAttachment: z.object({downloadUrl: z.string(), fileName: z.string(), id: z.string()}).nullable().optional(), displayStatus: z.enum(["open", "paid", "draft", "cancelled", "overdue", "partiallyPaid", "processing"]), dueDate: z.string().nullable().optional(), effectiveDate: z.string(), externalId: z.string().nullable().optional(), externalPartyId: z.union([z.object({contents: booksCounterpartyId, tag: z.literal("counterpartyId")}).nullable(), z.object({contents: customerId, tag: z.literal("customerId")}).nullable()]).optional(), files: z.array(booksAccrualSourceFile).nullable().optional(), grossAmount: z.number(), id: z.string().nullable().optional(), journalEntryIds: z.array(z.string()), lines: z.array(booksAccrualSourceLine).nullable().optional(), needsActionReason: z.enum(["transactionNotInTeal", "transactionAmountExceedsInvoiceBalance", "transactionAmountDoesNotCoverInvoices", "sourceAccountNotMapped", "transactionPredatesBooksStartDate", "transactionAppliedToOtherInvoices", "cardChargeStripeNotConnected", "cardChargeStripeSetupPending"]).nullable().optional(), notes: z.string().nullable().optional(), paymentApplications: z.array(booksAccrualSourcePaymentApplication).nullable().optional(), referenceNumber: z.string().nullable().optional(), status: z.enum(["open", "paid", "draft", "cancelled", "processing"]), type: z.enum(["invoice", "bill", "payroll"]), unappliedPayments: z.array(booksAccrualSourceUnappliedPayment).nullable().optional()}).nullable().optional(), autocatResult: z.object({confidence: z.number(), createdAt: z.string(), id: z.string(), ledgerId: z.string(), method: z.enum(["rule", "transactionKindDefaults", "similarity", "embedding", "llmClassifier", "transfersBetweenAccounts"]), ruleId: z.string().nullable().optional()}).nullable().optional(), categorizationStatus: z.enum(["pending", "delayed", "completed", "notAttempted"]), creationDate: z.string(), creationSource: z.enum(["manual", "transaction", "accrual", "paymentApplication", "legacy"]), datetime: z.string(), description: z.string(), id: z.string(), isOpeningBalance: z.boolean(), lineEntries: z.array(booksLineEntry).nullable().optional(), lineEntryIds: z.array(z.string()).nullable().optional(), reviewStatus: z.enum(["unreviewed", "reviewed"]), reviewStatusSetAt: z.string().nullable().optional(), transfer: z.object({fromEntry: z.object({datetime: z.string(), description: z.string(), journalEntryId: z.string(), lineEntries: z.array(booksLineEntry)}), toEntry: z.object({datetime: z.string(), description: z.string(), journalEntryId: z.string(), lineEntries: z.array(booksLineEntry)})}).nullable().optional()})}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Retrieve a journal entry * * GET /books/journal-entry/{journalEntryId} */ export const getApiBooksJournalEntryJournalEntryId = async (args: GetApiBooksJournalEntryJournalEntryIdArgs, options?: GetApiBooksJournalEntryJournalEntryIdOptions) => { const {baseUrl = "https://api.mercury.com/api/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.booksId != null) query.append("booksId", String(args.booksId)) if (args.expand != null) query.append("expand", String(args.expand)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/books/journal-entry/${encodeURIComponent(String(args.journalEntryId))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getBooksAPIJournalEntryResponse, await res.json()) };