|
| 1 | +import httpStatus from 'http-status' |
| 2 | +import { and, eq, isNull } from 'drizzle-orm' |
| 3 | + |
| 4 | +import { BaseService } from '@/app/api/core/services/base.service' |
| 5 | +import APIError from '@/app/api/core/exceptions/api' |
| 6 | +import { SyncLogService } from '@/app/api/quickbooks/syncLog/syncLog.service' |
| 7 | +import { PaymentService } from '@/app/api/quickbooks/payment/payment.service' |
| 8 | +import { TokenService } from '@/app/api/quickbooks/token/token.service' |
| 9 | +import { |
| 10 | + MixedPayoutIntentError, |
| 11 | + TerminalPayoutError, |
| 12 | +} from '@/app/api/quickbooks/payout/payout.errors' |
| 13 | +import { |
| 14 | + QBPayoutSync, |
| 15 | + QBPayoutSyncSelectSchemaType, |
| 16 | +} from '@/db/schema/qbPayoutSync' |
| 17 | +import { PayoutLineItem } from '@/type/dto/webhook.dto' |
| 18 | +import IntuitAPI, { IntuitAPITokensType } from '@/utils/intuitAPI' |
| 19 | +import { AccountTypeObj } from '@/constant/qbConnection' |
| 20 | +import { validateAccessToken } from '@/utils/auth' |
| 21 | + |
| 22 | +export class PayoutService extends BaseService { |
| 23 | + private syncLogService = new SyncLogService(this.user) |
| 24 | + |
| 25 | + // Same (portalId, payoutId) updates the same row, so a re-sent payout |
| 26 | + // never makes a duplicate. |
| 27 | + async upsertPayoutSync(input: { |
| 28 | + payoutId: string |
| 29 | + lineItems: PayoutLineItem[] |
| 30 | + netAmount: number |
| 31 | + feeCents: number |
| 32 | + arrivalDate: number |
| 33 | + }): Promise<QBPayoutSyncSelectSchemaType> { |
| 34 | + const [row] = await this.db |
| 35 | + .insert(QBPayoutSync) |
| 36 | + .values({ |
| 37 | + portalId: this.user.workspaceId, |
| 38 | + payoutId: input.payoutId, |
| 39 | + lineItems: input.lineItems, |
| 40 | + netAmount: input.netAmount, |
| 41 | + feeAmount: input.feeCents, |
| 42 | + arrivalDate: input.arrivalDate, |
| 43 | + }) |
| 44 | + .onConflictDoUpdate({ |
| 45 | + target: [QBPayoutSync.portalId, QBPayoutSync.payoutId], |
| 46 | + // Must match the partial unique index (only rows where deleted_at is |
| 47 | + // null). In drizzle-orm 0.42 that goes in `targetWhere`, not `where`. |
| 48 | + targetWhere: isNull(QBPayoutSync.deletedAt), |
| 49 | + set: { |
| 50 | + lineItems: input.lineItems, |
| 51 | + netAmount: input.netAmount, |
| 52 | + feeAmount: input.feeCents, |
| 53 | + arrivalDate: input.arrivalDate, |
| 54 | + }, |
| 55 | + }) |
| 56 | + .returning() |
| 57 | + return row |
| 58 | + } |
| 59 | + |
| 60 | + async getPayoutSync( |
| 61 | + payoutId: string, |
| 62 | + ): Promise<QBPayoutSyncSelectSchemaType | null> { |
| 63 | + const row = await this.db.query.QBPayoutSync.findFirst({ |
| 64 | + where: and( |
| 65 | + eq(QBPayoutSync.portalId, this.user.workspaceId), |
| 66 | + eq(QBPayoutSync.payoutId, payoutId), |
| 67 | + isNull(QBPayoutSync.deletedAt), |
| 68 | + ), |
| 69 | + }) |
| 70 | + return row ?? null |
| 71 | + } |
| 72 | + |
| 73 | + // Checks the payout, finds its payments, then builds and creates the deposit. |
| 74 | + // Neither caller claims again. Returns { depositId: null } when there is |
| 75 | + // nothing to deposit. |
| 76 | + async reconcile( |
| 77 | + row: QBPayoutSyncSelectSchemaType, |
| 78 | + qbTokenInfo: IntuitAPITokensType, |
| 79 | + opts: { runIdempotencyCheck: boolean }, |
| 80 | + ): Promise<{ depositId: string | null }> { |
| 81 | + validateAccessToken(qbTokenInfo) |
| 82 | + |
| 83 | + const payoutId = row.payoutId |
| 84 | + // One source for the note, used to both find and create the deposit, |
| 85 | + // so the two can never drift apart. |
| 86 | + const privateNote = `Stripe payout ${payoutId}` |
| 87 | + const lineItems = row.lineItems |
| 88 | + const copilotInvoiceIds = lineItems.map((line) => line.copilotInvoiceId) |
| 89 | + const grossCents = lineItems.reduce( |
| 90 | + (sum, line) => sum + line.grossAmount, |
| 91 | + 0, |
| 92 | + ) |
| 93 | + const feeCents = lineItems.reduce((sum, line) => sum + line.feeAmount, 0) |
| 94 | + const netAmount = row.netAmount |
| 95 | + |
| 96 | + // These problems never fix themselves on retry, so fail for good. |
| 97 | + if (lineItems.some((line) => line.grossAmount < 0)) { |
| 98 | + throw new TerminalPayoutError( |
| 99 | + `Payout ${payoutId} contains refund lines; batched deposit unsupported in v1`, |
| 100 | + ) |
| 101 | + } |
| 102 | + if (feeCents < 0) { |
| 103 | + throw new TerminalPayoutError( |
| 104 | + `Payout ${payoutId} has a negative aggregate fee (${feeCents}); unsupported in v1`, |
| 105 | + ) |
| 106 | + } |
| 107 | + if (new Set(copilotInvoiceIds).size !== copilotInvoiceIds.length) { |
| 108 | + throw new TerminalPayoutError( |
| 109 | + `Payout ${payoutId} contains duplicate invoice line items`, |
| 110 | + ) |
| 111 | + } |
| 112 | + |
| 113 | + // On resync only: reuse a deposit we already made, or find one already in QBO. |
| 114 | + if (opts.runIdempotencyCheck) { |
| 115 | + if (row.qbDepositId) return { depositId: row.qbDepositId } |
| 116 | + const intuitApi = new IntuitAPI(qbTokenInfo) |
| 117 | + const txnDate = new Date(row.arrivalDate * 1000) |
| 118 | + .toISOString() |
| 119 | + .split('T')[0] |
| 120 | + const existing = await intuitApi.getDepositsByTxnDate(txnDate) |
| 121 | + const match = existing.find( |
| 122 | + (deposit) => deposit.PrivateNote === privateNote, |
| 123 | + ) |
| 124 | + if (match) { |
| 125 | + await this.db |
| 126 | + .update(QBPayoutSync) |
| 127 | + .set({ qbDepositId: match.Id }) |
| 128 | + .where( |
| 129 | + and( |
| 130 | + eq(QBPayoutSync.id, row.id), |
| 131 | + eq(QBPayoutSync.portalId, this.user.workspaceId), |
| 132 | + ), |
| 133 | + ) |
| 134 | + return { depositId: match.Id } |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + const paymentIdByInvoice = |
| 139 | + await this.syncLogService.getSuccessfulPaidPaymentIds(copilotInvoiceIds) |
| 140 | + const unresolved = copilotInvoiceIds.filter( |
| 141 | + (id) => !paymentIdByInvoice.has(id), |
| 142 | + ) |
| 143 | + if (unresolved.length > 0) { |
| 144 | + // Can retry: the invoice.paid event may just not be saved yet. |
| 145 | + throw new APIError( |
| 146 | + httpStatus.NOT_FOUND, |
| 147 | + `Payout ${payoutId}: no SUCCESS INVOICE/PAID sync log for invoices [${unresolved.join(', ')}]`, |
| 148 | + ) |
| 149 | + } |
| 150 | + |
| 151 | + const allBatched = copilotInvoiceIds.every( |
| 152 | + (id) => paymentIdByInvoice.get(id)?.isBatchedDeposit, |
| 153 | + ) |
| 154 | + const allNonBatched = copilotInvoiceIds.every( |
| 155 | + (id) => !paymentIdByInvoice.get(id)?.isBatchedDeposit, |
| 156 | + ) |
| 157 | + // All non-batched means the fees were already booked, so nothing to deposit. |
| 158 | + if (allNonBatched) return { depositId: null } |
| 159 | + if (!allBatched) { |
| 160 | + throw new MixedPayoutIntentError( |
| 161 | + `Payout ${payoutId} mixes batched and non-batched invoices; unsupported`, |
| 162 | + ) |
| 163 | + } |
| 164 | + |
| 165 | + if (grossCents - feeCents !== netAmount) { |
| 166 | + throw new TerminalPayoutError( |
| 167 | + `Payout ${payoutId}: deposit total ${grossCents - feeCents} != payout net ${netAmount}`, |
| 168 | + ) |
| 169 | + } |
| 170 | + |
| 171 | + const bankAccountRef = qbTokenInfo.bankAccountRef |
| 172 | + if (!bankAccountRef) { |
| 173 | + // Can retry: works once a bank account is set in settings. |
| 174 | + throw new APIError( |
| 175 | + httpStatus.BAD_REQUEST, |
| 176 | + `Bank account ref is not configured for portal ${this.user.workspaceId}. Please select a bank account in the QuickBooks integration settings.`, |
| 177 | + ) |
| 178 | + } |
| 179 | + |
| 180 | + const intuitApi = new IntuitAPI(qbTokenInfo) |
| 181 | + const tokenService = new TokenService(this.user) |
| 182 | + const verifiedBankAccountRef = |
| 183 | + await tokenService.checkAndUpdateAccountStatus( |
| 184 | + AccountTypeObj.Bank, |
| 185 | + qbTokenInfo.intuitRealmId, |
| 186 | + intuitApi, |
| 187 | + bankAccountRef, |
| 188 | + ) |
| 189 | + const expenseAccountRef = await tokenService.checkAndUpdateAccountStatus( |
| 190 | + AccountTypeObj.Expense, |
| 191 | + qbTokenInfo.intuitRealmId, |
| 192 | + intuitApi, |
| 193 | + qbTokenInfo.expenseAccountRef, |
| 194 | + ) |
| 195 | + |
| 196 | + const paymentService = new PaymentService(this.user) |
| 197 | + const depositId = await paymentService.createBankDepositForPayment( |
| 198 | + intuitApi, |
| 199 | + { |
| 200 | + lines: lineItems.map((line) => ({ |
| 201 | + qbPaymentId: paymentIdByInvoice.get(line.copilotInvoiceId) |
| 202 | + ?.paymentId as string, |
| 203 | + amount: line.grossAmount / 100, |
| 204 | + })), |
| 205 | + feeTotal: feeCents / 100, |
| 206 | + bankAccountRef: verifiedBankAccountRef, |
| 207 | + expenseAccountRef, |
| 208 | + txnDate: new Date(row.arrivalDate * 1000).toISOString().split('T')[0], |
| 209 | + privateNote, |
| 210 | + }, |
| 211 | + ) |
| 212 | + |
| 213 | + await this.db |
| 214 | + .update(QBPayoutSync) |
| 215 | + .set({ qbDepositId: depositId }) |
| 216 | + .where( |
| 217 | + and( |
| 218 | + eq(QBPayoutSync.id, row.id), |
| 219 | + eq(QBPayoutSync.portalId, this.user.workspaceId), |
| 220 | + ), |
| 221 | + ) |
| 222 | + |
| 223 | + return { depositId } |
| 224 | + } |
| 225 | +} |
0 commit comments