CprQueryController.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Psr\Http\Message\ServerRequestInterface;
  5. use React\Http\Message\Response;
  6. use Models\CprQueryModel;
  7. class CprQueryController
  8. {
  9. private CprQueryModel $model;
  10. public function __construct()
  11. {
  12. $this->model = new CprQueryModel();
  13. }
  14. public function __invoke(ServerRequestInterface $request)
  15. {
  16. $body = json_decode((string)$request->getBody(), true);
  17. if (!is_array($body)) {
  18. return ResponseLib::sendFail('Invalid JSON body', [], 'E_VALIDATE')->withStatus(400);
  19. }
  20. $authCompanyId = (int)($request->getAttribute('api_company_id') ?? 0);
  21. if ($authCompanyId <= 0) {
  22. return ResponseLib::sendFail('Authenticated company not found', [], 'E_VALIDATE')->withStatus(401);
  23. }
  24. $bodyCompanyId = (int)($body['company_id'] ?? $authCompanyId);
  25. if ($bodyCompanyId <= 0) {
  26. return ResponseLib::sendFail('company_id is required', [], 'E_VALIDATE')->withStatus(400);
  27. }
  28. if ($authCompanyId !== 1 && $authCompanyId !== $bodyCompanyId) {
  29. return ResponseLib::sendFail(
  30. 'Unauthorized company access',
  31. [],
  32. 'E_AUTH'
  33. )->withStatus(403);
  34. }
  35. $hasGlobalAccess = $authCompanyId === 1;
  36. $cprId = isset($body['cpr_id']) ? (int)$body['cpr_id'] : null;
  37. try {
  38. if ($cprId) {
  39. $record = $hasGlobalAccess
  40. ? $this->model->getById($cprId)
  41. : $this->model->getByIdAndCompany($cprId, $authCompanyId);
  42. if (!$record) {
  43. return ResponseLib::sendFail(
  44. 'CPR not found',
  45. [],
  46. 'E_NOT_FOUND'
  47. )->withStatus(404);
  48. }
  49. return Response::json($record)->withStatus(200);
  50. }
  51. $list = $hasGlobalAccess
  52. ? $this->model->listAll()
  53. : $this->model->listByCompany($authCompanyId);
  54. return Response::json($list)->withStatus(200);
  55. } catch (\Throwable $e) {
  56. return ResponseLib::sendFail(
  57. 'Failed to query CPRs: ' . $e->getMessage(),
  58. [],
  59. 'E_DATABASE'
  60. )->withStatus(500);
  61. }
  62. }
  63. }