Procházet zdrojové kódy

revert changes, added log for debug

EduLascala před 6 dny
rodič
revize
a7db019366

+ 6 - 44
controllers/TshieldWebhookController.php

@@ -23,62 +23,24 @@ class TshieldWebhookController
             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) {
+        $statusDescription = $body['status']['status'] ?? null;
+        if ($statusDescription !== 'Aprovado') {
             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) {
+        $externalNumber = $body['number'] ?? $body['token'] ?? null;
+        if (!is_string($externalNumber) || trim($externalNumber) === '') {
             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);
+        $updated = $this->model->approveByExternalId($externalNumber);
         if (!$updated) {
             return ResponseLib::sendFail(
                 'No user found for provided analysis number.',
-                ['number' => $externalNumber, 'candidates' => $externalIds],
+                ['number' => $externalNumber],
                 'E_NOT_FOUND'
             )->withStatus(404);
         }

+ 4 - 33
models/TshieldWebhookModel.php

@@ -17,39 +17,10 @@ class TshieldWebhookModel
 
     public function approveByExternalId(string $externalId): bool
     {
-        return $this->approveByExternalIds([$externalId]);
-    }
-
-    public function approveByExternalIds(array $externalIds): bool
-    {
-        $externalIds = array_values(array_unique(array_filter(array_map(static function ($id) {
-            if (is_numeric($id)) {
-                $id = (string)$id;
-            }
-            if (!is_string($id)) {
-                return null;
-            }
-            $id = trim($id);
-            return $id === '' ? null : $id;
-        }, $externalIds))));
-
-        if (empty($externalIds)) {
-            return false;
-        }
-
-        $params = [];
-        $placeholders = [];
-        foreach ($externalIds as $i => $id) {
-            $key = 'id' . $i;
-            $placeholders[] = ':' . $key;
-            $params[$key] = $id;
-        }
-
-        $sql = 'UPDATE "user" SET user_kyc = 1 '
-            . 'WHERE kyc_external_id IN (' . implode(',', $placeholders) . ') '
-            . 'AND user_flag = \'a\'';
-        $stmt = $this->pdo->prepare($sql);
-        $stmt->execute($params);
+        $stmt = $this->pdo->prepare(
+            'UPDATE "user" SET user_kyc = 1 WHERE kyc_external_id = :external_id AND user_flag = \'a\''
+        );
+        $stmt->execute(['external_id' => $externalId]);
         return $stmt->rowCount() > 0;
     }
 }

+ 40 - 0
services/TshieldService.php

@@ -16,6 +16,7 @@ class TshieldService
     private ?string $token = null;
     private UserModel $userModel;
     private array $individualFieldMap;
+    private string $logFilePath;
 
     public function __construct()
     {
@@ -40,6 +41,7 @@ class TshieldService
         }
 
         $this->userModel = new UserModel();
+        $this->logFilePath = $this->resolveLogFilePath($_ENV['TSHIELD_LOG_FILE'] ?? null);
         $this->individualFieldMap = [
             'name' => (int)($_ENV['TSHIELD_FIELD_NAME_ID'] ?? 16175),
             'document' => (int)($_ENV['TSHIELD_FIELD_DOCUMENT_ID'] ?? 16176),
@@ -230,6 +232,8 @@ class TshieldService
         $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
         curl_close($ch);
 
+        $this->logToFile($method, $url, $httpCode, $payload, $responseBody);
+
         if ($curlErrNo !== 0) {
             throw new \RuntimeException(sprintf('cURL error while calling %s: %s (%d)', $url, $curlErr, $curlErrNo));
         }
@@ -256,6 +260,42 @@ class TshieldService
         return $decoded;
     }
 
+    private function resolveLogFilePath(?string $path): string
+    {
+        $path = trim((string)$path);
+
+        if ($path === '') {
+            $path = 'storage/logs/tshield_response.txt';
+        }
+
+        if (!preg_match('/^(?:[A-Za-z]:\\\\|\\/)/', $path)) {
+            $path = rtrim(dirname(__DIR__), '/\\') . DIRECTORY_SEPARATOR . $path;
+        }
+
+        $dir = dirname($path);
+        if (!is_dir($dir)) {
+            @mkdir($dir, 0775, true);
+        }
+
+        return $path;
+    }
+
+    private function logToFile(string $method, string $url, int $httpCode, array $payload, $responseBody): void
+    {
+        $ts = (new \DateTimeImmutable())->format('c');
+        $payloadEncoded = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
+        $responseText = is_string($responseBody) ? $responseBody : '';
+        $entry = "[$ts] $method $url HTTP=$httpCode\n" .
+            "payload=$payloadEncoded\n" .
+            "response=$responseText\n" .
+            "----\n";
+
+        try {
+            @file_put_contents($this->logFilePath, $entry, FILE_APPEND | LOCK_EX);
+        } catch (\Throwable $e) {
+        }
+    }
+
     private function logRequest(string $method, string $url, array $payload): void
     {
         $encoded = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);