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:
hamed
2026-06-14 22:10:28 +03:30
parent dcd631f503
commit b0244f28f5
53 changed files with 4434 additions and 40 deletions
+218
View File
@@ -0,0 +1,218 @@
<?php
namespace App\Sms\Controller;
use App\Auth\Entity\User;
use App\Clinic\Repository\ClinicRepository;
use App\Config\Repository\SiteConfigRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Payment\Entity\Payment;
use App\Payment\Gateway\MellatGateway;
use App\Payment\Gateway\SepGateway;
use App\Payment\Repository\PaymentRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Sms\Entity\SmsSettings;
use App\Sms\Repository\SmsSettingsRepository;
use App\Sms\Repository\SmsWalletRepository;
use App\Sms\Repository\SmsWalletTransactionRepository;
use App\Sms\Service\SmsWalletService;
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;
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class SmsWalletController extends BaseController
{
public function __construct(
private readonly SmsWalletService $walletService,
private readonly SmsWalletRepository $walletRepo,
private readonly SmsWalletTransactionRepository $txRepo,
private readonly SmsSettingsRepository $settingsRepo,
private readonly PaymentRepository $paymentRepo,
private readonly SiteConfigRepository $configRepo,
private readonly MellatGateway $mellat,
private readonly SepGateway $sep,
private readonly DoctorRepository $doctorRepo,
private readonly ClinicRepository $clinicRepo,
private readonly string $appBaseUrl,
) {}
#[Route('/api/v1/sms/wallet/balance', methods: ['GET'])]
public function balance(#[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
if ($entityId === null) {
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
}
$balanceRials = $this->walletService->getBalance($entityType, $entityId);
$smsPriceRials = (int) ($this->configRepo->get('sms_price_rials') ?? 500);
$estimatedSms = $smsPriceRials > 0 ? (int) floor($balanceRials / $smsPriceRials) : 0;
return $this->success([
'balance_rials' => $balanceRials,
'sms_price_rials' => $smsPriceRials,
'estimated_sms_count' => $estimatedSms,
]);
}
#[Route('/api/v1/sms/wallet/charge', methods: ['POST'])]
public function charge(Request $request, #[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
if ($entityId === null) {
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
}
$data = json_decode($request->getContent(), true) ?? [];
$gatewayName = trim($data['gateway'] ?? 'mellat');
$amountRials = (int) ($data['amount_rials'] ?? 0);
if ($amountRials <= 0) {
return $this->error(ErrorCodes::ERR_PAYMENT_002, 'مبلغ شارژ نامعتبر است', 422);
}
$gateway = match ($gatewayName) {
'mellat' => $this->mellat,
'sep' => $this->sep,
default => null,
};
if ($gateway === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'درگاه پرداخت نامعتبر است', 422);
}
$frontendAddress = trim($data['frontend_address'] ?? '');
$payment = new Payment($user, $amountRials, $gatewayName, Payment::TYPE_SMS_WALLET, $frontendAddress);
$payment->setMetadata(['entity_type' => $entityType, 'entity_id' => $entityId]);
$this->paymentRepo->save($payment);
$callbackUrl = $this->appBaseUrl . '/api/v1/payment/callback/' . $gatewayName . '?order_id=' . $payment->getOrderId();
$result = $gateway->initiate($amountRials, $payment->getOrderId(), $callbackUrl);
if (!$result->success) {
return $this->error(ErrorCodes::ERR_PAYMENT_001, $result->errorMessage ?? 'درگاه در دسترس نیست', 503);
}
$payment->setGatewayToken($result->token);
$this->paymentRepo->save($payment);
return $this->success([
'payment_uuid' => $payment->getUuid(),
'redirect_url' => $result->redirectUrl,
'order_id' => $payment->getOrderId(),
]);
}
#[Route('/api/v1/sms/wallet/logs', methods: ['GET'])]
public function logs(Request $request, #[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
if ($entityId === null) {
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
}
$page = max(1, (int) $request->query->get('page', 1));
$limit = min(50, max(10, (int) $request->query->get('limit', 20)));
$wallet = $this->walletService->getOrCreate($entityType, $entityId);
$txs = $this->txRepo->findByWallet($wallet, $page, $limit);
$total = $this->txRepo->countByWallet($wallet);
return $this->paginated(
array_map(fn($tx) => $tx->toArray(), $txs),
$total,
$page,
$limit
);
}
#[Route('/api/v1/sms/settings', methods: ['GET'])]
public function getSettings(#[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
if ($entityId === null) {
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
}
$settings = $this->settingsRepo->findByEntity($entityType, $entityId);
if ($settings === null) {
return $this->success([
'entity_type' => $entityType,
'entity_id' => $entityId,
'reminder_enabled' => false,
'reminder_hours_before' => 2,
'post_visit_enabled' => false,
'post_visit_text' => null,
]);
}
return $this->success($settings->toArray());
}
#[Route('/api/v1/sms/settings', methods: ['PATCH'])]
public function updateSettings(Request $request, #[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->resolveEntity($user);
if ($entityId === null) {
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
}
$settings = $this->settingsRepo->findByEntity($entityType, $entityId);
if ($settings === null) {
$settings = new SmsSettings($entityType, $entityId);
}
$data = json_decode($request->getContent(), true) ?? [];
if (isset($data['reminder_enabled'])) { $settings->setReminderEnabled((bool) $data['reminder_enabled']); }
if (isset($data['reminder_hours_before'])) { $settings->setReminderHoursBefore((int) $data['reminder_hours_before']); }
if (isset($data['post_visit_enabled'])) { $settings->setPostVisitEnabled((bool) $data['post_visit_enabled']); }
if (array_key_exists('post_visit_text', $data)) { $settings->setPostVisitText($data['post_visit_text']); }
$this->settingsRepo->save($settings);
return $this->success($settings->toArray());
}
#[Route('/api/v1/admin/sms/wallet-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->walletRepo->createQueryBuilder('w')
->select('COUNT(w.id)')
->getQuery()
->getSingleScalarResult();
$wallets = $this->walletRepo->createQueryBuilder('w')
->orderBy('w.balanceRials', 'DESC')
->setFirstResult(($page - 1) * $limit)
->setMaxResults($limit)
->getQuery()
->getArrayResult();
return $this->paginated($wallets, $total, $page, $limit);
}
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];
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Sms\Entity;
use App\Sms\Repository\SmsSettingsRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SmsSettingsRepository::class)]
#[ORM\Table(name: 'sms_settings')]
#[ORM\UniqueConstraint(name: 'uniq_sms_settings_entity', columns: ['entity_type', 'entity_id'])]
class SmsSettings
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(name: 'entity_type', type: 'string', length: 10)]
private string $entityType;
#[ORM\Column(name: 'entity_id', type: 'integer')]
private int $entityId;
#[ORM\Column(name: 'reminder_enabled', type: 'boolean')]
private bool $reminderEnabled = false;
#[ORM\Column(name: 'reminder_hours_before', type: 'smallint')]
private int $reminderHoursBefore = 2;
#[ORM\Column(name: 'post_visit_enabled', type: 'boolean')]
private bool $postVisitEnabled = false;
#[ORM\Column(name: 'post_visit_text', type: 'text', nullable: true)]
private ?string $postVisitText = null;
#[ORM\Column(name: 'updated_at', type: 'integer')]
private int $updatedAt;
public function __construct(string $entityType, int $entityId)
{
$this->entityType = $entityType;
$this->entityId = $entityId;
$this->updatedAt = time();
}
public function getId(): ?int { return $this->id; }
public function getEntityType(): string { return $this->entityType; }
public function getEntityId(): int { return $this->entityId; }
public function isReminderEnabled(): bool { return $this->reminderEnabled; }
public function getReminderHoursBefore(): int { return $this->reminderHoursBefore; }
public function isPostVisitEnabled(): bool { return $this->postVisitEnabled; }
public function getPostVisitText(): ?string { return $this->postVisitText; }
public function setReminderEnabled(bool $v): self { $this->reminderEnabled = $v; $this->updatedAt = time(); return $this; }
public function setReminderHoursBefore(int $v): self { $this->reminderHoursBefore = $v; $this->updatedAt = time(); return $this; }
public function setPostVisitEnabled(bool $v): self { $this->postVisitEnabled = $v; $this->updatedAt = time(); return $this; }
public function setPostVisitText(?string $v): self { $this->postVisitText = $v; $this->updatedAt = time(); return $this; }
public function toArray(): array
{
return [
'entity_type' => $this->entityType,
'entity_id' => $this->entityId,
'reminder_enabled' => $this->reminderEnabled,
'reminder_hours_before' => $this->reminderHoursBefore,
'post_visit_enabled' => $this->postVisitEnabled,
'post_visit_text' => $this->postVisitText,
'updated_at' => $this->updatedAt,
];
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace App\Sms\Entity;
use App\Sms\Repository\SmsWalletRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: SmsWalletRepository::class)]
#[ORM\Table(name: 'sms_wallets')]
#[ORM\UniqueConstraint(name: 'uniq_sms_wallet_entity', columns: ['entity_type', 'entity_id'])]
class SmsWallet
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(name: 'entity_type', type: 'string', length: 10)]
private string $entityType;
#[ORM\Column(name: 'entity_id', type: 'integer')]
private int $entityId;
#[ORM\Column(name: 'balance_rials', type: 'integer')]
private int $balanceRials = 0;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
#[ORM\Column(name: 'updated_at', type: 'integer')]
private int $updatedAt;
public function __construct(string $entityType, int $entityId)
{
$this->entityType = $entityType;
$this->entityId = $entityId;
$this->createdAt = time();
$this->updatedAt = time();
}
public function getId(): ?int { return $this->id; }
public function getEntityType(): string { return $this->entityType; }
public function getEntityId(): int { return $this->entityId; }
public function getBalanceRials(): int { return $this->balanceRials; }
public function credit(int $amount): void
{
$this->balanceRials += $amount;
$this->updatedAt = time();
}
public function debit(int $amount): bool
{
if ($this->balanceRials < $amount) {
return false;
}
$this->balanceRials -= $amount;
$this->updatedAt = time();
return true;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Sms\Entity;
use App\Payment\Entity\Payment;
use App\Sms\Repository\SmsWalletTransactionRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
#[ORM\Entity(repositoryClass: SmsWalletTransactionRepository::class)]
#[ORM\Table(name: 'sms_wallet_transactions')]
class SmsWalletTransaction
{
public const TYPE_CREDIT = 'credit';
public const TYPE_DEBIT = 'debit';
#[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: SmsWallet::class)]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
private SmsWallet $wallet;
#[ORM\Column(type: 'string', length: 10)]
private string $type;
#[ORM\Column(name: 'amount_rials', type: 'integer')]
private int $amountRials;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private ?string $description = null;
#[ORM\ManyToOne(targetEntity: Payment::class)]
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
private ?Payment $payment = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
public function __construct(SmsWallet $wallet, string $type, int $amountRials, ?string $description = null, ?Payment $payment = null)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->wallet = $wallet;
$this->type = $type;
$this->amountRials = $amountRials;
$this->description = $description;
$this->payment = $payment;
$this->createdAt = time();
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getType(): string { return $this->type; }
public function getAmountRials(): int { return $this->amountRials; }
public function getDescription(): ?string { return $this->description; }
public function getCreatedAt(): int { return $this->createdAt; }
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'type' => $this->type,
'amount_rials' => $this->amountRials,
'description' => $this->description,
'created_at' => $this->createdAt,
];
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Sms\Repository;
use App\Sms\Entity\SmsSettings;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class SmsSettingsRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, SmsSettings::class);
}
public function findByEntity(string $entityType, int $entityId): ?SmsSettings
{
return $this->findOneBy(['entityType' => $entityType, 'entityId' => $entityId]);
}
public function save(SmsSettings $settings): void
{
$this->getEntityManager()->persist($settings);
$this->getEntityManager()->flush();
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Sms\Repository;
use App\Sms\Entity\SmsWallet;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class SmsWalletRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, SmsWallet::class);
}
public function findByEntity(string $entityType, int $entityId): ?SmsWallet
{
return $this->findOneBy(['entityType' => $entityType, 'entityId' => $entityId]);
}
public function getBalance(string $entityType, int $entityId): int
{
$wallet = $this->findByEntity($entityType, $entityId);
return $wallet?->getBalanceRials() ?? 0;
}
public function save(SmsWallet $wallet): void
{
$this->getEntityManager()->persist($wallet);
$this->getEntityManager()->flush();
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Sms\Repository;
use App\Sms\Entity\SmsWallet;
use App\Sms\Entity\SmsWalletTransaction;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class SmsWalletTransactionRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, SmsWalletTransaction::class);
}
public function findByWallet(SmsWallet $wallet, int $page = 1, int $limit = 20): array
{
return $this->createQueryBuilder('t')
->where('t.wallet = :wallet')
->setParameter('wallet', $wallet)
->orderBy('t.id', 'DESC')
->setFirstResult(($page - 1) * $limit)
->setMaxResults($limit)
->getQuery()
->getResult();
}
public function countByWallet(SmsWallet $wallet): int
{
return (int) $this->createQueryBuilder('t')
->select('COUNT(t.id)')
->where('t.wallet = :wallet')
->setParameter('wallet', $wallet)
->getQuery()
->getSingleScalarResult();
}
public function save(SmsWalletTransaction $tx): void
{
$this->getEntityManager()->persist($tx);
$this->getEntityManager()->flush();
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Sms\Service;
use App\Payment\Entity\Payment;
use App\Sms\Entity\SmsWallet;
use App\Sms\Entity\SmsWalletTransaction;
use App\Sms\Repository\SmsWalletRepository;
use App\Sms\Repository\SmsWalletTransactionRepository;
class SmsWalletService
{
public function __construct(
private readonly SmsWalletRepository $walletRepo,
private readonly SmsWalletTransactionRepository $txRepo,
) {}
public function getOrCreate(string $entityType, int $entityId): SmsWallet
{
$wallet = $this->walletRepo->findByEntity($entityType, $entityId);
if ($wallet === null) {
$wallet = new SmsWallet($entityType, $entityId);
$this->walletRepo->save($wallet);
}
return $wallet;
}
public function charge(SmsWallet $wallet, int $amountRials, Payment $payment): void
{
$wallet->credit($amountRials);
$this->walletRepo->save($wallet);
$tx = new SmsWalletTransaction(
$wallet,
SmsWalletTransaction::TYPE_CREDIT,
$amountRials,
'شارژ کیف پیامک',
$payment
);
$this->txRepo->save($tx);
}
public function deduct(SmsWallet $wallet, int $amountRials, string $description): bool
{
if (!$wallet->debit($amountRials)) {
return false;
}
$this->walletRepo->save($wallet);
$tx = new SmsWalletTransaction(
$wallet,
SmsWalletTransaction::TYPE_DEBIT,
$amountRials,
$description,
null
);
$this->txRepo->save($tx);
return true;
}
public function getBalance(string $entityType, int $entityId): int
{
return $this->walletRepo->getBalance($entityType, $entityId);
}
}