- NEW: IntegrationsRepository::shopproExportProduct() — eksport produktu do zdalnej instancji shopPRO (pola główne, tłumaczenia, custom fields, zdjęcia) - NEW: sendImageToShopproApi() — wysyłka zdjęć przez API shopPRO (base64 POST) - REFACTOR: shopproImportProduct() — wydzielono shopproDb() i missingShopproSetting(); dodano security_information, producer_id, custom fields, alt zdjęcia - NEW: AttributeRepository::ensureAttributeForApi() i ensureAttributeValueForApi() — idempotent find-or-create dla słowników - NEW: API POST dictionaries/ensure_attribute — utwórz lub znajdź atrybut - NEW: API POST dictionaries/ensure_attribute_value — utwórz lub znajdź wartość - NEW: API POST products/upload_image — przyjmuje base64, zapisuje plik i DB - NEW: IntegrationsController::shoppro_product_export() — akcja admina - NEW: przycisk "Eksportuj do shopPRO" w liście produktów - NEW: pole API key w ustawieniach integracji shopPRO Tests: 765 tests, 2153 assertions — all green Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
994 lines
38 KiB
PHP
994 lines
38 KiB
PHP
<?php
|
|
namespace Domain\Integrations;
|
|
|
|
class IntegrationsRepository
|
|
{
|
|
private $db;
|
|
|
|
private const SETTINGS_TABLES = [
|
|
'apilo' => 'pp_shop_apilo_settings',
|
|
'shoppro' => 'pp_shop_shoppro_settings',
|
|
];
|
|
|
|
public function __construct( $db )
|
|
{
|
|
$this->db = $db;
|
|
}
|
|
|
|
// ── Settings ────────────────────────────────────────────────
|
|
|
|
private function settingsTable( string $provider ): string
|
|
{
|
|
if ( !isset( self::SETTINGS_TABLES[$provider] ) )
|
|
throw new \InvalidArgumentException( "Unknown provider: $provider" );
|
|
|
|
return self::SETTINGS_TABLES[$provider];
|
|
}
|
|
|
|
public function getSettings( string $provider ): array
|
|
{
|
|
$table = $this->settingsTable( $provider );
|
|
$stmt = $this->db->query( "SELECT * FROM $table" );
|
|
$results = $stmt ? $stmt->fetchAll( \PDO::FETCH_ASSOC ) : [];
|
|
$settings = [];
|
|
foreach ( $results as $row )
|
|
$settings[$row['name']] = $row['value'];
|
|
|
|
return $settings;
|
|
}
|
|
|
|
public function getSetting( string $provider, string $name ): ?string
|
|
{
|
|
$table = $this->settingsTable( $provider );
|
|
$value = $this->db->get( $table, 'value', [ 'name' => $name ] );
|
|
return $value !== false ? $value : null;
|
|
}
|
|
|
|
public function saveSetting( string $provider, string $name, $value ): bool
|
|
{
|
|
$table = $this->settingsTable( $provider );
|
|
if ( $this->db->count( $table, [ 'name' => $name ] ) ) {
|
|
$this->db->update( $table, [ 'value' => $value ], [ 'name' => $name ] );
|
|
} else {
|
|
$this->db->insert( $table, [ 'name' => $name, 'value' => $value ] );
|
|
}
|
|
\Shared\Helpers\Helpers::delete_dir('../temp/');
|
|
return true;
|
|
}
|
|
|
|
// ── Logs ────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Pobiera logi z tabeli pp_log z paginacją, sortowaniem i filtrowaniem.
|
|
*
|
|
* @return array{items:array, total:int}
|
|
*/
|
|
public function getLogs( array $filters, string $sortColumn, string $sortDir, int $page, int $perPage ): array
|
|
{
|
|
$where = [];
|
|
|
|
if ( !empty( $filters['log_action'] ) ) {
|
|
$where['action[~]'] = '%' . $filters['log_action'] . '%';
|
|
}
|
|
|
|
if ( !empty( $filters['message'] ) ) {
|
|
$where['message[~]'] = '%' . $filters['message'] . '%';
|
|
}
|
|
|
|
if ( !empty( $filters['order_id'] ) ) {
|
|
$where['order_id'] = (int) $filters['order_id'];
|
|
}
|
|
|
|
$total = $this->db->count( 'pp_log', $where );
|
|
|
|
$where['ORDER'] = [ $sortColumn => $sortDir ];
|
|
$where['LIMIT'] = [ ( $page - 1 ) * $perPage, $perPage ];
|
|
|
|
$items = $this->db->select( 'pp_log', '*', $where );
|
|
if ( !is_array( $items ) ) {
|
|
$items = [];
|
|
}
|
|
|
|
return [
|
|
'items' => $items,
|
|
'total' => (int) $total,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Usuwa wpis logu po ID.
|
|
*/
|
|
public function deleteLog( int $id ): bool
|
|
{
|
|
$this->db->delete( 'pp_log', [ 'id' => $id ] );
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Czyści wszystkie logi z tabeli pp_log.
|
|
*/
|
|
public function clearLogs(): bool
|
|
{
|
|
$this->db->delete( 'pp_log', [] );
|
|
return true;
|
|
}
|
|
|
|
// ── Product linking (Apilo) ─────────────────────────────────
|
|
|
|
public function linkProduct( int $productId, $externalId, $externalName ): bool
|
|
{
|
|
return (bool) $this->db->update( 'pp_shop_products', [
|
|
'apilo_product_id' => $externalId,
|
|
'apilo_product_name' => \Shared\Helpers\Helpers::remove_special_chars( $externalName ),
|
|
], [ 'id' => $productId ] );
|
|
}
|
|
|
|
public function unlinkProduct( int $productId ): bool
|
|
{
|
|
return (bool) $this->db->update( 'pp_shop_products', [
|
|
'apilo_product_id' => null,
|
|
'apilo_product_name' => null,
|
|
], [ 'id' => $productId ] );
|
|
}
|
|
|
|
// ── Apilo OAuth ─────────────────────────────────────────────
|
|
|
|
public function apiloAuthorize( string $clientId, string $clientSecret, string $authCode ): bool
|
|
{
|
|
$postData = [
|
|
'grantType' => 'authorization_code',
|
|
'token' => $authCode,
|
|
];
|
|
|
|
$ch = curl_init( "https://projectpro.apilo.com/rest/auth/token/" );
|
|
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
|
|
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
|
|
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $postData ) );
|
|
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
|
|
"Authorization: Basic " . base64_encode( $clientId . ":" . $clientSecret ),
|
|
"Accept: application/json"
|
|
] );
|
|
|
|
$response = curl_exec( $ch );
|
|
if ( curl_errno( $ch ) ) {
|
|
curl_close( $ch );
|
|
return false;
|
|
}
|
|
curl_close( $ch );
|
|
$response = json_decode( $response, true );
|
|
|
|
if ( empty( $response['accessToken'] ) )
|
|
return false;
|
|
|
|
$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'] );
|
|
|
|
return true;
|
|
}
|
|
|
|
public function apiloGetAccessToken( int $refreshLeadSeconds = 300 ): ?string
|
|
{
|
|
$settings = $this->getSettings( 'apilo' );
|
|
|
|
$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;
|
|
}
|
|
|
|
if (
|
|
!empty( $settings['refresh-token-expire-at'] ) &&
|
|
!$this->isFutureDate( (string)$settings['refresh-token-expire-at'] )
|
|
) {
|
|
return null;
|
|
}
|
|
|
|
return $this->refreshApiloAccessToken( $settings );
|
|
}
|
|
|
|
/**
|
|
* 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'],
|
|
];
|
|
|
|
$ch = curl_init( "https://projectpro.apilo.com/rest/auth/token/" );
|
|
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
|
|
"Authorization: Basic " . base64_encode( $settings['client-id'] . ":" . $settings['client-secret'] ),
|
|
"Accept: application/json"
|
|
] );
|
|
curl_setopt( $ch, CURLOPT_POST, true );
|
|
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $postData ) );
|
|
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
|
|
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
|
|
|
|
$response = curl_exec( $ch );
|
|
if ( curl_errno( $ch ) ) {
|
|
curl_close( $ch );
|
|
return null;
|
|
}
|
|
curl_close( $ch );
|
|
$response = json_decode( $response, true );
|
|
|
|
if ( empty( $response['accessToken'] ) ) {
|
|
return null;
|
|
}
|
|
|
|
$this->saveSetting( 'apilo', 'access-token', $response['accessToken'] );
|
|
$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 = [
|
|
'platform' => 'https://projectpro.apilo.com/rest/api/orders/platform/map/',
|
|
'status' => 'https://projectpro.apilo.com/rest/api/orders/status/map/',
|
|
'carrier' => 'https://projectpro.apilo.com/rest/api/orders/carrier-account/map/',
|
|
'payment' => 'https://projectpro.apilo.com/rest/api/orders/payment/map/',
|
|
];
|
|
|
|
private const APILO_SETTINGS_KEYS = [
|
|
'platform' => 'platform-list',
|
|
'status' => 'status-types-list',
|
|
'carrier' => 'carrier-account-list',
|
|
'payment' => 'payment-types-list',
|
|
];
|
|
|
|
/**
|
|
* Fetch list from Apilo API and save to settings.
|
|
* @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 [
|
|
'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 );
|
|
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
|
|
"Authorization: Bearer " . $accessToken,
|
|
"Accept: application/json"
|
|
] );
|
|
|
|
$response = curl_exec( $ch );
|
|
if ( curl_errno( $ch ) ) {
|
|
$error = curl_error( $ch );
|
|
curl_close( $ch );
|
|
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 ( !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;
|
|
|
|
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
|
|
{
|
|
$sku = $this->db->get( 'pp_shop_products', 'sku', [ 'id' => $productId ] );
|
|
return $sku ?: null;
|
|
}
|
|
|
|
public function apiloProductSearch( string $sku ): array
|
|
{
|
|
$accessToken = $this->apiloGetAccessToken();
|
|
if ( !$accessToken )
|
|
return [ 'status' => 'error', 'msg' => 'Brak tokenu Apilo.' ];
|
|
|
|
$url = "https://projectpro.apilo.com/rest/api/warehouse/product/?" . http_build_query( [ 'sku' => $sku ] );
|
|
|
|
$ch = curl_init( $url );
|
|
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
|
|
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
|
|
"Authorization: Bearer " . $accessToken,
|
|
"Accept: application/json"
|
|
] );
|
|
|
|
$response = curl_exec( $ch );
|
|
if ( curl_errno( $ch ) ) {
|
|
$error = curl_error( $ch );
|
|
curl_close( $ch );
|
|
return [ 'status' => 'error', 'msg' => 'Błąd cURL: ' . $error ];
|
|
}
|
|
curl_close( $ch );
|
|
|
|
$data = json_decode( $response, true );
|
|
if ( $data && isset( $data['products'] ) ) {
|
|
$data['status'] = 'SUCCESS';
|
|
return $data;
|
|
}
|
|
|
|
return [ 'status' => 'SUCCESS', 'msg' => 'Brak wyników dla podanego SKU.', 'products' => '' ];
|
|
}
|
|
|
|
public function apiloCreateProduct( int $productId ): array
|
|
{
|
|
$accessToken = $this->apiloGetAccessToken();
|
|
if ( !$accessToken )
|
|
return [ 'success' => false, 'message' => 'Brak tokenu Apilo.' ];
|
|
|
|
$product = ( new \Domain\Product\ProductRepository( $this->db ) )->findCached( $productId );
|
|
|
|
$params = [
|
|
'sku' => $product['sku'],
|
|
'ean' => $product['ean'],
|
|
'name' => $product['language']['name'],
|
|
'tax' => (int) $product['vat'],
|
|
'status' => 1,
|
|
'quantity' => (int) $product['quantity'],
|
|
'priceWithTax' => $product['price_brutto'],
|
|
'description' => $product['language']['description'] . '<br>' . $product['language']['short_description'],
|
|
'shortDescription' => '',
|
|
'images' => [],
|
|
];
|
|
|
|
foreach ( $product['images'] as $image )
|
|
$params['images'][] = "https://" . $_SERVER['HTTP_HOST'] . $image['src'];
|
|
|
|
$ch = curl_init( "https://projectpro.apilo.com/rest/api/warehouse/product/" );
|
|
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( [ $params ] ) );
|
|
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
|
|
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
|
|
"Authorization: Bearer " . $accessToken,
|
|
"Content-Type: application/json",
|
|
"Accept: application/json"
|
|
] );
|
|
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
|
|
$response = curl_exec( $ch );
|
|
$responseData = json_decode( $response, true );
|
|
|
|
if ( curl_errno( $ch ) ) {
|
|
$error = curl_error( $ch );
|
|
curl_close( $ch );
|
|
return [ 'success' => false, 'message' => 'Błąd cURL: ' . $error ];
|
|
}
|
|
curl_close( $ch );
|
|
|
|
if ( !empty( $responseData['products'] ) ) {
|
|
$this->db->update( 'pp_shop_products', [
|
|
'apilo_product_id' => reset( $responseData['products'] ),
|
|
'apilo_product_name' => $product['language']['name'],
|
|
], [ 'id' => $product['id'] ] );
|
|
|
|
return [ 'success' => true, 'message' => 'Produkt został dodany do magazynu APILO.' ];
|
|
}
|
|
|
|
return [ 'success' => false, 'message' => 'Podczas dodawania produktu wystąpił błąd.' ];
|
|
}
|
|
|
|
// ── ShopPRO import ──────────────────────────────────────────
|
|
|
|
public function shopproImportProduct( int $productId ): array
|
|
{
|
|
$settings = $this->getSettings( 'shoppro' );
|
|
$missingSetting = $this->missingShopproSetting( $settings, [ 'domain', 'db_name', 'db_host', 'db_user' ] );
|
|
if ( $missingSetting !== null ) {
|
|
return [ 'success' => false, 'message' => 'Brakuje konfiguracji shopPRO: ' . $missingSetting . '.' ];
|
|
}
|
|
|
|
$mdb2 = $this->shopproDb( $settings );
|
|
|
|
$product = $mdb2->get( 'pp_shop_products', '*', [ 'id' => $productId ] );
|
|
if ( !$product )
|
|
return [ 'success' => false, 'message' => 'Podczas importowania produktu wystąpił błąd.' ];
|
|
|
|
$this->db->insert( 'pp_shop_products', [
|
|
'price_netto' => $product['price_netto'],
|
|
'price_brutto' => $product['price_brutto'],
|
|
'vat' => $product['vat'],
|
|
'stock_0_buy' => $product['stock_0_buy'],
|
|
'quantity' => $product['quantity'],
|
|
'wp' => $product['wp'],
|
|
'sku' => $product['sku'],
|
|
'ean' => $product['ean'],
|
|
'custom_label_0' => $product['custom_label_0'],
|
|
'custom_label_1' => $product['custom_label_1'],
|
|
'custom_label_2' => $product['custom_label_2'],
|
|
'custom_label_3' => $product['custom_label_3'],
|
|
'custom_label_4' => $product['custom_label_4'],
|
|
'additional_message' => $product['additional_message'],
|
|
'additional_message_text' => $product['additional_message_text'],
|
|
'additional_message_required'=> $product['additional_message_required'],
|
|
'weight' => $product['weight'],
|
|
'producer_id' => $product['producer_id'] ?? null,
|
|
] );
|
|
|
|
$newProductId = $this->db->id();
|
|
if ( !$newProductId )
|
|
return [ 'success' => false, 'message' => 'Podczas importowania produktu wystąpił błąd.' ];
|
|
|
|
// Import translations
|
|
$languages = $mdb2->select( 'pp_shop_products_langs', '*', [ 'product_id' => $productId ] );
|
|
if ( is_array( $languages ) ) {
|
|
foreach ( $languages as $lang ) {
|
|
$this->db->insert( 'pp_shop_products_langs', [
|
|
'product_id' => $newProductId,
|
|
'lang_id' => $lang['lang_id'],
|
|
'name' => $lang['name'],
|
|
'short_description' => $lang['short_description'],
|
|
'description' => $lang['description'],
|
|
'tab_name_1' => $lang['tab_name_1'],
|
|
'tab_description_1' => $lang['tab_description_1'],
|
|
'tab_name_2' => $lang['tab_name_2'],
|
|
'tab_description_2' => $lang['tab_description_2'],
|
|
'meta_title' => $lang['meta_title'],
|
|
'meta_description' => $lang['meta_description'],
|
|
'meta_keywords' => $lang['meta_keywords'],
|
|
'seo_link' => $lang['seo_link'],
|
|
'copy_from' => $lang['copy_from'],
|
|
'warehouse_message_zero' => $lang['warehouse_message_zero'],
|
|
'warehouse_message_nonzero'=> $lang['warehouse_message_nonzero'],
|
|
'canonical' => $lang['canonical'],
|
|
'xml_name' => $lang['xml_name'],
|
|
'security_information' => $lang['security_information'] ?? null,
|
|
] );
|
|
}
|
|
}
|
|
|
|
// Import custom fields
|
|
$customFields = $mdb2->select( 'pp_shop_products_custom_fields', '*', [ 'id_product' => $productId ] );
|
|
if ( is_array( $customFields ) ) {
|
|
foreach ( $customFields as $field ) {
|
|
$this->db->insert( 'pp_shop_products_custom_fields', [
|
|
'id_product' => $newProductId,
|
|
'name' => (string)($field['name'] ?? ''),
|
|
'type' => (string)($field['type'] ?? 'text'),
|
|
'is_required' => !empty( $field['is_required'] ) ? 1 : 0,
|
|
] );
|
|
}
|
|
}
|
|
|
|
// Import images
|
|
$images = $mdb2->select( 'pp_shop_products_images', '*', [ 'product_id' => $productId ] );
|
|
if ( is_array( $images ) ) {
|
|
foreach ( $images as $image ) {
|
|
$imageUrl = 'https://' . $settings['domain'] . $image['src'];
|
|
|
|
$ch = curl_init( $imageUrl );
|
|
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
|
|
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
|
|
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
|
|
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
|
|
$imageData = curl_exec( $ch );
|
|
curl_close( $ch );
|
|
|
|
$imageName = basename( $imageUrl );
|
|
$imageDir = '../upload/product_images/product_' . $newProductId;
|
|
$imagePath = $imageDir . '/' . $imageName;
|
|
|
|
if ( !file_exists( $imageDir ) )
|
|
mkdir( $imageDir, 0777, true );
|
|
|
|
file_put_contents( $imagePath, $imageData );
|
|
|
|
$this->db->insert( 'pp_shop_products_images', [
|
|
'product_id' => $newProductId,
|
|
'src' => '/upload/product_images/product_' . $newProductId . '/' . $imageName,
|
|
'alt' => $image['alt'] ?? '',
|
|
'o' => $image['o'],
|
|
] );
|
|
}
|
|
}
|
|
|
|
return [ 'success' => true, 'message' => 'Produkt został zaimportowany.' ];
|
|
}
|
|
|
|
// ── ShopPRO export ──────────────────────────────────────────
|
|
|
|
public function shopproExportProduct( int $productId ): array
|
|
{
|
|
$settings = $this->getSettings( 'shoppro' );
|
|
$missingSetting = $this->missingShopproSetting( $settings, [ 'db_name', 'db_host', 'db_user' ] );
|
|
if ( $missingSetting !== null ) {
|
|
return [ 'success' => false, 'message' => 'Brakuje konfiguracji shopPRO: ' . $missingSetting . '.' ];
|
|
}
|
|
|
|
$product = $this->db->get( 'pp_shop_products', '*', [ 'id' => $productId ] );
|
|
if ( !$product ) {
|
|
return [ 'success' => false, 'message' => 'Nie znaleziono produktu do eksportu.' ];
|
|
}
|
|
|
|
$mdb2 = $this->shopproDb( $settings );
|
|
|
|
$mdb2->insert( 'pp_shop_products', [
|
|
'price_netto' => $product['price_netto'] ?? null,
|
|
'price_brutto' => $product['price_brutto'] ?? null,
|
|
'vat' => $product['vat'] ?? null,
|
|
'stock_0_buy' => $product['stock_0_buy'] ?? 0,
|
|
'quantity' => $product['quantity'] ?? 0,
|
|
'wp' => $product['wp'] ?? null,
|
|
'sku' => $product['sku'] ?? '',
|
|
'ean' => $product['ean'] ?? '',
|
|
'custom_label_0' => $product['custom_label_0'] ?? null,
|
|
'custom_label_1' => $product['custom_label_1'] ?? null,
|
|
'custom_label_2' => $product['custom_label_2'] ?? null,
|
|
'custom_label_3' => $product['custom_label_3'] ?? null,
|
|
'custom_label_4' => $product['custom_label_4'] ?? null,
|
|
'additional_message' => $product['additional_message'] ?? 0,
|
|
'additional_message_text' => $product['additional_message_text'] ?? null,
|
|
'additional_message_required'=> $product['additional_message_required'] ?? 0,
|
|
'weight' => $product['weight'] ?? null,
|
|
'producer_id' => $product['producer_id'] ?? null,
|
|
] );
|
|
|
|
$newProductId = (int) $mdb2->id();
|
|
if ( $newProductId <= 0 ) {
|
|
return [ 'success' => false, 'message' => 'Podczas eksportowania produktu wystąpił błąd.' ];
|
|
}
|
|
|
|
$languages = $this->db->select( 'pp_shop_products_langs', '*', [ 'product_id' => $productId ] );
|
|
if ( is_array( $languages ) ) {
|
|
foreach ( $languages as $lang ) {
|
|
$mdb2->insert( 'pp_shop_products_langs', [
|
|
'product_id' => $newProductId,
|
|
'lang_id' => $lang['lang_id'] ?? '',
|
|
'name' => $lang['name'] ?? '',
|
|
'short_description' => $lang['short_description'] ?? null,
|
|
'description' => $lang['description'] ?? null,
|
|
'tab_name_1' => $lang['tab_name_1'] ?? null,
|
|
'tab_description_1' => $lang['tab_description_1'] ?? null,
|
|
'tab_name_2' => $lang['tab_name_2'] ?? null,
|
|
'tab_description_2' => $lang['tab_description_2'] ?? null,
|
|
'meta_title' => $lang['meta_title'] ?? null,
|
|
'meta_description' => $lang['meta_description'] ?? null,
|
|
'meta_keywords' => $lang['meta_keywords'] ?? null,
|
|
'seo_link' => $lang['seo_link'] ?? null,
|
|
'copy_from' => $lang['copy_from'] ?? null,
|
|
'warehouse_message_zero' => $lang['warehouse_message_zero'] ?? null,
|
|
'warehouse_message_nonzero'=> $lang['warehouse_message_nonzero'] ?? null,
|
|
'canonical' => $lang['canonical'] ?? null,
|
|
'xml_name' => $lang['xml_name'] ?? null,
|
|
'security_information' => $lang['security_information'] ?? null,
|
|
] );
|
|
}
|
|
}
|
|
|
|
$customFields = $this->db->select( 'pp_shop_products_custom_fields', '*', [ 'id_product' => $productId ] );
|
|
if ( is_array( $customFields ) ) {
|
|
foreach ( $customFields as $field ) {
|
|
$mdb2->insert( 'pp_shop_products_custom_fields', [
|
|
'id_product' => $newProductId,
|
|
'name' => (string)($field['name'] ?? ''),
|
|
'type' => (string)($field['type'] ?? 'text'),
|
|
'is_required' => !empty( $field['is_required'] ) ? 1 : 0,
|
|
] );
|
|
}
|
|
}
|
|
|
|
$images = $this->db->select( 'pp_shop_products_images', '*', [ 'product_id' => $productId ] );
|
|
if ( is_array( $images ) && count( $images ) > 0 ) {
|
|
$missingImageApiSetting = $this->missingShopproSetting( $settings, [ 'domain', 'api_key' ] );
|
|
if ( $missingImageApiSetting !== null ) {
|
|
return [ 'success' => false, 'message' => 'Brakuje konfiguracji shopPRO dla wysylki zdjec: ' . $missingImageApiSetting . '.' ];
|
|
}
|
|
}
|
|
|
|
if ( is_array( $images ) ) {
|
|
foreach ( $images as $image ) {
|
|
$remoteImageSrc = $this->sendImageToShopproApi(
|
|
(string)($image['src'] ?? ''),
|
|
(int)$newProductId,
|
|
(string)($settings['domain'] ?? ''),
|
|
(string)($settings['api_key'] ?? ''),
|
|
(string)($image['alt'] ?? ''),
|
|
(int)($image['o'] ?? 0)
|
|
);
|
|
if ( $remoteImageSrc === '' ) {
|
|
return [ 'success' => false, 'message' => 'Nie udalo sie wyslac zdjec produktu przez API shopPRO.' ];
|
|
}
|
|
}
|
|
}
|
|
|
|
return [
|
|
'success' => true,
|
|
'message' => 'Produkt został wyeksportowany (ID: ' . $newProductId . ').',
|
|
];
|
|
}
|
|
|
|
private function missingShopproSetting( array $settings, array $requiredKeys ): ?string
|
|
{
|
|
foreach ( $requiredKeys as $requiredKey ) {
|
|
if ( trim( (string)($settings[$requiredKey] ?? '') ) === '' ) {
|
|
return $requiredKey;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function shopproDb( array $settings ): \medoo
|
|
{
|
|
return new \medoo( [
|
|
'database_type' => 'mysql',
|
|
'database_name' => $settings['db_name'],
|
|
'server' => $settings['db_host'],
|
|
'username' => $settings['db_user'],
|
|
'password' => $settings['db_password'] ?? '',
|
|
'charset' => 'utf8'
|
|
] );
|
|
}
|
|
|
|
private function sendImageToShopproApi(
|
|
string $src,
|
|
int $remoteProductId,
|
|
string $remoteDomain,
|
|
string $apiKey,
|
|
string $alt,
|
|
int $position
|
|
): string
|
|
{
|
|
$src = trim( $src );
|
|
if ( $src === '' ) {
|
|
return '';
|
|
}
|
|
|
|
$localSourcePath = '..' . $src;
|
|
if ( !is_file( $localSourcePath ) ) {
|
|
return '';
|
|
}
|
|
|
|
$content = @file_get_contents( $localSourcePath );
|
|
if ( $content === false ) {
|
|
return '';
|
|
}
|
|
|
|
$remoteDomain = trim( $remoteDomain );
|
|
if ( $remoteDomain === '' ) {
|
|
return '';
|
|
}
|
|
|
|
if ( strpos( $remoteDomain, 'http://' ) !== 0 && strpos( $remoteDomain, 'https://' ) !== 0 ) {
|
|
$remoteDomain = 'https://' . $remoteDomain;
|
|
}
|
|
$remoteDomain = rtrim( $remoteDomain, '/' );
|
|
|
|
$url = $remoteDomain . '/api.php?endpoint=products&action=upload_image';
|
|
$payload = [
|
|
'id' => $remoteProductId,
|
|
'file_name' => basename( $src ),
|
|
'content_base64' => base64_encode( $content ),
|
|
'alt' => $alt,
|
|
'o' => $position,
|
|
];
|
|
|
|
$ch = curl_init( $url );
|
|
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
|
|
curl_setopt( $ch, CURLOPT_POST, true );
|
|
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $payload, JSON_UNESCAPED_UNICODE ) );
|
|
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
|
|
'Content-Type: application/json',
|
|
'Accept: application/json',
|
|
'X-Api-Key: ' . $apiKey,
|
|
] );
|
|
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
|
|
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
|
|
$response = curl_exec( $ch );
|
|
|
|
if ( curl_errno( $ch ) ) {
|
|
curl_close( $ch );
|
|
return '';
|
|
}
|
|
|
|
$httpCode = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );
|
|
curl_close( $ch );
|
|
|
|
if ( $httpCode >= 400 || $response === false ) {
|
|
return '';
|
|
}
|
|
|
|
$responseData = json_decode( (string) $response, true );
|
|
if ( !is_array( $responseData ) || ( $responseData['status'] ?? '' ) !== 'ok' ) {
|
|
return '';
|
|
}
|
|
|
|
return (string)($responseData['data']['src'] ?? '');
|
|
}
|
|
}
|