ver. 0.295: Admin order product editing — add/remove/modify products, AJAX search, stock adjustment

- Order product CRUD in admin panel (add, delete, edit quantity/prices)
- AJAX product search endpoint for order edit form
- Automatic stock adjustment when editing order products
- Transport cost recalculation based on free delivery threshold
- Fix: promo price = 0 when equal to base price (no real promotion)
- Clean up stale temp/ build artifacts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-19 19:30:38 +01:00
parent 662c9f63de
commit ccff6155ce
73 changed files with 1037 additions and 9560 deletions

View File

@@ -4,10 +4,20 @@ namespace Domain\Order;
class OrderAdminService
{
private OrderRepository $orders;
private $productRepo;
private $settingsRepo;
private $transportRepo;
public function __construct(OrderRepository $orders)
{
public function __construct(
OrderRepository $orders,
$productRepo = null,
$settingsRepo = null,
$transportRepo = null
) {
$this->orders = $orders;
$this->productRepo = $productRepo;
$this->settingsRepo = $settingsRepo;
$this->transportRepo = $transportRepo;
}
public function details(int $orderId): array
@@ -71,6 +81,215 @@ class OrderAdminService
return $saved;
}
// =========================================================================
// Order products management (admin)
// =========================================================================
public function searchProducts(string $query, string $langId): array
{
if (!$this->productRepo || trim($query) === '') {
return [];
}
$rows = $this->productRepo->searchProductByNameAjax($query, $langId);
$results = [];
foreach ($rows as $row) {
$productId = (int)($row['product_id'] ?? 0);
if ($productId <= 0) {
continue;
}
$product = $this->productRepo->findCached($productId, $langId);
if (!is_array($product)) {
continue;
}
$name = isset($product['language']['name']) ? (string)$product['language']['name'] : '';
$img = $this->productRepo->getProductImg($productId);
$results[] = [
'product_id' => $productId,
'parent_product_id' => (int)($product['parent_id'] ?? 0),
'name' => $name,
'sku' => (string)($product['sku'] ?? ''),
'ean' => (string)($product['ean'] ?? ''),
'price_brutto' => (float)($product['price_brutto'] ?? 0),
'price_brutto_promo' => (float)($product['price_brutto_promo'] ?? 0),
'vat' => (float)($product['vat'] ?? 0),
'quantity' => (int)($product['quantity'] ?? 0),
'image' => $img,
];
}
return $results;
}
public function saveOrderProducts(int $orderId, array $productsData): bool
{
if ($orderId <= 0) {
return false;
}
$currentProducts = $this->orders->orderProducts($orderId);
$currentById = [];
foreach ($currentProducts as $cp) {
$currentById[(int)$cp['id']] = $cp;
}
$submittedIds = [];
foreach ($productsData as $item) {
$orderProductId = (int)($item['order_product_id'] ?? 0);
$deleted = !empty($item['delete']);
if ($deleted && $orderProductId > 0) {
// Usunięcie — zwrot na stan
$existing = isset($currentById[$orderProductId]) ? $currentById[$orderProductId] : null;
if ($existing) {
$this->adjustStock((int)$existing['product_id'], (int)$existing['quantity']);
}
$this->orders->deleteOrderProduct($orderProductId);
$submittedIds[] = $orderProductId;
continue;
}
if ($deleted) {
continue;
}
if ($orderProductId > 0 && isset($currentById[$orderProductId])) {
// Istniejący produkt — aktualizacja
$existing = $currentById[$orderProductId];
$newQty = max(1, (int)($item['quantity'] ?? 1));
$oldQty = (int)$existing['quantity'];
$qtyDiff = $oldQty - $newQty;
$update = [
'quantity' => $newQty,
'price_brutto' => (float)($item['price_brutto'] ?? $existing['price_brutto']),
'price_brutto_promo' => (float)($item['price_brutto_promo'] ?? $existing['price_brutto_promo']),
];
$this->orders->updateOrderProduct($orderProductId, $update);
// Korekta stanu: qtyDiff > 0 = zmniejszono ilość = zwrot na stan
if ($qtyDiff !== 0) {
$this->adjustStock((int)$existing['product_id'], $qtyDiff);
}
$submittedIds[] = $orderProductId;
} elseif ($orderProductId === 0) {
// Nowy produkt
$productId = (int)($item['product_id'] ?? 0);
$qty = max(1, (int)($item['quantity'] ?? 1));
$this->orders->addOrderProduct($orderId, [
'product_id' => $productId,
'parent_product_id' => (int)($item['parent_product_id'] ?? $productId),
'name' => (string)($item['name'] ?? ''),
'attributes' => '',
'vat' => (float)($item['vat'] ?? 0),
'price_brutto' => (float)($item['price_brutto'] ?? 0),
'price_brutto_promo' => (float)($item['price_brutto_promo'] ?? 0),
'quantity' => $qty,
'message' => '',
'custom_fields' => '',
]);
// Zmniejsz stan magazynowy
$this->adjustStock($productId, -$qty);
}
}
// Usunięte z formularza (nie przesłane) — zwrot na stan
foreach ($currentById as $cpId => $cp) {
if (!in_array($cpId, $submittedIds)) {
$this->adjustStock((int)$cp['product_id'], (int)$cp['quantity']);
$this->orders->deleteOrderProduct($cpId);
}
}
// Przelicz koszt dostawy (próg darmowej dostawy)
$this->recalculateTransportCost($orderId);
return true;
}
public function getFreeDeliveryThreshold(): float
{
if (!$this->settingsRepo) {
return 0.0;
}
return (float)$this->settingsRepo->getSingleValue('free_delivery');
}
private function adjustStock(int $productId, int $delta): void
{
if (!$this->productRepo || $productId <= 0 || $delta === 0) {
return;
}
$currentQty = $this->productRepo->getQuantity($productId);
if ($currentQty === null) {
return;
}
$newQty = max(0, $currentQty + $delta);
$this->productRepo->updateQuantity($productId, $newQty);
}
private function recalculateTransportCost(int $orderId): void
{
$order = $this->orders->findRawById($orderId);
if (!$order) {
return;
}
$transportId = (int)($order['transport_id'] ?? 0);
if ($transportId <= 0 || !$this->transportRepo || !$this->settingsRepo) {
return;
}
$transport = $this->transportRepo->findActiveById($transportId);
if (!is_array($transport)) {
return;
}
// Oblicz sumę produktów (bez dostawy)
$productsSummary = $this->calculateProductsTotal($orderId);
$freeDelivery = (float)$this->settingsRepo->getSingleValue('free_delivery');
if ((int)($transport['delivery_free'] ?? 0) === 1 && $freeDelivery > 0 && $productsSummary >= $freeDelivery) {
$transportCost = 0.0;
} else {
$transportCost = (float)($transport['cost'] ?? 0);
}
$this->orders->updateTransportCost($orderId, $transportCost);
}
private function calculateProductsTotal(int $orderId): float
{
$products = $this->orders->orderProducts($orderId);
$summary = 0.0;
foreach ($products as $row) {
$pricePromo = (float)($row['price_brutto_promo'] ?? 0);
$price = (float)($row['price_brutto'] ?? 0);
$quantity = (float)($row['quantity'] ?? 0);
if ($pricePromo > 0) {
$summary += $pricePromo * $quantity;
} else {
$summary += $price * $quantity;
}
}
return $summary;
}
public function changeStatus(int $orderId, int $status, bool $sendEmail): array
{
$order = $this->orders->findRawById($orderId);

View File

@@ -435,6 +435,91 @@ class OrderRepository
return true;
}
// --- Order product CRUD (admin) ---
public function getOrderProduct(int $orderProductId): ?array
{
if ($orderProductId <= 0) {
return null;
}
$row = $this->db->get('pp_shop_order_products', '*', ['id' => $orderProductId]);
return is_array($row) ? $row : null;
}
public function addOrderProduct(int $orderId, array $data): ?int
{
if ($orderId <= 0) {
return null;
}
$this->db->insert('pp_shop_order_products', [
'order_id' => $orderId,
'product_id' => (int)($data['product_id'] ?? 0),
'parent_product_id' => (int)($data['parent_product_id'] ?? 0),
'name' => (string)($data['name'] ?? ''),
'attributes' => (string)($data['attributes'] ?? ''),
'vat' => (float)($data['vat'] ?? 0),
'price_brutto' => (float)($data['price_brutto'] ?? 0),
'price_brutto_promo' => (float)($data['price_brutto_promo'] ?? 0),
'quantity' => max(1, (int)($data['quantity'] ?? 1)),
'message' => (string)($data['message'] ?? ''),
'custom_fields' => (string)($data['custom_fields'] ?? ''),
]);
$id = $this->db->id();
return $id ? (int)$id : null;
}
public function updateOrderProduct(int $orderProductId, array $data): bool
{
if ($orderProductId <= 0) {
return false;
}
$update = [];
if (array_key_exists('quantity', $data)) {
$update['quantity'] = max(1, (int)$data['quantity']);
}
if (array_key_exists('price_brutto', $data)) {
$update['price_brutto'] = (float)$data['price_brutto'];
}
if (array_key_exists('price_brutto_promo', $data)) {
$update['price_brutto_promo'] = (float)$data['price_brutto_promo'];
}
if (empty($update)) {
return false;
}
$this->db->update('pp_shop_order_products', $update, ['id' => $orderProductId]);
return true;
}
public function deleteOrderProduct(int $orderProductId): bool
{
if ($orderProductId <= 0) {
return false;
}
$this->db->delete('pp_shop_order_products', ['id' => $orderProductId]);
return true;
}
public function updateTransportCost(int $orderId, float $cost): void
{
if ($orderId <= 0) {
return;
}
$this->db->update('pp_shop_orders', ['transport_cost' => $cost], ['id' => $orderId]);
}
// --- Frontend methods ---
public function findIdByHash(string $hash)
@@ -652,6 +737,11 @@ class OrderRepository
$product_price_tmp = \Domain\Basket\BasketCalculator::calculateBasketProductPrice((float)$product['price_brutto_promo'], (float)$product['price_brutto'], $coupon, $basket_position, $productRepo);
// Cena promo = 0 gdy taka sama jak cena bazowa (brak realnej promocji/kuponu)
$effectivePromoPrice = (float)$product_price_tmp['price_new'];
$effectiveBasePrice = (float)$product_price_tmp['price'];
$promoPrice = ($effectivePromoPrice != $effectiveBasePrice) ? $effectivePromoPrice : 0;
$this->db->insert('pp_shop_order_products', [
'order_id' => $order_id,
'product_id' => $basket_position['product-id'],
@@ -659,8 +749,8 @@ class OrderRepository
'name' => $product['language']['name'],
'attributes' => $attributes,
'vat' => $product['vat'],
'price_brutto' => $product_price_tmp['price'],
'price_brutto_promo' => $product_price_tmp['price_new'],
'price_brutto' => $effectiveBasePrice,
'price_brutto_promo' => $promoPrice,
'quantity' => $basket_position['quantity'],
'message' => $basket_position['message'],
'custom_fields' => $product_custom_fields,

View File

@@ -417,10 +417,15 @@ class App
},
'ShopOrder' => function() {
global $mdb;
$productRepo = new \Domain\Product\ProductRepository( $mdb );
return new \admin\Controllers\ShopOrderController(
new \Domain\Order\OrderAdminService(
new \Domain\Order\OrderRepository( $mdb )
)
new \Domain\Order\OrderRepository( $mdb ),
$productRepo,
new \Domain\Settings\SettingsRepository( $mdb ),
new \Domain\Transport\TransportRepository( $mdb )
),
$productRepo
);
},
'Update' => function() {

View File

@@ -2,15 +2,18 @@
namespace admin\Controllers;
use Domain\Order\OrderAdminService;
use Domain\Product\ProductRepository;
use admin\ViewModels\Common\PaginatedTableViewModel;
class ShopOrderController
{
private OrderAdminService $service;
private $productRepo;
public function __construct(OrderAdminService $service)
public function __construct(OrderAdminService $service, ProductRepository $productRepo = null)
{
$this->service = $service;
$this->productRepo = $productRepo;
}
public function list(): string
@@ -187,12 +190,27 @@ class ShopOrderController
public function order_edit(): string
{
$orderId = (int)\Shared\Helpers\Helpers::get('order_id');
$transports = ( new \Domain\Transport\TransportRepository( $GLOBALS['mdb'] ) )->allActive();
// Dane transportów do JS (id, cost, delivery_free)
$transportsJson = [];
if (is_array($transports)) {
foreach ($transports as $t) {
$transportsJson[] = [
'id' => (int)$t['id'],
'cost' => (float)$t['cost'],
'delivery_free' => (int)($t['delivery_free'] ?? 0),
];
}
}
return \Shared\Tpl\Tpl::view('shop-order/order-edit', [
'order' => $this->service->details($orderId),
'order_statuses' => $this->service->statuses(),
'transport' => ( new \Domain\Transport\TransportRepository( $GLOBALS['mdb'] ) )->allActive(),
'transport' => $transports,
'payment_methods' => ( new \Domain\PaymentMethod\PaymentMethodRepository( $GLOBALS['mdb'] ) )->allActive(),
'free_delivery' => $this->service->getFreeDeliveryThreshold(),
'transports_json' => json_encode($transportsJson),
]);
}
@@ -203,8 +221,16 @@ class ShopOrderController
public function order_save(): void
{
$orderId = (int)\Shared\Helpers\Helpers::get('order_id');
// Zapisz produkty PRZED zapisem zamówienia (bo saveOrderByAdmin przelicza summary)
$productsData = \Shared\Helpers\Helpers::get('products');
if (is_array($productsData)) {
$this->service->saveOrderProducts($orderId, $productsData);
}
$saved = $this->service->saveOrderByAdmin([
'order_id' => (int)\Shared\Helpers\Helpers::get('order_id'),
'order_id' => $orderId,
'client_name' => (string)\Shared\Helpers\Helpers::get('client_name'),
'client_surname' => (string)\Shared\Helpers\Helpers::get('client_surname'),
'client_street' => (string)\Shared\Helpers\Helpers::get('client_street'),
@@ -225,7 +251,22 @@ class ShopOrderController
\Shared\Helpers\Helpers::alert('Zamówienie zostało zapisane.');
}
header('Location: /admin/shop_order/order_details/order_id=' . (int)\Shared\Helpers\Helpers::get('order_id'));
header('Location: /admin/shop_order/order_details/order_id=' . $orderId);
exit;
}
public function search_products_ajax(): void
{
$query = trim((string)\Shared\Helpers\Helpers::get('query'));
$langId = trim((string)\Shared\Helpers\Helpers::get('lang_id'));
if ($langId === '') {
$langId = isset($_SESSION['lang_id']) ? (string)$_SESSION['lang_id'] : 'pl';
}
$results = $this->service->searchProducts($query, $langId);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['status' => 'ok', 'products' => $results]);
exit;
}