feat(ledger): VAT per ledger row from Stripe's own data

stripe_transactions gets a nullable `tax` column: the VAT inside the
row's amount, in signed cents like amount, NULL = unknown.

- Charges/payments: the charge's invoice tax (tax, else total_tax_amounts
  / total_taxes) pro-rated by captured amount over invoice total, so a
  partly credit-paid invoice counts only the cash part; without an invoice,
  the Checkout Session of the payment intent (total_details.amount_tax).
- refund, payment_refund, payment_failure_refund, refund_failure carry the
  same share of the charge's VAT as their amount, signed like it.
- Fees, payouts, transfers, disputes and PayPal rows stay NULL.
- syncLedgerForCharge expands charge.invoice (falls back without it on API
  versions that lack Charge.invoice). A charge and its refunds share one
  lookup; refunds reuse the charge's ledger row; a re-import keeps a known
  value without a Stripe call. Stripe holding no VAT data is marked
  meta.tax_source=none and not asked again. A failed lookup leaves NULL and
  never breaks the import.
- shop:import-stripe-ledger --backfill-tax [--dry-run] [--since] [--recheck]
  and Shop::backfillLedgerTax() fill missing VAT read-only, idempotently.
- ledgerTotals, revenueLedgerByDay, ledgerTotalsByAccount and
  customerLedgerTotals gain a `tax` key (SUM(COALESCE(tax,0))); existing
  keys unchanged. Before the migration runs, rows save without tax and
  tax reads 0.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-11-02 12:10:11 +01:00
parent e2ea2ff9ab
commit c170595ac8
7 changed files with 1179 additions and 19 deletions

View File

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* The VAT contained in a ledger row's `amount`, in signed cents with the same
* sign as `amount` (a refund carries the refunded share of its charge's VAT,
* negative). Read from Stripe per charge: the charge's invoice, else the
* Checkout Session of its payment intent. NULL = unknown (not looked up yet,
* the lookup failed, or the row is not a charge share). Revenue without VAT is
* then `SUM(amount) - SUM(COALESCE(tax, 0))`.
*
* Guarded so a re-run or a consumer that already added the column is left
* untouched.
*/
return new class extends Migration
{
public function up(): void
{
$table = config('shop.tables.stripe_transactions', 'stripe_transactions');
if (! Schema::hasTable($table) || Schema::hasColumn($table, 'tax')) {
return;
}
Schema::table($table, function (Blueprint $blueprint) {
$blueprint->bigInteger('tax')->nullable()->after('net');
});
}
public function down(): void
{
$table = config('shop.tables.stripe_transactions', 'stripe_transactions');
if (Schema::hasTable($table) && Schema::hasColumn($table, 'tax')) {
Schema::table($table, function (Blueprint $blueprint) {
$blueprint->dropColumn('tax');
});
}
}
};

View File

@ -11,6 +11,25 @@ Besides charges, refunds and disputes, the default revenue types include bounced
- Stripe: `shop:import-stripe-ledger` pages all BalanceTransactions; `Shop::syncLedgerForCharge()` writes a charge in real time from the webhook.
- PayPal: `shop:import-paypal-ledger` pages PayPal's Transaction Search API for every configured account. Read-only. Without `--since` it resumes 14 days before the account's newest row; the first run reaches back three years. Schedule it hourly or daily, after the Stripe import.
## VAT (`tax`)
`tax` is the VAT inside a row's `amount`, in signed cents like `amount`. It comes from Stripe per charge, never from a flat rate, so reverse-charge and untaxed invoices count as 0:
- Subscription and invoice payments: the charge's invoice (`tax`, else the sum of `total_tax_amounts` / `total_taxes`), pro-rated by the captured amount over the invoice total. An invoice paid partly from the customer's credit balance counts only the cash part; one paid fully from credit has no charge and no row.
- One-off Checkout payments without an invoice: the Checkout Session of the payment intent (`total_details.amount_tax`).
- `refund`, `payment_refund`, `payment_failure_refund`, `refund_failure`: the same share of the charge's VAT as their amount is of the charge, signed like the amount.
- Every other row (fees, payouts, transfers, disputes, PayPal rows): NULL.
NULL means unknown. A failed lookup leaves NULL and never stops the import; the next import tries again. When Stripe holds no VAT data for a charge, the row stays NULL with `meta.tax_source = none` and is not asked again. Otherwise `meta.tax_source` is `invoice` or `checkout_session`.
The import looks the VAT up once per row: the webhook sync expands the invoice on the charge it already fetches, a charge and its refunds share one lookup, and a re-import keeps a known value without calling Stripe.
`ledgerTotals`, `revenueLedgerByDay`, `ledgerTotalsByAccount` and `customerLedgerTotals` return `tax` = `SUM(COALESCE(tax, 0))`, so the money kept without VAT is `net - tax`.
Existing rows: `php artisan shop:import-stripe-ledger --backfill-tax` fills `tax` on Stripe charge, payment and refund rows that have none yet (read-only against Stripe, idempotent). `--dry-run` prints the totals and writes nothing, `--since=YYYY-MM-DD` limits it, `--recheck` also retries rows marked `none`. The same is available as `Shop::backfillLedgerTax($dryRun, $since, $recheck)`.
Projects with `shop.run_migrations = false` publish the migration that adds the column (`2026_11_02_000001_add_tax_to_stripe_transactions_table.php`). Until it runs, rows save without `tax` and the aggregates report `tax` = 0.
## PayPal setup
Create a REST app in the PayPal developer dashboard (live) with the "Transaction search" permission, then set:

View File

@ -14,13 +14,19 @@ use Stripe\Stripe;
* customer — so a charge whose customer was deleted (or never existed locally)
* is still recorded. Idempotent: upserts on the `txn_` id and preserves Stripe's
* own `created`/`available_on` timestamps.
*
* Each charge-backed row also gets its VAT (`tax`) from Stripe, looked up once
* per row. `--backfill-tax` skips the import and only fills `tax` on existing
* charge, payment and refund rows that have none yet (read-only against Stripe).
*/
class ShopImportStripeLedgerCommand extends Command
{
protected $signature = 'shop:import-stripe-ledger
{--dry-run : Report what would change, write nothing}
{--since= : Only import transactions created on/after this date (YYYY-MM-DD)}
{--limit=100 : Stripe page size (max 100)}';
{--limit=100 : Stripe page size (max 100)}
{--backfill-tax : Only fill the VAT (tax) of existing charge, payment and refund rows that have none yet}
{--recheck : With --backfill-tax, also retry rows Stripe held no VAT data for last time}';
protected $description = 'Mirror all Stripe balance transactions into the local ledger (user-independent).';
@ -41,6 +47,10 @@ class ShopImportStripeLedgerCommand extends Command
$dry = (bool) $this->option('dry-run');
$model = config('shop.models.stripe_transaction', \Blax\Shop\Models\StripeTransaction::class);
if ($this->option('backfill-tax')) {
return $this->backfillTax($dry);
}
$params = [
'limit' => max(1, min(100, (int) $this->option('limit'))),
'expand' => ['data.source'],
@ -112,6 +122,45 @@ class ShopImportStripeLedgerCommand extends Command
*/
protected function rowFromTransaction($txn): array
{
return \Blax\Shop\Facades\Shop::ledgerRowFromBalanceTransaction($txn);
// Without the VAT: recordBalanceTransaction() looks it up only where needed.
return \Blax\Shop\Facades\Shop::ledgerRowFromBalanceTransaction($txn, null, false);
}
/** `--backfill-tax`: fill the missing VAT of existing rows from Stripe. */
protected function backfillTax(bool $dry): int
{
$model = config('shop.models.stripe_transaction', \Blax\Shop\Models\StripeTransaction::class);
if (! \Illuminate\Support\Facades\Schema::hasColumn((new $model)->getTable(), 'tax')) {
$this->error('The ledger has no `tax` column yet. Run the migration that adds it first.');
return self::FAILURE;
}
$since = $this->option('since') ? Carbon::parse($this->option('since'))->startOfDay() : null;
$totals = \Blax\Shop\Facades\Shop::backfillLedgerTax(
$dry,
$since,
(bool) $this->option('recheck'),
function (array $t) {
if ($t['scanned'] % 100 === 0) {
$this->line(sprintf(' … %d rows, %d filled, %s VAT', $t['scanned'], $t['filled'], number_format($t['tax'] / 100, 2)));
}
},
);
$this->newLine();
$this->info(sprintf(
'%s VAT for %d of %d rows without it: %s in total. Stripe holds no VAT data for %d, %d lookups failed%s.',
$dry ? '[dry-run] would fill' : 'Filled',
$totals['filled'],
$totals['scanned'],
number_format($totals['tax'] / 100, 2),
$totals['none'],
$totals['failed'],
$totals['failed'] > 0 ? ' (left empty, tried again on the next run)' : ''
));
return self::SUCCESS;
}
}

View File

@ -70,9 +70,10 @@ use Illuminate\Support\Facades\Facade;
* @method static \Illuminate\Support\Collection ledgerTotalsByAccount(\DateTimeInterface $from, \DateTimeInterface $until)
* @method static array customerLedgerTotals(string|array $customerIds = [], string|array $emails = [], ?\DateTimeInterface $from = null, ?\DateTimeInterface $until = null)
* @method static \Illuminate\Support\Collection ledgerAmountByCustomer(?\DateTimeInterface $from = null, ?\DateTimeInterface $until = null)
* @method static array ledgerRowFromBalanceTransaction($txn, $source = null)
* @method static array ledgerRowFromBalanceTransaction($txn, $source = null, bool $withTax = true)
* @method static string recordBalanceTransaction($txn, $source = null)
* @method static int syncLedgerForCharge(?string $chargeId)
* @method static array backfillLedgerTax(bool $dryRun = false, ?\DateTimeInterface $since = null, bool $recheck = false, ?callable $progress = null)
*
* Refunds:
* @method static object refundOrder(\Blax\Shop\Models\Order $order, int $amount, ?string $reason = null, array $params = [])

View File

@ -16,6 +16,12 @@ use Illuminate\Database\Eloquent\Model;
* `amount` is the charge's gross and `net` is gross minus fee; Stripe's own
* figures stay in `meta` (`settled_outside_stripe`, `stripe_amount`, `stripe_net`).
*
* `tax` is the VAT inside `amount`, signed like it (a refund carries the
* refunded share of its charge's VAT). It comes from Stripe per charge (the
* invoice, else the Checkout Session); `meta.tax_source` says which (`invoice`,
* `checkout_session`, or `none` when Stripe holds no VAT data for the charge).
* NULL = unknown.
*
* @property string $stripe_id
* @property string|null $source_type
* @property string|null $reporting_category
@ -23,6 +29,7 @@ use Illuminate\Database\Eloquent\Model;
* @property int $amount
* @property int $fee
* @property int $net
* @property int|null $tax
* @property string|null $currency
* @property string|null $customer_id
* @property string|null $customer_email
@ -41,6 +48,7 @@ class StripeTransaction extends Model
'amount' => 'integer',
'fee' => 'integer',
'net' => 'integer',
'tax' => 'integer',
'created' => 'datetime',
'available_on' => 'datetime',
'meta' => 'object',

View File

@ -24,6 +24,14 @@ use Stripe\Stripe;
class ShopService
{
/** Charge VAT per charge id / `pi:` payment intent, for one process. */
protected array $ledgerVatCache = [];
/** Retrieved invoices and Checkout Sessions, for one process. */
protected array $ledgerStripeCache = [];
protected bool $ledgerTaxColumn = false;
// =========================================================================
// PRODUCT QUERIES
// =========================================================================
@ -975,9 +983,11 @@ class ShopService
* One row per day with signed `gross` (SUM amount), `fee` (SUM fee) and
* `net` (SUM net = the money kept after fees and refunds) plus the row
* `count`. Refund/dispute days push `gross`/`net` down. Feed the `net`
* column into a cumulative sum for a break-even balance line.
* column into a cumulative sum for a break-even balance line. `tax` is the
* signed VAT inside `gross` (rows with unknown VAT count as 0), so
* `net - tax` is the day's money kept without VAT.
*
* @return \Illuminate\Support\Collection<int, object{date: string, gross: int, fee: int, net: int, count: int}>
* @return \Illuminate\Support\Collection<int, object{date: string, gross: int, fee: int, net: int, count: int, tax: int}>
*/
public function revenueLedgerByDay(\DateTimeInterface $from, \DateTimeInterface $until): \Illuminate\Support\Collection
{
@ -985,6 +995,7 @@ class ShopService
->whereBetween('created', [$from, $until])
->whereIn('source_type', $this->ledgerRevenueTypes())
->selectRaw('DATE(created) as date, SUM(amount) as gross, SUM(fee) as fee, SUM(net) as net, COUNT(*) as count')
->selectRaw($this->ledgerTaxSumSql())
->groupBy('date')
->orderBy('date')
->get()
@ -994,6 +1005,7 @@ class ShopService
'fee' => (int) $r->fee,
'net' => (int) $r->net,
'count' => (int) $r->count,
'tax' => (int) $r->tax,
]);
}
@ -1001,8 +1013,11 @@ class ShopService
* Window totals over the revenue-bearing ledger, in cents: gross sales
* (positive charge lines), the negative refund total, Stripe fees, and the
* resulting net collected. `count` is the number of ledger rows in range.
* `tax` is the signed VAT inside those rows (charges add, refunds take
* their share back; unknown counts as 0), so `net - tax` is the money kept
* without VAT.
*
* @return array{gross: int, refunds: int, fees: int, net: int, count: int}
* @return array{gross: int, refunds: int, fees: int, net: int, count: int, tax: int}
*/
public function ledgerTotals(\DateTimeInterface $from, \DateTimeInterface $until): array
{
@ -1015,6 +1030,7 @@ class ShopService
->selectRaw('SUM(fee) as fees')
->selectRaw('SUM(net) as net')
->selectRaw('COUNT(*) as count')
->selectRaw($this->ledgerTaxSumSql())
->first();
return [
@ -1023,6 +1039,7 @@ class ShopService
'fees' => (int) ($row->fees ?? 0),
'net' => (int) ($row->net ?? 0),
'count' => (int) ($row->count ?? 0),
'tax' => (int) ($row->tax ?? 0),
];
}
@ -1032,7 +1049,7 @@ class ShopService
* to ledgerTotals. Before the provider columns are migrated everything is
* reported as the one Stripe account.
*
* @return \Illuminate\Support\Collection<int, array{provider: string, account: string|null, gross: int, refunds: int, fees: int, net: int, count: int}>
* @return \Illuminate\Support\Collection<int, array{provider: string, account: string|null, gross: int, refunds: int, fees: int, net: int, count: int, tax: int}>
*/
public function ledgerTotalsByAccount(\DateTimeInterface $from, \DateTimeInterface $until): \Illuminate\Support\Collection
{
@ -1053,6 +1070,7 @@ class ShopService
->selectRaw('SUM(fee) as fees')
->selectRaw('SUM(net) as net')
->selectRaw('COUNT(*) as count')
->selectRaw($this->ledgerTaxSumSql())
->orderBy('provider')
->get()
->map(fn ($r) => [
@ -1063,6 +1081,7 @@ class ShopService
'fees' => (int) $r->fees,
'net' => (int) $r->net,
'count' => (int) $r->count,
'tax' => (int) $r->tax,
])
->values();
}
@ -1076,11 +1095,12 @@ class ShopService
* `amount` = SUM(amount) over revenue-type rows = gross charges minus
* refunds: the euros we kept, before Stripe's per-charge fee. This is the
* figure that catches subscription payments the per-user product_purchases
* sum misses (they are stored there as amount=0).
* sum misses (they are stored there as amount=0). `tax` is the signed VAT
* inside `amount` (unknown counts as 0).
*
* @param string|array<int,string> $customerIds Stripe customer id(s) (cus_…)
* @param string|array<int,string> $emails buyer email(s)
* @return array{amount: int, gross: int, refunds: int, fees: int, net: int, count: int}
* @return array{amount: int, gross: int, refunds: int, fees: int, net: int, count: int, tax: int}
*/
public function customerLedgerTotals(
string|array $customerIds = [],
@ -1091,7 +1111,7 @@ class ShopService
$customerIds = array_values(array_filter((array) $customerIds, static fn ($v) => is_string($v) && $v !== ''));
$emails = array_values(array_filter((array) $emails, static fn ($v) => is_string($v) && $v !== ''));
$zero = ['amount' => 0, 'gross' => 0, 'refunds' => 0, 'fees' => 0, 'net' => 0, 'count' => 0];
$zero = ['amount' => 0, 'gross' => 0, 'refunds' => 0, 'fees' => 0, 'net' => 0, 'count' => 0, 'tax' => 0];
// No identity to match on → nothing attributable. Guard so an empty
// whereIn can never degrade into a match-everything.
@ -1117,6 +1137,7 @@ class ShopService
->selectRaw('SUM(fee) as fees')
->selectRaw('SUM(net) as net')
->selectRaw('COUNT(*) as count')
->selectRaw($this->ledgerTaxSumSql())
->first();
return [
@ -1126,6 +1147,7 @@ class ShopService
'fees' => (int) ($row->fees ?? 0),
'net' => (int) ($row->net ?? 0),
'count' => (int) ($row->count ?? 0),
'tax' => (int) ($row->tax ?? 0),
];
}
@ -1161,12 +1183,15 @@ class ShopService
* importer path). A refund's buyer is read from its underlying charge so
* refunds net against the right customer.
*
* Once the ledger has its `tax` column the row also carries `tax`, the VAT
* inside `amount` ({@see ledgerRowTax}); it is looked up only when
* `$withTax` is true, else null.
*
* @return array<string, mixed>
*/
public function ledgerRowFromBalanceTransaction($txn, $source = null): array
public function ledgerRowFromBalanceTransaction($txn, $source = null, bool $withTax = true): array
{
$source = is_object($source) ? $source : (is_object($txn->source ?? null) ? $txn->source : null);
$sourceId = $source?->id ?? (is_string($txn->source ?? null) ? $txn->source : null);
[$source, $sourceId] = $this->ledgerSourceOf($txn, $source);
$chargeSource = is_object($source->charge ?? null) ? $source->charge : null;
@ -1220,7 +1245,7 @@ class ShopService
$net = -$fee;
}
return [
$row = [
'stripe_id' => $txn->id,
'source_type' => $txn->type ?? null,
'reporting_category' => $txn->reporting_category ?? null,
@ -1236,6 +1261,33 @@ class ShopService
'available_on' => isset($txn->available_on) ? Carbon::createFromTimestamp($txn->available_on) : null,
'meta' => $meta,
];
// Only once the column exists, so the row still saves before the migration.
if ($this->ledgerHasTaxColumn()) {
$row['tax'] = null;
if ($withTax) {
[$row['tax'], $taxSource] = $this->ledgerRowTax($row['source_type'], $source, $sourceId, $amount, $meta['payment_intent'] ?? null);
if ($taxSource !== null) {
$row['meta']['tax_source'] = $taxSource;
}
}
}
return $row;
}
/**
* The object behind a balance transaction and its id: the explicit
* `$source`, else the transaction's own (expanded or id-only) `source`.
*
* @return array{0: object|null, 1: string|null}
*/
protected function ledgerSourceOf($txn, $source): array
{
$source = is_object($source) ? $source : (is_object($txn->source ?? null) ? $txn->source : null);
$sourceId = $source?->id ?? (is_string($txn->source ?? null) ? $txn->source : null);
return [$source, is_string($sourceId) ? $sourceId : null];
}
/**
@ -1291,12 +1343,37 @@ class ShopService
* id). Never downgrades a known customer_id/email back to null — so the
* real-time webhook, which resolves the buyer, is not clobbered by a later
* importer pass that couldn't. Returns 'created' or 'updated'.
*
* The VAT (`tax`) is looked up once: a row whose VAT is already known for
* the same amount keeps it without a Stripe call, and a failed lookup never
* replaces a known value.
*/
public function recordBalanceTransaction($txn, $source = null): string
{
$row = $this->ledgerRowFromBalanceTransaction($txn, $source);
$row = $this->ledgerRowFromBalanceTransaction($txn, $source, false);
$existing = $this->ledgerModel()::query()->where('stripe_id', $row['stripe_id'])->first();
if ($this->ledgerHasTaxColumn()) {
$existingSource = $existing ? ($existing->meta->tax_source ?? null) : null;
$known = $existing && ($existing->tax !== null || $existingSource === 'none');
if ($known && (int) $existing->amount === $row['amount']) {
[$tax, $taxSource] = [$existing->tax, $existingSource];
} else {
[$txnSource, $sourceId] = $this->ledgerSourceOf($txn, $source);
[$tax, $taxSource] = $this->ledgerRowTax($row['source_type'], $txnSource, $sourceId, $row['amount'], $row['meta']['payment_intent'] ?? null);
if ($tax === null && $taxSource === null && $existing?->tax !== null) {
[$tax, $taxSource] = [$existing->tax, $existingSource];
}
}
$row['tax'] = $tax;
if ($taxSource !== null) {
$row['meta']['tax_source'] = $taxSource;
}
}
if ($existing) {
if ($row['customer_id'] === null && $existing->customer_id !== null) {
$row['customer_id'] = $existing->customer_id;
@ -1335,10 +1412,7 @@ class ShopService
try {
Stripe::setApiKey($secret);
$charge = Charge::retrieve([
'id' => $chargeId,
'expand' => ['balance_transaction', 'refunds.data.balance_transaction'],
]);
$charge = $this->retrieveLedgerSyncCharge($chargeId);
$count = 0;
if (is_object($charge->balance_transaction ?? null)) {
@ -1364,6 +1438,463 @@ class ShopService
}
}
/**
* The charge for {@see syncLedgerForCharge}, with its balance transaction,
* its refunds' balance transactions and its invoice expanded (the invoice
* holds the VAT, so expanding it saves a call). API versions without
* `Charge.invoice` (2025-03-31 and later) refuse that expansion; the charge
* is then fetched without it.
*/
protected function retrieveLedgerSyncCharge(string $chargeId): object
{
$expand = ['balance_transaction', 'refunds.data.balance_transaction'];
try {
return Charge::retrieve(['id' => $chargeId, 'expand' => [...$expand, 'invoice']]);
} catch (\Stripe\Exception\InvalidRequestException $e) {
return Charge::retrieve(['id' => $chargeId, 'expand' => $expand]);
}
}
// =========================================================================
// LEDGER VAT
// =========================================================================
/**
* Ledger row types whose amount is a share of a charge, and so carries the
* charge's VAT: the charge itself (`charge`, `payment`), and what gives
* some of it back or returns it (`refund`, `payment_refund`, a bounced
* debit's `payment_failure_refund`, a failed refund's `refund_failure`).
*
* @return list<string>
*/
protected function ledgerTaxTypes(): array
{
return ['charge', 'payment', 'refund', 'payment_refund', 'payment_failure_refund', 'refund_failure'];
}
/** Whether the ledger table has the `tax` column (a found column is remembered). */
protected function ledgerHasTaxColumn(): bool
{
if ($this->ledgerTaxColumn) {
return true;
}
$model = $this->ledgerModel();
return $this->ledgerTaxColumn = \Illuminate\Support\Facades\Schema::hasColumn((new $model)->getTable(), 'tax');
}
/** `SUM(tax) as tax` for the aggregates, or `0 as tax` before the column exists. */
protected function ledgerTaxSumSql(): string
{
return $this->ledgerHasTaxColumn() ? 'SUM(COALESCE(tax, 0)) as tax' : '0 as tax';
}
/**
* The VAT inside one ledger row's `amount`, signed like the amount, and
* where it came from: `[tax, source]`.
*
* The charge's VAT comes from Stripe: its invoice (`tax`, pro-rated by the
* captured amount over the invoice total, so a partly credit-paid invoice
* counts only the cash part), else the Checkout Session of its payment
* intent (`total_details.amount_tax`). A row then carries the share of it
* its amount is of the charge, so a refund carries the refunded share,
* negative. Prices may or may not include VAT; only Stripe's figures count.
*
* Returns `[null, 'none']` when Stripe holds no VAT data for the charge,
* `[null, null]` when the row is not a charge share or the lookup failed
* (it is tried again on the next import). Never throws.
*
* @return array{0: int|null, 1: string|null}
*/
protected function ledgerRowTax(?string $type, ?object $source, ?string $sourceId, int $amount, ?string $paymentIntent): array
{
if (! in_array($type, $this->ledgerTaxTypes(), true)) {
return [null, null];
}
if ($amount === 0) {
return [0, null];
}
try {
[$charge, $chargeId] = $this->ledgerChargeOf($source, $sourceId);
$isCharge = in_array($type, ['charge', 'payment'], true);
$vat = $this->ledgerChargeVat($charge ?? $chargeId, $paymentIntent, ! $isCharge);
// A refund known only by its id: ask Stripe which charge it refunds.
if ($vat === null && $charge === null && $chargeId === null && $this->isLedgerRefundId($sourceId)) {
$refund = $this->stripeClient()->refunds->retrieve($sourceId);
$refundCharge = $refund->charge ?? null;
$refundIntent = $refund->payment_intent ?? null;
$vat = $this->ledgerChargeVat(
is_object($refundCharge) ? $refundCharge : (is_string($refundCharge) ? $refundCharge : null),
$paymentIntent ?? (is_string($refundIntent) ? $refundIntent : null),
true,
);
}
} catch (\Throwable $e) {
Log::warning('[shop:ledger] VAT lookup failed', ['source' => $sourceId, 'error' => $e->getMessage()]);
return [null, null];
}
if ($vat === null) {
return [null, null];
}
if ($vat['tax'] === null) {
return [null, 'none'];
}
return [$vat['base'] > 0 ? (int) round($amount * $vat['tax'] / $vat['base']) : 0, $vat['source']];
}
/**
* The charge a row belongs to, as `[object|null, id|null]`: the source
* itself when it is a charge (`ch_`, `py_`), the refunded charge when it is
* a refund.
*
* @return array{0: object|null, 1: string|null}
*/
protected function ledgerChargeOf(?object $source, ?string $sourceId): array
{
$isCharge = static fn ($id) => is_string($id) && (str_starts_with($id, 'ch_') || str_starts_with($id, 'py_'));
if ($source !== null) {
$kind = $source->object ?? null;
$id = $source->id ?? null;
if ($kind === 'charge' || ($kind === null && $isCharge($id))) {
return [$source, is_string($id) ? $id : null];
}
if ($kind === 'refund' || ($kind === null && $this->isLedgerRefundId($id))) {
$charge = $source->charge ?? null;
if (is_object($charge)) {
return [$charge, is_string($charge->id ?? null) ? $charge->id : null];
}
return [null, $isCharge($charge) ? $charge : null];
}
return [null, null];
}
return [null, $isCharge($sourceId) ? $sourceId : null];
}
protected function isLedgerRefundId(mixed $id): bool
{
return is_string($id) && (str_starts_with($id, 're_') || str_starts_with($id, 'pyr_'));
}
/**
* One charge's VAT as `{tax, base, source}`: `tax` is the VAT inside the
* charge's captured amount `base` (null when Stripe holds none, `source`
* then `none`). Remembered per charge and payment intent for the process,
* so a charge and its refunds cost one lookup. With `$fromLedger`, the
* charge's own ledger row is asked first (refunds of a known charge then
* need no Stripe call). Returns null when nothing identifies the charge or
* the lookup failed.
*
* @return array{tax: int|null, base: int, source: string}|null
*/
protected function ledgerChargeVat(object|string|null $charge, ?string $paymentIntent = null, bool $fromLedger = false): ?array
{
$chargeId = is_object($charge) ? ($charge->id ?? null) : $charge;
$chargeId = is_string($chargeId) && $chargeId !== '' ? $chargeId : null;
if (is_object($charge) && $paymentIntent === null) {
$paymentIntent = $this->ledgerIdOf($charge->payment_intent ?? null);
}
$paymentIntent = is_string($paymentIntent) && $paymentIntent !== '' ? $paymentIntent : null;
$keys = array_values(array_filter([$chargeId, $paymentIntent ? 'pi:'.$paymentIntent : null]));
foreach ($keys as $key) {
if (array_key_exists($key, $this->ledgerVatCache)) {
return $this->ledgerVatCache[$key] ?: null;
}
}
if ($keys === []) {
return null;
}
try {
$vat = $fromLedger ? $this->ledgerVatFromChargeRow($chargeId, $paymentIntent) : null;
if ($vat === null && ! is_object($charge)) {
if ($chargeId === null) {
// Only a payment intent, and no ledger row has it: nothing
// to ask Stripe here, and nothing to remember.
return null;
}
$charge = $this->retrieveLedgerCharge($chargeId);
}
if ($vat === null && is_object($charge)) {
$vat = $this->ledgerVatOfCharge($charge);
}
} catch (\Throwable $e) {
Log::warning('[shop:ledger] VAT lookup failed', [
'charge' => $chargeId,
'payment_intent' => $paymentIntent,
'error' => $e->getMessage(),
]);
$vat = null;
}
if (is_object($charge) && ($pi = $this->ledgerIdOf($charge->payment_intent ?? null))) {
$keys[] = 'pi:'.$pi;
}
foreach (array_unique($keys) as $key) {
// Failures are remembered too, so one broken charge is not asked
// again for each of its refunds in the same run.
$this->rememberLedgerLookup($this->ledgerVatCache, $key, $vat ?? false);
}
return $vat;
}
/**
* The VAT of a charge whose ledger row already has it, matched on the
* charge id or its payment intent.
*
* @return array{tax: int|null, base: int, source: string}|null
*/
protected function ledgerVatFromChargeRow(?string $chargeId, ?string $paymentIntent): ?array
{
if ($chargeId === null && $paymentIntent === null) {
return null;
}
$row = $this->ledgerModel()::query()
->whereIn('source_type', ['charge', 'payment'])
->where('amount', '!=', 0)
->where(function ($q) use ($chargeId, $paymentIntent) {
if ($chargeId !== null) {
$q->orWhere('source_id', $chargeId);
}
if ($paymentIntent !== null) {
$q->orWhere('meta->payment_intent', $paymentIntent);
}
})
->where(fn ($q) => $q->whereNotNull('tax')->orWhere('meta->tax_source', 'none'))
->first();
if (! $row) {
return null;
}
return [
'tax' => $row->tax === null ? null : (int) $row->tax,
'base' => (int) $row->amount,
'source' => (string) ($row->meta->tax_source ?? 'ledger'),
];
}
/**
* The VAT inside a Stripe charge, from its invoice, else from the Checkout
* Session of its payment intent. `source` is `none` (and `tax` null) when
* neither exists.
*
* @return array{tax: int|null, base: int, source: string}
*/
protected function ledgerVatOfCharge(object $charge): array
{
$captured = (int) ($charge->amount_captured ?? $charge->amount ?? 0);
$invoice = $charge->invoice ?? null;
if (is_string($invoice) && $invoice !== '') {
$invoice = $this->retrieveLedgerInvoice($invoice);
}
if (is_object($invoice)) {
return [
'tax' => $this->ledgerProRate($this->ledgerInvoiceTax($invoice), $captured, (int) ($invoice->total ?? 0)),
'base' => $captured,
'source' => 'invoice',
];
}
$paymentIntent = $this->ledgerIdOf($charge->payment_intent ?? null);
$session = $paymentIntent ? $this->retrieveLedgerCheckoutSession($paymentIntent) : null;
if (is_object($session)) {
return [
'tax' => $this->ledgerProRate((int) ($session->total_details->amount_tax ?? 0), $captured, (int) ($session->amount_total ?? 0)),
'base' => $captured,
'source' => 'checkout_session',
];
}
return ['tax' => null, 'base' => $captured, 'source' => 'none'];
}
/**
* An invoice's VAT: `tax` (API versions up to 2025-02-24), else the sum of
* `total_tax_amounts`, else of `total_taxes` (2025-03-31 and later).
* Inclusive and exclusive taxes both count.
*/
protected function ledgerInvoiceTax(object $invoice): int
{
if (isset($invoice->tax) && is_numeric($invoice->tax)) {
return (int) $invoice->tax;
}
foreach (['total_tax_amounts', 'total_taxes'] as $field) {
$lines = $invoice->{$field} ?? null;
if ($lines !== null) {
$sum = 0;
foreach ($lines as $line) {
$sum += (int) ($line->amount ?? 0);
}
return $sum;
}
}
return 0;
}
/** The share of `$tax` (on `$total`) the captured cash pays, capped at all of it. */
protected function ledgerProRate(int $tax, int $captured, int $total): int
{
if ($total <= 0 || $captured <= 0) {
return 0;
}
return (int) round($tax * min($captured, $total) / $total);
}
protected function ledgerIdOf(mixed $value): ?string
{
$id = is_object($value) ? ($value->id ?? null) : $value;
return is_string($id) && $id !== '' ? $id : null;
}
/** A charge with its invoice expanded (without, where the API version has no `Charge.invoice`). */
protected function retrieveLedgerCharge(string $chargeId): object
{
try {
return $this->stripeClient()->charges->retrieve($chargeId, ['expand' => ['invoice']]);
} catch (\Stripe\Exception\InvalidRequestException $e) {
return $this->stripeClient()->charges->retrieve($chargeId);
}
}
protected function retrieveLedgerInvoice(string $invoiceId): object
{
$key = 'invoice:'.$invoiceId;
if (! array_key_exists($key, $this->ledgerStripeCache)) {
$this->rememberLedgerLookup($this->ledgerStripeCache, $key, $this->stripeClient()->invoices->retrieve($invoiceId));
}
return $this->ledgerStripeCache[$key];
}
/** The Checkout Session that took the payment intent, or null when none did. */
protected function retrieveLedgerCheckoutSession(string $paymentIntent): ?object
{
$key = 'session:'.$paymentIntent;
if (! array_key_exists($key, $this->ledgerStripeCache)) {
$list = $this->stripeClient()->checkout->sessions->all(['payment_intent' => $paymentIntent, 'limit' => 1]);
$this->rememberLedgerLookup($this->ledgerStripeCache, $key, $list->data[0] ?? null);
}
return $this->ledgerStripeCache[$key];
}
/** Remember a lookup, dropping the oldest once a long-running process holds many. */
protected function rememberLedgerLookup(array &$cache, string $key, mixed $value): void
{
unset($cache[$key]);
$cache[$key] = $value;
if (count($cache) > 2000) {
array_shift($cache);
}
}
/**
* Fill `tax` on the Stripe charge, payment and refund rows that have none
* yet, from Stripe's own data (read-only; see {@see ledgerRowTax}). Charges
* go first, so their refunds reuse the charge's VAT without another call.
* Idempotent: rows that got a value are not touched again, and rows Stripe
* holds no VAT data for are marked `meta.tax_source = none` and skipped on
* later runs unless `$recheck`. A failed lookup leaves the row NULL and
* goes on. `$dryRun` writes nothing. `$progress` is called with the running
* totals after every row.
*
* @return array{scanned: int, filled: int, tax: int, none: int, failed: int}
*/
public function backfillLedgerTax(
bool $dryRun = false,
?\DateTimeInterface $since = null,
bool $recheck = false,
?callable $progress = null,
): array {
$totals = ['scanned' => 0, 'filled' => 0, 'tax' => 0, 'none' => 0, 'failed' => 0];
if (! $this->ledgerHasTaxColumn()) {
return $totals;
}
$model = $this->ledgerModel();
$hasProvider = \Illuminate\Support\Facades\Schema::hasColumn((new $model)->getTable(), 'provider');
$chargeTypes = ['charge', 'payment'];
foreach ([$chargeTypes, array_values(array_diff($this->ledgerTaxTypes(), $chargeTypes))] as $types) {
$rows = $model::query()
->whereNull('tax')
->whereIn('source_type', $types)
->when($hasProvider, fn ($q) => $q->where('provider', 'stripe'))
->when($since, fn ($q) => $q->where('created', '>=', $since))
->lazyById(200);
foreach ($rows as $row) {
$meta = json_decode(json_encode($row->meta ?? new \stdClass), true) ?: [];
if (! $recheck && ($meta['tax_source'] ?? null) === 'none') {
continue;
}
$totals['scanned']++;
[$tax, $taxSource] = $this->ledgerRowTax(
$row->source_type,
null,
$row->source_id,
(int) $row->amount,
$meta['payment_intent'] ?? null,
);
if ($tax === null) {
$taxSource === 'none' ? $totals['none']++ : $totals['failed']++;
} else {
$totals['filled']++;
$totals['tax'] += $tax;
}
if (! $dryRun && ($tax !== null || $taxSource !== null)) {
if ($taxSource !== null) {
$meta['tax_source'] = $taxSource;
}
$row->forceFill(['tax' => $tax, 'meta' => $meta])->save();
}
if ($progress) {
$progress($totals);
}
}
}
return $totals;
}
// =========================================================================
// REFUNDS
// =========================================================================

View File

@ -0,0 +1,507 @@
<?php
namespace Blax\Shop\Tests\Feature\Ledger;
use Blax\Shop\Facades\Shop;
use Blax\Shop\Models\StripeTransaction;
use Blax\Shop\Services\ShopService;
use Blax\Shop\Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use PHPUnit\Framework\Attributes\Test;
/**
* The VAT (`tax`) inside each ledger row comes from Stripe per charge: the
* charge's invoice (pro-rated by the cash captured), else the Checkout Session
* of its payment intent. Refunds carry the refunded share, negative.
*
* Stripe is faked through the container-bound `\Stripe\StripeClient`; plain
* objects stand in for stripe-php's (see LedgerMetricsTest for why).
*/
class LedgerTaxTest extends TestCase
{
use RefreshDatabase;
/**
* A StripeClient stand-in answering `invoices|charges|refunds->retrieve($id)`
* and `checkout->sessions->all(['payment_intent' => …])` from `$responses`
* (`'invoices.retrieve' => [id => object|Throwable]`, `'sessions.all' =>
* [pi => session]`). Every call lands in `->calls`.
*/
private function fakeStripe(array $responses = []): object
{
$fake = new class($responses)
{
public array $calls = [];
public object $invoices;
public object $charges;
public object $refunds;
public object $checkout;
public function __construct(public array $responses)
{
$make = fn (string $name) => new class($this, $name)
{
public function __construct(private object $outer, private string $name) {}
public function retrieve($id, $params = null, $opts = null)
{
return $this->outer->answer("{$this->name}.retrieve", (string) $id);
}
public function all($params = null, $opts = null)
{
return $this->outer->answer("{$this->name}.all", (string) ($params['payment_intent'] ?? ''));
}
};
$this->invoices = $make('invoices');
$this->charges = $make('charges');
$this->refunds = $make('refunds');
$this->checkout = (object) ['sessions' => $make('sessions')];
}
public function answer(string $op, string $key)
{
$this->calls[] = "{$op}:{$key}";
$answer = $this->responses[$op][$key] ?? null;
if ($answer instanceof \Throwable) {
throw $answer;
}
if ($op === 'sessions.all') {
return (object) ['data' => $answer ? [$answer] : []];
}
if ($answer === null) {
throw new \RuntimeException("No such object: {$key}");
}
return $answer;
}
};
$this->app->instance(\Stripe\StripeClient::class, $fake);
return $fake;
}
/** DE 19 % inclusive: 23.80 gross holds 3.80 VAT. */
private function invoice(string $id = 'in_1', int $total = 2380, ?int $tax = 380, array $extra = []): object
{
return (object) array_merge(['id' => $id, 'object' => 'invoice', 'total' => $total, 'tax' => $tax], $extra);
}
private function charge(string $id, int $captured, $invoice = null, ?string $paymentIntent = null): object
{
return (object) [
'id' => $id, 'object' => 'charge', 'amount' => $captured, 'amount_captured' => $captured,
'currency' => 'eur', 'customer' => 'cus_T', 'invoice' => $invoice, 'payment_intent' => $paymentIntent,
];
}
private function chargeTxn(string $id, object|string $source, int $amount, string $type = 'charge'): object
{
return (object) [
'id' => $id, 'type' => $type, 'amount' => $amount, 'fee' => 50, 'net' => $amount - 50,
'currency' => 'eur', 'created' => strtotime('2026-10-05'), 'source' => $source,
];
}
private function refundTxn(string $id, object|string $source, int $amount, string $type = 'refund'): object
{
return (object) [
'id' => $id, 'type' => $type, 'amount' => $amount, 'fee' => 0, 'net' => $amount,
'currency' => 'eur', 'created' => strtotime('2026-10-06'), 'source' => $source,
];
}
private function row(string $stripeId): StripeTransaction
{
return StripeTransaction::where('stripe_id', $stripeId)->firstOrFail();
}
#[Test]
public function invoice_vat_is_the_charge_share_of_the_invoice(): void
{
$fake = $this->fakeStripe();
// The webhook expands the invoice on the charge: no extra call.
Shop::recordBalanceTransaction($this->chargeTxn('txn_1', $this->charge('ch_1', 2380, $this->invoice()), 2380));
// An invoice paid half from the customer's credit balance: only the
// cash part's VAT counts.
Shop::recordBalanceTransaction($this->chargeTxn('txn_2', $this->charge('ch_2', 1190, $this->invoice('in_2')), 1190));
// Reverse charge / untaxed: Stripe says 0, so 0 (never a flat 19/119).
Shop::recordBalanceTransaction($this->chargeTxn('txn_3', $this->charge('ch_3', 2000, $this->invoice('in_3', 2000, null, ['total_tax_amounts' => []])), 2000));
$this->assertSame(380, $this->row('txn_1')->tax);
$this->assertSame('invoice', $this->row('txn_1')->meta->tax_source);
$this->assertSame(190, $this->row('txn_2')->tax);
$this->assertSame(0, $this->row('txn_3')->tax);
$this->assertSame([], $fake->calls);
}
#[Test]
public function an_invoice_id_is_retrieved_once_and_total_tax_amounts_count_when_tax_is_absent(): void
{
$fake = $this->fakeStripe(['invoices.retrieve' => [
'in_9' => (object) ['id' => 'in_9', 'total' => 4760, 'total_tax_amounts' => [
(object) ['amount' => 760, 'inclusive' => true],
]],
]]);
// Importer shape: the expanded charge carries the invoice id only. Two
// partial charges of one invoice share the lookup.
Shop::recordBalanceTransaction($this->chargeTxn('txn_a', $this->charge('ch_a', 2380, 'in_9'), 2380));
Shop::recordBalanceTransaction($this->chargeTxn('txn_b', $this->charge('ch_b', 2380, 'in_9'), 2380));
$this->assertSame(380, $this->row('txn_a')->tax);
$this->assertSame(380, $this->row('txn_b')->tax);
$this->assertSame(['invoices.retrieve:in_9'], $fake->calls);
}
#[Test]
public function a_one_off_checkout_takes_the_vat_from_its_checkout_session(): void
{
$fake = $this->fakeStripe(['sessions.all' => [
'pi_once' => (object) ['id' => 'cs_1', 'amount_total' => 4990, 'total_details' => (object) ['amount_tax' => 797]],
]]);
Shop::recordBalanceTransaction($this->chargeTxn('txn_cs', $this->charge('ch_cs', 4990, null, 'pi_once'), 4990));
$row = $this->row('txn_cs');
$this->assertSame(797, $row->tax);
$this->assertSame('checkout_session', $row->meta->tax_source);
$this->assertSame('pi_once', $row->meta->payment_intent);
$this->assertSame(['sessions.all:pi_once'], $fake->calls);
}
#[Test]
public function a_payment_settled_in_paypal_gets_vat_on_the_charge_gross(): void
{
$this->fakeStripe(['sessions.all' => [
'pi_pp' => (object) ['amount_total' => 2040, 'total_details' => (object) ['amount_tax' => 326]],
]]);
// Stripe books amount 0; the ledger books the charge gross and its VAT.
Shop::recordBalanceTransaction((object) [
'id' => 'txn_pp', 'type' => 'payment', 'amount' => 0, 'fee' => 14, 'net' => -14,
'currency' => 'eur', 'created' => strtotime('2026-10-05'),
'source' => (object) ['id' => 'py_pp', 'object' => 'charge', 'amount' => 2040, 'amount_captured' => 2040,
'currency' => 'eur', 'invoice' => null, 'payment_intent' => 'pi_pp'],
]);
$this->assertSame(2040, $this->row('txn_pp')->amount);
$this->assertSame(326, $this->row('txn_pp')->tax);
}
#[Test]
public function a_refund_carries_the_refunded_share_of_the_charge_vat_negated(): void
{
$fake = $this->fakeStripe();
$charge = $this->charge('ch_r', 2380, $this->invoice(), 'pi_r');
// Webhook shape: the refund's source is the retrieved charge.
Shop::recordBalanceTransaction($this->chargeTxn('txn_c', $charge, 2380), $charge);
Shop::recordBalanceTransaction($this->refundTxn('txn_r1', $charge, -1000), $charge);
// Importer shape, in a fresh process: the refund knows its charge by id
// and the VAT comes off the charge's ledger row, without a Stripe call.
$refund = (object) ['id' => 're_2', 'object' => 'refund', 'amount' => 1380, 'charge' => 'ch_r', 'payment_intent' => 'pi_r'];
(new ShopService)->recordBalanceTransaction($this->refundTxn('txn_r2', $refund, -1380));
$this->assertSame(380, $this->row('txn_c')->tax);
$this->assertSame(-160, $this->row('txn_r1')->tax); // 1000 × 380 / 2380 = 159.7
$this->assertSame(-220, $this->row('txn_r2')->tax); // 1380 × 380 / 2380 = 220.3
$this->assertSame([], $fake->calls);
}
#[Test]
public function a_refund_imported_before_its_charge_costs_one_call_for_both(): void
{
// The importer pages newest first, so a refund comes before its charge.
$fake = $this->fakeStripe(['charges.retrieve' => [
'ch_n' => $this->charge('ch_n', 2380, $this->invoice('in_n'), 'pi_n'),
]]);
$refund = (object) ['id' => 're_n', 'object' => 'refund', 'amount' => 2380, 'charge' => 'ch_n', 'payment_intent' => 'pi_n'];
Shop::recordBalanceTransaction($this->refundTxn('txn_rn', $refund, -2380));
Shop::recordBalanceTransaction($this->chargeTxn('txn_cn', $this->charge('ch_n', 2380, 'in_n', 'pi_n'), 2380));
$this->assertSame(-380, $this->row('txn_rn')->tax);
$this->assertSame(380, $this->row('txn_cn')->tax);
$this->assertSame(['charges.retrieve:ch_n'], $fake->calls);
}
#[Test]
public function a_bounced_direct_debit_takes_its_vat_back(): void
{
$this->fakeStripe();
$charge = $this->charge('py_sepa', 2380, $this->invoice('in_sepa'));
Shop::recordBalanceTransaction($this->chargeTxn('txn_sepa', $charge, 2380, 'payment'), $charge);
Shop::recordBalanceTransaction((object) [
'id' => 'txn_bounce', 'type' => 'payment_failure_refund', 'amount' => -2380, 'fee' => 315, 'net' => -2695,
'currency' => 'eur', 'created' => strtotime('2026-10-09'),
], $charge);
$this->assertSame(380, $this->row('txn_sepa')->tax);
$this->assertSame(-380, $this->row('txn_bounce')->tax);
}
#[Test]
public function a_failed_lookup_leaves_tax_null_and_still_records_the_row(): void
{
$fake = $this->fakeStripe(['invoices.retrieve' => ['in_x' => new \RuntimeException('Stripe is down')]]);
$this->assertSame('created', Shop::recordBalanceTransaction($this->chargeTxn('txn_x', $this->charge('ch_x', 2380, 'in_x'), 2380)));
$row = $this->row('txn_x');
$this->assertNull($row->tax);
$this->assertSame(2380, $row->amount);
$this->assertSame(2330, $row->net);
$this->assertObjectNotHasProperty('tax_source', $row->meta);
// The next import, with Stripe back, fills it.
$fake->responses['invoices.retrieve']['in_x'] = $this->invoice('in_x');
(new ShopService)->recordBalanceTransaction($this->chargeTxn('txn_x', $this->charge('ch_x', 2380, 'in_x'), 2380));
$this->assertSame(380, $this->row('txn_x')->tax);
}
#[Test]
public function without_stripe_credentials_the_lookup_fails_quietly(): void
{
// No bound client and no secret: stripeClient() throws, the row stays.
Shop::recordBalanceTransaction($this->chargeTxn('txn_ns', $this->charge('ch_ns', 2380, 'in_ns'), 2380));
$this->assertNull($this->row('txn_ns')->tax);
$this->assertSame(2380, $this->row('txn_ns')->amount);
}
#[Test]
public function a_known_vat_is_kept_on_reimport_without_a_stripe_call(): void
{
$fake = $this->fakeStripe(['invoices.retrieve' => ['in_k' => $this->invoice('in_k')]]);
$txn = $this->chargeTxn('txn_k', $this->charge('ch_k', 2380, 'in_k'), 2380);
Shop::recordBalanceTransaction($txn);
(new ShopService)->recordBalanceTransaction($txn);
$this->assertSame(380, $this->row('txn_k')->tax);
$this->assertSame(['invoices.retrieve:in_k'], $fake->calls);
}
#[Test]
public function a_charge_stripe_holds_no_vat_for_is_marked_and_not_asked_again(): void
{
$fake = $this->fakeStripe(); // no session for pi_none
$txn = $this->chargeTxn('txn_none', $this->charge('ch_none', 1500, null, 'pi_none'), 1500);
Shop::recordBalanceTransaction($txn);
(new ShopService)->recordBalanceTransaction($txn);
$row = $this->row('txn_none');
$this->assertNull($row->tax);
$this->assertSame('none', $row->meta->tax_source);
$this->assertSame(['sessions.all:pi_none'], $fake->calls);
}
#[Test]
public function fees_and_payouts_carry_no_vat(): void
{
$fake = $this->fakeStripe();
Shop::recordBalanceTransaction((object) [
'id' => 'txn_fee', 'type' => 'stripe_fee', 'amount' => -14, 'fee' => 0, 'net' => -14,
'currency' => 'eur', 'created' => strtotime('2026-10-05'),
]);
Shop::recordBalanceTransaction((object) [
'id' => 'txn_po', 'type' => 'payout', 'amount' => -5000, 'fee' => 0, 'net' => -5000,
'currency' => 'eur', 'created' => strtotime('2026-10-05'), 'source' => 'po_1',
]);
$this->assertNull($this->row('txn_fee')->tax);
$this->assertNull($this->row('txn_po')->tax);
$this->assertSame([], $fake->calls);
}
#[Test]
public function sync_ledger_for_charge_expands_the_invoice_and_books_charge_and_refund_vat(): void
{
config(['services.stripe.secret' => 'sk_test_fake']);
$fake = $this->fakeStripe();
$charge = $this->charge('ch_sync', 2380, $this->invoice('in_sync'), 'pi_sync');
$charge->balance_transaction = (object) [
'id' => 'txn_sync', 'type' => 'charge', 'amount' => 2380, 'fee' => 50, 'net' => 2330,
'currency' => 'eur', 'created' => strtotime('2026-10-05'),
];
$charge->refunds = (object) ['data' => [(object) ['id' => 're_sync', 'amount' => 1190, 'balance_transaction' => (object) [
'id' => 'txn_sync_r', 'type' => 'refund', 'amount' => -1190, 'fee' => 0, 'net' => -1190,
'currency' => 'eur', 'created' => strtotime('2026-10-06'),
]]]];
$service = new class($charge) extends ShopService
{
public array $retrieved = [];
public function __construct(private object $fixture) {}
protected function retrieveLedgerSyncCharge(string $chargeId): object
{
$this->retrieved[] = $chargeId;
return $this->fixture;
}
};
$this->assertSame(2, $service->syncLedgerForCharge('ch_sync'));
$this->assertSame(['ch_sync'], $service->retrieved);
$this->assertSame(380, $this->row('txn_sync')->tax);
$this->assertSame(-190, $this->row('txn_sync_r')->tax);
$this->assertSame([], $fake->calls);
}
#[Test]
public function aggregates_sum_the_signed_vat_and_count_unknown_as_zero(): void
{
$make = fn (array $a) => StripeTransaction::create(array_merge([
'stripe_id' => 'txn_'.bin2hex(random_bytes(6)), 'source_type' => 'charge', 'currency' => 'eur',
'customer_id' => 'cus_A', 'created' => Carbon::parse('2026-10-05 10:00'),
], $a));
$make(['amount' => 2380, 'fee' => 50, 'net' => 2330, 'tax' => 380]);
$make(['amount' => 4990, 'fee' => 90, 'net' => 4900, 'tax' => 797]);
$make(['source_type' => 'refund', 'amount' => -1190, 'net' => -1190, 'tax' => -190]);
$make(['amount' => 1000, 'fee' => 30, 'net' => 970, 'tax' => null]); // unknown
$make(['source_type' => 'stripe_fee', 'amount' => 0, 'fee' => 14, 'net' => -14, 'customer_id' => null]);
$make(['source_type' => 'payout', 'amount' => -5000, 'net' => -5000, 'tax' => 999, 'customer_id' => null]); // not revenue
$from = Carbon::parse('2026-10-01');
$until = Carbon::parse('2026-10-31');
$vat = 380 + 797 - 190;
$totals = Shop::ledgerTotals($from, $until);
$this->assertSame($vat, $totals['tax']);
$this->assertSame(['gross', 'refunds', 'fees', 'net', 'count', 'tax'], array_keys($totals));
$day = Shop::revenueLedgerByDay($from, $until)->first();
$this->assertSame($vat, $day->tax);
$this->assertSame($totals['net'], $day->net);
$byAccount = Shop::ledgerTotalsByAccount($from, $until);
$this->assertSame($vat, $byAccount->sum('tax'));
$this->assertSame('stripe', $byAccount->first()['provider']);
$this->assertSame($vat, Shop::customerLedgerTotals('cus_A')['tax']);
$this->assertSame(0, Shop::customerLedgerTotals([], [])['tax']);
$this->assertSame(0, Shop::ledgerTotals(Carbon::parse('2020-01-01'), Carbon::parse('2020-01-02'))['tax']);
}
#[Test]
public function backfill_fills_missing_vat_read_only_and_idempotently(): void
{
config(['services.stripe.secret' => 'sk_test_fake']);
$fake = $this->fakeStripe([
'charges.retrieve' => [
'ch_b1' => $this->charge('ch_b1', 2380, $this->invoice('in_b1'), 'pi_b1'),
'ch_b2' => $this->charge('ch_b2', 1190, $this->invoice('in_b2'), 'pi_b2'), // half paid from credit
'ch_b3' => $this->charge('ch_b3', 1500, null, 'pi_b3'), // Stripe holds no VAT
'ch_bx' => new \RuntimeException('Stripe is down'),
],
]);
$make = fn (array $a) => StripeTransaction::create(array_merge([
'stripe_id' => 'txn_'.bin2hex(random_bytes(6)), 'source_type' => 'charge', 'currency' => 'eur',
'created' => Carbon::parse('2026-10-05'), 'fee' => 0,
], $a));
$make(['source_id' => 'ch_b1', 'amount' => 2380, 'net' => 2380, 'meta' => ['payment_intent' => 'pi_b1']]);
$make(['source_id' => 'ch_b2', 'amount' => 1190, 'net' => 1190, 'meta' => ['payment_intent' => 'pi_b2']]);
$make(['source_id' => 'ch_b3', 'amount' => 1500, 'net' => 1500, 'meta' => ['payment_intent' => 'pi_b3']]);
$make(['source_id' => 'ch_bx', 'amount' => 999, 'net' => 999]);
// An importer refund row: known by its re_ id and payment intent only.
$make(['source_type' => 'refund', 'source_id' => 're_b1', 'amount' => -1190, 'net' => -1190, 'meta' => ['payment_intent' => 'pi_b1']]);
// Already known, not a charge share, or not Stripe's: left alone.
$make(['source_id' => 'ch_done', 'amount' => 2380, 'net' => 2380, 'tax' => 380]);
$make(['source_type' => 'payout', 'source_id' => 'po_1', 'amount' => -5000, 'net' => -5000]);
$make(['provider' => 'paypal', 'source_type' => 'payment', 'source_id' => 'PP-1', 'amount' => 3000, 'net' => 2900]);
// Dry run: totals, no writes.
$dry = Shop::backfillLedgerTax(true);
$this->assertSame(['scanned' => 5, 'filled' => 3, 'tax' => 380 + 190 - 190, 'none' => 1, 'failed' => 1], $dry);
$this->assertSame(1, StripeTransaction::whereNotNull('tax')->count());
// Reads only, one per charge; the refund reuses its charge's VAT.
$this->assertEqualsCanonicalizing([
'charges.retrieve:ch_b1', 'charges.retrieve:ch_b2', 'charges.retrieve:ch_b3',
'sessions.all:pi_b3', 'charges.retrieve:ch_bx',
], $fake->calls);
$this->artisan('shop:import-stripe-ledger', ['--backfill-tax' => true])
->assertSuccessful();
$this->assertSame(380, StripeTransaction::where('source_id', 'ch_b1')->value('tax'));
$this->assertSame(190, StripeTransaction::where('source_id', 'ch_b2')->value('tax'));
$this->assertNull(StripeTransaction::where('source_id', 'ch_b3')->value('tax'));
$this->assertSame('none', StripeTransaction::where('source_id', 'ch_b3')->firstOrFail()->meta->tax_source);
$this->assertNull(StripeTransaction::where('source_id', 'ch_bx')->value('tax'));
$this->assertSame(-190, StripeTransaction::where('source_id', 're_b1')->value('tax'));
$this->assertNull(StripeTransaction::where('source_id', 'po_1')->value('tax'));
$this->assertNull(StripeTransaction::where('source_id', 'PP-1')->value('tax'));
// Again: only the failed row is tried; the "none" row only with recheck.
$fake->calls = [];
$again = (new ShopService)->backfillLedgerTax();
$this->assertSame(['scanned' => 1, 'filled' => 0, 'tax' => 0, 'none' => 0, 'failed' => 1], $again);
$this->assertSame(['charges.retrieve:ch_bx'], $fake->calls);
$recheck = (new ShopService)->backfillLedgerTax(false, null, true);
$this->assertSame(2, $recheck['scanned']);
$this->assertSame(1, $recheck['none']);
}
#[Test]
public function before_the_migration_rows_save_without_tax_and_totals_report_zero(): void
{
// A consumer that publishes migrations may update the package first.
\Illuminate\Support\Facades\Schema::table('stripe_transactions', fn ($t) => $t->dropColumn('tax'));
$fake = $this->fakeStripe();
$txn = $this->chargeTxn('txn_old', $this->charge('ch_old', 2380, $this->invoice()), 2380);
$this->assertArrayNotHasKey('tax', Shop::ledgerRowFromBalanceTransaction($txn));
$this->assertSame('created', Shop::recordBalanceTransaction($txn));
$this->assertSame('updated', Shop::recordBalanceTransaction($txn));
$totals = Shop::ledgerTotals(Carbon::parse('2026-10-01'), Carbon::parse('2026-10-31'));
$this->assertSame(2380, $totals['gross']);
$this->assertSame(0, $totals['tax']);
$this->assertSame(0, Shop::revenueLedgerByDay(Carbon::parse('2026-10-01'), Carbon::parse('2026-10-31'))->first()->tax);
$this->assertSame(0, Shop::ledgerTotalsByAccount(Carbon::parse('2026-10-01'), Carbon::parse('2026-10-31'))->first()['tax']);
$this->assertSame(0, Shop::customerLedgerTotals('cus_T')['tax']);
$this->assertSame(['scanned' => 0, 'filled' => 0, 'tax' => 0, 'none' => 0, 'failed' => 0], Shop::backfillLedgerTax());
$this->assertSame([], $fake->calls);
}
#[Test]
public function backfill_dry_run_command_prints_totals_and_writes_nothing(): void
{
config(['services.stripe.secret' => 'sk_test_fake']);
$this->fakeStripe(['charges.retrieve' => ['ch_d' => $this->charge('ch_d', 2380, $this->invoice('in_d'))]]);
StripeTransaction::create([
'stripe_id' => 'txn_d', 'source_type' => 'charge', 'source_id' => 'ch_d', 'amount' => 2380, 'fee' => 0,
'net' => 2380, 'currency' => 'eur', 'created' => Carbon::parse('2026-10-05'),
]);
$this->artisan('shop:import-stripe-ledger', ['--backfill-tax' => true, '--dry-run' => true])
->expectsOutputToContain('[dry-run] would fill VAT for 1 of 1 rows without it: 3.80 in total')
->assertSuccessful();
$this->assertNull($this->row('txn_d')->tax);
}
}