feat: implement staff management and subscription system
- Added StaffController for managing clinic staff, including listing, creating, updating, and toggling staff status. - Created ClinicStaff entity and repository for staff data handling. - Developed SubscriptionController to manage subscription plans and periods, including trial subscriptions. - Introduced SubscriptionPlan, SubscriptionPeriod, and ClinicSubscription entities for subscription management. - Implemented SubscriptionService for handling subscription logic, including trial activation and subscription creation from payments. - Added necessary repositories for subscription entities to facilitate data access and manipulation.
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Controller;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Clinic\Repository\ClinicRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
use App\Shared\Exception\AppException;
|
||||
use App\Subscription\Entity\SubscriptionPeriod;
|
||||
use App\Subscription\Entity\SubscriptionPlan;
|
||||
use App\Subscription\Repository\SubscriptionPlanRepository;
|
||||
use App\Subscription\Repository\SubscriptionPeriodRepository;
|
||||
use App\Subscription\Repository\ClinicSubscriptionRepository;
|
||||
use App\Subscription\Service\SubscriptionService;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\CurrentUser;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
class SubscriptionController extends BaseController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SubscriptionService $subscriptionService,
|
||||
private readonly SubscriptionPlanRepository $planRepo,
|
||||
private readonly SubscriptionPeriodRepository $periodRepo,
|
||||
private readonly ClinicSubscriptionRepository $subscriptionRepo,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
private readonly ClinicRepository $clinicRepo,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
// ── Public ──────────────────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/subscription/plans', methods: ['GET'])]
|
||||
public function plans(): JsonResponse
|
||||
{
|
||||
$plans = $this->planRepo->findAllActive();
|
||||
|
||||
return $this->success(array_map(
|
||||
fn(SubscriptionPlan $p) => $p->toArray(withPeriods: true),
|
||||
$plans
|
||||
));
|
||||
}
|
||||
|
||||
// ── Authenticated ────────────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/subscription/my', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function my(#[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$subscription = $this->subscriptionService->getActiveSubscription($entityType, $entityId);
|
||||
$usedTrial = $this->subscriptionService->hasUsedTrial($entityType, $entityId);
|
||||
|
||||
return $this->success([
|
||||
'subscription' => $subscription?->toArray(),
|
||||
'used_trial' => $usedTrial,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/subscription/trial', methods: ['POST'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function trial(#[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
try {
|
||||
$subscription = $this->subscriptionService->activateTrial($entityType, $entityId);
|
||||
} catch (AppException $e) {
|
||||
return $this->error($e->getErrorCode(), $e->getMessage(), $e->getHttpStatus());
|
||||
}
|
||||
|
||||
return $this->success($subscription->toArray(), 201);
|
||||
}
|
||||
|
||||
// ── Admin ────────────────────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/admin/subscription/plans', methods: ['GET'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function adminPlans(): JsonResponse
|
||||
{
|
||||
$plans = $this->planRepo->findAllActive();
|
||||
|
||||
return $this->paginated(
|
||||
array_map(fn(SubscriptionPlan $p) => $p->toArray(withPeriods: true), $plans),
|
||||
count($plans),
|
||||
1,
|
||||
100
|
||||
);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/subscription/plan', methods: ['POST'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function adminCreatePlan(Request $request): JsonResponse
|
||||
{
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
|
||||
$name = trim($data['name'] ?? '');
|
||||
if ($name === '' || !isset($data['level'])) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'name و level الزامی هستند', 422);
|
||||
}
|
||||
|
||||
$plan = new SubscriptionPlan(
|
||||
$name,
|
||||
(int) $data['level'],
|
||||
(int) ($data['max_secretaries'] ?? 1),
|
||||
$data['features'] ?? []
|
||||
);
|
||||
|
||||
$this->planRepo->save($plan);
|
||||
|
||||
return $this->success($plan->toArray(), 201);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/subscription/plan/{uuid}', methods: ['PATCH'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function adminUpdatePlan(string $uuid, Request $request): JsonResponse
|
||||
{
|
||||
$plan = $this->planRepo->findByUuid($uuid);
|
||||
if ($plan === null) {
|
||||
return $this->error(ErrorCodes::ERR_SUBSCRIPTION_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SUBSCRIPTION_NOT_FOUND), 404);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
|
||||
if (isset($data['name'])) { $plan->setName($data['name']); }
|
||||
if (isset($data['level'])) { $plan->setLevel((int) $data['level']); }
|
||||
if (isset($data['max_secretaries'])) { $plan->setMaxSecretaries((int) $data['max_secretaries']); }
|
||||
if (isset($data['features'])) { $plan->setFeatures($data['features']); }
|
||||
if (isset($data['active'])) { $plan->setActive((bool) $data['active']); }
|
||||
|
||||
$this->planRepo->save($plan);
|
||||
|
||||
return $this->success($plan->toArray());
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/subscription/period', methods: ['POST'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function adminCreatePeriod(Request $request): JsonResponse
|
||||
{
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
|
||||
$planUuid = $data['plan_uuid'] ?? '';
|
||||
$plan = $this->planRepo->findByUuid($planUuid);
|
||||
if ($plan === null) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'پنل یافت نشد', 404);
|
||||
}
|
||||
|
||||
if (empty($data['label']) || !isset($data['duration_months'])) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'label و duration_months الزامی هستند', 422);
|
||||
}
|
||||
|
||||
$period = new SubscriptionPeriod(
|
||||
$plan,
|
||||
$data['label'],
|
||||
(int) $data['duration_months'],
|
||||
(int) ($data['price_rials'] ?? 0),
|
||||
(bool) ($data['is_trial'] ?? false)
|
||||
);
|
||||
$period->setSortOrder((int) ($data['sort_order'] ?? 0));
|
||||
|
||||
$this->periodRepo->save($period);
|
||||
|
||||
return $this->success($period->toArray(), 201);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/subscription/period/{uuid}', methods: ['PATCH'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function adminUpdatePeriod(string $uuid, Request $request): JsonResponse
|
||||
{
|
||||
$period = $this->periodRepo->findByUuid($uuid);
|
||||
if ($period === null) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'دوره یافت نشد', 404);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
|
||||
if (isset($data['label'])) { $period->setLabel($data['label']); }
|
||||
if (isset($data['duration_months'])) { $period->setDurationMonths((int) $data['duration_months']); }
|
||||
if (isset($data['price_rials'])) { $period->setPriceRials((int) $data['price_rials']); }
|
||||
if (isset($data['active'])) { $period->setActive((bool) $data['active']); }
|
||||
if (isset($data['sort_order'])) { $period->setSortOrder((int) $data['sort_order']); }
|
||||
|
||||
$this->periodRepo->save($period);
|
||||
|
||||
return $this->success($period->toArray());
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/subscription/period/{uuid}', methods: ['DELETE'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function adminDeletePeriod(string $uuid): JsonResponse
|
||||
{
|
||||
$period = $this->periodRepo->findByUuid($uuid);
|
||||
if ($period === null) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'دوره یافت نشد', 404);
|
||||
}
|
||||
|
||||
$period->setActive(false);
|
||||
$this->periodRepo->save($period);
|
||||
|
||||
return $this->success(['message' => 'دوره غیرفعال شد']);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/subscription/report', methods: ['GET'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function adminReport(Request $request): JsonResponse
|
||||
{
|
||||
$page = max(1, (int) $request->query->get('page', 1));
|
||||
$limit = min(100, max(10, (int) $request->query->get('limit', 20)));
|
||||
|
||||
$total = (int) $this->em->createQuery('SELECT COUNT(s.id) FROM App\Subscription\Entity\ClinicSubscription s')
|
||||
->getSingleScalarResult();
|
||||
|
||||
$subscriptions = $this->em->createQuery('
|
||||
SELECT s.uuid, s.entityType, s.entityId, s.isTrial, s.startsAt, s.expiresAt, s.createdAt,
|
||||
p.name AS plan_name, p.level AS plan_level
|
||||
FROM App\Subscription\Entity\ClinicSubscription s
|
||||
JOIN s.plan p
|
||||
ORDER BY s.id DESC
|
||||
')
|
||||
->setFirstResult(($page - 1) * $limit)
|
||||
->setMaxResults($limit)
|
||||
->getArrayResult();
|
||||
|
||||
return $this->paginated($subscriptions, $total, $page, $limit);
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
private function resolveEntity(User $user): array
|
||||
{
|
||||
if ($user->hasRole('ROLE_DOCTOR')) {
|
||||
$doctor = $this->doctorRepo->findByUser($user);
|
||||
return $doctor !== null ? ['doctor', $doctor->getId()] : ['doctor', null];
|
||||
}
|
||||
|
||||
if ($user->hasRole('ROLE_CLINIC')) {
|
||||
$clinic = $this->clinicRepo->findByUser($user);
|
||||
return $clinic !== null ? ['clinic', $clinic->getId()] : ['clinic', null];
|
||||
}
|
||||
|
||||
return ['unknown', null];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Entity;
|
||||
|
||||
use App\Payment\Entity\Payment;
|
||||
use App\Subscription\Repository\ClinicSubscriptionRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: ClinicSubscriptionRepository::class)]
|
||||
#[ORM\Table(name: 'clinic_subscriptions')]
|
||||
#[ORM\Index(columns: ['entity_type', 'entity_id', 'expires_at'], name: 'idx_subscription_entity_expires')]
|
||||
class ClinicSubscription
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(name: 'entity_type', type: 'string', length: 10)]
|
||||
private string $entityType;
|
||||
|
||||
#[ORM\Column(name: 'entity_id', type: 'integer')]
|
||||
private int $entityId;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: SubscriptionPlan::class)]
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
private SubscriptionPlan $plan;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: SubscriptionPeriod::class)]
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
private SubscriptionPeriod $period;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Payment::class)]
|
||||
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
|
||||
private ?Payment $payment = null;
|
||||
|
||||
#[ORM\Column(name: 'is_trial', type: 'boolean')]
|
||||
private bool $isTrial = false;
|
||||
|
||||
#[ORM\Column(name: 'starts_at', type: 'integer')]
|
||||
private int $startsAt;
|
||||
|
||||
#[ORM\Column(name: 'expires_at', type: 'integer', nullable: true)]
|
||||
private ?int $expiresAt = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
public function __construct(
|
||||
string $entityType,
|
||||
int $entityId,
|
||||
SubscriptionPlan $plan,
|
||||
SubscriptionPeriod $period,
|
||||
bool $isTrial = false,
|
||||
?int $expiresAt = null,
|
||||
?Payment $payment = null
|
||||
) {
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->entityType = $entityType;
|
||||
$this->entityId = $entityId;
|
||||
$this->plan = $plan;
|
||||
$this->period = $period;
|
||||
$this->isTrial = $isTrial;
|
||||
$this->startsAt = time();
|
||||
$this->expiresAt = $expiresAt;
|
||||
$this->payment = $payment;
|
||||
$this->createdAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getEntityType(): string { return $this->entityType; }
|
||||
public function getEntityId(): int { return $this->entityId; }
|
||||
public function getPlan(): SubscriptionPlan { return $this->plan; }
|
||||
public function getPeriod(): SubscriptionPeriod { return $this->period; }
|
||||
public function getPayment(): ?Payment { return $this->payment; }
|
||||
public function isTrial(): bool { return $this->isTrial; }
|
||||
public function getStartsAt(): int { return $this->startsAt; }
|
||||
public function getExpiresAt(): ?int { return $this->expiresAt; }
|
||||
public function getCreatedAt(): int { return $this->createdAt; }
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->expiresAt === null || $this->expiresAt > time();
|
||||
}
|
||||
|
||||
public function getDaysRemaining(): ?int
|
||||
{
|
||||
if ($this->expiresAt === null) {
|
||||
return null;
|
||||
}
|
||||
$remaining = $this->expiresAt - time();
|
||||
return max(0, (int) ceil($remaining / 86400));
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'plan' => $this->plan->toArray(),
|
||||
'period' => $this->period->toArray(),
|
||||
'is_trial' => $this->isTrial,
|
||||
'starts_at' => $this->startsAt,
|
||||
'expires_at' => $this->expiresAt,
|
||||
'days_remaining' => $this->getDaysRemaining(),
|
||||
'is_active' => $this->isActive(),
|
||||
'created_at' => $this->createdAt,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Entity;
|
||||
|
||||
use App\Subscription\Repository\SubscriptionPeriodRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: SubscriptionPeriodRepository::class)]
|
||||
#[ORM\Table(name: 'subscription_periods')]
|
||||
class SubscriptionPeriod
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: SubscriptionPlan::class, inversedBy: 'periods')]
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
private SubscriptionPlan $plan;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 50)]
|
||||
private string $label;
|
||||
|
||||
#[ORM\Column(name: 'duration_months', type: 'smallint')]
|
||||
private int $durationMonths;
|
||||
|
||||
#[ORM\Column(name: 'price_rials', type: 'integer')]
|
||||
private int $priceRials = 0;
|
||||
|
||||
#[ORM\Column(name: 'is_trial', type: 'boolean')]
|
||||
private bool $isTrial = false;
|
||||
|
||||
#[ORM\Column(type: 'boolean')]
|
||||
private bool $active = true;
|
||||
|
||||
#[ORM\Column(name: 'sort_order', type: 'smallint')]
|
||||
private int $sortOrder = 0;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
public function __construct(SubscriptionPlan $plan, string $label, int $durationMonths, int $priceRials, bool $isTrial = false)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->plan = $plan;
|
||||
$this->label = $label;
|
||||
$this->durationMonths = $durationMonths;
|
||||
$this->priceRials = $priceRials;
|
||||
$this->isTrial = $isTrial;
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getPlan(): SubscriptionPlan { return $this->plan; }
|
||||
public function getLabel(): string { return $this->label; }
|
||||
public function getDurationMonths(): int { return $this->durationMonths; }
|
||||
public function getPriceRials(): int { return $this->priceRials; }
|
||||
public function isTrial(): bool { return $this->isTrial; }
|
||||
public function isActive(): bool { return $this->active; }
|
||||
public function getSortOrder(): int { return $this->sortOrder; }
|
||||
public function getCreatedAt(): int { return $this->createdAt; }
|
||||
public function getUpdatedAt(): int { return $this->updatedAt; }
|
||||
|
||||
public function setLabel(string $label): self { $this->label = $label; $this->updatedAt = time(); return $this; }
|
||||
public function setDurationMonths(int $v): self { $this->durationMonths = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setPriceRials(int $v): self { $this->priceRials = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setActive(bool $active): self { $this->active = $active; $this->updatedAt = time(); return $this; }
|
||||
public function setSortOrder(int $order): self { $this->sortOrder = $order; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'plan_uuid' => $this->plan->getUuid(),
|
||||
'label' => $this->label,
|
||||
'duration_months'=> $this->durationMonths,
|
||||
'price_rials' => $this->priceRials,
|
||||
'is_trial' => $this->isTrial,
|
||||
'active' => $this->active,
|
||||
'sort_order' => $this->sortOrder,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Entity;
|
||||
|
||||
use App\Subscription\Repository\SubscriptionPlanRepository;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity(repositoryClass: SubscriptionPlanRepository::class)]
|
||||
#[ORM\Table(name: 'subscription_plans')]
|
||||
class SubscriptionPlan
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 30, unique: true)]
|
||||
private string $name;
|
||||
|
||||
#[ORM\Column(type: 'smallint')]
|
||||
private int $level;
|
||||
|
||||
#[ORM\Column(name: 'max_secretaries', type: 'smallint')]
|
||||
private int $maxSecretaries = 1;
|
||||
|
||||
#[ORM\Column(type: 'json')]
|
||||
private array $features = [];
|
||||
|
||||
#[ORM\Column(type: 'boolean')]
|
||||
private bool $active = true;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
#[ORM\OneToMany(targetEntity: SubscriptionPeriod::class, mappedBy: 'plan')]
|
||||
private Collection $periods;
|
||||
|
||||
public function __construct(string $name, int $level, int $maxSecretaries, array $features)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->name = $name;
|
||||
$this->level = $level;
|
||||
$this->maxSecretaries = $maxSecretaries;
|
||||
$this->features = $features;
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
$this->periods = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getName(): string { return $this->name; }
|
||||
public function getLevel(): int { return $this->level; }
|
||||
public function getMaxSecretaries(): int { return $this->maxSecretaries; }
|
||||
public function getFeatures(): array { return $this->features; }
|
||||
public function isActive(): bool { return $this->active; }
|
||||
public function getCreatedAt(): int { return $this->createdAt; }
|
||||
public function getUpdatedAt(): int { return $this->updatedAt; }
|
||||
public function getPeriods(): Collection { return $this->periods; }
|
||||
|
||||
public function setName(string $name): self { $this->name = $name; $this->updatedAt = time(); return $this; }
|
||||
public function setLevel(int $level): self { $this->level = $level; $this->updatedAt = time(); return $this; }
|
||||
public function setMaxSecretaries(int $v): self { $this->maxSecretaries = $v; $this->updatedAt = time(); return $this; }
|
||||
public function setFeatures(array $features): self { $this->features = $features; $this->updatedAt = time(); return $this; }
|
||||
public function setActive(bool $active): self { $this->active = $active; $this->updatedAt = time(); return $this; }
|
||||
|
||||
public function hasFeature(string $feature): bool
|
||||
{
|
||||
return (bool) ($this->features[$feature] ?? false);
|
||||
}
|
||||
|
||||
public function toArray(bool $withPeriods = false): array
|
||||
{
|
||||
$data = [
|
||||
'uuid' => $this->uuid,
|
||||
'name' => $this->name,
|
||||
'level' => $this->level,
|
||||
'max_secretaries' => $this->maxSecretaries,
|
||||
'features' => $this->features,
|
||||
'active' => $this->active,
|
||||
];
|
||||
|
||||
if ($withPeriods) {
|
||||
$data['periods'] = array_map(
|
||||
fn(SubscriptionPeriod $p) => $p->toArray(),
|
||||
$this->periods->filter(fn(SubscriptionPeriod $p) => $p->isActive())->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Repository;
|
||||
|
||||
use App\Subscription\Entity\ClinicSubscription;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class ClinicSubscriptionRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, ClinicSubscription::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?ClinicSubscription
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
public function findActive(string $entityType, int $entityId): ?ClinicSubscription
|
||||
{
|
||||
return $this->createQueryBuilder('s')
|
||||
->where('s.entityType = :type')
|
||||
->andWhere('s.entityId = :id')
|
||||
->andWhere('s.expiresAt IS NULL OR s.expiresAt > :now')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->setParameter('now', time())
|
||||
->orderBy('s.id', 'DESC')
|
||||
->setMaxResults(1)
|
||||
->getQuery()
|
||||
->getOneOrNullResult();
|
||||
}
|
||||
|
||||
public function hasUsedTrial(string $entityType, int $entityId): bool
|
||||
{
|
||||
$count = $this->createQueryBuilder('s')
|
||||
->select('COUNT(s.id)')
|
||||
->where('s.entityType = :type')
|
||||
->andWhere('s.entityId = :id')
|
||||
->andWhere('s.isTrial = true')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->getQuery()
|
||||
->getSingleScalarResult();
|
||||
|
||||
return $count > 0;
|
||||
}
|
||||
|
||||
public function save(ClinicSubscription $subscription): void
|
||||
{
|
||||
$this->getEntityManager()->persist($subscription);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Repository;
|
||||
|
||||
use App\Subscription\Entity\SubscriptionPeriod;
|
||||
use App\Subscription\Entity\SubscriptionPlan;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class SubscriptionPeriodRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, SubscriptionPeriod::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?SubscriptionPeriod
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
public function findTrialPeriodForPlan(SubscriptionPlan $plan): ?SubscriptionPeriod
|
||||
{
|
||||
return $this->findOneBy(['plan' => $plan, 'isTrial' => true, 'active' => true]);
|
||||
}
|
||||
|
||||
public function save(SubscriptionPeriod $period): void
|
||||
{
|
||||
$this->getEntityManager()->persist($period);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Repository;
|
||||
|
||||
use App\Subscription\Entity\SubscriptionPlan;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class SubscriptionPlanRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, SubscriptionPlan::class);
|
||||
}
|
||||
|
||||
public function findByUuid(string $uuid): ?SubscriptionPlan
|
||||
{
|
||||
return $this->findOneBy(['uuid' => $uuid]);
|
||||
}
|
||||
|
||||
public function findByName(string $name): ?SubscriptionPlan
|
||||
{
|
||||
return $this->findOneBy(['name' => $name, 'active' => true]);
|
||||
}
|
||||
|
||||
public function findAllActive(): array
|
||||
{
|
||||
return $this->createQueryBuilder('p')
|
||||
->where('p.active = true')
|
||||
->orderBy('p.level', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
public function save(SubscriptionPlan $plan): void
|
||||
{
|
||||
$this->getEntityManager()->persist($plan);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Subscription\Service;
|
||||
|
||||
use App\Config\Repository\SiteConfigRepository;
|
||||
use App\Payment\Entity\Payment;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
use App\Subscription\Entity\ClinicSubscription;
|
||||
use App\Subscription\Repository\ClinicSubscriptionRepository;
|
||||
use App\Subscription\Repository\SubscriptionPeriodRepository;
|
||||
use App\Subscription\Repository\SubscriptionPlanRepository;
|
||||
|
||||
class SubscriptionService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClinicSubscriptionRepository $subscriptionRepo,
|
||||
private readonly SubscriptionPlanRepository $planRepo,
|
||||
private readonly SubscriptionPeriodRepository $periodRepo,
|
||||
private readonly SiteConfigRepository $configRepo,
|
||||
) {}
|
||||
|
||||
public function getActiveSubscription(string $entityType, int $entityId): ?ClinicSubscription
|
||||
{
|
||||
return $this->subscriptionRepo->findActive($entityType, $entityId);
|
||||
}
|
||||
|
||||
public function hasFeature(string $entityType, int $entityId, string $feature): bool
|
||||
{
|
||||
$subscription = $this->getActiveSubscription($entityType, $entityId);
|
||||
if ($subscription === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $subscription->getPlan()->hasFeature($feature);
|
||||
}
|
||||
|
||||
public function getSecretaryLimit(string $entityType, int $entityId): int
|
||||
{
|
||||
$subscription = $this->getActiveSubscription($entityType, $entityId);
|
||||
if ($subscription === null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return $subscription->getPlan()->getMaxSecretaries();
|
||||
}
|
||||
|
||||
public function hasUsedTrial(string $entityType, int $entityId): bool
|
||||
{
|
||||
return $this->subscriptionRepo->hasUsedTrial($entityType, $entityId);
|
||||
}
|
||||
|
||||
public function activateTrial(string $entityType, int $entityId): ClinicSubscription
|
||||
{
|
||||
if ($this->hasUsedTrial($entityType, $entityId)) {
|
||||
throw new AppException(ErrorCodes::ERR_TRIAL_ALREADY_USED, null, 422);
|
||||
}
|
||||
|
||||
$trialEnabled = $this->configRepo->get('trial_enabled');
|
||||
if ($trialEnabled === '0') {
|
||||
throw new AppException(ErrorCodes::ERR_TRIAL_DISABLED, null, 422);
|
||||
}
|
||||
|
||||
$basicPlan = $this->planRepo->findByName('basic');
|
||||
if ($basicPlan === null) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, null, 500);
|
||||
}
|
||||
|
||||
$trialPeriod = $this->periodRepo->findTrialPeriodForPlan($basicPlan);
|
||||
if ($trialPeriod === null) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, null, 500);
|
||||
}
|
||||
|
||||
$expiresAt = $this->calculateExpiresAt(null, $trialPeriod->getDurationMonths());
|
||||
|
||||
$subscription = new ClinicSubscription(
|
||||
$entityType,
|
||||
$entityId,
|
||||
$basicPlan,
|
||||
$trialPeriod,
|
||||
true,
|
||||
$expiresAt,
|
||||
null
|
||||
);
|
||||
|
||||
$this->subscriptionRepo->save($subscription);
|
||||
|
||||
return $subscription;
|
||||
}
|
||||
|
||||
public function createFromPayment(Payment $payment, string $entityType, int $entityId, string $periodUuid): ClinicSubscription
|
||||
{
|
||||
$period = $this->periodRepo->findByUuid($periodUuid);
|
||||
if ($period === null) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, null, 404);
|
||||
}
|
||||
|
||||
$currentSub = $this->getActiveSubscription($entityType, $entityId);
|
||||
$currentExpires = $currentSub?->getExpiresAt();
|
||||
|
||||
$expiresAt = $this->calculateExpiresAt($currentExpires, $period->getDurationMonths());
|
||||
|
||||
$subscription = new ClinicSubscription(
|
||||
$entityType,
|
||||
$entityId,
|
||||
$period->getPlan(),
|
||||
$period,
|
||||
false,
|
||||
$expiresAt,
|
||||
$payment
|
||||
);
|
||||
|
||||
$this->subscriptionRepo->save($subscription);
|
||||
|
||||
return $subscription;
|
||||
}
|
||||
|
||||
public function calculateExpiresAt(?int $currentExpiresAt, int $durationMonths): int
|
||||
{
|
||||
$base = max($currentExpiresAt ?? 0, time());
|
||||
return $base + $durationMonths * 30 * 86400;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user