| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\TshieldWebhookModel;
- use Psr\Http\Message\ServerRequestInterface;
- class TshieldWebhookController
- {
- private TshieldWebhookModel $model;
- public function __construct()
- {
- $this->model = new TshieldWebhookModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true);
- if (!is_array($body)) {
- return ResponseLib::sendFail('Invalid JSON payload.', [], 'E_VALIDATE')->withStatus(400);
- }
- error_log('[TShieldWebhook] payload=' . json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
- $statusDescription = $body['status']['status']
- ?? $body['status']
- ?? ($body['data']['status']['status'] ?? null);
- $statusNormalized = is_string($statusDescription) ? mb_strtolower(trim($statusDescription)) : '';
- $isApproved = $statusNormalized === 'aprovado'
- || $statusNormalized === 'aprovada'
- || (is_string($statusNormalized) && str_contains($statusNormalized, 'aprov'));
- if (!$isApproved) {
- return ResponseLib::sendOk([
- 'processed' => false,
- 'reason' => 'Status not approved. No action taken.',
- 'status' => $statusDescription,
- ], 'S_IGNORED');
- }
- $externalIds = [
- $body['number'] ?? null,
- $body['token'] ?? null,
- $body['data']['number'] ?? null,
- $body['data']['token'] ?? null,
- $body['analysis']['number'] ?? null,
- $body['analysis']['token'] ?? null,
- $body['query']['number'] ?? null,
- $body['query']['token'] ?? null,
- ];
- $externalNumber = null;
- foreach ($externalIds as $candidate) {
- if (is_numeric($candidate)) {
- $candidate = (string)$candidate;
- }
- if (!is_string($candidate)) {
- continue;
- }
- $candidate = trim($candidate);
- if ($candidate === '') {
- continue;
- }
- $externalNumber = $candidate;
- break;
- }
- if ($externalNumber === null) {
- return ResponseLib::sendFail('Missing analysis number/token in payload.', [], 'E_VALIDATE')->withStatus(400);
- }
- error_log('[TShieldWebhook] approved candidates=' . json_encode($externalIds, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
- error_log('[TShieldWebhook] approved number=' . $externalNumber);
- $updated = $this->model->approveByExternalIds($externalIds);
- if (!$updated) {
- return ResponseLib::sendFail(
- 'No user found for provided analysis number.',
- ['number' => $externalNumber, 'candidates' => $externalIds],
- 'E_NOT_FOUND'
- )->withStatus(404);
- }
- return ResponseLib::sendOk([
- 'processed' => true,
- 'number' => $externalNumber,
- ]);
- }
- }
|