* fix(mcp-oauth): allow ChatGPT connector callbacks and resume OAuth after login Add chatgpt.com/connector/oauth/* (per-instance) and the legacy chatgpt.com/connector_platform_oauth_redirect to the built-in OAuth redirect allowlist so ChatGPT MCP connectors can register and authorize. Fix the login page dropping the ?next= destination: an OAuth-initiated visit that required login previously ended on the dashboard and the connection flow silently died. Login now resumes to the sanitized next path (hard navigation, since the consent page is route-handler HTML), carries it through the MFA step-up as returnTo, and /mfa/verify hard-navigates for /api/ destinations. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(transactions): dedup incoming feed rows against booked hand-entered twins Users who bookkeep via MCP/chat first and connect their bank afterwards got the same movement twice: the synced row's external_id lives in a different namespace, the free-form manual title never text-bridges the bank's raw string, and the cross-channel mirror deliberately excluded manual/mcp rows. Extend the mirror with a booked-hand-entered track: an incoming feed row is skipped when a BOOKED manual/mcp row shares its (date, ore) bucket count- symmetrically. Gates beyond the feed-vs-feed mirror: stored row must be booked (staged rows never consume an import), currencies must not contradict (bucket key is date+ore only), the cash-account guard applies to the count exactly as to consumption, and symmetry uses the Layer-1-unmatched incoming count so an already-stored row cannot inflate it. Consumption stamps the batch cash_account_id onto an account-unbound hand row, so one hand row can never consume feed rows on other accounts in later syncs. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): inline verifikat rattelse (strike lines + text/date edit) Second sanctioned correction track under BFL 5 kap 5/9 pp, Fortnox-style: strike lines inside a posted verifikat with replacements in the same voucher, and correct description/entry_date without an andringsverifikat. Envelope: posted entries, open unlocked periods, company lock date, same-period date moves, structural/FX/doc-linked lines excluded, and a reconciliation guard preserving per-account net on bank/reskontra sides of externally linked entries. Every rattelse writes an immutable who/when row (journal_entry_rattelse_log, WORM, archived as rakenskapsinformation) and struck originals render struck-through in the verifikat; list rows and the detail header carry a Rattad marker. CLAUDE.md hard rule 1 and the swedish-accounting-compliance skill are amended to state the two-track rule. Staging carries the DDL; prod gets it on merge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: live saldo in booking form, prior-year window comparison, hideable assistant FAB - Manual journal entry: saldo column now shows before -> after computed from the typed debit/credit amounts (direction feedback while booking) - Resultatrapport: a narrowed date range now compares against the same window shifted one year back (#862), merged across fiscal periods for brutet rakenskapsar; P&L rows report window activity instead of rolled-forward YTD closing - Assistant FAB: per-user hide toggle (user_preferences.hide_assistant_fab, settings > assistant), sidebar entry unaffected; collapsed sessions keep their reopen handle Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(stripe): sync balance transactions as a bank feed on 1686 Import the connected Stripe balance into the transactions inbox, opt-in per connection (transaction_sync_enabled on stripe_connections): - Balance transactions map to feed rows with the two-row gross+fee split and frozen external_id formats (stripe_{acct}_{txn} / _fee), dated on created, bound to a provisioned "Stripe-saldo" cash account on 1686 so booking settles against the clearing account by construction. - Double-booking protection: settled payment-link charges import pre-linked to their settlement entry; payout rows import pre-linked to the payout entry; processPayoutPaidEvent claims the payout's fee rows at booking time (linkPayoutFeedRows, idempotent from both directions). - Cursor last_balance_txn_synced_at with 24h overlap; first run backfills 90 days floored at the day after the company lock date. - Nightly cron /api/extensions/stripe/transactions/cron (03:30), transaction-sync toggle route, "Synka nu" covers both feeds, settings panel toggle with last-synced/backfill note, sv+en strings. - Migration 20260723200000 (applied to staging). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(transactions): offer match-to-voucher on unbooked history rows Unbooked transactions with is_business already set (e.g. left behind when a voucher was removed without a full uncategorize) land in the history list instead of the inbox, where the match-against-existing-voucher action did not exist, leaving them with no path back to voucher matching. Add the same menu item to the history list for unbooked rows. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(transactions): enhance ownership checks and error handling in journal entry routes --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
275 lines
9.3 KiB
TypeScript
275 lines
9.3 KiB
TypeScript
import type Stripe from 'stripe'
|
|
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { getStripe } from '@/lib/stripe/client'
|
|
import { createJournalEntry, findFiscalPeriod } from '@/lib/bookkeeping/engine'
|
|
import {
|
|
generateReverseChargeBasisLines,
|
|
generateReverseChargeLines,
|
|
} from '@/lib/bookkeeping/vat-entries'
|
|
import { createLogger, type Logger } from '@/lib/logger'
|
|
import type { CreateJournalEntryInput, CreateJournalEntryLineInput } from '@/types'
|
|
import { connectedAccountOptions } from './connect'
|
|
import { linkPayoutFeedRows } from './transaction-sync'
|
|
import type { StripeConnection } from '../types'
|
|
|
|
const defaultLog = createLogger('stripe/payouts')
|
|
|
|
/**
|
|
* Book a Stripe payout as one journal entry:
|
|
*
|
|
* Debit 1930 Företagskonto [net]
|
|
* Debit 6570 Bankkostnader [fees]
|
|
* Debit 4535 + Credit 4598 [fees] ruta 21 basis pair
|
|
* Debit 2645 / Credit 2614 [25% of fees] fiktiv moms
|
|
* Credit 1686 Fordringar för kontokort [gross]
|
|
*
|
|
* Stripe Payments Europe Ltd (Ireland) invoices the fees, so they are an EU
|
|
* services purchase under omvänd skattskyldighet: the same vat-entries
|
|
* generators as supplier invoices produce the ruta 21 basis pair and the
|
|
* 2645/2614 fiktiv-moms pair, keeping the momsdeklaration correct by
|
|
* construction (rutor 21, 30, 48).
|
|
*
|
|
* Auto-booked ONLY when fully deterministic: every balance transaction in the
|
|
* payout is a charge/payment (plus the payout row itself), the currency is
|
|
* SEK, the company is VAT registered, and gross - fees equals the payout net
|
|
* exactly. Refunds, disputes, adjustments, FX or arithmetic drift become
|
|
* needs_review rows: a human decides, the sync never guesses.
|
|
*
|
|
* The 1930 debit then appears in bank reconciliation
|
|
* (get_unlinked_1930_lines) for linking against the incoming bank feed
|
|
* transaction, which closes the loop without double-booking the deposit.
|
|
*/
|
|
|
|
/** Balance transaction types that make up a plain card-payment payout. */
|
|
const DETERMINISTIC_TXN_TYPES = new Set(['charge', 'payment'])
|
|
|
|
interface PayoutLike {
|
|
id: string
|
|
amount?: number | null
|
|
currency?: string | null
|
|
arrival_date?: number | null
|
|
livemode?: boolean
|
|
}
|
|
|
|
export interface PayoutOutcome {
|
|
status: 'booked' | 'needs_review' | 'ignored' | 'already_processed'
|
|
reason: string | null
|
|
}
|
|
|
|
export async function processPayoutPaidEvent(
|
|
supabase: SupabaseClient,
|
|
connection: StripeConnection,
|
|
event: Stripe.Event,
|
|
log: Logger = defaultLog,
|
|
): Promise<PayoutOutcome> {
|
|
const payout = event.data.object as PayoutLike
|
|
if (!payout?.id) return { status: 'ignored', reason: 'malformed_event' }
|
|
|
|
// Claim (idempotency): one row per (connection, payout). A duplicate event
|
|
// or overlapping poll window is a no-op.
|
|
const { data: inserted } = await supabase
|
|
.from('stripe_payouts')
|
|
.upsert(
|
|
{
|
|
company_id: connection.company_id,
|
|
connection_id: connection.id,
|
|
payout_id: payout.id,
|
|
stripe_event_id: event.id,
|
|
amount: typeof payout.amount === 'number' ? payout.amount / 100 : null,
|
|
currency: payout.currency?.toUpperCase() ?? null,
|
|
arrival_date: payout.arrival_date
|
|
? new Date(payout.arrival_date * 1000).toISOString().split('T')[0]
|
|
: null,
|
|
status: 'processing',
|
|
event_created_at: new Date(event.created * 1000).toISOString(),
|
|
},
|
|
{ onConflict: 'connection_id,payout_id', ignoreDuplicates: true },
|
|
)
|
|
.select('id')
|
|
|
|
if (!inserted || inserted.length === 0) {
|
|
return { status: 'already_processed', reason: null }
|
|
}
|
|
const claimId = (inserted[0] as { id: string }).id
|
|
|
|
const outcome = await evaluateAndBook(supabase, connection, payout, event, log)
|
|
|
|
await supabase
|
|
.from('stripe_payouts')
|
|
.update({
|
|
status: outcome.status === 'booked' ? 'booked' : outcome.status,
|
|
reason: outcome.reason,
|
|
...(outcome.journalEntryId ? { journal_entry_id: outcome.journalEntryId } : {}),
|
|
...(outcome.gross != null ? { gross: outcome.gross } : {}),
|
|
...(outcome.fees != null ? { fees: outcome.fees } : {}),
|
|
})
|
|
.eq('id', claimId)
|
|
|
|
return { status: outcome.status, reason: outcome.reason }
|
|
}
|
|
|
|
interface EvaluationOutcome {
|
|
status: 'booked' | 'needs_review' | 'ignored'
|
|
reason: string | null
|
|
journalEntryId?: string
|
|
gross?: number
|
|
fees?: number
|
|
}
|
|
|
|
async function evaluateAndBook(
|
|
supabase: SupabaseClient,
|
|
connection: StripeConnection,
|
|
payout: PayoutLike,
|
|
event: Stripe.Event,
|
|
log: Logger,
|
|
): Promise<EvaluationOutcome> {
|
|
if (payout.livemode !== undefined && payout.livemode !== connection.livemode) {
|
|
return { status: 'ignored', reason: 'livemode_mismatch' }
|
|
}
|
|
if (payout.currency?.toLowerCase() !== 'sek') {
|
|
return { status: 'needs_review', reason: 'non_sek_payout' }
|
|
}
|
|
|
|
const { data: settings } = await supabase
|
|
.from('company_settings')
|
|
.select('vat_registered')
|
|
.eq('company_id', connection.company_id)
|
|
.maybeSingle()
|
|
if (settings?.vat_registered === false) {
|
|
// Reverse charge on the fees interacts with the company's VAT status;
|
|
// a human decides how a non-VAT-registered company books this.
|
|
return { status: 'needs_review', reason: 'not_vat_registered' }
|
|
}
|
|
|
|
const stripe = getStripe()
|
|
const txns = await stripe.balanceTransactions
|
|
.list({ payout: payout.id, limit: 100 }, connectedAccountOptions(connection.stripe_account_id!))
|
|
.autoPagingToArray({ limit: 1000 })
|
|
|
|
let grossOre = 0
|
|
let feesOre = 0
|
|
for (const txn of txns) {
|
|
if (txn.type === 'payout') continue // the payout row itself (negative net)
|
|
if (!DETERMINISTIC_TXN_TYPES.has(txn.type)) {
|
|
return { status: 'needs_review', reason: `non_deterministic_txn_${txn.type}` }
|
|
}
|
|
if (txn.currency?.toLowerCase() !== 'sek') {
|
|
return { status: 'needs_review', reason: 'non_sek_balance_txn' }
|
|
}
|
|
grossOre += txn.amount
|
|
feesOre += txn.fee
|
|
}
|
|
|
|
const gross = grossOre / 100
|
|
const fees = feesOre / 100
|
|
const net = typeof payout.amount === 'number' ? payout.amount / 100 : null
|
|
|
|
if (net == null || Math.round((gross - fees) * 100) !== Math.round(net * 100)) {
|
|
return {
|
|
status: 'needs_review',
|
|
reason: 'arithmetic_mismatch',
|
|
gross,
|
|
fees,
|
|
}
|
|
}
|
|
if (!(gross > 0)) {
|
|
return { status: 'needs_review', reason: 'empty_payout', gross, fees }
|
|
}
|
|
|
|
const arrivalDate = payout.arrival_date
|
|
? new Date(payout.arrival_date * 1000).toISOString().split('T')[0]
|
|
: new Date(event.created * 1000).toISOString().split('T')[0]
|
|
|
|
const fiscalPeriodId = await findFiscalPeriod(supabase, connection.company_id, arrivalDate)
|
|
if (!fiscalPeriodId) {
|
|
return { status: 'needs_review', reason: 'no_open_fiscal_period', gross, fees }
|
|
}
|
|
|
|
const round = (n: number) => Math.round(n * 100) / 100
|
|
const lines: CreateJournalEntryLineInput[] = [
|
|
{
|
|
account_number: '1930',
|
|
debit_amount: round(net),
|
|
credit_amount: 0,
|
|
line_description: `Stripe-utbetalning ${payout.id}`,
|
|
},
|
|
]
|
|
if (fees > 0) {
|
|
lines.push({
|
|
account_number: '6570',
|
|
debit_amount: round(fees),
|
|
credit_amount: 0,
|
|
line_description: 'Stripe-avgifter (omvänd skattskyldighet, EU)',
|
|
})
|
|
// Ruta 21 basis pair (4535 / 4598) + fiktiv moms (2645 / 2614): same
|
|
// generators as the supplier reverse-charge flow, so the VAT report
|
|
// picks the fees up identically.
|
|
lines.push(...generateReverseChargeBasisLines(round(fees), 0.25, 'eu_business'))
|
|
lines.push(...generateReverseChargeLines(round(fees), 0.25, false))
|
|
}
|
|
lines.push({
|
|
account_number: '1686',
|
|
debit_amount: 0,
|
|
credit_amount: round(gross),
|
|
line_description: 'Avräkning Stripe-betalningar',
|
|
})
|
|
|
|
const input: CreateJournalEntryInput = {
|
|
fiscal_period_id: fiscalPeriodId,
|
|
entry_date: arrivalDate,
|
|
description: `Stripe-utbetalning ${payout.id}`,
|
|
source_type: 'stripe_payout',
|
|
lines,
|
|
}
|
|
|
|
try {
|
|
const entry = await createJournalEntry(
|
|
supabase,
|
|
connection.company_id,
|
|
connection.user_id,
|
|
input,
|
|
)
|
|
if (!entry) {
|
|
return { status: 'needs_review', reason: 'booking_returned_null', gross, fees }
|
|
}
|
|
// Claim this payout's transaction-feed rows (the payout row + the fee
|
|
// rows of its charges): the entry just booked carries exactly that money,
|
|
// so leaving them unbooked in the inbox would invite double-booking the
|
|
// fees. No-op for companies without the balance-transaction feed. The
|
|
// entry is already posted, so a linking failure must NOT flip the payout
|
|
// to needs_review: swallow and let the nightly sync retry (idempotent).
|
|
try {
|
|
await linkPayoutFeedRows(
|
|
supabase,
|
|
connection.company_id,
|
|
connection.stripe_account_id!,
|
|
entry.id,
|
|
txns,
|
|
log,
|
|
)
|
|
} catch (linkErr) {
|
|
log.warn('payout feed-row linking failed after booking', {
|
|
connectionId: connection.id,
|
|
payoutId: payout.id,
|
|
journalEntryId: entry.id,
|
|
message: linkErr instanceof Error ? linkErr.message : String(linkErr),
|
|
})
|
|
}
|
|
log.info('booked stripe payout', {
|
|
connectionId: connection.id,
|
|
payoutId: payout.id,
|
|
journalEntryId: entry.id,
|
|
net,
|
|
fees,
|
|
})
|
|
return { status: 'booked', reason: null, journalEntryId: entry.id, gross, fees }
|
|
} catch (err) {
|
|
return {
|
|
status: 'needs_review',
|
|
reason: `booking_failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
gross,
|
|
fees,
|
|
}
|
|
}
|
|
}
|