| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\OrderModel;
- use Models\UserModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Respect\Validation\Validator as v;
- use Respect\Validation\Exceptions\ValidationException;
- class OrderCreateController
- {
- private OrderModel $model;
- private UserModel $userModel;
- public function __construct()
- {
- $this->model = new OrderModel();
- $this->userModel = new UserModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true) ?? [];
- try {
- v::key('table_id', v::intType()->positive())
- ->key('user_name', v::stringType()->notEmpty()->alnum('_'))
- ->key('company_id', v::intType()->positive())
- ->key('order_name', v::stringType()->notEmpty()->regex('/^[\p{L}\p{N}\s\-\'\"]+$/u'))
- ->key('order_phone', v::optional(v::stringType()->notEmpty()->length(8, 20)), false)
- ->key('status_status', v::stringType()->notEmpty()->in(['Aberta', 'Finalizada', 'Cancelada']))
- ->assert($body);
- } catch (ValidationException $e) {
- return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
- }
- $tableId = (int) $body['table_id'];
- $companyId = (int) $body['company_id'];
- $orderName = $body['order_name'];
- $orderPhone = $body['order_phone'] ?? '';
- $statusStatus = $body['status_status'];
- $userName = $body['user_name'];
- // Buscar user_id correspondente ao user_name
- $userId = $this->getUserIdByUserName($userName, $companyId);
- if (!$userId) {
- return ResponseLib::sendFail("User '{$userName}' Not Found", [], "E_USER_NOT_FOUND")->withStatus(204);
- }
- $statusId = $this->model->getStatusIdByName($statusStatus);
- if ($statusId === null) {
- return ResponseLib::sendFail("Invalid status_status Provided: '{$statusStatus}'", [], "E_VALIDATE")->withStatus(400);
- }
- $created = $this->model->createOrder(
- $tableId,
- $userId,
- $companyId,
- $orderName,
- $orderPhone,
- $statusId
- );
- return $created
- ? ResponseLib::sendOk(['created' => true, 'order_id' => $created])
- : ResponseLib::sendFail("Failed to Create Order", [], "E_DATABASE")->withStatus(500);
- }
- private function getUserIdByUserName(string $username, int $companyId): ?int
- {
- $users = $this->userModel->getUsersByCompany($companyId);
- foreach ($users as $user) {
- if ($user['user_name'] === $username) {
- return (int) $user['user_id'];
- }
- }
- return null;
- }
- }
|