<?php
namespace App\Entity;
use App\Entity\Garages\Garage;
use App\Entity\PointsCatalog\CatalogPointMovement;
use App\Enum\UserRolesEnum;
use App\Repository\UserRepository;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Constraints\Email;
/**
* @ORM\Table(name="vulco_user")
*
* @ORM\Entity(repositoryClass=UserRepository::class)
*
* @Gedmo\SoftDeleteable(fieldName="removedAt", timeAware=false)
*
* https://symfony.com/doc/5.x/reference/constraints/UniqueEntity.html:
* (no he conseguit que funcioni)
* @UniqueEntity("email")
* @UniqueEntity("username")
*/
class User extends AbstractBase implements PasswordAuthenticatedUserInterface, UserInterface
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\UserGroup", inversedBy="users")
*
* @ORM\JoinColumn(name="user_group_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
private ?UserGroup $userGroup = null;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Garages\Garage", mappedBy="owner")
*/
private ?Collection $garages;
/**
* @ORM\OneToMany(targetEntity="App\Entity\OnlineShop\Supplier", mappedBy="user")
*/
private ?Collection $suppliers;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Province")
*
* @ORM\JoinTable(name="vulco_user_province",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="province_id", referencedColumnName="id")}
* )
*
* @ORM\OrderBy({"name": "ASC"})
*/
private ?Collection $workProvinces;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Documents\DocumentDownload", mappedBy="user", orphanRemoval=true)
*/
private ?Collection $documentDownloads;
/**
* @ORM\OneToMany(targetEntity="App\Entity\OnlineShop\SupplierDocumentDownload", mappedBy="user", orphanRemoval=true)
*/
private ?Collection $supplierDocumentDownloads;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Tracking\UserTracking", mappedBy="user", orphanRemoval=true)
*/
private ?Collection $userTrackings;
/**
* @ORM\OneToMany(targetEntity="App\Entity\PointsCatalog\CatalogPointMovement", mappedBy="user", orphanRemoval=true)
*/
private ?Collection $pointMovements;
/**
* @ORM\Column(type="string", length=180, unique=true)
* @Assert\Email
*/
private string $email;
/**
* @ORM\Column(type="string", length=180, nullable=true)
*
* inhereted from legacy vulco FOSUserBundle
*/
private ?string $emailCanonical = null;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private string $username;
/**
* @ORM\Column(type="string", length=180, nullable=true)
*
* inhereted from legacy vulco FOSUserBundle
*/
private ?string $usernameCanonical = null;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private ?string $name;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private ?string $zone;
/**
* @ORM\Column(type="array")
*/
private array $roles = [];
/**
* @ORM\Column(type="string")
*/
private string $password;
/**
* @ORM\Column(type="string", nullable=true)
*/
private ?string $salt = null;
/**
* @ORM\Column(type="datetime", name="last_login", nullable=true)
*/
private ?\DateTimeInterface $lastLogin;
/**
* @ORM\Column(type="datetime", name="last_old_login", nullable=true)
*/
private ?\DateTimeInterface $lastOldLogin;
/**
* @ORM\Column(type="datetime", name="last_visit_on", nullable=true)
*/
private ?\DateTimeInterface $lastVisitOn;
/**
* @ORM\Column(type="datetime", name="password_requested_at", nullable=true)
*/
private ?\DateTimeInterface $passwordRequestedAt;
/**
* @ORM\Column(type="string", name="internal_description", nullable=true)
*/
private ?string $internalDescription;
/**
* @ORM\Column(type="boolean", name="enabled", nullable=false)
*/
private bool $enabled = true;
/**
* @ORM\Column(type="boolean", nullable=true, options={"default": 0})
*/
private bool $enableStatisticsManagement = false;
/**
* @ORM\Column(type="boolean", name="readed_confidentiality", nullable=false)
*/
private bool $readedConfidentiality = false;
/**
* @ORM\Column(type="datetime", name="readed_confidentiality_at", nullable=true)
*/
private ?\DateTimeInterface $readedConfidentialityAt;
/**
* @ORM\Column(type="string", name="login_token", nullable=true)
*/
private ?string $token = null;
/**
* @ORM\Column(type="string", name="confirmation_token", length=180, nullable=true, unique=true)
*/
private string $confirmationToken;
public function __construct()
{
$this->createdAt = new \DateTime();
$this->garages = new ArrayCollection();
$this->suppliers = new ArrayCollection();
$this->workProvinces = new ArrayCollection();
$this->documentDownloads = new ArrayCollection();
$this->supplierDocumentDownloads = new ArrayCollection();
$this->userTrackings = new ArrayCollection();
$this->pointMovements = new ArrayCollection();
}
public function getUserIdentifier(): string
{
return $this->getUsername();
}
public function getUserGroup(): ?UserGroup
{
return $this->userGroup;
}
public function setUserGroup(?UserGroup $userGroup): self
{
$this->userGroup = $userGroup;
return $this;
}
public function getGarages(): ?Collection
{
return $this->garages;
}
public function setGarages(?Collection $garages): self
{
$this->garages = $garages;
return $this;
}
public function addGarage(Garage $garage): self
{
if (!$this->garages->contains($garage)) {
$this->garages->add($garage);
}
return $this;
}
public function getSuppliers(): ?Collection
{
return $this->suppliers;
}
public function setSuppliers($suppliers): self
{
$this->suppliers = $suppliers;
return $this;
}
public function getWorkProvinces(): ?Collection
{
return $this->workProvinces;
}
public function setWorkProvinces(?Collection $workProvinces): self
{
$this->workProvinces = $workProvinces;
return $this;
}
public function getDocumentDownloads(): ?Collection
{
return $this->documentDownloads;
}
public function setDocumentDownloads(?Collection $documentDownloads): self
{
$this->documentDownloads = $documentDownloads;
return $this;
}
public function getSupplierDocumentDownloads(): ?Collection
{
return $this->supplierDocumentDownloads;
}
public function setSupplierDocumentDownloads(?Collection $supplierDocumentDownloads): self
{
$this->supplierDocumentDownloads = $supplierDocumentDownloads;
return $this;
}
public function getUserTrackings(): ?Collection
{
return $this->userTrackings;
}
public function setUserTrackings(?Collection $userTrackings): self
{
$this->userTrackings = $userTrackings;
return $this;
}
public function getPointMovements(): ?Collection
{
return $this->pointMovements;
}
public function setPointMovements(?Collection $pointMovements): self
{
$this->pointMovements = $pointMovements;
return $this;
}
public function getNameOrEmail(): string
{
return $this->getName() ?: $this->getEmail();
}
public function getNameAndEmailString(): string
{
return $this->getName() ? $this->getName().' ('.$this->getEmail().')' : $this->getEmail();
}
public function getUsername(): string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getRoles(): array
{
$roles = $this->roles;
$roles[] = UserRolesEnum::ROLE_USER_LONG; // guarantee every user at least has ROLE_USER
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
public function hasRole(string $role): bool
{
return in_array(strtoupper($role), $this->roles, true);
}
public function addRole(string $role): self
{
if (!$this->hasRole($role)) {
$this->roles[] = strtoupper($role);
}
return $this;
}
public function removeRole(string $role): self
{
if (false !== $key = array_search(strtoupper($role), $this->roles, true)) {
unset($this->roles[$key]);
$this->roles = array_values($this->roles);
}
return $this;
}
public function getUserRole()
{
$role = '';
if ($this->hasRole(UserRolesEnum::ROLE_ADMIN_LONG) || $this->hasRole(UserRolesEnum::ROLE_SUPER_ADMIN_LONG)) {
$role = UserRolesEnum::ROLE_ADMIN;
} elseif ($this->hasRole(UserRolesEnum::ROLE_MANAGER_LONG)) {
$role = UserRolesEnum::ROLE_MANAGER;
} elseif ($this->hasRole(UserRolesEnum::ROLE_ASSOCIATED_LONG)) {
$role = UserRolesEnum::ROLE_ASSOCIATED;
} elseif ($this->hasRole(UserRolesEnum::ROLE_ASSOCIATED_MANAGER_LONG)) {
$role = UserRolesEnum::ROLE_ASSOCIATED_MANAGER;
} elseif ($this->hasRole(UserRolesEnum::ROLE_COORDINATOR_LONG)) {
$role = UserRolesEnum::ROLE_COORDINATOR;
} elseif ($this->hasRole(UserRolesEnum::ROLE_PROVIDER_LONG)) {
$role = UserRolesEnum::ROLE_PROVIDER;
} elseif ($this->hasRole(UserRolesEnum::ROLE_QUALITY_ADVISOR_LONG)) {
$role = UserRolesEnum::ROLE_QUALITY_ADVISOR;
}
return $role;
}
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getToken(): ?string
{
return $this->token;
}
public function setToken(string $token): self
{
$this->token = $token;
return $this;
}
public function getSalt(): ?string
{
return $this->salt;
}
public function setSalt(?string $salt): self
{
$this->salt = $salt;
return $this;
}
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getUsernameCanonical(): ?string
{
return $this->usernameCanonical;
}
public function setUsernameCanonical(?string $usernameCanonical): self
{
$this->usernameCanonical = $usernameCanonical;
return $this;
}
public function getEmail(): string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = strtolower($email);
return $this;
}
public function getEmailCanonical(): ?string
{
return $this->emailCanonical;
}
public function setEmailCanonical(?string $emailCanonical): self
{
$this->emailCanonical = $emailCanonical;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
public function getZone(): ?string
{
return $this->zone;
}
public function setZone(?string $zone): self
{
$this->zone = $zone;
return $this;
}
public function getLastLogin(): ?\DateTimeInterface
{
return $this->lastLogin;
}
public function setLastLogin(?\DateTimeInterface $lastLogin): self
{
$this->lastLogin = $lastLogin;
return $this;
}
public function getLastOldLogin(): ?\DateTimeInterface
{
return $this->lastOldLogin;
}
public function setLastOldLogin(?\DateTimeInterface $lastOldLogin): self
{
$this->lastOldLogin = $lastOldLogin;
return $this;
}
public function getLastVisitOn(): ?\DateTimeInterface
{
return $this->lastVisitOn;
}
public function setLastVisitOn(?\DateTimeInterface $lastVisitOn): self
{
$this->lastVisitOn = $lastVisitOn;
return $this;
}
public function getPasswordRequestedAt(): ?\DateTimeInterface
{
return $this->passwordRequestedAt;
}
public function setPasswordRequestedAt(?\DateTimeInterface $passwordRequestedAt): self
{
$this->passwordRequestedAt = $passwordRequestedAt;
return $this;
}
public function getInternalDescription(): ?string
{
return $this->internalDescription;
}
public function setInternalDescription(?string $internalDescription): self
{
$this->internalDescription = $internalDescription;
return $this;
}
public function isEnabled(): bool
{
return $this->enabled;
}
public function getEnabled(): bool
{
return $this->isEnabled();
}
public function setEnabled(bool $enabled): self
{
$this->enabled = $enabled;
return $this;
}
public function isEnableStatisticsManagement(): bool
{
return $this->enableStatisticsManagement;
}
public function getEnableStatisticsManagement(): bool
{
return $this->isEnableStatisticsManagement();
}
public function setEnableStatisticsManagement(bool $enableStatisticsManagement): self
{
$this->enableStatisticsManagement = $enableStatisticsManagement;
return $this;
}
public function isReadedConfidentiality(): bool
{
return $this->readedConfidentiality;
}
public function setReadedConfidentiality(bool $readedConfidentiality): self
{
$this->readedConfidentiality = $readedConfidentiality;
return $this;
}
public function getReadedConfidentialityAt(): ?\DateTimeInterface
{
return $this->readedConfidentialityAt;
}
public function setReadedConfidentialityAt(?\DateTimeInterface $readedConfidentialityAt): self
{
$this->readedConfidentialityAt = $readedConfidentialityAt;
return $this;
}
public function getConfirmationToken(): string
{
return $this->confirmationToken;
}
public function setConfirmationToken(string $confirmationToken): self
{
$this->confirmationToken = $confirmationToken;
return $this;
}
public function belongsToUserGroup($userGroups): bool
{
$result = false;
if (null !== $userGroups && null !== $this->getUserGroup()) {
/** @var UserGroup $userGroup */
foreach ($userGroups as $userGroup) {
if ($userGroup->getId() === $this->getUserGroup()->getId()) {
$result = true;
break;
}
}
}
return $result;
}
public function belongsToUsers($users): bool
{
$result = false;
if (null !== $users) {
/** @var User $user */
foreach ($users as $user) {
if ($user->getId() === $this->getId()) {
$result = true;
break;
}
}
}
return $result;
}
public function getCatalogPointsAmount(): float
{
$catalogPointsAmount = 0.0;
/** @var CatalogPointMovement $pointMovement */
foreach ($this->pointMovements as $pointMovement) {
$catalogPointsAmount += $pointMovement->getPoints();
}
return $catalogPointsAmount;
}
public function getCatalogPointsAmountUntilDate(DateTime $date): float
{
$catalogPointsAmount = 0.0;
$dateStr = $date->format('Y-m-d');
/** @var CatalogPointMovement $pointMovement */
foreach ($this->pointMovements as $pointMovement) {
$pointMovementDateStr = $pointMovement->getDate()->format(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT);
if (strtotime($pointMovementDateStr) <= strtotime($dateStr)) {
$catalogPointsAmount += $pointMovement->getPoints();
}
}
return $catalogPointsAmount;
}
public function getOwnerEarnedPointsWithinCalendarYear(\DateTimeInterface $date): float
{
$catalogPointsAmount = 0.0;
$firstDate = \DateTimeImmutable::createFromFormat(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT, $date->format('Y').'-01-01');
$lastDate = \DateTimeImmutable::createFromFormat(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT, $date->format('Y').'-12-31');
$firstDateYearStr = $firstDate->format(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT);
$lastDateYearStr = $lastDate->format(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT);
/** @var CatalogPointMovement $pointMovement */
foreach ($this->pointMovements as $pointMovement) {
// if the pointMovement date is within the given calendar year
$pointMovementDateStr = $pointMovement->getDate()->format(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT);
// si son puntos positivos (los que gasta son negativos) y no es una devolucion
if ($pointMovementDateStr >= $firstDateYearStr && $pointMovementDateStr <= $lastDateYearStr && !$pointMovement->isReturnMovement() && ($pointMovement->getPoints() > 0.00001)) {
$catalogPointsAmount += $pointMovement->getPoints();
}
}
return $catalogPointsAmount;
}
public function getGarageEarnedPointsWithinCalendarYear(Garage $garage, \DateTimeInterface $date): float
{
$catalogPointsAmount = 0.0;
$firstDate = \DateTimeImmutable::createFromFormat(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT, $date->format('Y').'-01-01');
$lastDate = \DateTimeImmutable::createFromFormat(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT, $date->format('Y').'-12-31');
$firstDateYearStr = $firstDate->format(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT);
$lastDateYearStr = $lastDate->format(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT);
/** @var CatalogPointMovement $pointMovement */
foreach ($this->pointMovements as $pointMovement) {
// if the pointMovement belongs to the given garage
if ($pointMovement->getGarage() && $pointMovement->getGarage()->getId() === $garage->getId()) {
// if the pointMovement date is within the given calendar year
$pointMovementDateStr = $pointMovement->getDate()->format(MiniAbstractBase::DEFAULT_DATE_DATABASE_FORMAT);
// si son puntos positivos (los que gasta son negativos) y no es una devolucion
if ($pointMovementDateStr >= $firstDateYearStr && $pointMovementDateStr <= $lastDateYearStr && !$pointMovement->isReturnMovement() && ($pointMovement->getPoints() > 0.00001)) {
$catalogPointsAmount += $pointMovement->getPoints();
}
}
}
return $catalogPointsAmount;
}
public function __toString(): string
{
return $this->id ? $this->getUsername() : MiniAbstractBase::DEFAULT_EMPTY_STRING;
}
}