# Street Sweeping Inspection PWA — Final Implementation Brief > Audience: an AI coding agent that will implement this project end to end. > > Owner: Sari Municipality, Urban Services (IT/FAVA). > > Product language: **Persian (fa-IR), RTL, Jalali dates**. > > **Read this whole document before writing code. Follow the milestone order in §14.** > > This document is the **single source of truth**. Do not invent unspecified vendor APIs or business rules. > > Where something is marked **OPEN**, use the stated default and leave a `TODO(open)` comment. > > **Important:** This specification uses **MariaDB 11.4+**, not PostgreSQL/PostGIS. Do not introduce PostgreSQL/PostGIS dependencies. --- # 1. Context and goal One duty of Sari Municipality's Urban Services is cleaning alleys and streets (رفت و روب). The workforce is organised as a three-level hierarchy: ```text ناظر خدمات شهری (Urban Services Supervisor) ~10 people | مسئول رفت و روب (Sweeping Officer) count unknown | کارگر رفت و روب (Sweeping Worker) < 200 people ``` Default for development/seed data: ```text 2 supervisors 4 officers ~12 workers ``` There is **no code-level limit** on the number of production officers/workers. Workers are NOT system users in phase 1. Each worker is responsible for a manually drawn polygon work area. Management also assigns each worker an **approximate daily target in metres**. This is a plain number entered by management. The system does **not** calculate the total length of all roads/streets inside the work area. Every night, supervisors/officers go **on site** and inspect each worker's area. When a stretch was not cleaned properly, the inspector marks it on a map by clicking points. The system then: * snaps the clicked points to pedestrian routes using Neshan, * constructs the route through consecutive clicked points, * calculates raw length, * removes repeated route portions, * calculates **unique length**, * records a grade, * stores the affected geometry, * associates the issue with the responsible worker, * and exposes the result in reports. Management must be able to answer: * how many metres were left uncleaned, * by whom, * where, * on which dates, * at what grade, * how often the same place repeated, * and how a worker/area performs over time. --- # 1.1 Core ideas These rules drive every design decision. ## 1. Worker work area A worker has: ```text work area = manually drawn polygon daily target = approximate number of metres entered by management ``` Do not calculate road length inside this polygon. The polygon is only the worker's operational boundary. --- ## 2. Uncleaned stretch An inspector marks an uncleaned stretch by clicking any number of points. Points are ordered. Between each two consecutive points in the same chain: ```text clicked point A ↓ Neshan pedestrian routing ↓ street-following route ↓ clicked point B ``` The route is drawn on the map. Points can be dragged to adjust them. --- ## 3. Multiple chains An inspection item can contain multiple chains. A new chain starts only when the inspector presses: ```text شروع بخش جدید ``` Example: ```text Chain 0: P1 → P2 → P3 Chain 1: P4 → P5 Chain 2: P6 → P7 → P8 ``` Each consecutive pair inside each chain becomes one route. --- ## 4. Repeated routes Routes can overlap. This is expected. Examples: * entering a dead end and returning, * going down a branch and returning on the same street, * starting a new route on a street already traversed, * multiple routes overlapping partially. Every metre must be counted only once. The resulting value is: ```text length_unique_m ``` This is the authoritative number used in reports. Repeated portions must be visually highlighted in orange in the inspection UI. --- ## 5. Grades Each issue has exactly one grade: ```text fair = نسبتاً تمیز dirty = کثیف not_done = انجام نشده ``` UI colours: ```text fair = yellow dirty = orange not_done = red ``` --- ## 6. Inspection record Every worker must have exactly one inspection record per operational date. This is important because: ```text no inspection ``` must be distinguishable from: ```text inspection completed with no problem ``` Therefore: ```text result = ok ``` means: > بازرسی شد، مشکلی نبود and counts as inspected with: ```text unclean_total = 0 ``` No record means: > بازرسی نشده --- ## 7. Reports Reports must show uncleaned stretches for arbitrary date ranges. The map must visually communicate repetition: ```text 1 occurrence yellow 2–3 occurrences orange 4+ occurrences red ``` Repetition is based on **distinct operational dates**, not number of inspection items. --- # 2. Product scope We are building: 1. Mobile-first PWA for field inspection. 2. Desktop-friendly admin/dashboard UI. 3. Laravel 13 API. 4. MariaDB 11.4+ / InnoDB / Spatial. 5. Neshan map. 6. Neshan pedestrian routing. 7. Offline inspection outbox. 8. Worker work-area management. 9. Reporting and CSV export. --- # 3. Explicitly out of scope The following are NOT required in phase 1: * worker login, * worker-facing app, * worker self-reporting, * municipal road-network GIS import, * computing total road length inside a work polygon, * automatic work-area splitting, * live GPS tracking, * GPS trace map matching, * PDF reports, * push notifications, * Bale bot integration. --- # 4. GIS strategy There is no municipal road-network GIS dataset available for phase 1. We do NOT build a road network. We use: 1. Neshan base map for visualization. 2. Neshan pedestrian routing for snapping/correct street-following route generation. 3. Manually drawn worker work-area polygons. 4. Inspector-created clicked points. 5. Derived route geometry returned by Neshan. 6. Application-side geometry/length algorithms. The system does not import OSM. The system does not require municipal road GIS. --- # 5. Technology | Layer | Choice | | ----------------- | -------------------------------------- | | Backend | PHP 8.3+, Laravel 13 | | Authentication | Laravel Sanctum | | Database | MariaDB 11.4+ | | Engine | InnoDB | | Spatial | MariaDB Spatial | | Frontend | Vue 3 + TypeScript + Vite | | State | Pinia | | Router | vue-router | | PWA | vite-plugin-pwa / Workbox | | Offline DB | IndexedDB via `idb` | | Map | Neshan Web SDK, OpenLayers build | | Dates | Jalali display; Gregorian `DATE` in DB | | UI | RTL, Persian digits, Vazirmatn | | Theme | Dark-first/night-friendly UI | | Production | cPanel | | Local development | XAMPP | | Queue | Laravel database queue | | Scheduler | Laravel scheduler + cPanel Cron | | Timezone | Asia/Tehran for operational date logic | --- # 5.1 Database environment The verified production database environment is: ```text MariaDB 11.4.13 InnoDB PHP 8.4.25 cPanel 11.138.0.11 ``` The following have been manually verified on the real server: * POINT * POLYGON * LINESTRING * SRID 4326 * SPATIAL INDEX * geometry insertion * geometry reading * `ST_CONTAINS` / containment behaviour Do not replace MariaDB with PostgreSQL. Do not install or require PostGIS. Do not use PostgreSQL-specific SQL. --- # 5.2 Database conventions All user-facing tables: ```text ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ``` Prefer: ```text utf8mb4_unicode_ci ``` or another UTF-8 collation confirmed compatible with the production MariaDB version. Never use: ```text latin1 ``` All timestamps use the Laravel application convention and UTC storage where timestamps are persisted. Operational date is stored separately as a Gregorian `DATE`. --- # 6. Spatial data conventions All application geometries use: ```text SRID = 4326 ``` Coordinate order is: ```text longitude, latitude ``` Example: ```text POINT(53.06 36.56) ``` Geometry columns use native MariaDB spatial types: ```text POINT LINESTRING POLYGON MULTILINESTRING ``` Do NOT use PostgreSQL/PostGIS syntax such as: ```text geometry(...) GEOGRAPHY GiST GIST CREATE EXTENSION postgis ST_Transform ST_DWithin ::geometry jsonb timestamptz bigserial ``` For every application write that stores geometry, validate: ```text ST_SRID(geometry) = 4326 ``` where supported. The authoritative distance algorithm does not depend on database projections. --- # 6.1 Spatial indexes Use MariaDB/InnoDB SPATIAL INDEX on non-null geometry columns where useful. Example: ```sql SPATIAL INDEX idx_work_areas_geom (geom) ``` Do NOT add a SPATIAL INDEX to nullable geometry columns unless the implementation has been verified for the exact MariaDB target. `work_areas.geom` is NOT NULL and should have a spatial index. `item_routes.geom` is NOT NULL and may have a spatial index if profiling shows value. `inspection_items.geom_raw` and `geom_unique` may be NULL during pending routing, so do not blindly create spatial indexes on those columns. --- # 7. Organisation and permissions Roles: ```text admin supervisor officer ``` Workers are not users. Hierarchy: ```text admin | ├── supervisor | | | ├── officer | | ├── worker | | └── worker | | | └── officer | └── supervisor ``` Database relationships: ```text users.parent_id: officer -> supervisor workers.officer_id: worker -> officer ``` --- # 7.1 Permissions | Capability | admin | supervisor | officer | | --------------------------------- | ---------------- | ---------------- | ---------------- | | Manage users | all | no | no | | See workers/areas | all | own tree | own workers | | Create/edit workers | yes | yes in scope | yes in own scope | | Create/edit work areas | yes | yes in scope | yes in own scope | | Create inspections | yes | yes in scope | own workers | | Edit own/scope inspection | yes | yes in scope | own | | Edit another officer's inspection | yes | yes within scope | no | | Reports | all | own scope | own scope | | Delete inspections | soft delete, yes | no | no | --- # 7.2 Authorization implementation Use Laravel Policies. Also create a reusable query scope/service concept: ```text visibleTo($user) ``` Every: * worker list, * worker map, * area query, * inspection list, * report, * report map, * inspection detail, * photo access must apply authorization scope. Do not rely only on controller-level filtering. Required tests must prove that: ```text officer A cannot see worker B officer A cannot see B's inspections officer A cannot see B's areas officer A cannot see B's report rows officer A cannot see B's map features ``` Supervisor sees only the complete subordinate tree. --- # 8. Data model Use Laravel migrations. Do not depend on PostgreSQL-specific migration helpers. Use raw SQL only where MariaDB Spatial definitions/indexes require it. --- ## 8.1 users ```sql users ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, phone VARCHAR(30) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, role VARCHAR(20) NOT NULL, parent_id BIGINT UNSIGNED NULL, active TINYINT(1) NOT NULL DEFAULT 1, created_at DATETIME(6) NULL, updated_at DATETIME(6) NULL, deleted_at DATETIME(6) NULL ) ``` Roles: ```text admin supervisor officer ``` Enforce parent hierarchy in application logic and tests. --- ## 8.2 workers ```sql workers ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, code VARCHAR(100) NULL UNIQUE, first_name VARCHAR(100) NOT NULL, last_name VARCHAR(100) NOT NULL, photo_path VARCHAR(500) NULL, officer_id BIGINT UNSIGNED NOT NULL, daily_target_m INT UNSIGNED NULL, active TINYINT(1) NOT NULL DEFAULT 1, created_at DATETIME(6) NULL, updated_at DATETIME(6) NULL, deleted_at DATETIME(6) NULL ) ``` `daily_target_m` is approximate and entered manually. No road-network calculation is used to derive it. --- # 8.3 work_areas Work-area history must never be overwritten. When a new area is assigned: 1. close previous open area, 2. insert a new row. `valid_to` is **exclusive**. Example: ```text old: valid_from = 2026-10-01 valid_to = 2026-10-10 new: valid_from = 2026-10-10 valid_to = NULL ``` Thus the new area is valid on 2026-10-10. Schema: ```sql work_areas ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, worker_id BIGINT UNSIGNED NOT NULL, geom POLYGON NOT NULL, valid_from DATE NOT NULL, valid_to DATE NULL, created_by BIGINT UNSIGNED NULL, created_at DATETIME(6) NULL, updated_at DATETIME(6) NULL, INDEX idx_work_areas_worker_dates (worker_id, valid_from, valid_to), SPATIAL INDEX idx_work_areas_geom (geom) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` All inserted polygons must contain SRID 4326. Exactly one open area per worker must exist. MariaDB does not provide PostgreSQL partial unique indexes. Preferred implementation: ```text generated/open marker column + unique index ``` or a transaction-safe application constraint. Do not allow two simultaneous open areas. --- # 8.4 inspections ```sql inspections ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, client_uuid CHAR(36) NOT NULL UNIQUE, worker_id BIGINT UNSIGNED NOT NULL, inspector_id BIGINT UNSIGNED NOT NULL, op_date DATE NOT NULL, result VARCHAR(20) NOT NULL, note TEXT NULL, inspected_at DATETIME(6) NOT NULL, submitted_at DATETIME(6) NOT NULL, version INT UNSIGNED NOT NULL DEFAULT 1, created_at DATETIME(6) NULL, updated_at DATETIME(6) NULL, deleted_at DATETIME(6) NULL, UNIQUE KEY uq_inspection_worker_date (worker_id, op_date), INDEX idx_inspections_op_date (op_date) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` `result`: ```text ok issues ``` There must be one inspection per: ```text worker_id + op_date ``` --- # 8.5 inspection_items One issue item is one group of clicked points belonging to one grade. ```sql inspection_items ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, inspection_id BIGINT UNSIGNED NOT NULL, worker_id BIGINT UNSIGNED NOT NULL, op_date DATE NOT NULL, grade VARCHAR(20) NOT NULL, note TEXT NULL, points JSON NOT NULL, geom_raw MULTILINESTRING NULL, geom_unique MULTILINESTRING NULL, length_raw_m DECIMAL(10,1) NULL, length_unique_m DECIMAL(10,1) NULL, api_length_m DECIMAL(10,1) NULL, inside_area_m DECIMAL(10,1) NULL, status VARCHAR(20) NOT NULL DEFAULT 'ready', created_at DATETIME(6) NULL, updated_at DATETIME(6) NULL, deleted_at DATETIME(6) NULL, INDEX idx_items_op_worker (op_date, worker_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` Grades: ```text fair dirty not_done ``` Statuses: ```text ready pending_snap snap_failed ``` `points` stores: ```json [ {"lat":36.56,"lng":53.06,"chain":0}, {"lat":36.561,"lng":53.061,"chain":0} ] ``` --- # 8.6 item_routes One row per consecutive pair of clicked points. ```sql item_routes ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, item_id BIGINT UNSIGNED NOT NULL, seq INT NOT NULL, chain INT NOT NULL, from_pt POINT NOT NULL, to_pt POINT NOT NULL, snapped_from POINT NULL, snapped_to POINT NULL, geom LINESTRING NOT NULL, method VARCHAR(20) NOT NULL, api_length_m DECIMAL(10,1) NULL, created_at DATETIME(6) NULL, updated_at DATETIME(6) NULL, INDEX idx_item_routes_item_seq (item_id, chain, seq) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` `method`: ```text snap manual ``` All geometry uses SRID 4326. --- # 8.7 item_photos ```sql item_photos ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, item_id BIGINT UNSIGNED NOT NULL, path VARCHAR(500) NOT NULL, created_at DATETIME(6) NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` --- # 8.8 audit_logs ```sql audit_logs ( id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, user_id BIGINT UNSIGNED NULL, entity VARCHAR(100) NOT NULL, entity_id BIGINT UNSIGNED NULL, action VARCHAR(100) NOT NULL, changes JSON NULL, created_at DATETIME(6) NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` Audit: * inspection create/edit/delete, * user changes, * worker changes, * area changes, * relevant permission-sensitive changes. --- # 9. Worker map layer For every active worker, display: * work-area polygon, * worker name, * worker photo, * responsible officer, * daily target. At zoom >= 15: ```text round photo + first/last name ``` using HTML overlay. At lower zoom: ```text small coloured dot + initials ``` Avoid label overlap. Clicking a worker feature/card opens: ```text photo name officer daily target last 7 nights summary ``` --- # 10. Work-area editor Desktop-friendly. Features: * draw polygon, * edit vertices, * delete polygon, * show area in m², * show overlap warning, * save as new historical row, * view area history. Worker area label point: ```text point on surface of polygon ``` Do not use a simple centroid if it can fall outside the polygon. Current area is the row where: ```text valid_from <= requested_date AND ( valid_to IS NULL OR requested_date < valid_to ) ``` --- # 10.1 Overlap warning Overlapping work areas are allowed. They are not a validation error. When saving an area: * detect overlap with other active work areas relevant to the same date, * display a warning, * do not block save. Default: > any non-zero overlap = warning. Leave `TODO(open)` if a percentage/area threshold is requested later. --- # 11. Neshan integration ## 11.1 Keys Two different keys exist. ### Service key Purpose: ```text Pedestrian Routing API ``` Environment: ```env NESHAN_SERVICE_KEY= ``` Rules: * server only, * never sent to browser, * never committed, * never logged. ### Web map key Purpose: ```text browser map SDK ``` Environment: ```env NESHAN_MAP_KEY= ``` Rules: * sent through authenticated `/api/config`, * domain-restricted in Neshan panel, * not treated as a server secret, * never confuse it with service key. --- # 11.2 Neshan map SDK Use the OpenLayers build specified by the approved PoC: ```html ``` npm alternative: ```text @neshan-maps-platform/ol ``` Map creation: ```js const map = new ol.Map({ mapType: 'neshan', target: 'map', key: MAP_KEY, poi: false, traffic: false, view: new ol.View({ center: ol.proj.fromLonLat([53.0601, 36.5633]), zoom: 14 }) }); ``` Add custom vector layers after creation. Do not pass custom layers to the constructor. Port PoC behaviours: * vector layers, * draggable pins, * Translate interaction, * `singleclick`, * `dblclick`, * removing `DoubleClickZoom`. **OPEN:** whether Neshan tiles may be cached for offline use. Default: ```text do not cache Neshan map tiles. ``` --- # 11.3 Pedestrian routing API Use only this documented endpoint: ```text GET https://api.neshan.org/v4/direction ``` Never invent other endpoints. Header: ```text Api-Key: ``` Parameters: ```text type=pedestrian origin=, destination=, waypoints=,|, optional, not used alternative=true|false optional, not used bearing=0..360 optional ``` URL encode query parameters. `|` must become: ```text %7C ``` --- # 11.4 Neshan response Relevant structure: ```json { "routes": [ { "overview_polyline": { "points": "..." }, "legs": [ { "summary": "...", "distance": { "value": 574.0 }, "duration": {}, "steps": [ { "name": "...", "distance": { "value": 4.0 }, "polyline": "...", "start_location": [53.06, 36.56] } ] } ] } ] } ``` Rules: * use `routes[0]`, * do NOT use `overview_polyline` for geometry, * geometry is concatenation of all `steps[].polyline`, * encoded polyline precision = 5, * drop duplicate junction vertex between steps, * `start_location` is `[lng, lat]`, * `origin` is `[lat,lng]`, * verify snapped start/end behaviour against PoC/recorded fixture. Do not store raw Neshan response. Only store the derived route data needed by the application. --- # 11.5 Neshan response storage/cache Do not persist raw vendor responses. A short-lived route cache <= 24h is allowed. Cache key: ```text rounded origin + rounded destination ``` Recommended client key: ```text lat6,lng6>lat6,lng6 ``` **OPEN:** Neshan terms regarding storage/caching of returned geometry. Default: * derived application geometry may be stored, * raw response may not be stored, * route cache <= 24h, * keep provider behind an interface so it can be replaced. --- # 11.6 Routing service abstraction Create: ```text App\Services\Routing\RoutingProvider ``` interface. Implementation: ```text NeshanPedestrianProvider ``` Controllers must not know Neshan response structure. Only this service understands: ```text routes[0] legs steps polyline start_location ``` A future self-hosted Valhalla/OSRM implementation must not require controller/frontend changes. --- # 11.7 Routing endpoint Authenticated: ```text POST /api/routing/pedestrian ``` Request: ```json { "from": { "lat": 36.56, "lng": 53.06 }, "to": { "lat": 36.561, "lng": 53.061 } } ``` Success: ```json { "polyline": "", "api_length_m": 643.0, "snapped_from": { "lat": 36.56, "lng": 53.06 }, "snapped_to": { "lat": 36.561, "lng": 53.061 } } ``` No route: ```http 404 ``` ```json { "code": "no_route" } ``` Rate limit: ```http 429 ``` ```json { "code": "rate_limited" } ``` Upstream: ```http 502 ``` ```json { "code": "upstream_error", "upstream": 481 } ``` --- # 11.8 Routing errors Known upstream statuses: ```text 400 bad params 470 bad coordinates 480 missing/invalid key 481 quota exceeded 482 per-minute rate exceeded 483 wrong key type 484 key scope/whitelist 485 service not enabled 500 generic ``` Rules: * timeout: 15 sec, * no retries on 4xx, * one retry on network error, * short route cache, * upstream 481/482 -> local 429, * never log service key. --- # 12. Length algorithm This section is authoritative. The approved PoC already exists: ```text poc/index.html poc/proxy.php ``` Port behaviour faithfully. Implement algorithm twice: ```text TypeScript PHP ``` Both must produce the same results. Shared fixtures: ```text docs/fixtures/dedupe/ ``` --- # 12.1 Constants ```text STEP = 1 metre DEDUP_RADIUS = 3 metres SNAP_WARN = 30 metres ``` --- # 12.2 Pair routing Points are processed in click order. Only consecutive points in the same chain are routed. Pairs with original clicked-point Haversine distance: ```text < 2 metres ``` are skipped. Do not call Neshan for these pairs. --- # 12.3 Request efficiency A new/moved point should cause at most approximately 1–2 routing calls. Client route cache: ```text lat6,lng6>lat6,lng6 ``` Only changed pairs are requested. Debounce: ```text 400 ms ``` Stale responses must be discarded using a run-id/token. Stop the routing loop on: ```text 480 481 482 483 ``` until user action/state permits a retry. --- # 12.4 Raw length ```text length_raw_m = sum(length of every pair route) ``` All pair routes count, including repeated routes. --- # 12.5 Unique length Process pair routes in order. Maintain a spatial hash of samples from earlier pair routes. Grid cell size: ```text DEDUP_RADIUS = 3m ``` For each route: 1. sample polyline every 1 metre using cumulative distance; 2. final remainder is retained; 3. compare current samples only against earlier route samples; 4. current route does not compare against itself; 5. check current cell plus surrounding 3x3 cells; 6. Haversine/local metric distance determines duplicate; 7. duplicate sample does not contribute to unique length; 8. non-duplicate sample contributes its weight; 9. after processing route, insert all current-route samples into the spatial hash. A repeated run of consecutive duplicate samples with at least 2 samples is displayed in orange. --- # 12.6 Sample weight definition Sampling must be deterministic. For a route length of 3.4m: ```text 0m -> weight 1.0 1m -> weight 1.0 2m -> weight 1.0 3m -> weight 0.4 ``` General rule: * samples occur at cumulative positions 0, 1, 2, ..., * the final remainder sample carries the exact remaining weight, * all sample weights sum to the route length within floating-point tolerance. This exact rule must be implemented identically in PHP and TypeScript. --- # 12.7 Local metric grid Use a local equirectangular projection around the first point: ```text kx = 111320 * cos(lat0) ky = 110540 ``` Use Haversine: ```text R = 6371008.8m ``` for polyline distances and duplicate checks where specified. --- # 12.8 Geometry outputs Store: ```text geom_raw geom_unique ``` `geom_unique` is generated from runs of consecutive non-duplicate samples. Single-vertex runs do not make a visible line and may be omitted from `geom_unique`. Their sampling weight remains part of: ```text length_unique_m ``` Therefore: ```text length_unique_m ``` is authoritative and must NOT be expected to equal database geometry length. Do not substitute: ```text ST_Length(geom_unique) ``` for the authoritative algorithm. --- # 12.9 TS/PHP parity Use shared fixtures: ```text out_and_back_dead_end mid_street_start parallel_streets_12m_apart ``` Required tolerance: ```text ±0.5m ``` Both implementations must pass the same fixture set. --- # 12.10 Snap quality After routing: * show original clicked point, * show snapped point, * draw dashed connector, * measure snap distance. If snap distance > 30m: ```text نقطه N: X متر با معبر فاصله دارد ``` If no route: * show dashed red straight line, * exclude that pair from totals, * show a message. Inspector may choose: ```text manual ``` Manual route: * straight segment, * `method='manual'`, * flagged in reports. --- # 13. inside_area_m Do not use road-network calculation. For each item's unique route: ```text inside_area_m ``` means the approximate unique route length lying inside the worker's work-area polygon valid on `op_date`. Default implementation: 1. reuse the same 1m sample/weight representation, 2. test each sample against the worker polygon, 3. sum weights of samples inside the polygon, 4. use same local metric model as unique-length algorithm. The result is approximate at the sampling resolution. Warning condition: ```text inside_area_m < 0.8 * length_unique_m ``` Show: ```text ⚠ بیشتر مسیر ثبت‌شده خارج از محدوده کاری است. ``` Do not block save. Reports should preserve this warning/metric. --- # 14. Inspection workflows ## 14.1 Admin/officer setup ### Create officers Admin creates officers under supervisors. ### Create worker Fields: * first name, * last name, * code, * photo, * officer, * daily target. Photo processing: * client-side resize, * max 1600px, * JPEG, * quality approximately 0.8. ### Draw work area Admin/supervisor/officer within scope can: * draw polygon, * edit vertices, * delete, * see area in m², * see overlap warning, * save new historical area. Previous area is closed. Never overwrite historical geometry. --- # 14.2 Nightly inspection Screen: ```text بازرسی شبانه ``` Header: ```text operational date in Jalali ``` Checklist includes all workers in scope. Each worker displays: ```text بازرسی نشده بدون مشکل دارای مشکل (N متر) ``` Filters: ```text all not inspected ok issues ``` Search by worker name. --- # 14.3 Worker inspection screen Tap worker. Map opens: * centered on work area, * polygon visible, * worker card visible, * inspector GPS visible, * button: ```text موقعیت من ``` * accuracy circle. --- # 14.4 No-problem flow Button: ```text بازرسی شد، مشکلی نبود ``` creates: ```text inspection.result = ok ``` with zero issue length. --- # 14.5 Problem flow Inspector: 1. clicks points, 2. drags points, 3. can delete last point, 4. can double-click a pin to remove, 5. can start a new chain, 6. sees snap points, 7. sees connectors, 8. sees repeated portions, 9. sees unique length live, 10. sees raw length live, 11. sees warnings. Then selects: ```text نسبتاً تمیز کثیف انجام نشده ``` Optional: * note, * photos. Press: ```text ثبت مورد ``` The item is added to the inspection. The inspector may create multiple items for the same worker/night. Example: ```text Item 1 = dirty Item 2 = fair Item 3 = not_done ``` --- # 14.6 Complete inspection Button: ```text ثبت بازرسی ``` Submits the inspection. Editing later updates the same: ```text worker_id + op_date ``` inspection. Every edit is audit logged. --- # 14.7 Global-map inspection If inspection starts globally without choosing a worker: 1. inspector draws issue, 2. system estimates which worker area contains most of the stretch, 3. suggests that worker, 4. inspector confirms or changes. This is: ```text should-have ``` not mandatory for initial MVP if it materially complicates the flow. Leave: ```text TODO(open) ``` if deferred. --- # 15. Operational date Inspection nights cross midnight. Operational date: ```text Asia/Tehran local time ``` Rule: ```text before 06:00 op_date = previous calendar date 06:00 or later op_date = current calendar date ``` Examples: ```text 23:30 on 2026-10-04 → op_date = 2026-10-04 01:30 on 2026-10-05 → op_date = 2026-10-04 06:00 on 2026-10-05 → op_date = 2026-10-05 ``` Admin/supervisor may change operational date for dates older than 3 days. Officers cannot change old dates beyond the allowed window. Required tests: ```text 23:30 01:30 06:00 ``` --- # 16. Inspection metrics ## Per item Store: ```text length_unique_m length_raw_m api_length_m inside_area_m grade ``` --- ## Per worker/night ```text fair_m dirty_m not_done_m unclean_total_m ``` Where: ```text unclean_total_m = fair_m + dirty_m + not_done_m ``` --- ## Approximate completion Only when: ```text daily_target_m > 0 ``` Formula: ```text max( 0, 100 * (daily_target_m - unclean_total_m) / daily_target_m ) ``` Display with label: ```text تقریبی ``` --- ## Worker/range metrics For arbitrary date range: * nights inspected, * nights with issues, * fair metres, * dirty metres, * not-done metres, * total uncleaned metres, * average approximate completion. --- # 17. Offline behaviour The field environment may have weak or intermittent internet. PWA must support offline operation. After first successful load, cache in IndexedDB/service worker: * workers in scope, * work areas, * checklist data, * worker thumbnails, * app shell. Do not assume Neshan map tiles are available offline. --- # 17.1 Offline outbox Submission is written to IndexedDB. Every submission has: ```text client_uuid ``` and is safely retryable. Use: ```text retry with exponential backoff ``` and Background Sync where supported. Show: ```text آفلاین ``` banner. Show: ```text صف ارسال: N ``` counter. --- # 17.2 Offline routing Routing needs internet. When offline: 1. save clicked points, 2. show approximate straight-line length, 3. label: ```text تقریبی — در انتظار محاسبه ``` 4. submit item with: ```text status = pending_snap ``` 5. no `item_routes` yet, 6. server queue later calls Neshan, 7. builds routes, 8. recomputes raw/unique lengths, 9. sets: ```text ready ``` or: ```text snap_failed ``` The SPA displays final values after sync. --- # 18. Idempotent sync `client_uuid` is the idempotency key. Same request repeated: ```text same client_uuid + same authenticated user + same logical payload ``` must return the existing record. Do not create duplicates. Conflicting reuse: ```text same client_uuid + different logical payload ``` must return: ```text 409 idempotency_conflict ``` --- # 19. Inspection versioning Add: ```text version INT UNSIGNED DEFAULT 1 ``` to inspections. When editing: ```text client sends version server compares version ``` If stored version differs: ```text 409 inspection_version_conflict ``` This protects against: * offline edits, * two devices, * duplicate tabs. On successful update: ```text version += 1 ``` Preserve photo records unless explicitly removed. Do not blindly destroy/recreate all item rows. --- # 20. Photo handling Worker photos and inspection photos are personal data. Store in private storage. Never expose public direct file paths. Use short-lived signed URLs. Strip EXIF metadata from uploaded images. Worker photo: ```text client resize <=1600px JPEG ~0.8 ``` Inspection photos: * camera-friendly input, * queued offline, * uploaded independently if needed, * associated to item. --- # 21. API Base: ```text /api ``` All responses JSON. Consistent error shape: ```json { "message": "...", "code": "...", "errors": {} } ``` Use Form Requests. Validation messages must be Persian. Use API Resources. Paginate lists. --- # 21.1 Authentication ```text POST /auth/login POST /auth/logout GET /auth/me GET /config ``` Authentication: ```text phone + password ``` SMS OTP is a later swap. Keep the auth boundary modular. --- # 21.2 Users ```text GET /users POST /users PUT /users/{id} DELETE /users/{id} ``` Admin only. --- # 21.3 Workers ```text GET /workers POST /workers PUT /workers/{id} DELETE /workers/{id} POST /workers/{id}/photo ``` Delete must be soft-delete where applicable. --- # 21.4 Work areas ```text GET /workers/{id}/areas POST /workers/{id}/areas ``` Create body: ```json { "geom": { "type": "Polygon", "coordinates": [] }, "valid_from": "2026-10-04" } ``` Server: 1. validates polygon, 2. validates authorization, 3. validates SRID/coordinates, 4. closes previous open area, 5. inserts new row, 6. writes audit log, 7. returns current area. --- # 21.5 Worker map ```text GET /map/workers ``` Returns: ```text GeoJSON FeatureCollection ``` Each feature: * worker ID, * worker name, * officer, * daily target, * area geometry, * label point, * photo URL, * summary data if requested. Only authorized scope is returned. --- # 21.6 Routing ```text POST /routing/pedestrian ``` As defined in §11. --- # 21.7 Inspections ```text GET /inspections?date=YYYY-MM-DD POST /inspections PUT /inspections/{id} DELETE /inspections/{id} GET /inspections/{id} POST /inspections/{id}/items/{item}/photos ``` Delete: ```text admin only soft delete audit log ``` PUT must use inspection versioning. --- # 21.8 Inspection item payload ```json { "grade": "dirty", "note": "...", "points": [ { "lat": 36.56, "lng": 53.06, "chain": 0 }, { "lat": 36.561, "lng": 53.061, "chain": 0 } ], "routes": [ { "seq": 1, "chain": 0, "polyline": "", "api_length_m": 120.0, "snapped_from": { "lat": 36.56, "lng": 53.06 }, "snapped_to": { "lat": 36.561, "lng": 53.061 }, "method": "snap" } ] } ``` --- # 21.9 Server validation of client routes Never trust client length. Server: 1. decodes polyline, 2. validates precision 5, 3. validates first/last vertices, 4. verifies first/last vertex is within 100m of corresponding clicked point, 5. rejects absurd route lengths: ```text > 5 × straight-line + 200m ``` 6. recomputes raw length, 7. recomputes unique length, 8. validates grades, 9. validates chain structure. If `routes` is missing: ```text status = pending_snap ``` Server queue resolves it later. --- # 22. Reports ## 22.1 Summary ```text GET /reports/summary?from&to&officer_id&worker_id ``` Per-worker table. Columns: * worker, * officer, * nights inspected, * nights with issues, * fair metres, * dirty metres, * not-done metres, * total uncleaned metres, * average approximate completion. --- # 22.2 Ranking ```text GET /reports/ranking?from&to ``` Ranking should support: * total uncleaned metres, * percentage, * issue count, * average approximate completion. Default ranking: ```text highest uncleaned metres ``` --- # 22.3 Map report ```text GET /reports/map?from&to&worker_id&officer_id&grade ``` Returns GeoJSON FeatureCollection. Properties: ```text worker op_date grade repeat_count item_id length_unique_m ``` --- # 22.4 Repetition logic Do NOT depend on PostGIS. At requested range: 1. load authorized `geom_unique` geometries, 2. split each line into approximately 10m cumulative-length pieces in PHP, 3. maintain a spatial/grid index in PHP, 4. compare candidate pieces, 5. use Haversine/local metric distance, 6. a piece from date A matches a piece from date B when representative geometry is within 5m according to the configured comparison, 7. count DISTINCT `op_date`, 8. assign: ```text repeat_count ``` Only authorized records participate in the comparison. Distinct date semantics: ```text same date repeated several times = 1 three different dates = 3 ``` Colour: ```text 1 yellow 2–3 orange >= 4 red ``` This calculation can be query-time PHP at current project scale (<200 workers). --- # 22.5 CSV ```text GET /reports/export.csv?from&to&... ``` CSV must be UTF-8. Persian column labels are acceptable if consistent. Recommended columns: ```text کارگر مسئول رفت‌وروب تاریخ نسبتاً تمیز (متر) کثیف (متر) انجام نشده (متر) جمع (متر) درصد تقریبی انجام ``` --- # 23. Frontend screens ## 23.1 Login Fields: ```text شماره موبایل رمز عبور ``` Persian validation. --- ## 23.2 Home / nightly checklist Header: ```text بازرسی شبانه ``` Shows operational date. Worker cards: ```text نام وضعیت متراژ مشکل ``` Status: ```text بازرسی نشده بدون مشکل دارای مشکل (N متر) ``` Large touch targets >= 44px. Dark mode. Persian digits. --- # 23.3 Inspection map screen Must port approved PoC behaviour faithfully. Features: * click to add point, * numbered pins, * first point of each chain green, * drag, * double-click remove, * delete last point, * start new chain, * snap point circles, * dashed snap connectors, * orange repeated sections, * warnings, * live unique length, * live raw length. --- # 23.4 Workers Worker list. Create/edit: * first name, * last name, * code, * photo, * officer, * daily target, * active/inactive. --- # 23.5 Area editor Features: * desktop-friendly drawing, * edit polygon, * delete, * show m², * overlap warning, * save historical area, * history list. --- # 23.6 Worker map dashboard Polygon colour stable by officer. Zoom >= 15: ```text round photo + first/last name ``` Low zoom: ```text dot + initials ``` Avoid overlap. Click -> card. Filters: ```text supervisor officer active/inactive ``` Layer toggles. --- # 23.7 Reports Date range picker: ```text امشب ۷ روز اخیر این ماه ``` Features: * summary table, * ranking, * report map, * repetition legend, * grade filter, * worker filter, * officer filter, * CSV export. --- # 23.8 Admin Manage: * users, * hierarchy, * supervisors, * officers. --- # 24. PWA Manifest: ```text fa RTL standalone icons ``` Service worker: * app-shell precache, * offline page, * runtime caching appropriate for app data, * update prompt. Do not silently cache Neshan tiles. --- # 25. cPanel deployment Production is cPanel. Do not require Docker. Recommended deployment: ```text cPanel | ├── Laravel backend ├── built Vue/PWA assets ├── MariaDB ├── private storage └── Cron ``` Laravel public document root must point to: ```text public/ ``` Never expose: ```text .env vendor/ storage/ source files composer credentials database credentials ``` to public web. Node/Vite are build-time requirements. Production should serve compiled assets. --- # 25.1 Environment Example: ```env APP_ENV=production APP_DEBUG=false APP_URL=https://... DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=... DB_USERNAME=... DB_PASSWORD=... NESHAN_SERVICE_KEY= NESHAN_MAP_KEY= ``` Use Laravel's `mysql` database driver for MariaDB. Never use: ```text DB_CONNECTION=pgsql ``` --- # 25.2 cPanel Cron Use Laravel scheduler. Production must document exact cron commands in: ```text docs/deployment-cpanel.md ``` At minimum: ```text every minute: php artisan schedule:run ``` Queue processing must work without requiring a permanent Supervisor process. Use database queue. Recommended strategy: ```text scheduler ↓ short queue worker invocation ↓ process pending jobs ↓ exit ``` Exact cron syntax must be documented for cPanel. --- # 25.3 Database backup Provide documented backup script/process. At minimum: ```text daily database backup ``` Keep multiple rotations. Document: * where backup is stored, * restore procedure, * backup verification. Backups must not be web-accessible. --- # 26. Security Required: * Sanctum authentication, * rate limiting, * Policies, * query scoping, * Form Requests, * validation, * escaped output, * CORS restricted to app origin, * private files, * signed URLs, * audit logs, * password hashing, * no secret logging, * no API key logging. --- # 26.1 Neshan security Service key: ```text server-only ``` Never: * frontend, * Git, * logs, * exception response, * client payload. Web map key: * delivered via authenticated config, * restricted to application domain. --- # 27. API configuration ```text GET /config ``` Returns only frontend-safe config: ```json { "map_key": "...", "constants": { "step": 1, "dedup_radius": 3, "snap_warn": 30 } } ``` The config can be cached client-side for offline app startup. Service key is NEVER included. --- # 28. Audit logging Audit: * worker creation/edit, * work-area creation/closing, * user changes, * inspection create, * inspection edit, * inspection soft-delete, * relevant permission-sensitive changes. Store: ```text who when what before/after changes where practical ``` --- # 29. Performance Expected scale: ```text < 200 workers ~10 supervisors ~30 officers ``` A normal cPanel server is sufficient if properly configured. Keep map payloads scoped. Do not return unauthorized geometries. For overview map: * simplify polygon geometry if necessary, * do not simplify inspection geometry used for length calculation, * simplification is visualization only. --- # 30. Accessibility and UX * RTL correct everywhere, * Persian digits, * night-friendly dark mode, * large buttons, * no tiny map controls, * clear Persian errors, * no ambiguous status, * loading states, * retry actions, * offline state visible, * outbox count visible, * routing errors understandable. --- # 31. Internationalisation All user-facing UI strings must live in a Persian locale structure. Do not hard-code Persian strings inside Vue components. Domain terms: | English | Persian | | ------------------------------ | ------------------------------- | | Urban services supervisor | ناظر خدمات شهری | | Sweeping officer | مسئول رفت و روب | | Sweeping worker | کارگر رفت و روب | | Work area | محدوده کاری | | Nightly inspection | بازرسی شبانه | | Uncleaned stretch / issue item | مورد تمیزنشده | | Fair | نسبتاً تمیز | | Dirty | کثیف | | Not done | انجام نشده | | Inspected, no problem | بازرسی شد، مشکلی نبود | | Unique length | طول یکتا | | Daily target | متراژ برنامه‌ای روزانه (تقریبی) | | Report | گزارش | --- # 32. Testing ## 32.1 Authorization Test: ```text officer A cannot see worker B officer A cannot edit worker B officer A cannot see B's inspection officer A cannot edit B's inspection officer A cannot see B's area officer A cannot see B's report officer A cannot see B's map feature supervisor sees only subordinate officers/workers admin sees all ``` --- # 32.2 Dedupe parity Shared fixtures: ```text out-and-back dead end mid-street start parallel streets approximately 12m apart ``` Expected: ```text same street = dedupe 12m apart = do not merge ``` TS and PHP must produce: ```text raw unique ``` within: ```text ±0.5m ``` --- # 32.3 Operational date Test: ```text 23:30 -> current date 01:30 -> previous operational date 06:00 -> current date ``` Timezone: ```text Asia/Tehran ``` --- # 32.4 Inspection state Test: ```text result=ok ``` means: ```text inspected unclean=0 ``` No inspection means: ```text بازرسی نشده ``` --- # 32.5 Idempotency Post same `client_uuid` twice. Expected: ```text one inspection only ``` Same logical payload: ```text return existing ``` Different payload: ```text 409 idempotency_conflict ``` --- # 32.6 Version conflict Two clients edit same inspection. Second client with stale version: ```text 409 inspection_version_conflict ``` No silent overwrite. --- # 32.7 Polyline decoding Test: * precision 5, * step concatenation, * duplicate junction point removal, * `[lng,lat]` start_location handling, * `[lat,lng]` request handling. Use recorded Neshan response fixture. --- # 32.8 Routing error mapping Test: ```text 480 481 482 483 484 485 500 timeout ``` No key leakage. --- # 32.9 Spatial smoke test M0 must prove: 1. POINT can be stored. 2. POLYGON can be stored. 3. LINESTRING can be stored. 4. MULTILINESTRING can be stored. 5. SRID 4326 can be stored/read. 6. spatial index can be created where valid. 7. polygon containment works. Required conceptual test: ```text point inside polygon -> 1 point outside polygon -> 0 ``` --- # 32.10 UTF-8 test Insert: ```text کارگر نمونه بازرسی شبانه محدوده کاری ``` Read them back correctly. No mojibake. --- # 33. Code quality Required: ```text PHP Pint PHPStan level 6+ Backend tests PHPUnit or Pest Frontend ESLint Prettier Vitest TypeScript strict mode ``` Keep files small. Prefer conventional Laravel architecture. Do not introduce packages without justification. --- # 34. Repository layout ```text / ├── backend/ ├── frontend/ ├── poc/ ├── docs/ ├── docker/ └── README.md ``` The `docker/` directory may contain optional/local tooling documentation, but production must NOT depend on Docker. `poc/` is: ```text reference read-only ``` --- # 35. Documentation Create: ```text docs/ ├── architecture.md ├── deployment-cpanel.md ├── gis.md ├── routing.md ├── offline-sync.md ├── permissions.md ├── fixtures/ │ └── dedupe/ └── CHANGELOG.md ``` README must include: * prerequisites, * local XAMPP setup, * Composer setup, * Node setup, * database setup, * `.env`, * migration, * seed, * run commands, * tests, * production deployment, * cPanel Cron setup, * backup/restore. --- # 36. Open decisions Use the defaults below. ## 1. Login Default: ```text phone + password ``` SMS OTP later. Leave: ```text TODO(open): SMS OTP future integration ``` --- ## 2. Number of officers Production number is unknown. Default seed: ```text 4 officers ``` No hard code limit. --- ## 3. Officer permissions Default: ```text officers can create/edit their own workers and work areas ``` --- ## 4. Neshan geometry storage Default: ```text store derived stretch geometry short route cache <=24h no raw Neshan response ``` Leave: ```text TODO(open): Neshan terms verification ``` --- ## 5. Neshan narrow alleys Assume routing works. Keep manual fallback. Owner will field-test. --- ## 6. Hosting Production: ```text cPanel MariaDB ``` No foreign cloud requirement. Self-hosted/municipal hosting remains the ownership model. --- ## 7. Grade colours ```text fair = yellow dirty = orange not_done = red ``` Repetition: ```text 1 = yellow 2–3 = orange >=4 = red ``` --- # 37. Acceptance criteria for major workflows ## Worker setup Given: ```text worker A ``` When admin/officer creates area: Then: ```text polygon saved history exists worker map displays it overlap warning works ``` --- ## No-problem inspection Given: ```text worker A ``` When inspector taps: ```text بازرسی شد، مشکلی نبود ``` Then: ```text inspection exists result=ok unclean_total=0 worker status=بدون مشکل ``` --- ## Issue inspection Given: ```text worker A ``` Inspector clicks: ```text P1 P2 P3 ``` Then: ```text route requested for P1->P2 route requested for P2->P3 ``` Unique length updates live. --- ## Overlapping route Given two routes over the same street: ```text route A route B ``` Then: ```text overlapped metres are counted once repeated region is orange ``` --- ## Operational date At: ```text 01:30 ``` inspection belongs to previous operational date. --- ## Offline inspection Given offline state: ```text points are stored approximate length shown outbox increments ``` When online: ```text inspection syncs Neshan routing occurs on server final numbers appear ``` --- # 38. Milestones Build in this order. Do not skip. Each milestone must end with: * working/demoable UI, * migrations from clean database, * tests green, * no secrets, * short `docs/CHANGELOG.md` entry, * clear git commit. --- ## M0 — Foundation Deliver: * Laravel 13 * Vue 3 + TS * MariaDB connection * Sanctum scaffold * env example * health endpoint * UTF-8 setup * spatial smoke test * basic migrations * testing infrastructure * linting * cPanel deployment documentation * cPanel Cron documentation * `CHANGELOG` Definition of done: ```text php artisan migrate ``` works against clean MariaDB. Spatial smoke test passes. --- ## M1 — Users / Auth / Hierarchy Deliver: * users * roles * hierarchy * Sanctum * policies * `visibleTo` * login UI * admin users CRUD * seed: * 1 admin * 2 supervisors * 4 officers Tests: * authorization scope, * login, * hierarchy, * Persian validation. --- ## M2 — Workers / Areas / Map Deliver: * workers CRUD, * worker photos, * work-area history, * area editor, * overlap warning, * `/map/workers`, * worker map layer, * photo/name labels, * seed ~12 demo workers with polygons around Sari centre. Tests: * area history, * valid dates, * overlap warning, * map authorization, * spatial smoke behaviour. --- ## M3 — Routing / Inspection Deliver: * Neshan routing service, * provider interface, * `/routing/pedestrian`, * inspection map, * PoC port, * TS dedupe, * PHP dedupe, * fixtures, * checklist, * grades, * notes, * photos, * no-problem flow, * `POST/PUT /inspections`, * offline `pending_snap` base support if feasible within milestone. Tests: * routing fixture, * polyline decoding, * snap warning, * dedupe parity, * idempotency, * operational date, * no-problem inspection. --- ## M4 — Reports Deliver: * summary, * ranking, * range map, * repetition colouring, * CSV export, * worker/officer filters, * grade filters. Tests: * authorization, * repeat count by distinct date, * report correctness. --- ## M5 — PWA / Offline / Production polish Deliver: * manifest, * service worker, * app-shell precache, * offline page, * IndexedDB outbox, * retry/backoff, * background sync where supported, * `pending_snap` queue jobs, * offline banner, * install prompt, * cPanel deployment README, * backup documentation, * final UX polish. Final tests: * full suite, * build, * production config, * deployment checklist. --- # 39. Critical implementation rules 1. Do not use PostgreSQL. 2. Do not use PostGIS. 3. Do not use PostgreSQL-specific migrations. 4. Do not use PostgreSQL-specific geometry SQL. 5. Do not use `jsonb`; use MariaDB JSON. 6. Do not use `timestamptz`; use the chosen MariaDB timestamp convention. 7. Do not use `bigserial`; use `BIGINT UNSIGNED AUTO_INCREMENT`. 8. Do not use partial unique indexes; implement equivalent MariaDB-safe logic. 9. Do not trust client length calculations. 10. Server recomputes raw/unique lengths. 11. PHP and TypeScript dedupe implementations must match. 12. Neshan service key stays server-side. 13. Never invent Neshan endpoints or parameters. 14. Follow the PoC interaction exactly. 15. Never expose unauthorized geometry. 16. Never hard-delete inspection history. 17. Never overwrite work-area history. 18. Treat `ok` as inspected, not as "unknown". 19. No inspection is distinct from successful inspection. 20. Offline sync must be idempotent. 21. Do not silently overwrite stale inspection edits. 22. Keep geometry SRID 4326. 23. Do not use database planar length as authoritative unique length. 24. No Neshan raw-response persistence. 25. No Neshan tile cache unless explicitly approved. 26. Keep all UI Persian/RTL. 27. Do not add dependencies casually. 28. Every milestone must end in a working/demoable state. 29. Use `TODO(open)` wherever this specification explicitly leaves a decision open. 30. When uncertain about Neshan behaviour, do not guess; follow the PoC/documented contract and leave `TODO(open)`. --- # 40. Final implementation target The final product is: ```text Users | v +---------------+ | PWA | | Vue + TS | | RTL / Persian | +-------+-------+ | v +---------------+ | Laravel 13 | | Sanctum | | API / Queue | +-------+-------+ | v +---------------+ | MariaDB 11.4+ | | InnoDB Spatial | +-------+-------+ | +-----------+-----------+ | | v v Worker Areas Inspection Geometry | | +-----------+-----------+ | v Reports / GIS ``` Business flow: ```text تعریف کاربران ↓ تعریف کارگر ↓ تعریف محدوده کاری ↓ بازرسی شبانه ↓ انتخاب کارگر ↓ کلیک روی نقاط ↓ Neshan pedestrian routing ↓ Snap / route geometry ↓ Unique-length algorithm ↓ ثبت درجه مشکل ↓ ثبت عکس/یادداشت ↓ ذخیره بازرسی ↓ گزارش عملکرد ↓ نمایش تکرار روی نقشه ``` The system must remain simple operationally: ```text cPanel + MariaDB + Laravel + Vue/PWA + Neshan ``` Do not add infrastructure unless the existing environment proves insufficient.