Files
rkm-conectasus-ci-sandbox/api/app/Services/TransportePaciente/PreAgendamentoTransporteService.php
Antonio Lopes dos Santos afec302c3e
All checks were successful
build-api-image / build (push) Successful in 51s
init commit
2026-08-04 16:52:02 -03:00

577 lines
27 KiB
PHP

<?php
namespace App\Services\TransportePaciente;
use App\Enums\TransportePaciente\Status;
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
use App\Models\Cadastro\SujeitoAtencao\Paciente;
use App\Models\Geral\DiaSemana;
use App\Models\Intranet\Cliente;
use App\Models\TransportePaciente\Acompanhante;
use App\Models\TransportePaciente\Agendar\Agendar;
use App\Models\TransportePaciente\Parametrizacao\Parametrizacao;
use App\Models\TransportePaciente\PreAgendamentoTransporte;
use App\Models\TransportePaciente\Relacao;
use App\Models\TransportePaciente\Veiculo\TipoPassageiro;
use App\Models\TransportePaciente\Agendar\Historico;
use App\Services\Integracao\CnsService;
use App\Services\Service;
use App\Services\TransportePaciente\Agendar\AgendarService;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class PreAgendamentoTransporteService extends Service
{
public static function store()
{
self::validate();
$agendamentos = [];
DB::transaction(function () use (&$agendamentos) {
foreach(request()->agendamentos as $agendamento)
{
$agendar = null;
if($agendamento['acompanhante_1_id'] || $agendamento['nome1']) {
$agendamento['acompanhante_1_id'] = Acompanhante::create([
'usuario_id' => $agendamento['acompanhante_1_id'] ?? null,
'relacao_id' => $agendamento['acompanhante_1_relacao'],
'nome' =>$agendamento['nome1'] ?? null,
'telefone' =>$agendamento['telefone1'] ?? null
])->fresh()->id;
}
if($agendamento['acompanhante_2_id'] || $agendamento['nome2']) {
$agendamento['acompanhante_2_id'] = Acompanhante::create([
'usuario_id' => $agendamento['acompanhante_2_id'] ?? null,
'relacao_id' => $agendamento['acompanhante_2_relacao'],
'nome' => $agendamento['nome2'] ?? null,
'telefone' =>$agendamento['telefone2'] ?? null
])->fresh()->id;
}
$pre_agendamento = PreAgendamentoTransporte::create($agendamento)->fresh();
if($agendamento['agendar']) {
$agendamento['consulta_observacao'] = $agendamento['observacao'] ?? null;
$agendamento['observacao'] = null;
foreach($agendamento as $key => $value) {
request()->merge([$key => $value]);
}
request()->merge(['pre_agendamento_id' => $pre_agendamento->id]);
$agendar = AgendarService::store();
}
$jornadaIdAgendado = $agendar ? $agendar->jornada_id : null;
$horarioSaida = $pre_agendamento->horario_saida ? Carbon::createFromFormat('H:i:s', $pre_agendamento->horario_saida)->format('H:i') : null;
if (is_null($jornadaIdAgendado)) {
array_push($agendamentos, [
'id' => $pre_agendamento->id,
'paciente_id' => $pre_agendamento->paciente_id,
'municipio' => $pre_agendamento->municipio->nome,
'municipio_id' => $pre_agendamento->municipio_id,
'transporte_paciente_destino' => $pre_agendamento->destino->descricao_destino,
'destino_id' => $pre_agendamento->destino_id,
'transporte_paciente_motivo' => $pre_agendamento->motivo->descricao,
'motivo_id' => $pre_agendamento->motivo_id,
'pre_agendamento_data' => $pre_agendamento->data,
'pre_agendamento_horario' => $pre_agendamento->horario,
'acompanhante' => $pre_agendamento->acompanhante,
'ponto_id' => $pre_agendamento->ponto->id,
'observacao' => $pre_agendamento->observacao,
'data_saida' => $pre_agendamento->data_saida,
'horario_saida' => $pre_agendamento->horario_saida,
'veiculo_id' => $pre_agendamento->veiculo_id,
'veiculos' => AgendarService::getVeiculos(true, $pre_agendamento->data_saida, $pre_agendamento->horario_saida),
'agendar_id' => $agendar->id ?? null,
'veiculo_descricao' => $pre_agendamento->veiculo_descricao,
'jornada_id' => $pre_agendamento->jornada_id,
'jornadas' => $pre_agendamento->veiculo_id ? AgendarService::getJornadas($pre_agendamento->veiculo_id, "{$pre_agendamento->data_saida} {$horarioSaida}") : [],
'jornada_descricao' => $pre_agendamento->jornada_descricao,
'tipo_passageiro_id' => $pre_agendamento->tipo_passageiro_id,
'selecionado' => false
]);
}
}
});
return $agendamentos;
}
public static function edit($id)
{
return [
'additionals' => [
'permissoes_atualizacao_cadastro_paciente' => self::getPermissoesAtualizacaoCadastroPaciente(),
],
'form' => self::getFormData($id),
'model' => self::getModelData($id),
'paciente' => self::getPacienteData($id),
'agendamentos' => self::getAgendamentos($id),
'agendados' => self::getAgendados($id),
'items' => []
];
}
public static function destroy($id)
{
DB::transaction(function() use($id) {
Agendar::where('pre_agendamento_id', $id)->update([
'pre_agendamento_id' => null,
'status_id' => 2,
'acompanhante_1_id' => null,
'acompanhante_2_id' => null
]);
$preAgendamento = PreAgendamentoTransporte::find($id);
$preAgendamento->delete();
if($preAgendamento->acompanhante1) {
$preAgendamento->acompanhante1->delete();
}
if($preAgendamento->acompanhante2) {
$preAgendamento->acompanhante2->delete();
}
});
}
public static function destroyAll()
{
foreach(request()->all() as $id) {
self::destroy($id);
}
}
private static function getMunicipios()
{
return DB::table('transporte_paciente_destino as destino')
->select('municipio.id', 'municipio.nome')
->join('intranet.cadastro_municipio as municipio', 'destino.municipio_id', 'municipio.id')
->where('bloqueado', false)
->groupBy('destino.municipio_id')
->get();
}
private static function getFormData()
{
$cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail();
$currentLotacao = self::getCurrentLotacao();
$parametrizacao = Parametrizacao::first();
return [
'municipios' => self::getMunicipios(),
'pontos' => AgendarService::getPontos(),
'destinos' => [],
'veiculos' => [],
'jornadas' => [],
'agendar_transporte_jornada' => $parametrizacao->agendar_transporte_jornada ?? null,
'dados_acompanhante' => $parametrizacao->dados_acompanhante ?? null,
'campo_livre' => $parametrizacao->campo_livre ?? null,
'comprovante_acompanhante' => $parametrizacao->comprovante_acompanhante ?? null,
'veiculo_obrigatorio' => $parametrizacao->veiculo ?? null,
'mensagem_protocolo' => $parametrizacao->mensagem_protocolo ?? null,
'dias_semana' => DiaSemana::get()->map(fn($dia) => [
'id' => $dia->id,
'descricao' => $dia->descricao,
'disabled' => true,
]),
'tipos_passageiro' => TipoPassageiro::get(),
'acompanhante' => [
['value' => 0, 'text' => 'Nenhum'],
['value' => 1, 'text' => '1'],
['value' => 2, 'text' => '2'],
],
'relacoes' => Relacao::get(),
'status' => [
['value' => true, 'text' => 'Agendados'],
['value' => false, 'text' => 'Não agendados'],
],
'cliente' => [
'sistema' => [
'ramo_atividade' => [
'nome' => $cliente->sistema->ramoAtividade->nome ?? null,
],
'nome' => $cliente->sistema->nome ?? null,
'versao' => $cliente->sistema->versao ?? null,
],
'municipio' => [
'estado' => [
'uf' => $cliente->municipio->estado->uf ?? null,
],
'nome' => $cliente->municipio->nome ?? null,
],
'nome' => $cliente->nome ?? null,
'email' => $cliente->email ?? null,
'site' => $cliente->site ?? null,
'logotipo' => $cliente->logotipo ?? null,
],
'usuario' => $currentLotacao->usuario->cidadao->nome,
'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia,
'unidadeTelefone' => MaskUtil::getPhoneMasked($currentLotacao->infraestrutura->telefone)
];
}
private static function getModelData($id)
{
return [
'id' => null,
'paciente_id' => $id,
'motivo' => null,
'horario' => null,
'diasSemana' => [],
'tipo_passageiro_id' => null,
'periodo' => [
'start' => null,
'end' => null,
],
'busca' => [
'start' => null,
'end' => null,
],
'status' => null,
'data_inicial' => null,
'data_final' => null,
'municipio' => null,
'destino_id' => null,
'acompanhante' => 0,
'acompanhante1' => null,
'nome1' => null,
'relacao1' => null,
'acompanhante2' => null,
'nome2' => null,
'relacao2' => null,
'ponto_id' => null,
'observacao' => null,
'hora_saida' => null,
'veiculo_id' => null,
'jornada_id' => null,
'min_date' => Carbon::now()->format('d/m/Y'),
];
}
private static function getPacienteData($id)
{
$paciente = Paciente::find($id);
$responsavel = Lotacao::find($paciente->created_lotacao_id);
return [
'nome' => $paciente->cidadao->nome,
'nome_social' => $paciente->cidadao->nome_social,
'prontuario' => $paciente->prontuario,
'telefones' => $paciente->cidadao->telefones ? join(', ', $paciente->cidadao->telefones->map(fn ($t) => MaskUtil::getPhoneMasked($t->numero))->all()) : null,
'sexo' => $paciente->cidadao->sexo,
'cpf' => $paciente->cidadao->cpf,
'data_nascimento' => $paciente->cidadao->data_nascimento,
'rg' => $paciente->cidadao->carteiraIdentidade->numero ?? null,
'cns' => $paciente->cidadao->cns,
'idade' => $paciente->cidadao->idade,
'classificacao' => $paciente->classificacao->nome,
'unidade_referencia' => $paciente->unidade->nome_fantasia ?? null,
'endereco' => $paciente->cidadao->domicilio->endereco ?? null,
'classificacao' => $paciente->classificacao->descricao,
'responsavel_cadastro' => $responsavel->usuario->cidadao->nome ?? null
];
}
private static function getAgendados($id)
{
return DB::table('transporte_paciente_agendar_transporte')
->join(
'transporte_paciente_motivo_viagem_procedimento',
'transporte_paciente_agendar_transporte.motivo_id',
'transporte_paciente_motivo_viagem_procedimento.id'
)
->leftJoin(
'intranet.cadastro_municipio',
'transporte_paciente_agendar_transporte.municipio_id',
'intranet.cadastro_municipio.id'
)
->leftJoin(
'transporte_paciente_destino',
'transporte_paciente_agendar_transporte.destino_id',
'transporte_paciente_destino.id'
)
->leftJoin(
'transporte_paciente_veiculo',
'transporte_paciente_agendar_transporte.veiculo_id',
'transporte_paciente_veiculo.id'
)
->leftJoin(
'transporte_paciente_jornada',
'transporte_paciente_agendar_transporte.jornada_id',
'transporte_paciente_jornada.id'
)
->select(
'transporte_paciente_agendar_transporte.data',
'transporte_paciente_agendar_transporte.motivo_id',
'transporte_paciente_motivo_viagem_procedimento.descricao as motivo_descricao',
'transporte_paciente_agendar_transporte.veiculo_id',
DB::raw("CONCAT(transporte_paciente_veiculo.numero_placa, ' - ', transporte_paciente_veiculo.descricao_modelo) as veiculo_descricao"),
'cadastro_municipio.nome as municipio',
'transporte_paciente_destino.descricao_destino as destino',
DB::raw("DATE_FORMAT(transporte_paciente_agendar_transporte.horario, '%H:%i') as horario"),
'transporte_paciente_agendar_transporte.observacao',
DB::raw("CONCAT(
DATE_FORMAT(transporte_paciente_jornada.data_inicial, '%d/%m/%Y %H:%i'),
' - ',
DATE_FORMAT(transporte_paciente_jornada.data_final, '%d/%m/%Y %H:%i'),
' - ',
transporte_paciente_jornada.id
) as jornada_descricao")
)
->where('transporte_paciente_agendar_transporte.paciente_id', $id)
->where('transporte_paciente_agendar_transporte.data', '>=', Carbon::now()->format('Y-m-d'))
->whereNull('transporte_paciente_agendar_transporte.jornada_id')
->whereNotIn('status_id', [Status::CANCELADO, Status::TRANSPORTADO])
->get();
}
private static function getAgendamentos($id)
{
$agendamentos = DB::table('transporte_paciente_pre_agendamento_transporte as agendamento')
->select(
'agendamento.id',
'agendar.status_id',
'agendamento.paciente_id',
'municipio.nome as municipio',
'municipio.id as municipio_id',
'destino.descricao_destino as transporte_paciente_destino',
'destino.id as destino_id',
'motivo.descricao as transporte_paciente_motivo',
'motivo.id as motivo_id',
'agendamento.data as pre_agendamento_data',
'agendamento.horario as pre_agendamento_horario',
'agendamento.acompanhante',
'acompanhante1.usuario_id as acompanhante1',
'acompanhante1.relacao_id as relacao1',
'acompanhante2.usuario_id as acompanhante2',
'acompanhante2.relacao_id as relacao2',
'agendamento.ponto_id',
'agendamento.observacao',
'agendamento.data_saida',
'agendamento.horario_saida',
'agendamento.tipo_passageiro_id',
'agendamento.veiculo_id',
'agendar.id as agendar_id',
DB::raw("CONCAT(veiculo.numero_placa, ' - ', veiculo.descricao_modelo) as veiculo_descricao"),
'agendamento.jornada_id',
DB::raw("CONCAT(DATE_FORMAT(jornada.data_inicial, '%d/%m/%Y %H:%i'), ' - ', DATE_FORMAT(jornada.data_final, '%d/%m/%Y %H:%i'), ' - ', jornada.id) as jornada_descricao"),
)
->leftJoin('intranet.cadastro_municipio as municipio', 'agendamento.municipio_id', 'municipio.id')
->leftJoin('transporte_paciente_destino as destino', 'agendamento.destino_id', 'destino.id')
->leftJoin('transporte_paciente_motivo_viagem_procedimento as motivo', 'agendamento.motivo_id', 'motivo.id')
->leftJoin('transporte_paciente_veiculo as veiculo', 'agendamento.veiculo_id', 'veiculo.id')
->leftJoin('transporte_paciente_jornada as jornada', 'agendamento.jornada_id', 'jornada.id')
->leftJoin('transporte_paciente_acompanhante as acompanhante1','acompanhante1.id', 'agendamento.acompanhante_1_id')
->leftJoin('transporte_paciente_acompanhante as acompanhante2','acompanhante2.id', 'agendamento.acompanhante_2_id')
->leftJoin('transporte_paciente_agendar_transporte as agendar', 'agendar.pre_agendamento_id', 'agendamento.id')
->where('agendamento.paciente_id', $id)
->where('agendamento.data', '>=', Carbon::now()->format('Y-m-d'))
->whereNull('agendar.jornada_id')
->when(request()->query('status'), function ($query) {
if (request()->query('status') == 'true') {
$query->whereNotNull('agendar.id');
} else {
$query->whereNull('agendar.id');
}
})
->where(function ($query) {
$query->whereNotIn('agendar.status_id', [Status::CANCELADO, Status::TRANSPORTADO])
->orWhereNull('agendar.status_id');
})
->orderBy('agendamento.data')
->orderBy('agendamento.horario')
->get();
$agendamentos->transform(function ($agendamento) {
if (!is_null($agendamento->horario_saida)) {
$preAgendado = true;
$data_saida = $agendamento->data_saida;
$horario_saida = $agendamento->horario_saida;
$agendamento->veiculos = AgendarService::getVeiculos($preAgendado, $data_saida, $horario_saida);
if (!is_null($agendamento->veiculo_id)) {
$data_saida = $agendamento->data_saida;
$horarioSaida = Carbon::createFromFormat('H:i:s', $agendamento->horario_saida)->format('H:i');
$idVeiculo = $agendamento->veiculo_id;
$agendamento->jornadas = AgendarService::getJornadas($idVeiculo, "{$data_saida} {$horarioSaida}");
}
}
return $agendamento;
});
return $agendamentos;
}
private static function validate()
{
$validations = [
'agendamentos.*.paciente_id' => [
'required',
'exists:cadastro_paciente,id'
],
'agendamentos.*.motivo_id' => [
'required',
'exists:transporte_paciente_motivo_viagem_procedimento,id'
],
'agendamentos.*.horario' => [
'required',
],
'agendamentos.*.data' => [
'required',
'date',
],
'agendamentos.*.municipio_id' => [
'required',
'exists:intranet.cadastro_municipio,id'
],
'agendamentos.*.destino_id' => [
'required',
'exists:transporte_paciente_destino,id'
],
'agendamentos.*.acompanhante' => [
'required',
'integer',
],
'agendamentos.*.ponto_id' => [
'required',
'exists:transporte_paciente_ponto,id'
],
'agendamentos.*.observacao' => [
'nullable',
'string',
'max:200',
],
];
$messages = [
'agendamentos.*.paciente_id.required' => 'O paciente selecionado é inválido.',
'agendamentos.*.paciente_id.exists' => 'O paciente selecionado é inválido',
'agendamentos.*.motivo_id.required' => 'O campo motivo é obrigatório.',
'agendamentos.*.motivo_id.exists' => 'O campo motivo selecionado é inválido.',
'agendamentos.*.horario.required' => 'O campo horario é obrigatório.',
'agendamentos.*.data.required' => 'O campo data é obrigatório.',
'agendamentos.*.data.date' => 'O campo data não é válido.',
'agendamentos.*.municipio_id.required' =>'O campo municipio é obrigatório.',
'agendamentos.*.municipio_id.exists' =>'O campo municipio selecionado é inválido.',
'agendamentos.*.destino_id.required' => 'O campo destino é obrigatório.',
'agendamentos.*.destino_id.exists' => 'O campo destino selecionado é inválido.',
'agendamentos.*.acompanhante.required' => 'O campo acompanhante é obrigatório.',
'agendamentos.*.ponto_id.required' => 'O campo ponto referencia é obrigatório.',
'agendamentos.*.ponto_id.exists' => 'O campo ponto referencia selecionado é inválido.',
'agendamentos.*.observacao.max' => 'O campo observação não pode ser superior a :max caracteres.',
'agendamentos.*.hora_saida.required' => 'O campo hora saida é obrigatório.',
'agendamentos.*.veiculo_id.required' => 'O campo veiculo é obrigatório.',
'agendamentos.*.veiculo_id.exists' => 'O campo veiculo selecionado é inválido.',
'agendamentos.*.jornada_id.required' => 'O campo jornada é obrigatório.',
'agendamentos.*.jornada_id.exists' => 'O campo jornada selecionado é inválido.',
'agendamentos.*.horario_saida.required' => 'O campo hora saida é obrigatório.',
'agendamentos.*.veiculo_id.required' => 'O campo veiculo é obrigatório.',
'agendamentos.*.veiculo_id.exists' => 'O campo veiculo selecionado é inválido.',
'agendamentos.*.jornada_id.required' => 'O campo jornada é obrigatório.',
'agendamentos.*.jornada_id.exists' => 'O campo jornada selecionado é inválido.',
];
return request()->validate($validations, $messages);
}
public static function search()
{
return DB::table('transporte_paciente_pre_agendamento_transporte as agendamento')
->select(
'agendamento.id',
'agendar.status_id',
'agendamento.paciente_id',
'municipio.nome as municipio',
'municipio.id as municipio_id',
'destino.descricao_destino as transporte_paciente_destino',
'destino.id as destino_id',
'motivo.descricao as transporte_paciente_motivo',
'motivo.id as motivo_id',
'agendamento.data as pre_agendamento_data',
'agendamento.horario as pre_agendamento_horario',
'agendamento.acompanhante',
'acompanhante1.usuario_id as acompanhante1',
'acompanhante1.relacao_id as relacao1',
'acompanhante2.usuario_id as acompanhante2',
'acompanhante2.relacao_id as relacao2',
'agendamento.ponto_id',
'agendamento.observacao',
'agendamento.data_saida',
'agendamento.horario_saida',
'agendamento.tipo_passageiro_id',
'agendamento.veiculo_id',
'agendar.id as agendar_id',
DB::raw("CONCAT(veiculo.numero_placa, ' - ', veiculo.descricao_modelo) as veiculo_descricao"),
'agendamento.jornada_id',
DB::raw("CONCAT(DATE_FORMAT(jornada.data_inicial, '%d/%m/%Y %H:%i'), ' - ', DATE_FORMAT(jornada.data_final, '%d/%m/%Y %H:%i'), ' - ', jornada.id) as jornada_descricao"),
)
->leftJoin('intranet.cadastro_municipio as municipio', 'agendamento.municipio_id', 'municipio.id')
->leftJoin('transporte_paciente_destino as destino', 'agendamento.destino_id', 'destino.id')
->leftJoin('transporte_paciente_motivo_viagem_procedimento as motivo', 'agendamento.motivo_id', 'motivo.id')
->leftJoin('transporte_paciente_veiculo as veiculo', 'agendamento.veiculo_id', 'veiculo.id')
->leftJoin('transporte_paciente_jornada as jornada', 'agendamento.jornada_id', 'jornada.id')
->leftJoin('transporte_paciente_acompanhante as acompanhante1','acompanhante1.id', 'agendamento.acompanhante_1_id')
->leftJoin('transporte_paciente_acompanhante as acompanhante2','acompanhante2.id', 'agendamento.acompanhante_2_id')
->leftJoin('transporte_paciente_agendar_transporte as agendar', 'agendar.pre_agendamento_id', 'agendamento.id')
->where('agendamento.paciente_id', request()->paciente_id)
->where('agendamento.data', '>=', request()->data_inicial)
->where('agendamento.data', '<=', request()->data_final)
->whereNull('agendar.jornada_id')
->when(request()->query('status'), function ($query) {
if (request()->query('status') == 'true') {
$query->whereNotNull('agendar.id');
} else {
$query->whereNull('agendar.id');
}
})
->where(function ($query) {
$query->whereNotIn('agendar.status_id', [Status::CANCELADO])
->orWhereNull('agendar.status_id');
})
->orderBy('agendamento.data')
->orderBy('agendamento.horario')
->get();
}
public static function update()
{
foreach(request()->all() as $value){
$pre_agendamento = PreAgendamentoTransporte::find($value['id']);
$pre_agendamento->horario_saida = $value['horario_saida'];
$pre_agendamento->data_saida = $value['data_saida'];
$pre_agendamento->save();
}
}
private static function getPermissoesAtualizacaoCadastroPaciente()
{
$parametrizacao = CnsService::getParametrizacao();
if (!is_null($parametrizacao)) {
$lotacao = self::getCurrentLotacao();
return DB::table('cadastro_parametrizacao_permissao_usuario')
->select([
'municipe',
'provisorio',
'outro_municipio',
])
->where('infraestrutura_id', $lotacao->infraestrutura_id)
->where('usuario_id', $lotacao->usuario_id)
->get()
->first();
}
return null;
}
}