feat(migrations): add ownership fields to doctors table for IRIMC import
- Introduced new columns: owner_status, source, source_ref, managed_by, and claimed_at to the doctors table. - Created indexes for owner_status and source to optimize queries related to unclaimed doctors. feat(auth): implement SystemOwnerCommand for managing system-owner user - Added command to create, activate, and deactivate a system-owner user for IRIMC crawler. - Ensured the user has ROLE_ADMIN to access import endpoints. - Handled password setting and user status management within the command.
This commit is contained in:
@@ -10,6 +10,7 @@ use App\Shared\Service\InputValidator;
|
||||
use App\Location\Entity\City;
|
||||
use App\Clinic\Entity\Clinic;
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Location\Entity\Province;
|
||||
use App\Specialty\Entity\Specialty;
|
||||
use App\Payment\Entity\Payment;
|
||||
use App\Rating\Entity\Comment;
|
||||
@@ -28,6 +29,7 @@ use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\CurrentUser;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
#[OA\Tag(name: 'Admin')]
|
||||
@@ -442,6 +444,129 @@ class AdminApiController extends BaseController
|
||||
return $this->success(['uuid' => $doctor->getUuid()], 201);
|
||||
}
|
||||
|
||||
/**
|
||||
* ایمپورت یک پزشک از سازمان نظام پزشکی (بدون شماره موبایل).
|
||||
*
|
||||
* برخلاف createDoctor، این اندپوینت موبایل نمیخواهد: برای هر پزشک یک «کاربر
|
||||
* جانشین» غیرفعال با شناسهٔ مصنوعی ساخته میشود و پروفایل در وضعیت unclaimed
|
||||
* ذخیره میگردد تا بعداً به پزشک واقعی منتقل شود. idempotent بر پایهٔ
|
||||
* (source, medical_system_code): اجرای مجدد، رکورد موجود را بهروزرسانی میکند.
|
||||
*/
|
||||
#[OA\Post(
|
||||
path: '/api/v1/admin/doctors/import',
|
||||
summary: 'Import an IRIMC doctor without a mobile number (unclaimed profile)',
|
||||
security: [['bearerAuth' => []]],
|
||||
requestBody: new OA\RequestBody(
|
||||
required: true,
|
||||
content: new OA\JsonContent(
|
||||
required: ['name', 'medical_system_code'],
|
||||
properties: [
|
||||
new OA\Property(property: 'name', type: 'string'),
|
||||
new OA\Property(property: 'medical_system_code', type: 'string'),
|
||||
new OA\Property(property: 'source', type: 'string', default: 'irimc'),
|
||||
new OA\Property(property: 'source_ref', type: 'string', nullable: true, description: 'profile_url یا شناسهٔ مبدأ'),
|
||||
new OA\Property(property: 'gender', type: 'string', nullable: true),
|
||||
new OA\Property(property: 'degree', type: 'string', nullable: true),
|
||||
new OA\Property(property: 'info', type: 'string', nullable: true),
|
||||
new OA\Property(property: 'specialties', type: 'array', items: new OA\Items(type: 'integer'), nullable: true),
|
||||
new OA\Property(property: 'states', type: 'array', items: new OA\Items(type: 'integer'), nullable: true),
|
||||
new OA\Property(property: 'cities', type: 'array', items: new OA\Items(type: 'integer'), nullable: true),
|
||||
]
|
||||
)
|
||||
),
|
||||
responses: [
|
||||
new OA\Response(response: 201, description: 'Doctor imported (created)'),
|
||||
new OA\Response(response: 200, description: 'Doctor already existed (updated or skipped)'),
|
||||
new OA\Response(response: 422, description: 'Validation error'),
|
||||
]
|
||||
)]
|
||||
#[Route('/api/v1/admin/doctors/import', methods: ['POST'])]
|
||||
public function importDoctor(Request $request, #[CurrentUser] User $admin): JsonResponse
|
||||
{
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$name = trim((string) ($data['name'] ?? ''));
|
||||
$code = trim((string) ($data['medical_system_code'] ?? $data['medicalSystemCode'] ?? ''));
|
||||
$source = trim((string) ($data['source'] ?? 'irimc')) ?: 'irimc';
|
||||
|
||||
if ($name === '') {
|
||||
return $this->error(ErrorCodes::VALIDATION, 'نام الزامی است', 422, 'name');
|
||||
}
|
||||
if ($code === '') {
|
||||
return $this->error(ErrorCodes::VALIDATION, 'کد نظام پزشکی الزامی است', 422, 'medical_system_code');
|
||||
}
|
||||
|
||||
$doctorRepo = $this->em->getRepository(Doctor::class);
|
||||
$userRepo = $this->em->getRepository(User::class);
|
||||
|
||||
// idempotency: همان پزشکِ منبع → بهروزرسانی، نه ساخت تکراری
|
||||
$doctor = $doctorRepo->findOneBy(['source' => $source, 'medicalSystemCode' => $code]);
|
||||
$created = false;
|
||||
|
||||
// پروفایل تصاحبشده را با ایمپورت مجدد بازنویسی نکن (مالک واقعی اولویت دارد)
|
||||
if ($doctor !== null && $doctor->getOwnerStatus() === 'claimed') {
|
||||
return $this->success(['uuid' => $doctor->getUuid(), 'created' => false, 'skipped' => 'claimed']);
|
||||
}
|
||||
|
||||
if ($doctor === null) {
|
||||
// کاربر جانشینِ یکتا و غیرفعال؛ شناسهٔ مصنوعی قطعی از روی کد نظام پزشکی
|
||||
$synthetic = 'imp_' . substr(md5($source . ':' . $code), 0, 14); // ≤ ۱۸ کاراکتر، ASCII، یکتا
|
||||
$user = $userRepo->findOneBy(['mobileNumber' => $synthetic]);
|
||||
if ($user === null) {
|
||||
$user = new User($synthetic);
|
||||
$user->setRealName($name);
|
||||
$user->setStatus(0); // جانشین: هرگز لاگین نمیکند
|
||||
$this->em->persist($user);
|
||||
}
|
||||
$doctor = new Doctor($user, $name);
|
||||
$doctor->setSource($source);
|
||||
$doctor->setOwnerStatus('unclaimed');
|
||||
$doctor->setActiveDoctorAppointment(false); // تا مالک واقعی برنامهٔ کاری بسازد
|
||||
$created = true;
|
||||
}
|
||||
|
||||
// فیلدهای مشترک
|
||||
$doctor->setName($name);
|
||||
$doctor->setMedicalSystemCode($code);
|
||||
$doctor->setManagedBy($admin->getId());
|
||||
if (array_key_exists('source_ref', $data) || array_key_exists('profile_url', $data)) {
|
||||
$doctor->setSourceRef($data['source_ref'] ?? $data['profile_url'] ?? null);
|
||||
}
|
||||
if (!empty($data['gender'])) $doctor->setGender($data['gender']);
|
||||
if (!empty($data['degree'])) $doctor->setDegree($data['degree']);
|
||||
if (array_key_exists('info', $data)) $doctor->setInfo($data['info']);
|
||||
|
||||
// روابط بر پایهٔ شناسههای مرجع (تخصص/استان/شهر)
|
||||
$this->syncRefCollection($doctor->getSpecialties(), $data['specialties'] ?? null, Specialty::class);
|
||||
$this->syncRefCollection($doctor->getProvinces(), $data['states'] ?? null, Province::class);
|
||||
$this->syncRefCollection($doctor->getCities(), $data['cities'] ?? null, City::class);
|
||||
|
||||
$this->em->persist($doctor);
|
||||
$this->em->flush();
|
||||
|
||||
return $this->success(
|
||||
['uuid' => $doctor->getUuid(), 'created' => $created],
|
||||
$created ? 201 : 200
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* یک مجموعهٔ ManyToMany پزشک را با آرایهای از شناسههای مرجع همگام میکند.
|
||||
* اگر $ids null باشد دست نمیخورد؛ اگر آرایه باشد، پاک و از نو پر میشود.
|
||||
*/
|
||||
private function syncRefCollection(\Doctrine\Common\Collections\Collection $col, ?array $ids, string $class): void
|
||||
{
|
||||
if ($ids === null) {
|
||||
return;
|
||||
}
|
||||
$col->clear();
|
||||
foreach ($ids as $id) {
|
||||
$ref = $this->em->getRepository($class)->find((int) $id);
|
||||
if ($ref !== null && !$col->contains($ref)) {
|
||||
$col->add($ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Clinics ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[Route('/api/v1/admin/clinics', methods: ['GET'])]
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth\Command;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
|
||||
/**
|
||||
* کاربر «مالک سیستمی» (پیشفرض موبایل 0000000000) که کرالر با آن به API لاگین میکند
|
||||
* تا پزشکان نظام پزشکی را وارد کند. ROLE_ADMIN دارد تا اندپوینت ایمپورت را صدا بزند.
|
||||
*
|
||||
* ساخت/بهروزرسانی رمز و فعالسازی:
|
||||
* php bin/console app:system-owner 0000000000 --password=secret --activate
|
||||
* غیرفعالسازی پس از پایان کار کرالر:
|
||||
* php bin/console app:system-owner 0000000000 --deactivate
|
||||
*/
|
||||
#[AsCommand(
|
||||
name: 'app:system-owner',
|
||||
description: 'Manage the system-owner user used by the IRIMC crawler (create/activate/deactivate).',
|
||||
)]
|
||||
class SystemOwnerCommand extends Command
|
||||
{
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $em,
|
||||
private readonly UserPasswordHasherInterface $hasher,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->addArgument('mobile', InputArgument::OPTIONAL, 'System-owner mobile identifier', '0000000000')
|
||||
->addOption('password', 'p', InputOption::VALUE_REQUIRED, 'Set/replace the login password')
|
||||
->addOption('activate', null, InputOption::VALUE_NONE, 'Activate the account (status=1)')
|
||||
->addOption('deactivate', null, InputOption::VALUE_NONE, 'Deactivate the account (status=0)');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
$mobile = (string) $input->getArgument('mobile');
|
||||
$password = $input->getOption('password');
|
||||
$activate = (bool) $input->getOption('activate');
|
||||
$deactiv = (bool) $input->getOption('deactivate');
|
||||
|
||||
if ($activate && $deactiv) {
|
||||
$io->error('--activate و --deactivate با هم مجاز نیستند.');
|
||||
return Command::INVALID;
|
||||
}
|
||||
|
||||
$repo = $this->em->getRepository(User::class);
|
||||
$user = $repo->findOneBy(['mobileNumber' => $mobile]);
|
||||
$existed = $user !== null;
|
||||
|
||||
if (!$existed) {
|
||||
$user = new User($mobile);
|
||||
$user->setRealName('مالک سیستمی (کرالر نظام پزشکی)');
|
||||
if ($password === null) {
|
||||
$io->error('برای ساخت کاربر جدید، --password الزامی است.');
|
||||
return Command::INVALID;
|
||||
}
|
||||
}
|
||||
|
||||
$roles = $user->getRoles();
|
||||
if (!in_array('ROLE_ADMIN', $roles, true)) {
|
||||
$roles[] = 'ROLE_ADMIN';
|
||||
$user->setRoles(array_values(array_unique($roles)));
|
||||
}
|
||||
|
||||
if ($password !== null) {
|
||||
$user->setPasswordHash($this->hasher->hashPassword($user, (string) $password));
|
||||
}
|
||||
|
||||
// پیشفرضِ کاربرِ تازه: فعال، مگر آنکه --deactivate داده شده باشد.
|
||||
if ($activate) {
|
||||
$user->setStatus(1);
|
||||
} elseif ($deactiv) {
|
||||
$user->setStatus(0);
|
||||
} elseif (!$existed) {
|
||||
$user->setStatus(1);
|
||||
}
|
||||
|
||||
$this->em->persist($user);
|
||||
$this->em->flush();
|
||||
|
||||
$io->success(sprintf(
|
||||
'%s system-owner %s (uuid=%s, status=%d, roles=%s)',
|
||||
$existed ? 'Updated' : 'Created',
|
||||
$mobile,
|
||||
$user->getUuid(),
|
||||
$user->getStatus(),
|
||||
implode(',', $user->getRoles()),
|
||||
));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ class ClinicDoctorInvitation
|
||||
$this->clinic = $clinic;
|
||||
$this->invitedBy = $invitedBy;
|
||||
$this->mobile = $mobile;
|
||||
$this->token = bin2hex(random_bytes(48));
|
||||
$this->token = bin2hex(random_bytes(16));
|
||||
$this->invitedAt = time();
|
||||
$this->expiresAt = $this->invitedAt + 72 * 3600;
|
||||
}
|
||||
@@ -94,7 +94,7 @@ class ClinicDoctorInvitation
|
||||
|
||||
public function refresh(): void
|
||||
{
|
||||
$this->token = bin2hex(random_bytes(48));
|
||||
$this->token = bin2hex(random_bytes(16));
|
||||
$this->tokenUsed = false;
|
||||
$this->invitedAt = time();
|
||||
$this->expiresAt = $this->invitedAt + 72 * 3600;
|
||||
|
||||
@@ -41,6 +41,7 @@ class DoctorController extends BaseController
|
||||
private readonly UserRepository $userRepo,
|
||||
private readonly FileValidatorService $fileValidator,
|
||||
private readonly WeeklyScheduleRepository $scheduleRepo,
|
||||
private readonly \App\Appointment\Repository\AppointmentRepository $appointmentRepo,
|
||||
private readonly TenantInsuranceCleanupService $insuranceCleanup,
|
||||
private readonly \App\Representation\Service\DomainContextResolver $domainResolver,
|
||||
private readonly string $projectDir,
|
||||
@@ -375,6 +376,10 @@ class DoctorController extends BaseController
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دکتر یافت نشد', 404);
|
||||
}
|
||||
|
||||
if ($this->appointmentRepo->count(['doctor' => $doctor]) > 0) {
|
||||
return $this->error(ErrorCodes::ERR_CONFLICT_001, 'این پزشک نوبت ثبتشده دارد و قابل حذف نیست', 409);
|
||||
}
|
||||
|
||||
$this->insuranceCleanup->purgeForEntity(TenantInsurance::TYPE_DOCTOR, $doctor->getId());
|
||||
$this->doctorRepo->remove($doctor);
|
||||
return $this->success(['message' => 'دکتر با موفقیت حذف شد']);
|
||||
|
||||
@@ -77,6 +77,26 @@ class Doctor
|
||||
#[ORM\Column(name: 'notification_mobile', type: 'string', length: 15, nullable: true)]
|
||||
private ?string $notificationMobile = null;
|
||||
|
||||
// ── Profile ownership (IRIMC import) ───────────────────────────────────────
|
||||
// owner_status: claimed | unclaimed | pending_transfer
|
||||
#[ORM\Column(name: 'owner_status', type: 'string', length: 20)]
|
||||
private string $ownerStatus = 'claimed';
|
||||
|
||||
// source: manual | irimc
|
||||
#[ORM\Column(type: 'string', length: 20)]
|
||||
private string $source = 'manual';
|
||||
|
||||
// شناسه رکورد مبدأ (profile_url یا کد نظام پزشکی) برای idempotency و ممیزی
|
||||
#[ORM\Column(name: 'source_ref', type: 'string', length: 100, nullable: true)]
|
||||
private ?string $sourceRef = null;
|
||||
|
||||
// شناسه کاربری که این پروفایلِ بدونمالک را وارد/مدیریت کرده (مثلاً کاربر سیستمی)
|
||||
#[ORM\Column(name: 'managed_by', type: 'integer', nullable: true)]
|
||||
private ?int $managedBy = null;
|
||||
|
||||
#[ORM\Column(name: 'claimed_at', type: 'integer', nullable: true)]
|
||||
private ?int $claimedAt = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
@@ -200,6 +220,26 @@ class Doctor
|
||||
{
|
||||
return $this->notificationMobile;
|
||||
}
|
||||
public function getOwnerStatus(): string
|
||||
{
|
||||
return $this->ownerStatus;
|
||||
}
|
||||
public function getSource(): string
|
||||
{
|
||||
return $this->source;
|
||||
}
|
||||
public function getSourceRef(): ?string
|
||||
{
|
||||
return $this->sourceRef;
|
||||
}
|
||||
public function getManagedBy(): ?int
|
||||
{
|
||||
return $this->managedBy;
|
||||
}
|
||||
public function getClaimedAt(): ?int
|
||||
{
|
||||
return $this->claimedAt;
|
||||
}
|
||||
public function getCreatedAt(): int
|
||||
{
|
||||
return $this->createdAt;
|
||||
@@ -312,6 +352,50 @@ class Doctor
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
public function setOwnerStatus(string $v): self
|
||||
{
|
||||
$this->ownerStatus = $v;
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
public function setSource(string $v): self
|
||||
{
|
||||
$this->source = $v;
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
public function setSourceRef(?string $v): self
|
||||
{
|
||||
$this->sourceRef = $v;
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
public function setManagedBy(?int $v): self
|
||||
{
|
||||
$this->managedBy = $v;
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
public function setClaimedAt(?int $v): self
|
||||
{
|
||||
$this->claimedAt = $v;
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* انتقال مالکیت پروفایلِ بدونمالک به کاربر واقعی پزشک.
|
||||
* user_id را پر میکند، مدیریت سیستمی را برمیدارد و وضعیت را claimed میکند.
|
||||
*/
|
||||
public function transferOwnershipTo(User $user): self
|
||||
{
|
||||
$this->user = $user;
|
||||
$this->managedBy = null;
|
||||
$this->ownerStatus = 'claimed';
|
||||
$this->claimedAt = time();
|
||||
$this->touch();
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function touch(): void
|
||||
{
|
||||
|
||||
@@ -66,6 +66,9 @@ class MellatGateway implements PaymentGatewayInterface
|
||||
/** SoapClient تنبل — فقط prod و فقط وقتی لازم شد ساخته میشود. */
|
||||
private function soap(): \SoapClient
|
||||
{
|
||||
if (!class_exists(\SoapClient::class)) {
|
||||
throw new \App\Shared\Exception\AppException(\App\Shared\Constant\ErrorCodes::ERR_PAYMENT_001, null, 503);
|
||||
}
|
||||
if ($this->soap === null) {
|
||||
$this->soap = new \SoapClient($this->wsdlUrl(), [
|
||||
'trace' => true,
|
||||
|
||||
@@ -102,6 +102,7 @@ class ErrorCodes
|
||||
public const ERR_GONE = 'ERR_GONE';
|
||||
public const ERR_MOVED = 'ERR_MOVED';
|
||||
public const ERR_ACCESS_DENIED = 'ERR_ACCESS_DENIED';
|
||||
public const ERR_METHOD_NOT_ALLOWED_001 = 'ERR_METHOD_NOT_ALLOWED_001';
|
||||
|
||||
public static function message(string $code): string
|
||||
{
|
||||
@@ -162,6 +163,7 @@ class ErrorCodes
|
||||
self::ERR_GONE => 'این منبع دیگر در دسترس نیست',
|
||||
self::ERR_MOVED => 'این منبع منتقل شده است',
|
||||
self::ERR_ACCESS_DENIED => 'دسترسی مجاز نیست',
|
||||
self::ERR_METHOD_NOT_ALLOWED_001 => 'متد درخواستی برای این آدرس مجاز نیست',
|
||||
default => 'خطای ناشناخته',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
namespace App\Shared\EventSubscriber;
|
||||
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
|
||||
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
|
||||
@@ -108,6 +110,21 @@ class ExceptionSubscriber implements EventSubscriberInterface
|
||||
return;
|
||||
}
|
||||
|
||||
// Bots/scanners and stray preflight hit disallowed methods on public paths (e.g. POST /).
|
||||
// Client errors, not server faults: respond 405 and log at notice so they don't flood
|
||||
// the error channel through the generic fallback below.
|
||||
if ($exception instanceof MethodNotAllowedHttpException) {
|
||||
$this->logger->notice('Method not allowed', [
|
||||
'path' => $event->getRequest()->getPathInfo(),
|
||||
'method' => $event->getRequest()->getMethod(),
|
||||
]);
|
||||
$event->setResponse(new JsonResponse(
|
||||
['success' => false, 'data' => null, 'errors' => [['code' => ErrorCodes::ERR_METHOD_NOT_ALLOWED_001, 'message' => ErrorCodes::message(ErrorCodes::ERR_METHOD_NOT_ALLOWED_001)]]],
|
||||
405
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
// Generic fallback: never leak stack traces or internal details in API responses.
|
||||
// The class/message/location go into the log MESSAGE itself so they surface in
|
||||
// platforms (e.g. Liara) whose default logger only prints the message string.
|
||||
|
||||
Reference in New Issue
Block a user