Ver Fonte

Criação das rotas category e products

EduLascala há 5 meses atrás
pai
commit
595623c355

+ 77 - 0
controllers/ProductController.php

@@ -0,0 +1,77 @@
+<?php
+
+namespace Controllers;
+
+use Libs\ResponseLib;
+use Models\ProductModel;
+use Psr\Http\Message\ServerRequestInterface;
+
+class ProductController
+{
+    private ProductModel $model;
+
+    public function __construct()
+    {
+        $this->model = new ProductModel();
+    }
+
+    public function __invoke(ServerRequestInterface $request)
+    {
+        $method = $request->getMethod();
+        $body = json_decode((string)$request->getBody(), true) ?? [];
+
+        $companyId = $body['company_id'] ?? null;
+
+        if (!$companyId) {
+            return ResponseLib::sendFail("Missing Company ID", [], "E_VALIDATE")->withStatus(401);
+        }
+
+        if ($method === 'GET') {
+            $products = $this->model->getProducts($companyId);
+            return ResponseLib::sendOk($products);
+        }
+
+        if ($method === 'POST') {
+            // 1. Criar Produto
+            if (isset($body['product_name'], $body['product_price'], $body['category_id'])) {
+                $created = $this->model->createProduct(
+                    $body['product_name'],
+                    (float)$body['product_price'],
+                    (int)$body['category_id'],
+                    $companyId
+                );
+                return $created ? ResponseLib::sendOk(['created' => true]) : ResponseLib::sendFail("Failed to Create Product", [], "E_VALIDATE")->withStatus(402);
+            }
+
+            // 2. Deletar Produto (usando 'delete_product_id' para clareza)
+            if (isset($body['delete_product_id'])) {
+                $deleted = $this->model->deleteProduct((int)$body['delete_product_id'], $companyId);
+                return $deleted ? ResponseLib::sendOk(['deleted' => true]) : ResponseLib::sendFail("Failed to Delete Product or Product Not Found", [], "E_VALIDATE")->withStatus(403);
+            }
+
+            // 3. Atualizar Produto (usando 'update_product_id')
+            if (isset($body['update_product_id'])) {
+                $productId = (int)$body['update_product_id'];
+                $productName = $body['product_name'] ?? null;
+                $productPrice = isset($body['product_price']) ? (float)$body['product_price'] : null;
+
+                if ($productName === null && $productPrice === null) {
+                    return ResponseLib::sendFail("Missing product_name or product_price for update", [], "E_VALIDATE")->withStatus(400);
+                }
+
+                $updated = $this->model->updateProduct(
+                    $productId,
+                    $companyId,
+                    $productName,
+                    $productPrice
+                );
+                return $updated ? ResponseLib::sendOk(['updated' => true]) : ResponseLib::sendFail("Failed to Update Product or Product Not Found", [], "E_VALIDATE")->withStatus(404);
+            }
+
+            // Se nenhuma das ações POST acima for reconhecida
+            return ResponseLib::sendFail("Missing Data for Product POST action", [], "E_VALIDATE")->withStatus(405);
+        }
+
+        return ResponseLib::sendMethodNotAllowed(['GET', 'POST']);
+    }
+}

+ 1 - 1
migrations/migrations_v1.sql

@@ -54,7 +54,7 @@ CREATE TABLE "product" (
     "company_id" INTEGER NOT NULL,
     "category_id" INTEGER NOT NULL,
     "product_name" TEXT NOT NULL,
-    "product_price" TEXT NOT NULL,
+    "product_price" REAL NOT NULL,
     "product_flag" TEXT NOT NULL,    
     FOREIGN KEY ("category_id") REFERENCES "category" ("category_id"),
     FOREIGN KEY ("company_id") REFERENCES "company" ("company_id")

+ 70 - 0
models/ProductModel.php

@@ -0,0 +1,70 @@
+<?php
+
+namespace Models;
+
+class ProductModel
+{
+    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);
+    }
+
+    public function getProducts(int $companyId): array
+    {
+        $stmt = $this->pdo->prepare("SELECT * FROM product WHERE company_id = :company_id AND product_flag = 'a'");
+        $stmt->execute(['company_id' => $companyId]);
+        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
+    }
+
+    public function createProduct(string $name, float $price, int $categoryId, int $companyId): bool
+    {
+        $stmt = $this->pdo->prepare("INSERT INTO product (product_name, product_price, category_id, company_id, product_flag)
+                                    VALUES (:name, :price, :category_id, :company_id, 'a')");
+        return $stmt->execute([
+            'name' => $name,
+            'price' => $price,
+            'category_id' => $categoryId,
+            'company_id' => $companyId
+        ]);
+    }
+
+    public function updateProduct(int $productId, int $companyId, ?string $productName = null, ?float $productPrice = null): bool
+    {
+        $sql = "UPDATE product SET ";
+        $params = [];
+        if ($productName !== null) {
+            $sql .= "product_name = :product_name";
+            $params['product_name'] = $productName;
+        }
+        if ($productPrice !== null) {
+            if ($productName !== null) {
+                $sql .= ", ";
+            }
+            $sql .= "product_price = :product_price";
+            $params['product_price'] = $productPrice;
+        }
+
+        if (empty($params)) {
+            return false; // Nothing to update
+        }
+
+        $sql .= " WHERE product_id = :product_id AND company_id = :company_id AND product_flag = 'a'";
+        $params['product_id'] = $productId;
+        $params['company_id'] = $companyId;
+
+        $stmt = $this->pdo->prepare($sql);
+        return $stmt->execute($params);
+    }
+
+    public function deleteProduct(int $productId, int $companyId): bool
+    {
+        $stmt = $this->pdo->prepare("UPDATE product SET product_flag = 'd'
+                                    WHERE product_id = :product_id AND company_id = :company_id AND product_flag = 'a'");
+        return $stmt->execute(['product_id' => $productId, 'company_id' => $companyId]);
+    }
+}

+ 7 - 1
public/index.php

@@ -58,15 +58,21 @@ $app->options('/hmachelloworld', $handleOptions);
 $app->get('/jwthelloworld', $withCors($authJwt), \Controllers\HelloController::class);
 $app->options('/jwthelloworld', $handleOptions);
 
+
+//Rotas User
 $app->post('/login', $withCors(\Controllers\LoginController::class));
 $app->options('/login', $handleOptions);
-
 $app->post('/register', $withCors(\Controllers\RegisterController::class));
 $app->options('/register', $handleOptions);
 
+//Rotas Category
 $app->get('/category', \Controllers\CategoryController::class);
 $app->post('/category', \Controllers\CategoryController::class);
 $app->post('/category/delete', \Controllers\CategoryController::class);
 $app->post('/category/add-product', \Controllers\CategoryController::class);
 
+//Rotas Product
+$app->get('/product', \Controllers\ProductController::class);
+$app->post('/product', \Controllers\ProductController::class);
+
 $app->run();