feat(tenant): mark the financial tables with their owning environment

Phase 6 of the tenant series. GlobalTables::DEFERRED is now empty and the
coverage test asserts it stays that way.

payments carries the (entity_type, entity_id) pair and belongs to the
receiving side, never the payer: an appointment payment takes the
appointment's environment, a subscription takes the environment its buyer
owns, and an SMS wallet top-up takes the wallet's. The patient never chose
an environment, so TenantFilter stays off for them and they still see their
own payment.

Three corrections to the analysis the phase was planned on, each backed by
the code or the data rather than the plan:

- A third payment type exists. Payment::TYPE_SMS_WALLET is created in
  SmsWalletController and already carries its environment in the metadata;
  without assigning it the write would fail at flush.
- clinic_subscriptions has no user_id, and its trial rows carry no payment,
  so it cannot drive the subscription backfill. The environment is derived
  the way handleSubscriptionActivation derives it — and that method now
  reads the pair off the payment instead of re-deriving it, so a payment and
  the subscription it buys can no longer land on different environments.
- WalletTransaction is not a child of Payment. payment_id is nullable and
  none of the four creation sites set it; the wallet is a person's, with a
  running balance per user. It and Settlement, which withdraws from that same
  wallet, are global with a recorded reason instead.

bank_accounts and pos_devices move from the registering user to the
environment. Their pair is deliberately nullable: nothing in the existing
data says which of a multi-environment owner's cards belongs where, and
guessing would point real money at the wrong account. Ambiguous rows stay
unassigned and the migration reports how many. The cost is that such a row
is invisible in every environment, so the owner reaches it through a
user-scoped lookup that runs outside the filter, and assigns it with
PATCH .../{uuid}/environment. The admin panel marks those rows and offers
the assignment.

Tests: 896 backend (+11), 570 frontend (+4). PHPStan unchanged at its 17
pre-existing errors.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-28 15:06:28 +03:30
co-authored by Claude Opus 5
parent d2f4b5c428
commit c9d4348c46
40 changed files with 1582 additions and 163 deletions
@@ -730,6 +730,7 @@ class SeedDemoDataCommand extends Command
$user = $this->em->getReference(\App\Auth\Entity\User::class, $patientIds[$i]);
$payment = new Payment($user, $fee, 'mock', Payment::TYPE_APPOINTMENT, 'https://' . $rep['domain'] . '/payment/result');
$payment->assignTenantPair('doctor', (int) $doc['id']);
$payment->setMetadata(['demo' => true, 'scenario' => 'match-service']);
$this->em->persist($payment);
$this->em->flush();
+2
View File
@@ -29,6 +29,7 @@ class ErrorCodes
public const ERR_PAYMENT_001 = 'ERR_PAYMENT_001';
public const ERR_PAYMENT_002 = 'ERR_PAYMENT_002';
public const ERR_PAYMENT_003 = 'ERR_PAYMENT_003';
public const ERR_PAYMENT_004 = 'ERR_PAYMENT_004';
// Appointment
public const ERR_APPOINTMENT_001 = 'ERR_APPOINTMENT_001';
@@ -127,6 +128,7 @@ class ErrorCodes
self::ERR_PAYMENT_001 => 'درگاه پرداخت در دسترس نیست',
self::ERR_PAYMENT_002 => 'مبلغ پرداخت نامعتبر است',
self::ERR_PAYMENT_003 => 'وضعیت نوبت برای پرداخت مناسب نیست',
self::ERR_PAYMENT_004 => 'محیط این پرداخت مشخص نیست',
self::ERR_APPOINTMENT_001 => 'اسلات انتخاب‌شده در دسترس نیست',
self::ERR_APPOINTMENT_002 => 'نوبت قابل لغو نیست',
self::ERR_FILE_001 => 'فرمت فایل مجاز نیست',
@@ -73,6 +73,25 @@ class EntityContextResolver
}
}
/**
* محیطی که کاربر **صاحبش** است، مستقل از محیط فعال و از نقش‌هایش.
*
* برای خریدهایی است که به حساب خودِ صاحب می‌نشیند (اشتراک): آنجا «کجا ایستاده‌ام»
* مهم نیست، «چه چیزی دارم» مهم است. تنها مرجعِ این پرسش همین متد است تا پرداختِ
* اشتراک و خودِ اشتراک هرگز روی دو محیط متفاوت ننشینند.
*/
public function ownedEntity(User $user): EntityContext
{
$doctor = $this->doctorRepo->findByUser($user);
if ($doctor !== null) {
return EntityContext::forDoctor($doctor);
}
$clinic = $this->clinicRepo->findByUser($user);
return $clinic !== null ? EntityContext::forClinic($clinic) : EntityContext::unknown();
}
/** مالک کلینیک، ادمین، پزشکِ عضو همان کلینیک، یا منشیِ دارای رابطهٔ فعال در آن. */
public function canActInClinic(User $user, Clinic $clinic): bool
{
+14 -14
View File
@@ -66,6 +66,10 @@ final class GlobalTables
// استثنای مستندشده در فاز ۲
\App\Appointment\Entity\Holiday::class => 'clinic=NULL یعنی «همهٔ محیط‌ها»، نه «مطب شخصی» — جفت tenant این را نمی‌تواند بیان کند',
// کیف پولِ شخص — استثنای مستندشده در فاز ۶
\App\Settlement\Entity\WalletTransaction::class => 'کیف پول خودِ شخص است نه محیط: موجودی از مجموع credit−debitِ همان کاربر مشتق می‌شود و payment_id تهی‌پذیر است، پس تفکیک به محیط، موجودی را بی‌معنا می‌کند',
\App\Settlement\Entity\Settlement::class => 'برداشت از همان کیف پولِ شخصی (SettlementController موجودی را با getWalletBalance(user) می‌سنجد)؛ محیط ندارد چون کیف پول ندارد',
];
/**
@@ -107,25 +111,21 @@ final class GlobalTables
\App\Insurance\Entity\TenantServiceCoverage::class => \App\Insurance\Entity\TenantInsurance::class,
\App\Sms\Entity\SmsWalletTransaction::class => \App\Sms\Entity\SmsWallet::class,
\App\Payment\Entity\PaymentLog::class => \App\Payment\Entity\Payment::class,
\App\Settlement\Entity\FinancialBreakdown::class => \App\Payment\Entity\Payment::class,
\App\Secretary\Entity\SecretaryEarning::class => \App\Settlement\Entity\FinancialBreakdown::class,
];
/**
* بدهی ثبت‌شده: مالکیتشان دوگانه است (پرداخت‌کننده در برابر دریافت‌کننده) و
* تصمیم درباره‌شان تحلیل جدا می‌خواهد. migration اشتباه روی دادهٔ مالی برگشت‌پذیر
* نیست، پس عمداً در این فاز دست نخوردند.
* بدهیِ طبقه‌بندی: کلاسی که هنوز تصمیمی درباره‌اش گرفته نشده.
*
* این فهرست باید کوچک شود، نه بزرگ.
* فاز ۶ آخرین هشت موردش را تعیین تکلیف کرد و اکنون خالی است. خالی بماند:
* هر افزوده‌ای یعنی جدولی بیرون از هر تضمینی مانده. اگر تصمیم واقعاً به تحلیل
* بیشتری نیاز دارد، همین‌جا با دلیل ثبتش کن — ولی TenantSchemaCoverageTest
* خالی‌بودن را اجبار می‌کند تا این کار بی‌صدا نگذرد.
*
* @var array<class-string, string>
*/
public const DEFERRED = [
\App\Payment\Entity\Payment::class => 'پرداخت بین بیمار و محیط؛ هر دو طرف باید ببینندش',
\App\Payment\Entity\PaymentLog::class => 'فرزند Payment؛ با همان تصمیم می‌رود',
\App\Settlement\Entity\Settlement::class => 'تسویهٔ سامانه با صاحب محیط',
\App\Settlement\Entity\FinancialBreakdown::class => 'تفکیک سهم‌ها بین چند طرف یک پرداخت',
\App\Settlement\Entity\WalletTransaction::class => 'کیف پول کاربر، نه محیط',
\App\Secretary\Entity\SecretaryEarning::class => 'سهم منشی از یک پرداخت',
\App\PaymentMethod\Entity\BankAccount::class => 'حساب بانکی روی User ثبت شده، نه روی محیط',
\App\PaymentMethod\Entity\Pos::class => 'دستگاه کارتخوان روی User ثبت شده، نه روی محیط',
];
public const DEFERRED = [];
}
@@ -0,0 +1,50 @@
<?php
namespace App\Shared\Tenant;
use App\Shared\Context\EntityContext;
use Doctrine\ORM\Mapping as ORM;
/**
* همان جفت محیطِ {@see TenantOwnedTrait}، ولی تهی‌پذیر — برای جدول‌هایی که پیش از
* نشانه‌گذاری وجود داشتند و مالکِ بعضی ردیف‌هایشان از روی داده قابل تشخیص نیست.
*
* تنها مصرفش حساب بانکی و کارتخوان است: تا فاز ۶ روی `User` ثبت می‌شدند و کاربری
* که چند محیط دارد، هیچ ستونی نمی‌گوید کدام کارتش مال کدام محیط است. حدس زدنش
* یعنی پول به حساب اشتباه؛ پس تهی می‌مانند تا مالک خودش تعیین کند.
*
* ⚠️ ردیفِ تهی در **هیچ** محیطی دیده نمی‌شود، چون TenantFilter شرط تساوی می‌گذارد
* و NULL با هیچ مقداری برابر نیست. این عمدی است ولی نقطهٔ ضعف است و در
* docs/architecture/tenancy.md ثبت شده: تا وقتی مالک محیط را تعیین نکند، کارتش
* از فهرست‌ها غایب است.
*/
trait NullableTenantOwnedTrait
{
#[ORM\Column(name: 'entity_type', type: 'string', length: 10, nullable: true)]
private ?string $entityType = null;
#[ORM\Column(name: 'entity_id', type: 'integer', nullable: true)]
private ?int $entityId = null;
public function getEntityType(): ?string { return $this->entityType; }
public function getEntityId(): ?int { return $this->entityId; }
public function hasTenant(): bool
{
return $this->entityType !== null && $this->entityId !== null;
}
/** @throws \InvalidArgumentException اگر محیط حل نشده باشد */
public function assignTenant(EntityContext $context): void
{
if (!$context->isResolved()) {
throw new \InvalidArgumentException(sprintf(
'Cannot assign an unresolved tenant context to %s.',
static::class,
));
}
[$this->entityType, $this->entityId] = $context->toEntityPair();
}
}