<?php
namespace Entrepreneurs\Bundle\AppBundle\Propel;
use Entrepreneurs\Bundle\AppBundle\Propel\Base\Entrepreneur as BaseEntrepreneur;
use Entrepreneurs\Bundle\AppBundle\Propel\Map\EntrepreneurSecteursActiviteTableMap;
use Entrepreneurs\Bundle\AppBundle\Propel\Map\SecteurActiviteTableMap;
use Entrepreneurs\Bundle\AppBundle\Util\Password;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Collection\Collection;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Propel;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
class Entrepreneur extends BaseEntrepreneur implements UserInterface, PasswordAuthenticatedUserInterface
{
public const MONSIEUR = 'Monsieur';
public const PK_PAS_DEVENIR_RT = 'Pourquoi pas, je veux bien en savoir plus sur les missions';
public const ACCEPT_DEVENIR_RT = "Oui ça m'intéresse et je peux dégager du temps";
public const REFUSE_DEVENIR_RT = 'Non';
public const RT_VALIDE_NON = 'Non';
public const RT_VALIDE_EN_COURS = 'En cours';
public const RT_VALIDE_OUI = 'Oui';
public const RT_VALIDE_ANCIEN = 'Ancien RT';
protected $plainMotDePasse;
public function __toString()
{
return $this->getNomComplet();
}
public function getNomCompletStatut()
{
return $this->getNomComplet().' ('.$this->getStatut().')';
}
public function getNomComplet()
{
return $this->getCivilite().' '.$this->getPrenomNom();
}
public function getPrenomNom()
{
return $this->getPrenom().' '.mb_strtoupper($this->getNom(), 'UTF-8');
}
public function eraseCredentials()
{
$this->plainMotDePasse = '';
}
public function getPassword(): ?string
{
return $this->getMotDePasse();
}
public function getRoles(): array
{
return ['ROLE_ENTREPRENEUR'];
}
public function getSalt(): ?string
{
return $this->getSel();
}
public function getUsername(): string
{
return $this->getEmail();
}
public function initMotDePasse(): string
{
$password = Password::create();
$this->setMotDePasse($password);
return $password;
}
public function setMotDePasse($v, $encode = true, $algorithm = 'sha256'): self
{
if ($encode) {
$this->setSel(sha1(uniqid((string) time(), true)));
parent::setMotDePasse(hash($algorithm, $v.'{'.$this->getSel().'}'));
} else {
parent::setMotDePasse($v);
}
return $this;
}
public function setPlainMotDePasse($v): void
{
$this->plainMotDePasse = $v;
}
public function getPlainMotDePasse(): string
{
return $this->plainMotDePasse;
}
public function getCodePostal($short = false): string
{
if ($short) {
return substr($this->code_postal, 0, 2);
}
return $this->code_postal;
}
public function getReseaux(Criteria $criteria = null, ConnectionInterface $con = null)
{
return parent::getReseaus($criteria, $con);
}
public function setReseaux(Collection $reseaus, ConnectionInterface $con = null)
{
return parent::setReseaus($reseaus, $con);
}
public function hasThisDepartement($departementReceive)
{
$flag = false;
foreach ($this->getDepartements() as $departement) {
if ($departement->getNumero() == $departementReceive->getNumero()) {
return true;
}
}
return $flag;
}
/**
* Retourne les demandes d'intervention dont les caractéristiques géographiques
* correspondent à la l'entrepreneur courrant.
*/
public function getMatchingDemandesIntervention()
{
$ids = [];
foreach ($this->getInterventions() as $intervention) {
$ids[] = $intervention->getDemandeInterventionId();
}
return DemandeInterventionQuery::create()
->filterById($ids, Criteria::NOT_IN)
->filterByStatutId(DemandeInterventionStatut::EN_ATTENTE_INTERVENANT)
->filterByCreneau1Debut(new \DateTime(), Criteria::GREATER_THAN)
->_or()
->filterByCreneau2Debut(new \DateTime(), Criteria::GREATER_THAN)
->_or()
->filterByCreneau3Debut(new \DateTime(), Criteria::GREATER_THAN)
->useEtablissementQuery()
->useVilleQuery()
->filterByDepartement($this->getDepartements())
->endUse()
->endUse()
->distinct()
->find()
;
}
/**
* Associe et enregistre les demandes d'intervention dont les caractéristiques
* géographiques correspondent à l'entrepreneur courrant.
*/
public function matchDemandesIntervention()
{
$demandes = $this->getMatchingDemandesIntervention();
foreach ($demandes as $demande) {
$intervention = new Intervention();
$intervention->setDemandeIntervention($demande);
$intervention->setEntrepreneur($this);
$intervention->setMatchingAuto(true);
$intervention->save();
}
return $demandes;
}
/**
* NB: EntrepreneurStatut::EN_ATTENTE_ACTIVATION is not enabled, not disabled.
*/
public function isDisabled(): bool
{
return in_array($this->getStatutId(), [
EntrepreneurStatut::SUPPRIME,
EntrepreneurStatut::SUSPENDU,
]);
}
/**
* NB: EntrepreneurStatut::EN_ATTENTE_ACTIVATION is not enabled, not disabled.
*/
public function isEnabled(): bool
{
return in_array($this->getStatutId(), [
EntrepreneurStatut::ACTIF,
EntrepreneurStatut::MDP_REINITIALISE,
]);
}
public function initQuestionnaire(): Entrepreneur
{
return $this
->generateNewUID()
->setStatutId(EntrepreneurStatut::EN_ATTENTE_ACTIVATION);
}
public function estForme(): ?bool
{
return $this->getEstForme();
}
public function getInscriptionFormationActive()
{
$query = FormationInscriptionQuery::create()
->filterByStatutId([
FormationInscriptionStatut::ANNULEE,
FormationInscriptionStatut::REFUSEE,
], Criteria::NOT_IN)
->useFormationQuery()
->filterByDate(['min' => new \DateTime()])
->endUse()
->orderByDateCreation(Criteria::DESC);
return $this->getFormationInscriptions($query)->getFirst();
}
/**
* @throws PropelException
*/
public function getFormationInscriptionElearning()
{
return FormationInscriptionQuery::create()
->useFormationQuery()
->filterById(Formation::E_LEARNING)
->endUse()
->filterByEntrepreneur($this)
->find()
->getFirst()
;
}
public function getFormationActive()
{
return $this->getInscriptionFormationActive() ? $this->getInscriptionFormationActive()->getFormation() : null;
}
public function hasAtLeastOneDepartementInterventionActif()
{
foreach ($this->getDepartements() as $departement) {
if ($departement->getActif()) {
return true;
}
}
return false;
}
public function getAnnotations(Criteria $criteria = null, ConnectionInterface $con = null)
{
if (!$criteria) {
$criteria = AnnotationEntrepreneurQuery::create()->orderByDateCreation(Criteria::DESC);
}
return parent::getAnnotations($criteria, $con);
}
public function hasMotdePasseAndSel()
{
return $this->getMotDePasse() && $this->getSalt();
}
public function getDelegue(): ?Gestionnaire
{
if ($departement = $this->getDepartements()->getFirst()) {
return $departement->getDelegue();
}
return null;
}
public function getCoordinateur(): ?Gestionnaire
{
$cp = substr($this->getEntrepriseCodePostal(), 0, 2);
if ($cp >= 96) {
$cp = substr($this->getEntrepriseCodePostal(), 0, 3);
}
$organismeDepartement = DepartementQuery::create()
->filterByActif(true)
->filterByNumero($cp)
->findOne();
if ($organismeDepartement) {
return $organismeDepartement->getCoordinateur();
} elseif ($departementIntervention = $this->getDepartementInterventions(DepartementQuery::create()->filterByActif(true))->getFirst()) {
if ($departement = $departementIntervention->getDepartement()) {
return $departement->getCoordinateur();
}
}
return null;
}
public function formationELearningEnCours()
{
foreach ($this->getFormationInscriptions() as $formationInscription) {
if (
-1 === $formationInscription->getFormationId()
&& $formationInscription->getStatutId()
&& FormationInscriptionStatut::EN_ATTENTE === $formationInscription->getStatutId()
) {
return true;
}
}
return false;
}
public function getTelephone(): string
{
return parent::getTelephone1();
}
public function getNombreInterventionParDate(\DateTime $date): int
{
return InterventionQuery::create()
->filterByEntrepreneurAndDate($this, $date)
->find()
->count();
}
public function logSurvey1(): void
{
$surveyStat = new SurveyStats();
$surveyStat->setEntrepreneur($this)
->setsurveyEntrepreneur1(true);
$surveyStat->save();
}
public function logSurvey2(): void
{
$surveyStat = new SurveyStats();
$surveyStat->setEntrepreneur($this)
->setsurveyEntrepreneur2(true);
$surveyStat->save();
}
public function logSurveySEF(): void
{
$surveyStat = new SurveyStats();
$surveyStat->setEntrepreneur($this)
->setsurveyEntrepreneurSEF(true);
$surveyStat->save();
}
/**
* @throws PropelException
*/
public function setStatutId($v): Entrepreneur
{
if (EntrepreneurStatut::SUSPENDU === $v) {
if (null !== $this->getDateReactivation()) {
$duree = (int) ceil(($this->getDateReactivation()->getTimestamp() - time()) / (60 * 60 * 24));
}
}
return parent::setStatutId($v);
}
public function getSecteursActivitesLabels(): string
{
$con = Propel::getConnection();
$sql = 'SELECT '.SecteurActiviteTableMap::COL_LABEL.
' FROM '.SecteurActiviteTableMap::TABLE_NAME.
' INNER JOIN '.EntrepreneurSecteursActiviteTableMap::TABLE_NAME.
' ON '.EntrepreneurSecteursActiviteTableMap::COL_SECTEUR_ACTIVITE_ID.' = '.SecteurActiviteTableMap::COL_ID.
' WHERE '.EntrepreneurSecteursActiviteTableMap::COL_ENTREPRENEUR_ID.' = '.$this->getId();
$stmt = $con->prepare($sql);
$stmt->execute();
$secteursActivites = $stmt->fetchAll();
$secteursActivitesString = '';
foreach ($secteursActivites as $secteurActivite) {
$secteursActivitesString .= $secteurActivite['label'].', ';
}
return '' !== $secteursActivitesString ? substr($secteursActivitesString, 0, -2) : '';
}
public function getFonctionLabel(): string
{
$fonction = FonctionEntrepreneurQuery::create()->filterById($this->getFonctionId())->findOne();
return $fonction ? $fonction->getLabel() : '';
}
public function getEffectifLabel(): string
{
return $this->getEntrepriseEffectif() ? $this->getEntrepriseEffectif()->getLabel() : '';
}
public function getReseauxLabels(): string
{
$reseaux = ReseauQuery::create()
->useEntrepreneurReseauExistsQuery()
->filterByEntrepreneur($this)
->endUse()
->find();
$reseauString = '';
/** @var Reseau $reseau */
foreach ($reseaux as $reseau) {
$reseauString .= $reseau->getNom().', ';
}
return '' !== $reseauString ? substr($reseauString, 0, -2) : '';
}
public function getModeCommunicationLabels(): string
{
$modeCommunication = ModeCommunicationQuery::create()->
useEntrepreneurModeCommunicationExistsQuery()
->filterByEntrepreneur($this)
->endUse()
->find();
$modeCommunicationString = '';
/** @var ModeCommunication $mode */
foreach ($modeCommunication as $mode) {
$modeCommunicationString .= $mode->getLabel().', ';
}
return '' !== $modeCommunicationString ? substr($modeCommunicationString, 0, -2) : '';
}
public function getDepartementsLabels(): string
{
$departements = DepartementQuery::create()
->useDepartementInterventionExistsQuery()
->filterByEntrepreneur($this)
->endUse()
->find();
$departementString = '';
/** @var Departement $departement */
foreach ($departements as $departement) {
$departementString .= $departement->getLabel().', ';
}
return '' !== $departementString ? substr($departementString, 0, -2) : '';
}
public function getProvenanceLabel(): string
{
$provenance = ProvenanceEntrepreneurQuery::create()->filterById($this->getProvenanceId())->findOne();
return $provenance ? $provenance->getLabel() : '';
}
public function getTelephoneLabel(): string
{
$tel = $this->getTelephone();
$tel = str_replace(' ', '', $tel);
$tel = str_replace('.', '', $tel);
$tel = str_replace('/', '', $tel);
return $tel;
}
public function getCollegeLabel(): string
{
return $this->getCollege() ? $this->getCollege()->getLabel() : '';
}
public function getLyceeLabel(): string
{
return $this->getLycee() ? $this->getLycee()->getLabel() : '';
}
public function getEtablissementsEnfantsLabels(): string
{
$etablissements = EtablissementQuery::create()
->useEntrepreneurEtablissementEnfantExistsQuery()
->filterByEntrepreneur($this)
->endUse()
->find();
$etablissementsLabels = '';
/** @var Etablissement $etablissement */
foreach ($etablissements as $etablissement) {
$etablissementsLabels .= $etablissement->getLabel().', ';
}
return '' !== $etablissementsLabels ? substr($etablissementsLabels, 0, -2) : '';
}
public function getThematiquesLabels(): string
{
$evenements = EvenementQuery::create()
->useEntrepreneurEvenementQuery()
->filterByEntrepreneur($this)
->endUse()
->find();
$thematiques = '';
/** @var Evenement $evenement */
foreach ($evenements as $evenement) {
$thematiques .= $evenement->getLabel().', ';
}
return '' !== $thematiques ? substr($thematiques, 0, -2) : '';
}
public function getLanguesEtrangeresLabels(): string
{
$langues = LangueEtrangereQuery::create()
->useEntrepreneurLangueEtrangereExistsQuery()
->filterByEntrepreneur($this)
->endUse()
->find();
$languesLabels = '';
/** @var LangueEtrangere $langue */
foreach ($langues as $langue) {
$languesLabels .= $langue->getLabel().', ';
}
return '' !== $languesLabels ? substr($languesLabels, 0, -2) : '';
}
public function getFullAdress(): string
{
try {
$countryName = $this->pays ? Countries::getName($this->pays, 'fr') : null;
} catch (\Exception $exception) {
$countryName = $this->pays;
}
$fullAddress = $this->adresse_1;
$fullAddress .= ($fullAddress && !empty($this->adresse_1) ? ' ' : '').$this->adresse_2;
$fullAddress .= ($fullAddress ? ', ' : '').$this->code_postal;
$fullAddress .= ($fullAddress && !empty($this->code_postal) ? ' ' : '').$this->ville;
$fullAddress .= ($fullAddress && (!empty($this->ville) || !empty($this->code_postal)) && !empty($countryName) ? ', ' : '').$countryName;
return $fullAddress;
}
public function getFullEntrepriseAdresse(): string
{
try {
$countryName = $this->entreprise_pays ? Countries::getName($this->entreprise_pays, 'fr') : '';
} catch (\Exception $exception) {
$countryName = $this->entreprise_pays;
}
$fullAddress = $this->entreprise_adresse;
$fullAddress .= ($fullAddress ? ', ' : '').$this->entreprise_code_postal;
$fullAddress .= ($fullAddress && !empty($this->entreprise_code_postal) ? ' ' : '').$this->entreprise_ville;
$fullAddress .= ($fullAddress && (!empty($this->entreprise_ville) || !empty($this->entreprise_code_postal)) && !empty($countryName) ? ', ' : '').$countryName;
return $fullAddress;
}
public function suspendre(\DateTime $dateReactivation): Entrepreneur
{
if (EntrepreneurStatut::SUSPENDU === $this->getStatutId()) {
return $this;
}
$this->setStatutId(EntrepreneurStatut::SUSPENDU);
$this->setDateReactivation($dateReactivation);
$this->setDureeSuspension(($dateReactivation->getTimestamp() - time()) / 86400);
return $this;
}
public function generateNewUID(): self
{
$this->setUid(sha1(uniqid((string) time(), true)));
return $this;
}
public function generateNewTokenReinitialisation(): self
{
$this->setTokenReinitialisation(sha1(uniqid((string) time(), true)));
return $this;
}
public function isDeletable()
{
$linkedInterventions = InterventionQuery::create()
->filterByEntrepreneur($this)
->filterByStatutId([
InterventionStatut::ACCEPTEE,
InterventionStatut::EN_ATTENTE_EVALUATION,
InterventionStatut::SUSPENDU,
InterventionStatut::TERMINEE,
])
->count()
;
return EntrepreneurStatut::SUPPRIME === $this->getStatutId() && !$linkedInterventions > 0;
}
public function hasAlreadyOneReservation(): bool
{
return InterventionQuery::create()
->filterByEntrepreneur($this)
->filterByStatutId(InterventionStatut::RESERVED)
->count() > 0;
}
/**
* @throws PropelException
*/
public function getInterventionsWithEvaluationNotCompleted(): ObjectCollection
{
return InterventionQuery::create()
->filterByEntrepreneur($this)
->filterByStatutId(InterventionStatut::EN_ATTENTE_EVALUATION)
->find();
}
public function getDateAdhesionReseau(int $reseauId, string $format): string|null
{
$adhesionReseau = EntrepreneurReseauQuery::create()
->filterByEntrepreneur($this)
->filterByReseauId($reseauId)
->findOne();
return $adhesionReseau?->getDateCreation($format);
}
}