ver. 0.269: ShopPaymentMethod refactor + Apilo keepalive

This commit is contained in:
2026-02-14 15:22:02 +01:00
parent 847fdbbf3f
commit 9c23e7f16b
31 changed files with 1832 additions and 269 deletions

View File

@@ -110,20 +110,83 @@ class IntegrationsRepository
return true;
}
public function apiloGetAccessToken(): ?string
public function apiloGetAccessToken( int $refreshLeadSeconds = 300 ): ?string
{
$settings = $this->getSettings( 'apilo' );
if ( empty( $settings['access-token-expire-at'] ) || empty( $settings['access-token'] ) )
$hasRefreshCredentials = !empty( $settings['refresh-token'] )
&& !empty( $settings['client-id'] )
&& !empty( $settings['client-secret'] );
$accessToken = trim( (string)($settings['access-token'] ?? '') );
$accessTokenExpireAt = trim( (string)($settings['access-token-expire-at'] ?? '') );
if ( $accessToken !== '' && $accessTokenExpireAt !== '' ) {
if ( !$this->shouldRefreshAccessToken( $accessTokenExpireAt, $refreshLeadSeconds ) ) {
return $accessToken;
}
}
if ( !$hasRefreshCredentials ) {
return null;
}
$expireAt = new \DateTime( $settings['access-token-expire-at'] );
$now = new \DateTime( date( 'Y-m-d H:i:s' ) );
if (
!empty( $settings['refresh-token-expire-at'] ) &&
!$this->isFutureDate( (string)$settings['refresh-token-expire-at'] )
) {
return null;
}
if ( $expireAt >= $now )
return $settings['access-token'];
return $this->refreshApiloAccessToken( $settings );
}
// Token expired - refresh
/**
* Keepalive tokenu Apilo do uzycia w CRON.
* Odswieza token, gdy wygasa lub jest bliski wygasniecia.
*
* @return array{success:bool,skipped:bool,message:string}
*/
public function apiloKeepalive( int $refreshLeadSeconds = 300 ): array
{
$settings = $this->getSettings( 'apilo' );
if ( (int)($settings['enabled'] ?? 0) !== 1 ) {
return [
'success' => false,
'skipped' => true,
'message' => 'Apilo disabled.',
];
}
if ( empty( $settings['client-id'] ) || empty( $settings['client-secret'] ) ) {
return [
'success' => false,
'skipped' => true,
'message' => 'Missing Apilo credentials.',
];
}
$token = $this->apiloGetAccessToken( $refreshLeadSeconds );
if ( !$token ) {
return [
'success' => false,
'skipped' => false,
'message' => 'Unable to refresh Apilo token.',
];
}
$this->saveSetting( 'apilo', 'token-keepalive-at', date( 'Y-m-d H:i:s' ) );
return [
'success' => true,
'skipped' => false,
'message' => 'Apilo token keepalive OK.',
];
}
private function refreshApiloAccessToken( array $settings ): ?string
{
$postData = [
'grantType' => 'refresh_token',
'token' => $settings['refresh-token'],
@@ -147,17 +210,102 @@ class IntegrationsRepository
curl_close( $ch );
$response = json_decode( $response, true );
if ( empty( $response['accessToken'] ) )
if ( empty( $response['accessToken'] ) ) {
return null;
}
$this->saveSetting( 'apilo', 'access-token', $response['accessToken'] );
$this->saveSetting( 'apilo', 'refresh-token', $response['refreshToken'] );
$this->saveSetting( 'apilo', 'access-token-expire-at', $response['accessTokenExpireAt'] );
$this->saveSetting( 'apilo', 'refresh-token-expire-at', $response['refreshTokenExpireAt'] );
$this->saveSetting( 'apilo', 'refresh-token', $response['refreshToken'] ?? ( $settings['refresh-token'] ?? '' ) );
$this->saveSetting( 'apilo', 'access-token-expire-at', $response['accessTokenExpireAt'] ?? null );
$this->saveSetting( 'apilo', 'refresh-token-expire-at', $response['refreshTokenExpireAt'] ?? null );
return $response['accessToken'];
}
private function shouldRefreshAccessToken( string $expiresAtRaw, int $leadSeconds = 300 ): bool
{
try {
$expiresAt = new \DateTime( $expiresAtRaw );
} catch ( \Exception $e ) {
return true;
}
$threshold = new \DateTime( date( 'Y-m-d H:i:s', time() + max( 0, $leadSeconds ) ) );
return $expiresAt <= $threshold;
}
private function isFutureDate( string $dateRaw ): bool
{
try {
$date = new \DateTime( $dateRaw );
} catch ( \Exception $e ) {
return false;
}
return $date > new \DateTime( date( 'Y-m-d H:i:s' ) );
}
/**
* Sprawdza aktualny stan integracji Apilo i zwraca komunikat dla UI.
*
* @return array{is_valid:bool,severity:string,message:string}
*/
public function apiloIntegrationStatus(): array
{
$settings = $this->getSettings( 'apilo' );
$missing = [];
foreach ( [ 'client-id', 'client-secret' ] as $field ) {
if ( trim( (string)($settings[$field] ?? '') ) === '' )
$missing[] = $field;
}
if ( !empty( $missing ) ) {
return [
'is_valid' => false,
'severity' => 'danger',
'message' => 'Brakuje konfiguracji Apilo: ' . implode( ', ', $missing ) . '.',
];
}
$accessToken = trim( (string)($settings['access-token'] ?? '') );
$authorizationCode = trim( (string)($settings['authorization-code'] ?? '') );
if ( $accessToken === '' ) {
if ( $authorizationCode === '' ) {
return [
'is_valid' => false,
'severity' => 'warning',
'message' => 'Brak authorization-code i access-token. Wpisz kod autoryzacji i uruchom autoryzacje.',
];
}
return [
'is_valid' => false,
'severity' => 'warning',
'message' => 'Brak access-token. Uruchom autoryzacje Apilo.',
];
}
$token = $this->apiloGetAccessToken();
if ( !$token ) {
return [
'is_valid' => false,
'severity' => 'danger',
'message' => 'Token Apilo jest niewazny lub wygasl i nie udal sie refresh. Wykonaj ponowna autoryzacje.',
];
}
$expiresAt = trim( (string)($settings['access-token-expire-at'] ?? '') );
$suffix = $expiresAt !== '' ? ( ' Token wazny do: ' . $expiresAt . '.' ) : '';
return [
'is_valid' => true,
'severity' => 'success',
'message' => 'Integracja Apilo jest aktywna.' . $suffix,
];
}
// ── Apilo API fetch lists ───────────────────────────────────
private const APILO_ENDPOINTS = [
@@ -179,13 +327,45 @@ class IntegrationsRepository
* @param string $type platform|status|carrier|payment
*/
public function apiloFetchList( string $type ): bool
{
$result = $this->apiloFetchListResult( $type );
return !empty( $result['success'] );
}
/**
* Fetch list from Apilo API and return detailed status for UI.
*
* @param string $type platform|status|carrier|payment
* @return array{success:bool,count:int,message:string}
*/
public function apiloFetchListResult( string $type ): array
{
if ( !isset( self::APILO_ENDPOINTS[$type] ) )
throw new \InvalidArgumentException( "Unknown apilo list type: $type" );
$settings = $this->getSettings( 'apilo' );
$missingFields = [];
foreach ( [ 'client-id', 'client-secret' ] as $requiredField ) {
if ( trim( (string)($settings[$requiredField] ?? '') ) === '' )
$missingFields[] = $requiredField;
}
if ( !empty( $missingFields ) ) {
return [
'success' => false,
'count' => 0,
'message' => 'Brakuje konfiguracji Apilo: ' . implode( ', ', $missingFields ) . '. Uzupelnij pola i zapisz ustawienia.',
];
}
$accessToken = $this->apiloGetAccessToken();
if ( !$accessToken )
return false;
if ( !$accessToken ) {
return [
'success' => false,
'count' => 0,
'message' => 'Brak aktywnego tokenu Apilo. Wykonaj autoryzacje Apilo i sprobuj ponownie.',
];
}
$ch = curl_init( self::APILO_ENDPOINTS[$type] );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
@@ -196,19 +376,140 @@ class IntegrationsRepository
$response = curl_exec( $ch );
if ( curl_errno( $ch ) ) {
$error = curl_error( $ch );
curl_close( $ch );
return false;
return [
'success' => false,
'count' => 0,
'message' => 'Blad polaczenia z Apilo: ' . $error . '. Sprawdz polaczenie serwera i sprobuj ponownie.',
];
}
$httpCode = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
$data = json_decode( $response, true );
if ( !$data )
if ( !is_array( $data ) ) {
$responsePreview = substr( trim( (string)$response ), 0, 180 );
if ( $responsePreview === '' )
$responsePreview = '[pusta odpowiedz]';
return [
'success' => false,
'count' => 0,
'message' => 'Apilo zwrocilo niepoprawny format odpowiedzi (HTTP ' . $httpCode . '). Odpowiedz: ' . $responsePreview,
];
}
if ( $httpCode >= 400 ) {
return [
'success' => false,
'count' => 0,
'message' => 'Apilo zwrocilo blad HTTP ' . $httpCode . ': ' . $this->extractApiloErrorMessage( $data ),
];
}
$normalizedList = $this->normalizeApiloMapList( $data );
if ( $normalizedList === null ) {
return [
'success' => false,
'count' => 0,
'message' => 'Apilo zwrocilo dane w nieoczekiwanym formacie. Odswiez token i sproboj ponownie.',
];
}
$this->saveSetting( 'apilo', self::APILO_SETTINGS_KEYS[$type], $normalizedList );
return [
'success' => true,
'count' => count( $normalizedList ),
'message' => 'OK',
];
}
/**
* Normalizuje odpowiedz API mapowania do listy rekordow ['id' => ..., 'name' => ...].
* Zwraca null dla payloadu bledow lub nieoczekiwanego formatu.
*
* @return array<int, array{id:mixed,name:mixed}>|null
*/
private function normalizeApiloMapList( array $data ): ?array
{
if ( isset( $data['message'] ) && isset( $data['code'] ) )
return null;
if ( $this->isMapListShape( $data ) )
return $data;
if ( isset( $data['items'] ) && is_array( $data['items'] ) && $this->isMapListShape( $data['items'] ) )
return $data['items'];
if ( isset( $data['data'] ) && is_array( $data['data'] ) && $this->isMapListShape( $data['data'] ) )
return $data['data'];
// Dopuszczamy rowniez format asocjacyjny: [id => name, ...], ale tylko dla kluczy liczbowych.
if ( !empty( $data ) ) {
$normalized = [];
foreach ( $data as $key => $value ) {
if ( !( is_int( $key ) || ( is_string( $key ) && preg_match('/^-?\d+$/', $key) === 1 ) ) )
return null;
if ( !is_scalar( $value ) )
return null;
$normalized[] = [
'id' => $key,
'name' => (string) $value,
];
}
return !empty( $normalized ) ? $normalized : null;
}
return null;
}
private function isMapListShape( array $list ): bool
{
if ( empty( $list ) )
return false;
$this->saveSetting( 'apilo', self::APILO_SETTINGS_KEYS[$type], $data );
foreach ( $list as $row ) {
if ( !is_array( $row ) || !array_key_exists( 'id', $row ) || !array_key_exists( 'name', $row ) )
return false;
}
return true;
}
private function extractApiloErrorMessage( array $data ): string
{
foreach ( [ 'message', 'error', 'detail', 'title' ] as $key ) {
if ( isset( $data[$key] ) && is_scalar( $data[$key] ) ) {
$message = trim( (string)$data[$key] );
if ( $message !== '' )
return $message;
}
}
if ( isset( $data['errors'] ) ) {
if ( is_array( $data['errors'] ) ) {
$flat = [];
foreach ( $data['errors'] as $errorItem ) {
if ( is_scalar( $errorItem ) )
$flat[] = (string)$errorItem;
elseif ( is_array( $errorItem ) )
$flat[] = json_encode( $errorItem, JSON_UNESCAPED_UNICODE );
}
if ( !empty( $flat ) )
return implode( '; ', $flat );
} elseif ( is_scalar( $data['errors'] ) ) {
return (string)$data['errors'];
}
}
return 'Nieznany blad odpowiedzi API.';
}
// ── Apilo product operations ────────────────────────────────
public function getProductSku( int $productId ): ?string

View File

@@ -0,0 +1,309 @@
<?php
namespace Domain\PaymentMethod;
class PaymentMethodRepository
{
private const MAX_PER_PAGE = 100;
private $db;
public function __construct($db)
{
$this->db = $db;
}
/**
* @return array{items: array<int, array<string, mixed>>, total: int}
*/
public function listForAdmin(
array $filters,
string $sortColumn = 'name',
string $sortDir = 'ASC',
int $page = 1,
int $perPage = 15
): array {
$allowedSortColumns = [
'id' => 'spm.id',
'name' => 'spm.name',
'status' => 'spm.status',
'apilo_payment_type_id' => 'spm.apilo_payment_type_id',
];
$sortSql = $allowedSortColumns[$sortColumn] ?? 'spm.name';
$sortDir = strtoupper(trim($sortDir)) === 'DESC' ? 'DESC' : 'ASC';
$page = max(1, $page);
$perPage = min(self::MAX_PER_PAGE, max(1, $perPage));
$offset = ($page - 1) * $perPage;
$where = ['1 = 1'];
$params = [];
$name = trim((string)($filters['name'] ?? ''));
if ($name !== '') {
if (strlen($name) > 255) {
$name = substr($name, 0, 255);
}
$where[] = 'spm.name LIKE :name';
$params[':name'] = '%' . $name . '%';
}
$status = trim((string)($filters['status'] ?? ''));
if ($status === '0' || $status === '1') {
$where[] = 'spm.status = :status';
$params[':status'] = (int)$status;
}
$whereSql = implode(' AND ', $where);
$sqlCount = "
SELECT COUNT(0)
FROM pp_shop_payment_methods AS spm
WHERE {$whereSql}
";
$stmtCount = $this->db->query($sqlCount, $params);
$countRows = $stmtCount ? $stmtCount->fetchAll() : [];
$total = isset($countRows[0][0]) ? (int)$countRows[0][0] : 0;
$sql = "
SELECT
spm.id,
spm.name,
spm.description,
spm.status,
spm.apilo_payment_type_id
FROM pp_shop_payment_methods AS spm
WHERE {$whereSql}
ORDER BY {$sortSql} {$sortDir}, spm.id ASC
LIMIT {$perPage} OFFSET {$offset}
";
$stmt = $this->db->query($sql, $params);
$items = $stmt ? $stmt->fetchAll() : [];
if (!is_array($items)) {
$items = [];
}
foreach ($items as &$item) {
$item = $this->normalizePaymentMethod($item);
}
unset($item);
return [
'items' => $items,
'total' => $total,
];
}
public function find(int $paymentMethodId): ?array
{
if ($paymentMethodId <= 0) {
return null;
}
$paymentMethod = $this->db->get('pp_shop_payment_methods', '*', ['id' => $paymentMethodId]);
if (!is_array($paymentMethod)) {
return null;
}
return $this->normalizePaymentMethod($paymentMethod);
}
public function save(int $paymentMethodId, array $data): ?int
{
if ($paymentMethodId <= 0) {
return null;
}
$row = [
'description' => trim((string)($data['description'] ?? '')),
'status' => $this->toSwitchValue($data['status'] ?? 0),
'apilo_payment_type_id' => $this->normalizeApiloPaymentTypeId($data['apilo_payment_type_id'] ?? null),
];
$this->db->update('pp_shop_payment_methods', $row, ['id' => $paymentMethodId]);
return $paymentMethodId;
}
/**
* @return array<int, array<string, mixed>>
*/
public function allActive(): array
{
$rows = $this->db->select('pp_shop_payment_methods', '*', [
'status' => 1,
'ORDER' => ['id' => 'ASC'],
]);
if (!is_array($rows)) {
return [];
}
$result = [];
foreach ($rows as $row) {
if (is_array($row)) {
$result[] = $this->normalizePaymentMethod($row);
}
}
return $result;
}
/**
* @return array<int, array<string, mixed>>
*/
public function allForAdmin(): array
{
$rows = $this->db->select('pp_shop_payment_methods', '*', [
'ORDER' => ['name' => 'ASC'],
]);
if (!is_array($rows)) {
return [];
}
$result = [];
foreach ($rows as $row) {
if (is_array($row)) {
$result[] = $this->normalizePaymentMethod($row);
}
}
return $result;
}
public function findActiveById(int $paymentMethodId): ?array
{
if ($paymentMethodId <= 0) {
return null;
}
$paymentMethod = $this->db->get('pp_shop_payment_methods', '*', [
'AND' => [
'id' => $paymentMethodId,
'status' => 1,
],
]);
if (!is_array($paymentMethod)) {
return null;
}
return $this->normalizePaymentMethod($paymentMethod);
}
public function isActive(int $paymentMethodId): int
{
if ($paymentMethodId <= 0) {
return 0;
}
$status = $this->db->get('pp_shop_payment_methods', 'status', ['id' => $paymentMethodId]);
return $this->toSwitchValue($status);
}
/**
* @return int|string|null
*/
public function getApiloPaymentTypeId(int $paymentMethodId)
{
if ($paymentMethodId <= 0) {
return null;
}
$value = $this->db->get('pp_shop_payment_methods', 'apilo_payment_type_id', ['id' => $paymentMethodId]);
return $this->normalizeApiloPaymentTypeId($value);
}
/**
* @return array<int, array<string, mixed>>
*/
public function forTransport(int $transportMethodId): array
{
if ($transportMethodId <= 0) {
return [];
}
$sql = "
SELECT
spm.id,
spm.name,
spm.description,
spm.status,
spm.apilo_payment_type_id
FROM pp_shop_payment_methods AS spm
INNER JOIN pp_shop_transport_payment_methods AS stpm
ON stpm.id_payment_method = spm.id
WHERE spm.status = 1
AND stpm.id_transport = :transport_id
";
$stmt = $this->db->query($sql, [':transport_id' => $transportMethodId]);
$rows = $stmt ? $stmt->fetchAll() : [];
if (!is_array($rows)) {
return [];
}
$result = [];
foreach ($rows as $row) {
if (is_array($row)) {
$result[] = $this->normalizePaymentMethod($row);
}
}
return $result;
}
private function normalizePaymentMethod(array $row): array
{
$row['id'] = (int)($row['id'] ?? 0);
$row['name'] = trim((string)($row['name'] ?? ''));
$row['description'] = (string)($row['description'] ?? '');
$row['status'] = $this->toSwitchValue($row['status'] ?? 0);
$row['apilo_payment_type_id'] = $this->normalizeApiloPaymentTypeId($row['apilo_payment_type_id'] ?? null);
return $row;
}
/**
* @return int|string|null
*/
private function normalizeApiloPaymentTypeId($value)
{
if ($value === null || $value === false) {
return null;
}
$text = trim((string)$value);
if ($text === '') {
return null;
}
if (preg_match('/^-?\d+$/', $text) === 1) {
return (int)$text;
}
return $text;
}
private function toSwitchValue($value): int
{
if (is_bool($value)) {
return $value ? 1 : 0;
}
if (is_numeric($value)) {
return ((int)$value) === 1 ? 1 : 0;
}
if (is_string($value)) {
$normalized = strtolower(trim($value));
return in_array($normalized, ['1', 'on', 'true', 'yes'], true) ? 1 : 0;
}
return 0;
}
}