Bladeren bron

New Order_Item Routes

EduLascala 5 maanden geleden
bovenliggende
commit
40e6e755ce

+ 44 - 0
controllers/OrderItemCreateController.php

@@ -0,0 +1,44 @@
+<?php
+
+namespace Controllers;
+
+use Libs\ResponseLib;
+use Models\OrderItemModel;
+use Psr\Http\Message\ServerRequestInterface;
+use Respect\Validation\Validator as v;
+use Respect\Validation\Exceptions\ValidationException;
+
+class OrderItemCreateController
+{
+    private OrderItemModel $model;
+
+    public function __construct()
+    {
+        $this->model = new OrderItemModel();
+    }
+
+    public function __invoke(ServerRequestInterface $request)
+    {
+        $body = json_decode((string)$request->getBody(), true) ?? [];
+
+        try {
+            // company_id, order_id e product_id são obrigatórios para criar um item de pedido
+            v::key('company_id', v::intType()->positive()) // company_id agora é obrigatório
+                ->key('order_id', v::intType()->positive())
+                ->key('product_id', v::intType()->positive())
+                ->assert($body);
+        } catch (ValidationException $e) {
+            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
+        }
+
+        $companyId = (int) $body['company_id'];
+        $orderId = (int) $body['order_id'];
+        $productId = (int) $body['product_id'];
+
+        $created = $this->model->createOrderItem($orderId, $productId, $companyId);
+
+        return $created
+            ? ResponseLib::sendOk(['created' => true, 'order_item_id' => $created])
+            : ResponseLib::sendFail("Failed to create order item", [], "E_DATABASE")->withStatus(500);
+    }
+}

+ 42 - 0
controllers/OrderItemDeleteController.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace Controllers;
+
+use Libs\ResponseLib;
+use Models\OrderItemModel;
+use Psr\Http\Message\ServerRequestInterface;
+use Respect\Validation\Validator as v;
+use Respect\Validation\Exceptions\ValidationException;
+
+class OrderItemDeleteController
+{
+    private OrderItemModel $model;
+
+    public function __construct()
+    {
+        $this->model = new OrderItemModel();
+    }
+
+    public function __invoke(ServerRequestInterface $request)
+    {
+        $body = json_decode((string)$request->getBody(), true) ?? [];
+
+        try {
+            // order_item_id e company_id são obrigatórios para deletar um item específico
+            v::key('order_item_id', v::intType()->positive())
+                ->key('company_id', v::intType()->positive()) 
+                ->assert($body);
+        } catch (ValidationException $e) {
+            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
+        }
+
+        $orderItemId = (int) $body['order_item_id'];
+        $companyId = (int) $body['company_id']; // Obtém o company_id do payload
+
+        $deleted = $this->model->deleteOrderItem($orderItemId, $companyId); // Passa company_id para o Model
+
+        return $deleted
+            ? ResponseLib::sendOk(['deleted' => true])
+            : ResponseLib::sendFail("Failed to delete order item or item not found for this company", [], "E_DATABASE")->withStatus(404);
+    }
+}

+ 55 - 0
controllers/OrderItemGetController.php

@@ -0,0 +1,55 @@
+<?php
+
+namespace Controllers;
+
+use Libs\ResponseLib;
+use Models\OrderItemModel;
+use Models\ProductModel; // Mantenha se for usar o enriquecimento de produto
+use Psr\Http\Message\ServerRequestInterface;
+use Respect\Validation\Validator as v;
+use Respect\Validation\Exceptions\ValidationException;
+
+class OrderItemGetController
+{
+    private OrderItemModel $model;
+
+    public function __construct()
+    {
+        $this->model = new OrderItemModel();
+    }
+
+    public function __invoke(ServerRequestInterface $request)
+    {
+        $body = json_decode((string)$request->getBody(), true) ?? [];
+
+        try {
+            // company_id e order_id são obrigatórios para listar os itens de um pedido
+            v::key('company_id', v::intType()->positive()) // Validação para company_id
+                ->key('order_id', v::intType()->positive())
+                ->assert($body);
+        } catch (ValidationException $e) {
+            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
+        }
+
+        $companyId = (int) $body['company_id']; // Obtenha o company_id do body
+        $orderId = (int) $body['order_id'];
+
+        // CORREÇÃO AQUI: Passe o $companyId para o método do Model
+        $orderItems = $this->model->getOrderItemsByOrderId($orderId, $companyId);
+        
+        $productModel = new ProductModel(); // Instancie ProductModel aqui
+        foreach ($orderItems as &$item) {
+            // Certifique-se que getProductById em ProductModel aceita $companyId
+            $product = $productModel->getProductById($item['product_id'], $companyId); 
+            $item['product_details'] = $product;
+        }
+
+
+        if (!empty($orderItems)) {
+            return ResponseLib::sendOk($orderItems);
+        }
+
+        // Atualize a mensagem de falha para refletir a nova validação
+        return ResponseLib::sendFail("No order items found for the given order ID or company ID", [], "E_DATABASE")->withStatus(404);
+    }
+}

+ 3 - 1
migrations/migrations_v1.sql

@@ -80,8 +80,10 @@ CREATE TABLE "order_item" (
     "order_item_id" INTEGER PRIMARY KEY AUTOINCREMENT,
     "order_id" INTEGER NOT NULL,
     "product_id" INTEGER NOT NULL,
+    "company_id" INTEGER NOT NULL,
     FOREIGN KEY ("order_id") REFERENCES "order" ("order_id"),
-    FOREIGN KEY ("product_id") REFERENCES "product" ("product_id")
+    FOREIGN KEY ("product_id") REFERENCES "product" ("product_id"),
+    FOREIGN KEY ("company_id") REFERENCES "company" ("company_id")
 );
 
 CREATE TABLE "sale" (

+ 84 - 0
models/OrderItemModel.php

@@ -0,0 +1,84 @@
+<?php
+
+namespace Models;
+
+use Models\OrderModel;
+use Models\ProductModel;
+
+class OrderItemModel
+{
+    private \PDO $pdo;
+
+    public function __construct()
+    {
+        $dbFile = $_ENV['DB_FILE'];
+        $dbPath = __DIR__ . '/../' . $dbFile;
+        $this->pdo = new \PDO("sqlite:" . $dbPath);
+        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
+        $this->pdo->exec('PRAGMA journal_mode = WAL;');
+        $this->pdo->exec('PRAGMA busy_timeout = 5000;');
+    }
+
+    public function createOrderItem(int $orderId, int $productId, int $companyId): int|false
+    {
+        $orderModel = new OrderModel();
+        $productModel = new ProductModel();
+
+        $order = $orderModel->getOrderById($orderId, $companyId);
+        if (!$order) {
+            return false;
+        }
+
+        $product = $productModel->getProductById($productId, $companyId);
+        if (!$product) {
+            return false;
+        }
+
+        $stmt = $this->pdo->prepare("
+            INSERT INTO order_item (order_id, product_id, company_id)
+            VALUES (:order_id, :product_id, :company_id)
+        ");
+
+        try {
+            $executed = $stmt->execute([
+                'order_id' => $orderId,
+                'product_id' => $productId,
+                'company_id' => $companyId
+            ]);
+            return $executed ? (int)$this->pdo->lastInsertId() : false;
+        } catch (\PDOException $e) {
+            // Em ambiente de produção, considere logar a exceção de forma mais robusta
+            // ou retornar uma mensagem de erro genérica mais amigável.
+            error_log("PDO Exception during order item creation: " . $e->getMessage());
+            return false;
+        }
+    }
+
+    public function deleteOrderItem(int $orderItemId, int $companyId): bool
+    {
+        $stmt = $this->pdo->prepare("
+            DELETE FROM order_item
+            WHERE order_item_id = :order_item_id
+              AND order_id IN (
+                  SELECT order_id FROM `order` WHERE company_id = :company_id AND order_flag = 'a'
+              )
+        ");
+        $executed = $stmt->execute(['order_item_id' => $orderItemId, 'company_id' => $companyId]);
+        return $executed && $stmt->rowCount() > 0;
+    }
+
+    public function getOrderItemsByOrderId(int $orderId, int $companyId): array
+    {
+        $orderModel = new OrderModel();
+        $order = $orderModel->getOrderById($orderId, $companyId);
+
+        if (!$order) {
+            return [];
+        }
+
+        // Seleciona explicitamente o 'company_id' para que ele apareça na resposta JSON
+        $stmt = $this->pdo->prepare("SELECT order_item_id, order_id, product_id, company_id FROM order_item WHERE order_id = :order_id");
+        $stmt->execute(['order_id' => $orderId]);
+        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
+    }
+}

+ 11 - 0
models/ProductModel.php

@@ -88,4 +88,15 @@ class ProductModel
                                      WHERE product_name = :product_name AND company_id = :company_id AND product_flag = 'a'");
         return $stmt->execute(['product_name' => $productName, 'company_id' => $companyId]);
     }
+
+        public function getProductById(int $productId, int $companyId): ?array
+    {
+        $stmt = $this->pdo->prepare("SELECT product_id, company_id, category_id, product_is_kitchen, product_name, product_price FROM product WHERE product_id = :product_id AND company_id = :company_id AND product_flag = 'a'");
+        $stmt->execute(['product_id' => $productId, 'company_id' => $companyId]);
+        $product = $stmt->fetch(\PDO::FETCH_ASSOC);
+        if ($product) {
+            $product['product_is_kitchen'] = (bool) $product['product_is_kitchen'];
+        }
+        return $product ?: null;
+    }
 }