Explorar el Código

logs para identificar anormalidades em producao

Gustavo Zanatta hace 2 días
padre
commit
b97da24250

+ 27 - 0
app/Http/Controllers/UserController.php

@@ -9,6 +9,7 @@ use App\Http\Requests\UserRequest;
 use App\Http\Resources\UserResource;
 use Illuminate\Http\JsonResponse;
 use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Str;
 
 class UserController extends Controller
 {
@@ -65,8 +66,34 @@ class UserController extends Controller
 
   public function updateMe(UpdateMeRequest $request): JsonResponse
   {
+      $traceId = Str::uuid()->toString();
+      Log::withContext(['trace_id' => $traceId]);
+
+      $hasAvatar = $request->hasFile('avatar');
+      $avatar    = $request->file('avatar');
+
+      Log::info('[avatar-upload] Requisição recebida em updateMe', [
+          'user_id'          => auth()->id(),
+          'has_avatar'       => $hasAvatar,
+          'avatar_valid'     => $hasAvatar ? $avatar->isValid() : null,
+          'avatar_size'      => $hasAvatar ? $avatar->getSize() : null,
+          'avatar_mime'      => $hasAvatar ? $avatar->getMimeType() : null,
+          'avatar_extension' => $hasAvatar ? $avatar->getClientOriginalExtension() : null,
+          'avatar_error'     => $hasAvatar ? $avatar->getError() : null,
+          'method'           => $request->method(),
+          'content_type'     => $request->header('Content-Type'),
+      ]);
+
       $user = $this->service->updateMe($request->validated());
 
+      Log::info('[avatar-upload] updateMe concluído com sucesso', [
+          'user_id'         => $user->id,
+          'client_id'       => $user->client?->id,
+          'profile_media_id'=> $user->client?->profile_media_id,
+          'media_path'      => $user->client?->profileMedia?->path,
+          'media_url'       => $user->client?->profileMedia?->url,
+      ]);
+
       return $this->successResponse(
           payload: new UserResource($user),
           message: __('messages.updated'),

+ 38 - 1
app/Services/MediaService.php

@@ -7,6 +7,7 @@ use App\Traits\RemoveArchiveS3;
 use App\Traits\UploadsFile;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Log;
 
 class MediaService
 {
@@ -56,21 +57,57 @@ class MediaService
 
     public function createFromFile(UploadedFile $file, string $folder, string $source, int $sourceId, ?string $filename = null): Media
     {
+        Log::info('[avatar-upload] MediaService::createFromFile — iniciando upload para S3', [
+            'folder'            => $folder,
+            'source'            => $source,
+            'source_id'         => $sourceId,
+            'file_original_name'=> $file->getClientOriginalName(),
+            'file_size'         => $file->getSize(),
+            'file_mime'         => $file->getMimeType(),
+            'file_extension'    => $file->getClientOriginalExtension(),
+            'file_is_valid'     => $file->isValid(),
+        ]);
+
         $path = $this->uploadFile($file, $folder, $filename);
 
-        return Media::create([
+        Log::info('[avatar-upload] MediaService::createFromFile — upload concluído, criando registro Media', [
+            'path_retornado' => $path,
+            'source'         => $source,
+            'source_id'      => $sourceId,
+        ]);
+
+        $media = Media::create([
             'source'    => $source,
             'source_id' => $sourceId,
             'name'      => $file->getClientOriginalName(),
             'path'      => $path,
         ]);
+
+        Log::info('[avatar-upload] MediaService::createFromFile — Media criado no banco', [
+            'media_id'   => $media->id,
+            'media_path' => $media->path,
+            'media_url'  => $media->url ?? null,
+        ]);
+
+        return $media;
     }
 
     public function replaceFile(UploadedFile $newFile, string $folder, string $source, int $sourceId, ?Media $old = null, ?string $filename = null): Media
     {
+        Log::info('[avatar-upload] MediaService::replaceFile iniciado', [
+            'folder'       => $folder,
+            'source'       => $source,
+            'source_id'    => $sourceId,
+            'has_old_media'=> $old !== null,
+            'old_media_id' => $old?->id,
+            'old_path'     => $old?->path,
+        ]);
+
         if ($old) {
+            Log::info('[avatar-upload] Removendo arquivo antigo do S3', ['old_path' => $old->path]);
             $this->removeArchiveByPath($old->path);
             $old->delete();
+            Log::info('[avatar-upload] Arquivo antigo removido do S3 e Media deletado do banco');
         }
 
         return $this->createFromFile($newFile, $folder, $source, $sourceId, $filename);

+ 42 - 1
app/Services/UserService.php

@@ -67,6 +67,15 @@ class UserService
 
             $user = User::with(['client.profileMedia'])->findOrFail(Auth::id());
 
+            Log::info('[avatar-upload] UserService::updateMe iniciado', [
+                'user_id'        => $user->id,
+                'client_id'      => $user->client?->id,
+                'has_avatar_key' => isset($data['avatar']),
+                'avatar_is_file' => isset($data['avatar']) && $data['avatar'] instanceof UploadedFile,
+                'old_media_id'   => $user->client?->profile_media_id,
+                'old_media_path' => $user->client?->profileMedia?->path,
+            ]);
+
             $userFields = array_filter(
                 array_intersect_key($data, array_flip(['name', 'email', 'phone', 'language'])),
                 fn ($v) => $v !== null,
@@ -86,6 +95,15 @@ class UserService
 
             if (isset($data['avatar']) && $data['avatar'] instanceof UploadedFile) {
                 $client = $user->client ?? Client::create(['user_id' => $user->id]);
+
+                Log::info('[avatar-upload] Iniciando replaceFile para avatar do cliente', [
+                    'client_id'    => $client->id,
+                    'folder'       => "client/avatar/{$client->id}",
+                    'has_old_media'=> $client->profileMedia !== null,
+                    'old_media_id' => $client->profileMedia?->id,
+                    'old_media_path'=> $client->profileMedia?->path,
+                ]);
+
                 $media = $this->mediaService->replaceFile(
                     newFile: $data['avatar'],
                     folder: "client/avatar/{$client->id}",
@@ -93,8 +111,26 @@ class UserService
                     sourceId: $client->id,
                     old: $client->profileMedia,
                 );
+
+                Log::info('[avatar-upload] replaceFile concluído — salvando profile_media_id', [
+                    'client_id'      => $client->id,
+                    'new_media_id'   => $media->id,
+                    'new_media_path' => $media->path,
+                ]);
+
                 $client->profile_media_id = $media->id;
                 $client->save();
+
+                Log::info('[avatar-upload] Client salvo com novo profile_media_id', [
+                    'client_id'       => $client->id,
+                    'profile_media_id'=> $client->profile_media_id,
+                ]);
+            } else {
+                Log::warning('[avatar-upload] Avatar NÃO processado no service', [
+                    'isset_avatar'   => isset($data['avatar']),
+                    'is_upload_file' => isset($data['avatar']) ? ($data['avatar'] instanceof UploadedFile) : false,
+                    'data_keys'      => array_keys($data),
+                ]);
             }
 
             $user->load('client');
@@ -115,7 +151,12 @@ class UserService
         } catch (\Exception $e) {
             DB::rollBack();
 
-            Log::error('Erro ao atualizar perfil.', ['error' => $e->getMessage()]);
+            Log::error('[avatar-upload] ERRO em UserService::updateMe', [
+                'error'     => $e->getMessage(),
+                'exception' => get_class($e),
+                'file'      => $e->getFile(),
+                'line'      => $e->getLine(),
+            ]);
 
             throw $e;
         }

+ 18 - 2
app/Traits/RemoveArchiveS3.php

@@ -3,6 +3,7 @@
 namespace App\Traits;
 
 use Exception;
+use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Storage;
 
 trait RemoveArchiveS3
@@ -14,11 +15,26 @@ trait RemoveArchiveS3
      */
     public function removeArchiveByPath(string $path): bool
     {
-        if (! Storage::exists($path)) {
+        $exists = Storage::exists($path);
+
+        Log::info('[avatar-upload] RemoveArchiveS3::removeArchiveByPath', [
+            'path'   => $path,
+            'exists' => $exists,
+        ]);
+
+        if (! $exists) {
+            Log::warning('[avatar-upload] Arquivo antigo NÃO encontrado no S3 para remoção', ['path' => $path]);
             return false;
         }
 
-        if (! Storage::delete($path)) {
+        $deleted = Storage::delete($path);
+
+        Log::info('[avatar-upload] Resultado da remoção do arquivo antigo', [
+            'path'    => $path,
+            'deleted' => $deleted,
+        ]);
+
+        if (! $deleted) {
             throw new Exception('Deletion was not possible');
         }
 

+ 36 - 3
app/Traits/UploadsFile.php

@@ -3,6 +3,7 @@
 namespace App\Traits;
 
 use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Storage;
 use Illuminate\Support\Str;
 
@@ -11,10 +12,42 @@ trait UploadsFile
     public function uploadFile(UploadedFile $file, string $folder, ?string $filename = null): string
     {
         $extension = $file->getClientOriginalExtension();
-        $name = $filename ?? Str::random(20).'.'.$extension;
-        $path = $folder.'/'.$name;
+        $name      = $filename ?? Str::random(20).'.'.$extension;
+        $path      = $folder.'/'.$name;
 
-        Storage::disk('s3')->put($path, file_get_contents($file));
+        Log::info('[avatar-upload] UploadsFile::uploadFile — chamando Storage::disk(s3)->put()', [
+            'path'           => $path,
+            'disk'           => 's3',
+            'file_size'      => $file->getSize(),
+            'file_real_path' => $file->getRealPath(),
+            'content_length' => strlen(file_get_contents($file)),
+        ]);
+
+        $result = Storage::disk('s3')->put($path, file_get_contents($file));
+
+        Log::info('[avatar-upload] UploadsFile::uploadFile — resultado do Storage::put()', [
+            'path'           => $path,
+            'result'         => $result,
+            'result_type'    => gettype($result),
+            'upload_success' => $result !== false,
+        ]);
+
+        if ($result === false) {
+            Log::error('[avatar-upload] FALHA NO UPLOAD S3 — Storage::put() retornou false', [
+                'path'      => $path,
+                'disk'      => 's3',
+                'bucket'    => config('filesystems.disks.s3.bucket'),
+                'region'    => config('filesystems.disks.s3.region'),
+                'endpoint'  => config('filesystems.disks.s3.endpoint'),
+            ]);
+        }
+
+        // Verificar se o arquivo realmente existe no S3 após o upload
+        $existsAfterUpload = Storage::disk('s3')->exists($path);
+        Log::info('[avatar-upload] Verificação pós-upload: arquivo existe no S3?', [
+            'path'   => $path,
+            'exists' => $existsAfterUpload,
+        ]);
 
         return $path;
     }