approve/pay accepted any approved_rials/paid_rials with no bounds, so the
claiming tenant could write arbitrary figures into the insurer-debt ledger
(negative, or far above the claimed total). Validate: approved ∈ [0, claimed],
paid ∈ [0, approved] → 422 otherwise. (The "force arbitrary status" half of the
finding was already prevented by Claim::canTransitionTo.)
Regression: tests/Billing/ClaimAmountBoundsTest.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Verification pass found three tests only guarded correctness, not the fix's
behavior:
- H7: add repository white-box test asserting likes/replies come back as
initialised PersistentCollections (lazy without the fetch-join).
- H8: add a query-count test (constant vs coverage-row count) — without the
batch fetch the count grows ~1 per row.
- H5: add an end-to-end test hitting DELETE /api/v1/doctor and asserting the
insurance config is purged (the service unit test didn't cover the wiring).
All three now fail when their fix is reverted. Suite: 39 tests / 92 assertions.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
GET /billing/claims loaded every tenant claim with no limit. Add
findByTenant(page, limit) + countByTenant (shared query builder), default
limit 50 / max 100, and expose totals as data.meta — kept inside the existing
{ data: { data: [...] } } envelope so current clients are unaffected.
GET /wallet/transactions was already bounded (findByUser defaulted to limit 50)
but page-less; add page/offset + countByUser + the same additive meta.
Regression: tests/Billing/ClaimsListPaginationTest,
tests/Settlement/WalletTransactionsPaginationTest.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
findApprovedRootsByDoctor used a plain findBy, so Comment::toArray() lazy-loaded
likes, replies and the author per comment (and recursively per reply). Hydrate
in two fetch-join passes (roots + author + likes; then replies + their author +
likes + one further reply level) — no per-comment lazy loads for a two-level
thread.
Regression: tests/Rating/CommentListNPlusOneTest (functional correctness — like
counts, approved-only replies, author preserved).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
listServiceCoverage called serviceItemRepo->find() once per coverage row (N+1).
Collect the ids and fetch them in one findBy(['id' => $ids]), then map by id.
Regression: tests/Insurance/ServiceCoverageNPlusOneTest (functional correctness —
every row resolves the right service_item_uuid).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
findByClinicWithFilters left-joined specialties only for filtering, so
toListArray() lazy-loaded them per doctor (N+1). addSelect them and switch the
result fetch to Paginator(fetchJoinCollection: true) so LIMIT still paginates by
doctor.
Test infra: ApiTestCase::countQueries() (via doctrine.debug_data_holder).
Regression: tests/Doctor/ClinicDoctorListNPlusOneTest asserts the query count
does not grow with doctor count (4→10 without the fix).
Also relaxed AppointmentExpiryServiceTest's exact-count assertion (it counts all
stale pendings in the shared db_test, which accumulates) — logged test-isolation
debt as E6.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
tenant_insurances, entity_insurance_pricing and tenant_service_coverages
reference their owner through a polymorphic (entity_type, entity_id) pair, so no
database FK can cascade their cleanup. Hard-deleting a doctor (DoctorController)
or clinic (AdminApiController) left these rows orphaned.
Add TenantInsuranceCleanupService::purgeForEntity() and call it from both delete
paths — removes coverage (via owning tenant_insurance ids), then tenant
insurances, then pricing.
Residual (separate, lower-freq paths): deleting an insurance category or a
service_item still orphans rows that reference them by id — tracked under the
medium-tier soft-ref findings.
Regression: tests/Insurance/TenantInsuranceCleanupTest.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The ledger FK used ON DELETE CASCADE on a non-nullable column, so deleting a
Payment silently destroyed its immutable financial breakdown rows. Switch to
RESTRICT — a settled payment can no longer be deleted out from under its ledger.
Regression: tests/Settlement/FinancialBreakdownIntegrityTest.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
reference_id (the gateway's settled-transaction ref) was not unique, so the
same successful callback — or a RefNum replayed onto another order — could
credit twice. Add a unique index (NULL until success, so pending/failed rows
don't collide) and an application-level pre-check in the callback that fails the
payment if the reference already belongs to another order. The unique index is
the hard backstop behind the check.
Regression: PaymentCallbackAmountTest::testReplayedGatewayReferenceIsRejected.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A non-unique index on (doctor_id, slot_start) plus a count-then-insert check
left a TOCTOU race: two concurrent requests could both pass isSlotTaken and
both insert. wrapInTransaction alone doesn't stop the phantom under InnoDB
REPEATABLE-READ.
Add a nullable, unique active_slot_key on Appointment = "doctorId:slotStart"
while the booking occupies the slot (pending/confirmed — in lockstep with
isSlotTaken); NULL once expired/completed/no_show/cancelled (NULLs don't collide
in a MySQL unique index, so released slots rebook freely). bookAtomically now:
catches the unique violation -> SlotTakenException, and expires lapsed pendings
in-transaction so the ~1-min window before the expiry cron doesn't wrongly block
rebooking. All three booking paths (online / my / admin) routed through it.
Migration backfills one row per (doctor, slot) — the latest id — so the index
builds even on dirty historical data without destructively cancelling bookings.
(Backfill surfaced a real pre-existing double-booked slot in dev data.)
Regression: tests/Appointment/SlotUniquenessTest. Adjusted the expiry-service
test fixture to use distinct slots (one live booking per slot is now enforced).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
createAppointment only checked the caller held an allowed role, then booked
onto whatever doctor_uuid the request named — a doctor could book onto any
other doctor's calendar, a clinic onto doctors outside it, a secretary outside
their scope. Add canBookForDoctor(): doctor→own only, clinic→member doctors,
secretary→active scope + appointments.create permission, admin→any.
Regression: tests/Appointment/BookingScopeTest.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The callback marked an order success on any verify-ok result without comparing
the gateway-settled amount to the amount charged. SEP returns AffectiveAmount;
an underpayment or a replayed RefNum from a cheaper order would confirm the
expensive order. Now reject (status=failed, no activation) when the gateway
reports an amount that mismatches the stored amount_rials. Gateways that don't
report a settled amount (Mellat binds it server-side) skip the check.
MockGateway now echoes mock_amount so the guard is exercisable in tests.
Regression: tests/Payment/PaymentCallbackAmountTest (underpayment rejected,
matching amount succeeds).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Persists the audit plan so a session restart no longer loses it (TodoWrite
is volatile). 10 done, 1 critical, 10 high, 21 medium, 12 low, 4 epics.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A representation editing its own record could raise its own commission or
self-activate (privilege escalation). Restrict both fields to ROLE_ADMIN and
range-check commission (0–100). Owner can still edit name/city/bank.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- container_xml_path -> containerXmlPath (phpstan-symfony v2 rename); the old
key made phpstan abort with an invalid-configuration error, so analysis
silently never ran
- add the missing tests/doctrine_object_manager.php loader
- drop a stale ignoreErrors pattern
phpstan now runs and surfaces 42 pre-existing level-5 errors (tracked separately).
- appointments(status, expires_at): the per-minute expiry scheduler filtered on
these with no covering index
- patient_sessions(created_at): dashboard revenue range scans
- users(status): admin user-list filter
PatientRecord(entity_type,entity_id) already covered by its unique constraint;
UserActiveContext.user_id is the PK — neither needed a new index.
AppointmentExpiryService ran one findPendingByAppointment query per expiring
booking. Add PaymentRepository::findPendingByAppointments (one IN query keyed
by appointment id) and use it. Test covers expiry + payment cancellation for
several appointments at once.
Eight required (nullable:false) FKs had no referential action. Set per the
codebase's existing pattern: CASCADE for owned relations (doctor_insurances,
doctor_secretaries), RESTRICT for owner/reference FKs (Doctor/Clinic.user_id,
invited_by_id, subscription plan/period). Only the two CASCADE FKs need DDL —
RESTRICT is the MySQL default.
Auto-discovers each mapped entity that has a sibling <Entity>Repository class
and asserts getRepository() returns it (not Doctrine's default). Catches the
prod-only opcache.preload bug class that broke /oauth/userinfo.
getOverride leaked any doctor's override to any authenticated user; add the
owner-or-admin check (matching the update/delete endpoints) + regression test.
getSchedule returned any doctor's schedule to any authenticated user — the
mutation endpoints (update/delete) already checked owner-or-admin but this GET
did not. Add the same check + regression test (fails without the fix).
On prod (opcache.preload + prod container), getRepository(Entity::class)
returned Doctrine's default repository instead of the custom one when the
entity's #[ORM\Entity] had no repositoryClass — so custom finders like
DoctorSecretaryRepository::findAllActiveBySecretary threw BadMethodCallException,
making /oauth/userinfo return 500 after login. Declare repositoryClass explicitly
on all 25 affected entities.
Also add app:create-admin command (create/promote a ROLE_ADMIN user by mobile).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Coolify builds with --no-cache, so intl (C++) recompiles from source every
deploy (~180s single-threaded) and overran the build timeout (exit 255).
Compile across all cores via MAKEFLAGS=-j$(nproc) to cut it several-fold.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Coolify-doc-driven production hardening of the deploy stack:
- run the whole stack as non-root www-data; nginx on 8080 (non-privileged),
pid in /tmp, user directive dropped (Coolify routes to any port)
- docker/healthcheck.sh: hit real /health route via PHP (not just port probe)
- split OPcache config into docker/php/opcache.ini
- graceful shutdown: supervisord stopsignal/stopwaitsecs + worker stop_grace_period
- APCu intentionally not added (Symfony cache uses redis)
- DEPLOY.md: 8080 port, non-root, resource-limit guidance
Verified on linux/amd64: non-root uid=82, /health 200, migrations run,
worker process healthcheck OK.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
worker-async crashed in a loop with 'No transport supports Messenger DSN
redis://...' because symfony/redis-messenger was never installed — 10x restart
killed the whole stack. Add the package (v7.4.8).
Also harden healthchecks:
- app: hit the real /health route via PHP get_headers (verifies app boots and
serves, not just that port 80 is open)
- workers: confirm the messenger:consume process is alive via busybox ps
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Coolify build host intermittently gets HTTP 400 from codeload.github.com on
Composer dist downloads. Bump COMPOSER_HTTP_RETRIES, wrap the install in a
5x retry loop, and on final attempt fall back to --prefer-source (git clone,
different endpoint than dist zips).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Symfony Dotenv::bootEnv() hard-requires a .env file even in prod. The repo's
.env holds dev secrets and is gitignored, so Coolify's clone ships none and the
app fatals with 'Unable to read /app/.env'. Write a minimal APP_ENV=prod .env
at build if one wasn't copied; all real values still come from the compose
environment (clear_env=no), which Dotenv never overwrites.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
pecl install redis and install-php-extensions both fail on the Coolify build
host with 'No releases available for package pecl.php.net/redis' — that host
cannot reach the pecl registry. Build phpredis 6.1.0 from its GitHub source
tarball instead (github.com is reachable); pdo_mysql/intl/opcache stay as
bundled docker-php-ext-install (no network).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Added Dockerfile for multi-stage build including PHP, Node.js, and Nginx.
- Created docker-compose.coolify.yaml for service orchestration with app, workers, MariaDB, and Redis.
- Introduced entrypoint.sh for initialization tasks like JWT key generation and database migrations.
- Configured Nginx with default.conf for handling requests and routing to PHP-FPM.
- Added php.ini with production settings and opcache configuration.
- Set up supervisord.conf to manage PHP-FPM and Nginx processes.
- Created frontend-domains.json for managing allowed frontend domains.
- Added gen-cors-env.php script to generate CORS environment variables from frontend domains.
- Updated framework.yaml to configure trusted proxies and headers.
- Created .dockerignore to exclude unnecessary files from the Docker context.
- Added .env.coolify.example for environment variable configuration.
- Documented deployment steps and troubleshooting in coolify.md.
- Created a new JSON file for the representation API documentation, including nodes and edges that describe the API structure and relationships.
- Added another JSON file for the ApiIrService class, detailing its methods, imports, and relationships with other components.
- Added a new column `national_code_verified` to the `users` table.
- Normalized the `bank_account` field in the `representations` table from a single object to an array of IBANs with a default `verified` status of false.
feat(ApiIrService): implement identity verification client for api.ir
- Created `ApiIrService` to handle identity verification via api.ir.
- Implemented methods for matching national code with mobile and IBAN with national code and birth date.
- Added error handling and logging for external API requests.