OwnPay icon indicating copy to clipboard operation
OwnPay copied to clipboard

Several Architectural issues

Open fattain-naime opened this issue 1 month ago • 1 comments

Confirmed issues

  1. Ledger dedup keyed on description text — LedgerService::postEntries prevents double-posting by matching (merchant_id, reference_type, reference_id, description), so any two events sharing a description are silently dropped and legitimate entries can be skipped. 1

  2. Ledger account create race — LedgerRepository::findOrCreateAccount does SELECT-then-INSERT with no unique key/upsert, so concurrent posts can create duplicate accounts and split balances. 2

  3. Denormalized balance can drift — op_ledger_accounts.balance is updated via balance +/- :amount alongside entry inserts rather than derived from entries, so any missed adjustBalance call permanently desyncs balances from the journal. 3

  4. Silent no-op on missing account — adjustBalance returns without error if the account ID isn't found, so a posting can complete with entries but no balance update. 4

  5. Unknown account codes default to 'asset' — LedgerService::getAccountType maps any unrecognized code to asset, silently inverting debit/credit semantics for typos or new account types. 5

  6. Account resolution outside the posting transaction — postEntries resolves/creates accounts before opening the DB transaction, so account creation isn't atomic with the journal post it belongs to. 6

  7. Tenant isolation is opt-in, not enforced — LedgerRepository only applies the merchant_id filter when tenantId !== null, so any unscoped repository instance can read/update every tenant's balances; there's no DB-level enforcement (RLS/constraints). 7

  8. Refund find-or-create race in webhook handler — WebhookInboundProcessor selects then inserts op_refunds by (transaction_id, amount) with no unique constraint, so concurrent/duplicated webhook deliveries can double-count refunds. 8

  9. Non-atomic refund saga — RefundService::create commits a pending refund row in one transaction, then calls the gateway afterward; a crash between the two strands a pending refund with no compensating/queue mechanism. 9

  10. ~30+ gateway modules are auto-generated stubs — dozens of adapters (BillerGenie, FastSpring, Shift4, Heartland, 2Checkout, etc.) share identical boilerplate and rely on GatewayDefaults, so the claimed "120+ gateway integrations" largely don't implement real initiation/verification. 10 11

  11. Simulated refunds in non-production — 2Checkout's refund() returns a fabricated success (REF_...uniqid()) outside production, meaning refunds can be marked complete without money moving. 12

  12. Default initiate silently degrades — gateways without programmatic initiation return a warning div instead of an error, so checkout misconfiguration surfaces as broken UI rather than a failure. 13

  13. Gateways bypass the HTTP/SSRF abstraction — e.g. Square uses raw curl_init directly instead of the sandboxed HTTP_OUTBOUND capability layer, with a hardcoded API version and uniqid idempotency key. 14

  14. MD5 used for request signing — Rocket gateway computes its secure hash with md5() (likely provider-mandated, but still a weak primitive baked into the adapter). 15

  15. Singleton DB bypasses DI — services and controllers call Database::getInstance() directly (e.g. RefundService, PaymentIntentCheckoutController), undermining the PSR-11 container and making unit isolation hard. 16

  16. Duplicated atomic-pay blocks — PaymentIntentCheckoutController contains two near-identical SELECT FOR UPDATE transaction-setup blocks (~lines 601 and ~1261), a maintenance/drift hazard where a fix in one may not reach the other. 17

  17. Ad-hoc error logging — the checkout controller writes exceptions via fwrite(STDERR, ...) then falls back to the logger, which is fragile and inconsistent with the rest of the logging pipeline. 18

Likely but unverified

  • Lock-ordering deadlock risk: several paths take FOR UPDATE on op_payment_intents → op_transactions while the webhook path locks op_transactions directly; I didn't map all lock orders, so deadlock potential is plausible but unconfirmed.
  • Middleware, RBAC, plugin sandbox, and migrations were not inspected, so additional issues likely exist there.

Citations

File: src/Service/Payment/LedgerService.php (L35-48)

    public function getAccountType(string $code): string
    {
        $code = strtoupper($code);
        switch ($code) {
            case 'CASH':
            case 'BANK_OUT':
                return 'asset';
            case 'MERCHANT_PAYABLE':
                return 'liability';
            case 'PLATFORM_FEE_REVENUE':
                return 'revenue';
            default:
                return 'asset';
        }

File: src/Service/Payment/LedgerService.php (L74-127)

        $resolvedEntries = [];
        $totalDebit = '0.00';
        $totalCredit = '0.00';

        foreach ($entries as $entry) {
            $code = $entry['account'];
            $type = $entry['type']; // 'debit' or 'credit'
            $amount = (string) $entry['amount'];
            /** @var numeric-string $amount */

            $acctType = $this->getAccountType($code);
            $account = $this->ledger->findOrCreateAccount($code, $acctType, $currency, $merchantId);

            $acctIdVal = $account['id'] ?? 0;
            $resolvedEntries[] = [
                'account_id' => is_scalar($acctIdVal) ? (int) $acctIdVal : 0,
                'type' => $type,
                'amount' => $amount
            ];

            if ($type === 'debit') {
                $totalDebit = bcadd($totalDebit, $amount, 4);
            } else {
                $totalCredit = bcadd($totalCredit, $amount, 4);
            }
        }

        // Safety check to ensure debits equal credits
        if (bccomp($totalDebit, $totalCredit, 4) !== 0) {
            throw new \InvalidArgumentException("Ledger transaction is not balanced. Debits: {$totalDebit}, Credits: {$totalCredit}");
        }

        $scopedLedger = $this->ledger->forTenant($merchantId);
        $db = $scopedLedger->getDatabase();
        $db->transaction(function () use ($scopedLedger, $merchantId, $eventType, $resolvedEntries, $currency, $referenceType, $referenceId, $description, $totalDebit) {
            // Check for pre-existing transaction to prevent double ledger posting
            $exists = $scopedLedger->getDatabase()->fetchOne(
                "SELECT `id` FROM `op_ledger_transactions` 
                 WHERE `merchant_id` = :mid 
                   AND `reference_type` = :rt 
                   AND `reference_id` = :ri 
                   AND `description` = :desc 
                 FOR UPDATE",
                [
                    'mid' => $merchantId,
                    'rt' => $referenceType,
                    'ri' => (int) $referenceId,
                    'desc' => $description ?? $eventType
                ]
            );

            if ($exists !== null) {
                return;
            }

File: src/Repository/LedgerRepository.php (L65-82)

        $account = $this->db->fetchOne("SELECT * FROM {$this->table} WHERE {$where} LIMIT 1", $params);

        if ($account !== null) {
            return $account;
        }

        $id = $this->insert([
            'name' => $name,
            'type' => $type,
            'currency' => $currency,
            'merchant_id' => $mid,
            'balance' => '0.00',
        ]);

        $account = $this->find($id);
        if ($account === null) {
            throw new \RuntimeException("Failed to retrieve newly created ledger account.");
        }

File: src/Repository/LedgerRepository.php (L112-144)

    public function adjustBalance(int $accountId, string $amount, string $entryType): void
    {
        $account = $this->find($accountId);
        if ($account === null) {
            return;
        }

        $typeVal = $account['type'] ?? '';
        $type = strtolower(is_scalar($typeVal) ? (string) $typeVal : '');
        $entryType = strtolower($entryType);

        // Double-entry rules
        // Asset/Expense: debit increases (+), credit decreases (-)
        // Liability/Equity/Revenue: credit increases (+), debit decreases (-)
        $isIncrease = false;
        if (in_array($type, ['asset', 'expense'], true)) {
            $isIncrease = ($entryType === 'debit');
        } elseif (in_array($type, ['liability', 'equity', 'revenue'], true)) {
            $isIncrease = ($entryType === 'credit');
        }

        $operator = $isIncrease ? '+' : '-';

        $where = "`id` = :id";
        $params = ['amount' => $amount, 'id' => $accountId];
        if ($this->tenantId !== null) {
            $where .= " AND `merchant_id` = :mid";
            $params['mid'] = $this->requireTenant();
        }
        $this->db->execute(
            "UPDATE `op_ledger_accounts` SET `balance` = `balance` {$operator} :amount WHERE {$where}",
            $params
        );

File: src/Gateway/WebhookInboundProcessor.php (L453-474)

            // Find or create a refund record in op_refunds to get a unique refund ID for the ledger
            $refundRepo = $this->db->fetchOne(
                "SELECT id FROM op_refunds WHERE transaction_id = :txid AND merchant_id = :mid AND amount = :amt LIMIT 1",
                ['txid' => $txnId, 'mid' => $merchantId, 'amt' => $amount]
            );

            if ($refundRepo !== null && isset($refundRepo['id'])) {
                $idVal = $refundRepo['id'];
                $refundId = is_scalar($idVal) ? (int) $idVal : 0;
                $this->db->execute(
                    "UPDATE op_refunds SET status = 'completed', processed_at = NOW() WHERE id = :id",
                    ['id' => $refundId]
                );
            } else {
                $uuid = \Ramsey\Uuid\Uuid::uuid4()->toString();
                $this->db->execute(
                    "INSERT INTO op_refunds (merchant_id, transaction_id, uuid, amount, reason, status, processed_at)
                     VALUES (:mid, :txid, :uuid, :amt, 'Refund completed via webhook', 'completed', NOW())",
                    ['mid' => $merchantId, 'txid' => $txnId, 'uuid' => $uuid, 'amt' => $amount]
                );
                $refundId = (int) $this->db->lastInsertId();
            }

File: src/Service/Payment/RefundService.php (L80-84)

        $db = \OwnPay\Core\Database::getInstance();

        $preparation = $db->transaction(function () use ($db, $merchantId, $transactionId, $amount, $data) {
            $txn = $db->fetchOne(
                "SELECT * FROM op_transactions WHERE id = :id AND merchant_id = :mid FOR UPDATE",

File: src/Service/Payment/RefundService.php (L168-210)

            $id = $this->refunds->forTenant($merchantId)->createRefund([
                'transaction_id' => $txnId,
                'amount' => (string)$amount,
                'reason' => $data['reason'] ?? '',
                'status' => 'pending'
            ]);

            $refund = $this->refunds->forTenant($merchantId)->findScoped((int)$id);
            if (!$refund) {
                throw new RuntimeException("Refund record not found after creation");
            }

            $gwSlugVal = $txn['gateway_slug'] ?? '';
            $gwSlug = is_scalar($gwSlugVal) ? (string)$gwSlugVal : '';
            $gwTrxIdVal = $txn['gateway_trx_id'] ?? $txn['trx_id'] ?? '';
            $gwTrxId = is_scalar($gwTrxIdVal) ? (string)$gwTrxIdVal : '';

            return [
                'refund' => $refund,
                'refund_id' => (int)$id,
                'txn_id' => $txnId,
                'amount' => (string)$amount,
                'currency' => $currency,
                'gateway_slug' => $gwSlug,
                'gateway_trx_id' => $gwTrxId,
                'orig_amount' => $origAmount,
            ];
        });

        $refundId = $preparation['refund_id'];
        $txnId = $preparation['txn_id'];
        $amountStr = $preparation['amount'];
        $currency = $preparation['currency'];
        $gwSlug = $preparation['gateway_slug'];
        $gwTrxId = $preparation['gateway_trx_id'];
        $origAmount = $preparation['orig_amount'];

        $gatewaySuccess = false;
        $gatewayError = null;

        try {
            $result = $this->bridge->refund(
                $gwSlug,

File: modules/gateways/biller-genie/BillerGenieGateway.php (L21-52)

final class BillerGenieGateway implements PluginInterface, GatewayAdapterInterface
{
    use GatewayDefaults;

    private ?Container $container = null;

    /**
     * static metadata descriptor.
     */
    public static function metadata(): array
    {
        return [
            'name'        => 'Biller Genie',
            'slug'        => 'biller-genie',
            'version'     => '1.0.0',
            'description' => 'Biller Genie payment gateway integration for OwnPay',
            'author'      => 'OwnPay Core',
            'type'        => 'gateway',
        ];
    }

    /**
     * Expose capabilities.
     */
    public function capabilities(): array
    {
        return [
            Capability::GATEWAY,
            Capability::HTTP_OUTBOUND,
            Capability::HOOKS,
        ];
    }

File: src/Gateway/GatewayDefaults.php (L22-45)

    public function initiate(array $params, array $credentials): array
    {
        return [
            'redirect_url' => null,
            'form_html'    => '<div class="op-alert op-alert-warning">This gateway does not support programmatic initiation.</div>',
        ];
    }

    /**
     * Fallback verification indicating failure of transaction lookups.
     *
     * @param array<string, mixed> $callbackData Payload received from the payment provider.
     * @param array<string, mixed> $credentials Decrypted, merchant-configured gateway credentials.
     * @return array{success: bool, gateway_trx_id?: string|null, amount?: string|null, status?: string} Unsuccessful verification state.
     */
    public function verify(array $callbackData, array $credentials): array
    {
        return [
            'success'        => false,
            'gateway_trx_id' => null,
            'amount'         => null,
            'status'         => 'unsupported',
        ];
    }

File: modules/gateways/2checkout/TwoCheckoutGateway.php (L314-333)

    public function refund(string $gatewayTrxId, string $amount, array $credentials): array
    {
        // Automated refunds are not implemented for this gateway; the simulated
        // success below is for local testing only. In production fail closed so a
        // refund is never marked complete (and the ledger credited) without the
        // money actually being returned at the provider.
        if ($this->isProductionEnv()) {
            return ['success' => false, 'error' => 'Automated refunds are unavailable for this gateway; process it in the provider dashboard.'];
        }

        $mode = $this->getString($credentials['mode'] ?? 'sandbox');
        if ($mode === 'live') {
            throw new \RuntimeException('2Checkout live refund integration is not supported in this version.');
        }
        // Dynamic refund simulation
        return [
            'success'   => true,
            'refund_id' => 'REF_' . $this->slug() . '_' . uniqid(),
        ];
    }

File: modules/gateways/square/SquareGateway.php (L66-88)

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_HTTPHEADER     => [
                'Authorization: Bearer ' . $accessToken,
                'Content-Type: application/json',
                'Square-Version: 2026-05-28',
            ],
            CURLOPT_POSTFIELDS     => (string) json_encode([
                'idempotency_key' => uniqid('sq_', true),
                'quick_pay' => [
                    'name' => 'Payment ' . $params['trx_id'],
                    'price_money' => ['amount' => $amount, 'currency' => strtoupper($params['currency'])],
                    'location_id' => $locationId,
                ],
                'redirect_url' => $params['redirect_url'],
            ]),
        ]);
        $response = curl_exec($ch);
        $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

File: modules/gateways/rocket/RocketGateway.php (L65-76)

        $amount = number_format((float)$params['amount'], 2, '.', '');
        $secureHash = md5($merchantId . $params['trx_id'] . $amount . $secretKey);

        $formHtml = '
        <form action="' . htmlspecialchars($url) . '" method="POST" id="rocket-form">
            <input type="hidden" name="merchant_id" value="' . htmlspecialchars($merchantId) . '">
            <input type="hidden" name="order_id" value="' . htmlspecialchars($params['trx_id']) . '">
            <input type="hidden" name="amount" value="' . htmlspecialchars($amount) . '">
            <input type="hidden" name="hash" value="' . htmlspecialchars($secureHash) . '">
            <input type="hidden" name="redirect_url" value="' . htmlspecialchars($params['redirect_url']) . '">
        </form>
        <script>document.getElementById("rocket-form").submit();</script>';

File: src/Controller/Checkout/PaymentIntentCheckoutController.php (L655-660)

        } catch (\Throwable $e) {
            fwrite(STDERR, "\n[EX] Atomic pay transaction setup failed: " . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n");
            $logger = $this->c->get(\OwnPay\Service\System\Logger::class);
            if ($logger instanceof \OwnPay\Service\System\Logger) {
                $logger->error('Atomic pay transaction setup failed: ' . $e->getMessage());
            }

File: src/Controller/Checkout/PaymentIntentCheckoutController.php (L1267-1300)

        try {
            $db->transaction(function () use ($db, $token, $mid, $intentId, $gatewaySlug, $intentAmount, $intentCurrency, $txnData, &$txn, &$errorResponse) {
                // 1. SELECT FOR UPDATE on the payment intent by token to block concurrent checkout pay requests.
                $lockedIntent = $db->fetchOne(
                    "SELECT * FROM op_payment_intents WHERE token = :t FOR UPDATE",
                    ['t' => $token]
                );

                if (!$lockedIntent) {
                    $errorResponse = Response::json(['success' => false, 'error' => 'Transaction expired or not found.'], 404);
                    return;
                }

                $intentStatusVal = $lockedIntent['status'] ?? '';
                $intentStatus = is_string($intentStatusVal) ? $intentStatusVal : '';
                if ($intentStatus !== 'pending') {
                    $errorResponse = Response::json(['success' => false, 'error' => 'Payment already submitted.'], 409);
                    return;
                }

                // Check expiry
                $expiresAtVal = $lockedIntent['expires_at'] ?? '';
                $expiresAt = is_scalar($expiresAtVal) ? (string) $expiresAtVal : '';
                if (DateHelper::isPast($expiresAt)) {
                    $db->execute("UPDATE op_payment_intents SET status = 'expired' WHERE id = :id", ['id' => $lockedIntent['id']]);
                    $errorResponse = Response::json(['success' => false, 'error' => 'Transaction expired.'], 410);
                    return;
                }

                // Check for existing pending/processing transaction to reuse (with FOR UPDATE lock)
                $existingTxn = $db->fetchOne(
                    "SELECT * FROM op_transactions WHERE payment_intent_id = :pi AND merchant_id = :mid ORDER BY id DESC LIMIT 1 FOR UPDATE",
                    ['pi' => $intentId, 'mid' => $mid]
                );

Reported by Kamla 😛


fattain-naime avatar Nov 01 '26 12:11 fattain-naime

Plan: Issue #656 — Several Architectural Issues

Clarity Check (gaps flagged)

  • The issue lists 17 confirmed items plus 2 "likely but unverified" (lock-ordering deadlock, middleware/RBAC/plugin/migration review). No priority/ordering, no test expectations, and no migration tooling is specified.
  • Scope is epic-sized; attempting all in one PR risks regressions. Recommend splitting into 4-5 focused PRs by phase (below). Items 10-14 (gateway stubs) touch 123 modules and should be a separate, dedicated cleanup PR.
  • "Likely but unverified" deadlock mapping needs a lock-order audit before any change; leave as a follow-up investigation task, not a code change.
  • No reproduction steps for most items; each is a design smell rather than a reproducible bug. Treat as refactoring/hardening work with regression tests as the spec.

Scope & Target

Ledger core:

  • src/Service/Payment/LedgerService.php (getAccountType, postEntries, recordPaymentReceived, recordRefund)
  • src/Repository/LedgerRepository.php (findOrCreateAccount, getBalance, adjustBalance, createTransaction)
  • database/schema.sql (op_ledger_accounts, op_ledger_transactions, op_refunds)

Refunds:

  • src/Service/Payment/RefundService.php (saga + Database::getInstance())
  • src/Gateway/WebhookInboundProcessor.php (refund find-or-create)

Checkout controller:

  • src/Controller/Checkout/PaymentIntentCheckoutController.php (duplicated atomic-pay blocks ~601/~1261, fwrite(STDERR), Database::getInstance())

Gateways:

  • modules/gateways/* (123 modules; stubs using GatewayDefaults), src/Gateway/GatewayDefaults.php
  • modules/gateways/2checkout/TwoCheckoutGateway.php (refund)
  • modules/gateways/square/SquareGateway.php (raw curl_init, uniqid idempotency key)
  • modules/gateways/rocket/RocketGateway.php (MD5 signing)

Tenant isolation:

  • src/Repository/TenantScope.php, src/Repository/BaseRepository.php

Step-by-Step Plan (phased, minimal)

Phase 1 — Ledger correctness (highest financial risk)

  1. Dedup key: change postEntries existence check from (merchant_id, reference_type, reference_id, description) to (merchant_id, reference_type, reference_id). Drop description from the SELECT and the bind.
  2. Add migration + schema unique key uk_merchant_ref on op_ledger_transactions(merchant_id, reference_type, reference_id). Make the existence check + insert idempotent: on duplicate-key (SQLSTATE 23000 / 1062) treat as already posted and return.
  3. findOrCreateAccount: keep existing uk_merchant_name_currency. Wrap insert in try/catch for duplicate-key; on 1062 re-SELECT and return the existing row. Ensures concurrent first-time posts don't throw.
  4. adjustBalance: throw RuntimeException when account row not found instead of silent return. Keep the tenant-scoped UPDATE. Add affected-rows check; throw if 0 rows updated in a scoped context.
  5. getAccountType: throw InvalidArgumentException for unrecognized codes instead of defaulting to asset. Callers must use known codes; new types registered explicitly.
  6. Move account resolution (findOrCreateAccount) inside the db->transaction(...) in postEntries so account creation is atomic with the journal post. Resolve types before opening transaction? Keep type resolution (pure) outside; only DB writes inside.
  7. Tenant isolation enforcement: mutating methods (adjustBalance, findOrCreateAccount insert) require tenantId !== null (throw via requireTenant()). Keep read paths allowing null for the superadmin "All Brands" view, but document that forAllTenants() is the only legitimate unscoped entry point.

Phase 2 — Refund saga & webhook idempotency

  1. WebhookInboundProcessor refund path: lock the parent transaction row FOR UPDATE before find-or-create; add unique key on op_refunds(transaction_id, merchant_id, amount) (or an idempotency-key column from the webhook event id). Handle duplicate-key as "already refunded" and skip double-counting.
  2. RefundService::create: keep the two-phase shape (gateway is external) but (a) persist a pending row with a unique idempotency key, (b) on gateway failure mark failed and release balance (already done), (c) add a reconciliation path for stranded pending rows older than N hours that re-attempts the gateway instead of auto-failing (fix RefundReconciliationJob to consult the gateway before releasing funds).
  3. Replace Database::getInstance() in RefundService and PaymentIntentCheckoutController with constructor-injected Database (PSR-11). Update container wiring in config/ and tests.

Phase 3 — Checkout controller cleanup

  1. Extract the two near-identical SELECT-FOR-UPDATE transaction-setup blocks (~601 and ~1261) in PaymentIntentCheckoutController into a single private method; both call sites use it.
  2. Replace fwrite(STDERR, ...) fallback with $this->logger->error(...) when a logger is available, else error_log(...). Never write to STDERR directly.

Phase 4 — Gateway hardening

  1. GatewayDefaults::initiate: return an error result (or throw) instead of a warning div; controllers must treat success=false/exception as a hard failure and surface a configuration error, not broken UI.
  2. Audit the 123 modules: remove or quarantine auto-generated stubs that only use GatewayDefaults without real initiate/verify. Expose a clear "not implemented" status in admin gateway list.
  3. TwoCheckoutGateway::refund: keep production gate (already present); remove sandbox simulation or gate it behind APP_ENV=testing only.
  4. SquareGateway: replace raw curl_init with the sandboxed HTTP_OUTBOUND capability layer; use a UUID idempotency key (not uniqid); make API version configurable.
  5. RocketGateway: MD5 is provider-mandated; document the constraint and isolate the hash computation in a single method so a future provider upgrade is one-line. Do not change the primitive without provider confirmation.

Phase 5 — Migrations & verification

  1. Add migrations: unique key on op_ledger_transactions(merchant_id, reference_type, reference_id); unique key on op_refunds(transaction_id, merchant_id, amount) (or idempotency column).
  2. Run vendor/bin/parallel-lint, vendor/bin/phpstan, vendor/bin/phpunit, vendor/bin/twig-cs-fixer, npm run lint with zero regressions.

Risk & Edge Cases

  • Changing the dedup key from description to (merchant, ref_type, ref_id) means two distinct events sharing a reference can no longer both post. That is the desired idempotency, but verify no caller relies on posting twice for the same reference (e.g., retries after partial failure). If a retry must re-post, the first must roll back entirely.
  • findOrCreateAccount upsert: if concurrent inserts specify different type for the same code, first wins. Acceptable; add a check to reject type mismatch on existing account.
  • adjustBalance throwing on missing account is a behavior change: callers that previously relied on silent no-op will now fail. Audit all call sites (only postEntries in-tree) before merging.
  • getAccountType throwing on unknown codes requires every account code in use to be registered; grep for getAccountType callers and account codes first.
  • Moving account creation inside the transaction lengthens lock hold time; acceptable given low volume, but monitor deadlock metrics (ties to the unverified deadlock item).
  • Tenant scope enforcement may break superadmin global mutations that currently pass no merchantId; audit callers of adjustBalance/findOrCreateAccount with null tenant.
  • Gateway stub removal may break admin UI that assumes every module is runnable; add a capability flag and filter the UI accordingly.
  • MD5 change is provider-contract risk; keep as-is unless provider confirms SHA-256.

Verification Checklist

  • Unit: LedgerServiceTest — dedup skips second identical reference; distinct references both post; getAccountType('UNKNOWN') throws; balanced check still rejects unbalanced.
  • Unit: LedgerRepositoryTest (DB-mocked) — findOrCreateAccount returns existing on duplicate-key; adjustBalance throws on missing account; tenant scope required on mutate.
  • Integration (MySQL): concurrent postEntries for same reference yields exactly one transaction row; concurrent findOrCreateAccount yields one account row.
  • Unit: WebhookInboundProcessorTest — duplicate webhook delivery does not double-count refund.
  • Unit: RefundServiceTest — gateway failure marks refund failed and releases balance; stranded pending reconciliation re-attempts gateway.
  • Unit: PaymentIntentCheckoutControllerTest — both pay paths use shared block; no STDERR writes.
  • Static: vendor/bin/parallel-lint, vendor/bin/phpstan analyse, vendor/bin/twig-cs-fixer lint templates, npm run lint — zero errors.
  • Tests: vendor/bin/phpunit — zero regressions (pre-existing failures in tests/Integration/ due to no MySQL are environmental, not regressions).

Pullfrog  | Implement plan ➔ | View workflow run | via Pullfrog | Using beam-free (free) | 𝕏

pullfrog[bot] avatar Nov 01 '26 12:11 pullfrog[bot]