Sfoglia il codice sorgente

ajustes gerais antes da apresentacao

Gustavo Zanatta 3 settimane fa
parent
commit
f25baad81c

+ 18 - 8
app/Exports/ContatosAssociadosExport.php

@@ -16,16 +16,26 @@ use Illuminate\Support\Collection;
 
 class ContatosAssociadosExport implements FromCollection, WithHeadings, WithStyles, WithColumnWidths, WithTitle
 {
+    public function __construct(private readonly ?string $search = null) {}
+
     public function collection(): Collection
     {
-        return User::where('type', UserTypeEnum::ASSOCIADO)
-            ->orderBy('name', 'asc')
-            ->get()
-            ->map(fn($u) => [
-                $u->name,
-                $u->phone ?? '',
-                $u->email ?? '',
-            ]);
+        $query = User::where('type', UserTypeEnum::ASSOCIADO)->orderBy('name', 'asc');
+
+        if ($this->search) {
+            $term = '%' . mb_strtolower($this->search) . '%';
+            $query->where(function ($q) use ($term) {
+                $q->whereRaw('UNACCENT(LOWER(name)) LIKE UNACCENT(?)', [$term])
+                  ->orWhereRaw('UNACCENT(LOWER(email)) LIKE UNACCENT(?)', [$term])
+                  ->orWhereRaw('UNACCENT(LOWER(COALESCE(phone, \'\'))) LIKE UNACCENT(?)', [$term]);
+            });
+        }
+
+        return $query->get()->map(fn($u) => [
+            $u->name,
+            $u->phone ?? '',
+            $u->email ?? '',
+        ]);
     }
 
     public function headings(): array

+ 19 - 8
app/Exports/ExclusoesMesExport.php

@@ -17,21 +17,32 @@ use Illuminate\Support\Collection;
 
 class ExclusoesMesExport implements FromCollection, WithHeadings, WithStyles, WithColumnWidths, WithTitle
 {
+    public function __construct(private readonly ?string $search = null) {}
+
     public function collection(): Collection
     {
         $now = Carbon::now();
 
-        return User::where('type', UserTypeEnum::ASSOCIADO)
+        $query = User::where('type', UserTypeEnum::ASSOCIADO)
             ->whereNotNull('excluded_at')
             ->whereYear('excluded_at', $now->year)
             ->whereMonth('excluded_at', $now->month)
-            ->orderBy('excluded_at', 'desc')
-            ->get()
-            ->map(fn($u) => [
-                $u->name,
-                $u->cpf ?? '',
-                $u->excluded_at?->format('d/m/Y') ?? '',
-            ]);
+            ->orderBy('excluded_at', 'desc');
+
+        if ($this->search) {
+            $term = '%' . mb_strtolower($this->search) . '%';
+            $query->where(function ($q) use ($term) {
+                $q->whereRaw('UNACCENT(LOWER(name)) LIKE UNACCENT(?)', [$term])
+                  ->orWhereRaw('UNACCENT(LOWER(cpf)) LIKE UNACCENT(?)', [$term])
+                  ->orWhereRaw("TO_CHAR(excluded_at, 'DD/MM/YYYY') LIKE ?", [$term]);
+            });
+        }
+
+        return $query->get()->map(fn($u) => [
+            $u->name,
+            $u->cpf ?? '',
+            $u->excluded_at?->format('d/m/Y') ?? '',
+        ]);
     }
 
     public function headings(): array

+ 19 - 8
app/Exports/NovoAssociadosExport.php

@@ -17,20 +17,31 @@ use Illuminate\Support\Collection;
 
 class NovoAssociadosExport implements FromCollection, WithHeadings, WithStyles, WithColumnWidths, WithTitle
 {
+    public function __construct(private readonly ?string $search = null) {}
+
     public function collection(): Collection
     {
         $now = Carbon::now();
 
-        return User::where('type', UserTypeEnum::ASSOCIADO)
+        $query = User::where('type', UserTypeEnum::ASSOCIADO)
             ->whereYear('created_at', $now->year)
             ->whereMonth('created_at', $now->month)
-            ->orderBy('created_at', 'desc')
-            ->get()
-            ->map(fn($u) => [
-                $u->name,
-                $u->cpf ?? '',
-                $u->created_at?->format('d/m/Y') ?? '',
-            ]);
+            ->orderBy('created_at', 'desc');
+
+        if ($this->search) {
+            $term = '%' . mb_strtolower($this->search) . '%';
+            $query->where(function ($q) use ($term) {
+                $q->whereRaw('UNACCENT(LOWER(name)) LIKE UNACCENT(?)', [$term])
+                  ->orWhereRaw('UNACCENT(LOWER(cpf)) LIKE UNACCENT(?)', [$term])
+                  ->orWhereRaw("TO_CHAR(created_at, 'DD/MM/YYYY') LIKE ?", [$term]);
+            });
+        }
+
+        return $query->get()->map(fn($u) => [
+            $u->name,
+            $u->cpf ?? '',
+            $u->created_at?->format('d/m/Y') ?? '',
+        ]);
     }
 
     public function headings(): array

+ 14 - 0
app/Http/Controllers/PartnerAgreementController.php

@@ -44,6 +44,20 @@ class PartnerAgreementController extends Controller
         ]);
     }
 
+    public function indexExpiring(Request $request): JsonResponse
+    {
+        $days    = min((int) $request->get('days', 30), 365);
+        $perPage = min((int) $request->get('per_page', 10), 100);
+        $paginator = $this->service->getExpiringPaginated($days, $perPage);
+
+        return $this->successResponse(payload: [
+            'data'  => PartnerAgreementListResource::collection($paginator->items()),
+            'total' => $paginator->total(),
+            'from'  => $paginator->firstItem() ?? 0,
+            'to'    => $paginator->lastItem() ?? 0,
+        ]);
+    }
+
     public function store(PartnerAgreementRequest $request): JsonResponse
     {
         $item = $this->service->create($request->validated());

+ 6 - 6
app/Http/Controllers/ReportController.php

@@ -86,21 +86,21 @@ class ReportController extends Controller
         ]);
     }
 
-    public function exportNovoAssociados(): BinaryFileResponse
+    public function exportNovoAssociados(Request $request): BinaryFileResponse
     {
         $filename = 'novos_associados_' . now()->format('d-m-Y') . '.xlsx';
-        return Excel::download(new NovoAssociadosExport(), $filename);
+        return Excel::download(new NovoAssociadosExport($request->get('search')), $filename);
     }
 
-    public function exportContatosAssociados(): BinaryFileResponse
+    public function exportContatosAssociados(Request $request): BinaryFileResponse
     {
         $filename = 'contatos_associados_' . now()->format('d-m-Y') . '.xlsx';
-        return Excel::download(new ContatosAssociadosExport(), $filename);
+        return Excel::download(new ContatosAssociadosExport($request->get('search')), $filename);
     }
 
-    public function exportExclusoesMes(): BinaryFileResponse
+    public function exportExclusoesMes(Request $request): BinaryFileResponse
     {
         $filename = 'exclusoes_mes_' . now()->format('d-m-Y') . '.xlsx';
-        return Excel::download(new ExclusoesMesExport(), $filename);
+        return Excel::download(new ExclusoesMesExport($request->get('search')), $filename);
     }
 }

+ 1 - 15
app/Http/Requests/AssociateValidationRequest.php

@@ -14,23 +14,9 @@ class AssociateValidationRequest extends FormRequest
     public function rules(): array
     {
         return [
-
-            'cpf' => [
-                'nullable',
-                'string',
-                'required_without_all:name,registration',
-            ],
-
-            'name' => [
-                'nullable',
-                'string',
-                'required_without_all:cpf,registration',
-            ],
-
-            'registration' => [
+            'search' => [
                 'nullable',
                 'string',
-                'required_without_all:cpf,name',
             ],
 
         ];

+ 7 - 3
app/Http/Requests/PartnerAgreementRequest.php

@@ -5,7 +5,6 @@ namespace App\Http\Requests;
 use App\Enums\PartnerAgreementStatusEnum;
 use App\Models\PartnerAgreement;
 use Illuminate\Foundation\Http\FormRequest;
-use Illuminate\Support\Facades\Log;
 use Illuminate\Validation\Rule;
 
 class PartnerAgreementRequest extends FormRequest
@@ -18,7 +17,9 @@ class PartnerAgreementRequest extends FormRequest
             $cnpjUnique = 'unique:partner_agreements,cnpj,' . $partnerId;
         }
         $rules = [
-            'user_id'             => 'sometimes|nullable|integer|exists:users,id',
+            'user_name'           => 'sometimes|nullable|string|max:255',
+            'user_email'          => 'sometimes|nullable|email|max:255',
+            'user_password'       => 'sometimes|nullable|string|min:6',
             'company_name'        => 'sometimes|string|max:255',
             'cnpj'                => ['sometimes', 'nullable', 'string', 'max:18', $cnpjUnique],
             'category_id'         => 'sometimes|nullable|integer|exists:categories,id',
@@ -41,7 +42,10 @@ class PartnerAgreementRequest extends FormRequest
         ];
 
         if ($this->isMethod('post')) {
-            $rules['company_name'] = 'required|string|max:255';
+            $rules['company_name']   = 'required|string|max:255';
+            $rules['user_name']      = 'required|string|max:255';
+            $rules['user_email']     = 'required|email|max:255|unique:users,email';
+            $rules['user_password']  = 'required|string|min:6';
         }
 
         return $rules;

+ 2 - 0
app/Http/Resources/PartnerAgreementListResource.php

@@ -24,6 +24,8 @@ class PartnerAgreementListResource extends JsonResource
             'logo'                => $this->whenLoaded('logo', fn() => $this->logo ? ['url' => $this->logo->url] : null),
             'discount_percentage' => $this->discount_percentage,
             'contract_end'        => $this->contract_end?->format('Y-m-d'),
+            'status'              => $this->status,
+            'created_at'          => $this->created_at?->format('Y-m-d H:i:s'),
         ];
     }
 }

+ 10 - 23
app/Services/AssociateValidationService.php

@@ -8,33 +8,20 @@ class AssociateValidationService
 {
     public function validate(array $data): ?User
     {
+      $search = $data['search'] ?? null;
         return User::query()
 
-            ->where(function ($query) use ($data) {
-                if (!empty($data['cpf'])) {
-
-                    $query->orWhere(
-                        'cpf',
-                        $data['cpf']
-                    );
-                }
-                if (!empty($data['registration'])) {
-
-                    $query->orWhere(
-                        'registration',
-                        $data['registration']
-                    );
-                }
-                if (!empty($data['name'])) {
-
-                    $query->orWhere(
-                        'name',
-                        'like',
-                        '%' . $data['name'] . '%'
-                    );
+            ->where(function ($query) use ($data, $search) {
+                if (!empty($search)) {
+                    $query->where(function ($query) use ($search) {
+                        $query->where('cpf', $search)
+                            ->orWhere('registration', $search)
+                            ->orWhere('name', $search);
+                    });
                 }
             })
-            
+            ->where('status', 'active')
+            ->where('type', 'associado')
             ->first();
     }
 }

+ 1 - 2
app/Services/DashboardService.php

@@ -27,9 +27,8 @@ class DashboardService
 
   public function getPartnerStats(): array
   {
-    // $partnerAgreementId = Auth::user()->partner_agreement_id;
+    $partnerAgreementId = PartnerAgreement::where('user_id', Auth::id())->value('id');
 
-    $partnerAgreementId = 1;
     return [
       'authorization' => Appointment::where('partner_agreement_id', $partnerAgreementId)
         ->where('status', 'pendente')

+ 26 - 2
app/Services/PartnerAgreementService.php

@@ -2,9 +2,12 @@
 
 namespace App\Services;
 
+use App\Enums\UserTypeEnum;
 use App\Models\PartnerAgreement;
+use App\Models\User;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Pagination\LengthAwarePaginator;
+use Illuminate\Support\Facades\Hash;
 
 class PartnerAgreementService
 {
@@ -42,6 +45,15 @@ class PartnerAgreementService
         return $query->paginate($perPage);
     }
 
+    public function getExpiringPaginated(int $days = 30, int $perPage = 10): LengthAwarePaginator
+    {
+        return PartnerAgreement::with(['category', 'city', 'logo'])
+            ->whereNotNull('contract_end')
+            ->whereBetween('contract_end', [now()->startOfDay(), now()->addDays($days)->endOfDay()])
+            ->orderBy('contract_end')
+            ->paginate($perPage);
+    }
+
     public function findById(int $id): ?PartnerAgreement
     {
         return PartnerAgreement::with(['category', 'city', 'state', 'services', 'logo', 'media', 'user'])->find($id);
@@ -86,8 +98,20 @@ class PartnerAgreementService
 
     public function create(array $data): PartnerAgreement
     {
-        $model = PartnerAgreement::create($data);
-        return $model->fresh(['category', 'logo']);
+        $user = User::create([
+            'name'     => $data['user_name'],
+            'email'    => $data['user_email'],
+            'password' => Hash::make($data['user_password']),
+            'type'     => UserTypeEnum::PARCEIRO,
+        ]);
+
+        $partnerData = collect($data)
+            ->except(['user_name', 'user_email', 'user_password'])
+            ->put('user_id', $user->id)
+            ->all();
+
+        $model = PartnerAgreement::create($partnerData);
+        return $model->fresh(['category', 'logo', 'user']);
     }
 
     public function update(int $id, array $data): ?PartnerAgreement

+ 1 - 1
app/Services/StateService.php

@@ -9,7 +9,7 @@ class StateService
 {
     public function getAll(): Collection
     {
-        return State::orderBy("created_at", "desc")->get();
+        return State::orderBy("name", "asc")->get();
     }
 
     public function findById(int $id): ?State

+ 1 - 1
app/Services/UserService.php

@@ -13,7 +13,7 @@ class UserService
     public function authUser(): ?User
     {
         $user = Auth::user();
-        return $user;
+        return $user?->load(['position', 'sector']);
     }
 
     public function getAll(): Collection

+ 3 - 0
routes/authRoutes/partner_agreement.php

@@ -13,6 +13,7 @@ Route::controller(PartnerAgreementController::class)->prefix('partner-agreement'
     Route::get('/', 'index')->middleware('permission:parceiro.convenio,view');
 
     Route::get('/paginated', 'indexPaginated')->middleware('permission:parceiro.convenio,view');
+    Route::get('/expiring',  'indexExpiring') ->middleware('permission:parceiro.convenio,view');
 
     Route::post('/', 'store')->middleware('permission:parceiro.convenio,add');
 
@@ -31,3 +32,5 @@ Route::controller(PartnerAgreementController::class)->prefix('partner-agreement'
     Route::post('/{id}/media', 'uploadMedia')->middleware('permission:parceiro.convenio,edit');
     Route::delete('/{id}/media/{mediaId}', 'deleteMedia')->middleware('permission:parceiro.convenio,edit');
 });
+
+Route::get('associado-partner-agreement', [PartnerAgreementController::class, 'index'])->middleware('permission:associado.convenio,view');