feat(doctor): complete IRIMC import feature — claim flow, least-privilege importer, unique import key

- Extract import logic from AdminApiController into DoctorImportService
  (thin DoctorImportController keeps the same route/contract)
- Surrogate users get marker role ROLE_UNCLAIMED_DOCTOR (+ backfill command
  app:doctors:backfill-surrogate-role) enabling safe deletion after claim
- DB-level UNIQUE (source, medical_system_code) + concurrent-import retry
- Doctor profile claim flow (climed.md): shahkar + PersonInfo identity checks
  via existing ApiIrService, Persian name normalization (PersianText),
  pessimistic-lock race protection, DoctorClaimRequest audit table
  (national code hashed, mobile masked), doctor_claim rate limiter,
  public claim-info endpoint, welcome SMS
- Admin support tools: manual transfer endpoint + paginated doctor-claims
  audit list + owner_status filter/fields in admin doctors list
- Least privilege: system owner now gets ROLE_IMPORTER (ROLE_ADMIN stripped),
  import endpoint accepts ADMIN|IMPORTER, isStaff includes IMPORTER
- Headless crawler login: X-Service-Token header bypasses captcha only
  (rate limit + password checks intact; empty env = no bypass)
- docs: doctor-claim.md (new), doctor-import.md, admin.md, doctor.md
- tests: DoctorImportTest (6), DoctorClaimTest (11), PersianTextTest (5)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-11 11:39:15 +03:30
co-authored by Claude Opus 4.8
parent 83c872bb78
commit af125572c9
29 changed files with 1944 additions and 303 deletions
+199
View File
@@ -0,0 +1,199 @@
<?php
namespace App\Doctor\Service;
use App\Auth\Entity\User;
use App\Doctor\Entity\Doctor;
use App\Doctor\Entity\DoctorClaimRequest;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Exception\AppException;
use App\Shared\Service\ApiIrService;
use App\Shared\Util\PersianText;
use App\Sms\Entity\SmsLog;
use App\Sms\Service\SmsService;
use Doctrine\DBAL\LockMode;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
/**
* تصاحب پروفایل پزشک ایمپورت‌شده (unclaimed) توسط پزشک واقعی.
*
* دو مسیر: self-claim (احراز هویت API.ir: شاهکار + PersonInfo + تطبیق نام) و
* انتقال دستی ادمین. نهایی‌سازی هر دو مسیر یکی است: اتصال کاربر واقعی، نقش
* ROLE_DOCTOR، حذف امن کاربر جانشین، و ثبت رکورد ممیزی DoctorClaimRequest.
*
* ضد race: تغییر وضعیت unclaimed→pending_transfer زیر قفل PESSIMISTIC_WRITE
* انجام می‌شود؛ درخواست هم‌زمان دوم 409 می‌گیرد. فراخوانی خارجی هرگز داخل قفل نیست.
*/
class DoctorClaimService
{
public const METHOD_APIIR = 'apiir_personinfo';
public const METHOD_APIIR_SHAHKAR = 'apiir_personinfo+shahkar';
public const METHOD_ADMIN = 'admin_manual';
public function __construct(
private readonly EntityManagerInterface $em,
private readonly ApiIrService $apiIr,
private readonly SmsService $smsService,
private readonly LoggerInterface $logger,
) {}
public function claim(Doctor $doctor, User $user, string $nationalCode, string $birthDateJalali, string $firstName, string $lastName): DoctorClaimRequest
{
$method = $this->apiIr->isConfigured() ? self::METHOD_APIIR_SHAHKAR : self::METHOD_APIIR;
// مرحلهٔ ۱ — رزرو اتمیک پروفایل زیر قفل (تراکنش کوتاه، بدون فراخوان خارجی)
$claim = $this->em->wrapInTransaction(function () use ($doctor, $user, $nationalCode, $method): DoctorClaimRequest {
$locked = $this->em->find(Doctor::class, $doctor->getId(), LockMode::PESSIMISTIC_WRITE);
if ($locked->getOwnerStatus() !== 'unclaimed') {
throw new AppException(ErrorCodes::ERR_CONFLICT_001, 'این پروفایل قابل تصاحب نیست یا درخواست دیگری در جریان است', 409);
}
$existing = $this->em->getRepository(Doctor::class)->findOneBy(['user' => $user]);
if ($existing !== null) {
throw new AppException(ErrorCodes::ERR_CONFLICT_001, 'شما از قبل یک پروفایل پزشک دارید', 409);
}
$codeOwner = $this->em->getRepository(User::class)->findOneBy(['nationalCode' => $nationalCode]);
if ($codeOwner !== null && $codeOwner->getId() !== $user->getId()) {
throw new AppException(ErrorCodes::ERR_PROFILE_NATIONAL_CODE_TAKEN, null, 409);
}
$locked->setOwnerStatus('pending_transfer');
$claim = new DoctorClaimRequest($locked, $user, $nationalCode, $user->getMobileNumber(), $method);
$this->em->persist($claim);
return $claim;
});
// مرحلهٔ ۲ — احراز هویت (خارج از قفل)
try {
$this->verifyIdentity($doctor, $user, $nationalCode, $birthDateJalali, $firstName, $lastName);
} catch (AppException $e) {
$this->revert($doctor, $claim, $e->getMessage());
throw $e;
}
// مرحلهٔ ۳ — نهایی‌سازی اتمیک
$this->finalize($doctor, $user, $claim, $nationalCode);
// مرحلهٔ ۴ — پیامک خوش‌آمد (غیر بحرانی؛ شکستش claim را باطل نمی‌کند)
$this->smsService->dispatchTemplate(SmsLog::TAG_WELCOME, $user->getMobileNumber(), [
'name' => PersianText::stripDoctorTitle($doctor->getName()),
'site' => 'نوبت۷۲۴',
]);
return $claim;
}
/** انتقال دستی توسط ادمین (پشتیبانی) — بدون استعلام هویت؛ کاربر هدف با موبایل پیدا/ساخته می‌شود. */
public function transferByAdmin(Doctor $doctor, string $mobile): DoctorClaimRequest
{
$claim = $this->em->wrapInTransaction(function () use ($doctor, $mobile): DoctorClaimRequest {
$locked = $this->em->find(Doctor::class, $doctor->getId(), LockMode::PESSIMISTIC_WRITE);
if ($locked->getOwnerStatus() === 'claimed') {
throw new AppException(ErrorCodes::ERR_CONFLICT_001, 'این پروفایل قبلاً تصاحب شده است', 409);
}
$userRepo = $this->em->getRepository(User::class);
$target = $userRepo->findOneBy(['mobileNumber' => $mobile]);
if ($target === null) {
$target = new User($mobile);
$target->setRealName(PersianText::stripDoctorTitle($locked->getName()));
$target->setStatus(1);
$this->em->persist($target);
}
$existing = $this->em->getRepository(Doctor::class)->findOneBy(['user' => $target]);
if ($existing !== null && $existing->getId() !== $locked->getId()) {
throw new AppException(ErrorCodes::ERR_CONFLICT_001, 'این کاربر قبلاً پروفایل پزشک دیگری دارد', 409);
}
$locked->setOwnerStatus('pending_transfer');
$claim = new DoctorClaimRequest($locked, $target, '', $mobile, self::METHOD_ADMIN);
$this->em->persist($claim);
return $claim;
});
$this->finalize($doctor, $claim->getUser(), $claim, null);
return $claim;
}
private function verifyIdentity(Doctor $doctor, User $user, string $nationalCode, string $birthDateJalali, string $firstName, string $lastName): void
{
// تطبیق موبایل ↔ کد ملی (شاهکار). بدون پیکربندی api.ir استعلام ممکن نیست →
// موبایلِ OTP-تأییدشدهٔ کاربر لاگین‌شده مبنا می‌ماند و فقط PersonInfo چک می‌شود.
if ($this->apiIr->isConfigured() && !$this->apiIr->shahkarMatch($nationalCode, $user->getMobileNumber())) {
throw new AppException(ErrorCodes::ERR_NATIONAL_CODE_MISMATCH, null, 422);
}
$person = $this->apiIr->personInfo($nationalCode, $birthDateJalali);
if ($person === null || !$person['alive']) {
throw new AppException(ErrorCodes::ERR_NATIONAL_CODE_MISMATCH, 'اطلاعات هویتی با سامانهٔ ثبت احوال مطابقت ندارد', 422);
}
// ورودی کاربر ↔ هویت تأییدشده
if (!PersianText::sameName($firstName . ' ' . $lastName, $person['firstName'] . ' ' . $person['lastName'])) {
throw new AppException(ErrorCodes::ERR_NATIONAL_CODE_MISMATCH, 'نام واردشده با اطلاعات هویتی مطابقت ندارد', 422);
}
// هویت تأییدشده ↔ نام پروفایل ایمپورت‌شده از نظام پزشکی
$profileName = PersianText::stripDoctorTitle($doctor->getName());
$verifiedName = PersianText::normalize($person['firstName'] . ' ' . $person['lastName']);
if ($profileName !== $verifiedName) {
throw new AppException(ErrorCodes::ERR_NATIONAL_CODE_MISMATCH, 'نام شما با نام این پروفایل پزشک مطابقت ندارد', 422);
}
}
private function finalize(Doctor $doctor, User $target, DoctorClaimRequest $claim, ?string $nationalCode): void
{
$surrogate = $this->em->wrapInTransaction(function () use ($doctor, $target, $claim, $nationalCode): ?User {
$locked = $this->em->find(Doctor::class, $doctor->getId(), LockMode::PESSIMISTIC_WRITE);
if ($locked->getOwnerStatus() !== 'pending_transfer') {
throw new AppException(ErrorCodes::ERR_CONFLICT_001, 'وضعیت پروفایل در این میان تغییر کرده است', 409);
}
$surrogate = $locked->getUser();
if ($nationalCode !== null && $nationalCode !== '') {
$target->setNationalCode($nationalCode);
$target->setNationalCodeVerified(true);
}
$target->addRole('ROLE_DOCTOR');
$locked->transferOwnershipTo($target);
$claim->markCompleted();
return $surrogate;
});
// حذف امن جانشین — پس از flush انتقال، تا شمارش پزشکانِ متصل قطعی باشد
if ($surrogate !== null
&& $surrogate->getId() !== $target->getId()
&& $surrogate->hasRole(DoctorImportService::ROLE_UNCLAIMED_DOCTOR)
&& $this->em->getRepository(Doctor::class)->count(['user' => $surrogate]) === 0) {
$this->em->remove($surrogate);
$this->em->flush();
}
$this->logger->info('doctor profile claimed', [
'claim_uuid' => $claim->getUuid(),
'doctor_uuid' => $doctor->getUuid(),
'user_id' => $target->getId(),
'method' => $claim->getVerificationMethod(),
]);
}
private function revert(Doctor $doctor, DoctorClaimRequest $claim, string $reason): void
{
$this->em->wrapInTransaction(function () use ($doctor, $claim, $reason): void {
$locked = $this->em->find(Doctor::class, $doctor->getId(), LockMode::PESSIMISTIC_WRITE);
if ($locked->getOwnerStatus() === 'pending_transfer') {
$locked->setOwnerStatus('unclaimed');
}
$claim->markFailed($reason);
});
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace App\Doctor\Service;
use App\Doctor\Entity\Doctor;
final class DoctorImportResult
{
public function __construct(
public readonly Doctor $doctor,
public readonly bool $created,
public readonly ?string $skipped = null,
) {}
}
+131
View File
@@ -0,0 +1,131 @@
<?php
namespace App\Doctor\Service;
use App\Auth\Entity\User;
use App\Doctor\Entity\Doctor;
use App\Location\Entity\City;
use App\Location\Entity\Province;
use App\Specialty\Entity\Specialty;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
/**
* ایمپورت پزشک از سازمان نظام پزشکی (IRIMC) — منطق دامنه، جدا از کنترلر.
*
* برخلاف ساخت عادی پزشک، موبایل لازم نیست: برای هر پزشک یک «کاربر جانشین»
* غیرفعال با شناسهٔ مصنوعی ساخته می‌شود و پروفایل در وضعیت unclaimed ذخیره
* می‌گردد تا بعداً به پزشک واقعی منتقل شود. idempotent بر پایهٔ
* (source, medical_system_code): اجرای مجدد، رکورد موجود را به‌روزرسانی می‌کند
* و پروفایل claimed هرگز بازنویسی نمی‌شود (مالک واقعی اولویت دارد).
*/
class DoctorImportService
{
/** نقش marker کاربر جانشین — permission نمی‌دهد؛ مبنای شناسایی و حذف امن پس از claim است. */
public const ROLE_UNCLAIMED_DOCTOR = 'ROLE_UNCLAIMED_DOCTOR';
public function __construct(
private readonly EntityManagerInterface $em,
private readonly ManagerRegistry $registry,
) {}
/** @param array $data بدنهٔ validated (name و medical_system_code غیرخالی). */
public function import(array $data, User $importedBy): DoctorImportResult
{
try {
return $this->doImport($data, $importedBy);
} catch (UniqueConstraintViolationException) {
// برندهٔ هم‌زمانی رکورد را همین الان ساخته (قید uniq_doctors_source_code).
// EM پس از این خطا بسته است — reset و اجرای مجدد که این‌بار مسیر update را می‌رود.
$this->registry->resetManager();
return $this->doImport($data, $importedBy);
}
}
private function doImport(array $data, User $importedBy): DoctorImportResult
{
return $this->em->wrapInTransaction(function () use ($data, $importedBy): DoctorImportResult {
$name = trim((string) $data['name']);
$code = trim((string) ($data['medical_system_code'] ?? $data['medicalSystemCode']));
$source = trim((string) ($data['source'] ?? 'irimc')) ?: 'irimc';
$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 new DoctorImportResult($doctor, false, '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); // جانشین: هرگز لاگین نمی‌کند
$user->addRole(self::ROLE_UNCLAIMED_DOCTOR);
$this->em->persist($user);
}
$doctor = new Doctor($user, $name);
$doctor->setSource($source);
$doctor->setOwnerStatus('unclaimed');
$doctor->setActiveDoctorAppointment(false); // تا مالک واقعی برنامهٔ کاری بسازد
$created = true;
}
// backfill: جانشین‌های ایمپورت‌شده پیش از افزودن نقش marker، در ایمپورت مجدد نقش می‌گیرند
$surrogate = $doctor->getUser();
if (!$created
&& str_starts_with($surrogate->getMobileNumber(), 'imp_')
&& !$surrogate->hasRole(self::ROLE_UNCLAIMED_DOCTOR)) {
$surrogate->addRole(self::ROLE_UNCLAIMED_DOCTOR);
}
// فیلدهای مشترک
$doctor->setName($name);
$doctor->setMedicalSystemCode($code);
$doctor->setManagedBy($importedBy->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 new DoctorImportResult($doctor, $created);
});
}
/**
* یک مجموعهٔ 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);
}
}
}
}