<?php
namespace EADPlataforma\Controller\Api\v1;
use OpenApi\Annotations as OA;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use EADPlataforma\Controller\Api\AbstractApiController;
use EADPlataforma\Entity\User;
use EADPlataforma\Entity\UserCustomField;
use EADPlataforma\Entity\UserProfile;
use EADPlataforma\Entity\City;
use EADPlataforma\Entity\State;
use EADPlataforma\Entity\Country;
use EADPlataforma\Entity\Session;
use EADPlataforma\DataTransferObject\UserDTO;
use EADPlataforma\Enum\TrashEnum;
use EADPlataforma\Enum\UserEnum;
use EADPlataforma\Enum\UserLogEnum;
use EADPlataforma\Enum\UserCustomFieldEnum;
use EADPlataforma\Enum\UserPermissionEnum;
use EADPlataforma\Enum\ErrorEnum;
class UserApiController extends AbstractApiController {
public function getEntityClass(){
return User::class;
}
/**
* Listagem dos usuários do EAD.
*
* @Route("/api/1/student", methods={"GET"})
* @OA\Response(
* response=200,
* description="Retorna os cursos do EAD.",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="aluno_id", type="integer", example=12, description="Id do aluno cadastrado no EAD."),
* @OA\Property(property="nome", type="string", example="Exemplo", description="Nome do aluno cadastrado no EAD."),
* @OA\Property(property="email", type="string", example="email@email.com", description="E-mail do aluno cadastrado no EAD."),
* @OA\Property(property="username", type="string", example="UserName", description="Apelido do aluno no EAD."),
* @OA\Property(property="tipo", type="integer", example=1, description="Tipo do usuário (1-Aluno / 2-Tutor / 3-Professor(a) / 4-Administrador)."),
* @OA\Property(property="data_cadastro", type="date time", example="2019-01-01 09:00:00", description="Data e hora de cadastro do usuário."),
* @OA\Property(property="status", type="integer", example=1, description="Status atual da conta (0-Aguardando confirmação / 1-Confirmado / 2-Bloqueado)."),
* @OA\Property(property="cpf", type="datetime", example="2020-01-01 00:00:01", description="CPF do aluno."),
* @OA\Property(property="profissao", example="SP", type="string"),
* @OA\Property(property="biografia", type="string"),
* @OA\Property(property="curriculum", type="string"),
* @OA\Property(property="personalizado", type="string", description="Informações adicionais."),
* @OA\Property(property="anotacoes", type="string", description="Informações adicionais."),
* @OA\Property(property="nascimento", type="string", example="500", description="Data de nascimento."),
* @OA\Property(property="cidade", type="string"),
* @OA\Property(property="uf", type="string", description="Estado."),
* @OA\Property(property="telefone", type="string"),
* @OA\Property(property="cep", type="string"),
* @OA\Property(property="endereco", type="string"),
* @OA\Property(property="numero", type="string"),
* @OA\Property(property="complemento", type="string"),
* @OA\Property(property="bairro", type="string"),
* @OA\Property(property="site", type="string", description="Endereço do site de um usuário."),
* @OA\Property(property="twitter", type="string"),
* @OA\Property(property="facebook", type="string"),
* @OA\Property(property="linkedin", type="string"),
* @OA\Property(property="youtube", type="string"),
* @OA\Property(property="instagram", type="string"),
* @OA\Property(property="tiktok", type="string"),
* @OA\Property(property="ultimo_acesso", type="date time", example="2019-01-01 09:00:00", description="Data e hora do último acesso do usuário."),
* @OA\Property(property="foto", type="string", example="seudominio/upload/profiles/foto.png", description="Imagem do perfil."),
* @OA\Property(property="campos_personalizados", type="string", description="Campos adicionais criados na plataforma pelo admin.")
* )
* )
*
* @OA\Response(
* response=204,
* description="No content"
* )
*
* @OA\Response(
* response=401,
* description="Token not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=401, description="Token not found"),
* @OA\Property(property="message", type="string", example="Token not found")
* )
* )
*
* @OA\Response(
* response=429,
* description="Too many requests",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=429, description="Too many requests"),
* @OA\Property(property="message", type="string", example="Too many requests")
* )
* )
*
* @OA\Response(
* response=500,
* description="Internal Server Error",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=500, description="Internal Server Error"),
* @OA\Property(property="message", type="string", example="Internal Server Error")
* )
* )
*
* @OA\Parameter(
* name="id",
* in="query",
* description="Usuário Id",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="email",
* in="query",
* description="E-mail",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="status",
* in="query",
* description="Status (0-Aguardando confirmação / 1-Confirmado / 2-Bloqueado)",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="data_inicio",
* in="query",
* description="Data inicial data de cadastro (yyyy-mm-dd)",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="data_fim",
* in="query",
* description="Data final data de cadastro (yyyy-mm-dd)",
* @OA\Schema(type="string")
* )
*
* @OA\Parameter(
* name="paginate",
* in="query",
* description="Informaçoes para paginação",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="limit",
* in="query",
* description="Número máximo de dados retornados por página, valor padrão 1000",
* @OA\Schema(type="integer")
* )
*
* @OA\Parameter(
* name="offset",
* in="query",
* description="Indica o início da leitura, caso não informado valor padrão será 0",
* @OA\Schema(type="integer")
* )
*
* @OA\Tag(name="Usuários")
* @Security(name="Bearer")
*
*/
public function getStudent(Request $request)
{
$this->requestUtil->setRequest($request)->setData();
$columns = [
"u.id AS aluno_id",
"u.name AS nome",
"u.email",
"up.name AS username",
"u.type AS tipo",
"DATE_FORMAT(u.dateRegister, '%Y-%m-%d %H:%i:%s') AS data_cadastro",
"u.status",
"u.document AS cpf",
"u.occupation AS profissao",
"u.biography AS biografia",
"u.resume AS curriculum",
"u.custom AS personalizado",
"u.notes AS anotacoes",
"DATE_FORMAT(u.birthDate, '%Y-%m-%d') AS nascimento",
"ci.name cidade",
"st.name AS uf",
"u.phone AS telefone",
"u.zipCode AS cep",
"u.address AS endereco",
"u.addressNumber AS numero",
"u.addressComplement AS complemento",
"u.addressNeighborhood AS bairro",
"u.website AS site",
"u.twitter",
"u.facebook",
"u.linkedin",
"u.youtube",
"u.instagram",
"u.tiktok",
"DATE_FORMAT(u.dateLastAccess, '%Y-%m-%d %H:%i:%s') AS ultimo_acesso",
"u.photo AS foto",
"u.customField AS campos_personalizados",
"'' AS campos_personalizados_decoded"
];
$profileClass = UserProfile::class;
$cityClass = City::class;
$stateClass = State::class;
$countryClass = Country::class;
$filter = [];
$joins = [
"{$profileClass} AS up" => "up.id = u.userProfile",
"{$cityClass} AS ci" => ["LEFT", "u.city = ci.id"],
"{$stateClass} AS st" => ["LEFT", "u.state = st.id"],
"{$countryClass} AS co" => ["LEFT", "u.country = co.id"]
];
$userId = $request->get('id');
$email = $request->get('email');
$status = $request->get('status');
$dateStart = $request->get('data_inicio');
$dateEnd = $request->get('data_fim');
$paginate = $request->get('paginate');
$limit = (int)$request->get('limit');
$offset = (int)$request->get('offset');
$filter = [
"u.id" => ["!=", 1 ],
"u.deleted" => 0
];
if(empty($limit) || $limit > 1000){
$limit = 1000;
}
if(empty($offset)){
$offset = 0;
}
if(!empty($userId) && $userId > 1){
$filter["u.id"] = (int)$userId;
}
if(!is_null($email)){
$filter["u.email"] = $email;
}
if(!is_null($status)){
$filter["u.status"] = (int)$status;
}
if(empty($dateStart) && !empty($dateEnd)){
$dateStart = date('Y-m-d', strtotime("-1 day",strtotime($dateEnd)));
}
if(empty($dateEnd) && !empty($dateStart)){
$dateEnd = date('Y-m-d', strtotime("+1 day",strtotime($dateStart)));
}
if(!empty($dateStart) && !empty($dateEnd)){
$filter["whereText"] = "u.dateRegister BETWEEN '{$dateStart}' AND '{$dateEnd}'";
}
$order = [ "u.id" => "ASC" ];
$data = $this->repository->paginate("u", null, $columns, $joins, $filter, $order, $limit, $offset);
$clientDomain = '//'.$this->eadDomain.'/';
if(count($data['rows']) == 0){
return $this->eadResponse(null, ErrorEnum::NO_CONTENT, null);
}
$customFields = $this->em->getRepository(UserCustomField::class)->findBy([
"status" => UserCustomFieldEnum::PUBLISHED,
"deleted" => UserEnum::ITEM_NO_DELETED
]);
$fields = [];
$userCustomField = null;
foreach ($data['rows'] as $key => $value) {
if(!empty($value->foto)){
$value->foto = $clientDomain."upload/profiles/".$data['rows'][$key]->foto;
}
if(!empty($value->campos_personalizados) && !empty($customFields)){
$userCustomField = json_decode($value->campos_personalizados);
foreach ($customFields as $keyCustom => $customField) {
$idCustomField = $customField->getId();
if(!empty($userCustomField->{$idCustomField})){
if(!empty($userCustomField->{$idCustomField}->fieldId)){
$fieldId = $userCustomField->{$idCustomField}->fieldId;
if($userCustomField->{$idCustomField}->type == UserCustomFieldEnum::FIELD_MULTIPLE){
$userCustomField->{$idCustomField}->value = (array)$userCustomField->{$idCustomField}->value;
$userCustomField->{$idCustomField}->value = implode(',', $userCustomField->{$idCustomField}->value);
}elseif($userCustomField->{$idCustomField}->type == UserCustomFieldEnum::FIELD_FILE){
$userCustomField->{$idCustomField}->value = "{$clientDomain}user/download/custom/file/{$value->aluno_id}/{$idCustomField}";
}elseif($userCustomField->{$idCustomField}->type == UserCustomFieldEnum::FIELD_OPTION_SELECT && is_array($userCustomField->{$idCustomField}->value)){
$userCustomField->{$idCustomField}->value = (array)$userCustomField->{$idCustomField}->value;
$userCustomField->{$idCustomField}->value = implode(',', $userCustomField->{$idCustomField}->value);
}
if($userCustomField->{$idCustomField}->fieldId == $idCustomField && !empty($userCustomField->{$idCustomField}->value)){
$fields[$customField->getName()] = $userCustomField->{$idCustomField}->value;
}else{
$fields[$customField->getName()] = "";
}
}else{
$fields[$customField->getName()] = "";
}
}else{
$fields[$customField->getName()]= "";
}
}
$value->campos_personalizados_decoded = $fields;
}
}
if($paginate == 1){
unset($data['searchText']);
return $this->json($data);
}
return $this->json($data['rows']);
}
/**
* Inserir um novo usuário no EAD.
*
* @Route("/api/1/student", methods={"POST"})
* consumes={"application/json"}
* produces={"application/json"}
*
* @OA\Response(
* response=200,
* description="Success",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=200, description="Success"),
* @OA\Property(property="message", type="string", example="Success"),
* @OA\Property(
* property="data",
* type="object",
* @OA\Property(property="aluno_id", type="integer", example=12),
* @OA\Property(property="nome", type="string", example="Nome do aluno"),
* @OA\Property(property="email", type="string", example="email@email.com"),
* @OA\Property(property="senha", type="string", example="password"),
* @OA\Property(property="username", type="string", example="username"),
* @OA\Property(property="tipo", type="integer", example=1),
* @OA\Property(property="permissao_id", type="integer", example=2),
* @OA\Property(property="status", type="integer", example=1),
* @OA\Property(property="cpf", type="string", example="222.222.222-22"),
* @OA\Property(property="foto", type="string", example="caminhodaimagem.com"),
* @OA\Property(property="ocupacao", type="string", example="Desenvolvedor"),
* @OA\Property(property="personalizado", type="string", example="Personalizado"),
* @OA\Property(property="anotacoes", type="string", example="Anotacoes"),
* @OA\Property(property="nascimento", type="string", example="1974-10-03"),
* @OA\Property(property="telefone", type="string", example="(88)88888-8888"),
* @OA\Property(property="cep", type="string", example="11111111"),
* @OA\Property(property="endereco", type="string", example="Endereco"),
* @OA\Property(property="numero", type="string", example="222"),
* @OA\Property(property="complemento", type="string", example="Complemento"),
* @OA\Property(property="bairro", type="string", example="Bairro")
* )
* )
* )
*
* @OA\Response(
* response=401,
* description="Token not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=401, description="Token not found"),
* @OA\Property(property="message", type="string", example="Token not found")
* )
* )
*
* @OA\Response(
* response=406,
* description="Empty Fields",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=406, description="Empty Field"),
* @OA\Property(property="message", type="string", example="Error"),
* @OA\Property(
* property="data",
* type="array",
* collectionFormat="multi",
* @OA\Items(
* type="string",
* example="field"
* )
* ),
* )
* )
*
* @OA\Response(
* response=429,
* description="Too many requests",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=429, description="Too many requests"),
* @OA\Property(property="message", type="string", example="Too many requests")
* )
* )
*
* @OA\Response(
* response=500,
* description="Internal Server Error",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=500, description="Internal Server Error"),
* @OA\Property(property="message", type="string", example="Internal Server Error")
* )
* )
*
* @OA\RequestBody(
* required=true,
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="email",
* description="E-mail do Usuário",
* type="string(75)"
* ),
* @OA\Property(
* property="nome",
* description="Nome do Usuário",
* type="string(75)"
* ),
* @OA\Property(
* property="tipo",
* description="Tipo do usuário (1-Aluno / 2-Tutor / 3-Professor(a) / 4-Administrador)",
* type="integer"
* ),
* @OA\Property(
* property="permissao_id",
* description="Id do template de permissão",
* type="integer"
* ),
* @OA\Property(
* property="status",
* description="Status atual da conta (0-Aguardando confirmação / 1-Confirmado / 2-Bloqueado)",
* type="integer"
* ),
* @OA\Property(
* property="senha",
* description="Senha Provisória",
* type="string(40)"
* ),
* @OA\Property(
* property="telefone",
* description="Telefone do usuário",
* type="string(40)"
* ),
* @OA\Property(
* property="data_cadastro",
* description="Data de Cadastro",
* type="datetime"
* ),
* @OA\Property(
* property="personalizado",
* description="Qualquer informação adicional, visível apenas para admin",
* type="string"
* ),
* @OA\Property(
* property="anotacoes",
* description="Observação sobre o usuário, visível apenas para admin",
* type="string"
* ),
* @OA\Property(
* property="notificar",
* description="Notificar por e-mail 0-Não / 1-Sim",
* type="integer"
* ),
* required={"tipo", "nome", "email", "status"}
* )
* )
* )
*
* @OA\Tag(name="Usuários")
* @Security(name="Bearer")
*
*/
public function postUser(Request $request)
{
$this->requestUtil->setRequest($request)->setData();
$type = $this->requestUtil->getField('tipo');
$status = $this->requestUtil->getField('status');
$name = $this->requestUtil->getField('nome');
$email = $this->requestUtil->getField('email');
$phone = $this->requestUtil->getField('telefone');
$password = $this->requestUtil->getField('senha');
$dateRegister = $this->requestUtil->getField('data_cadastro');
$custom = $this->requestUtil->getField('personalizado');
$notes = $this->requestUtil->getField('anotacoes');
if(!empty($this->requestUtil->getField('tipo'))){
$type = (int)$this->requestUtil->getField('tipo');
}
if(!empty($this->requestUtil->getField('status'))){
$status = (int)$this->requestUtil->getField('status');
}
if(is_numeric($this->requestUtil->getField('permissao_id'))){
$userProfileId = $this->requestUtil->getField('permissao_id');
}else{
$userProfileId = $type;
}
if(is_numeric($this->requestUtil->getField('notificar'))){
$notify = $this->requestUtil->getField('notificar');
}else{
$notify = null;
}
$totalEmail = $this->repository->countByEmail($email);
if(!empty($totalEmail))
{
$user = $this->repository->findOneBy([
"email" => $email,
"deleted" => UserEnum::ITEM_ON_TRASH
]);
if($user){
$this->repository->delete($user, null, null, null, null, null, null, null, true);
$this->userLogService->logDelete("user", $user->getId(), null, UserLogEnum::ORIGIN_CLIENT_API);
}else{
return $this->eadResponse([ 'email' ], ErrorEnum::CONFLICT, "Email já cadastrado.");
}
}
$dataUser = [
"type" => $type,
"status" => $status,
"dateRegister" => $dateRegister,
"name" => $name,
"email" => $email,
"password" => $password,
"phone" => $phone,
"custom" => $custom,
"notes" => $notes,
"userProfileId" => $userProfileId,
"notify" => $notify
];
$userDTO = new UserDTO($dataUser);
$data = $this->repository->newUser($userDTO);
if($data->errors){
return $this->eadResponse($data->errors, ErrorEnum::FIELD_EMPTY, ErrorEnum::MESSAGE_EMPTY_FIELD);
}
$user = $data->user;
$return = $user->toReturnApi();
$this->userLogService->logInsert("user", $user->getId(), $return, UserLogEnum::ORIGIN_CLIENT_API);
return $this->eadResponse($return, ErrorEnum::SUCCESS, ErrorEnum::MESSAGE_SUCCESS);
}
/**
* Atualizar um usuário do EAD.
*
* @Route("/api/1/student/{aluno_id}", methods={"PUT"})
* consumes={"application/json"}
* produces={"application/json"}
*
* @OA\Response(
* response=200,
* description="Success",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=200, description="Success"),
* @OA\Property(property="message", type="string", example="Success"),
* @OA\Property(
* property="data",
* type="object",
* @OA\Property(property="aluno_id", type="integer", example=12),
* @OA\Property(property="nome", type="string", example="Nome do aluno"),
* @OA\Property(property="email", type="string", example="email@email.com"),
* @OA\Property(property="senha", type="string", example="password"),
* @OA\Property(property="username", type="string", example="username"),
* @OA\Property(property="tipo", type="integer", example=1),
* @OA\Property(property="permissao_id", type="integer", example=2),
* @OA\Property(property="status", type="integer", example=1),
* @OA\Property(property="cpf", type="string", example="222.222.222-22"),
* @OA\Property(property="foto", type="string", example="caminhodaimagem.com"),
* @OA\Property(property="ocupacao", type="string", example="Desenvolvedor"),
* @OA\Property(property="personalizado", type="string", example="Personalizado"),
* @OA\Property(property="anotacoes", type="string", example="Anotacoes"),
* @OA\Property(property="nascimento", type="string", example="1974-10-03"),
* @OA\Property(property="telefone", type="string", example="(88)88888-8888"),
* @OA\Property(property="cep", type="string", example="11111111"),
* @OA\Property(property="endereco", type="string", example="Endereco"),
* @OA\Property(property="numero", type="string", example="222"),
* @OA\Property(property="complemento", type="string", example="Complemento"),
* @OA\Property(property="bairro", type="string", example="Bairro")
* )
* )
* )
*
* @OA\Response(
* response=401,
* description="Token not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=401, description="Token not found"),
* @OA\Property(property="message", type="string", example="Token not found")
* )
* )
*
* @OA\Response(
* response=404,
* description="Not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=404, description="Not found"),
* @OA\Property(property="message", type="string", example="Not found"),
* @OA\Property(
* property="data",
* type="array",
* collectionFormat="multi",
* @OA\Items(
* type="string",
* example="field"
* )
* ),
* )
* )
*
* @OA\Response(
* response=406,
* description="Empty Fields",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=406, description="Empty Field"),
* @OA\Property(property="message", type="string", example="Error"),
* @OA\Property(
* property="data",
* type="array",
* collectionFormat="multi",
* @OA\Items(
* type="string",
* example="field"
* )
* ),
* )
* )
*
* @OA\Response(
* response=429,
* description="Too many requests",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=429, description="Too many requests"),
* @OA\Property(property="message", type="string", example="Too many requests")
* )
* )
*
* @OA\Response(
* response=500,
* description="Internal Server Error",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=500, description="Internal Server Error"),
* @OA\Property(property="message", type="string", example="Internal Server Error")
* )
* )
*
* @OA\Parameter(
* name="aluno_id",
* in="path",
* description="Aluno Id",
* required=true,
* @OA\Schema(type="integer")
* )
*
* @OA\RequestBody(
* required=false,
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* type="object",
* @OA\Property(
* property="tipo",
* description="Tipo do usuário (1-Aluno / 2-Tutor / 3-Professor(a) / 4-Administrador)",
* type="integer"
* ),
* @OA\Property(
* property="status",
* description="Status atual da conta (0-Aguardando confirmação / 1-Confirmado / 2-Bloqueado)",
* type="integer"
* ),
* @OA\Property(
* property="nome",
* description="Nome do Usuário",
* type="string(75)"
* ),
* @OA\Property(
* property="email",
* description="E-mail do Usuário",
* type="string(75)"
* ),
* @OA\Property(
* property="telefone",
* description="Telefone do usuário",
* type="string(40)"
* ),
* @OA\Property(
* property="senha",
* description="Senha",
* type="string"
* ),
* @OA\Property(
* property="username",
* description="Username",
* type="string(75)"
* ),
* @OA\Property(
* property="cpf",
* description="CPF somente números",
* type="string(40)"
* ),
* @OA\Property(
* property="nascimento",
* description="Data de nascimento (YYYY-MM-DD)",
* type="date"
* ),
* @OA\Property(
* property="endereco",
* description="Endereço",
* type="string(115)"
* ),
* @OA\Property(
* property="numero",
* description="Número",
* type="string(10)"
* ),
* @OA\Property(
* property="complemento",
* description="Complemento",
* type="string(115)"
* ),
* @OA\Property(
* property="bairro",
* description="Bairro",
* type="string(60)"
* ),
* @OA\Property(
* property="cep",
* description="CEP",
* type="string(40)"
* ),
* @OA\Property(
* property="profissao",
* description="Profissão",
* type="string(45)"
* ),
* @OA\Property(
* property="personalizado",
* description="Qualquer informação adicional, visível apenas para admin",
* type="string"
* ),
* @OA\Property(
* property="anotacoes",
* description="Observação sobre o usuário, visível apenas para admin",
* type="string"
* ),
* @OA\Property(
* property="notificar",
* description="Notificar por e-mail 0-Não / 1-Sim",
* type="integer"
* ),
* )
* )
* ),
*
* @OA\Tag(name="Usuários")
* @Security(name="Bearer")
*
*/
public function putUser(Request $request)
{
$this->requestUtil->setRequest($request)->setData();
$userId = $request->get('aluno_id');
if ($userId == 1) {
return $this->eadResponse(null, ErrorEnum::NOT_FOUND, ErrorEnum::MESSAGE_NOT_FOUND);
}
$user = $this->repository->findOneBy([
"id" => $userId,
"deleted" => UserEnum::ITEM_NO_DELETED
]);
if (!$user) {
return $this->eadResponse(null, ErrorEnum::NOT_FOUND, ErrorEnum::MESSAGE_NOT_FOUND);
}
$type = (int)$this->requestUtil->getField('tipo');
if(is_numeric($type) && $type >= 1 && $type <= 4){
$user->setType($type);
}
$status = $this->requestUtil->getField('status');
if(is_numeric($status) && $status >= 0 && $type <= 2){
$user->setStatus($status);
}
$name = $this->requestUtil->getField('nome');
if(!empty($name)){
$user->setName($name);
}
$email = $this->requestUtil->getField('email');
if(!empty($email))
{
if($user->getEmail() != $email)
{
$totalEmail = $this->repository->countByEmail($email);
if(!empty($totalEmail))
{
return $this->eadResponse([ 'email' ], ErrorEnum::CONFLICT, "Email já cadastrado.");
}
$user->setEmail(strtolower($email));
}
}
$phone = $this->requestUtil->getField('telefone');
if(!empty($phone)){
$user->setPhone($phone);
}
$updatePassword = false;
$password = $this->requestUtil->getField('senha');
if(!empty($password)){
$oldPassword = $user->getPassword();
$user->setPassword($password);
$oldPass = $user->getOldPassword(true);
if(in_array($user->getPassword(), $oldPass)){
return $this->eadResponse(
[ 'senha' ],
ErrorEnum::CONFLICT,
"Nova senha precisa ser diferente da anterior!"
);
}
$updatePassword = true;
if($oldPassword != UserEnum::PASSWORD_RESET){
$user->setOldPassword($oldPassword);
}
}
$username = $this->requestUtil->getField('username');
if(!empty($username))
{
if($user->getUsername() != $username)
{
$totalUsername = $this->repository->countByUsername($username);
if(!empty($totalUsername))
{
return $this->eadResponse(
[ 'username' ],
ErrorEnum::CONFLICT,
"Username já cadastrado."
);
}
$user->setUsername($username);
}
}
$document = $this->requestUtil->getField('cpf');
if(!empty($document)){
$user->setDocument($document);
}
$birthDate = $this->requestUtil->getField('nascimento');
if(!empty($birthDate)){
$user->setBirthDate($birthDate);
}
$address = $this->requestUtil->getField('endereco');
if(!empty($address)){
$user->setAddress($address);
}
$addressNumber = $this->requestUtil->getField('numero');
if(!empty($addressNumber)){
$user->setAddressNumber($addressNumber);
}
$addressComplement = $this->requestUtil->getField('complemento');
if(!empty($addressComplement)){
$user->setAddressComplement($addressComplement);
}
$addressNeighborhood = $this->requestUtil->getField('bairro');
if(!empty($addressNeighborhood)){
$user->setAddressNeighborhood($addressNeighborhood);
}
$zipCode = $this->requestUtil->getField('cep');
if(!empty($zipCode)){
$user->setZipCode($zipCode);
}
$occupation = $this->requestUtil->getField('profissao');
if(!empty($occupation)){
$user->setOccupation($occupation);
}
$custom = $this->requestUtil->getField('personalizado');
if(!empty($custom)){
$user->setCustom($custom);
}
$notes = $this->requestUtil->getField('anotacoes');
if(!empty($notes)){
$user->setNotes($notes);
}
$notify = (int)$this->requestUtil->getField('notificar');
$errors = $this->validateEntity($user);
if($errors){
return $this->eadResponse($errors, ErrorEnum::FIELD_EMPTY, ErrorEnum::MESSAGE_EMPTY_FIELD);
}
if($updatePassword){
$this->em->getRepository(Session::class)->resetSessions($user);
if($notify == UserEnum::YES){
$emailService = $this->generalService->getService('EmailService');
if(
$emailService->checkUserToSend($user, false) ||
$this->configuration->get("allow_send_email_user") == UserEnum::YES
){
$hashData = [
"today" => date('Ymd'),
"userId" => $user->getId()
];
$hash = $stringUtil->encodeHex(base64_encode(json_encode($hashData)));
$emailService->setToEmail($user->getEmail());
$emailService->setToName($user->getName());
$subject = $this->configuration->getLanguage('change_password.subject', 'email')." - ".$this->client->getBrand();
$emailService->setSubject($subject);
$emailService->setData([
"userName" => $user->getName(),
"btnLink" => 'https://'.$this->client->getDomainPrimary()."/profile",
]);
$emailService->setTemplateBody("change_password");
$emailService->send();
}
}
}
if($user->getState()){
$country = $user->getState()->getCountry();
if($country){
$user->setCountry($country);
}
}
$this->em->flush();
$return = $user->toReturnApi();
$this->userLogService->logUpdate("user", $user->getId(), $return, UserLogEnum::ORIGIN_CLIENT_API);
if(!empty($return['foto'])){
$return['foto'] = '//'.$this->eadDomain.$return['foto'];
}
return $this->eadResponse($return, ErrorEnum::SUCCESS, ErrorEnum::MESSAGE_SUCCESS);
}
/**
* Excluir um usuário do EAD.
*
*
* @Route("/api/1/student/{id}", methods={"DELETE"})
* @OA\Response(
* response=200,
* description="Success",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=200, description="Success"),
* @OA\Property(property="message", type="string", example="Success"),
* @OA\Property(property="data", nullable=true, type="application/json", example="null"),
* )
* )
*
* @OA\Response(
* response=401,
* description="Token not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=401, description="Token not found"),
* @OA\Property(property="message", type="string", example="Token not found")
* )
* )
*
* @OA\Response(
* response=404,
* description="Not found",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=404, description="Not found"),
* @OA\Property(property="message", type="string", example="Not found"),
* @OA\Property(
* property="data",
* type="array",
* collectionFormat="multi",
* @OA\Items(
* type="string",
* example="field"
* )
* ),
* )
* )
*
* @OA\Response(
* response=429,
* description="Too many requests",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=429, description="Too many requests"),
* @OA\Property(property="message", type="string", example="Too many requests")
* )
* )
*
* @OA\Response(
* response=500,
* description="Internal Server Error",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="http_status", type="integer", example=500, description="Internal Server Error"),
* @OA\Property(property="message", type="string", example="Internal Server Error")
* )
* )
*
* @OA\Parameter(
* name="id",
* in="path",
* description="Usuário Id",
* required=true,
* @OA\Schema(type="integer")
* )
*
* @OA\Tag(name="Usuários")
* @Security(name="Bearer")
*
*/
public function deleteUser(Request $request)
{
$this->requestUtil->setRequest($request)->setData();
$userId = $request->get('id');
$user = $this->repository->findOneBy([
"id" => $userId,
"deleted" => UserEnum::ITEM_NO_DELETED
]);
if (!$user) {
return $this->eadResponse(null, ErrorEnum::NOT_FOUND, ErrorEnum::MESSAGE_NOT_FOUND);
}
$this->repository->delete($user, null, null, null, null, null, null, null, true);
$this->userLogService->logDelete("user", $user->getId(), null, UserLogEnum::ORIGIN_CLIENT_API);
return $this->eadResponse(null, ErrorEnum::SUCCESS, ErrorEnum::MESSAGE_SUCCESS);
}
}