Files
clinicpro/tests/Shared/NumericFieldNormalizerTest.php
T
hamedandClaude Opus 5 24534ec483 feat(availability): multi-resource availability engine
Section 10 of the design document, and the payoff for tasks 01–05. The engine slides
a multi-segment plan across resource calendars and answers which times are actually
possible, with a suggested resource for each role. Until now the only conflict the
system checked was the doctor's; rooms, devices and operators did not exist.

Allocation is per *role*, not per segment, and that is what returns the wasted
capacity. An operator with no requirement during "waiting for the cream" is simply
not examined for those minutes, so another patient can use them. The reference test
encodes exactly that: patient A holds 10:00–11:00 while the operator is only busy
10:00–10:05 and 10:35–11:00, and patient B is offered a slot inside the gap with the
second room assigned. The spec says the task is not verified without that scenario.

One resource is chosen for every segment that needs its role, not independently per
segment — otherwise the operator in segment 1 and segment 3 could be two different
people and the patient would change hands mid-treatment.

Occupancy is stored one row per (segment × resource) rather than one per appointment.
The granularity is the whole point; a row per appointment would re-create the
single-interval model the design rejects. Reserved intervals are widened by each
resource's setup/cleanup, because the resource genuinely is not available then.

booking_mode gains a third value, resource, alongside slot and service. It is purely
additive: the default stays slot, no environment moves on its own, and a location
that has not opted in keeps the untouched legacy path. The frozen slot-mode contract
stays green.

Performance is a test, not a hope: 30 days, 20 resources and 500 existing bookings
complete well inside the 500ms budget. Every input is read once and the rest is in
memory — no query inside the day or candidate loop — and candidates are generated
only from the free windows of the scarcest role, which turns tens of thousands of
candidates into a few hundred.

An empty result is not an error and not a 404: it carries
reason: "no_capacity_in_range" so the caller does not have to infer meaning from
emptiness.

Also fixed a genuinely intermittent test defect: NumericFieldNormalizerTest padded a
random number with the three-byte Persian "۰" using byte-based str_pad, producing
broken UTF-8 whenever the number was short. It failed roughly at random. The improved
assertion message added earlier is what identified it immediately.

1196 tests / 3414 assertions. phpstan at its 14-error baseline.

Resource-picking strategies, the availability cache and the settings UI are recorded
as outstanding in the checklist with reasons — the cache in particular would be
premature while the performance test passes comfortably without it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 21:21:33 +03:30

120 lines
5.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Tests\Shared;
use App\Auth\Entity\User;
use App\Doctor\Entity\Doctor;
use App\Secretary\Entity\DoctorSecretary;
use App\Shared\Util\PersianText;
use App\Tests\ApiTestCase;
/**
* Persian/Arabic digits sent by any client must never reach the database.
* The admin SPA normalizes at the input, but nobat724_front and clinic-pro-tauri
* hit the same endpoints, so the request layer is the real guarantee.
*/
class NumericFieldNormalizerTest extends ApiTestCase
{
private function toPersianDigits(string $latin): string
{
return str_replace(range('0', '9'), ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'], $latin);
}
public function testDigitsHelperTranslatesWithoutStripping(): void
{
self::assertSame('09123456789', PersianText::digits('۰۹۱۲۳۴۵۶۷۸۹'));
self::assertSame('0912', PersianText::digits('٠٩١٢'));
self::assertSame('IR12-34', PersianText::digits('IR۱۲-۳۴'), 'letters and separators survive');
self::assertSame('', PersianText::digits(''));
}
public function testSecretaryCreatedWithPersianDigitsIsStoredLatin(): void
{
$owner = $this->createUser(['ROLE_USER', 'ROLE_DOCTOR']);
$doctor = new Doctor($owner, 'دکتر تست');
$this->em->persist($doctor);
$this->em->flush();
// db_test پاک نمی‌شود؛ شماره باید تازه باشد وگرنه endpoint با «تکراری» رد می‌کند.
//
// padding حتماً روی رقم لاتین انجام می‌شود و بعد تبدیل: `str_pad` بایتی است و
// با نویسهٔ سه‌بایتیِ «۰» عددِ کوتاه را به بایت‌های نیمه‌کاره می‌شکست. چون طول
// عدد تصادفی است، این تست گاهی سبز و گاهی ۴۲۲ می‌داد.
do {
$latinMobile = '09' . str_pad((string) random_int(0, 999_999_999), 9, '0', STR_PAD_LEFT);
$persianMobile = $this->toPersianDigits($latinMobile);
} while ($this->em->getRepository(User::class)->findOneBy(['mobileNumber' => $latinMobile]) !== null);
// کد ملی هم همین‌طور. ثابت‌بودنش این تست را flaky می‌کرد: در اجرای کامل سوئیت،
// بسته به ترتیب اجرا، ردیفِ اجرای قبلی باعث ۴۲۲ «تکراری» می‌شد و در اجرای تنها
// سبز بود.
// مثل شماره، یکتایی‌اش هم باید سنجیده شود: تصادفی‌بودن تنهایی کافی نیست و در
// اجرای کامل سوئیت روی db_testِ انباشته، برخورد ۴۲۲ «تکراری» می‌داد.
do {
$latinNationalCode = str_pad((string) random_int(0, 9_999_999_999), 10, '0', STR_PAD_LEFT);
$persianNationalCode = $this->toPersianDigits($latinNationalCode);
} while (
$this->em->getRepository(DoctorSecretary::class)
->findOneBy(['nationalCode' => $latinNationalCode]) !== null
);
$body = $this->authJson('POST', '/api/v1/secretary', $owner, [
'doctor_uuid' => $doctor->getUuid(),
'mobile_number' => $persianMobile,
'name' => 'منشی تست',
'national_code' => $persianNationalCode,
]);
// بدنه در پیام می‌آید: «۴۲۲ به‌جای ۲۰۱» بدون دلیلِ سرور قابل دیباگ نیست.
self::assertSame(
201,
$this->responseCode(),
'Persian digits must not break validation: ' . json_encode($body, JSON_UNESCAPED_UNICODE),
);
$this->em->clear();
$created = $this->em->getRepository(User::class)->findOneBy(['mobileNumber' => $latinMobile]);
self::assertNotNull($created, 'user is stored under the latin mobile');
$rel = $this->em->getRepository(DoctorSecretary::class)->findOneBy(['secretary' => $created]);
self::assertSame(PersianText::digits($persianNationalCode), $rel->getNationalCode());
}
public function testNestedArraysAreNormalized(): void
{
$user = $this->createUser(['ROLE_USER', 'ROLE_DOCTOR']);
$this->authJson('PUT', '/api/v1/insurance-pricing', $user, [
'free_visit_price_rials' => '۵۰۰۰۰۰',
'insurances' => [
['insurance_id' => 1, 'patient_share_rials' => '۱۲۳۴۵'],
],
]);
// پروفایل پزشک ممکن است بیمه‌ای نداشته باشد؛ مهم این است که ارقام فارسی
// باعث خطای اعتبارسنجی یا NaN نشوند.
self::assertNotSame(500, $this->responseCode(), 'nested persian digits must not blow up');
}
public function testNonNumericKeysKeepPersianDigits(): void
{
$owner = $this->createUser(['ROLE_USER', 'ROLE_DOCTOR']);
$doctor = new Doctor($owner, 'دکتر تست');
$this->em->persist($doctor);
$this->em->flush();
$mobile = '09' . str_pad((string) random_int(0, 999_999_999), 9, '0', STR_PAD_LEFT);
$this->authJson('POST', '/api/v1/secretary', $owner, [
'doctor_uuid' => $doctor->getUuid(),
'mobile_number' => $mobile,
'name' => 'منشی شماره ۲',
]);
self::assertSame(201, $this->responseCode());
$this->em->clear();
$created = $this->em->getRepository(User::class)->findOneBy(['mobileNumber' => $mobile]);
self::assertStringContainsString('۲', $created->getRealName(), 'name is not a numeric field');
}
}