- Docs
- Architecture
- Client-service contract
Client-Service Contract¶
This document defines the API contract that TyteRide surfaces code against. It consolidates the API conventions, the preserved build-spec API/channel sections in ../04-product/01-b2b-rework-plan.md §7–§8, and TyteRide naming rules.
1. Base URL and versioning¶
- Base path:
/api. - Versioning: No URL version segment for the beta. Breaking changes bump the surface semver and are announced in the changelog.
- Format: All responses are JSON. Mutations return the documented resource or
{ message }result. - Resource wrapping:
JsonResource/ResourceCollectiononly; auth resources are returned without Laravel's additionaldatawrapper. - Source of truth: This contract and the API implementation tests define behavior; clients must not guess missing fields.
2. Authentication and OTP flow¶
Authentication is phone + OTP everywhere. No email/password flow exists.
2.1 Auth contract¶
| Item | Contract |
|---|---|
| Public auth endpoints | POST /api/auth/otp/send, POST /api/auth/otp/verify |
| Session endpoints | GET /api/auth/me, POST /api/auth/logout with auth:sanctum |
| Token type | Sanctum bearer token |
| Header | Authorization: Bearer <token> on every authenticated request |
| Token name | auth, unless verify supplies client, which is used as the token name |
| Roles | passenger, driver, manager, administrator |
| Enrollment | POST /api/auth/enroll-company (with gender) is specified in a future slice |
2.2 Send OTP¶
POST /api/auth/otp/send
{ "phone": "+967700000000", "locale": "en" }
phone: required string; surrounding whitespace is trimmed.locale: optionalenorar; takes precedence overAccept-Languagefor the send response/SMS and is retained with the pending challenge.
200:
{ "message": "OTP sent." }
Arabic locale returns تم إرسال رمز التحقق..
2.3 Verify OTP¶
POST /api/auth/otp/verify
{ "phone": "+967700000000", "otp": "123456", "client": "dashboard" }
phone: required string; surrounding whitespace is trimmed.otp: required six-digit string.client: optional string used as the Sanctum token name.
200:
{
"token": "<sanctum-bearer-token>",
"user": {
"id": 1,
"name": "+967700000000",
"phone": "+967700000000",
"email": null,
"role": "passenger",
"locale": "en",
"company_id": null
},
"locale": "en"
}
First verification creates the User with name equal to the trimmed phone, nullable email, role passenger, and nullable company_id. Existing Users retain their profile/role. The response never contains the OTP.
2.4 Current User and logout¶
GET /api/auth/me (auth:sanctum) returns 200. For a User with a Company membership:
{
"user": {
"id": 1,
"name": "Ahmad Ali",
"phone": "+967700000000",
"email": "ahmad@acme.example",
"role": "manager",
"locale": "en",
"company_id": 1
},
"company": {
"id": 1,
"name_en": "Acme Logistics",
"name_ar": "أكمي للخدمات اللوجستية",
"status": "pending",
"seats_used": 3,
"tier": {
"code": "starter",
"name": "Starter",
"max_users": 50
}
},
"locale": "en"
}
For a User without a membership, company is present and null. company_id on the User is derived from the membership, never from the client. tier.name is localized with the User's locale (name_ar for ar, otherwise name_en). seats_used is the count of approved Passenger memberships (memberships.role=passenger, status=active) in the company. A pending Manager can authenticate; the membership status is not exposed by this endpoint.
POST /api/auth/logout (auth:sanctum) revokes only the current token and returns 200:
{ "message": "Logged out." }
2.5 Phone + OTP sequence¶
sequenceDiagram
autonumber
actor User
participant Client as Client App / Web
participant API as /api/auth
participant OTP as OTP Provider/SMS Boundary
participant Auth as Sanctum/Auth Domain
User->>Client: Enter phone number
Client->>API: POST /api/auth/otp/send { phone, locale? }
API->>API: Validate + rate limit
API->>OTP: Send OTP
OTP-->>User: SMS/code delivery
API-->>Client: 200 { message }
User->>Client: Enter OTP code
Client->>API: POST /api/auth/otp/verify { phone, otp, client? }
API->>Auth: Verify code and resolve/create user session
Auth-->>API: Sanctum token + user payload
API-->>Client: 200 { token, user, locale }
Client->>API: Authenticated request with Authorization: Bearer <token>
API->>Auth: Validate token and User
API-->>Client: JsonResource or error envelope
2.6 OTP policy¶
| Rule | Contract |
|---|---|
| Code | Six digits. |
| TTL | Five minutes. |
| Resend cooldown | 60 seconds per phone. |
| Incorrect attempts | Maximum five per code; the fifth locks the code. |
| Send rate limit | Five per ten minutes per phone + IP pair. |
| Storage | otp_codes stores phone, code_hash, attempts, expires_at, consumed_at, created_at; phone indexed. |
| SMS | SmsSender boundary; Slice 1 binds sms.driver=log and sms.from. |
| Secret handling | Persist only the hash; never return OTP. Local/testing uses the SMS log driver. |
See Phone + OTP for the full behavior and Sessions and Roles for lifecycle and role rules.
3. Error envelope¶
Every error uses exactly:
{ "message": "Human-readable message", "errors": { "field": ["Reason"] } }
Rules:
errorsis present only for validation failures (HTTP 422), including wrong/expired OTP errors underotp.messageis human-readable and localized throughAccept-Language.429responses containmessageonly and includeRetry-Afterwhen the limiter supplies it.- A contract test enforces this shape for every endpoint group.
4. Status codes¶
| Status | Meaning | Contract note |
|---|---|---|
| 400 | Bad request | Malformed or invalid request outside validation rules. |
| 401 | Unauthenticated | Missing/invalid/expired bearer token. |
| 403 | Forbidden/suspended | Authenticated but not allowed; suspended company returns 403 with clear message on authenticated company routes. |
| 404 | Not found | Missing resource; also used for cross-tenant access to avoid leaking existence. |
| 422 | Validation failure | Includes errors object. |
| 429 | Rate-limited | OTP cooldown/send limit or per-code attempt limit; message-only envelope. |
| 500 | Server error | Unexpected failure; no internal details leaked. |
5. Response, pagination, date, and money conventions¶
| Area | Convention |
|---|---|
| Resource shape | Always JsonResource / ResourceCollection; never raw models or ad-hoc arrays. Auth resources are unwrapped. |
| Field naming | Resource field names are snake_case and mirror TypeScript types exactly. |
| Pagination | ?page=&per_page=; response includes data, meta (current_page, last_page, per_page, total), and links. |
| Dates | ISO-8601 UTC. |
| Money | Tier price is integer minor units or decimal string as defined in the resource; never floats in transit. |
6. Tenancy and company scope¶
company_idis never accepted from the client. It is derived from authenticated membership.- Slice 2 adds
tiers,companies,memberships, andcompany_codes.users.company_idmirrors the User's single membership. TenantContextholds the resolved Company for the request. Thecompanymiddleware resolves it from the authenticated User's membership and applies to every authenticated/company/*route.CompanyScopeis a global scope on company-owned models (memberships,company_codes,nav_routes,vehicles,trips,bookings); it filters by the resolvedcompany_id. With no resolved tenant (public onboarding) the scope is a no-op, so every authenticated company route must pass through thecompanymiddleware. Bookings carrycompany_iddirectly in Slice 4 and it must matchtrip.company_id.- Cross-tenant access returns 404, not 403. A User without a membership cannot use company routes (404).
- Suspended company access returns 403 with
{"message": "Company is suspended."}on every authenticated company route. - Driver sees only trips for their company and assignment; Passenger sees only their own bookings and permitted company trips.
7. Localization¶
Accept-Language: en|arselects response language; defaulten.lang/enandlang/arhold messages and validation translations.- Send body
locale, when present, overridesAccept-Languagefor that request and is retained for verification. - Arabic entity fields (
name_ar,label_ar) are returned alongside English where applicable. users.localeand top-levellocaleare returned by verify/me so clients can persist the choice.- Validation messages and
messageare localized.
8. Route prefixes and endpoint groups¶
All prefixes below are relative to /api.
| Prefix | Audience | Examples / notes |
|---|---|---|
/auth/* |
Public/session | otp/send, otp/verify, me, logout, enroll-company |
/onboarding/* |
Public | POST /onboarding/companies (Front Views), rate-limited 3/hour/IP |
/passenger/* |
Passenger | Trips, bookings, live, tracking, D2D |
/driver/* |
Driver | Trips, location, lifecycle, D2D, route-plan |
/company/* |
Manager | Enrollments, fleet, trips, bookings, live tracking, D2D, reviews |
/platform/* |
Platform Admin | Companies, status, tiers |
/trips/{id}/review |
Passenger | Post-trip review (completed trip, approved booking owner) |
8.1 Preserved spec endpoint mapping¶
The preserved build spec §7 contains useful endpoint intent but uses legacy prefixes. TyteRide replacements apply:
| Preserved spec endpoint | TyteRide naming | Notes |
|---|---|---|
GET /coordinator/trips/{id}/route-plan |
GET /driver/trips/{id}/route-plan |
Legacy prefix in preserved spec; use /driver/*. |
POST /coordinator/trips/{id}/feedback |
POST /driver/trips/{id}/feedback |
Legacy prefix in preserved spec; use /driver/*. |
GET /company/* |
GET /company/* |
Unchanged. |
GET /passenger/* |
GET /passenger/* |
Preserved spec used /passenger/* in some areas; keep Passenger naming. |
Supersession note: Where the preserved spec text still says
/coordinator/*, read it as/driver/*in TyteRide. Where old code/docs might say/consumer/*, read it as/passenger/*.
9. Reverb authorization and realtime contract¶
| Channel | Audience | Authorization rule |
|---|---|---|
private-company.{companyId} |
Managers only | Manager of that company only. |
trip.{tripId} |
Trip participants | Passenger with a booking on the trip, assigned Driver, or Manager of the trip's company. |
Realtime rules:
- Channel callbacks re-check membership; stale tokens must not retain access.
- Existing notification channels stay.
- Driver App publishes GPS every 10–15 seconds during an active trip.
- Company channel events include trip status, vehicle position, passenger boarded, extra car assigned, and driver feedback.
10. Validation, idempotency, and rate limiting¶
- Validation lives in FormRequests; business rules live in the domain.
- Booking and car-request creation should be idempotent per client-supplied key where duplicate taps are likely. Slice 4 does not invent a key header/field: duplicate active Booking requests are rejected with
422 errors.trip_id, and request/approval serialize on the Trip row. A future idempotency-key contract remains source silent for clients that require replay-safe mutation keys. - OTP send uses named Laravel rate limiters: five sends per phone + IP per ten minutes and one send per phone per 60 seconds.
- OTP verify enforces five incorrect attempts per code; the fifth locks the code and returns 429.
- Time-dependent rules use a frozen clock in tests.
11. Documentation and contract duties¶
When adding or changing an API endpoint:
- Add a feature test.
- Add an error-shape assertion (
{ message, errors? }). - Add/update a
JsonResource/ResourceCollection. - Update this document if a new prefix or convention appears.
- Update consuming TypeScript types in the same slice when a field changes.
- Add tenant-isolation tests for company-scoped endpoints.
- For realtime, add channel authorization tests for membership and stale-token cases.
12. Notifications (Slice 10)¶
Full contract: ../03-specs/notifications/01-notifications.md.
| Method | Path | Auth / role | Purpose |
|---|---|---|---|
POST |
/api/notifications/device-tokens |
auth:sanctum + active Passenger/Driver membership |
Register/refresh device token (upsert by token). |
DELETE |
/api/notifications/device-tokens/{id} |
auth:sanctum + owner |
Revoke/delete device token. |
GET |
/api/notifications |
auth:sanctum |
List current User notifications, newest first, paginated. |
GET |
/api/notifications/unread-count |
auth:sanctum |
Current User unread count. |
POST |
/api/notifications/{id}/read |
auth:sanctum + owner |
Mark one notification read (idempotent). |
POST |
/api/notifications/read-all |
auth:sanctum |
Mark all current User unread notifications read. |
NotificationResource: {id, type, title, body, data, read_at, created_at}. DeviceTokenResource: {id, platform, token, last_seen_at, created_at, updated_at}. Device-token create returns 201, token refresh/other mutations return 200. Collections use data, meta, links.
| Case | Status | Envelope |
|---|---|---|
| Invalid payload/filter | 422 | message + field errors |
| Device token endpoint without active Passenger/Driver Membership | 403 | message only |
| Missing/cross-user notification or device token | 404 | message only |
14. Company onboarding (Slice 2)¶
POST /api/onboarding/companies is public and rate-limited to 3 requests/hour/IP (429, message-only envelope with Retry-After). The full contract is in ../03-specs/onboarding/01-company-onboarding.md.
Request fields: company_name_en, company_name_ar, manager_name, manager_phone, manager_email, tier_code, locale, optional notes. No payment or privileged fields (company_id, status, role, tier_id) are accepted.
201 response (unwrapped JsonResource):
{
"message": "Application submitted for review.",
"company": { "id": 1, "name_en": "Acme Logistics", "name_ar": "أكمي للخدمات اللوجستية", "status": "pending" },
"manager": { "id": 1, "name": "Ahmad Ali", "phone": "+967700000000", "status": "pending" }
}
The use case creates the Company (pending), the Manager User (role: manager, locale from the request), a pending manager Membership, and the first unique Company Code in one transaction. Duplicate manager_phone/manager_email and invalid tier_code return 422 with field-level errors. Platform Admin approval is Slice 8; until then the Company and manager Membership stay pending.
13. Enrollment and approval (Slice 3)¶
Full contract: ../03-specs/onboarding/03-enrollment-approval.md.
| Method | Path | Auth | Notes |
|---|---|---|---|
POST |
/api/auth/enroll-company |
auth:sanctum |
Creates pending membership. Body: company_code, gender (male\|female), role (passenger\|driver), optional driver fields driver_license_number, vehicle_description, documents_note. 201 {enrollment: EnrollmentResource}. 422 for invalid/inactive code, duplicate/one-company, gender conflict. |
GET |
/api/company/enrollments |
auth:sanctum + company + manager |
Paginated company enrollments. Filters: role, status (pending\|approved\|rejected\|all), gender, search, page, per_page. |
POST |
/api/company/enrollments/{id}/approve |
auth:sanctum + company + manager |
Approves pending enrollment. Passenger approval enforces tier max_users; at limit 422 {message, errors:{seats:[...]}}. |
POST |
/api/company/enrollments/{id}/reject |
auth:sanctum + company + manager |
Rejects pending enrollment. Optional body {reason}. |
EnrollmentResource: {id, role, status, submitted_at, user:{id,name,phone,gender}, driver:{license_number,vehicle_description,documents_note}|null, rejection_reason}. status is pending|approved|rejected (API maps membership active to approved).
15. Trips and Bookings (Slice 4)¶
Full contract: Trips and Cars, Seat Approval, and Reservation Deadline.
| Method | Path | Auth / role | Purpose |
|---|---|---|---|
GET |
/api/company/trips |
auth:sanctum + company + Manager |
Paginated company Trips; status, page, per_page. |
POST |
/api/company/trips |
Same | Create scheduled Trip. |
GET |
/api/company/trips/{id} |
Same | Show company Trip. |
PUT |
/api/company/trips/{id} |
Same | Full planning-field replacement while scheduled. |
POST |
/api/company/trips/{id}/cancel |
Same | Cancel scheduled/in-transit Trip and active Bookings. |
GET |
/api/company/trips/{id}/tracking |
Same | Company Trip tracking: latest location, destination ETA, status, Driver/Vehicle summary. |
GET |
/api/company/live |
Same | Paginated in-transit Company Trips with latest locations/ETA. |
GET |
/api/company/trips/{id}/bookings |
Same | Paginated Trip Bookings; status, page, per_page. |
POST |
/api/company/trips/{id}/bookings/{booking_id}/approve |
Same | Approve pending Booking. |
POST |
/api/company/trips/{id}/bookings/{booking_id}/reject |
Same | Reject pending Booking; optional reason. |
GET |
/api/passenger/trips |
auth:sanctum + company + active Passenger |
Paginated bookable Trips (scheduled, future departure, open deadline, seats left). Filters: origin, destination, date (Y-m-d), nav_route_id, page, per_page. |
GET |
/api/passenger/trips/{id}/tracking |
Same | Approved-Booking tracking: latest location, ETA, status, Driver/Vehicle summary. |
POST |
/api/passenger/trips/{id}/bookings |
Same | Create pending Booking; no body fields. |
GET |
/api/passenger/bookings |
Same | Paginated own Bookings; status, page, per_page. |
GET |
/api/passenger/bookings/{id} |
Same | Show own Booking. |
POST |
/api/passenger/bookings/{id}/cancel |
Same | Cancel own pending/approved Booking. |
GET |
/api/driver/trips |
auth:sanctum + company + active Driver |
Paginated assigned Trips; status, page, per_page. |
GET |
/api/driver/trips/{id} |
Same | Show assigned Trip. |
POST |
/api/driver/trips/{id}/location |
Same | Record Driver GPS point for assigned in-transit Trip. |
POST |
/api/driver/trips/{id}/start |
Same | scheduled → in_transit; rejects pending Bookings. |
POST |
/api/driver/trips/{id}/complete |
Same | in_transit → completed. |
14.1 Trip create/update fields¶
nav_route_id, origin, destination, departure_at, vehicle_id, driver_id, seat_capacity are required. Optional: reservation_deadline_at, trip_group_code, notes. driver_id is an active Driver Membership ID. seat_capacity is 1–100 and cannot exceed Vehicle capacity. company_id, status, derived seat counts, lifecycle timestamps, and price/payment fields are prohibited. Datetimes are ISO-8601; responses use UTC.
TripResource: {id, company_id, nav_route_id, route:{id,name_en,name_ar,origin,destination}, origin, destination, departure_at, reservation_deadline_at, vehicle:{id,name,seat_capacity}, driver:{id,user_id,name}, seat_capacity, seats_left, trip_group_code, notes, status, started_at, completed_at, cancelled_at, created_at, updated_at}.
14.2 Booking contract and errors¶
BookingResource: {id, company_id, trip_id, trip:{id,origin,destination,departure_at,status}, passenger:{id,name}, status, rejection_reason, requested_at, decided_at, cancelled_at, boarded_at}. Status is pending|approved|rejected|cancelled. Only approved Bookings consume Trip capacity; there is no separate Trip-seat table and no charge/price.
Create returns 201; other mutations return 200. List responses use data, meta (current_page, last_page, per_page, total), and links.
| Case | Status | Envelope |
|---|---|---|
| Validation / cross-company create reference | 422 | message + field-level errors |
| Deadline passed | 422 | errors.reservation_deadline_at |
| Trip full | 422 | errors.seats |
| Tier integrity exceeded | 422 | errors.seats |
| Duplicate active Booking | 422 | errors.trip_id |
| Invalid transition | 422 | errors.status |
| Trip not scheduled/future or otherwise not bookable | 422 | errors.trip |
| Wrong role / inactive Passenger or Driver Membership | 403 | message only |
| Suspended Company | 403 | message only |
| Missing/cross-company Trip or Booking | 404 | message only |
An active Passenger at exactly the Tier max_users may book because Booking consumes no subscription Seat. D2D request fields, route-plan, boarding, live tracking, duplication, and extra cars are not part of Slice 4.
16. Fleet (Slice 7)¶
Full contract: Trips and Cars §7. Fleet resources are company-scoped, Manager-only, and suspended-company blocked (403). Cross-tenant access returns 404.
| Method | Path | Auth / role | Purpose |
|---|---|---|---|
GET |
/api/company/vehicles |
auth:sanctum + company + Manager |
Paginated vehicles. Filters: status=active\|inactive\|all, page, per_page. |
POST |
/api/company/vehicles |
Same | Create vehicle. |
GET |
/api/company/vehicles/{id} |
Same | Show vehicle. |
PUT |
/api/company/vehicles/{id} |
Same | Update vehicle. |
DELETE |
/api/company/vehicles/{id} |
Same | Hard-delete only when no trips reference it; otherwise 422 instructing deactivation. |
GET |
/api/company/nav-routes |
Same | Paginated nav routes. Filters: active=true\|false\|all, page, per_page. |
POST |
/api/company/nav-routes |
Same | Create nav route. |
GET |
/api/company/nav-routes/{id} |
Same | Show nav route. |
PUT |
/api/company/nav-routes/{id} |
Same | Update nav route. |
DELETE |
/api/company/nav-routes/{id} |
Same | Hard-delete only when no trips reference it; otherwise 422 instructing deactivation. |
VehicleResource: {id, company_id, name, plate, capacity, type, icon, status}. capacity maps to stored seat_capacity; Trip planning validates seat_capacity against Vehicle capacity and active Vehicle status. Plate is normalized to uppercase trim and must be unique within company when present.
NavRouteResource: {id, company_id, name_en, name_ar, origin, destination, stops, origin_lat, origin_lng, destination_lat, destination_lng, active}. Stops are ordered objects {name, name_ar?, lat?, lng?}; coordinate pairs must be supplied together. Inactive nav routes are rejected by Trip create/update (errors.nav_route_id).
Deletion/reference rules: active trips (scheduled, in_transit) and historical trip references block hard delete with 422 errors.vehicle or errors.nav_route; deactivation is done via update (status=inactive / active=false). Vehicle capacity cannot be reduced below max active trip seat_capacity.
17. D2D (Slice 6)¶
Full contract: D2D. D2D is a separate context with its own settings and request aggregate; it does not add D2D columns to bookings and does not change Tier/Trip seat accounting.
| Method | Path | Auth / role | Purpose |
|---|---|---|---|
GET |
/api/company/d2d/settings |
auth:sanctum + company + Manager |
Company D2D settings (defaults when unset). |
PUT |
/api/company/d2d/settings |
Same | Upsert company D2D settings. |
GET |
/api/company/d2d/requests |
Same | Paginated company D2D requests; status, trip_id, page, per_page. |
POST |
/api/company/d2d/requests/{id}/approve |
Same | Approve a pending request. |
POST |
/api/company/d2d/requests/{id}/reject |
Same | Reject a pending request; optional reason. |
POST |
/api/passenger/d2d/requests |
auth:sanctum + company + active Passenger |
Request D2D for an approved Booking. |
GET |
/api/driver/trips/{id}/d2d-requests |
auth:sanctum + company + active assigned Driver |
Approved D2D pickup/drop-off points for an assigned Trip. |
D2DSettingsResource: {id, company_id, enabled, zone_lat, zone_lng, service_radius_meters, pickup_enabled, dropoff_enabled, per_trip_enabled, max_detour_minutes, created_at, updated_at}.
D2DRequestResource: {id, company_id, trip_id, booking_id, passenger:{id,name}, status, pickup_address, pickup_lat, pickup_lng, dropoff_address, dropoff_lat, dropoff_lng, rejection_reason, requested_at, decided_at, cancelled_at, created_at, updated_at}. Status is pending|approved|rejected|cancelled.
DriverD2DRequestResource: {id, trip_id, booking_id, status, pickup_address, pickup_lat, pickup_lng, dropoff_address, dropoff_lat, dropoff_lng} — no Passenger identity, company id, or timestamps.
Request body for POST /api/passenger/d2d/requests: trip_id, booking_id, pickup_address, pickup_lat, pickup_lng, dropoff_address, dropoff_lat, dropoff_lng. company_id is never accepted. Create returns 201; other mutations return 200. Collections use data, meta, and links as in §5.
| Case | Status | Envelope |
|---|---|---|
| Validation / invalid coordinates / partial zone triple | 422 | message + field-level errors |
| D2D disabled or per-trip availability off | 422 | errors.d2d |
| Pickup/drop-off rule disabled or point outside service radius | 422 | errors.pickup / errors.dropoff |
| Trip not scheduled/future | 422 | errors.trip |
| Booking not approved | 422 | errors.booking |
| Duplicate active request | 422 | errors.booking_id |
| Invalid approve/reject transition | 422 | errors.status |
| Wrong role / inactive membership | 403 | message only |
| Suspended Company | 403 | message only |
| Missing/cross-tenant resource or unassigned Driver Trip | 404 | message only |
Directions-based detour estimation and GET /driver/trips/{id}/route-plan remain future work; Slice 6 stores max_detour_minutes but does not compute detours.
18. Reviews (Slice 8)¶
Full contract: Reviews. Reviews are Company-scoped, Passenger-submitted after Trip completion, and Manager-listed with aggregate summary. Cross-tenant access returns 404; suspended Company returns 403.
| Method | Path | Auth / role | Purpose |
|---|---|---|---|
POST |
/api/trips/{id}/review |
auth:sanctum + company + active Passenger |
Submit a review for a completed Trip the Passenger booked (approved Booking). |
GET |
/api/company/reviews |
auth:sanctum + company + Manager |
Paginated Company reviews with filters. |
GET |
/api/company/reviews/summary |
auth:sanctum + company + Manager |
Aggregate summary for the same filtered Company reviews. |
Create request body: rating (required integer 1–5), comment (optional nullable string, max 1000; empty becomes null). company_id, user_id, driver_id, trip_id body fields are not accepted; Trip/Driver/Passenger are derived server-side.
ReviewResource: {id, company_id, trip_id, driver:{id,user_id,name}, passenger:{id,name}, rating, comment, created_at, updated_at}. Dates are ISO-8601 UTC.
Manager list filters: rating (1–5 exact), trip_id, driver_id, date_from (Y-m-d, inclusive), date_to (Y-m-d, inclusive), page, per_page (1–100, default 15). Default sort newest first (created_at desc, id desc). Collections use data, meta, links.
Summary response: {average_rating:number|null, review_count:int, rating_distribution:{"1":int,"2":int,"3":int,"4":int,"5":int}}. average_rating is rounded to two decimals or null when empty.
| Case | Status | Envelope |
|---|---|---|
| Validation (rating/comment/filter format) | 422 | message + field errors |
| Trip not completed | 422 | errors.trip |
| Passenger has no approved Booking on Trip | 422 | errors.booking |
| Duplicate review for same Passenger+Trip | 422 | errors.review |
| Wrong role / inactive Passenger Membership | 403 | message only |
| Suspended Company | 403 | message only |
| Missing/cross-tenant Trip | 404 | message only |
19. Analytics Overview (Slice 9)¶
Full contract: Analytics Overview. Manager-only, company-scoped, read-only KPI snapshot over an inclusive UTC date range. No payment/revenue fields.
| Method | Path | Auth / role | Purpose |
|---|---|---|---|
GET |
/api/company/analytics/overview |
auth:sanctum + company + Manager |
Company KPI overview for trips, bookings, seat utilization, D2D, enrollments, reviews, completion/on-time rates. |
Query filters: date_from (Y-m-d, default date_to - 29 days, inclusive), date_to (Y-m-d, default current UTC date, inclusive). date_to must be on/after date_from.
AnalyticsOverviewResource: {date_from, date_to, trips:{total,scheduled,in_transit,completed,cancelled}, bookings:{total,pending,approved,rejected,cancelled}, seats:{used,available,capacity,utilization_percent}, d2d_requests:{total,pending,approved,rejected,cancelled}, enrollments:{pending,approved,rejected,suspended}, reviews:{average_rating,review_count}, performance:{completion_rate_percent,on_time_departure_rate_percent}}.
Empty range returns zeroed counts, 0.0 utilization/completion rates when denominators are zero, reviews.average_rating=null when no reviews, and performance.on_time_departure_rate_percent=null until Trip Analysis computation is implemented.
| Case | Status | Envelope |
|---|---|---|
Invalid date format / date_to < date_from |
422 | message + field errors |
| Wrong role | 403 | message only |
| Suspended Company | 403 | message only |
| Missing company membership | 404 | message only |
20. Company Settings (Slice 11)¶
Full contract: ../03-specs/onboarding/04-company-settings.md. Manager-only, company-scoped, suspended-company blocked (403). Cross-tenant access returns 404. company_id is never accepted from clients.
| Method | Path | Auth / role | Purpose |
|---|---|---|---|
GET |
/api/company/settings |
auth:sanctum + company + Manager |
Return Company profile, tier, seat usage/limit, active company code, and Manager contact. |
PUT |
/api/company/settings |
Same | Update allowed fields: name_en, name_ar, locale, manager_name, manager_phone, manager_email. |
POST |
/api/company/settings/company-code/regenerate |
Same | Deactivate current active Company Code and issue a new unique active code. |
CompanySettingsResource: {id, name_en, name_ar, status, company_code, locale, seats_used, seats_limit, tier:{code,name,max_users}, manager:{id,name,phone,email}}. status, tier, seats_used, seats_limit, and company_code are read-only via PUT; company_code changes only through the regeneration endpoint.
PUT accepts any subset of allowed fields; at least one allowed field is required. Immutable/prohibited fields in the body (id, status, tier, tier_id, tier_code, company_id, company_code, seats_used, seats_limit, manager.id) return 422 field errors. Duplicate manager_phone/manager_email return 422 field errors.
| Case | Status | Envelope |
|---|---|---|
| Validation / immutable field / duplicate manager contact | 422 | message + field errors |
| Wrong role | 403 | message only |
| Suspended Company | 403 | message only |
| Missing company context / cross-tenant | 404 | message only |