Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe2a77e995 | |||
| f0b1152ab1 | |||
| 44ac25b063 | |||
| ee8459ca2a | |||
| 8e2e070eb7 | |||
| ec4e25946d | |||
| 4f66dbe42c | |||
| 4e720c5689 | |||
| 702e3a94be | |||
| 9a351c16ee | |||
| 4056296dab | |||
| 7158f4d369 | |||
| 1d613d8226 | |||
| 174a85a707 | |||
| 835386a887 | |||
| d2277c6d9d | |||
| 908c997b91 | |||
| 9d3ae9a470 | |||
| 09d266204e | |||
| 8f43f5ab4d | |||
| b17463bcbc | |||
| 76de81bca4 |
@@ -48,7 +48,26 @@
|
||||
"Bash(python3:*)",
|
||||
"Bash(python:*)",
|
||||
"Bash(grep:*)",
|
||||
"Bash(grep ^<b>ver:*)"
|
||||
"Bash(grep ^<b>ver:*)",
|
||||
"Bash(claude mcp:*)",
|
||||
"mcp__serena__get_current_config",
|
||||
"Bash(cd \"C:\\\\visual studio code\\\\projekty\\\\shopPRO\" && npx sass admin/layout/style-scss/style.scss admin/layout/style-css/style.css --no-source-map 2>&1 || sass admin/layout/style-scss/style.scss admin/layout/style-css/style.css --no-source-map 2>&1)",
|
||||
"Bash(echo no 7z:*)",
|
||||
"Bash(cd \"C:/visual studio code/projekty/shopPRO\" && php -r \"\n\\\\$files = [\n 'admin/templates/integrations/logs.php',\n 'admin/templates/site/main-layout.php',\n 'autoload/Domain/Integrations/IntegrationsRepository.php',\n 'autoload/admin/Controllers/IntegrationsController.php',\n];\n\\\\$zipPath = 'updates/0.30/ver_0.310.zip';\nif \\(!is_dir\\('updates/0.30'\\)\\) mkdir\\('updates/0.30', 0777, true\\);\nif \\(file_exists\\(\\\\$zipPath\\)\\) unlink\\(\\\\$zipPath\\);\n\\\\$zip = new ZipArchive\\(\\);\nif \\(\\\\$zip->open\\(\\\\$zipPath, ZipArchive::CREATE\\) !== true\\) { echo 'Cannot create ZIP'; exit\\(1\\); }\nforeach \\(\\\\$files as \\\\$f\\) {\n if \\(file_exists\\(\\\\$f\\)\\) {\n \\\\$zip->addFile\\(\\\\$f, \\\\$f\\);\n echo \\\\\"Added: \\\\$f\\\\n\\\\\";\n } else {\n echo \\\\\"MISSING: \\\\$f\\\\n\\\\\";\n }\n}\n\\\\$zip->close\\(\\);\necho \\\\\"ZIP created: \\\\$zipPath \\(\\\\\".filesize\\(\\\\$zipPath\\).\\\\\" bytes\\)\\\\n\\\\\";\n\" 2>&1)",
|
||||
"Bash(where jar:*)",
|
||||
"Bash(echo php not found:*)",
|
||||
"Bash(/c/xampp/php/php:*)",
|
||||
"Bash(curl:*)",
|
||||
"Bash(cat:*)",
|
||||
"Bash(rm -rf \"/c/visual studio code/projekty/shopPRO/temp/temp_313\" && cd \"/c/visual studio code/projekty/shopPRO\" && powershell -File ./build-update.ps1 -FromTag v0.312 -ToTag v0.313 -ChangelogEntry \"FIX - sync płatności Apilo \\(int cast na apilo_order_id PPxxxxxx dawał 0\\) + logowanie decyzji sync do pp_log\" 2>&1)",
|
||||
"Bash(which php:*)",
|
||||
"mcp__serena__replace_symbol_body",
|
||||
"mcp__serena__insert_after_symbol",
|
||||
"Bash(php:*)",
|
||||
"Bash(rm -rf \"C:/visual studio code/projekty/shopPRO/temp/temp_314\" && cd \"C:/visual studio code/projekty/shopPRO\" && powershell -ExecutionPolicy Bypass -File build-update.ps1 -FromTag v0.313 -ToTag v0.314 -ChangelogEntry \"FIX - naprawa globalnej wyszukiwarki admin \\(Content-Type, Cache-Control, POST, try/catch\\), NEW - title strony z numerem zamówienia\" 2>&1)",
|
||||
"mcp__serena__initial_instructions",
|
||||
"mcp__serena__list_memories",
|
||||
"mcp__serena__find_referencing_symbols"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -27,6 +27,7 @@ project_name: "shopPRO"
|
||||
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
|
||||
languages:
|
||||
- typescript
|
||||
- php
|
||||
|
||||
# the encoding used by text files in the project
|
||||
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
|
||||
|
||||
6
.vscode/ftp-kr.json
vendored
6
.vscode/ftp-kr.json
vendored
@@ -14,6 +14,10 @@
|
||||
".git",
|
||||
".svn",
|
||||
"/.vscode",
|
||||
"/temp/*"
|
||||
"/temp",
|
||||
"/.serena",
|
||||
"/.claude",
|
||||
"/docs",
|
||||
"/tests"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ composer test
|
||||
|
||||
PHPUnit 9.6 via `phpunit.phar`. Bootstrap: `tests/bootstrap.php`. Config: `phpunit.xml`.
|
||||
|
||||
Current suite: **758 tests, 2135 assertions**.
|
||||
Current suite: **765 tests, 2153 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.
|
||||
|
||||
@@ -91,6 +91,20 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- API key -->
|
||||
<div class="form-group">
|
||||
<label class="col-lg-3 control-label" for="inputDefault">API key</label>
|
||||
<div class="col-lg-9">
|
||||
<div class="bs-component">
|
||||
<div class="input-group">
|
||||
<input class="form-control" type="text" id="api_key" name="api_key" placeholder="" value="<?= $this -> settings['api_key'];?>">
|
||||
<span class="input-group-addon cursor" field-id="api_key">
|
||||
<i class="fa fa-save"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
|
||||
@@ -123,4 +137,4 @@
|
||||
});
|
||||
})
|
||||
});
|
||||
</script>
|
||||
</script>
|
||||
|
||||
@@ -3,6 +3,7 @@ $orderId = (int)($this -> order['id'] ?? 0);
|
||||
?>
|
||||
|
||||
<div class="site-title">Szczegóły zamówienia: <?= htmlspecialchars((string)($this -> order['number'] ?? ''), ENT_QUOTES, 'UTF-8');?></div>
|
||||
<script>document.title = 'Zamówienie <?= htmlspecialchars((string)($this -> order['number'] ?? ''), ENT_QUOTES, 'UTF-8');?> - shopPro';</script>
|
||||
|
||||
<div class="od-actions mb15">
|
||||
<a href="/admin/shop_order/list/" class="btn btn-dark btn-sm">
|
||||
@@ -89,6 +90,19 @@ $orderId = (int)($this -> order['id'] ?? 0);
|
||||
<div>
|
||||
<b><?= $this -> order[ 'payment_method' ];?> </b>
|
||||
</div>
|
||||
<? if ( !empty($this -> order['apilo_order_id']) ):?>
|
||||
<br/>
|
||||
<div>
|
||||
<i class="fa fa-cloud"></i> Apilo: <b style="color: #27ae60;">tak</b>
|
||||
— ID: <b id="order-apilo-id"><?= htmlspecialchars((string)$this -> order['apilo_order_id'], ENT_QUOTES, 'UTF-8');?></b>
|
||||
<i class="fa fa-copy" onclick="copyToClipboard( 'order-apilo-id' ); return false;"></i>
|
||||
</div>
|
||||
<? else:?>
|
||||
<br/>
|
||||
<div>
|
||||
<i class="fa fa-cloud"></i> Apilo: <b style="color: #c0392b;">nie</b>
|
||||
</div>
|
||||
<? endif;?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="paid-status panel">
|
||||
|
||||
@@ -322,7 +322,7 @@
|
||||
|
||||
$.ajax({
|
||||
url: '/admin/settings/globalSearchAjax/',
|
||||
type: 'GET',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { q: phrase },
|
||||
success: function(response) {
|
||||
@@ -333,8 +333,12 @@
|
||||
|
||||
renderResults(response.items || []);
|
||||
},
|
||||
error: function() {
|
||||
$results.html('<div class="admin-global-search-empty">Błąd połączenia</div>').addClass('open');
|
||||
error: function(xhr) {
|
||||
var msg = 'Błąd połączenia';
|
||||
if (xhr.status === 200) {
|
||||
msg = 'Błąd parsowania odpowiedzi';
|
||||
}
|
||||
$results.html('<div class="admin-global-search-empty">' + msg + '</div>').addClass('open');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
45
api.php
45
api.php
@@ -47,6 +47,43 @@ if ( !$isApiRequest )
|
||||
}
|
||||
}
|
||||
|
||||
// --- API routing (ordersPRO) ---
|
||||
if ( $isApiRequest )
|
||||
{
|
||||
if ( !headers_sent() )
|
||||
header( 'Content-Type: application/json; charset=utf-8' );
|
||||
|
||||
try
|
||||
{
|
||||
$mdb = new medoo( [
|
||||
'database_type' => 'mysql',
|
||||
'database_name' => $database[ 'name' ],
|
||||
'server' => $database[ 'host' ],
|
||||
'username' => $database[ 'user' ],
|
||||
'password' => $database[ 'password' ],
|
||||
'charset' => 'utf8'
|
||||
] );
|
||||
|
||||
$settingsRepo = new \Domain\Settings\SettingsRepository( $mdb );
|
||||
$router = new \api\ApiRouter( $mdb, $settingsRepo );
|
||||
$router->handle();
|
||||
}
|
||||
catch ( \Throwable $e )
|
||||
{
|
||||
if ( !headers_sent() )
|
||||
header( 'Content-Type: application/json; charset=utf-8' );
|
||||
|
||||
http_response_code( 500 );
|
||||
echo json_encode( [
|
||||
'status' => 'error',
|
||||
'code' => 'INTERNAL_ERROR',
|
||||
'message' => 'Internal server error'
|
||||
], JSON_UNESCAPED_UNICODE );
|
||||
}
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
$mdb = new medoo( [
|
||||
'database_type' => 'mysql',
|
||||
'database_name' => $database[ 'name' ],
|
||||
@@ -59,14 +96,6 @@ $mdb = new medoo( [
|
||||
$settingsRepo = new \Domain\Settings\SettingsRepository( $mdb );
|
||||
$settings = $settingsRepo->allSettings();
|
||||
|
||||
// --- API routing (ordersPRO) ---
|
||||
if ( $isApiRequest )
|
||||
{
|
||||
$router = new \api\ApiRouter( $mdb, $settingsRepo );
|
||||
$router->handle();
|
||||
exit;
|
||||
}
|
||||
|
||||
// --- Ekomi CSV export ---
|
||||
if ( \Shared\Helpers\Helpers::get( 'ekomi_csv' ) )
|
||||
{
|
||||
|
||||
@@ -48,7 +48,7 @@ class AttributeRepository
|
||||
FROM pp_shop_attributes AS sa
|
||||
WHERE {$whereSql}
|
||||
";
|
||||
$stmtCount = $this->db->query($sqlCount, $params);
|
||||
$stmtCount = $this->db->query($sqlCount, $whereData['params']);
|
||||
$countRows = $stmtCount ? $stmtCount->fetchAll() : [];
|
||||
$total = isset($countRows[0][0]) ? (int)$countRows[0][0] : 0;
|
||||
|
||||
@@ -655,6 +655,95 @@ class AttributeRepository
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find existing attribute by name/type or create a new one for API integration.
|
||||
*
|
||||
* @return array{id:int,created:bool}|null
|
||||
*/
|
||||
public function ensureAttributeForApi(string $name, int $type = 0, string $langId = 'pl'): ?array
|
||||
{
|
||||
$normalizedName = trim($name);
|
||||
$normalizedLangId = trim($langId) !== '' ? trim($langId) : 'pl';
|
||||
$normalizedType = $this->toTypeValue($type);
|
||||
if ($normalizedName === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$existingId = $this->findAttributeIdByNameAndType($normalizedName, $normalizedType);
|
||||
if ($existingId > 0) {
|
||||
return ['id' => $existingId, 'created' => false];
|
||||
}
|
||||
|
||||
$this->db->insert('pp_shop_attributes', [
|
||||
'status' => 1,
|
||||
'type' => $normalizedType,
|
||||
'o' => $this->nextOrder(),
|
||||
]);
|
||||
$attributeId = (int) $this->db->id();
|
||||
if ($attributeId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->db->insert('pp_shop_attributes_langs', [
|
||||
'attribute_id' => $attributeId,
|
||||
'lang_id' => $normalizedLangId,
|
||||
'name' => $normalizedName,
|
||||
]);
|
||||
|
||||
$this->clearTempAndCache();
|
||||
$this->clearFrontCache($attributeId, 'frontAttributeDetails');
|
||||
|
||||
return ['id' => $attributeId, 'created' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Find existing value by name within attribute or create a new one for API integration.
|
||||
*
|
||||
* @return array{id:int,created:bool}|null
|
||||
*/
|
||||
public function ensureAttributeValueForApi(int $attributeId, string $name, string $langId = 'pl'): ?array
|
||||
{
|
||||
$normalizedName = trim($name);
|
||||
$normalizedLangId = trim($langId) !== '' ? trim($langId) : 'pl';
|
||||
$attributeId = max(0, $attributeId);
|
||||
|
||||
if ($attributeId <= 0 || $normalizedName === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$attributeExists = (int) $this->db->count('pp_shop_attributes', ['id' => $attributeId]) > 0;
|
||||
if (!$attributeExists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$existingId = $this->findAttributeValueIdByName($attributeId, $normalizedName);
|
||||
if ($existingId > 0) {
|
||||
return ['id' => $existingId, 'created' => false];
|
||||
}
|
||||
|
||||
$this->db->insert('pp_shop_attributes_values', [
|
||||
'attribute_id' => $attributeId,
|
||||
'impact_on_the_price' => null,
|
||||
'is_default' => 0,
|
||||
]);
|
||||
$valueId = (int) $this->db->id();
|
||||
if ($valueId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->db->insert('pp_shop_attributes_values_langs', [
|
||||
'value_id' => $valueId,
|
||||
'lang_id' => $normalizedLangId,
|
||||
'name' => $normalizedName,
|
||||
'value' => null,
|
||||
]);
|
||||
|
||||
$this->clearTempAndCache();
|
||||
$this->clearFrontCache($valueId, 'frontValueDetails');
|
||||
|
||||
return ['id' => $valueId, 'created' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{sql: string, params: array<string, mixed>}
|
||||
*/
|
||||
@@ -972,6 +1061,52 @@ class AttributeRepository
|
||||
return $this->defaultLangId;
|
||||
}
|
||||
|
||||
private function findAttributeIdByNameAndType(string $name, int $type): int
|
||||
{
|
||||
$statement = $this->db->query(
|
||||
'SELECT sa.id
|
||||
FROM pp_shop_attributes sa
|
||||
INNER JOIN pp_shop_attributes_langs sal ON sal.attribute_id = sa.id
|
||||
WHERE sa.type = :type
|
||||
AND LOWER(TRIM(sal.name)) = LOWER(TRIM(:name))
|
||||
ORDER BY sa.id ASC
|
||||
LIMIT 1',
|
||||
[
|
||||
':type' => $type,
|
||||
':name' => $name,
|
||||
]
|
||||
);
|
||||
if (!$statement) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$id = $statement->fetchColumn();
|
||||
return $id === false ? 0 : (int) $id;
|
||||
}
|
||||
|
||||
private function findAttributeValueIdByName(int $attributeId, string $name): int
|
||||
{
|
||||
$statement = $this->db->query(
|
||||
'SELECT sav.id
|
||||
FROM pp_shop_attributes_values sav
|
||||
INNER JOIN pp_shop_attributes_values_langs savl ON savl.value_id = sav.id
|
||||
WHERE sav.attribute_id = :attribute_id
|
||||
AND LOWER(TRIM(savl.name)) = LOWER(TRIM(:name))
|
||||
ORDER BY sav.id ASC
|
||||
LIMIT 1',
|
||||
[
|
||||
':attribute_id' => $attributeId,
|
||||
':name' => $name,
|
||||
]
|
||||
);
|
||||
if (!$statement) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$id = $statement->fetchColumn();
|
||||
return $id === false ? 0 : (int) $id;
|
||||
}
|
||||
|
||||
// ── Frontend methods ──────────────────────────────────────────
|
||||
|
||||
public function frontAttributeDetails(int $attributeId, string $langId): array
|
||||
|
||||
@@ -668,15 +668,12 @@ class IntegrationsRepository
|
||||
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 = new \medoo( [
|
||||
'database_type' => 'mysql',
|
||||
'database_name' => $settings['db_name'],
|
||||
'server' => $settings['db_host'],
|
||||
'username' => $settings['db_user'],
|
||||
'password' => $settings['db_password'],
|
||||
'charset' => 'utf8'
|
||||
] );
|
||||
$mdb2 = $this->shopproDb( $settings );
|
||||
|
||||
$product = $mdb2->get( 'pp_shop_products', '*', [ 'id' => $productId ] );
|
||||
if ( !$product )
|
||||
@@ -700,6 +697,7 @@ class IntegrationsRepository
|
||||
'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();
|
||||
@@ -729,6 +727,20 @@ class IntegrationsRepository
|
||||
'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,
|
||||
] );
|
||||
}
|
||||
}
|
||||
@@ -759,6 +771,7 @@ class IntegrationsRepository
|
||||
$this->db->insert( 'pp_shop_products_images', [
|
||||
'product_id' => $newProductId,
|
||||
'src' => '/upload/product_images/product_' . $newProductId . '/' . $imageName,
|
||||
'alt' => $image['alt'] ?? '',
|
||||
'o' => $image['o'],
|
||||
] );
|
||||
}
|
||||
@@ -766,4 +779,28 @@ class IntegrationsRepository
|
||||
|
||||
return [ 'success' => true, 'message' => 'Produkt został zaimportowany.' ];
|
||||
}
|
||||
|
||||
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'
|
||||
] );
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -393,17 +393,38 @@ class OrderAdminService
|
||||
global $mdb;
|
||||
|
||||
if ($orderId <= 0) {
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$mdb,
|
||||
'resend_order',
|
||||
$orderId,
|
||||
'Nieprawidlowe ID zamowienia (orderId <= 0)',
|
||||
['order_id' => $orderId]
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
$order = $this->orders->findForAdmin($orderId);
|
||||
if (empty($order) || empty($order['apilo_order_id'])) {
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$mdb,
|
||||
'resend_order',
|
||||
$orderId,
|
||||
'Brak zamowienia lub brak apilo_order_id',
|
||||
['order_found' => !empty($order), 'apilo_order_id' => $order['apilo_order_id'] ?? null]
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
$integrationsRepository = new \Domain\Integrations\IntegrationsRepository( $mdb );
|
||||
$accessToken = $integrationsRepository -> apiloGetAccessToken();
|
||||
if (!$accessToken) {
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$mdb,
|
||||
'resend_order',
|
||||
$orderId,
|
||||
'Nie udalo sie uzyskac tokenu Apilo (access token)',
|
||||
['apilo_order_id' => $order['apilo_order_id']]
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -641,6 +662,17 @@ class OrderAdminService
|
||||
$apilo_settings = $integrationsRepository->getSettings('apilo');
|
||||
|
||||
if (!$apilo_settings['enabled'] || !$apilo_settings['access-token'] || !$apilo_settings['sync_orders']) {
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$db,
|
||||
'payment_sync',
|
||||
(int)$order['id'],
|
||||
'Pominięto sync płatności — Apilo wyłączone lub brak tokenu/sync_orders',
|
||||
[
|
||||
'enabled' => $apilo_settings['enabled'] ?? false,
|
||||
'has_token' => !empty($apilo_settings['access-token']),
|
||||
'sync_orders' => $apilo_settings['sync_orders'] ?? false,
|
||||
]
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -650,8 +682,22 @@ class OrderAdminService
|
||||
|
||||
if (!$order['apilo_order_id']) {
|
||||
// Zamówienie jeszcze nie wysłane do Apilo — kolejkuj sync płatności na później
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$db,
|
||||
'payment_sync',
|
||||
(int)$order['id'],
|
||||
'Brak apilo_order_id — płatność zakolejkowana do sync',
|
||||
['apilo_order_id' => $order['apilo_order_id'] ?? null]
|
||||
);
|
||||
self::queueApiloSync((int)$order['id'], true, null, 'awaiting_apilo_order');
|
||||
} elseif (!$this->syncApiloPayment($order)) {
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$db,
|
||||
'payment_sync',
|
||||
(int)$order['id'],
|
||||
'Sync płatności nieudany — zakolejkowano ponowną próbę',
|
||||
['apilo_order_id' => $order['apilo_order_id']]
|
||||
);
|
||||
self::queueApiloSync((int)$order['id'], true, null, 'payment_sync_failed');
|
||||
}
|
||||
}
|
||||
@@ -665,6 +711,18 @@ class OrderAdminService
|
||||
$apilo_settings = $integrationsRepository->getSettings('apilo');
|
||||
|
||||
if (!$apilo_settings['enabled'] || !$apilo_settings['access-token'] || !$apilo_settings['sync_orders']) {
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$db,
|
||||
'status_sync',
|
||||
(int)$order['id'],
|
||||
'Pominięto sync statusu — Apilo wyłączone lub brak tokenu/sync_orders',
|
||||
[
|
||||
'target_status' => $status,
|
||||
'enabled' => $apilo_settings['enabled'] ?? false,
|
||||
'has_token' => !empty($apilo_settings['access-token']),
|
||||
'sync_orders' => $apilo_settings['sync_orders'] ?? false,
|
||||
]
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -674,8 +732,22 @@ class OrderAdminService
|
||||
|
||||
if (!$order['apilo_order_id']) {
|
||||
// Zamówienie jeszcze nie wysłane do Apilo — kolejkuj sync statusu na później
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$db,
|
||||
'status_sync',
|
||||
(int)$order['id'],
|
||||
'Brak apilo_order_id — status zakolejkowany do sync',
|
||||
['apilo_order_id' => $order['apilo_order_id'] ?? null, 'target_status' => $status]
|
||||
);
|
||||
self::queueApiloSync((int)$order['id'], false, $status, 'awaiting_apilo_order');
|
||||
} elseif (!$this->syncApiloStatus($order, $status)) {
|
||||
\Domain\Integrations\ApiloLogger::log(
|
||||
$db,
|
||||
'status_sync',
|
||||
(int)$order['id'],
|
||||
'Sync statusu nieudany — zakolejkowano ponowną próbę',
|
||||
['apilo_order_id' => $order['apilo_order_id'], 'target_status' => $status]
|
||||
);
|
||||
self::queueApiloSync((int)$order['id'], false, $status, 'status_sync_failed');
|
||||
}
|
||||
}
|
||||
@@ -687,7 +759,7 @@ class OrderAdminService
|
||||
$db = $this->orders->getDb();
|
||||
$integrationsRepository = new \Domain\Integrations\IntegrationsRepository($db);
|
||||
|
||||
if (!(int)$order['apilo_order_id']) {
|
||||
if (empty($order['apilo_order_id'])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -754,7 +826,7 @@ class OrderAdminService
|
||||
$db = $this->orders->getDb();
|
||||
$integrationsRepository = new \Domain\Integrations\IntegrationsRepository($db);
|
||||
|
||||
if (!(int)$order['apilo_order_id']) {
|
||||
if (empty($order['apilo_order_id'])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -357,4 +357,34 @@ class ProducerRepository
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Znajdź producenta po nazwie lub utwórz nowego (dla API).
|
||||
*
|
||||
* @return array{id: int, created: bool}
|
||||
*/
|
||||
public function ensureProducerForApi(string $name): array
|
||||
{
|
||||
$name = trim($name);
|
||||
if ($name === '') {
|
||||
return ['id' => 0, 'created' => false];
|
||||
}
|
||||
|
||||
$existing = $this->db->get('pp_shop_producer', 'id', ['name' => $name]);
|
||||
if (!empty($existing)) {
|
||||
return ['id' => (int)$existing, 'created' => false];
|
||||
}
|
||||
|
||||
$this->db->insert('pp_shop_producer', [
|
||||
'name' => $name,
|
||||
'status' => 1,
|
||||
'img' => null,
|
||||
]);
|
||||
$id = (int)$this->db->id();
|
||||
if ($id <= 0) {
|
||||
return ['id' => 0, 'created' => false];
|
||||
}
|
||||
|
||||
return ['id' => $id, 'created' => true];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -657,6 +657,7 @@ class ProductRepository
|
||||
'set_id' => $product['set_id'] !== null ? (int)$product['set_id'] : null,
|
||||
'product_unit_id' => $product['product_unit_id'] !== null ? (int)$product['product_unit_id'] : null,
|
||||
'producer_id' => $product['producer_id'] !== null ? (int)$product['producer_id'] : null,
|
||||
'producer_name' => $this->resolveProducerName($product['producer_id']),
|
||||
'date_add' => $product['date_add'],
|
||||
'date_modify' => $product['date_modify'],
|
||||
];
|
||||
@@ -682,6 +683,7 @@ class ProductRepository
|
||||
'tab_name_2' => $lang['tab_name_2'],
|
||||
'tab_description_2' => $lang['tab_description_2'],
|
||||
'canonical' => $lang['canonical'],
|
||||
'security_information' => $lang['security_information'] ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -733,6 +735,19 @@ class ProductRepository
|
||||
}
|
||||
}
|
||||
|
||||
// Custom fields (Dodatkowe pola)
|
||||
$customFields = $this->db->select('pp_shop_products_custom_fields', ['name', 'type', 'is_required'], ['id_product' => $id]);
|
||||
$result['custom_fields'] = [];
|
||||
if (is_array($customFields)) {
|
||||
foreach ($customFields as $cf) {
|
||||
$result['custom_fields'][] = [
|
||||
'name' => $cf['name'],
|
||||
'type' => !empty($cf['type']) ? $cf['type'] : 'text',
|
||||
'is_required' => $cf['is_required'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Variants (only for parent products)
|
||||
if (empty($product['parent_id'])) {
|
||||
$result['variants'] = $this->findVariantsForApi($id);
|
||||
@@ -1116,6 +1131,21 @@ class ProductRepository
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zwraca nazwę producenta po ID (null jeśli brak).
|
||||
*
|
||||
* @param mixed $producerId
|
||||
* @return string|null
|
||||
*/
|
||||
private function resolveProducerName($producerId): ?string
|
||||
{
|
||||
if (empty($producerId)) {
|
||||
return null;
|
||||
}
|
||||
$name = $this->db->get('pp_shop_producer', 'name', ['id' => (int)$producerId]);
|
||||
return ($name !== false && $name !== null) ? (string)$name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Szczegóły produktu (admin) — zastępuje factory product_details().
|
||||
*/
|
||||
@@ -1239,7 +1269,7 @@ class ProductRepository
|
||||
|
||||
$productData = [
|
||||
'date_modify' => date( 'Y-m-d H:i:s' ),
|
||||
'modify_by' => $userId,
|
||||
'modify_by' => $userId !== null ? (int) $userId : 0,
|
||||
'status' => ( $d['status'] ?? '' ) === 'on' ? 1 : 0,
|
||||
'price_netto' => $this->nullIfEmpty( $d['price_netto'] ?? null ),
|
||||
'price_brutto' => $this->nullIfEmpty( $d['price_brutto'] ?? null ),
|
||||
|
||||
@@ -71,6 +71,7 @@ class SettingsRepository
|
||||
'infinitescroll' => $this->isEnabled($values['infinitescroll'] ?? null) ? 1 : 0,
|
||||
'own_gtm_js' => $values['own_gtm_js'] ?? '',
|
||||
'own_gtm_html' => $values['own_gtm_html'] ?? '',
|
||||
'api_key' => $values['api_key'] ?? '',
|
||||
];
|
||||
|
||||
$warehouseMessageZero = $values['warehouse_message_zero'] ?? [];
|
||||
|
||||
@@ -73,26 +73,45 @@ class SettingsController
|
||||
*/
|
||||
public function globalSearchAjax(): void
|
||||
{
|
||||
global $mdb;
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
|
||||
$phrase = trim((string)\Shared\Helpers\Helpers::get('q'));
|
||||
if ($phrase === '' || mb_strlen($phrase) < 2) {
|
||||
try {
|
||||
$this->executeGlobalSearch();
|
||||
} catch (\Throwable $e) {
|
||||
echo json_encode([
|
||||
'status' => 'ok',
|
||||
'status' => 'error',
|
||||
'items' => [],
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
exit;
|
||||
}
|
||||
|
||||
private function executeGlobalSearch(): void
|
||||
{
|
||||
global $mdb;
|
||||
|
||||
$phrase = isset($_REQUEST['q']) ? trim((string)$_REQUEST['q']) : '';
|
||||
if ($phrase === '' || mb_strlen($phrase) < 2) {
|
||||
echo json_encode(['status' => 'ok', 'items' => []]);
|
||||
return;
|
||||
}
|
||||
|
||||
$phrase = mb_substr($phrase, 0, 120);
|
||||
$phraseNormalized = preg_replace('/\s+/', ' ', $phrase);
|
||||
$phraseNormalized = trim((string)$phraseNormalized);
|
||||
$phraseNormalized = trim((string)preg_replace('/\s+/', ' ', $phrase));
|
||||
$like = '%' . $phrase . '%';
|
||||
$likeNormalized = '%' . $phraseNormalized . '%';
|
||||
|
||||
$items = [];
|
||||
$defaultLang = (string)$this->languagesRepository->defaultLanguage();
|
||||
|
||||
$defaultLang = '1';
|
||||
try {
|
||||
$defaultLang = (string)$this->languagesRepository->defaultLanguage();
|
||||
} catch (\Throwable $e) {
|
||||
// fallback to '1'
|
||||
}
|
||||
|
||||
// --- Produkty ---
|
||||
try {
|
||||
$productStmt = $mdb->query(
|
||||
'SELECT '
|
||||
@@ -115,7 +134,10 @@ class SettingsController
|
||||
$productStmt = false;
|
||||
}
|
||||
|
||||
$productRows = $productStmt ? $productStmt->fetchAll() : [];
|
||||
$productRows = ($productStmt && method_exists($productStmt, 'fetchAll'))
|
||||
? $productStmt->fetchAll(\PDO::FETCH_ASSOC)
|
||||
: [];
|
||||
|
||||
if (is_array($productRows)) {
|
||||
foreach ($productRows as $row) {
|
||||
$productId = (int)($row['id'] ?? 0);
|
||||
@@ -147,6 +169,7 @@ class SettingsController
|
||||
}
|
||||
}
|
||||
|
||||
// --- Zamowienia ---
|
||||
try {
|
||||
$orderStmt = $mdb->query(
|
||||
'SELECT '
|
||||
@@ -178,7 +201,10 @@ class SettingsController
|
||||
$orderStmt = false;
|
||||
}
|
||||
|
||||
$orderRows = $orderStmt ? $orderStmt->fetchAll() : [];
|
||||
$orderRows = ($orderStmt && method_exists($orderStmt, 'fetchAll'))
|
||||
? $orderStmt->fetchAll(\PDO::FETCH_ASSOC)
|
||||
: [];
|
||||
|
||||
if (is_array($orderRows)) {
|
||||
foreach ($orderRows as $row) {
|
||||
$orderId = (int)($row['id'] ?? 0);
|
||||
@@ -214,11 +240,12 @@ class SettingsController
|
||||
}
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'status' => 'ok',
|
||||
'items' => array_slice($items, 0, 20),
|
||||
]);
|
||||
exit;
|
||||
$json = json_encode(['status' => 'ok', 'items' => array_slice($items, 0, 20)]);
|
||||
if ($json === false) {
|
||||
echo json_encode(['status' => 'ok', 'items' => []], JSON_UNESCAPED_UNICODE);
|
||||
return;
|
||||
}
|
||||
echo $json;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -444,8 +471,7 @@ class SettingsController
|
||||
'label' => 'Htaccess cache',
|
||||
'tab' => 'system',
|
||||
]),
|
||||
FormField::text('api_key', [
|
||||
'label' => 'Klucz API (ordersPRO)',
|
||||
FormField::custom('api_key', $this->renderApiKeyField($data['api_key'] ?? ''), [
|
||||
'tab' => 'system',
|
||||
]),
|
||||
|
||||
@@ -533,4 +559,23 @@ class SettingsController
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function renderApiKeyField(string $value): string
|
||||
{
|
||||
$escaped = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
|
||||
|
||||
$js = "var c='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',"
|
||||
. "k='';for(var i=0;i<32;i++){k+=c.charAt(Math.floor(Math.random()*c.length));}"
|
||||
. "document.getElementById('api_key').value=k;";
|
||||
|
||||
return '<div class="form-group row">'
|
||||
. '<label class="col-lg-4 control-label">Klucz API:</label>'
|
||||
. '<div class="col-lg-8">'
|
||||
. '<div class="input-group">'
|
||||
. '<input type="text" id="api_key" class="form-control" name="api_key" value="' . $escaped . '" />'
|
||||
. '<span class="input-group-addon btn btn-info" onclick="' . htmlspecialchars($js, ENT_QUOTES, 'UTF-8') . '">Generuj</span>'
|
||||
. '</div>'
|
||||
. '</div>'
|
||||
. '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,6 +140,7 @@ class ShopProductController
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ class ApiRouter
|
||||
}
|
||||
|
||||
$controller->$action();
|
||||
} catch (\Exception $e) {
|
||||
} catch (\Throwable $e) {
|
||||
self::sendError('INTERNAL_ERROR', 'Internal server error', 500);
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,8 @@ class ApiRouter
|
||||
$transportRepo = new \Domain\Transport\TransportRepository($db);
|
||||
$paymentRepo = new \Domain\PaymentMethod\PaymentMethodRepository($db);
|
||||
$attrRepo = new \Domain\Attribute\AttributeRepository($db);
|
||||
return new Controllers\DictionariesApiController($statusRepo, $transportRepo, $paymentRepo, $attrRepo);
|
||||
$producerRepo = new \Domain\Producer\ProducerRepository($db);
|
||||
return new Controllers\DictionariesApiController($statusRepo, $transportRepo, $paymentRepo, $attrRepo, $producerRepo);
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ namespace api\Controllers;
|
||||
|
||||
use api\ApiRouter;
|
||||
use Domain\Attribute\AttributeRepository;
|
||||
use Domain\Producer\ProducerRepository;
|
||||
use Domain\ShopStatus\ShopStatusRepository;
|
||||
use Domain\Transport\TransportRepository;
|
||||
use Domain\PaymentMethod\PaymentMethodRepository;
|
||||
@@ -13,17 +14,20 @@ class DictionariesApiController
|
||||
private $transportRepo;
|
||||
private $paymentRepo;
|
||||
private $attrRepo;
|
||||
private $producerRepo;
|
||||
|
||||
public function __construct(
|
||||
ShopStatusRepository $statusRepo,
|
||||
TransportRepository $transportRepo,
|
||||
PaymentMethodRepository $paymentRepo,
|
||||
AttributeRepository $attrRepo
|
||||
AttributeRepository $attrRepo,
|
||||
ProducerRepository $producerRepo
|
||||
) {
|
||||
$this->statusRepo = $statusRepo;
|
||||
$this->transportRepo = $transportRepo;
|
||||
$this->paymentRepo = $paymentRepo;
|
||||
$this->attrRepo = $attrRepo;
|
||||
$this->producerRepo = $producerRepo;
|
||||
}
|
||||
|
||||
public function statuses(): void
|
||||
@@ -94,4 +98,111 @@ class DictionariesApiController
|
||||
|
||||
ApiRouter::sendSuccess($attributes);
|
||||
}
|
||||
|
||||
public function ensure_attribute(): void
|
||||
{
|
||||
if (!ApiRouter::requireMethod('POST')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$body = ApiRouter::getJsonBody();
|
||||
if (!is_array($body)) {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid JSON body', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$name = trim((string) ($body['name'] ?? ''));
|
||||
if ($name === '') {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing name', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$type = (int) ($body['type'] ?? 0);
|
||||
$lang = trim((string) ($body['lang'] ?? 'pl'));
|
||||
if ($lang === '') {
|
||||
$lang = 'pl';
|
||||
}
|
||||
|
||||
$result = $this->attrRepo->ensureAttributeForApi($name, $type, $lang);
|
||||
if (!is_array($result) || (int) ($result['id'] ?? 0) <= 0) {
|
||||
ApiRouter::sendError('INTERNAL_ERROR', 'Failed to ensure attribute', 500);
|
||||
return;
|
||||
}
|
||||
|
||||
ApiRouter::sendSuccess([
|
||||
'id' => (int) ($result['id'] ?? 0),
|
||||
'created' => !empty($result['created']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function ensure_attribute_value(): void
|
||||
{
|
||||
if (!ApiRouter::requireMethod('POST')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$body = ApiRouter::getJsonBody();
|
||||
if (!is_array($body)) {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid JSON body', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$attributeId = (int) ($body['attribute_id'] ?? 0);
|
||||
if ($attributeId <= 0) {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid attribute_id', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$name = trim((string) ($body['name'] ?? ''));
|
||||
if ($name === '') {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing name', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$lang = trim((string) ($body['lang'] ?? 'pl'));
|
||||
if ($lang === '') {
|
||||
$lang = 'pl';
|
||||
}
|
||||
|
||||
$result = $this->attrRepo->ensureAttributeValueForApi($attributeId, $name, $lang);
|
||||
if (!is_array($result) || (int) ($result['id'] ?? 0) <= 0) {
|
||||
ApiRouter::sendError('INTERNAL_ERROR', 'Failed to ensure attribute value', 500);
|
||||
return;
|
||||
}
|
||||
|
||||
ApiRouter::sendSuccess([
|
||||
'id' => (int) ($result['id'] ?? 0),
|
||||
'created' => !empty($result['created']),
|
||||
]);
|
||||
}
|
||||
|
||||
public function ensure_producer(): void
|
||||
{
|
||||
if (!ApiRouter::requireMethod('POST')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$body = ApiRouter::getJsonBody();
|
||||
if (!is_array($body)) {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid JSON body', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$name = trim((string) ($body['name'] ?? ''));
|
||||
if ($name === '') {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing name', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$result = $this->producerRepo->ensureProducerForApi($name);
|
||||
if ((int) ($result['id'] ?? 0) <= 0) {
|
||||
ApiRouter::sendError('INTERNAL_ERROR', 'Failed to ensure producer', 500);
|
||||
return;
|
||||
}
|
||||
|
||||
ApiRouter::sendSuccess([
|
||||
'id' => (int) ($result['id'] ?? 0),
|
||||
'created' => !empty($result['created']),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +296,95 @@ class ProductsApiController
|
||||
ApiRouter::sendSuccess(['id' => $variantId, 'deleted' => true]);
|
||||
}
|
||||
|
||||
public function upload_image(): void
|
||||
{
|
||||
if (!ApiRouter::requireMethod('POST')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$body = ApiRouter::getJsonBody();
|
||||
if ($body === null) {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid JSON body', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$productId = (int)($body['id'] ?? 0);
|
||||
if ($productId <= 0) {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid product id', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$product = $this->productRepo->find($productId);
|
||||
if ($product === null) {
|
||||
ApiRouter::sendError('NOT_FOUND', 'Product not found', 404);
|
||||
return;
|
||||
}
|
||||
|
||||
$fileName = trim((string)($body['file_name'] ?? ''));
|
||||
$base64 = (string)($body['content_base64'] ?? '');
|
||||
if ($fileName === '' || $base64 === '') {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Missing file_name or content_base64', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$binary = base64_decode($base64, true);
|
||||
if ($binary === false) {
|
||||
ApiRouter::sendError('BAD_REQUEST', 'Invalid content_base64 payload', 400);
|
||||
return;
|
||||
}
|
||||
|
||||
$safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', basename($fileName));
|
||||
if ($safeName === '' || $safeName === null) {
|
||||
$safeName = 'image_' . md5((string)microtime(true)) . '.jpg';
|
||||
}
|
||||
|
||||
$baseDir = '../upload/product_images/product_' . $productId;
|
||||
if (!is_dir($baseDir) && !mkdir($baseDir, 0775, true) && !is_dir($baseDir)) {
|
||||
ApiRouter::sendError('INTERNAL_ERROR', 'Failed to create target directory', 500);
|
||||
return;
|
||||
}
|
||||
|
||||
$targetPath = $baseDir . '/' . $safeName;
|
||||
if (is_file($targetPath)) {
|
||||
$name = pathinfo($safeName, PATHINFO_FILENAME);
|
||||
$ext = pathinfo($safeName, PATHINFO_EXTENSION);
|
||||
$targetPath = $baseDir . '/' . $name . '_' . substr(md5($safeName . microtime(true)), 0, 8) . ($ext !== '' ? '.' . $ext : '');
|
||||
}
|
||||
|
||||
if (file_put_contents($targetPath, $binary) === false) {
|
||||
ApiRouter::sendError('INTERNAL_ERROR', 'Failed to save image file', 500);
|
||||
return;
|
||||
}
|
||||
|
||||
$src = '/upload/product_images/product_' . $productId . '/' . basename($targetPath);
|
||||
$alt = (string)($body['alt'] ?? '');
|
||||
$position = isset($body['o']) ? (int)$body['o'] : null;
|
||||
|
||||
$db = $GLOBALS['mdb'] ?? null;
|
||||
if (!$db) {
|
||||
ApiRouter::sendError('INTERNAL_ERROR', 'Database not available', 500);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($position === null) {
|
||||
$max = $db->max('pp_shop_products_images', 'o', ['product_id' => $productId]);
|
||||
$position = (int)$max + 1;
|
||||
}
|
||||
|
||||
$db->insert('pp_shop_products_images', [
|
||||
'product_id' => $productId,
|
||||
'src' => $src,
|
||||
'alt' => $alt,
|
||||
'o' => $position,
|
||||
]);
|
||||
|
||||
ApiRouter::sendSuccess([
|
||||
'src' => $src,
|
||||
'alt' => $alt,
|
||||
'o' => $position,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mapuje dane z JSON API na format oczekiwany przez saveProduct().
|
||||
*
|
||||
@@ -339,6 +428,11 @@ class ProductsApiController
|
||||
}
|
||||
}
|
||||
|
||||
// saveProduct() traktuje float 0.00 jako "puste", ale cena 0 musi pozostać jawnie ustawiona.
|
||||
if (isset($d['price_brutto']) && is_numeric($d['price_brutto']) && (float)$d['price_brutto'] === 0.0) {
|
||||
$d['price_brutto'] = '0';
|
||||
}
|
||||
|
||||
// String fields — direct mapping
|
||||
$stringFields = [
|
||||
'sku', 'ean', 'custom_label_0', 'custom_label_1', 'custom_label_2',
|
||||
@@ -403,6 +497,21 @@ class ProductsApiController
|
||||
$d['products_related'] = $body['products_related'];
|
||||
}
|
||||
|
||||
// Custom fields (Dodatkowe pola)
|
||||
if (isset($body['custom_fields']) && is_array($body['custom_fields'])) {
|
||||
$d['custom_field_name'] = [];
|
||||
$d['custom_field_type'] = [];
|
||||
$d['custom_field_required'] = [];
|
||||
foreach ($body['custom_fields'] as $cf) {
|
||||
if (!is_array($cf) || empty($cf['name'])) {
|
||||
continue;
|
||||
}
|
||||
$d['custom_field_name'][] = (string)$cf['name'];
|
||||
$d['custom_field_type'][] = !empty($cf['type']) ? (string)$cf['type'] : 'text';
|
||||
$d['custom_field_required'][] = !empty($cf['is_required']) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
return $d;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,6 +262,10 @@ if (Test-Path $tempDir) {
|
||||
Remove-Item -Recurse -Force $tempDir
|
||||
}
|
||||
|
||||
if (-not (Test-Path $tempDir)) {
|
||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||
}
|
||||
|
||||
foreach ($f in $filesToPack) {
|
||||
$destPath = Join-Path $tempDir $f
|
||||
$destDir = Split-Path $destPath -Parent
|
||||
@@ -295,7 +299,16 @@ if (Test-Path $zipPath) {
|
||||
# Pakuj zawartosc temp dir (bez folderu temp/)
|
||||
$originalLocation = Get-Location
|
||||
Set-Location $tempDir
|
||||
Compress-Archive -Path '*' -DestinationPath "../../$zipPath" -Force
|
||||
$tempItems = Get-ChildItem -Force
|
||||
if ($tempItems) {
|
||||
Compress-Archive -Path '*' -DestinationPath "../../$zipPath" -Force
|
||||
} else {
|
||||
# SQL-only update: create minimal ZIP with empty placeholder
|
||||
$placeholderPath = "_sql_only_update.txt"
|
||||
Set-Content -Path $placeholderPath -Value "SQL-only update $versionNumber"
|
||||
Compress-Archive -Path $placeholderPath -DestinationPath "../../$zipPath" -Force
|
||||
Remove-Item $placeholderPath -Force
|
||||
}
|
||||
Set-Location $originalLocation
|
||||
|
||||
Write-Ok "Utworzono ZIP: $zipPath"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
$database['host'] = 'localhost';
|
||||
$database['remote_host'] = 'host700513.hostido.net.pl';
|
||||
$database['remote_host'] = 'host117523.hostido.net.pl';
|
||||
$database['user'] = 'host117523_shoppro';
|
||||
$database['password'] = 'mhA9WCEXEnRfTtbN33hL';
|
||||
$database['name'] = 'host117523_shoppro';
|
||||
@@ -13,7 +13,7 @@ $config['redis']['host'] = '127.0.0.1';
|
||||
$config['redis']['port'] = 20470;
|
||||
$config['redis']['password'] = 'Gi7FzWtkry19hZ1BqT1LKEWfwokQpigh';
|
||||
|
||||
$config['debug']['apilo'] = false;
|
||||
$config['debug']['apilo'] = true;
|
||||
|
||||
$config['trustmate']['enabled'] = true;
|
||||
$config['trustmate']['uid'] = '34eb36ba-c715-4cdc-8707-22376c9f14c7';
|
||||
|
||||
40
docs/API.md
40
docs/API.md
@@ -219,6 +219,7 @@ Odpowiedz:
|
||||
"set_id": null,
|
||||
"product_unit_id": 1,
|
||||
"producer_id": 3,
|
||||
"producer_name": "Nike",
|
||||
"date_add": "2026-01-15 10:00:00",
|
||||
"date_modify": "2026-02-19 12:00:00",
|
||||
"languages": {
|
||||
@@ -237,7 +238,8 @@ Odpowiedz:
|
||||
"tab_description_1": null,
|
||||
"tab_name_2": null,
|
||||
"tab_description_2": null,
|
||||
"canonical": null
|
||||
"canonical": null,
|
||||
"security_information": null
|
||||
}
|
||||
},
|
||||
"images": [
|
||||
@@ -253,6 +255,9 @@ Odpowiedz:
|
||||
"value_names": {"pl": "Czerwony", "en": "Red"}
|
||||
}
|
||||
],
|
||||
"custom_fields": [
|
||||
{"name": "Napis na koszulce", "type": "text", "is_required": 1}
|
||||
],
|
||||
"variants": [
|
||||
{
|
||||
"id": 101,
|
||||
@@ -297,11 +302,15 @@ Content-Type: application/json
|
||||
}
|
||||
},
|
||||
"categories": [1, 5],
|
||||
"products_related": [10, 20]
|
||||
"products_related": [10, 20],
|
||||
"custom_fields": [
|
||||
{"name": "Napis na koszulce", "type": "text", "is_required": 1}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Wymagane: `languages` (min. 1 jezyk z `name`) oraz `price_brutto`.
|
||||
`custom_fields` — opcjonalne; kazdy element wymaga `name`, `type` (domyslnie `text`), `is_required` (0/1).
|
||||
|
||||
Odpowiedz (HTTP 201):
|
||||
```json
|
||||
@@ -468,6 +477,31 @@ GET api.php?endpoint=dictionaries&action=attributes
|
||||
|
||||
Zwraca aktywne atrybuty z wartosciami i wielojezycznymi nazwami.
|
||||
|
||||
#### Znajdz lub utworz producenta
|
||||
```
|
||||
POST api.php?endpoint=dictionaries&action=ensure_producer
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"name": "Nike"
|
||||
}
|
||||
```
|
||||
|
||||
Zwraca istniejacego producenta po nazwie lub tworzy nowego. Uzyc przed tworzeniem produktu, jesli producent moze nie istniec.
|
||||
|
||||
Odpowiedz:
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"data": {
|
||||
"id": 5,
|
||||
"created": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`created: true` gdy producent zostal nowo dodany, `false` gdy juz istnial.
|
||||
|
||||
Odpowiedz:
|
||||
```json
|
||||
{
|
||||
@@ -514,4 +548,4 @@ UPDATE pp_settings SET value = 'twoj-klucz-api' WHERE param = 'api_key';
|
||||
- Kontrolery: `autoload/api/Controllers/`
|
||||
- `OrdersApiController` — zamowienia (5 akcji)
|
||||
- `ProductsApiController` — produkty (8 akcji: list, get, create, update, variants, create_variant, update_variant, delete_variant)
|
||||
- `DictionariesApiController` — slowniki (4 akcje: statuses, transports, payment_methods, attributes)
|
||||
- `DictionariesApiController` — slowniki (5 akcji: statuses, transports, payment_methods, attributes, ensure_producer)
|
||||
|
||||
@@ -4,6 +4,56 @@ Logi zmian z migracji na Domain-Driven Architecture. Najnowsze na gorze.
|
||||
|
||||
---
|
||||
|
||||
## ver. 0.318 (2026-02-24) - ShopPRO export produktów + API endpoints
|
||||
|
||||
- **NEW**: `IntegrationsRepository::shopproExportProduct()` — eksport produktu do zdalnej instancji shopPRO: pola główne, tłumaczenia, custom fields, zdjęcia przez API (base64)
|
||||
- **NEW**: `IntegrationsRepository::sendImageToShopproApi()` — wysyłka zdjęć do remote API shopPRO (endpoint `upload_image`) z base64
|
||||
- **REFACTOR**: `shopproImportProduct()` — wydzielono `shopproDb()` i `missingShopproSetting()` jako prywatne helpery; dodano import `security_information`, `producer_id`, custom fields i `alt` zdjęcia
|
||||
- **NEW**: `AttributeRepository::ensureAttributeForApi()` i `ensureAttributeValueForApi()` — idempotent find-or-create dla atrybutów i ich wartości (integracje API)
|
||||
- **NEW**: API endpoint `POST /api.php?endpoint=dictionaries&action=ensure_attribute` — utwórz lub znajdź atrybut po nazwie i typie
|
||||
- **NEW**: API endpoint `POST /api.php?endpoint=dictionaries&action=ensure_attribute_value` — utwórz lub znajdź wartość atrybutu po nazwie
|
||||
- **NEW**: API endpoint `POST /api.php?endpoint=products&action=upload_image` — przyjmuje zdjęcie produktu jako base64 JSON, zapisuje plik i rekord w `pp_shop_products_images`
|
||||
- **NEW**: `IntegrationsController::shoppro_product_export()` — akcja admina eksportująca produkt do shopPRO
|
||||
- **NEW**: Przycisk "Eksportuj do shopPRO" w liście produktów (widoczny gdy shopPRO enabled)
|
||||
- **NEW**: Pole "API key" w ustawieniach integracji shopPRO (`shoppro-settings.php`)
|
||||
|
||||
---
|
||||
|
||||
## ver. 0.317 (2026-02-23) - Klucz API: przycisk generowania + fix zapisu
|
||||
|
||||
- **FIX**: `SettingsRepository::saveSettings()` — pole `api_key` brakowało w whiteliście zapisywanych pól, przez co wartość była tracona przy każdym zapisie (TRUNCATE + insert)
|
||||
- **NEW**: Pole "Klucz API" w ustawieniach — przycisk "Generuj" do losowego 32-znakowego klucza alfanumerycznego, usunięto "(ordersPRO)" z nazwy
|
||||
- **FIX**: `api.php` — routing API przeniesiony przed ładowanie globalnych settings (wczesne wyjście), obsługa błędów przez `\Throwable`
|
||||
- **FIX**: `ApiRouter` — catch `\Throwable` zamiast `\Exception` dla pełniejszego łapania błędów
|
||||
|
||||
---
|
||||
|
||||
## ver. 0.316 (2026-02-23) - Migracja brakującej kolumny type w custom fields
|
||||
|
||||
- **FIX**: Dodanie brakującej kolumny `type` w tabeli `pp_shop_products_custom_fields` — kolumna była używana w kodzie od v0.277 ale nigdy nie miała migracji ALTER TABLE, przez co instancje ze starszą bazą dostawały `PDOException: Column not found: 1054 Unknown column 'type'` przy zapisie produktu
|
||||
|
||||
---
|
||||
|
||||
## ver. 0.315 (2026-02-23) - Fix listowania atrybutów w admin
|
||||
|
||||
- **FIX**: `AttributeRepository::listForAdmin()` — zapytanie COUNT dostawało parametr `:default_lang_id` którego nie miało w SQL, powodując `PDOException: SQLSTATE[HY093]: Invalid parameter number`. Parametr potrzebny tylko w głównym SELECT, nie w COUNT
|
||||
|
||||
---
|
||||
|
||||
## ver. 0.314 (2026-02-23) - Fix wyszukiwarki admin + title zamówienia
|
||||
|
||||
- **FIX**: Globalna wyszukiwarka w panelu admina przestała zwracać wyniki — dodano `Content-Type: application/json` i `Cache-Control: no-store` (zapobiega cache'owaniu przez proxy/CDN), zmiana AJAX z GET na POST, `fetchAll(PDO::FETCH_ASSOC)`, top-level try/catch z gwarantowaną odpowiedzią JSON
|
||||
- **NEW**: `document.title` w widoku szczegółów zamówienia pokazuje numer zamówienia (np. "Zamówienie ZAM/123 - shopPro")
|
||||
|
||||
---
|
||||
|
||||
## ver. 0.313 (2026-02-23) - Fix sync płatności Apilo + logowanie
|
||||
|
||||
- **FIX**: `syncApiloPayment()` i `syncApiloStatus()` — `(int)` cast na `apilo_order_id` (format `"PPxxxxxx"`) dawał `0`, przez co metody pomijały sync z API Apilo. Zmiana na `empty()`
|
||||
- **NEW**: Logowanie w `syncApiloPaymentIfNeeded()` i `syncApiloStatusIfNeeded()` — każda ścieżka decyzyjna (Apilo wyłączone, brak tokenu, brak `apilo_order_id`, sync nieudany) zapisuje wpis do `pp_log` z kontekstem
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
156
docs/CRON_QUEUE_PLAN.md
Normal file
156
docs/CRON_QUEUE_PLAN.md
Normal file
@@ -0,0 +1,156 @@
|
||||
# Plan: System kolejki zadań cron oparty o bazę danych
|
||||
|
||||
## Kontekst
|
||||
|
||||
Obecny system cron ma dwa problemy:
|
||||
1. **Kolejka plikowa (JSON)** — sync płatności/statusów Apilo trzymany w `/temp/apilo-sync-queue.json` — kruchy, brak transakcji, ryzyko utraty danych
|
||||
2. **Monolityczny cron.php** (~550 linii) — brak priorytetów, brak retry z backoff, brak centralnego zarządzania
|
||||
|
||||
Cel: Zastąpienie całego systemu cron tabelą `pp_cron_jobs` z priorytetami, retry/backoff i harmonogramem `pp_cron_schedules`.
|
||||
|
||||
## Nowe pliki
|
||||
|
||||
| Plik | Opis |
|
||||
|------|------|
|
||||
| `autoload/Domain/CronJob/CronJobType.php` | Stałe typów zadań i priorytetów |
|
||||
| `autoload/Domain/CronJob/CronJobRepository.php` | CRUD na `pp_cron_jobs` + `pp_cron_schedules` |
|
||||
| `autoload/Domain/CronJob/CronJobProcessor.php` | Orkiestracja: pobierz zadanie → wywołaj handler → obsłuż wynik |
|
||||
| `tests/Unit/Domain/CronJob/CronJobTypeTest.php` | Testy stałych |
|
||||
| `tests/Unit/Domain/CronJob/CronJobRepositoryTest.php` | Testy repozytorium |
|
||||
| `tests/Unit/Domain/CronJob/CronJobProcessorTest.php` | Testy procesora |
|
||||
| `migrations/0.315.sql` | CREATE TABLE + INSERT harmonogramów |
|
||||
|
||||
## Modyfikowane pliki
|
||||
|
||||
| Plik | Zmiana |
|
||||
|------|--------|
|
||||
| `cron.php` | Zastąpienie ~550 linii orchestratorem (~100 linii) z rejestracją handlerów |
|
||||
| `cron/cron-xml.php` | Usunięcie — logika przeniesiona do handlera `google_xml_feed` |
|
||||
| `cron-turstmate.php` | Usunięcie — logika przeniesiona do handlera `trustmate_invitation` |
|
||||
| `autoload/Domain/Order/OrderAdminService.php` | `queueApiloSync()` → enqueue do DB; usunięcie metod plikowych; `syncApiloPayment()`/`syncApiloStatus()` → public |
|
||||
| `tests/Unit/Domain/Order/OrderAdminServiceTest.php` | Refaktor testów kolejki: mock `CronJobRepository` zamiast pliku JSON |
|
||||
| `docs/DATABASE_STRUCTURE.md` | Dodanie tabel `pp_cron_jobs`, `pp_cron_schedules` |
|
||||
| `docs/CHANGELOG.md` | Wpis o nowym systemie |
|
||||
|
||||
## Schemat DB (`migrations/0.315.sql`)
|
||||
|
||||
### `pp_cron_jobs`
|
||||
```sql
|
||||
CREATE TABLE pp_cron_jobs (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
job_type VARCHAR(50) NOT NULL,
|
||||
status ENUM('pending','processing','completed','failed','cancelled') NOT NULL DEFAULT 'pending',
|
||||
priority TINYINT UNSIGNED NOT NULL DEFAULT 100, -- niższy = ważniejszy
|
||||
payload TEXT NULL, -- JSON z danymi zadania
|
||||
result TEXT NULL, -- JSON z wynikiem
|
||||
attempts SMALLINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
max_attempts SMALLINT UNSIGNED NOT NULL DEFAULT 10,
|
||||
last_error VARCHAR(500) NULL,
|
||||
scheduled_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
started_at DATETIME NULL,
|
||||
completed_at DATETIME NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
INDEX idx_status_priority_scheduled (status, priority, scheduled_at),
|
||||
INDEX idx_job_type (job_type),
|
||||
INDEX idx_status (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
```
|
||||
|
||||
### `pp_cron_schedules`
|
||||
```sql
|
||||
CREATE TABLE pp_cron_schedules (
|
||||
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
job_type VARCHAR(50) NOT NULL UNIQUE,
|
||||
interval_seconds INT UNSIGNED NOT NULL,
|
||||
priority TINYINT UNSIGNED NOT NULL DEFAULT 100,
|
||||
max_attempts SMALLINT UNSIGNED NOT NULL DEFAULT 3,
|
||||
payload TEXT NULL,
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
last_run_at DATETIME NULL,
|
||||
next_run_at DATETIME NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX idx_enabled_next_run (enabled, next_run_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
||||
```
|
||||
|
||||
## Typy zadań i priorytety
|
||||
|
||||
| Typ | Priorytet | Harmonogram |
|
||||
|-----|-----------|-------------|
|
||||
| `apilo_token_keepalive` | 10 (krytyczny) | co 4 min |
|
||||
| `apilo_send_order` | 50 (wysoki) | co 1 min |
|
||||
| `apilo_sync_payment` | 50 (wysoki) | event-driven (enqueue przy zmianie) |
|
||||
| `apilo_sync_status` | 50 (wysoki) | event-driven |
|
||||
| `apilo_product_sync` | 100 (normalny) | co 10 min |
|
||||
| `apilo_pricelist_sync` | 100 (normalny) | co 1h |
|
||||
| `apilo_status_poll` | 100 (normalny) | co 10 min |
|
||||
| `price_history` | 100 (normalny) | co 24h |
|
||||
| `order_analysis` | 100 (normalny) | co 10 min |
|
||||
| `trustmate_invitation` | 200 (niski) | co 10 min |
|
||||
| `google_xml_feed` | 200 (niski) | co 1h |
|
||||
|
||||
## Architektura klas
|
||||
|
||||
### CronJobRepository — metody kluczowe
|
||||
- `enqueue($jobType, $payload, $priority, $maxAttempts, $scheduledAt)` — dodaj do kolejki
|
||||
- `fetchNext($limit)` — atomowe pobranie pending jobs (UPDATE WHERE status='pending')
|
||||
- `markCompleted($jobId, $result)` / `markFailed($jobId, $error, $backoffSeconds)`
|
||||
- `hasPendingJob($jobType, $payloadMatch)` — zapobiega duplikatom
|
||||
- `cleanup($olderThanDays)` — GC starych wpisów
|
||||
- `recoverStuck($olderThanMinutes)` — reset stuck "processing" jobs
|
||||
- `getDueSchedules()` / `touchSchedule($id)` — harmonogram
|
||||
|
||||
### CronJobProcessor — orkiestracja
|
||||
- `registerHandler($jobType, callable)` — rejestracja handlera
|
||||
- `createScheduledJobs()` — tworzy jobs z harmonogramów których `next_run_at <= NOW`
|
||||
- `processQueue($limit)` — pobierz + wywołaj handler + markCompleted/markFailed
|
||||
- `run($limit)` — główna metoda: schedules + process
|
||||
|
||||
### Exponential backoff
|
||||
```
|
||||
Próba 1: 60s, Próba 2: 120s, Próba 3: 240s, ... max 3600s (1h)
|
||||
```
|
||||
|
||||
### Zależność "order not yet in Apilo"
|
||||
Handler `apilo_sync_payment`/`apilo_sync_status` sprawdza `apilo_order_id`. Jeśli brak → zwraca false → `markFailed()` z backoffem → zadanie wraca do kolejki. Max 50 prób.
|
||||
|
||||
## Nowy cron.php (schemat)
|
||||
|
||||
```php
|
||||
$cronRepo = new \Domain\CronJob\CronJobRepository($mdb);
|
||||
$processor = new \Domain\CronJob\CronJobProcessor($mdb, $cronRepo);
|
||||
|
||||
// Rejestracja handlerów (każdy to callable)
|
||||
$processor->registerHandler('apilo_token_keepalive', function($payload) use ($integrationsRepo) { ... });
|
||||
$processor->registerHandler('apilo_send_order', function($payload) use ($orderService, ...) { ... });
|
||||
// ... inne handlery
|
||||
|
||||
$result = $processor->run(20);
|
||||
```
|
||||
|
||||
## Zmiany w OrderAdminService
|
||||
|
||||
1. `queueApiloSync()` → `CronJobRepository::enqueue()` zamiast zapisu do pliku JSON
|
||||
2. Usunięcie: `loadApiloSyncQueue()`, `saveApiloSyncQueue()`, `apiloSyncQueuePath()`, stała `APILO_SYNC_QUEUE_FILE`
|
||||
3. `syncApiloPayment()`, `syncApiloStatus()` → zmiana z `private` na `public`
|
||||
4. Jednorazowa migracja: odczyt JSON → insert do DB → usunięcie pliku
|
||||
|
||||
## Kolejność implementacji
|
||||
|
||||
1. Migracja SQL
|
||||
2. `CronJobType.php`
|
||||
3. `CronJobRepository.php` + testy
|
||||
4. `CronJobProcessor.php` + testy
|
||||
5. Modyfikacja `OrderAdminService` (queue → DB, public methods)
|
||||
6. Jednorazowa migracja pliku JSON → DB
|
||||
7. Nowy `cron.php` z handlerami (ekstrakcja logiki z bloków proceduralnych)
|
||||
8. Aktualizacja testów OrderAdminService
|
||||
9. Dokumentacja (DATABASE_STRUCTURE.md, CHANGELOG.md)
|
||||
|
||||
## Weryfikacja
|
||||
|
||||
1. Uruchomienie pełnego zestawu testów: `./test.ps1`
|
||||
2. Sprawdzenie czy nowe testy CronJob* przechodzą
|
||||
3. Sprawdzenie czy istniejące testy OrderAdminService przechodzą po refaktorze
|
||||
4. Weryfikacja migracji SQL na pustej bazie
|
||||
@@ -23,10 +23,10 @@ composer test # standard
|
||||
## Aktualny stan
|
||||
|
||||
```text
|
||||
OK (758 tests, 2135 assertions)
|
||||
OK (765 tests, 2153 assertions)
|
||||
```
|
||||
|
||||
Zweryfikowano: 2026-02-22 (ver. 0.304)
|
||||
Zweryfikowano: 2026-02-24 (ver. 0.318)
|
||||
|
||||
## Konfiguracja
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
1. Dodać przycisk kopiowania przy atrybutach produktu w zamówieniu
|
||||
1
migrations/0.316.sql
Normal file
1
migrations/0.316.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE `pp_shop_products_custom_fields` ADD COLUMN `type` VARCHAR(30) NOT NULL DEFAULT '' AFTER `name`;
|
||||
@@ -4,6 +4,7 @@ namespace Tests\Unit\api\Controllers;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use api\Controllers\DictionariesApiController;
|
||||
use Domain\Attribute\AttributeRepository;
|
||||
use Domain\Producer\ProducerRepository;
|
||||
use Domain\ShopStatus\ShopStatusRepository;
|
||||
use Domain\Transport\TransportRepository;
|
||||
use Domain\PaymentMethod\PaymentMethodRepository;
|
||||
@@ -14,6 +15,7 @@ class DictionariesApiControllerTest extends TestCase
|
||||
private $mockTransportRepo;
|
||||
private $mockPaymentRepo;
|
||||
private $mockAttrRepo;
|
||||
private $mockProducerRepo;
|
||||
private $controller;
|
||||
|
||||
protected function setUp(): void
|
||||
@@ -22,12 +24,14 @@ class DictionariesApiControllerTest extends TestCase
|
||||
$this->mockTransportRepo = $this->createMock(TransportRepository::class);
|
||||
$this->mockPaymentRepo = $this->createMock(PaymentMethodRepository::class);
|
||||
$this->mockAttrRepo = $this->createMock(AttributeRepository::class);
|
||||
$this->mockProducerRepo = $this->createMock(ProducerRepository::class);
|
||||
|
||||
$this->controller = new DictionariesApiController(
|
||||
$this->mockStatusRepo,
|
||||
$this->mockTransportRepo,
|
||||
$this->mockPaymentRepo,
|
||||
$this->mockAttrRepo
|
||||
$this->mockAttrRepo,
|
||||
$this->mockProducerRepo
|
||||
);
|
||||
|
||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||
@@ -186,4 +190,52 @@ class DictionariesApiControllerTest extends TestCase
|
||||
|
||||
$this->assertSame(405, http_response_code());
|
||||
}
|
||||
|
||||
public function testEnsureAttributeRejectsGetMethod(): void
|
||||
{
|
||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||
|
||||
ob_start();
|
||||
$this->controller->ensure_attribute();
|
||||
ob_get_clean();
|
||||
|
||||
$this->assertSame(405, http_response_code());
|
||||
}
|
||||
|
||||
public function testEnsureAttributeReturns400WhenNoBody(): void
|
||||
{
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
|
||||
ob_start();
|
||||
$this->controller->ensure_attribute();
|
||||
$output = ob_get_clean();
|
||||
|
||||
$this->assertSame(400, http_response_code());
|
||||
$json = json_decode($output, true);
|
||||
$this->assertSame('BAD_REQUEST', $json['code']);
|
||||
}
|
||||
|
||||
public function testEnsureAttributeValueRejectsGetMethod(): void
|
||||
{
|
||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||
|
||||
ob_start();
|
||||
$this->controller->ensure_attribute_value();
|
||||
ob_get_clean();
|
||||
|
||||
$this->assertSame(405, http_response_code());
|
||||
}
|
||||
|
||||
public function testEnsureAttributeValueReturns400WhenNoBody(): void
|
||||
{
|
||||
$_SERVER['REQUEST_METHOD'] = 'POST';
|
||||
|
||||
ob_start();
|
||||
$this->controller->ensure_attribute_value();
|
||||
$output = ob_get_clean();
|
||||
|
||||
$this->assertSame(400, http_response_code());
|
||||
$json = json_decode($output, true);
|
||||
$this->assertSame('BAD_REQUEST', $json['code']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,6 +351,19 @@ class ProductsApiControllerTest extends TestCase
|
||||
$this->assertSame('5901234123457', $result['ean']);
|
||||
}
|
||||
|
||||
public function testMapApiToFormDataPreservesZeroBasePriceForSaveProduct(): void
|
||||
{
|
||||
$method = new \ReflectionMethod(ProductsApiController::class, 'mapApiToFormData');
|
||||
$method->setAccessible(true);
|
||||
|
||||
$result = $method->invoke($this->controller, [
|
||||
'price_brutto' => 0.0,
|
||||
'languages' => ['pl' => ['name' => 'Zero']],
|
||||
]);
|
||||
|
||||
$this->assertSame('0', $result['price_brutto']);
|
||||
}
|
||||
|
||||
public function testMapApiToFormDataMapsCategories(): void
|
||||
{
|
||||
$method = new \ReflectionMethod(ProductsApiController::class, 'mapApiToFormData');
|
||||
|
||||
BIN
updates/0.30/ver_0.312.zip
Normal file
BIN
updates/0.30/ver_0.312.zip
Normal file
Binary file not shown.
23
updates/0.30/ver_0.312_manifest.json
Normal file
23
updates/0.30/ver_0.312_manifest.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"changelog": "FIX - krytyczne bugi integracji Apilo: curl_getinfo po curl_close, nieskończona pętla wysyłki, ceny 0.00 PLN, walidacja cen",
|
||||
"version": "0.312",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"cron.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:07f9efd02a6a83327ab8dd9403e0c072a5f38b680d6e3f6c67a96d2af8b8fc85",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-23",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.313.zip
Normal file
BIN
updates/0.30/ver_0.313.zip
Normal file
Binary file not shown.
24
updates/0.30/ver_0.313_manifest.json
Normal file
24
updates/0.30/ver_0.313_manifest.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"changelog": "FIX - sync płatności Apilo (int cast na apilo_order_id PPxxxxxx dawał 0) + logowanie decyzji sync do pp_log",
|
||||
"version": "0.313",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"admin/templates/shop-order/order-details.php",
|
||||
"autoload/Domain/Order/OrderAdminService.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:f344da1f3270abfc63653f8912ec1abbc006154db784cfee5a565fc0daaa75f8",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-23",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.314.zip
Normal file
BIN
updates/0.30/ver_0.314.zip
Normal file
Binary file not shown.
25
updates/0.30/ver_0.314_manifest.json
Normal file
25
updates/0.30/ver_0.314_manifest.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"changelog": "FIX - naprawa globalnej wyszukiwarki admin (Content-Type, Cache-Control, POST, try/catch), NEW - title strony z numerem zamówienia",
|
||||
"version": "0.314",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"admin/templates/shop-order/order-details.php",
|
||||
"admin/templates/site/main-layout.php",
|
||||
"autoload/admin/Controllers/SettingsController.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:5ef21d158850db4036e3ee3ed4e9d2938d0451cd9b8602d26fd53163085a391f",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-23",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.315.zip
Normal file
BIN
updates/0.30/ver_0.315.zip
Normal file
Binary file not shown.
23
updates/0.30/ver_0.315_manifest.json
Normal file
23
updates/0.30/ver_0.315_manifest.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"changelog": "FIX - PDOException w listowaniu atrybutow admin (SQLSTATE HY093)",
|
||||
"version": "0.315",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"autoload/Domain/Attribute/AttributeRepository.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:cfe6eb7dfad896c4ea885c2f9a52c6a389d4e38379a0bf64f5d429910d87e55f",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-23",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.316.zip
Normal file
BIN
updates/0.30/ver_0.316.zip
Normal file
Binary file not shown.
23
updates/0.30/ver_0.316_manifest.json
Normal file
23
updates/0.30/ver_0.316_manifest.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"changelog": "FIX - migracja brakujacej kolumny type w pp_shop_products_custom_fields",
|
||||
"version": "0.316",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:654a3683c0add19d0cb2f87db6f6a45cd4ce08799dd3692c6adacc07666f13b1",
|
||||
"sql": [
|
||||
"ALTER TABLE `pp_shop_products_custom_fields` ADD COLUMN `type` VARCHAR(30) NOT NULL DEFAULT \u0027\u0027 AFTER `name`;"
|
||||
],
|
||||
"date": "2026-02-23",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.317.zip
Normal file
BIN
updates/0.30/ver_0.317.zip
Normal file
Binary file not shown.
26
updates/0.30/ver_0.317_manifest.json
Normal file
26
updates/0.30/ver_0.317_manifest.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"changelog": "FIX - klucz API: fix zapisu (brakowalo w whiteliście), przycisk Generuj losowy klucz, ulepszony routing API",
|
||||
"version": "0.317",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"api.php",
|
||||
"autoload/Domain/Settings/SettingsRepository.php",
|
||||
"autoload/admin/Controllers/SettingsController.php",
|
||||
"autoload/api/ApiRouter.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:130e5f4fd15b635bb277dc639d528e017de866fbaada5db2d08d9426251824b3",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-23",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.318.zip
Normal file
BIN
updates/0.30/ver_0.318.zip
Normal file
Binary file not shown.
30
updates/0.30/ver_0.318_manifest.json
Normal file
30
updates/0.30/ver_0.318_manifest.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"changelog": "NEW - shopPRO export produktów + API endpoints (ensure_attribute, ensure_attribute_value, upload_image)",
|
||||
"version": "0.318",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"admin/templates/integrations/shoppro-settings.php",
|
||||
"autoload/Domain/Attribute/AttributeRepository.php",
|
||||
"autoload/Domain/Integrations/IntegrationsRepository.php",
|
||||
"autoload/Domain/Product/ProductRepository.php",
|
||||
"autoload/admin/Controllers/IntegrationsController.php",
|
||||
"autoload/admin/Controllers/ShopProductController.php",
|
||||
"autoload/api/Controllers/DictionariesApiController.php",
|
||||
"autoload/api/Controllers/ProductsApiController.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:6a7eba1b390db94ccda210a5f2cbcd33f17f43d9f34031c4d0793d224df5d541",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-24",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.319.zip
Normal file
BIN
updates/0.30/ver_0.319.zip
Normal file
Binary file not shown.
26
updates/0.30/ver_0.319_manifest.json
Normal file
26
updates/0.30/ver_0.319_manifest.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"changelog": "FIX - usunięcie shopPRO eksportu produktów; API produktu: dodano custom_fields i security_information",
|
||||
"version": "0.319",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"autoload/Domain/Integrations/IntegrationsRepository.php",
|
||||
"autoload/Domain/Product/ProductRepository.php",
|
||||
"autoload/admin/Controllers/IntegrationsController.php",
|
||||
"autoload/admin/Controllers/ShopProductController.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:99e07eb85aeca1c96607e95c90408bfbc166d97c0b999cc9eb033c6a4f208b97",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-24",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.320.zip
Normal file
BIN
updates/0.30/ver_0.320.zip
Normal file
Binary file not shown.
26
updates/0.30/ver_0.320_manifest.json
Normal file
26
updates/0.30/ver_0.320_manifest.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"changelog": "NEW - API: endpoint ensure_producer (znajdź lub utwórz producenta); GET product zwraca producer_name",
|
||||
"version": "0.320",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"autoload/Domain/Producer/ProducerRepository.php",
|
||||
"autoload/Domain/Product/ProductRepository.php",
|
||||
"autoload/api/ApiRouter.php",
|
||||
"autoload/api/Controllers/DictionariesApiController.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:eb38b6f260768c25d331de60098eba647a897972c211b37b39314c8a3f954bf3",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-24",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
BIN
updates/0.30/ver_0.321.zip
Normal file
BIN
updates/0.30/ver_0.321.zip
Normal file
Binary file not shown.
23
updates/0.30/ver_0.321_manifest.json
Normal file
23
updates/0.30/ver_0.321_manifest.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"changelog": "NEW - API: obsługa custom_fields w create/update produktu",
|
||||
"version": "0.321",
|
||||
"files": {
|
||||
"added": [
|
||||
|
||||
],
|
||||
"deleted": [
|
||||
|
||||
],
|
||||
"modified": [
|
||||
"autoload/api/Controllers/ProductsApiController.php"
|
||||
]
|
||||
},
|
||||
"checksum_zip": "sha256:a04ac9975618bc3b21d80a8e449f98e5bc825ce49a37142e1e621a2ef34a19f1",
|
||||
"sql": [
|
||||
|
||||
],
|
||||
"date": "2026-02-24",
|
||||
"directories_deleted": [
|
||||
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -1,5 +1,5 @@
|
||||
<?
|
||||
$current_ver = 312;
|
||||
$current_ver = 322;
|
||||
|
||||
for ($i = 1; $i <= $current_ver; $i++)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user