Commit cec70616 authored by Alfonso Rafael Solis Rangel's avatar Alfonso Rafael Solis Rangel
Browse files

Merge branch 'contactos' into 'main'

Contactos

See merge request !17
parents af61fe26 a4f0e167
Loading
Loading
Loading
Loading
+338 −0
Original line number Diff line number Diff line
<?php

namespace App\Http\Controllers;

use App\Models\Caracteristicas;
use App\Models\cargos;
use App\Models\Contacto;
use App\Models\CorreoContactos;
use App\Models\Profesion;
use App\Models\Subgrupo;
use App\Models\Telefono;
use App\Models\RedesSociales;   

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ContactoController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $contactos = Contacto::get();
        return view('adminGen.contactos.index', compact('contactos'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //TODO Instituciones pendientes
        $conyuges = Contacto::get();
        $profesiones = Profesion::get();
        $cargos = cargos::get();
        $caracteristicas = Caracteristicas::get();
        $subgrupos = Subgrupo::get();
        return view('adminGen.contactos.create', compact('conyuges', 'profesiones', 'cargos', 'caracteristicas', 'subgrupos'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'foto_perfil' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
            'nombre' => 'required|max:255|string',
        ]);

        $telefonosData = $request->only(['prefijo', 'lada', 'numero', 'tipo', 'estatus', 'ext', 'id_radio', 'observaciones']);
        $telefonosData = array_map(function ($item) {
            return array_map(function ($value) {
                return ($value === "null") ? null : $value;
            }, $item);
        }, $telefonosData);

        $redesSocialesData = $request->only(['red_social', 'tipo_red_social']);
        $redesSocialesData = array_map(function ($item) {
            return array_map(function ($value) {
                return ($value === "null") ? null : $value;
            }, $item);
        }, $redesSocialesData);

        // Transformar valores '0' y "null" en null en los campos de correos electrónicos
        $correosData = $request->only(['correo_electronico', 'tipo_correo_electronico']);
        $correosData = array_map(function ($item) {
            return array_map(function ($value) {
                return ($value === '0' || $value === "null") ? null : $value;
            }, $item);
        }, $correosData);

        DB::beginTransaction();

        try{
            $path_file = $this->storeProfilePicture($request);
            $fieldsToCheck = [
                'conyuge_id',
                'profesion_id',
                'cargo_id',
                'caracteristica_id',
                'subgrupo_id',
                'mes_cump',
                'dia_cump',
                //institucion_id
            ];
            $requestData = $request->all();
            foreach ($fieldsToCheck as $field) {
                if (isset($requestData[$field]) && $requestData[$field] === "null") {
                    unset($requestData[$field]);
                }
            }

            $request->replace($requestData);

            $data = $request->all();

            if ($path_file) {
                $data['foto_perfil'] = 'storage/' . $path_file;
            }else{
                $data['foto_perfil'] = 'assets/images/profile-icon.webp';
            }

            if($request->finado === 'on') $data['finado'] = true;

            $contacto = Contacto::create($data);
            // Manejar los datos de teléfonos
            $telefonosGuardados = $this->storeTelefonos($contacto->id, $telefonosData);

             // Manejar los datos de redes sociales
             $redesSocialesGuardadas = $this->storeRedesSociales($contacto->id, $redesSocialesData);

            // Manejar los datos de correos electrónicos
            $correosGuardados = $this->storeCorreos($contacto->id, $correosData);

            // Si había datos de teléfonos y no se guardaron, lanzar excepción
            if ($telefonosGuardados === false && $this->telefonoDataPresent($telefonosData)) {
                throw new \Exception('Error al guardar los teléfonos');
            }

            // Si había datos de redes sociales y no se guardaron, lanzar excepción
            if ($redesSocialesGuardadas === false && $this->redSocialDataPresent($redesSocialesData)) {
                throw new \Exception('Error al guardar las redes sociales');
            }

            if ($correosGuardados === false && $this->correoDataPresent($correosData)) {
                throw new \Exception('Error al guardar los correos electrónicos');
            }

            DB::commit();
            return redirect()->route('contacto.get')->with('success', 'Contacto guardado correctamente');
        }catch (\Exception $e){
            DB::rollBack();
            return redirect()->route('contacto.create')->withErrors('Hubo un problema al crear el contacto:' . $e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Contacto $contacto)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Contacto $contacto)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Contacto $contacto)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Contacto $contacto)
    {
        //
    }

    /**
     * Save profile picture in laravel project
     */
    private function storeProfilePicture(Request $request)
    {
        if ($request->hasFile('foto_perfil')) {
            // Obtener el archivo de la solicitud
            $file = $request->file('foto_perfil');

            // Generar un UUID de versión 4
            $uuid = Str::uuid()->toString();

            // Obtener la extensión del archivo
            $extension = $file->getClientOriginalExtension();

            // Crear el nuevo nombre de archivo
            $filename = $uuid . '.' . $extension;

            // Almacenar el archivo en el directorio storage/app/public/fotos_perfil
            $path = $file->storeAs('public/fotos_perfil', $filename);

            // Retornar la ruta del archivo sin el prefijo 'public/'
            return str_replace('public/', '', $path);
        }

        // Retornar null si no hay archivo
        return null;
    }

    private function storeTelefonos($contactoId, $telefonosData)
    {
        $telefonos = [];

        foreach ($telefonosData['numero'] as $index => $numero) {
            // Verificar si todos los campos del teléfono están vacíos (null o "null")
            $isEmpty = true;
            foreach ($telefonosData as $key => $values) {
                if (!is_null($values[$index]) && $values[$index] !== "null") {
                    $isEmpty = false;
                    break;
                }
            }

            if (!$isEmpty) {
                $telefonos[] = [
                    'contacto_id' => $contactoId,
                    'prefijo' => $telefonosData['prefijo'][$index],
                    'lada' => $telefonosData['lada'][$index],
                    'numero' => $numero,
                    'tipo' => $telefonosData['tipo'][$index],
                    'estatus' => $telefonosData['estatus'][$index],
                    'ext' => $telefonosData['ext'][$index],
                    'id_radio' => $telefonosData['id_radio'][$index],
                    'observaciones' => $telefonosData['observaciones'][$index],
                ];
            }
        }

        if (!empty($telefonos)) {
            Telefono::insert($telefonos);
            return true;
        }

        return false;
    }

    private function telefonoDataPresent($telefonosData)
    {
        foreach ($telefonosData['numero'] as $index => $numero) {
            foreach ($telefonosData as $key => $values) {
                if (!is_null($values[$index]) && $values[$index] !== "null") {
                    return true;
                }
            }
        }

        return false;
    }

    private function storeRedesSociales($contactoId, $redesSocialesData)
    {
        $redesSociales = [];

        foreach ($redesSocialesData['red_social'] as $index => $redSocial) {
            // Verificar si todos los campos de la red social están vacíos (null o "null")
            $isEmpty = true;
            foreach ($redesSocialesData as $key => $values) {
                if (!is_null($values[$index]) && $values[$index] !== "null") {
                    $isEmpty = false;
                    break;
                }
            }

            if (!$isEmpty) {
                $redesSociales[] = [
                    'contacto_id' => $contactoId,
                    'red_social' => $redSocial,
                    'tipo_red_social' => $redesSocialesData['tipo_red_social'][$index],
                ];
            }
        }

        if (!empty($redesSociales)) {
            RedesSociales::insert($redesSociales);
            return true;
        }

        return false;
    }

    private function redSocialDataPresent($redesSocialesData)
    {
        foreach ($redesSocialesData['red_social'] as $index => $redSocial) {
            foreach ($redesSocialesData as $key => $values) {
                if (!is_null($values[$index]) && $values[$index] !== "null") {
                    return true;
                }
            }
        }

        return false;
    }

    private function storeCorreos($contactoId, $correosData)
    {
        $correos = [];

        foreach ($correosData['correo_electronico'] as $index => $correo) {
            // Verificar si todos los campos del correo están vacíos (null o "null")
            $isEmpty = true;
            foreach ($correosData as $key => $values) {
                if (!is_null($values[$index]) && $values[$index] !== "null") {
                    $isEmpty = false;
                    break;
                }
            }

            if (!$isEmpty) {
                $correos[] = [
                    'contacto_id' => $contactoId,
                    'correo_electronico' => $correo,
                    'tipo_correo_electronico' => $correosData['tipo_correo_electronico'][$index],
                ];
            }
        }

        if (!empty($correos)) {
            CorreoContactos::insert($correos);
            return true;
        }

        return false;
    }

    private function correoDataPresent($correosData)
    {
        foreach ($correosData['correo_electronico'] as $index => $redSocial) {
            foreach ($correosData as $key => $values) {
                if (!is_null($values[$index]) && $values[$index] !== "null") {
                    return true;
                }
            }
        }

        return false;
    }
}
+65 −0
Original line number Diff line number Diff line
<?php

namespace App\Http\Controllers;

use App\Models\CorreoContactos;
use Illuminate\Http\Request;

class CorreoContactosController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(CorreoContactos $correoContactos)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(CorreoContactos $correoContactos)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, CorreoContactos $correoContactos)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(CorreoContactos $correoContactos)
    {
        //
    }
}
+65 −0
Original line number Diff line number Diff line
<?php

namespace App\Http\Controllers;

use App\Models\RedesSociales;
use Illuminate\Http\Request;

class RedesSocialesController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(RedesSociales $redesSociales)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(RedesSociales $redesSociales)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, RedesSociales $redesSociales)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(RedesSociales $redesSociales)
    {
        //
    }
}
+65 −0
Original line number Diff line number Diff line
<?php

namespace App\Http\Controllers;

use App\Models\Telefono;
use Illuminate\Http\Request;

class TelefonoController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(Telefono $telefono)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Telefono $telefono)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Telefono $telefono)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Telefono $telefono)
    {
        //
    }
}
+42 −0
Original line number Diff line number Diff line
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contacto extends Model
{
    use HasFactory;

    //TODO Agregar la relacion hacia la tabla instituciones cuando Alejandro la tenga terminada.

    protected $fillable = [
        'nombre',
        'ap_paterno',
        'ap_materno',
        'cargo_desc',
        'mes_cump',
        'dia_cump',
        'domicilio_oficial',
        'codigo_postal',
        'localidad_oficial',
        'municipio_oficial',
        'estado',
        'pais',
        'domicilio_par',
        'codigo_postal_par',
        'localidad_par',
        'municipio_par',
        'estado_par',
        'pais_par',
        'finado',
        'foto_perfil',
        'conyuge_id',
        'profesion_id',
        'cargo_id',
        'caracteristica_id',
        //'institucion_id',
        'subgrupo_id',
    ];
}
Loading