connection; } public static function isId(string $value): bool { return preg_match('/\A[0-9a-f]{32}\z/', $value) === 1; } /** * An order whose current transaction is this plugin's method, or null. * * @return array{id: string, number: string, deep_link_code: string, state: string, currency: string, decimals: int, sales_channel_id: string, language_id: string, customer_id: ?string, transaction: array{id: string, state: string, state_id: string, amount: string}}|null */ public function find(string $orderId): ?array { if (!self::isId($orderId)) { return null; } return $this->load('o.id = ?', [hex2bin($orderId)], [ParameterType::BINARY]); } /** * The id of the order with this order number (or this id), or null. */ public function idOf(string $numberOrId): ?string { if (self::isId($numberOrId)) { return $numberOrId; } $rows = $this->connection->fetchAllAssociative( 'SELECT id FROM `order` WHERE order_number = ? AND version_id = ? ORDER BY created_at DESC LIMIT 1', [$numberOrId, hex2bin(self::LIVE_VERSION)], [ParameterType::STRING, ParameterType::BINARY], ); return isset($rows[0]['id']) ? bin2hex((string) $rows[0]['id']) : null; } /** * The order an order transaction belongs to, or null. */ public function orderIdOfTransaction(string $transactionId): ?string { if (!self::isId($transactionId)) { return null; } $rows = $this->connection->fetchAllAssociative( 'SELECT order_id FROM order_transaction WHERE id = ? AND version_id = ?', [hex2bin($transactionId), hex2bin(self::LIVE_VERSION)], [ParameterType::BINARY, ParameterType::BINARY], ); return isset($rows[0]['order_id']) ? bin2hex((string) $rows[0]['order_id']) : null; } /** * @return array{id: string, number: string, deep_link_code: string, state: string, currency: string, decimals: int, sales_channel_id: string, language_id: string, customer_id: ?string, transaction: array{id: string, state: string, state_id: string, amount: string}}|null */ public function findByDeepLinkCode(string $code): ?array { if (preg_match('/\A[A-Za-z0-9_-]{16,64}\z/', $code) !== 1) { return null; } $order = $this->load('o.deep_link_code = ?', [$code], [ParameterType::STRING]); // The lookup is by value; compare in constant time all the same. return $order !== null && hash_equals($order['deep_link_code'], $code) ? $order : null; } /** * Whether a new invoice may be made for the order: the order is open, and its current * transaction (this method's) waits for a payment. * * @param array{state: string, transaction: array{state: string}} $order */ public static function mintable(array $order): bool { return in_array($order['state'], self::OPEN_ORDER_STATES, true) && in_array($order['transaction']['state'], self::MINTABLE, true); } /** * Whether a settled payment may move the order's transaction to paid. * * @param array{state: string, transaction: array{state: string}} $order */ public static function settleable(array $order): bool { return in_array($order['state'], self::OPEN_ORDER_STATES, true) && in_array($order['transaction']['state'], self::SETTLEABLE, true); } /** * @param array{transaction: array{state: string}} $order */ public static function paid(array $order): bool { return $order['transaction']['state'] === 'paid'; } /** * Whether Shopware's state machine has a `paid` transition out of the state. */ public function paidTransitionFrom(string $stateId): bool { $rows = $this->connection->fetchAllAssociative( 'SELECT t.id FROM state_machine_transition t' . ' INNER JOIN state_machine m ON m.id = t.state_machine_id' . ' WHERE m.technical_name = \'order_transaction.state\' AND t.action_name = \'paid\' AND t.from_state_id = ?', [hex2bin($stateId)], [ParameterType::BINARY], ); return $rows !== []; } /** * Inside the settlement transaction: holds the order's transactions until * it commits, so two processes never move the same one. */ public function lock(string $orderId): void { if (!self::isId($orderId) || !$this->isMySql()) { return; } $this->connection->fetchAllAssociative( 'SELECT id FROM order_transaction WHERE order_id = ? AND version_id = ? FOR UPDATE', [hex2bin($orderId), hex2bin(self::LIVE_VERSION)], [ParameterType::BINARY, ParameterType::BINARY], ); } /** * The hash of the order's first settled attempt, or null. */ public function settledHash(string $orderId): ?string { $rows = $this->connection->fetchAllAssociative( 'SELECT payment_hash FROM ' . PaymentsSchema::DEFAULT_TABLE . ' WHERE reference = ? AND status = ? ORDER BY id LIMIT 1', [$orderId, 'settled'], ); return isset($rows[0]['payment_hash']) ? (string) $rows[0]['payment_hash'] : null; } /** * Orders whose payment settled while their current transaction, this * method's, still waits: the repair pass completes them. * * @return list order ids */ public function awaitingRepair(): array { $rows = $this->connection->fetchAllAssociative( 'SELECT DISTINCT p.reference FROM ' . PaymentsSchema::DEFAULT_TABLE . ' p' . ' INNER JOIN `order` o ON o.id = UNHEX(p.reference) AND o.version_id = ?' . ' INNER JOIN state_machine_state os ON os.id = o.state_id' . ' INNER JOIN order_transaction ot ON ot.order_id = o.id AND ot.order_version_id = o.version_id AND ot.version_id = o.version_id' . ' INNER JOIN state_machine_state ts ON ts.id = ot.state_id' . ' INNER JOIN payment_method pm ON pm.id = ot.payment_method_id' . ' WHERE p.status = ? AND pm.handler_identifier = ?' . ' AND os.technical_name IN (?, ?)' . ' AND ts.technical_name IN (?, ?, ?, ?, ?)' . ' AND NOT EXISTS (SELECT 1 FROM order_transaction newer WHERE newer.order_id = ot.order_id' . ' AND newer.version_id = ot.version_id AND newer.created_at > ot.created_at)' . ' ORDER BY p.reference LIMIT ' . self::REPAIR_BATCH, [hex2bin(self::LIVE_VERSION), 'settled', LightningPaymentHandler::class, ...self::OPEN_ORDER_STATES, ...self::SETTLEABLE], [ParameterType::BINARY], ); return array_values(array_filter(array_map(static fn (array $row): string => (string) $row['reference'], $rows), self::isId(...))); } /** * Orders paid in the wallet while Shopware no longer took the payment * (cancelled, or moved to another method): the doctor lists them. * * @return list */ public function paidWhileClosed(): array { $rows = $this->connection->fetchAllAssociative( 'SELECT DISTINCT p.reference FROM ' . PaymentsSchema::DEFAULT_TABLE . ' p WHERE p.status = ? ORDER BY p.reference', ['settled'], ); $closed = []; foreach ($rows as $row) { $reference = (string) $row['reference']; if (!self::isId($reference)) { continue; } $order = $this->find($reference); if ($order === null) { $any = $this->load('o.id = ?', [hex2bin($reference)], [ParameterType::BINARY], anyMethod: true); if ($any !== null && !self::paid($any)) { $closed[] = ['number' => $any['number'], 'state' => $any['state'], 'transaction' => $any['transaction']['state'] . ' (another method)']; } continue; } if (!self::paid($order) && !self::settleable($order)) { $closed[] = ['number' => $order['number'], 'state' => $order['state'], 'transaction' => $order['transaction']['state']]; } if (count($closed) >= self::REPAIR_BATCH) { break; } } return $closed; } /** * @return list ISO codes of the currencies the sales channels sell in, else every currency */ public function currencies(): array { $codes = $this->connection->fetchFirstColumn( 'SELECT DISTINCT c.iso_code FROM currency c INNER JOIN sales_channel_currency s ON s.currency_id = c.id ORDER BY c.iso_code' ); if ($codes === []) { $codes = $this->connection->fetchFirstColumn('SELECT iso_code FROM currency ORDER BY iso_code'); } $codes = array_values(array_unique(array_filter(array_map(static fn (mixed $code): string => strtoupper(trim((string) $code)), $codes)))); return $codes === [] ? ['EUR'] : $codes; } /** * The storefront address the order was placed on: its sales channel's * domain in the order's language, else the channel's first domain. */ public function storefrontUrl(string $salesChannelId, string $languageId): ?string { $rows = $this->connection->fetchAllAssociative( 'SELECT url, language_id FROM sales_channel_domain WHERE sales_channel_id = ? ORDER BY created_at', [hex2bin($salesChannelId)], [ParameterType::BINARY], ); $chosen = null; foreach ($rows as $row) { $chosen ??= (string) $row['url']; if (bin2hex((string) $row['language_id']) === $languageId) { return rtrim((string) $row['url'], '/'); } } return $chosen === null ? null : rtrim($chosen, '/'); } /** * @param list $params * @param list $types * * @return array{id: string, number: string, deep_link_code: string, state: string, currency: string, decimals: int, sales_channel_id: string, language_id: string, customer_id: ?string, transaction: array{id: string, state: string, state_id: string, amount: string}}|null */ private function load(string $where, array $params, array $types, bool $anyMethod = false): ?array { $rows = $this->connection->fetchAllAssociative( 'SELECT o.id, o.order_number, o.deep_link_code, o.total_rounding, o.sales_channel_id, o.language_id,' . ' os.technical_name AS order_state, c.iso_code, oc.customer_id' . ' FROM `order` o' . ' INNER JOIN state_machine_state os ON os.id = o.state_id' . ' INNER JOIN currency c ON c.id = o.currency_id' . ' LEFT JOIN order_customer oc ON oc.order_id = o.id AND oc.order_version_id = o.version_id AND oc.version_id = o.version_id' . ' WHERE ' . $where . ' AND o.version_id = ?', [...$params, hex2bin(self::LIVE_VERSION)], [...$types, ParameterType::BINARY], ); $row = $rows[0] ?? null; if ($row === null) { return null; } $transactions = $this->connection->fetchAllAssociative( 'SELECT ot.id, ot.state_id, ot.amount, ts.technical_name AS state, pm.handler_identifier' . ' FROM order_transaction ot' . ' INNER JOIN state_machine_state ts ON ts.id = ot.state_id' . ' INNER JOIN payment_method pm ON pm.id = ot.payment_method_id' . ' WHERE ot.order_id = ? AND ot.order_version_id = ? AND ot.version_id = ?' . ' ORDER BY ot.created_at DESC, ot.id DESC LIMIT 1', [$row['id'], hex2bin(self::LIVE_VERSION), hex2bin(self::LIVE_VERSION)], [ParameterType::BINARY, ParameterType::BINARY, ParameterType::BINARY], ); $transaction = $transactions[0] ?? null; if ($transaction === null || (!$anyMethod && $transaction['handler_identifier'] !== LightningPaymentHandler::class)) { return null; } $rounding = json_decode((string) ($row['total_rounding'] ?? ''), true); $decimals = is_array($rounding) && is_int($rounding['decimals'] ?? null) ? $rounding['decimals'] : 2; return [ 'id' => bin2hex((string) $row['id']), 'number' => (string) $row['order_number'], 'deep_link_code' => (string) $row['deep_link_code'], 'state' => (string) $row['order_state'], 'currency' => strtoupper((string) $row['iso_code']), 'decimals' => $decimals, 'sales_channel_id' => bin2hex((string) $row['sales_channel_id']), 'language_id' => bin2hex((string) $row['language_id']), 'customer_id' => $row['customer_id'] === null ? null : bin2hex((string) $row['customer_id']), 'transaction' => [ 'id' => bin2hex((string) $transaction['id']), 'state' => (string) $transaction['state'], 'state_id' => bin2hex((string) $transaction['state_id']), 'amount' => (string) $transaction['amount'], ], ]; } private function isMySql(): bool { return $this->connection->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\AbstractMySQLPlatform; } }