TokenOrderbookController.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\OrderbookModel;
  5. use Models\TokenModel;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. use Respect\Validation\Validator as val;
  9. class TokenOrderbookController
  10. {
  11. private TokenModel $tokenModel;
  12. private OrderbookModel $orderbookModel;
  13. private \PDO $pdo;
  14. public function __construct()
  15. {
  16. if (!isset($GLOBALS['pdo']) || !$GLOBALS['pdo'] instanceof \PDO) {
  17. throw new \RuntimeException('Global PDO connection not initialized');
  18. }
  19. $this->pdo = $GLOBALS['pdo'];
  20. $this->tokenModel = new TokenModel();
  21. $this->orderbookModel = new OrderbookModel();
  22. }
  23. public function __invoke(ServerRequestInterface $request)
  24. {
  25. $body = json_decode((string)$request->getBody(), true) ?? [];
  26. try {
  27. val::key('cpr_id', val::intType()->positive())
  28. ->key('value', val::numericVal())
  29. ->assert($body);
  30. } catch (ValidationException $e) {
  31. return ResponseLib::sendFail(
  32. 'Validation failed: ' . $e->getFullMessage(),
  33. [],
  34. 'E_VALIDATE'
  35. )->withStatus(400);
  36. }
  37. $cprId = (int)$body['cpr_id'];
  38. $newValue = (int)round((float)$body['value']);
  39. try {
  40. $this->pdo->beginTransaction();
  41. $token = $this->tokenModel->findByCprId($cprId, true);
  42. if (!$token) {
  43. $this->pdo->rollBack();
  44. return ResponseLib::sendFail(
  45. 'Token não encontrado para a CPR informada',
  46. ['cpr_id' => $cprId],
  47. 'E_TOKEN_NOT_FOUND'
  48. )->withStatus(404);
  49. }
  50. $this->tokenModel->updateCommoditiesValue((int)$token['token_id'], $newValue);
  51. $orderbook = $this->orderbookModel->create([
  52. 'orderbook_flag' => '',
  53. 'orderbook_ts' => time(),
  54. 'orderbook_is_token' => true,
  55. 'orderbook_amount' => (string)($token['token_commodities_amount'] ?? '0'),
  56. 'status_id' => 1,
  57. 'user_id' => (int)$token['user_id'],
  58. 'wallet_id' => (int)$token['wallet_id'],
  59. 'token_id' => (int)$token['token_id'],
  60. 'currency_id' => null,
  61. 'chain_id' => (int)$token['chain_id'],
  62. ]);
  63. $this->pdo->commit();
  64. } catch (\Throwable $e) {
  65. if ($this->pdo->inTransaction()) {
  66. $this->pdo->rollBack();
  67. }
  68. return ResponseLib::sendFail(
  69. 'Falha ao atualizar token e criar ordem: ' . $e->getMessage(),
  70. [],
  71. 'E_ORDERBOOK'
  72. )->withStatus(500);
  73. }
  74. return ResponseLib::sendOk([
  75. 'message' => 'Token atualizado e ordem registrada com sucesso',
  76. 'token_id' => (int)$token['token_id'],
  77. 'orderbook_id' => $orderbook['orderbook_id'],
  78. ], 'S_ORDERBOOK_CREATED');
  79. }
  80. }