refactor(shop-coupon): migrate admin module to DI and release 0.266

This commit is contained in:
2026-02-14 00:05:23 +01:00
parent 88e5673569
commit 40e777afe6
40 changed files with 1668 additions and 426 deletions

View File

@@ -602,6 +602,7 @@ class ArticleRepository
]);
}
\S::delete_dir('../temp/');
return true;
}
@@ -636,6 +637,7 @@ class ArticleRepository
}
}
\S::delete_dir('../temp/');
return true;
}

View File

@@ -102,6 +102,8 @@ class BannerRepository
$this->saveTranslations($bannerId, $data['src'], $data['url'], $data['html'], $data['text']);
}
\S::delete_dir('../temp/');
return (int)$bannerId;
}

View File

@@ -0,0 +1,391 @@
<?php
namespace Domain\Coupon;
class CouponRepository
{
private const MAX_PER_PAGE = 100;
private $db;
private ?string $defaultLangId = null;
public function __construct($db)
{
$this->db = $db;
}
/**
* @return array{items: array<int, array<string, mixed>>, total: int}
*/
public function listForAdmin(
array $filters,
string $sortColumn = 'name',
string $sortDir = 'ASC',
int $page = 1,
int $perPage = 15
): array {
$allowedSortColumns = [
'id' => 'sc.id',
'status' => 'sc.status',
'used_count' => 'sc.used_count',
'name' => 'sc.name',
'type' => 'sc.type',
'amount' => 'sc.amount',
'one_time' => 'sc.one_time',
'send' => 'sc.send',
'used' => 'sc.used',
'date_used' => 'sc.date_used',
];
$sortSql = $allowedSortColumns[$sortColumn] ?? 'sc.name';
$sortDir = strtoupper(trim($sortDir)) === 'DESC' ? 'DESC' : 'ASC';
$page = max(1, $page);
$perPage = min(self::MAX_PER_PAGE, max(1, $perPage));
$offset = ($page - 1) * $perPage;
$where = ['1 = 1'];
$params = [];
$name = trim((string)($filters['name'] ?? ''));
if ($name !== '') {
if (strlen($name) > 255) {
$name = substr($name, 0, 255);
}
$where[] = 'sc.name LIKE :name';
$params[':name'] = '%' . $name . '%';
}
$status = trim((string)($filters['status'] ?? ''));
if ($status === '0' || $status === '1') {
$where[] = 'sc.status = :status';
$params[':status'] = (int)$status;
}
$used = trim((string)($filters['used'] ?? ''));
if ($used === '0' || $used === '1') {
$where[] = 'sc.used = :used';
$params[':used'] = (int)$used;
}
$send = trim((string)($filters['send'] ?? ''));
if ($send === '0' || $send === '1') {
$where[] = 'sc.send = :send';
$params[':send'] = (int)$send;
}
$whereSql = implode(' AND ', $where);
$sqlCount = "
SELECT COUNT(0)
FROM pp_shop_coupon AS sc
WHERE {$whereSql}
";
$stmtCount = $this->db->query($sqlCount, $params);
$countRows = $stmtCount ? $stmtCount->fetchAll() : [];
$total = isset($countRows[0][0]) ? (int)$countRows[0][0] : 0;
$sql = "
SELECT
sc.id,
sc.name,
sc.status,
sc.used,
sc.type,
sc.amount,
sc.one_time,
sc.send,
sc.include_discounted_product,
sc.categories,
sc.date_used,
sc.used_count
FROM pp_shop_coupon AS sc
WHERE {$whereSql}
ORDER BY {$sortSql} {$sortDir}, sc.id DESC
LIMIT {$perPage} OFFSET {$offset}
";
$stmt = $this->db->query($sql, $params);
$items = $stmt ? $stmt->fetchAll() : [];
if (!is_array($items)) {
$items = [];
}
foreach ($items as &$item) {
$item['id'] = (int)($item['id'] ?? 0);
$item['status'] = $this->toSwitchValue($item['status'] ?? 0);
$item['used'] = $this->toSwitchValue($item['used'] ?? 0);
$item['one_time'] = $this->toSwitchValue($item['one_time'] ?? 0);
$item['send'] = $this->toSwitchValue($item['send'] ?? 0);
$item['used_count'] = (int)($item['used_count'] ?? 0);
$item['type'] = (int)($item['type'] ?? 1);
$item['categories'] = $this->decodeIdList($item['categories'] ?? null);
}
unset($item);
return [
'items' => $items,
'total' => $total,
];
}
public function find(int $couponId): array
{
if ($couponId <= 0) {
return $this->defaultCoupon();
}
$coupon = $this->db->get('pp_shop_coupon', '*', ['id' => $couponId]);
if (!is_array($coupon)) {
return $this->defaultCoupon();
}
$coupon['id'] = (int)($coupon['id'] ?? 0);
$coupon['status'] = $this->toSwitchValue($coupon['status'] ?? 0);
$coupon['send'] = $this->toSwitchValue($coupon['send'] ?? 0);
$coupon['used'] = $this->toSwitchValue($coupon['used'] ?? 0);
$coupon['one_time'] = $this->toSwitchValue($coupon['one_time'] ?? 0);
$coupon['include_discounted_product'] = $this->toSwitchValue($coupon['include_discounted_product'] ?? 0);
$coupon['type'] = (int)($coupon['type'] ?? 1);
$coupon['used_count'] = (int)($coupon['used_count'] ?? 0);
$coupon['categories'] = $this->decodeIdList($coupon['categories'] ?? null);
return $coupon;
}
public function save(array $data): ?int
{
$couponId = (int)($data['id'] ?? 0);
$row = [
'name' => trim((string)($data['name'] ?? '')),
'status' => $this->toSwitchValue($data['status'] ?? 0),
'send' => $this->toSwitchValue($data['send'] ?? 0),
'used' => $this->toSwitchValue($data['used'] ?? 0),
'type' => (int)($data['type'] ?? 1),
'amount' => $this->toNullableNumeric($data['amount'] ?? null),
'one_time' => $this->toSwitchValue($data['one_time'] ?? 0),
'include_discounted_product' => $this->toSwitchValue($data['include_discounted_product'] ?? 0),
'categories' => $this->encodeIdList($data['categories'] ?? null),
];
if ($couponId <= 0) {
$this->db->insert('pp_shop_coupon', $row);
$id = (int)$this->db->id();
return $id > 0 ? $id : null;
}
$this->db->update('pp_shop_coupon', $row, ['id' => $couponId]);
return $couponId;
}
public function delete(int $couponId): bool
{
if ($couponId <= 0) {
return false;
}
return (bool)$this->db->delete('pp_shop_coupon', ['id' => $couponId]);
}
/**
* @return array<int, array<string, mixed>>
*/
public function categoriesTree($parentId = null): array
{
$rows = $this->db->select('pp_shop_categories', ['id'], [
'parent_id' => $parentId,
'ORDER' => ['o' => 'ASC'],
]);
if (!is_array($rows)) {
return [];
}
$categories = [];
foreach ($rows as $row) {
$categoryId = (int)($row['id'] ?? 0);
if ($categoryId <= 0) {
continue;
}
$category = $this->db->get('pp_shop_categories', '*', ['id' => $categoryId]);
if (!is_array($category)) {
continue;
}
$translations = $this->db->select('pp_shop_categories_langs', '*', ['category_id' => $categoryId]);
$category['languages'] = [];
if (is_array($translations)) {
foreach ($translations as $translation) {
$langId = (string)($translation['lang_id'] ?? '');
if ($langId !== '') {
$category['languages'][$langId] = $translation;
}
}
}
$category['title'] = $this->categoryTitle($category['languages']);
$category['subcategories'] = $this->categoriesTree($categoryId);
$categories[] = $category;
}
return $categories;
}
private function defaultCoupon(): array
{
return [
'id' => 0,
'name' => '',
'status' => 1,
'send' => 0,
'used' => 0,
'type' => 1,
'amount' => null,
'one_time' => 1,
'include_discounted_product' => 0,
'categories' => [],
'used_count' => 0,
'date_used' => null,
];
}
private function toSwitchValue($value): int
{
if (is_bool($value)) {
return $value ? 1 : 0;
}
if (is_numeric($value)) {
return ((int)$value) === 1 ? 1 : 0;
}
if (is_string($value)) {
$normalized = strtolower(trim($value));
return in_array($normalized, ['1', 'on', 'true', 'yes'], true) ? 1 : 0;
}
return 0;
}
private function toNullableNumeric($value): ?string
{
if ($value === null) {
return null;
}
$stringValue = trim((string)$value);
if ($stringValue === '') {
return null;
}
return str_replace(',', '.', $stringValue);
}
private function encodeIdList($values): ?string
{
$ids = $this->normalizeIdList($values);
if (empty($ids)) {
return null;
}
return json_encode($ids);
}
/**
* @return int[]
*/
private function decodeIdList($raw): array
{
if (is_array($raw)) {
return $this->normalizeIdList($raw);
}
$text = trim((string)$raw);
if ($text === '') {
return [];
}
$decoded = json_decode($text, true);
if (!is_array($decoded)) {
return [];
}
return $this->normalizeIdList($decoded);
}
/**
* @return int[]
*/
private function normalizeIdList($values): array
{
if ($values === null) {
return [];
}
if (!is_array($values)) {
$text = trim((string)$values);
if ($text === '') {
return [];
}
if (strpos($text, ',') !== false) {
$values = explode(',', $text);
} else {
$values = [$text];
}
}
$ids = [];
foreach ($values as $value) {
$id = (int)$value;
if ($id > 0) {
$ids[$id] = $id;
}
}
return array_values($ids);
}
private function categoryTitle(array $languages): string
{
$defaultLang = $this->defaultLanguageId();
if ($defaultLang !== '' && isset($languages[$defaultLang]['title'])) {
$title = trim((string)$languages[$defaultLang]['title']);
if ($title !== '') {
return $title;
}
}
foreach ($languages as $language) {
$title = trim((string)($language['title'] ?? ''));
if ($title !== '') {
return $title;
}
}
return '';
}
private function defaultLanguageId(): string
{
if ($this->defaultLangId !== null) {
return $this->defaultLangId;
}
$rows = $this->db->select('pp_langs', ['id', 'start', 'o'], [
'status' => 1,
'ORDER' => ['start' => 'DESC', 'o' => 'ASC'],
]);
if (is_array($rows) && !empty($rows)) {
$this->defaultLangId = (string)($rows[0]['id'] ?? '');
} else {
$this->defaultLangId = '';
}
return $this->defaultLangId;
}
}

View File

@@ -249,6 +249,7 @@ class DictionariesRepository
private function clearCache(): void
{
if (class_exists('\S') && method_exists('\S', 'delete_dir')) {
\S::delete_dir('../temp/');
\S::delete_dir('../temp/dictionaries');
}
}

View File

@@ -51,6 +51,7 @@ class IntegrationsRepository
} else {
$this->db->insert( $table, [ 'name' => $name, 'value' => $value ] );
}
\S::delete_dir('../temp/');
return true;
}

View File

@@ -18,7 +18,13 @@ class LayoutsRepository
return false;
}
return (bool)$this->db->delete('pp_layouts', ['id' => $layoutId]);
$deleted = (bool)$this->db->delete('pp_layouts', ['id' => $layoutId]);
if ($deleted) {
\S::delete_dir('../temp/');
$this->clearFrontLayoutsCache();
}
return $deleted;
}
public function find(int $layoutId): array
@@ -77,6 +83,7 @@ class LayoutsRepository
$this->syncCategories($layoutId, $data['categories'] ?? []);
\S::delete_dir('../temp/');
$this->clearFrontLayoutsCache();
return $layoutId;
}
@@ -288,6 +295,22 @@ class LayoutsRepository
];
}
private function clearFrontLayoutsCache(): void
{
if (!class_exists('\CacheHandler')) {
return;
}
try {
$cacheHandler = new \CacheHandler();
if (method_exists($cacheHandler, 'deletePattern')) {
$cacheHandler->deletePattern('*Layouts::*');
}
} catch (\Throwable $e) {
// Inwalidacja cache nie moze blokowac zapisu/usuwania.
}
}
private function menuPages(int $menuId, $parentId = null): array
{
if ($menuId <= 0) {

View File

@@ -25,6 +25,7 @@ class NewsletterRepository
{
$this->settingsRepository->updateSetting('newsletter_footer', (string)($values['newsletter_footer'] ?? ''));
$this->settingsRepository->updateSetting('newsletter_header', (string)($values['newsletter_header'] ?? ''));
\S::delete_dir('../temp/');
return true;
}
@@ -289,4 +290,3 @@ class NewsletterRepository
];
}
}

View File

@@ -172,6 +172,9 @@ class PagesRepository
'status' => $statusValue,
]);
if ($result) {
\S::delete_dir('../temp/');
}
return (bool)$result;
}
@@ -182,6 +185,7 @@ class PagesRepository
'id' => $menuId,
]);
\S::delete_dir('../temp/');
return true;
}
@@ -278,6 +282,7 @@ class PagesRepository
]);
}
\S::delete_dir('../temp/');
return true;
}

View File

@@ -148,11 +148,13 @@ class PromotionRepository
}
$this->invalidateActivePromotionsCache();
\S::delete_dir('../temp/');
return $id;
}
$this->db->update('pp_shop_promotion', $row, ['id' => $promotionId]);
$this->invalidateActivePromotionsCache();
\S::delete_dir('../temp/');
return $promotionId;
}

View File

@@ -90,6 +90,7 @@ class SettingsRepository
// Zachowanie zgodne z dotychczasowym flow: pelna podmiana zestawu ustawien.
$this->db->query('TRUNCATE pp_settings');
$this->updateSettings($settingsToSave);
\S::delete_dir('../temp/');
\S::set_message('Ustawienia zostaly zapisane');

View File

@@ -154,6 +154,7 @@ class UserRepository
]);
if ($inserted) {
\S::delete_dir('../temp/');
return ['status' => 'ok', 'msg' => 'Uzytkownik zostal zapisany.'];
}
@@ -186,6 +187,7 @@ class UserRepository
'id' => $userId,
]);
\S::delete_dir('../temp/');
return ['status' => 'ok', 'msg' => 'Uzytkownik zostal zapisany.'];
}