Browse Source

User Routes (delete and get), changes to the database (category_is_kitchen is now product_is_kitchen)

EduLascala 5 months ago
parent
commit
d166cf0e82

+ 3 - 0
bin/setup

@@ -16,6 +16,9 @@ INSERT OR IGNORE INTO status (status_status) VALUES ('Livre');
 
 INSERT OR IGNORE INTO status (status_status) VALUES ('Ocupado');
 
+INSERT OR IGNORE INTO user (user_name, user_email, user_password, user_flag, company_id, role_id) VALUES ('admin', 'admin@example.com', 'admin', 'a', 1, 1);
+
+
 EOF
 
 echo "Banco de dados '$DB_FILE' criado e populado com sucesso! Senhas estão hasheadas."

+ 1 - 3
controllers/CategoryCreateController.php

@@ -24,7 +24,6 @@ class CategoryCreateController
         try {
             v::key('company_id', v::intType()->positive())
              ->key('category_name', v::stringType()->notEmpty()->alnum(' '))
-             ->key('category_is_kitchen', v::optional(v::boolType()))
              ->assert($body);
         } catch (ValidationException $e) {
             return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
@@ -32,9 +31,8 @@ class CategoryCreateController
 
         $companyId = $body['company_id'];
         $categoryName = $body['category_name'];
-        $categoryIsKitchen = $body['category_is_kitchen'] ?? false;
 
-        $created = $this->model->createCategory($categoryName, $companyId, $categoryIsKitchen);
+        $created = $this->model->createCategory($categoryName, $companyId);
 
         return $created
             ? ResponseLib::sendOk(['created' => true])

+ 4 - 1
controllers/ProductCreateController.php

@@ -26,6 +26,7 @@ class ProductCreateController
              ->key('product_name', v::stringType()->notEmpty()->alnum(' '))
              ->key('product_price', v::number()->positive())
              ->key('category_id', v::intType()->positive())
+             ->key('product_is_kitchen', v::optional(v::boolType()))
              ->assert($body);
         } catch (ValidationException $e) {
             return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
@@ -35,12 +36,14 @@ class ProductCreateController
         $productName = $body['product_name'];
         $productPrice = (float) $body['product_price'];
         $categoryId = $body['category_id'];
+        $productIsKitchen = $body['product_is_kitchen'] ?? false;
 
         $created = $this->model->createProduct(
             $productName,
             $productPrice,
             (int)$categoryId,
-            (int)$companyId
+            (int)$companyId,
+            $productIsKitchen
         );
 
         return $created

+ 8 - 4
controllers/ProductUpdateController.php

@@ -26,29 +26,33 @@ class ProductUpdateController
              ->key('update_product_id', v::intType()->positive())
              ->key('product_name', v::optional(v::stringType()->notEmpty()), false)
              ->key('product_price', v::optional(v::number()->positive()), false)
+             ->key('category_id', v::optional(v::intType()->positive()), false) // opcional mas ignorado
+             ->key('product_is_kitchen', v::optional(v::boolType()), false)
              ->assert($body);
         } catch (ValidationException $e) {
             return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
         }
 
-        // Verifica se pelo menos um dos dois está presente
         $hasProductName = isset($body['product_name']) && $body['product_name'] !== null;
         $hasProductPrice = isset($body['product_price']) && $body['product_price'] !== null;
+        $hasProductIsKitchen = array_key_exists('product_is_kitchen', $body);
 
-        if (!$hasProductName && !$hasProductPrice) {
-            return ResponseLib::sendFail("Missing product_name or product_price for update", [], "E_VALIDATE")->withStatus(400);
+        if (!$hasProductName && !$hasProductPrice && !$hasProductIsKitchen) {
+            return ResponseLib::sendFail("Missing fields to update", [], "E_VALIDATE")->withStatus(400);
         }
 
         $companyId = $body['company_id'];
         $productId = $body['update_product_id'];
         $productName = $hasProductName ? $body['product_name'] : null;
         $productPrice = $hasProductPrice ? (float)$body['product_price'] : null;
+        $productIsKitchen = $hasProductIsKitchen ? (bool)$body['product_is_kitchen'] : null;
 
         $updated = $this->model->updateProduct(
             (int)$productId,
             (int)$companyId,
             $productName,
-            $productPrice
+            $productPrice,
+            $productIsKitchen
         );
 
         return $updated

+ 42 - 0
controllers/UserDeleteController.php

@@ -0,0 +1,42 @@
+<?php
+
+namespace Controllers;
+
+use Libs\ResponseLib;
+use Models\UserModel;
+use Psr\Http\Message\ServerRequestInterface;
+use Respect\Validation\Validator as v;
+use Respect\Validation\Exceptions\ValidationException;
+
+class UserDeleteController
+{
+    private UserModel $model;
+
+    public function __construct()
+    {
+        $this->model = new UserModel();
+    }
+
+    public function __invoke(ServerRequestInterface $request)
+    {
+        $body = json_decode((string)$request->getBody(), true) ?? [];
+
+        try {
+            v::key('company_id', v::intType()->positive())
+             ->key('user_name', v::stringType()->notEmpty()->alnum(' _'))  // permite espaço e underline
+             ->assert($body);
+        } catch (ValidationException $e) {
+            return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")
+                             ->withStatus(400);
+        }
+
+        $companyId = (int) $body['company_id'];
+        $username = $body['user_name'];
+
+        $deleted = $this->model->deleteUserByName($username, $companyId);
+
+        return $deleted
+            ? ResponseLib::sendOk(['deleted' => true])
+            : ResponseLib::sendFail("Failed to delete user or user not found", [], "E_DATABASE")->withStatus(403);
+    }
+}

+ 38 - 0
controllers/UserGetController.php

@@ -0,0 +1,38 @@
+<?php
+
+namespace Controllers;
+
+use Libs\ResponseLib;
+use Models\UserModel;
+use Psr\Http\Message\ServerRequestInterface;
+use Respect\Validation\Validator as v;
+use Respect\Validation\Exceptions\ValidationException;
+
+class UserGetController
+{
+    private UserModel $model;
+
+    public function __construct()
+    {
+        $this->model = new UserModel();
+    }
+
+    public function __invoke(ServerRequestInterface $request)
+    {
+        $body = json_decode((string)$request->getBody(), true) ?? [];
+
+        try {
+            v::key('company_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'];
+        $users = $this->model->getUsersByCompany($companyId);
+
+        return $users
+            ? ResponseLib::sendOk($users)
+            : ResponseLib::sendFail("No users found", [], "E_DATABASE")->withStatus(404);
+    }
+}

+ 1 - 1
migrations/migrations_v1.sql

@@ -44,7 +44,6 @@ CREATE TABLE "category" (
     "category_id" INTEGER PRIMARY KEY AUTOINCREMENT,
     "company_id" INTEGER NOT NULL,
     "category_name" TEXT NOT NULL,
-    "category_is_kitchen" BOOLEAN NOT NULL,
     "category_flag" TEXT NOT NULL,
     FOREIGN KEY ("company_id") REFERENCES "company" ("company_id")
 );
@@ -53,6 +52,7 @@ CREATE TABLE "product" (
     "product_id" INTEGER PRIMARY KEY AUTOINCREMENT,
     "company_id" INTEGER NOT NULL,
     "category_id" INTEGER NOT NULL,
+    "product_is_kitchen" BOOLEAN NOT NULL,
     "product_name" TEXT NOT NULL,
     "product_price" TEXT NOT NULL,
     "product_flag" TEXT NOT NULL,    

+ 4 - 4
models/CategoryModel.php

@@ -21,11 +21,11 @@ class CategoryModel
         return $stmt->fetchAll(\PDO::FETCH_ASSOC);
     }
 
-    public function createCategory(string $name, int $companyId, bool $isKitchen): bool
+    public function createCategory(string $name, int $companyId): bool
     {
-        $stmt = $this->pdo->prepare("INSERT INTO category (category_name, category_is_kitchen, category_flag, company_id)
-            VALUES (:name, :is_kitchen, 'a', :company_id)");
-        return $stmt->execute(['name' => $name, 'is_kitchen' => $isKitchen ? 1 : 0, 'company_id' => $companyId]);
+        $stmt = $this->pdo->prepare("INSERT INTO category (category_name, category_flag, company_id)
+            VALUES (:name, 'a', :company_id)");
+        return $stmt->execute(['name' => $name, 'company_id' => $companyId]);
     }
 
     public function deleteByName(string $name, int $companyId): bool

+ 30 - 17
models/ProductModel.php

@@ -18,41 +18,55 @@ class ProductModel
     {
         $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);
+
+        $products = $stmt->fetchAll(\PDO::FETCH_ASSOC);
+
+        foreach ($products as &$product) {
+            $product['product_is_kitchen'] = (bool) $product['product_is_kitchen'];
+        }
+
+        return $products;
     }
 
-    public function createProduct(string $name, float $price, int $categoryId, int $companyId): bool
+    public function createProduct(string $name, float $price, int $categoryId, int $companyId, bool $productIsKitchen): 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')");
+        $stmt = $this->pdo->prepare("INSERT INTO product (product_name, product_price, category_id, company_id, product_flag, product_is_kitchen)
+                                     VALUES (:name, :price, :category_id, :company_id, 'a', :product_is_kitchen)");
         return $stmt->execute([
             'name' => $name,
             'price' => $price,
             'category_id' => $categoryId,
-            'company_id' => $companyId
+            'company_id' => $companyId,
+            'product_is_kitchen' => $productIsKitchen ? 1 : 0
         ]);
     }
 
-    public function updateProduct(int $productId, int $companyId, ?string $productName = null, ?float $productPrice = null): bool
+    public function updateProduct(int $productId, int $companyId, ?string $productName = null, ?float $productPrice = null, ?bool $productIsKitchen = null): bool
     {
         $sql = "UPDATE product SET ";
         $params = [];
+        $updates = [];
+
         if ($productName !== null) {
-            $sql .= "product_name = :product_name";
+            $updates[] = "product_name = :product_name";
             $params['product_name'] = $productName;
         }
+
         if ($productPrice !== null) {
-            if ($productName !== null) {
-                $sql .= ", ";
-            }
-            $sql .= "product_price = :product_price";
+            $updates[] = "product_price = :product_price";
             $params['product_price'] = $productPrice;
         }
 
-        if (empty($params)) {
-            return false; // Nothing to update
+        if ($productIsKitchen !== null) {
+            $updates[] = "product_is_kitchen = :product_is_kitchen";
+            $params['product_is_kitchen'] = $productIsKitchen ? 1 : 0;
+        }
+
+        if (empty($updates)) {
+            return false; // nada para atualizar
         }
 
+        $sql .= implode(', ', $updates);
         $sql .= " WHERE product_id = :product_id AND company_id = :company_id AND product_flag = 'a'";
         $params['product_id'] = $productId;
         $params['company_id'] = $companyId;
@@ -64,15 +78,14 @@ class ProductModel
     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'");
+                                     WHERE product_id = :product_id AND company_id = :company_id AND product_flag = 'a'");
         return $stmt->execute(['product_id' => $productId, 'company_id' => $companyId]);
     }
 
-    // NOVO MÉTODO PARA DELETAR POR NOME
     public function deleteProductByName(string $productName, int $companyId): bool
     {
         $stmt = $this->pdo->prepare("UPDATE product SET product_flag = 'd'
-                                    WHERE product_name = :product_name AND company_id = :company_id AND product_flag = 'a'");
+                                     WHERE product_name = :product_name AND company_id = :company_id AND product_flag = 'a'");
         return $stmt->execute(['product_name' => $productName, 'company_id' => $companyId]);
     }
-}
+}

+ 19 - 0
models/UserModel.php

@@ -78,4 +78,23 @@ class UserModel
             'api_key_secret' => $apiSecret  // Retorne para o usuário (apenas uma vez!)
         ];
     }
+
+    public function getUsersByCompany(int $companyId): array
+    {
+        $stmt = $this->pdo->prepare("SELECT user_id, user_name, user_email, role_id FROM user WHERE company_id = :company_id AND user_flag = 'a'");
+        $stmt->execute(['company_id' => $companyId]);
+        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
+    }
+
+    public function deleteUserByName(string $username, int $companyId): bool
+    {
+        $stmt = $this->pdo->prepare("UPDATE user SET user_flag = 'd' WHERE user_name = :username AND company_id = :company_id AND user_flag = 'a'");
+        $stmt->execute([
+            'username' => $username,
+            'company_id' => $companyId
+        ]);
+
+        return $stmt->rowCount() > 0;
+    }
+
 }

+ 4 - 1
public/index.php

@@ -43,7 +43,10 @@ $app->get('/jwthelloworld', $cors, $authJwt,  \Controllers\HelloController::clas
 
 //Rotas User
 $app->post('/login', $cors, \Controllers\LoginController::class);
-$app->post('/register', $cors, $authJwt, \Controllers\RegisterController::class);
+$app->post('/register', $cors, \Controllers\RegisterController::class);
+$app->post('/user/get', $cors, $authJwt, \Controllers\UserGetController::class);
+$app->post('/user/delete', $cors, $authJwt, \Controllers\UserDeleteController::class);
+
 
 //Rotas Category
 $app->post('/category/get', $cors, \Controllers\CategoryGetController::class);