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

File diff suppressed because one or more lines are too long

View File

@@ -28,4 +28,4 @@ To ma pomóc zachować spójność zmian i dokumentacji.
## INNE
Przejdźmy teraz do refaktoringu wszystkiego co związane z https://shoppro.project-dc.pl/admin/articles_archive/, nowe widoki, klasy (usuwanie starych), poprawa routingu, przeszukanie innych klas pod względem zależności. Zapisz plan i przedstaw mi go a po akceptacji realizuj krok po kroku w trybie Human In The Loop
Przejdźmy teraz do refaktoringu wszystkiego co związane z https://shoppro.project-dc.pl/admin/shop_coupon/, nowe widoki, klasy (usuwanie starych), poprawa routingu, przeszukanie innych klas pod względem zależności. Zapisz plan i przedstaw mi go a po akceptacji realizuj krok po kroku w trybie Human In The Loop

View File

@@ -320,6 +320,28 @@ Tlumaczenia kontenerow statycznych (per jezyk).
**Aktualizacja 2026-02-12 (ver. 0.260):** modul `/admin/articles_archive` korzysta z `Domain\Article\ArticleRepository` (`listArchivedForAdmin`, `restore`, `deletePermanently`) przez `admin\Controllers\ArticlesArchiveController`.
## pp_shop_coupon
Kody rabatowe sklepu (modul `/admin/shop_coupon`).
| Kolumna | Opis |
|---------|------|
| id | PK |
| name | Kod kuponu (UNIQUE) |
| status | Status: 1 = aktywny, 0 = nieaktywny |
| send | Czy kupon zostal wyslany (0/1) |
| used | Czy kupon zostal wykorzystany (0/1) |
| date_used | Data wykorzystania kuponu (NULL gdy brak) |
| used_count | Licznik uzyc kuponu |
| type | Typ kuponu (obecnie: 1 = rabat procentowy na koszyk) |
| amount | Wartosc kuponu (np. procent) |
| one_time | Czy kupon jednorazowy (0/1) |
| include_discounted_product | Czy obejmuje rowniez produkty przecenione (0/1) |
| categories | JSON z ID kategorii objetych kuponem (NULL = bez ograniczenia) |
**Uzywane w:** `Domain\Coupon\CouponRepository`, `admin\Controllers\ShopCouponController`, `shop\Coupon`, `front\factory\ShopCoupon`, `front\factory\ShopOrder`
**Aktualizacja 2026-02-13 (ver. 0.266):** modul `/admin/shop_coupon` korzysta z `Domain\Coupon\CouponRepository` przez `admin\Controllers\ShopCouponController`. Usunieto legacy klasy `admin\controls\ShopCoupon` i `admin\factory\ShopCoupon`.
## pp_shop_promotion
Promocje sklepu (modul `/admin/shop_promotion`).

View File

@@ -492,3 +492,14 @@ Aktualnie w suite są też testy modułów `Dictionaries`, `Articles` i `Users`
- UPDATE: `shop\Promotion::get_active_promotions()` uwzglednia `date_from` (`NULL` lub `<= dzisiaj`) obok `date_to`.
- FIX: edycja promocji zapisuje update zamiast insert (stabilne przekazanie `id` przez hidden field + fallback `id` z URL w `save()`).
- Testy: **OK (222 tests, 614 assertions)**.
## Aktualizacja 2026-02-13 (ShopCoupon refactor, ver. 0.266)
- NOWE: `Domain\Coupon\CouponRepository` (`listForAdmin`, `find`, `save`, `delete`, `categoriesTree`).
- NOWE: `admin\Controllers\ShopCouponController` (DI) dla akcji `list`, `edit`, `save`, `delete`.
- UPDATE: zachowana kompatybilnosc aliasow legacy akcji (`view_list`, `coupon_edit`, `coupon_save`, `coupon_delete`) w nowym kontrolerze.
- UPDATE: modul `/admin/shop_coupon/*` przepiety z legacy `grid/gridEdit` na `components/table-list` i `components/form-edit`.
- NOWE: widoki/partiale `shop-coupon/coupons-list`, `shop-coupon/coupon-edit-new`, `shop-coupon/coupon-categories-selector`, `shop-coupon/coupon-categories-tree`, `shop-coupon/coupon-edit-custom-script`.
- CLEANUP: usuniete legacy klasy/pliki `autoload/admin/controls/class.ShopCoupon.php`, `autoload/admin/factory/class.ShopCoupon.php`, `admin/templates/shop-coupon/view-list.php`, `admin/templates/shop-coupon/coupon-edit.php`.
- UPDATE: menu admin wskazuje kanoniczny URL `/admin/shop_coupon/list/`.
- FIX: ujednolicone zachowanie drzewek i styl checkboxow miedzy widokami `/admin/shop_coupon/edit/*` i `/admin/layouts/edit/*` (strzalki, focus, iCheck).
- Testy: **OK (235 tests, 682 assertions)**.

View File

@@ -511,15 +511,15 @@ class BannerController
{
$formHandler = new FormRequestHandler();
$viewModel = $this->buildFormViewModel(); // jak w edit()
$result = $formHandler->handleSubmit($viewModel, $_POST);
if (!$result['success']) {
// Błędy walidacji - zapisane automatycznie do sesji
echo json_encode(['success' => false, 'errors' => $result['errors']]);
exit;
}
// Sukces - persist wyczyszczony automatycznie
$this->repository->save($result['data']);
echo json_encode(['success' => true]);
@@ -782,3 +782,92 @@ Gdy `persist = true`:
- FIX: zapis edycji promocji nie tworzy nowego rekordu (hidden `id` + fallback `id` z URL)
- TEST: rozszerzono `PromotionRepositoryTest` o asercje `date_from`
- Testy po zmianie: **OK (222 tests, 614 assertions)**.
## Plan 2026-02-13 - Refaktoryzacja `/admin/shop_coupon/` (HITL)
- [x] Etap 1 (analiza i kontrakt URL/routingu):
- potwierdzic docelowy kontrakt URL: `/admin/shop_coupon/list/`, `/admin/shop_coupon/edit/`, `/admin/shop_coupon/save/`, `/admin/shop_coupon/delete/`
- decyzja: utrzymujemy aliasy legacy (`view_list`, `coupon_edit`, `coupon_save`, `coupon_delete`) w nowym kontrolerze jako kompatybilnosc wsteczna, przy jednoczesnym przejsciu menu i nowych widokow na URL kanoniczne
- sprawdzic mapowanie modulu `ShopCoupon` w `admin\Site` (DI factory + fallback)
- [x] Etap 2 (Domain):
- dodac `Domain\Coupon\CouponRepository`:
- `listForAdmin(filters, sort, dir, page, perPage)` (whitelist sortowania + paginacja)
- `find(int $id)` (domyslne dane dla nowego formularza)
- `save(array $data): ?int` (insert/update, normalizacja switchy, JSON dla `categories`)
- `delete(int $id): bool`
- `categoriesTree(?int $parentId): array` (drzewo kategorii bez zaleznosci od `admin\factory\ShopCategory`)
- [x] Etap 3 (Admin Controller + routing DI):
- dodac `admin\Controllers\ShopCouponController` z akcjami `list`, `edit`, `save`, `delete`
- przepiac routing DI w `admin\Site::$newControllers` dla modulu `ShopCoupon`
- zachowac obsluge legacy payload `values` JSON i nowego payload `$_POST` z `components/form-edit`
- [x] Etap 4 (widoki):
- przepiac liste z `grid` na `components/table-list` (filtry: nazwa, aktywny, uzyty, wyslany)
- przepiac edycje z `gridEdit` na `components/form-edit`
- dodac partiale drzewa kategorii w module `shop-coupon` (usuniecie zaleznosci od `shop-product/subcategories-list`)
- dodac `shop-coupon/coupon-edit-custom-script.php` (obsluga drzewa kategorii i zachowania formularza)
- [x] Etap 5 (cleanup i zaleznosci):
- usunac legacy po pelnym przepieciu:
- `autoload/admin/controls/class.ShopCoupon.php`
- `autoload/admin/factory/class.ShopCoupon.php`
- `admin/templates/shop-coupon/view-list.php` (wersja grid)
- `admin/templates/shop-coupon/coupon-edit.php` (wersja gridEdit)
- przepiac menu admin na kanoniczny URL `/admin/shop_coupon/list/`
- przeszukac repo i usunac pozostale odwolania do `shop_coupon/view_list` i legacy klas `admin\controls\ShopCoupon`, `admin\factory\ShopCoupon`
- [x] Etap 6 (testy):
- dodac `tests/Unit/Domain/Coupon/CouponRepositoryTest.php`
- dodac `tests/Unit/admin/Controllers/ShopCouponControllerTest.php`
- uruchomic testy modulu + pelny `composer test`
- [x] Etap 7 (dokumentacja i release note):
- zaktualizowac `DATABASE_STRUCTURE.md` (dodac `pp_shop_coupon`)
- zaktualizowac `PROJECT_STRUCTURE.md`
- zaktualizowac `REFACTORING_PLAN.md` (sekcja "Aktualizacja ...")
- zaktualizowac `TESTING.md` (nowy wynik suite + nowe testy)
- dopisac wpis w `updates/changelog.php`
### Tryb HITL dla realizacji
- Po kazdym etapie (1-7) zatrzymanie i krotkie podsumowanie diffu do akceptacji przed kolejnym krokiem.
### Postep 2026-02-13 (ShopCoupon)
- Etap 2 zakonczony:
- NOWE: `autoload/Domain/Coupon/CouponRepository.php`
- Zakres: `listForAdmin`, `find`, `save`, `delete`, `categoriesTree`
- Walidacja: `php -l` OK
- Etap 3 zakonczony:
- NOWE: `autoload/admin/Controllers/ShopCouponController.php`
- UPDATE: `autoload/admin/class.Site.php` - rejestracja DI factory dla modulu `ShopCoupon`
- Kompatybilnosc: dodane aliasy akcji `view_list`, `coupon_edit`, `coupon_save`, `coupon_delete`
- Walidacja: `php -l` OK
- Etap 4 zakonczony:
- NOWE widoki: `admin/templates/shop-coupon/coupons-list.php`, `admin/templates/shop-coupon/coupon-edit-new.php`
- NOWE partiale: `admin/templates/shop-coupon/coupon-categories-selector.php`, `admin/templates/shop-coupon/coupon-categories-tree.php`
- NOWY skrypt: `admin/templates/shop-coupon/coupon-edit-custom-script.php`
- UPDATE: `ShopCouponController::edit()` buduje `FormEditViewModel` (zakladki ustawienia/kategorie)
- Walidacja: `php -l` OK
- Etap 5 zakonczony:
- CLEANUP: usuniete pliki legacy:
- `autoload/admin/controls/class.ShopCoupon.php`
- `autoload/admin/factory/class.ShopCoupon.php`
- `admin/templates/shop-coupon/view-list.php`
- `admin/templates/shop-coupon/coupon-edit.php`
- UPDATE: menu admin (`admin/templates/site/main-layout.php`) wskazuje kanoniczny URL `/admin/shop_coupon/list/`
- WERYFIKACJA: brak odwolan do `shop_coupon/view_list`, `admin\controls\ShopCoupon`, `admin\factory\ShopCoupon` w kodzie
- Etap 6 zakonczony:
- NOWE testy:
- `tests/Unit/Domain/Coupon/CouponRepositoryTest.php` (8 testow)
- `tests/Unit/admin/Controllers/ShopCouponControllerTest.php` (5 testow)
- Test modulu: `OK (8 tests, 49 assertions)`
- Pelny suite: `OK (235 tests, 682 assertions)`
- Etap 7 zakonczony:
- UPDATE: dokumentacja techniczna zaktualizowana (`DATABASE_STRUCTURE.md`, `PROJECT_STRUCTURE.md`, `TESTING.md`)
- UPDATE: dopisany release note w `updates/changelog.php` (ver. 0.266)
## Aktualizacja 2026-02-13 (ver. 0.266)
- **ShopCoupon** - migracja `/admin/shop_coupon` na Domain + DI + nowe widoki
- NOWE: `Domain\Coupon\CouponRepository` (`listForAdmin`, `find`, `save`, `delete`, `categoriesTree`)
- NOWE: `admin\Controllers\ShopCouponController` (DI) z akcjami `list`, `edit`, `save`, `delete`
- UPDATE: kompatybilnosc aliasow legacy (`view_list`, `coupon_edit`, `coupon_save`, `coupon_delete`) obslugiwana przez nowy kontroler
- UPDATE: modul `/admin/shop_coupon/*` dziala na `components/table-list` i `components/form-edit`
- NOWE: widoki/partiale `shop-coupon/coupons-list`, `shop-coupon/coupon-edit-new`, `shop-coupon/coupon-categories-selector`, `shop-coupon/coupon-categories-tree`, `shop-coupon/coupon-edit-custom-script`
- CLEANUP: usuniete legacy `autoload/admin/controls/class.ShopCoupon.php`, `autoload/admin/factory/class.ShopCoupon.php`, `admin/templates/shop-coupon/view-list.php`, `admin/templates/shop-coupon/coupon-edit.php`
- UPDATE: menu admin przepiete na kanoniczny URL `/admin/shop_coupon/list/`
- FIX: po akceptacji HITL ujednolicone UI drzewek i checkboxow miedzy kuponami i layoutami (spojne strzalki, brak nieestetycznego focusu, iCheck dla checkboxow)
- Testy po zmianie: **OK (235 tests, 682 assertions)**.

View File

@@ -33,10 +33,10 @@ Alternatywnie (Git Bash):
## Aktualny stan suite
Ostatnio zweryfikowano: 2026-02-10
Ostatnio zweryfikowano: 2026-02-13
```text
OK (82 tests, 181 assertions)
OK (235 tests, 682 assertions)
```
## Struktura testow
@@ -49,6 +49,7 @@ tests/
| | |-- Article/ArticleRepositoryTest.php
| | |-- Banner/BannerRepositoryTest.php
| | |-- Cache/CacheRepositoryTest.php
| | |-- Coupon/CouponRepositoryTest.php
| | |-- Dictionaries/DictionariesRepositoryTest.php
| | |-- Product/ProductRepositoryTest.php
| | |-- Settings/SettingsRepositoryTest.php
@@ -61,6 +62,7 @@ tests/
| |-- IntegrationsControllerTest.php
| |-- ProductArchiveControllerTest.php
| |-- SettingsControllerTest.php
| |-- ShopCouponControllerTest.php
| `-- UsersControllerTest.php
`-- Integration/
```
@@ -318,3 +320,17 @@ OK (222 tests, 614 assertions)
Zmiany testowe 2026-02-13:
- rozszerzenie `tests/Unit/Domain/Promotion/PromotionRepositoryTest.php` o asercje `date_from`
## Aktualizacja suite (ShopCoupon refactor, ver. 0.266)
Ostatnio zweryfikowano: 2026-02-13
```text
OK (235 tests, 682 assertions)
```
Nowe testy dodane 2026-02-13:
- `tests/Unit/Domain/Coupon/CouponRepositoryTest.php` (8 testow: find default/normalize, save insert/update, delete, whitelist sortowania, drzewo kategorii)
- `tests/Unit/admin/Controllers/ShopCouponControllerTest.php` (5 testow: kontrakty metod, aliasy legacy, DI konstruktora)
Ponowna weryfikacja po poprawkach UI (drzewko + checkboxy): 2026-02-13
- `OK (235 tests, 682 assertions)`

View File

@@ -7,6 +7,48 @@
<script type="text/javascript" src="/libraries/codemirror/mode/javascript/javascript.js"></script>
<script type="text/javascript" src="/libraries/codemirror/mode/htmlmixed/htmlmixed.js"></script>
<script type="text/javascript" src="/libraries/codemirror/addon/mode/multiplex.js"></script>
<style type="text/css">
.layout-tree-toggle {
width: 18px;
height: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 0;
background: transparent;
padding: 0;
margin-right: 4px;
color: #666;
cursor: pointer;
}
.layout-tree-toggle:focus,
.layout-tree-toggle:active,
.layout-tree-toggle:focus-visible {
outline: none;
box-shadow: none;
}
li.sort-expanded > div .layout-tree-toggle i {
transform: rotate(90deg);
}
#fg-layout-edit input[type=checkbox].g-checkbox {
-webkit-appearance: checkbox;
appearance: auto;
position: static;
width: 14px;
height: 14px;
background: initial;
border-radius: 0;
box-shadow: none;
vertical-align: middle;
}
#fg-layout-edit input[type=checkbox].g-checkbox:before {
content: none;
}
</style>
<script type="text/javascript">
$( function()
{
@@ -76,9 +118,43 @@
}
});
function refreshTreeDisclosureState()
{
$( 'ol.sortable li' ).each( function()
{
var $li = $( this );
var hasChildren = $li.children( 'ol' ).children( 'li' ).length > 0;
var $disclose = $li.children( 'div' ).children( '.disclose' );
if ( hasChildren )
{
$li.removeClass( 'sort-leaf' );
if ( !$li.hasClass( 'sort-collapsed' ) && !$li.hasClass( 'sort-expanded' ) )
$li.addClass( 'sort-collapsed' );
$li.addClass( 'sort-branch' );
$disclose.attr( 'aria-expanded', $li.hasClass( 'sort-expanded' ) ? 'true' : 'false' );
$disclose.show();
}
else
{
$li.removeClass( 'sort-branch sort-collapsed sort-expanded' ).addClass( 'sort-leaf' );
$disclose.attr( 'aria-expanded', 'false' );
$disclose.hide();
}
});
}
refreshTreeDisclosureState();
$( '.disclose' ).on( 'click', function()
{
$( this ).closest( 'li' ).toggleClass( 'sort-collapsed' ).toggleClass( 'sort-expanded' );
var $li = $( this ).closest( 'li' );
if ( !$li.hasClass( 'sort-branch' ) )
return;
$li.toggleClass( 'sort-collapsed' ).toggleClass( 'sort-expanded' );
$( this ).attr( 'aria-expanded', $li.hasClass( 'sort-expanded' ) ? 'true' : 'false' );
this.blur();
});
$( '.disclose' ).mousedown( function(e)
@@ -116,21 +192,39 @@
});
<?php
$array = unserialize( $_COOKIE[ 'cookie_pages' ] );
if ( is_array( $array ) ): foreach ( $array as $key => $val ):
if ( $val ):
?>$( '.<?= $key;?>' ).children( 'div' ).children( 'span.disclose' ).click();<?
endif;
endforeach; endif;
$cookiePages = [];
$cookieMenus = [];
$array = unserialize( $_COOKIE[ 'cookie_menus' ] );
if ( is_array( $array ) ): foreach ( $array as $key => $val ):
if ( $val ):
?>$( '.menu_<?= $key;?>' ).children( 'div' ).children( 'span.disclose' ).click();<?
endif;
endforeach; endif;
if ( !empty( $_COOKIE['cookie_pages'] ) )
{
$decoded = @unserialize( (string)$_COOKIE['cookie_pages'], [ 'allowed_classes' => false ] );
if ( is_array( $decoded ) )
$cookiePages = $decoded;
}
if ( !empty( $_COOKIE['cookie_menus'] ) )
{
$decoded = @unserialize( (string)$_COOKIE['cookie_menus'], [ 'allowed_classes' => false ] );
if ( is_array( $decoded ) )
$cookieMenus = $decoded;
}
?>
var cookiePages = <?= json_encode( $cookiePages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );?>;
var cookieMenus = <?= json_encode( $cookieMenus, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );?>;
Object.keys( cookiePages || {} ).forEach( function( key )
{
if ( String( cookiePages[key] ) === '1' && /^\d+$/.test( String( key ) ) )
$( '.list_' + key ).children( 'div' ).children( '.disclose' ).click();
});
Object.keys( cookieMenus || {} ).forEach( function( key )
{
if ( String( cookieMenus[key] ) === '1' && /^\d+$/.test( String( key ) ) )
$( '.menu_' + key ).children( 'div' ).children( '.disclose' ).click();
});
});
</script>
<?
@@ -177,7 +271,9 @@ ob_start();
<ol class="sortable" id="sortable_<?= $menu['id'];?>">
<li id="list_<?= $menu['id'];?>" class="menu_<?= $menu['id'];?>" menu="<?= $menu['id'];?>">
<div class="context_0 content content_menu" <? if ( !$menu['status'] ) echo 'style="color: #cc0000;"';?>>
<span class="disclose"><span></span></span>
<button type="button" class="disclose layout-tree-toggle" aria-expanded="false" title="Rozwin / zwin">
<i class="fa fa-caret-right"></i>
</button>
Menu: <b><?= $menu['name'];?></b>
</div>
<?= \Tpl::view( 'layouts/subpages-list', [
@@ -199,7 +295,9 @@ ob_start();
<? if ( is_array( $this -> categories ) ): foreach ( $this -> categories as $category ):?>
<li id="list_<?= $category['id'];?>" class="category_<?= $category['id'];?>" category="<?= $category['id'];?>">
<div class="context_0 content content_menu">
<span class="disclose"><span></span></span>
<button type="button" class="disclose layout-tree-toggle" aria-expanded="false" title="Rozwin / zwin">
<i class="fa fa-caret-right"></i>
</button>
<? if ( !$category['status'] ) echo '<i class="fa fa-ban fa-lg text-danger" title="Kategoria nieaktywna"></i>';?>
<input type="checkbox" class="g-checkbox" name="categories[]" value="<?= $category['id'];?>" <? if ( is_array( $this -> layout['categories'] ) and in_array( $category['id'], $this -> layout['categories'] ) ):?>checked="checked"<? endif;?> />
<b><?= $category['languages'][$this -> dlang]['title'];?></b>

View File

@@ -3,7 +3,9 @@
<? foreach ( $this -> categories as $category ):?>
<li id="list_<?= $category['id'];?>" class="list_<?= $category['id'];?>" category="<?= $category['id'];?>">
<div class="context_0 content content_menu">
<span class="disclose"><span></span></span>
<button type="button" class="disclose layout-tree-toggle" aria-expanded="false" title="Rozwin / zwin">
<i class="fa fa-caret-right"></i>
</button>
<? if ( !$category['status'] ) echo '<i class="fa fa-ban fa-lg text-danger" title="Kategoria nieaktywna"></i>';?>
<input type="checkbox" class="g-checkbox" name="categories[]" value="<?= $category['id'];?>" <? if ( is_array( $this -> product_categories ) and in_array( $category['id'], $this -> product_categories ) ):?>checked="checked"<? endif;?> />
<b><?= $category['languages'][$this -> dlang]['title'];?></b>
@@ -17,4 +19,3 @@
<? endforeach;?>
</ol>
<? endif;?>

View File

@@ -3,7 +3,9 @@
<? foreach ( $this -> pages as $page ):?>
<li id="list_<?= $page['id'];?>" idk="<?= $page['id'];?>" class="list_<?= $page['id'];?>" menu="<?= $page['menu_id'];?>">
<div class="content <?= $this -> step < 2 ? $tmp = 'content_page' : $tmp = 'content_page_last_level';?>" <? if ( !$page['status'] ) echo 'style="color: #cc0000;"';?>>
<span class="disclose"><span></span></span>
<button type="button" class="disclose layout-tree-toggle" aria-expanded="false" title="Rozwin / zwin">
<i class="fa fa-caret-right"></i>
</button>
<input type="checkbox" class="g-checkbox" name="pages[]" value="<?= $page['id'];?>" <? if ( is_array( $this -> layout_pages ) and in_array( $page['id'], $this -> layout_pages ) ):?>checked="checked"<? endif;?> /><?= $page['title'];?>
</div>
<?

View File

@@ -0,0 +1,19 @@
<?php
$label = trim((string)($this->label ?? 'Kategorie'));
$inputName = trim((string)($this->inputName ?? 'categories[]'));
$categories = is_array($this->categories ?? null) ? $this->categories : [];
$selectedIds = is_array($this->selectedIds ?? null) ? $this->selectedIds : [];
?>
<div class="form-group row js-coupon-row js-coupon-row-categories">
<label class="col-lg-4 control-label"><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?>:</label>
<div class="col-lg-8">
<div class="coupon-categories-box">
<?= \Tpl::view('shop-coupon/coupon-categories-tree', [
'categories' => $categories,
'selectedIds' => $selectedIds,
'inputName' => $inputName,
]); ?>
</div>
</div>
</div>

View File

@@ -0,0 +1,68 @@
<?php
$categories = is_array($this->categories ?? null) ? $this->categories : [];
$inputName = trim((string)($this->inputName ?? 'categories[]'));
$selectedRaw = is_array($this->selectedIds ?? null) ? $this->selectedIds : [];
$selected = [];
foreach ($selectedRaw as $value) {
$id = (int)$value;
if ($id > 0) {
$selected[$id] = true;
}
}
?>
<?php if (!empty($categories)): ?>
<ol class="coupon-categories-tree">
<?php foreach ($categories as $category): ?>
<?php
$categoryId = (int)($category['id'] ?? 0);
if ($categoryId <= 0) {
continue;
}
$title = trim((string)($category['title'] ?? ''));
if ($title === '') {
$title = 'Kategoria #' . $categoryId;
}
$isActive = (int)($category['status'] ?? 0) === 1;
$children = is_array($category['subcategories'] ?? null) ? $category['subcategories'] : [];
$hasChildren = !empty($children);
?>
<li class="coupon-category-item<?= $hasChildren ? ' has-children is-collapsed' : ''; ?>">
<div class="coupon-category-row">
<?php if ($hasChildren): ?>
<button type="button" class="coupon-tree-toggle" aria-expanded="false" title="Rozwin / zwin">
<i class="fa fa-caret-right"></i>
</button>
<?php else: ?>
<span class="coupon-tree-spacer"></span>
<?php endif; ?>
<?php if (!$isActive): ?>
<i class="fa fa-ban text-danger" title="Kategoria nieaktywna"></i>
<?php endif; ?>
<label class="coupon-category-label">
<input
type="checkbox"
class="g-checkbox"
name="<?= htmlspecialchars($inputName, ENT_QUOTES, 'UTF-8'); ?>"
value="<?= $categoryId; ?>"
<?= isset($selected[$categoryId]) ? 'checked="checked"' : ''; ?>
/>
<span><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></span>
</label>
</div>
<?php if ($hasChildren): ?>
<?= \Tpl::view('shop-coupon/coupon-categories-tree', [
'categories' => $children,
'selectedIds' => array_keys($selected),
'inputName' => $inputName,
]); ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>

View File

@@ -0,0 +1,109 @@
<style type="text/css">
.coupon-categories-box {
max-height: 420px;
overflow: auto;
border: 1px solid #d6d6d6;
border-radius: 4px;
padding: 8px 10px;
background: #fff;
}
.coupon-categories-tree {
margin: 0;
padding: 0 0 0 16px;
list-style: none;
}
.coupon-category-item {
margin: 2px 0;
}
.coupon-category-item.is-collapsed > ol {
display: none;
}
.coupon-category-row {
display: flex;
align-items: center;
gap: 6px;
min-height: 28px;
}
.coupon-tree-toggle,
.coupon-tree-spacer {
width: 18px;
height: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 0;
background: transparent;
padding: 0;
}
.coupon-tree-toggle {
cursor: pointer;
color: #666;
}
.coupon-tree-toggle:focus,
.coupon-tree-toggle:active,
.coupon-tree-toggle:focus-visible {
outline: none;
box-shadow: none;
}
.coupon-category-item:not(.is-collapsed) > .coupon-category-row .coupon-tree-toggle i {
transform: rotate(90deg);
}
.coupon-category-label {
margin: 0;
font-weight: 600;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
}
.coupon-category-row .icheckbox_minimal-blue {
margin-top: 0;
}
</style>
<script type="text/javascript">
(function($) {
if (!$) {
return;
}
$(document).off('click.shopCouponTree', '.coupon-tree-toggle');
$(document).on('click.shopCouponTree', '.coupon-tree-toggle', function(e) {
e.preventDefault();
var $item = $(this).closest('.coupon-category-item');
$item.toggleClass('is-collapsed');
$(this).attr('aria-expanded', $item.hasClass('is-collapsed') ? 'false' : 'true');
this.blur();
});
function initCouponCategoryCheckboxes() {
if (!$.fn || typeof $.fn.iCheck !== 'function') {
return;
}
$('.coupon-categories-box .g-checkbox').each(function() {
var $checkbox = $(this);
if ($checkbox.parent().hasClass('icheckbox_minimal-blue')) {
return;
}
$checkbox.iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue'
});
});
}
initCouponCategoryCheckboxes();
})(window.jQuery);
</script>

View File

@@ -0,0 +1,3 @@
<?= \Tpl::view('components/form-edit', ['form' => $this->form]); ?>
<?= \Tpl::view('shop-coupon/coupon-edit-custom-script'); ?>

View File

@@ -1,151 +0,0 @@
<script type="text/javascript" src="/libraries/framework/vendor/plugins/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/libraries/framework/vendor/plugins/ckeditor/adapters/jquery.js"></script>
<script type="text/javascript" src="/libraries/jquery/sortable/sortable.js"></script>
<?
global $db;
ob_start();
?>
<div id="settings-tabs">
<ul class="resp-tabs-list settings-tabs">
<li><i class="fa fa-wrench"></i>Ustawienia</li>
</ul>
<div class="resp-tabs-container settings-tabs">
<div>
<?= \Html::input([
'label' => 'Nazwa',
'name' => 'name',
'id' => 'name',
'value' => $this -> coupon['name']
]); ?>
<?= \Html::input_switch([
'label' => 'Wysłany',
'name' => 'send',
'checked' => $this -> coupon['send'] == 1 ? true : false
]); ?>
<?= \Html::input_switch([
'label' => 'Aktywny',
'name' => 'status',
'checked' => $this -> coupon['status'] == 1 ? true : false
]); ?>
<?= \Html::input_switch( [
'label' => 'Użyty',
'name' => 'used',
'checked' => $this -> coupon['used'] == 1 ? true : false,
]); ?>
<?= \Html::select([
'label' => 'Typ kuponu',
'name' => 'type',
'values' => [ 1 => 'Rabat procentowy na koszyk'],
'value' => $this -> coupo['type'],
]); ?>
<?= \Html::input([
'label' => 'Wartość',
'class' => 'number-format',
'name' => 'amount',
'id' => 'amount',
'value' => $this -> coupon['amount']
]); ?>
<?= \Html::input_switch([
'label' => 'Kupon jednorazowy',
'name' => 'one_time',
'checked' => $this -> coupon['one_time'] == 1 ? true : false
]); ?>
<?= \Html::input_switch([
'label' => 'Dotyczy również produktów przecenionych',
'name' => 'include_discounted_product',
'checked' => $this -> coupon['include_discounted_product'] == 1 ? true : false,
]); ?>
<div class="form-group row">
<label class="col-lg-4 control-label">Ogranicz promocję do wybranych kategorii:</label>
<div class="col-lg-8">
<div class="menu_sortable">
<ol class="sortable" id="sortable">
<?
if ( is_array( $this -> categories ) )
{
foreach ( $this -> categories as $category )
{
?>
<li id="list_<?= $category[ 'id' ];?>" class="category_<?= $category[ 'id' ];?>" category="<?= $category[ 'id' ];?>">
<div class="context_0 content content_menu">
<span class="disclose"><span></span></span>
<? if ( !$category[ 'status' ] ) echo '<i class="fa fa-ban fa-lg text-danger" title="Kategoria nieaktywna"></i>';?>
<input type="checkbox" class="g-checkbox" name="categories[]" value="<?= $category[ 'id' ];?>" <? if ( is_array( json_decode( $this -> coupon['categories'] ) ) and in_array( $category[ 'id' ], json_decode( $this -> coupon['categories'] ) ) ):?>checked="checked"<? endif;?> />
<b><?= $category[ 'languages' ][ $this -> dlang ][ 'title' ];?></b>
</div>
<?=
\Tpl::view( 'shop-product/subcategories-list', [
'categories' => \admin\factory\ShopCategory::subcategories( $category[ 'id' ] ),
'product_categories' => json_decode( $this -> coupon['categories'] ),
'dlang' => $this -> dlang
] );
?>
</li>
<?
}
}
?>
</ol>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<?
$out = ob_get_clean();
$grid = new \gridEdit;
$grid->id = 'coupon-edit';
$grid->gdb_opt = $gdb;
$grid->include_plugins = true;
$grid->title = $this -> coupon['id'] ? 'Edycja kuponu: <u>' . $this -> coupon['name'] . '</u>' : 'Nowy kupon';
$grid->fields = [
[
'db' => 'id',
'type' => 'hidden',
'value' => $this -> coupon['id']
]
];
$grid->actions = [
'save' => ['url' => '/admin/shop_coupon/coupon_save/', 'back_url' => '/admin/shop_coupon/view_list/'],
'cancel' => ['url' => '/admin/shop_coupon/view_list/']
];
$grid->external_code = $out;
$grid->persist_edit = true;
$grid->id_param = 'id';
echo $grid->draw();
?>
<link type="text/css" rel="stylesheet" href="/libraries/plupload/jquery.plupload.queue/css/jquery.plupload.queue.css">
<link type="text/css" rel="stylesheet" href="/libraries/selectize/css/selectize.css">
<link type="text/css" rel="stylesheet" href="/libraries/selectize/css/selectize.default.css">
<script type="text/javascript" src="/libraries/plupload/plupload.js"></script>
<script type="text/javascript" src="/libraries/plupload/plupload.flash.js"></script>
<script type="text/javascript" src="/libraries/plupload/plupload.html5.js"></script>
<script type="text/javascript" src="/libraries/plupload/plupload.html4.js"></script>
<script type="text/javascript" src="/libraries/plupload/jquery.plupload.queue/jquery.plupload.queue.js"></script>
<script type="text/javascript" src="/libraries/plupload/i18n/pl.js"></script>
<script type="text/javascript" src="/libraries/jquery-nested-sortable/jquery.mjs.nestedSortable.js"></script>
<script type="text/javascript" src="/libraries/jquery/lozad.js"></script>
<script type="text/javascript" src="/libraries/selectize/js/standalone/selectize.js"></script>
<script type="text/javascript">
$(function() {
const observer = lozad();
observer.observe();
disable_menu();
$('#settings-tabs').easyResponsiveTabs({
width: 'auto',
fit: true,
tabidentify: 'settings-tabs',
type: 'vertical'
});
});
</script>

View File

@@ -0,0 +1,2 @@
<?= \Tpl::view('components/table-list', ['list' => $this->viewModel]); ?>

View File

@@ -1,88 +0,0 @@
<?php
global $gdb;
$grid = new \grid( 'pp_shop_coupon' );
$grid -> gdb_opt = $gdb;
$grid -> debug = true;
$grid -> order = [ 'column' => 'name', 'type' => 'ASC' ];
$grid -> search = [
[ 'name' => 'Nazwa', 'db' => 'name', 'type' => 'text' ],
[ 'name' => 'Aktywny', 'db' => 'status', 'type' => 'select', 'replace' => [ 'array' => [ 0 => 'nie', 1 => 'tak' ] ] ],
[ 'name' => 'Użyty', 'db' => 'used', 'type' => 'select', 'replace' => [ 'array' => [ 0 => 'nie', 1 => 'tak' ] ] ],
[ 'name' => 'Wysłany', 'db' => 'send', 'type' => 'select', 'replace' => [ 'array' => [ 0 => 'nie', 1 => 'tak' ] ] ]
];
$grid -> columns_view = [
[
'name' => 'Lp.',
'th' => [ 'class' => 'g-lp' ],
'td' => [ 'class' => 'g-center' ],
'autoincrement' => true
], [
'name' => 'Aktywny',
'db' => 'status',
'replace' => [ 'array' => [ 0 => '<span style="color: #FF0000;">nie</span>', 1 => 'tak' ] ],
'td' => [ 'class' => 'g-center' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 150px;' ],
'sort' => true
], [
'name' => 'Użyto X razy',
'db' => 'used_count',
'td' => [ 'class' => 'g-center' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 150px;' ],
], [
'name' => 'Nazwa',
'db' => 'name',
'sort' => true,
'php' => 'echo "<a href=\'/admin/shop_coupon/coupon_edit/id=[id]\'>[name]</a>";'
], [
'name' => 'Typ kuponu',
'db' => 'type',
'replace' => [ 'array' => [ 1 => 'Rabat procentowy na koszyk' ] ]
], [
'name' => 'Wartość',
'db' => 'amount',
'php' => 'if ( [type] == 1 ) echo "[amount]%";'
], [
'name' => 'Kupon jednorazowy',
'db' => 'one_time',
'replace' => [ 'array' => [ 0 => 'nie', 1 => 'tak' ] ],
'td' => [ 'class' => 'g-center' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 150px;' ]
], [
'name' => 'Wysłany',
'db' => 'send',
'replace' => [ 'array' => [ 0 => 'nie', 1 => 'tak' ] ],
'td' => [ 'class' => 'g-center' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 150px;' ]
], [
'name' => 'Użyty',
'db' => 'used',
'replace' => [ 'array' => [ 0 => 'nie', 1 => 'tak' ] ],
'td' => [ 'class' => 'g-center' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 150px;' ]
], [
'name' => 'Data użycia',
'db' => 'date_used',
'td' => [ 'class' => 'g-center' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 150px;' ]
], [
'name' => 'Edytuj',
'action' => [ 'type' => 'edit', 'url' => '/admin/shop_coupon/coupon_edit/id=[id]' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 70px;' ],
'td' => [ 'class' => 'g-center' ]
], [
'name' => 'Usuń',
'action' => [ 'type' => 'delete', 'url' => '/admin/shop_coupon/coupon_delete/id=[id]' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 70px;' ],
'td' => [ 'class' => 'g-center' ]
]
];
$grid -> buttons = [
[
'label' => 'Dodaj kupon',
'url' => '/admin/shop_coupon/coupon_edit/',
'icon' => 'fa-plus-circle',
'class' => 'btn-success'
]
];
echo $grid -> draw();

View File

@@ -75,7 +75,7 @@
<li>
<a href="/admin/shop_statuses/view_list/"><i class="fa fa-bars"></i>Statusy zam&#243;wie&#324;</a>
</li>
<li><a href="/admin/shop_coupon/view_list/"><img src="/admin/layout/icon/icon-menu/piggy-bank-coins.svg">Kody rabatowe</a></li>
<li><a href="/admin/shop_coupon/list/"><img src="/admin/layout/icon/icon-menu/piggy-bank-coins.svg">Kody rabatowe</a></li>
<li><a href="/admin/shop_promotion/list/"><img src="/admin/layout/icon/icon-menu/burst-sale.svg">Promocje</a></li>
</ul>
<div class="title">Zawarto&#347;&#263;</div>
@@ -197,6 +197,55 @@
</div>
</div>
<script class="footer" type="text/javascript">
(function() {
function bindClearCacheButton() {
$(document)
.off('click.clearCacheBtn', '#clear-cache-btn')
.on('click.clearCacheBtn', '#clear-cache-btn', function(e) {
e.preventDefault();
var $btn = $(this);
var originalText = $btn.text();
// Show pending state
$btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Czyszcz\u0119 cache...');
// Send AJAX request
$.ajax({
url: '/admin/settings/clearCacheAjax/',
type: 'POST',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
// Show success state
$btn.html('<i class="fa fa-check"></i> Cache wyczyszczony!').removeClass('btn-danger').addClass('btn-success');
// Restore original state after delay
setTimeout(function() {
$btn.prop('disabled', false).html(originalText).removeClass('btn-success').addClass('btn-danger');
}, 2000);
} else {
// Request failed on server
$btn.html('<i class="fa fa-exclamation-triangle"></i> B\u0142\u0105d!').removeClass('btn-danger').addClass('btn-warning');
setTimeout(function() {
$btn.prop('disabled', false).html(originalText).removeClass('btn-warning').addClass('btn-danger');
}, 2000);
}
},
error: function() {
// Network or transport error
$btn.html('<i class="fa fa-exclamation-triangle"></i> B\u0142\u0105d po\u0142\u0105czenia!').removeClass('btn-danger').addClass('btn-warning');
setTimeout(function() {
$btn.prop('disabled', false).html(originalText).removeClass('btn-warning').addClass('btn-danger');
}, 2000);
}
});
});
}
bindClearCacheButton();
})();
$(document).ready(function () {
var user_agent = navigator.userAgent.toLowerCase();
var click_event = user_agent.match(/(iphone|ipod|ipad)/) ? "touchend" : "click";
@@ -218,47 +267,6 @@
}
});
// Cache clear button handler
$('#clear-cache-btn').on('click', function(e) {
e.preventDefault();
var $btn = $(this);
var originalText = $btn.text();
// Show pending state
$btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Czyszcz\u0119 cache...');
// Send AJAX request
$.ajax({
url: '/admin/settings/clearCacheAjax/',
type: 'POST',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
// Show success state
$btn.html('<i class="fa fa-check"></i> Cache wyczyszczony!').removeClass('btn-danger').addClass('btn-success');
// Restore original state after delay
setTimeout(function() {
$btn.prop('disabled', false).html(originalText).removeClass('btn-success').addClass('btn-danger');
}, 2000);
} else {
// Request failed on server
$btn.html('<i class="fa fa-exclamation-triangle"></i> B\u0142\u0105d!').removeClass('btn-danger').addClass('btn-warning');
setTimeout(function() {
$btn.prop('disabled', false).html(originalText).removeClass('btn-warning').addClass('btn-danger');
}, 2000);
}
},
error: function() {
// Network or transport error
$btn.html('<i class="fa fa-exclamation-triangle"></i> B\u0142\u0105d po\u0142\u0105czenia!').removeClass('btn-danger').addClass('btn-warning');
setTimeout(function() {
$btn.prop('disabled', false).html(originalText).removeClass('btn-warning').addClass('btn-danger');
}, 2000);
}
});
});
});
</script>
</body>

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.'];
}

View File

@@ -210,7 +210,6 @@ class BannerController
$savedId = $this->repository->save($data);
if ($savedId) {
\S::delete_dir('../temp/');
$response = [
'success' => true,
'id' => $savedId,

View File

@@ -0,0 +1,353 @@
<?php
namespace admin\Controllers;
use Domain\Coupon\CouponRepository;
use admin\ViewModels\Common\PaginatedTableViewModel;
use admin\ViewModels\Forms\FormAction;
use admin\ViewModels\Forms\FormEditViewModel;
use admin\ViewModels\Forms\FormField;
use admin\ViewModels\Forms\FormTab;
class ShopCouponController
{
private CouponRepository $repository;
public function __construct(CouponRepository $repository)
{
$this->repository = $repository;
}
public function list(): string
{
$sortableColumns = ['id', 'status', 'used_count', 'name', 'type', 'amount', 'one_time', 'send', 'used', 'date_used'];
$filterDefinitions = [
[
'key' => 'name',
'label' => 'Nazwa',
'type' => 'text',
],
[
'key' => 'status',
'label' => 'Aktywny',
'type' => 'select',
'options' => [
'' => '- aktywny -',
'1' => 'tak',
'0' => 'nie',
],
],
[
'key' => 'used',
'label' => 'Uzyty',
'type' => 'select',
'options' => [
'' => '- uzyty -',
'1' => 'tak',
'0' => 'nie',
],
],
[
'key' => 'send',
'label' => 'Wyslany',
'type' => 'select',
'options' => [
'' => '- wyslany -',
'1' => 'tak',
'0' => 'nie',
],
],
];
$listRequest = \admin\Support\TableListRequestFactory::fromRequest(
$filterDefinitions,
$sortableColumns,
'name'
);
$sortDir = $listRequest['sortDir'];
if (trim((string)\S::get('sort')) === '') {
$sortDir = 'ASC';
}
$result = $this->repository->listForAdmin(
$listRequest['filters'],
$listRequest['sortColumn'],
$sortDir,
$listRequest['page'],
$listRequest['perPage']
);
$rows = [];
$lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
foreach ($result['items'] as $item) {
$id = (int)($item['id'] ?? 0);
$name = trim((string)($item['name'] ?? ''));
$status = (int)($item['status'] ?? 0);
$used = (int)($item['used'] ?? 0);
$send = (int)($item['send'] ?? 0);
$oneTime = (int)($item['one_time'] ?? 0);
$type = (int)($item['type'] ?? 0);
$amount = (string)($item['amount'] ?? '');
$dateUsed = trim((string)($item['date_used'] ?? ''));
$rows[] = [
'lp' => $lp++ . '.',
'status' => $status === 1 ? 'tak' : '<span style="color: #FF0000;">nie</span>',
'used_count' => (int)($item['used_count'] ?? 0),
'name' => '<a href="/admin/shop_coupon/edit/id=' . $id . '">' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '</a>',
'type' => htmlspecialchars((string)($type === 1 ? 'Rabat procentowy na koszyk' : '-'), ENT_QUOTES, 'UTF-8'),
'amount' => $type === 1 && $amount !== '' ? htmlspecialchars($amount, ENT_QUOTES, 'UTF-8') . '%' : '-',
'one_time' => $oneTime === 1 ? 'tak' : 'nie',
'send' => $send === 1 ? 'tak' : 'nie',
'used' => $used === 1 ? 'tak' : 'nie',
'date_used' => $dateUsed !== '' ? htmlspecialchars($dateUsed, ENT_QUOTES, 'UTF-8') : '-',
'_actions' => [
[
'label' => 'Edytuj',
'url' => '/admin/shop_coupon/edit/id=' . $id,
'class' => 'btn btn-xs btn-primary',
],
[
'label' => 'Usun',
'url' => '/admin/shop_coupon/delete/id=' . $id,
'class' => 'btn btn-xs btn-danger',
'confirm' => 'Na pewno chcesz usunac wybrany kupon?',
'confirm_ok' => 'Usun',
'confirm_cancel' => 'Anuluj',
],
],
];
}
$total = (int)$result['total'];
$totalPages = max(1, (int)ceil($total / $listRequest['perPage']));
$viewModel = new PaginatedTableViewModel(
[
['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
['key' => 'status', 'sort_key' => 'status', 'label' => 'Aktywny', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
['key' => 'used_count', 'sort_key' => 'used_count', 'label' => 'Uzyto X razy', 'class' => 'text-center', 'sortable' => true],
['key' => 'name', 'sort_key' => 'name', 'label' => 'Nazwa', 'sortable' => true, 'raw' => true],
['key' => 'type', 'sort_key' => 'type', 'label' => 'Typ kuponu', 'sortable' => true],
['key' => 'amount', 'sort_key' => 'amount', 'label' => 'Wartosc', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
['key' => 'one_time', 'sort_key' => 'one_time', 'label' => 'Kupon jednorazowy', 'class' => 'text-center', 'sortable' => true],
['key' => 'send', 'sort_key' => 'send', 'label' => 'Wyslany', 'class' => 'text-center', 'sortable' => true],
['key' => 'used', 'sort_key' => 'used', 'label' => 'Uzyty', 'class' => 'text-center', 'sortable' => true],
['key' => 'date_used', 'sort_key' => 'date_used', 'label' => 'Data uzycia', 'class' => 'text-center', 'sortable' => true, 'raw' => true],
],
$rows,
$listRequest['viewFilters'],
[
'column' => $listRequest['sortColumn'],
'dir' => $sortDir,
],
[
'page' => $listRequest['page'],
'per_page' => $listRequest['perPage'],
'total' => $total,
'total_pages' => $totalPages,
],
array_merge($listRequest['queryFilters'], [
'sort' => $listRequest['sortColumn'],
'dir' => $sortDir,
'per_page' => $listRequest['perPage'],
]),
$listRequest['perPageOptions'],
$sortableColumns,
'/admin/shop_coupon/list/',
'Brak danych w tabeli.',
'/admin/shop_coupon/edit/',
'Dodaj kupon'
);
return \Tpl::view('shop-coupon/coupons-list', [
'viewModel' => $viewModel,
]);
}
public function view_list(): string
{
return $this->list();
}
public function edit(): string
{
$coupon = $this->repository->find((int)\S::get('id'));
$categories = $this->repository->categoriesTree(null);
return \Tpl::view('shop-coupon/coupon-edit-new', [
'form' => $this->buildFormViewModel($coupon, $categories),
]);
}
public function coupon_edit(): string
{
return $this->edit();
}
public function save(): void
{
$legacyValues = \S::get('values');
if ($legacyValues) {
$values = json_decode((string)$legacyValues, true);
$response = [
'status' => 'error',
'msg' => 'Podczas zapisywania kuponu wystapil blad. Prosze sprobowac ponownie.',
];
if (is_array($values)) {
$id = $this->repository->save($values);
if (!empty($id)) {
$response = [
'status' => 'ok',
'msg' => 'Kupon zostal zapisany.',
'id' => (int)$id,
];
}
}
echo json_encode($response);
exit;
}
$payload = $_POST;
if (empty($payload['id'])) {
$routeId = (int)\S::get('id');
if ($routeId > 0) {
$payload['id'] = $routeId;
}
}
$id = $this->repository->save($payload);
if (!empty($id)) {
echo json_encode([
'success' => true,
'id' => (int)$id,
'message' => 'Kupon zostal zapisany.',
]);
exit;
}
echo json_encode([
'success' => false,
'errors' => ['general' => 'Podczas zapisywania kuponu wystapil blad.'],
]);
exit;
}
public function coupon_save(): void
{
$this->save();
}
public function delete(): void
{
if ($this->repository->delete((int)\S::get('id'))) {
\S::alert('Kupon zostal usuniety.');
}
header('Location: /admin/shop_coupon/list/');
exit;
}
public function coupon_delete(): void
{
$this->delete();
}
private function buildFormViewModel(array $coupon, array $categories): FormEditViewModel
{
$id = (int)($coupon['id'] ?? 0);
$isNew = $id <= 0;
$data = [
'id' => $id,
'name' => (string)($coupon['name'] ?? ''),
'send' => (int)($coupon['send'] ?? 0),
'status' => (int)($coupon['status'] ?? 1),
'used' => (int)($coupon['used'] ?? 0),
'type' => (int)($coupon['type'] ?? 1),
'amount' => (string)($coupon['amount'] ?? ''),
'one_time' => (int)($coupon['one_time'] ?? 1),
'include_discounted_product' => (int)($coupon['include_discounted_product'] ?? 0),
];
$fields = [
FormField::hidden('id', $id),
FormField::text('name', [
'label' => 'Nazwa',
'tab' => 'settings',
'required' => true,
]),
FormField::switch('send', [
'label' => 'Wyslany',
'tab' => 'settings',
]),
FormField::switch('status', [
'label' => 'Aktywny',
'tab' => 'settings',
'value' => true,
]),
FormField::switch('used', [
'label' => 'Uzyty',
'tab' => 'settings',
]),
FormField::select('type', [
'label' => 'Typ kuponu',
'tab' => 'settings',
'options' => [
1 => 'Rabat procentowy na koszyk',
],
'required' => true,
]),
FormField::text('amount', [
'label' => 'Wartosc',
'tab' => 'settings',
'attributes' => ['class' => 'number-format'],
]),
FormField::switch('one_time', [
'label' => 'Kupon jednorazowy',
'tab' => 'settings',
'value' => true,
]),
FormField::switch('include_discounted_product', [
'label' => 'Dotyczy rowniez produktow przecenionych',
'tab' => 'settings',
]),
FormField::custom('coupon_categories', \Tpl::view('shop-coupon/coupon-categories-selector', [
'label' => 'Ogranicz promocje do wybranych kategorii',
'inputName' => 'categories[]',
'categories' => $categories,
'selectedIds' => is_array($coupon['categories'] ?? null) ? $coupon['categories'] : [],
]), [
'tab' => 'categories',
]),
];
$tabs = [
new FormTab('settings', 'Ustawienia', 'fa-wrench'),
new FormTab('categories', 'Kategorie', 'fa-folder-open'),
];
$actionUrl = '/admin/shop_coupon/save/' . ($isNew ? '' : ('id=' . $id));
$actions = [
FormAction::save($actionUrl, '/admin/shop_coupon/list/'),
FormAction::cancel('/admin/shop_coupon/list/'),
];
return new FormEditViewModel(
'shop-coupon-edit',
$isNew ? 'Nowy kupon' : ('Edycja kuponu: ' . (string)($coupon['name'] ?? '')),
$data,
$fields,
$tabs,
$actions,
'POST',
$actionUrl,
'/admin/shop_coupon/list/',
true,
['id' => $id]
);
}
}

View File

@@ -309,6 +309,13 @@ class Site
new \Domain\Promotion\PromotionRepository( $mdb )
);
},
'ShopCoupon' => function() {
global $mdb;
return new \admin\Controllers\ShopCouponController(
new \Domain\Coupon\CouponRepository( $mdb )
);
},
'Pages' => function() {
global $mdb;

View File

@@ -1,58 +0,0 @@
<?php
namespace admin\controls;
class ShopCoupon
{
public static function coupon_delete()
{
$coupon = new \shop\Coupon( (int)\S::get( 'id' ) );
if ( $coupon -> delete() )
\S::alert( 'Kupon został usunięty.' );
header( 'Location: /admin/shop_coupon/view_list/' );
exit;
}
public static function coupon_save()
{
$response = ['status' => 'error', 'msg' => 'Podczas zapisywania kuponu wystąpił błąd. Proszę spróbować ponownie.'];
$values = json_decode( \S::get( 'values' ), true );
if ( $values['categories'] != null )
$categories = is_array( $values['categories'] ) ? json_encode( $values['categories'] ) : json_encode( [ $values['categories'] ] );
else
$categories = null;
if ( \admin\factory\ShopCoupon::save(
$values['id'],
$values['name'],
$values['status'] == 'on' ? 1 : 0,
$values['send'] == 'on' ? 1 : 0,
$values['used'] == 'on' ? 1 : 0,
$values['type'],
$values['amount'],
$values['one_time'] == 'on' ? 1 : 0,
$values['include_discounted_product'] == 'on' ? 1 : 0,
$categories
)
)
$response = [ 'status' => 'ok', 'msg' => 'Kupon został zapisany.', 'id' => $values['id'] ];
echo json_encode( $response );
exit;
}
public static function coupon_edit()
{
return \Tpl::view( 'shop-coupon/coupon-edit', [
'coupon' => \admin\factory\ShopCoupon::details( (int)\S::get( 'id' ) ),
'categories' => \admin\factory\ShopCategory::subcategories( null ),
'dlang' => \front\factory\Languages::default_language()
] );
}
public static function view_list()
{
return \Tpl::view( 'shop-coupon/view-list' );
}
}

View File

@@ -1,54 +0,0 @@
<?php
namespace admin\factory;
class ShopCoupon
{
static public function details( int $coupon_id )
{
global $mdb;
return $mdb -> get( 'pp_shop_coupon', '*', [ 'id' => $coupon_id ] );
}
public static function coupon_delete( $coupon_id )
{
global $mdb;
return $mdb -> delete( 'pp_shop_coupon', [ 'id' => $coupon_id ] );
}
public static function save( $coupon_id, $name, $status, $send, $used, $type, $amount, $one_time, $include_discounted_product, $categories )
{
global $mdb;
if ( !$coupon_id )
{
if ( $mdb -> insert( 'pp_shop_coupon', [
'name' => $name,
'status' => $status,
'used' => $used,
'type' => $type,
'amount' => $amount,
'one_time' => $one_time,
'send' => $send,
'include_discounted_product' => $include_discounted_product,
'categories' => $categories
] ) )
return $mdb -> id();
}
else
{
$mdb -> update( 'pp_shop_coupon', [
'name' => $name,
'status' => $status,
'used' => $used,
'type' => $type,
'amount' => $amount,
'one_time' => $one_time,
'send' => $send,
'include_discounted_product' => $include_discounted_product,
'categories' => $categories
], [
'id' => $coupon_id
] );
return true;
}
}
}

View File

@@ -136,6 +136,17 @@ if ( \S::get( 'a' ) == 'page' and \S::get( 'id' ) )
\S::set_session( 'page', $page );
}
if ( !is_array( $page ) or !(int)$page['id'] )
{
$page = \S::get_session( 'page' );
}
if ( !is_array( $page ) or !(int)$page['id'] )
{
$page = \front\factory\Pages::page_details();
\S::set_session( 'page', $page );
}
if ( \S::get( 'devel' ) )
$settings[ 'devel' ] = true;
@@ -350,4 +361,4 @@ if ( file_exists( 'plugins/special-actions-end.php' ) )
include 'plugins/special-actions-end.php';
echo $html;
?>
?>

View File

@@ -0,0 +1,268 @@
<?php
namespace Tests\Unit\Domain\Coupon;
use PHPUnit\Framework\TestCase;
use Domain\Coupon\CouponRepository;
class CouponRepositoryTest extends TestCase
{
public function testFindReturnsDefaultCouponForInvalidId(): void
{
$mockDb = $this->createMock(\medoo::class);
$repository = new CouponRepository($mockDb);
$result = $repository->find(0);
$this->assertIsArray($result);
$this->assertSame(0, (int)$result['id']);
$this->assertSame(1, (int)$result['status']);
$this->assertSame(1, (int)$result['one_time']);
$this->assertSame([], $result['categories']);
}
public function testFindNormalizesCouponData(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->expects($this->once())
->method('get')
->with('pp_shop_coupon', '*', ['id' => 15])
->willReturn([
'id' => '15',
'name' => 'KOD15',
'status' => '1',
'send' => 0,
'used' => '1',
'type' => '1',
'amount' => '15.00',
'one_time' => '0',
'include_discounted_product' => '1',
'categories' => '[4,6,6]',
'used_count' => '3',
]);
$repository = new CouponRepository($mockDb);
$result = $repository->find(15);
$this->assertSame(15, (int)$result['id']);
$this->assertSame(1, (int)$result['status']);
$this->assertSame(0, (int)$result['send']);
$this->assertSame(1, (int)$result['used']);
$this->assertSame(0, (int)$result['one_time']);
$this->assertSame(1, (int)$result['include_discounted_product']);
$this->assertSame([4, 6], $result['categories']);
$this->assertSame(3, (int)$result['used_count']);
}
public function testSaveInsertsCouponAndReturnsId(): void
{
$mockDb = $this->createMock(\medoo::class);
$insertRow = null;
$mockDb->expects($this->once())
->method('insert')
->willReturnCallback(function ($table, $row) use (&$insertRow) {
$this->assertSame('pp_shop_coupon', $table);
$insertRow = $row;
});
$mockDb->expects($this->once())
->method('id')
->willReturn(321);
$repository = new CouponRepository($mockDb);
$id = $repository->save([
'name' => ' KOD25 ',
'status' => 'on',
'send' => '1',
'used' => 0,
'type' => 1,
'amount' => '25,50',
'one_time' => 'on',
'include_discounted_product' => 'on',
'categories' => [1, '2', 'abc', 2],
]);
$this->assertSame(321, $id);
$this->assertIsArray($insertRow);
$this->assertSame('KOD25', $insertRow['name'] ?? '');
$this->assertSame(1, (int)($insertRow['status'] ?? 0));
$this->assertSame(1, (int)($insertRow['send'] ?? 0));
$this->assertSame(0, (int)($insertRow['used'] ?? 1));
$this->assertSame('25.50', $insertRow['amount'] ?? null);
$this->assertSame('[1,2]', $insertRow['categories'] ?? null);
}
public function testSaveUpdatesCouponAndReturnsId(): void
{
$mockDb = $this->createMock(\medoo::class);
$updateRow = null;
$updateWhere = null;
$mockDb->expects($this->once())
->method('update')
->willReturnCallback(function ($table, $row, $where) use (&$updateRow, &$updateWhere) {
$this->assertSame('pp_shop_coupon', $table);
$updateRow = $row;
$updateWhere = $where;
return true;
});
$mockDb->expects($this->never())->method('insert');
$mockDb->expects($this->never())->method('id');
$repository = new CouponRepository($mockDb);
$id = $repository->save([
'id' => 77,
'name' => 'KOD77',
'status' => '0',
'send' => 'off',
'used' => '0',
'type' => 1,
'amount' => '',
'one_time' => '0',
'include_discounted_product' => 0,
'categories' => '',
]);
$this->assertSame(77, $id);
$this->assertIsArray($updateRow);
$this->assertArrayHasKey('amount', $updateRow);
$this->assertArrayHasKey('categories', $updateRow);
$this->assertNull($updateRow['amount']);
$this->assertNull($updateRow['categories']);
$this->assertSame(0, (int)($updateRow['status'] ?? 1));
$this->assertSame(['id' => 77], $updateWhere);
}
public function testDeleteReturnsFalseForInvalidId(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->expects($this->never())->method('delete');
$repository = new CouponRepository($mockDb);
$this->assertFalse($repository->delete(0));
}
public function testDeleteReturnsTrueWhenDatabaseDeleteSucceeds(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->expects($this->once())
->method('delete')
->with('pp_shop_coupon', ['id' => 55])
->willReturn(true);
$repository = new CouponRepository($mockDb);
$this->assertTrue($repository->delete(55));
}
public function testListForAdminWhitelistsSortAndDirection(): void
{
$mockDb = $this->createMock(\medoo::class);
$queries = [];
$mockDb->method('query')
->willReturnCallback(function ($sql, $params = []) use (&$queries) {
$queries[] = ['sql' => $sql, 'params' => $params];
if (strpos($sql, 'COUNT(0)') !== false) {
return new class {
public function fetchAll()
{
return [[1]];
}
};
}
return new class {
public function fetchAll()
{
return [[
'id' => 1,
'name' => 'KOD',
'status' => 1,
'used' => 0,
'type' => 1,
'amount' => '10',
'one_time' => 1,
'send' => 0,
'include_discounted_product' => 0,
'categories' => '[3,5]',
'date_used' => null,
'used_count' => 7,
]];
}
};
});
$repository = new CouponRepository($mockDb);
$result = $repository->listForAdmin(
[],
'date_used DESC; DROP TABLE pp_shop_coupon; --',
'DESC; DELETE FROM pp_users; --',
1,
999
);
$this->assertCount(2, $queries);
$dataSql = $queries[1]['sql'];
$this->assertMatchesRegularExpression('/ORDER BY\s+sc\.name\s+ASC,\s+sc\.id\s+DESC/i', $dataSql);
$this->assertStringNotContainsString('DROP TABLE', $dataSql);
$this->assertStringNotContainsString('DELETE FROM pp_users', $dataSql);
$this->assertMatchesRegularExpression('/LIMIT\s+100\s+OFFSET\s+0/i', $dataSql);
$this->assertSame([3, 5], $result['items'][0]['categories']);
}
public function testCategoriesTreeReturnsHierarchy(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->method('select')
->willReturnCallback(function ($table, $columns, $where) {
if ($table === 'pp_shop_categories' && array_key_exists('parent_id', $where)) {
if ($where['parent_id'] === null) {
return [['id' => 10]];
}
if ((int)$where['parent_id'] === 10) {
return [['id' => 11]];
}
return [];
}
if ($table === 'pp_shop_categories_langs') {
if ((int)$where['category_id'] === 10) {
return [['lang_id' => 'pl', 'title' => 'Kategoria A']];
}
if ((int)$where['category_id'] === 11) {
return [['lang_id' => 'pl', 'title' => 'Podkategoria A1']];
}
return [];
}
if ($table === 'pp_langs') {
return [['id' => 'pl', 'start' => 1, 'o' => 1]];
}
return [];
});
$mockDb->method('get')
->willReturnCallback(function ($table, $columns, $where) {
if ($table === 'pp_shop_categories') {
$id = (int)$where['id'];
return ['id' => $id, 'status' => 1];
}
return null;
});
$repository = new CouponRepository($mockDb);
$tree = $repository->categoriesTree(null);
$this->assertCount(1, $tree);
$this->assertSame(10, (int)$tree[0]['id']);
$this->assertSame('Kategoria A', $tree[0]['title']);
$this->assertCount(1, $tree[0]['subcategories']);
$this->assertSame(11, (int)$tree[0]['subcategories'][0]['id']);
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Tests\Unit\admin\Controllers;
use PHPUnit\Framework\TestCase;
use admin\Controllers\ShopCouponController;
use Domain\Coupon\CouponRepository;
class ShopCouponControllerTest extends TestCase
{
private $repository;
private $controller;
protected function setUp(): void
{
$this->repository = $this->createMock(CouponRepository::class);
$this->controller = new ShopCouponController($this->repository);
}
public function testConstructorAcceptsRepository(): void
{
$controller = new ShopCouponController($this->repository);
$this->assertInstanceOf(ShopCouponController::class, $controller);
}
public function testHasMainActionMethods(): void
{
$this->assertTrue(method_exists($this->controller, 'list'));
$this->assertTrue(method_exists($this->controller, 'edit'));
$this->assertTrue(method_exists($this->controller, 'save'));
$this->assertTrue(method_exists($this->controller, 'delete'));
}
public function testHasLegacyAliasMethods(): void
{
$this->assertTrue(method_exists($this->controller, 'view_list'));
$this->assertTrue(method_exists($this->controller, 'coupon_edit'));
$this->assertTrue(method_exists($this->controller, 'coupon_save'));
$this->assertTrue(method_exists($this->controller, 'coupon_delete'));
}
public function testActionMethodReturnTypes(): void
{
$reflection = new \ReflectionClass($this->controller);
$this->assertEquals('string', (string)$reflection->getMethod('list')->getReturnType());
$this->assertEquals('string', (string)$reflection->getMethod('view_list')->getReturnType());
$this->assertEquals('string', (string)$reflection->getMethod('edit')->getReturnType());
$this->assertEquals('string', (string)$reflection->getMethod('coupon_edit')->getReturnType());
$this->assertEquals('void', (string)$reflection->getMethod('save')->getReturnType());
$this->assertEquals('void', (string)$reflection->getMethod('coupon_save')->getReturnType());
$this->assertEquals('void', (string)$reflection->getMethod('delete')->getReturnType());
$this->assertEquals('void', (string)$reflection->getMethod('coupon_delete')->getReturnType());
}
public function testConstructorRequiresCouponRepository(): void
{
$reflection = new \ReflectionClass(ShopCouponController::class);
$constructor = $reflection->getConstructor();
$params = $constructor->getParameters();
$this->assertCount(1, $params);
$this->assertEquals('Domain\Coupon\CouponRepository', $params[0]->getType()->getName());
}
}

BIN
updates/0.20/ver_0.266.zip Normal file

Binary file not shown.

View File

@@ -0,0 +1,4 @@
F: ../admin/templates/shop-coupon/coupon-edit.php
F: ../admin/templates/shop-coupon/view-list.php
F: ../autoload/admin/controls/class.ShopCoupon.php
F: ../autoload/admin/factory/class.ShopCoupon.php

View File

@@ -1,3 +1,14 @@
<b>ver. 0.266 - 13.02.2026</b><br />
- NEW - migracja modulu `ShopCoupon` do architektury Domain + DI (`Domain\Coupon\CouponRepository`, `admin\Controllers\ShopCouponController`)
- UPDATE - modul `/admin/shop_coupon/*` przepiety z legacy `grid/gridEdit` na `components/table-list` i `components/form-edit`
- UPDATE - nowe widoki i partiale: `shop-coupon/coupons-list`, `shop-coupon/coupon-edit-new`, `shop-coupon/coupon-categories-selector`, `shop-coupon/coupon-categories-tree`, `shop-coupon/coupon-edit-custom-script`
- UPDATE - zachowana kompatybilnosc aliasow legacy akcji (`view_list`, `coupon_edit`, `coupon_save`, `coupon_delete`) w nowym kontrolerze
- CLEANUP - usuniete legacy klasy/pliki: `autoload/admin/controls/class.ShopCoupon.php`, `autoload/admin/factory/class.ShopCoupon.php`, `admin/templates/shop-coupon/view-list.php`, `admin/templates/shop-coupon/coupon-edit.php`
- UPDATE - menu admin wskazuje kanoniczny URL `/admin/shop_coupon/list/`
- FIX - ujednolicone drzewka (strzalki + focus) i wyglad checkboxow miedzy `/admin/shop_coupon/edit/*` oraz `/admin/layouts/edit/*`
- UPDATE - testy: `OK (235 tests, 682 assertions)` + nowe pliki testowe `CouponRepositoryTest`, `ShopCouponControllerTest`
- UPDATE - pliki aktualizacji: `updates/0.20/ver_0.266.zip`, `ver_0.266_files.txt`
<hr>
<b>ver. 0.265 - 13.02.2026</b><br />
- UPDATE - modul `/admin/shop_promotion/*`: dodano pole `Data od` (`date_from`) w repozytorium, formularzu i liscie
- UPDATE - front: `shop\Promotion::get_active_promotions()` uwzglednia `date_from` (okno aktywnosci od-do)
@@ -452,6 +463,3 @@

View File

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