Compare commits

..

6 Commits

Author SHA1 Message Date
842ed77f5b ver. 0.312: fix krytycznych bugów integracji Apilo
- curl_getinfo() po curl_close() dawał HTTP 0 — przeniesienie przed close
- nieskończona pętla wysyłki zamówienia przy błędzie serwera Apilo (apilo_order_id = -1)
- ceny 0.00 PLN — string "0.00" z MySQL jest truthy, zmiana na (float) > 0
- walidacja zerowych cen przed wysyłką (apilo_order_id = -2)
- niezainicjalizowana $order_message

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 11:11:28 +01:00
96ed86649a build: update package v0.311
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:51:50 +01:00
fdc4cac593 ver. 0.311: fix race condition Apilo + persistence filtrów + poprawki cen
- Fix: race condition callback płatności przed wysłaniem do Apilo
- Fix: processApiloSyncQueue czeka na apilo_order_id zamiast usuwać task
- Fix: drugie wywołanie processApiloSyncQueue po wysyłce zamówień w cronie
- Fix: ceny w szczegółach zamówienia (effective price zamiast 0 zł)
- New: persistence filtrów tabel admin (localStorage)
- Testy: 760 tests, 2141 assertions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 10:50:34 +01:00
8f67d9de0a build: update package v0.310
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:57:20 +01:00
3ae0bc95e0 ver. 0.310: logi integracji w panelu admin
Nowa zakladka "Logi" w sekcji Integracje - podglad tabeli pp_log
z paginacja, sortowaniem, filtrami i rozwijalnym kontekstem JSON.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:54:09 +01:00
92ec5e1194 build: update package v0.309
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 09:32:51 +01:00
23 changed files with 635 additions and 15 deletions

View File

@@ -36,7 +36,7 @@ composer test
PHPUnit 9.6 via `phpunit.phar`. Bootstrap: `tests/bootstrap.php`. Config: `phpunit.xml`.
Current suite: **750 tests, 2114 assertions**.
Current suite: **758 tests, 2135 assertions**.
### Creating Updates
See `docs/UPDATE_INSTRUCTIONS.md` for the full procedure. Updates are ZIP packages in `updates/0.XX/`. Never include `*.md` files, `updates/changelog.php`, or root `.htaccess` in update ZIPs.

View File

@@ -162,7 +162,7 @@ $isCompactColumn = function(array $column): bool {
<div class="col-sm-12">
<button type="submit" class="btn btn-primary btn-sm">Szukaj</button>
<a href="<?= htmlspecialchars($list->basePath, ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-default btn-sm">Wyczyść</a>
<a href="<?= htmlspecialchars($list->basePath, ENT_QUOTES, 'UTF-8'); ?>" class="btn btn-default btn-sm js-table-filters-clear">Wyczyść</a>
</div>
</form>
</div>
@@ -312,6 +312,40 @@ $isCompactColumn = function(array $column): bool {
</div>
</div>
<script type="text/javascript">
// Table state persistence — redirect ASAP to saved view
(function() {
var basePath = <?= json_encode($list->basePath); ?>;
var stateKey = 'tableListQuery_' + basePath;
var clearKey = 'tableListCleared_' + basePath;
var pathname = window.location.pathname.replace(/\/+$/, '/');
var bp = basePath.replace(/\/+$/, '/');
var queryPart = '';
if (pathname.length > bp.length && pathname.indexOf(bp) === 0) {
queryPart = pathname.substring(bp.length);
}
if (!queryPart && window.location.search) {
queryPart = window.location.search.substring(1);
}
try {
var justCleared = sessionStorage.getItem(clearKey) === '1';
sessionStorage.removeItem(clearKey);
if (queryPart) {
localStorage.setItem(stateKey, queryPart);
} else if (!justCleared) {
var saved = localStorage.getItem(stateKey);
if (saved) {
window.location.replace(basePath + saved);
}
}
} catch (e) {}
})();
</script>
<script type="text/javascript">
(function($) {
if (!$) {
@@ -550,5 +584,17 @@ $isCompactColumn = function(array $column): bool {
$(document).on('change.tablePerPage', '.js-per-page-select', function() {
$(this).closest('form').trigger('submit');
});
// --- Table state clear on "Wyczyść" ---
var stateStorageKey = 'tableListQuery_' + <?= json_encode($list->basePath); ?>;
var stateClearKey = 'tableListCleared_' + <?= json_encode($list->basePath); ?>;
$(document).off('click.tableClearState', '.js-table-filters-clear');
$(document).on('click.tableClearState', '.js-table-filters-clear', function() {
try {
localStorage.removeItem(stateStorageKey);
sessionStorage.setItem(stateClearKey, '1');
} catch (e) {}
});
})(window.jQuery);
</script>

View File

@@ -0,0 +1,19 @@
<?= \Shared\Tpl\Tpl::view('components/table-list', ['list' => $this->viewModel]); ?>
<div class="mt15">
<a href="/admin/integrations/logs_clear/" class="btn btn-danger btn-sm"
onclick="return confirm('Na pewno chcesz usunac wszystkie logi?');">
<i class="fa fa-trash"></i> Wyczysc wszystkie logi
</a>
</div>
<script type="text/javascript">
$(function() {
$('body').on('click', '.log-context-btn', function(e) {
e.preventDefault();
var id = $(this).data('id');
$('#log-context-' + id).toggle();
$(this).text($('#log-context-' + id).is(':visible') ? 'Ukryj' : 'Pokaz');
});
});
</script>

View File

@@ -184,13 +184,14 @@ $orderId = (int)($this -> order['id'] ?? 0);
<?= $product[ 'message' ] != '' ? '<strong>Wiadomość:</strong> ' . $product['message'] : '';?>
</div>
<div class="od-mobile-price-line">
<?= (int)$product['quantity'];?> &times; <?= \Shared\Helpers\Helpers::decimal( $product['price_brutto_promo'] );?> = <?= \Shared\Helpers\Helpers::decimal( $product['price_brutto_promo'] * $product['quantity'] );?> zł
<? $effective = ((float)$product['price_brutto_promo'] > 0 && (float)$product['price_brutto_promo'] < (float)$product['price_brutto']) ? (float)$product['price_brutto_promo'] : (float)$product['price_brutto'];?>
<?= (int)$product['quantity'];?> &times; <?= \Shared\Helpers\Helpers::decimal( $effective );?> = <?= \Shared\Helpers\Helpers::decimal( $effective * $product['quantity'] );?> zł
</div>
</td>
<td class="tab-center"><?= $product[ 'quantity' ];?></td>
<td class="tab-right"><?= \Shared\Helpers\Helpers::decimal( $product[ 'price_brutto' ] );?> zł</td>
<td class="tab-right"><?= \Shared\Helpers\Helpers::decimal( $product[ 'price_brutto_promo' ] );?> zł</td>
<td class="tab-right"><?= \Shared\Helpers\Helpers::decimal( $product[ 'price_brutto_promo' ] * $product[ 'quantity' ] );?> zł</td>
<td class="tab-right"><?= \Shared\Helpers\Helpers::decimal( $effective );?> zł</td>
<td class="tab-right"><?= \Shared\Helpers\Helpers::decimal( $effective * $product[ 'quantity' ] );?> zł</td>
</tr>
<? endforeach; endif;?>
</tbody>

View File

@@ -153,6 +153,11 @@
<i class="fa fa-cogs" aria-hidden="true"></i>shopPRO
</a>
</li>
<li>
<a href="/admin/integrations/logs/">
<i class="fa fa-list-alt" aria-hidden="true"></i>Logi
</a>
</li>
</ul>
</div>
<div class="preview">

View File

@@ -56,6 +56,63 @@ class IntegrationsRepository
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

View File

@@ -533,9 +533,26 @@ class OrderAdminService
$error = '';
$sync_failed = false;
$max_attempts = 50; // ~8h przy cronie co 10 min
// Zamówienie jeszcze nie wysłane do Apilo — czekaj na crona
if (!(int)$order['apilo_order_id']) {
$attempts = (int)($task['attempts'] ?? 0) + 1;
if ($attempts >= $max_attempts) {
// Przekroczono limit prób — porzuć task
unset($queue[$key]);
} else {
$task['attempts'] = $attempts;
$task['last_error'] = 'awaiting_apilo_order';
$task['updated_at'] = date('Y-m-d H:i:s');
$queue[$key] = $task;
}
$processed++;
continue;
}
$payment_pending = !empty($task['payment']) && (int)$order['paid'] === 1;
if ($payment_pending && (int)$order['apilo_order_id']) {
if ($payment_pending) {
if (!$this->syncApiloPayment($order)) {
$sync_failed = true;
$error = 'payment_sync_failed';
@@ -543,7 +560,7 @@ class OrderAdminService
}
$status_pending = isset($task['status']) && $task['status'] !== null && $task['status'] !== '';
if (!$sync_failed && $status_pending && (int)$order['apilo_order_id']) {
if (!$sync_failed && $status_pending) {
if (!$this->syncApiloStatus($order, (int)$task['status'])) {
$sync_failed = true;
$error = 'status_sync_failed';
@@ -631,7 +648,10 @@ class OrderAdminService
self::appendApiloLog("SET AS PAID\n" . print_r($order, true));
}
if ($order['apilo_order_id'] && !$this->syncApiloPayment($order)) {
if (!$order['apilo_order_id']) {
// Zamówienie jeszcze nie wysłane do Apilo — kolejkuj sync płatności na później
self::queueApiloSync((int)$order['id'], true, null, 'awaiting_apilo_order');
} elseif (!$this->syncApiloPayment($order)) {
self::queueApiloSync((int)$order['id'], true, null, 'payment_sync_failed');
}
}
@@ -652,7 +672,10 @@ class OrderAdminService
self::appendApiloLog("UPDATE STATUS\n" . print_r($order, true));
}
if ($order['apilo_order_id'] && !$this->syncApiloStatus($order, $status)) {
if (!$order['apilo_order_id']) {
// Zamówienie jeszcze nie wysłane do Apilo — kolejkuj sync statusu na później
self::queueApiloSync((int)$order['id'], false, $status, 'awaiting_apilo_order');
} elseif (!$this->syncApiloStatus($order, $status)) {
self::queueApiloSync((int)$order['id'], false, $status, 'status_sync_failed');
}
}

View File

@@ -2,6 +2,7 @@
namespace admin\Controllers;
use Domain\Integrations\IntegrationsRepository;
use admin\ViewModels\Common\PaginatedTableViewModel;
class IntegrationsController
{
@@ -12,6 +13,114 @@ class IntegrationsController
$this->repository = $repository;
}
public function logs(): string
{
$sortableColumns = ['id', 'action', 'order_id', 'message', 'date'];
$filterDefinitions = [
[
'key' => 'log_action',
'label' => 'Akcja',
'type' => 'text',
],
[
'key' => 'message',
'label' => 'Wiadomosc',
'type' => 'text',
],
[
'key' => 'order_id',
'label' => 'ID zamowienia',
'type' => 'text',
],
];
$listRequest = \admin\Support\TableListRequestFactory::fromRequest(
$filterDefinitions,
$sortableColumns,
'id'
);
$result = $this->repository->getLogs(
$listRequest['filters'],
$listRequest['sortColumn'],
$listRequest['sortDir'],
$listRequest['page'],
$listRequest['perPage']
);
$rows = [];
$lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
foreach ( $result['items'] as $item ) {
$id = (int)($item['id'] ?? 0);
$context = trim( (string)($item['context'] ?? '') );
$contextHtml = '';
if ( $context !== '' ) {
$contextHtml = '<button class="btn btn-xs btn-default log-context-btn" data-id="' . $id . '">Pokaz</button>'
. '<pre class="log-context-pre" id="log-context-' . $id . '" style="display:none;max-height:300px;overflow:auto;margin-top:5px;font-size:11px;white-space:pre-wrap;">'
. htmlspecialchars( $context, ENT_QUOTES, 'UTF-8' )
. '</pre>';
}
$rows[] = [
'lp' => $lp++ . '.',
'action' => htmlspecialchars( (string)($item['action'] ?? ''), ENT_QUOTES, 'UTF-8' ),
'order_id' => $item['order_id'] ? (int)$item['order_id'] : '-',
'message' => htmlspecialchars( (string)($item['message'] ?? ''), ENT_QUOTES, 'UTF-8' ),
'context' => $contextHtml,
'date' => !empty( $item['date'] ) ? date( 'Y-m-d H:i:s', strtotime( (string)$item['date'] ) ) : '-',
];
}
$total = (int)$result['total'];
$totalPages = max( 1, (int)ceil( $total / $listRequest['perPage'] ) );
$viewModel = new PaginatedTableViewModel(
[
['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
['key' => 'date', 'sort_key' => 'date', 'label' => 'Data', 'class' => 'text-center', 'sortable' => true],
['key' => 'action', 'sort_key' => 'action', 'label' => 'Akcja', 'sortable' => true],
['key' => 'order_id', 'sort_key' => 'order_id', 'label' => 'Zamowienie', 'class' => 'text-center', 'sortable' => true],
['key' => 'message', 'sort_key' => 'message', 'label' => 'Wiadomosc', 'sortable' => true],
['key' => 'context', 'label' => 'Kontekst', 'sortable' => false, 'raw' => true],
],
$rows,
$listRequest['viewFilters'],
[
'column' => $listRequest['sortColumn'],
'dir' => $listRequest['sortDir'],
],
[
'page' => $listRequest['page'],
'per_page' => $listRequest['perPage'],
'total' => $total,
'total_pages' => $totalPages,
],
array_merge( $listRequest['queryFilters'], [
'sort' => $listRequest['sortColumn'],
'dir' => $listRequest['sortDir'],
'per_page' => $listRequest['perPage'],
] ),
$listRequest['perPageOptions'],
$sortableColumns,
'/admin/integrations/logs/',
'Brak wpisow w logach.'
);
return \Shared\Tpl\Tpl::view( 'integrations/logs', [
'viewModel' => $viewModel,
] );
}
public function logs_clear(): void
{
$this->repository->clearLogs();
\Shared\Helpers\Helpers::alert( 'Logi zostaly wyczyszczone.' );
header( 'Location: /admin/integrations/logs/' );
exit;
}
public function apilo_settings(): string
{
return \Shared\Tpl\Tpl::view( 'integrations/apilo-settings', [

View File

@@ -201,6 +201,7 @@ if ( $apilo_settings['enabled'] and $apilo_settings['sync_orders'] and $apilo_se
{
$products = $mdb -> select( 'pp_shop_order_products', '*', [ 'order_id' => $order['id'] ] );
$products_array = [];
$order_message = '';
foreach ( $products as $product )
{
$productRepo = new \Domain\Product\ProductRepository( $mdb );
@@ -211,8 +212,8 @@ if ( $apilo_settings['enabled'] and $apilo_settings['sync_orders'] and $apilo_se
'ean' => $productRepo->getEanWithFallback( (int)$product['product_id'], true ),
'sku' => $sku ? $sku : md5( $product['product_id'] ),
'originalName' => $product['name'],
'originalPriceWithTax' => $product['price_brutto_promo'] ? str_replace( ',', '.', $product['price_brutto_promo'] ) : str_replace( ',', '.', $product['price_brutto'] ),
'originalPriceWithoutTax' => $product['price_brutto_promo'] ? str_replace( ',', '.', round( $product['price_brutto_promo'] / ( 1 + $product['vat']/100 ), 2 ) ) : str_replace( ',', '.', round( $product['price_brutto'] / ( 1 + $product['vat']/100 ), 2 ) ),
'originalPriceWithTax' => (float)$product['price_brutto_promo'] > 0 ? str_replace( ',', '.', $product['price_brutto_promo'] ) : str_replace( ',', '.', $product['price_brutto'] ),
'originalPriceWithoutTax' => (float)$product['price_brutto_promo'] > 0 ? str_replace( ',', '.', round( $product['price_brutto_promo'] / ( 1 + $product['vat']/100 ), 2 ) ) : str_replace( ',', '.', round( $product['price_brutto'] / ( 1 + $product['vat']/100 ), 2 ) ),
'quantity' => $product['quantity'],
'tax' => number_format( $product['vat'], 2, '.', '' ),
'status' => 1,
@@ -255,6 +256,25 @@ if ( $apilo_settings['enabled'] and $apilo_settings['sync_orders'] and $apilo_se
'media' => null
];
// Walidacja: sprawdź czy zamówienie ma produkty z cenami > 0
$has_priced_products = false;
foreach ( $products_array as $pa )
{
if ( $pa['type'] == 1 && (float)$pa['originalPriceWithTax'] > 0 )
{
$has_priced_products = true;
break;
}
}
if ( !$has_priced_products )
{
\Domain\Integrations\ApiloLogger::log( $mdb, 'send_order', (int)$order['id'], 'Pominięto zamówienie - wszystkie produkty mają cenę 0.00', [ 'products' => $products_array ] );
\Shared\Helpers\Helpers::send_email( 'biuro@project-pro.pl', 'Apilo: zamówienie #' . $order['id'] . ' ma zerowe ceny produktów', 'Zamówienie #' . $order['id'] . ' nie zostało wysłane do Apilo, ponieważ wszystkie produkty mają cenę 0.00 PLN. Sprawdź zamówienie w panelu sklepu.' );
$mdb -> update( 'pp_shop_orders', [ 'apilo_order_id' => -2 ], [ 'id' => $order['id'] ] );
echo '<p>Pominięto zamówienie #' . $order['id'] . ' - zerowe ceny produktów</p>';
continue;
}
$access_token = $integrationsRepository -> apiloGetAccessToken();
$order_date = new DateTime( $order['date_order'] );
@@ -410,9 +430,9 @@ if ( $apilo_settings['enabled'] and $apilo_settings['sync_orders'] and $apilo_se
\Domain\Integrations\ApiloLogger::log( $mdb, 'send_order', (int)$order['id'], 'Błąd cURL przy wysyłaniu zamówienia: ' . $curl_error_send, [ 'curl_error' => $curl_error_send ] );
echo 'Błąd cURL: ' . $curl_error_send;
}
$http_code_send = (int)curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
$http_code_send = (int)curl_getinfo( $ch, CURLINFO_HTTP_CODE );
$response = json_decode( $response, true );
if ( $config['debug']['apilo'] )
@@ -497,6 +517,20 @@ if ( $apilo_settings['enabled'] and $apilo_settings['sync_orders'] and $apilo_se
\Shared\Helpers\Helpers::send_email( 'biuro@project-pro.pl', 'Błąd wysyłania zamówienia do apilo.com', $email_data );
}
}
elseif ( $http_code_send >= 400 || !isset( $response['id'] ) )
{
// Błąd serwera lub brak ID w odpowiedzi — logujemy i pomijamy, NIE ustawiamy apilo_order_id
// żeby zamówienie nie wpadło w nieskończoną pętlę, ustawiamy apilo_order_id na -1 (błąd)
$mdb -> update( 'pp_shop_orders', [ 'apilo_order_id' => -1 ], [ 'id' => $order['id'] ] );
\Domain\Integrations\ApiloLogger::log( $mdb, 'send_order', (int)$order['id'], 'Błąd wysyłania zamówienia do Apilo (HTTP ' . $http_code_send . ')', [ 'http_code' => $http_code_send, 'response' => $response ] );
$email_data = 'HTTP Code: ' . $http_code_send . "\n\n";
$email_data .= print_r( $response, true );
$email_data .= print_r( $postData, true );
\Shared\Helpers\Helpers::send_email( 'biuro@project-pro.pl', 'Błąd wysyłania zamówienia #' . $order['id'] . ' do apilo.com (HTTP ' . $http_code_send . ')', $email_data );
echo '<p>Błąd wysyłania zamówienia do apilo.com: ID: ' . $order['id'] . ' (HTTP ' . $http_code_send . ')</p>';
}
else
{
$mdb -> update( 'pp_shop_orders', [ 'apilo_order_id' => $response['id'] ], [ 'id' => $order['id'] ] );
@@ -504,6 +538,9 @@ if ( $apilo_settings['enabled'] and $apilo_settings['sync_orders'] and $apilo_se
echo '<p>Wysłałem zamówienie do apilo.com: ID: ' . $order['id'] . ' - ' . $response['id'] . '</p>';
}
}
// Po wysłaniu zamówień: przetwórz kolejkę sync (płatności/statusy oczekujące na apilo_order_id)
$orderAdminService->processApiloSyncQueue( 10 );
}
// sprawdzanie statusów zamówień w apilo.com jeżeli zamówienie nie jest zrealizowane, anulowane lub nieodebrane

View File

@@ -4,6 +4,35 @@ Logi zmian z migracji na Domain-Driven Architecture. Najnowsze na gorze.
---
## ver. 0.312 (2026-02-23) - Fix krytycznych bugów integracji Apilo
- **FIX**: `curl_getinfo()` wywoływane po `curl_close()` — HTTP code zawsze wynosił 0, uniemożliwiając prawidłową obsługę odpowiedzi Apilo
- **FIX**: Nieskończona pętla wysyłania zamówienia — gdy Apilo zwracało błąd serwera, zamówienie nie dostawało `apilo_order_id` i było ponownie wybierane w każdym cyklu crona. Teraz błędne zamówienia oznaczane `apilo_order_id = -1` z powiadomieniem email
- **FIX**: Ceny produktów 0.00 PLN w Apilo — string `"0.00"` z MySQL jest truthy w PHP, więc ternary wybierał `price_brutto_promo` (0.00) zamiast `price_brutto`. Zmiana na `(float)... > 0`
- **FIX**: Walidacja cen przed wysyłką — zamówienia z zerowymi cenami produktów nie są wysyłane do Apilo (`apilo_order_id = -2`) z powiadomieniem email
- **FIX**: Niezainicjalizowana zmienna `$order_message` powodująca PHP warning
---
## ver. 0.311 (2026-02-23) - Fix race condition Apilo + persistence filtrów + poprawki cen
- **FIX**: Race condition — callback płatności przed wysłaniem zamówienia do Apilo nie synchronizował płatności (task trafiał w pustkę). Teraz `syncApiloPaymentIfNeeded` i `syncApiloStatusIfNeeded` kolejkują sync do retry gdy `apilo_order_id` jeszcze nie istnieje
- **FIX**: `processApiloSyncQueue` — zamówienia bez `apilo_order_id` były usuwane z kolejki bez synchronizacji. Teraz czekają (max 50 prób ~8h) aż cron wyśle zamówienie do Apilo
- **FIX**: Drugie wywołanie `processApiloSyncQueue` w cronie po wysyłce zamówień — sync płatności/statusów w tym samym cyklu
- **FIX**: Ceny w szczegółach zamówienia (admin + frontend) — gdy `price_brutto_promo` = 0 lub >= ceny regularnej, wyświetla cenę regularną zamiast 0 zł
- **NEW**: Persistence filtrów tabel w panelu admin — localStorage zapamiętuje ostatni widok (filtry, sortowanie, paginacja) i przywraca go przy powrocie do listy. Przycisk "Wyczyść" resetuje zapisany stan
---
## ver. 0.310 (2026-02-23) - Logi integracji w panelu admin
- **NEW**: Zakładka "Logi" w sekcji Integracje — podgląd tabeli `pp_log` z paginacją, sortowaniem, filtrami (akcja, wiadomość, ID zamówienia) i rozwijalnym kontekstem JSON
- **NEW**: `IntegrationsRepository::getLogs()`, `deleteLog()`, `clearLogs()` — metody do obsługi logów
- **NEW**: `IntegrationsController::logs()`, `logs_clear()` — akcje kontrolera
- **NEW**: Przycisk "Wyczyść wszystkie logi" z potwierdzeniem
---
## ver. 0.309 (2026-02-23) - ApiloLogger + cache-busting CSS/JS + poprawki UI
- **NEW**: `ApiloLogger` — logowanie operacji Apilo do tabeli `pp_log` z kontekstem JSON (send_order, resend_order, payment_sync, status_sync, status_poll)

View File

@@ -23,7 +23,7 @@ composer test # standard
## Aktualny stan
```text
OK (750 tests, 2114 assertions)
OK (758 tests, 2135 assertions)
```
Zweryfikowano: 2026-02-22 (ver. 0.304)

View File

@@ -179,7 +179,7 @@
'id': <?= (int)$product['product_id'];?>,
'name': '<?= $product['name'];?>',
'quantity': <?= $product['quantity'];?>,
'price': <?= $product['price_brutto_promo'];?>
'price': <?= ((float)$product['price_brutto_promo'] > 0 && (float)$product['price_brutto_promo'] < (float)$product['price_brutto']) ? (float)$product['price_brutto_promo'] : (float)$product['price_brutto'];?>
}<? if ( $product != end( $this -> order['products'] ) ) echo ',';?>
<? endforeach;?>
]

View File

@@ -298,4 +298,69 @@ class IntegrationsRepositoryTest extends TestCase
$this->assertSame('1', (string)$result[0]['id']);
$this->assertSame('Przelew', (string)$result[0]['name']);
}
// ── Logs ────────────────────────────────────────────────────
public function testGetLogsReturnsItemsAndTotal(): void
{
$this->mockDb->expects($this->once())
->method('count')
->with('pp_log', $this->anything())
->willReturn(2);
$this->mockDb->expects($this->once())
->method('select')
->with('pp_log', '*', $this->anything())
->willReturn([
['id' => 1, 'action' => 'send_order', 'message' => 'OK', 'date' => '2026-01-01 12:00:00'],
['id' => 2, 'action' => 'status_sync', 'message' => 'Synced', 'date' => '2026-01-02 12:00:00'],
]);
$result = $this->repository->getLogs([], 'id', 'DESC', 1, 15);
$this->assertIsArray($result);
$this->assertArrayHasKey('items', $result);
$this->assertArrayHasKey('total', $result);
$this->assertCount(2, $result['items']);
$this->assertSame(2, $result['total']);
}
public function testGetLogsReturnsEmptyWhenNoResults(): void
{
$this->mockDb->method('count')->willReturn(0);
$this->mockDb->method('select')->willReturn([]);
$result = $this->repository->getLogs([], 'id', 'DESC', 1, 15);
$this->assertSame(0, $result['total']);
$this->assertEmpty($result['items']);
}
public function testGetLogsHandlesNullFromSelect(): void
{
$this->mockDb->method('count')->willReturn(0);
$this->mockDb->method('select')->willReturn(null);
$result = $this->repository->getLogs([], 'id', 'DESC', 1, 15);
$this->assertSame([], $result['items']);
}
public function testDeleteLogCallsDelete(): void
{
$this->mockDb->expects($this->once())
->method('delete')
->with('pp_log', ['id' => 42]);
$this->assertTrue($this->repository->deleteLog(42));
}
public function testClearLogsDeletesAll(): void
{
$this->mockDb->expects($this->once())
->method('delete')
->with('pp_log', []);
$this->assertTrue($this->repository->clearLogs());
}
}

View File

@@ -227,4 +227,110 @@ class OrderAdminServiceTest extends TestCase
$service = $this->createService(null, null, $settingsRepo);
$this->assertSame(150.0, $service->getFreeDeliveryThreshold());
}
// =========================================================================
// processApiloSyncQueue — awaiting apilo_order_id
// =========================================================================
private function getQueuePath(): string
{
// Musi odpowiadać ścieżce w OrderAdminService::apiloSyncQueuePath()
// dirname(autoload/Domain/Order/, 2) = autoload/
return dirname(__DIR__, 4) . '/autoload/temp/apilo-sync-queue.json';
}
private function writeQueue(array $queue): void
{
$path = $this->getQueuePath();
$dir = dirname($path);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($path, json_encode($queue, JSON_PRETTY_PRINT));
}
private function readQueue(): array
{
$path = $this->getQueuePath();
if (!file_exists($path)) return [];
$content = file_get_contents($path);
return $content ? json_decode($content, true) : [];
}
protected function tearDown(): void
{
$path = $this->getQueuePath();
if (file_exists($path)) {
unlink($path);
}
parent::tearDown();
}
public function testProcessApiloSyncQueueKeepsTaskWhenApiloOrderIdIsNull(): void
{
// Zamówienie bez apilo_order_id — task powinien zostać w kolejce
$this->writeQueue([
'42' => [
'order_id' => 42,
'payment' => 1,
'status' => null,
'attempts' => 0,
'last_error' => 'awaiting_apilo_order',
'updated_at' => '2026-01-01 00:00:00',
],
]);
$orderRepo = $this->createMock(OrderRepository::class);
$orderRepo->method('findRawById')
->with(42)
->willReturn([
'id' => 42,
'apilo_order_id' => null,
'paid' => 1,
'summary' => '100.00',
]);
$service = new OrderAdminService($orderRepo);
$processed = $service->processApiloSyncQueue(10);
$this->assertSame(1, $processed);
$queue = $this->readQueue();
$this->assertArrayHasKey('42', $queue);
$this->assertSame('awaiting_apilo_order', $queue['42']['last_error']);
$this->assertSame(1, $queue['42']['attempts']);
}
public function testProcessApiloSyncQueueRemovesTaskAfterMaxAttempts(): void
{
// Task z 49 próbami — limit to 50, więc powinien zostać usunięty
$this->writeQueue([
'42' => [
'order_id' => 42,
'payment' => 1,
'status' => null,
'attempts' => 49,
'last_error' => 'awaiting_apilo_order',
'updated_at' => '2026-01-01 00:00:00',
],
]);
$orderRepo = $this->createMock(OrderRepository::class);
$orderRepo->method('findRawById')
->with(42)
->willReturn([
'id' => 42,
'apilo_order_id' => null,
'paid' => 1,
'summary' => '100.00',
]);
$service = new OrderAdminService($orderRepo);
$processed = $service->processApiloSyncQueue(10);
$this->assertSame(1, $processed);
$queue = $this->readQueue();
$this->assertArrayNotHasKey('42', $queue);
}
}

View File

@@ -35,6 +35,33 @@ class IntegrationsControllerTest extends TestCase
);
}
public function testHasLogsMethods(): void
{
$methods = [
'logs',
'logs_clear',
];
foreach ($methods as $method) {
$this->assertTrue(
method_exists($this->controller, $method),
"Method $method does not exist"
);
}
}
public function testLogsReturnsString(): void
{
$reflection = new \ReflectionClass($this->controller);
$this->assertEquals('string', (string) $reflection->getMethod('logs')->getReturnType());
}
public function testLogsClearReturnsVoid(): void
{
$reflection = new \ReflectionClass($this->controller);
$this->assertEquals('void', (string) $reflection->getMethod('logs_clear')->getReturnType());
}
public function testHasAllApiloSettingsMethods(): void
{
$methods = [

BIN
updates/0.30/ver_0.309.zip Normal file

Binary file not shown.

View File

@@ -0,0 +1,35 @@
{
"changelog": "NEW - ApiloLogger (logowanie operacji Apilo do pp_log), cache-busting CSS/JS w admin panelu, poprawki UI listy produktow, clipboard API",
"version": "0.309",
"files": {
"added": [
"autoload/Domain/Integrations/ApiloLogger.php"
],
"deleted": [
],
"modified": [
"admin/index.php",
"admin/layout/style-css/style.css",
"admin/layout/style-css/style.css.map",
"admin/layout/style-scss/style.scss",
"admin/templates/site/main-layout.php",
"autoload/Domain/Order/OrderAdminService.php",
"autoload/admin/Controllers/ShopProductController.php",
"cron.php",
"libraries/functions.js"
]
},
"checksum_zip": "sha256:87a3db1a6038da742d21d92b65c21156493af52543b3810694ea91e000acf920",
"sql": [
"ALTER TABLE pp_log ADD COLUMN `action` VARCHAR(100) NULL DEFAULT NULL AFTER `id`;",
"ALTER TABLE pp_log ADD COLUMN `order_id` INT NULL DEFAULT NULL AFTER `action`;",
"ALTER TABLE pp_log ADD COLUMN `context` TEXT NULL DEFAULT NULL AFTER `message`;",
"ALTER TABLE pp_log ADD INDEX `idx_action` (`action`);",
"ALTER TABLE pp_log ADD INDEX `idx_order_id` (`order_id`);"
],
"date": "2026-02-23",
"directories_deleted": [
]
}

BIN
updates/0.30/ver_0.310.zip Normal file

Binary file not shown.

View File

@@ -0,0 +1,25 @@
{
"changelog": "NEW - Zakladka Logi w sekcji Integracje (podglad pp_log z paginacja, sortowaniem, filtrami)",
"version": "0.310",
"files": {
"added": [
"admin/templates/integrations/logs.php"
],
"deleted": [
],
"modified": [
"admin/templates/site/main-layout.php",
"autoload/Domain/Integrations/IntegrationsRepository.php",
"autoload/admin/Controllers/IntegrationsController.php"
]
},
"checksum_zip": "sha256:e3b14e239230548aba203a83f01c91b00651e5114e92e162f6da7389c6a92975",
"sql": [
],
"date": "2026-02-23",
"directories_deleted": [
]
}

BIN
updates/0.30/ver_0.311.zip Normal file

Binary file not shown.

View File

@@ -0,0 +1,27 @@
{
"changelog": "FIX - race condition callback płatności Apilo, persistence filtrów tabel admin, poprawki cen zamówień",
"version": "0.311",
"files": {
"added": [
],
"deleted": [
],
"modified": [
"admin/templates/components/table-list.php",
"admin/templates/shop-order/order-details.php",
"autoload/Domain/Order/OrderAdminService.php",
"cron.php",
"templates/shop-order/order-details.php"
]
},
"checksum_zip": "sha256:542f599e844d48bba1378fbe91c06ef00d5487aca56af118ad9c9ea27343ebdb",
"sql": [
],
"date": "2026-02-23",
"directories_deleted": [
]
}

View File

@@ -1,3 +1,12 @@
<b>ver. 0.311 - 23.02.2026</b><br />
FIX - race condition callback płatności Apilo, persistence filtrów tabel admin, poprawki cen zamówień
<hr>
<b>ver. 0.310 - 23.02.2026</b><br />
NEW - Zakladka Logi w sekcji Integracje (podglad pp_log z paginacja, sortowaniem, filtrami)
<hr>
<b>ver. 0.309 - 23.02.2026</b><br />
NEW - ApiloLogger (logowanie operacji Apilo do pp_log), cache-busting CSS/JS w admin panelu, poprawki UI listy produktow, clipboard API
<hr>
<b>ver. 0.308 - 22.02.2026</b><br />
NEW - kolorowe badge statusow zamowien, walidacja hex, sanityzacja HTML transport, optymalizacja SQL
<hr>

View File

@@ -1,5 +1,5 @@
<?
$current_ver = 309;
$current_ver = 312;
for ($i = 1; $i <= $current_ver; $i++)
{