ver. 0.277: ShopProduct factory, Dashboard, Update migration, legacy cleanup, admin\App

- ShopProduct factory: full migration (~40 ProductRepository methods, ~30 controller actions)
- Dashboard: Domain+DI migration (DashboardRepository + DashboardController)
- Update: Domain+DI migration (UpdateRepository + UpdateController, template rewrite)
- Renamed admin\Site to admin\App, removed dead fallback routing
- Removed all legacy folders: admin/controls, admin/factory, admin/view
- Newsletter: switched from admin\factory\Articles to ArticleRepository
- 414 tests, 1335 assertions passing

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-16 01:06:29 +01:00
parent be93a7e330
commit 74343b0f33
51 changed files with 4960 additions and 5403 deletions

View File

@@ -840,4 +840,28 @@ class ArticleRepository
$this->db->delete('pp_articles_images', ['article_id' => null]);
}
/**
* Pobiera artykuly opublikowane w podanym zakresie dat.
*/
public function articlesByDateAdd( string $dateStart, string $dateEnd ): array
{
$stmt = $this->db->query(
'SELECT id FROM pp_articles '
. 'WHERE status = 1 '
. 'AND date_add BETWEEN \'' . addslashes( $dateStart ) . '\' AND \'' . addslashes( $dateEnd ) . '\' '
. 'ORDER BY date_add DESC'
);
$articles = [];
$rows = $stmt ? $stmt->fetchAll( \PDO::FETCH_ASSOC ) : [];
if ( is_array( $rows ) ) {
foreach ( $rows as $row ) {
$articles[] = \front\factory\Articles::article_details( $row['id'], 'pl' );
}
}
return $articles;
}
}

View File

@@ -0,0 +1,153 @@
<?php
namespace Domain\Dashboard;
class DashboardRepository
{
private $db;
public function __construct( $db )
{
$this->db = $db;
}
public function summaryOrders(): int
{
try {
$redis = \RedisConnection::getInstance()->getConnection();
if ( $redis ) {
$cached = $redis->get( 'summary_ordersd' );
if ( $cached !== false ) {
return (int) unserialize( $cached );
}
$summary = (int) $this->db->count( 'pp_shop_orders', [ 'status' => 6 ] );
$redis->setex( 'summary_ordersd', 300, serialize( $summary ) );
return $summary;
}
} catch ( \RedisException $e ) {
// fallback
}
return (int) $this->db->count( 'pp_shop_orders', [ 'status' => 6 ] );
}
public function summarySales(): float
{
try {
$redis = \RedisConnection::getInstance()->getConnection();
if ( $redis ) {
$cached = $redis->get( 'summary_salesd' );
if ( $cached !== false ) {
return (float) unserialize( $cached );
}
$summary = $this->calculateTotalSales();
$redis->setex( 'summary_salesd', 300, serialize( $summary ) );
return $summary;
}
} catch ( \RedisException $e ) {
// fallback
}
return $this->calculateTotalSales();
}
private function calculateTotalSales(): float
{
return (float) $this->db->sum( 'pp_shop_orders', 'summary', [ 'status' => 6 ] )
- (float) $this->db->sum( 'pp_shop_orders', 'transport_cost', [ 'status' => 6 ] );
}
public function salesGrid(): array
{
$grid = [];
$rows = $this->db->select( 'pp_shop_orders', [ 'id', 'date_order' ], [ 'status' => 6 ] );
if ( is_array( $rows ) ) {
foreach ( $rows as $row ) {
$ts = strtotime( $row['date_order'] );
$dayOfWeek = date( 'N', $ts );
$hour = date( 'G', $ts );
if ( !isset( $grid[$dayOfWeek][$hour] ) ) {
$grid[$dayOfWeek][$hour] = 0;
}
$grid[$dayOfWeek][$hour]++;
}
}
return $grid;
}
public function mostViewedProducts(): array
{
$stmt = $this->db->query(
'SELECT id, SUM(visits) AS visits '
. 'FROM pp_shop_products '
. 'GROUP BY id '
. 'ORDER BY visits DESC '
. 'LIMIT 10'
);
return $stmt ? $stmt->fetchAll( \PDO::FETCH_ASSOC ) : [];
}
public function bestSalesProducts(): array
{
$stmt = $this->db->query(
'SELECT parent_product_id, SUM(quantity) AS quantity_summary, SUM(price_brutto_promo * quantity) AS sales '
. 'FROM pp_shop_order_products AS psop '
. 'INNER JOIN pp_shop_orders AS pso ON pso.id = psop.order_id '
. 'WHERE pso.status = 6 '
. 'GROUP BY parent_product_id '
. 'ORDER BY sales DESC '
. 'LIMIT 10'
);
return $stmt ? $stmt->fetchAll( \PDO::FETCH_ASSOC ) : [];
}
public function last24MonthsSales(): array
{
$sales = [];
$date = new \DateTime();
for ( $i = 0; $i < 24; $i++ ) {
$dateStart = $date->format( 'Y-m-01' );
$dateEnd = $date->format( 'Y-m-t' );
$where = [
'AND' => [
'status' => 6,
'date_order[>=]' => $dateStart,
'date_order[<=]' => $dateEnd,
]
];
$monthSales = (float) $this->db->sum( 'pp_shop_orders', 'summary', $where )
- (float) $this->db->sum( 'pp_shop_orders', 'transport_cost', $where );
$sales[] = [
'date' => $date->format( 'Y-m' ),
'sales' => $monthSales,
];
$date->sub( new \DateInterval( 'P1M' ) );
}
return $sales;
}
public function lastOrders( int $limit = 10 ): array
{
$stmt = $this->db->query(
'SELECT id, number, date_order, '
. 'CONCAT( client_name, \' \', client_surname ) AS client, '
. 'client_email, '
. 'CONCAT( client_street, \', \', client_postal_code, \' \', client_city ) AS address, '
. 'status, client_phone, summary '
. 'FROM pp_shop_orders '
. 'ORDER BY date_order DESC '
. 'LIMIT ' . (int) $limit
);
return $stmt ? $stmt->fetchAll( \PDO::FETCH_ASSOC ) : [];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,319 @@
<?php
namespace Domain\Update;
class UpdateRepository
{
private $db;
public function __construct( $db )
{
$this->db = $db;
}
/**
* Wykonuje aktualizację do następnej wersji.
*
* @return array{success: bool, log: array, no_updates?: bool}
*/
public function update(): array
{
global $settings;
@file_put_contents( '../libraries/update_log.txt', '' );
$log = [];
$log[] = '[START] Rozpoczęcie aktualizacji - ' . date( 'Y-m-d H:i:s' );
$log[] = '[INFO] Aktualna wersja: ' . \S::get_version();
\S::delete_session( 'new-version' );
$versionsUrl = 'https://shoppro.project-dc.pl/updates/versions.php?key=' . $settings['update_key'];
$versions = @file_get_contents( $versionsUrl );
if ( $versions === false ) {
$log[] = '[ERROR] Nie udało się pobrać listy wersji z: ' . $versionsUrl;
$this->saveLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$log[] = '[OK] Pobrano listę wersji';
$versions = explode( PHP_EOL, $versions );
$log[] = '[INFO] Znaleziono ' . count( $versions ) . ' wersji do sprawdzenia';
foreach ( $versions as $ver ) {
$ver = trim( $ver );
if ( floatval( $ver ) <= (float) \S::get_version() ) {
continue;
}
$log[] = '[INFO] Aktualizacja do wersji: ' . $ver;
$dir = strlen( $ver ) == 5
? substr( $ver, 0, strlen( $ver ) - 2 ) . '0'
: substr( $ver, 0, strlen( $ver ) - 1 ) . '0';
$result = $this->downloadAndApply( $ver, $dir, $log );
$this->saveLog( $result['log'] );
return $result;
}
$log[] = '[INFO] Brak nowych wersji do zainstalowania';
$this->saveLog( $log );
return [ 'success' => true, 'log' => $log, 'no_updates' => true ];
}
private function downloadAndApply( string $ver, string $dir, array $log ): array
{
$baseUrl = 'https://shoppro.project-dc.pl/updates/' . $dir;
// Pobieranie ZIP
$zipUrl = $baseUrl . '/ver_' . $ver . '.zip';
$log[] = '[INFO] Pobieranie pliku ZIP: ' . $zipUrl;
$file = @file_get_contents( $zipUrl );
if ( $file === false ) {
$log[] = '[ERROR] Nie udało się pobrać pliku ZIP';
return [ 'success' => false, 'log' => $log ];
}
$fileSize = strlen( $file );
$log[] = '[OK] Pobrano plik ZIP, rozmiar: ' . $fileSize . ' bajtów';
if ( $fileSize < 100 ) {
$log[] = '[ERROR] Plik ZIP jest za mały (prawdopodobnie błąd pobierania)';
return [ 'success' => false, 'log' => $log ];
}
$dlHandler = @fopen( 'update.zip', 'w' );
if ( !$dlHandler ) {
$log[] = '[ERROR] Nie udało się otworzyć pliku update.zip do zapisu';
$log[] = '[INFO] Katalog roboczy: ' . getcwd();
return [ 'success' => false, 'log' => $log ];
}
$written = fwrite( $dlHandler, $file );
fclose( $dlHandler );
if ( $written === false || $written === 0 ) {
$log[] = '[ERROR] Nie udało się zapisać pliku ZIP';
return [ 'success' => false, 'log' => $log ];
}
$log[] = '[OK] Zapisano plik ZIP (' . $written . ' bajtów)';
// Wykonanie SQL
$log = $this->executeSql( $baseUrl . '/ver_' . $ver . '_sql.txt', $log );
// Usuwanie plików
$log = $this->deleteFiles( $baseUrl . '/ver_' . $ver . '_files.txt', $log );
// Rozpakowywanie ZIP
$log = $this->extractZip( 'update.zip', $log );
// Aktualizacja wersji
$versionFile = '../libraries/version.ini';
$handle = @fopen( $versionFile, 'w' );
if ( !$handle ) {
$log[] = '[ERROR] Nie udało się otworzyć pliku version.ini do zapisu';
return [ 'success' => false, 'log' => $log ];
}
fwrite( $handle, $ver );
fclose( $handle );
$log[] = '[OK] Zaktualizowano plik version.ini do wersji: ' . $ver;
$log[] = '[SUCCESS] Aktualizacja do wersji ' . $ver . ' zakończona pomyślnie';
return [ 'success' => true, 'log' => $log ];
}
private function executeSql( string $sqlUrl, array $log ): array
{
$log[] = '[INFO] Sprawdzanie aktualizacji SQL: ' . $sqlUrl;
$ch = curl_init( $sqlUrl );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
$response = curl_exec( $ch );
$contentType = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
$httpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
if ( !$response || strpos( $contentType, 'text/plain' ) === false ) {
$log[] = '[INFO] Brak aktualizacji SQL (HTTP: ' . $httpCode . ')';
return $log;
}
$queries = explode( PHP_EOL, $response );
$log[] = '[OK] Pobrano ' . count( $queries ) . ' zapytań SQL';
$success = 0;
$errors = 0;
foreach ( $queries as $query ) {
$query = trim( $query );
if ( $query !== '' ) {
if ( $this->db->query( $query ) ) {
$success++;
} else {
$errors++;
}
}
}
$log[] = '[INFO] Wykonano zapytania SQL - sukces: ' . $success . ', błędy: ' . $errors;
return $log;
}
private function deleteFiles( string $filesUrl, array $log ): array
{
$log[] = '[INFO] Sprawdzanie plików do usunięcia: ' . $filesUrl;
$ch = curl_init( $filesUrl );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
$response = curl_exec( $ch );
$contentType = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
curl_close( $ch );
if ( !$response || strpos( $contentType, 'text/plain' ) === false ) {
$log[] = '[INFO] Brak plików do usunięcia';
return $log;
}
$files = explode( PHP_EOL, $response );
$deletedFiles = 0;
$deletedDirs = 0;
foreach ( $files as $entry ) {
if ( strpos( $entry, 'F: ' ) !== false ) {
$path = substr( $entry, 3 );
if ( file_exists( $path ) ) {
if ( @unlink( $path ) ) {
$deletedFiles++;
} else {
$log[] = '[WARNING] Nie udało się usunąć pliku: ' . $path;
}
}
}
if ( strpos( $entry, 'D: ' ) !== false ) {
$path = substr( $entry, 3 );
if ( is_dir( $path ) ) {
\S::delete_dir( $path );
$deletedDirs++;
}
}
}
$log[] = '[INFO] Usunięto plików: ' . $deletedFiles . ', katalogów: ' . $deletedDirs;
return $log;
}
private function extractZip( string $fileName, array $log ): array
{
$log[] = '[INFO] Rozpoczęcie rozpakowywania pliku ZIP';
$path = pathinfo( realpath( $fileName ), PATHINFO_DIRNAME );
$path = substr( $path, 0, strlen( $path ) - 5 );
if ( !is_dir( $path ) || !is_writable( $path ) ) {
$log[] = '[ERROR] Ścieżka docelowa nie istnieje lub brak uprawnień: ' . $path;
return $log;
}
$zip = new \ZipArchive;
$res = $zip->open( $fileName );
if ( $res !== true ) {
$log[] = '[ERROR] Nie udało się otworzyć pliku ZIP (kod: ' . $res . ')';
return $log;
}
$log[] = '[OK] Otwarto archiwum ZIP, liczba plików: ' . $zip->numFiles;
$extracted = 0;
$errors = 0;
for ( $i = 0; $i < $zip->numFiles; $i++ ) {
$filename = str_replace( '\\', '/', $zip->getNameIndex( $i ) );
if ( substr( $filename, -1 ) === '/' ) {
$dirPath = $path . '/' . $filename;
if ( !is_dir( $dirPath ) ) {
@mkdir( $dirPath, 0755, true );
}
continue;
}
$targetFile = $path . '/' . $filename;
$targetDir = dirname( $targetFile );
if ( !is_dir( $targetDir ) ) {
@mkdir( $targetDir, 0755, true );
}
$existed = file_exists( $targetFile );
$content = $zip->getFromIndex( $i );
if ( $content === false ) {
$log[] = '[ERROR] Nie udało się odczytać z ZIP: ' . $filename;
$errors++;
continue;
}
if ( @file_put_contents( $targetFile, $content ) === false ) {
$log[] = '[ERROR] Nie udało się zapisać: ' . $filename;
$errors++;
} else {
$tag = $existed ? '[UPDATED]' : '[NEW]';
$log[] = $tag . ' ' . $filename . ' (' . strlen( $content ) . ' bajtów)';
$extracted++;
}
}
$log[] = '[OK] Rozpakowano ' . $extracted . ' plików, błędów: ' . $errors;
$zip->close();
if ( @unlink( $fileName ) ) {
$log[] = '[OK] Usunięto plik update.zip';
}
return $log;
}
private function saveLog( array $log ): void
{
@file_put_contents( '../libraries/update_log.txt', implode( "\n", $log ) );
}
/**
* Wykonuje zaległe migracje z tabeli pp_updates.
*/
public function runPendingMigrations(): void
{
$results = $this->db->select( 'pp_updates', [ 'name' ], [ 'done' => 0 ] );
if ( !is_array( $results ) ) {
return;
}
foreach ( $results as $row ) {
$method = $row['name'];
if ( method_exists( $this, $method ) ) {
$this->$method();
}
}
}
public function update0197(): void
{
$rows = $this->db->select( 'pp_shop_order_products', [ 'id', 'product_id' ], [ 'parent_product_id' => null ] );
if ( is_array( $rows ) ) {
foreach ( $rows as $row ) {
$parentId = $this->db->get( 'pp_shop_products', 'parent_id', [ 'id' => $row['product_id'] ] );
$this->db->update( 'pp_shop_order_products', [
'parent_product_id' => $parentId ?: $row['product_id'],
], [ 'id' => $row['id'] ] );
}
}
$this->db->update( 'pp_updates', [ 'done' => 1 ], [ 'name' => 'update0197' ] );
}
}

View File

@@ -1,13 +1,17 @@
<?php
namespace admin;
class Site
class App
{
// define APP_SECRET_KEY
const APP_SECRET_KEY = 'c3cb2537d25c0efc9e573d059d79c3b8';
static public function finalize_admin_login( array $user, string $domain, string $cookie_name, bool $remember = false ) {
/**
* Mapa nowych kontrolerów: module => fabryka kontrolera (DI)
*/
private static $newControllers = [];
public static function finalize_admin_login( array $user, string $domain, string $cookie_name, bool $remember = false )
{
\S::set_session( 'user', $user );
\S::delete_session( 'twofa_pending' );
@@ -17,18 +21,18 @@ class Site
'ts' => time()
];
$json = json_encode($payloadArr, JSON_UNESCAPED_SLASHES);
$sig = hash_hmac('sha256', $json, self::APP_SECRET_KEY);
$payload = base64_encode($json . '.' . $sig);
$json = json_encode( $payloadArr, JSON_UNESCAPED_SLASHES );
$sig = hash_hmac( 'sha256', $json, self::APP_SECRET_KEY );
$payload = base64_encode( $json . '.' . $sig );
setcookie( $cookie_name, $payload, [
'expires' => time() + (86400 * 14),
'expires' => time() + ( 86400 * 14 ),
'path' => '/',
'domain' => $domain,
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
] );
}
}
@@ -36,165 +40,183 @@ class Site
{
global $mdb;
$sa = \S::get('s-action');
$domain = preg_replace('/^www\./', '', $_SERVER['SERVER_NAME']);
$cookie_name = 'admin_remember_' . str_replace( '.', '-', $domain );
$users = new \Domain\User\UserRepository($mdb);
$sa = \S::get( 's-action' );
if ( !$sa ) return;
switch ($sa)
$domain = preg_replace( '/^www\./', '', $_SERVER['SERVER_NAME'] );
$cookie_name = 'admin_remember_' . str_replace( '.', '-', $domain );
$users = new \Domain\User\UserRepository( $mdb );
switch ( $sa )
{
case 'user-logon':
{
$login = \S::get('login');
$pass = \S::get('password');
$result = $users->logon($login, $pass);
$login = \S::get( 'login' );
$pass = \S::get( 'password' );
$result = $users->logon( $login, $pass );
if ( $result == 1 )
{
$user = $users->details($login);
$user = $users->details( $login );
if ( $user['twofa_enabled'] == 1 )
{
\S::set_session( 'twofa_pending', [
'uid' => (int)$user['id'],
'uid' => (int) $user['id'],
'login' => $login,
'remember' => (bool)\S::get('remember'),
'remember' => (bool) \S::get( 'remember' ),
'started' => time(),
] );
if ( !$users->sendTwofaCode( (int)$user['id'] ) )
if ( !$users->sendTwofaCode( (int) $user['id'] ) )
{
\S::alert('Nie udało się wysłać kodu 2FA. Spróbuj ponownie.');
\S::delete_session('twofa_pending');
header('Location: /admin/');
\S::alert( 'Nie udało się wysłać kodu 2FA. Spróbuj ponownie.' );
\S::delete_session( 'twofa_pending' );
header( 'Location: /admin/' );
exit;
}
header('Location: /admin/user/twofa/');
header( 'Location: /admin/user/twofa/' );
exit;
}
else
{
$user = $users->details($login);
self::finalize_admin_login(
$user,
$domain,
$cookie_name,
(bool)\S::get('remember')
);
header('Location: /admin/articles/list/');
exit;
}
}
else
{
if ($result == -1)
{
\S::alert('Z powodu 5 nieudanych prób Twoje konto zostało zablokowane.');
}
else
{
\S::alert('Podane hasło jest nieprawidłowe lub użytkownik nie istnieje.');
}
header('Location: /admin/');
self::finalize_admin_login( $user, $domain, $cookie_name, (bool) \S::get( 'remember' ) );
header( 'Location: /admin/articles/list/' );
exit;
}
}
break;
if ( $result == -1 )
\S::alert( 'Z powodu 5 nieudanych prób Twoje konto zostało zablokowane.' );
else
\S::alert( 'Podane hasło jest nieprawidłowe lub użytkownik nie istnieje.' );
header( 'Location: /admin/' );
exit;
case 'user-2fa-verify':
{
$pending = \S::get_session('twofa_pending');
$pending = \S::get_session( 'twofa_pending' );
if ( !$pending || empty( $pending['uid'] ) ) {
\S::alert('Sesja 2FA wygasła. Zaloguj się ponownie.');
header('Location: /admin/');
\S::alert( 'Sesja 2FA wygasła. Zaloguj się ponownie.' );
header( 'Location: /admin/' );
exit;
}
$code = trim((string)\S::get('twofa'));
if (!preg_match('/^\d{6}$/', $code))
$code = trim( (string) \S::get( 'twofa' ) );
if ( !preg_match( '/^\d{6}$/', $code ) )
{
\S::alert('Nieprawidłowy format kodu.');
header('Location: /admin/user/twofa/');
\S::alert( 'Nieprawidłowy format kodu.' );
header( 'Location: /admin/user/twofa/' );
exit;
}
$ok = $users->verifyTwofaCode((int)$pending['uid'], $code);
if (!$ok)
if ( !$users->verifyTwofaCode( (int) $pending['uid'], $code ) )
{
\S::alert('Błędny lub wygasły kod.');
header('Location: /admin/user/twofa/');
\S::alert( 'Błędny lub wygasły kod.' );
header( 'Location: /admin/user/twofa/' );
exit;
}
// 2FA OK - finalna sesja
$user = $users->details($pending['login']);
self::finalize_admin_login(
$user,
$domain,
$cookie_name,
$pending['remember'] ? true : false
);
header('Location: /admin/articles/list/');
$user = $users->details( $pending['login'] );
self::finalize_admin_login( $user, $domain, $cookie_name, !empty( $pending['remember'] ) );
header( 'Location: /admin/articles/list/' );
exit;
}
break;
case 'user-2fa-resend':
{
$pending = \S::get_session('twofa_pending');
if (!$pending || empty($pending['uid']))
$pending = \S::get_session( 'twofa_pending' );
if ( !$pending || empty( $pending['uid'] ) )
{
\S::alert('Sesja 2FA wygasła. Zaloguj się ponownie.');
header('Location: /admin/');
\S::alert( 'Sesja 2FA wygasła. Zaloguj się ponownie.' );
header( 'Location: /admin/' );
exit;
}
if (!$users->sendTwofaCode((int)$pending['uid'], true))
{
\S::alert('Kod można wysłać ponownie po krótkiej przerwie.');
}
if ( !$users->sendTwofaCode( (int) $pending['uid'], true ) )
\S::alert( 'Kod można wysłać ponownie po krótkiej przerwie.' );
else
{
\S::alert('Nowy kod został wysłany.');
}
header('Location: /admin/user/twofa/');
\S::alert( 'Nowy kod został wysłany.' );
header( 'Location: /admin/user/twofa/' );
exit;
}
break;
case 'user-logout':
{
setcookie($cookie_name, "", [
setcookie( $cookie_name, '', [
'expires' => time() - 86400,
'path' => '/',
'domain' => $domain,
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
\S::delete_session('twofa_pending');
] );
\S::delete_session( 'twofa_pending' );
session_destroy();
header('Location: /admin/');
header( 'Location: /admin/' );
exit;
}
break;
}
}
/**
* Mapa nowych kontrolerów: module => fabryka kontrolera (DI)
* Przy migracji kolejnego kontrolera - dodaj wpis tutaj
* Entry point auth check + layout rendering.
*/
private static $newControllers = [];
public static function render(): string
{
global $user;
if ( \S::get( 'module' ) === 'user' && \S::get( 'action' ) === 'twofa' ) {
$controller = self::createController( 'Users' );
return $controller->twofa();
}
if ( !$user || !$user['admin'] )
{
$controller = self::createController( 'Users' );
return $controller->login_form();
}
$tpl = new \Tpl;
$tpl->content = self::route();
return $tpl->render( 'site/main-layout' );
}
/**
* Zwraca mapę fabryk kontrolerów (inicjalizacja runtime)
* Routing buduje nazwę modułu z URL i wywołuje akcję kontrolera.
*/
public static function route()
{
$_SESSION['admin'] = true;
if ( \S::get( 'p' ) )
\S::set_session( 'p', \S::get( 'p' ) );
// Budowanie nazwy modułu: shop_product → ShopProduct
$moduleName = '';
$parts = explode( '_', (string) \S::get( 'module' ) );
foreach ( $parts as $part )
$moduleName .= ucfirst( $part );
$action = \S::get( 'action' );
$controller = self::createController( $moduleName );
if ( $controller && method_exists( $controller, $action ) )
return $controller->$action();
\S::alert( 'Nieprawidłowy adres url.' );
return false;
}
/**
* Tworzy instancję kontrolera z Dependency Injection.
*/
private static function createController( string $moduleName )
{
$factories = self::getControllerFactories();
if ( !isset( $factories[$moduleName] ) )
return null;
$factory = $factories[$moduleName];
return is_callable( $factory ) ? $factory() : null;
}
/**
* Zwraca mapę fabryk kontrolerów (lazy init).
*/
private static function getControllerFactories(): array
{
@@ -202,9 +224,15 @@ class Site
return self::$newControllers;
self::$newControllers = [
'Dashboard' => function() {
global $mdb;
return new \admin\Controllers\DashboardController(
new \Domain\Dashboard\DashboardRepository( $mdb ),
new \Domain\ShopStatus\ShopStatusRepository( $mdb )
);
},
'Articles' => function() {
global $mdb;
return new \admin\Controllers\ArticlesController(
new \Domain\Article\ArticleRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb ),
@@ -214,14 +242,12 @@ class Site
},
'ArticlesArchive' => function() {
global $mdb;
return new \admin\Controllers\ArticlesArchiveController(
new \Domain\Article\ArticleRepository( $mdb )
);
},
'Banners' => function() {
global $mdb;
return new \admin\Controllers\BannerController(
new \Domain\Banner\BannerRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -229,7 +255,6 @@ class Site
},
'Settings' => function() {
global $mdb;
return new \admin\Controllers\SettingsController(
new \Domain\Settings\SettingsRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -237,22 +262,18 @@ class Site
},
'ProductArchive' => function() {
global $mdb;
return new \admin\Controllers\ProductArchiveController(
new \Domain\Product\ProductRepository( $mdb )
);
},
// Alias dla starego modułu /admin/archive/list/
'Archive' => function() {
global $mdb;
return new \admin\Controllers\ProductArchiveController(
new \Domain\Product\ProductRepository( $mdb )
);
},
'Dictionaries' => function() {
global $mdb;
return new \admin\Controllers\DictionariesController(
new \Domain\Dictionaries\DictionariesRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -263,21 +284,18 @@ class Site
},
'Users' => function() {
global $mdb;
return new \admin\Controllers\UsersController(
new \Domain\User\UserRepository( $mdb )
);
},
'Languages' => function() {
global $mdb;
return new \admin\Controllers\LanguagesController(
new \Domain\Languages\LanguagesRepository( $mdb )
);
},
'Layouts' => function() {
global $mdb;
return new \admin\Controllers\LayoutsController(
new \Domain\Layouts\LayoutsRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -285,7 +303,6 @@ class Site
},
'Newsletter' => function() {
global $mdb;
return new \admin\Controllers\NewsletterController(
new \Domain\Newsletter\NewsletterRepository(
$mdb,
@@ -296,7 +313,6 @@ class Site
},
'Scontainers' => function() {
global $mdb;
return new \admin\Controllers\ScontainersController(
new \Domain\Scontainers\ScontainersRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -304,21 +320,18 @@ class Site
},
'ShopPromotion' => function() {
global $mdb;
return new \admin\Controllers\ShopPromotionController(
new \Domain\Promotion\PromotionRepository( $mdb )
);
},
'ShopCoupon' => function() {
global $mdb;
return new \admin\Controllers\ShopCouponController(
new \Domain\Coupon\CouponRepository( $mdb )
);
},
'ShopAttribute' => function() {
global $mdb;
return new \admin\Controllers\ShopAttributeController(
new \Domain\Attribute\AttributeRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -326,14 +339,12 @@ class Site
},
'ShopPaymentMethod' => function() {
global $mdb;
return new \admin\Controllers\ShopPaymentMethodController(
new \Domain\PaymentMethod\PaymentMethodRepository( $mdb )
);
},
'ShopTransport' => function() {
global $mdb;
return new \admin\Controllers\ShopTransportController(
new \Domain\Transport\TransportRepository( $mdb ),
new \Domain\PaymentMethod\PaymentMethodRepository( $mdb )
@@ -341,7 +352,6 @@ class Site
},
'Pages' => function() {
global $mdb;
return new \admin\Controllers\PagesController(
new \Domain\Pages\PagesRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb ),
@@ -350,28 +360,24 @@ class Site
},
'Integrations' => function() {
global $mdb;
return new \admin\Controllers\IntegrationsController(
new \Domain\Integrations\IntegrationsRepository( $mdb )
);
},
'ShopStatuses' => function() {
global $mdb;
return new \admin\Controllers\ShopStatusesController(
new \Domain\ShopStatus\ShopStatusRepository( $mdb )
);
},
'ShopProductSets' => function() {
global $mdb;
return new \admin\Controllers\ShopProductSetsController(
new \Domain\ProductSet\ProductSetRepository( $mdb )
);
},
'ShopProducer' => function() {
global $mdb;
return new \admin\Controllers\ShopProducerController(
new \Domain\Producer\ProducerRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -379,7 +385,6 @@ class Site
},
'ShopCategory' => function() {
global $mdb;
return new \admin\Controllers\ShopCategoryController(
new \Domain\Category\CategoryRepository( $mdb ),
new \Domain\Languages\LanguagesRepository( $mdb )
@@ -387,116 +392,41 @@ class Site
},
'ShopProduct' => function() {
global $mdb;
return new \admin\Controllers\ShopProductController(
new \Domain\Product\ProductRepository( $mdb )
new \Domain\Product\ProductRepository( $mdb ),
new \Domain\Integrations\IntegrationsRepository( $mdb )
);
},
'ShopClients' => function() {
global $mdb;
return new \admin\Controllers\ShopClientsController(
new \Domain\Client\ClientRepository( $mdb )
);
},
'ShopOrder' => function() {
global $mdb;
return new \admin\Controllers\ShopOrderController(
new \Domain\Order\OrderAdminService(
new \Domain\Order\OrderRepository( $mdb )
)
);
},
'Update' => function() {
global $mdb;
return new \admin\Controllers\UpdateController(
new \Domain\Update\UpdateRepository( $mdb )
);
},
];
return self::$newControllers;
}
/**
* Tworzy instancję nowego kontrolera z Dependency Injection
*/
private static function createController( string $moduleName )
public static function update()
{
global $mdb;
$factories = self::getControllerFactories();
if ( !isset( $factories[$moduleName] ) )
return null;
$factory = $factories[$moduleName];
if ( !is_callable( $factory ) )
return null;
return $factory();
}
public static function route()
{
$_SESSION['admin'] = true;
if ( \S::get( 'p' ) )
\S::set_session( 'p' , \S::get( 'p' ) );
$page = \S::get_session( 'p' );
// Budowanie nazwy modułu
$moduleName = '';
$results = explode( '_', \S::get( 'module' ) );
if ( is_array( $results ) ) foreach ( $results as $row )
$moduleName .= ucfirst( $row );
$action = \S::get( 'action' );
// 1. Sprawdź czy istnieje nowy kontroler
$factories = self::getControllerFactories();
if ( isset( $factories[$moduleName] ) )
{
$controller = self::createController( $moduleName );
if ( $controller )
{
if ( method_exists( $controller, $action ) )
{
return $controller->$action();
}
if ( $moduleName === 'ShopAttribute' )
{
\S::alert( 'Nieprawidłowy adres url.' );
return false;
}
}
}
// 2. Fallback na stary kontroler
$class = '\admin\controls\\' . $moduleName;
if ( class_exists( $class ) and method_exists( new $class, $action ) )
return call_user_func_array( array( $class, $action ), array() );
else
{
\S::alert( 'Nieprawidłowy adres url.' );
return false;
}
}
static public function update()
{
global $mdb;
if ( $results = $mdb -> select( 'pp_updates', [ 'name' ], [ 'done' => 0 ] ) )
{
foreach ( $results as $row )
{
$class = '\admin\factory\Update';
$method = $row['name'];
if ( class_exists( $class ) and method_exists( new $class, $method ) )
call_user_func_array( array( $class, $method ), array() );
}
}
$repository = new \Domain\Update\UpdateRepository( $mdb );
$repository->runPendingMigrations();
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace admin\Controllers;
use Domain\Dashboard\DashboardRepository;
use Domain\ShopStatus\ShopStatusRepository;
class DashboardController
{
private DashboardRepository $repository;
private ShopStatusRepository $statusesRepository;
public function __construct( DashboardRepository $repository, ShopStatusRepository $statusesRepository )
{
$this->repository = $repository;
$this->statusesRepository = $statusesRepository;
}
public function main_view(): string
{
return \Tpl::view( 'dashboard/main-view', [
'last_orders' => $this->repository->lastOrders(),
'order_statuses' => $this->statusesRepository->allStatuses(),
'sales' => $this->repository->last24MonthsSales(),
'best_sales_products' => $this->repository->bestSalesProducts(),
'most_view_products' => $this->repository->mostViewedProducts(),
'sales_grid' => $this->repository->salesGrid(),
'summary_sales' => $this->repository->summarySales(),
'summary_orders' => $this->repository->summaryOrders(),
] );
}
}

View File

@@ -60,7 +60,7 @@ class ProductArchiveController
$imageSrc = '/' . ltrim($imageSrc, '/');
}
$categories = trim((string)\admin\factory\ShopProduct::product_categories($id));
$categories = trim((string)$this->repository->productCategoriesText($id));
$categoriesHtml = '';
if ($categories !== '') {
$categoriesHtml = '<small class="text-muted product-categories">'

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
<?php
namespace admin\Controllers;
use Domain\Update\UpdateRepository;
class UpdateController
{
private UpdateRepository $repository;
public function __construct( UpdateRepository $repository )
{
$this->repository = $repository;
}
public function main_view(): string
{
return \Tpl::view( 'update/main-view', [
'ver' => \S::get_version(),
'new_ver' => \S::get_new_version(),
] );
}
public function update(): void
{
$result = $this->repository->update();
if ( !$result['success'] ) {
\S::alert( 'W trakcie aktualizacji systemu wystąpił błąd. Proszę spróbować ponownie.' );
} else {
\S::set_message( 'Aktualizacja przebiegła pomyślnie.' );
}
header( 'Location: /admin/update/main_view/' );
exit;
}
public function updateAll(): void
{
$result = $this->repository->update();
$response = [
'status' => !empty( $result['success'] ) && empty( $result['no_updates'] ),
'version' => number_format( (float) \S::get( 'version_current' ) + 0.001, 3, '.', '' ),
];
echo json_encode( $response );
exit;
}
}

View File

@@ -1,22 +0,0 @@
<?
namespace admin\controls;
class Dashboard
{
static public function main_view()
{
global $mdb;
$statusesRepository = new \Domain\ShopStatus\ShopStatusRepository( $mdb );
return \Tpl::view( 'dashboard/main-view', [
'last_orders' => \shop\Dashboard::last_orders(),
'order_statuses' => $statusesRepository -> allStatuses(),
'sales' => \shop\Dashboard::last_24_months_sales(),
'best_sales_products' => \shop\Dashboard::best_sales_products(),
'most_view_products' => \shop\Dashboard::most_view_products(),
'sales_grid' => \shop\Dashboard::sales_grid(),
'summary_sales' => \shop\Dashboard::summary_sales(),
'summary_orders' => \shop\Dashboard::summary_orders(),
] );
}
}

View File

@@ -1,381 +0,0 @@
<?php
namespace admin\controls;
class ShopProduct
{
static public function generate_combination()
{
foreach ( $_POST as $key => $val )
{
if ( strpos( $key, 'attribute_' ) !== false )
{
$attribute = explode( 'attribute_', $key );
$attributes[ $attribute[1] ] = $val;
}
}
if ( \admin\factory\ShopProduct::generate_permutation( (int) \S::get( 'product_id' ), $attributes ) )
\S::alert( 'Kombinacje produktu zostały wygenerowane.' );
header( 'Location: /admin/shop_product/product_combination/product_id=' . (int) \S::get( 'product_id' ) );
exit;
}
//usunięcie kombinacji produktu
static public function delete_combination()
{
if ( \admin\factory\ShopProduct::delete_combination( (int)\S::get( 'combination_id' ) ) )
\S::alert( 'Kombinacja produktu została usunięta' );
else
\S::alert( 'Podczas usuwania kombinacji produktu wystąpił błąd. Proszę spróbować ponownie' );
header( 'Location: /admin/shop_product/product_combination/product_id=' . \S::get( 'product_id' ) );
exit;
}
static public function duplicate_product()
{
if ( \admin\factory\ShopProduct::duplicate_product( (int)\S::get( 'product-id' ), (int)\S::get( 'combination' ) ) )
\S::set_message( 'Produkt został zduplikowany.' );
else
\S::alert( 'Podczas duplikowania produktu wystąpił błąd. Proszę spróbować ponownie' );
header( 'Location: /admin/shop_product/view_list/' );
exit;
}
public static function image_delete()
{
$response = [ 'status' => 'error', 'msg' => 'Podczas usuwania zdjecia wystąpił błąd. Proszę spróbować ponownie.' ];
if ( \admin\factory\ShopProduct::delete_img( \S::get( 'image_id' ) ) )
$response = [ 'status' => 'ok' ];
echo json_encode( $response );
exit;
}
public static function images_order_save()
{
if ( \admin\factory\ShopProduct::images_order_save( \S::get( 'product_id' ), \S::get( 'order' ) ) )
echo json_encode( [ 'status' => 'ok', 'msg' => 'Produkt został zapisany.' ] );
exit;
}
public static function image_alt_change()
{
$response = [ 'status' => 'error', 'msg' => 'Podczas zmiany atrybutu alt zdjęcia wystąpił błąd. Proszę spróbować ponownie.' ];
if ( \admin\factory\ShopProduct::image_alt_change( \S::get( 'image_id' ), \S::get( 'image_alt' ) ) )
$response = [ 'status' => 'ok' ];
echo json_encode( $response );
exit;
}
// szybka zmiana statusu produktu
static public function change_product_status() {
if ( \admin\factory\ShopProduct::change_product_status( (int)\S::get( 'product-id' ) ) )
\S::set_message( 'Status produktu został zmieniony' );
header( 'Location: ' . $_SERVER['HTTP_REFERER'] );
exit;
}
// szybka zmiana google xml label
static public function product_change_custom_label()
{
$response = [ 'status' => 'error', 'msg' => 'Podczas zmiany google xml label wystąpił błąd. Proszę spróbować ponownie.' ];
if ( \admin\factory\ShopProduct::product_change_custom_label( (int) \S::get( 'product_id' ), \S::get( 'custom_label' ), \S::get( 'value' ) ) )
$response = [ 'status' => 'ok' ];
echo json_encode( $response );
exit;
}
// szybka zmiana ceny promocyjnej
static public function product_change_price_brutto_promo()
{
$response = [ 'status' => 'error', 'msg' => 'Podczas zmiany ceny wystąpił błąd. Proszę spróbować ponownie.' ];
if ( \admin\factory\ShopProduct::product_change_price_brutto_promo( (int) \S::get( 'product_id' ), \S::get( 'price' ) ) )
$response = [ 'status' => 'ok' ];
echo json_encode( $response );
exit;
}
// szybka zmiana ceny
static public function product_change_price_brutto()
{
$response = [ 'status' => 'error', 'msg' => 'Podczas zmiany ceny wystąpił błąd. Proszę spróbować ponownie.' ];
if ( \admin\factory\ShopProduct::product_change_price_brutto( (int) \S::get( 'product_id' ), \S::get( 'price' ) ) )
$response = [ 'status' => 'ok' ];
echo json_encode( $response );
exit;
}
// pobierz bezpośredni url produktu
static public function ajax_product_url()
{
echo json_encode( [ 'url' => \shop\Product::getProductUrl( \S::get( 'product_id' ) ) ] );
exit;
}
// zapisanie produktu
public static function save()
{
$response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania produktu wystąpił błąd. Proszę spróbować ponownie.' ];
$values = json_decode( \S::get( 'values' ), true );
if ( $id = \admin\factory\ShopProduct::save(
$values['id'], $values['name'], $values['short_description'], $values['description'], $values['status'], $values['meta_description'], $values['meta_keywords'], $values['seo_link'],
$values['copy_from'], $values['categories'], $values['price_netto'], $values['price_brutto'], $values['vat'], $values['promoted'], $values['warehouse_message_zero'], $values['warehouse_message_nonzero'], $values['tab_name_1'],
$values['tab_description_1'], $values['tab_name_2'], $values['tab_description_2'], $values['layout_id'], $values['products_related'], (int) $values['set'], $values['price_netto_promo'], $values['price_brutto_promo'],
$values['new_to_date'], $values['stock_0_buy'], $values['wp'], $values['custom_label_0'], $values['custom_label_1'], $values['custom_label_2'], $values['custom_label_3'], $values['custom_label_4'], $values['additional_message'], (int)$values['quantity'], $values['additional_message_text'], $values['additional_message_required'] == 'on' ? 1 : 0, $values['canonical'], $values['meta_title'], $values['producer_id'], $values['sku'], $values['ean'], $values['product_unit'], $values['weight'], $values['xml_name'], $values['custom_field_name'], $values['custom_field_required'], $values['security_information'], $values['custom_field_type']
) ) {
$response = [ 'status' => 'ok', 'msg' => 'Produkt został zapisany.', 'id' => $id ];
}
echo json_encode( $response );
exit;
}
// product_unarchive
static public function product_unarchive()
{
if ( \admin\factory\ShopProduct::product_unarchive( (int) \S::get( 'product_id' ) ) )
\S::alert( 'Produkt został przywrócony z archiwum.' );
else
\S::alert( 'Podczas przywracania produktu z archiwum wystąpił błąd. Proszę spróbować ponownie' );
header( 'Location: /admin/product_archive/list/' );
exit;
}
static public function product_archive()
{
if ( \admin\factory\ShopProduct::product_archive( (int) \S::get( 'product_id' ) ) )
\S::alert( 'Produkt został przeniesiony do archiwum.' );
else
\S::alert( 'Podczas przenoszenia produktu do archiwum wystąpił błąd. Proszę spróbować ponownie' );
header( 'Location: /admin/shop_product/view_list/' );
exit;
}
public static function product_delete()
{
if ( \admin\factory\ShopProduct::product_delete( (int) \S::get( 'id' ) ) )
\S::set_message( 'Produkt został usunięty.' );
else
\S::alert( 'Podczas usuwania produktu wystąpił błąd. Proszę spróbować ponownie' );
header( 'Location: /admin/shop_product/view_list/' );
exit;
}
// edycja produktu
public static function product_edit() {
global $user, $mdb;
if ( !$user ) {
header( 'Location: /admin/' );
exit;
}
\admin\factory\ShopProduct::delete_nonassigned_images();
\admin\factory\ShopProduct::delete_nonassigned_files();
return \Tpl::view( 'shop-product/product-edit', [
'product' => \admin\factory\ShopProduct::product_details( (int) \S::get( 'id' ) ),
'languages' => ( new \Domain\Languages\LanguagesRepository( $GLOBALS['mdb'] ) )->languagesList(),
'categories' => ( new \Domain\Category\CategoryRepository( $GLOBALS['mdb'] ) )->subcategories( null ),
'layouts' => self::layouts_for_product_edit( $mdb ),
'products' => \admin\factory\ShopProduct::products_list(),
'dlang' => \front\factory\Languages::default_language(),
'sets' => \shop\ProductSet::sets_list(),
'producers' => ( new \Domain\Producer\ProducerRepository( $mdb ) )->allProducers(),
'units' => ( new \Domain\Dictionaries\DictionariesRepository( $mdb ) ) -> allUnits(),
'user' => $user
] );
}
private static function layouts_for_product_edit( $db )
{
if ( class_exists( '\Domain\Layouts\LayoutsRepository' ) )
{
$rows = ( new \Domain\Layouts\LayoutsRepository( $db ) ) -> listAll();
return is_array( $rows ) ? $rows : [];
}
return [];
}
// ajax_load_products ARCHIVE
static public function ajax_load_products_archive()
{
echo json_encode( [
'status' => 'deprecated',
'msg' => 'Endpoint nie jest juz wspierany. Uzyj /admin/product_archive/list/.',
'redirect_url' => '/admin/product_archive/list/'
] );
exit;
}
// ajax_load_products
static public function ajax_load_products() {
global $mdb;
$integrationsRepository = new \Domain\Integrations\IntegrationsRepository( $mdb );
$response = [ 'status' => 'error', 'msg' => 'Podczas ładowania produktów wystąpił błąd. Proszę spróbować ponownie.' ];
\S::set_session( 'products_list_current_page', \S::get( 'current_page' ) );
\S::set_session( 'products_list_query', \S::get( 'query' ) );
if ( $products = \admin\factory\ShopProduct::ajax_products_list( \S::get_session( 'products_list_current_page' ), \S::get_session( 'products_list_query' ) ) ) {
$response = [
'status' => 'ok',
'pagination_max' => ceil( $products['products_count'] / 10 ),
'html' => \Tpl::view( 'shop-product/products-list-table', [
'products' => $products['products'],
'current_page' => \S::get( 'current_page' ),
'apilo_enabled' => $integrationsRepository -> getSetting( 'apilo', 'enabled' ),
'show_xml_data' => \S::get_session( 'show_xml_data' )
] )
];
}
echo json_encode( $response );
exit;
}
static public function view_list()
{
global $mdb;
$integrationsRepository = new \Domain\Integrations\IntegrationsRepository( $mdb );
$current_page = \S::get_session( 'products_list_current_page' );
if ( !$current_page ) {
$current_page = 1;
\S::set_session( 'products_list_current_page', $current_page );
}
$query = \S::get_session( 'products_list_query' );
if ( $query ) {
$query_array = [];
parse_str( $query, $query_array );
}
if ( \S::get( 'show_xml_data' ) === 'true' ) {
\S::set_session( 'show_xml_data', true );
} else if ( \S::get( 'show_xml_data' ) === 'false' ) {
\S::set_session( 'show_xml_data', false );
}
return \Tpl::view( 'shop-product/products-list', [
'current_page' => $current_page,
'query_array' => $query_array,
'pagination_max' => ceil( \admin\factory\ShopProduct::count_product() / 10 ),
'apilo_enabled' => $integrationsRepository -> getSetting( 'apilo', 'enabled' ),
'show_xml_data' => \S::get_session( 'show_xml_data' ),
'shoppro_enabled' => $integrationsRepository -> getSetting( 'shoppro', 'enabled' )
] );
}
//
// KOMBINACJE PRODUKTU
//
// zapisanie możliwości zakupu przy stanie 0 w kombinacji produktu
static public function product_combination_stock_0_buy_save()
{
\admin\factory\ShopProduct::product_combination_stock_0_buy_save( (int)\S::get( 'product_id' ), \S::get( 'stock_0_buy' ) );
exit;
}
// zapisanie sku w kombinacji produktu
static public function product_combination_sku_save()
{
\admin\factory\ShopProduct::product_combination_sku_save( (int)\S::get( 'product_id' ), \S::get( 'sku' ) );
exit;
}
// zapisanie ilości w kombinacji produktu
static public function product_combination_quantity_save()
{
\admin\factory\ShopProduct::product_combination_quantity_save( (int)\S::get( 'product_id' ), \S::get( 'quantity' ) );
exit;
}
// zapisanie ceny w kombinacji produktu
static public function product_combination_price_save()
{
\admin\factory\ShopProduct::product_combination_price_save( (int)\S::get( 'product_id' ), \S::get( 'price' ) );
exit;
}
//wyświetlenie kombinacji produktu
static public function product_combination()
{
global $mdb;
return \Tpl::view( 'shop-product/product-combination', [
'product' => \admin\factory\ShopProduct::product_details( (int) \S::get( 'product_id' ) ),
'attributes' => ( new \Domain\Attribute\AttributeRepository( $mdb ) ) -> getAttributesListForCombinations(),
'default_language' => \front\factory\Languages::default_language(),
'product_permutations' => \admin\factory\ShopProduct::get_product_permutations( (int) \S::get( 'product_id' ) )
] );
}
// generate_sku_code
static public function generate_sku_code() {
$response = [ 'status' => 'error', 'msg' => 'Podczas generowania kodu sku wystąpił błąd. Proszę spróbować ponownie.' ];
if ( $sku = \shop\Product::generate_sku_code( \S::get( 'product_id' ) ) )
$response = [ 'status' => 'ok', 'sku' => $sku ];
echo json_encode( $response );
exit;
}
// product_xml_name_save
static public function product_xml_name_save() {
$response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania nazwy produktu wystąpił błąd. Proszę spróbować ponownie.' ];
if ( \shop\Product::product_xml_name_save( \S::get( 'product_id' ), \S::get( 'product_xml_name' ), \S::get( 'lang_id' ) ) )
$response = [ 'status' => 'ok' ];
echo json_encode( $response );
exit;
}
// product_custom_label_suggestions
static public function product_custom_label_suggestions() {
$response = [ 'status' => 'error', 'msg' => 'Podczas pobierania sugestii dla custom label wystąpił błąd. Proszę spróbować ponownie.' ];
if ( $suggestions = \shop\Product::product_custom_label_suggestions( \S::get( 'custom_label' ), \S::get( 'label_type' ) ) )
$response = [ 'status' => 'ok', 'suggestions' => $suggestions ];
echo json_encode( $response );
exit;
}
// product_custom_label_save
static public function product_custom_label_save() {
$response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania custom label wystąpił błąd. Proszę spróbować ponownie.' ];
if ( \shop\Product::product_custom_label_save( \S::get( 'product_id' ), \S::get( 'custom_label' ), \S::get( 'label_type' ) ) )
$response = [ 'status' => 'ok' ];
echo json_encode( $response );
exit;
}
}

View File

@@ -1,29 +0,0 @@
<?php
namespace admin\controls;
class Update
{
public static function update()
{
if ( !\admin\factory\Update::update() )
\S::alert( 'W trakcie aktualizacji systemu wystąpił błąd. Proszę spróbować ponownie.' );
else
\S::set_message( 'Aktualizacja przebiegła pomyślnie.' );
header( 'Location: /admin/update/main_view/' );
exit;
}
public static function updateAll()
{
$response['status'] = \admin\factory\Update::update();
$response['version'] = number_format( \S::get('version_current') + 0.001, 3, '.', '' );
echo json_encode( $response );
exit;
}
public static function main_view()
{
return \admin\view\Update::main_view();
}
}

View File

@@ -1,173 +0,0 @@
<?php
namespace admin\factory;
class Articles
{
/**
* @deprecated Logika przeniesiona do Domain\Article\ArticleRepository::saveGalleryOrder().
*/
public static function gallery_order_save( $article_id, $order )
{
global $mdb;
$repository = new \Domain\Article\ArticleRepository( $mdb );
return $repository->saveGalleryOrder( (int)$article_id, (string)$order );
}
public static function image_alt_change( $image_id, $image_alt )
{
global $mdb;
$result = $mdb -> update( 'pp_articles_images', [
'alt' => $image_alt
], [
'id' => $image_id
] );
\S::delete_cache();
return $result;
}
public static function article_url( $article_id )
{
global $mdb;
$results = $mdb -> query( "SELECT seo_link FROM pp_articles_langs AS pal, pp_langs AS pl WHERE lang_id = pl.id AND article_id = " . (int)$article_id . " AND seo_link != '' ORDER BY o ASC LIMIT 1" ) -> fetchAll();
if ( !$results[0]['seo_link'] )
{
$title = self::article_title( $article_id );
return 'a-' . $article_id . '-' . \S::seo( $title );
}
else
return $results[0]['seo_link'];
}
public static function articles_by_date_add( $date_start, $date_end )
{
global $mdb;
$results = $mdb -> query( 'SELECT '
. 'id '
. 'FROM '
. 'pp_articles '
. 'WHERE '
. 'status = 1 '
. 'AND '
. 'date_add BETWEEN \'' . $date_start . '\' AND \'' . $date_end . '\' '
. 'ORDER BY '
. 'date_add DESC' ) -> fetchAll();
if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
$articles[] = \front\factory\Articles::article_details( $row['id'], 'pl' );
return $articles;
}
public static function article_pages( $article_id )
{
global $mdb;
$pagesRepository = new \Domain\Pages\PagesRepository( $mdb );
$results = $mdb -> query( "SELECT page_id FROM pp_articles_pages WHERE article_id = " . (int)$article_id ) -> fetchAll();
if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
{
if ( $out == '' )
$out .= ' - ';
$out .= $pagesRepository->pageTitle( (int)$row['page_id'] );
if ( end( $results ) != $row )
$out .= ' / ';
}
return $out;
}
public static function article_title( $article_id )
{
global $mdb;
$results = $mdb -> query( "SELECT title FROM pp_articles_langs AS pal, pp_langs AS pl WHERE lang_id = pl.id AND article_id = " . (int)$article_id . " AND title != '' ORDER BY o ASC LIMIT 1" ) -> fetchAll();
return $results[0]['title'];
}
/**
* @deprecated Logika przeniesiona do Domain\Article\ArticleRepository::archive().
*/
public static function articles_set_archive( $article_id )
{
global $mdb;
$repository = new \Domain\Article\ArticleRepository( $mdb );
return $repository->archive( (int)$article_id );
}
public static function file_name_change( $file_id, $file_name )
{
global $mdb;
$mdb -> update( 'pp_articles_files', [ 'name' => $file_name ], [ 'id' => (int)$file_id ] );
return true;
}
public static function delete_file( $file_id )
{
global $mdb;
$mdb -> update( 'pp_articles_files', [ 'to_delete' => 1 ], [ 'id' => (int)$file_id ] );
return true;
}
public static function delete_img( $image_id )
{
global $mdb;
$mdb -> update( 'pp_articles_images', [ 'to_delete' => 1 ], [ 'id' => (int)$image_id ] );
return true;
}
public static function article_details( $article_id )
{
global $mdb;
$repository = new \Domain\Article\ArticleRepository( $mdb );
return $repository->find( (int)$article_id );
}
public static function max_order()
{
global $mdb;
return $mdb -> max( 'pp_articles_pages', 'o' );
}
/**
* @deprecated Logika przeniesiona do Domain\Article\ArticleRepository::save().
* Ta metoda pozostaje jako fasada dla backward compatibility.
*/
public static function article_save(
$article_id, $title, $main_image, $entry, $text, $table_of_contents, $status, $show_title, $show_table_of_contents, $show_date_add, $date_add, $show_date_modify, $date_modify, $seo_link, $meta_title, $meta_description, $meta_keywords, $layout_id, $pages,
$noindex, $repeat_entry, $copy_from, $social_icons, $block_direct_access )
{
global $mdb, $user;
$repository = new \Domain\Article\ArticleRepository( $mdb );
return $repository->save( (int)$article_id, [
'title' => $title, 'main_image' => $main_image, 'entry' => $entry,
'text' => $text, 'table_of_contents' => $table_of_contents,
'status' => $status, 'show_title' => $show_title,
'show_table_of_contents' => $show_table_of_contents,
'show_date_add' => $show_date_add, 'date_add' => $date_add,
'show_date_modify' => $show_date_modify, 'date_modify' => $date_modify,
'seo_link' => $seo_link, 'meta_title' => $meta_title,
'meta_description' => $meta_description, 'meta_keywords' => $meta_keywords,
'layout_id' => $layout_id, 'pages' => $pages, 'noindex' => $noindex,
'repeat_entry' => $repeat_entry, 'copy_from' => $copy_from,
'social_icons' => $social_icons, 'block_direct_access' => $block_direct_access,
], (int)$user['id'] );
}
public static function delete_nonassigned_files()
{
global $mdb;
$repository = new \Domain\Article\ArticleRepository( $mdb );
$repository->deleteNonassignedFiles();
}
public static function delete_nonassigned_images()
{
global $mdb;
$repository = new \Domain\Article\ArticleRepository( $mdb );
$repository->deleteNonassignedImages();
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -1,365 +0,0 @@
<?php
namespace admin\factory;
class Update
{
public static function update()
{
global $mdb, $settings;
@file_put_contents( '../libraries/update_log.txt', '' );
$log = [];
$log[] = '[START] Rozpoczęcie aktualizacji - ' . date('Y-m-d H:i:s');
$log[] = '[INFO] Aktualna wersja: ' . \S::get_version();
\S::delete_session( 'new-version' );
$versions_url = 'https://shoppro.project-dc.pl/updates/versions.php?key=' . $settings['update_key'];
$versions = @file_get_contents( $versions_url );
if ( $versions === false )
{
$log[] = '[ERROR] Nie udało się pobrać listy wersji z: ' . $versions_url;
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$log[] = '[OK] Pobrano listę wersji';
$versions = explode( PHP_EOL, $versions );
$log[] = '[INFO] Znaleziono ' . count($versions) . ' wersji do sprawdzenia';
foreach ( $versions as $ver )
{
$ver = trim( $ver );
if ( floatval( $ver ) > (float)\S::get_version() )
{
$log[] = '[INFO] Aktualizacja do wersji: ' . $ver;
if ( strlen( $ver ) == 5 )
$dir = substr( $ver, 0, strlen( $ver ) - 2 ) . 0;
else
$dir = substr( $ver, 0, strlen( $ver ) - 1 ) . 0;
$zip_url = 'https://shoppro.project-dc.pl/updates/' . $dir . '/ver_' . $ver . '.zip';
$log[] = '[INFO] Pobieranie pliku ZIP: ' . $zip_url;
$file = @file_get_contents( $zip_url );
if ( $file === false )
{
$log[] = '[ERROR] Nie udało się pobrać pliku ZIP';
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$file_size = strlen( $file );
$log[] = '[OK] Pobrano plik ZIP, rozmiar: ' . $file_size . ' bajtów';
if ( $file_size < 100 )
{
$log[] = '[ERROR] Plik ZIP jest za mały (prawdopodobnie błąd pobierania)';
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$dlHandler = @fopen( 'update.zip' , 'w' );
if ( !$dlHandler )
{
$log[] = '[ERROR] Nie udało się otworzyć pliku update.zip do zapisu';
$log[] = '[INFO] Katalog roboczy: ' . getcwd();
$log[] = '[INFO] Uprawnienia katalogu: ' . substr(sprintf('%o', fileperms('.')), -4);
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$written = fwrite( $dlHandler, $file );
fclose( $dlHandler );
if ( $written === false || $written === 0 )
{
$log[] = '[ERROR] Nie udało się zapisać pliku ZIP (zapisano: ' . ($written === false ? 'false' : $written) . ' bajtów)';
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$log[] = '[OK] Zapisano plik ZIP (' . $written . ' bajtów)';
if ( !file_exists( 'update.zip' ) )
{
$log[] = '[ERROR] Plik update.zip nie istnieje po zapisie';
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$actual_size = filesize( 'update.zip' );
$log[] = '[OK] Plik update.zip istnieje, rozmiar na dysku: ' . $actual_size . ' bajtów';
/* aktualizacja bazy danych */
$sql_url = 'https://shoppro.project-dc.pl/updates/' . $dir . '/ver_' . $ver . '_sql.txt';
$log[] = '[INFO] Sprawdzanie aktualizacji SQL: ' . $sql_url;
$ch = curl_init( $sql_url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
$response = curl_exec( $ch );
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
$content_type = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
curl_close( $ch );
$sql = [];
if ( $response && strpos( $content_type, 'text/plain' ) !== false )
{
$sql = explode( PHP_EOL, $response );
$log[] = '[OK] Pobrano ' . count($sql) . ' zapytań SQL';
}
else
{
$log[] = '[INFO] Brak aktualizacji SQL (HTTP: ' . $http_code . ')';
}
if ( is_array( $sql ) && !empty( $sql ) )
{
$sql_success = 0;
$sql_errors = 0;
foreach ( $sql as $query )
{
$query = trim( $query );
if ( !empty( $query ) )
{
$result = $mdb->query( $query );
if ( $result ) $sql_success++;
else $sql_errors++;
}
}
$log[] = '[INFO] Wykonano zapytania SQL - sukces: ' . $sql_success . ', błędy: ' . $sql_errors;
}
/* usuwanie zbędnych plików */
$files_url = 'https://shoppro.project-dc.pl/updates/' . $dir . '/ver_' . $ver . '_files.txt';
$log[] = '[INFO] Sprawdzanie plików do usunięcia: ' . $files_url;
$ch = curl_init( $files_url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HEADER, false );
$response = curl_exec( $ch );
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
$content_type = curl_getinfo( $ch, CURLINFO_CONTENT_TYPE );
curl_close( $ch );
$files = [];
if ( $response && strpos( $content_type, 'text/plain' ) !== false )
$files = explode( PHP_EOL, $response );
$deleted_files = 0;
$deleted_dirs = 0;
if ( is_array( $files ) && !empty( $files ) )
{
foreach ( $files as $file )
{
if ( strpos( $file, 'F: ' ) !== false )
{
$file = substr( $file, 3, strlen( $file ) );
if ( file_exists( $file ) )
{
if ( @unlink( $file ) ) $deleted_files++;
else $log[] = '[WARNING] Nie udało się usunąć pliku: ' . $file;
}
}
if ( strpos( $file, 'D: ' ) !== false )
{
$dir_to_delete = substr( $file, 3, strlen( $file ) );
if ( is_dir( $dir_to_delete ) )
{
\S::delete_dir( $dir_to_delete );
$deleted_dirs++;
}
}
}
}
$log[] = '[INFO] Usunięto plików: ' . $deleted_files . ', katalogów: ' . $deleted_dirs;
/* wgrywanie nowych plików */
$file_name = 'update.zip';
$log[] = '[INFO] Rozpoczęcie rozpakowywania pliku ZIP';
$path = pathinfo( realpath( $file_name ), PATHINFO_DIRNAME );
$log[] = '[INFO] Ścieżka pathinfo: ' . $path;
$path = substr( $path, 0, strlen( $path ) - 5 );
$log[] = '[INFO] Ścieżka docelowa (po obcięciu): ' . $path;
if ( !is_dir( $path ) )
{
$log[] = '[ERROR] Ścieżka docelowa nie istnieje: ' . $path;
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
if ( !is_writable( $path ) )
{
$log[] = '[ERROR] Brak uprawnień do zapisu w: ' . $path;
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$log[] = '[OK] Ścieżka docelowa istnieje i jest zapisywalna';
$zip = new \ZipArchive;
$res = $zip->open( $file_name );
if ( $res !== true )
{
$zip_errors = [
\ZipArchive::ER_EXISTS => 'Plik już istnieje',
\ZipArchive::ER_INCONS => 'Archiwum ZIP jest niespójne',
\ZipArchive::ER_INVAL => 'Nieprawidłowy argument',
\ZipArchive::ER_MEMORY => 'Błąd alokacji pamięci',
\ZipArchive::ER_NOENT => 'Plik nie istnieje',
\ZipArchive::ER_NOZIP => 'Plik nie jest archiwum ZIP',
\ZipArchive::ER_OPEN => 'Nie można otworzyć pliku',
\ZipArchive::ER_READ => 'Błąd odczytu',
\ZipArchive::ER_SEEK => 'Błąd seek',
];
$error_msg = isset( $zip_errors[$res] ) ? $zip_errors[$res] : 'Nieznany błąd (' . $res . ')';
$log[] = '[ERROR] Nie udało się otworzyć pliku ZIP: ' . $error_msg;
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
$log[] = '[OK] Otwarto archiwum ZIP, liczba plików: ' . $zip->numFiles;
$extracted_count = 0;
$extract_errors = 0;
$skipped_dirs = 0;
for ( $i = 0; $i < $zip->numFiles; $i++ )
{
$filename = $zip->getNameIndex( $i );
$filename_clean = str_replace( '\\', '/', $filename );
if ( substr( $filename_clean, -1 ) === '/' )
{
$dir_path = $path . '/' . $filename_clean;
if ( !is_dir( $dir_path ) )
{
if ( @mkdir( $dir_path, 0755, true ) )
$log[] = '[DIR] Utworzono katalog: ' . $filename_clean;
else
$log[] = '[WARNING] Nie udało się utworzyć katalogu: ' . $filename_clean;
}
$skipped_dirs++;
continue;
}
$target_file = $path . '/' . $filename_clean;
$target_dir = dirname( $target_file );
if ( !is_dir( $target_dir ) )
{
if ( !@mkdir( $target_dir, 0755, true ) )
{
$log[] = '[ERROR] Nie udało się utworzyć katalogu dla: ' . $filename_clean;
$extract_errors++;
continue;
}
}
$file_existed = file_exists( $target_file );
$old_size = $file_existed ? filesize( $target_file ) : 0;
$old_mtime = $file_existed ? filemtime( $target_file ) : 0;
$content = $zip->getFromIndex( $i );
if ( $content === false )
{
$log[] = '[ERROR] Nie udało się odczytać z ZIP: ' . $filename_clean;
$extract_errors++;
continue;
}
$write_result = @file_put_contents( $target_file, $content );
if ( $write_result === false )
{
$log[] = '[ERROR] Nie udało się zapisać: ' . $filename_clean . ' (uprawnienia?)';
$extract_errors++;
}
else
{
$new_size = filesize( $target_file );
$new_mtime = filemtime( $target_file );
if ( $file_existed )
{
if ( $old_mtime !== $new_mtime || $old_size !== $new_size )
$log[] = '[UPDATED] ' . $filename_clean . ' (' . $old_size . ' -> ' . $new_size . ' bajtów)';
else
$log[] = '[UNCHANGED] ' . $filename_clean . ' (nie zmieniono - identyczny?)';
}
else
{
$log[] = '[NEW] ' . $filename_clean . ' (' . $new_size . ' bajtów)';
}
$extracted_count++;
}
}
$log[] = '[OK] Rozpakowano ' . $extracted_count . ' plików, błędów: ' . $extract_errors . ', katalogów: ' . $skipped_dirs;
$zip->close();
if ( @unlink( $file_name ) )
$log[] = '[OK] Usunięto plik update.zip';
else
$log[] = '[WARNING] Nie udało się usunąć pliku update.zip';
/* aktualizacja wersji */
$version_file = '../libraries/version.ini';
$updateThis = @fopen( $version_file, 'w' );
if ( !$updateThis )
{
$log[] = '[ERROR] Nie udało się otworzyć pliku version.ini do zapisu';
self::saveUpdateLog( $log );
return [ 'success' => false, 'log' => $log ];
}
fwrite( $updateThis, $ver );
fclose( $updateThis );
$log[] = '[OK] Zaktualizowano plik version.ini do wersji: ' . $ver;
$log[] = '[SUCCESS] Aktualizacja do wersji ' . $ver . ' zakończona pomyślnie';
self::saveUpdateLog( $log );
return [ 'success' => true, 'log' => $log ];
}
}
$log[] = '[INFO] Brak nowych wersji do zainstalowania';
self::saveUpdateLog( $log );
return [ 'success' => true, 'log' => $log, 'no_updates' => true ];
}
private static function saveUpdateLog( $log )
{
$log_content = implode( "\n", $log );
@file_put_contents( '../libraries/update_log.txt', $log_content );
}
public static function update0197()
{
global $mdb;
$rows = $mdb -> select( 'pp_shop_order_products', [ 'id', 'product_id' ], [ 'parent_product_id' => null ] );
foreach ( $rows as $row )
{
$parent_id = $mdb -> get( 'pp_shop_products', 'parent_id', [ 'id' => $row['product_id'] ] );
if ( $parent_id )
$mdb -> update( 'pp_shop_order_products', [ 'parent_product_id' => $parent_id ], [ 'id' => $row['id'] ] );
else
$mdb -> update( 'pp_shop_order_products', [ 'parent_product_id' => $row['product_id'] ], [ 'id' => $row['id'] ] );
}
$mdb -> update( 'pp_updates', [ 'done' => 1 ], [ 'name' => 'update0197' ] );
}
}

View File

@@ -1,30 +0,0 @@
<?php
namespace admin\view;
class Page {
public static function show()
{
global $user, $mdb;
if ( $_GET['module'] == 'user' && $_GET['action'] == 'twofa' ) {
$controller = new \admin\Controllers\UsersController(
new \Domain\User\UserRepository( $mdb )
);
return $controller->twofa();
}
if ( !$user || !$user['admin'] )
{
$controller = new \admin\Controllers\UsersController(
new \Domain\User\UserRepository( $mdb )
);
return $controller->login_form();
}
$tpl = new \Tpl;
$tpl -> content = \admin\Site::route();
return $tpl -> render( 'site/main-layout' );
}
}
?>

View File

@@ -1,21 +0,0 @@
<?php
namespace admin\view;
class PagePanel {
public static function show( $add = false, $save = false, $cancel = false, $title = '', $form = 'formularz', $back = false, $update = false, $save_ajax = false, $delete_ajax = false )
{
$tpl = new \Tpl();
$tpl -> _add = $add;
$tpl -> _save = $save;
$tpl -> _cancel = $cancel;
$tpl -> _id_form = $form;
$tpl -> _title = $title;
$tpl -> _back = $back;
$tpl -> _update = $update;
$tpl -> _save_ajax = $save_ajax;
$tpl -> _delete_ajax = $delete_ajax;
return $tpl -> render( 'other/page-panel' );
}
}
?>

View File

@@ -1,11 +0,0 @@
<?php
namespace admin\view;
class ShopProduct
{
public static function products_list()
{
$tpl = new \Tpl();
return $tpl -> render('shop-product/products-list');
}
}

View File

@@ -1,13 +0,0 @@
<?php
namespace admin\view;
class Update
{
public static function main_view()
{
$tpl = new \Tpl;
$tpl -> ver = \S::get_version();
$tpl -> new_ver = \S::get_new_version();
return $tpl -> render( 'update/main-view' );
}
}

View File

@@ -39,8 +39,9 @@ class Newsletter
$dates = explode( ' - ', $row['dates'] );
$articles = [];
$articleRepository = new \Domain\Article\ArticleRepository( $mdb );
if ( isset( $dates[0], $dates[1] ) )
$articles = \admin\factory\Articles::articles_by_date_add( $dates[0], $dates[1] );
$articles = $articleRepository->articlesByDateAdd( $dates[0], $dates[1] );
$text = $previewRenderer -> render(
is_array( $articles ) ? $articles : [],

View File

@@ -1,162 +0,0 @@
<?php
namespace shop;
class Dashboard implements \ArrayAccess
{
static public function summary_orders()
{
global $mdb;
try
{
$redis = \RedisConnection::getInstance() -> getConnection();
if ( $redis )
{
$objectData = $redis -> get( "summary_ordersd" );
if ( !$objectData )
{
$summary = $mdb -> count( 'pp_shop_orders', [ 'status' => 6 ] );
$redis -> setex( "summary_ordersd", 60 * 5, serialize( $summary ) );
}
else
$summary = unserialize( $objectData );
}
else
{
$summary = $mdb -> count( 'pp_shop_orders', [ 'status' => 6 ] );
}
}
catch ( \RedisException $e )
{
$summary = $mdb -> count( 'pp_shop_orders', [ 'status' => 6 ] );
}
return $summary;
}
static public function summary_sales()
{
global $mdb;
try
{
$redis = \RedisConnection::getInstance() -> getConnection();
if ( $redis )
{
$objectData = $redis -> get( "summary_salesd" );
if ( !$objectData )
{
$summary = $mdb -> sum( 'pp_shop_orders', 'summary', [ 'status' => 6 ] ) - $mdb -> sum( 'pp_shop_orders', 'transport_cost', [ 'status' => 6 ] );
$redis -> setex( "summary_salesd", 60 * 5, serialize( $summary ) );
}
else
$summary = unserialize( $objectData );
}
else
{
$summary = $mdb -> sum( 'pp_shop_orders', 'summary', [ 'status' => 6 ] ) - $mdb -> sum( 'pp_shop_orders', 'transport_cost', [ 'status' => 6 ] );
}
}
catch ( \RedisException $e )
{
$summary = $mdb -> sum( 'pp_shop_orders', 'summary', [ 'status' => 6 ] ) - $mdb -> sum( 'pp_shop_orders', 'transport_cost', [ 'status' => 6 ] );
}
return $summary;
}
static public function sales_grid()
{
global $mdb;
$rows = $mdb -> select( 'pp_shop_orders', [ 'id', 'date_order' ], [ 'status' => 6 ] );
if ( \S::is_array_fix( $rows ) ) foreach ( $rows as $row )
{
if ( date( 'N', strtotime( $row['date_order'] ) ) )
$grid[ date( 'N', strtotime( $row['date_order'] ) ) ][ date( 'G', strtotime($row['date_order'] ) ) ] += 1;
}
return $grid;
}
static public function most_view_products()
{
global $mdb;
return $mdb -> query( 'SELECT '
. 'id, SUM(visits) AS visits '
. 'FROM '
. 'pp_shop_products AS psop '
. 'GROUP BY '
. 'id '
. 'ORDER BY '
. 'visits DESC '
. 'LIMIT 10' ) -> fetchAll( \PDO::FETCH_ASSOC );
}
static public function best_sales_products()
{
global $mdb;
return $mdb -> query( 'SELECT parent_product_id, SUM(quantity) AS quantity_summary, SUM(price_brutto_promo * quantity) AS sales FROM pp_shop_order_products AS psop INNER JOIN pp_shop_orders AS pso ON pso.id = psop.order_id WHERE pso.status = 6 GROUP BY parent_product_id ORDER BY sales DESC LIMIT 10' ) -> fetchAll( \PDO::FETCH_ASSOC );
}
static public function last_24_months_sales()
{
global $mdb;
$monthsBack = 24;
$sales = [ [ 'date' => date( 'Y-m' ) ] ];
$previousMonthDate = new \DateTime();
for ( $monthInterval = 0; $monthInterval < $monthsBack; $monthInterval++)
{
$previousMonthDate -> sub( new \DateInterval( "P1M" ) );
array_push( $sales, [ 'date' => $previousMonthDate -> format( 'Y-m' ) ] );
}
for ( $i = 0; $i < 24; $i++ )
{
$date_start = date( 'Y-m-1', strtotime( $sales[$i]['date'] ) );
$date_end = date( 'Y-m-t', strtotime( $sales[$i]['date'] ) );
$sales[$i]['sales'] = $mdb -> sum( 'pp_shop_orders', 'summary', [ 'AND' => [ 'status' => 6, 'date_order[>=]' => $date_start, 'date_order[<=]' => $date_end ] ] ) - $mdb -> sum( 'pp_shop_orders', 'transport_cost', [ 'AND' => [ 'status' => 6, 'date_order[>=]' => $date_start, 'date_order[<=]' => $date_end ] ] );
}
return $sales;
}
static public function last_orders()
{
global $mdb;
return $mdb -> query( 'SELECT '
. 'id, number, date_order, CONCAT( client_name, \' \', client_surname ) AS client, client_email, CONCAT( client_street, \', \', client_postal_code, \' \', client_city ) AS address, status, client_phone, summary '
. 'FROM '
. 'pp_shop_orders AS pso '
. 'ORDER BY '
. 'date_order DESC '
. 'LIMIT '
. '10' ) -> fetchAll( \PDO::FETCH_ASSOC );
}
public function offsetExists( $offset )
{
return isset( $this -> $offset );
}
public function offsetGet( $offset )
{
return $this -> $offset;
}
public function offsetSet( $offset, $value )
{
$this -> $offset = $value;
}
public function offsetUnset( $offset )
{
unset( $this -> $offset );
}
}