OrderCreateController.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\OrderModel;
  5. use Models\UserModel;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. use Respect\Validation\Validator as v;
  8. use Respect\Validation\Exceptions\ValidationException;
  9. class OrderCreateController
  10. {
  11. private OrderModel $model;
  12. private UserModel $userModel;
  13. public function __construct()
  14. {
  15. $this->model = new OrderModel();
  16. $this->userModel = new UserModel();
  17. }
  18. public function __invoke(ServerRequestInterface $request)
  19. {
  20. $body = json_decode((string)$request->getBody(), true) ?? [];
  21. try {
  22. v::key('table_id', v::intType()->positive())
  23. ->key('user_name', v::stringType()->notEmpty()->alnum('_'))
  24. ->key('company_id', v::intType()->positive())
  25. ->key('order_name', v::stringType()->notEmpty()->alnum(' '))
  26. ->key('order_phone', v::optional(v::stringType()->notEmpty()->length(8, 20)), false)
  27. ->key('status_status', v::stringType()->notEmpty()->in(['Aberta', 'Finalizada', 'Cancelada']))
  28. ->assert($body);
  29. } catch (ValidationException $e) {
  30. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(422);
  31. }
  32. $tableId = (int) $body['table_id'];
  33. $companyId = (int) $body['company_id'];
  34. $orderName = $body['order_name'];
  35. $orderPhone = $body['order_phone'] ?? '';
  36. $statusStatus = $body['status_status'];
  37. $userName = $body['user_name'];
  38. // Buscar user_id correspondente ao user_name
  39. $userId = $this->getUserIdByUserName($userName, $companyId);
  40. if (!$userId) {
  41. return ResponseLib::sendFail("User '{$userName}' Not Found", [], "E_USER_NOT_FOUND")->withStatus(404);
  42. }
  43. $statusId = $this->model->getStatusIdByName($statusStatus);
  44. if ($statusId === null) {
  45. return ResponseLib::sendFail("Invalid status_status Provided: '{$statusStatus}'", [], "E_VALIDATE")->withStatus(400);
  46. }
  47. $created = $this->model->createOrder(
  48. $tableId,
  49. $userId,
  50. $companyId,
  51. $orderName,
  52. $orderPhone,
  53. $statusId
  54. );
  55. return $created
  56. ? ResponseLib::sendOk(['created' => true, 'order_id' => $created])
  57. : ResponseLib::sendFail("Failed to Create Order", [], "E_DATABASE")->withStatus(500);
  58. }
  59. private function getUserIdByUserName(string $username, int $companyId): ?int
  60. {
  61. $users = $this->userModel->getUsersByCompany($companyId);
  62. foreach ($users as $user) {
  63. if ($user['user_name'] === $username) {
  64. return (int) $user['user_id'];
  65. }
  66. }
  67. return null;
  68. }
  69. }