<?php
namespace App\Entity;
use App\Entity\Account\Avatar;
use App\Entity\Location\City;
use App\Entity\Sales\AccountCharge;
use App\Entity\Sales\AccountEnrollment;
use App\Entity\Sales\AccountTransaction;
use App\PaymentProcessing\Exception\CurrencyMismatchException;
use App\PaymentProcessing\Exception\NotEnoughMoneyException;
use App\Repository\UserRepository;
use App\Service\CountryCurrencyResolver;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Money\Currency;
use Money\Money;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
//use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[UniqueEntity(fields: ['email'], groups: ['Registration'])]
#[UniqueEntity(fields: ['nickName'], groups: ['Registration'])] // //Vich\Uploadable
#[ORM\HasLifecycleCallbacks]
#[ORM\InheritanceType('SINGLE_TABLE')]
#[ORM\DiscriminatorColumn(name: 'type', type: 'string', length: 12)]
#[ORM\DiscriminatorMap(['advertiser' => Account\Advertiser::class, 'customer' => Account\Customer::class])]
abstract class User implements UserInterface, \Serializable
{
public const ROLE_USER = 'ROLE_USER';
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private int $id;
#[ORM\Column(type: 'string', length: 180, unique: true)]
#[Assert\NotBlank(groups: ['Registration'])]
#[Assert\Email(groups: ['Registration'])]
private ?string $email = null;
#[ORM\Column(type: 'string', length: 100)]
#[Assert\NotBlank(groups: ['Registration'])]
#[Assert\Length(max: 64, groups: ['Registration'])]
private ?string $nickName = null;
#[ORM\Column(type: 'text', nullable: true)]
private ?string $notes = null;
#[ORM\Column(name: 'country_code', type: 'string', length: 2)]
private string $country;
#[ORM\JoinColumn(name: 'city_id', referencedColumnName: 'id')]
#[ORM\ManyToOne(targetEntity: City::class)]
private ?City $city = null;
#[ORM\OneToOne(targetEntity: Avatar::class, mappedBy: 'user', cascade: ['all'], orphanRemoval: true)]
protected ?Avatar $avatar;
#[ORM\Column(type: 'json')]
private array $roles = [];
/** The hashed password*/
#[ORM\Column(type: 'string')]
private string $password;
#[Assert\NotBlank(groups: ['Registration'])]
private ?string $plainPassword = null;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private ?string $confirmationCode;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private ?string $smscCode;
#[ORM\Column(type: 'boolean')]
private bool $enabled;
#[ORM\Column(type: 'boolean')]
private bool $trusted = false;
#[ORM\Column(name: 'credits', type: 'integer')]
private int $credits = 0;
/**
* Валюта для финансовых операций аккаунта.
* Устанавливается при регистрации в зависимости от выбранной страны, и не может быть изменена через кабинет.
*/
#[ORM\Column(name: 'currency_code', type: 'string', length: 3)]
private string $currencyCode;
#[ORM\Column(type: 'boolean', options: ['default' => 1])]
private bool $fullRegistered = true;
#[ORM\Column(type: 'integer', options: ['default' => 0])]
private int $postRegistrationStep = 0;
/** @var AccountEnrollment[] */
#[ORM\OneToMany(targetEntity: AccountEnrollment::class, mappedBy: 'account')]
private Collection $enrollments;
/** @var AccountCharge[] */
#[ORM\OneToMany(targetEntity: AccountCharge::class, mappedBy: 'account')]
private Collection $charges;
/** @var AccountTransaction[] */
#[ORM\OneToMany(targetEntity: AccountTransaction::class, mappedBy: 'account')]
private Collection $transactions;
#[ORM\Column(name: 'created', type: 'datetime')]
private \DateTimeInterface $created;
#[ORM\Column(name: 'updated', type: 'datetime', nullable: true)]
private ?\DateTimeInterface $updated;
#[ORM\Column(name: 'balance_low_notified_at', type: 'datetime', nullable: true)]
private ?\DateTimeInterface $lowBalanceNotifiedAt;
#[ORM\Column(name: 'ban', type: 'string', length: 5, nullable: true)]
private ?string $ban = null;
#[ORM\OneToOne(targetEntity: OfferBarHidden::class, cascade: ['all'], mappedBy: 'account')]
private ?OfferBarHidden $offerBarHidden;
public function __construct()
{
$this->roles = [self::ROLE_USER];
$this->enabled = false;
$this->enrollments = new ArrayCollection();
$this->charges = new ArrayCollection();
$this->transactions = new ArrayCollection();
//TODO temp
$this->created = new \DateTime();
$this->updated = new \DateTime();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): void
{
$this->email = $email;
}
public function getNickName(): ?string
{
return $this->nickName;
}
public function setNickName(string $nickName): void
{
$this->nickName = $nickName;
}
public function getCountry(): ?string
{
return $this->country;
}
public function setCountry($country): void
{
$this->country = $country;
}
public function getCity(): ?City
{
return $this->city;
}
public function setCity(City $city): void
{
$this->city = $city;
$this->country = $city->getCountryCode();
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string)$this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string)$this->password;
}
public function setPassword(string $password): void
{
$this->password = $password;
}
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
public function setPlainPassword(string $plainPassword): void
{
$this->plainPassword = $plainPassword;
}
public function getConfirmationCode(): string
{
return $this->confirmationCode;
}
public function setConfirmationCode(string $confirmationCode): void
{
$this->confirmationCode = $confirmationCode;
}
public function getSmscCode(): string
{
return $this->smscCode;
}
public function setSmscCode(string $smscCode): void
{
$this->smscCode = $smscCode;
}
public function isEnabled(): bool
{
return $this->enabled;
}
public function setEnabled(bool $enabled): void
{
$this->enabled = $enabled;
}
public function isTrusted(): bool
{
return $this->trusted;
}
public function setTrusted(bool $trusted): void
{
$this->trusted = $trusted;
}
public function isFullRegistered(): bool
{
return $this->fullRegistered;
}
public function setFullRegistered(bool $fullRegistered): void
{
$this->fullRegistered = $fullRegistered;
}
/**
* Зачисляет деньги на счет аккаунта
*
* @param Money $toEnroll
*
* @throws \DomainException Если указана отрицательная или нулевая сумма
* @throws CurrencyMismatchException Если валюты баланса и суммы зачисления не совпадают
*/
public function enroll(Money $toEnroll): void
{
if ($toEnroll->isNegative() || $toEnroll->isZero()) {
throw new \DomainException('Can not enroll negative or zero amount.');
}
$currentBalance = $this->getCurrentBalance();
if (!$currentBalance->isSameCurrency($toEnroll)) {
throw new CurrencyMismatchException();
}
$newBalance = $currentBalance->add($toEnroll);
$this->credits = $newBalance->getAmount();
}
/**
* Списывает деньги со счета аккаунта
*
* @param Money $toCharge
* @param bool $withOverdraft Возможность делать отрицательный баланс для ручных списаний
*
* @throws \DomainException Если указана отрицательная или нулевая сумма
* @throws CurrencyMismatchException Если валюты баланса и суммы списания не совпадают
* @throws NotEnoughMoneyException Если на счету недостаточно средств
*/
public function charge(Money $toCharge, bool $withOverdraft = false): void
{
if ($toCharge->isNegative() || $toCharge->isZero()) {
throw new \DomainException('Can not charge negative or zero amount.');
}
$currentBalance = $this->getCurrentBalance();
if (!$currentBalance->isSameCurrency($toCharge)) {
throw new CurrencyMismatchException();
}
if ($currentBalance->lessThan($toCharge) && !$withOverdraft) {
throw new NotEnoughMoneyException();
}
$newBalance = $currentBalance->subtract($toCharge);
$this->credits = $newBalance->getAmount();
}
public function getCurrentBalance(): Money
{
return new Money($this->credits, new Currency($this->currencyCode));
}
public function getCurrencyCode(): string
{
return $this->currencyCode;
}
public function resolveCurrency(CountryCurrencyResolver $currencyResolver): void
{
$this->currencyCode = $currencyResolver->getCurrencyFor($this->country);
}
/**
* @return AccountEnrollment[]
*/
public function getEnrollments(): Collection
{
return $this->enrollments;
}
/**
* @return AccountCharge[]
*/
public function getCharges(): Collection
{
return $this->charges;
}
/**
* @return AccountTransaction[]
*/
public function getTransactions(): Collection
{
return $this->transactions;
}
/**
* @see UserInterface
*/
public function getSalt(): void
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials(): void
{
// If you store any temporary, sensitive data on the user, clear it here
$this->plainPassword = null;
}
public function getCreated(): \DateTimeInterface
{
return $this->created;
}
/**
* @inheritDoc
*/
public function serialize()
{
return \serialize([
$this->id,
$this->email,
$this->password,
$this->roles,
$this->enabled,
]);
}
/**
* @inheritDoc
*/
public function unserialize($serialized): void
{
list(
$this->id,
$this->email,
$this->password,
$this->roles,
$this->enabled
) = \unserialize($serialized, ['allowed_classes' => false]);
}
public function getNotes(): ?string
{
return $this->notes;
}
public function setNotes(?string $notes): void
{
$this->notes = $notes;
}
public function isBanned(): bool
{
return null != $this->ban;
}
public function getBan(): ?string
{
return $this->ban;
}
public function setBan(?string $ban): void
{
$this->ban = $ban;
}
public function isLowBalanceNotified(): bool
{
return $this->lowBalanceNotifiedAt != null;
}
public function setLowBalanceNotified(?\DateTimeInterface $dateTime): void
{
$this->lowBalanceNotifiedAt = $dateTime;
}
public function getAvatar(): ?Avatar
{
return $this->avatar;
}
public function setAvatar(string $path): void
{
$this->avatar = new Avatar($this, $path);
}
public function getPostRegistrationStep(): int
{
return $this->postRegistrationStep;
}
public function setPostRegistrationStep(int $postRegistrationStep): void
{
$this->postRegistrationStep = $postRegistrationStep;
}
public function offerBarHidden(): ?OfferBarHidden
{
return $this->offerBarHidden;
}
public function setOfferBarHidden(): void
{
if (null !== $this->offerBarHidden) {
return;
}
$this->offerBarHidden = new OfferBarHidden($this);
}
}