diff --git a/.github/workflows/ember.yml b/.github/workflows/ember.yml index 3d443ebb7..1aefda134 100644 --- a/.github/workflows/ember.yml +++ b/.github/workflows/ember.yml @@ -6,7 +6,7 @@ on: tags: - 'v*' pull_request: - branches: [ main, 'release/v*', 'dev-v*' ] + branches: [ main, 'release/v*', 'dev-v*', release/v*, dev-v* ] env: NODE_VERSION: 22.x diff --git a/.github/workflows/postman.yml b/.github/workflows/postman.yml index 157d770b0..aef7db2a2 100644 --- a/.github/workflows/postman.yml +++ b/.github/workflows/postman.yml @@ -27,9 +27,14 @@ permissions: jobs: contract: + # Laravel 12 release only. Remove `stack` once this release ships. The published image is + # Laravel 10 and its extensions require core-api 1.x, so this branch can only resolve + # against the whole Laravel 12 train: the `l12` stack builds the image from fleetbase's + # Laravel 12 branch and links core-api and every extension from their release branches. uses: fleetbase/fleetbase/.github/workflows/api-contract.yml@main with: collections: "Fleetbase API" + stack: l12 build-from-source: false # Without this the run tests the version of fleetbase/fleetops-api baked into the # published image, not the branch under review. The workflow checks this diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index e9699443b..e260a5c57 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -6,7 +6,7 @@ on: tags: - 'v*' pull_request: - branches: [ main, 'release/v*', 'dev-v*' ] + branches: [ main, 'release/v*', 'dev-v*', release/v*, dev-v* ] jobs: build: diff --git a/RELEASE.md b/RELEASE.md index a32ec2d8d..157dda28a 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,36 +1,33 @@ -> v0.6.75 ~ "Road distance and ETAs from one routing engine, tenant-isolated profile accounts and App Review access for Navigator" +> v0.7.0 ~ "Laravel 12 and core-api 2.0" --- ## Highlights -- **Feature: one routing engine for order distance, ETAs and the map.** An order's stored distance and time, its live ETAs and remaining distance, and the route drawn on the map now all come from the organization's routing engine. Before this, order distance defaulted to a straight-line estimate at a flat ~50 km/h; a reported ~30 km run was stored as 25.0 km / 30 min and is now 32.1 km / 32 min. The engine is chosen in order: the organization's routing engine, then the admin default, then the platform's Valhalla server, then the straight-line estimate. An engine only counts if it is allowed and configured. A failed road lookup falls back to the straight-line estimate and is logged, instead of storing 0. Road results are cached for 24 hours. (#406) -- **Feature: routing provider controls in Admin → Fleet-Ops → Routing.** Administrators choose which providers organizations may use (Google, Valhalla, OSRM, VROOM), with per-organization exceptions. They also set the default routing and optimization engines, and whether server-side routing uses roads or only the straight-line estimate. Saved admin settings take precedence over environment variables. **Google is off until an administrator enables it**, for map routing, optimization, order distance and ETAs. The public OSRM demo server is never called by the server. The admin menu entry "Fleet-Ops Config" is now "Fleet-Ops". (#406) -- **Feature: the OSRM server is a setting, for the platform and per organization.** Administrators set it in Admin → Fleet-Ops → Routing → OSRM Server; `OSRM_HOST` is now only the starting value. Organizations that route or optimize with OSRM can use their own server under Fleet-Ops Settings → Routing → OSRM Server, like the Valhalla and VROOM overrides. An organization host must be a public address (`OSRM_ALLOW_PRIVATE_HOSTS=true` lifts that on self-hosted installs). Order distance, ETAs, tracking and the console's OSRM routes and route control all use the resolved server. The public demo server still only draws map routes. -- **Security: an organization's routing host can't point at a private address.** Order distance, ETAs and VROOM allocation ignore an organization's Valhalla or VROOM override whose host is loopback, a private or link-local network, cloud metadata or another non-public range, and use the system server instead. This also covers values saved before the Valhalla and VROOM extensions started rejecting them. (#417) -- **Security: a profile never links to another organization's login account.** Creating a driver, customer or contact with an email or phone that belongs to another organization's account linked that account and exposed its name, email and phone. The new organization could then reset its password or deactivate it. Only accounts that already belong to the organization, or belong to no organization, are reused now. The refusal does not say whose account it is. `POST /v1/drivers` also ignores a `company` that is not the API credential's own. Logins already shared by the old behaviour can only be managed by their holder. (#414) -- **Fix: orders can be edited with a partial payload.** `PUT /v1/orders/{id}` accepts a `payload` with only the parts that change, such as only entities or only a new dropoff. (#411) -- **Fix: addresses sent with coordinates keep their street.** A place given as a street address plus `latitude`/`longitude` was reverse-geocoded and stored as a different nearby address. The street and the coordinates are now kept as sent, without a geocoding call. (#411) -- **Feature: idempotent order creation.** `POST /v1/orders` accepts an `Idempotency-Key` header. A retry with the same key within 24 hours returns the order already created, with `Idempotent-Replayed: true`, and a concurrent duplicate gets `409`. (#412) -- **Fix: `scheduled_at` keeps its UTC offset.** `2026-10-21T11:00:00-07:00` is now stored as 18:00 UTC instead of 11:00, and `PUT /v1/orders/{id}/schedule` stores the UTC instant of a date and time in the company timezone. Rows written before this keep their old values. (#412) -- **Fix: service quotes.** The `currency` filter works again, stored quotes expire after 48 hours by default (`fleetops.service_quotes.ttl_minutes`), and `preview=1` prices a request without storing quote rows. (#412) -- **Fix: tracking numbers with a space can be looked up again.** Since v0.6.72, a number such as `AL 7796486490AE`, generated for a company whose name has a space in its first three letters, got "not found". Single inner spaces are accepted now. New numbers only use letters and digits: the company prefix skips spaces and punctuation ("Al Noor" gives `ALN`), and a region such as "New York" becomes `NEWYORK`. (#413, #416) -- **Feature: App Review access for Navigator.** Apple and Google reviewers can't receive the texted sign-in code. An organization can turn on **Settings → Navigator App → App Review**: reviewers sign in to its Navigator with the test number +1 202 555 0144 (a range kept for fiction, never texted) and a six-digit code the owner creates and enters in App Store Connect and Google Play Console. The code is stored hashed, shown once, and only works for that organization. The first sign-in adds an **App Reviewer** driver, which ad-hoc offers, nearest-driver assignment and the orchestrator always leave out. Built on core-api's App Review access; the `NAVIGATOR_*` review env settings still work on self-hosted installs. See `docs/NAVIGATOR_APP_REVIEW.md`. (#418) +- **Laravel 12.** The server package now runs on Laravel 12 with Carbon 3 and requires `fleetbase/core-api` ^2.0. It installs into the Laravel 12 Fleetbase API (fleetbase/fleetbase v0.8.0); Laravel 10 installs stay on the v0.6.75 line. +- **No security advisory exceptions.** `composer audit` reports no advisories on the Laravel 12 dependency set, so the Composer advisory workarounds are gone. +- **Order config policies and triggers.** An order config now decides more of how its orders behave, for any kind of operation. + - **Policies:** + - how adhoc orders are offered (strategy, offer time, radius, and what happens when nobody accepts); + - driver matching by vehicle type, and leaving out busy drivers; + - what customers may do: payment methods, a required quote, settling earlier orders first, cancelling, chat, rating and sharing tracking; + - pricing an order again from the actual distance and time. + - **Triggers:** actions that run when an order reaches an activity, is created, completed or canceled, when no driver accepts, or when the driver comes close to the pickup or drop-off. The built-in actions notify the customer or driver, open or close the customer chat, set meta, or cancel. Extensions can add their own, for example Ledger's `send_invoice`. + - Both are edited in the Console's new **Policies** and **Triggers** tabs, and are returned with the public order config. +- **Order config templates.** Make a config from a template in the Console (**New Order Config**) or with `php artisan fleetops:create-order-config {template} --company=`. The templates are `transport`, the default, and `passenger`, for on-demand trips. +- **Adhoc dispatch strategies.** Adhoc orders can be offered to every nearby driver at once, or one driver at a time with a timed offer (the default), with decline and expiry. The company default is set under Settings → Dispatch, and a config or an order can override it. +- **Customer API.** These endpoints work for any kind of customer: + - places, sign-in codes and phone changes; + - for an order: dispatch, cancel, driver, tracker and ETA; + - chat with the driver, driver ratings, sharing a tracking link, and account deletion. + + The order's config decides which of them a customer may use. +- **Configs enforce what they declare.** The public API now applies the config's strict transitions, proof-of-delivery requirement, dispatch setting and initial status, as the Console already did. Orders created through the API accept `custom_fields`, and flow conditions can read the config's custom fields. The flow condition operators `in`, `has`, `contains`, `beginsWith` and `endsWith` now work as their names say. +- fix(request): call core-api's inputArray instead of array (#423) +- chore(l12): keep fresh-install columns identical without Doctrine (#422) --- ## Upgrading -- **Requires fleetbase/core-api v1.6.74** (`composer.json` now requires `^1.6.74`), which adds App Review access and its `review_accesses` table: run `php artisan migrate`. -- **Routing defaults changed (#406).** Review **Admin → Fleet-Ops → Routing** after upgrading: - - The default routing engine is now **Valhalla** (it was OSRM). Without a Valhalla server (`VALHALLA_HOST`, or the Valhalla extension's settings), order distance and ETAs use the straight-line estimate. Self-hosters running their own OSRM can make it the default in the panel or with `ROUTING_DISPLAY_ENGINE=osrm`. - - **Google is off.** Turn it on in the panel or set `ROUTING_GOOGLE_ENABLED=true`. `DISTANCE_MATRIX_PROVIDER=google` also enables it until the panel is saved. - - Tracking follows the routing engine. `TRACKING_PROVIDER` and `TRACKING_PROVIDER_FALLBACKS` are no longer read, and saved tracking provider and fallback choices are ignored. - - `DISTANCE_MATRIX_PROVIDER` only seeds the admin defaults now; it no longer overrides order distance. - - New starting values, read until the panel is first saved: `ROUTING_GOOGLE_ENABLED`, `ROUTING_DISPLAY_ENGINE`, `ROUTING_OPTIMIZATION_ENGINE`, `ROUTING_SERVER_ROUTING`, plus `VALHALLA_HOST`, `VALHALLA_API_KEY`, `VALHALLA_COSTING` and `VALHALLA_TIMEOUT`. - - Existing orders: started, unfinished orders from the last 2 days are re-measured by `fleetops:update-estimations`; unstarted orders pick up road distance at their next ready or edit; completed and cancelled orders keep their stored values. No migration. -- **OSRM server.** Nothing to do: `OSRM_HOST` keeps working until a host is saved in Admin → Fleet-Ops → Routing. Organization OSRM servers are new and empty. -- **Private routing hosts (#417).** On self-hosted installs, an organization override pointing at a private host (for example `http://valhalla:8002`) now falls back to the system server. Set `VALHALLA_ALLOW_PRIVATE_HOSTS=true` or `VROOM_ALLOW_PRIVATE_HOSTS=true` to allow it. System-level private hosts are unaffected. -- **Fleetbase Cloud.** After deploying, set the Valhalla host to `https://valhalla.routing.fleetbase.io` with Cloud's gateway key, Google and OSRM off, and Valhalla as the default engine with road routing. Enter the gateway key only after fleetbase/valhalla v0.0.5 and fleetbase/vroom v0.0.5 ship (valhalla#9, vroom#8), because the extensions' settings endpoints return the key to any signed-in user until then. ---- -## Need help? -- [GitHub Discussions](https://github.com/fleetbase/fleetbase/discussions) -- [Discord](https://discord.gg/HnTqQ6zAVn) +- **Requires fleetbase/core-api v2.0.0** (Laravel 12, PHP 8.2 or later). Upgrade the API to fleetbase/fleetbase v0.8.0 first, then this extension. +- Run `php artisan migrate` after upgrading. +- **Flow conditions:** a config whose flow `logic` used `in`, `has`, `contains`, `beginsWith` or `endsWith` now gets the documented result. Before this release those operators compared the wrong way round, or never matched. diff --git a/addon/components/activity/form.hbs b/addon/components/activity/form.hbs index e334ea4db..e867e946b 100644 --- a/addon/components/activity/form.hbs +++ b/addon/components/activity/form.hbs @@ -1,52 +1,109 @@ -
- - - - - - - {{t "activity.form.completes-order"}} - - - - - {{t "activity.form.require-pod"}} - - - {{#if @resource.require_pod}} - - + - {{/each}} - - + {{#each this.podOptions as |podOption|}} + + {{/each}} + + + {{/if}} + {{#unless this.readonlyDetails}} +
+ {{t "order-config-manager.step.developer-events"}} + {{t "order-config-manager.step.developer-events-help"}} + +
+ {{/unless}} + {{else if (eq this.tab "happens")}} +

{{t "order-config-manager.step.when-reaches" step=(or @resource.status @resource.code)}}

+ +

{{t "order-config-manager.step.footnote"}}

+ {{else}} +

{{t "order-config-manager.step.conditions-lead" step=(or @resource.status @resource.code)}}

+ {{#if this.readonlyDetails}} + + {{else}} + + {{/if}} {{/if}} - {{#unless (cannot "fleet-ops update order-config")}} - - - {{/unless}} - -
\ No newline at end of file + + diff --git a/addon/components/activity/form.js b/addon/components/activity/form.js index fd4a4079f..7d0bea445 100644 --- a/addon/components/activity/form.js +++ b/addon/components/activity/form.js @@ -3,8 +3,60 @@ import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; import { underscore, capitalize, w } from '@ember/string'; import { task } from 'ember-concurrency'; +import { inject as service } from '@ember/service'; +/** + * A step of an order config's flow, in its side panel: Details (status, code, details, whether it + * completes the order and needs proof of delivery), What happens here (the triggers that run when + * an order reaches it) and Conditions (logic that must pass to reach it). + * + * The panel passes options on its overlay: `readonlyDetails` for system configs and steps that + * can't change, `actions` and `placeholders` from capabilities, and `initialTab`. + */ export default class ActivityFormComponent extends Component { + @service abilities; + @service intl; + + @tracked tab; + + constructor() { + super(...arguments); + this.tab = this.args.overlay?.initialTab ?? 'details'; + } + + get canUpdate() { + return this.abilities.can('fleet-ops update order-config'); + } + + get readonlyDetails() { + return !this.canUpdate || Boolean(this.args.overlay?.readonlyDetails); + } + + get triggers() { + return this.args.resource?.get?.('actions') ?? this.args.resource?.actions ?? []; + } + + get tabs() { + const tab = (key, label) => ({ key, label, selected: this.tab === key }); + return [ + tab('details', this.intl.t('order-config-manager.step.tab-details')), + tab('happens', this.intl.t('order-config-manager.step.tab-happens', { count: this.triggers.length })), + tab('conditions', this.intl.t('order-config-manager.step.tab-conditions')), + ]; + } + + @action selectTab(key) { + this.tab = key; + } + + @action setTriggers(triggers) { + this.args.resource.set('actions', triggers); + } + + @action toggle(key, value) { + this.args.resource.set(key, value); + } + /** * Proof of delivery options. * diff --git a/addon/components/activity/logic-builder.hbs b/addon/components/activity/logic-builder.hbs index 14bf3219d..a59ecaeee 100644 --- a/addon/components/activity/logic-builder.hbs +++ b/addon/components/activity/logic-builder.hbs @@ -1,16 +1,16 @@
-
{{t "activity.form.logic-builder.activity-logic"}}
+
{{or @title (t "activity.form.logic-builder.activity-logic")}}
- +
\ No newline at end of file +
+
+ {{t "order-config-manager.entities.preview"}} + + + + {{or @resource.name (t "order-config-manager.entities.name-preview")}} + {{this.previewMeta}} + + +
+
+
diff --git a/addon/components/custom-entity/form.js b/addon/components/custom-entity/form.js index 8709280cc..f30b0f8b5 100644 --- a/addon/components/custom-entity/form.js +++ b/addon/components/custom-entity/form.js @@ -7,8 +7,20 @@ import { dasherize } from '@ember/string'; export default class CustomEntityFormComponent extends Component { @service notifications; @service fetch; + @service intl; @tracked config; + /** How the entity reads when it's picked for an order: type, size and weight. */ + get previewMeta() { + const resource = this.args.resource; + const get = (key) => resource?.get?.(key) ?? resource?.[key]; + const size = [get('length'), get('width'), get('height')].every((value) => value !== undefined && value !== null && value !== '') + ? `${get('length')} × ${get('width')} × ${get('height')} ${get('dimensions_unit') ?? ''}`.trim() + : this.intl.t('order-config-manager.entities.no-size'); + const weight = get('weight') ? `${get('weight')} ${get('weight_unit') ?? ''}`.trim() : this.intl.t('order-config-manager.entities.no-weight'); + return [get('type') || this.intl.t('order-config-manager.entities.type-preview'), size, weight].join(' · '); + } + /** * Action method to save the custom entity. It triggers an optional onSave callback * with the current state of the custom entity. diff --git a/addon/components/layout/fleet-ops-sidebar.js b/addon/components/layout/fleet-ops-sidebar.js index 6c643569d..47cf18d29 100644 --- a/addon/components/layout/fleet-ops-sidebar.js +++ b/addon/components/layout/fleet-ops-sidebar.js @@ -206,6 +206,7 @@ export default class LayoutFleetOpsSidebarComponent extends Component { this.createItem('menu.payments', 'cash-register', 'settings.payments', 'fleet-ops view payments', 'fleet-ops see payments'), this.createItem('menu.notifications', 'bell', 'settings.notifications', 'fleet-ops view notification-settings', 'fleet-ops see notification-settings'), this.createItem('menu.routing', 'route', 'settings.routing', 'fleet-ops view routing-settings', 'fleet-ops see routing-settings'), + this.createItem('menu.dispatch', 'paper-plane', 'settings.dispatch', 'fleet-ops view routing-settings', 'fleet-ops see routing-settings'), this.createItem('menu.orchestrator', 'circle-nodes', 'settings.orchestrator', 'fleet-ops view routing-settings', 'fleet-ops see routing-settings'), this.createItem('menu.scheduling', 'calendar-days', 'settings.scheduling', 'fleet-ops view scheduling-settings', 'fleet-ops see scheduling-settings'), this.createItem( @@ -411,12 +412,13 @@ export default class LayoutFleetOpsSidebarComponent extends Component { 'settings.payments': 3, 'settings.notifications': 4, 'settings.routing': 5, - 'settings.orchestrator': 6, - 'settings.scheduling': 7, - 'settings.tracking-page': 8, - 'settings.telematics': 9, - 'settings.custom-fields': 10, - 'settings.avatars': 11, + 'settings.dispatch': 6, + 'settings.orchestrator': 7, + 'settings.scheduling': 8, + 'settings.tracking-page': 9, + 'settings.telematics': 10, + 'settings.custom-fields': 11, + 'settings.avatars': 12, }; return priorities[route] ?? 0; diff --git a/addon/components/modals/new-order-config.hbs b/addon/components/modals/new-order-config.hbs index f168e7131..d8bc78118 100644 --- a/addon/components/modals/new-order-config.hbs +++ b/addon/components/modals/new-order-config.hbs @@ -1,19 +1,99 @@ - -
-
-
\ No newline at end of file diff --git a/addon/components/order-config-manager/activity-flow.js b/addon/components/order-config-manager/activity-flow.js index 3ed847ca8..2117d3d07 100644 --- a/addon/components/order-config-manager/activity-flow.js +++ b/addon/components/order-config-manager/activity-flow.js @@ -13,6 +13,29 @@ import inlineTask from '@fleetbase/ember-core/utils/inline-task'; import createFlowActivity from '../../utils/create-flow-activity'; import contextComponentCallback from '@fleetbase/ember-core/utils/context-component-callback'; import normalizeOrderConfigFlow, { getOrderConfigFlowRootCode } from '../../utils/normalize-order-config-flow'; +import { ICON_GROUPS, actionIcon, actionLabel } from '../../utils/order-config-action-meta'; + +const NODE_WIDTH = 236; +const NODE_HEIGHT = 64; + +/** Role tile icons, drawn on a 24 × 24 grid. */ +const ROLE_ICONS = { + start: 'M8 5v14l11-7z', + step: 'M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z', + complete: 'M5 12l5 5L20 7', + end: 'M7 7h10v10H7z', +}; + +/** Action icons on a node, drawn on a 24 × 24 grid, keyed by the icon names in order-config-action-meta. */ +const ACTION_PATHS = { + bell: 'M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10 21h4', + comments: 'M21 12a8 8 0 0 1-12 7l-5 1 1-4a8 8 0 1 1 16-4z', + 'comment-slash': 'M21 12a8 8 0 0 1-12 7l-5 1 1-4a8 8 0 1 1 16-4zM4 4l16 16', + 'file-invoice': 'M6 3h12v18l-3-2-3 2-3-2-3 2zM9 8h6M9 12h6', + tag: 'M3 12V4h8l10 10-8 8zM7.5 7.5h.01', + ban: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM5.6 5.6l12.8 12.8', + bolt: 'M13 3L5 14h6l-1 7 8-11h-6z', +}; /** * Manages the activity flow for order configuration, allowing users to create, edit, and view a sequence of activities. @@ -23,6 +46,10 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { @service notifications; @service intl; @service abilities; + @service fetch; + + /** Actions, events and placeholders triggers can use, from `order-configs/capabilities`. */ + @tracked capabilities = { actions: [], events: [], placeholders: [] }; /** * Represents the current state of the activity flow. @@ -94,6 +121,7 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { constructor(owner, { config, configManagerContext }) { super(...arguments); this.config = config; + this.loadCapabilities.perform(); configManagerContext.on('onConfigChanged', (newConfig) => { this.changeConfig(newConfig); @@ -256,46 +284,32 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { * Initializes the custom JointJS shapes used in the activity flow. */ initializeActivityJointModel() { + const chip = (index) => [ + { tagName: 'rect', selector: `chip${index}`, className: 'flow-activity-chip' }, + { tagName: 'path', selector: `chipIcon${index}`, className: 'flow-activity-chip-icon' }, + ]; joint.shapes.fleetbase = {}; - joint.shapes.fleetbase.Activity = joint.shapes.standard.Rectangle.define( + joint.shapes.fleetbase.Activity = joint.dia.Element.define( 'fleetbase.Activity', { attrs: { - rect: { stroke: 'none', fillOpacity: 0 }, - text: { - textVerticalAnchor: 'middle', - textAnchor: 'middle', - refX: '50%', - refY: '50%', - fontSize: 14, - fill: '#333', - }, + body: { width: 'calc(w)', height: 'calc(h)', rx: 12, ry: 12 }, + tile: { x: 12, y: 'calc(0.5*h-16)', width: 32, height: 32, rx: 9, ry: 9 }, + tileIcon: { transform: 'translate(20, 24) scale(0.67)' }, + status: { x: 54, y: 'calc(0.5*h-4)', fontSize: 13, fontWeight: 600, textVerticalAnchor: 'middle' }, + meta: { x: 54, y: 'calc(0.5*h+13)', fontSize: 11, textVerticalAnchor: 'middle' }, }, }, { markup: [ - { - tagName: 'rect', - selector: 'body', - className: 'flow-activity', - }, - { - tagName: 'rect', - selector: 'pill', - className: 'flow-activity-status-pill', - }, - { - tagName: 'text', - selector: 'code', - }, - { - tagName: 'text', - selector: 'status', - }, - { - tagName: 'text', - selector: 'details', - }, + { tagName: 'rect', selector: 'body', className: 'flow-activity' }, + { tagName: 'rect', selector: 'tile', className: 'flow-activity-tile' }, + { tagName: 'path', selector: 'tileIcon', className: 'flow-activity-tile-icon' }, + { tagName: 'text', selector: 'status', className: 'flow-activity-status' }, + { tagName: 'text', selector: 'meta', className: 'flow-activity-meta' }, + ...chip(0), + ...chip(1), + ...chip(2), ], } ); @@ -315,6 +329,63 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { }); } + /** + * Saves the flow as it is on the canvas without redrawing it, for "Save step". + */ + @task *persistFlow() { + this.config.set('flow', this.serializeFlow()); + try { + yield this.config.save(); + this.notifications.success(this.intl.t('order-config-manager.step.saved')); + this.args.onConfigUpdated?.(this.config); + } catch (error) { + this.notifications.serverError(error); + } + } + + @task *loadCapabilities() { + try { + const { actions, events, placeholders } = yield this.fetch.get('order-configs/capabilities'); + this.capabilities = { actions: actions ?? [], events: events ?? [], placeholders: placeholders ?? [] }; + } catch { + this.capabilities = { actions: [], events: [], placeholders: [] }; + } + } + + get eventCount() { + return (this.config?.triggers ?? []).length; + } + + /** The actions used anywhere on the flow, for the legend. */ + get legend() { + const used = new Set( + Object.values(this.config?.flow ?? {}) + .flatMap((activity) => activity?.actions ?? []) + .map((trigger) => trigger?.action) + ); + return ICON_GROUPS.filter((group) => group.actions.some((name) => used.has(name))).map((group) => ({ + icon: group.icon, + label: this.intl.t(`order-config-manager.flow.${group.key}`), + })); + } + + /** + * Opens the order events: triggers for things that happen to an order outside its steps. + */ + @action openOrderEvents() { + this.resourceContextPanel.open({ + content: 'order-config/order-events', + title: this.intl.t('order-config-manager.events.title'), + panelContentClass: 'py-2 px-4', + resource: this.config, + config: this.config, + actions: this.capabilities.actions, + events: this.capabilities.events, + placeholders: this.capabilities.placeholders, + onSaved: (config) => this.args.onConfigUpdated?.(config), + }); + } + /** * If any context is provided then initialize the state. * @@ -577,21 +648,55 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { * @returns {Object} - The link object that has been added to the graph. */ addLinkToGraph(parentActivity, childActivity) { - const link = new joint.shapes.standard.Link({ - source: { id: parentActivity.get('id') }, - target: { id: childActivity.get('id') }, - }); + const link = this.createLink(parentActivity, childActivity); link.addTo(this.graph); return link; } + /** + * A connector from a step to one it leads to: a smooth curve with an arrowhead, labelled "or" + * when it's the second (or later) way out of the step. + */ + createLink(parentActivity, childActivity) { + const siblings = (parentActivity.get('activities') ?? []).map((activity) => activity?.get?.('id')); + const isBranch = siblings.indexOf(childActivity.get('id')) > 0; + return new joint.shapes.standard.Link({ + source: { id: parentActivity.get('id'), anchor: { name: 'right' } }, + target: { id: childActivity.get('id'), anchor: { name: 'left' } }, + connector: { name: 'smooth' }, + attrs: { + line: { + class: 'flow-activity-link', + stroke: '#64748b', + strokeWidth: 1.6, + targetMarker: { type: 'path', d: 'M 9 -4.5 L 0 0 L 9 4.5', fill: 'none', 'stroke-width': 1.6 }, + }, + }, + labels: isBranch + ? [ + { + markup: [ + { tagName: 'rect', selector: 'labelBody', className: 'flow-activity-link-label' }, + { tagName: 'text', selector: 'labelText', className: 'flow-activity-link-label-text' }, + ], + attrs: { + labelText: { text: this.intl.t('order-config-manager.common.or'), fontSize: 11, textAnchor: 'middle', textVerticalAnchor: 'middle' }, + labelBody: { ref: 'labelText', x: 'calc(x-8)', y: 'calc(y-3)', width: 'calc(w+16)', height: 'calc(h+6)', rx: 9, ry: 9 }, + }, + position: { distance: 0.5 }, + }, + ] + : [], + }); + } + /** * Handles activity clicks within the JointJS paper. * @param {Object} elementView - The JointJS element view of the clicked activity. */ onActivityClicked(elementView) { - // Disable editing activity if core service or if cannot view order config - if (this.config.core_service || this.abilities.cannot('fleet-ops view order-config')) return; + // Anyone who can view the config can open a step; what they can change is decided in the panel. + if (this.abilities.cannot('fleet-ops view order-config')) return; const { model } = elementView; const activity = this.getActivityById(model.id); @@ -744,38 +849,10 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { */ createActivityNode(activity, positionals = {}) { const { width, height, x, y } = positionals; - const code = this.activityText(activity.get('code')); - const status = this.activityText(activity.get('status')); - const details = this.activityText(activity.get('details')); - const wrappedDetails = this.activityText(joint.util.breakText(details, { width })); const activityNode = new joint.shapes.fleetbase.Activity({ position: { x, y }, size: { width, height }, - attrs: { - pill: { - ref: 'code', - refWidth: code.length * 1.35, - refHeight: 5, - refX: -5, - refY: -2, - rx: 5, - ry: 5, - fill: '#374151', - stroke: '#374151', - strokeWidth: 1, - }, - code: { ref: 'pill', text: code, fill: 'white', fontSize: 14, textAnchor: 'left', refX: 15, refY: 20, yAlignment: 'middle' }, - status: { text: status, fill: 'white', fontSize: 14, fontWeight: 'bold', refY: 40, refX: 10, textAnchor: 'left' }, - details: { - text: wrappedDetails, - fill: 'white', - refY: 60, - fontSize: 14, - refX: 10, - textAnchor: 'left', - }, - body: { fill: activity.get('color'), stroke: '#374151', strokeWidth: 1, rx: 10, ry: 10 }, - }, + attrs: this.activityNodeAttrs(activity, width), interactive: false, activity: activity, }); @@ -786,6 +863,72 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { return activity; } + /** + * What a step's node shows: a tile for its role (start, step, completes the order, ends it), + * its status and code, and an icon for each thing that happens when an order reaches it. + * + * @param {Object} activity + * @param {Number} width + * @returns {Object} JointJS attrs + */ + activityNodeAttrs(activity, width = NODE_WIDTH) { + const code = this.activityText(activity.get('code')); + const status = this.activityText(activity.get('status')) || code; + const role = this.activityRole(activity); + const actions = (activity.get('actions') ?? []).map((trigger) => trigger?.action).filter(Boolean); + const shown = actions.slice(0, 3); + const roleText = role === 'step' ? '' : ` · ${this.intl.t(`order-config-manager.flow.role-${role}`)}`; + const textWidth = width - 54 - 12 - shown.length * 23; + const attrs = { + body: { class: 'flow-activity' }, + tile: { class: `flow-activity-tile flow-activity-tile--${role}` }, + tileIcon: { d: ROLE_ICONS[role], class: `flow-activity-tile-icon flow-activity-tile-icon--${role}` }, + status: { text: joint.util.breakText(status, { width: textWidth }, { 'font-size': 13, 'font-weight': 600 }, { maxLineCount: 1, ellipsis: true }) }, + meta: { text: joint.util.breakText(`${code}${roleText}`, { width: textWidth }, { 'font-size': 11 }, { maxLineCount: 1, ellipsis: true }) }, + }; + for (let index = 0; index < 3; index++) { + const name = shown[index]; + const chipX = width - 12 - (shown.length - index) * 23 + 3; + attrs[`chip${index}`] = name ? { display: 'block', x: chipX, y: 22, width: 20, height: 20, rx: 6, ry: 6 } : { display: 'none' }; + attrs[`chipIcon${index}`] = name + ? { display: 'block', d: ACTION_PATHS[actionIcon(name)] ?? ACTION_PATHS.bolt, transform: `translate(${chipX + 4.5}, 26.5) scale(0.46)` } + : { display: 'none' }; + if (name) { + attrs[`chip${index}`].title = actionLabel(this.intl, name, this.capabilities.actions); + } + } + + return attrs; + } + + /** + * A step's role in the lifecycle: where orders start, a step along the way, the step that + * completes them, or another step that ends them. + */ + activityRole(activity) { + const code = activity.get('code'); + const lifecycle = this.lifecycle ?? {}; + const root = getOrderConfigFlowRootCode(normalizeOrderConfigFlow(this.config?.flow ?? {}), lifecycle.initial); + if (activity.get('complete') || lifecycle.completed === code) { + return 'complete'; + } + if (lifecycle.canceled === code || (lifecycle.terminal ?? []).includes(code)) { + return 'end'; + } + if (code === (lifecycle.initial ?? root ?? 'created')) { + return 'start'; + } + return 'step'; + } + + /** Redraws a step's node after it changed in the side panel. */ + refreshActivityNode(activity) { + const node = activity?.get?.('node'); + if (node) { + node.attr(this.activityNodeAttrs(activity, node.size().width)); + } + } + /** * Determines the positioning for an activity node. * @param {Object} activity - The activity for which to determine positioning. @@ -794,13 +937,8 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { */ getActivityPositioning(activity, parentActivity) { const parentActivities = parentActivity ? parentActivity.get('activities') : []; - const width = 250; - const baseHeight = 90; - const lineHeight = 10; - const details = this.activityText(activity.get('details')); - const wrappedDetails = this.activityText(joint.util.breakText(details, { width })); - const numberOfLines = wrappedDetails.split('\n').length; - const height = baseHeight + lineHeight * (numberOfLines - 1); + const width = NODE_WIDTH; + const height = NODE_HEIGHT; let x = 100; if (parentActivity) { const parentActivityX = parentActivity.get('node').position().x; @@ -1059,17 +1197,25 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { * @param {Object} targetActivity - The target activity object that may be linked to the activity being edited. */ editActivity(activity, targetActivity) { - // if immutable do nothing - if (this.immutableActivities.includes(activity.get('code'))) return; + const isNew = Boolean(targetActivity) && !this.flow[activity.get('code')]; + // A system config's steps, and the standard dispatch steps, keep their details; what happens at them can still change. + const readonlyDetails = Boolean(this.config.core_service) || this.immutableActivities.includes(activity.get('code')); + const steps = Object.keys(this.flow); + const position = steps.indexOf(activity.get('code')) + 1; contextComponentCallback(this, 'onContextChanged', this._createContextualActivity(activity)); this.resourceContextPanel.open({ content: 'activity/form', - title: this.intl.t('common.create-new-resource', { resource: lowercase(this.intl.t('resource.activity')) }), + title: isNew ? this.intl.t('common.create-new-resource', { resource: lowercase(this.intl.t('resource.activity')) }) : activity.get('status') || activity.get('code'), panelContentClass: 'py-2 px-4', resource: activity, pojoResource: true, - saveTask: inlineTask(() => { + readonlyDetails, + initialTab: isNew ? 'details' : 'happens', + actions: this.capabilities.actions, + placeholders: this.capabilities.placeholders, + stepPosition: position > 0 ? this.intl.t('order-config-manager.step.kicker', { position, total: steps.length }) : null, + saveTask: inlineTask(async () => { // Check if the activity exists and if it's not the same instance being updated const existingActivity = this.flow[activity.get('code')]; if (existingActivity && existingActivity !== activity) { @@ -1081,10 +1227,13 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { if (targetActivity) { this.addNewLinkedActivity(targetActivity, activity); } + this.refreshActivityNode(activity); this.resourceContextPanel.closeAll(); + await this.persistFlow.perform(); }), onClose: () => { contextComponentCallback(this, 'onContextChanged', null); + this.refreshActivityNode(activity); }, }); } @@ -1128,11 +1277,7 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { this.repositionActivities(targetActivity); // Link the new activity - const link = new joint.shapes.standard.Link({ - source: { id: targetActivity.get('id') }, - target: { id: newActivity.get('id') }, - }); - link.addTo(this.graph); + this.addLinkToGraph(targetActivity, newActivity); this.resizePaperWidthToFitActivities(); return newActivity; diff --git a/addon/components/order-config-manager/entities.hbs b/addon/components/order-config-manager/entities.hbs index 677f47571..47a8e89f4 100644 --- a/addon/components/order-config-manager/entities.hbs +++ b/addon/components/order-config-manager/entities.hbs @@ -1,60 +1,66 @@ -
-
-
- {{#each this.customEntities as |customEntity index|}} - -
-
-
-
-
- {{customEntity.name}} -
-
-
-
-
-
{{t "order-config-manager.entities.name"}}
-
{{customEntity.name}}
-
-
-
{{t "order-config-manager.entities.description"}}
-
{{customEntity.description}}
-
-
-
{{t "order-config-manager.entities.type"}}
-
{{customEntity.type}}
+ + {{#if this.customEntities.length}} +
+ {{#each this.customEntities as |customEntity index|}} +
+ +
+
+ {{customEntity.name}} + {{#if customEntity.type}}{{customEntity.type}}{{/if}}
-
-
-
-
{{t "order-config-manager.entities.length"}}
-
{{customEntity.length}} {{customEntity.dimensions_unit}}
-
-
-
{{t "order-config-manager.entities.width"}}
-
{{customEntity.width}} {{customEntity.dimensions_unit}}
+ {{customEntity.description}} +
+ {{entity-size customEntity (t "order-config-manager.entities.no-size")}} + {{entity-weight customEntity (t "order-config-manager.entities.no-weight")}}
-
-
{{t "order-config-manager.entities.height"}}
-
{{customEntity.height}} {{customEntity.dimensions_unit}}
-
-
-
{{t "order-config-manager.entities.weight"}}
-
{{customEntity.weight}} {{customEntity.weight_unit}}
+
+
-
- - {{/each}} -
\ No newline at end of file + {{/each}} +
+ {{else}} +
+ + {{t "order-config-manager.entities.empty-title"}} + {{t "order-config-manager.entities.empty-body"}} + {{#if (can "fleet-ops update order-config")}} +
+ {{t "order-config-manager.entities.start-from"}} + {{#each this.suggestions as |suggestion|}} + + {{/each}} +
+ {{/if}} +
+ {{/if}} +
diff --git a/addon/components/order-config-manager/entities.js b/addon/components/order-config-manager/entities.js index 404cd436c..41b745d01 100644 --- a/addon/components/order-config-manager/entities.js +++ b/addon/components/order-config-manager/entities.js @@ -58,6 +58,22 @@ export default class OrderConfigManagerEntitiesComponent extends Component { * Action method to create a new custom entity and open it for editing. * @action */ + /** Common things to start from, with their usual size and weight filled in. */ + get suggestions() { + const S = 'order-config-manager.entities.suggest'; + return [ + { key: 'pallet', type: 'Pallet', props: { length: 120, width: 80, height: 14.4, dimensions_unit: 'cm', weight: 25, weight_unit: 'kg' } }, + { key: 'parcel', type: 'Parcel', props: { length: 30, width: 20, height: 15, dimensions_unit: 'cm' } }, + { key: 'crate', type: 'Crate', props: { dimensions_unit: 'cm' } }, + { key: 'container', type: 'Container', props: { length: 6.06, width: 2.44, height: 2.59, dimensions_unit: 'm', weight: 2300, weight_unit: 'kg' } }, + { key: 'suitcase', type: 'Luggage', props: { length: 75, width: 50, height: 30, dimensions_unit: 'cm' } }, + ].map((suggestion) => ({ ...suggestion, label: this.intl.t(`${S}.${suggestion.key}`) })); + } + + @action startFrom(suggestion) { + return this.editCustomEntity(createCustomEntity(suggestion.label, suggestion.type, '', suggestion.props), -1); + } + @action createNewCustomEntity() { const customEntity = createCustomEntity(); return this.editCustomEntity(customEntity); @@ -77,6 +93,9 @@ export default class OrderConfigManagerEntitiesComponent extends Component { resource: customEntity, pojoResource: true, saveTask: inlineTask(() => { + if (!customEntity.get('name')) { + return this.notifications.warning(this.intl.t('order-config-manager.entities.name-required')); + } if (index > -1) { this.customEntities = this.customEntities.map((_, i) => { if (i === index) { diff --git a/addon/components/order-config-manager/lifecycle.hbs b/addon/components/order-config-manager/lifecycle.hbs index 8799540a5..b002562cd 100644 --- a/addon/components/order-config-manager/lifecycle.hbs +++ b/addon/components/order-config-manager/lifecycle.hbs @@ -1,250 +1,73 @@ -
- -

{{t "order-config-manager.lifecycle.description"}}

- -
- -
+
+
+
+ {{#if this.isSystemConfig}} + + {{else if this.readonly}} + + {{/if}} - {{#if this.enabled}} -
-
-
{{t "order-config-manager.lifecycle.activities"}}
- {{#if (and this.canEdit this.hasActivities)}} - - {{/if}} +
+
+

{{t "order-config-manager.lifecycle.title"}}

+ {{t "order-config-manager.lifecycle.description"}}
-

{{t "order-config-manager.lifecycle.activities-help"}}

- - {{#if this.hasActivities}} -
- {{#each this.activityRows as |activity|}} -
- - - - -
{{activity.code}}{{#if activity.isInitial}} ({{t "order-config-manager.lifecycle.initial-short"}}){{/if}}
-
- - - - -
- - {{next.label}} - -
-
-
- - {{#if this.canEdit}} -
-
- {{/each}} -
- {{else}} -
{{t "order-config-manager.lifecycle.no-activities"}}
- {{/if}} +
+ {{#each this.lines as |line|}} + + {{/each}} +
+
- {{#if this.canEdit}} -
-
{{t "order-config-manager.lifecycle.add-activity"}}
-
- - - - - - - - - -
- -
+ {{#if this.own}} +
+

{{t "order-config-manager.lifecycle.checks"}}

+ {{#each this.checks as |check|}} +
+ + + + {{check.title}} + {{#if check.body}}{{check.body}}{{/if}} + + + {{#if check.fix}} +
- {{#if this.newActivityCodeTaken}} -
{{t "order-config-manager.lifecycle.problem-duplicate-code" code=this.newActivityCode}}
- {{/if}} -
- {{/if}} -
- -
- -
- - {{activity.label}} - {{activity.code}} - -
-
- - -
- - {{activity.label}} - -
-
+ {{/each}} + + {{/if}} - -
- - {{activity.label}} - {{activity.code}} - -
-
+ +
- -
- - {{activity.label}} - {{activity.code}} - +
\ No newline at end of file + {{/each}} + +
+
diff --git a/addon/components/order-config-manager/lifecycle.js b/addon/components/order-config-manager/lifecycle.js index 6712e5899..3249838bc 100644 --- a/addon/components/order-config-manager/lifecycle.js +++ b/addon/components/order-config-manager/lifecycle.js @@ -4,51 +4,33 @@ import { inject as service } from '@ember/service'; import { action } from '@ember/object'; import { isArray } from '@ember/array'; import { task } from 'ember-concurrency'; -import { underscore } from '@ember/string'; -import generateUUID from '@fleetbase/ember-core/utils/generate-uuid'; import normalizeOrderConfigFlow, { getOrderConfigFlowRootCode } from '../../utils/normalize-order-config-flow'; +import sentenceParts from '../../utils/sentence-parts'; -/** Keys of `meta.lifecycle` understood by the server (see OrderConfig::lifecycle()). */ +const L = 'order-config-manager.lifecycle'; const DEFAULTS = { initial: null, completed: null, canceled: null, terminal: [], dispatch: true, strict_transitions: false }; - -const NEW_ACTIVITY = { status: '', code: '', details: '', color: '#1f2937' }; +const STANDARD = ['created', 'dispatched', 'started', 'completed']; /** - * Manages an order config's configured lifecycle (`meta.lifecycle`): the activity new orders start - * at, the activities that complete, cancel and end an order, whether orders may be dispatched and - * whether transitions must follow the flow. Without a configured lifecycle the default dispatch - * lifecycle applies. + * How orders of a config start and end: whether they follow the standard dispatch steps or the + * config's own, which step they start at, which complete or cancel them, which other steps end + * them, whether they're dispatched, and whether they must follow the flow's arrows. Stored under + * `meta.lifecycle`; without one the config follows the standard dispatch steps. * - * The activities themselves (the config's `flow`) can be defined here too, so a lifecycle can be - * built from scratch without the graph editor: add or remove activities, set their labels and the - * activities each one can move to. Flow and lifecycle are saved together. + * The steps themselves are edited on Activity Flow. Checks here point out steps orders would get + * stuck at. * * @extends Component */ export default class OrderConfigManagerLifecycleComponent extends Component { - @service modalsManager; @service notifications; @service abilities; @service intl; - /** The config being managed. */ @tracked config; - - /** Working copy of `meta.lifecycle`, or null when the config has none. */ @tracked lifecycle = null; - - /** Last saved lifecycle, to tell whether there is anything to save. */ @tracked saved = null; - /** Working copy of the config's flow, keyed by activity code, with next activities as codes. */ - @tracked flow = {}; - - /** Flow as last saved, serialized, to tell whether there is anything to save. */ - @tracked savedFlow = '{}'; - - /** The activity being added. */ - @tracked newActivity = { ...NEW_ACTIVITY }; - constructor(owner, { config, configManagerContext }) { super(...arguments); this.changeConfig(config); @@ -62,217 +44,285 @@ export default class OrderConfigManagerLifecycleComponent extends Component { return this.abilities.can('fleet-ops update order-config') && !this.config?.core_service; } - get enabled() { - return this.lifecycle !== null; + get readonly() { + return !this.canEdit; } - /** Activities of the flow as select options. */ - get activities() { - return Object.values(this.flow).map((activity) => ({ code: activity.code, label: activity.status || activity.code })); + get isSystemConfig() { + return Boolean(this.config?.core_service); } - /** Activities with their next activities resolved, for the editor. */ - get activityRows() { - return Object.values(this.flow).map((activity) => ({ - ...activity, - next: (activity.activities ?? []).map((code) => this.option(code)).filter(Boolean), - isInitial: this.lifecycle?.initial === activity.code, - })); + get own() { + return this.lifecycle !== null; } - get hasActivities() { - return Object.keys(this.flow).length > 0; + get flow() { + return normalizeOrderConfigFlow(this.config?.flow ?? {}); } - get newActivityCode() { - return underscore((this.newActivity.code || this.newActivity.status || '').trim()); + get steps() { + return Object.values(this.flow) + .filter((activity) => activity && (activity.code || activity.key)) + .map((activity) => ({ + code: activity.code ?? activity.key, + label: activity.status || activity.code || activity.key, + next: (isArray(activity.activities) ? activity.activities : []).map((next) => (typeof next === 'string' ? next : (next?.code ?? next?.key))).filter(Boolean), + complete: Boolean(activity.complete), + })); } - get canAddActivity() { - const code = this.newActivityCode; - return this.canEdit && this.newActivity.status.trim() !== '' && code !== '' && !this.flow[code]; + label(code) { + return this.steps.find((step) => step.code === code)?.label ?? code; } - get newActivityCodeTaken() { - const code = this.newActivityCode; - return code !== '' && Boolean(this.flow[code]); + t(key, values) { + return this.intl.t(`${L}.${key}`, values); } - get selectedInitial() { - return this.option(this.lifecycle?.initial); - } + // ----- editing - get selectedCompleted() { - return this.option(this.lifecycle?.completed); + patch(patch) { + this.lifecycle = { ...(this.lifecycle ?? DEFAULTS), ...patch }; } - get selectedCanceled() { - return this.option(this.lifecycle?.canceled); + @action setMode(own) { + if (!own) { + this.lifecycle = null; + return; + } + this.lifecycle = this.saved ? { ...this.saved, terminal: [...this.saved.terminal] } : { ...DEFAULTS, terminal: [], initial: getOrderConfigFlowRootCode(this.flow) ?? null }; } - get selectedTerminal() { - return (this.lifecycle?.terminal ?? []).map((code) => this.option(code)).filter(Boolean); + @action discard() { + this.lifecycle = this.saved ? { ...this.saved, terminal: [...this.saved.terminal] } : null; } - get isDirty() { - return JSON.stringify(this.lifecycle) !== JSON.stringify(this.saved) || this.serializeFlow() !== this.savedFlow; + @action endAt(code) { + this.patch({ terminal: [...new Set([...(this.lifecycle?.terminal ?? []), code])] }); } - /** Problems that make the lifecycle unusable server-side. */ - get problems() { - if (!this.lifecycle) { - return []; - } + // ----- sentences - const problems = []; - const codes = this.activities.map((activity) => activity.code); - if (codes.length === 0) { - problems.push(this.intl.t('order-config-manager.lifecycle.problem-no-activities')); - } - if (!this.lifecycle.initial) { - problems.push(this.intl.t('order-config-manager.lifecycle.problem-initial-required')); - } + isUnsaved(key) { + return JSON.stringify(this.lifecycle?.[key] ?? null) !== JSON.stringify(this.saved?.[key] ?? null); + } - const referenced = [this.lifecycle.initial, this.lifecycle.completed, this.lifecycle.canceled, ...(this.lifecycle.terminal ?? [])].filter(Boolean); - for (const code of new Set(referenced)) { - if (!codes.includes(code)) { - problems.push(this.intl.t('order-config-manager.lifecycle.problem-missing-activity', { code })); - } - } + stepChoice(key, ariaKey, { allowNone } = {}) { + const options = this.steps.map((step) => ({ value: step.code, label: step.label })); + return { + kind: 'choice', + value: this.lifecycle?.[key] ?? null, + isDefault: false, + label: this.lifecycle?.[key] ? this.label(this.lifecycle[key]) : this.t('not-set'), + invalid: !this.lifecycle?.[key] && !allowNone, + ariaLabel: this.t(ariaKey), + options: allowNone ? [{ value: null, label: this.t('not-set') }, ...options] : options, + onChange: (value) => this.patch({ [key]: value }), + }; + } - return problems; + flagChoice(key, pairs, ariaKey) { + const value = this.lifecycle?.[key] ?? DEFAULTS[key]; + return { + kind: 'choice', + value, + isDefault: value === DEFAULTS[key], + ariaLabel: this.t(ariaKey), + options: pairs.map(([optionValue, label]) => ({ value: optionValue, label, isDefault: optionValue === DEFAULTS[key] })), + onChange: (next) => this.patch({ [key]: next }), + }; } - get canSave() { - return this.canEdit && this.isDirty && this.problems.length === 0; + line(keys, key, controls, help, error) { + return { keys, parts: sentenceParts(this.intl, `${L}.${key}`, controls), help, error, unsaved: keys.some((k) => this.isUnsaved(k)) }; } - /** Arrow function so templates can call it as a helper: (this.option code). */ - option = (code) => { - return code ? (this.activities.find((activity) => activity.code === code) ?? { code, label: code }) : null; - }; + get lines() { + const modeLine = { + keys: ['mode'], + parts: sentenceParts(this.intl, `${L}.mode.sentence`, { + choice: { + kind: 'choice', + value: this.own, + isDefault: !this.own, + ariaLabel: this.t('mode-aria'), + options: [ + { value: false, label: this.t('mode.standard'), isDefault: true }, + { value: true, label: this.t('mode.own') }, + ], + onChange: (own) => this.setMode(own), + }, + }), + help: this.own ? this.t('mode-help-own') : this.t('mode-help-standard'), + unsaved: (this.lifecycle === null) !== (this.saved === null), + }; - changeConfig(config) { - this.config = config; - this.saved = this.normalize(config?.meta?.lifecycle); - this.lifecycle = this.normalize(config?.meta?.lifecycle); - this.flow = this.readFlow(config?.flow); - this.savedFlow = this.serializeFlow(); - this.newActivity = { ...NEW_ACTIVITY }; - } + if (!this.own) { + return [modeLine]; + } - /** The stored flow as plain activity objects with next activities as codes. */ - readFlow(flow) { - const normalized = normalizeOrderConfigFlow(flow ?? {}); - const result = {}; - Object.values(normalized).forEach((activity, index) => { - if (!activity || typeof activity !== 'object') { - return; - } - const code = activity.code ?? activity.key; - if (!code) { - return; - } - result[code] = { - ...activity, - code, - key: activity.key ?? code, - sequence: activity.sequence ?? index, - activities: (isArray(activity.activities) ? activity.activities : []).map((next) => (typeof next === 'string' ? next : (next?.code ?? next?.key))).filter(Boolean), - }; - }); - return result; + const ends = new Set([this.lifecycle.completed, this.lifecycle.canceled].filter(Boolean)); + const endable = this.steps.filter((step) => !ends.has(step.code) && step.code !== this.lifecycle.initial).map((step) => step.code); + + return [ + modeLine, + this.line( + ['initial'], + 'initial', + { step: this.stepChoice('initial', 'initial-aria') }, + this.t('initial-help'), + this.lifecycle.initial ? null : this.t('problem-initial-required') + ), + this.line(['completed'], 'completed', { step: this.stepChoice('completed', 'completed-aria', { allowNone: true }) }, this.t('completed-help')), + this.line(['canceled'], 'canceled', { step: this.stepChoice('canceled', 'canceled-aria', { allowNone: true }) }, this.t('canceled-help')), + this.line( + ['terminal'], + 'terminal', + { + steps: { + kind: 'list', + items: (this.lifecycle.terminal ?? []).map((code) => ({ value: code, label: this.label(code) })), + options: endable.map((code) => ({ value: code, label: this.label(code) })), + emptyLabel: this.t('terminal-none'), + ariaLabel: this.t('terminal-aria'), + onChange: (terminal) => this.patch({ terminal }), + }, + }, + this.t('terminal-help') + ), + this.line( + ['dispatch'], + 'dispatch.sentence', + { + choice: this.flagChoice( + 'dispatch', + [ + [true, this.t('dispatch.on')], + [false, this.t('dispatch.off')], + ], + 'dispatch-aria' + ), + }, + this.t('dispatch-help') + ), + this.line( + ['strict_transitions'], + 'strict.sentence', + { + choice: this.flagChoice( + 'strict_transitions', + [ + [false, this.t('strict.off')], + [true, this.t('strict.on')], + ], + 'strict-aria' + ), + }, + this.t('strict-help') + ), + ]; } - serializeFlow() { - const serialized = {}; - Object.values(this.flow).forEach((activity) => { - // Graph-only state never belongs in the stored flow. - // eslint-disable-next-line no-unused-vars - const { node, id, parentId, _internalModel, ...stored } = activity; - serialized[activity.code] = { ...stored, activities: [...(activity.activities ?? [])] }; - }); - return JSON.stringify(serialized); + // ----- checks + + get endCodes() { + if (!this.lifecycle) { + return new Set(); + } + return new Set([this.lifecycle.completed, this.lifecycle.canceled, ...(this.lifecycle.terminal ?? [])].filter(Boolean)); } - @action setNewActivityField(field, event) { - this.newActivity = { ...this.newActivity, [field]: event.target.value }; + /** Steps with nowhere to go that don't end the order: orders reaching them get stuck. */ + get deadEnds() { + return this.steps.filter((step) => step.next.length === 0 && !step.complete && !this.endCodes.has(step.code)); } - @action addActivity() { - if (!this.canAddActivity) { - return; + get missing() { + if (!this.lifecycle) { + return []; } + const codes = this.steps.map((step) => step.code); + const referenced = [this.lifecycle.initial, this.lifecycle.completed, this.lifecycle.canceled, ...(this.lifecycle.terminal ?? [])].filter(Boolean); + return [...new Set(referenced)].filter((code) => !codes.includes(code)); + } - const code = this.newActivityCode; - const activity = { - key: code, - code, - status: this.newActivity.status.trim(), - details: this.newActivity.details.trim(), - color: this.newActivity.color || '#1f2937', - sequence: Object.keys(this.flow).length, - activities: [], - events: [], - logic: [], - actions: [], - entities: [], - complete: false, - require_pod: false, - pod_method: 'scan', - options: {}, - internalId: generateUUID(), - }; + get checks() { + if (!this.own) { + return []; + } - this.flow = { ...this.flow, [code]: activity }; - if (this.lifecycle && !this.lifecycle.initial) { - this.lifecycle = { ...this.lifecycle, initial: code }; + const checks = []; + if (this.lifecycle.completed) { + checks.push({ ok: true, title: this.t('check-completable', { step: this.label(this.lifecycle.completed) }) }); + } + this.missing.forEach((code) => checks.push({ ok: false, title: this.t('problem-missing-activity', { code }) })); + this.deadEnds.forEach((step) => + checks.push({ + ok: false, + title: this.t('check-dead-end', { step: step.label }), + body: this.t('check-dead-end-body'), + fix: this.canEdit ? () => this.endAt(step.code) : null, + }) + ); + if (this.deadEnds.length === 0) { + checks.push({ ok: true, title: this.t('check-no-dead-ends') }); } - this.newActivity = { ...NEW_ACTIVITY }; - } - @action removeActivity(code) { - const flow = { ...this.flow }; - delete flow[code]; - Object.keys(flow).forEach((key) => { - flow[key] = { ...flow[key], activities: flow[key].activities.filter((next) => next !== code) }; - }); - this.flow = flow; + return checks; + } - if (this.lifecycle) { - const without = (value) => (value === code ? null : value); - this.lifecycle = { - ...this.lifecycle, - initial: without(this.lifecycle.initial), - completed: without(this.lifecycle.completed), - canceled: without(this.lifecycle.canceled), - terminal: this.lifecycle.terminal.filter((item) => item !== code), - }; + // ----- at a glance + + get glance() { + if (!this.own) { + const label = (code) => this.intl.t(`${L}.standard.${code}`); + return [ + { title: this.t('glance-starts'), items: [{ role: 'start', label: label('created') }] }, + { title: this.t('glance-along'), items: STANDARD.slice(1, 3).map((code) => ({ role: 'step', label: label(code) })) }, + { + title: this.t('glance-ends'), + items: [ + { role: 'complete', label: label('completed'), note: this.t('glance-complete') }, + { role: 'end', label: label('canceled'), note: this.t('glance-canceled') }, + ], + }, + ]; } - } - @action setActivityField(code, field, event) { - this.flow = { ...this.flow, [code]: { ...this.flow[code], [field]: event.target.value } }; + const { initial, completed, canceled, terminal = [] } = this.lifecycle; + const ends = this.endCodes; + return [ + { title: this.t('glance-starts'), items: initial ? [{ role: 'start', label: this.label(initial) }] : [] }, + { title: this.t('glance-along'), items: this.steps.filter((step) => step.code !== initial && !ends.has(step.code)).map((step) => ({ role: 'step', label: step.label })) }, + { + title: this.t('glance-ends'), + items: [ + completed ? { role: 'complete', label: this.label(completed), note: this.t('glance-complete') } : null, + canceled ? { role: 'end', label: this.label(canceled), note: this.t('glance-canceled') } : null, + ...terminal.map((code) => ({ role: 'end', label: this.label(code) })), + ].filter(Boolean), + }, + { + title: this.t('glance-rules'), + items: [ + { role: 'step', label: this.lifecycle.dispatch === false ? this.t('glance-never-dispatched') : this.t('glance-dispatched') }, + { role: 'step', label: this.lifecycle.strict_transitions ? this.t('glance-strict') : this.t('glance-any') }, + ], + }, + ]; } - @action setNextActivities(code, selected) { - this.flow = { ...this.flow, [code]: { ...this.flow[code], activities: (selected ?? []).map((activity) => activity.code) } }; + // ----- saving + + get unsavedCount() { + return this.lines.filter((line) => line.unsaved).length; } - /** Drops the default dispatch activities so a lifecycle can be designed from nothing. */ - @action startBlankFlow() { - this.modalsManager.confirm({ - title: this.intl.t('order-config-manager.lifecycle.blank-flow-title'), - body: this.intl.t('order-config-manager.lifecycle.blank-flow-body'), - acceptButtonText: this.intl.t('order-config-manager.lifecycle.blank-flow-confirm'), - confirm: (modal) => { - this.flow = {}; - if (this.lifecycle) { - this.lifecycle = { ...this.lifecycle, initial: null, completed: null, canceled: null, terminal: [] }; - } - modal.done(); - }, - }); + get errorHint() { + if (!this.lifecycle) { + return null; + } + return !this.lifecycle.initial || this.missing.length ? this.t('save-blocked') : null; } normalize(lifecycle) { @@ -289,47 +339,17 @@ export default class OrderConfigManagerLifecycleComponent extends Component { }; } - @action toggleEnabled(enabled) { - if (enabled) { - const flow = normalizeOrderConfigFlow(this.config?.flow ?? {}); - this.lifecycle = this.saved ? { ...this.saved, terminal: [...this.saved.terminal] } : { ...DEFAULTS, terminal: [], initial: getOrderConfigFlowRootCode(flow) ?? null }; - return; - } + changeConfig(config) { + this.config = config; + this.saved = this.normalize(config?.meta?.lifecycle); + this.lifecycle = this.normalize(config?.meta?.lifecycle); + } - if (this.saved) { - this.modalsManager.confirm({ - title: this.intl.t('order-config-manager.lifecycle.remove-title'), - body: this.intl.t('order-config-manager.lifecycle.remove-body'), - acceptButtonText: this.intl.t('order-config-manager.lifecycle.remove-confirm'), - confirm: async (modal) => { - modal.startLoading(); - this.lifecycle = null; - await this.save.perform(); - modal.done(); - }, - decline: (modal) => { - modal.done(); - }, - }); + @task *save() { + if (this.errorHint) { return; } - this.lifecycle = null; - } - - @action setActivity(key, activity) { - this.lifecycle = { ...this.lifecycle, [key]: activity?.code ?? null }; - } - - @action setTerminal(activities) { - this.lifecycle = { ...this.lifecycle, terminal: (activities ?? []).map((activity) => activity.code) }; - } - - @action setFlag(key, value) { - this.lifecycle = { ...this.lifecycle, [key]: Boolean(value) }; - } - - @task *save() { const meta = { ...(this.config.meta ?? {}) }; if (this.lifecycle) { meta.lifecycle = { ...this.lifecycle }; @@ -339,19 +359,16 @@ export default class OrderConfigManagerLifecycleComponent extends Component { try { this.config.set('meta', meta); - this.config.set('flow', JSON.parse(this.serializeFlow())); yield this.config.save(); this.saved = this.normalize(this.lifecycle); this.lifecycle = this.normalize(this.lifecycle); - this.savedFlow = this.serializeFlow(); - this.notifications.success(this.intl.t('order-config-manager.lifecycle.saved', { orderConfigName: this.config.name })); + this.notifications.success(this.t('saved', { orderConfigName: this.config.name })); if (typeof this.args.onConfigUpdated === 'function') { this.args.onConfigUpdated(this.config); } } catch (error) { this.config.rollbackAttributes(); this.lifecycle = this.normalize(this.config.meta?.lifecycle); - this.flow = this.readFlow(this.config.flow); this.notifications.serverError(error); } } diff --git a/addon/components/order-config-manager/overview.hbs b/addon/components/order-config-manager/overview.hbs new file mode 100644 index 000000000..899780b12 --- /dev/null +++ b/addon/components/order-config-manager/overview.hbs @@ -0,0 +1,86 @@ +
+
+
+
+

{{t "order-config-manager.overview.title" config=this.config.name}}

+ {{t "order-config-manager.overview.readonly-hint"}} +
+ + {{#if this.before}} +
+ 0 +
+
+ {{t "order-config-manager.overview.before"}} + +
+ {{#each this.before as |rule|}} + {{rule}} + {{/each}} +
+
+ {{/if}} + +
    + {{#each this.steps as |step|}} +
  1. +
    + {{step.number}} + {{#unless step.isLast}}{{/unless}} +
    +
    +
    + + {{step.label}} + {{step.code}} + {{#if step.tag}}{{step.tag}}{{/if}} + + +
    +
    +
    + {{t "order-config-manager.overview.happens-here"}} + {{#each step.happens as |item|}} + {{item.text}} + {{else}} + {{t "order-config-manager.overview.nothing"}} + {{/each}} +
    +
    + {{t "order-config-manager.overview.policies-apply"}} + {{#each step.rules as |rule|}} + {{rule}} + {{else}} + {{t "order-config-manager.overview.none"}} + {{/each}} +
    +
    +
    +
  2. + {{/each}} +
+
+ + +
+
diff --git a/addon/components/order-config-manager/overview.js b/addon/components/order-config-manager/overview.js new file mode 100644 index 000000000..e3392e2a1 --- /dev/null +++ b/addon/components/order-config-manager/overview.js @@ -0,0 +1,179 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action, get } from '@ember/object'; +import { task } from 'ember-concurrency'; +import orderConfigSteps from '../../utils/order-config-steps'; +import { actionIcon, triggerSummary } from '../../utils/order-config-action-meta'; + +const O = 'order-config-manager.overview'; +const EVENT_KEYS = { + 'order.created': 'created', + 'order.completed': 'completed', + 'order.canceled': 'canceled', + 'dispatch.offer_exhausted': 'exhausted', + 'driver.approaching': 'approaching', +}; + +/** + * What happens to an order of this config, read-only: before it's placed, at each step, and at + * any time. Each part links to the tab where it's changed. + * + * @extends Component + */ +export default class OrderConfigManagerOverviewComponent extends Component { + @service fetch; + @service intl; + + @tracked config; + @tracked actions = []; + + constructor(owner, { config, configManagerContext }) { + super(...arguments); + this.config = config; + this.loadCapabilities.perform(); + + configManagerContext.on('onConfigChanged', (newConfig) => { + this.config = newConfig; + }); + } + + @task *loadCapabilities() { + try { + const { actions } = yield this.fetch.get('order-configs/capabilities'); + this.actions = actions ?? []; + } catch { + this.actions = []; + } + } + + @action go(tab) { + this.args.onSwitchTab?.(tab); + } + + t(key, values) { + return this.intl.t(`${O}.${key}`, values); + } + + policy(key, name) { + return get(this.config?.policies ?? {}, `${key}.${name}`); + } + + get lifecycle() { + return this.config?.meta?.lifecycle ?? null; + } + + get endCodes() { + const lifecycle = this.lifecycle ?? {}; + return new Set([lifecycle.completed, lifecycle.canceled, ...(lifecycle.terminal ?? [])].filter(Boolean)); + } + + get before() { + const items = []; + const methods = this.policy('customer.ordering', 'payment_methods') ?? []; + if (methods.length) { + items.push(this.t('rule-payment', { methods: methods.map((m) => this.methodLabel(m)).join(', ') })); + } + if (this.policy('customer.ordering', 'require_quote')) { + items.push(this.t('rule-quote')); + } + const settle = this.policy('customer.ordering', 'require_settlement') ?? []; + if (settle.length) { + items.push(this.t('rule-settlement', { methods: settle.map((m) => this.methodLabel(m)).join(', ') })); + } + const interactions = ['chat', 'rating', 'share_tracking'].filter((name) => this.policy('customer.interactions', name)); + if (interactions.length) { + items.push(this.t('rule-interactions', { list: interactions.map((name) => this.t(`interaction-${name}`)).join(', ') })); + } + return items; + } + + methodLabel(method) { + const key = `order-config-manager.policies.ordering.method.${method}`; + return this.intl.exists(key) ? this.intl.t(key) : method; + } + + get steps() { + const steps = orderConfigSteps(this.config); + const label = (code) => steps.find((step) => step.code === code)?.label ?? code; + const adhoc = this.policy('dispatch.adhoc', 'customer_orders'); + const cancelUntil = this.policy('customer.cancellation', 'allowed_until'); + const cancelOff = this.policy('customer.cancellation', 'enabled') === false; + const reprice = this.policy('pricing', 'reprice_on_completion'); + const meterFrom = this.policy('pricing', 'metering_starts_at'); + const rating = this.policy('customer.interactions', 'rating'); + const cancelIndex = cancelUntil ? steps.findIndex((step) => step.code === cancelUntil) : -1; + + return steps.map((step, index) => { + const isComplete = step.activity?.complete || this.lifecycle?.completed === step.code; + const ends = isComplete || this.endCodes.has(step.code); + const rules = []; + if (index === 0 && adhoc) { + rules.push(this.t('rule-offered')); + } + if (index === 0 && this.policy('dispatch.matching', 'vehicle_type')) { + rules.push(this.t('rule-vehicle')); + } + if (!cancelOff && cancelIndex >= 0 && !ends) { + rules.push(index < cancelIndex ? this.t('rule-can-cancel') : this.t('rule-cannot-cancel')); + } + if (reprice && meterFrom === step.code) { + rules.push(this.t('rule-metering')); + } + if (isComplete && reprice) { + rules.push(this.t('rule-repriced')); + } + if (isComplete && rating) { + rules.push(this.t('rule-rating')); + } + const happens = (step.activity?.actions ?? []).map((trigger) => ({ icon: actionIcon(trigger.action), text: triggerSummary(this.intl, trigger, this.actions) })); + + return { + ...step, + number: index + 1, + happens, + rules, + tag: isComplete ? this.t('tag-completes') : ends ? (step.branchFrom ? this.t('branch-from', { step: label(step.branchFrom) }) : this.t('tag-ends')) : null, + ends, + isLast: index === steps.length - 1, + }; + }); + } + + get anyTime() { + return (this.config?.triggers ?? []).map((trigger) => { + const event = EVENT_KEYS[trigger.event]; + const options = trigger.options ?? {}; + const when = event ? this.intl.t(`order-config-manager.events.${event}-menu`, {}) : trigger.event; + const detail = + trigger.event === 'driver.approaching' + ? this.intl.t('order-config-manager.events.approaching-short', { + metres: options.distance ?? 500, + target: this.intl.t(`order-config-manager.events.target-${options.target === 'dropoff' ? 'dropoff' : 'pickup'}`), + }) + : when; + return { when: detail, then: triggerSummary(this.intl, trigger, this.actions), hasCondition: (trigger.when ?? []).length > 0 }; + }); + } + + get glance() { + const steps = this.steps; + const automatic = steps.reduce((sum, step) => sum + step.happens.length, 0) + this.anyTime.length; + let changed = 0; + const walk = (node) => { + Object.values(node ?? {}).forEach((value) => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + walk(value); + } else { + changed += 1; + } + }); + }; + walk(this.config?.policies); + return [ + this.t('glance-steps', { count: steps.length, ends: steps.filter((step) => step.ends).length }), + this.t('glance-automatic', { count: automatic }), + this.t('glance-policies', { count: changed }), + ]; + } +} diff --git a/addon/components/order-config-manager/policies.hbs b/addon/components/order-config-manager/policies.hbs new file mode 100644 index 000000000..5356aed58 --- /dev/null +++ b/addon/components/order-config-manager/policies.hbs @@ -0,0 +1,84 @@ +
+
+ + +
+ {{#if this.readonly}} + + {{else if this.isSystemConfig}} + + {{/if}} + {{#if (and this.allDefaults this.policies.length)}} + + {{/if}} + + {{#if this.loadPolicies.isRunning}} +
+ {{/if}} + + {{#each this.groups as |group|}} +
+
+
+

{{group.title}}

+ {{#if group.isExtension}} + {{t "order-config-manager.policies.extension-badge"}} + {{/if}} +
+ {{group.description}} +
+
+ {{#each group.lines as |line|}} + + {{/each}} +
+
+ {{/each}} + + +
+
+
diff --git a/addon/components/order-config-manager/policies.js b/addon/components/order-config-manager/policies.js new file mode 100644 index 000000000..d52df1ccf --- /dev/null +++ b/addon/components/order-config-manager/policies.js @@ -0,0 +1,585 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action, get } from '@ember/object'; +import { task } from 'ember-concurrency'; +import humanize from '@fleetbase/ember-core/utils/humanize'; +import sentenceParts from '../../utils/sentence-parts'; + +const P = 'order-config-manager.policies'; +const PAYMENT_METHODS = ['cash', 'card', 'bank_transfer', 'wallet']; + +/** + * An order config's policies, written as plain sentences with the settings inline. Each built-in + * policy has its own sentences; a policy an extension registers reads "Label: [control]" for each + * of its settings. A setting left at its default isn't stored, and reads as the default. + * + * Policies and their settings come from `order-configs/capabilities`; the company's dispatch + * defaults (offer method, time, radius) come from Settings → Dispatch, so placeholders show what + * an empty setting falls back to. + * + * @extends Component + */ +export default class OrderConfigManagerPoliciesComponent extends Component { + @service fetch; + @service notifications; + @service abilities; + @service intl; + + /** The config being managed. */ + @tracked config; + + /** The registered policies, each with its settings. */ + @tracked policies = []; + + /** Working copy of the config's stored policies, keyed by policy key. */ + @tracked values = {}; + + /** The stored policies as last saved, keyed by policy key. */ + @tracked savedValues = {}; + + /** The company's adhoc dispatch defaults. */ + @tracked companyDefaults = { adhoc_strategy: 'sequential', adhoc_offer_timeout: 20, adhoc_distance: 6000 }; + + constructor(owner, { config, configManagerContext }) { + super(...arguments); + this.changeConfig(config); + this.loadPolicies.perform(); + this.loadCompanyDefaults.perform(); + + configManagerContext.on('onConfigChanged', (newConfig) => { + this.changeConfig(newConfig); + }); + } + + get canEdit() { + return this.abilities.can('fleet-ops update order-config'); + } + + get readonly() { + return !this.canEdit; + } + + get isSystemConfig() { + return Boolean(this.config?.core_service); + } + + get allDefaults() { + return Object.values(this.values).every((settings) => Object.keys(settings ?? {}).length === 0); + } + + get unsavedCount() { + return this.lines.filter((line) => line.unsaved).length; + } + + get errorCount() { + return this.lines.filter((line) => line.error).length; + } + + get errorHint() { + return this.errorCount ? this.intl.t(`${P}.save-hint-errors`, { count: this.errorCount }) : null; + } + + get lines() { + return this.groups.flatMap((group) => group.lines); + } + + /** The config's steps, for settings that name one. */ + get steps() { + return Object.values(this.config?.flow ?? {}) + .filter((activity) => activity && activity.code) + .map((activity) => ({ value: activity.code, label: activity.status || activity.code })); + } + + // ----- reading and writing values + + stored(policyKey, name) { + return this.values?.[policyKey]?.[name]; + } + + definition(policyKey) { + return this.policies.find((policy) => policy.key === policyKey); + } + + setting(policyKey, name) { + return (this.definition(policyKey)?.settings ?? []).find((setting) => setting.name === name); + } + + valueOf(policyKey, name) { + const stored = this.stored(policyKey, name); + return stored === undefined ? this.setting(policyKey, name)?.default : stored; + } + + isDefault(policyKey, name) { + return this.stored(policyKey, name) === undefined; + } + + isUnsaved(policyKey, name) { + return JSON.stringify(this.values?.[policyKey]?.[name]) !== JSON.stringify(this.savedValues?.[policyKey]?.[name]); + } + + @action setValue(policyKey, name, value) { + const policy = { ...(this.values[policyKey] ?? {}) }; + const setting = this.setting(policyKey, name); + const isEmptyList = Array.isArray(value) && value.length === 0; + // Choosing the default, or emptying a setting, stores nothing so it keeps following the default. + if (value === '' || value === undefined || value === null || isEmptyList || JSON.stringify(value) === JSON.stringify(setting?.default)) { + delete policy[name]; + } else { + policy[name] = value; + } + + this.values = { ...this.values, [policyKey]: policy }; + } + + @action reset(policyKey, names) { + const policy = { ...(this.values[policyKey] ?? {}) }; + names.forEach((name) => delete policy[name]); + this.values = { ...this.values, [policyKey]: policy }; + } + + @action discard() { + this.values = JSON.parse(JSON.stringify(this.savedValues)); + } + + // ----- building sentences + + t(key, values) { + return this.intl.t(`${P}.${key}`, values); + } + + /** A choice part for a setting, from `[value, label]` pairs. */ + choice(policyKey, name, pairs, ariaKey) { + const setting = this.setting(policyKey, name); + return { + kind: 'choice', + value: this.valueOf(policyKey, name), + isDefault: this.isDefault(policyKey, name), + ariaLabel: this.t(ariaKey), + options: pairs.map(([value, label]) => ({ value, label, isDefault: value === (setting?.default ?? null) })), + onChange: (value) => this.setValue(policyKey, name, value), + }; + } + + /** An on/off setting as a two-way choice. */ + toggle(policyKey, name, offLabel, onLabel, ariaKey) { + return this.choice( + policyKey, + name, + [ + [false, offLabel], + [true, onLabel], + ], + ariaKey + ); + } + + /** A number part with the range from the setting's rules. Returns `[part, error]`. */ + number(policyKey, name, defaultLabel, ariaKey, width) { + const setting = this.setting(policyKey, name) ?? {}; + const value = this.stored(policyKey, name); + const n = Number(value); + const invalid = value !== undefined && (Number.isNaN(n) || (setting.min !== undefined && n < setting.min) || (setting.max !== undefined && n > setting.max)); + const part = { + kind: 'number', + value: value ?? '', + defaultLabel, + invalid, + width, + ariaLabel: this.t(ariaKey), + onChange: (number) => this.setValue(policyKey, name, number), + }; + + return [part, invalid ? this.intl.t('order-config-manager.common.number-range-error', { min: setting.min, max: setting.max }) : null]; + } + + methodLabel(method) { + const key = `${P}.ordering.method.${method}`; + return this.intl.exists(key) ? this.intl.t(key) : humanize(method); + } + + list(policyKey, name, choices, emptyKey, ariaKey) { + const values = this.valueOf(policyKey, name) ?? []; + return { + kind: 'list', + items: values.map((value) => ({ value, label: this.methodLabel(value) })), + options: choices.map((value) => ({ value, label: this.methodLabel(value) })), + emptyLabel: this.intl.t('order-config-manager.common.default-suffix', { value: this.t(emptyKey) }), + ariaLabel: this.t(ariaKey), + onChange: (list) => this.setValue(policyKey, name, list), + }; + } + + /** A sentence line. `settings` are the `[policyKey, name]` pairs it shows. */ + line(policyKey, names, key, controls, { help, error, dim, values } = {}) { + return { + policyKey, + names, + parts: sentenceParts(this.intl, `${P}.${key}`, controls, values), + help, + error, + dim, + unsaved: names.some((name) => this.isUnsaved(policyKey, name)), + isSet: names.some((name) => !this.isDefault(policyKey, name)), + canReset: names.some((name) => !this.isDefault(policyKey, name)), + onReset: () => this.reset(policyKey, names), + }; + } + + strategyLabel(value) { + const key = `${P}.offering.strategy.${value}`; + if (this.intl.exists(key)) { + return this.intl.t(key); + } + return (this.setting('dispatch.adhoc', 'strategy')?.choices ?? []).find((choice) => choice.value === value)?.label ?? humanize(value ?? ''); + } + + stepLabel(code) { + return this.steps.find((step) => step.value === code)?.label ?? code; + } + + // ----- groups + + get groups() { + if (!this.policies.length) { + return []; + } + + const known = ['dispatch.adhoc', 'dispatch.matching', 'customer.ordering', 'customer.cancellation', 'customer.interactions', 'pricing']; + const groups = [this.offeringGroup(), this.driversGroup(), this.orderingGroup(), this.cancellingGroup(), this.interactionsGroup(), this.priceGroup()].filter(Boolean); + const extensions = this.policies.filter((policy) => !known.includes(policy.key)).map((policy) => this.extensionGroup(policy)); + + return [...groups, ...extensions].map((group) => { + const set = group.lines.filter((line) => line.isSet).length; + const unsaved = group.lines.filter((line) => line.unsaved).length; + return { + ...group, + anchor: `oc-policy-${group.id.replace(/[^a-z0-9]+/gi, '-')}`, + navCount: [set ? this.t('nav-set', { count: set }) : this.t('nav-defaults'), unsaved ? this.t('nav-unsaved', { count: unsaved }) : null].filter(Boolean).join(' · '), + hasUnsaved: unsaved > 0, + }; + }); + } + + offeringGroup() { + const K = 'dispatch.adhoc'; + if (!this.definition(K)) return null; + const company = this.companyDefaults; + const offering = this.valueOf(K, 'customer_orders') === true; + const strategy = this.valueOf(K, 'strategy') ?? company.adhoc_strategy; + const dimHelp = offering ? null : this.t('applies-when-offered'); + const strategyChoices = (this.setting(K, 'strategy')?.choices ?? []).map((choice) => [choice.value, this.strategyLabel(choice.value)]); + const strategyBase = this.choice(K, 'strategy', strategyChoices, 'offering.strategy-aria'); + // An empty strategy follows the company's, so that is the option marked as the default. + const strategyPart = { ...strategyBase, value: strategy, options: strategyBase.options.map((option) => ({ ...option, isDefault: option.value === company.adhoc_strategy })) }; + const [seconds, secondsError] = this.number(K, 'offer_timeout', String(company.adhoc_offer_timeout ?? 20), 'offering.seconds-aria', 132); + const [metres, metresError] = this.number(K, 'radius', Number(company.adhoc_distance ?? 6000).toLocaleString(), 'offering.radius-aria', 150); + const companyHelp = this.t('offering.strategy-help', { strategy: this.strategyLabel(company.adhoc_strategy), seconds: company.adhoc_offer_timeout ?? 20 }); + + return { + id: K, + nav: this.t('offering.nav'), + title: this.t('offering.title'), + description: this.t('offering.description'), + lines: [ + this.line( + K, + ['customer_orders'], + 'offering.customer-orders.sentence', + { choice: this.toggle(K, 'customer_orders', this.t('offering.customer-orders.wait'), this.t('offering.customer-orders.offer'), 'offering.customer-orders-aria') }, + { help: this.t('offering.customer-orders-help') } + ), + strategy === 'sequential' + ? this.line( + K, + ['strategy', 'offer_timeout'], + 'offering.strategy.sentence', + { strategy: strategyPart, seconds }, + { help: dimHelp ?? companyHelp, error: secondsError, dim: !offering } + ) + : this.line(K, ['strategy', 'offer_timeout'], 'offering.strategy-only', { strategy: strategyPart }, { help: dimHelp ?? companyHelp, dim: !offering }), + this.line( + K, + ['radius'], + 'offering.radius', + { metres }, + { help: dimHelp ?? this.t('offering.radius-help', { metres: Number(company.adhoc_distance ?? 6000).toLocaleString() }), error: metresError, dim: !offering } + ), + this.line( + K, + ['on_exhausted'], + 'offering.exhausted.sentence', + { + choice: this.choice( + K, + 'on_exhausted', + [ + ['keep_open', this.t('offering.exhausted.keep-open')], + ['cancel', this.t('offering.exhausted.cancel')], + ], + 'offering.exhausted-aria' + ), + }, + { help: dimHelp ?? this.t('offering.exhausted-help'), dim: !offering } + ), + ], + }; + } + + driversGroup() { + const K = 'dispatch.matching'; + if (!this.definition(K)) return null; + return { + id: K, + nav: this.t('drivers.nav'), + title: this.t('drivers.title'), + description: this.t('drivers.description'), + lines: [ + this.line( + K, + ['vehicle_type'], + 'drivers.vehicle.sentence', + { choice: this.toggle(K, 'vehicle_type', this.t('drivers.vehicle.any'), this.t('drivers.vehicle.match'), 'drivers.vehicle-aria') }, + { help: this.t('drivers.vehicle-help') } + ), + this.line( + K, + ['exclude_busy_drivers'], + 'drivers.busy.sentence', + { choice: this.toggle(K, 'exclude_busy_drivers', this.t('drivers.busy.offered'), this.t('drivers.busy.skipped'), 'drivers.busy-aria') }, + { help: this.t('drivers.busy-help') } + ), + ], + }; + } + + orderingGroup() { + const K = 'customer.ordering'; + if (!this.definition(K)) return null; + const chosen = this.valueOf(K, 'payment_methods') ?? []; + const allMethods = [...new Set([...PAYMENT_METHODS, ...chosen, ...(this.valueOf(K, 'require_settlement') ?? [])])]; + return { + id: K, + nav: this.t('ordering.nav'), + title: this.t('ordering.title'), + description: this.t('ordering.description'), + lines: [ + this.line( + K, + ['payment_methods'], + 'ordering.payment', + { methods: this.list(K, 'payment_methods', allMethods, 'ordering.payment-empty', 'ordering.payment-aria') }, + { help: this.t('ordering.payment-help') } + ), + this.line( + K, + ['require_quote'], + 'ordering.quote.sentence', + { choice: this.toggle(K, 'require_quote', this.t('ordering.quote.optional'), this.t('ordering.quote.required'), 'ordering.quote-aria') }, + { help: this.t('ordering.quote-help') } + ), + this.line( + K, + ['require_settlement'], + 'ordering.settlement', + { methods: this.list(K, 'require_settlement', chosen.length ? chosen : allMethods, 'ordering.settlement-empty', 'ordering.settlement-aria') }, + { help: this.t('ordering.settlement-help') } + ), + ], + }; + } + + cancellingGroup() { + const K = 'customer.cancellation'; + if (!this.definition(K)) return null; + const enabled = this.valueOf(K, 'enabled') !== false; + const can = this.choice( + K, + 'enabled', + [ + [true, this.t('cancelling.can')], + [false, this.t('cancelling.cannot')], + ], + 'cancelling.enabled-aria' + ); + const until = this.choice( + K, + 'allowed_until', + [[null, this.t('cancelling.finishes')], ...this.steps.map((step) => [step.value, this.t('cancelling.reaches', { step: step.label })])], + 'cancelling.until-aria' + ); + return { + id: K, + nav: this.t('cancelling.nav'), + title: this.t('cancelling.title'), + description: this.t('cancelling.description'), + lines: [ + enabled + ? this.line(K, ['enabled', 'allowed_until'], 'cancelling.until', { choice: can, step: until }, { help: this.t('cancelling-help') }) + : this.line(K, ['enabled', 'allowed_until'], 'cancelling.off', { choice: can }), + ], + }; + } + + interactionsGroup() { + const K = 'customer.interactions'; + if (!this.definition(K)) return null; + return { + id: K, + nav: this.t('interactions.nav'), + title: this.t('interactions.title'), + description: this.t('interactions.description'), + lines: [ + this.line( + K, + ['chat', 'rating', 'share_tracking'], + 'interactions.sentence', + { + message: this.toggle(K, 'chat', this.t('interactions.message.off'), this.t('interactions.message.on'), 'interactions.message-aria'), + rate: this.toggle(K, 'rating', this.t('interactions.rate.off'), this.t('interactions.rate.on'), 'interactions.rate-aria'), + share: this.toggle(K, 'share_tracking', this.t('interactions.share.off'), this.t('interactions.share.on'), 'interactions.share-aria'), + }, + { help: this.t('interactions-help') } + ), + ], + }; + } + + priceGroup() { + const K = 'pricing'; + if (!this.definition(K)) return null; + const reprice = this.valueOf(K, 'reprice_on_completion') === true; + const choice = this.toggle(K, 'reprice_on_completion', this.t('price.stands'), this.t('price.recalculate'), 'price.reprice-aria'); + const from = this.choice(K, 'metering_starts_at', [[null, this.t('price.from-start')], ...this.steps.map((step) => [step.value, step.label])], 'price.from-aria'); + return { + id: K, + nav: this.t('price.nav'), + title: this.t('price.title'), + description: this.t('price.description'), + lines: [ + reprice + ? this.line(K, ['reprice_on_completion', 'metering_starts_at'], 'price.reprice', { choice, step: from }, { help: this.t('price-help') }) + : this.line(K, ['reprice_on_completion', 'metering_starts_at'], 'price.no-reprice', { choice }, { help: this.t('price-help') }), + ], + }; + } + + /** A policy an extension registered: "Label: [control]" for each setting. */ + extensionGroup(policy) { + const K = policy.key; + const lines = (policy.settings ?? []).map((setting) => { + const label = humanize(setting.name); + let control; + let error = null; + if (setting.type === 'boolean') { + control = this.toggle(K, setting.name, this.t('extension-off'), this.t('extension-on'), 'extension-aria'); + } else if (setting.type === 'choice' && Array.isArray(setting.choices)) { + control = this.choice(K, setting.name, [[null, this.t('extension-none')], ...setting.choices.map((choice) => [choice.value, choice.label])], 'extension-aria'); + } else if (setting.type === 'choice' && setting.choices === 'activity') { + control = this.choice(K, setting.name, [[null, this.t('extension-none')], ...this.steps.map((step) => [step.value, step.label])], 'extension-aria'); + } else if (setting.type === 'list') { + const values = this.valueOf(K, setting.name) ?? []; + control = { + kind: 'list', + items: values.map((value) => ({ value, label: String(value) })), + options: [], + emptyLabel: this.t('extension-none'), + ariaLabel: label, + disabled: true, + }; + } else { + [control, error] = this.number(K, setting.name, setting.default === null || setting.default === undefined ? '' : String(setting.default), 'extension-aria', 150); + } + control.ariaLabel = label; + + return this.line(K, [setting.name], 'extension-fallback', { control }, { values: { label }, error }); + }); + + return { id: K, nav: policy.label, title: policy.label, description: policy.description, isExtension: true, lines }; + } + + // ----- loading and saving + + @task *loadPolicies() { + try { + const { policies } = yield this.fetch.get('order-configs/capabilities'); + this.policies = policies ?? []; + this.changeConfig(this.config); + } catch (error) { + this.policies = []; + this.notifications.serverError(error); + } + } + + @task *loadCompanyDefaults() { + try { + const settings = yield this.fetch.get('fleet-ops/settings/adhoc-dispatch-settings'); + this.companyDefaults = { ...this.companyDefaults, ...settings }; + } catch { + // The built-in defaults stand in. + } + } + + @task *save() { + if (this.errorCount) { + return; + } + + this.config.policies = this.merge(this.config.policies, this.values); + + try { + yield this.config.save(); + this.savedValues = JSON.parse(JSON.stringify(this.values)); + this.notifications.success(this.t('saved')); + if (typeof this.args.onConfigUpdated === 'function') { + this.args.onConfigUpdated(this.config); + } + } catch (error) { + this.notifications.serverError(error); + } + } + + /** + * The stored policies with the edited ones written in, nested by key as the server keeps them + * (`dispatch.adhoc` under `dispatch`). Policies this console doesn't know are kept as they are. + */ + merge(stored, values) { + const nested = JSON.parse(JSON.stringify(stored ?? {})); + for (const policy of this.policies) { + const path = policy.key.split('.'); + let node = nested; + path.slice(0, -1).forEach((segment) => { + node[segment] = node[segment] && typeof node[segment] === 'object' ? node[segment] : {}; + node = node[segment]; + }); + + const settings = values[policy.key] ?? {}; + if (Object.keys(settings).length) { + node[path[path.length - 1]] = settings; + } else { + delete node[path[path.length - 1]]; + } + } + + return nested; + } + + /** The stored settings of each known policy, keyed by policy key, for editing. */ + flatten(stored) { + const flat = {}; + for (const policy of this.policies) { + const settings = get(stored ?? {}, policy.key); + if (settings && typeof settings === 'object' && !Array.isArray(settings)) { + flat[policy.key] = { ...settings }; + } + } + + return flat; + } + + changeConfig(config) { + this.config = config; + this.values = this.flatten(config?.policies ?? {}); + this.savedValues = JSON.parse(JSON.stringify(this.values)); + } +} diff --git a/addon/components/order-config/inline-list.hbs b/addon/components/order-config/inline-list.hbs new file mode 100644 index 000000000..6d071ae2c --- /dev/null +++ b/addon/components/order-config/inline-list.hbs @@ -0,0 +1,25 @@ + + {{#each @items as |item|}} + + {{item.label}} + {{#unless @disabled}} + + {{/unless}} + + {{else}} + {{@emptyLabel}} + {{/each}} + {{#if this.canAdd}} + + {{/if}} + diff --git a/addon/components/order-config/inline-list.js b/addon/components/order-config/inline-list.js new file mode 100644 index 000000000..30d21bd09 --- /dev/null +++ b/addon/components/order-config/inline-list.js @@ -0,0 +1,33 @@ +import Component from '@glimmer/component'; +import { action } from '@ember/object'; + +/** + * A list of values inside a sentence, such as payment methods: removable chips and an Add menu. + * + * @argument {Array<{value, label}>} items the chosen values + * @argument {Array<{value, label}>} options every value that can be chosen + * @argument {String} emptyLabel shown when nothing is chosen + * @argument {Function} onChange called with the new array of values + */ +export default class OrderConfigInlineListComponent extends Component { + get addable() { + const chosen = (this.args.items ?? []).map((item) => item.value); + return (this.args.options ?? []).filter((option) => !chosen.includes(option.value)); + } + + get canAdd() { + return !this.args.disabled && this.addable.length > 0; + } + + get values() { + return (this.args.items ?? []).map((item) => item.value); + } + + @action add(value) { + this.args.onChange?.([...this.values, value]); + } + + @action remove(item) { + this.args.onChange?.(this.values.filter((value) => value !== item.value)); + } +} diff --git a/addon/components/order-config/inline-number.hbs b/addon/components/order-config/inline-number.hbs new file mode 100644 index 000000000..360f68a53 --- /dev/null +++ b/addon/components/order-config/inline-number.hbs @@ -0,0 +1,12 @@ + diff --git a/addon/components/order-config/inline-number.js b/addon/components/order-config/inline-number.js new file mode 100644 index 000000000..476804899 --- /dev/null +++ b/addon/components/order-config/inline-number.js @@ -0,0 +1,36 @@ +import Component from '@glimmer/component'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; +import { htmlSafe } from '@ember/template'; + +/** + * A number inside a sentence. Left empty it follows the default, which the placeholder shows. + * + * @argument {Number|String} value + * @argument {String} defaultLabel the default, shown as the placeholder ("20 · default") + * @argument {Function} onChange called with the number, or undefined when emptied + * @argument {Boolean} invalid + * @argument {Number} width in pixels + */ +export default class OrderConfigInlineNumberComponent extends Component { + @service intl; + + get isEmpty() { + return this.args.value === undefined || this.args.value === null || this.args.value === ''; + } + + get placeholder() { + return this.args.defaultLabel ? this.intl.t('order-config-manager.common.default-suffix', { value: this.args.defaultLabel }) : ''; + } + + get style() { + return htmlSafe(`width: ${this.args.width ?? 132}px`); + } + + @action change(event) { + const raw = String(event.target.value ?? '').replace(/[^0-9.-]/g, ''); + if (typeof this.args.onChange === 'function') { + this.args.onChange(raw === '' ? undefined : Number(raw), raw); + } + } +} diff --git a/addon/components/order-config/inline-select.hbs b/addon/components/order-config/inline-select.hbs new file mode 100644 index 000000000..7f5e22a10 --- /dev/null +++ b/addon/components/order-config/inline-select.hbs @@ -0,0 +1,46 @@ +{{#if @disabled}} + {{this.displayLabel}} +{{else}} + + + {{this.displayLabel}} + {{#unless @hideCaret}} + + {{/unless}} + + +
    + {{#each @options as |option|}} +
  • + + {{option.label}} + {{#if option.description}} + {{option.description}} + {{/if}} + + + {{#if option.isDefault}} + {{t "order-config-manager.common.default"}} + {{/if}} + {{#if (eq option.value @value)}} + + {{/if}} + +
  • + {{/each}} +
+
+
+{{/if}} diff --git a/addon/components/order-config/inline-select.js b/addon/components/order-config/inline-select.js new file mode 100644 index 000000000..eb2545f91 --- /dev/null +++ b/addon/components/order-config/inline-select.js @@ -0,0 +1,37 @@ +import Component from '@glimmer/component'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; + +/** + * A choice inside a sentence: the chosen option's words, styled as following the default + * (dashed, "· default") or set for this config (solid). Opens a list of the options. + * + * @argument {Array<{value, label, description?, isDefault?}>} options + * @argument {*} value the chosen option's value + * @argument {Boolean} isDefault the value is the default, so it reads as one + * @argument {Function} onSelect called with the chosen option's value + * @argument {Boolean} disabled render as read-only text + * @argument {String} label words to show instead of the chosen option's label + */ +export default class OrderConfigInlineSelectComponent extends Component { + @service intl; + + get displayLabel() { + const label = this.args.label ?? this.args.options?.find((option) => option.value === this.args.value)?.label ?? ''; + return this.args.isDefault && !this.args.hideDefaultSuffix ? this.intl.t('order-config-manager.common.default-suffix', { value: label }) : label; + } + + @action select(dropdown, option) { + dropdown.actions.close(); + if (typeof this.args.onSelect === 'function') { + this.args.onSelect(option.value, option); + } + } + + @action selectOnKey(dropdown, option, event) { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + this.select(dropdown, option); + } + } +} diff --git a/addon/components/order-config/notice.hbs b/addon/components/order-config/notice.hbs new file mode 100644 index 000000000..1a3bd9734 --- /dev/null +++ b/addon/components/order-config/notice.hbs @@ -0,0 +1,6 @@ +
+ + + {{#if @title}}{{@title}} {{/if}}{{@text}}{{yield}} + +
diff --git a/addon/components/order-config/order-events.hbs b/addon/components/order-config/order-events.hbs new file mode 100644 index 000000000..f2ebcf07f --- /dev/null +++ b/addon/components/order-config/order-events.hbs @@ -0,0 +1,75 @@ +
+

{{t "order-config-manager.events.intro"}}

+ + {{#each this.cards as |card|}} +
+
+
+ + {{#each card.parts as |part|}} + {{#if (eq part.kind "text")}} + {{part.text}} + {{else if (eq part.kind "number")}} + + {{else if (eq part.kind "choice")}} + + {{/if}} + {{/each}} +
+ {{#unless this.readonly}} +
+ {{#if card.help}}{{card.help}}{{/if}} + +
+ {{else}} +
{{t "order-config-manager.events.empty"}}
+ {{/each}} + + {{#unless this.readonly}} + + {{/unless}} + + {{#if this.isDirty}} +
+ {{t "order-config-manager.common.unsaved-changes"}} + +
+ {{/if}} +
diff --git a/addon/components/order-config/order-events.js b/addon/components/order-config/order-events.js new file mode 100644 index 000000000..1332cc5da --- /dev/null +++ b/addon/components/order-config/order-events.js @@ -0,0 +1,187 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; +import { task } from 'ember-concurrency'; +import sentenceParts from '../../utils/sentence-parts'; + +const E = 'order-config-manager.events'; +const EVENT_KEYS = { + 'order.created': 'created', + 'order.completed': 'completed', + 'order.canceled': 'canceled', + 'dispatch.offer_exhausted': 'exhausted', + 'driver.approaching': 'approaching', +}; +const APPROACHING_DISTANCE = 500; + +/** + * An order config's order events: what happens when something happens to an order outside its + * steps, such as being canceled or the driver approaching. Opened from the Activity Flow canvas. + * + * Stored triggers (`config.triggers`, each `{ event, options, action, params, when }`) are shown + * grouped by event and options, each group listing its actions; saving writes them back flat. + */ +export default class OrderConfigOrderEventsComponent extends Component { + @service abilities; + @service notifications; + @service intl; + + @tracked groups = []; + @tracked saved = '[]'; + + constructor() { + super(...arguments); + this.groups = this.read(this.config?.triggers ?? []); + this.saved = JSON.stringify(this.serialize(this.groups)); + } + + get config() { + return this.args.overlay?.config ?? this.args.resource; + } + + get readonly() { + return this.abilities.cannot('fleet-ops update order-config'); + } + + get isDirty() { + return JSON.stringify(this.serialize(this.groups)) !== this.saved; + } + + get eventMenu() { + const events = this.args.overlay?.events?.length ? this.args.overlay.events : Object.keys(EVENT_KEYS); + return events.map((event) => { + const key = EVENT_KEYS[event]; + return { + value: event, + label: key ? this.intl.t(`${E}.${key}-menu`) : event, + description: key ? this.intl.t(`${E}.${key}-description`) : '', + }; + }); + } + + get cards() { + return this.groups.map((group, index) => { + const key = EVENT_KEYS[group.event]; + let parts; + let help = null; + if (group.event === 'driver.approaching') { + const distance = group.options?.distance; + const target = group.options?.target === 'dropoff' ? 'dropoff' : 'pickup'; + parts = sentenceParts(this.intl, `${E}.approaching`, { + metres: { + kind: 'number', + value: distance ?? '', + defaultLabel: String(APPROACHING_DISTANCE), + width: 128, + ariaLabel: this.intl.t(`${E}.distance-aria`), + invalid: distance !== undefined && (Number.isNaN(Number(distance)) || Number(distance) < 50), + onChange: (value) => this.setOption(index, 'distance', value), + }, + target: { + kind: 'choice', + value: target, + isDefault: false, + ariaLabel: this.intl.t(`${E}.target-aria`), + options: [ + { value: 'pickup', label: this.intl.t(`${E}.target-pickup`), isDefault: true }, + { value: 'dropoff', label: this.intl.t(`${E}.target-dropoff`) }, + ], + onChange: (value) => this.setOption(index, 'target', value), + }, + }); + help = this.intl.t(target === 'dropoff' ? `${E}.approaching-help-dropoff` : `${E}.approaching-help`); + } else { + parts = [{ kind: 'text', text: this.intl.t(`${E}.when`, { event: key ? this.intl.t(`${E}.${key}`) : group.event }) }]; + } + + return { index, group, parts, help, isNew: group.isNew }; + }); + } + + // ----- editing + + @action addEvent(event) { + const options = event === 'driver.approaching' ? { target: 'pickup' } : {}; + this.groups = [...this.groups, { id: this.nextId(), event, options, triggers: [], isNew: true }]; + } + + @action removeGroup(index) { + this.groups = this.groups.filter((_, i) => i !== index); + } + + @action setTriggers(index, triggers) { + this.groups = this.groups.map((group, i) => (i === index ? { ...group, triggers } : group)); + } + + setOption(index, name, value) { + this.groups = this.groups.map((group, i) => { + if (i !== index) return group; + const options = { ...(group.options ?? {}) }; + if (value === undefined || value === null || value === '') { + delete options[name]; + } else { + options[name] = value; + } + return { ...group, options }; + }); + } + + @action discard() { + this.groups = this.read(JSON.parse(this.saved)); + } + + @task *save() { + this.config.triggers = this.serialize(this.groups); + try { + yield this.config.save(); + this.saved = JSON.stringify(this.config.triggers); + this.groups = this.read(this.config.triggers); + this.notifications.success(this.intl.t(`${E}.saved`)); + this.args.overlay?.onSaved?.(this.config); + } catch (error) { + this.notifications.serverError(error); + } + } + + // ----- reading and writing + + read(triggers) { + const groups = []; + (triggers ?? []).forEach((trigger) => { + const options = trigger.event === 'driver.approaching' ? { ...(trigger.options ?? {}) } : {}; + const key = JSON.stringify([trigger.event, options]); + let group = groups.find((candidate) => candidate.key === key); + if (!group) { + group = { id: this.nextId(), key, event: trigger.event, options, triggers: [] }; + groups.push(group); + } + const item = { action: trigger.action }; + if (trigger.params) item.params = { ...trigger.params }; + if (trigger.when?.length) item.when = trigger.when; + group.triggers.push(item); + }); + return groups; + } + + serialize(groups) { + return groups.flatMap((group) => + (group.triggers ?? []) + .filter((trigger) => trigger.action) + .map((trigger) => { + const row = { event: group.event }; + const options = Object.fromEntries(Object.entries(group.options ?? {}).filter(([, value]) => value !== undefined && value !== null && value !== '')); + if (group.event === 'driver.approaching' && Object.keys(options).length) row.options = options; + if (trigger.when?.length) row.when = trigger.when; + row.action = trigger.action; + if (trigger.params && Object.keys(trigger.params).length) row.params = trigger.params; + return row; + }) + ); + } + + nextId() { + this._id = (this._id ?? 0) + 1; + return this._id; + } +} diff --git a/addon/components/order-config/sentence-field.hbs b/addon/components/order-config/sentence-field.hbs new file mode 100644 index 000000000..cfb3a33c7 --- /dev/null +++ b/addon/components/order-config/sentence-field.hbs @@ -0,0 +1,55 @@ +
+
+
+ {{#each @parts as |part|}} + {{#if (eq part.kind "text")}} + {{part.text}} + {{else if (eq part.kind "choice")}} + + {{else if (eq part.kind "number")}} + + {{else if (eq part.kind "list")}} + + {{/if}} + {{/each}} +
+
+ {{#if @unsaved}} + {{t "order-config-manager.common.unsaved"}} + {{/if}} + {{#if (and @canReset (not @readonly))}} + + {{/if}} +
+
+ {{#if @help}} + {{@help}} + {{/if}} + {{#if @error}} + {{@error}} + {{/if}} +
diff --git a/addon/components/order-config/trigger-list.hbs b/addon/components/order-config/trigger-list.hbs new file mode 100644 index 000000000..d0534d25f --- /dev/null +++ b/addon/components/order-config/trigger-list.hbs @@ -0,0 +1,123 @@ +
+ {{#each this.cards as |card|}} + {{#if card.isEditing}} +
+
+ {{t "order-config-manager.step.then"}} + + {{#if card.isNew}}{{t "order-config-manager.step.new"}}{{/if}} +
+ {{#if this.missingAction}} + {{t "order-config-manager.step.no-action-error"}} + {{/if}} + + {{#if this.draftIsNotify}} + + + + + + +
+ {{t "order-config-manager.step.insert"}} + {{#each this.placeholders as |token|}} + + {{/each}} +
+
+ {{t "order-config-manager.step.preview"}} + + + + {{this.previewTitle}} + {{this.previewMessage}} + + +
+ {{/if}} + + {{#each this.draftParameters as |parameter|}} + + + + {{/each}} + + + +
+
+
+ {{else}} +
+ +
+ {{card.label}}{{#if card.title}} “{{card.title}}”{{/if}} + {{#if card.message}}{{card.message}}{{/if}} + {{card.meta}} +
+ {{#unless @readonly}} +
+ {{#if card.isChanged}}{{t "order-config-manager.step.edited"}}{{/if}} +
+ {{/unless}} +
+ {{/if}} + {{/each}} + + {{#each this.removed as |entry|}} +
+ {{entry.label}} · {{t "order-config-manager.step.removed-note"}} + +
+ {{/each}} + + {{#unless this.triggers.length}} + {{#unless this.removed.length}} +
{{or @emptyText (t "order-config-manager.step.empty")}}
+ {{/unless}} + {{/unless}} + + {{#unless @readonly}} + {{#unless this.draft}} + + {{#unless @hideQuickAdd}} +
+ {{t "order-config-manager.step.quick-add"}} + {{#each this.quickAdd as |quick|}} + + {{/each}} +
+ {{/unless}} + {{/unless}} + {{/unless}} +
diff --git a/addon/components/order-config/trigger-list.js b/addon/components/order-config/trigger-list.js new file mode 100644 index 000000000..87cfc69c7 --- /dev/null +++ b/addon/components/order-config/trigger-list.js @@ -0,0 +1,205 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; +import { actionIcon, actionLabel, actionDescription } from '../../utils/order-config-action-meta'; + +const S = 'order-config-manager.step'; +const NOTIFY = ['notify_customer', 'notify_driver']; +const SAMPLE = { + 'driver.first_name': 'Sam', + 'driver.name': 'Sam Lee', + 'customer.name': 'Alex Kim', + 'order.id': 'order_7f3k2', + 'order.tracking_number': 'FLB102938', + 'order.status': 'started', +}; + +/** + * The things that happen at one point of an order, as cards: "Notify the customer 'Your driver + * has arrived'". Edit opens the card in place: what happens, its settings (title and message + * with placeholder chips and a preview for notifications), and "Only if" conditions. A removed + * card can be undone until the list is saved. + * + * Triggers are `{ action, params, when }`; the list hands the whole new array to `onChange`. + * + * @argument {Array} triggers + * @argument {Function} onChange + * @argument {Array} actions the actions from `order-configs/capabilities` + * @argument {Array} placeholders the message placeholders from capabilities + * @argument {String} stepStatus the step's status, used when a notification has no title + * @argument {String} stepDetails the step's details, used when it has no message + * @argument {Boolean} readonly + */ +export default class OrderConfigTriggerListComponent extends Component { + @service intl; + + @tracked editing = null; + @tracked draft = null; + @tracked missingAction = false; + @tracked removed = []; + @tracked changedIndexes = []; + messageElement; + + get triggers() { + return this.args.triggers ?? []; + } + + get actionOptions() { + return (this.args.actions ?? []).map((described) => ({ + value: described.name, + label: actionLabel(this.intl, described.name, this.args.actions), + description: actionDescription(this.intl, described.name, this.args.actions), + })); + } + + get quickAdd() { + const names = (this.args.actions ?? []).map((described) => described.name); + return ['notify_customer', 'notify_driver', 'open_chat', 'close_chat', 'send_invoice'] + .filter((name) => names.includes(name)) + .map((name) => ({ name, label: this.intl.t(`${S}.quick.${name}`, { default: actionLabel(this.intl, name, this.args.actions) }) })); + } + + get cards() { + return this.triggers.map((trigger, index) => { + const isNotify = NOTIFY.includes(trigger.action); + const conditions = (trigger.when ?? []).reduce((count, block) => count + (block?.conditions?.length ?? 0), 0); + return { + index, + trigger, + icon: actionIcon(trigger.action), + label: actionLabel(this.intl, trigger.action, this.args.actions), + title: isNotify ? trigger.params?.title || this.args.stepStatus : null, + message: isNotify ? trigger.params?.message || this.intl.t(`${S}.message-fallback`) : null, + meta: [isNotify ? this.intl.t(`${S}.push-notification`) : null, conditions ? this.intl.t(`${S}.only-if-count`, { count: conditions }) : this.intl.t(`${S}.every-time`)] + .filter(Boolean) + .join(' · '), + isEditing: this.editing === index, + isNew: this.editing === index && this.draft?.isNew, + isChanged: this.changedIndexes.includes(index), + }; + }); + } + + get draftIsNotify() { + return NOTIFY.includes(this.draft?.action); + } + + /** The draft action's parameters other than a notification's title and message. */ + get draftParameters() { + const described = (this.args.actions ?? []).find((item) => item.name === this.draft?.action); + if (!described || this.draftIsNotify) { + return []; + } + return Object.entries(described.parameters ?? {}).map(([name, description]) => ({ name, description, value: this.draft.params?.[name] ?? '' })); + } + + get titlePlaceholder() { + return this.intl.t(`${S}.title-placeholder`, { status: this.args.stepStatus || this.intl.t(`${S}.title-placeholder-event`) }); + } + + get placeholders() { + return (this.args.placeholders ?? Object.keys(SAMPLE)).filter((token) => !token.startsWith('activity.') || this.args.stepStatus).map((token) => `{${token}}`); + } + + fill(text) { + return String(text ?? '').replace(/\{\s*([a-z_]+(?:\.[a-z_]+)*)\s*\}/gi, (match, token) => { + const key = token.toLowerCase(); + if (key === 'activity.status') return this.args.stepStatus ?? ''; + if (key === 'activity.details') return this.args.stepDetails ?? ''; + return SAMPLE[key] ?? ''; + }); + } + + get previewTitle() { + return this.fill(this.draft?.params?.title || this.args.stepStatus || ''); + } + + get previewMessage() { + return this.fill(this.draft?.params?.message || this.args.stepDetails || ''); + } + + // ----- editing + + @action edit(index) { + const trigger = this.triggers[index]; + this.editing = index; + this.missingAction = false; + this.draft = { action: trigger.action, params: { ...(trigger.params ?? {}) }, when: JSON.parse(JSON.stringify(trigger.when ?? [])), isNew: false }; + } + + @action add(name = null) { + const list = [...this.triggers, { action: name, params: {}, when: [] }]; + this.args.onChange?.(list); + this.editing = list.length - 1; + this.missingAction = false; + this.draft = { action: name, params: {}, when: [], isNew: true }; + } + + @action setDraftAction(name) { + this.draft = { ...this.draft, action: name }; + this.missingAction = false; + } + + @action setParam(name, event) { + this.draft = { ...this.draft, params: { ...this.draft.params, [name]: event.target.value } }; + } + + @action setWhen(logic) { + this.draft = { ...this.draft, when: logic ?? [] }; + } + + @action registerMessage(element) { + this.messageElement = element; + } + + @action insertToken(token) { + const current = this.draft.params?.message ?? ''; + const element = this.messageElement; + const start = element && typeof element.selectionStart === 'number' ? element.selectionStart : current.length; + const end = element && typeof element.selectionEnd === 'number' ? element.selectionEnd : current.length; + const needsSpace = start > 0 && !/\s$/.test(current.slice(0, start)); + const message = current.slice(0, start) + (needsSpace ? ' ' : '') + token + current.slice(end); + this.draft = { ...this.draft, params: { ...this.draft.params, message } }; + } + + @action cancel() { + if (this.draft?.isNew) { + this.args.onChange?.(this.triggers.filter((_, index) => index !== this.editing)); + } + this.editing = null; + this.draft = null; + this.missingAction = false; + } + + @action done() { + if (!this.draft?.action) { + this.missingAction = true; + return; + } + + const params = Object.fromEntries(Object.entries(this.draft.params ?? {}).filter(([, value]) => value !== '' && value !== undefined && value !== null)); + const trigger = { action: this.draft.action }; + if (Object.keys(params).length) trigger.params = params; + if ((this.draft.when ?? []).length) trigger.when = this.draft.when; + + const index = this.editing; + this.args.onChange?.(this.triggers.map((existing, i) => (i === index ? { ...existing, ...trigger, params: trigger.params, when: trigger.when } : existing))); + this.changedIndexes = [...new Set([...this.changedIndexes, index])]; + this.editing = null; + this.draft = null; + } + + @action remove(index) { + const trigger = this.triggers[index]; + this.removed = [...this.removed, { trigger, index, label: actionLabel(this.intl, trigger.action, this.args.actions) }]; + this.args.onChange?.(this.triggers.filter((_, i) => i !== index)); + } + + @action undo(entry) { + const list = [...this.triggers]; + list.splice(Math.min(entry.index, list.length), 0, entry.trigger); + this.removed = this.removed.filter((item) => item !== entry); + this.args.onChange?.(list); + } +} diff --git a/addon/components/order-config/unsaved-bar.hbs b/addon/components/order-config/unsaved-bar.hbs new file mode 100644 index 000000000..72fbe950d --- /dev/null +++ b/addon/components/order-config/unsaved-bar.hbs @@ -0,0 +1,20 @@ +{{#if @count}} +
+ + {{t "order-config-manager.common.unsaved-count" count=@count}} + {{or @errorHint @hint}} + + +
+{{/if}} diff --git a/addon/components/order/form/details.hbs b/addon/components/order/form/details.hbs index fec97dabe..a41325b0b 100644 --- a/addon/components/order/form/details.hbs +++ b/addon/components/order/form/details.hbs @@ -171,6 +171,25 @@ @wrapperClass="mb-0" @helpText={{t "order.fields.adhoc-ping-help-text"}} /> + + + +
+ {{#if this.usesOfferTimeout}} + +
+ + {{t "settings.dispatch.seconds"}} +
+ {{#if this.timeoutInvalid}} + {{t "settings.dispatch.offer-timeout-error"}} + {{/if}} +
+ {{/if}} + +
+ + {{t "settings.dispatch.metres"}} +
+
+
+ + {{#if this.adhocConfigs.length}} + + {{#each this.adhocConfigs as |config|}} +
+ + {{config.name}} + + {{if config.own (t "settings.dispatch.sets-own" settings=config.ownSettings) (t "settings.dispatch.uses-defaults")}} + + +
+ {{/each}} +
+ {{/if}} +
+
+ diff --git a/addon/utils/order-config-action-meta.js b/addon/utils/order-config-action-meta.js new file mode 100644 index 000000000..0384c16d3 --- /dev/null +++ b/addon/utils/order-config-action-meta.js @@ -0,0 +1,52 @@ +import humanize from '@fleetbase/ember-core/utils/humanize'; + +/** The icon each known action shows on the flow and in lists; extension actions get a bolt. */ +export const ACTION_ICONS = { + notify_customer: 'bell', + notify_driver: 'bell', + open_chat: 'comments', + close_chat: 'comment-slash', + send_invoice: 'file-invoice', + set_meta: 'tag', + cancel: 'ban', +}; + +/** What the legend calls each icon. */ +export const ICON_GROUPS = [ + { icon: 'bell', key: 'legend-notification', actions: ['notify_customer', 'notify_driver'] }, + { icon: 'comments', key: 'legend-chat', actions: ['open_chat', 'close_chat'] }, + { icon: 'file-invoice', key: 'legend-invoice', actions: ['send_invoice'] }, +]; + +export function actionIcon(name) { + return ACTION_ICONS[name] ?? 'bolt'; +} + +/** + * An action's label: the console's translation when there is one, else the label the server + * describes (an extension's own), else the name made readable. + */ +export function actionLabel(intl, name, described = []) { + for (const key of [`order-config-manager.actions.${name}`, `ledger.order-config-actions.${name}`]) { + if (intl.exists(key)) { + return intl.t(key); + } + } + return described.find((action) => action.name === name)?.label ?? humanize(name ?? ''); +} + +export function actionDescription(intl, name, described = []) { + for (const key of [`order-config-manager.actions.${name}-description`, `ledger.order-config-actions.${name}-description`]) { + if (intl.exists(key)) { + return intl.t(key); + } + } + return described.find((action) => action.name === name)?.description ?? ''; +} + +/** A one-line summary of a trigger: its action and, for notifications, the title in quotes. */ +export function triggerSummary(intl, trigger, described = []) { + const label = actionLabel(intl, trigger?.action, described); + const title = trigger?.params?.title; + return title ? `${label} “${title}”` : label; +} diff --git a/addon/utils/order-config-steps.js b/addon/utils/order-config-steps.js new file mode 100644 index 000000000..ea344778d --- /dev/null +++ b/addon/utils/order-config-steps.js @@ -0,0 +1,38 @@ +import { isArray } from '@ember/array'; +import normalizeOrderConfigFlow, { getOrderConfigFlowRootCode } from './normalize-order-config-flow'; + +/** + * A config's steps in reading order: from the first step, each step followed by the steps it + * leads to, breadth first. A step reached as a second (or later) way out of another is a branch, + * and says which step it branches from. Steps nothing leads to come last. + * + * @returns {Array<{code, label, details, activity, next: Array, branchFrom: ?String, index}>} + */ +export default function orderConfigSteps(config) { + const flow = normalizeOrderConfigFlow(config?.flow ?? {}); + const nextOf = (activity) => (isArray(activity?.activities) ? activity.activities : []).map((next) => (typeof next === 'string' ? next : (next?.code ?? next?.key))).filter(Boolean); + const root = getOrderConfigFlowRootCode(flow, config?.meta?.lifecycle?.initial); + const ordered = []; + const seen = new Set(); + const queue = root ? [{ code: root, branchFrom: null }] : []; + + while (queue.length) { + const { code, branchFrom } = queue.shift(); + if (seen.has(code) || !flow[code]) { + continue; + } + seen.add(code); + ordered.push({ code, branchFrom }); + nextOf(flow[code]).forEach((next, index) => queue.push({ code: next, branchFrom: index > 0 ? code : null })); + } + Object.keys(flow).forEach((code) => { + if (!seen.has(code)) { + ordered.push({ code, branchFrom: null }); + } + }); + + return ordered.map(({ code, branchFrom }, index) => { + const activity = flow[code]; + return { code, label: activity.status || code, details: activity.details, activity, next: nextOf(activity), branchFrom, index }; + }); +} diff --git a/addon/utils/sentence-parts.js b/addon/utils/sentence-parts.js new file mode 100644 index 000000000..f06f42587 --- /dev/null +++ b/addon/utils/sentence-parts.js @@ -0,0 +1,35 @@ +const MARK = '\u0000'; + +/** + * Turns a translated sentence with `{placeholders}` into parts for `OrderConfig::SentenceField`: + * text between the placeholders, and each placeholder replaced by its control. Translating with + * markers instead of splitting the source string keeps word order right in every language. + * + * @param {Service} intl the intl service + * @param {String} key the translation key of the sentence + * @param {Object} controls a part for each placeholder name, e.g. `{ choice: { kind: 'choice', ... } }` + * @param {Object} values other ICU values the sentence needs + * @returns {Array} parts in reading order + */ +export default function sentenceParts(intl, key, controls = {}, values = {}) { + const markers = Object.fromEntries(Object.keys(controls).map((name) => [name, `${MARK}${name}${MARK}`])); + const text = intl.t(key, { ...values, ...markers }); + const parts = []; + + text.split(MARK).forEach((chunk, index) => { + // Odd chunks are placeholder names; even chunks are text between them. + if (index % 2 === 1) { + if (controls[chunk]) { + parts.push(controls[chunk]); + } + return; + } + + const trimmed = chunk.trim(); + if (trimmed) { + parts.push({ kind: 'text', text: trimmed }); + } + }); + + return parts; +} diff --git a/app/components/order-config/inline-list.js b/app/components/order-config/inline-list.js new file mode 100644 index 000000000..48dbe995f --- /dev/null +++ b/app/components/order-config/inline-list.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/inline-list'; diff --git a/app/components/order-config/inline-number.js b/app/components/order-config/inline-number.js new file mode 100644 index 000000000..9c47d1b21 --- /dev/null +++ b/app/components/order-config/inline-number.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/inline-number'; diff --git a/app/components/order-config/inline-select.js b/app/components/order-config/inline-select.js new file mode 100644 index 000000000..663e9921e --- /dev/null +++ b/app/components/order-config/inline-select.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/inline-select'; diff --git a/app/components/order-config/notice.js b/app/components/order-config/notice.js new file mode 100644 index 000000000..43399f86a --- /dev/null +++ b/app/components/order-config/notice.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/notice'; diff --git a/app/components/order-config/order-events.js b/app/components/order-config/order-events.js new file mode 100644 index 000000000..ba7783ab8 --- /dev/null +++ b/app/components/order-config/order-events.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/order-events'; diff --git a/app/components/order-config/sentence-field.js b/app/components/order-config/sentence-field.js new file mode 100644 index 000000000..7c77fb6d2 --- /dev/null +++ b/app/components/order-config/sentence-field.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/sentence-field'; diff --git a/app/components/order-config/trigger-list.js b/app/components/order-config/trigger-list.js new file mode 100644 index 000000000..dfe4ad68c --- /dev/null +++ b/app/components/order-config/trigger-list.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/trigger-list'; diff --git a/app/components/order-config/unsaved-bar.js b/app/components/order-config/unsaved-bar.js new file mode 100644 index 000000000..e2cd32b48 --- /dev/null +++ b/app/components/order-config/unsaved-bar.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/unsaved-bar'; diff --git a/app/controllers/settings/dispatch.js b/app/controllers/settings/dispatch.js new file mode 100644 index 000000000..f5f546f82 --- /dev/null +++ b/app/controllers/settings/dispatch.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/controllers/settings/dispatch'; diff --git a/app/helpers/entity-size.js b/app/helpers/entity-size.js new file mode 100644 index 000000000..054e0497f --- /dev/null +++ b/app/helpers/entity-size.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/helpers/entity-size'; diff --git a/app/helpers/entity-weight.js b/app/helpers/entity-weight.js new file mode 100644 index 000000000..a524c4e61 --- /dev/null +++ b/app/helpers/entity-weight.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/helpers/entity-weight'; diff --git a/app/routes/settings/dispatch.js b/app/routes/settings/dispatch.js new file mode 100644 index 000000000..0f5220bd4 --- /dev/null +++ b/app/routes/settings/dispatch.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/routes/settings/dispatch'; diff --git a/app/templates/settings/dispatch.js b/app/templates/settings/dispatch.js new file mode 100644 index 000000000..6608858ad --- /dev/null +++ b/app/templates/settings/dispatch.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/templates/settings/dispatch'; diff --git a/app/utils/order-config-action-meta.js b/app/utils/order-config-action-meta.js new file mode 100644 index 000000000..6dd8a439f --- /dev/null +++ b/app/utils/order-config-action-meta.js @@ -0,0 +1 @@ +export { ACTION_ICONS, ICON_GROUPS, actionIcon, actionLabel, actionDescription, triggerSummary } from '@fleetbase/fleetops-engine/utils/order-config-action-meta'; diff --git a/app/utils/order-config-steps.js b/app/utils/order-config-steps.js new file mode 100644 index 000000000..9d4af272d --- /dev/null +++ b/app/utils/order-config-steps.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/utils/order-config-steps'; diff --git a/app/utils/sentence-parts.js b/app/utils/sentence-parts.js new file mode 100644 index 000000000..f065bcdfa --- /dev/null +++ b/app/utils/sentence-parts.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/utils/sentence-parts'; diff --git a/composer.json b/composer.json index 924dc7d61..0ad42d219 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "fleetbase/fleetops-api", - "version": "0.6.75", + "version": "0.7.0", "description": "Fleet & Transport Management Extension for Fleetbase", "keywords": [ "fleetbase-extension", @@ -21,30 +21,30 @@ } ], "require": { - "php": "^8.0", + "php": "^8.2", "barryvdh/laravel-dompdf": "^3.1", "brick/geo": "0.7.2", - "cknow/laravel-money": "^7.1", - "fleetbase/core-api": "^1.6.74", + "cknow/laravel-money": "^8.0", + "fleetbase/core-api": "^2.0", "geocoder-php/google-maps-places-provider": "^1.4", "giggsey/libphonenumber-for-php": "^8.13", "league/geotools": "^1.1.0", - "milon/barcode": "^10.0", + "milon/barcode": "^13.0", "php-http/guzzle7-adapter": "^1.0", "php-units-of-measure/php-units-of-measure": "^2.2", "psr/http-factory-implementation": "*", "rlanvin/php-rrule": "^2.6", - "toin0u/geocoder-laravel": "^4.4", + "toin0u/geocoder-laravel": "^13.0", "webit/eval-math": "^1.0", "spatie/icalendar-generator": "^2.8" }, "require-dev": { - "illuminate/encryption": "^9.0|^10.0", + "illuminate/encryption": "^12.69", "friendsofphp/php-cs-fixer": "^3.34.1", - "nunomaduro/collision": "^7.0", - "pestphp/pest": "^2.33.2", - "phpstan/phpstan": "^1.10.38", - "symfony/var-dumper": "^5.4.29" + "nunomaduro/collision": "^8.0", + "pestphp/pest": "^3.0", + "phpstan/phpstan": "^2.0", + "symfony/var-dumper": "^7.0" }, "autoload": { "psr-4": { diff --git a/extension.json b/extension.json index c0757d489..c6ec6a88a 100644 --- a/extension.json +++ b/extension.json @@ -1,6 +1,6 @@ { "name": "Fleet-Ops", - "version": "0.6.75", + "version": "0.7.0", "description": "Fleet & Transport Management Extension for Fleetbase", "repository": "https://github.com/fleetbase/fleetops", "license": "AGPL-3.0-or-later", diff --git a/package.json b/package.json index 0822d957b..827bad169 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fleetbase/fleetops-engine", - "version": "0.6.75", + "version": "0.7.0", "description": "Fleet & Transport Management Extension for Fleetbase", "fleetbase": { "route": "fleet-ops" diff --git a/scripts/pest-bootstrap.php b/scripts/pest-bootstrap.php index 95b00ad3a..ef246c774 100644 --- a/scripts/pest-bootstrap.php +++ b/scripts/pest-bootstrap.php @@ -300,8 +300,8 @@ function now($tz = null): Illuminate\Support\Carbon } if (class_exists('Illuminate\Http\Request') && method_exists('Illuminate\Http\Request', 'macro')) { - if (!method_exists('Illuminate\Http\Request', 'array')) { - Illuminate\Http\Request::macro('array', function (string $key, array $default = []): array { + if (!method_exists('Illuminate\Http\Request', 'inputArray')) { + Illuminate\Http\Request::macro('inputArray', function (string $key, array $default = []): array { $value = $this->input($key, $default); return is_array($value) ? $value : $default; @@ -418,6 +418,36 @@ public static function dispatchNow(...$arguments) { \Fleetbase\TestSupport\Dispa eval('namespace Fleetbase\Ai\Support; class AiRelativeDateResolver { public function __construct($parser = null) {} public function resolveDateTime(string $prompt, ?string $timezone = null): ?\Illuminate\Support\Carbon { if (preg_match("/(\d+)\s+days?\s+from\s+now/i", $prompt, $matches)) { return \Illuminate\Support\Carbon::now($timezone)->addDays((int) $matches[1]); } return null; } public function resolveWindow(string $prompt, ?string $timezone = null): ?array { $timezone = $timezone ?: date_default_timezone_get(); $now = \Illuminate\Support\Carbon::now($timezone); if (str_contains(strtolower($prompt), "last week")) { $start = $now->copy()->subWeek()->startOfWeek(); $end = $now->copy()->subWeek()->endOfWeek(); return ["label" => "last week", "timezone" => $timezone, "start" => $start, "end" => $end]; } if (str_contains(strtolower($prompt), "yesterday")) { $start = $now->copy()->subDay()->startOfDay(); $end = $now->copy()->subDay()->endOfDay(); return ["label" => "yesterday", "timezone" => $timezone, "start" => $start, "end" => $end]; } return null; } }'); } +// cknow/laravel-money 8 finds its ISO currency table through config, which this harness never loads. +if (class_exists(Cknow\Money\Money::class)) { + Cknow\Money\Money::setCurrencies(new Money\Currencies\ISOCurrencies()); +} + +/** + * Laravel 12's loadMissing() always starts a query, even when every relation is set, so a + * model test without a connection needs a resolver to reach that point. + */ +function fleetopsTestConnectionResolver(): void +{ + Illuminate\Database\Eloquent\Model::setConnectionResolver(new class implements Illuminate\Database\ConnectionResolverInterface { + private ?Illuminate\Database\Connection $connection = null; + + public function connection($name = null) + { + return $this->connection ??= new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')); + } + + public function getDefaultConnection() + { + return 'sqlite'; + } + + public function setDefaultConnection($name) + { + } + }); +} + set_error_handler(function (int $severity, string $message): bool { if (str_contains($message, '/pestphp/pest/vendor/autoload.php')) { return true; diff --git a/server/migrations/2023_04_27_053456_create_routes_table.php b/server/migrations/2023_04_27_053456_create_routes_table.php index 0c22f685a..f1f0899db 100644 --- a/server/migrations/2023_04_27_053456_create_routes_table.php +++ b/server/migrations/2023_04_27_053456_create_routes_table.php @@ -19,12 +19,19 @@ public function up() $table->char('company_uuid', 36)->nullable()->index(); $table->char('order_uuid', 36)->nullable()->index(); $table->json('details')->nullable(); - $table->double('total_distance', 12, 2)->nullable(); - $table->double('total_time', 12, 2)->nullable(); + $table->double('total_distance')->nullable(); + $table->double('total_time')->nullable(); $table->softDeletes(); $table->timestamp('created_at')->nullable()->index(); $table->timestamp('updated_at')->nullable(); }); + + // Blueprint::double() only takes total and places before Laravel 11, so set them in SQL. + if (Schema::getConnection()->getDriverName() === 'mysql') { + Schema::getConnection()->statement( + 'ALTER TABLE `routes` MODIFY COLUMN `total_distance` DOUBLE(12,2) NULL, MODIFY COLUMN `total_time` DOUBLE(12,2) NULL' + ); + } } /** diff --git a/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php b/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php index 3727a3a03..42e4e4886 100644 --- a/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php +++ b/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php @@ -17,7 +17,7 @@ public function up() $table->string('category')->nullable()->after('type'); $table->json('tags')->nullable()->after('priority'); $table->json('meta')->nullable()->after('priority'); - $table->mediumText('report')->change(); + $table->mediumText('report')->nullable()->change(); $table->foreignUuid('reported_by_uuid')->nullable()->after('assigned_to_uuid')->references('uuid')->on('users')->onDelete('cascade'); }); } @@ -33,7 +33,7 @@ public function down() $table->string('longitude')->nullable()->after('location'); $table->string('latitude')->nullable()->after('location'); $table->string('odometer')->nullable()->after('location'); - $table->string('report')->change(); + $table->string('report')->nullable()->change(); $table->dropForeign(['reported_by_uuid']); $table->dropColumn(['reported_by_uuid', 'meta', 'tags', 'category']); }); diff --git a/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php b/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php index 13bb4c1be..ecc5166fa 100644 --- a/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php +++ b/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php @@ -14,7 +14,7 @@ public function up() { // Increase size of vehicles avatar url column for signed urls Schema::table('vehicles', function (Blueprint $table) { - $table->mediumText('avatar_url')->change(); + $table->mediumText('avatar_url')->nullable()->change(); }); // Add avatar url column to places @@ -38,7 +38,7 @@ public function down() // @todo this can break migrations if avatar url is over 300 characters to we need to remove this and keep mediumtext // Reverse: Increase size of vehicles avatar url column for signed urls Schema::table('vehicles', function (Blueprint $table) { - $table->string('avatar_url', 300)->change(); + $table->string('avatar_url', 300)->nullable()->change(); }); // Reverse: Add avatar url column to places diff --git a/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php b/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php index 2b658b3d8..acb915210 100644 --- a/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php +++ b/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php @@ -11,7 +11,7 @@ public function up(): void { Schema::table('service_quotes', function (Blueprint $table) { - $table->bigInteger('amount')->change(); + $table->bigInteger('amount')->nullable()->change(); }); } @@ -21,7 +21,7 @@ public function up(): void public function down(): void { Schema::table('service_quotes', function (Blueprint $table) { - $table->integer('amount')->change(); + $table->integer('amount')->nullable()->change(); }); } }; diff --git a/server/migrations/2025_08_28_054926_create_sensors_table.php b/server/migrations/2025_08_28_054926_create_sensors_table.php index 731ae7158..55f3e7697 100644 --- a/server/migrations/2025_08_28_054926_create_sensors_table.php +++ b/server/migrations/2025_08_28_054926_create_sensors_table.php @@ -48,6 +48,13 @@ public function up(): void $table->index(['company_uuid', 'sensor_type']); }); + + // Blueprint::float() defaulted to total and places before Laravel 11, so set them in SQL. + if (Schema::getConnection()->getDriverName() === 'mysql') { + Schema::getConnection()->statement( + 'ALTER TABLE `sensors` MODIFY COLUMN `min_threshold` DOUBLE(8,2) NULL, MODIFY COLUMN `max_threshold` DOUBLE(8,2) NULL' + ); + } } /** diff --git a/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php b/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php index 00f072dd9..da5711049 100644 --- a/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php +++ b/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php @@ -23,7 +23,7 @@ public function up(): void $table->mediumText('notes')->after('meta')->nullable(); $table->string('usage_type')->after('type')->nullable(); $table->string('measurement_system')->after('type')->nullable(); - $table->json('vin_data')->change(); + $table->json('vin_data')->nullable()->change(); $table->renameColumn('model_data', 'specs'); }); @@ -70,7 +70,7 @@ public function down(): void $table->dropColumn('usage_type'); $table->dropColumn('measurement_system'); $table->dropColumn('ownership_type'); - $table->mediumText('vin_data')->change(); + $table->mediumText('vin_data')->nullable()->change(); $table->renameColumn('specs', 'model_data'); }); } diff --git a/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php b/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php index 17b129cc5..a1065bdf4 100644 --- a/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php +++ b/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php @@ -1,5 +1,6 @@ getDoctrineSchemaManager(); - $indexes = $doctrineSchemaManager->listTableIndexes($table); - - return isset($indexes[$index]); + return isset(TableIndexes::for($table)[$index]); } catch (Exception $e) { return false; } diff --git a/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php b/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php index e9555ac8f..e4725974e 100644 --- a/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php +++ b/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php @@ -25,8 +25,8 @@ public function up(): void // Skills / capabilities $table->json('skills')->nullable()->after('status'); // Multi-dimensional capacity - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('skills'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('skills'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); // Route constraints diff --git a/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php b/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php index 002226d38..5703f5c7a 100644 --- a/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php +++ b/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php @@ -20,8 +20,8 @@ public function up(): void { Schema::table('payloads', function (Blueprint $table) { - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('cod_currency'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('cod_currency'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); }); diff --git a/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php b/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php index 2b028548a..df1eed0c3 100644 --- a/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php +++ b/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php @@ -35,8 +35,8 @@ public function up(): void public function down(): void { Schema::table('payloads', function (Blueprint $table) { - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('cod_currency'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('cod_currency'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); }); diff --git a/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php b/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php index 0f5e809d7..e9f65903a 100644 --- a/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php +++ b/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php @@ -39,7 +39,7 @@ public function down(): void { Schema::table('vehicles', function (Blueprint $table) { // Restore the dropped column - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('skills'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('skills'); // Reverse the renames $table->renameColumn('payload_capacity_volume', 'capacity_volume_m3'); diff --git a/server/migrations/2026_11_06_000001_adhoc_dispatch_and_order_config_policies.php b/server/migrations/2026_11_06_000001_adhoc_dispatch_and_order_config_policies.php new file mode 100644 index 000000000..5c03618ba --- /dev/null +++ b/server/migrations/2026_11_06_000001_adhoc_dispatch_and_order_config_policies.php @@ -0,0 +1,84 @@ +increments('id'); + $table->uuid('uuid')->unique(); + $table->uuid('company_uuid')->nullable()->index(); + $table->uuid('order_uuid')->index(); + $table->uuid('driver_uuid')->index(); + $table->string('status', 16)->default('pending'); + $table->unsignedInteger('distance')->nullable(); + $table->timestamp('expires_at')->nullable()->index(); + $table->timestamp('responded_at')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->index(['order_uuid', 'status']); + $table->index(['driver_uuid', 'status']); + }); + + Schema::create('driver_ratings', function (Blueprint $table) { + $table->increments('id'); + $table->uuid('uuid')->unique(); + $table->uuid('company_uuid')->nullable()->index(); + $table->uuid('order_uuid')->unique(); + $table->uuid('driver_uuid')->index(); + $table->uuid('customer_uuid')->nullable()->index(); + $table->string('customer_type')->nullable(); + $table->unsignedTinyInteger('stars'); + $table->text('comment')->nullable(); + $table->timestamps(); + $table->softDeletes(); + }); + + Schema::table('orders', function (Blueprint $table) { + $table->string('adhoc_strategy', 32)->nullable()->after('adhoc_distance'); + $table->string('required_vehicle_type')->nullable()->after('adhoc_strategy'); + $table->uuid('chat_channel_uuid')->nullable(); + }); + + Schema::table('order_configs', function (Blueprint $table) { + $table->json('policies')->nullable(); + $table->json('triggers')->nullable(); + }); + + Schema::table('service_quotes', function (Blueprint $table) { + $table->unsignedInteger('distance')->nullable(); + $table->unsignedInteger('time')->nullable(); + }); + + Schema::table('drivers', function (Blueprint $table) { + $table->decimal('rating_average', 3, 2)->nullable(); + $table->unsignedInteger('rating_count')->default(0); + }); + } + + public function down(): void + { + Schema::table('drivers', fn (Blueprint $table) => $table->dropColumn(['rating_average', 'rating_count'])); + Schema::table('service_quotes', fn (Blueprint $table) => $table->dropColumn(['distance', 'time'])); + Schema::table('order_configs', fn (Blueprint $table) => $table->dropColumn(['policies', 'triggers'])); + Schema::table('orders', fn (Blueprint $table) => $table->dropColumn(['adhoc_strategy', 'required_vehicle_type', 'chat_channel_uuid'])); + Schema::dropIfExists('driver_ratings'); + Schema::dropIfExists('order_offers'); + } +}; diff --git a/server/src/Console/Commands/CreateOrderConfig.php b/server/src/Console/Commands/CreateOrderConfig.php new file mode 100644 index 000000000..3780198c3 --- /dev/null +++ b/server/src/Console/Commands/CreateOrderConfig.php @@ -0,0 +1,49 @@ +option('list') || !$this->argument('template')) { + $this->table(['Key', 'Name', 'Description'], OrderConfigTemplates::describe()); + + return self::SUCCESS; + } + + $key = (string) $this->argument('template'); + if (!OrderConfigTemplates::has($key)) { + $this->error('No order config template named ' . $key . '. Run with --list to see them.'); + + return self::FAILURE; + } + + $id = (string) $this->option('company'); + $company = $id !== '' ? Company::where('uuid', $id)->orWhere('public_id', $id)->first() : null; + if (!$company) { + $this->error($id === '' ? 'Give the company with --company.' : 'No company found for ' . $id . '.'); + + return self::FAILURE; + } + + $name = $this->option('name'); + $config = OrderConfigTemplates::create($key, $company, is_string($name) && trim($name) !== '' ? trim($name) : null); + + $this->info(($config->wasRecentlyCreated ? 'Created' : 'Found') . ' order config ' . $config->name . ' (' . $config->public_id . ', key ' . $config->key . ') for ' . $company->name . '.'); + + return self::SUCCESS; + } +} diff --git a/server/src/Console/Commands/DispatchAdhocOrders.php b/server/src/Console/Commands/DispatchAdhocOrders.php index 31e91f342..5d4e9bf3f 100644 --- a/server/src/Console/Commands/DispatchAdhocOrders.php +++ b/server/src/Console/Commands/DispatchAdhocOrders.php @@ -2,12 +2,10 @@ namespace Fleetbase\FleetOps\Console\Commands; -use Fleetbase\FleetOps\Models\Driver; +use Fleetbase\FleetOps\Contracts\AdhocDispatchStrategy; use Fleetbase\FleetOps\Models\Order; -use Fleetbase\FleetOps\Notifications\OrderPing; -use Fleetbase\FleetOps\Support\NavigatorReview; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Fleetbase\FleetOps\Support\Utils; -use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Console\Command; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Carbon; @@ -29,7 +27,7 @@ class DispatchAdhocOrders extends Command * * @var string */ - protected $description = 'Dispatch & ping ad-hoc orders without assigned drivers (within a recent time window)'; + protected $description = 'Offer ad-hoc orders still without a driver again, through each order\'s dispatch strategy (within a recent time window)'; /** * Execute the console command. @@ -57,31 +55,25 @@ public function handle(): void $this->table(['Order', 'Dispatched At'], $orders->map(fn ($order) => [$order->public_id, $order->dispatched_at])); foreach ($orders as $order) { - $pickup = $order->getPickupLocation(); - $distance = $order->getAdhocPingDistance(); + $strategy = $this->strategyFor($order); + $offered = $strategy->redispatch($order, $testingMode); - if (!Utils::isPoint($pickup)) { - $this->error('Invalid pickup location for order ' . $order->public_id); - continue; - } - - $drivers = $this->getNearbyDriversForOrder($order, $pickup, $distance, $testingMode); - - $this->line('Checking order ' . $order->public_id . ' for nearby drivers within ' . $distance . ' meters.'); - - if ($drivers->count()) { - $order->dispatch(true); - $this->info('Order ' . $order->public_id . ' dispatched successfully to ' . $drivers->count() . ' nearby drivers.'); - foreach ($drivers as $driver) { - $this->info('Pinging driver ' . $driver->name . ' (' . $driver->public_id . ') ...'); - $driver->notify(new OrderPing($order, $distance)); - } + if ($offered) { + $this->info('Order ' . $order->public_id . ' offered to ' . $offered . ' driver(s) (' . $strategy->name() . ').'); } else { - $this->warn('No available drivers found for order ' . $order->public_id); + $this->line('No new offer for order ' . $order->public_id . ' (' . $strategy->name() . ').'); } } } + /** + * The strategy that offers the order to drivers. + */ + protected function strategyFor(Order $order): AdhocDispatchStrategy + { + return AdhocDispatch::for($order); + } + /** * Retrieve a collection of dispatchable orders created or dispatched within the last N days. * @@ -95,16 +87,16 @@ public function getDispatchableOrders(int $days = 2, int $intervalMinutes = 4, i { $sandbox = Utils::castBoolean($this->option('sandbox')); + // Each bound gets its own instance: subtracting from one shared Carbon moved both ends + // back 72 hours, leaving a window that never matched. $cutoffDate = Carbon::now()->subDays($days); - $now = Carbon::now(); + $oldest = Carbon::now()->subHours($expiryHours); + $newest = Carbon::now()->subMinutes($intervalMinutes); return $this->newOrderQuery($sandbox ? 'sandbox' : 'mysql') ->withoutGlobalScopes() ->where(['adhoc' => 1, 'dispatched' => 1, 'started' => 0]) - ->whereBetween('dispatched_at', [ - $now->subHours($expiryHours), // not older than 72 hours - $now->subMinutes($intervalMinutes), - ]) + ->whereBetween('dispatched_at', [$oldest, $newest]) ->where('created_at', '>=', $cutoffDate) ->whereNull('driver_assigned_uuid') ->whereNull('deleted_at') @@ -121,43 +113,8 @@ public function getDispatchableOrders(int $days = 2, int $intervalMinutes = 4, i ->get(); } - /** - * Fetch nearby drivers for a given order. - */ - public function getNearbyDriversForOrder(Order $order, Point $pickup, int $distance, bool $testing = false): Collection - { - $driverQuery = $this->newDriverQuery() - ->where(['online' => 1]) - ->where(function ($q) use ($order) { - $q->where('company_uuid', $order->company_uuid) - ->orWhereHas('user', fn ($q) => $q->where('company_uuid', $order->company_uuid)); - }) - ->whereNull('deleted_at') - ->withoutGlobalScopes(); - - // An app store reviewer's driver is never offered a real order. - NavigatorReview::excludeFrom($driverQuery); - - if (!$testing) { - $driverQuery->whereNotNull('location')->whereRaw(' - ST_Y(location) BETWEEN -90 AND 90 - AND ST_X(location) BETWEEN -180 AND 180 - AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0) - '); - $driverQuery->distanceSphere('location', $pickup, $distance); - $driverQuery->distanceSphereValue('location', $pickup); - } - - return $driverQuery->get(); - } - protected function newOrderQuery(string $connection) { return Order::on($connection); } - - protected function newDriverQuery() - { - return Driver::query(); - } } diff --git a/server/src/Console/Commands/ReplayVehicleLocations.php b/server/src/Console/Commands/ReplayVehicleLocations.php index ede009996..f72e96bbf 100644 --- a/server/src/Console/Commands/ReplayVehicleLocations.php +++ b/server/src/Console/Commands/ReplayVehicleLocations.php @@ -259,7 +259,7 @@ protected function calculateReplayDelay(string $previousTimestamp, string $creat { $currentTime = Carbon::parse($createdAt); $previousTime = Carbon::parse($previousTimestamp); - $diffInSeconds = $currentTime->diffInSeconds($previousTime); + $diffInSeconds = (int) $currentTime->diffInSeconds($previousTime, true); return [$diffInSeconds, $diffInSeconds / $speedMultiplier]; } diff --git a/server/src/Console/Commands/SimulateGeofenceEvents.php b/server/src/Console/Commands/SimulateGeofenceEvents.php index 95044f89c..f2928899d 100644 --- a/server/src/Console/Commands/SimulateGeofenceEvents.php +++ b/server/src/Console/Commands/SimulateGeofenceEvents.php @@ -273,6 +273,6 @@ protected function calculateDwellMinutes(string $subjectType, Driver|Vehicle $su return $fallback; } - return max(1, Carbon::parse($state->entered_at)->diffInMinutes(now())); + return max(1, (int) Carbon::parse($state->entered_at)->diffInMinutes(now(), true)); } } diff --git a/server/src/Constraints/HOSConstraint.php b/server/src/Constraints/HOSConstraint.php index 80304b524..378692e49 100644 --- a/server/src/Constraints/HOSConstraint.php +++ b/server/src/Constraints/HOSConstraint.php @@ -128,7 +128,7 @@ protected function check14HourDutyWindow(ScheduleItem $item, $recentItems): bool $dutyStart = Carbon::parse($lastOffDutyPeriod); $itemEnd = Carbon::parse($item->end_at); - $hoursSinceDutyStart = $dutyStart->diffInHours($itemEnd); + $hoursSinceDutyStart = (int) $dutyStart->diffInHours($itemEnd, true); return $hoursSinceDutyStart <= 14; } @@ -172,7 +172,7 @@ protected function check30MinuteBreak(ScheduleItem $item, $recentItems): bool foreach ($recentItems as $recentItem) { if ($recentItem->break_start_at && $recentItem->break_end_at) { - $breakDuration = Carbon::parse($recentItem->break_start_at)->diffInMinutes($recentItem->break_end_at); + $breakDuration = (int) Carbon::parse($recentItem->break_start_at)->diffInMinutes($recentItem->break_end_at, true); if ($breakDuration >= 30) { $lastBreak = $recentItem->break_end_at; $drivingHours = 0; // Reset driving hours after break @@ -188,7 +188,7 @@ protected function check30MinuteBreak(ScheduleItem $item, $recentItems): bool // If more than 8 hours of driving, require a 30-minute break if ($drivingHours > 8) { return $item->break_start_at && $item->break_end_at - && Carbon::parse($item->break_start_at)->diffInMinutes($item->break_end_at) >= 30; + && (int) Carbon::parse($item->break_start_at)->diffInMinutes($item->break_end_at, true) >= 30; } return true; diff --git a/server/src/Contracts/AdhocDispatchStrategy.php b/server/src/Contracts/AdhocDispatchStrategy.php new file mode 100644 index 000000000..2a179c1a7 --- /dev/null +++ b/server/src/Contracts/AdhocDispatchStrategy.php @@ -0,0 +1,61 @@ + description`. + */ + public function parameters(): array; + + /** + * Run the action for the order. The context names the event and, for an activity, its code, + * status and details. + */ + public function handle(Order $order, array $params = [], array $context = []): void; +} diff --git a/server/src/Contracts/OrderConfigPolicy.php b/server/src/Contracts/OrderConfigPolicy.php new file mode 100644 index 000000000..f860400c9 --- /dev/null +++ b/server/src/Contracts/OrderConfigPolicy.php @@ -0,0 +1,38 @@ +geofence = $geofence; $this->geofenceType = $geofenceType; $this->enteredAt = $enteredAt; - $this->dwellDurationMinutes = (int) $enteredAt->diffInMinutes(now()); + $this->dwellDurationMinutes = (int) $enteredAt->diffInMinutes(now(), true); $this->timestamp = now(); $this->modelRecordName = $geofence->name ?? $geofence->public_id ?? $geofence->uuid ?? null; $this->userSession = session('user'); diff --git a/server/src/Events/OrderOfferClosed.php b/server/src/Events/OrderOfferClosed.php new file mode 100644 index 000000000..21bd5f52b --- /dev/null +++ b/server/src/Events/OrderOfferClosed.php @@ -0,0 +1,62 @@ +eventId = uniqid('event_'); + $this->sentAt = Carbon::now()->toDateTimeString(); + $this->channelNames = array_values(array_filter([ + $driverPublicId ? 'driver.' . $driverPublicId : null, + 'driver.' . $driverUuid, + ])); + $this->data = ['id' => $orderPublicId, 'status' => $status]; + } + + public function broadcastOn(): array + { + return array_map(fn (string $name) => new Channel($name), $this->channelNames); + } + + public function broadcastAs(): string + { + return 'order.offer_closed'; + } + + public function broadcastWith(): array + { + return [ + 'id' => $this->eventId, + 'api_version' => config('api.version'), + 'event' => $this->broadcastAs(), + 'created_at' => $this->sentAt, + 'data' => $this->data, + ]; + } +} diff --git a/server/src/Flow/Activity.php b/server/src/Flow/Activity.php index 86502b5d6..0fe59e2bd 100644 --- a/server/src/Flow/Activity.php +++ b/server/src/Flow/Activity.php @@ -125,7 +125,7 @@ public function getChildActivities(Order|Waypoint|null $context = null) foreach ($activities as $childActivityCode) { $childActivity = $this->flow->getActivity($childActivityCode); // if waypoint context skip `created` - `started` - `dispatched` - if ($waypointContext && in_array($childActivity->code, ['created', 'started', 'dispatched'])) { + if ($childActivity && $waypointContext && in_array($childActivity->code, ['created', 'started', 'dispatched'])) { return $childActivity->getChildActivities($context); } diff --git a/server/src/Flow/Condition.php b/server/src/Flow/Condition.php index 80cb23199..fa6aa5a6a 100644 --- a/server/src/Flow/Condition.php +++ b/server/src/Flow/Condition.php @@ -10,6 +10,11 @@ class Condition extends FlowResource /** * Evaluate the condition against an order. * + * The field is read from the order (`Order::resolveDynamicValue()`: payload shortcuts such as + * `pickup.city`, attributes, the config's custom fields, meta, then relations). Strings compare + * without case. A list operator (`in`, `notIn`) takes the value as a list, or a comma + * separated string; `has` and `doesntHave` look for the value in a field that is a list. + * * @param Order $order the order to evaluate the condition against * * @return bool the result of the condition evaluation @@ -18,36 +23,37 @@ class Condition extends FlowResource */ public function eval(Order $order) { - $field = $this->field; $operator = $this->operator; - $value = $this->value; - $actualValue = strtolower($order->resolveDynamicValue($field)); - - // if value is string convert to lowercase - if (is_string($value)) { - $value = strtolower($value); - } + $value = static::normalize($this->value); + $field = (string) $this->field; + $resolved = $order->resolveDynamicValue($field); + // `resolveDynamicValue()` hands back the field name itself when the order has no such value. + $actualValue = static::normalize($resolved === $field ? null : $resolved); switch ($operator) { case 'exists': - return isset($actualValue); + return $actualValue !== null && $actualValue !== '' && $actualValue !== []; case 'in': - case 'has': - return is_array($actualValue) && in_array($actualValue, $value); + return !is_array($actualValue) && in_array($actualValue, static::toList($value), false); case 'notIn': + return !in_array($actualValue, static::toList($value), false); + + case 'has': + return in_array($value, static::toList($actualValue), false); + case 'doesntHave': - return is_array($actualValue) && !in_array($actualValue, $value); + return !in_array($value, static::toList($actualValue), false); case 'contains': - return is_string($value) && is_string($actualValue) && Str::contains($value, $actualValue); + return is_string($value) && is_string($actualValue) && Str::contains($actualValue, $value); case 'beginsWith': - return is_string($value) && is_string($actualValue) && Str::startsWith($value, $actualValue); + return is_string($value) && is_string($actualValue) && Str::startsWith($actualValue, $value); case 'endsWith': - return is_string($value) && is_string($actualValue) && Str::endsWith($value, $actualValue); + return is_string($value) && is_string($actualValue) && Str::endsWith($actualValue, $value); case 'equal': return $actualValue == $value; @@ -76,9 +82,41 @@ public function eval(Order $order) case 'lessThanOrEqual': return $actualValue <= $value; - // ... and so on for the other operators default: throw new \Exception("Unknown operator: {$operator}"); } } + + /** + * Lower-case strings, and each string in a list, so comparisons ignore case. + */ + protected static function normalize(mixed $value): mixed + { + if (is_string($value)) { + return strtolower(trim($value)); + } + + if ($value instanceof \Illuminate\Support\Collection) { + $value = $value->all(); + } + + if (is_array($value)) { + return array_map(fn ($item) => is_string($item) ? strtolower(trim($item)) : $item, $value); + } + + return $value; + } + + protected static function toList(mixed $value): array + { + if (is_array($value)) { + return array_values($value); + } + + if (is_string($value) && str_contains($value, ',')) { + return array_map('trim', explode(',', $value)); + } + + return $value === null ? [] : [$value]; + } } diff --git a/server/src/Flow/Flow.php b/server/src/Flow/Flow.php index cec61f0ca..3b0e66855 100644 --- a/server/src/Flow/Flow.php +++ b/server/src/Flow/Flow.php @@ -11,8 +11,13 @@ class Flow extends FlowResource implements \IteratorAggregate */ public function getIterator(): \Traversable { - foreach ($this->attributes['activities'] as $activityAttributes) { - yield new Activity($activityAttributes, $this->serialize()); + // Stored flows are keyed by activity code; older ones list them under `activities`. + $activities = isset($this->attributes['activities']) && is_array($this->attributes['activities']) ? $this->attributes['activities'] : $this->attributes; + + foreach ($activities as $activityAttributes) { + if (is_array($activityAttributes) && isset($activityAttributes['code'])) { + yield new Activity($activityAttributes, $this->serialize()); + } } } diff --git a/server/src/Http/Controllers/Api/v1/CustomerController.php b/server/src/Http/Controllers/Api/v1/CustomerController.php index 0fc7479c8..48e506c00 100644 --- a/server/src/Http/Controllers/Api/v1/CustomerController.php +++ b/server/src/Http/Controllers/Api/v1/CustomerController.php @@ -18,6 +18,13 @@ use Fleetbase\FleetOps\Models\Place; use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Support\CustomerAuth; +use Fleetbase\FleetOps\Support\DriverRatings; +use Fleetbase\FleetOps\Support\OrderChat; +use Fleetbase\FleetOps\Support\OrderCustomFields; +use Fleetbase\FleetOps\Support\PlaceSearch; +use Fleetbase\FleetOps\Support\TrackingCode; +use Fleetbase\FleetOps\Support\TrackingPage\TrackingShare; +use Fleetbase\FleetOps\Support\TrackingScope; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Controllers\Controller; use Fleetbase\LaravelMysqlSpatial\Types\Point as SpatialPoint; @@ -48,6 +55,11 @@ class CustomerController extends Controller public const DEACTIVATED_LOGIN_MESSAGE = 'This customer login has been deactivated.'; + /** + * Relations a customer's order is returned with. + */ + protected const CUSTOMER_ORDER_RELATIONS = ['payload', 'payload.pickup', 'payload.dropoff', 'transaction', 'driverRating']; + /** * Wrong guesses a single code tolerates before it locks itself (core's check()). */ @@ -183,7 +195,10 @@ public function create(CreateCustomerRequest $request) 'email' => $isEmail ? $identity : $request->input('email'), 'phone' => $isEmail ? static::phone($request->input('phone')) : $identity, ]); - $user->password = $request->input('password'); + // Customers who sign in by phone use a code, so they may have no password at all. + if ($request->filled('password')) { + $user->password = $request->input('password'); + } $user->save(); $user->setUserType('customer'); } else { @@ -200,7 +215,9 @@ public function create(CreateCustomerRequest $request) $update['email'] = $request->input('email'); } $user->fill($update); - $user->password = $request->input('password'); // mutator hashes + if ($request->filled('password')) { + $user->password = $request->input('password'); // mutator hashes + } $user->save(); if (!$user->type) { $user->setUserType('customer'); @@ -431,6 +448,28 @@ public function loginWithPhone(Request $request) return static::sendFailureResponse($smsFailure, 'Unable to send verification code.'); } + /** + * Send a code to a phone number without revealing whether it has an account. An + * existing customer gets a login code and a new one gets a signup code; both answer the + * same way. {@see verifyCode} tells them apart once the code is proven. + */ + public function requestCode(Request $request) + { + $phone = $request->input('phone') ?? $request->input('identity'); + if (!$phone || $this->isEmail($phone)) { + return response()->apiError('A phone number is required.', 400); + } + + $phone = static::phone($phone); + $input = ['phone' => $phone, 'identity' => $phone, 'mode' => 'sms']; + + $response = $this->findActiveUserByIdentity($phone, 'phone') + ? $this->loginWithPhone(Request::create('', 'POST', $input)) + : $this->requestCreationCode(VerifyCreateCustomerRequest::create('', 'POST', $input)); + + return $response->getStatusCode() === 200 ? response()->json(['status' => 'ok']) : $response; + } + /** * Verify the SMS/email code from {@see loginWithPhone} and issue a token. */ @@ -446,7 +485,17 @@ public function verifyCode(Request $request) $user = $this->findUserForVerification($identity); if (!$user) { - return response()->apiError('Unable to verify code.'); + // A proven signup code from requestCode(). It stays live for create(), which uses it up. + $signupCode = $this->verificationCodeMatches([ + 'code' => $code, + 'for' => 'fleetops_create_customer', + 'meta->identity' => $identity, + ]); + if ($signupCode || $this->verificationBypassMatches($identity, $code)) { + return response()->json(['status' => 'new_customer']); + } + + return response()->apiError('Invalid verification code.'); } if ($user->status === 'inactive') { @@ -598,6 +647,12 @@ public function updateMe(UpdateContactRequest $request) $input = $request->only(['name', 'title', 'email', 'phone', 'meta']); if (isset($input['phone'])) { $input['phone'] = static::phone($input['phone']); + if ($input['phone'] !== $customer->phone) { + $refusal = $this->refusePhoneChange($customer, $input['phone'], $request->input('phone_code')); + if ($refusal) { + return $refusal; + } + } } // Photo handling. @@ -642,6 +697,31 @@ public function updateMe(UpdateContactRequest $request) return $this->customerResource($customer->fresh()); } + /** + * Delete the customer's account: sign them out everywhere, delete their saved places and + * remove their name and contact details. Their past orders stay on the operator's books + * without them. + */ + public function deleteMe() + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + if ($this->hasOrdersInProgress($customer)) { + return response()->apiError('You have orders in progress. Wait for them to finish, or cancel them, before deleting your account.', 422); + } + + $user = $customer->user_uuid ? $this->findUserByUuid($customer->user_uuid) : null; + if ($user) { + $this->deleteUserTokens($user); + } + $this->eraseCustomer($customer, $user); + + return response()->json(['status' => 'deleted']); + } + /** * Revoke the Customer-Token used on this request. */ @@ -753,14 +833,48 @@ public function createOrder(CreateCustomerOrderRequest $request) return response()->apiError('No order config available for this company.', 422); } + if (!$this->customersMayOrder($orderConfig)) { + return response()->apiError('Customers cannot place this type of order.', 422); + } + + $serviceQuote = $this->resolveServiceQuote($request); + if ($serviceQuote instanceof ServiceQuote && ($serviceQuote->company_uuid !== $sessionCompany || $serviceQuote->expired_at?->isPast())) { + return response()->apiError('This quote has expired. Please get a new one.', 422); + } + + // Matching drivers by vehicle type needs a quote, whose service says the type. + $byVehicleType = (bool) $orderConfig->policy('dispatch.matching.vehicle_type'); + if (($byVehicleType || $orderConfig->policy('customer.ordering.require_quote')) && !$serviceQuote instanceof ServiceQuote) { + return response()->apiError('Choose a service quote for this order first.', 422); + } + + $paymentMethod = $request->input('payment_method'); + $paymentMethods = array_values((array) $orderConfig->policy('customer.ordering.payment_methods', [])); + if ($paymentMethod !== null && $paymentMethods !== [] && !in_array($paymentMethod, $paymentMethods, true)) { + return response()->apiError('Choose a payment method: ' . implode(', ', $paymentMethods) . '.', 422); + } + + if ($this->hasUnsettledOrder($customer, $orderConfig)) { + return response()->apiError('Settle your previous order before placing another.', 402); + } + + $customFieldErrors = OrderCustomFields::validate($orderConfig, (array) $request->input('custom_fields', [])); + if ($customFieldErrors) { + return response()->apiError($customFieldErrors, 422); + } + + $vehicleType = $byVehicleType ? $serviceQuote->serviceRate?->service_type : null; + // Build the Payload (matching the operator OrderController convention). // - `payload` may be an array of {pickup, dropoff, return, waypoints, entities} // - `payload` may be a string public_id referencing an existing Payload // - Or top-level pickup/dropoff/return/waypoints/entities are accepted $payloadUuid = null; + $builtHere = false; if ($request->isArray('payload')) { $payloadInput = (array) $request->input('payload'); $payloadUuid = $this->buildPayloadFromInput($payloadInput, $sessionCompany)->uuid; + $builtHere = true; } elseif ($request->isString('payload')) { $payloadUuid = $this->getUuid('payloads', [ 'public_id' => $request->input('payload'), @@ -770,32 +884,41 @@ public function createOrder(CreateCustomerOrderRequest $request) $payloadInput = $request->only(['pickup', 'dropoff', 'return', 'waypoints', 'entities']); if (array_filter($payloadInput, fn ($v) => $v !== null && $v !== '' && $v !== [])) { $payloadUuid = $this->buildPayloadFromInput($payloadInput, $sessionCompany)->uuid; + $builtHere = true; } } + // How the customer will pay, kept on the payload this order was given. + if ($builtHere && is_string($paymentMethod) && in_array($paymentMethod, $paymentMethods, true)) { + $this->setPayloadPaymentMethod($payloadUuid, $paymentMethod); + } + $order = $this->createOrderRecord([ - 'company_uuid' => $sessionCompany, - 'customer_uuid' => $customer->uuid, - 'customer_type' => $this->getModelClassName('contact'), - 'payload_uuid' => $payloadUuid, - 'order_config_uuid' => $orderConfig->uuid, - 'type' => $orderConfig->key, - 'status' => 'created', - 'scheduled_at' => $request->input('scheduled_at'), - 'notes' => $request->input('notes'), - 'internal_id' => $request->input('internal_id'), - 'meta' => (array) $request->input('meta', []), + 'company_uuid' => $sessionCompany, + 'customer_uuid' => $customer->uuid, + 'customer_type' => $this->getModelClassName('contact'), + 'payload_uuid' => $payloadUuid, + 'order_config_uuid' => $orderConfig->uuid, + 'type' => $orderConfig->key, + 'status' => $orderConfig->getInitialStatusCode(), + 'scheduled_at' => $request->input('scheduled_at'), + 'notes' => $request->input('notes'), + 'internal_id' => $request->input('internal_id'), + 'adhoc' => (bool) $orderConfig->policy('dispatch.adhoc.customer_orders'), + 'required_vehicle_type' => $vehicleType, + 'meta' => (array) $request->input('meta', []), ]); // If the customer picked a ServiceQuote up front, consume it now to // lock the pricing onto the order's PurchaseRate (mirrors how // OrderController::create handles `service_quote`). - $serviceQuote = $this->resolveServiceQuote($request); if ($serviceQuote instanceof ServiceQuote) { $order->purchaseServiceQuote($serviceQuote); } - return $this->orderResource($order->fresh(['payload', 'payload.pickup', 'payload.dropoff', 'payload.entities'])); + OrderCustomFields::apply($order, (array) $request->input('custom_fields', [])); + + return $this->orderResource($order->fresh([...static::CUSTOMER_ORDER_RELATIONS, 'payload.entities'])); } /** @@ -859,6 +982,377 @@ public function places(Request $request) return $this->placeResourceCollection($results); } + /** + * Search this customer's saved places and the geocoder. Other customers' places are never + * returned, and neither are unowned rows, which hold addresses from other customers' orders. + */ + public function searchPlaces(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + return $this->placeResourceCollection($this->runPlaceSearch($this->customerPlaceQuery($customer), (string) $request->input('query', ''), [ + 'limit' => min((int) $request->input('limit', 10), 50), + 'geo' => true, + 'latitude' => $request->input('latitude', false), + 'longitude' => $request->input('longitude', false), + 'no_query_order' => 'name_desc', + ])); + } + + /** + * Look up an address or coordinates. Nothing is stored. + */ + public function geocode(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + $query = trim((string) $request->input('query', '')); + $latitude = $request->input('latitude'); + $longitude = $request->input('longitude'); + if ($query === '' && (!is_numeric($latitude) || !is_numeric($longitude))) { + return response()->apiError('A query or coordinates are required.', 400); + } + + return $this->placeResourceCollection($this->geocodePlaces($query, $latitude, $longitude)); + } + + /** + * Save a place for the authenticated customer. + */ + public function savePlace(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + $location = $this->savedPlaceLocation($request); + if (!$location || !trim((string) $request->input('name'))) { + return response()->apiError('A name, latitude and longitude are required.', 422); + } + + $place = $this->createPlace(array_merge($this->savedPlaceAttributes($request), [ + 'company_uuid' => $this->sessionCompany(), + 'owner_uuid' => $customer->uuid, + 'owner_type' => get_class($customer), + 'location' => $location, + ])); + + return $this->placeResource($place); + } + + /** + * Update one of the authenticated customer's saved places. + */ + public function updatePlace(string $id, Request $request) + { + $place = $this->ownedPlace($id); + if (!$place) { + return response()->apiError('Place not found.', 404); + } + + $attributes = $this->savedPlaceAttributes($request); + if ($request->hasAny(['latitude', 'longitude'])) { + $location = $this->savedPlaceLocation($request); + if (!$location) { + return response()->apiError('A latitude and longitude are required.', 422); + } + $attributes['location'] = $location; + } + + $place->update($attributes); + + return $this->placeResource($place); + } + + /** + * Delete one of the authenticated customer's saved places. + */ + public function deletePlace(string $id) + { + $place = $this->ownedPlace($id); + if (!$place) { + return response()->apiError('Place not found.', 404); + } + + $place->delete(); + + return response()->json(['status' => 'ok']); + } + + /** + * Send a code to the number a customer wants to change to, so {@see updateMe} can prove + * they hold it. + */ + public function requestPhoneChangeCode(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + if (!$request->filled('phone') || !$customer->user_uuid) { + return response()->apiError('A phone number is required.', 400); + } + + $phone = static::phone($request->input('phone')); + + // Answer the same for a number another account holds, so this can't discover accounts. + // updateMe() refuses the change if it is ever attempted. + if ($this->findActiveUserByIdentity($phone, 'phone')) { + return response()->json(['status' => 'ok']); + } + + $subject = $this->findUserByUuid($customer->user_uuid); + if (!$subject) { + return response()->apiError('Unable to send verification code.'); + } + + try { + $this->generateSmsVerification($subject, 'fleetops_customer_phone_change', [ + 'phone' => $phone, + 'hashed' => true, + 'messageCallback' => fn ($verification) => 'Your ' . config('app.name') . ' verification code is ' . $verification->code, + 'meta' => ['identity' => $phone], + ]); + } catch (SmsBlockedException $e) { + return static::smsBlockedResponse($e); + } catch (\Throwable $e) { + return static::sendFailureResponse($e, 'Unable to send verification code.'); + } + + return response()->json(['status' => 'ok']); + } + + /** + * Request a driver for one of the authenticated customer's orders. + */ + public function dispatchOrder(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + if ($order->dispatched) { + return response()->apiError('Order has already been dispatched.', 422); + } + if ($this->orderHasEnded($order) || $order->status !== $order->config()->getInitialStatusCode() || !$order->config()->allowsDispatch()) { + return response()->apiError('This order can no longer be dispatched.', 422); + } + if (!$order->hasDriverAssigned && !$order->adhoc) { + return response()->apiError('No driver is available for this order.', 422); + } + + $order->dispatch(); + $order->insertDispatchActivity(); + + return $this->orderResource($order->fresh(static::CUSTOMER_ORDER_RELATIONS)); + } + + /** + * Cancel one of the authenticated customer's orders, when its config lets customers cancel. + */ + public function cancelOrder(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + if (!$this->customerMayCancel($order)) { + return response()->apiError('This order can no longer be canceled.', 422); + } + + $reason = $request->input('reason'); + if (is_string($reason) && trim($reason) !== '') { + $order->cancelWithReason(Str::limit(trim($reason), 1000, '')); + } else { + $order->cancel(); + } + + return $this->orderResource($order->fresh(static::CUSTOMER_ORDER_RELATIONS)); + } + + /** + * The driver and vehicle of one of the customer's orders, so the customer can recognise them. + * The driver's contact details stay out: customers and drivers don't share phone numbers. + */ + public function orderDriver(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + $driver = $order->driverAssigned; + $vehicle = $order->vehicleAssigned ?? $driver?->vehicle; + if (!$driver) { + return response()->json(['driver' => null, 'vehicle' => null]); + } + + return response()->json([ + 'driver' => ['name' => $driver->name, 'photo_url' => $driver->photo_url, 'location' => $driver->location, 'rating' => $driver->rating_average !== null ? (float) $driver->rating_average : null], + 'vehicle' => $vehicle ? [ + 'make' => $vehicle->make, + 'model' => $vehicle->model, + 'color' => $vehicle->color ?? null, + 'plate_number' => $vehicle->plate_number, + ] : null, + ]); + } + + /** + * Live tracking data for one of the authenticated customer's orders. + */ + public function orderTracker(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + try { + return response()->json($order->tracker()->toArray($request->only(['provider', 'fallbacks', 'traffic_enabled']))); + } catch (\Throwable) { + return response()->apiError('Unable to track this order.', 503); + } + } + + /** + * ETA for one of the authenticated customer's orders. + */ + public function orderEta(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + try { + return response()->json($order->tracker()->eta($request->only(['provider', 'fallbacks', 'traffic_enabled']))); + } catch (\Throwable) { + return response()->apiError('Unable to track this order.', 503); + } + } + + /** + * The chat with the driver of one of the customer's orders, oldest message first. Empty until + * a driver is assigned. Needs the config's `customer.interactions.chat` policy. + */ + public function orderMessages(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + if (!$order->config()->policy('customer.interactions.chat')) { + return response()->apiError('Messaging the driver is not available for this order.', 403); + } + + $channel = $this->orderChannel($order); + + return response()->json($channel ? OrderChat::messages($channel, $this->currentCustomer()->user_uuid)->all() : []); + } + + /** + * Send the driver a message. The customer always writes as themselves. + */ + public function sendOrderMessage(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + if (!$order->config()->policy('customer.interactions.chat')) { + return response()->apiError('Messaging the driver is not available for this order.', 403); + } + + $text = trim((string) $request->input('text')); + if ($text === '' || mb_strlen($text) > 2000) { + return response()->apiError('Write a message of up to 2000 characters.', 422); + } + + $channel = $this->orderChannel($order); + if ($this->chatIsClosed($order, $channel)) { + return response()->apiError('This conversation has ended.', 422); + } + if (!$channel) { + return response()->apiError('You can message the driver once one is assigned.', 422); + } + + $customerUser = $this->currentCustomer()->user_uuid; + $message = OrderChat::send($channel, $customerUser, $text); + + return response()->json(OrderChat::messages($channel, $customerUser)->firstWhere('id', $message->public_id ?? $message->uuid), 201); + } + + /** + * Rate the driver of a completed order, once. Needs the config's `customer.interactions.rating` policy. + */ + public function rateOrder(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + if (!$order->config()->policy('customer.interactions.rating')) { + return response()->apiError('Rating the driver is not available for this order.', 403); + } + + $stars = $request->input('stars'); + if (!is_numeric($stars) || (int) $stars != $stars || $stars < 1 || $stars > 5) { + return response()->apiError('Rate from 1 to 5 stars.', 422); + } + if ($order->status !== $order->config()->getCompletedActivity()?->code || !$order->driver_assigned_uuid) { + return response()->apiError('Only a completed order can be rated.', 422); + } + + $comment = $request->input('comment'); + if (!DriverRatings::rate($order, (int) $stars, is_string($comment) ? Str::limit($comment, 1000, '') : null)) { + return response()->apiError('You already rated this order.', 409); + } + + return response()->json(['status' => 'rated']); + } + + /** + * A link the customer can send to someone they trust to follow the order live, without a + * code. Needs the config's `customer.interactions.share_tracking` policy. + */ + public function shareOrder(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + if (!$order->config()->policy('customer.interactions.share_tracking')) { + return response()->apiError('Sharing tracking is not available for this order.', 403); + } + + $number = data_get($order, 'trackingNumber.tracking_number'); + if (!$number || $this->orderHasEnded($order)) { + return response()->apiError('This order can no longer be shared.', 422); + } + + $scope = TrackingScope::forCustomer($order, $this->currentCustomer()); + $expiresAt = now()->addHours(TrackingShare::HOURS); + $url = $this->trackingPageUrl($number, $order->company_uuid); + + return response()->json([ + 'url' => $url . (str_contains($url, '?') ? '&' : '?') . 'share=' . TrackingShare::token($scope->order_uuid, $scope->customer_uuid, $expiresAt), + 'expires_at' => $expiresAt->toISOString(), + ]); + } + /** * Register a push-notification device for the authenticated customer's user. */ @@ -892,6 +1386,183 @@ public function registerDevice(Request $request) | Helpers * ============================================================ */ + /** + * Why a customer can't change to this phone number, or null if they can. A number is only + * accepted with a code sent to it, and never if another account holds it. + */ + protected function refusePhoneChange(Contact $customer, string $phone, mixed $code): ?JsonResponse + { + $holder = $this->findActiveUserByIdentity($phone, 'phone'); + $proven = $code && $customer->user_uuid && $this->verificationCodeExists([ + 'subject_uuid' => $customer->user_uuid, + 'code' => $code, + 'for' => 'fleetops_customer_phone_change', + 'meta->identity' => $phone, + ]); + + if (!$proven || ($holder && $holder->uuid !== $customer->user_uuid)) { + return response()->apiError('Changing your phone number needs a valid verification code.', 422); + } + + return null; + } + + protected function setPayloadPaymentMethod(string $payloadUuid, string $paymentMethod): void + { + Payload::where('uuid', $payloadUuid)->update(['payment_method' => $paymentMethod]); + } + + protected function trackingPageUrl(string $number, ?string $companyUuid): string + { + return TrackingCode::pageUrl($number, $companyUuid); + } + + protected function orderChannel(Order $order): mixed + { + return OrderChat::open($order); + } + + protected function chatIsClosed(Order $order, mixed $channel): bool + { + return OrderChat::isClosed($order, $channel ?: null); + } + + protected function orderHasEnded(Order $order): bool + { + return in_array($order->status, ['completed', 'canceled'], true) || (bool) $order->config()?->isTerminalActivityCode($order->status); + } + + /** + * Whether customers may place orders of the config: every config, unless the company chose + * which configs customers may use (`fleet-ops.customer-enabled-order-configs`). + */ + protected function customersMayOrder(OrderConfig $orderConfig): bool + { + $enabled = array_filter((array) $this->lookupCompanySetting('fleet-ops.customer-enabled-order-configs', [])); + + return $enabled === [] || in_array($orderConfig->uuid, $enabled, true) || in_array($orderConfig->public_id, $enabled, true); + } + + protected function lookupCompanySetting(string $key, mixed $default = null): mixed + { + return \Fleetbase\Models\Setting::lookupFromCompany($key, $default); + } + + /** + * Whether the customer may still cancel the order: their config lets customers cancel, the + * order hasn't finished, and it hasn't reached the config's `allowed_until` activity. + */ + protected function customerMayCancel(Order $order): bool + { + if ($this->orderHasEnded($order)) { + return false; + } + + $config = $order->config(); + if (!$config->policy('customer.cancellation.enabled', true)) { + return false; + } + + $until = $config->policy('customer.cancellation.allowed_until'); + $limit = is_string($until) && $until !== '' ? $config->getActivityByCode($until) : null; + + return !$limit || ($order->status !== $limit->code && !$order->hasCompletedActivity($limit)); + } + + /** + * Whether an earlier order of the config, paid by one of the methods its + * `customer.ordering.require_settlement` policy names, is completed but its transaction + * isn't paid. Methods the policy leaves out (cash collected by the driver, say) never block. + */ + protected function hasUnsettledOrder(Contact $customer, OrderConfig $orderConfig): bool + { + $methods = array_values(array_filter((array) $orderConfig->policy('customer.ordering.require_settlement', []), 'is_string')); + if ($methods === []) { + return false; + } + + return Order::withoutGlobalScopes() + ->where('customer_uuid', $customer->uuid) + ->where('order_config_uuid', $orderConfig->uuid) + ->where('status', $orderConfig->getCompletedActivity()?->code ?? 'completed') + ->whereNull('deleted_at') + ->whereHas('payload', fn ($payload) => $payload->whereIn('payment_method', $methods)) + ->whereHas('transaction', fn ($transaction) => $transaction->where('amount', '>', 0)->whereNotIn('settlement_status', ['paid', 'refunded', 'partially_refunded'])) + ->exists(); + } + + /** + * Whether the customer has an order that was sent to drivers and hasn't finished, by the + * order's own config. + */ + protected function hasOrdersInProgress(Contact $customer): bool + { + return Order::withoutGlobalScopes() + ->with('orderConfig') + ->where('customer_uuid', $customer->uuid) + ->where('dispatched', 1) + ->whereNull('deleted_at') + ->whereNotIn('status', ['completed', 'canceled']) + ->get() + ->contains(fn (Order $order) => !$this->orderHasEnded($order)); + } + + /** + * Remove what identifies the customer, then delete their records. A user who is only this + * company's customer goes too; one with other roles or companies keeps their account. + */ + protected function eraseCustomer(Contact $customer, ?User $user): void + { + Place::where('owner_uuid', $customer->uuid)->delete(); + + $customer->forceFill(['name' => 'Deleted customer', 'email' => null, 'phone' => null, 'photo_uuid' => null, 'meta' => []])->saveQuietly(); + $customer->delete(); + + $otherContacts = $user ? Contact::withoutGlobalScopes()->where('user_uuid', $user->uuid)->where('uuid', '!=', $customer->uuid)->exists() : true; + if ($user && $user->type === 'customer' && !$otherContacts) { + $user->forceFill(['name' => 'Deleted customer', 'email' => 'deleted-' . $user->uuid . '@deleted.invalid', 'phone' => null])->saveQuietly(); + $user->delete(); + } + } + + protected function ownedOrder(string $id): ?Order + { + $customer = $this->currentCustomer(); + + try { + $order = $this->findOrderOrFail($id); + } catch (\Illuminate\Database\Eloquent\ModelNotFoundException) { + return null; + } + + return $customer && $order->customer_uuid === $customer->uuid ? $order : null; + } + + protected function ownedPlace(string $id): ?Place + { + $customer = $this->currentCustomer(); + $place = $customer ? $this->findPlaceByPublicId($id, (string) $this->sessionCompany()) : null; + + return $place && $place->owner_uuid === $customer->uuid ? $place : null; + } + + protected function savedPlaceAttributes(Request $request): array + { + return $request->only(['name', 'street1', 'street2', 'city', 'province', 'postal_code', 'neighborhood', 'district', 'building', 'country', 'phone', 'meta']); + } + + protected function savedPlaceLocation(Request $request): ?SpatialPoint + { + $latitude = $request->input('latitude'); + $longitude = $request->input('longitude'); + + if (!is_numeric($latitude) || !is_numeric($longitude) || abs($latitude) > 90 || abs($longitude) > 180) { + return null; + } + + return new SpatialPoint((float) $latitude, (float) $longitude); + } + protected function isEmail(?string $identity): bool { return Utils::isEmail($identity); @@ -1033,6 +1704,23 @@ protected function verificationCodeExists(array $attributes): bool return $this->findVerificationCode($attributes) !== null; } + /** + * Whether the submitted code verifies, leaving it live. A wrong guess still counts + * against it. + */ + protected function verificationCodeMatches(array $attributes): bool + { + $code = (string) ($attributes['code'] ?? ''); + + foreach ($this->liveVerificationCodes($attributes) as $verificationCode) { + if ($verificationCode->check($code, static::CODE_CHECK_ATTEMPTS) === VerificationCode::CHECK_VALID) { + return true; + } + } + + return false; + } + /** * The live code the submitted code verified against, used up so it cannot verify * again, or null. `$attributes` carries `code`, `for` and either `subject_uuid` or @@ -1191,11 +1879,18 @@ protected function customerResource(Contact $contact): mixed protected function orderResource(Order $order): mixed { + $order->loadMissing(static::CUSTOMER_ORDER_RELATIONS); + return new OrderResource($order); } protected function orderResourceCollection(mixed $results): mixed { + if ($results instanceof \Illuminate\Support\Collection || $results instanceof \Illuminate\Contracts\Pagination\Paginator) { + collect($results instanceof \Illuminate\Contracts\Pagination\Paginator ? $results->items() : $results) + ->each(fn ($order) => $order instanceof Order ? $order->loadMissing(static::CUSTOMER_ORDER_RELATIONS) : null); + } + return OrderResource::collection($results); } @@ -1204,6 +1899,28 @@ protected function placeResourceCollection(mixed $results): mixed return PlaceResource::collection($results); } + protected function placeResource(Place $place): mixed + { + return new PlaceResource($place); + } + + protected function customerPlaceQuery(Contact $customer): mixed + { + return Place::where('company_uuid', $this->sessionCompany()) + ->where('owner_uuid', $customer->uuid) + ->whereNull('deleted_at'); + } + + protected function runPlaceSearch(mixed $query, string $searchQuery, array $options): mixed + { + return PlaceSearch::search($query, $searchQuery, $options); + } + + protected function geocodePlaces(string $query, mixed $latitude, mixed $longitude): mixed + { + return PlaceSearch::geocode($query, $latitude, $longitude); + } + /** * Normalize a phone number to international format (with leading `+`). */ diff --git a/server/src/Http/Controllers/Api/v1/DriverController.php b/server/src/Http/Controllers/Api/v1/DriverController.php index fd006cb2c..a73deb09b 100644 --- a/server/src/Http/Controllers/Api/v1/DriverController.php +++ b/server/src/Http/Controllers/Api/v1/DriverController.php @@ -26,6 +26,7 @@ use Fleetbase\FleetOps\Support\Geocoding; use Fleetbase\FleetOps\Support\GeofenceIntersectionService; use Fleetbase\FleetOps\Support\NavigatorReview; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; use Fleetbase\FleetOps\Support\OSRM; use Fleetbase\FleetOps\Support\ProfileAccountManager; use Fleetbase\FleetOps\Support\TrackingPublisher; @@ -335,7 +336,7 @@ public function track(string $id, Request $request) return $this->driverResource($driver); } - $isGeocodable = Carbon::parse($driver->updated_at)->diffInMinutes(Carbon::now(), false) > 10 || empty($driver->country) || empty($driver->city); + $isGeocodable = (int) Carbon::parse($driver->updated_at)->diffInMinutes(Carbon::now(), false) > 10 || empty($driver->country) || empty($driver->city); $positionData = [ 'location' => new Point($latitude, $longitude), @@ -394,6 +395,9 @@ public function track(string $id, Request $request) broadcast(new DriverLocationChanged($driver)); app(TrackingPublisher::class)->driverMoved($driver); + // The order's config can act when its driver comes close to the pickup or drop-off. + OrderConfigTriggers::driverMoved($driver, $order instanceof Order ? $order : null); + // ---------------------------------------------------------------- // Geofence intersection detection // @@ -1309,7 +1313,7 @@ private function processSubjectGeofenceCrossings(Driver|Vehicle $subject, Point $dwellMinutes = null; if ($state && $state->entered_at) { - $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now()); + $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now(), true); } DB::table($stateTable) diff --git a/server/src/Http/Controllers/Api/v1/OrderConfigController.php b/server/src/Http/Controllers/Api/v1/OrderConfigController.php index 02ec96a40..4d340fdb3 100644 --- a/server/src/Http/Controllers/Api/v1/OrderConfigController.php +++ b/server/src/Http/Controllers/Api/v1/OrderConfigController.php @@ -69,11 +69,17 @@ protected function findOrderConfigOrFail(string $id): OrderConfig protected function orderConfigCollection($results) { + collect($results instanceof \Illuminate\Contracts\Pagination\Paginator ? $results->items() : $results) + ->each(fn ($orderConfig) => $orderConfig instanceof OrderConfig ? $orderConfig->loadMissing('customFields') : null); + return OrderConfigResource::collection($results); } protected function orderConfigResource(OrderConfig $orderConfig) { + // Customer apps read the config's custom fields to ask for them when ordering. + $orderConfig->loadMissing('customFields'); + return new OrderConfigResource($orderConfig); } diff --git a/server/src/Http/Controllers/Api/v1/OrderController.php b/server/src/Http/Controllers/Api/v1/OrderController.php index b4e654289..4afdd5022 100644 --- a/server/src/Http/Controllers/Api/v1/OrderController.php +++ b/server/src/Http/Controllers/Api/v1/OrderController.php @@ -25,7 +25,11 @@ use Fleetbase\FleetOps\Models\Proof; use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Models\Waypoint; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing; +use Fleetbase\FleetOps\Support\OrderCustomFields; use Fleetbase\FleetOps\Support\OrderEdit; +use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\ResolvesOrderServiceStops; use Fleetbase\FleetOps\Support\TrackingCode; use Fleetbase\FleetOps\Support\Utils; @@ -34,6 +38,7 @@ use Fleetbase\Models\Company; use Fleetbase\Models\File; use Fleetbase\Models\Setting; +use Fleetbase\Models\User; use Fleetbase\Support\Auth; use Fleetbase\Support\TemplateString; use Illuminate\Database\Eloquent\ModelNotFoundException; @@ -351,9 +356,14 @@ protected function createOrderFromRequest(CreateOrderRequest $request) } } - // if no status is set its default to `created` + // if no status is set it starts at the config's initial activity, `created` by default if (!isset($input['status'])) { - $input['status'] = 'created'; + $input['status'] = $orderConfig->getInitialStatusCode(); + } + + $customFieldErrors = OrderCustomFields::validate($orderConfig, (array) $request->input('custom_fields', [])); + if ($customFieldErrors) { + return response()->apiError($customFieldErrors, 422); } // if adhoc set convert to sql ready boolean value 1 or 0 @@ -373,6 +383,7 @@ protected function createOrderFromRequest(CreateOrderRequest $request) // create the order $order = $this->createOrder($input); + OrderCustomFields::apply($order, (array) $request->input('custom_fields', [])); // if it's integrated vendor order apply to meta if ($integratedVendorOrder) { @@ -385,8 +396,8 @@ protected function createOrderFromRequest(CreateOrderRequest $request) // load required relations $order->load(['trackingNumber', 'trackingStatuses', 'driverAssigned', 'vehicleAssigned', 'purchaseRate.serviceQuote.items', 'customer', 'facilitator']); - // Determine if order should be dispatched on creation - $shouldDispatch = $request->boolean('dispatch') && $integratedVendorOrder === null; + // Determine if order should be dispatched on creation, unless its config turns dispatch off + $shouldDispatch = $request->boolean('dispatch') && $integratedVendorOrder === null && $orderConfig->allowsDispatch(); $this->dispatchFinalizeApiOrderCreation( $order->uuid, @@ -715,7 +726,7 @@ protected function orderCreateInputFromRequest(Request $request): array { return $request->only([ 'internal_id', 'payload', 'service_quote', 'purchase_rate', - 'adhoc', 'adhoc_distance', 'pod_method', 'pod_required', + 'adhoc', 'adhoc_distance', 'adhoc_strategy', 'required_vehicle_type', 'pod_method', 'pod_required', 'scheduled_at', 'status', 'meta', 'notes', // Orchestrator constraints 'time_window_start', 'time_window_end', @@ -726,7 +737,7 @@ protected function orderCreateInputFromRequest(Request $request): array protected function orderUpdateInputFromRequest(Request $request): array { return $request->only([ - 'internal_id', 'payload', 'adhoc', 'adhoc_distance', + 'internal_id', 'payload', 'adhoc', 'adhoc_distance', 'adhoc_strategy', 'required_vehicle_type', 'pod_method', 'pod_required', 'scheduled_at', 'meta', 'type', 'status', 'notes', // Orchestrator constraints 'time_window_start', 'time_window_end', @@ -769,7 +780,15 @@ public function query(Request $request) { set_time_limit(180); - $results = Order::queryWithRequest($request, function (&$query, $request) { + // A driver listing orders near them sees only the adhoc orders they could take. That + // depends on live offers, so the list isn't cached. + $offerDriver = $this->nearbyDriverUuid($request); + + $results = Order::queryWithRequest($request, function (&$query, $request) use ($offerDriver) { + if ($offerDriver) { + AdhocOfferListing::apply($query, $offerDriver, Company::currentSession()); + } + $query->with(['trackingStatuses', 'driverAssigned', 'vehicleAssigned', 'customer', 'facilitator']); $query->where('company_uuid', session('company')); $query->whereNotNull('payload_uuid'); @@ -942,7 +961,11 @@ public function query(Request $request) } } } - }); + }, (bool) $offerDriver); + + if ($offerDriver) { + AdhocOfferListing::attach($results, $offerDriver); + } return OrderResource::collection($results); } @@ -1054,6 +1077,10 @@ public function dispatchOrder(string $id) return $this->apiError('Order has already been dispatched!'); } + if ($order->currentConfig()?->allowsDispatch() === false) { + return $this->apiError('Orders of this type are not dispatched.'); + } + $order->dispatch(); $order->insertDispatchActivity(); @@ -1131,9 +1158,16 @@ public function startOrder(string $id, Request $request) return response()->apiError('Order has already started.'); } - // if the order is adhoc and the parameter of `assign` is set with a valid driver id, assign the driver and continue + if ($order->status === 'canceled') { + return response()->apiError('This order was canceled.', 409); + } + + // An adhoc order goes to the first driver who claims it; everyone after is refused. if ($order->adhoc && $assignAdhocDriver && Str::startsWith($assignAdhocDriver, 'driver_')) { - $order->assignDriver($assignAdhocDriver, true); + $refusal = $this->claimAdhocOrder($order, $assignAdhocDriver); + if ($refusal) { + return $refusal; + } } /** @var \Fleetbase\Models\Driver */ @@ -1194,6 +1228,131 @@ public function startOrder(string $id, Request $request) return $this->updateActivity($order, $updateActivityRequest); } + /** + * Claim an adhoc order for a driver of its company who is online. The claim is one + * conditional update, so of two drivers accepting at once only one gets the order. Returns + * the refusal, or null once the driver holds the order. + */ + protected function claimAdhocOrder(Order $order, string $driverId): mixed + { + $driver = $this->findAdhocDriver($driverId); + if (!$driver || !$this->driverServesCompany($driver, $order->company_uuid)) { + return response()->apiError('Driver not found.', 404); + } + + // A driver signed in to the app may only accept for themselves. + $signedIn = $this->signedInDriver($order->company_uuid); + if ($signedIn && $signedIn->uuid !== $driver->uuid) { + return response()->apiError('You can only accept orders for yourself.', 403); + } + + if ($order->driver_assigned_uuid === $driver->uuid) { + return null; + } + + if (!$driver->online) { + return response()->apiError('Go online to accept orders.', 422); + } + + // The order's dispatch strategy decides who may accept it, for example only the driver + // with the open offer. + if (!AdhocDispatch::for($order)->accept($order, $driver)) { + return response()->apiError('This order is no longer offered to you.', 409); + } + + $claimed = Order::withoutGlobalScopes() + ->where('uuid', $order->uuid) + ->whereNull('driver_assigned_uuid') + ->where('status', '!=', 'canceled') + ->where(fn ($query) => $query->whereNull('started')->orWhere('started', 0)) + ->update(['driver_assigned_uuid' => $driver->uuid]); + + if (!$claimed) { + return response()->apiError('This order was taken by another driver.', 409); + } + + // The claim saved the driver directly; assigning again runs the order observer for it. + $order->driver_assigned_uuid = null; + $order->assignDriver($driver, true); + + // Everyone else's offer is withdrawn. + OrderOffers::claimed($order, $driver); + + return null; + } + + /** + * Turn down an adhoc order. It isn't offered to the driver again, and with one-at-a-time + * offers it goes to the next driver. + */ + public function declineOrder(string $id, Request $request) + { + try { + $order = $this->findOrder($id); + } catch (ModelNotFoundException $exception) { + return response()->apiError('Order resource not found.', 404); + } + + $driver = $this->signedInDriver($order->company_uuid); + $named = $request->input('driver'); + if (!$driver && is_string($named) && Str::startsWith($named, 'driver_')) { + $driver = $this->findAdhocDriver($named); + $driver = $driver && $this->driverServesCompany($driver, $order->company_uuid) ? $driver : null; + } + if (!$driver) { + return response()->apiError('Driver not found.', 404); + } + + if (!$order->adhoc || $order->driver_assigned_uuid || !AdhocDispatch::for($order)->decline($order, $driver)) { + return response()->apiError('This order is not offered to you.', 409); + } + + return response()->json(['status' => 'declined', 'order' => $order->public_id]); + } + + /** + * The driver whose surroundings are asked for with `nearby=driver_…`, if they belong to this company. + */ + protected function nearbyDriverUuid(Request $request): ?string + { + $nearby = $request->input('nearby'); + if (!is_string($nearby) || !Str::startsWith($nearby, 'driver_')) { + return null; + } + + return Driver::withoutGlobalScopes()->where('public_id', $nearby)->where('company_uuid', session('company'))->whereNull('deleted_at')->value('uuid'); + } + + protected function findAdhocDriver(string $publicId): ?Driver + { + return Driver::withoutGlobalScopes()->where('public_id', $publicId)->whereNull('deleted_at')->first(); + } + + /** + * Whether the driver works for the company, directly or through their user. + */ + protected function driverServesCompany(Driver $driver, ?string $companyUuid): bool + { + if ($driver->company_uuid === $companyUuid) { + return true; + } + + return $driver->user_uuid && User::where('uuid', $driver->user_uuid)->value('company_uuid') === $companyUuid; + } + + /** + * The driver profile of the user whose token signed this request, if they drive for the company. + */ + protected function signedInDriver(?string $companyUuid): ?Driver + { + $userUuid = session('user'); + if (!$userUuid) { + return null; + } + + return Driver::withoutGlobalScopes()->where('user_uuid', $userUuid)->where('company_uuid', $companyUuid)->whereNull('deleted_at')->first(); + } + /** * Update an order activity. * @@ -1255,11 +1414,22 @@ public function updateActivity($id, Request $request) // Get the order config $orderConfig = $order->config(); - $activity = $request->array('activity'); + $activity = $request->inputArray('activity'); if (!Utils::isActivity($activity)) { $activity = new Activity($activity, $order->getConfigFlow()); } + // The order's config decides whether the update is allowed: a finished order, a step the + // config's strict transitions don't permit, dispatch on a config that turns it off, or a + // step that needs proof of delivery without it. With strict transitions the server's + // activity definition replaces the one sent. + if ($orderConfig && !($activity->is('dispatched') && $skipDispatch)) { + [$activity, $refusal] = $orderConfig->authorizeTransition($order, $activity, $proof); + if ($refusal) { + return response()->apiError($refusal, 422); + } + } + // if we're going to skip the dispatch get the next activity status and flow and continue if (Utils::isActivity($activity) && $activity->is('dispatched') && $skipDispatch) { $activity = $orderConfig->getStartedActivity(); diff --git a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php index 17518b775..5c8805f1d 100644 --- a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php +++ b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php @@ -4,6 +4,7 @@ use Fleetbase\FleetOps\Http\Requests\QueryServiceQuotesRequest; use Fleetbase\FleetOps\Http\Resources\v1\ServiceQuote as ServiceQuoteResource; +use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Entity; use Fleetbase\FleetOps\Models\IntegratedVendor; use Fleetbase\FleetOps\Models\Payload; @@ -11,8 +12,11 @@ use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Models\ServiceQuoteItem; use Fleetbase\FleetOps\Models\ServiceRate; +use Fleetbase\FleetOps\Models\Vehicle; +use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Controllers\Controller; +use Fleetbase\LaravelMysqlSpatial\Types\Point as SpatialPoint; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; @@ -168,22 +172,23 @@ function ($query) use ($request) { */ public function queryFromPreliminary(QueryServiceQuotesRequest $request) { - $facilitator = $request->input('facilitator'); - $scheduledAt = $request->input('scheduled_at'); - $service = $request->input('service', 'all'); // the specific service rate to query - defaults to `all` - $serviceType = $request->input('service_type'); // the specific type of service rate to query - $isCashOnDelivery = $request->has('cod'); - $currency = $this->currencyFromRequest($request); - $totalDistance = $request->input('distance'); - $totalTime = $request->input('time'); - $preliminaryData = $this->preliminaryDataFromRequest($request); - $pickup = $preliminaryData['pickup']; - $dropoff = $preliminaryData['dropoff']; - $return = $preliminaryData['return']; - $waypoints = $preliminaryData['waypoints']; - $entities = $preliminaryData['entities']; - $single = $request->boolean('single'); - $isRouteOptimized = $request->boolean('is_route_optimized', true); + $facilitator = $request->input('facilitator'); + $scheduledAt = $request->input('scheduled_at'); + $service = $request->input('service', 'all'); // the specific service rate to query - defaults to `all` + $serviceType = $request->input('service_type'); // the specific type of service rate to query + $isCashOnDelivery = $request->has('cod'); + $currency = $this->currencyFromRequest($request); + $totalDistance = $request->input('distance'); + $totalTime = $request->input('time'); + $preliminaryData = $this->preliminaryDataFromRequest($request); + $pickup = $preliminaryData['pickup']; + $this->availabilityFrom = $this->availabilityPoint($request, $pickup); + $dropoff = $preliminaryData['dropoff']; + $return = $preliminaryData['return']; + $waypoints = $preliminaryData['waypoints']; + $entities = $preliminaryData['entities']; + $single = $request->boolean('single'); + $isRouteOptimized = $request->boolean('is_route_optimized', true); $requestId = $this->generateServiceQuoteRequestId(); $serviceQuotes = []; @@ -342,7 +347,8 @@ protected function generateServiceQuoteRequestId(): string protected function createPlaceFromMixed(mixed $value): Place { - return Place::createFromMixed($value); + // A preview must not leave a place behind for every price a customer checks. + return Place::createFromMixed($value, [], !$this->previewOnly); } protected function findPlaceByPublicId(string $publicId): ?Place @@ -438,9 +444,67 @@ protected function serviceQuoteResource(ServiceQuote $serviceQuote) protected function serviceQuoteResourceCollection(iterable $serviceQuotes) { + if ($this->availabilityFrom) { + foreach ($serviceQuotes as $quote) { + $this->addAvailability($quote, $this->availabilityFrom); + } + } + return ServiceQuoteResource::collection($serviceQuotes); } + /** + * Where the request asked how soon a vehicle could come (`availability`). + */ + protected ?SpatialPoint $availabilityFrom = null; + + /** + * The pickup to measure availability from, when the request asked for it with coordinates. + */ + protected function availabilityPoint(Request $request, mixed $pickup): ?SpatialPoint + { + return $request->boolean('availability') && is_array($pickup) && Utils::isCoordinates($pickup) ? Utils::getPointFromMixed($pickup) : null; + } + + /** + * Average speed in metres per second used to turn the nearest vehicle's distance into a pickup + * ETA, unless `fleetops.availability.pickup_speed` sets another. + */ + public const PICKUP_SPEED = 7.0; + + /** + * Add the most seats a vehicle of the quote's service type has, and how soon its nearest free + * driver could reach the pickup, in seconds. Both are null when the company has no such + * vehicle; the ETA is a straight-line estimate. + */ + protected function addAvailability(ServiceQuote $quote, SpatialPoint $pickup): void + { + $class = data_get($quote, 'serviceRate.service_type'); + $company = $quote->company_uuid; + + $seatingCapacity = $class ? Vehicle::where('company_uuid', $company)->whereRaw('LOWER(type) = ?', [strtolower($class)])->max('seating_capacity') : null; + + $drivers = Driver::query() + ->withoutGlobalScopes() + ->where(['status' => 'available', 'online' => 1]) + ->whereNull('deleted_at') + ->whereNotNull('location') + ->distanceSphere('location', $pickup, 15000) + ->distanceSphereValue('location', $pickup) + ->orderBy('distance'); + DriverMatching::inCompany($drivers, $company); + DriverMatching::notBusy($drivers, $company); + DriverMatching::forVehicleClass($drivers, $class); + $nearest = $drivers->first(); + + $speed = (float) config('fleetops.availability.pickup_speed', self::PICKUP_SPEED) ?: self::PICKUP_SPEED; + + $quote->availability = [ + 'seating_capacity' => $seatingCapacity ? (int) $seatingCapacity : null, + 'pickup_eta' => $nearest ? (int) round(60 + (float) $nearest->distance / $speed) : null, + ]; + } + protected function preliminaryDataFromRequest(Request $request): array { return [ diff --git a/server/src/Http/Controllers/Api/v1/VehicleController.php b/server/src/Http/Controllers/Api/v1/VehicleController.php index 387d8a2d2..5c419a0aa 100644 --- a/server/src/Http/Controllers/Api/v1/VehicleController.php +++ b/server/src/Http/Controllers/Api/v1/VehicleController.php @@ -369,7 +369,7 @@ private function processVehicleGeofenceCrossings(Vehicle $vehicle, Point $newLoc $dwellMinutes = null; if ($state && $state->entered_at) { - $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now()); + $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now(), true); } DB::table('vehicle_geofence_states') diff --git a/server/src/Http/Controllers/Internal/v1/ContactController.php b/server/src/Http/Controllers/Internal/v1/ContactController.php index ecfdf21fd..b72d236bf 100644 --- a/server/src/Http/Controllers/Internal/v1/ContactController.php +++ b/server/src/Http/Controllers/Internal/v1/ContactController.php @@ -77,7 +77,7 @@ public function afterSave(Request $request, Contact $contact) $this->sendCustomerPortalWelcomeEmail($contact); } - $customFieldValues = $request->array('contact.custom_field_values'); + $customFieldValues = $request->inputArray('contact.custom_field_values'); if ($customFieldValues) { $contact->syncCustomFieldValues($customFieldValues); } @@ -175,7 +175,7 @@ public function convertToVendor(Request $request, string $id) public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('contacts-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new ContactExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/DeviceController.php b/server/src/Http/Controllers/Internal/v1/DeviceController.php index ce969fbc2..ccc3f3b87 100644 --- a/server/src/Http/Controllers/Internal/v1/DeviceController.php +++ b/server/src/Http/Controllers/Internal/v1/DeviceController.php @@ -43,7 +43,7 @@ class DeviceController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('devices-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new DeviceExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/DriverController.php b/server/src/Http/Controllers/Internal/v1/DriverController.php index f121aeb83..8561c5166 100644 --- a/server/src/Http/Controllers/Internal/v1/DriverController.php +++ b/server/src/Http/Controllers/Internal/v1/DriverController.php @@ -122,7 +122,7 @@ function (&$request, &$input) { }, function ($request, &$driver) { $driver->load(['user']); - $customFieldValues = $request->array('driver.custom_field_values'); + $customFieldValues = $request->inputArray('driver.custom_field_values'); if ($customFieldValues) { $driver->syncCustomFieldValues($customFieldValues); } @@ -191,7 +191,7 @@ function ($request, &$driver) { } $driver->setHidden(['user']); - $customFieldValues = $request->array('driver.custom_field_values'); + $customFieldValues = $request->inputArray('driver.custom_field_values'); if ($customFieldValues) { $driver->syncCustomFieldValues($customFieldValues); } @@ -395,7 +395,7 @@ public function avatars() public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('drivers-' . date('Y-m-d-H:i')) . '.' . $format); return static::downloadExport(new DriverExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/EquipmentController.php b/server/src/Http/Controllers/Internal/v1/EquipmentController.php index b11c5d410..11ae3e1a0 100644 --- a/server/src/Http/Controllers/Internal/v1/EquipmentController.php +++ b/server/src/Http/Controllers/Internal/v1/EquipmentController.php @@ -27,7 +27,7 @@ class EquipmentController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('equipment-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new EquipmentExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/FleetController.php b/server/src/Http/Controllers/Internal/v1/FleetController.php index e66c1e1fe..adf585e74 100644 --- a/server/src/Http/Controllers/Internal/v1/FleetController.php +++ b/server/src/Http/Controllers/Internal/v1/FleetController.php @@ -32,7 +32,7 @@ class FleetController extends FleetOpsController */ public function afterSave(Request $request, Fleet $fleet) { - $customFieldValues = $request->array('fleet.custom_field_values'); + $customFieldValues = $request->inputArray('fleet.custom_field_values'); if ($customFieldValues) { $fleet->syncCustomFieldValues($customFieldValues); } @@ -47,7 +47,7 @@ public function afterSave(Request $request, Fleet $fleet) public static function onQueryRecord($query, $request): void { if ($request->has('excludeDriverJobs')) { - $excludeJobs = $request->array('excludeDriverJobs'); + $excludeJobs = $request->inputArray('excludeDriverJobs'); $query->with('drivers', function ($query) use ($excludeJobs) { $query->with('jobs', function ($query) use ($excludeJobs) { if (is_array($excludeJobs)) { @@ -97,7 +97,7 @@ function ($q) { public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('fleets-' . date('Y-m-d-H:i')) . '.' . $format); return static::downloadExport(new FleetExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php b/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php index df99e25e3..c31b2e962 100644 --- a/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php +++ b/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php @@ -59,7 +59,7 @@ public function testCredentials(Request $request, string $provider): JsonRespons $result = $this->fuelProviderService->testCredentials( $provider, - $request->array('credentials'), + $request->inputArray('credentials'), $request->input('environment', 'production') ); @@ -89,7 +89,7 @@ public function sync(Request $request, string $id): JsonResponse $async = $request->boolean('async', true); $from = $request->input('from') ? Carbon::parse($request->input('from'))->startOfDay() : null; $to = $request->input('to') ? Carbon::parse($request->input('to'))->endOfDay() : null; - $options = $request->array('options', []); + $options = $request->inputArray('options', []); $syncRun = $this->fuelProviderService->createSyncRun($connection, $from, $to, $async ? 'queued' : 'running'); if ($async) { diff --git a/server/src/Http/Controllers/Internal/v1/FuelReportController.php b/server/src/Http/Controllers/Internal/v1/FuelReportController.php index c2e8db2bf..ebec4cb41 100644 --- a/server/src/Http/Controllers/Internal/v1/FuelReportController.php +++ b/server/src/Http/Controllers/Internal/v1/FuelReportController.php @@ -27,7 +27,7 @@ class FuelReportController extends FleetOpsController * * Reads the custom field values from the payload the base controller already extracted * rather than from the raw request: Ember Data sends the resource under a camelCase root - * (`fuelReport`), so `$request->array('fuel_report.custom_field_values')` was always empty and no + * (`fuelReport`), so `$request->inputArray('fuel_report.custom_field_values')` was always empty and no * custom field value was ever persisted for this resource. */ public function afterSave(Request $request, FuelReport $fuelReport, array $input = []) @@ -46,7 +46,7 @@ public function afterSave(Request $request, FuelReport $fuelReport, array $input public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('fuel_report-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new FuelReportExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php b/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php index 223c82c75..5836a160c 100644 --- a/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php +++ b/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php @@ -78,7 +78,7 @@ protected function syncAnswersFromRequest(Request $request, InspectionSubmission * The first of the given keys that carries a list. * * The console posts a record under its resource name and the app posts it - * flat, so both spellings are read. `Request::array()` arrived in Laravel + * flat, so both spellings are read. `Request::inputArray()` arrived in Laravel * 11 and this runs on 10, where calling it is a BadMethodCallException. * * @return array diff --git a/server/src/Http/Controllers/Internal/v1/IssueController.php b/server/src/Http/Controllers/Internal/v1/IssueController.php index bdd9fb98c..e235beaf4 100644 --- a/server/src/Http/Controllers/Internal/v1/IssueController.php +++ b/server/src/Http/Controllers/Internal/v1/IssueController.php @@ -42,12 +42,12 @@ public function afterSave(Request $request, Issue $issue) } } - $customFieldValues = $request->array('issue.custom_field_values'); + $customFieldValues = $request->inputArray('issue.custom_field_values'); if ($customFieldValues) { $issue->syncCustomFieldValues($customFieldValues); } - $uploads = $request->array('issue.files'); + $uploads = $request->inputArray('issue.files'); if ($uploads) { $this->filesForUploads($uploads)->each(function (File $file) use ($issue) { $file->setKey($issue); @@ -346,7 +346,7 @@ protected function formatChangeDescription(string $field, $from, $to): string public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('issue-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new IssueExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/LiveController.php b/server/src/Http/Controllers/Internal/v1/LiveController.php index 690960baf..0e415ce96 100644 --- a/server/src/Http/Controllers/Internal/v1/LiveController.php +++ b/server/src/Http/Controllers/Internal/v1/LiveController.php @@ -123,7 +123,7 @@ function ($q) { */ public function orders(Request $request) { - $exclude = $request->array('exclude'); + $exclude = $request->inputArray('exclude'); $active = $request->boolean('active'); $unassigned = $request->boolean('unassigned'); diff --git a/server/src/Http/Controllers/Internal/v1/MaintenanceController.php b/server/src/Http/Controllers/Internal/v1/MaintenanceController.php index 49e1ca3e3..122518b0d 100644 --- a/server/src/Http/Controllers/Internal/v1/MaintenanceController.php +++ b/server/src/Http/Controllers/Internal/v1/MaintenanceController.php @@ -42,7 +42,7 @@ class MaintenanceController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('maintenances-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new MaintenanceExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php b/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php index 083ef8aad..68a2f7042 100644 --- a/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php +++ b/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php @@ -49,7 +49,7 @@ class MaintenanceScheduleController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('maintenance-schedules-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new MaintenanceScheduleExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/MetricsController.php b/server/src/Http/Controllers/Internal/v1/MetricsController.php index 4d3b374fd..3ae99059b 100644 --- a/server/src/Http/Controllers/Internal/v1/MetricsController.php +++ b/server/src/Http/Controllers/Internal/v1/MetricsController.php @@ -30,7 +30,7 @@ public function all(Request $request) { $start = $request->date('start'); $end = $request->date('end'); - $discover = $request->array('discover', []); + $discover = $request->inputArray('discover', []); try { $data = $this->metricsForCompany($request->user()->company, $start, $end)->with($discover)->get(); diff --git a/server/src/Http/Controllers/Internal/v1/OrderConfigController.php b/server/src/Http/Controllers/Internal/v1/OrderConfigController.php index fc99602be..f6340ea92 100644 --- a/server/src/Http/Controllers/Internal/v1/OrderConfigController.php +++ b/server/src/Http/Controllers/Internal/v1/OrderConfigController.php @@ -6,8 +6,16 @@ use Fleetbase\FleetOps\Http\Controllers\FleetOpsController; use Fleetbase\FleetOps\Http\Requests\Internal\CreateOrderConfigRequest; use Fleetbase\FleetOps\Models\OrderConfig; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\Action; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigActions; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; +use Fleetbase\Models\Company; +use Fleetbase\Support\Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Str; class OrderConfigController extends FleetOpsController { @@ -72,6 +80,50 @@ public function deleteRecord($id, Request $request) return $this->deletedResource($orderConfig); } + /** + * The templates, policies, actions and trigger events order configs can use, for the console. + */ + public function capabilities() + { + return response()->json([ + 'templates' => OrderConfigTemplates::describe(), + 'policies' => OrderConfigPolicies::describe(), + 'actions' => OrderConfigActions::describe(), + 'events' => OrderConfigTriggers::EVENTS, + 'placeholders' => Action::PLACEHOLDERS, + ]); + } + + /** + * Create a config from a template, under a name of the company's choosing. + */ + public function createFromTemplate(Request $request) + { + $template = (string) $request->input('template'); + $name = trim((string) $request->input('name')); + if (!OrderConfigTemplates::has($template)) { + return $this->errorResponse('Choose an order config template.'); + } + if ($name === '') { + return $this->errorResponse('Give the order config a name.'); + } + + $company = $this->currentCompany(); + if (!$company) { + return $this->errorResponse('No organization in session.'); + } + if (OrderConfig::where('company_uuid', $company->uuid)->where(fn ($query) => $query->where('name', $name)->orWhere('key', Str::slug($name)))->exists()) { + return $this->errorResponse('An order config with this name already exists.'); + } + + return $this->createdOrderConfigResource(OrderConfigTemplates::create($template, $company, $name)); + } + + protected function currentCompany(): ?Company + { + return Auth::getCompany(); + } + protected function findOrderConfig(string $id): ?OrderConfig { return OrderConfig::where('uuid', $id)->first(); diff --git a/server/src/Http/Controllers/Internal/v1/OrderController.php b/server/src/Http/Controllers/Internal/v1/OrderController.php index 2bbe6420d..866887b4c 100644 --- a/server/src/Http/Controllers/Internal/v1/OrderController.php +++ b/server/src/Http/Controllers/Internal/v1/OrderController.php @@ -97,18 +97,18 @@ class OrderController extends FleetOpsController */ public function onAfterUpdate($request, $order) { - $uploads = $request->array('order.files'); + $uploads = $request->inputArray('order.files'); if ($uploads) { $order->attachFiles($uploads); } - $waypoints = $request->array('order.payload.waypoints'); + $waypoints = $request->inputArray('order.payload.waypoints'); if ($waypoints) { $order->loadMissing('payload'); $order->payload->updateWaypoints($waypoints); } - $customFieldValues = $request->array('order.custom_field_values'); + $customFieldValues = $request->inputArray('order.custom_field_values'); if ($customFieldValues) { $order->syncCustomFieldValues($customFieldValues); } @@ -310,7 +310,7 @@ public function editOrderRoute(string $id, Request $request) $pickup = $request->input('pickup'); $dropoff = $request->input('dropoff'); $return = $request->input('return'); - $waypoints = $request->array('waypoints', []); + $waypoints = $request->inputArray('waypoints', []); $hasPickupInput = $request->exists('pickup'); $hasDropoffInput = $request->exists('dropoff'); $hasReturnInput = $request->exists('return'); @@ -957,26 +957,17 @@ public function updateActivity(string $id, Request $request) $proof = $request->input('proof'); $bypassProof = $request->boolean('bypass_proof'); - $activity = $request->array('activity'); + $activity = $request->inputArray('activity'); $activity = new Activity($activity, $order->getConfigFlow()); - // Configs with strict transitions only accept a configured child of the current - // activity, and the server-side activity definition replaces the client payload. + // The order's config decides whether the update is allowed. Operators may still correct a + // finished order, so a terminal status alone doesn't refuse it here. $orderConfig = $order->config(); - if ($orderConfig && $orderConfig->hasStrictTransitions()) { - $targetCode = $activity->get('code'); - $configured = $targetCode ? $orderConfig->getActivityByCode($targetCode) : null; - if (!$configured || !$orderConfig->canTransition($order->status, $targetCode)) { - return response()->error('This activity is not a permitted next step for the order.', 422); + if ($orderConfig) { + [$activity, $refusal] = $orderConfig->authorizeTransition($order, $activity, $proof, $bypassProof, true); + if ($refusal) { + return response()->error($refusal, 422); } - - $activity = $configured; - } - - $requiresProof = Utils::isActivity($activity) - && ($activity->get('require_pod') || ($activity->completesOrder() && $order->pod_required)); - if ($requiresProof && !$proof && !$bypassProof) { - return response()->error('Proof of delivery is required for this activity or must be explicitly bypassed.', 422); } // Handle pickup/dropoff order activity update as normal @@ -1932,7 +1923,7 @@ protected function proofsForSubject(Order $order, Order|Waypoint|Entity $subject public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('order-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadOrderExport($selections, $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/PartController.php b/server/src/Http/Controllers/Internal/v1/PartController.php index dd0df7ef9..0de693e35 100644 --- a/server/src/Http/Controllers/Internal/v1/PartController.php +++ b/server/src/Http/Controllers/Internal/v1/PartController.php @@ -27,7 +27,7 @@ class PartController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('parts-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new PartExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/PlaceController.php b/server/src/Http/Controllers/Internal/v1/PlaceController.php index 88b6d0306..071a54f71 100644 --- a/server/src/Http/Controllers/Internal/v1/PlaceController.php +++ b/server/src/Http/Controllers/Internal/v1/PlaceController.php @@ -28,7 +28,7 @@ class PlaceController extends FleetOpsController */ public function afterSave(Request $request, Place $place) { - $customFieldValues = $request->array('place.custom_field_values'); + $customFieldValues = $request->inputArray('place.custom_field_values'); if ($customFieldValues) { $this->syncCustomFieldValues($place, $customFieldValues); } @@ -86,7 +86,7 @@ public function geocode(ExportRequest $request) public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('places-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new PlaceExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/PositionController.php b/server/src/Http/Controllers/Internal/v1/PositionController.php index 0d6865e9c..9e798150d 100644 --- a/server/src/Http/Controllers/Internal/v1/PositionController.php +++ b/server/src/Http/Controllers/Internal/v1/PositionController.php @@ -167,7 +167,7 @@ private function calculateMetrics($positions) } } else { if ($dwellStart !== null) { - $dwellDuration = $previousPosition->created_at->diffInSeconds($dwellStart); + $dwellDuration = (int) $previousPosition->created_at->diffInSeconds($dwellStart, true); if ($dwellDuration >= $dwellThreshold) { $dwellTimes[] = [ 'start' => $dwellStart->toDateTimeString(), @@ -181,7 +181,7 @@ private function calculateMetrics($positions) // Calculate acceleration if ($previousSpeed !== null) { - $timeDiff = $position->created_at->diffInSeconds($previousPosition->created_at); + $timeDiff = (int) $position->created_at->diffInSeconds($previousPosition->created_at, true); if ($timeDiff > 0) { $acceleration = abs($speed - $previousSpeed) / $timeDiff; if ($acceleration > $accelerationThreshold) { @@ -207,7 +207,7 @@ private function calculateMetrics($positions) // Calculate total duration $firstPosition = $positions->first(); $lastPosition = $positions->last(); - $totalDuration = $lastPosition->created_at->diffInSeconds($firstPosition->created_at); + $totalDuration = (int) $lastPosition->created_at->diffInSeconds($firstPosition->created_at, true); return [ 'total_distance' => round($totalDistance / 1000, 2), // Convert to km diff --git a/server/src/Http/Controllers/Internal/v1/RadarController.php b/server/src/Http/Controllers/Internal/v1/RadarController.php index 9cd1e7961..7f46fdf5f 100644 --- a/server/src/Http/Controllers/Internal/v1/RadarController.php +++ b/server/src/Http/Controllers/Internal/v1/RadarController.php @@ -861,7 +861,7 @@ protected function snoozeMinutes(Request $request): ?int if (!$until || $until->lte($this->now())) { return null; } - $minutes = (int) ceil($this->now()->diffInMinutes($until)); + $minutes = (int) $this->now()->diffInMinutes($until, true); return $minutes >= 1 && $minutes <= $max ? $minutes : null; } diff --git a/server/src/Http/Controllers/Internal/v1/SensorController.php b/server/src/Http/Controllers/Internal/v1/SensorController.php index 8ba62feeb..b9b6b2c5b 100644 --- a/server/src/Http/Controllers/Internal/v1/SensorController.php +++ b/server/src/Http/Controllers/Internal/v1/SensorController.php @@ -25,7 +25,7 @@ class SensorController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('sensors-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new SensorExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php b/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php index 36926e45a..82249ff6c 100644 --- a/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php +++ b/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php @@ -25,7 +25,7 @@ class ServiceAreaController extends FleetOpsController * * Reads the custom field values from the payload the base controller already extracted * rather than from the raw request: Ember Data sends the resource under a camelCase root - * (`serviceArea`), so `$request->array('service_area.custom_field_values')` was always empty and no + * (`serviceArea`), so `$request->inputArray('service_area.custom_field_values')` was always empty and no * custom field value was ever persisted for this resource. */ public function afterSave(Request $request, ServiceArea $serviceArea, array $input = []) @@ -44,7 +44,7 @@ public function afterSave(Request $request, ServiceArea $serviceArea, array $inp public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('service-areas-' . date('Y-m-d-H:i')) . '.' . $format); return static::downloadExport(new ServiceAreaExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/ServiceRateController.php b/server/src/Http/Controllers/Internal/v1/ServiceRateController.php index 577bc2316..fe786fb4e 100644 --- a/server/src/Http/Controllers/Internal/v1/ServiceRateController.php +++ b/server/src/Http/Controllers/Internal/v1/ServiceRateController.php @@ -129,7 +129,7 @@ protected function getServicableForWaypoints(Collection $waypoints, \Closure $qu public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('contacts-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new ServiceRateExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/SettingController.php b/server/src/Http/Controllers/Internal/v1/SettingController.php index dad37acd8..ae68ab485 100644 --- a/server/src/Http/Controllers/Internal/v1/SettingController.php +++ b/server/src/Http/Controllers/Internal/v1/SettingController.php @@ -4,6 +4,7 @@ use Fleetbase\FleetOps\Jobs\DispatchTelematicsRetentionJobs; use Fleetbase\FleetOps\Orchestration\Support\OrchestratorSettings; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Fleetbase\FleetOps\Support\Routing\HostPolicy; use Fleetbase\FleetOps\Support\Routing\OsrmConnection; use Fleetbase\FleetOps\Support\Routing\RoutingEngineResolver; @@ -137,7 +138,7 @@ public function getDriverOnboardSettings($companyId = null) */ public function savedDriverOnboardSettings(Request $request) { - $driverOnboardSettings = $request->array('driverOnboardSettings', []); + $driverOnboardSettings = $request->inputArray('driverOnboardSettings', []); $driverOnboardSettings['companyId'] = session('company'); if (empty($driverOnboardSettings['enableDriverOnboardFromApp'])) { @@ -154,7 +155,7 @@ public function savedDriverOnboardSettings(Request $request) public function saveCustomerEnabledOrderConfigs(Request $request) { - $enabledOrderConfigs = array_values($request->array('enabledOrderConfigs')); + $enabledOrderConfigs = array_values($request->inputArray('enabledOrderConfigs')); $this->configureCompanySetting('fleet-ops.customer-enabled-order-configs', $enabledOrderConfigs); return response()->json($enabledOrderConfigs); @@ -169,7 +170,7 @@ public function getCustomerEnabledOrderConfigs() public function saveCustomerPortalPaymentConfig(Request $request) { - $paymentsConfig = $request->array('paymentsConfig'); + $paymentsConfig = $request->inputArray('paymentsConfig'); $this->configureCompanySetting('fleet-ops.customer-payments-configs', $paymentsConfig); return response()->json($paymentsConfig); @@ -248,6 +249,58 @@ public function getNotificationSettings() ]); } + /** + * How adhoc orders are offered by default: the ping radius, the strategy and the offer + * timeout, kept in the company's Fleet-Ops options. Orders and order configs can override them. + */ + public function getAdhocDispatchSettings() + { + $company = $this->currentCompany(); + + return response()->json([ + 'adhoc_distance' => (int) ($company?->getOption('fleetops.adhoc_distance') ?? 6000), + 'adhoc_strategy' => AdhocDispatch::companyDefault($company), + 'adhoc_offer_timeout' => (int) ($company?->getOption('fleetops.adhoc_offer_timeout') ?? AdhocDispatch::OFFER_TIMEOUT), + 'strategies' => AdhocDispatch::describe(), + ]); + } + + public function saveAdhocDispatchSettings(Request $request) + { + $distance = $request->input('adhoc_distance'); + $strategy = $request->input('adhoc_strategy'); + $timeout = $request->input('adhoc_offer_timeout'); + if (!is_numeric($distance) || $distance < 100 || $distance > 100000) { + return response()->error('Choose a ping radius between 100 m and 100 km.', 422); + } + if (!AdhocDispatch::has($strategy)) { + return response()->error('Choose a dispatch strategy.', 422); + } + if (!is_numeric($timeout) || $timeout < AdhocDispatch::MIN_OFFER_TIMEOUT || $timeout > AdhocDispatch::MAX_OFFER_TIMEOUT) { + return response()->error('Choose an offer time between ' . AdhocDispatch::MIN_OFFER_TIMEOUT . ' and ' . AdhocDispatch::MAX_OFFER_TIMEOUT . ' seconds.', 422); + } + + $company = $this->currentCompany(); + if (!$company) { + return response()->error('No organization found.', 404); + } + + $company->setOption('fleetops.adhoc_distance', (int) $distance); + $company->setOption('fleetops.adhoc_strategy', $strategy); + $company->setOption('fleetops.adhoc_offer_timeout', (int) $timeout); + $company->save(); + + return response()->json(['status' => 'ok', 'message' => 'Dispatch settings saved.']); + } + + /** + * The adhoc dispatch strategies an order, order config or company can use. + */ + public function getAdhocDispatchStrategies() + { + return response()->json(['strategies' => AdhocDispatch::describe()]); + } + /** * Save routing settings. * diff --git a/server/src/Http/Controllers/Internal/v1/TelematicController.php b/server/src/Http/Controllers/Internal/v1/TelematicController.php index 4f056da5b..93b8ff7f5 100644 --- a/server/src/Http/Controllers/Internal/v1/TelematicController.php +++ b/server/src/Http/Controllers/Internal/v1/TelematicController.php @@ -56,7 +56,7 @@ public function __construct(TelematicService $service, TelematicProviderRegistry public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('telematics-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new TelematicExport($selections), $fileName); @@ -108,7 +108,7 @@ public function testConnection(Request $request, string $id): JsonResponse #[SkipAuthorizationCheck] public function testCredentials(Request $request, string $key): JsonResponse { - $credentials = $request->array('credentials', []); + $credentials = $request->inputArray('credentials', []); $async = $request->input('async', false); try { diff --git a/server/src/Http/Controllers/Internal/v1/TrailerController.php b/server/src/Http/Controllers/Internal/v1/TrailerController.php index 41420ded5..106471679 100644 --- a/server/src/Http/Controllers/Internal/v1/TrailerController.php +++ b/server/src/Http/Controllers/Internal/v1/TrailerController.php @@ -50,7 +50,7 @@ class TrailerController extends FleetOpsController */ public function afterSave(Request $request, Trailer $trailer): void { - $values = $request->array('trailer.custom_field_values'); + $values = $request->inputArray('trailer.custom_field_values'); if ($values) { $trailer->syncCustomFieldValues($values); @@ -313,7 +313,7 @@ public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - return $this->downloadExport(new TrailerExport($request->array('selections')), Str::slug('trailers-' . date('Y-m-d-H:i')) . '.' . $format); + return $this->downloadExport(new TrailerExport($request->inputArray('selections')), Str::slug('trailers-' . date('Y-m-d-H:i')) . '.' . $format); } public function import(ImportRequest $request) diff --git a/server/src/Http/Controllers/Internal/v1/VehicleController.php b/server/src/Http/Controllers/Internal/v1/VehicleController.php index 25712b6cb..7d6f25ede 100644 --- a/server/src/Http/Controllers/Internal/v1/VehicleController.php +++ b/server/src/Http/Controllers/Internal/v1/VehicleController.php @@ -56,7 +56,7 @@ public function afterSave(Request $request, Vehicle $vehicle, array $input = []) $this->syncDriverAssignment($vehicle, $this->driverIdentifierFromRequest($request)); } - $customFieldValues = $request->array('vehicle.custom_field_values'); + $customFieldValues = $request->inputArray('vehicle.custom_field_values'); if ($customFieldValues) { $vehicle->syncCustomFieldValues($customFieldValues); } @@ -472,7 +472,7 @@ public function avatars() public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('vehicles-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new VehicleExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/VendorController.php b/server/src/Http/Controllers/Internal/v1/VendorController.php index 69c100da2..f243d2cfe 100644 --- a/server/src/Http/Controllers/Internal/v1/VendorController.php +++ b/server/src/Http/Controllers/Internal/v1/VendorController.php @@ -44,7 +44,7 @@ class VendorController extends FleetOpsController */ public function afterSave(Request $request, Vendor $vendor) { - $customFieldValues = $request->array('vendor.custom_field_values'); + $customFieldValues = $request->inputArray('vendor.custom_field_values'); if ($customFieldValues) { $vendor->syncCustomFieldValues($customFieldValues); } @@ -94,7 +94,7 @@ public function getAsCustomer($id) public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('vendors-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new VendorExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/WorkOrderController.php b/server/src/Http/Controllers/Internal/v1/WorkOrderController.php index 28d37e315..0e0e22e63 100644 --- a/server/src/Http/Controllers/Internal/v1/WorkOrderController.php +++ b/server/src/Http/Controllers/Internal/v1/WorkOrderController.php @@ -41,7 +41,7 @@ class WorkOrderController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('work-orders-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new WorkOrderExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/ZoneController.php b/server/src/Http/Controllers/Internal/v1/ZoneController.php index e790d0a57..2b1515a3b 100644 --- a/server/src/Http/Controllers/Internal/v1/ZoneController.php +++ b/server/src/Http/Controllers/Internal/v1/ZoneController.php @@ -20,7 +20,7 @@ class ZoneController extends FleetOpsController */ public function afterSave(Request $request, Zone $zone) { - $customFieldValues = $request->array('zone.custom_field_values'); + $customFieldValues = $request->inputArray('zone.custom_field_values'); if ($customFieldValues) { $zone->syncCustomFieldValues($customFieldValues); } diff --git a/server/src/Http/Controllers/Public/TrackingController.php b/server/src/Http/Controllers/Public/TrackingController.php index 758c3436f..255e1d6c8 100644 --- a/server/src/Http/Controllers/Public/TrackingController.php +++ b/server/src/Http/Controllers/Public/TrackingController.php @@ -10,6 +10,7 @@ use Fleetbase\FleetOps\Support\TrackingPage\TrackingAccess; use Fleetbase\FleetOps\Support\TrackingPage\TrackingRecipient; use Fleetbase\FleetOps\Support\TrackingPage\TrackingResolver; +use Fleetbase\FleetOps\Support\TrackingPage\TrackingShare; use Fleetbase\FleetOps\Support\TrackingPage\TrackingTarget; use Fleetbase\FleetOps\Support\TrackingPage\TrackingView; use Fleetbase\FleetOps\Support\TrackingPublisher; @@ -152,6 +153,24 @@ public function verifyCode(Request $request, string $number): JsonResponse }; } + /** + * Open a link a customer shared: a valid token gives this device the customer's live view, + * as a verified code would. + */ + public function redeemShare(Request $request, string $number): JsonResponse + { + if (!$this->access->allowVerify($request)) { + return $this->json(['error' => 'limited', 'retry_after' => TrackingAccess::LOOKUP_WINDOW], 429); + } + + $target = $this->resolve($request, $number); + if (!$target || !$target->scope) { + return $this->notFound(); + } + + return TrackingShare::valid($request->input('token'), $target->scope) ? $this->verified($request, $target, 'share') : $this->json(['error' => 'invalid'], 422); + } + /** * Sign this device out: of one delivery with `?number=`, otherwise of every one. */ diff --git a/server/src/Http/Requests/CreateCustomerRequest.php b/server/src/Http/Requests/CreateCustomerRequest.php index 761606858..e019f916e 100644 --- a/server/src/Http/Requests/CreateCustomerRequest.php +++ b/server/src/Http/Requests/CreateCustomerRequest.php @@ -33,7 +33,7 @@ public function rules(): array // non-production testing bypass (fleetops.customers.verification_bypass_code). 'code' => 'required|string', 'name' => 'required|string', - 'password' => 'required|string|min:8', + 'password' => 'nullable|string|min:8', 'email' => [ 'email', 'nullable', Rule::unique('contacts')->where(function ($query) { diff --git a/server/src/Http/Requests/CreateOrderRequest.php b/server/src/Http/Requests/CreateOrderRequest.php index e110627db..de9aa839c 100644 --- a/server/src/Http/Requests/CreateOrderRequest.php +++ b/server/src/Http/Requests/CreateOrderRequest.php @@ -26,19 +26,21 @@ public function rules(): array $podMethods = is_array($podMethods) ? implode(',', $podMethods) : (string) $podMethods; $validations = [ - 'adhoc' => ['nullable', 'boolean'], - 'dispatch' => ['nullable', 'boolean'], - 'adhoc_distance' => ['nullable', 'numeric'], - 'pod_required' => ['nullable', 'boolean'], - 'pod_method' => ['nullable', 'in:' . $podMethods], - 'scheduled_at' => ['nullable', 'date'], - 'driver' => ['nullable', 'exists:drivers,public_id'], - 'service_quote' => ['nullable', 'exists:service_quotes,public_id'], - 'purchase_rate' => ['nullable', 'exists:purchase_rates,public_id'], - 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['public_id', 'provider'])], - 'customer' => ['nullable', new CustomerIdOrDetails(['vendors', 'contacts'], 'public_id')], - 'status' => ['nullable', 'string'], - 'type' => ['string'], + 'adhoc' => ['nullable', 'boolean'], + 'dispatch' => ['nullable', 'boolean'], + 'adhoc_distance' => ['nullable', 'numeric'], + 'adhoc_strategy' => ['nullable', 'string', 'in:' . implode(',', \Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch::names())], + 'required_vehicle_type' => ['nullable', 'string', 'max:191'], + 'pod_required' => ['nullable', 'boolean'], + 'pod_method' => ['nullable', 'in:' . $podMethods], + 'scheduled_at' => ['nullable', 'date'], + 'driver' => ['nullable', 'exists:drivers,public_id'], + 'service_quote' => ['nullable', 'exists:service_quotes,public_id'], + 'purchase_rate' => ['nullable', 'exists:purchase_rates,public_id'], + 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['public_id', 'provider'])], + 'customer' => ['nullable', new CustomerIdOrDetails(['vendors', 'contacts'], 'public_id')], + 'status' => ['nullable', 'string'], + 'type' => ['string'], ]; // Conditionally require 'pod_method' if 'pod_required' is truthy diff --git a/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php b/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php index 54906e0cc..7ad96302e 100644 --- a/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php +++ b/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php @@ -2,6 +2,9 @@ namespace Fleetbase\FleetOps\Http\Requests\Internal; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigActions; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; use Fleetbase\Http\Requests\FleetbaseRequest; use Fleetbase\Support\Auth; use Illuminate\Validation\Rule; @@ -21,7 +24,7 @@ public function authorize(): bool */ public function rules(): array { - return [ + return array_merge([ 'name' => [ 'required', Rule::unique('order_configs', 'name') @@ -32,6 +35,12 @@ public function rules(): array Rule::unique('order_configs', 'key') ->where('company_uuid', request()->session()->get('company'))->whereNull('deleted_at'), ], - ]; + 'triggers' => ['nullable', 'array'], + 'triggers.*.event' => ['required', 'string', Rule::in(OrderConfigTriggers::EVENTS)], + 'triggers.*.action' => ['required', 'string', Rule::in(OrderConfigActions::names())], + 'triggers.*.params' => ['nullable', 'array'], + 'triggers.*.options' => ['nullable', 'array'], + 'triggers.*.when' => ['nullable', 'array'], + ], OrderConfigPolicies::rules()); } } diff --git a/server/src/Http/Requests/Internal/CreateOrderRequest.php b/server/src/Http/Requests/Internal/CreateOrderRequest.php index 7b5466857..c3f142067 100644 --- a/server/src/Http/Requests/Internal/CreateOrderRequest.php +++ b/server/src/Http/Requests/Internal/CreateOrderRequest.php @@ -26,20 +26,22 @@ public function rules(): array $podMethods = is_array($podMethods) ? implode(',', $podMethods) : (string) $podMethods; $validations = [ - 'order_config_uuid' => ['required'], - 'adhoc' => ['nullable', 'boolean'], - 'dispatch' => ['nullable', 'boolean'], - 'adhoc_distance' => ['nullable', 'numeric'], - 'pod_required' => ['nullable', 'boolean'], - 'pod_method' => ['nullable', 'in:' . $podMethods], - 'scheduled_at' => ['nullable', 'date'], - 'driver' => ['nullable', 'exists:drivers,uuid'], - 'service_quote' => ['nullable', 'exists:service_quotes,uuid'], - 'purchase_rate' => ['nullable', 'exists:purchase_rates,uuid'], - 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['uuid', 'provider'])], - 'customer' => ['nullable', new ExistsInAny(['vendors', 'contacts'], 'uuid')], - 'status' => ['nullable', 'string'], - 'type' => ['string'], + 'order_config_uuid' => ['required'], + 'adhoc' => ['nullable', 'boolean'], + 'dispatch' => ['nullable', 'boolean'], + 'adhoc_distance' => ['nullable', 'numeric'], + 'adhoc_strategy' => ['nullable', 'string', 'in:' . implode(',', \Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch::names())], + 'required_vehicle_type' => ['nullable', 'string', 'max:191'], + 'pod_required' => ['nullable', 'boolean'], + 'pod_method' => ['nullable', 'in:' . $podMethods], + 'scheduled_at' => ['nullable', 'date'], + 'driver' => ['nullable', 'exists:drivers,uuid'], + 'service_quote' => ['nullable', 'exists:service_quotes,uuid'], + 'purchase_rate' => ['nullable', 'exists:purchase_rates,uuid'], + 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['uuid', 'provider'])], + 'customer' => ['nullable', new ExistsInAny(['vendors', 'contacts'], 'uuid')], + 'status' => ['nullable', 'string'], + 'type' => ['string'], ]; // Conditionally require 'pod_method' if 'pod_required' is truthy diff --git a/server/src/Http/Resources/Internal/v1/OrderConfig.php b/server/src/Http/Resources/Internal/v1/OrderConfig.php index 2f001484c..c8741653c 100644 --- a/server/src/Http/Resources/Internal/v1/OrderConfig.php +++ b/server/src/Http/Resources/Internal/v1/OrderConfig.php @@ -32,6 +32,9 @@ public function toArray($request): array 'entities' => $this->entities ?? [], 'tags' => $this->tags ?? [], 'meta' => $this->meta ?? [], + // As stored, for editing: settings left out take their defaults on the server. + 'policies' => $this->policies ?? (object) [], + 'triggers' => $this->triggers ?? [], 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'deleted_at' => $this->deleted_at, diff --git a/server/src/Http/Resources/v1/Order.php b/server/src/Http/Resources/v1/Order.php index 6ed174612..17dc5acda 100644 --- a/server/src/Http/Resources/v1/Order.php +++ b/server/src/Http/Resources/v1/Order.php @@ -3,6 +3,7 @@ namespace Fleetbase\FleetOps\Http\Resources\v1; use Fleetbase\FleetOps\Models\Contact as ContactModel; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Resources\Comment; use Fleetbase\Http\Resources\File; @@ -88,6 +89,15 @@ public function toArray($request): array 'started' => (bool) data_get($this, 'started', false), 'adhoc' => (bool) data_get($this, 'adhoc', false), 'adhoc_distance' => (int) $this->getAdhocDistance(), + 'adhoc_strategy' => $this->adhoc_strategy, + 'required_vehicle_type' => $this->required_vehicle_type, + // The asking driver's open offer, when they listed orders near them. + 'adhoc_offer' => $this->when($this->resource->relationLoaded('adhocOffer'), fn () => AdhocOfferListing::present($this->adhocOffer)), + // How offering an adhoc order ended, e.g. `no_driver_found`; null while it is open or taken. + 'dispatch_outcome' => $this->when((bool) data_get($this, 'adhoc', false), fn () => $this->resource->dispatchOutcome()), + 'driver_rating' => $this->when($this->resource->relationLoaded('driverRating'), fn () => $this->driverRating ? ['stars' => $this->driverRating->stars, 'comment' => $this->driverRating->comment] : null), + // Whether the order's transaction is paid (core's settlement status), when it was loaded. + 'payment_status' => $this->when($this->resource->relationLoaded('transaction'), fn () => $this->transaction?->settlement_status), 'distance' => (int) $this->distance, 'time' => (int) $this->time, 'transaction_amount' => $this->transaction_amount, diff --git a/server/src/Http/Resources/v1/OrderConfig.php b/server/src/Http/Resources/v1/OrderConfig.php index 7b52fa2e9..5796b6efb 100644 --- a/server/src/Http/Resources/v1/OrderConfig.php +++ b/server/src/Http/Resources/v1/OrderConfig.php @@ -23,23 +23,45 @@ class OrderConfig extends FleetbaseResource public function toArray($request): array { return [ - 'id' => $this->when(Http::isInternalRequest(), $this->id, $this->public_id), - 'uuid' => $this->when(Http::isInternalRequest(), $this->uuid), - 'public_id' => $this->when(Http::isInternalRequest(), $this->public_id), - 'company_uuid' => $this->when(Http::isInternalRequest(), $this->company_uuid), - 'key' => $this->key, - 'name' => $this->name, - 'namespace' => $this->namespace, - 'description' => $this->description, - 'tags' => $this->tags, - 'status' => $this->status, - 'version' => $this->version, - 'flow' => $this->projectFlow(), - 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at, + 'id' => $this->when(Http::isInternalRequest(), $this->id, $this->public_id), + 'uuid' => $this->when(Http::isInternalRequest(), $this->uuid), + 'public_id' => $this->when(Http::isInternalRequest(), $this->public_id), + 'company_uuid' => $this->when(Http::isInternalRequest(), $this->company_uuid), + 'key' => $this->key, + 'name' => $this->name, + 'namespace' => $this->namespace, + 'description' => $this->description, + 'tags' => $this->tags, + 'status' => $this->status, + 'version' => $this->version, + 'flow' => $this->projectFlow(), + // Every policy setting, defaults filled in: what a customer app needs to know about + // ordering, cancelling, payment methods and the like for this order type. + 'policies' => $this->resource->resolvedPolicies(), + 'triggers' => $this->when(Http::isInternalRequest(), $this->triggers ?? []), + 'custom_fields' => $this->when($this->resource->relationLoaded('customFields'), fn () => $this->projectCustomFields()), + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, ]; } + /** + * The custom fields orders of the config carry, with what a form needs to ask for them. + */ + protected function projectCustomFields(): array + { + return $this->resource->customFields->map(fn ($field) => [ + 'name' => $field->name, + 'label' => $field->label, + 'type' => $field->type, + 'component' => $field->component, + 'options' => $field->options, + 'required' => (bool) $field->required, + 'default_value' => $field->default_value, + 'help_text' => $field->help_text, + ])->values()->all(); + } + /** * Project the flow JSON into a list of activities, keeping the public-safe * per-activity fields. diff --git a/server/src/Http/Resources/v1/PurchaseRate.php b/server/src/Http/Resources/v1/PurchaseRate.php index 86ca1106e..36d5d408f 100644 --- a/server/src/Http/Resources/v1/PurchaseRate.php +++ b/server/src/Http/Resources/v1/PurchaseRate.php @@ -24,9 +24,12 @@ public function toArray($request) 'order' => $this->order_id, 'customer' => $this->customer_id, 'transaction' => $this->transaction_id, + 'service_name' => data_get($this, 'serviceQuote.serviceRate.service_name'), 'amount' => $this->amount, 'currency' => $this->currency, 'status' => $this->status, + // Priced again from the order's actual distance and time (the config's pricing policy). + 'repriced' => (bool) data_get($this->meta, 'repriced'), // 'type' => $this->when(Http::isInternalRequest(), 'service-rate'), 'updated_at' => $this->updated_at, 'created_at' => $this->created_at, diff --git a/server/src/Http/Resources/v1/ServiceQuote.php b/server/src/Http/Resources/v1/ServiceQuote.php index 2376cb7d1..cba5e4974 100644 --- a/server/src/Http/Resources/v1/ServiceQuote.php +++ b/server/src/Http/Resources/v1/ServiceQuote.php @@ -32,6 +32,8 @@ public function toArray($request) 'amount' => $this->amount, 'currency' => $this->currency, 'meta' => data_get($this, 'meta', Utils::createObject()), + 'seating_capacity' => $this->when($this->resource->availability !== null, fn () => $this->resource->availability['seating_capacity']), + 'pickup_eta' => $this->when($this->resource->availability !== null, fn () => $this->resource->availability['pickup_eta']), 'updated_at' => $this->updated_at, 'created_at' => $this->created_at, ]; diff --git a/server/src/Jobs/ExpireOrderOffer.php b/server/src/Jobs/ExpireOrderOffer.php new file mode 100644 index 000000000..2af7d423f --- /dev/null +++ b/server/src/Jobs/ExpireOrderOffer.php @@ -0,0 +1,34 @@ +offerUuid)->first(); + + return $offer ? app(SequentialStrategy::class)->expire($offer) : false; + } +} diff --git a/server/src/Jobs/ReplayPositions.php b/server/src/Jobs/ReplayPositions.php index 2a7d67bc6..c8a2b253b 100644 --- a/server/src/Jobs/ReplayPositions.php +++ b/server/src/Jobs/ReplayPositions.php @@ -45,7 +45,7 @@ public function handle(): void foreach ($this->positions as $index => $position) { $currentTime = Carbon::parse($position->created_at); - $offset = $baseTime->diffInSeconds($currentTime, false) / $this->speed; + $offset = (int) $baseTime->diffInSeconds($currentTime, false) / $this->speed; // Schedule a small job for each event with its own delay $this->dispatchReplayPosition($position, $index, max(0, $offset)); diff --git a/server/src/Jobs/RunOrderConfigAction.php b/server/src/Jobs/RunOrderConfigAction.php new file mode 100644 index 000000000..b719b29d7 --- /dev/null +++ b/server/src/Jobs/RunOrderConfigAction.php @@ -0,0 +1,43 @@ +orderUuid = $order->uuid; + } + + public function handle(): bool + { + $order = Order::withoutGlobalScopes()->where('uuid', $this->orderUuid)->first(); + $action = OrderConfigActions::get($this->action); + if (!$order || !$action) { + return false; + } + + $action->handle($order, $this->params, $this->context); + + return true; + } +} diff --git a/server/src/Jobs/SyncTelematicDevicesJob.php b/server/src/Jobs/SyncTelematicDevicesJob.php index d32093fb3..4add5b8a0 100644 --- a/server/src/Jobs/SyncTelematicDevicesJob.php +++ b/server/src/Jobs/SyncTelematicDevicesJob.php @@ -125,7 +125,7 @@ public function handle(TelematicProviderRegistry $registry, TelematicService $se &$inventoryFetched, &$inventoryLinked, &$inventorySkipped, &$totalEnrichment, &$totalEnrichmentCompleted, &$totalEnrichmentFailures ): void { - if (!$force && $itemsSinceCheckpoint < 25 && $lastCheckpointAt->diffInSeconds(now(), true) < 5) { + if (!$force && $itemsSinceCheckpoint < 25 && (int) $lastCheckpointAt->diffInSeconds(now(), true) < 5) { return; } $this->telematic->status = 'synchronizing'; diff --git a/server/src/Listeners/HandleOrderDispatched.php b/server/src/Listeners/HandleOrderDispatched.php index 59d2a826b..cb4747ac0 100644 --- a/server/src/Listeners/HandleOrderDispatched.php +++ b/server/src/Listeners/HandleOrderDispatched.php @@ -7,8 +7,7 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\TrackingStatus; use Fleetbase\FleetOps\Notifications\OrderDispatched as OrderDispatchedNotification; -use Fleetbase\FleetOps\Notifications\OrderPing; -use Fleetbase\FleetOps\Support\Utils; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Support\Carbon; @@ -26,7 +25,7 @@ class HandleOrderDispatched implements ShouldQueue */ public function handle(OrderDispatched $event) { - /** @var \Fleetbase\FleetOps\Models\Order $order */ + /** @var Order $order */ $order = $event->getModelRecord(); // set company session @@ -60,24 +59,9 @@ public function handle(OrderDispatched $event) $order->save(); $order->flushAttributesCache(); - /* if order is adhoc ping drivers within radius of pickup to accept order * */ + // An adhoc order is offered to drivers by its dispatch strategy. if ($order->adhoc) { - $order->load(['company']); - $pickup = $order->getPickupLocation(); - $distance = $order->getAdhocDistance(); - if (!Utils::isPoint($pickup)) { - return; - } - - $drivers = $this->nearbyAvailableDrivers($pickup, $distance); - - return $drivers->each(function ($driver) use ($order) { - try { - $this->notifyAdhocDriver($driver, $order); - } catch (\Exception $exception) { - // failed to notify driver for order dispatch for reason uknown -- exit silently - } - }); + return $this->dispatchAdhoc($order); } /** @var \Fleetbase\Models\Driver */ @@ -95,6 +79,13 @@ public function handle(OrderDispatched $event) } } + protected function dispatchAdhoc($order): mixed + { + AdhocDispatch::for($order)->dispatch($order); + + return null; + } + protected function dispatchFailed($order, string $reason): mixed { return event(new OrderDispatchFailed($order, $reason)); @@ -110,34 +101,6 @@ protected function getDispatchActivity($order): mixed return $order->config()?->getDispatchActivity(); } - protected function nearbyAvailableDrivers($pickup, int|float $distance) - { - return Driver::where(['status' => 'available', 'online' => 1]) - ->whereHas('company', function ($q) { - $q->whereHas('users', function ($q) { - $q->whereHas('driver', function ($q) { - $q->where(['status' => 'available', 'online' => 1]); - $q->whereNull('deleted_at'); - }); - }); - }) - ->whereNull('deleted_at') - ->whereNotNull('location')->whereRaw(' - ST_Y(location) BETWEEN -90 AND 90 - AND ST_X(location) BETWEEN -180 AND 180 - AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0) - ') - ->distanceSphere('location', $pickup, $distance) - ->distanceSphereValue('location', $pickup) - ->withoutGlobalScopes() - ->get(); - } - - protected function notifyAdhocDriver(Driver $driver, $order): void - { - $driver->notify(new OrderPing($order, $driver->distance)); - } - protected function findAssignedDriver($order): ?Driver { return Driver::where('uuid', $order->driver_assigned_uuid)->withoutGlobalScopes()->first(); diff --git a/server/src/Models/Device.php b/server/src/Models/Device.php index d38ecf3c4..52621bf8c 100644 --- a/server/src/Models/Device.php +++ b/server/src/Models/Device.php @@ -373,7 +373,7 @@ public function getConnectionStatusAttribute(): string return 'never_connected'; } - $minutesOffline = $this->last_online_at->diffInMinutes(now()); + $minutesOffline = (int) $this->last_online_at->diffInMinutes(now(), true); if ($minutesOffline <= 10) { return 'online'; diff --git a/server/src/Models/DeviceEvent.php b/server/src/Models/DeviceEvent.php index 5b5d4a16f..375926858 100644 --- a/server/src/Models/DeviceEvent.php +++ b/server/src/Models/DeviceEvent.php @@ -311,7 +311,7 @@ public function getAgeMinutesAttribute(): int { $startTime = $this->occurred_at ?? $this->created_at; - return $startTime->diffInMinutes(now()); + return (int) $startTime->diffInMinutes(now(), true); } /** @@ -325,7 +325,7 @@ public function getProcessingDelayMinutesAttribute(): ?int $startTime = $this->occurred_at ?? $this->created_at; - return $startTime->diffInMinutes($this->processed_at); + return (int) $startTime->diffInMinutes($this->processed_at, true); } /** diff --git a/server/src/Models/Driver.php b/server/src/Models/Driver.php index 146e9bf78..f25c54959 100644 --- a/server/src/Models/Driver.php +++ b/server/src/Models/Driver.php @@ -99,6 +99,8 @@ class Driver extends Model 'vehicle_uuid', 'vendor_uuid', 'current_job_uuid', + 'rating_average', + 'rating_count', 'auth_token', 'signup_token_used', 'avatar_url', @@ -157,6 +159,8 @@ class Driver extends Model 'location' => Point::class, 'online' => 'boolean', 'meta' => Json::class, + 'rating_average' => 'float', + 'rating_count' => 'integer', 'license_expiry' => 'date', // Orchestrator 'skills' => Json::class, diff --git a/server/src/Models/DriverRating.php b/server/src/Models/DriverRating.php new file mode 100644 index 000000000..b9aabafab --- /dev/null +++ b/server/src/Models/DriverRating.php @@ -0,0 +1,32 @@ + 'integer', + ]; + + public function order() + { + return $this->belongsTo(Order::class, 'order_uuid', 'uuid')->withoutGlobalScopes(); + } + + public function driver() + { + return $this->belongsTo(Driver::class, 'driver_uuid', 'uuid')->withoutGlobalScopes(); + } +} diff --git a/server/src/Models/Equipment.php b/server/src/Models/Equipment.php index ee53004fd..b6fabb1f1 100644 --- a/server/src/Models/Equipment.php +++ b/server/src/Models/Equipment.php @@ -297,7 +297,7 @@ public function getIsEquippedAttribute(): bool public function getAgeInDaysAttribute(): ?int { if ($this->purchased_at) { - return $this->purchased_at->diffInDays(now()); + return (int) $this->purchased_at->diffInDays(now(), true); } return null; @@ -314,7 +314,7 @@ public function getDepreciatedValueAttribute(): ?float $meta = $this->meta ?? []; $depreciationRate = $meta['depreciation_rate'] ?? 0.1; // 10% per year default - $yearsOld = $this->purchased_at->diffInYears(now()); + $yearsOld = (int) $this->purchased_at->diffInYears(now(), true); $depreciatedAmount = $this->purchase_price * ($depreciationRate * $yearsOld); $currentValue = $this->purchase_price - $depreciatedAmount; @@ -460,7 +460,7 @@ public function needsMaintenance(): bool ->first(); $lastMaintenanceDate = $lastMaintenance?->completed_at ?? $this->purchased_at; - $daysSinceLastMaintenance = $lastMaintenanceDate->diffInDays(now()); + $daysSinceLastMaintenance = (int) $lastMaintenanceDate->diffInDays(now(), true); return $daysSinceLastMaintenance >= $maintenanceIntervalDays; } @@ -534,7 +534,7 @@ public function getReplacementCostEstimate(): ?float // Estimate based on purchase price with inflation if ($this->purchase_price && $this->purchased_at) { - $yearsOld = $this->purchased_at->diffInYears(now()); + $yearsOld = (int) $this->purchased_at->diffInYears(now(), true); $inflationRate = $meta['inflation_rate'] ?? 0.03; // 3% default return $this->purchase_price * pow(1 + $inflationRate, $yearsOld); diff --git a/server/src/Models/Maintenance.php b/server/src/Models/Maintenance.php index 10457ef0f..847880fdc 100644 --- a/server/src/Models/Maintenance.php +++ b/server/src/Models/Maintenance.php @@ -234,7 +234,7 @@ public function getPerformedByNameAttribute(): ?string public function getDurationHoursAttribute(): ?float { if ($this->started_at && $this->completed_at) { - return $this->started_at->diffInHours($this->completed_at); + return (int) $this->started_at->diffInHours($this->completed_at, true); } return null; @@ -261,7 +261,7 @@ public function getDaysUntilDueAttribute(): ?int return null; } - return now()->diffInDays($this->scheduled_at, false); + return (int) now()->diffInDays($this->scheduled_at, false); } /** diff --git a/server/src/Models/Order.php b/server/src/Models/Order.php index 5d5b90a20..263c846c2 100644 --- a/server/src/Models/Order.php +++ b/server/src/Models/Order.php @@ -11,9 +11,11 @@ use Fleetbase\FleetOps\Events\OrderDriverUnassigned; use Fleetbase\FleetOps\Flow\Activity; use Fleetbase\FleetOps\Notifications\OrderUnassigned; +use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\LabelPdf; use Fleetbase\FleetOps\Support\NavigatorReview; use Fleetbase\FleetOps\Support\OrderEditPolicy; +use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\OrderTracker; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\FleetOps\Traits\HasTrackingNumber; @@ -35,6 +37,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasManyThrough; +use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Support\Carbon; @@ -114,6 +117,9 @@ class Order extends Model 'dispatched', 'adhoc', 'adhoc_distance', + 'adhoc_strategy', + 'required_vehicle_type', + 'chat_channel_uuid', 'started', 'started_at', 'pod_method', @@ -239,17 +245,17 @@ class Order extends Model * @var array */ protected $casts = [ - 'meta' => Json::class, - 'options' => Json::class, - 'customer_type' => PolymorphicType::class, - 'facilitator_type' => PolymorphicType::class, - 'dispatched' => 'boolean', - 'adhoc' => 'boolean', - 'started' => 'boolean', - 'pod_required' => 'boolean', - 'scheduled_at' => 'datetime', - 'dispatched_at' => 'datetime', - 'started_at' => 'datetime', + 'meta' => Json::class, + 'options' => Json::class, + 'customer_type' => PolymorphicType::class, + 'facilitator_type' => PolymorphicType::class, + 'dispatched' => 'boolean', + 'adhoc' => 'boolean', + 'started' => 'boolean', + 'pod_required' => 'boolean', + 'scheduled_at' => 'datetime', + 'dispatched_at' => 'datetime', + 'started_at' => 'datetime', // Orchestrator 'required_skills' => Json::class, 'time_window_start' => 'datetime', @@ -503,6 +509,39 @@ public function purchaseRate(): BelongsTo return $this->belongsTo(PurchaseRate::class); } + /** + * The customer's rating of the driver, once the order is finished and rated. + */ + public function driverRating(): HasOne + { + return $this->hasOne(DriverRating::class, 'order_uuid', 'uuid'); + } + + /** + * The chat between the order's customer and its driver, once opened. + */ + public function chatChannel(): BelongsTo + { + return $this->belongsTo(\Fleetbase\Models\ChatChannel::class, 'chat_channel_uuid', 'uuid'); + } + + /** + * How offering the order to drivers ended, for example `no_driver_found`. Null while it is + * still being offered, once a driver took it, or for an order that wasn't adhoc. + */ + public function dispatchOutcome(): ?string + { + return OrderOffers::outcome($this); + } + + /** + * The custom fields of the order's config. Values are stored on the order. + */ + public function customFields(): HasMany + { + return $this->hasMany(\Fleetbase\Models\CustomField::class, 'subject_uuid', 'order_config_uuid')->orderBy('order'); + } + /** * @return MorphTo */ @@ -1506,6 +1545,14 @@ public function cancelWithReason(?string $reason = null) $this->status = $canceledActivity->code ?? 'canceled'; $this->updateActivity($canceledActivity); + // The driver is free for other work, and nobody else is offered a canceled order. + if ($this->driver_assigned_uuid) { + Driver::withoutGlobalScopes()->where(['uuid' => $this->driver_assigned_uuid, 'current_job_uuid' => $this->uuid])->update(['current_job_uuid' => null]); + } + if ($this->adhoc) { + OrderOffers::withdraw($this); + } + if ($this->isIntegratedVendorOrder()) { $api = $this->facilitator->api(); @@ -2006,7 +2053,9 @@ public function isIntegratedVendorOrder() */ public function getAdhocPingDistance(): int { - return (int) Utils::get($this, 'adhoc_distance', Utils::get($this, 'company.options.fleetops.adhoc_distance', 6000)); + $radius = $this->adhoc_distance ?? $this->currentConfig()?->policy('dispatch.adhoc.radius'); + + return (int) ($radius ?? Utils::get($this, 'company.options.fleetops.adhoc_distance', 6000)); } /** @@ -2075,6 +2124,21 @@ public function config(): ?OrderConfig return null; } + /** + * The order's own config, reusing the one already loaded on the order, for reading its + * policies and triggers often without loading it each time. Null for an order without a + * config of its own, which has no policies or triggers; `config()` falls back to the + * company's default config instead. + */ + public function currentConfig(): ?OrderConfig + { + if ($this->relationLoaded('orderConfig') && $this->orderConfig instanceof OrderConfig && $this->orderConfig->uuid === $this->order_config_uuid) { + return $this->orderConfig->setOrderContext($this); + } + + return $this->order_config_uuid ? $this->config() : null; + } + /** * Ensure the order has a persisted order config and normalized type. */ @@ -2334,9 +2398,9 @@ public function findClosestDrivers(int $distance = 6000): Collection ') ->distanceSphere('location', $pickup, $distance) ->distanceSphereValue('location', $pickup) - ->withoutGlobalScopes() - ->get(); + ->withoutGlobalScopes(); - return $drivers; + // Only this order's company, and not drivers already on another job. + return DriverMatching::forOrder($drivers, $this)->get(); } } diff --git a/server/src/Models/OrderConfig.php b/server/src/Models/OrderConfig.php index 32d074d30..b783f8cbf 100644 --- a/server/src/Models/OrderConfig.php +++ b/server/src/Models/OrderConfig.php @@ -5,7 +5,9 @@ use Fleetbase\Casts\Json; use Fleetbase\FleetOps\Casts\OrderConfigEntities; use Fleetbase\FleetOps\Flow\Activity; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Fleetbase\FleetOps\Support\FleetOps; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies; use Fleetbase\Models\Company; use Fleetbase\Models\Model; use Fleetbase\Support\Auth; @@ -68,6 +70,8 @@ class OrderConfig extends Model 'flow', 'entities', 'meta', + 'policies', + 'triggers', ]; /** @@ -80,6 +84,8 @@ class OrderConfig extends Model 'flow' => Json::class, 'entities' => OrderConfigEntities::class, 'meta' => Json::class, + 'policies' => Json::class, + 'triggers' => Json::class, ]; /** @@ -122,6 +128,52 @@ protected static function boot() $model->status = 'private'; $model->key = Str::slug($model->name); }); + + static::saving(fn ($model) => $model->normalizePolicies()); + } + + /** + * Keep stored policies valid: drop an adhoc strategy that isn't registered, and keep the + * offer timeout within its limits. + */ + public function normalizePolicies(): void + { + if (!is_array($this->policies)) { + return; + } + + $policies = $this->policies; + + $strategy = data_get($policies, 'dispatch.adhoc.strategy'); + if ($strategy !== null && !AdhocDispatch::has($strategy)) { + data_set($policies, 'dispatch.adhoc.strategy', null); + } + + $timeout = data_get($policies, 'dispatch.adhoc.offer_timeout'); + if ($timeout !== null && $timeout !== '') { + data_set($policies, 'dispatch.adhoc.offer_timeout', max(AdhocDispatch::MIN_OFFER_TIMEOUT, min(AdhocDispatch::MAX_OFFER_TIMEOUT, (int) $timeout))); + } + + $this->policies = $policies; + } + + /** + * Every policy setting, with each one the config doesn't set taken from its default. + */ + public function resolvedPolicies(): array + { + return OrderConfigPolicies::resolve(is_array($this->policies) ? $this->policies : []); + } + + /** + * One policy setting, in dot notation (`dispatch.adhoc.strategy`), or a whole policy + * (`dispatch.adhoc`). The registered default applies when the config doesn't set it. + */ + public function policy(string $key, mixed $default = null): mixed + { + $value = data_get($this->resolvedPolicies(), $key); + + return $value ?? $default; } /** @@ -499,6 +551,47 @@ public function canTransition(?string $fromCode, string $toCode): bool return $from->children()->contains(fn ($activity) => $activity->code === $toCode); } + /** + * Check an activity update against what the config declares, for every path that moves an + * order (console, API, driver app). Returns the activity to apply, which is the config's own + * definition when transitions are strict, and the reason the update is refused, or null. + * + * - a finished order takes no more activities, unless `$fromTerminal` (operator corrections) + * - strict transitions only allow a configured child of the current activity + * - a config whose lifecycle turns dispatch off refuses `dispatched` + * - an activity that needs proof of delivery (`require_pod`, or completing an order that + * requires proof) needs proof, unless `$bypassProof` + * + * @return array{0: Activity, 1: ?string} + */ + public function authorizeTransition(Order $order, Activity $activity, mixed $proof = null, bool $bypassProof = false, bool $fromTerminal = false): array + { + if (!$fromTerminal && $this->isTerminalActivityCode($order->status)) { + return [$activity, 'This order has already finished.']; + } + + if ($this->hasStrictTransitions()) { + $targetCode = $activity->get('code'); + $configured = $targetCode ? $this->getActivityByCode($targetCode) : null; + if (!$configured || !$this->canTransition($order->status, $targetCode)) { + return [$activity, 'This activity is not a permitted next step for the order.']; + } + + $activity = $configured; + } + + if ($activity->is('dispatched') && !$this->allowsDispatch()) { + return [$activity, 'Orders of this type are not dispatched.']; + } + + $requiresProof = $activity->get('require_pod') || ($activity->completesOrder() && $order->pod_required); + if ($requiresProof && !$proof && !$bypassProof) { + return [$activity, 'Proof of delivery is required for this activity or must be explicitly bypassed.']; + } + + return [$activity, null]; + } + /** * Creates an Activity instance representing a canceled order. * diff --git a/server/src/Models/OrderOffer.php b/server/src/Models/OrderOffer.php new file mode 100644 index 000000000..094a035e8 --- /dev/null +++ b/server/src/Models/OrderOffer.php @@ -0,0 +1,41 @@ + 'integer', + 'expires_at' => 'datetime', + 'responded_at' => 'datetime', + ]; + + public function order() + { + return $this->belongsTo(Order::class, 'order_uuid', 'uuid')->withoutGlobalScopes(); + } + + public function driver() + { + return $this->belongsTo(Driver::class, 'driver_uuid', 'uuid')->withoutGlobalScopes(); + } +} diff --git a/server/src/Models/ServiceQuote.php b/server/src/Models/ServiceQuote.php index e5b30a9b3..9d0593357 100644 --- a/server/src/Models/ServiceQuote.php +++ b/server/src/Models/ServiceQuote.php @@ -62,10 +62,16 @@ class ServiceQuote extends Model /** * The attributes that are mass assignable. + */ + /** + * Seating capacity and pickup ETA for the quote's service type, when the request asked for + * availability. Not stored. * - * @var array + * @var array{seating_capacity: ?int, pickup_eta: ?int}|null */ - protected $fillable = ['_key', 'request_id', 'company_uuid', 'service_rate_uuid', 'payload_uuid', 'amount', 'currency', 'meta', 'expired_at']; + public ?array $availability = null; + + protected $fillable = ['_key', 'request_id', 'company_uuid', 'service_rate_uuid', 'payload_uuid', 'amount', 'currency', 'meta', 'expired_at', 'distance', 'time']; /** * Dynamic attributes that are appended to object. @@ -154,6 +160,11 @@ public static function resolveFromRequest(Request|CreateOrderRequest|UpdateOrder $serviceQuote = static::where('public_id', $serviceQuote)->first(); } + // A quote from another company is treated as not found. + if ($serviceQuote instanceof self && session('company') && $serviceQuote->company_uuid !== session('company')) { + return null; + } + return $serviceQuote; } diff --git a/server/src/Models/Telematic.php b/server/src/Models/Telematic.php index 513f9aa1e..c89e30ba0 100644 --- a/server/src/Models/Telematic.php +++ b/server/src/Models/Telematic.php @@ -377,7 +377,7 @@ public function getConnectionStatus(): string return 'never_connected'; } - $minutesOffline = $this->last_seen_at->diffInMinutes(now()); + $minutesOffline = (int) $this->last_seen_at->diffInMinutes(now(), true); if ($minutesOffline <= 5) { return 'online'; diff --git a/server/src/Models/Warranty.php b/server/src/Models/Warranty.php index e5da4e2be..e0e858161 100644 --- a/server/src/Models/Warranty.php +++ b/server/src/Models/Warranty.php @@ -226,7 +226,7 @@ public function getDaysRemainingAttribute(): ?int return 0; } - return now()->diffInDays($this->end_date, false); + return (int) now()->diffInDays($this->end_date, false); } /** diff --git a/server/src/Models/WorkOrder.php b/server/src/Models/WorkOrder.php index f6688816a..4520644e8 100644 --- a/server/src/Models/WorkOrder.php +++ b/server/src/Models/WorkOrder.php @@ -261,7 +261,7 @@ public function getDaysUntilDueAttribute(): ?int return null; } - $days = now()->diffInDays($this->due_at, false); + $days = (int) now()->diffInDays($this->due_at, false); return $days; } @@ -526,7 +526,7 @@ public function getActualDuration(): ?float return null; } - return $this->opened_at->diffInHours($this->closed_at); + return (int) $this->opened_at->diffInHours($this->closed_at, true); } /** diff --git a/server/src/Notifications/OrderUpdate.php b/server/src/Notifications/OrderUpdate.php new file mode 100644 index 000000000..f7729d8bf --- /dev/null +++ b/server/src/Notifications/OrderUpdate.php @@ -0,0 +1,42 @@ +data = ['id' => $order->public_id, 'type' => $event]; + } + + public function via($notifiable) + { + return [FcmChannel::class, ApnChannel::class]; + } + + public function toFcm($notifiable) + { + return PushNotification::createFcmMessage($this->title, $this->message, $this->data); + } + + public function toApn($notifiable) + { + return PushNotification::createApnMessage($this->title, $this->message, $this->data, 'view_order'); + } +} diff --git a/server/src/Observers/OrderObserver.php b/server/src/Observers/OrderObserver.php index 45c9261bd..b1fdaf73f 100644 --- a/server/src/Observers/OrderObserver.php +++ b/server/src/Observers/OrderObserver.php @@ -9,6 +9,8 @@ use Fleetbase\FleetOps\Models\TrackingStatus; use Fleetbase\FleetOps\Models\Waypoint; use Fleetbase\FleetOps\Support\LiveCacheService; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; +use Fleetbase\FleetOps\Support\OrderRepricing; use Fleetbase\FleetOps\Support\TrackingPublisher; use Fleetbase\Support\ApiModelCache; use Illuminate\Support\Facades\Cache; @@ -32,6 +34,8 @@ class OrderObserver public function created(Order $order) { $this->invalidateCache($order); + + OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED); } /** @@ -73,6 +77,38 @@ public function updated(Order $order) // Public tracking channels follow status, assignment and ETA changes. app(TrackingPublisher::class)->orderChanged($order); + + if ($order->wasChanged('status')) { + // A completed order is priced again from what actually happened, when its config's + // pricing policy asks for it. This comes first, so triggers see the final price. + OrderRepricing::settle($order); + + $this->runStatusTriggers($order); + } + } + + /** + * Run the config's triggers for the order's new status: the actions of the activity it + * reached, then `order.completed` or `order.canceled` when it reached one of those. + */ + protected function runStatusTriggers(Order $order): void + { + $config = $order->currentConfig(); + if (!$config) { + return; + } + + $completed = $config->getCompletedActivity()?->code; + $canceled = $config->getCanceledActivity()?->code; + $activity = $config->getActivityByCode((string) $order->status); + + OrderConfigTriggers::activity($order, $activity); + + if ($order->status === $completed) { + OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_COMPLETED); + } elseif ($order->status === $canceled) { + OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CANCELED); + } } /** diff --git a/server/src/Providers/FleetOpsServiceProvider.php b/server/src/Providers/FleetOpsServiceProvider.php index 8633f4730..7e48459ea 100644 --- a/server/src/Providers/FleetOpsServiceProvider.php +++ b/server/src/Providers/FleetOpsServiceProvider.php @@ -58,6 +58,7 @@ class FleetOpsServiceProvider extends CoreServiceProvider public $commands = [ \Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class, \Fleetbase\FleetOps\Console\Commands\DispatchOrders::class, + \Fleetbase\FleetOps\Console\Commands\CreateOrderConfig::class, \Fleetbase\FleetOps\Console\Commands\TrackOrderDistanceAndTime::class, \Fleetbase\FleetOps\Console\Commands\FixDriverCompanies::class, \Fleetbase\FleetOps\Console\Commands\FixCustomerCompanies::class, diff --git a/server/src/Support/AdhocDispatch/AdhocDispatch.php b/server/src/Support/AdhocDispatch/AdhocDispatch.php new file mode 100644 index 000000000..c2809da59 --- /dev/null +++ b/server/src/Support/AdhocDispatch/AdhocDispatch.php @@ -0,0 +1,130 @@ +> + */ + protected static array $strategies = [ + self::BROADCAST => BroadcastStrategy::class, + self::SEQUENTIAL => SequentialStrategy::class, + ]; + + /** + * Add a strategy, or replace one, under its name. + * + * @param class-string $class + */ + public static function register(string $name, string $class): void + { + if (!is_subclass_of($class, AdhocDispatchStrategy::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . AdhocDispatchStrategy::class . '.'); + } + + static::$strategies[$name] = $class; + } + + /** + * Every registered strategy name. + */ + public static function names(): array + { + return array_keys(static::$strategies); + } + + public static function has(?string $name): bool + { + return is_string($name) && isset(static::$strategies[$name]); + } + + /** + * The strategy name for the order: its own, its config's `dispatch.adhoc` policy, its + * company's, or the default. A name that isn't registered is skipped. + */ + public static function nameFor(Order $order): string + { + foreach ([$order->adhoc_strategy, $order->currentConfig()?->policy('dispatch.adhoc.strategy')] as $name) { + if (static::has($name)) { + return $name; + } + } + + return static::companyDefault($order->company); + } + + /** + * The company's default strategy (`fleetops.adhoc_strategy`), or the default when it has none. + */ + public static function companyDefault(?Company $company): string + { + $name = $company?->getOption('fleetops.adhoc_strategy'); + + return static::has($name) ? $name : self::DEFAULT; + } + + public static function for(Order $order): AdhocDispatchStrategy + { + return static::strategy(static::nameFor($order)); + } + + /** + * The registered strategy of that name. + */ + public static function strategy(string $name): AdhocDispatchStrategy + { + return app(static::$strategies[$name]); + } + + /** + * Every registered strategy, for people choosing one. + * + * @return array + */ + public static function describe(): array + { + return array_map(function (string $name) { + $strategy = static::strategy($name); + + return ['name' => $name, 'label' => $strategy->label(), 'description' => $strategy->description()]; + }, static::names()); + } + + /** + * Strategies whose orders drivers see without holding an offer. + */ + public static function openlyListed(): array + { + return array_values(array_filter(static::names(), fn (string $name) => static::strategy($name)->listsOpenly())); + } + + /** + * Seconds a driver has to accept a one-at-a-time offer: the config's `dispatch.adhoc` + * policy, the company's, or the default. + */ + public static function offerTimeout(Order $order): int + { + $timeout = $order->currentConfig()?->policy('dispatch.adhoc.offer_timeout') ?? $order->company?->getOption('fleetops.adhoc_offer_timeout') ?? self::OFFER_TIMEOUT; + + return max(self::MIN_OFFER_TIMEOUT, min(self::MAX_OFFER_TIMEOUT, (int) $timeout)); + } +} diff --git a/server/src/Support/AdhocDispatch/AdhocOfferListing.php b/server/src/Support/AdhocDispatch/AdhocOfferListing.php new file mode 100644 index 000000000..1921231d8 --- /dev/null +++ b/server/src/Support/AdhocDispatch/AdhocOfferListing.php @@ -0,0 +1,83 @@ +getModel()->getTable(); + $names = AdhocDispatch::names(); + $open = AdhocDispatch::openlyListed(); + $inNames = implode(', ', array_fill(0, count($names), '?')); + // The config's strategy is its `dispatch.adhoc` policy, in the `policies` JSON. + $configStrategy = "(SELECT oc.policies->>'$.dispatch.adhoc.strategy' FROM order_configs oc WHERE oc.uuid = {$orders}.order_config_uuid)"; + $strategy = "CASE WHEN {$orders}.adhoc_strategy IN ({$inNames}) THEN {$orders}.adhoc_strategy" + . " WHEN {$configStrategy} IN ({$inNames}) THEN {$configStrategy} ELSE ? END"; + $bindings = [...$names, ...$names, AdhocDispatch::companyDefault($company)]; + + return $query->where(function ($query) use ($orders, $driverUuid, $open, $strategy, $bindings) { + $query->whereNull("{$orders}.adhoc") + ->orWhere("{$orders}.adhoc", 0) + ->orWhereNotNull("{$orders}.driver_assigned_uuid") + ->orWhereExists(fn ($offers) => static::offersOf($offers, $orders, $driverUuid) + ->where('order_offers.status', OrderOffer::PENDING) + ->where(fn ($expiry) => $expiry->whereNull('order_offers.expires_at')->orWhere('order_offers.expires_at', '>', now()))); + + if ($open !== []) { + $query->orWhere(function ($query) use ($orders, $driverUuid, $open, $strategy, $bindings) { + $query->whereRaw("({$strategy}) IN (" . implode(', ', array_fill(0, count($open), '?')) . ')', [...$bindings, ...$open]) + ->whereNotExists(fn ($offers) => static::offersOf($offers, $orders, $driverUuid)->where('order_offers.status', OrderOffer::DECLINED)); + }); + } + }); + } + + /** + * Put each order's open offer for the driver on it (`adhocOffer`), for the order resource's `adhoc_offer`. + */ + public static function attach(iterable $orders, string $driverUuid): void + { + // A page of results is a paginator, whose array form wraps the orders. + $orders = $orders instanceof AbstractPaginator ? $orders->getCollection() : collect($orders); + $offers = OrderOffer::where('driver_uuid', $driverUuid) + ->whereIn('order_uuid', $orders->pluck('uuid')->filter()->all()) + ->where('status', OrderOffer::PENDING) + ->get() + ->keyBy('order_uuid'); + + foreach ($orders as $order) { + $order->setRelation('adhocOffer', $offers->get($order->uuid)); + } + } + + /** + * The driver's open offer as the order resource shows it. + */ + public static function present(?OrderOffer $offer): ?array + { + return $offer ? ['status' => $offer->status, 'expires_at' => $offer->expires_at?->toISOString()] : null; + } + + protected static function offersOf($offers, string $orders, string $driverUuid) + { + return $offers->selectRaw('1') + ->from('order_offers') + ->whereColumn('order_offers.order_uuid', "{$orders}.uuid") + ->where('order_offers.driver_uuid', $driverUuid) + ->whereNull('order_offers.deleted_at'); + } +} diff --git a/server/src/Support/AdhocDispatch/BroadcastStrategy.php b/server/src/Support/AdhocDispatch/BroadcastStrategy.php new file mode 100644 index 000000000..04b6be543 --- /dev/null +++ b/server/src/Support/AdhocDispatch/BroadcastStrategy.php @@ -0,0 +1,96 @@ +offer($order); + } + + public function redispatch(Order $order, bool $testing = false): int + { + $offered = $this->offer($order, $testing)->count(); + if ($offered) { + // Restart the re-offer interval without dispatching again, which would offer it twice. + $order->forceFill(['dispatched_at' => Carbon::now()])->saveQuietly(); + } + + return $offered; + } + + public function accept(Order $order, Driver $driver): bool + { + return true; + } + + public function decline(Order $order, Driver $driver): bool + { + OrderOffers::recordDecline($order, $driver); + + return true; + } + + /** + * Offer the order to every nearby driver who hasn't declined it. Returns those drivers. + */ + protected function offer(Order $order, bool $testing = false): Collection + { + $pickup = $order->getPickupLocation(); + if (!Utils::isPoint($pickup)) { + return collect(); + } + + $drivers = DriverMatching::nearby($order, $pickup, $testing)->whereNotIn('uuid', OrderOffers::declinedDrivers($order))->get(); + foreach ($drivers as $driver) { + OrderOffers::record($order, $driver); + $this->ping($order, $driver); + } + + return $drivers; + } + + protected function ping(Order $order, Driver $driver): void + { + try { + $driver->notify(new OrderPing($order, $driver->distance ?? null)); + } catch (\Throwable) { + // One driver's failed push doesn't stop the others being offered the order. + } + } +} diff --git a/server/src/Support/AdhocDispatch/SequentialStrategy.php b/server/src/Support/AdhocDispatch/SequentialStrategy.php new file mode 100644 index 000000000..dca66939e --- /dev/null +++ b/server/src/Support/AdhocDispatch/SequentialStrategy.php @@ -0,0 +1,134 @@ +uuid)->exists()) { + $this->offerNext($order); + } + } + + /** + * Move on from an offer whose expiry job was lost, or start offers that never began. + */ + public function redispatch(Order $order, bool $testing = false): int + { + $pending = OrderOffers::pending($order); + if ($pending && $pending->expires_at?->isPast()) { + return $this->expire($pending) ? 1 : 0; + } + + if (!$pending && !OrderOffer::where('order_uuid', $order->uuid)->exists()) { + return $this->offerNext($order) ? 1 : 0; + } + + return 0; + } + + public function accept(Order $order, Driver $driver): bool + { + return OrderOffers::acceptPending($order, $driver); + } + + public function decline(Order $order, Driver $driver): bool + { + if (!OrderOffers::declinePending($order, $driver)) { + return false; + } + + $this->offerNext($order); + + return true; + } + + /** + * Close an offer that has run out and offer the order to the next driver. + */ + public function expire(OrderOffer $offer): bool + { + $expired = OrderOffer::where('uuid', $offer->uuid) + ->where('status', OrderOffer::PENDING) + ->where('expires_at', '<=', now()) + ->update(['status' => OrderOffer::EXPIRED, 'responded_at' => now()]) > 0; + + if ($expired && ($order = Order::withoutGlobalScopes()->where('uuid', $offer->order_uuid)->first())) { + OrderOffers::announceClosed($order, [$offer->driver_uuid], OrderOffer::EXPIRED); + $this->offerNext($order); + } + + return $expired; + } + + /** + * Offer the order to the nearest driver who hasn't had it yet. + */ + public function offerNext(Order $order): ?OrderOffer + { + $order->refresh(); + if ($order->started || $order->driver_assigned_uuid || in_array($order->status, ['completed', 'canceled'], true)) { + return null; + } + + $pickup = $order->getPickupLocation(); + $driver = Utils::isPoint($pickup) + ? DriverMatching::nearby($order, $pickup)->whereNotIn('uuid', OrderOffers::offeredDrivers($order))->orderBy('distance')->first() + : null; + if (!$driver) { + OrderOffers::exhausted($order); + + return null; + } + + $timeout = AdhocDispatch::offerTimeout($order); + $offer = OrderOffers::record($order, $driver, now()->addSeconds($timeout)); + + try { + $driver->notify(new OrderPing($order, $offer->distance)); + } catch (\Throwable $exception) { + Log::warning('Unable to send an order offer', ['order' => $order->public_id, 'error' => $exception->getMessage()]); + } + + ExpireOrderOffer::dispatch($offer->uuid)->delay(now()->addSeconds($timeout + 1)); + + return $offer; + } +} diff --git a/server/src/Support/DriverMatching.php b/server/src/Support/DriverMatching.php new file mode 100644 index 000000000..87aa00863 --- /dev/null +++ b/server/src/Support/DriverMatching.php @@ -0,0 +1,131 @@ +withoutGlobalScopes() + ->where(['status' => 'available', 'online' => 1]) + ->whereNull('deleted_at'); + + if (!$testing) { + $query->whereNotNull('location') + ->whereRaw('ST_Y(location) BETWEEN -90 AND 90 AND ST_X(location) BETWEEN -180 AND 180 AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0)') + ->distanceSphere('location', $pickup, $order->getAdhocPingDistance()) + ->distanceSphereValue('location', $pickup); + } + + // An app store reviewer's driver is never offered a real order. + NavigatorReview::excludeFrom($query); + + return static::forOrder($query, $order); + } + + /** + * Apply every filter for the order. + */ + public static function forOrder(Builder $query, Order $order): Builder + { + static::inCompany($query, $order->company_uuid); + + if ($order->currentConfig()?->policy('dispatch.matching.exclude_busy_drivers')) { + static::notBusy($query, $order->company_uuid); + } + + return static::forVehicleClass($query, static::vehicleClass($order)); + } + + /** + * Drivers of the company, directly or through their user. + */ + public static function inCompany(Builder $query, ?string $companyUuid): Builder + { + return $query->where(function ($query) use ($companyUuid) { + $query->where($query->getModel()->getTable() . '.company_uuid', $companyUuid) + ->orWhereHas('user', fn ($query) => $query->where('company_uuid', $companyUuid)); + }); + } + + /** + * Drivers with no current job, or whose current job has finished. A job left behind by an + * order that ended without clearing it doesn't keep the driver busy. + */ + public static function notBusy(Builder $query, ?string $companyUuid = null): Builder + { + $drivers = $query->getModel()->getTable(); + $freeStatuses = static::freeJobStatuses($companyUuid); + + return $query->where(function ($query) use ($drivers, $freeStatuses) { + $query->whereNull($drivers . '.current_job_uuid') + ->orWhereNotExists(function ($jobs) use ($drivers, $freeStatuses) { + $jobs->selectRaw('1') + ->from('orders') + ->whereColumn('orders.uuid', $drivers . '.current_job_uuid') + ->whereNull('orders.deleted_at') + ->whereNotIn('orders.status', $freeStatuses); + }); + }); + } + + /** + * The statuses at which an order no longer keeps its driver busy: completed, canceled, and + * every terminal activity of the company's order configs. + */ + public static function freeJobStatuses(?string $companyUuid): array + { + $statuses = self::FREE_JOB_STATUSES; + if ($companyUuid) { + foreach (OrderConfig::where('company_uuid', $companyUuid)->get() as $config) { + $statuses = array_merge($statuses, $config->getTerminalActivityCodes()); + } + } + + return array_values(array_unique(array_filter($statuses, 'is_string'))); + } + + /** + * Drivers whose vehicle is of the class, compared without case. No class matches everyone. + */ + public static function forVehicleClass(Builder $query, ?string $class): Builder + { + if ($class === null || trim($class) === '') { + return $query; + } + + return $query->whereHas('vehicle', fn ($query) => $query->whereRaw('LOWER(type) = ?', [strtolower(trim($class))])); + } + + /** + * The vehicle type the order needs, if any (`required_vehicle_type`). + */ + public static function vehicleClass(Order $order): ?string + { + $class = $order->required_vehicle_type; + + return is_string($class) && trim($class) !== '' ? trim($class) : null; + } +} diff --git a/server/src/Support/DriverRatings.php b/server/src/Support/DriverRatings.php new file mode 100644 index 000000000..7d9608daa --- /dev/null +++ b/server/src/Support/DriverRatings.php @@ -0,0 +1,58 @@ +uuid)->exists()) { + return false; + } + + try { + DriverRating::create([ + 'company_uuid' => $order->company_uuid, + 'order_uuid' => $order->uuid, + 'driver_uuid' => $order->driver_assigned_uuid, + 'customer_uuid' => $order->customer_uuid, + 'customer_type' => $order->customer_type, + 'stars' => max(1, min(5, $stars)), + 'comment' => $comment !== null && trim($comment) !== '' ? trim($comment) : null, + ]); + } catch (QueryException) { + // Another request rated the order first; `order_uuid` is unique. + return false; + } + + static::refresh($order->driver_assigned_uuid); + + return true; + } + + /** + * Work out the driver's average and count again from their ratings. + */ + public static function refresh(?string $driverUuid): void + { + $ratings = DriverRating::where('driver_uuid', $driverUuid)->whereNull('deleted_at'); + $count = (clone $ratings)->count(); + + Driver::withoutGlobalScopes()->where('uuid', $driverUuid)->update([ + 'rating_average' => $count ? round((float) (clone $ratings)->avg('stars'), 2) : null, + 'rating_count' => $count, + ]); + } +} diff --git a/server/src/Support/FleetOps.php b/server/src/Support/FleetOps.php index a4593dc31..fc873e3e3 100644 --- a/server/src/Support/FleetOps.php +++ b/server/src/Support/FleetOps.php @@ -3,18 +3,16 @@ namespace Fleetbase\FleetOps\Support; use Fleetbase\FleetOps\Models\OrderConfig; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; use Fleetbase\Models\Company; -use Illuminate\Support\Str; class FleetOps { /** * Creates or retrieves an existing transport configuration for a given company. * - * This method attempts to find a transport configuration (`OrderConfig`) for the specified company. - * If such a configuration exists, it's returned. Otherwise, a new configuration is created with default values, - * such as the company UUID, key, core service flag, status, version, tags, and predefined workflow steps. - * These steps include 'created', 'enroute', 'started', 'completed', and 'dispatched', each with specific attributes. + * The configuration comes from the `transport` order config template: an order is created, + * dispatched, started, driven and completed. * * @param Company $company the company for which the transport configuration is being created or retrieved * @@ -22,121 +20,6 @@ class FleetOps */ public static function createTransportConfig(Company $company): OrderConfig { - return OrderConfig::firstOrCreate( - [ - 'company_uuid' => $company->uuid, - 'key' => 'transport', - 'namespace' => 'system:order-config:transport', - ], - static::transportConfigDefaults() - ); - } - - private static function transportConfigDefaults(): array - { - return [ - 'name' => 'Transport', - 'key' => 'transport', - 'namespace' => 'system:order-config:transport', - 'description' => 'Default order configuration for transport', - 'core_service' => 1, - 'status' => 'private', - 'version' => '0.0.1', - 'tags' => ['transport', 'delivery'], - 'entities' => [], - 'meta' => [], - 'flow' => [ - 'created' => [ - 'key' => 'created', - 'code' => 'created', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Created', - 'actions' => [], - 'details' => 'New order was created.', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['dispatched'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'enroute' => [ - 'key' => 'enroute', - 'code' => 'enroute', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Driver Enroute', - 'actions' => [], - 'details' => 'Driver is en-route.', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['completed'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'started' => [ - 'key' => 'started', - 'code' => 'started', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Started', - 'actions' => [], - 'details' => 'Order has been started', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['enroute'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'completed' => [ - 'key' => 'completed', - 'code' => 'completed', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Completed', - 'actions' => [], - 'details' => 'Order has been completed.', - 'options' => [], - 'complete' => true, - 'entities' => [], - 'sequence' => 0, - 'activities' => [], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'dispatched' => [ - 'key' => 'dispatched', - 'code' => 'dispatched', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Dispatched', - 'actions' => [], - 'details' => 'Order has been dispatched.', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['started'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - ], - ]; + return OrderConfigTemplates::create('transport', $company); } } diff --git a/server/src/Support/OrderChat.php b/server/src/Support/OrderChat.php new file mode 100644 index 000000000..401c64d9f --- /dev/null +++ b/server/src/Support/OrderChat.php @@ -0,0 +1,148 @@ + $order->company_uuid, + 'created_by_uuid' => $customerUser, + 'name' => 'Order ' . $order->public_id, + 'meta' => ['order_public_id' => $order->public_id, 'kind' => 'group'], + ]); + $order->forceFill(['chat_channel_uuid' => $channel->uuid])->saveQuietly(); + } + + static::participant($channel, $customerUser, 'customer'); + static::participant($channel, $driverUser, 'driver'); + + return $channel; + }); + } + + /** + * The order's channel if it was opened. + */ + public static function find(Order $order): ?ChatChannel + { + return $order->chat_channel_uuid ? ChatChannel::where('uuid', $order->chat_channel_uuid)->first() : null; + } + + /** + * Stop new messages in the order's channel. Its history stays readable. + */ + public static function close(Order $order): bool + { + $channel = static::find($order); + if (!$channel) { + return false; + } + + $channel->meta = array_merge((array) ($channel->meta ?? []), ['closed_at' => now()->toISOString()]); + + return $channel->save(); + } + + /** + * No one can write: the channel was closed, or the order has finished. + */ + public static function isClosed(Order $order, ?ChatChannel $channel = null): bool + { + $channel ??= static::find($order); + + return (bool) data_get($channel, 'meta.closed_at') || (bool) $order->config()?->isTerminalActivityCode($order->status); + } + + /** + * Messages oldest first, each marked as the customer's or the driver's. + */ + public static function messages(ChatChannel $channel, string $customerUser): Collection + { + return ChatMessage::where('chat_channel_uuid', $channel->uuid) + ->with('sender') + ->latest() + ->limit(self::MESSAGE_LIMIT) + ->get() + ->reverse() + ->values() + ->map(fn (ChatMessage $message) => [ + 'id' => $message->public_id ?? $message->uuid, + 'from' => data_get($message, 'sender.user_uuid') === $customerUser ? 'customer' : 'driver', + 'text' => (string) $message->content, + 'sent_at' => $message->created_at?->toISOString(), + ]); + } + + /** + * Send a message as the customer, and tell the driver. + */ + public static function send(ChatChannel $channel, string $customerUser, string $text): ChatMessage + { + return static::asUser($customerUser, function () use ($channel, $customerUser, $text) { + $sender = static::participant($channel, $customerUser, 'customer'); + $message = ChatMessage::create([ + 'company_uuid' => $channel->company_uuid, + 'chat_channel_uuid' => $channel->uuid, + 'sender_uuid' => $sender->uuid, + 'content' => $text, + ]); + $message->notifyParticipants(); + + return $message; + }); + } + + /** + * Core's chat logs record who added a participant from the signed-in user, which on a + * customer request is the key's owner rather than the customer, so the customer is signed in + * for the change. + */ + protected static function asUser(string $userUuid, callable $callback): mixed + { + $previous = session('user'); + session(['user' => $userUuid]); + + try { + return $callback(); + } finally { + session(['user' => $previous]); + } + } + + protected static function participant(ChatChannel $channel, string $userUuid, string $role): ChatParticipant + { + return ChatParticipant::firstOrCreate( + ['chat_channel_uuid' => $channel->uuid, 'user_uuid' => $userUuid], + ['company_uuid' => $channel->company_uuid, 'meta' => ['role' => $role]] + ); + } +} diff --git a/server/src/Support/OrderConfig/Actions/Action.php b/server/src/Support/OrderConfig/Actions/Action.php new file mode 100644 index 000000000..859d484a6 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/Action.php @@ -0,0 +1,95 @@ +name; + } + + public function label(): string + { + return $this->label; + } + + public function description(): string + { + return $this->description; + } + + public function parameters(): array + { + return $this->parameters; + } + + /** + * Fill `{placeholders}` in the text: `{driver.name}`, `{driver.first_name}`, + * `{customer.name}`, `{order.id}`, `{order.tracking_number}`, `{order.status}`, and the + * activity's `{activity.status}` and `{activity.details}`. An unknown placeholder is left out. + */ + public static function render(?string $text, Order $order, array $context = []): string + { + if ($text === null || $text === '') { + return ''; + } + + $driverName = static::driverName($order); + $values = [ + 'driver.name' => $driverName ?? '', + 'driver.first_name' => $driverName ? (string) strtok($driverName, ' ') : '', + 'customer.name' => (string) data_get($order, 'customer.name', ''), + 'order.id' => (string) $order->public_id, + 'order.tracking_number' => (string) data_get($order, 'trackingNumber.tracking_number', ''), + 'order.status' => (string) $order->status, + 'activity.status' => (string) data_get($context, 'activity.status', ''), + 'activity.details' => (string) data_get($context, 'activity.details', ''), + ]; + + $rendered = preg_replace_callback('/\{\s*([a-z_]+(?:\.[a-z_]+)*)\s*\}/i', fn ($match) => $values[strtolower($match[1])] ?? '', $text); + + return trim(preg_replace('/\s{2,}/', ' ', $rendered)); + } + + /** + * The assigned driver's name, read without loading their whole record. + */ + public static function driverName(Order $order): ?string + { + if ($order->relationLoaded('driverAssigned')) { + return data_get($order, 'driverAssigned.name'); + } + + $userUuid = $order->driver_assigned_uuid ? Driver::withoutGlobalScopes()->where('uuid', $order->driver_assigned_uuid)->value('user_uuid') : null; + + return $userUuid ? User::where('uuid', $userUuid)->value('name') : null; + } +} diff --git a/server/src/Support/OrderConfig/Actions/CancelOrder.php b/server/src/Support/OrderConfig/Actions/CancelOrder.php new file mode 100644 index 000000000..2d8f85548 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/CancelOrder.php @@ -0,0 +1,27 @@ + 'Why the order was canceled.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + if ($order->config()?->isTerminalActivityCode($order->status)) { + return; + } + + $order->cancelWithReason(isset($params['reason']) ? (string) $params['reason'] : null); + } +} diff --git a/server/src/Support/OrderConfig/Actions/CloseChat.php b/server/src/Support/OrderConfig/Actions/CloseChat.php new file mode 100644 index 000000000..70d93d871 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/CloseChat.php @@ -0,0 +1,21 @@ + 'Notification title. Defaults to the activity\'s status. Placeholders such as {driver.first_name} are filled in.', + 'message' => 'Notification message. Defaults to the activity\'s details.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + $customer = $order->customer; + if (!$customer || !method_exists($customer, 'notify')) { + return; + } + + $title = static::render($params['title'] ?? data_get($context, 'activity.status'), $order, $context); + $message = static::render($params['message'] ?? data_get($context, 'activity.details'), $order, $context); + if ($title === '' && $message === '') { + return; + } + + $customer->notify(new OrderUpdate($order, $title, $message, static::eventType($context))); + } + + /** + * The `type` apps receive in the push: the activity code or event, as `order_`. + */ + public static function eventType(array $context): string + { + $name = data_get($context, 'activity.code') ?? data_get($context, 'event', 'update'); + + return 'order_' . preg_replace('/[^a-z0-9_]+/', '_', strtolower((string) $name)); + } +} diff --git a/server/src/Support/OrderConfig/Actions/NotifyDriver.php b/server/src/Support/OrderConfig/Actions/NotifyDriver.php new file mode 100644 index 000000000..a132d68b9 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/NotifyDriver.php @@ -0,0 +1,36 @@ + 'Notification title. Defaults to the activity\'s status.', + 'message' => 'Notification message. Defaults to the activity\'s details.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + $driver = $order->driver_assigned_uuid ? $order->loadAssignedDriver()->driverAssigned : null; + if (!$driver) { + return; + } + + $title = static::render($params['title'] ?? data_get($context, 'activity.status'), $order, $context); + $message = static::render($params['message'] ?? data_get($context, 'activity.details'), $order, $context); + if ($title === '' && $message === '') { + return; + } + + $driver->notify(new OrderUpdate($order, $title, $message, NotifyCustomer::eventType($context))); + } +} diff --git a/server/src/Support/OrderConfig/Actions/OpenChat.php b/server/src/Support/OrderConfig/Actions/OpenChat.php new file mode 100644 index 000000000..6260d7aa6 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/OpenChat.php @@ -0,0 +1,21 @@ + 'The meta key, in dot notation.', + 'value' => 'The value. `{now}` writes the current time.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + $key = $params['key'] ?? null; + if (!is_string($key) || trim($key) === '') { + return; + } + + $value = $params['value'] ?? null; + $order->updateMeta(trim($key), $value === '{now}' ? now()->toISOString() : $value); + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigActions.php b/server/src/Support/OrderConfig/OrderConfigActions.php new file mode 100644 index 000000000..f77dbe2fa --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigActions.php @@ -0,0 +1,73 @@ +> + */ + protected static array $actions = [ + 'notify_customer' => NotifyCustomer::class, + 'notify_driver' => NotifyDriver::class, + 'open_chat' => OpenChat::class, + 'close_chat' => CloseChat::class, + 'set_meta' => SetMeta::class, + 'cancel' => CancelOrder::class, + ]; + + /** + * Add an action, or replace one, under its name. + * + * @param class-string $class + */ + public static function register(string $class): void + { + if (!is_subclass_of($class, OrderConfigAction::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . OrderConfigAction::class . '.'); + } + + static::$actions[app($class)->name()] = $class; + } + + public static function has(?string $name): bool + { + return is_string($name) && isset(static::$actions[$name]); + } + + public static function get(string $name): ?OrderConfigAction + { + return static::has($name) ? app(static::$actions[$name]) : null; + } + + public static function names(): array + { + return array_keys(static::$actions); + } + + /** + * Every action, for people configuring triggers. + * + * @return array + */ + public static function describe(): array + { + return array_map(function (string $name) { + $action = static::get($name); + + return ['name' => $name, 'label' => $action->label(), 'description' => $action->description(), 'parameters' => $action->parameters()]; + }, static::names()); + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigPolicies.php b/server/src/Support/OrderConfig/OrderConfigPolicies.php new file mode 100644 index 000000000..979d6ea44 --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigPolicies.php @@ -0,0 +1,149 @@ +> + */ + protected static array $policies = [ + 'dispatch.adhoc' => AdhocDispatchPolicy::class, + 'dispatch.matching' => DriverMatchingPolicy::class, + 'customer.ordering' => CustomerOrderingPolicy::class, + 'customer.cancellation' => CustomerCancellationPolicy::class, + 'customer.interactions' => CustomerInteractionsPolicy::class, + 'pricing' => PricingPolicy::class, + ]; + + /** + * Add a policy, or replace one, under its key. + * + * @param class-string $class + */ + public static function register(string $class): void + { + if (!is_subclass_of($class, OrderConfigPolicy::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . OrderConfigPolicy::class . '.'); + } + + static::$policies[app($class)->key()] = $class; + } + + /** + * @return array + */ + public static function all(): array + { + return array_map(fn (string $class) => app($class), static::$policies); + } + + public static function get(string $key): ?OrderConfigPolicy + { + return isset(static::$policies[$key]) ? app(static::$policies[$key]) : null; + } + + /** + * Every policy's defaults, nested by key. + */ + public static function defaults(): array + { + $defaults = []; + foreach (static::all() as $key => $policy) { + data_set($defaults, $key, $policy->defaults()); + } + + return $defaults; + } + + /** + * The stored policies with every missing setting filled in from its default. Settings of + * policies that aren't registered are kept as stored. + */ + public static function resolve(?array $stored): array + { + $resolved = $stored ?? []; + foreach (static::all() as $key => $policy) { + $settings = data_get($resolved, $key); + data_set($resolved, $key, array_replace($policy->defaults(), is_array($settings) ? $settings : [])); + } + + return $resolved; + } + + /** + * Validation rules for a request carrying `policies`. + */ + public static function rules(string $prefix = 'policies'): array + { + $rules = [$prefix => ['nullable', 'array']]; + foreach (static::all() as $key => $policy) { + $rules[$prefix . '.' . $key] = ['nullable', 'array']; + foreach ($policy->rules() as $setting => $settingRules) { + $rules[$prefix . '.' . $key . '.' . $setting] = $settingRules; + } + } + + return $rules; + } + + /** + * Every policy, for people configuring them, with each setting's type (`boolean`, `number`, + * `text`, `list` or `choice`), choices, and for numbers the `min` and `max` its rules allow. + * + * @return array + */ + public static function describe(): array + { + return array_values(array_map(function (OrderConfigPolicy $policy) { + $rules = $policy->rules(); + $choices = $policy->choices(); + $settings = []; + foreach ($policy->defaults() as $name => $default) { + $settingRules = (array) ($rules[$name] ?? []); + $type = match (true) { + isset($choices[$name]) => 'choice', + is_bool($default) || in_array('boolean', $settingRules, true) => 'boolean', + is_array($default) || in_array('array', $settingRules, true) => 'list', + in_array('integer', $settingRules, true) || in_array('numeric', $settingRules, true) => 'number', + default => 'text', + }; + $settings[] = ['name' => $name, 'type' => $type, 'default' => $default, 'choices' => $choices[$name] ?? null] + ($type === 'number' ? static::bounds($settingRules) : []); + } + + return [ + 'key' => $policy->key(), + 'label' => $policy->label(), + 'description' => $policy->description(), + 'defaults' => $policy->defaults(), + 'settings' => $settings, + ]; + }, static::all())); + } + + /** + * The `min` and `max` in a setting's rules, as numbers, when it has them. + */ + protected static function bounds(array $rules): array + { + $bounds = []; + foreach ($rules as $rule) { + if (is_string($rule) && preg_match('/^(min|max):(-?\d+(?:\.\d+)?)$/', $rule, $match)) { + $bounds[$match[1]] = $match[2] + 0; + } + } + + return $bounds; + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigTemplates.php b/server/src/Support/OrderConfig/OrderConfigTemplates.php new file mode 100644 index 000000000..bff72ec67 --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigTemplates.php @@ -0,0 +1,160 @@ +> + */ + protected static array $templates = [ + 'transport' => TransportTemplate::class, + 'passenger' => PassengerTemplate::class, + ]; + + /** + * Add a template, or replace one, under its key. + * + * @param class-string $class + */ + public static function register(string $class): void + { + if (!is_subclass_of($class, OrderConfigTemplate::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . OrderConfigTemplate::class . '.'); + } + + static::$templates[app($class)->key()] = $class; + } + + public static function has(?string $key): bool + { + return is_string($key) && isset(static::$templates[$key]); + } + + public static function get(string $key): ?OrderConfigTemplate + { + return static::has($key) ? app(static::$templates[$key]) : null; + } + + /** + * Every template, for people choosing one, with what it sets up: the step labels along its + * main path and how many steps, policies, triggers and custom fields it brings. + * + * @return array, summary: array{steps: int, policies: int, triggers: int, custom_fields: int}}> + */ + public static function describe(): array + { + return array_values(array_map(function (string $class) { + $template = app($class); + $attributes = $template->attributes(); + $flow = is_array($attributes['flow'] ?? null) ? $attributes['flow'] : []; + + return [ + 'key' => $template->key(), + 'name' => $template->name(), + 'description' => $template->description(), + 'steps' => static::mainPath($flow, data_get($attributes, 'meta.lifecycle.initial')), + 'summary' => [ + 'steps' => count($flow), + 'policies' => static::countPolicies($attributes['policies'] ?? []), + 'triggers' => count($attributes['triggers'] ?? []) + array_sum(array_map(fn ($activity) => count($activity['actions'] ?? []), $flow)), + 'custom_fields' => count($template->customFields()), + ], + ]; + }, static::$templates)); + } + + /** + * The status labels from the first step, following each step's first next step. + */ + protected static function mainPath(array $flow, ?string $initial = null): array + { + $code = $initial ?: (isset($flow['created']) ? 'created' : array_key_first($flow)); + $labels = []; + $seen = []; + while ($code && isset($flow[$code]) && !isset($seen[$code])) { + $seen[$code] = true; + $labels[] = (string) ($flow[$code]['status'] ?? $code); + $code = $flow[$code]['activities'][0] ?? null; + } + + return $labels; + } + + /** + * How many registered policies the template sets anything on. + */ + protected static function countPolicies(array $policies): int + { + return count(array_filter(array_keys(OrderConfigPolicies::all()), fn (string $key) => !empty(data_get($policies, $key)))); + } + + /** + * The attributes of the system config made from the template (`system:order-config:`). + */ + public static function attributes(string $key): array + { + $template = static::get($key); + if (!$template) { + throw new \InvalidArgumentException('No order config template named ' . $key . '.'); + } + + return array_replace([ + 'name' => $template->name(), + 'key' => $template->key(), + 'namespace' => 'system:order-config:' . $template->key(), + 'core_service' => 1, + 'status' => 'private', + 'version' => '0.0.1', + ], $template->attributes()); + } + + /** + * The company's config from the template, made when it doesn't have one yet. Without a name + * it is the company's system config for the template (`system:order-config:`), found + * again on the next call; with a name it is a new config of that name. + */ + public static function create(string $key, Company $company, ?string $name = null): OrderConfig + { + $template = static::get($key); + if (!$template) { + throw new \InvalidArgumentException('No order config template named ' . $key . '.'); + } + + $attributes = static::attributes($key); + + if ($name) { + $config = OrderConfig::create(array_replace($attributes, [ + 'company_uuid' => $company->uuid, + 'name' => $name, + 'core_service' => 0, + 'key' => Str::slug($name), + 'namespace' => Str::slug($company->name) . ':order-config:' . Str::slug($name), + ])); + } else { + $config = OrderConfig::firstOrCreate( + ['company_uuid' => $company->uuid, 'key' => $attributes['key'], 'namespace' => $attributes['namespace']], + $attributes + ); + } + + if ($config->wasRecentlyCreated) { + foreach ($template->customFields() as $field) { + $config->customFields()->create(array_replace($field, ['company_uuid' => $company->uuid])); + } + } + + return $config; + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigTriggers.php b/server/src/Support/OrderConfig/OrderConfigTriggers.php new file mode 100644 index 000000000..b67b61887 --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigTriggers.php @@ -0,0 +1,165 @@ + 'order.activity', + 'activity' => ['code' => $activity->code, 'status' => $activity->status, 'details' => $activity->details], + ]; + + return static::run($order, (array) ($activity->get('actions') ?? []), $context); + } + + /** + * An order event happened: run the config's triggers for it. + */ + public static function fire(Order $order, string $event, array $context = []): int + { + return static::run($order, static::forEvent($order, $event), ['event' => $event] + $context); + } + + /** + * The driver of an order reported a position: fire `driver.approaching` for each target + * the driver has just come close to. + */ + public static function driverMoved(Driver $driver, ?Order $order): int + { + if (!$order || !Utils::isPoint($driver->location)) { + return 0; + } + + $ran = 0; + foreach (static::forEvent($order, self::DRIVER_APPROACHING) as $trigger) { + $target = data_get($trigger, 'options.target', 'pickup') === 'dropoff' ? 'dropoff' : 'pickup'; + $distance = (int) data_get($trigger, 'options.distance', self::APPROACHING_DISTANCE); + $point = $target === 'dropoff' ? $order->payload?->dropoff?->location : $order->getPickupLocation(); + + if (!Utils::isPoint($point) || Utils::vincentyGreatCircleDistance($driver->location, $point) > $distance) { + continue; + } + + $onceKey = 'fleetops:order-config:approaching:' . $order->uuid . ':' . $target . ':' . $distance; + if (!static::passes($order, $trigger) || !Cache::add($onceKey, 1, now()->addHours(12))) { + continue; + } + + $ran += static::run($order, [$trigger], ['event' => self::DRIVER_APPROACHING, 'target' => $target]); + } + + return $ran; + } + + /** + * The config's triggers for the event. + */ + public static function forEvent(Order $order, string $event): array + { + $triggers = $order->currentConfig()?->triggers; + + return array_values(array_filter(is_array($triggers) ? $triggers : [], fn ($trigger) => is_array($trigger) && ($trigger['event'] ?? null) === $event)); + } + + /** + * Whether every condition of the trigger passes for the order. A trigger without any always passes. + */ + public static function passes(Order $order, array $trigger): bool + { + $when = $trigger['when'] ?? []; + if (!is_array($when) || $when === []) { + return true; + } + + try { + return collect($when)->every(fn ($logic) => is_array($logic) && (new Logic($logic))->passes($order)); + } catch (\Throwable $exception) { + Log::warning('Skipped an order config trigger whose conditions could not be read', ['order' => $order->public_id, 'error' => $exception->getMessage()]); + + return false; + } + } + + /** + * Queue (or run) each trigger whose action is registered and whose conditions pass. + */ + protected static function run(Order $order, array $triggers, array $context): int + { + $ran = 0; + foreach ($triggers as $trigger) { + $name = is_array($trigger) ? ($trigger['action'] ?? null) : null; + if (!OrderConfigActions::has($name) || !static::passes($order, $trigger)) { + continue; + } + + $params = is_array($trigger['params'] ?? null) ? $trigger['params'] : []; + + try { + if (static::$runImmediately) { + OrderConfigActions::get($name)->handle($order, $params, $context); + } else { + dispatch(new RunOrderConfigAction($order, $name, $params, $context)); + } + $ran++; + } catch (\Throwable $exception) { + Log::warning('An order config action failed', ['order' => $order->public_id, 'action' => $name, 'error' => $exception->getMessage()]); + } + } + + return $ran; + } +} diff --git a/server/src/Support/OrderConfig/Policies/AdhocDispatchPolicy.php b/server/src/Support/OrderConfig/Policies/AdhocDispatchPolicy.php new file mode 100644 index 000000000..e35343e4e --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/AdhocDispatchPolicy.php @@ -0,0 +1,59 @@ + false, + // A registered strategy name; empty uses the company's default. + 'strategy' => null, + // Seconds a driver has to accept a one-at-a-time offer; empty uses the company's. + 'offer_timeout' => null, + // Metres around the pickup to look for drivers; empty uses the order's or company's. + 'radius' => null, + // When every driver declined or let the offer run out: keep the order open for + // the operator, or cancel it. + 'on_exhausted' => self::KEEP_OPEN, + ]; + } + + public function choices(): array + { + return [ + 'strategy' => array_map(fn ($strategy) => ['value' => $strategy['name'], 'label' => $strategy['label']], AdhocDispatch::describe()), + 'on_exhausted' => [ + ['value' => self::KEEP_OPEN, 'label' => 'Keep the order open for the operator'], + ['value' => self::CANCEL, 'label' => 'Cancel the order'], + ], + ]; + } + + public function rules(): array + { + return [ + 'customer_orders' => ['nullable', 'boolean'], + 'strategy' => ['nullable', 'string', Rule::in(AdhocDispatch::names())], + 'offer_timeout' => ['nullable', 'integer', 'min:' . AdhocDispatch::MIN_OFFER_TIMEOUT, 'max:' . AdhocDispatch::MAX_OFFER_TIMEOUT], + 'radius' => ['nullable', 'integer', 'min:100', 'max:200000'], + 'on_exhausted' => ['nullable', Rule::in([self::KEEP_OPEN, self::CANCEL])], + ]; + } +} diff --git a/server/src/Support/OrderConfig/Policies/CustomerCancellationPolicy.php b/server/src/Support/OrderConfig/Policies/CustomerCancellationPolicy.php new file mode 100644 index 000000000..4f80d46bf --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/CustomerCancellationPolicy.php @@ -0,0 +1,27 @@ + true, + // An activity code: once the order has reached it, the customer can no longer cancel. + // Empty: any time before the order finishes. + 'allowed_until' => null, + ]; + + protected array $choices = ['allowed_until' => 'activity']; + + protected array $rules = [ + 'enabled' => ['nullable', 'boolean'], + 'allowed_until' => ['nullable', 'string', 'max:64'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/CustomerInteractionsPolicy.php b/server/src/Support/OrderConfig/Policies/CustomerInteractionsPolicy.php new file mode 100644 index 000000000..9f8d6a94f --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/CustomerInteractionsPolicy.php @@ -0,0 +1,25 @@ + false, + 'rating' => false, + 'share_tracking' => false, + ]; + + protected array $rules = [ + 'chat' => ['nullable', 'boolean'], + 'rating' => ['nullable', 'boolean'], + 'share_tracking' => ['nullable', 'boolean'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/CustomerOrderingPolicy.php b/server/src/Support/OrderConfig/Policies/CustomerOrderingPolicy.php new file mode 100644 index 000000000..cc1614df6 --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/CustomerOrderingPolicy.php @@ -0,0 +1,33 @@ + [], + // The order must be placed with a service quote. + 'require_quote' => false, + // While an earlier order of this config paid by one of these methods is completed but + // not settled, the customer can't place another. + 'require_settlement' => [], + ]; + + protected array $rules = [ + 'payment_methods' => ['nullable', 'array'], + 'payment_methods.*' => ['string', 'max:32'], + 'require_quote' => ['nullable', 'boolean'], + 'require_settlement' => ['nullable', 'array'], + 'require_settlement.*' => ['string', 'max:32'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/DriverMatchingPolicy.php b/server/src/Support/OrderConfig/Policies/DriverMatchingPolicy.php new file mode 100644 index 000000000..c830e7b30 --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/DriverMatchingPolicy.php @@ -0,0 +1,25 @@ + false, + // Drivers whose current order hasn't finished aren't offered another. + 'exclude_busy_drivers' => false, + ]; + + protected array $rules = [ + 'vehicle_type' => ['nullable', 'boolean'], + 'exclude_busy_drivers' => ['nullable', 'boolean'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/Policy.php b/server/src/Support/OrderConfig/Policies/Policy.php new file mode 100644 index 000000000..17425c4ca --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/Policy.php @@ -0,0 +1,48 @@ +key; + } + + public function label(): string + { + return $this->label; + } + + public function description(): string + { + return $this->description; + } + + public function defaults(): array + { + return $this->defaults; + } + + public function rules(): array + { + return $this->rules; + } + + public function choices(): array + { + return $this->choices; + } +} diff --git a/server/src/Support/OrderConfig/Policies/PricingPolicy.php b/server/src/Support/OrderConfig/Policies/PricingPolicy.php new file mode 100644 index 000000000..63f8ec0f0 --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/PricingPolicy.php @@ -0,0 +1,26 @@ + false, + // The activity from which distance and time are measured. Empty: from when the order started. + 'metering_starts_at' => null, + ]; + + protected array $choices = ['metering_starts_at' => 'activity']; + + protected array $rules = [ + 'reprice_on_completion' => ['nullable', 'boolean'], + 'metering_starts_at' => ['nullable', 'string', 'max:64'], + ]; +} diff --git a/server/src/Support/OrderConfig/Templates/PassengerTemplate.php b/server/src/Support/OrderConfig/Templates/PassengerTemplate.php new file mode 100644 index 000000000..944fa1aca --- /dev/null +++ b/server/src/Support/OrderConfig/Templates/PassengerTemplate.php @@ -0,0 +1,108 @@ + ['action' => 'notify_customer', 'params' => ['title' => $title, 'message' => $message]]; + + return [ + 'description' => $this->description, + 'tags' => ['passenger', 'on-demand'], + 'entities' => [], + 'meta' => [ + 'lifecycle' => [ + 'initial' => 'created', + 'completed' => 'completed', + 'canceled' => 'canceled', + 'terminal' => ['no_show'], + 'strict_transitions' => true, + ], + ], + 'policies' => [ + 'dispatch' => [ + 'adhoc' => ['customer_orders' => true, 'strategy' => 'sequential', 'offer_timeout' => 20, 'on_exhausted' => 'cancel'], + 'matching' => ['vehicle_type' => true, 'exclude_busy_drivers' => true], + ], + 'customer' => [ + 'ordering' => ['payment_methods' => ['cash', 'card'], 'require_quote' => true, 'require_settlement' => ['card']], + 'cancellation' => ['enabled' => true, 'allowed_until' => 'in_progress'], + 'interactions' => ['chat' => true, 'rating' => true, 'share_tracking' => true], + ], + 'pricing' => ['reprice_on_completion' => true, 'metering_starts_at' => 'in_progress'], + ], + 'triggers' => [ + [ + 'event' => OrderConfigTriggers::DRIVER_APPROACHING, + 'options' => ['target' => 'pickup', 'distance' => 400], + 'when' => [['type' => 'and', 'conditions' => [['field' => 'status', 'operator' => 'equal', 'value' => 'started']]]], + ] + $notify('Your driver is almost there', '{driver.first_name} is about a minute away.'), + ['event' => OrderConfigTriggers::DISPATCH_OFFER_EXHAUSTED] + $notify('No driver found', 'No drivers are free right now. Try again in a few minutes.'), + [ + 'event' => OrderConfigTriggers::ORDER_CANCELED, + // The customer was already told nobody was found. + 'when' => [['type' => 'and', 'conditions' => [['field' => 'dispatch_outcome', 'operator' => 'notEqual', 'value' => 'no_driver_found']]]], + ] + $notify('Your trip was canceled', "You haven't been charged. You can book again."), + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'close_chat'], + ], + 'flow' => [ + 'created' => static::activity('created', 'Trip requested', 'The customer requested a trip.', ['dispatched']), + 'dispatched' => static::activity('dispatched', 'Finding a driver', 'Looking for a driver nearby.', ['started']), + 'started' => static::activity('started', 'Driver on the way', 'The driver accepted and is on the way to the pickup.', ['arrived'], false, [ + $notify('Your driver is on the way', '{driver.first_name} accepted your trip.'), + ['action' => 'open_chat'], + ]), + 'arrived' => static::activity('arrived', 'Driver has arrived', 'The driver is waiting at the pickup.', ['in_progress', 'no_show'], false, [ + $notify('Your driver has arrived', '{driver.first_name} is waiting at the pickup point.'), + ]), + 'in_progress' => static::activity('in_progress', 'Trip in progress', 'The passenger is on board.', ['completed'], false, [ + $notify('Your trip has started', 'Sit back, you are on your way.'), + ]), + 'completed' => static::activity('completed', 'Trip completed', 'The passenger was dropped off.', [], true, [ + $notify('You have arrived', 'Your trip is complete. See the price in the app.'), + ['action' => 'close_chat'], + // Run when Ledger is installed: bill the final price straight away. + ['action' => 'send_invoice'], + ]), + 'no_show' => static::activity('no_show', 'Passenger didn\'t show', 'The passenger didn\'t come to the pickup.', [], false, [ + ['action' => 'close_chat'], + ]), + ], + ]; + } + + public function customFields(): array + { + return [ + [ + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'default_value' => '1', + 'required' => false, + 'editable' => true, + 'validation_rules' => ['nullable', 'integer', 'min:1', 'max:50'], + 'help_text' => 'How many people are travelling.', + 'order' => 0, + ], + ]; + } +} diff --git a/server/src/Support/OrderConfig/Templates/Template.php b/server/src/Support/OrderConfig/Templates/Template.php new file mode 100644 index 000000000..068f51888 --- /dev/null +++ b/server/src/Support/OrderConfig/Templates/Template.php @@ -0,0 +1,65 @@ +key; + } + + public function name(): string + { + return $this->name; + } + + public function description(): string + { + return $this->description; + } + + public function customFields(): array + { + return []; + } + + /** + * A flow activity in the stored format. + * + * @param array $next the codes of the activities that can follow + * @param array $actions triggers to run when an order reaches the activity + * @param array $extra any other activity attributes, such as `require_pod` + */ + protected static function activity(string $code, string $status, string $details, array $next = [], bool $complete = false, array $actions = [], array $extra = []): array + { + return array_replace([ + 'key' => $code, + 'code' => $code, + 'color' => '#1f2937', + 'logic' => [], + 'events' => [], + 'status' => $status, + 'actions' => $actions, + 'details' => $details, + 'options' => [], + 'complete' => $complete, + 'entities' => [], + 'sequence' => 0, + 'activities' => $next, + 'internalId' => (string) Str::uuid(), + 'pod_method' => 'scan', + 'require_pod' => false, + ], $extra); + } +} diff --git a/server/src/Support/OrderConfig/Templates/TransportTemplate.php b/server/src/Support/OrderConfig/Templates/TransportTemplate.php new file mode 100644 index 000000000..acff32231 --- /dev/null +++ b/server/src/Support/OrderConfig/Templates/TransportTemplate.php @@ -0,0 +1,31 @@ + $this->description, + 'tags' => ['transport', 'delivery'], + 'entities' => [], + 'meta' => [], + 'flow' => [ + 'created' => static::activity('created', 'Order Created', 'New order was created.', ['dispatched']), + 'enroute' => static::activity('enroute', 'Driver Enroute', 'Driver is en-route.', ['completed']), + 'started' => static::activity('started', 'Order Started', 'Order has been started', ['enroute']), + 'completed' => static::activity('completed', 'Order Completed', 'Order has been completed.', [], true), + 'dispatched' => static::activity('dispatched', 'Order Dispatched', 'Order has been dispatched.', ['started']), + ], + ]; + } +} diff --git a/server/src/Support/OrderCustomFields.php b/server/src/Support/OrderCustomFields.php new file mode 100644 index 000000000..871b3ca62 --- /dev/null +++ b/server/src/Support/OrderCustomFields.php @@ -0,0 +1,88 @@ +customFields()->get(); + if ($fields->isEmpty()) { + return null; + } + + $data = []; + $rules = []; + foreach ($fields as $field) { + $own = array_filter(is_array($field->validation_rules) ? $field->validation_rules : [], fn ($rule) => is_string($rule) && !in_array($rule, ['required', 'nullable'], true)); + + $data[$field->name] = static::valueFor($field, $values); + $rules[$field->name] = array_values(array_merge([$field->required ? 'required' : 'nullable'], $own)); + } + + $validator = Validator::make($data, $rules, [], $fields->mapWithKeys(fn (CustomField $field) => [$field->name => $field->label ?: $field->name])->all()); + + return $validator->fails() ? $validator->errors()->first() : null; + } + + /** + * Store the values on the order, for fields its config has. + */ + public static function apply(Order $order, array $values): int + { + if ($values === []) { + return 0; + } + + // The same path the console saves custom field values through, with each value's type. + $rows = []; + foreach ($order->customFields()->get() as $field) { + $value = static::valueFor($field, $values); + if ($value !== null) { + $rows[] = ['custom_field_uuid' => $field->uuid, 'value' => $value, 'value_type' => $field->type ?: 'text']; + } + } + + if ($rows === []) { + return 0; + } + + $result = $order->syncCustomFieldValues($rows); + + return (int) ($result['created'] ?? 0) + (int) ($result['updated'] ?? 0); + } + + /** + * The value given for the field under its name, its label, or its label in snake case. + */ + protected static function valueFor(CustomField $field, array $values): mixed + { + foreach (array_filter([$field->name, $field->label, $field->label ? Str::snake($field->label) : null]) as $key) { + if (array_key_exists($key, $values)) { + return $values[$key]; + } + } + + return null; + } +} diff --git a/server/src/Support/OrderOffers.php b/server/src/Support/OrderOffers.php new file mode 100644 index 000000000..46e352302 --- /dev/null +++ b/server/src/Support/OrderOffers.php @@ -0,0 +1,199 @@ + $order->uuid, 'driver_uuid' => $driver->uuid, 'status' => OrderOffer::PENDING], + [ + 'company_uuid' => $order->company_uuid, + 'distance' => isset($driver->distance) ? (int) round((float) $driver->distance) : null, + 'expires_at' => $expiresAt, + ] + ); + } + + /** + * The order's newest open offer, if any. + */ + public static function pending(Order $order): ?OrderOffer + { + return OrderOffer::where('order_uuid', $order->uuid)->where('status', OrderOffer::PENDING)->latest('id')->first(); + } + + /** + * Drivers the order was offered to, whatever they answered. + */ + public static function offeredDrivers(Order $order): array + { + return OrderOffer::where('order_uuid', $order->uuid)->pluck('driver_uuid')->all(); + } + + /** + * Drivers who turned the order down. + */ + public static function declinedDrivers(Order $order): array + { + return OrderOffer::where('order_uuid', $order->uuid)->where('status', OrderOffer::DECLINED)->pluck('driver_uuid')->all(); + } + + /** + * Accept the driver's open offer, if it hasn't run out. False when they have none. + */ + public static function acceptPending(Order $order, Driver $driver): bool + { + return OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) + ->where('status', OrderOffer::PENDING) + ->where(fn ($query) => $query->whereNull('expires_at')->orWhere('expires_at', '>', now())) + ->update(['status' => OrderOffer::ACCEPTED, 'responded_at' => now()]) > 0; + } + + /** + * Turn down the driver's open offer. False when they have none. + */ + public static function declinePending(Order $order, Driver $driver): bool + { + return OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) + ->where('status', OrderOffer::PENDING) + ->update(['status' => OrderOffer::DECLINED, 'responded_at' => now()]) > 0; + } + + /** + * Record that the driver doesn't want the order, offered to them or not, so it isn't offered to them again. + */ + public static function recordDecline(Order $order, Driver $driver): void + { + if (!static::declinePending($order, $driver) && !in_array($driver->uuid, static::declinedDrivers($order), true)) { + OrderOffer::create([ + 'company_uuid' => $order->company_uuid, + 'order_uuid' => $order->uuid, + 'driver_uuid' => $driver->uuid, + 'status' => OrderOffer::DECLINED, + 'responded_at' => now(), + ]); + } + } + + /** + * The driver got the order: their offer is accepted and everyone else's is withdrawn. + */ + public static function claimed(Order $order, Driver $driver): void + { + OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) + ->where('status', OrderOffer::PENDING) + ->update(['status' => OrderOffer::ACCEPTED, 'responded_at' => now()]); + + static::withdraw($order); + } + + /** + * Close the order's open offers, for an order that was taken or canceled. + */ + public static function withdraw(Order $order): int + { + $open = OrderOffer::where('order_uuid', $order->uuid)->where('status', OrderOffer::PENDING)->pluck('driver_uuid')->all(); + $withdrawn = OrderOffer::where('order_uuid', $order->uuid) + ->where('status', OrderOffer::PENDING) + ->update(['status' => OrderOffer::WITHDRAWN, 'responded_at' => now()]); + + if ($withdrawn) { + static::announceClosed($order, $open, OrderOffer::WITHDRAWN); + } + + return $withdrawn; + } + + /** + * Tell each driver their offer for the order closed, so their app takes it off screen. + */ + public static function announceClosed(Order $order, array $driverUuids, string $status): void + { + $publicIds = Driver::withoutGlobalScopes()->whereIn('uuid', $driverUuids)->pluck('public_id', 'uuid'); + + foreach ($driverUuids as $driverUuid) { + try { + event(new OrderOfferClosed($order->public_id, $status, $publicIds[$driverUuid] ?? null, $driverUuid)); + } catch (\Throwable $exception) { + Log::warning('Unable to broadcast order.offer_closed', ['order' => $order->public_id, 'error' => $exception->getMessage()]); + } + } + } + + /** + * Nobody is left to offer the order to. The config's `dispatch.offer_exhausted` triggers run, + * and the order is canceled as "No driver found" when its `dispatch.adhoc` policy says so. + * Otherwise it stays open for the operator to assign, and later runs that find nobody again + * do nothing more. + */ + public static function exhausted(Order $order): void + { + // An order kept open is offered again on each scheduled run; its config hears that + // nobody accepted only the first time. + if ($order->getMeta('dispatch_outcome') === self::NO_DRIVER_FOUND_OUTCOME) { + return; + } + + $order->updateMeta('dispatch_outcome', self::NO_DRIVER_FOUND_OUTCOME); + OrderConfigTriggers::fire($order, OrderConfigTriggers::DISPATCH_OFFER_EXHAUSTED); + + if ($order->currentConfig()?->policy('dispatch.adhoc.on_exhausted') === AdhocDispatchPolicy::CANCEL) { + $order->cancelWithReason(self::NO_DRIVER_FOUND); + } + } + + /** + * How offering an adhoc order ended: `no_driver_found` when every driver it was offered to + * declined or let the offer run out and no driver has been assigned since. Null otherwise, + * including when someone canceled it while an offer was still open, which withdraws that offer. + */ + public static function outcome(Order $order): ?string + { + if (!$order->adhoc || $order->driver_assigned_uuid) { + return null; + } + + if ($order->getMeta('dispatch_outcome') === self::NO_DRIVER_FOUND_OUTCOME) { + return self::NO_DRIVER_FOUND_OUTCOME; + } + + if ($order->status !== 'canceled') { + return null; + } + + $statuses = OrderOffer::where('order_uuid', $order->uuid)->pluck('status')->unique()->values()->all(); + + return $statuses !== [] && array_diff($statuses, [OrderOffer::DECLINED, OrderOffer::EXPIRED]) === [] ? self::NO_DRIVER_FOUND_OUTCOME : null; + } +} diff --git a/server/src/Support/OrderRepricing.php b/server/src/Support/OrderRepricing.php new file mode 100644 index 000000000..fee3f10c1 --- /dev/null +++ b/server/src/Support/OrderRepricing.php @@ -0,0 +1,143 @@ +currentConfig(); + if (!$config || !$config->policy('pricing.reprice_on_completion') || $order->status !== $config->getCompletedActivity()?->code) { + return null; + } + + if (data_get($order, 'purchaseRate.meta.repriced')) { + return null; + } + + $rate = data_get($order, 'purchaseRate.serviceQuote.serviceRate'); + if (!$rate instanceof ServiceRate) { + return null; + } + + $meteredFrom = static::meteringStartedAt($order, $config->policy('pricing.metering_starts_at')); + [$distance, $source] = static::distance($order, $meteredFrom); + $duration = max(0, (int) $meteredFrom->diffInSeconds(Carbon::now(), true)); + $stops = collect([$order->payload?->pickup, $order->payload?->dropoff])->filter()->values(); + [$subTotal, $lines] = $rate->quoteFromPreliminaryData([], $stops, $distance, $duration, false, 2); + + $quote = static::quote($order, $rate, (int) $subTotal, $distance, $duration, $lines); + $order->purchaseServiceQuote($quote, [ + 'repriced' => [ + 'distance' => $distance, + 'time' => $duration, + 'distance_source' => $source, + 'metered_from' => $meteredFrom->toISOString(), + 'previous_amount' => data_get($order, 'purchaseRate.serviceQuote.amount'), + ], + ]); + + return $quote; + } + + /** + * When metering began: the first time the order reached the activity, else when it started. + */ + public static function meteringStartedAt(Order $order, ?string $activityCode = null): Carbon + { + $reached = $activityCode && $order->tracking_number_uuid + ? TrackingStatus::where('tracking_number_uuid', $order->tracking_number_uuid)->where('code', TrackingStatus::prepareCode($activityCode))->oldest()->value('created_at') + : null; + + return Carbon::parse($reached ?? $order->started_at ?? $order->created_at ?? Carbon::now()); + } + + /** + * Metres the driver's recorded positions cover since metering began, and where the figure + * came from. With too few positions it falls back to the straight line between the stops. + */ + public static function distance(Order $order, Carbon $since): array + { + $points = Position::where('order_uuid', $order->uuid) + ->where('created_at', '>=', $since) + ->orderBy('created_at') + ->orderBy('id') + ->get() + ->map(fn (Position $position) => $position->coordinates) + ->filter(fn ($point) => Utils::isPoint($point)) + ->values(); + + $metres = 0.0; + for ($i = 1; $i < $points->count(); $i++) { + $metres += Utils::vincentyGreatCircleDistance($points[$i - 1], $points[$i]); + } + if ($metres > 0) { + return [(int) round($metres), 'positions']; + } + + $pickup = $order->payload?->pickup?->location; + $dropoff = $order->payload?->dropoff?->location; + + return Utils::isPoint($pickup) && Utils::isPoint($dropoff) ? [(int) round(Utils::vincentyGreatCircleDistance($pickup, $dropoff)), 'straight_line'] : [0, 'none']; + } + + protected static function label(ServiceRate $rate, string $details, int $index): string + { + if ($index === 0) { + return 'Base'; + } + + return match ($rate->rate_calculation_method) { + 'per_meter' => 'Distance', + 'algo', 'algorithm' => 'Distance and time', + default => $details !== '' ? $details : 'Charge', + }; + } + + protected static function quote(Order $order, ServiceRate $rate, int $amount, int $distance, int $duration, iterable $lines): ServiceQuote + { + $quote = ServiceQuote::create([ + 'request_id' => 'reprice_' . Str::lower(Str::random(12)), + 'company_uuid' => $order->company_uuid, + 'service_rate_uuid' => $rate->uuid, + 'payload_uuid' => $order->payload_uuid, + 'amount' => $amount, + 'currency' => $rate->currency, + 'distance' => $distance, + 'time' => $duration, + ]); + + foreach (collect($lines)->values() as $index => $line) { + ServiceQuoteItem::create([ + 'service_quote_uuid' => $quote->uuid, + 'amount' => (int) data_get($line, 'amount', 0), + 'currency' => $rate->currency, + 'details' => static::label($rate, (string) data_get($line, 'details'), $index), + 'code' => data_get($line, 'code'), + ]); + } + + return $quote; + } +} diff --git a/server/src/Support/Radar/RadarAgenda.php b/server/src/Support/Radar/RadarAgenda.php index c81cc25b5..d9cb74712 100644 --- a/server/src/Support/Radar/RadarAgenda.php +++ b/server/src/Support/Radar/RadarAgenda.php @@ -177,7 +177,7 @@ public static function handovers(array $open, array $shifts, array $drivers, arr 'key' => $item['key'], 'driver' => $item['subject'], 'rule' => $item['rule'], - 'shift' => ($item['window'] ?? []) + ['uuid' => $item['source']['uuid'] ?? null, 'public_id' => $item['source']['public_id'] ?? null, 'minutes_left' => $end ? max(0, $now->diffInMinutes($end, false)) : null], + 'shift' => ($item['window'] ?? []) + ['uuid' => $item['source']['uuid'] ?? null, 'public_id' => $item['source']['public_id'] ?? null, 'minutes_left' => $end ? max(0, (int) $now->diffInMinutes($end, false)) : null], 'orders' => array_map(fn ($order) => $order + ['finishes_after_shift' => self::finishesAfter($order, $end)], $driverOrders), 'active_orders' => (int) ($item['source']['active_orders'] ?? count($driverOrders)), 'suggested' => $suggested, @@ -276,7 +276,7 @@ protected static function entry(array $item, ?Carbon $at, bool $planned, Carbon if ($lane === RadarRules::LANE_ANYTIME) { $lane = self::LANE_BY_CATEGORY[$item['category'] ?? ''] ?? RadarRules::LANE_MAINTENANCE; } - $hours = max(1, $start->diffInHours($end)); + $hours = max(1, (int) $start->diffInHours($end, true)); return [ 'kind' => 'item', @@ -290,7 +290,7 @@ protected static function entry(array $item, ?Carbon $at, bool $planned, Carbon 'meta_line' => $item['meta_line'] ?? null, 'lane' => $lane, 'at' => $at?->toIso8601String(), - 'label' => $at ? $at->format($start->diffInHours($end) > 24 ? 'D H:i' : 'H:i') : null, + 'label' => $at ? $at->format((int) $start->diffInHours($end, true) > 24 ? 'D H:i' : 'H:i') : null, 'planned' => $planned, 'pct' => $at ? self::pct($at, $start, $hours) : null, 'state' => $item['state'] ?? null, @@ -308,7 +308,7 @@ protected static function shiftBar(array $shift, array $byDriver, Carbon $start, return null; } - $hours = max(1, $start->diffInHours($end)); + $hours = max(1, (int) $start->diffInHours($end, true)); $gaps = $byDriver[$driver['uuid'] ?? ''] ?? []; $handover = null; $worst = null; @@ -334,7 +334,7 @@ protected static function shiftBar(array $shift, array $byDriver, Carbon $start, 'end_at' => $to->toIso8601String(), 'label' => $from->format('H:i') . '–' . $to->format('H:i'), 'pct' => self::pct($from->max($start), $start, $hours), - 'width_pct' => max(1.0, round(($from->max($start)->diffInMinutes($to->min($end)) / 60) / $hours * 100, 2)), + 'width_pct' => max(1.0, round(((int) $from->max($start)->diffInMinutes($to->min($end), true) / 60) / $hours * 100, 2)), 'lane' => RadarRules::LANE_SHIFTS, 'severity' => $worst, 'gap_keys' => array_column($gaps, 'key'), @@ -365,7 +365,7 @@ protected static function ticks(Carbon $start, int $hours): array protected static function pct(Carbon $at, Carbon $start, int $hours): float { - return round(max(0, min(100, $start->diffInMinutes($at, false) / 60 / $hours * 100)), 2); + return round(max(0, min(100, (int) $start->diffInMinutes($at, false) / 60 / $hours * 100)), 2); } protected static function severityRank(?string $severity): int diff --git a/server/src/Support/Radar/RadarRules.php b/server/src/Support/Radar/RadarRules.php index e0bd123c2..125c17df4 100644 --- a/server/src/Support/Radar/RadarRules.php +++ b/server/src/Support/Radar/RadarRules.php @@ -477,7 +477,7 @@ public static function shiftItems(array $shifts, Carbon $now): array $source = ['type' => 'shift', 'uuid' => $shift['uuid'] ?? null, 'public_id' => $shift['public_id'] ?? null, 'driver_uuid' => $driver['uuid'] ?? null]; $record = self::record('management.drivers.index.details', $driver['public_id'] ?? null); - $minutesLate = $start->diffInMinutes($now, false); + $minutesLate = (int) $start->diffInMinutes($now, false); if (empty($shift['driver_online']) && in_array($status, self::SHIFT_NOT_STARTED_STATUSES, true) && $minutesLate >= self::LATE_START_MINUTES) { $items[] = self::item('shift_late_start', $driver, sprintf('%s scheduled %s, not online', $name, $start->format('H:i')), [ 'severity' => $minutesLate >= self::LATE_START_CRITICAL ? self::SEVERITY_CRITICAL : self::SEVERITY_WARNING, @@ -492,7 +492,7 @@ public static function shiftItems(array $shifts, Carbon $now): array if (empty($shift['driver_vehicle_uuid'])) { $items[] = self::item('shift_no_vehicle', $driver, sprintf('%s on shift since %s, no vehicle assigned', $name, $start->format('H:i')), [ 'severity' => self::SEVERITY_WARNING, - 'meta_line' => self::minutesWords($start->diffInMinutes($now)) . ' on shift', + 'meta_line' => self::minutesWords((int) $start->diffInMinutes($now, true)) . ' on shift', 'window' => $window, 'record' => $record, 'source' => $source, @@ -501,7 +501,7 @@ public static function shiftItems(array $shifts, Carbon $now): array } $activeOrders = (int) ($shift['active_orders'] ?? 0); - $minutesToEnd = $now->diffInMinutes($end, false); + $minutesToEnd = (int) $now->diffInMinutes($end, false); if ($activeOrders > 0 && $minutesToEnd <= self::HANDOVER_MINUTES) { $items[] = self::item('shift_handover', $driver, sprintf('%s shift ends in %s, %d active order%s still assigned', $name, self::minutesWords($minutesToEnd), $activeOrders, $activeOrders === 1 ? '' : 's'), [ 'severity' => self::SEVERITY_WARNING, @@ -1146,16 +1146,16 @@ public static function dueLabel(?Carbon $due, Carbon $now): ?string public static function overdueWords(Carbon $due, Carbon $now): string { - $minutes = $due->diffInMinutes($now); + $minutes = (int) $due->diffInMinutes($now, true); if ($minutes < 60) { return max(1, $minutes) . 'm overdue'; } - $hours = $due->diffInHours($now); + $hours = (int) $due->diffInHours($now, true); if ($hours < 24) { return $hours . 'h overdue'; } - return $due->diffInDays($now) . 'd overdue'; + return (int) $due->diffInDays($now, true) . 'd overdue'; } public static function dueInWords(Carbon $due, Carbon $now): string @@ -1167,7 +1167,7 @@ public static function dueInWords(Carbon $due, Carbon $now): string return 'tomorrow'; } - $days = $now->copy()->startOfDay()->diffInDays($due->copy()->startOfDay()); + $days = (int) $now->copy()->startOfDay()->diffInDays($due->copy()->startOfDay(), true); if ($days <= self::DUE_SOON_DAYS) { return sprintf('in %d day%s', $days, $days === 1 ? '' : 's'); } @@ -1180,7 +1180,7 @@ public static function dueInWords(Carbon $due, Carbon $now): string */ public static function agoWords(Carbon $then, Carbon $now): string { - $minutes = max(0, $then->diffInMinutes($now, false)); + $minutes = max(0, (int) $then->diffInMinutes($now, false)); if ($minutes < 60) { return max(1, $minutes) . 'm ago'; } diff --git a/server/src/Support/SocketChannels.php b/server/src/Support/SocketChannels.php index 84c7590c2..c5181bcd4 100644 --- a/server/src/Support/SocketChannels.php +++ b/server/src/Support/SocketChannels.php @@ -110,6 +110,7 @@ public static function register(SocketChannelRegistry $registry): void $registry->register(TrackingChannel::PREFIX, static fn (): bool => false); $registry->registerPrincipalResolver([static::class, 'driverPrincipal']); + $registry->registerPrincipalResolver([static::class, 'customerPrincipal']); } /** @@ -212,18 +213,12 @@ public static function narrowOrder(SocketPrincipal $principal, Model $order): bo } /** - * Drivers: a driver only themselves; a customer the driver of one of their active orders. + * Drivers: a driver only themselves. Never a customer, because the driver's location events + * carry their phone number; customers follow the driver through their order instead. */ public static function narrowDriver(SocketPrincipal $principal, Model $driver): bool { - if ($principal->kind === 'driver') { - return static::isSelf($principal, $driver->uuid); - } - - return $principal->kind === 'customer' - && static::activeCustomerOrders($principal, $driver->getConnectionName()) - ->where('driver_assigned_uuid', $driver->uuid) - ->exists(); + return $principal->kind === 'driver' && static::isSelf($principal, $driver->uuid); } /** @@ -307,6 +302,40 @@ public static function driverPrincipal(Request $request, $user): ?SocketPrincipa ); } + /** + * A customer's token gets the customer principal, so its socket reaches only their own + * records and not the whole company. + */ + public static function customerPrincipal(Request $request, $user): ?SocketPrincipal + { + if (!$user instanceof User || !$user->uuid || !$user->isType('customer')) { + return null; + } + + $companyUuid = session('company') ?: $user->company_uuid; + if (!$companyUuid) { + return null; + } + + $customer = Contact::where('user_uuid', $user->uuid)->where('company_uuid', $companyUuid)->where('type', 'customer')->first(); + if (!$customer) { + return null; + } + + $connection = $customer->getConnectionName(); + $cpid = Company::on($connection)->where('uuid', $companyUuid)->value('public_id'); + + return new SocketPrincipal( + kind: 'customer', + sub: (string) $customer->uuid, + cid: (string) $companyUuid, + cpid: is_string($cpid) && $cpid !== '' ? $cpid : null, + env: $connection === 'sandbox' ? 'test' : 'live', + ids: array_values(array_filter([$customer->uuid, $customer->public_id, $user->uuid])), + adm: false, + ); + } + /** * The customer's orders that are not completed or canceled. */ diff --git a/server/src/Support/Telematics/TelematicService.php b/server/src/Support/Telematics/TelematicService.php index 250ea5374..dfe50ff8b 100644 --- a/server/src/Support/Telematics/TelematicService.php +++ b/server/src/Support/Telematics/TelematicService.php @@ -674,7 +674,7 @@ protected function connectionStatusForDevice(Device $device, ?Carbon $lastSeen = return 'never_connected'; } - $minutesOffline = Carbon::parse($lastSeen)->diffInMinutes(now()); + $minutesOffline = (int) Carbon::parse($lastSeen)->diffInMinutes(now(), true); if ($minutesOffline <= 10) { return 'online'; diff --git a/server/src/Support/Telematics/Telemetry/Ingestor.php b/server/src/Support/Telematics/Telemetry/Ingestor.php index 9b790900d..e20b6e170 100644 --- a/server/src/Support/Telematics/Telemetry/Ingestor.php +++ b/server/src/Support/Telematics/Telemetry/Ingestor.php @@ -79,7 +79,7 @@ public function ingest(Telematic $telematic, TelemetryProviderInterface $provide $device->last_online_at = Carbon::parse($contact)->utc()->toDateTimeString(); $device->online = $device->last_online_at->gt(now()->subMinutes(10)); if (in_array($device->status, ['online', 'recently_offline', 'offline', 'long_offline', 'never_connected'], true)) { - $minutes = $device->last_online_at->diffInMinutes(now()); + $minutes = (int) $device->last_online_at->diffInMinutes(now(), true); $device->status = $minutes <= 10 ? 'online' : ($minutes <= 60 ? 'recently_offline' : ($minutes <= 1440 ? 'offline' : 'long_offline')); } $device->meta = array_replace_recursive($device->meta ?? [], ['telemetry' => ['provider_at' => $contact, 'last_received_at' => $received]]); diff --git a/server/src/Support/TrackingPage/TrackingShare.php b/server/src/Support/TrackingPage/TrackingShare.php new file mode 100644 index 000000000..77a913f0e --- /dev/null +++ b/server/src/Support/TrackingPage/TrackingShare.php @@ -0,0 +1,40 @@ +addHours(self::HOURS))->getTimestamp(); + + return $expires . '.' . static::sign($orderUuid, $customerUuid, $expires); + } + + public static function valid(mixed $token, ?TrackingScope $scope): bool + { + if (!$scope || !is_string($token) || !preg_match('/^(\d+)\.([a-f0-9]{64})$/', $token, $parts)) { + return false; + } + + $expires = (int) $parts[1]; + + return $expires > Carbon::now()->getTimestamp() + && hash_equals(static::sign((string) $scope->order_uuid, (string) $scope->customer_uuid, $expires), $parts[2]); + } + + protected static function sign(string $orderUuid, string $customerUuid, int $expires): string + { + return hash_hmac('sha256', 'tracking-share|' . $orderUuid . '|' . $customerUuid . '|' . $expires, (string) config('app.key')); + } +} diff --git a/server/src/Tracking/TrackingContextBuilder.php b/server/src/Tracking/TrackingContextBuilder.php index 870e2b223..ac3db93c3 100644 --- a/server/src/Tracking/TrackingContextBuilder.php +++ b/server/src/Tracking/TrackingContextBuilder.php @@ -30,7 +30,7 @@ public function build(Order $order, TrackingOptions $options): TrackingContext $payload = $order->payload; $driver = $order->driverAssigned; $warnings = []; - $driverLocationAge = $driver?->updated_at ? now()->diffInSeconds($driver->updated_at) : null; + $driverLocationAge = $driver?->updated_at ? (int) now()->diffInSeconds($driver->updated_at, true) : null; $origin = null; $driverLocation = null; diff --git a/server/src/Traits/Maintainable.php b/server/src/Traits/Maintainable.php index 2dcbb02f6..06e07afeb 100644 --- a/server/src/Traits/Maintainable.php +++ b/server/src/Traits/Maintainable.php @@ -111,7 +111,7 @@ protected function checkIntervalsSinceDate($date): bool // Check time-based intervals $maintenanceIntervalDays = $specs['maintenance_interval_days'] ?? $meta['maintenance_interval_days'] ?? null; - if ($maintenanceIntervalDays && $date->diffInDays(now()) >= $maintenanceIntervalDays) { + if ($maintenanceIntervalDays && (int) $date->diffInDays(now(), true) >= $maintenanceIntervalDays) { return true; } @@ -199,7 +199,7 @@ public function getAverageMaintenanceDuration(int $days = 365): ?float } $totalHours = $maintenances->sum(function ($maintenance) { - return $maintenance->started_at->diffInHours($maintenance->completed_at); + return (int) $maintenance->started_at->diffInHours($maintenance->completed_at, true); }); return $totalHours / $maintenances->count(); diff --git a/server/src/routes.php b/server/src/routes.php index 2159f61fa..ce9f8d020 100644 --- a/server/src/routes.php +++ b/server/src/routes.php @@ -35,6 +35,7 @@ function ($router) { $router->get('{number}/proofs/{id}', 'TrackingController@proof'); $router->post('{number}/report', 'TrackingController@report'); $router->get('{number}/socket-token', 'TrackingController@socketToken'); + $router->post('{number}/share', 'TrackingController@redeemShare'); }); $router->prefix('public')->namespace('Public')->middleware([Fleetbase\FleetOps\Http\Middleware\ForceJsonResponse::class, 'throttle:60,1,inspection-public'])->group(function ($router) { @@ -103,6 +104,7 @@ function ($router) { $router->post('/', 'CustomerController@create'); $router->post('login', 'CustomerController@login'); $router->post('login-with-sms', 'CustomerController@loginWithPhone')->middleware('throttle:5,1,fleetops-sms'); + $router->post('request-code', 'CustomerController@requestCode')->middleware('throttle:5,1,fleetops-sms'); $router->post('verify-code', 'CustomerController@verifyCode'); $router->post('forgot-password', 'CustomerController@forgotPassword')->middleware('throttle:5,1,fleetops-sms'); $router->post('reset-password', 'CustomerController@resetPassword'); @@ -115,10 +117,26 @@ function ($router) { $router->post('logout', 'CustomerController@logout'); $router->post('logout-all', 'CustomerController@logoutAll'); $router->post('register-device', 'CustomerController@registerDevice'); + $router->post('me/phone-code', 'CustomerController@requestPhoneChangeCode')->middleware('throttle:5,1,fleetops-sms'); + $router->get('geocode', 'CustomerController@geocode'); $router->get('places', 'CustomerController@places'); + $router->get('places/search', 'CustomerController@searchPlaces'); + $router->post('places', 'CustomerController@savePlace'); + $router->put('places/{id}', 'CustomerController@updatePlace'); + $router->delete('places/{id}', 'CustomerController@deletePlace'); $router->get('orders', 'CustomerController@orders'); $router->post('orders', 'CustomerController@createOrder'); $router->get('orders/{id}', 'CustomerController@findOrder'); + $router->post('orders/{id}/dispatch', 'CustomerController@dispatchOrder'); + $router->post('orders/{id}/cancel', 'CustomerController@cancelOrder'); + $router->get('orders/{id}/driver', 'CustomerController@orderDriver'); + $router->get('orders/{id}/tracker', 'CustomerController@orderTracker'); + $router->get('orders/{id}/eta', 'CustomerController@orderEta'); + $router->get('orders/{id}/messages', 'CustomerController@orderMessages'); + $router->post('orders/{id}/messages', 'CustomerController@sendOrderMessage')->middleware('throttle:30,1'); + $router->post('orders/{id}/rating', 'CustomerController@rateOrder'); + $router->post('orders/{id}/share', 'CustomerController@shareOrder'); + $router->delete('me', 'CustomerController@deleteMe'); }); }); // vendors routes @@ -211,6 +229,7 @@ function ($router) { $router->match(['post', 'patch'], '{id}/schedule', 'OrderController@scheduleOrder'); $router->match(['post', 'patch'], '{id}/dispatch', 'OrderController@dispatchOrder'); $router->post('{id}/start', 'OrderController@startOrder'); + $router->post('{id}/decline', 'OrderController@declineOrder'); $router->delete('{id}/cancel', 'OrderController@cancelOrder'); $router->match(['post', 'patch'], '{id}/update-activity', 'OrderController@updateActivity'); $router->post('{id}/complete', 'OrderController@completeOrder'); @@ -572,7 +591,13 @@ function ($router, $controller) { $router->match(['get', 'post'], 'export', $controller('export')); } ); - $router->fleetbaseRoutes('order-configs'); + $router->fleetbaseRoutes( + 'order-configs', + function ($router, $controller) { + $router->get('capabilities', $controller('capabilities')); + $router->post('from-template', $controller('createFromTemplate')); + } + ); $router->fleetbaseRoutes('payloads'); $router->fleetbaseRoutes( 'places', @@ -827,6 +852,9 @@ function ($router) { $router->get('notification-registry', 'SettingController@getNotificationRegistry'); $router->get('notification-settings', 'SettingController@getNotificationSettings'); $router->post('notification-settings', 'SettingController@saveNotificationSettings'); + $router->get('adhoc-dispatch-settings', 'SettingController@getAdhocDispatchSettings'); + $router->post('adhoc-dispatch-settings', 'SettingController@saveAdhocDispatchSettings'); + $router->get('adhoc-dispatch-strategies', 'SettingController@getAdhocDispatchStrategies'); $router->get('routing-settings', 'SettingController@getRoutingSettings'); $router->post('routing-settings', 'SettingController@saveRoutingSettings'); $router->get('tracking-settings', 'SettingController@getTrackingSettings'); diff --git a/server/tests/ApiCustomerControllerContractsTest.php b/server/tests/ApiCustomerControllerContractsTest.php index 00dffea9c..8e382b139 100644 --- a/server/tests/ApiCustomerControllerContractsTest.php +++ b/server/tests/ApiCustomerControllerContractsTest.php @@ -79,6 +79,25 @@ class FleetOpsApiCustomerControllerProbe extends CustomerController public array $uuidLookups = []; public array $devices = []; + protected function customerPlaceQuery(Contact $customer): mixed + { + return null; + } + + protected function runPlaceSearch(mixed $query, string $searchQuery, array $options): mixed + { + $this->placeQueries[] = ['search', $searchQuery, $options]; + + return collect(); + } + + protected function geocodePlaces(string $query, mixed $latitude, mixed $longitude): mixed + { + $this->placeQueries[] = ['geocode', $query, $latitude, $longitude]; + + return collect(); + } + protected function isEmail(?string $identity): bool { return filter_var($identity, FILTER_VALIDATE_EMAIL) !== false; @@ -185,6 +204,13 @@ protected function verificationCodeExists(array $attributes): bool return $this->verificationExists; } + protected function verificationCodeMatches(array $attributes): bool + { + $this->userUpdates[] = ['verificationMatches', $attributes]; + + return $this->verificationExists; + } + protected function findVerificationCode(array $attributes): mixed { $this->userUpdates[] = ['findVerification', $attributes]; @@ -305,6 +331,26 @@ protected function resolveOrderConfig(CreateCustomerOrderRequest $request, strin return $this->orderConfig; } + public bool $unsettledOrder = false; + public array $paymentMethods = []; + + protected function setPayloadPaymentMethod(string $payloadUuid, string $paymentMethod): void + { + $this->paymentMethods[] = [$payloadUuid, $paymentMethod]; + } + + public array $enabledOrderConfigs = []; + + protected function hasUnsettledOrder(Contact $customer, OrderConfig $orderConfig): bool + { + return $this->unsettledOrder && (bool) $orderConfig->policy('customer.ordering.require_settlement'); + } + + protected function lookupCompanySetting(string $key, mixed $default = null): mixed + { + return $key === 'fleet-ops.customer-enabled-order-configs' ? $this->enabledOrderConfigs : $default; + } + protected function getUuid(array|string $table, array $where, array $options = []): mixed { $this->uuidLookups[] = [$table, $where, $options]; @@ -656,6 +702,7 @@ function fleetopsApiCustomerController(): FleetOpsApiCustomerControllerProbe $controller->orderConfig->setRawAttributes(['uuid' => 'config-uuid', 'key' => 'transport'], true); $controller->order = fleetopsApiCustomerOrder(); $controller->serviceQuote = new ServiceQuote(); + $controller->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); $controller->file = (object) ['uuid' => 'public-file-uuid']; return $controller; @@ -863,9 +910,10 @@ function fleetopsApiCustomerJson($response): array $profile = $controller->me(); $updated = $controller->updateMe(new UpdateContactRequest([ - 'name' => 'Jane Updated', - 'phone' => '15550001111', - 'photo' => 'REMOVE', + 'name' => 'Jane Updated', + 'phone' => '15550001111', + 'phone_code' => '123456', + 'photo' => 'REMOVE', ])); $logout = $controller->logout(Request::create('/v1/customers/logout', 'POST', [], [], [], [ 'HTTP_CUSTOMER_TOKEN' => 'token-secret', @@ -1196,3 +1244,449 @@ public function hasDebugModeEnabled() config(['fleetops.customers.verification_bypass_code' => null, 'fleetops.customers.review_accounts' => []]); }); + +function fleetopsCustomerOrderFor(FleetOpsApiCustomerControllerProbe $controller, array $attributes = []): Order +{ + $order = $controller->order; + $order->setRawAttributes(array_merge($order->getAttributes(), $attributes), true); + + return $order; +} + +test('request code answers the same for known and unknown phone numbers', function () { + $known = fleetopsApiCustomerController(); + $unknown = fleetopsApiCustomerController(); + $unknown->activeUser = null; + + $request = fn () => Request::create('/v1/customers/request-code', 'POST', ['phone' => '+15550001111']); + + expect(fleetopsApiCustomerJson($known->requestCode($request())))->toBe(['status' => 'ok']) + ->and(fleetopsApiCustomerJson($unknown->requestCode($request())))->toBe(['status' => 'ok']) + ->and($known->smsVerifications[0][1] ?? null)->toBe('fleetops_customer_login') + ->and($unknown->smsVerifications[0][1] ?? null)->toBe('fleetops_create_customer'); +}); + +test('request code refuses a missing or email identity', function () { + $controller = fleetopsApiCustomerController(); + + expect($controller->requestCode(Request::create('/', 'POST', []))->getStatusCode())->toBe(400) + ->and($controller->requestCode(Request::create('/', 'POST', ['phone' => 'a@b.test']))->getStatusCode())->toBe(400); +}); + +test('verify code tells a new customer apart only after the code is proven', function () { + $controller = fleetopsApiCustomerController(); + $controller->verificationUser = null; + $request = fn () => Request::create('/', 'POST', ['identity' => '+15550001111', 'code' => '123456']); + + expect(fleetopsApiCustomerJson($controller->verifyCode($request())))->toBe(['status' => 'new_customer']); + expect(collect($controller->userUpdates)->pluck(0))->not->toContain('verificationExists'); + + $controller->verificationExists = false; + + expect(fleetopsApiCustomerJson($controller->verifyCode($request())))->toBe(['error' => 'Invalid verification code.']); +}); + +test('a customer cannot change phone without a code for that number', function () { + $controller = fleetopsApiCustomerController(); + $controller->activeUser = null; + $before = $controller->currentCustomer->phone; + + $withoutCode = $controller->updateMe(new UpdateContactRequest(['phone' => '15550002222'])); + + $controller->verificationExists = false; + $wrongCode = $controller->updateMe(new UpdateContactRequest(['phone' => '15550002222', 'phone_code' => '000000'])); + + expect($withoutCode->getStatusCode())->toBe(422) + ->and($wrongCode->getStatusCode())->toBe(422) + ->and($controller->currentCustomer->phone)->toBe($before); +}); + +test('a customer cannot take a phone number held by another account', function () { + $controller = fleetopsApiCustomerController(); + $controller->activeUser = fleetopsApiCustomerUser(); + $controller->activeUser->uuid = 'someone-else'; + + $response = $controller->updateMe(new UpdateContactRequest(['phone' => '15550002222', 'phone_code' => '123456'])); + + expect($response->getStatusCode())->toBe(422); +}); + +test('a phone change code does not reveal whether a number has an account', function () { + $held = fleetopsApiCustomerController(); + $free = fleetopsApiCustomerController(); + $free->activeUser = null; + $request = fn () => Request::create('/', 'POST', ['phone' => '+15550002222']); + + expect(fleetopsApiCustomerJson($held->requestPhoneChangeCode($request())))->toBe(['status' => 'ok']) + ->and(fleetopsApiCustomerJson($free->requestPhoneChangeCode($request())))->toBe(['status' => 'ok']) + ->and($held->smsVerifications)->toBe([]) + ->and($free->smsVerifications[0][1] ?? null)->toBe('fleetops_customer_phone_change'); +}); + +test('customer order actions treat another customer as not found', function () { + $controller = fleetopsApiCustomerController(); + fleetopsCustomerOrderFor($controller, ['customer_uuid' => 'someone-else', 'status' => 'created']); + $request = Request::create('/', 'POST'); + + expect($controller->dispatchOrder('order_1')->getStatusCode())->toBe(404) + ->and($controller->cancelOrder('order_1', $request)->getStatusCode())->toBe(404) + ->and($controller->orderDriver('order_1')->getStatusCode())->toBe(404) + ->and($controller->orderTracker('order_1', $request)->getStatusCode())->toBe(404) + ->and($controller->orderEta('order_1', $request)->getStatusCode())->toBe(404); +}); + +test('a finished order cannot be canceled or dispatched by its customer', function (string $status) { + $controller = fleetopsApiCustomerController(); + fleetopsCustomerOrderFor($controller, ['customer_uuid' => $controller->currentCustomer->uuid, 'status' => $status]); + + expect($controller->cancelOrder('order_1', Request::create('/', 'POST'))->getStatusCode())->toBe(422) + ->and($controller->dispatchOrder('order_1')->getStatusCode())->toBe(422); +})->with(['completed', 'canceled']); + +test('customer place routes only touch places the customer owns', function () { + $controller = fleetopsApiCustomerController(); + $controller->place = new Place(); + $controller->place->setRawAttributes(['uuid' => 'p', 'owner_uuid' => 'someone-else'], true); + + expect($controller->updatePlace('place_1', Request::create('/', 'PUT', ['name' => 'Mine now']))->getStatusCode())->toBe(404) + ->and($controller->deletePlace('place_1')->getStatusCode())->toBe(404); +}); + +test('saving a place needs a name and real coordinates', function () { + $controller = fleetopsApiCustomerController(); + + expect($controller->savePlace(Request::create('/', 'POST', ['latitude' => 1, 'longitude' => 2]))->getStatusCode())->toBe(422) + ->and($controller->savePlace(Request::create('/', 'POST', ['name' => 'Home', 'latitude' => 95, 'longitude' => 2]))->getStatusCode())->toBe(422) + ->and($controller->createdPlaces)->toBe([]); +}); + +test('geocode needs a query or coordinates', function () { + $controller = fleetopsApiCustomerController(); + + expect($controller->geocode(Request::create('/', 'GET'))->getStatusCode())->toBe(400); + $controller->geocode(Request::create('/', 'GET', ['latitude' => 1.28, 'longitude' => 103.85])); + expect($controller->placeQueries[0][0])->toBe('geocode'); +}); + +test('signup password is optional', function () { + $source = file_get_contents(dirname(__DIR__) . '/src/Http/Requests/CreateCustomerRequest.php'); + + expect($source)->toContain("'password' => 'nullable|string|min:8'"); +}); + +test('an expired quote or another company\'s quote is refused when ordering', function (array $attributes) { + $controller = fleetopsApiCustomerController(); + $controller->serviceQuote->setRawAttributes($attributes, true); + + $response = $controller->createOrder(new CreateCustomerOrderRequest(['service_quote' => 'quote_1', 'notes' => 'x'])); + + expect($response->getStatusCode())->toBe(422) + ->and($controller->order->purchasedQuotes)->toBe([]); +})->with([ + 'expired' => [['company_uuid' => 'company-uuid', 'expired_at' => Illuminate\Support\Carbon::parse('2020-01-01')]], + 'other company' => [['company_uuid' => 'other-company']], +]); + +test('a customer token gets the narrow customer socket principal', function () { + $source = file_get_contents(dirname(__DIR__) . '/src/Support/SocketChannels.php'); + + expect($source)->toContain("registerPrincipalResolver([static::class, 'customerPrincipal'])") + ->and($source)->toContain("kind: 'customer'") + ->and(Fleetbase\FleetOps\Support\SocketChannels::customerPrincipal(Request::create('/'), null))->toBeNull(); +}); + +class FleetOpsCustomerOwnOrderFake extends FleetOpsApiCustomerOrderFake +{ + public array $faked = []; + public array $calls = []; + public mixed $trackerFake = null; + + public function __get($key) + { + return array_key_exists($key, $this->faked) ? $this->faked[$key] : parent::__get($key); + } + + public function __isset($key) + { + return array_key_exists($key, $this->faked) ? isset($this->faked[$key]) : parent::__isset($key); + } + + public function dispatch(bool $save = true): self + { + $this->calls[] = 'dispatch'; + + return $this; + } + + public function insertDispatchActivity(): Order + { + $this->calls[] = 'activity'; + + return $this; + } + + public function cancel() + { + $this->calls[] = 'cancel'; + } + + public function cancelWithReason(?string $reason = null) + { + $this->calls[] = ['reason', $reason]; + } + + public function config(): ?OrderConfig + { + return $this->faked['config'] ?? new OrderConfig(); + } + + public function tracker(): Fleetbase\FleetOps\Support\OrderTracker + { + return $this->trackerFake; + } +} + +class FleetOpsCustomerTrackerFake extends Fleetbase\FleetOps\Support\OrderTracker +{ + public function __construct(private bool $fails = false) + { + } + + public function eta(array $options = []): array + { + return $this->answer('eta'); + } + + public function toArray(array $options = []): array + { + return $this->answer('tracker'); + } + + private function answer(string $name): array + { + if ($this->fails) { + throw new RuntimeException('tracking is down'); + } + + return ['answer' => $name]; + } +} + +class FleetOpsCustomerSavedPlaceFake extends Place +{ + public array $updates = []; + public bool $deleted = false; + + public function update(array $attributes = [], array $options = []) + { + $this->updates[] = $attributes; + + return true; + } + + public function delete() + { + $this->deleted = true; + + return true; + } +} + +function fleetopsCustomerOrderController(array $order = [], array $faked = []): FleetOpsApiCustomerControllerProbe +{ + $controller = fleetopsApiCustomerController(); + $owned = new FleetOpsCustomerOwnOrderFake(); + $owned->setRawAttributes(array_merge(['uuid' => 'order-uuid', 'customer_uuid' => $controller->currentCustomer->uuid, 'status' => 'created'], $order), true); + $owned->faked = array_merge(['dispatched' => false, 'hasDriverAssigned' => false, 'adhoc' => true, 'driverAssigned' => null, 'vehicleAssigned' => null], $faked); + $controller->order = $owned; + + return $controller; +} + +test('every customer route answers 401 without a signed-in customer', function () { + $controller = fleetopsApiCustomerController(); + $controller->currentCustomer = null; + $request = Request::create('/', 'GET'); + + expect($controller->searchPlaces($request)->getStatusCode())->toBe(401) + ->and($controller->geocode($request)->getStatusCode())->toBe(401) + ->and($controller->savePlace($request)->getStatusCode())->toBe(401) + ->and($controller->requestPhoneChangeCode($request)->getStatusCode())->toBe(401) + ->and($controller->updatePlace('place_1', $request)->getStatusCode())->toBe(404) + ->and($controller->deletePlace('place_1')->getStatusCode())->toBe(404) + ->and($controller->cancelOrder('order_1', $request)->getStatusCode())->toBe(404); +}); + +test('customer place search only asks for the customer and caps the limit', function () { + $controller = fleetopsApiCustomerController(); + + $controller->searchPlaces(Request::create('/', 'GET', ['query' => 'home', 'limit' => 500, 'latitude' => 1.2, 'longitude' => 103.8])); + + expect($controller->placeQueries[0][0])->toBe('search') + ->and($controller->placeQueries[0][1])->toBe('home') + ->and($controller->placeQueries[0][2])->toMatchArray(['limit' => 50, 'geo' => true, 'latitude' => 1.2, 'longitude' => 103.8]); +}); + +test('a customer saves, edits and deletes their own place', function () { + $controller = fleetopsApiCustomerController(); + $controller->place = new FleetOpsCustomerSavedPlaceFake(); + $controller->place->setRawAttributes(['uuid' => 'place-uuid', 'owner_uuid' => $controller->currentCustomer->uuid], true); + + $saved = $controller->savePlace(Request::create('/', 'POST', ['name' => 'Home', 'latitude' => 1.28, 'longitude' => 103.85, 'street1' => '1 Raffles Place', 'owner_uuid' => 'someone-else'])); + $edit = $controller->updatePlace('place_1', Request::create('/', 'PUT', ['name' => 'Work', 'latitude' => 1.3, 'longitude' => 103.9])); + $name = $controller->updatePlace('place_1', Request::create('/', 'PUT', ['name' => 'Office'])); + $bad = $controller->updatePlace('place_1', Request::create('/', 'PUT', ['latitude' => 95, 'longitude' => 103.9])); + $gone = $controller->deletePlace('place_1'); + + $created = collect($controller->createdPlaces)->first(fn ($entry) => isset($entry['name'])); + + expect($saved)->toBeInstanceOf(Fleetbase\FleetOps\Http\Resources\v1\Place::class) + ->and($created['owner_uuid'])->toBe($controller->currentCustomer->uuid) + ->and($created['location']->getLat())->toBe(1.28) + ->and($edit)->toBeInstanceOf(Fleetbase\FleetOps\Http\Resources\v1\Place::class) + ->and($controller->place->updates[0]['location']->getLng())->toBe(103.9) + ->and($controller->place->updates[1])->toBe(['name' => 'Office']) + ->and($bad->getStatusCode())->toBe(422) + ->and(fleetopsApiCustomerJson($gone))->toBe(['status' => 'ok']) + ->and($controller->place->deleted)->toBeTrue(); +}); + +test('a phone change code covers missing input, unknown users and send failures', function () { + $request = fn () => Request::create('/', 'POST', ['phone' => '+15550002222']); + + $missing = fleetopsApiCustomerController(); + + $noUser = fleetopsApiCustomerController(); + $noUser->activeUser = null; + $noUser->uuidUser = null; + + $blocked = fleetopsApiCustomerController(); + $blocked->activeUser = null; + $blocked->smsVerificationThrows = SmsBlockedException::limited('company_per_hour', 45); + + $down = fleetopsApiCustomerController(); + $down->activeUser = null; + $down->smsVerificationFails = true; + + expect($missing->requestPhoneChangeCode(Request::create('/', 'POST'))->getStatusCode())->toBe(400) + ->and($noUser->requestPhoneChangeCode($request())->getStatusCode())->toBe(400) + ->and($blocked->requestPhoneChangeCode($request())->getStatusCode())->toBe(429) + ->and($down->requestPhoneChangeCode($request())->getStatusCode())->toBeGreaterThanOrEqual(400); +}); + +test('a customer dispatches their own order only when it can go out', function () { + $ready = fleetopsCustomerOrderController(); + $ready->dispatchOrder('order_1'); + + expect($ready->order->calls)->toBe(['dispatch', 'activity']) + ->and(fleetopsCustomerOrderController([], ['dispatched' => true])->dispatchOrder('order_1')->getStatusCode())->toBe(422) + ->and(fleetopsCustomerOrderController(['status' => 'started'])->dispatchOrder('order_1')->getStatusCode())->toBe(422) + ->and(fleetopsCustomerOrderController([], ['adhoc' => false])->dispatchOrder('order_1')->getStatusCode())->toBe(422); +}); + +test('a customer cancels their own order, with or without a reason', function () { + $plain = fleetopsCustomerOrderController(); + $plain->cancelOrder('order_1', Request::create('/', 'POST', ['reason' => ' '])); + + $reason = fleetopsCustomerOrderController(); + $reason->cancelOrder('order_1', Request::create('/', 'POST', ['reason' => ' Changed my mind '])); + + expect($plain->order->calls)->toBe(['cancel']) + ->and($reason->order->calls)->toBe([['reason', 'Changed my mind']]); +}); + +test('a customer sees the driver and vehicle but no contact details', function () { + $driver = (object) ['name' => 'Dee Driver', 'photo_url' => 'photo', 'location' => 'here', 'phone' => '+15550009999', 'email' => 'd@example.test', 'vehicle' => null]; + $vehicle = (object) ['make' => 'Toyota', 'model' => 'Prius', 'color' => 'Blue', 'plate_number' => 'SGX1']; + + $none = fleetopsApiCustomerJson(fleetopsCustomerOrderController()->orderDriver('order_1')); + $noCar = fleetopsApiCustomerJson(fleetopsCustomerOrderController([], ['driverAssigned' => $driver])->orderDriver('order_1')); + $withCar = fleetopsApiCustomerJson(fleetopsCustomerOrderController([], ['driverAssigned' => $driver, 'vehicleAssigned' => $vehicle])->orderDriver('order_1')); + + expect($none)->toBe(['driver' => null, 'vehicle' => null]) + ->and($noCar['vehicle'])->toBeNull() + ->and($withCar['driver'])->toBe(['name' => 'Dee Driver', 'photo_url' => 'photo', 'location' => 'here', 'rating' => null]) + ->and($withCar['vehicle'])->toBe(['make' => 'Toyota', 'model' => 'Prius', 'color' => 'Blue', 'plate_number' => 'SGX1']); +}); + +test('customer tracking answers, and says so when tracking is down', function () { + $working = fleetopsCustomerOrderController(); + $working->order->trackerFake = new FleetOpsCustomerTrackerFake(); + $broken = fleetopsCustomerOrderController(); + $broken->order->trackerFake = new FleetOpsCustomerTrackerFake(true); + $request = Request::create('/', 'GET'); + + expect(fleetopsApiCustomerJson($working->orderTracker('order_1', $request)))->toBe(['answer' => 'tracker']) + ->and(fleetopsApiCustomerJson($working->orderEta('order_1', $request)))->toBe(['answer' => 'eta']) + ->and($broken->orderTracker('order_1', $request)->getStatusCode())->toBe(503) + ->and($broken->orderEta('order_1', $request)->getStatusCode())->toBe(503); +}); + +test('an order that does not exist is not found for a customer', function () { + $controller = fleetopsApiCustomerController(); + $controller->findOrderFails = true; + + expect($controller->orderDriver('order_missing')->getStatusCode())->toBe(404); +}); + +test('a config matching drivers by vehicle type needs a quote, makes customer orders adhoc, and takes the vehicle type from the quote', function () { + $onDemand = new OrderConfig(['key' => 'on-demand', 'policies' => [ + 'dispatch' => ['adhoc' => ['customer_orders' => true], 'matching' => ['vehicle_type' => true]], + 'customer' => ['ordering' => ['payment_methods' => ['cash', 'card'], 'require_settlement' => ['card']]], + ]]); + $onDemand->uuid = 'config-on-demand'; + $noQuote = fleetopsApiCustomerController(); + $noQuote->orderConfig = $onDemand; + $noQuote->serviceQuote = null; + $booked = fleetopsApiCustomerController(); + $booked->orderConfig = $onDemand; + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['service_type' => 'economy', 'service_name' => 'Economy'], true); + $booked->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); + $booked->serviceQuote->setRelation('serviceRate', $rate); + + $refused = $noQuote->createOrder(new FleetOpsApiCustomerOrderRequest(['pickup' => ['name' => 'A']])); + $booked->createOrder(new FleetOpsApiCustomerOrderRequest([ + 'service_quote' => 'quote_1', + 'pickup' => ['name' => 'A'], + 'payment_method' => 'card', + 'meta' => ['note' => 'Blue door'], + ])); + $byName = fleetopsApiCustomerController(); + $byName->createOrder(new FleetOpsApiCustomerOrderRequest(['payload' => 'payload_public', 'payment_method' => 'card'])); + + $owing = fleetopsApiCustomerController(); + $owing->orderConfig = $onDemand; + $owing->unsettledOrder = true; + $owing->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); + $blocked = $owing->createOrder(new FleetOpsApiCustomerOrderRequest(['service_quote' => 'quote_1'])); + + expect($refused->getStatusCode())->toBe(422) + ->and(fleetopsApiCustomerJson($refused))->toBe(['error' => 'Choose a service quote for this order first.']) + ->and($blocked->getStatusCode())->toBe(402) + ->and($owing->createdOrders)->toBe([]) + ->and($booked->createdOrders[0]['adhoc'])->toBeTrue() + ->and($booked->createdOrders[0]['required_vehicle_type'])->toBe('economy') + ->and($booked->createdOrders[0]['meta'])->toBe(['note' => 'Blue door']) + ->and($booked->paymentMethods)->toBe([['payload-built-uuid', 'card']]) + // An existing payload named by id keeps its own payment method. + ->and($byName->paymentMethods)->toBe([]); +}); + +test('an order that reached one of its config\'s terminal activities can no longer be canceled', function () { + $controller = fleetopsCustomerOrderController(['status' => 'no_show'], ['config' => new OrderConfig(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates::attributes('passenger'))]); + + expect($controller->cancelOrder('order_1', Request::create('/', 'POST'))->getStatusCode())->toBe(422) + ->and($controller->order->calls)->toBe([]); +}); + +test('a shared order links to the public tracking page', function () { + config()->set('fleetbase.console.host', 'https://console.test'); + $url = fleetopsApiCustomerWithEnvironment('production', function () { + $method = new ReflectionMethod(CustomerController::class, 'trackingPageUrl'); + + return $method->invoke(new CustomerController(), 'TRK1', null); + }); + + expect($url)->toContain('track/TRK1'); +}); diff --git a/server/tests/ApiOrderControllerContractsTest.php b/server/tests/ApiOrderControllerContractsTest.php index 228827ff1..98a72a079 100644 --- a/server/tests/ApiOrderControllerContractsTest.php +++ b/server/tests/ApiOrderControllerContractsTest.php @@ -1065,6 +1065,27 @@ public function isString(string $key): bool expect($controller->dispatchOrder('order-public'))->toBe(['apiError' => 'Order has already been dispatched!', 'status' => 400]); + // An order whose config turns dispatch off is refused, and not dispatched. + $withConfig = function (array $lifecycle) { + $config = new OrderConfig(); + $config->setRawAttributes(['uuid' => 'config-uuid', 'key' => 'pickup', 'meta' => json_encode(['lifecycle' => $lifecycle])], true); + $order = new FleetOpsApiOrderCrudFake(); + $order->order_config_uuid = 'config-uuid'; + $order->setRelation('orderConfig', $config); + $controller = new FleetOpsApiOrderCrudControllerProbe(); + $controller->order = $order; + + return [$controller->dispatchOrder('order-public'), $order]; + }; + [$refused, $kept] = $withConfig(['dispatch' => false]); + [$allowed, $sent] = $withConfig(['dispatch' => true]); + + expect($refused)->toBe(['apiError' => 'Orders of this type are not dispatched.', 'status' => 400]) + ->and($kept->dispatchedForTest)->toBeFalse() + ->and($kept->dispatchActivityInserted)->toBeFalse() + ->and($allowed)->toBe(['resource' => 'order', 'order' => $sent]) + ->and($sent->dispatchedForTest)->toBeTrue(); + $order = new FleetOpsApiOrderCrudFake(); $order->trackerFake->throwOnTrack = true; diff --git a/server/tests/CommandContractsTest.php b/server/tests/CommandContractsTest.php index f6d14ca32..f16841bf3 100644 --- a/server/tests/CommandContractsTest.php +++ b/server/tests/CommandContractsTest.php @@ -348,11 +348,11 @@ public function getDispatchableOrders(int $days = 2, int $intervalMinutes = 4, i return $this->orders; } - public function getNearbyDriversForOrder(Order $order, Point $pickup, int $distance, bool $testing = false): EloquentCollection - { - $this->messages[] = ['getNearbyDriversForOrder', $order->public_id, $distance, $testing]; + public ?FleetOpsAdhocStrategyFake $strategy = null; - return $this->drivers; + protected function strategyFor(Order $order): Fleetbase\FleetOps\Contracts\AdhocDispatchStrategy + { + return $this->strategy ??= new FleetOpsAdhocStrategyFake(); } public function info($string, $verbosity = null) @@ -389,13 +389,11 @@ public function warn($string, $verbosity = null) class FleetOpsDispatchAdhocOrdersQueryProbe extends DispatchAdhocOrders { public FleetOpsDispatchAdhocOrdersBuilderFake $orderQuery; - public FleetOpsDispatchAdhocOrdersBuilderFake $driverQuery; public function __construct(private array $testOptions) { parent::__construct(); $this->orderQuery = new FleetOpsDispatchAdhocOrdersBuilderFake(); - $this->driverQuery = new FleetOpsDispatchAdhocOrdersBuilderFake(); } public function option($key = null) @@ -409,10 +407,53 @@ protected function newOrderQuery(string $connection) return $this->orderQuery; } +} + +/** A dispatch strategy that offers each order to as many drivers as the test says. */ +class FleetOpsAdhocStrategyFake implements Fleetbase\FleetOps\Contracts\AdhocDispatchStrategy +{ + public array $offered = []; + public array $redispatched = []; + + public function name(): string + { + return 'fake'; + } + + public function label(): string + { + return 'Fake'; + } + + public function description(): string + { + return 'Offers to as many drivers as the test says.'; + } + + public function listsOpenly(): bool + { + return false; + } + + public function dispatch(Order $order): void + { + } + + public function redispatch(Order $order, bool $testing = false): int + { + $this->redispatched[] = [$order->public_id, $testing]; + + return $this->offered[$order->public_id] ?? 0; + } + + public function accept(Order $order, Driver $driver): bool + { + return true; + } - protected function newDriverQuery() + public function decline(Order $order, Driver $driver): bool { - return $this->driverQuery; + return true; } } @@ -2010,62 +2051,34 @@ public function getDropoffOrLastWaypoint(): object ->and($command->messages)->toContain(['info', 'No dispatchable orders found in the given timeframe.']); }); -test('dispatch adhoc command handles invalid pickups empty drivers and successful pings', function () { +test('dispatch adhoc command offers each order again through its strategy', function () { Carbon::setTestNow(Carbon::parse('2026-05-06 07:08:09')); - $invalidOrder = new FleetOpsDispatchAdhocOrdersOrderFake(); - $invalidOrder->public_id = 'order_invalid'; - $invalidOrder->dispatched_at = '2026-05-06 06:00:00'; - $invalidOrder->pickupLocation = null; + $quiet = new FleetOpsDispatchAdhocOrdersOrderFake(); + $quiet->public_id = 'order_quiet'; + $quiet->dispatched_at = '2026-05-06 06:00:00'; + $busy = new FleetOpsDispatchAdhocOrdersOrderFake(); + $busy->public_id = 'order_busy'; + $busy->dispatched_at = '2026-05-06 06:10:00'; - $emptyDriverOrder = new FleetOpsDispatchAdhocOrdersOrderFake(); - $emptyDriverOrder->public_id = 'order_empty'; - $emptyDriverOrder->dispatched_at = '2026-05-06 06:05:00'; - $emptyDriverOrder->pickupLocation = new Point(1.3, 103.8); - $emptyDriverOrder->adhocDistance = 1200; - - $pingOrder = new FleetOpsDispatchAdhocOrdersOrderFake(); - $pingOrder->public_id = 'order_ping'; - $pingOrder->dispatched_at = '2026-05-06 06:10:00'; - $pingOrder->pickupLocation = new Point(1.31, 103.81); - $pingOrder->adhocDistance = 2400; - - $driver = new FleetOpsDispatchAdhocOrdersDriverFake(); - $driver->public_id = 'driver_public'; - $driver->name = 'Jane Driver'; - - $command = new class(['sandbox' => true, 'testing' => true, 'days' => 3], $pingOrder, $driver) extends FleetOpsDispatchAdhocOrdersCommandFake { - public function __construct(array $options, private Order $pingOrder, private Driver $driver) - { - parent::__construct($options); - } - - public function getNearbyDriversForOrder(Order $order, Point $pickup, int $distance, bool $testing = false): EloquentCollection - { - parent::getNearbyDriversForOrder($order, $pickup, $distance, $testing); - - return $order === $this->pingOrder ? new EloquentCollection([$this->driver]) : new EloquentCollection(); - } - }; - $command->orders = new EloquentCollection([$invalidOrder, $emptyDriverOrder, $pingOrder]); + $command = new FleetOpsDispatchAdhocOrdersCommandFake(['sandbox' => true, 'testing' => true, 'days' => 3]); + $command->orders = new EloquentCollection([$quiet, $busy]); + $command->strategy = new FleetOpsAdhocStrategyFake(); + $command->strategy->offered = ['order_busy' => 2]; $command->handle(); expect($command->messages)->toContain(['info', 'Running in sandbox mode.']) - ->and($command->messages)->toContain(['alert', '3 orders found for ad-hoc dispatch. Current Time: 2026-05-06 07:08:09']) - ->and($command->messages)->toContain(['error', 'Invalid pickup location for order order_invalid']) - ->and($command->messages)->toContain(['warn', 'No available drivers found for order order_empty']) - ->and($command->messages)->toContain(['line', 'Checking order order_ping for nearby drivers within 2400 meters.']) - ->and($command->messages)->toContain(['info', 'Order order_ping dispatched successfully to 1 nearby drivers.']) - ->and($command->messages)->toContain(['info', 'Pinging driver Jane Driver (driver_public) ...']) - ->and($pingOrder->dispatchedForPing)->toBeTrue() - ->and($driver->notifications)->toBe([OrderPing::class]) + ->and($command->messages)->toContain(['alert', '2 orders found for ad-hoc dispatch. Current Time: 2026-05-06 07:08:09']) + ->and($command->messages)->toContain(['line', 'No new offer for order order_quiet (fake).']) + ->and($command->messages)->toContain(['info', 'Order order_busy offered to 2 driver(s) (fake).']) + ->and($command->strategy->redispatched)->toBe([['order_quiet', true], ['order_busy', true]]) ->and($command->tables)->toHaveCount(1); Carbon::setTestNow(); }); -test('dispatch adhoc command builds dispatchable order and nearby driver queries', function () { +test('dispatch adhoc command builds the dispatchable order query', function () { Carbon::setTestNow(Carbon::parse('2026-05-06 07:08:09')); $command = new FleetOpsDispatchAdhocOrdersQueryProbe([ @@ -2082,25 +2095,6 @@ public function getNearbyDriversForOrder(Order $order, Point $pickup, int $dista ->and($command->orderQuery->calls)->toContain(['whereHas', 'payload']) ->and($command->orderQuery->calls)->toContain(['with', ['company', 'payload']]); - $order = new Order(); - $order->setRawAttributes(['company_uuid' => 'company-uuid']); - $point = new Point(1.3, 103.8); - - expect($command->getNearbyDriversForOrder($order, $point, 500, true))->toBe($command->driverQuery->results) - ->and($command->driverQuery->calls)->toContain(['where', [['online' => 1]]]) - ->and($command->driverQuery->calls)->toContain(['whereNull', 'deleted_at']) - ->and($command->driverQuery->calls)->not->toContain(['whereNotNull', 'location']); - - $command = new FleetOpsDispatchAdhocOrdersQueryProbe([ - 'sandbox' => false, - ]); - - $command->getNearbyDriversForOrder($order, $point, 750, false); - - expect($command->driverQuery->calls)->toContain(['whereNotNull', 'location']) - ->and($command->driverQuery->calls)->toContain(['distanceSphere', 'location', $point, 750]) - ->and($command->driverQuery->calls)->toContain(['distanceSphereValue', 'location', $point]); - Carbon::setTestNow(); }); @@ -2361,6 +2355,8 @@ public function getNearbyDriversForOrder(Order $order, Point $pickup, int $dista }); test('assign driver roles command assigns non admin driver users and reports failures', function () { + fleetopsTestConnectionResolver(); + $company = new Company(); $company->setRawAttributes(['uuid' => 'company-uuid', 'name' => 'Acme Logistics'], true); diff --git a/server/tests/CompactResourceSerializationTest.php b/server/tests/CompactResourceSerializationTest.php index 658f68a7b..f20d6d7ad 100644 --- a/server/tests/CompactResourceSerializationTest.php +++ b/server/tests/CompactResourceSerializationTest.php @@ -67,7 +67,7 @@ public function isArray(string $key): bool return is_array($this->input($key)); } - public function array(string $key): array + public function inputArray(string $key): array { $value = $this->input($key); @@ -118,6 +118,11 @@ public function relationLoaded(string $relationship): bool return array_key_exists($relationship, $this->loaded); } + public function toArrayForTest(): array + { + return $this->attributes; + } + public function loadMissing(string|array $relationship): self { return $this; @@ -2842,3 +2847,44 @@ public function environment(...$environments) // Nor is there a tracking page to link to. ->and(array_key_exists('url', $withoutNumber))->toBeFalse(); }); + +test('the order resource adds the driver rating, payment status and how adhoc dispatch ended when they apply', function () { + $request = fleetopsCompactResourceRequest(false); + $rating = fleetopsCompactResourceFixture(['stars' => 5, 'comment' => 'Kind']); + $order = fleetopsCompactResourceFixture([ + 'orderConfig' => null, + 'payload' => fleetopsCompactResourceFixture(['payment_method' => 'card']), + 'trackingNumber' => null, + 'comments' => collect(), + 'files' => collect(), + 'purchaseRate' => null, + 'driverRating' => $rating, + 'transaction' => fleetopsCompactResourceFixture(['settlement_status' => 'paid']), + 'adhoc' => true, + 'type' => 'transport', + 'status' => 'completed', + 'meta' => [], + ], [ + 'driverRating' => $rating, + 'transaction' => true, + 'dispatchOutcome' => null, + ]); + $unrated = fleetopsCompactResourceFixture(array_merge($order->toArrayForTest(), ['driverRating' => null]), ['driverRating' => null, 'dispatchOutcome' => 'no_driver_found']); + $plain = fleetopsCompactResourceFixture(array_merge($order->toArrayForTest(), ['adhoc' => false]), ['dispatchOutcome' => null]); + + $payload = (new Fleetbase\FleetOps\Http\Resources\v1\Order($order))->resolve($request); + $other = (new Fleetbase\FleetOps\Http\Resources\v1\Order($unrated))->resolve($request); + $neither = (new Fleetbase\FleetOps\Http\Resources\v1\Order($plain))->resolve($request); + + expect($payload)->toMatchArray([ + 'id' => 'fixture_public', + 'driver_rating' => ['stars' => 5, 'comment' => 'Kind'], + 'payment_status' => 'paid', + 'dispatch_outcome' => null, + ]) + ->and($payload)->not->toHaveKeys(['fare', 'paid_at']) + ->and($other)->toMatchArray(['driver_rating' => null, 'dispatch_outcome' => 'no_driver_found']) + ->and($other)->not->toHaveKey('payment_status') + // Orders that weren't adhoc, and relations that weren't loaded, add nothing. + ->and($neither)->not->toHaveKeys(['dispatch_outcome', 'driver_rating', 'payment_status']); +}); diff --git a/server/tests/CustomerEndpointTest.php b/server/tests/CustomerEndpointTest.php index 38670211b..2c5697773 100644 --- a/server/tests/CustomerEndpointTest.php +++ b/server/tests/CustomerEndpointTest.php @@ -236,7 +236,7 @@ function fleetopsCustomerEndpointJson(JsonResponse $response): array // (code + for + meta->identity) is strictly stronger than exists:verification_codes. expect($create) ->toContain("'code' => 'required|string'") - ->toContain("'password' => 'required|string|min:8'") + ->toContain("'password' => 'nullable|string|min:8'") ->and($verify)->toContain("'mode' => 'required|in:email,sms'"); }); diff --git a/server/tests/DriverVehicleStatusDefaultTest.php b/server/tests/DriverVehicleStatusDefaultTest.php index 8cec78254..3ca0c1551 100644 --- a/server/tests/DriverVehicleStatusDefaultTest.php +++ b/server/tests/DriverVehicleStatusDefaultTest.php @@ -44,7 +44,7 @@ }); test('dispatch driver availability queries use available status', function () { - $listener = file_get_contents(dirname(__DIR__) . '/src/Listeners/HandleOrderDispatched.php'); + $listener = file_get_contents(dirname(__DIR__) . '/src/Support/DriverMatching.php'); $order = file_get_contents(dirname(__DIR__) . '/src/Models/Order.php'); expect($listener) diff --git a/server/tests/EventContractsTest.php b/server/tests/EventContractsTest.php index 78c4ccf61..7f109ab19 100644 --- a/server/tests/EventContractsTest.php +++ b/server/tests/EventContractsTest.php @@ -821,6 +821,8 @@ public function getPickupOrCurrentWaypoint(): mixed }); test('geofence entered listener handles arrival branch outcomes', function () { + fleetopsTestConnectionResolver(); + $listener = new HandleGeofenceEntered(); $arrival = new ReflectionMethod(HandleGeofenceEntered::class, 'handleOrderArrival'); $arrival->setAccessible(true); diff --git a/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php new file mode 100644 index 000000000..7601fb99b --- /dev/null +++ b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php @@ -0,0 +1,1827 @@ + $data, 'rules' => $rules, 'attributes' => $attributes]; + $errors = new Illuminate\Support\MessageBag(); + foreach ($rules as $field => $fieldRules) { + $value = $data[$field] ?? null; + $name = $attributes[$field] ?? $field; + if (in_array('required', $fieldRules, true) && ($value === null || $value === '')) { + $errors->add($field, 'The ' . $name . ' field is required.'); + } elseif ($value !== null && in_array('integer', $fieldRules, true) && filter_var($value, FILTER_VALIDATE_INT) === false) { + $errors->add($field, 'The ' . $name . ' field must be an integer.'); + } + } + + return new class($errors) { + public function __construct(public Illuminate\Support\MessageBag $bag) + { + } + + public function fails(): bool + { + return $this->bag->isNotEmpty(); + } + + public function errors(): Illuminate\Support\MessageBag + { + return $this->bag; + } + }; + } +} + +class AdhocCfgRecorder +{ + public static array $notified = []; + public static array $sent = []; + public static array $events = []; + public static bool $failEvents = false; +} + +/** An order whose cancellation is recorded rather than run, and whose pickup is set directly. */ +class AdhocCfgOrder extends Order +{ + public static ?Point $pickupPoint = null; + public static array $canceled = []; + + public function getPickupLocation(): mixed + { + return static::$pickupPoint; + } + + public function cancelWithReason(?string $reason = null) + { + static::$canceled[] = [$this->uuid, $reason]; + + return null; + } +} + +/** A point as MySQL stores it (SRID, then WKB), which the spatial models read back. */ +function adhocCfgWkb(float $longitude, float $latitude): string +{ + return pack('V', 0) . pack('C', 1) . pack('V', 1) . pack('e', $longitude) . pack('e', $latitude); +} + +/** [longitude, latitude] of a stored point or of WKT text. */ +function adhocCfgPoint(?string $value): array +{ + if ($value !== null && preg_match('/POINT\(\s*([-0-9.]+)\s+([-0-9.]+)\s*\)/i', $value, $m)) { + return [(float) $m[1], (float) $m[2]]; + } + if ($value === null || strlen($value) < 25) { + return [0.0, 0.0]; + } + $xy = unpack('ex/ey', substr($value, 9, 16)); + + return [$xy['x'], $xy['y']]; +} + +/** The policies the test config starts with: one driver at a time, 15 seconds per offer. */ +function adhocCfgBasePolicies(): array +{ + return ['dispatch' => ['adhoc' => ['strategy' => 'sequential', 'offer_timeout' => 15]]]; +} + +function adhocCfgBoot(): SQLiteConnection +{ + if (!Illuminate\Support\Str::hasMacro('humanize')) { + Illuminate\Support\Str::macro('humanize', fn ($value, $uppercase = true) => str_replace('_', ' ', Illuminate\Support\Str::snake((string) $value))); + } + + $pdo = new PDO('sqlite::memory:'); + $pdo->sqliteCreateFunction('ST_GeomFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); + $pdo->sqliteCreateFunction('ST_PointFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); + $pdo->sqliteCreateFunction('ST_X', fn ($wkt) => adhocCfgPoint($wkt)[0]); + $pdo->sqliteCreateFunction('ST_Y', fn ($wkt) => adhocCfgPoint($wkt)[1]); + $pdo->sqliteCreateFunction('st_distance_sphere', function ($a, $b) { + [$lng1, $lat1] = adhocCfgPoint($a); + [$lng2, $lat2] = adhocCfgPoint($b); + $rad = M_PI / 180; + $h = sin(($lat2 - $lat1) * $rad / 2) ** 2 + cos($lat1 * $rad) * cos($lat2 * $rad) * sin(($lng2 - $lng1) * $rad / 2) ** 2; + + return 2 * 6371000 * asin(sqrt($h)); + }); + $pdo->sqliteCreateFunction('LOWER', fn ($value) => $value === null ? null : strtolower((string) $value)); + + $connection = new SQLiteConnection($pdo); + $resolver = new ConnectionResolver(['default' => $connection, 'mysql' => $connection]); + $resolver->setDefaultConnection('mysql'); + EloquentModel::setConnectionResolver($resolver); + if (!EloquentModel::getEventDispatcher()) { + EloquentModel::setEventDispatcher(new Illuminate\Events\Dispatcher()); + } + app()->instance('db', new class($connection) { + public function __construct(public SQLiteConnection $c) + { + } + + public function connection($name = null): SQLiteConnection + { + return $this->c; + } + + public function __call($method, $arguments) + { + return $this->c->{$method}(...$arguments); + } + }); + Illuminate\Support\Facades\DB::clearResolvedInstance('db'); + app()->instance('responsecache', new class { + public function __call($method, $arguments) + { + return null; + } + }); + config()->set('activitylog.enabled', false); + config()->set('activitylog.default_auth_driver', 'web'); + app()->bind(Illuminate\Contracts\Config\Repository::class, fn () => config()); + Illuminate\Support\Facades\Cache::swap(new Illuminate\Cache\Repository(new Illuminate\Cache\ArrayStore())); + + app()->instance(Illuminate\Contracts\Notifications\Dispatcher::class, new class { + public function send($notifiables, $notification) + { + if (AdhocCfgRecorder::$notified === ['throw']) { + throw new RuntimeException('push failed'); + } + AdhocCfgRecorder::$notified[] = [$notifiables->uuid, $notification::class]; + AdhocCfgRecorder::$sent[] = $notification; + } + + public function sendNow($notifiables, $notification, ?array $channels = null) + { + $this->send($notifiables, $notification); + } + }); + app()->instance('log', new class { + public array $warnings = []; + + public function warning($message, array $context = []) + { + $this->warnings[] = $message; + } + + public function __call($method, $arguments) + { + return null; + } + }); + Illuminate\Support\Facades\Log::clearResolvedInstance('log'); + + $schema = $connection->getSchemaBuilder(); + $tables = [ + 'companies' => ['uuid', 'public_id', 'name', 'options'], + 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'type', 'status', 'email', 'phone'], + 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid', 'meta', 'rating_average', 'rating_count'], + 'vehicles' => ['uuid', 'public_id', 'company_uuid', 'type', 'plate_number', 'seating_capacity', 'vendor_uuid', 'photo_uuid', 'avatar_url', 'name', 'internal_id', 'location', 'online', 'speed', 'heading', 'altitude', 'year', 'make', 'model', 'class', 'color', 'call_sign', 'status', 'specs', 'vin_data', 'telematics', 'meta', 'slug', 'vin', 'trim', 'plate_number_type'], + 'orders' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'required_vehicle_type', 'chat_channel_uuid', 'tracking_number_uuid', 'dispatched_at', 'started_at', 'customer_uuid', 'customer_type', 'purchase_rate_uuid', 'transaction_uuid', 'order_config_uuid', 'payload_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'adhoc_distance', 'dispatched', 'started', 'meta'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'policies', 'triggers', 'version', 'core_service', 'status', 'type', 'tags'], + 'order_offers' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'status', 'distance', 'expires_at', 'responded_at'], + 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta', 'payment_method'], + 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'location', 'meta', 'owner_uuid', 'owner_type'], + 'waypoints' => ['uuid', 'payload_uuid', 'place_uuid', 'order'], + 'entities' => ['uuid', 'payload_uuid', 'name'], + 'tracking_statuses' => ['uuid', 'company_uuid', 'tracking_number_uuid', 'code', 'status'], + 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'status_uuid'], + 'contacts' => ['uuid', '_key', 'public_id', 'company_uuid', 'user_uuid', 'name', 'email', 'phone', 'type', 'photo_uuid', 'meta'], + 'chat_channels' => ['uuid', '_key', 'public_id', 'company_uuid', 'created_by_uuid', 'name', 'slug', 'meta'], + 'chat_participants' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'user_uuid', 'meta'], + 'chat_messages' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'sender_uuid', 'content', 'meta'], + 'chat_attachments' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'chat_message_uuid', 'sender_uuid', 'file_uuid'], + 'chat_logs' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'initiator_uuid', 'event_type', 'content', 'subjects', 'meta', 'status'], + 'vendors' => ['uuid', 'public_id', 'company_uuid', 'name'], + 'files' => ['uuid', 'public_id', 'company_uuid', 'type', 'path', 'disk', 'bucket', 'original_filename', 'content_type', 'file_size', 'meta'], + 'chat_receipts' => ['uuid', 'public_id', 'company_uuid', 'chat_message_uuid', 'participant_uuid', 'read_at'], + 'positions' => ['uuid', '_key', 'public_id', 'company_uuid', 'order_uuid', 'subject_uuid', 'subject_type', 'coordinates', 'heading', 'speed'], + 'service_rates' => ['uuid', 'public_id', 'company_uuid', 'service_name', 'service_type', 'base_fee', 'per_meter_flat_rate_fee', 'per_meter_unit', 'rate_calculation_method', 'algorithm', 'currency', 'has_cod_fee', 'has_peak_hours_fee'], + 'driver_ratings' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'customer_uuid', 'customer_type', 'stars', 'comment'], + 'service_quotes' => ['uuid', '_key', 'distance', 'time', 'public_id', 'company_uuid', 'request_id', 'service_rate_uuid', 'payload_uuid', 'amount', 'currency', 'meta', 'expired_at'], + 'service_quote_items' => ['uuid', '_key', 'public_id', 'service_quote_uuid', 'amount', 'currency', 'details', 'code'], + 'purchase_rates' => ['uuid', '_key', 'public_id', 'company_uuid', 'customer_uuid', 'customer_type', 'service_quote_uuid', 'transaction_uuid', 'payload_uuid', 'status', 'meta'], + 'transactions' => ['uuid', 'public_id', 'company_uuid', 'subject_uuid', 'subject_type', 'context_uuid', 'context_type', 'direction', 'type', 'status', 'settlement_status', 'amount', 'currency', 'meta'], + 'custom_fields' => ['uuid', 'public_id', 'company_uuid', 'category_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'for', 'component', 'options', 'required', 'editable', 'default_value', 'validation_rules', 'meta', 'description', 'help_text', 'order'], + 'custom_field_values' => ['uuid', 'public_id', 'company_uuid', 'custom_field_uuid', 'subject_uuid', 'subject_type', 'value', 'value_type'], + ]; + foreach ($tables as $table => $columns) { + $schema->create($table, function ($blueprint) use ($columns) { + $blueprint->increments('id'); + foreach ($columns as $column) { + $blueprint->string($column)->nullable(); + } + $blueprint->timestamps(); + $blueprint->timestamp('deleted_at')->nullable(); + }); + } + + session(['company' => 'company-1']); + $connection->table('companies')->insert([['uuid' => 'company-1', 'public_id' => 'company_one', 'name' => 'Acme Cabs'], ['uuid' => 'company-2', 'public_id' => 'company_two', 'name' => 'Other Cabs']]); + $passenger = OrderConfigTemplates::attributes('passenger'); + $connection->table('order_configs')->insert([ + 'uuid' => 'config-adhoc', + 'public_id' => 'order_config_passenger', + 'company_uuid' => 'company-1', + 'name' => $passenger['name'], + 'key' => $passenger['key'], + 'namespace' => $passenger['namespace'], + 'flow' => json_encode($passenger['flow']), + 'meta' => json_encode($passenger['meta']), + 'policies' => json_encode(adhocCfgBasePolicies()), + 'triggers' => json_encode([]), + ]); + $connection->table('places')->insert(['uuid' => 'place-pickup', 'company_uuid' => 'company-1', 'name' => 'Raffles Place', 'location' => adhocCfgWkb(103.8511, 1.2841)]); + $connection->table('payloads')->insert(['uuid' => 'payload-1', 'company_uuid' => 'company-1', 'pickup_uuid' => 'place-pickup']); + $connection->table('vehicles')->insert([ + ['uuid' => 'car-economy', 'company_uuid' => 'company-1', 'type' => 'Economy'], + ['uuid' => 'car-xl', 'company_uuid' => 'company-1', 'type' => 'xl'], + ]); + + OrderConfigTriggers::$runImmediately = true; + AdhocCfgRecorder::$notified = []; + AdhocCfgRecorder::$sent = []; + Fleetbase\TestSupport\DispatchRecorder::$dispatched = []; + AdhocCfgOrder::$canceled = []; + AdhocCfgOrder::$pickupPoint = new Point(1.2841, 103.8511); + + return $connection; +} + +/** Store policies on the test config, over the ones it starts with. */ +function adhocCfgPolicies(SQLiteConnection $connection, array $policies): void +{ + $connection->table('order_configs')->where('uuid', 'config-adhoc')->update(['policies' => json_encode(array_replace_recursive(adhocCfgBasePolicies(), $policies))]); +} + +/** Store the test config's triggers. */ +function adhocCfgTriggers(SQLiteConnection $connection, array $triggers): void +{ + $connection->table('order_configs')->where('uuid', 'config-adhoc')->update(['triggers' => json_encode($triggers)]); +} + +/** Drivers around the pickup at Raffles Place, nearest first: Amara 545 m, Chen 1.2 km, Ben (XL) 210 m. */ +function adhocCfgSeedDrivers(SQLiteConnection $connection): void +{ + $connection->table('drivers')->insert([ + ['uuid' => 'amara', 'public_id' => 'driver_amara', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2890)], + ['uuid' => 'chen', 'public_id' => 'driver_chen', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2950)], + ['uuid' => 'ben', 'public_id' => 'driver_ben', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-xl', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2860)], + ['uuid' => 'far', 'public_id' => 'driver_far', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.9915, 1.3644)], + ['uuid' => 'offline', 'public_id' => 'driver_offline', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 0, 'location' => adhocCfgWkb(103.8511, 1.2845)], + ['uuid' => 'rival', 'public_id' => 'driver_rival', 'company_uuid' => 'company-2', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2842)], + ]); +} + +function adhocCfgOrder(SQLiteConnection $connection, array $attributes = []): AdhocCfgOrder +{ + $connection->table('orders')->insert(array_merge([ + 'uuid' => 'order-1', + 'public_id' => 'order_one', + 'company_uuid' => 'company-1', + 'order_config_uuid' => 'config-adhoc', + 'payload_uuid' => 'payload-1', + 'status' => 'dispatched', + 'type' => 'passenger', + 'adhoc' => 1, + 'adhoc_distance' => 6000, + 'dispatched' => 1, + 'started' => 0, + 'required_vehicle_type' => 'economy', + ], $attributes)); + + return adhocCfgFresh($attributes['uuid'] ?? 'order-1'); +} + +function adhocCfgFresh(string $uuid = 'order-1'): AdhocCfgOrder +{ + return AdhocCfgOrder::where('uuid', $uuid)->first(); +} + +function adhocCfgDriver(string $uuid): Driver +{ + return Driver::withoutGlobalScopes()->where('uuid', $uuid)->first(); +} + +function adhocCfgStatuses(SQLiteConnection $connection): array +{ + return $connection->table('order_offers')->orderBy('id')->get(['driver_uuid', 'status'])->map(fn ($row) => [$row->driver_uuid, $row->status])->all(); +} + +function adhocCfgSequential(): SequentialStrategy +{ + return new SequentialStrategy(); +} + +test('drivers are matched by company and vehicle type, and busy drivers are left out only under the matching policy', function () { + $connection = adhocCfgBoot(); + $connection->table('users')->insert(['uuid' => 'user-moved', 'company_uuid' => 'company-1']); + $connection->table('orders')->insert([ + ['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => null], + ['uuid' => 'job-done', 'company_uuid' => 'company-1', 'status' => 'completed', 'deleted_at' => null], + ['uuid' => 'job-gone', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => now()], + ['uuid' => 'job-noshow', 'company_uuid' => 'company-1', 'status' => 'no_show', 'deleted_at' => null], + ]); + $connection->table('drivers')->insert([ + ['uuid' => 'free', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'via-user', 'company_uuid' => 'company-9', 'user_uuid' => 'user-moved', 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'other-company', 'company_uuid' => 'company-2', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'busy', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-live'], + ['uuid' => 'finished', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-done'], + ['uuid' => 'stale', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-gone'], + ['uuid' => 'no-show', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-noshow'], + ['uuid' => 'big-car', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-xl', 'current_job_uuid' => null], + ]); + $match = fn (Order $order) => DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $order)->orderBy('id')->pluck('uuid')->all(); + + // An order without a config of its own has no matching policy: busy drivers aren't left out. + $unconfigured = new Order(); + $unconfigured->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' ECONOMY '], true); + $anyClass = new Order(); + $anyClass->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' '], true); + + expect($match($unconfigured))->toBe(['free', 'via-user', 'busy', 'finished', 'stale', 'no-show']) + ->and($match($anyClass))->toBe(['free', 'via-user', 'busy', 'finished', 'stale', 'no-show', 'big-car']) + ->and(DriverMatching::vehicleClass($anyClass))->toBeNull() + ->and(DriverMatching::vehicleClass($unconfigured))->toBe('ECONOMY'); + + // The config's policy is off by default. + $configured = new Order(); + $configured->setRawAttributes(['company_uuid' => 'company-1', 'order_config_uuid' => 'config-adhoc', 'required_vehicle_type' => 'economy'], true); + expect($match($configured))->toBe(['free', 'via-user', 'busy', 'finished', 'stale', 'no-show']); + + // With it on, a driver on an unfinished order is left out. An order at one of the company + // configs' terminal activities (no_show here) doesn't keep its driver busy. + adhocCfgPolicies($connection, ['dispatch' => ['matching' => ['exclude_busy_drivers' => true]]]); + $configured = new Order(); + $configured->setRawAttributes(['company_uuid' => 'company-1', 'order_config_uuid' => 'config-adhoc', 'required_vehicle_type' => 'economy'], true); + + expect($match($configured))->toBe(['free', 'via-user', 'finished', 'stale', 'no-show']) + ->and(DriverMatching::freeJobStatuses('company-1'))->toBe(['completed', 'canceled', 'no_show']) + ->and(DriverMatching::freeJobStatuses('company-2'))->toBe(['completed', 'canceled']) + ->and(DriverMatching::freeJobStatuses(null))->toBe(['completed', 'canceled']); +}); + +test('one at a time: the order goes to the nearest free driver of its type first', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + + Carbon::setTestNow('2026-11-06 09:00:00'); + adhocCfgSequential()->dispatch($order); + Carbon::setTestNow(); + $offer = OrderOffers::pending($order); + + expect(adhocCfgSequential()->name())->toBe('sequential') + ->and($offer->driver_uuid)->toBe('amara') + ->and($offer->distance)->toBeGreaterThan(500)->toBeLessThan(600) + ->and($offer->expires_at->toDateTimeString())->toBe('2026-11-06 09:00:15') + ->and(AdhocCfgRecorder::$notified)->toBe([['amara', OrderPing::class]]) + ->and(Fleetbase\TestSupport\DispatchRecorder::$dispatched)->toBe([['job' => ExpireOrderOffer::class, 'arguments' => [$offer->uuid]]]) + ->and($offer->order->uuid)->toBe('order-1') + ->and($offer->driver->uuid)->toBe('amara'); + + // Dispatching again keeps the open offer instead of offering it twice. + adhocCfgSequential()->dispatch($order); + expect(adhocCfgStatuses($connection))->toBe([['amara', 'pending']]); +}); + +test('one at a time: declining moves the order on, and only the offered driver may accept', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + + expect(adhocCfgSequential()->accept($order, adhocCfgDriver('chen')))->toBeFalse() + ->and(adhocCfgSequential()->decline($order, adhocCfgDriver('chen')))->toBeFalse() + ->and(adhocCfgSequential()->decline($order, adhocCfgDriver('amara')))->toBeTrue() + ->and(OrderOffers::pending($order)->driver_uuid)->toBe('chen') + ->and(adhocCfgSequential()->accept($order, adhocCfgDriver('amara')))->toBeFalse() + ->and(adhocCfgSequential()->accept($order, adhocCfgDriver('chen')))->toBeTrue() + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'accepted']]); +}); + +test('one at a time: an offer that ran out cannot be accepted and moves on once', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + $offer = OrderOffers::pending($order); + + expect(adhocCfgSequential()->expire($offer))->toBeFalse(); + + Carbon::setTestNow(now()->addSeconds(30)); + $acceptedLate = adhocCfgSequential()->accept($order, adhocCfgDriver('amara')); + $first = (new ExpireOrderOffer($offer->uuid))->handle(); + $again = (new ExpireOrderOffer($offer->uuid))->handle(); + $missing = (new ExpireOrderOffer('no-such-offer'))->handle(); + Carbon::setTestNow(); + + expect($acceptedLate)->toBeFalse() + ->and($first)->toBeTrue() + ->and($again)->toBeFalse() + ->and($missing)->toBeFalse() + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'expired'], ['chen', 'pending']]); +}); + +test('one at a time: the scheduled check starts lost offers and moves stuck ones on', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + + expect(adhocCfgSequential()->redispatch($order))->toBe(1) + ->and(adhocCfgSequential()->redispatch($order))->toBe(0); + + Carbon::setTestNow(now()->addMinute()); + expect(adhocCfgSequential()->redispatch($order))->toBe(1); + Carbon::setTestNow(); + + $connection->table('order_offers')->update(['status' => 'declined']); + expect(adhocCfgSequential()->redispatch($order))->toBe(0) + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'declined']]); +}); + +test('one at a time: when nobody is left the order stays open by default, marked no driver found, and the exhausted triggers run', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgTriggers($connection, [ + ['event' => OrderConfigTriggers::DISPATCH_OFFER_EXHAUSTED, 'action' => 'set_meta', 'params' => ['key' => 'exhausted_seen', 'value' => 'yes']], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'set_meta', 'params' => ['key' => 'canceled_seen', 'value' => 'yes']], + ]); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + adhocCfgSequential()->decline($order, adhocCfgDriver('amara')); + adhocCfgSequential()->decline($order, adhocCfgDriver('chen')); + $open = adhocCfgFresh(); + + expect(AdhocCfgOrder::$canceled)->toBe([]) + ->and($open->status)->toBe('dispatched') + ->and($open->getMeta('dispatch_outcome'))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and($open->getMeta('exhausted_seen'))->toBe('yes') + ->and($open->getMeta('canceled_seen'))->toBeNull() + ->and(OrderOffers::outcome($open))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and($open->dispatchOutcome())->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(OrderOffers::pending($open))->toBeNull(); + + // A later scheduled run that finds nobody again doesn't fire the triggers a second time. + $open->updateMeta('exhausted_seen', 'cleared'); + OrderOffers::exhausted($open); + expect(adhocCfgFresh()->getMeta('exhausted_seen'))->toBe('cleared'); + + // Once the operator assigns a driver it is no longer an order nobody took. + $connection->table('orders')->where('uuid', 'order-1')->update(['driver_assigned_uuid' => 'ben']); + expect(OrderOffers::outcome(adhocCfgFresh()))->toBeNull(); +}); + +test('one at a time: when nobody is left an order whose policy says cancel is canceled as no driver found', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgPolicies($connection, ['dispatch' => ['adhoc' => ['on_exhausted' => 'cancel']]]); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + adhocCfgSequential()->decline($order, adhocCfgDriver('amara')); + adhocCfgSequential()->decline($order, adhocCfgDriver('chen')); + + // The cancel itself is recorded by the test order; mark it canceled as the real one would. + $connection->table('orders')->where('uuid', 'order-1')->update(['status' => 'canceled']); + + expect(AdhocCfgOrder::$canceled)->toBe([['order-1', OrderOffers::NO_DRIVER_FOUND]]) + ->and(OrderOffers::outcome(adhocCfgFresh()))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(OrderOffers::pending($order))->toBeNull(); + + // Without the meta, a canceled order's offers tell: all declined or expired is no driver found, + // while one canceled with an offer still open (withdrawn) wasn't for want of a driver. + $declined = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'status' => 'canceled']); + $withdrew = adhocCfgOrder($connection, ['uuid' => 'order-3', 'public_id' => 'order_three', 'status' => 'canceled']); + $connection->table('order_offers')->insert([ + ['uuid' => 'f-2a', 'order_uuid' => 'order-2', 'driver_uuid' => 'amara', 'status' => 'declined'], + ['uuid' => 'f-2b', 'order_uuid' => 'order-2', 'driver_uuid' => 'chen', 'status' => 'expired'], + ['uuid' => 'f-3a', 'order_uuid' => 'order-3', 'driver_uuid' => 'amara', 'status' => 'declined'], + ['uuid' => 'f-3b', 'order_uuid' => 'order-3', 'driver_uuid' => 'chen', 'status' => 'withdrawn'], + ]); + $notAdhoc = new Order(); + $notAdhoc->setRawAttributes(['uuid' => 'order-2', 'status' => 'canceled', 'adhoc' => 0], true); + $live = adhocCfgOrder($connection, ['uuid' => 'order-4', 'public_id' => 'order_four']); + + expect(OrderOffers::outcome($declined))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(OrderOffers::outcome($withdrew))->toBeNull() + ->and(OrderOffers::outcome($notAdhoc))->toBeNull() + ->and(OrderOffers::outcome($live))->toBeNull(); +}); + +test('one at a time: an order without a usable pickup finds no driver and stays open by default', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + AdhocCfgOrder::$pickupPoint = null; + + adhocCfgSequential()->dispatch(adhocCfgOrder($connection)); + + expect(AdhocCfgOrder::$canceled)->toBe([]) + ->and(adhocCfgFresh()->getMeta('dispatch_outcome'))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(adhocCfgStatuses($connection))->toBe([]); + + adhocCfgPolicies($connection, ['dispatch' => ['adhoc' => ['on_exhausted' => 'cancel']]]); + adhocCfgSequential()->dispatch(adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two'])); + expect(AdhocCfgOrder::$canceled)->toBe([['order-2', OrderOffers::NO_DRIVER_FOUND]]); +}); + +test('one at a time: started, assigned or finished orders are not offered again', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + + $started = adhocCfgOrder($connection, ['uuid' => 'o-started', 'started' => 1]); + $assigned = adhocCfgOrder($connection, ['uuid' => 'o-assigned', 'driver_assigned_uuid' => 'amara']); + $canceled = adhocCfgOrder($connection, ['uuid' => 'o-canceled', 'status' => 'canceled']); + + expect(adhocCfgSequential()->offerNext($started))->toBeNull() + ->and(adhocCfgSequential()->offerNext($assigned))->toBeNull() + ->and(adhocCfgSequential()->offerNext($canceled))->toBeNull() + ->and(adhocCfgStatuses($connection))->toBe([]) + ->and(AdhocCfgOrder::$canceled)->toBe([]); +}); + +test('one at a time: a failed push still leaves the offer open', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + AdhocCfgRecorder::$notified = ['throw']; + + adhocCfgSequential()->dispatch($order); + + expect(OrderOffers::pending($order)->driver_uuid)->toBe('amara') + ->and(app('log')->warnings)->toContain('Unable to send an order offer'); +}); + +test('at once: every nearby driver of the type is offered the order, and the first to accept gets it', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast']); + $broadcast = new BroadcastStrategy(); + + $broadcast->dispatch($order); + + expect($broadcast->name())->toBe('broadcast') + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'pending'], ['chen', 'pending']]) + ->and(AdhocCfgRecorder::$notified)->toBe([['amara', OrderPing::class], ['chen', OrderPing::class]]) + ->and($broadcast->accept($order, adhocCfgDriver('ben')))->toBeTrue(); + + OrderOffers::claimed($order, adhocCfgDriver('chen')); + expect(adhocCfgStatuses($connection))->toBe([['amara', 'withdrawn'], ['chen', 'accepted']]); +}); + +test('at once: a driver who declines is not offered the order again', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast', 'required_vehicle_type' => null]); + $broadcast = new BroadcastStrategy(); + $broadcast->dispatch($order); + + // Ben declines his offer; Far, never offered, declines from the list of nearby orders. + expect($broadcast->decline($order, adhocCfgDriver('ben')))->toBeTrue() + ->and($broadcast->decline($order, adhocCfgDriver('far')))->toBeTrue() + ->and($broadcast->decline($order, adhocCfgDriver('far')))->toBeTrue(); + + Carbon::setTestNow('2026-11-06 10:00:00'); + $offered = $broadcast->redispatch($order); + Carbon::setTestNow(); + + expect($offered)->toBe(2) + ->and(OrderOffers::declinedDrivers($order))->toBe(['ben', 'far']) + ->and($connection->table('order_offers')->where('status', 'pending')->orderBy('id')->pluck('driver_uuid')->all())->toBe(['amara', 'chen']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('dispatched_at'))->toBe('2026-11-06 10:00:00'); +}); + +test('at once: no pickup means nobody to offer, and a failed push skips only that driver', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $broadcast = new BroadcastStrategy(); + + AdhocCfgOrder::$pickupPoint = null; + expect($broadcast->redispatch(adhocCfgOrder($connection, ['uuid' => 'o-nowhere'])))->toBe(0); + + AdhocCfgOrder::$pickupPoint = new Point(1.2841, 103.8511); + AdhocCfgRecorder::$notified = ['throw']; + expect($broadcast->redispatch(adhocCfgOrder($connection)))->toBe(2); +}); + +test('which strategy an order uses: its own, its config\'s adhoc policy, its company\'s, then one at a time', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast']); + $fromConfig = adhocCfgOrder($connection, ['uuid' => 'o-config']); + $configName = AdhocDispatch::nameFor($fromConfig); + $configWait = AdhocDispatch::offerTimeout($fromConfig); + // Written straight to the table, past the model's normalizing, as an old or hand-edited row could be. + $connection->table('order_configs')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['strategy' => 'nonsense', 'offer_timeout' => null]]])]); + $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 500]])]); + $fromCompany = adhocCfgFresh('o-config')->load('company'); + $connection->table('companies')->update(['options' => null]); + $fallback = adhocCfgFresh('o-config'); + // An order without a config of its own has no policies, so goes straight to the company's. + $unconfigured = adhocCfgOrder($connection, ['uuid' => 'o-none', 'order_config_uuid' => null]); + + expect(AdhocDispatch::nameFor($order))->toBe('broadcast') + ->and(AdhocDispatch::for($order))->toBeInstanceOf(BroadcastStrategy::class) + ->and($configName)->toBe('sequential') + ->and($configWait)->toBe(15) + ->and(AdhocDispatch::nameFor($fromCompany))->toBe('broadcast') + ->and(AdhocDispatch::offerTimeout($fromCompany))->toBe(120) + ->and(AdhocDispatch::nameFor($fallback))->toBe(AdhocDispatch::DEFAULT) + ->and(AdhocDispatch::offerTimeout($fallback))->toBe(20) + ->and(AdhocDispatch::nameFor($unconfigured))->toBe(AdhocDispatch::DEFAULT) + ->and(AdhocDispatch::DEFAULT)->toBe('sequential'); + + $connection->table('order_configs')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['offer_timeout' => 2]]])]); + expect(AdhocDispatch::offerTimeout(adhocCfgFresh('o-config')))->toBe(10); +}); + +test('more strategies can be registered by name', function () { + $nearestOnly = new class extends SequentialStrategy { + public function name(): string + { + return 'nearest-only'; + } + }; + AdhocDispatch::register('nearest-only', $nearestOnly::class); + + expect(AdhocDispatch::names())->toContain('broadcast', 'sequential', 'nearest-only') + ->and(AdhocDispatch::has('nearest-only'))->toBeTrue() + ->and(AdhocDispatch::has(null))->toBeFalse() + ->and(fn () => AdhocDispatch::register('broken', stdClass::class))->toThrow(InvalidArgumentException::class); +}); + +test('offers record each driver once, and a decline from a driver who was never offered the order', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + $amara = adhocCfgDriver('amara'); + + $first = OrderOffers::record($order, $amara); + $again = OrderOffers::record($order, $amara); + OrderOffers::recordDecline($order, adhocCfgDriver('ben')); + + expect($again->uuid)->toBe($first->uuid) + ->and($first->expires_at)->toBeNull() + ->and(OrderOffers::offeredDrivers($order))->toBe(['amara', 'ben']) + ->and(OrderOffers::acceptPending($order, $amara))->toBeTrue() + ->and(OrderOffers::withdraw($order))->toBe(0); +}); + +test('the passenger config is a strict flow with a no-show ending, offered one driver at a time', function () { + $attributes = OrderConfigTemplates::attributes('passenger'); + $config = new OrderConfig($attributes); + + expect($attributes['key'])->toBe('passenger') + ->and(array_keys($attributes['flow']))->toBe(['created', 'dispatched', 'started', 'arrived', 'in_progress', 'completed', 'no_show']) + ->and($config->policy('dispatch.adhoc.strategy'))->toBe('sequential') + ->and($config->policy('dispatch.adhoc.customer_orders'))->toBeTrue() + ->and($config->policy('dispatch.matching.vehicle_type'))->toBeTrue() + ->and($config->hasStrictTransitions())->toBeTrue() + ->and($config->canTransition('arrived', 'no_show'))->toBeTrue() + ->and($config->canTransition('arrived', 'completed'))->toBeFalse() + ->and($config->canTransition('in_progress', 'completed'))->toBeTrue() + ->and($config->isTerminalActivityCode('no_show'))->toBeTrue() + ->and($config->getStartedActivity()->get('status'))->toBe('Driver on the way'); +}); + +class AdhocCfgCreateCommand extends CreateOrderConfig +{ + public array $lines = []; + public array $tables = []; + public ?string $key = null; + public array $opts = []; + + public function option($key = null) + { + return $this->opts[$key] ?? null; + } + + public function argument($key = null) + { + return $this->key; + } + + public function info($string, $verbosity = null) + { + $this->lines[] = $string; + } + + public function error($string, $verbosity = null) + { + $this->lines[] = $string; + } + + public function table($headers, $rows, $tableStyle = 'default', array $columnStyles = []) + { + $this->tables[] = [$headers, $rows]; + } +} + +test('the create order config command lists templates and makes a company\'s config once, or a named one', function () { + $connection = adhocCfgBoot(); + $connection->table('order_configs')->delete(); + $run = function (?string $key, array $opts = []) { + $command = new AdhocCfgCreateCommand(); + $command->key = $key; + $command->opts = $opts; + + return [$command->handle(), $command]; + }; + + [$listed, $list] = $run('passenger', ['list' => true]); + [$bare, $bareList] = $run(null); + [$unknown, $nope] = $run('limousine', ['company' => 'company-1']); + [$noCompany, $none] = $run('passenger'); + [$missing, $missed] = $run('passenger', ['company' => 'company_missing']); + [$made, $madeCommand] = $run('passenger', ['company' => 'company_one']); + [$again, $againCmd] = $run('passenger', ['company' => 'company-1']); + [$named, $namedCmd] = $run('passenger', ['company' => 'company-1', 'name' => ' Airport Transfers ']); + [$transport, $plainly] = $run('transport', ['company' => 'company-1']); + + $system = $connection->table('order_configs')->where('namespace', 'system:order-config:passenger')->get(); + $airport = $connection->table('order_configs')->where('key', 'airport-transfers')->first(); + $fields = $connection->table('custom_fields')->orderBy('id')->get(); + $plain = $connection->table('order_configs')->where('key', 'transport')->value('uuid'); + + expect([$listed, $bare, $unknown, $noCompany, $missing, $made, $again, $named, $transport])->toBe([0, 0, 1, 1, 1, 0, 0, 0, 0]) + ->and($list->tables[0][0])->toBe(['Key', 'Name', 'Description']) + ->and(array_column($list->tables[0][1], 'key'))->toBe(['transport', 'passenger']) + ->and($bareList->tables)->toHaveCount(1) + ->and($nope->lines[0])->toBe('No order config template named limousine. Run with --list to see them.') + ->and($none->lines[0])->toBe('Give the company with --company.') + ->and($missed->lines[0])->toBe('No company found for company_missing.') + ->and($madeCommand->lines[0])->toStartWith('Created order config Passenger')->toEndWith('for Acme Cabs.') + ->and($againCmd->lines[0])->toStartWith('Found order config Passenger') + ->and($namedCmd->lines[0])->toStartWith('Created order config Airport Transfers') + ->and($system)->toHaveCount(1) + ->and($system[0]->key)->toBe('passenger') + ->and(json_decode($system[0]->policies, true)['dispatch']['adhoc']['strategy'])->toBe('sequential') + ->and(json_decode($system[0]->triggers, true))->toHaveCount(4) + ->and($airport->namespace)->toBe('acme-cabs:order-config:airport-transfers') + ->and((int) $airport->core_service)->toBe(0) + ->and(json_decode($airport->policies, true))->toBe(json_decode($system[0]->policies, true)) + // The passenger template's custom field is made with each new config, and only then. + ->and($fields->pluck('name')->all())->toBe(['passengers', 'passengers']) + ->and($fields->pluck('subject_uuid')->all())->toBe([$system[0]->uuid, $airport->uuid]) + ->and($fields->pluck('company_uuid')->unique()->all())->toBe(['company-1']) + ->and($plain)->not->toBeNull() + ->and($connection->table('custom_fields')->where('subject_uuid', $plain)->count())->toBe(0); +}); + +test('a dispatched adhoc order is offered by its strategy, and a busy driver is offered it while the matching policy is off', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgOrder($connection, ['tracking_number_uuid' => 'tn-1']); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'TRK1', 'owner_uuid' => 'order-1']); + $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); + $connection->table('drivers')->where('uuid', 'amara')->update(['current_job_uuid' => 'job-live']); + + (new Fleetbase\FleetOps\Listeners\HandleOrderDispatched())->handle(new Fleetbase\FleetOps\Events\OrderDispatched(adhocCfgFresh())); + + expect(adhocCfgStatuses($connection))->toBe([['amara', 'pending']]) + ->and(AdhocCfgRecorder::$notified)->toBe([['amara', OrderPing::class]]); +}); + +test('a dispatched adhoc order skips a busy driver when its config excludes busy drivers', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgPolicies($connection, ['dispatch' => ['matching' => ['exclude_busy_drivers' => true]]]); + adhocCfgOrder($connection, ['tracking_number_uuid' => 'tn-1']); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'TRK1', 'owner_uuid' => 'order-1']); + $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); + $connection->table('drivers')->where('uuid', 'amara')->update(['current_job_uuid' => 'job-live']); + + (new Fleetbase\FleetOps\Listeners\HandleOrderDispatched())->handle(new Fleetbase\FleetOps\Events\OrderDispatched(adhocCfgFresh())); + + expect(adhocCfgStatuses($connection))->toBe([['chen', 'pending']]) + ->and(AdhocCfgRecorder::$notified)->toBe([['chen', OrderPing::class]]); +}); + +test('the scheduled adhoc command asks each order\'s strategy', function () { + $connection = adhocCfgBoot(); + $lookup = new ReflectionMethod(Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class, 'strategyFor'); + $command = new Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders(); + + expect($lookup->invoke($command, adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast'])))->toBeInstanceOf(BroadcastStrategy::class) + ->and($lookup->invoke($command, adhocCfgOrder($connection, ['uuid' => 'o-2'])))->toBeInstanceOf(SequentialStrategy::class); +}); + +test('quotes carry each service type\'s seating capacity and how soon its nearest free driver could arrive', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $connection->table('vehicles')->where('uuid', 'car-economy')->update(['seating_capacity' => 4]); + $connection->table('vehicles')->insert(['uuid' => 'car-economy-2', 'company_uuid' => 'company-1', 'type' => 'economy', 'seating_capacity' => 5]); + + $controller = new class extends Fleetbase\FleetOps\Http\Controllers\Api\v1\ServiceQuoteController { + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + + public function from(?Point $point): void + { + $this->availabilityFrom = $point; + } + }; + $quote = function (string $class) { + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['service_type' => $class], true); + $quote = new Fleetbase\FleetOps\Models\ServiceQuote(); + $quote->setRawAttributes(['company_uuid' => 'company-1'], true); + $quote->setRelation('serviceRate', $rate); + + return $quote; + }; + + $economy = $quote('economy'); + $limo = $quote('limo'); + $controller->from(new Point(1.2841, 103.8511)); + $controller->helper('serviceQuoteResourceCollection', [$economy, $limo]); + + $asked = Illuminate\Http\Request::create('/', 'GET', ['availability' => 1]); + $notAsked = Illuminate\Http\Request::create('/', 'GET'); + + expect($economy->availability)->toBe(['seating_capacity' => 5, 'pickup_eta' => 138]) + ->and($limo->availability)->toBe(['seating_capacity' => null, 'pickup_eta' => null]) + ->and($controller->helper('availabilityPoint', $asked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeInstanceOf(Point::class) + ->and($controller->helper('availabilityPoint', $asked, 'place_pickup'))->toBeNull() + ->and($controller->helper('availabilityPoint', $notAsked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeNull(); + + // Without a pickup, quotes are returned as they are. + $plain = $quote('economy'); + $controller->from(null); + $controller->helper('serviceQuoteResourceCollection', [$plain]); + expect($plain->availability)->toBeNull(); +}); + +/** A completed order by customer Sam with driver Chen, from Raffles Place to Bugis. */ +function adhocCfgSeedOrder(SQLiteConnection $connection, array $order = []): AdhocCfgOrder +{ + adhocCfgSeedDrivers($connection); + $connection->table('users')->insert([ + ['uuid' => 'user-sam', 'public_id' => 'user_sam', 'company_uuid' => 'company-1', 'name' => 'Sam Lee', 'type' => 'customer', 'email' => 'sam@customer.test', 'phone' => '+15550190301'], + ['uuid' => 'user-chen', 'public_id' => 'user_chen', 'company_uuid' => 'company-1', 'name' => 'Chen Test', 'type' => 'driver', 'email' => 'chen@cabs.test', 'phone' => '+15550190203'], + ]); + $connection->table('drivers')->where('uuid', 'chen')->update(['user_uuid' => 'user-chen']); + $connection->table('contacts')->insert(['uuid' => 'contact-sam', 'public_id' => 'contact_sam', 'company_uuid' => 'company-1', 'user_uuid' => 'user-sam', 'name' => 'Sam Lee', 'email' => 'sam@customer.test', 'phone' => '+15550190301', 'type' => 'customer']); + $connection->table('places')->insert(['uuid' => 'place-dropoff', 'company_uuid' => 'company-1', 'name' => 'Bugis', 'location' => adhocCfgWkb(103.8452, 1.3005)]); + $connection->table('payloads')->where('uuid', 'payload-1')->update(['dropoff_uuid' => 'place-dropoff']); + $connection->table('service_rates')->insert(['uuid' => 'rate-economy', 'company_uuid' => 'company-1', 'service_name' => 'Economy', 'service_type' => 'economy', 'base_fee' => 300, 'rate_calculation_method' => 'algo', 'algorithm' => 'max(200, {distance_km} * 120 + {time_min} * 20)', 'currency' => 'USD']); + $connection->table('service_quotes')->insert(['uuid' => 'quote-booked', 'company_uuid' => 'company-1', 'service_rate_uuid' => 'rate-economy', 'amount' => 533, 'currency' => 'USD']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'TRK1', 'owner_uuid' => 'order-1']); + $connection->table('purchase_rates')->insert(['uuid' => 'purchase-booked', 'company_uuid' => 'company-1', 'service_quote_uuid' => 'quote-booked', 'payload_uuid' => 'payload-1', 'status' => 'created']); + + return adhocCfgOrder($connection, array_merge([ + 'status' => 'completed', + 'started' => 1, + 'started_at' => '2026-11-06 09:00:00', + 'driver_assigned_uuid' => 'chen', + 'customer_uuid' => 'contact-sam', + 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact', + 'purchase_rate_uuid' => 'purchase-booked', + 'tracking_number_uuid' => 'tn-1', + ], $order)); +} + +test('the order chat opens once a driver is assigned, with just the customer and driver in it, and closes', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); + + expect(OrderChat::open($order))->toBeNull() + ->and(OrderChat::find($order))->toBeNull() + ->and(OrderChat::close($order))->toBeFalse(); + + $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); + $order = adhocCfgFresh(); + $channel = OrderChat::open($order); + $again = OrderChat::open(adhocCfgFresh()); + + expect($channel->meta)->toBe(['order_public_id' => 'order_one', 'kind' => 'group']) + ->and($again->uuid)->toBe($channel->uuid) + ->and(OrderChat::find(adhocCfgFresh())->uuid)->toBe($channel->uuid) + ->and($connection->table('chat_channels')->count())->toBe(1) + ->and($connection->table('chat_participants')->orderBy('id')->pluck('user_uuid')->all())->toBe(['user-sam', 'user-chen']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('chat_channel_uuid'))->toBe($channel->uuid); + + $sent = OrderChat::send($channel, 'user-sam', 'By the lobby'); + $chen = $connection->table('chat_participants')->where('user_uuid', 'user-chen')->value('uuid'); + $connection->table('chat_messages')->insert(['uuid' => 'm-2', 'company_uuid' => 'company-1', 'chat_channel_uuid' => $channel->uuid, 'sender_uuid' => $chen, 'content' => 'Two minutes', 'created_at' => now()->addMinute()]); + + $messages = OrderChat::messages($channel, 'user-sam'); + expect($messages->map(fn ($message) => [$message['from'], $message['text']])->all())->toBe([['customer', 'By the lobby'], ['driver', 'Two minutes']]) + ->and($messages[0]['id'])->toBe($sent->public_id ?? $sent->uuid) + ->and(OrderChat::isClosed(adhocCfgFresh()))->toBeFalse(); + + // A finished order's chat is closed by its config's terminal activities, and closing it marks the channel. + $connection->table('orders')->update(['status' => 'no_show']); + expect(OrderChat::isClosed(adhocCfgFresh()))->toBeTrue(); + $connection->table('orders')->update(['status' => 'started']); + expect(OrderChat::close(adhocCfgFresh()))->toBeTrue() + ->and(OrderChat::isClosed(adhocCfgFresh()))->toBeTrue() + ->and(json_decode($connection->table('chat_channels')->value('meta'), true))->toHaveKey('closed_at'); +}); + +test('a customer rates their driver once, and the driver keeps an average', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + $connection->table('driver_ratings')->insert(['uuid' => 'r-old', 'order_uuid' => 'order-old', 'driver_uuid' => 'chen', 'stars' => 4]); + + $first = DriverRatings::rate($order, 9, ' Great '); + $second = DriverRatings::rate(adhocCfgFresh(), 1); + $driver = adhocCfgDriver('chen'); + $rating = Fleetbase\FleetOps\Models\DriverRating::where('order_uuid', 'order-1')->first(); + + expect($first)->toBeTrue() + ->and($second)->toBeFalse() + ->and([$rating->stars, $rating->comment, $rating->customer_uuid])->toBe([5, 'Great', 'contact-sam']) + ->and($rating->order->uuid)->toBe('order-1') + ->and($rating->driver->uuid)->toBe('chen') + ->and($order->driverRating->stars)->toBe(5) + ->and([$driver->rating_average, $driver->rating_count])->toBe([4.5, 2]); + + // A driver whose ratings were all removed has no average. + $connection->table('driver_ratings')->update(['deleted_at' => now()]); + DriverRatings::refresh('chen'); + expect([adhocCfgDriver('chen')->rating_average, adhocCfgDriver('chen')->rating_count])->toBe([null, 0]); +}); + +test('two ratings racing for one order keep the first', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + // The other request's rating lands between the check and the insert; the unique index refuses this one. + $connection->statement("CREATE TRIGGER rating_race BEFORE INSERT ON driver_ratings BEGIN SELECT RAISE(ABORT, 'UNIQUE constraint failed: driver_ratings.order_uuid'); END"); + + expect(DriverRatings::rate($order, 5))->toBeFalse() + ->and(adhocCfgDriver('chen')->rating_count)->toBeNull(); +}); + +test('a share link opens only its customer\'s view of its order, until it expires', function () { + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + $order = new Order(); + $order->setRawAttributes(['uuid' => 'order-1', 'company_uuid' => 'company-1'], true); + $sam = new Fleetbase\FleetOps\Models\Contact(); + $sam->setRawAttributes(['uuid' => 'contact-sam'], true); + $other = new Fleetbase\FleetOps\Models\Contact(); + $other->setRawAttributes(['uuid' => 'contact-other'], true); + + $scope = Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $sam); + $token = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam'); + $expired = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam', Carbon::now()->subMinute()); + $valid = fn ($token, $scope) => Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::valid($token, $scope); + + expect($valid($token, $scope))->toBeTrue() + ->and($valid($token, Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $other)))->toBeFalse() + ->and($valid($expired, $scope))->toBeFalse() + ->and($valid(substr($token, 0, -1) . (str_ends_with($token, '0') ? '1' : '0'), $scope))->toBeFalse() + ->and($valid('not-a-token', $scope))->toBeFalse() + ->and($valid(['array'], $scope))->toBeFalse() + ->and($valid($token, null))->toBeFalse(); +}); + +test('an order update push carries its title, message and type to the device channels', function () { + $order = new Order(); + $order->setRawAttributes(['public_id' => 'order_one'], true); + + $update = new OrderUpdate($order, 'Your driver has arrived', 'Chen is waiting.', 'order_arrived'); + $default = new OrderUpdate($order, 'Title', 'Message'); + + expect([$update->title, $update->message])->toBe(['Your driver has arrived', 'Chen is waiting.']) + ->and($update->data)->toBe(['id' => 'order_one', 'type' => 'order_arrived']) + ->and($default->data)->toBe(['id' => 'order_one', 'type' => 'order_update']) + ->and($update->via(null))->toBe([NotificationChannels\Fcm\FcmChannel::class, NotificationChannels\Apn\ApnChannel::class]); + + // Building each channel's message hands the push to core's PushNotification, which needs the + // FCM and APN credentials this harness doesn't configure. + expect(fn () => $update->toFcm(null))->toThrow(TypeError::class) + ->and(fn () => $update->toApn(null))->toThrow(Error::class); +}); + +test('the notify actions push to the order\'s customer and driver, with placeholders filled in', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'arrived']); + $context = ['event' => 'order.activity', 'activity' => ['code' => 'arrived', 'status' => 'Driver has arrived', 'details' => 'The driver is waiting at the pickup.']]; + + (new NotifyCustomer())->handle($order, ['title' => '{driver.first_name} is here', 'message' => 'Order {order.id} ({order.tracking_number}) for {customer.name}: {order.status}. {nope}'], $context); + (new NotifyCustomer())->handle($order, [], $context); + (new NotifyCustomer())->handle($order, [], ['event' => 'order.completed']); + (new NotifyDriver())->handle($order, ['title' => 'Customer {customer.name} is waiting'], ['event' => OrderConfigTriggers::DRIVER_APPROACHING]); + + $orphan = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'customer_uuid' => null, 'driver_assigned_uuid' => null]); + (new NotifyCustomer())->handle($orphan, ['title' => 'Nobody hears this'], $context); + (new NotifyDriver())->handle($orphan, ['title' => 'Nobody hears this'], $context); + + $sent = AdhocCfgRecorder::$sent; + expect(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class], ['contact-sam', OrderUpdate::class], ['chen', OrderUpdate::class]]) + ->and([$sent[0]->title, $sent[0]->message, $sent[0]->data['type']])->toBe(['Chen is here', 'Order order_one (TRK1) for Sam Lee: arrived.', 'order_arrived']) + // Without a title or message of its own, the activity's status and details are used. + ->and([$sent[1]->title, $sent[1]->message])->toBe(['Driver has arrived', 'The driver is waiting at the pickup.']) + ->and([$sent[2]->title, $sent[2]->message, $sent[2]->data['type']])->toBe(['Customer Sam Lee is waiting', '', 'order_driver_approaching']) + ->and(NotifyCustomer::eventType([]))->toBe('order_update'); +}); + +test('reaching an activity runs its actions, and completing or canceling an order fires the config\'s triggers', function () { + $connection = adhocCfgBoot(); + $passenger = OrderConfigTemplates::attributes('passenger'); + adhocCfgTriggers($connection, $passenger['triggers']); + $order = adhocCfgSeedOrder($connection, ['status' => 'started']); + $observer = new Fleetbase\FleetOps\Observers\OrderObserver(); + + $order->status = 'arrived'; + $order->save(); + $observer->updated($order); + + expect(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class]]) + ->and([AdhocCfgRecorder::$sent[0]->title, AdhocCfgRecorder::$sent[0]->message, AdhocCfgRecorder::$sent[0]->data['type']])->toBe(['Your driver has arrived', 'Chen is waiting at the pickup point.', 'order_arrived']); + + // Nothing runs when the status didn't change. + $observer->updated(adhocCfgFresh()); + expect(AdhocCfgRecorder::$notified)->toHaveCount(1); + + // Canceling fires order.canceled: the customer is told, unless nobody was found for the order. + $order->status = 'canceled'; + $order->save(); + $observer->updated($order); + expect(AdhocCfgRecorder::$sent)->toHaveCount(2) + ->and(AdhocCfgRecorder::$sent[1]->title)->toBe('Your trip was canceled') + ->and(AdhocCfgRecorder::$sent[1]->data['type'])->toBe('order_order_canceled'); + + $quiet = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'status' => 'dispatched', 'customer_uuid' => 'contact-sam', 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact', 'meta' => json_encode(['dispatch_outcome' => 'no_driver_found'])]); + $quiet->status = 'canceled'; + $quiet->save(); + $observer->updated($quiet); + expect(AdhocCfgRecorder::$sent)->toHaveCount(2); + + // An order without a config of its own runs no triggers. + $plain = adhocCfgOrder($connection, ['uuid' => 'order-3', 'public_id' => 'order_three', 'status' => 'started', 'order_config_uuid' => null, 'customer_uuid' => 'contact-sam', 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact']); + $plain->status = 'arrived'; + $plain->save(); + $observer->updated($plain); + + // A push that fails is logged and doesn't break the update. + AdhocCfgRecorder::$notified = ['throw']; + $connection->table('orders')->where('uuid', 'order-1')->update(['status' => 'arrived']); + $order = adhocCfgFresh(); + $order->status = 'in_progress'; + $order->save(); + $observer->updated($order); + + expect(AdhocCfgRecorder::$sent)->toHaveCount(2) + ->and(app('log')->warnings)->toContain('An order config action failed'); +}); + +test('the customer is told once when the driver is about to reach the pickup, and only while the trigger\'s conditions pass', function () { + $connection = adhocCfgBoot(); + $passenger = OrderConfigTemplates::attributes('passenger'); + adhocCfgTriggers($connection, [ + ...$passenger['triggers'], + ['event' => OrderConfigTriggers::DRIVER_APPROACHING, 'options' => ['target' => 'dropoff', 'distance' => 300], 'action' => 'set_meta', 'params' => ['key' => 'near_dropoff', 'value' => 'yes']], + ]); + adhocCfgSeedOrder($connection, ['status' => 'arrived', 'driver_assigned_uuid' => 'ben']); + $connection->table('drivers')->where('uuid', 'far')->update(['location' => adhocCfgWkb(103.8452, 1.3010)]); + $connection->table('users')->insert(['uuid' => 'user-ben', 'company_uuid' => 'company-1', 'name' => 'Ben Tan', 'type' => 'driver']); + $connection->table('drivers')->where('uuid', 'ben')->update(['user_uuid' => 'user-ben']); + $near = adhocCfgDriver('ben'); + $far = adhocCfgDriver('chen'); + $nowhere = new Driver(); + + // Arrived already: the pickup trigger's `when` (status is started) doesn't pass, and isn't used up. + $arrived = adhocCfgFresh(); + expect(OrderConfigTriggers::driverMoved($near, null))->toBe(0) + ->and(OrderConfigTriggers::driverMoved($near, $arrived))->toBe(0); + + $connection->table('orders')->update(['status' => 'started']); + $started = adhocCfgFresh(); + expect(OrderConfigTriggers::driverMoved($far, $started))->toBe(0) + ->and(OrderConfigTriggers::driverMoved($nowhere, $started))->toBe(0) + ->and(OrderConfigTriggers::driverMoved($near, $started))->toBe(1) + ->and(OrderConfigTriggers::driverMoved($near, adhocCfgFresh()))->toBe(0) + ->and(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class]]) + ->and([AdhocCfgRecorder::$sent[0]->title, AdhocCfgRecorder::$sent[0]->message, AdhocCfgRecorder::$sent[0]->data['type']])->toBe(['Your driver is almost there', 'Ben is about a minute away.', 'order_driver_approaching']); + + // Each target is its own once: coming close to the drop-off fires that trigger, once. + $atDropoff = adhocCfgDriver('far'); + expect(OrderConfigTriggers::driverMoved($atDropoff, adhocCfgFresh()))->toBe(1) + ->and(OrderConfigTriggers::driverMoved($atDropoff, adhocCfgFresh()))->toBe(0) + ->and(adhocCfgFresh()->getMeta('near_dropoff'))->toBe('yes'); + + // An order without a config of its own has no triggers. + $plain = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'status' => 'started', 'order_config_uuid' => null]); + expect(OrderConfigTriggers::driverMoved($near, $plain))->toBe(0); +}); + +test('the queued action job reads the order again and runs a registered action', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgOrder($connection); + + $ran = (new RunOrderConfigAction($order, 'set_meta', ['key' => 'flag', 'value' => 'on']))->handle(); + $unknown = (new RunOrderConfigAction($order, 'send_invoice'))->handle(); + $connection->table('orders')->delete(); + $gone = (new RunOrderConfigAction($order, 'set_meta', ['key' => 'flag', 'value' => 'off']))->handle(); + + expect($ran)->toBeTrue() + ->and($unknown)->toBeFalse() + ->and($gone)->toBeFalse() + ->and((new RunOrderConfigAction($order, 'set_meta'))->orderUuid)->toBe('order-1'); +}); + +test('the cancel, open chat and set meta actions act on the order, and skip what they cannot do', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + + // A finished order, by its config's terminal activities, is not canceled again. + $connection->table('orders')->update(['status' => 'no_show']); + (new CancelOrder())->handle(adhocCfgFresh(), ['reason' => 'Too late']); + $connection->table('orders')->update(['status' => 'started']); + (new CancelOrder())->handle(adhocCfgFresh(), ['reason' => 'Rider asked']); + (new CancelOrder())->handle(adhocCfgFresh(), ['reason' => 42]); + (new CancelOrder())->handle(adhocCfgFresh()); + + expect(AdhocCfgOrder::$canceled)->toBe([['order-1', 'Rider asked'], ['order-1', '42'], ['order-1', null]]); + + (new OpenChat())->handle(adhocCfgFresh()); + $channel = $connection->table('chat_channels')->first(); + expect($channel)->not->toBeNull() + ->and($connection->table('orders')->where('uuid', 'order-1')->value('chat_channel_uuid'))->toBe($channel->uuid) + ->and($connection->table('chat_participants')->orderBy('id')->pluck('user_uuid')->all())->toBe(['user-sam', 'user-chen']); + + // A key that is blank or not a string writes nothing; `{now}` writes the current time. + Carbon::setTestNow('2026-11-06 09:30:00'); + (new SetMeta())->handle(adhocCfgFresh(), ['key' => ' ', 'value' => 'blank']); + (new SetMeta())->handle(adhocCfgFresh(), ['key' => 7, 'value' => 'number']); + (new SetMeta())->handle(adhocCfgFresh(), ['value' => 'missing']); + $untouched = adhocCfgFresh()->meta; + (new SetMeta())->handle(adhocCfgFresh(), ['key' => ' picked_up_at ', 'value' => '{now}']); + Carbon::setTestNow(); + + expect($untouched)->toBeEmpty() + ->and(adhocCfgFresh()->getMeta('picked_up_at'))->toBe('2026-11-06T09:30:00.000000Z'); +}); + +test('the notify driver action sends nothing when it has neither a title nor a message', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'started']); + + (new NotifyDriver())->handle($order, [], ['event' => 'order.completed']); + (new NotifyDriver())->handle($order, ['title' => '', 'message' => ''], ['event' => 'order.activity', 'activity' => ['status' => 'Started']]); + expect(AdhocCfgRecorder::$notified)->toBe([]); + + (new NotifyDriver())->handle($order, [], ['event' => 'order.activity', 'activity' => ['status' => 'Started']]); + expect(AdhocCfgRecorder::$notified)->toBe([['chen', OrderUpdate::class]]) + ->and([AdhocCfgRecorder::$sent[0]->title, AdhocCfgRecorder::$sent[0]->message])->toBe(['Started', '']); +}); + +/** The test config's custom fields, by name, label and snake-cased label, and a validator that checks them. */ +function adhocCfgCustomFields(SQLiteConnection $connection): void +{ + $subject = ['company_uuid' => 'company-1', 'subject_uuid' => 'config-adhoc', 'subject_type' => OrderConfig::class]; + $connection->table('custom_fields')->insert([ + [...$subject, 'uuid' => 'field-passengers', 'name' => 'passengers', 'label' => 'Passengers', 'type' => 'input', 'required' => 1, 'validation_rules' => json_encode(['nullable', 'integer', 'required', 5]), 'order' => '0'], + [...$subject, 'uuid' => 'field-flight', 'name' => 'cf_flight', 'label' => 'Flight Number', 'type' => null, 'required' => 0, 'validation_rules' => null, 'order' => '1'], + [...$subject, 'uuid' => 'field-notes', 'name' => 'cf_notes', 'label' => 'Pickup Notes', 'type' => 'textarea', 'required' => 0, 'validation_rules' => json_encode([]), 'order' => '2'], + [...$subject, 'uuid' => 'field-gate', 'name' => 'gate_code', 'label' => null, 'type' => 'input', 'required' => 0, 'validation_rules' => null, 'order' => '3'], + ]); + app()->instance('validator', new AdhocCfgValidator()); + Illuminate\Support\Facades\Validator::clearResolvedInstance('validator'); + AdhocCfgValidator::$made = []; +} + +test('custom field values are checked against the config\'s fields, found by name, label or snake-cased label', function () { + $connection = adhocCfgBoot(); + adhocCfgCustomFields($connection); + $connection->table('order_configs')->insert(['uuid' => 'config-bare', 'public_id' => 'order_config_bare', 'company_uuid' => 'company-1', 'name' => 'Bare', 'key' => 'bare']); + $config = OrderConfig::where('uuid', 'config-adhoc')->first(); + + $missing = OrderCustomFields::validate($config, ['flight_number' => 'SQ12', 'Pickup Notes' => 'By the lobby', 'gate_code' => '4411']); + $checked = AdhocCfgValidator::$made[0]; + $typed = OrderCustomFields::validate($config, ['passengers' => 'two']); + $fine = OrderCustomFields::validate($config, ['passengers' => 3, 'ignored' => 'x']); + + expect($missing)->toBe('The Passengers field is required.') + ->and($checked['data'])->toBe(['passengers' => null, 'cf_flight' => 'SQ12', 'cf_notes' => 'By the lobby', 'gate_code' => '4411']) + // A field's own `required` and `nullable` rules give way to its required flag; rules that aren't strings are dropped. + ->and($checked['rules'])->toBe(['passengers' => ['required', 'integer'], 'cf_flight' => ['nullable'], 'cf_notes' => ['nullable'], 'gate_code' => ['nullable']]) + ->and($checked['attributes'])->toBe(['passengers' => 'Passengers', 'cf_flight' => 'Flight Number', 'cf_notes' => 'Pickup Notes', 'gate_code' => 'gate_code']) + ->and($typed)->toBe('The Passengers field must be an integer.') + ->and($fine)->toBeNull() + // A config without fields, or a request without values, isn't checked. + ->and(OrderCustomFields::validate(OrderConfig::where('uuid', 'config-bare')->first(), ['passengers' => 2]))->toBeNull() + ->and(OrderCustomFields::validate($config, []))->toBeNull() + ->and(AdhocCfgValidator::$made)->toHaveCount(3); +}); + +test('custom field values are stored on the order for the fields its config has, typed by the field', function () { + $connection = adhocCfgBoot(); + adhocCfgCustomFields($connection); + $order = adhocCfgOrder($connection); + $stored = fn () => $connection->table('custom_field_values')->orderBy('id')->get(['custom_field_uuid', 'subject_uuid', 'value', 'value_type'])->map(fn ($row) => (array) $row)->all(); + + expect(OrderCustomFields::apply($order, ['luggage' => 2]))->toBe(0) + ->and(OrderCustomFields::apply($order, []))->toBe(0) + ->and($stored())->toBe([]) + ->and(OrderCustomFields::apply($order, ['passengers' => '2', 'flight_number' => 'SQ12', 'Pickup Notes' => 'By the lobby']))->toBe(3) + ->and($stored())->toBe([ + ['custom_field_uuid' => 'field-passengers', 'subject_uuid' => 'order-1', 'value' => '2', 'value_type' => 'input'], + ['custom_field_uuid' => 'field-flight', 'subject_uuid' => 'order-1', 'value' => 'SQ12', 'value_type' => 'text'], + ['custom_field_uuid' => 'field-notes', 'subject_uuid' => 'order-1', 'value' => 'By the lobby', 'value_type' => 'textarea'], + ]) + // Sending a field again updates its value rather than adding one. + ->and(OrderCustomFields::apply(adhocCfgFresh(), ['passengers' => '4']))->toBe(1) + ->and($connection->table('custom_field_values')->count())->toBe(3) + ->and($connection->table('custom_field_values')->where('custom_field_uuid', 'field-passengers')->value('value'))->toBe('4'); +}); + +/** Positions the driver reported: one before metering began, then 1.0 km and 1.05 km. */ +function adhocCfgSeedPositions(SQLiteConnection $connection): void +{ + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-board', 'tracking_number_uuid' => 'tn-1', 'code' => 'IN_PROGRESS', 'created_at' => '2026-11-06 09:05:00']); + $connection->table('positions')->insert([ + ['uuid' => 'p0', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8511, 1.2700), 'created_at' => '2026-11-06 09:04:00'], + ['uuid' => 'p1', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8511, 1.2841), 'created_at' => '2026-11-06 09:05:10'], + ['uuid' => 'p2', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8511, 1.2931), 'created_at' => '2026-11-06 09:09:00'], + ['uuid' => 'p3', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8452, 1.3005), 'created_at' => '2026-11-06 09:14:00'], + ]); +} + +test('a completed order is priced again from the distance its driver covered and the time since metering began', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['pricing' => ['reprice_on_completion' => true, 'metering_starts_at' => 'in_progress']]); + $order = adhocCfgSeedOrder($connection); + adhocCfgSeedPositions($connection); + + Carbon::setTestNow('2026-11-06 09:15:00'); + $quote = OrderRepricing::settle($order); + Carbon::setTestNow(); + + $purchaseUuid = $connection->table('orders')->where('uuid', 'order-1')->value('purchase_rate_uuid'); + $purchase = Fleetbase\FleetOps\Models\PurchaseRate::where('uuid', $purchaseUuid)->first(); + $repriced = data_get($purchase->meta, 'repriced'); + + // About 1.0 km plus 1.05 km over 10 minutes: base 300, then 2.05 × 120 + 10 × 20 = 746 cents. + expect($quote)->toBeInstanceOf(Fleetbase\FleetOps\Models\ServiceQuote::class) + ->and((int) $quote->amount)->toBeGreaterThan(740)->toBeLessThan(750) + ->and((int) $quote->distance)->toBeGreaterThan(2000)->toBeLessThan(2100) + ->and((int) $quote->time)->toBe(600) + ->and($quote->service_rate_uuid)->toBe('rate-economy') + ->and($purchaseUuid)->not->toBe('purchase-booked') + ->and($purchase->service_quote_uuid)->toBe($quote->uuid) + ->and($repriced['distance'])->toBe((int) $quote->distance) + ->and($repriced['time'])->toBe(600) + ->and($repriced['distance_source'])->toBe('positions') + ->and(Carbon::parse($repriced['metered_from'])->toDateTimeString())->toBe('2026-11-06 09:05:00') + ->and($repriced['previous_amount'])->toEqual(533) + ->and($connection->table('service_quote_items')->orderBy('id')->pluck('details')->all())->toBe(['Base', 'Distance and time']); + + // Priced once. + expect(OrderRepricing::settle(adhocCfgFresh()))->toBeNull(); +}); + +test('repricing waits for the pricing policy, a completed order with a rate, and a config of its own', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + + // The policy is off by default. + expect(OrderRepricing::settle($order))->toBeNull() + ->and($connection->table('service_quotes')->count())->toBe(1); + + adhocCfgPolicies($connection, ['pricing' => ['reprice_on_completion' => true]]); + expect(OrderRepricing::settle(adhocCfgOrder($connection, ['uuid' => 'o-live', 'status' => 'started', 'purchase_rate_uuid' => 'purchase-booked'])))->toBeNull() + ->and(OrderRepricing::settle(adhocCfgOrder($connection, ['uuid' => 'o-unpriced', 'status' => 'completed', 'purchase_rate_uuid' => null])))->toBeNull() + ->and(OrderRepricing::settle(adhocCfgOrder($connection, ['uuid' => 'o-plain', 'status' => 'completed', 'order_config_uuid' => null, 'purchase_rate_uuid' => 'purchase-booked'])))->toBeNull() + ->and($connection->table('service_quotes')->count())->toBe(1); +}); + +test('without positions the distance is the straight line, and metering starts at the activity, else when the order started', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + $order->started_at = null; + + [$metres, $source] = OrderRepricing::distance($order, Carbon::parse('2026-11-06 09:00:00')); + $connection->table('payloads')->update(['dropoff_uuid' => null]); + [$none, $nothing] = OrderRepricing::distance(adhocCfgFresh(), Carbon::now()); + + $fromStart = OrderRepricing::meteringStartedAt(adhocCfgFresh(), 'in_progress'); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-board', 'tracking_number_uuid' => 'tn-1', 'code' => 'IN_PROGRESS', 'created_at' => '2026-11-06 09:05:00']); + $fromActivity = OrderRepricing::meteringStartedAt(adhocCfgFresh(), 'in_progress'); + $noActivity = OrderRepricing::meteringStartedAt(adhocCfgFresh()); + + $label = new ReflectionMethod(OrderRepricing::class, 'label'); + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['rate_calculation_method' => 'per_meter'], true); + $other = new Fleetbase\FleetOps\Models\ServiceRate(); + $other->setRawAttributes(['rate_calculation_method' => 'fixed_meter'], true); + + expect($source)->toBe('straight_line') + ->and($metres)->toBeGreaterThan(1900)->toBeLessThan(2000) + ->and([$none, $nothing])->toBe([0, 'none']) + ->and($fromStart->toDateTimeString())->toBe('2026-11-06 09:00:00') + ->and($fromActivity->toDateTimeString())->toBe('2026-11-06 09:05:00') + ->and($noActivity->toDateTimeString())->toBe('2026-11-06 09:00:00') + ->and([$label->invoke(null, $rate, 'Base Fee', 0), $label->invoke(null, $rate, 'Service Fee', 1), $label->invoke(null, $other, 'Peak', 2), $label->invoke(null, $other, '', 3)])->toBe(['Base', 'Distance', 'Peak', 'Charge']); +}); + +test('completing an order through the observer prices it again before its completed actions run', function () { + $connection = adhocCfgBoot(); + $passenger = OrderConfigTemplates::attributes('passenger'); + adhocCfgPolicies($connection, $passenger['policies']); + $order = adhocCfgSeedOrder($connection, ['status' => 'in_progress']); + + $order->status = 'completed'; + $order->save(); + (new Fleetbase\FleetOps\Observers\OrderObserver())->updated($order); + + $purchase = Fleetbase\FleetOps\Models\PurchaseRate::where('uuid', $connection->table('orders')->value('purchase_rate_uuid'))->first(); + + expect($purchase->uuid)->not->toBe('purchase-booked') + ->and(data_get($purchase->meta, 'repriced.distance_source'))->toBe('straight_line') + ->and(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class]]) + ->and(AdhocCfgRecorder::$sent[0]->title)->toBe('You have arrived'); +}); + +class AdhocCfgCustomerController extends Fleetbase\FleetOps\Http\Controllers\Api\v1\CustomerController +{ + public ?string $customerUuid = 'contact-sam'; + public array $revoked = []; + public array $settings = []; + + protected function currentCustomer(): ?Fleetbase\FleetOps\Models\Contact + { + return $this->customerUuid ? Fleetbase\FleetOps\Models\Contact::where('uuid', $this->customerUuid)->first() : null; + } + + protected function findOrderOrFail(string $id): Order + { + return AdhocCfgOrder::where('public_id', $id)->firstOrFail(); + } + + protected function deleteUserTokens(Fleetbase\Models\User $user): void + { + $this->revoked[] = $user->uuid; + } + + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + + protected function trackingPageUrl(string $number, ?string $companyUuid): string + { + return 'https://console.test/~/track/' . $number . ($companyUuid === 'company-1' ? '' : '?org=other'); + } + + protected function lookupCompanySetting(string $key, mixed $default = null): mixed + { + return $this->settings[$key] ?? $default; + } + + protected function resolveOrderConfig(Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest $request, string $companyUuid): ?OrderConfig + { + return OrderConfig::where('uuid', 'config-adhoc')->first(); + } + + protected function resolveServiceQuote(Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest $request): mixed + { + return Fleetbase\FleetOps\Models\ServiceQuote::where('uuid', 'quote-booked')->first(); + } +} + +function adhocCfgJson($response): array +{ + return $response->getData(true); +} + +test('chat, rating and sharing are refused with 403 while the config\'s customer interactions are off', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + $controller = new AdhocCfgCustomerController(); + $post = fn (array $input) => Illuminate\Http\Request::create('/', 'POST', $input); + + expect($controller->orderMessages('order_one')->getStatusCode())->toBe(403) + ->and($controller->sendOrderMessage('order_one', $post(['text' => 'Hi']))->getStatusCode())->toBe(403) + ->and($controller->rateOrder('order_one', $post(['stars' => 5]))->getStatusCode())->toBe(403) + ->and($controller->shareOrder('order_one')->getStatusCode())->toBe(403) + ->and(adhocCfgJson($controller->shareOrder('order_one'))['error'])->toBe('Sharing tracking is not available for this order.') + // Someone else's order, or none, is not found before the policy is read. + ->and($controller->orderMessages('order_missing')->getStatusCode())->toBe(404); + + $controller->customerUuid = null; + expect($controller->orderMessages('order_one')->getStatusCode())->toBe(404); + + // Each interaction is its own setting. + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['rating' => true]]]); + $controller = new AdhocCfgCustomerController(); + expect($controller->orderMessages('order_one')->getStatusCode())->toBe(403) + ->and($controller->rateOrder('order_one', $post(['stars' => 5]))->getStatusCode())->toBe(422); +}); + +test('the customer chats with the driver of their own order only, as themselves', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['chat' => true]]]); + adhocCfgSeedOrder($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); + $controller = new AdhocCfgCustomerController(); + $send = fn (string $text, string $id = 'order_one') => $controller->sendOrderMessage($id, Illuminate\Http\Request::create('/', 'POST', ['text' => $text])); + + expect($controller->orderMessages('order_missing')->getStatusCode())->toBe(404) + ->and(adhocCfgJson($controller->orderMessages('order_one')))->toBe([]) + ->and($send('Hi', 'order_missing')->getStatusCode())->toBe(404) + ->and($send(' ')->getStatusCode())->toBe(422) + ->and($send(str_repeat('x', 2001))->getStatusCode())->toBe(422) + ->and(adhocCfgJson($send('Hi'))['error'])->toBe('You can message the driver once one is assigned.'); + + $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); + $sent = $send('By the lobby'); + + expect($sent->getStatusCode())->toBe(201) + ->and(adhocCfgJson($sent))->toMatchArray(['from' => 'customer', 'text' => 'By the lobby']) + ->and(array_column(adhocCfgJson($controller->orderMessages('order_one')), 'text'))->toBe(['By the lobby']); + + $connection->table('orders')->update(['status' => 'completed']); + expect(adhocCfgJson($send('Thanks'))['error'])->toBe('This conversation has ended.'); +}); + +test('the customer rates a completed order once, from 1 to 5 stars', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['rating' => true]]]); + adhocCfgSeedOrder($connection, ['status' => 'in_progress']); + $controller = new AdhocCfgCustomerController(); + $rate = fn ($stars, string $id = 'order_one') => $controller->rateOrder($id, Illuminate\Http\Request::create('/', 'POST', ['stars' => $stars, 'comment' => 'Kind'])); + + expect($rate(5, 'order_missing')->getStatusCode())->toBe(404) + ->and($rate(0)->getStatusCode())->toBe(422) + ->and($rate(2.5)->getStatusCode())->toBe(422) + ->and($rate('lots')->getStatusCode())->toBe(422) + ->and(adhocCfgJson($rate(5))['error'])->toBe('Only a completed order can be rated.'); + + $connection->table('orders')->update(['status' => 'completed']); + expect(adhocCfgJson($rate(4)))->toBe(['status' => 'rated']) + ->and($rate(1)->getStatusCode())->toBe(409); +}); + +test('the customer shares an order in progress, but not one that has ended or has no tracking number', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['share_tracking' => true]]]); + adhocCfgSeedOrder($connection, ['status' => 'started']); + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + $controller = new AdhocCfgCustomerController(); + + $shared = adhocCfgJson($controller->shareOrder('order_one')); + expect($controller->shareOrder('order_missing')->getStatusCode())->toBe(404) + ->and($shared['url'])->toContain('/~/track/TRK1') + ->and($shared['url'])->toMatch('/[?&]share=\d+\.[a-f0-9]{64}$/') + ->and($shared)->toHaveKey('expires_at'); + + $connection->table('orders')->update(['status' => 'no_show']); + expect($controller->shareOrder('order_one')->getStatusCode())->toBe(422); + + $connection->table('orders')->update(['status' => 'started', 'tracking_number_uuid' => null]); + expect($controller->shareOrder('order_one')->getStatusCode())->toBe(422); +}); + +test('customers may cancel until the config\'s cancellation policy says, and order configs the company enabled for them', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + $controller = new AdhocCfgCustomerController(); + $config = fn () => OrderConfig::where('uuid', 'config-adhoc')->first(); + $mayCancel = fn () => $controller->helper('customerMayCancel', adhocCfgFresh()); + + // By default customers cancel any time before the order finishes. + $before = $mayCancel(); + $connection->table('orders')->update(['status' => 'in_progress']); + $inProgress = $mayCancel(); + $connection->table('orders')->update(['status' => 'no_show']); + $ended = $mayCancel(); + + adhocCfgPolicies($connection, ['customer' => ['cancellation' => ['allowed_until' => 'in_progress']]]); + $connection->table('orders')->update(['status' => 'arrived']); + $arrived = $mayCancel(); + $connection->table('orders')->update(['status' => 'in_progress']); + $limited = $mayCancel(); + + adhocCfgPolicies($connection, ['customer' => ['cancellation' => ['enabled' => false]]]); + $connection->table('orders')->update(['status' => 'started']); + $disabled = $mayCancel(); + + expect([$before, $inProgress, $ended, $arrived, $limited, $disabled])->toBe([true, true, false, true, false, false]) + ->and($controller->helper('customersMayOrder', $config()))->toBeTrue(); + + $controller->settings = ['fleet-ops.customer-enabled-order-configs' => ['config-other']]; + $refused = $controller->helper('customersMayOrder', $config()); + $controller->settings = ['fleet-ops.customer-enabled-order-configs' => ['order_config_passenger']]; + expect($refused)->toBeFalse() + ->and($controller->helper('customersMayOrder', $config()))->toBeTrue(); +}); + +test('a customer deletes their account, but not while an order is in progress by its config', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + $connection->table('places')->insert(['uuid' => 'place-home', 'company_uuid' => 'company-1', 'name' => 'Home', 'owner_uuid' => 'contact-sam']); + $controller = new AdhocCfgCustomerController(); + + $refused = $controller->deleteMe(); + expect($refused->getStatusCode())->toBe(422) + ->and(adhocCfgJson($refused)['error'])->toContain('You have orders in progress'); + + // The config's terminal activity (no_show) ends the order, though it isn't completed or canceled. + $connection->table('orders')->update(['status' => 'no_show']); + expect(adhocCfgJson($controller->deleteMe()))->toBe(['status' => 'deleted']) + ->and($controller->revoked)->toBe(['user-sam']) + ->and($connection->table('contacts')->where('uuid', 'contact-sam')->first())->toMatchArray(['name' => 'Deleted customer', 'email' => null, 'phone' => null]) + ->and($connection->table('contacts')->where('uuid', 'contact-sam')->value('deleted_at'))->not->toBeNull() + ->and($connection->table('places')->where('uuid', 'place-home')->value('deleted_at'))->not->toBeNull() + ->and($connection->table('users')->where('uuid', 'user-sam')->first())->toMatchArray(['name' => 'Deleted customer', 'phone' => null, 'email' => 'deleted-user-sam@deleted.invalid']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('deleted_at'))->toBeNull(); + + $controller->customerUuid = null; + expect($controller->deleteMe()->getStatusCode())->toBe(401); +}); + +test('an order that was never dispatched does not hold up deleting the account', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'created', 'dispatched' => 0]); + + expect(adhocCfgJson((new AdhocCfgCustomerController())->deleteMe()))->toBe(['status' => 'deleted']); +}); + +test('a customer with another company keeps their user when one account is deleted', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection); + $connection->table('contacts')->insert(['uuid' => 'contact-sam-2', 'company_uuid' => 'company-2', 'user_uuid' => 'user-sam', 'name' => 'Sam Lee', 'type' => 'customer']); + $nobody = new AdhocCfgCustomerController(); + $connection->table('contacts')->insert(['uuid' => 'contact-guest', 'company_uuid' => 'company-1', 'name' => 'Guest', 'type' => 'customer']); + $nobody->customerUuid = 'contact-guest'; + + (new AdhocCfgCustomerController())->deleteMe(); + $nobody->deleteMe(); + + expect($connection->table('users')->where('uuid', 'user-sam')->value('deleted_at'))->toBeNull() + ->and($connection->table('users')->where('uuid', 'user-sam')->value('name'))->toBe('Sam Lee') + ->and($nobody->revoked)->toBe([]) + ->and($connection->table('contacts')->where('uuid', 'contact-guest')->value('deleted_at'))->not->toBeNull(); +}); + +test('an unsettled order paid by a method the ordering policy names blocks the next order with 402, whatever its type', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['ordering' => ['payment_methods' => ['cash', 'card'], 'require_settlement' => ['card']]]]); + adhocCfgSeedOrder($connection, ['transaction_uuid' => 'txn-1', 'type' => 'anything']); + $connection->table('transactions')->insert(['uuid' => 'txn-1', 'company_uuid' => 'company-1', 'amount' => 746, 'currency' => 'USD', 'settlement_status' => 'pending']); + $connection->table('payloads')->update(['payment_method' => 'card']); + $controller = new AdhocCfgCustomerController(); + $sam = Fleetbase\FleetOps\Models\Contact::where('uuid', 'contact-sam')->first(); + $unsettled = fn () => $controller->helper('hasUnsettledOrder', $sam, OrderConfig::where('uuid', 'config-adhoc')->first()); + + $blocked = $unsettled(); + $response = $controller->createOrder(new Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest(['payment_method' => 'card'])); + + $connection->table('transactions')->update(['settlement_status' => 'paid']); + $paid = $unsettled(); + $connection->table('transactions')->update(['settlement_status' => 'pending', 'amount' => 0]); + $free = $unsettled(); + $connection->table('transactions')->update(['amount' => 746]); + $connection->table('payloads')->update(['payment_method' => 'cash']); + $cash = $unsettled(); + $connection->table('payloads')->update(['payment_method' => 'card']); + $connection->table('orders')->update(['status' => 'started']); + $notCompleted = $unsettled(); + $connection->table('orders')->update(['status' => 'completed']); + adhocCfgPolicies($connection, ['customer' => ['ordering' => ['require_settlement' => []]]]); + $policyOff = $unsettled(); + + expect([$blocked, $paid, $free, $cash, $notCompleted, $policyOff])->toBe([true, false, false, false, false, false]) + ->and($response->getStatusCode())->toBe(402) + ->and(adhocCfgJson($response)['error'])->toBe('Settle your previous order before placing another.'); +}); + +test('a driver listing nearby orders sees only the adhoc orders they could take', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $connection->table('orders')->insert([ + ['uuid' => 'o-held', 'public_id' => 'order_held', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-adhoc', 'adhoc_strategy' => null], + ['uuid' => 'o-other', 'public_id' => 'order_other', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-adhoc', 'adhoc_strategy' => null], + ['uuid' => 'o-lapsed', 'public_id' => 'order_lapsed', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'sequential'], + ['uuid' => 'o-open', 'public_id' => 'order_open', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], + ['uuid' => 'o-refused', 'public_id' => 'order_refused', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], + ['uuid' => 'o-default', 'public_id' => 'order_default', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => null], + ['uuid' => 'o-planned', 'public_id' => 'order_planned', 'company_uuid' => 'company-1', 'adhoc' => 0, 'order_config_uuid' => null, 'adhoc_strategy' => null], + ]); + $connection->table('orders')->insert(['uuid' => 'o-taken', 'public_id' => 'order_taken', 'company_uuid' => 'company-1', 'adhoc' => 1, 'driver_assigned_uuid' => 'chen']); + $connection->table('order_offers')->insert([ + ['uuid' => 'f1', 'order_uuid' => 'o-held', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], + ['uuid' => 'f2', 'order_uuid' => 'o-other', 'driver_uuid' => 'chen', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], + ['uuid' => 'f3', 'order_uuid' => 'o-lapsed', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2020-01-01 00:00:00'], + ['uuid' => 'f4', 'order_uuid' => 'o-refused', 'driver_uuid' => 'amara', 'status' => 'declined', 'expires_at' => null], + ]); + $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); + $listed = fn ($company) => Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::apply(Order::query()->withoutGlobalScopes(), 'amara', $company)->orderBy('id')->pluck('public_id')->all(); + + // One at a time by default: Amara sees her own open offer, the open order she didn't decline, + // planned orders, and an order someone already took. + expect($listed($company))->toBe(['order_held', 'order_open', 'order_planned', 'order_taken']); + + // With the company defaulting to everyone at once, unset orders show too; orders whose config's + // adhoc policy says one at a time still don't. + $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast']])]); + $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); + expect($listed($company))->toBe(['order_held', 'order_open', 'order_default', 'order_planned', 'order_taken']); + + // Each order carries Amara's open offer, or none. + $orders = Order::withoutGlobalScopes()->whereIn('uuid', ['o-held', 'o-open'])->orderBy('id')->get(); + Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::attach($orders, 'amara'); + expect($orders[0]->adhocOffer->uuid)->toBe('f1') + ->and($orders[1]->adhocOffer)->toBeNull() + ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present($orders[0]->adhocOffer))->toBe(['status' => 'pending', 'expires_at' => '2099-01-01T00:00:00.000000Z']) + ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present(null))->toBeNull(); +}); + +test('only a strategy that lists openly shows orders without an offer, and a driver is found by public id', function () { + adhocCfgBoot(); + adhocCfgSeedDrivers(Illuminate\Support\Facades\DB::connection()); + $helper = new ReflectionMethod(Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController::class, 'nearbyDriverUuid'); + $ask = fn ($nearby) => $helper->invoke(new Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController(), Illuminate\Http\Request::create('/', 'GET', ['nearby' => $nearby])); + + expect(AdhocDispatch::openlyListed())->toBe(['broadcast']) + ->and((new BroadcastStrategy())->listsOpenly())->toBeTrue() + ->and((new SequentialStrategy())->listsOpenly())->toBeFalse() + ->and($ask('driver_amara'))->toBe('amara') + ->and($ask('driver_rival'))->toBeNull() + ->and($ask('1.28,103.85'))->toBeNull() + ->and($ask(null))->toBeNull(); +}); + +test('drivers hear when their offer closes, and a broadcast failure is only logged', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + AdhocCfgRecorder::$events = []; + + adhocCfgSequential()->dispatch($order); + $offer = OrderOffers::pending($order); + Carbon::setTestNow(now()->addMinute()); + adhocCfgSequential()->expire($offer); + Carbon::setTestNow(); + OrderOffers::withdraw($order); + $closed = array_values(array_filter(AdhocCfgRecorder::$events, fn ($event) => $event instanceof Fleetbase\FleetOps\Events\OrderOfferClosed)); + + expect(array_map(fn ($event) => $event->data, $closed))->toBe([['id' => 'order_one', 'status' => 'expired'], ['id' => 'order_one', 'status' => 'withdrawn']]) + ->and($closed[0]->broadcastAs())->toBe('order.offer_closed') + ->and(array_map(fn ($channel) => $channel->name, $closed[0]->broadcastOn()))->toBe(['driver.driver_amara', 'driver.amara']) + ->and($closed[1]->broadcastWith())->toMatchArray(['event' => 'order.offer_closed', 'data' => ['id' => 'order_one', 'status' => 'withdrawn']]); + + AdhocCfgRecorder::$failEvents = true; + OrderOffers::announceClosed($order, ['chen'], 'withdrawn'); + AdhocCfgRecorder::$failEvents = false; + expect(app('log')->warnings)->toContain('Unable to broadcast order.offer_closed'); +}); + +test('saving an order config drops an unknown strategy from its policies and keeps its offer time in range', function () { + $connection = adhocCfgBoot(); + $config = OrderConfig::where('uuid', 'config-adhoc')->first(); + $stored = fn () => json_decode($connection->table('order_configs')->value('policies'), true); + + $config->forceFill(['policies' => ['dispatch' => ['adhoc' => ['strategy' => 'lottery', 'offer_timeout' => 900]], 'custom' => ['kept' => true]]])->save(); + expect($stored())->toBe(['dispatch' => ['adhoc' => ['strategy' => null, 'offer_timeout' => 120]], 'custom' => ['kept' => true]]); + + $config->forceFill(['policies' => ['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => null]]]])->save(); + expect($stored())->toBe(['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => null]]]) + ->and(OrderConfig::where('uuid', 'config-adhoc')->first()->policy('dispatch.adhoc.strategy'))->toBe('broadcast'); +}); + +test('strategies describe themselves for people choosing one', function () { + expect(AdhocDispatch::describe())->toContain( + ['name' => 'broadcast', 'label' => 'Everyone nearby at once', 'description' => (new BroadcastStrategy())->description()], + ['name' => 'sequential', 'label' => 'One driver at a time', 'description' => (new SequentialStrategy())->description()], + ); +}); + +test('a customer order keeps how it will be paid on its payload, and tells how dispatch ended', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'canceled', 'driver_assigned_uuid' => null]); + $connection->table('order_offers')->insert(['uuid' => 'f-x', 'order_uuid' => 'order-1', 'driver_uuid' => 'amara', 'status' => 'declined']); + + (new AdhocCfgCustomerController())->helper('setPayloadPaymentMethod', 'payload-1', 'card'); + + expect($connection->table('payloads')->where('uuid', 'payload-1')->value('payment_method'))->toBe('card') + ->and($order->dispatchOutcome())->toBe('no_driver_found') + ->and($order->chatChannel)->toBeNull(); +}); + +test('a customer order is refused with 422 for a config customers may not order, a payment method the policy doesn\'t offer, or a bad custom field', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['ordering' => ['payment_methods' => ['cash', 'card']]]]); + adhocCfgSeedOrder($connection); + adhocCfgCustomFields($connection); + $controller = new AdhocCfgCustomerController(); + $order = fn (array $input) => $controller->createOrder(new Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest($input)); + + $controller->settings = ['fleet-ops.customer-enabled-order-configs' => ['config-other']]; + $notOffered = $order(['payment_method' => 'cash']); + $controller->settings = []; + $bitcoin = $order(['payment_method' => 'bitcoin']); + $noPassengers = $order(['payment_method' => 'cash', 'custom_fields' => ['flight_number' => 'SQ12']]); + $wordy = $order(['custom_fields' => ['passengers' => 'two']]); + + expect([$notOffered->getStatusCode(), $bitcoin->getStatusCode(), $noPassengers->getStatusCode(), $wordy->getStatusCode()])->toBe([422, 422, 422, 422]) + ->and(adhocCfgJson($notOffered)['error'])->toBe('Customers cannot place this type of order.') + ->and(adhocCfgJson($bitcoin)['error'])->toBe('Choose a payment method: cash, card.') + ->and(adhocCfgJson($noPassengers)['error'])->toBe('The Passengers field is required.') + ->and(adhocCfgJson($wordy)['error'])->toBe('The Passengers field must be an integer.') + // Nothing was made for a refused order. + ->and($connection->table('orders')->count())->toBe(1) + ->and($connection->table('payloads')->count())->toBe(1); +}); + +/** A customer controller that reads the company's settings from the settings table, as it does in production. */ +class AdhocCfgStoredSettingsCustomerController extends Fleetbase\FleetOps\Http\Controllers\Api\v1\CustomerController +{ + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } +} + +test('the order configs customers may use are read from the company\'s stored settings', function () { + $connection = adhocCfgBoot(); + $connection->getSchemaBuilder()->create('settings', function ($blueprint) { + $blueprint->increments('id'); + $blueprint->string('key')->nullable(); + $blueprint->text('value')->nullable(); + $blueprint->timestamps(); + }); + $controller = new AdhocCfgStoredSettingsCustomerController(); + $config = OrderConfig::where('uuid', 'config-adhoc')->first(); + $key = 'fleet-ops.customer-enabled-order-configs'; + + $unset = [$controller->helper('lookupCompanySetting', $key, ['fallback']), $controller->helper('customersMayOrder', $config)]; + + $connection->table('settings')->insert(['key' => 'company.company-1.' . $key, 'value' => json_encode(['order_config_other'])]); + $refused = [$controller->helper('lookupCompanySetting', $key), $controller->helper('customersMayOrder', $config)]; + + $connection->table('settings')->update(['value' => json_encode(['order_config_passenger'])]); + $allowed = $controller->helper('customersMayOrder', $config); + + // Another company's setting doesn't apply. + session(['company' => 'company-2']); + $elsewhere = $controller->helper('lookupCompanySetting', $key, []); + session(['company' => 'company-1']); + + expect($unset)->toBe([['fallback'], true]) + ->and($refused)->toBe([['order_config_other'], false]) + ->and($allowed)->toBeTrue() + ->and($elsewhere)->toBe([]); +}); diff --git a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php index d886630d2..f4cd0a0c0 100644 --- a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php +++ b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php @@ -229,6 +229,7 @@ public function __call($method, $arguments) 'companies' => ['uuid', 'public_id', 'name', 'country'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'proof_uuid', 'status', 'details', 'location', 'code', 'complete', '_key'], 'directives' => ['uuid', 'public_id', 'company_uuid', 'permission_uuid', 'key', 'rules', 'subject_type'], + 'driver_ratings' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'customer_uuid', 'customer_type', 'stars', 'comment'], ]; foreach ($tables as $table => $columns) { $schema->create($table, function ($blueprint) use ($columns) { @@ -251,6 +252,21 @@ public function __call($method, $arguments) $contractDisk = new class implements Illuminate\Contracts\Filesystem\Filesystem { public array $writes = []; + public function path($path) + { + return $path; + } + + public function putFile($path, $file = null, $options = []) + { + return false; + } + + public function putFileAs($path, $file, $name = null, $options = []) + { + return false; + } + public function url($path) { return 'https://cdn.test/' . ltrim((string) $path, '/'); @@ -585,7 +601,7 @@ public function parameters() 'identity' => 'ghost@example.com', 'code' => '111111', ])); - expect($unknown->getData(true)['error'] ?? '')->toContain('Unable to verify'); + expect($unknown->getData(true)['error'] ?? '')->toBe('Invalid verification code.'); // The create-customer intent delegates into the full creation flow $connection->table('verification_codes')->insert(['uuid' => 'vc-del', 'code' => '777777', 'for' => 'fleetops_create_customer', 'meta' => json_encode(['identity' => 'delegate@example.com']), 'status' => 'active']); @@ -711,7 +727,6 @@ public function parameters() $updated = $controller->updateMe(Fleetbase\FleetOps\Http\Requests\UpdateContactRequest::create('/v1/customers/me', 'PUT', [ 'name' => 'Profile Customer Updated', - 'phone' => '+6590001234', 'photo' => 'file_meavatar1', ])); expect($connection->table('contacts')->where('uuid', '88888888-8888-4888-8888-888888888810')->value('name'))->toBe('Profile Customer Updated') @@ -855,3 +870,33 @@ protected function createFileFromBase64(string $contents, string $path): mixed $again = $controller->create(CreateCustomerRequest::create('/v1/customers', 'POST', ['code' => '101010', 'identity' => 'spend@example.com', 'name' => 'Spender', 'password' => 'secret'])); expect($again->getData(true)['error'])->toContain('Invalid verification code'); }); + +test('a signup code can be checked without using it up, and a wrong one is refused', function () { + $connection = fleetopsCustomerHelperBoot(); + $controller = new CustomerController(); + $connection->table('verification_codes')->insert(['uuid' => 'vc-check', 'code' => '246810', 'for' => 'fleetops_create_customer', 'meta' => json_encode(['identity' => 'proof@example.com'])]); + + $wrong = $controller->verifyCode(Request::create('/v1/customers/verify-code', 'POST', ['identity' => 'proof@example.com', 'code' => '000000'])); + $right = $controller->verifyCode(Request::create('/v1/customers/verify-code', 'POST', ['identity' => 'proof@example.com', 'code' => '246810'])); + $again = $controller->verifyCode(Request::create('/v1/customers/verify-code', 'POST', ['identity' => 'proof@example.com', 'code' => '246810'])); + + expect($wrong->getData(true))->toBe(['error' => 'Invalid verification code.']) + ->and($right->getData(true))->toBe(['status' => 'new_customer']) + ->and($again->getData(true))->toBe(['status' => 'new_customer']); +}); + +test('rider place search and geocoding reach the place search service', function () { + fleetopsCustomerHelperBoot(); + $controller = new CustomerController(); + $search = new ReflectionMethod(CustomerController::class, 'runPlaceSearch'); + $geocode = new ReflectionMethod(CustomerController::class, 'geocodePlaces'); + $resource = new ReflectionMethod(CustomerController::class, 'placeResource'); + $owned = new ReflectionMethod(CustomerController::class, 'customerPlaceQuery'); + $customer = new Contact(); + $customer->setRawAttributes(['uuid' => 'rider-1'], true); + + expect($search->invoke($controller, Place::where('company_uuid', 'nobody'), '', ['geo' => false]))->toHaveCount(0) + ->and($owned->invoke($controller, $customer)->getBindings())->toContain('rider-1') + ->and($geocode->invoke($controller, '', null, null))->toHaveCount(0) + ->and($resource->invoke($controller, new Place()))->toBeInstanceOf(Fleetbase\FleetOps\Http\Resources\v1\Place::class); +}); diff --git a/server/tests/Feature/Http/Api/OrderConfigControllerTest.php b/server/tests/Feature/Http/Api/OrderConfigControllerTest.php index 9fbf13956..b715f2a42 100644 --- a/server/tests/Feature/Http/Api/OrderConfigControllerTest.php +++ b/server/tests/Feature/Http/Api/OrderConfigControllerTest.php @@ -51,7 +51,16 @@ public function __call($method, $arguments) $schema = $connection->getSchemaBuilder(); $schema->create('order_configs', function ($table) { $table->increments('id'); - foreach (['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'flow', 'meta', 'entities', 'version'] as $column) { + foreach (['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'flow', 'meta', 'policies', 'triggers', 'entities', 'version'] as $column) { + $table->string($column)->nullable(); + } + $table->timestamps(); + $table->timestamp('deleted_at')->nullable(); + }); + // Order config resources carry the config's custom fields, which customer apps ask for. + $schema->create('custom_fields', function ($table) { + $table->increments('id'); + foreach (['uuid', 'public_id', 'company_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'component', 'options', 'required', 'editable', 'default_value', 'validation_rules', 'help_text', 'order'] as $column) { $table->string($column)->nullable(); } $table->timestamps(); @@ -82,8 +91,11 @@ public function __call($method, $arguments) expect($probe->callProtected('findOrderConfigOrFail', 'order_config_test'))->toBeInstanceOf(OrderConfig::class); expect(fn () => $probe->callProtected('findOrderConfigOrFail', 'missing'))->toThrow(ModelNotFoundException::class); + $connection->table('custom_fields')->insert(['uuid' => 'field-1', 'company_uuid' => 'company-1', 'subject_uuid' => '44444444-4444-4444-8444-444444444444', 'subject_type' => OrderConfig::class, 'name' => 'passengers', 'label' => 'Passengers', 'order' => 0]); $config = OrderConfig::where('key', 'transport')->first(); expect($probe->callProtected('orderConfigResource', $config))->toBeInstanceOf(OrderConfigResource::class) + ->and($config->relationLoaded('customFields'))->toBeTrue() + ->and($config->customFields->pluck('name')->all())->toBe(['passengers']) ->and($probe->callProtected('orderConfigCollection', [[$config]])) ->toBeInstanceOf(Illuminate\Http\Resources\Json\ResourceCollection::class); diff --git a/server/tests/Feature/Http/Api/OrderControllerCreateTest.php b/server/tests/Feature/Http/Api/OrderControllerCreateTest.php index 07f78f0f0..750e44da1 100644 --- a/server/tests/Feature/Http/Api/OrderControllerCreateTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerCreateTest.php @@ -123,6 +123,7 @@ public function __call($method, $arguments) 'integrated_vendors' => ['uuid', 'public_id', 'company_uuid', 'provider'], 'companies' => ['uuid', 'public_id', 'name', 'options'], 'company_users' => ['uuid', 'company_uuid', 'user_uuid', 'status'], + 'custom_fields' => ['uuid', 'public_id', 'company_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'required', 'validation_rules', 'order'], ]; foreach ($tables as $table => $columns) { $schema->create($table, function ($blueprint) use ($columns) { @@ -277,3 +278,51 @@ protected function firstOrCreateCustomerContact(array $attributes, array $values ])); expect($existing->getData(true)['error'] ?? '')->toBe('That user already exists.'); }); + +test('create refuses custom field values that fail the order config\'s fields with 422, before making the order', function () { + $connection = fleetopsApiOrderCreateBoot(); + $connection->table('payloads')->insert(['uuid' => '66666666-6666-4666-8666-666666666666', 'public_id' => 'payload_test', 'company_uuid' => 'company-1']); + $connection->table('custom_fields')->insert(['uuid' => 'field-dock', 'company_uuid' => 'company-1', 'subject_uuid' => 'config-1', 'subject_type' => Fleetbase\FleetOps\Models\OrderConfig::class, 'name' => 'dock_number', 'label' => 'Dock Number', 'required' => '1', 'order' => '0']); + $checked = []; + app()->instance('validator', new class($checked) { + public function __construct(public array &$checked) + { + } + + public function make($data = [], $rules = [], $messages = [], $attributes = []) + { + $this->checked[] = [$data, $rules, $attributes]; + $missing = array_keys(array_filter($data, fn ($value) => $value === null)); + + return new class($missing ? 'The ' . $attributes[$missing[0]] . ' field is required.' : null) { + public function __construct(public ?string $message) + { + } + + public function fails(): bool + { + return $this->message !== null; + } + + public function errors(): Illuminate\Support\MessageBag + { + return new Illuminate\Support\MessageBag($this->message ? ['dock_number' => [$this->message]] : []); + } + }; + } + }); + Illuminate\Support\Facades\Validator::clearResolvedInstance('validator'); + + $response = (new FleetOpsApiOrderCreateProbe())->create(CreateOrderRequest::create('/v1/orders', 'POST', [ + 'type' => 'transport', + 'payload' => 'payload_test', + 'custom_fields' => ['gate' => 'B'], + 'dispatch' => false, + ])); + + expect($response)->toBeInstanceOf(JsonResponse::class) + ->and($response->getStatusCode())->toBe(422) + ->and($response->getData(true))->toBe(['error' => 'The Dock Number field is required.']) + ->and($checked)->toBe([[['dock_number' => null], ['dock_number' => ['required']], ['dock_number' => 'Dock Number']]]) + ->and($connection->table('orders')->count())->toBe(0); +}); diff --git a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php index 87dc1367b..c26e8a5ea 100644 --- a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php @@ -135,7 +135,7 @@ public function __call($method, $arguments) $schema = $connection->getSchemaBuilder(); $tables = [ - 'orders' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'payload_uuid', 'driver_assigned_uuid', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'tracking_number_uuid', 'status', 'pod_required', 'dispatched', 'scheduled_at', 'type'], + 'orders' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'order_config_uuid', 'adhoc', 'adhoc_strategy', 'payload_uuid', 'driver_assigned_uuid', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'tracking_number_uuid', 'status', 'pod_required', 'dispatched', 'scheduled_at', 'type'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'return_uuid', 'current_waypoint_uuid', 'type'], 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'street1', 'city', 'country', 'location', 'meta'], 'waypoints' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'place_uuid'], @@ -146,6 +146,8 @@ public function __call($method, $arguments) 'vendors' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'name'], 'integrated_vendors' => ['uuid', 'public_id', 'company_uuid', 'provider'], 'companies' => ['uuid', 'public_id', 'name', 'options'], + 'order_configs' => ['uuid', 'company_uuid', 'policies'], + 'order_offers' => ['uuid', 'order_uuid', 'driver_uuid', 'status', 'expires_at'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'owner_type', 'status_uuid', '_key'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'code', 'status', 'details'], 'directives' => ['uuid', 'company_uuid', 'permission_uuid', 'subject_type', 'subject_uuid', 'key', 'rules'], diff --git a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php index 5309ffca3..bc831317e 100644 --- a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php @@ -150,13 +150,13 @@ public function __call($method, $arguments) $schema = $connection->getSchemaBuilder(); app()->instance('db.schema', $schema); $tables = [ - 'orders' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'payload_uuid', 'order_config_uuid', 'tracking_number_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'dispatched', 'dispatched_at', 'started', 'started_at', 'scheduled_at', 'meta', 'distance', 'time', 'pod_required', 'pod_method', 'orchestrator_priority', 'adhoc_distance', 'notes', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'vehicle_assigned_uuid', 'route_uuid', 'purchase_rate_uuid', 'transaction_uuid', 'time_window_start', 'time_window_end', 'required_skills', '_key'], + 'orders' => ['uuid', 'public_id', 'internal_id', 'adhoc_strategy', 'required_vehicle_type', 'company_uuid', 'payload_uuid', 'order_config_uuid', 'tracking_number_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'dispatched', 'dispatched_at', 'started', 'started_at', 'scheduled_at', 'meta', 'distance', 'time', 'pod_required', 'pod_method', 'orchestrator_priority', 'adhoc_distance', 'notes', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'vehicle_assigned_uuid', 'route_uuid', 'purchase_rate_uuid', 'transaction_uuid', 'time_window_start', 'time_window_end', 'required_skills', '_key'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'return_uuid', 'current_waypoint_uuid', 'pickup_tracking_number_uuid', 'dropoff_tracking_number_uuid', 'meta', 'type', 'payment_method', 'cod_amount', 'cod_currency', '_key'], 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'street1', 'city', 'country', 'location', 'meta', 'street2', 'province', 'postal_code', 'phone', 'type', 'owner_uuid', 'owner_type', '_key', '_import_id'], 'waypoints' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'place_uuid', 'tracking_number_uuid', 'customer_uuid', 'customer_type', 'order', 'type', '_key', '_import_id'], 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'status', 'type', 'email', 'phone', 'password', 'slug', 'username', 'meta', '_key'], - 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', '_key'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'policies', 'triggers', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', '_key'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'region', 'location', 'status_uuid', 'owner_uuid', 'owner_type', 'qr_code', 'barcode', '_key'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'proof_uuid', 'status', 'details', 'location', 'code', 'complete', '_key'], 'entities' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'destination_uuid', 'tracking_number_uuid', 'customer_uuid', 'customer_type', 'name', 'type', 'meta', 'internal_id', 'qr_code', 'barcode', 'photo_uuid', '_key', '_import_id'], @@ -169,6 +169,7 @@ public function __call($method, $arguments) 'vehicles' => ['uuid', 'public_id', 'company_uuid', 'name', 'plate_number', 'location', 'online'], 'contacts' => ['uuid', 'public_id', 'company_uuid', 'name', 'type', 'email', 'phone'], 'vendors' => ['uuid', 'public_id', 'company_uuid', 'name', 'email', 'phone'], + 'order_offers' => ['uuid', 'company_uuid', 'order_uuid', 'driver_uuid', 'status', 'distance', 'expires_at', 'responded_at'], ]; foreach ($tables as $table => $columns) { $schema->create($table, function ($blueprint) use ($columns) { @@ -661,3 +662,162 @@ public function __call($method, $arguments) // The entity receives its own tracking status alongside the order expect($connection->table('tracking_statuses')->where('tracking_number_uuid', 'tn-entity-1')->count())->toBeGreaterThanOrEqual(1); }); + +/** An adhoc order on a config made from the passenger template: offered one driver at a time, with strict transitions. */ +function fleetopsOrderStartRide(SQLiteConnection $connection, array $order = []): void +{ + $defaults = Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates::attributes('passenger'); + // Triggers would queue pushes; these tests are about accepting and declining. + $connection->table('order_configs')->insert([ + 'uuid' => 'config-ride', + 'company_uuid' => 'company-1', + 'key' => 'passenger', + 'namespace' => 'system:order-config:passenger', + 'flow' => json_encode(array_map(fn ($activity) => array_replace($activity, ['actions' => []]), $defaults['flow'])), + 'meta' => json_encode($defaults['meta']), + 'policies' => json_encode($defaults['policies']), + ]); + fleetopsOrderStartSeedOrder($connection, array_merge(['order_config_uuid' => 'config-ride', 'type' => 'passenger', 'adhoc' => 1, 'status' => 'dispatched', 'dispatched' => 1, 'dispatched_at' => '2026-11-06 09:00:00'], $order)); + $connection->table('drivers')->where('uuid', 'driver-1')->update(['online' => 1]); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-dispatched', 'company_uuid' => 'company-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED', 'status' => 'Finding a driver']); + // Declining looks for the next driver, nearest first. + $connection->getPdo()->sqliteCreateFunction('st_distance_sphere', fn ($a, $b) => 100.0); + $connection->getPdo()->sqliteCreateFunction('ST_X', fn ($value) => 0.5); + $connection->getPdo()->sqliteCreateFunction('ST_Y', fn ($value) => 0.5); + $connection->table('users')->insert(['uuid' => 'user-2', 'company_uuid' => 'company-2', 'name' => 'Rival']); + $connection->table('drivers')->insert([ + ['uuid' => 'driver-2', 'public_id' => 'driver_two', 'company_uuid' => 'company-1', 'user_uuid' => null, 'online' => 1], + ['uuid' => 'driver-3', 'public_id' => 'driver_rival', 'company_uuid' => 'company-2', 'user_uuid' => 'user-2', 'online' => 1], + ['uuid' => 'driver-4', 'public_id' => 'driver_sleepy', 'company_uuid' => 'company-1', 'user_uuid' => null, 'online' => 0], + ]); +} + +function fleetopsOrderStartOffer(SQLiteConnection $connection, string $driverUuid, string $expiresAt = '2099-01-01 00:00:00'): void +{ + $connection->table('order_offers')->insert(['uuid' => 'offer-' . $driverUuid, 'company_uuid' => 'company-1', 'order_uuid' => 'order-1', 'driver_uuid' => $driverUuid, 'status' => 'pending', 'expires_at' => $expiresAt]); +} + +test('accepting an adhoc ride refuses unknown, foreign, offline and impersonated drivers', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + $controller = new OrderController(); + $accept = fn (string $driver) => $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => $driver])); + + expect($accept('driver_missing')->getStatusCode())->toBe(404) + ->and($accept('driver_rival')->getStatusCode())->toBe(404) + ->and($accept('driver_sleepy')->getStatusCode())->toBe(422); + + // Signed in as Driver One, nobody accepts for someone else. + session(['user' => 'user-1']); + $impersonated = $accept('driver_two'); + session(['user' => null]); + + expect($impersonated->getStatusCode())->toBe(403) + ->and($connection->table('orders')->value('driver_assigned_uuid'))->toBeNull(); +}); + +test('a ride with timed offers can only be accepted by the driver it is offered to', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + fleetopsOrderStartOffer($connection, 'driver-1'); + $controller = new OrderController(); + + $notOffered = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_two'])); + $offered = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); + + expect($notOffered->getStatusCode())->toBe(409) + ->and($notOffered->getData(true)['error'])->toContain('no longer offered') + ->and($connection->table('orders')->value('driver_assigned_uuid'))->toBe('driver-1') + ->and($connection->table('orders')->value('started'))->toBe(1) + ->and($connection->table('order_offers')->where('driver_uuid', 'driver-1')->value('status'))->toBe('accepted'); +}); + +test('of two drivers accepting the same adhoc order only the first gets it', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['strategy' => 'broadcast']]])]); + // Someone else claimed it after this request loaded the order. + $connection->table('orders')->update(['driver_assigned_uuid' => 'driver-2']); + + $order = Order::where('uuid', 'order-1')->first(); + $order->driver_assigned_uuid = null; + $order->syncOriginal(); + $refusal = (new class extends OrderController { + public function claim(Order $order, string $driver) + { + return $this->claimAdhocOrder($order, $driver); + } + })->claim($order, 'driver_one'); + + expect($refusal->getStatusCode())->toBe(409) + ->and($refusal->getData(true)['error'])->toContain('taken by another driver') + ->and($connection->table('orders')->value('driver_assigned_uuid'))->toBe('driver-2'); +}); + +test('the driver already holding an adhoc order passes, and a canceled order refuses everyone', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection, ['driver_assigned_uuid' => 'driver-1']); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['strategy' => 'broadcast']]])]); + $controller = new OrderController(); + + $held = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); + expect($connection->table('orders')->value('started'))->toBe(1); + + $connection->table('orders')->update(['started' => 0, 'status' => 'canceled']); + $canceled = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); + + expect($canceled->getStatusCode())->toBe(409) + ->and($canceled->getData(true)['error'])->toContain('canceled'); +}); + +test('a driver declines the ride offered to them, signed in or named', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + fleetopsOrderStartOffer($connection, 'driver-1'); + $connection->table('order_offers')->insert(['uuid' => 'offer-2', 'company_uuid' => 'company-1', 'order_uuid' => 'order-1', 'driver_uuid' => 'driver-2', 'status' => 'declined', 'expires_at' => '2099-01-01 00:00:00']); + $controller = new OrderController(); + + $missing = $controller->declineOrder('order_missing', Request::create('/x', 'POST')); + $nobody = $controller->declineOrder('order_start', Request::create('/x', 'POST')); + $rival = $controller->declineOrder('order_start', Request::create('/x', 'POST', ['driver' => 'driver_rival'])); + $named = $controller->declineOrder('order_start', Request::create('/x', 'POST', ['driver' => 'driver_two'])); + + session(['user' => 'user-1']); + $declined = $controller->declineOrder('order_start', Request::create('/x', 'POST', ['driver' => 'driver_two'])); + session(['user' => null]); + + expect($missing->getStatusCode())->toBe(404) + ->and($nobody->getStatusCode())->toBe(404) + ->and($rival->getStatusCode())->toBe(404) + ->and($named->getStatusCode())->toBe(409) + ->and($declined->getData(true))->toBe(['status' => 'declined', 'order' => 'order_start']) + ->and($connection->table('order_offers')->where('uuid', 'offer-driver-1')->value('status'))->toBe('declined') + // Nobody else has a position, so the ride ends as no driver found. + ->and($connection->table('orders')->value('status'))->toBe('canceled'); +}); + +test('a strict ride flow refuses skipped steps and uses the configured activity', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection, ['status' => 'arrived', 'started' => 1, 'driver_assigned_uuid' => 'driver-1']); + $controller = new OrderController(); + + $skipped = $controller->updateActivity('order_start', Request::create('/x', 'POST', ['activity' => ['code' => 'completed']])); + $onBoard = $controller->updateActivity('order_start', Request::create('/x', 'POST', ['activity' => ['code' => 'in_progress', 'status' => 'Anything the client says']])); + + expect($skipped->getStatusCode())->toBe(422) + ->and($connection->table('orders')->value('status'))->toBe('in_progress') + ->and($connection->table('tracking_statuses')->where('code', 'IN_PROGRESS')->value('status'))->toBe('Trip in progress'); +}); + +test('canceling a ride frees its driver and withdraws the open offer', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection, ['driver_assigned_uuid' => 'driver-1']); + fleetopsOrderStartOffer($connection, 'driver-2'); + $connection->table('drivers')->where('uuid', 'driver-1')->update(['current_job_uuid' => 'order-1']); + + Order::where('uuid', 'order-1')->first()->cancelWithReason('Rider changed their mind'); + + expect($connection->table('drivers')->where('uuid', 'driver-1')->value('current_job_uuid'))->toBeNull() + ->and($connection->table('order_offers')->value('status'))->toBe('withdrawn') + ->and($connection->table('orders')->value('status'))->toBe('canceled'); +}); diff --git a/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php b/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php index 2420ead6d..96b87a378 100644 --- a/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php +++ b/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php @@ -90,7 +90,7 @@ protected function importFile(TrailerImport $import, string $path, string $disk) class FleetOpsTrailerExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { return (array) $this->input($key, $default); } diff --git a/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php b/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php index b502938bc..30361c806 100644 --- a/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php @@ -27,7 +27,7 @@ class FleetOpsInternalDriverExportImportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php b/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php index 55cebc030..677608edc 100644 --- a/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php @@ -196,7 +196,7 @@ public function setKey($model, $type = null): File class FleetOpsInternalIssueRequestFake extends Request { - public function array($key = null, $default = []): array + public function inputArray($key = null, $default = []): array { $value = data_get($this->all(), $key, $default); diff --git a/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php b/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php index c840ed7cb..033720a91 100644 --- a/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php @@ -131,7 +131,7 @@ public function string($key = null, $default = null): Stringable return str((string) ($this->values[$key] ?? $default ?? '')); } - public function array($key = null, $default = []): array + public function inputArray($key = null, $default = []): array { $value = $this->values[$key] ?? $default; diff --git a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php index e1a714436..27fe6377b 100644 --- a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php @@ -178,8 +178,8 @@ function fleetopsInternalOrderConfigDbBoot(): SQLiteConnection return $default; }); } - if (!Request::hasMacro('array')) { - Request::macro('array', fn (string $key, $default = []) => (array) $this->input($key, $default)); + if (!Request::hasMacro('inputArray')) { + Request::macro('inputArray', fn (string $key, $default = []) => (array) $this->input($key, $default)); } if (!class_exists('Illuminate\\Validation\\Rule', false)) { eval('namespace Illuminate\\Validation; class Rule { public static function __callStatic($method, $arguments) { return new class { public function __call($method, $arguments) { return $this; } }; } }'); @@ -220,7 +220,7 @@ public function __call($method, $arguments) }); $schema->create('order_configs', function ($blueprint) { $blueprint->increments('id'); - foreach (['uuid', 'public_id', 'company_uuid', 'created_by_uuid', 'author_uuid', 'category_uuid', 'icon_uuid', 'name', 'key', 'namespace', 'description', 'tags', 'flow', 'entities', 'meta', 'version', 'status', 'type', '_key'] as $column) { + foreach (['uuid', 'public_id', 'company_uuid', 'created_by_uuid', 'author_uuid', 'category_uuid', 'icon_uuid', 'name', 'key', 'namespace', 'description', 'tags', 'flow', 'entities', 'meta', 'policies', 'triggers', 'version', 'status', 'type', '_key'] as $column) { $blueprint->string($column)->nullable(); } $blueprint->integer('core_service')->nullable(); @@ -228,6 +228,15 @@ public function __call($method, $arguments) $blueprint->timestamp('deleted_at')->nullable(); }); + $schema->create('custom_fields', function ($blueprint) { + $blueprint->increments('id'); + foreach (['uuid', 'public_id', 'company_uuid', 'category_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'for', 'component', 'options', 'required', 'editable', 'default_value', 'validation_rules', 'meta', 'description', 'help_text', 'order'] as $column) { + $blueprint->string($column)->nullable(); + } + $blueprint->timestamps(); + $blueprint->timestamp('deleted_at')->nullable(); + }); + session(['company' => 'company-1']); $connection->table('companies')->insert(['uuid' => 'company-1', 'name' => 'Acme']); app()->instance('responsecache', new class { @@ -312,3 +321,48 @@ public function __call($method, $arguments) $missing = $controller->deleteRecord('missing-uuid', Request::create('/int/v1/order-configs', 'DELETE')); expect(json_encode($missing->getData(true)))->toContain('No order config found'); }); + +test('internal order config controller describes what order configs can use, for the console', function () { + $response = (new FleetOpsInternalOrderConfigRealHelpersProbe())->capabilities(); + $body = $response->getData(true); + + expect($response->getStatusCode())->toBe(200) + ->and(array_keys($body))->toBe(['templates', 'policies', 'actions', 'events', 'placeholders']) + ->and($body['templates'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates::describe()) + ->and(array_column($body['templates'], 'key'))->toBe(['transport', 'passenger']) + ->and($body['policies'])->toBe(json_decode(json_encode(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies::describe()), true)) + ->and(array_column($body['actions'], 'name'))->toContain('cancel', 'open_chat', 'set_meta', 'notify_driver') + ->and($body['events'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers::EVENTS) + ->and($body['placeholders'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\Actions\Action::PLACEHOLDERS); +}); + +test('internal order config controller makes a named config from a template once, for the company in session', function () { + $connection = fleetopsInternalOrderConfigDbBoot(); + $controller = new FleetOpsInternalOrderConfigRealHelpersProbe(); + $make = fn (array $input) => $controller->createFromTemplate(Request::create('/int/v1/order-configs/from-template', 'POST', $input)); + $error = fn ($response) => $response->getData(true)['error'] ?? null; + + $unknown = $make(['template' => 'limousine', 'name' => 'Limos']); + $blank = $make(['template' => 'passenger', 'name' => ' ']); + $created = $make(['template' => 'passenger', 'name' => ' Airport Transfers ']); + $sameKey = $make(['template' => 'transport', 'name' => 'airport transfers']); + $sameName = $make(['template' => 'transport', 'name' => 'Airport Transfers']); + + session(['company' => null]); + $noCompany = $make(['template' => 'passenger', 'name' => 'Night Rides']); + session(['company' => 'company-1']); + + $config = $connection->table('order_configs')->first(); + expect($error($unknown))->toBe('Choose an order config template.') + ->and($error($blank))->toBe('Give the order config a name.') + ->and($error($sameKey))->toBe('An order config with this name already exists.') + ->and($error($sameName))->toBe('An order config with this name already exists.') + ->and($error($noCompany))->toBe('No organization in session.') + ->and($created)->toHaveKey('order_config') + ->and($created['order_config']->resource->uuid)->toBe($config->uuid) + ->and($connection->table('order_configs')->count())->toBe(1) + ->and([$config->company_uuid, $config->name, $config->key, $config->namespace, (int) $config->core_service])->toBe(['company-1', 'Airport Transfers', 'airport-transfers', 'acme:order-config:airport-transfers', 0]) + ->and(json_decode($config->policies, true)['dispatch']['adhoc']['strategy'])->toBe('sequential') + // The passenger template's custom field is made with the config. + ->and($connection->table('custom_fields')->where('subject_uuid', $config->uuid)->pluck('name')->all())->toBe(['passengers']); +}); diff --git a/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php b/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php index 14d5248dc..79c476ee9 100644 --- a/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php +++ b/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php @@ -161,6 +161,21 @@ public function errors() $disk = new class implements Illuminate\Contracts\Filesystem\Filesystem { public array $writes = []; + public function path($path) + { + return $path; + } + + public function putFile($path, $file = null, $options = []) + { + return false; + } + + public function putFileAs($path, $file, $name = null, $options = []) + { + return false; + } + public function url($path) { return 'https://cdn.example.com/' . ltrim((string) $path, '/'); diff --git a/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php b/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php index ff183cbe5..30af9c5d2 100644 --- a/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php @@ -912,7 +912,7 @@ public function input($key = null, $default = null) return data_get($this->payload, $key, $default); } - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php b/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php index e7c450ff8..9cafb6a26 100644 --- a/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php @@ -17,7 +17,7 @@ class FleetOpsInternalWorkOrderExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/Feature/Http/Public/TrackingControllerTest.php b/server/tests/Feature/Http/Public/TrackingControllerTest.php index 623549f09..a002f9c4f 100644 --- a/server/tests/Feature/Http/Public/TrackingControllerTest.php +++ b/server/tests/Feature/Http/Public/TrackingControllerTest.php @@ -2,7 +2,6 @@ use Fleetbase\FleetOps\Http\Controllers\Public\TrackingController; use Fleetbase\FleetOps\Models\Contact; -use Fleetbase\FleetOps\Models\Entity; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\Place; use Fleetbase\FleetOps\Models\Proof; @@ -23,10 +22,10 @@ class TrackingControllerResolverFake extends TrackingResolver { public ?TrackingTarget $target = null; - public ?string $slugCompany = null; - public array $company = []; - public array $admin = []; - public array $resolved = []; + public ?string $slugCompany = null; + public array $company = []; + public array $admin = []; + public array $resolved = []; public function resolve(mixed $input, ?string $slug = null): ?TrackingTarget { @@ -264,7 +263,7 @@ function trackingControllerRequest(array $input = []): Request test('the page config shows a company page or the shared page, and nothing for a page that is off', function () { $controller = trackingController(); - TrackingPageDatabase::insert(Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(), 'companies', ['uuid' => 'co-1', 'name' => 'Northwind Couriers', 'phone' => '+15105550142']); + TrackingPageDatabase::insert(EloquentModel::getConnectionResolver()->connection(), 'companies', ['uuid' => 'co-1', 'name' => 'Northwind Couriers', 'phone' => '+15105550142']); expect($controller->config(trackingControllerRequest(['org' => 'northwind']))->getStatusCode())->toBe(404); @@ -299,7 +298,7 @@ function trackingControllerRequest(array $input = []): Request // A tracking number alone: the public view, with the channels a code can use. $controller->fakeAccess->lookup = true; $controller->providers = ['vonage' => ['available' => true]]; - TrackingPageDatabase::insert(Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-1', 'email' => 'maya@example.com', 'phone' => '+15105554821']); + TrackingPageDatabase::insert(EloquentModel::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-1', 'email' => 'maya@example.com', 'phone' => '+15105554821']); $public = $controller->show(trackingControllerRequest(['org' => 'Northwind']), 'NOR1000000001US')->getData(true); expect($public['level'])->toBe(0) ->and(array_column($public['channels'], 'type'))->toBe(['sms', 'email']) @@ -317,10 +316,10 @@ function trackingControllerRequest(array $input = []): Request $controller->fakeAccess->granted = false; $controller->user = (object) ['uuid' => 'user-1', 'type' => 'customer', 'company_uuid' => 'co-1']; - TrackingPageDatabase::insert(Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-x', 'user_uuid' => 'user-1']); + TrackingPageDatabase::insert(EloquentModel::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-x', 'user_uuid' => 'user-1']); expect($controller->show(trackingControllerRequest(), 'NOR1000000001US')->getData(true)['level'])->toBe(0); - Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection()->table('contacts')->where('uuid', 'contact-1')->update(['user_uuid' => 'user-1']); + EloquentModel::getConnectionResolver()->connection()->table('contacts')->where('uuid', 'contact-1')->update(['user_uuid' => 'user-1']); expect($controller->show(trackingControllerRequest(), 'NOR1000000001US')->getData(true))->toMatchArray(['viewer' => 'account', 'level' => 2, 'expires_at' => null]); $controller->user = (object) ['uuid' => 'user-2', 'type' => 'user', 'company_uuid' => 'co-1']; @@ -335,7 +334,7 @@ function trackingControllerRequest(array $input = []): Request test('codes go out on an available channel, within the limits', function () { $controller = trackingController(); - $db = Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(); + $db = EloquentModel::getConnectionResolver()->connection(); TrackingPageDatabase::insert($db, 'contacts', ['uuid' => 'contact-1', 'email' => 'maya@example.com']); TrackingPageDatabase::insert($db, 'companies', ['uuid' => 'co-1', 'name' => 'Northwind', 'options' => json_encode(['alpha_numeric_sender_id_enabled' => true, 'alpha_numeric_sender_id' => 'NORTHWIND'])]); @@ -473,7 +472,7 @@ function trackingControllerRequest(array $input = []): Request test('a signed-in customer lists their orders with the number that opens their part', function () { $controller = trackingController(); - $db = Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(); + $db = EloquentModel::getConnectionResolver()->connection(); expect($controller->accountOrders(trackingControllerRequest())->getStatusCode())->toBe(401); @@ -493,3 +492,24 @@ function trackingControllerRequest(array $input = []): Request ['tracking_number' => 'NOR1', 'title' => 'Ceramic lamp', 'status' => 'completed', 'stage' => 'delivered', 'updated_at' => '2026-10-07T10:00:00.000000Z'], ]); }); + +test('a shared ride link opens the rider\'s live view, and a bad one doesn\'t', function () { + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + $controller = trackingController(); + $token = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-1'); + + $controller->fakeAccess->verify = false; + expect($controller->redeemShare(trackingControllerRequest(['token' => $token]), 'NOR1')->getStatusCode())->toBe(429); + + $controller->fakeAccess->verify = true; + expect($controller->redeemShare(trackingControllerRequest(['token' => $token]), 'NOR1')->getStatusCode())->toBe(404); + + $controller->fakeResolver->target = trackingControllerTarget(); + $bad = $controller->redeemShare(trackingControllerRequest(['token' => 'nope']), 'NOR1'); + $opened = $controller->redeemShare(trackingControllerRequest(['token' => $token]), 'NOR1'); + + expect($bad->getData(true))->toBe(['error' => 'invalid']) + ->and($opened->getStatusCode())->toBe(200) + ->and($opened->getData(true)['viewer'])->toBe('verified') + ->and($controller->fakeAccess->grants[0][1])->toBe('share'); +}); diff --git a/server/tests/FleetOpsSupportContractsTest.php b/server/tests/FleetOpsSupportContractsTest.php index 2ef8b2c1a..659df6cb1 100644 --- a/server/tests/FleetOpsSupportContractsTest.php +++ b/server/tests/FleetOpsSupportContractsTest.php @@ -2,15 +2,13 @@ use Fleetbase\FleetOps\Models\Place; use Fleetbase\FleetOps\Support\FleetOps; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; use Fleetbase\FleetOps\Support\Geocoding; use Illuminate\Support\Str; function fleetopsTransportConfigDefaults(): array { - $reflection = new ReflectionMethod(FleetOps::class, 'transportConfigDefaults'); - $reflection->setAccessible(true); - - return $reflection->invoke(null); + return OrderConfigTemplates::attributes('transport'); } class FleetOpsGeocodingResultFake diff --git a/server/tests/FlowResourceTest.php b/server/tests/FlowResourceTest.php index c189198a3..2e8a73d8f 100644 --- a/server/tests/FlowResourceTest.php +++ b/server/tests/FlowResourceTest.php @@ -144,9 +144,12 @@ function flowFixture(): array ->and((new Condition(['field' => 'status', 'operator' => 'notEqual', 'value' => 'completed']))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'priority', 'operator' => 'greaterThan', 'value' => 2]))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'priority', 'operator' => 'lessThanOrEqual', 'value' => 3]))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'notes', 'operator' => 'contains', 'value' => 'deliver fragile parcel today']))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'notes', 'operator' => 'beginsWith', 'value' => 'deliver fragile parcel']))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'notes', 'operator' => 'endsWith', 'value' => 'today deliver fragile parcel']))->eval($order))->toBeTrue(); + // The field holds the value: notes contain, begin with or end with it. + ->and((new Condition(['field' => 'notes', 'operator' => 'contains', 'value' => 'Fragile']))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'notes', 'operator' => 'contains', 'value' => 'deliver fragile parcel today']))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'notes', 'operator' => 'beginsWith', 'value' => 'deliver']))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'notes', 'operator' => 'beginsWith', 'value' => 'parcel']))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'notes', 'operator' => 'endsWith', 'value' => 'parcel']))->eval($order))->toBeTrue(); expect(fn () => (new Condition(['field' => 'status', 'operator' => 'between', 'value' => []]))->eval($order)) ->toThrow(Exception::class, 'Unknown operator: between'); @@ -154,12 +157,32 @@ function flowFixture(): array // Remaining operator arms: existence, array membership, boolean logic // and the strict lower-than comparison expect((new Condition(['field' => 'status', 'operator' => 'exists', 'value' => null]))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => ['ready']]))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => ['ready', 'held']]))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => 'held, ready']))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'notIn', 'value' => ['ready']]))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'status', 'operator' => 'notIn', 'value' => ['held']]))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'missing_field', 'operator' => 'exists', 'value' => null]))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'missing_field', 'operator' => 'notEqual', 'value' => 'anything']))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'and', 'value' => true]))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'or', 'value' => false]))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'not', 'value' => null]))->eval($order))->toBeFalse() ->and((new Condition(['field' => 'priority', 'operator' => 'lessThan', 'value' => 9]))->eval($order))->toBeTrue(); + + // `has` and `doesntHave` look for the value in a field that is a list. + $tagged = flowTestOrder(['tags' => ['Fragile', 'express']]); + expect((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'fragile']))->eval($tagged))->toBeTrue() + ->and((new Condition(['field' => 'tags', 'operator' => 'doesntHave', 'value' => 'oversize']))->eval($tagged))->toBeTrue() + ->and((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'oversize']))->eval($tagged))->toBeFalse(); + + // A field read as a collection, such as a relation, is compared as its list. + $collected = flowTestOrder(['tags' => collect(['Fragile', 'express']), 'status' => 'Ready']); + expect((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'FRAGILE']))->eval($collected))->toBeTrue() + ->and((new Condition(['field' => 'tags', 'operator' => 'doesntHave', 'value' => 'express']))->eval($collected))->toBeFalse() + // A single value is a list of one, and a missing field an empty list. + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => 'ready']))->eval($collected))->toBeTrue() + ->and((new Condition(['field' => 'status', 'operator' => 'notIn', 'value' => 'held']))->eval($collected))->toBeTrue() + ->and((new Condition(['field' => 'missing_field', 'operator' => 'has', 'value' => 'fragile']))->eval($collected))->toBeFalse() + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => null]))->eval($collected))->toBeFalse(); }); test('flow logic combines conditions with and or not and if semantics', function () { diff --git a/server/tests/InternalFleetControllerContractsTest.php b/server/tests/InternalFleetControllerContractsTest.php index 847ae4b9a..bd00b1cfa 100644 --- a/server/tests/InternalFleetControllerContractsTest.php +++ b/server/tests/InternalFleetControllerContractsTest.php @@ -23,7 +23,7 @@ class FleetOpsInternalFleetActionRequestFake extends FleetActionRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); @@ -33,7 +33,7 @@ public function array($key = null, $default = []) class FleetOpsInternalFleetExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/InternalImportExportControllerContractsTest.php b/server/tests/InternalImportExportControllerContractsTest.php index db8282592..9aeb01d36 100644 --- a/server/tests/InternalImportExportControllerContractsTest.php +++ b/server/tests/InternalImportExportControllerContractsTest.php @@ -25,7 +25,7 @@ class FleetOpsInternalExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); @@ -37,7 +37,7 @@ class FleetOpsInternalImportRequestFake extends ImportRequest { public array $resolvedFiles = []; - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/ModelAccessorContractsTest.php b/server/tests/ModelAccessorContractsTest.php index 2e034c2ff..d0342e215 100644 --- a/server/tests/ModelAccessorContractsTest.php +++ b/server/tests/ModelAccessorContractsTest.php @@ -1564,7 +1564,7 @@ public function raw($value): Illuminate\Database\Query\Expression ->and($imported->volume)->toBe('45.5') ->and($imported->metric_unit)->toBe('gal') ->and($imported->status)->toBe('approved') - ->and($imported->location->getValue(new Illuminate\Database\Query\Grammars\Grammar()))->toContain('POINT'); + ->and($imported->location->getValue(new Illuminate\Database\Query\Grammars\Grammar(new SQLiteConnection(new PDO('sqlite::memory:')))))->toContain('POINT'); }); test('fuel provider transaction accessors expose related names and station points', function () { diff --git a/server/tests/OrderDispatchListenerContractsTest.php b/server/tests/OrderDispatchListenerContractsTest.php index c8f5f6424..30ce1cded 100644 --- a/server/tests/OrderDispatchListenerContractsTest.php +++ b/server/tests/OrderDispatchListenerContractsTest.php @@ -19,7 +19,6 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\TrackingStatus; -use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Carbon; @@ -217,8 +216,7 @@ class FleetOpsHandleOrderDispatchedProbe extends HandleOrderDispatched public Illuminate\Support\Collection $nearbyDrivers; public array $failures = []; public array $assignedNotifications = []; - public array $adhocNotifications = []; - public array $nearbyQueries = []; + public array $adhocDispatches = []; public function __construct() { @@ -244,16 +242,11 @@ protected function getDispatchActivity($order): mixed return $order->dispatchActivity; } - protected function nearbyAvailableDrivers($pickup, int|float $distance) + protected function dispatchAdhoc($order): mixed { - $this->nearbyQueries[] = [(string) $pickup, $distance]; + $this->adhocDispatches[] = $order->public_id; - return $this->nearbyDrivers; - } - - protected function notifyAdhocDriver(Driver $driver, $order): void - { - $this->adhocNotifications[] = [$driver->public_id, $driver->distance, $order->driver_assigned_uuid]; + return null; } protected function findAssignedDriver($order): ?Driver @@ -538,40 +531,17 @@ function fleetOpsDispatchListenerDriver(string $publicId, float $distance = 0): ]); }); -test('order dispatched listener pings nearby adhoc drivers and ignores invalid pickup points', function () { - $listener = new FleetOpsHandleOrderDispatchedProbe(); - $listener->nearbyDrivers = collect([ - fleetOpsDispatchListenerDriver('nearby_one', 100.5), - fleetOpsDispatchListenerDriver('nearby_two', 250.25), - ]); - $order = fleetOpsDispatchListenerOrder([ +test('order dispatched listener hands adhoc orders to their dispatch strategy', function () { + $listener = new FleetOpsHandleOrderDispatchedProbe(); + $order = fleetOpsDispatchListenerOrder([ 'adhoc' => true, 'hasDriverAssigned' => false, - 'pickupLocation' => new Point(1.30, 103.80), - 'adhocDistance' => 2400, ]); + $order->public_id = 'order_adhoc'; $listener->handle(new FleetOpsOrderDispatchedEventFake($order)); - expect($order->calls)->toContain(['load', ['company']]) - ->and($order->calls)->toContain(['getPickupLocation']) - ->and($order->calls)->toContain(['getAdhocDistance']) - ->and($listener->nearbyQueries)->toBe([[(string) $order->pickupLocation, 2400]]) - ->and($listener->adhocNotifications)->toBe([ - ['nearby_one', 100.5, 'driver-uuid'], - ['nearby_two', 250.25, 'driver-uuid'], - ]) - ->and($listener->assignedNotifications)->toBe([]); - - $invalidPickup = fleetOpsDispatchListenerOrder([ - 'adhoc' => true, - 'hasDriverAssigned' => false, - 'pickupLocation' => null, - ]); - $invalidPickupListener = new FleetOpsHandleOrderDispatchedProbe(); - - $invalidPickupListener->handle(new FleetOpsOrderDispatchedEventFake($invalidPickup)); - - expect($invalidPickupListener->nearbyQueries)->toBe([]) - ->and($invalidPickupListener->adhocNotifications)->toBe([]); + expect($listener->adhocDispatches)->toBe(['order_adhoc']) + ->and($listener->assignedNotifications)->toBe([]) + ->and($listener->failures)->toBe([]); }); diff --git a/server/tests/OrderFileAttachmentTest.php b/server/tests/OrderFileAttachmentTest.php index c75d10a55..8ef19957d 100644 --- a/server/tests/OrderFileAttachmentTest.php +++ b/server/tests/OrderFileAttachmentTest.php @@ -7,7 +7,7 @@ $formJs = file_get_contents(dirname(dirname(__DIR__)) . '/addon/components/order/form/documents.js'); expect($controller) - ->toContain("\$uploads = \$request->array('order.files')") + ->toContain("\$uploads = \$request->inputArray('order.files')") ->toContain('$order->attachFiles($uploads)') ->and($orderModel) ->toContain('public function attachFiles($uploads): self') diff --git a/server/tests/RequestContractsTest.php b/server/tests/RequestContractsTest.php index a77d8d20e..12a779d45 100644 --- a/server/tests/RequestContractsTest.php +++ b/server/tests/RequestContractsTest.php @@ -788,7 +788,7 @@ protected function canUpdateDriver(): bool ->and($rules['identity'])->toBe('required|string') ->and($rules['code'])->toBe('required|string') ->and($rules['name'])->toBe('required|string') - ->and($rules['password'])->toBe('required|string|min:8') + ->and($rules['password'])->toBe('nullable|string|min:8') ->and(ruleStrings($rules['email']))->toContain('email', 'nullable', 'unique:contacts') ->and(ruleStrings($rules['phone']))->toContain('nullable', 'string', 'unique:contacts') ->and($rules['meta'])->toBe('nullable|array'); diff --git a/server/tests/ServiceRateRouteValidationTest.php b/server/tests/ServiceRateRouteValidationTest.php index 9b9916076..a2a00d216 100644 --- a/server/tests/ServiceRateRouteValidationTest.php +++ b/server/tests/ServiceRateRouteValidationTest.php @@ -151,7 +151,7 @@ public function where($column, $value) // Exports stream through the excel facade if (!class_exists('Fleetbase\\Http\\Requests\\ExportRequest', false)) { - eval('namespace Fleetbase\\Http\\Requests; class ExportRequest extends \\Illuminate\\Http\\Request { public function array($key, $default = []) { return (array) $this->input($key, $default); } }'); + eval('namespace Fleetbase\\Http\\Requests; class ExportRequest extends \\Illuminate\\Http\\Request { public function inputArray($key, $default = []) { return (array) $this->input($key, $default); } }'); } $excelFake = new class { public array $downloads = []; diff --git a/server/tests/SettingControllerContractsTest.php b/server/tests/SettingControllerContractsTest.php index d2b7f018e..2cfdacd1d 100644 --- a/server/tests/SettingControllerContractsTest.php +++ b/server/tests/SettingControllerContractsTest.php @@ -1061,3 +1061,48 @@ protected function tableCount(string $table, Closure $scope): int Cache::flush(); } }); + +test('adhoc dispatch settings read and save the company defaults and list the strategies', function () { + $company = new class extends Fleetbase\Models\Company { + public array $savedOptions = []; + public bool $saved = false; + + public function getOption($key = null, $defaultValue = null) + { + return $this->savedOptions[$key] ?? $defaultValue; + } + + public function setOption($keys, $value) + { + $this->savedOptions[$keys] = $value; + + return $this; + } + + public function save(array $options = []) + { + return $this->saved = true; + } + }; + $controller = new FleetOpsSettingControllerProbe(); + $controller->company = $company; + $save = fn (array $input) => $controller->saveAdhocDispatchSettings(Request::create('/', 'POST', $input)); + + $defaults = $controller->getAdhocDispatchSettings()->getData(true); + expect($defaults)->toMatchArray(['adhoc_distance' => 6000, 'adhoc_strategy' => 'sequential', 'adhoc_offer_timeout' => 20]) + ->and(array_column($defaults['strategies'], 'name'))->toContain('broadcast', 'sequential') + ->and($controller->getAdhocDispatchStrategies()->getData(true)['strategies'][0])->toHaveKeys(['name', 'label', 'description']); + + expect($save(['adhoc_distance' => 50, 'adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 30])->getStatusCode())->toBe(422) + ->and($save(['adhoc_distance' => 5000, 'adhoc_strategy' => 'lottery', 'adhoc_offer_timeout' => 30])->getStatusCode())->toBe(422) + ->and($save(['adhoc_distance' => 5000, 'adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 5])->getStatusCode())->toBe(422) + ->and($company->saved)->toBeFalse(); + + $saved = $save(['adhoc_distance' => '5000', 'adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => '30']); + expect($saved->getData(true)['status'])->toBe('ok') + ->and($company->savedOptions)->toBe(['fleetops.adhoc_distance' => 5000, 'fleetops.adhoc_strategy' => 'broadcast', 'fleetops.adhoc_offer_timeout' => 30]) + ->and($controller->getAdhocDispatchSettings()->getData(true))->toMatchArray(['adhoc_distance' => 5000, 'adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 30]); + + $controller->company = null; + expect($save(['adhoc_distance' => 5000, 'adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 30])->getStatusCode())->toBe(404); +}); diff --git a/server/tests/SmallControllerContractsTest.php b/server/tests/SmallControllerContractsTest.php index a55c96d93..f84a845fd 100644 --- a/server/tests/SmallControllerContractsTest.php +++ b/server/tests/SmallControllerContractsTest.php @@ -26,7 +26,7 @@ class FleetOpsSmallControllerExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/TelematicControllerContractsTest.php b/server/tests/TelematicControllerContractsTest.php index aa0ceef45..4b1f5fb7c 100644 --- a/server/tests/TelematicControllerContractsTest.php +++ b/server/tests/TelematicControllerContractsTest.php @@ -149,6 +149,8 @@ public function getAttribute($key) }); test('internal customer controller serializes portal login payloads', function () { + fleetopsTestConnectionResolver(); + $controller = new FleetOpsCustomerControllerProbe(); $customer = new Contact(); $customer->setRawAttributes([ diff --git a/server/tests/TrackingNumberTraitContractsTest.php b/server/tests/TrackingNumberTraitContractsTest.php index 5d374cecb..02acdf034 100644 --- a/server/tests/TrackingNumberTraitContractsTest.php +++ b/server/tests/TrackingNumberTraitContractsTest.php @@ -42,7 +42,7 @@ public function payload(): void function fleetopsTrackingExpressionValue(Expression $expression): string { - return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar()) : (string) $expression; + return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar(new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')))) : (string) $expression; } test('tracking number trait handles assignment status location and pickup fallbacks', function () { diff --git a/server/tests/Unit/Http/Resources/FleetResourceTest.php b/server/tests/Unit/Http/Resources/FleetResourceTest.php index cb80ecdf2..90dc5eb05 100644 --- a/server/tests/Unit/Http/Resources/FleetResourceTest.php +++ b/server/tests/Unit/Http/Resources/FleetResourceTest.php @@ -17,8 +17,8 @@ Request::macro('isArray', fn (string $key) => is_array($this->input($key))); } -if (!Request::hasMacro('array')) { - Request::macro('array', fn (string $key, $default = []) => (array) $this->input($key, $default)); +if (!Request::hasMacro('inputArray')) { + Request::macro('inputArray', fn (string $key, $default = []) => (array) $this->input($key, $default)); } function fleetopsFleetResourceBoot(): SQLiteConnection diff --git a/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php b/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php index 1ba4af30c..e6b5fd222 100644 --- a/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php +++ b/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php @@ -136,3 +136,55 @@ class FleetOpsSupportRequestState ->and($flow[0]['activities'])->toBe([]) ->and($flow[0]['logic'])->toBeNull(); }); + +test('order config resource lists the custom fields orders of the config carry, once they are loaded', function () { + $request = Request::create('/v1/fleet-ops/order-configs/order_config_public', 'GET'); + FleetOpsOrderConfigResourceRequestState::$request = $request; + FleetOpsSupportRequestState::$request = $request; + + $config = new OrderConfig(); + $config->setRawAttributes(['id' => 11, 'uuid' => 'order-config-uuid', 'public_id' => 'order_config_public', 'key' => 'passenger', 'name' => 'Passenger', 'flow' => []], true); + + // Without the relation loaded, the resource doesn't query for it. + expect((new OrderConfigResource($config))->resolve($request))->not->toHaveKey('custom_fields'); + + $passengers = new Fleetbase\Models\CustomField(); + $passengers->setRawAttributes([ + 'uuid' => 'field-passengers', + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'options' => json_encode(['min' => 1]), + 'required' => 1, + 'default_value' => '1', + 'help_text' => 'How many people are travelling.', + 'validation_rules' => json_encode(['integer']), + ], true); + $notes = new Fleetbase\Models\CustomField(); + $notes->setRawAttributes(['uuid' => 'field-notes', 'name' => 'notes', 'label' => 'Notes', 'type' => 'textarea', 'required' => null], true); + $config->setRelation('customFields', collect([3 => $passengers, 7 => $notes])); + + expect((new OrderConfigResource($config))->resolve($request)['custom_fields'])->toBe([ + [ + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'options' => ['min' => 1], + 'required' => true, + 'default_value' => '1', + 'help_text' => 'How many people are travelling.', + ], + [ + 'name' => 'notes', + 'label' => 'Notes', + 'type' => 'textarea', + 'component' => null, + 'options' => null, + 'required' => false, + 'default_value' => null, + 'help_text' => null, + ], + ]); +}); diff --git a/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php b/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php index 49d6a7721..105ac562f 100644 --- a/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php +++ b/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php @@ -100,9 +100,8 @@ class FleetOpsConcreteHandleOrderDispatchedProbe extends HandleOrderDispatched { public ?Driver $assignedDriver = null; public bool $throwAssignedNotification = false; - public bool $throwAdhocNotification = false; public array $assignedNotifications = []; - public array $adhocNotifications = []; + public array $adhocDispatches = []; public function getDispatchActivityForTest(Order $order): mixed { @@ -119,11 +118,11 @@ protected function findAssignedDriver($order): ?Driver return $this->assignedDriver; } - protected function nearbyAvailableDrivers($pickup, int|float $distance) + protected function dispatchAdhoc($order): mixed { - return collect([ - new FleetOpsConcreteDriverForDispatch(), - ]); + $this->adhocDispatches[] = $order; + + return null; } protected function notifyAssignedDriver(Driver $driver, $order): void @@ -135,16 +134,6 @@ protected function notifyAssignedDriver(Driver $driver, $order): void $this->assignedNotifications[] = $driver; parent::notifyAssignedDriver($driver, $order); } - - protected function notifyAdhocDriver(Driver $driver, $order): void - { - if ($this->throwAdhocNotification) { - throw new RuntimeException('adhoc notification failed'); - } - - $this->adhocNotifications[] = $driver; - parent::notifyAdhocDriver($driver, $order); - } } function fleetopsConcreteOrderForDispatch(array $attributes = []): FleetOpsConcreteOrderForDispatch @@ -187,17 +176,15 @@ function fleetopsConcreteOrderForDispatch(array $attributes = []): FleetOpsConcr ->and($listener->assignedNotifications)->toBe([]); }); -test('order dispatched listener swallows adhoc driver notification failures', function () { +test('order dispatched listener marks an adhoc order dispatched before its strategy offers it', function () { $listener = new FleetOpsConcreteHandleOrderDispatchedProbe(); $order = fleetopsConcreteOrderForDispatch(); $order->adhoc = true; $order->hasDriverAssigned = false; - $order->pickupLocation = new Fleetbase\LaravelMysqlSpatial\Types\Point(1.30, 103.80); - - $listener->throwAdhocNotification = true; $listener->handle(new FleetOpsConcreteOrderDispatchedEvent($order)); expect($order->dispatched)->toBeTrue() - ->and($listener->adhocNotifications)->toBe([]); + ->and($listener->adhocDispatches)->toBe([$order]) + ->and($listener->assignedNotifications)->toBe([]); }); diff --git a/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php b/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php index 7e9d8b32c..387b8e88c 100644 --- a/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php +++ b/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php @@ -4,7 +4,6 @@ use Fleetbase\FleetOps\Listeners\HandleOrderDispatched; use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; -use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\ConnectionResolver; use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\SQLiteConnection; @@ -92,7 +91,7 @@ public function __call($method, $arguments) 'orders' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'driver_assigned_uuid', 'status', 'adhoc', 'dispatched', 'dispatched_at', 'payload_uuid', 'meta', 'type'], 'tracking_statuses' => ['uuid', 'company_uuid', 'code', 'tracking_number_uuid', 'status', 'details'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'owner_type', 'status_uuid', 'type'], - 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'meta'], + 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'meta', 'current_job_uuid'], 'companies' => ['uuid', 'public_id', 'name'], 'company_users' => ['uuid', 'company_uuid', 'user_uuid'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'phone', 'email'], @@ -148,20 +147,6 @@ public function __call($method, $arguments) expect($probe->callHelper('doesntHaveDispatchActivity', $order))->toBeFalse(); }); -test('nearby available drivers runs the spatial company scoped query', function () { - $connection = fleetopsDispatchHelperBoot(); - - $probe = new FleetOpsDispatchHelperProbe(); - $drivers = $probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000); - - expect($drivers)->toHaveCount(1) - ->and($drivers->first()->uuid)->toBe('driver-1'); - - // Offline drivers are excluded - $connection->table('drivers')->where('uuid', 'driver-1')->update(['online' => '0']); - expect($probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000))->toHaveCount(0); -}); - test('assigned driver lookup and notification helpers resolve and send', function () { fleetopsDispatchHelperBoot(); $order = Order::where('uuid', 'order-1')->withoutGlobalScopes()->first(); @@ -179,8 +164,6 @@ public function __call($method, $arguments) app()->instance(Illuminate\Contracts\Notifications\Dispatcher::class, $dispatcher); $probe->callHelper('notifyAssignedDriver', $driver, $order); - $driver->distance = 250; - $probe->callHelper('notifyAdhocDriver', $driver, $order); - expect($dispatcher->sent)->toHaveCount(2); + expect($dispatcher->sent)->toHaveCount(1); }); diff --git a/server/tests/Unit/Models/OrderCancelReasonTest.php b/server/tests/Unit/Models/OrderCancelReasonTest.php index eddd2a606..cc9d04a23 100644 --- a/server/tests/Unit/Models/OrderCancelReasonTest.php +++ b/server/tests/Unit/Models/OrderCancelReasonTest.php @@ -83,6 +83,8 @@ function fleetopsOrderCancelReasonOrder(): array } test('canceling with a reason records it as the canceled details and on the event', function () { + fleetopsTestConnectionResolver(); + [$order, $config] = fleetopsOrderCancelReasonOrder(); $order->cancelWithReason(' Customer moved house '); @@ -97,6 +99,8 @@ function fleetopsOrderCancelReasonOrder(): array }); test('a plain cancel keeps the config activity and sends no reason', function () { + fleetopsTestConnectionResolver(); + [$order, $config] = fleetopsOrderCancelReasonOrder(); $order->cancel(); diff --git a/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php b/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php index c7afe1b6d..6dfc6b0ad 100644 --- a/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php +++ b/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php @@ -2,6 +2,7 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; +use Fleetbase\FleetOps\Models\OrderConfig; use Fleetbase\FleetOps\Models\Place; use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\ConnectionResolver; @@ -59,7 +60,8 @@ public function __call($method, $arguments) 'service_quotes' => ['uuid', 'public_id', 'request_id', 'company_uuid', 'payload_uuid', 'service_rate_uuid', 'amount', 'currency', 'meta', 'expired_at', '_key'], 'transactions' => ['uuid', 'public_id', 'company_uuid', 'customer_uuid', 'customer_type', 'subject_uuid', 'subject_type', 'context_uuid', 'context_type', 'gateway_transaction_id', 'gateway', 'amount', 'currency', 'description', 'type', 'direction', 'status', 'settlement_status', 'voided_at', 'meta', '_key'], 'companies' => ['uuid', 'public_id', 'name', 'currency', 'country'], - 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'status', 'online', 'location'], + 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'status', 'online', 'location', 'current_job_uuid', 'vehicle_uuid'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'key', 'name', 'flow', 'meta', 'policies', 'triggers'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name'], 'company_users' => ['uuid', 'company_uuid', 'user_uuid'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta'], @@ -174,6 +176,11 @@ function fleetopsOrderPurchaseOrder(): Order $connection->table('users')->insert(['uuid' => 'user-1', 'company_uuid' => 'company-1']); $connection->table('company_users')->insert(['uuid' => 'cu-1', 'company_uuid' => 'company-1', 'user_uuid' => 'user-1']); $connection->table('drivers')->insert(['uuid' => 'driver-1', 'company_uuid' => 'company-1', 'user_uuid' => 'user-1', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)']); + // On another company's books: never offered this one. Busy with an order still under way: + // offered unless the order's config excludes busy drivers. + $connection->table('drivers')->insert(['uuid' => 'driver-other', 'company_uuid' => 'company-2', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)']); + $connection->table('drivers')->insert(['uuid' => 'driver-busy', 'company_uuid' => 'company-1', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)', 'current_job_uuid' => 'order-busy']); + $connection->table('orders')->insert(['uuid' => 'order-busy', 'company_uuid' => 'company-1', 'status' => 'started']); $order = fleetopsOrderPurchaseOrder(); $pickup = new Place(); @@ -184,5 +191,12 @@ function fleetopsOrderPurchaseOrder(): Order $payload->setRelation('waypoints', collect()); $order->setRelation('payload', $payload); + expect($order->findClosestDrivers())->toHaveCount(2); + + $config = new OrderConfig(); + $config->setRawAttributes(['uuid' => 'config-1', 'company_uuid' => 'company-1', 'policies' => json_encode(['dispatch' => ['matching' => ['exclude_busy_drivers' => true]]])], true); + $order->order_config_uuid = 'config-1'; + $order->setRelation('orderConfig', $config); + expect($order->findClosestDrivers())->toHaveCount(1); }); diff --git a/server/tests/Unit/Models/PlaceCreationAndImportTest.php b/server/tests/Unit/Models/PlaceCreationAndImportTest.php index 7d2df89a0..feae70a71 100644 --- a/server/tests/Unit/Models/PlaceCreationAndImportTest.php +++ b/server/tests/Unit/Models/PlaceCreationAndImportTest.php @@ -62,6 +62,21 @@ public function __call($method, $arguments) Illuminate\Support\Facades\DB::clearResolvedInstance('db'); $disk = new class implements Filesystem { + public function path($path) + { + return $path; + } + + public function putFile($path, $file = null, $options = []) + { + return false; + } + + public function putFileAs($path, $file, $name = null, $options = []) + { + return false; + } + public function url($path) { return 'https://cdn.example.com/' . ltrim((string) $path, '/'); diff --git a/server/tests/Unit/Models/ServiceQuoteTest.php b/server/tests/Unit/Models/ServiceQuoteTest.php index 7814d2edf..4971c0b87 100644 --- a/server/tests/Unit/Models/ServiceQuoteTest.php +++ b/server/tests/Unit/Models/ServiceQuoteTest.php @@ -615,3 +615,20 @@ public function updateMeta($key, $value = null): bool Facade::setFacadeApplication($previousContainer); } }); + +test('service quote from another company resolves as not found', function () { + $quote = new ServiceQuote(); + $quote->setRawAttributes(['uuid' => '11111111-1111-4111-8111-111111111111', 'company_uuid' => 'company-b'], true); + + FleetOpsServiceQuoteUnitResolvableFake::$lookups = []; + FleetOpsServiceQuoteUnitResolvableFake::$records = ['uuid' => ['11111111-1111-4111-8111-111111111111' => $quote], 'public_id' => []]; + $request = fleetopsServiceQuoteUnitRequestWithQuote('11111111-1111-4111-8111-111111111111'); + + session(['company' => 'company-a']); + expect(FleetOpsServiceQuoteUnitResolvableFake::resolveFromRequest($request))->toBeNull(); + + session(['company' => 'company-b']); + expect(FleetOpsServiceQuoteUnitResolvableFake::resolveFromRequest($request))->toBe($quote); + + session(['company' => null]); +}); diff --git a/server/tests/Unit/Notifications/MonitoringNotificationsTest.php b/server/tests/Unit/Notifications/MonitoringNotificationsTest.php index dc00d87bc..871a226bf 100644 --- a/server/tests/Unit/Notifications/MonitoringNotificationsTest.php +++ b/server/tests/Unit/Notifications/MonitoringNotificationsTest.php @@ -131,6 +131,6 @@ function fleetopsMonitoringNotifOrder(): Order // Push transports and console urls are unavailable in the harness; the // delegation bodies still execute up to those seams. expect(fn () => $notification->toMail(null))->toThrow(Error::class) - ->and(fn () => $notification->toFcm(null))->toThrow(Exception::class) + ->and(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php b/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php index cb0a481ae..25590c4ac 100644 --- a/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php @@ -48,6 +48,6 @@ function fleetopsOrderAssignedOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php b/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php index 7fbd15f48..9389b12ca 100644 --- a/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php +++ b/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php @@ -42,7 +42,7 @@ function fleetopsOrderChangeNotificationOrder(): Order ->and((new OrderChanged(fleetopsOrderChangeNotificationOrder()))->message)->toBe('This order was changed, tap for details.'); // The push builders reach for the FCM and APN clients, which the harness does not configure - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); @@ -54,6 +54,6 @@ function fleetopsOrderChangeNotificationOrder(): Order ->and($notification->via(null))->toBe([FcmChannel::class, ApnChannel::class]) ->and($notification->toArray()['event'])->toBe('order.unassigned_notification'); - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php b/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php index 9446a7af3..00e8809d8 100644 --- a/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php @@ -76,6 +76,6 @@ function fleetopsOrderDispatchedOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderFailedChannelsTest.php b/server/tests/Unit/Notifications/OrderFailedChannelsTest.php index b06272654..cf86d51ef 100644 --- a/server/tests/Unit/Notifications/OrderFailedChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderFailedChannelsTest.php @@ -68,6 +68,6 @@ function fleetopsOrderFailedOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderPingChannelsTest.php b/server/tests/Unit/Notifications/OrderPingChannelsTest.php index ab57a6520..e5c939603 100644 --- a/server/tests/Unit/Notifications/OrderPingChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderPingChannelsTest.php @@ -64,6 +64,6 @@ function fleetopsOrderPingOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $ping->toFcm(null))->toThrow(Exception::class) + expect(fn () => $ping->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $ping->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php b/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php index 3953d2305..22115967e 100644 --- a/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php +++ b/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php @@ -164,6 +164,6 @@ public function __call($method, $arguments) expect(fn () => $withWaypoint->toMail(null))->toThrow(Error::class); // Push transports are unavailable; delegation bodies still execute - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Support/CarbonDiffContractTest.php b/server/tests/Unit/Support/CarbonDiffContractTest.php new file mode 100644 index 000000000..c795aa81d --- /dev/null +++ b/server/tests/Unit/Support/CarbonDiffContractTest.php @@ -0,0 +1,118 @@ +copy()->subSeconds(90), $now))->toBe('1m overdue') + ->and(RadarRules::overdueWords($now->copy()->subMinutes(150), $now))->toBe('2h overdue') + ->and(RadarRules::overdueWords($now->copy()->subHours(60), $now))->toBe('2d overdue'); +}); + +test('due words count whole days forward', function () { + $now = Carbon::parse('2026-09-15 12:00:00', 'UTC'); + + expect(RadarRules::dueInWords($now->copy()->addDays(3)->addHours(6), $now))->toBe('in 3 days'); +}); + +test('ago words clamp a future time and keep whole minutes', function () { + $now = Carbon::parse('2026-09-15 12:00:00', 'UTC'); + + expect(RadarRules::agoWords($now->copy()->addMinutes(5), $now))->toBe('1m ago') + ->and(RadarRules::agoWords($now->copy()->subSeconds(150), $now))->toBe('2m ago'); +}); + +test('agenda percentages use whole minutes and whole hours', function () { + $start = Carbon::parse('2026-09-15 08:00:00', 'UTC'); + $pct = new ReflectionMethod(RadarAgenda::class, 'pct'); + + expect($pct->invoke(null, $start->copy()->addSeconds(5430), $start, 10))->toBe(15.0) + ->and($pct->invoke(null, $start->copy()->subHour(), $start, 10))->toBe(0.0); +}); + +test('replay delay is a whole absolute number of seconds', function () { + $command = (new ReflectionClass(ReplayVehicleLocations::class))->newInstanceWithoutConstructor(); + $delay = new ReflectionMethod(ReplayVehicleLocations::class, 'calculateReplayDelay'); + + expect($delay->invoke($command, '2026-01-01T10:00:00Z', '2026-01-01T10:00:08.900Z', 2.0))->toBe([8, 4.0]) + ->and($delay->invoke($command, '2026-01-01T10:00:08.900Z', '2026-01-01T10:00:00Z', 2.0))->toBe([8, 4.0]); +}); + +test('position metrics keep dwell, acceleration and duration positive and whole', function () { + $position = fn (string $uuid, float $speed, string $at) => (object) [ + 'uuid' => $uuid, + 'speed' => $speed, + 'coordinates' => new Point(1.30, 103.80), + 'created_at' => Carbon::parse($at, 'UTC'), + ]; + $positions = collect([ + $position('a', 0.0, '2026-07-28 08:00:00'), + $position('b', 0.0, '2026-07-28 08:05:00.700000'), + $position('c', 10.0, '2026-07-28 08:05:02.900000'), + ]); + + $metrics = (new ReflectionMethod(PositionController::class, 'calculateMetrics')) + ->invoke(new PositionController(), $positions); + + expect($metrics['total_duration'])->toBe(302) + ->and($metrics['dwell_count'])->toBe(1) + ->and($metrics['dwell_times'][0]['duration'])->toBe(300) + ->and($metrics['acceleration_count'])->toBe(1) + ->and($metrics['acceleration_events'][0]['acceleration'])->toBe(5.0); +}); + +test('equipment age, depreciation and replacement cost use whole years', function () { + $equipment = new Equipment(); + $equipment->setRawAttributes([ + 'purchased_at' => Carbon::parse('2023-03-15 00:00:00', 'UTC'), + 'purchase_price' => 1000, + 'meta' => ['depreciation_rate' => 0.1, 'inflation_rate' => 0.1], + ], true); + + expect($equipment->age_in_days)->toBe(1280) + ->and($equipment->depreciated_value)->toEqualWithDelta(700.0, 0.0001) + ->and($equipment->getReplacementCostEstimate())->toEqualWithDelta(1331.0, 0.0001); +}); + +test('days until due stay signed whole days', function () { + $maintenance = new Maintenance(); + $maintenance->setRawAttributes(['scheduled_at' => now()->addHours(36), 'status' => 'scheduled'], true); + $overdue = new WorkOrder(); + $overdue->setRawAttributes(['due_at' => now()->subHours(36), 'status' => 'open'], true); + + expect($maintenance->days_until_due)->toBe(1) + ->and($overdue->days_until_due)->toBe(-1); +}); + +test('repair durations stay whole hours', function () { + $maintenance = new Maintenance(); + $maintenance->setRawAttributes(['started_at' => now()->subMinutes(150), 'completed_at' => now()], true); + $workOrder = new WorkOrder(); + $workOrder->setRawAttributes(['opened_at' => now()->subMinutes(150), 'closed_at' => now()], true); + + expect($maintenance->duration_hours)->toBe(2.0) + ->and($workOrder->getActualDuration())->toBe(2.0); +}); diff --git a/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php b/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php index bb48c7a77..af4cf34b2 100644 --- a/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php +++ b/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php @@ -159,6 +159,6 @@ public function sendNow($notifiables, $notification, ?array $channels = null) // Push transports are unavailable in the harness; the delegation bodies // still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigAuthorizeTransitionTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigAuthorizeTransitionTest.php new file mode 100644 index 000000000..df9dc7298 --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigAuthorizeTransitionTest.php @@ -0,0 +1,111 @@ +setRawAttributes(array_merge(['uuid' => 'order-1', 'status' => $status], $attributes), true); + + return $order; +} + +function orderConfigTransitionConfig(array $meta = [], ?array $flow = null): OrderConfig +{ + return new OrderConfig(['flow' => $flow ?? OrderConfigTemplates::attributes('transport')['flow'], 'meta' => $meta]); +} + +test('a finished order takes no more activities, unless an operator corrects it', function () { + $config = orderConfigTransitionConfig(); + $activity = new Activity(['code' => 'started', 'status' => 'Order Started']); + + [$kept, $refused] = $config->authorizeTransition(orderConfigTransitionOrder('completed'), $activity); + [, $canceled] = $config->authorizeTransition(orderConfigTransitionOrder('canceled'), $activity); + [, $corrected] = $config->authorizeTransition(orderConfigTransitionOrder('completed'), $activity, null, false, true); + [, $live] = $config->authorizeTransition(orderConfigTransitionOrder('dispatched'), $activity); + + expect($refused)->toBe('This order has already finished.') + ->and($kept)->toBe($activity) + ->and($canceled)->toBe('This order has already finished.') + ->and($corrected)->toBeNull() + ->and($live)->toBeNull(); +}); + +test('a config\'s own terminal activities end its orders too', function () { + $passenger = new OrderConfig(OrderConfigTemplates::attributes('passenger')); + + [, $noShow] = $passenger->authorizeTransition(orderConfigTransitionOrder('no_show'), new Activity(['code' => 'in_progress'])); + [, $fixed] = $passenger->authorizeTransition(orderConfigTransitionOrder('no_show'), new Activity(['code' => 'in_progress']), null, false, true); + + expect($noShow)->toBe('This order has already finished.') + // Correcting a finished order still follows strict transitions: nothing follows no_show. + ->and($fixed)->toBe('This activity is not a permitted next step for the order.'); +}); + +test('strict transitions use the config\'s own activity and refuse anything that is not a next step', function () { + $passenger = new OrderConfig(OrderConfigTemplates::attributes('passenger')); + $sent = new Activity(['code' => 'arrived', 'status' => 'Made up by the client', 'details' => 'Ignored', 'require_pod' => false]); + + [$applied, $allowed] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), $sent); + [, $skipped] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), new Activity(['code' => 'completed'])); + [, $unknown] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), new Activity(['code' => 'teleported'])); + [, $noCode] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), new Activity(['status' => 'Something'])); + + // Without strict transitions any activity is applied as sent. + $loose = orderConfigTransitionConfig(); + $free = new Activity(['code' => 'teleported', 'status' => 'Anything']); + [$looseApplied, $looseOk] = $loose->authorizeTransition(orderConfigTransitionOrder('created'), $free); + + expect($allowed)->toBeNull() + ->and($applied)->not->toBe($sent) + ->and($applied->get('status'))->toBe('Driver has arrived') + ->and($applied->get('details'))->toBe('The driver is waiting at the pickup.') + ->and($skipped)->toBe('This activity is not a permitted next step for the order.') + ->and($unknown)->toBe('This activity is not a permitted next step for the order.') + ->and($noCode)->toBe('This activity is not a permitted next step for the order.') + ->and($looseOk)->toBeNull() + ->and($looseApplied)->toBe($free); +}); + +test('a config whose lifecycle turns dispatch off refuses the dispatched activity', function () { + $dispatched = new Activity(['code' => 'dispatched']); + + [, $off] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => false]])->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $offText] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => 'false']])->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $on] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => true]])->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $default] = orderConfigTransitionConfig()->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $started] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => false]])->authorizeTransition(orderConfigTransitionOrder('created'), new Activity(['code' => 'started'])); + + expect($off)->toBe('Orders of this type are not dispatched.') + ->and($offText)->toBe('Orders of this type are not dispatched.') + ->and($on)->toBeNull() + ->and($default)->toBeNull() + ->and($started)->toBeNull(); +}); + +test('an activity that needs proof of delivery needs proof, unless it is bypassed', function () { + $config = orderConfigTransitionConfig(); + $needsPod = new Activity(['code' => 'dropped', 'require_pod' => true]); + $completes = new Activity(['code' => 'completed', 'complete' => true]); + $refusal = 'Proof of delivery is required for this activity or must be explicitly bypassed.'; + + [, $withoutProof] = $config->authorizeTransition(orderConfigTransitionOrder('started'), $needsPod); + [, $withProof] = $config->authorizeTransition(orderConfigTransitionOrder('started'), $needsPod, 'proof-1'); + [, $bypassed] = $config->authorizeTransition(orderConfigTransitionOrder('started'), $needsPod, null, true); + [, $podOrder] = $config->authorizeTransition(orderConfigTransitionOrder('started', ['pod_required' => 1]), $completes); + [, $plainOrder] = $config->authorizeTransition(orderConfigTransitionOrder('started', ['pod_required' => 0]), $completes); + + expect($withoutProof)->toBe($refusal) + ->and($withProof)->toBeNull() + ->and($bypassed)->toBeNull() + ->and($podOrder)->toBe($refusal) + ->and($plainOrder)->toBeNull(); +}); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php new file mode 100644 index 000000000..a5156745b --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php @@ -0,0 +1,150 @@ +values); } }; } }'); +} + +class OrderConfigPoliciesTestInvoicingPolicy extends Policy +{ + protected string $key = 'billing.invoicing'; + protected string $label = 'Invoicing'; + protected string $description = 'Send an invoice when the order completes.'; + protected array $defaults = ['auto_send' => false, 'note' => null, 'due_days' => 14]; + protected array $rules = ['note' => ['nullable', 'string'], 'due_days' => ['nullable', 'integer']]; +} + +function orderConfigPoliciesSetting(string $key, string $name): ?array +{ + $policy = collect(OrderConfigPolicies::describe())->firstWhere('key', $key); + + return collect($policy['settings'] ?? [])->firstWhere('name', $name); +} + +test('every policy has defaults: nothing a config does not ask for is switched on', function () { + expect(OrderConfigPolicies::defaults())->toBe([ + 'dispatch' => [ + 'adhoc' => ['customer_orders' => false, 'strategy' => null, 'offer_timeout' => null, 'radius' => null, 'on_exhausted' => 'keep_open'], + 'matching' => ['vehicle_type' => false, 'exclude_busy_drivers' => false], + ], + 'customer' => [ + 'ordering' => ['payment_methods' => [], 'require_quote' => false, 'require_settlement' => []], + 'cancellation' => ['enabled' => true, 'allowed_until' => null], + 'interactions' => ['chat' => false, 'rating' => false, 'share_tracking' => false], + ], + 'pricing' => ['reprice_on_completion' => false, 'metering_starts_at' => null], + ]) + ->and(array_keys(OrderConfigPolicies::all()))->toBe(['dispatch.adhoc', 'dispatch.matching', 'customer.ordering', 'customer.cancellation', 'customer.interactions', 'pricing']) + ->and(OrderConfigPolicies::get('pricing')->label())->toBe('Pricing') + ->and(OrderConfigPolicies::get('nope'))->toBeNull(); +}); + +test('resolving stored policies fills in each missing setting and keeps policies nobody registered', function () { + $resolved = OrderConfigPolicies::resolve([ + 'dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'on_exhausted' => 'cancel']], + 'pricing' => 'not a policy', + 'billing' => ['invoicing' => ['auto_send' => true]], + ]); + + expect(OrderConfigPolicies::resolve(null))->toBe(OrderConfigPolicies::defaults()) + ->and(OrderConfigPolicies::resolve([]))->toBe(OrderConfigPolicies::defaults()) + ->and($resolved['dispatch']['adhoc'])->toBe(['customer_orders' => false, 'strategy' => 'broadcast', 'offer_timeout' => null, 'radius' => null, 'on_exhausted' => 'cancel']) + ->and($resolved['dispatch']['matching'])->toBe(['vehicle_type' => false, 'exclude_busy_drivers' => false]) + ->and($resolved['pricing'])->toBe(['reprice_on_completion' => false, 'metering_starts_at' => null]) + ->and($resolved['billing'])->toBe(['invoicing' => ['auto_send' => true]]); +}); + +test('validation rules sit under the prefix, one set per policy and per setting', function () { + $rules = OrderConfigPolicies::rules(); + $custom = OrderConfigPolicies::rules('config.policies'); + + expect($rules['policies'])->toBe(['nullable', 'array']) + ->and($rules['policies.dispatch.adhoc'])->toBe(['nullable', 'array']) + ->and($rules['policies.dispatch.adhoc.customer_orders'])->toBe(['nullable', 'boolean']) + ->and($rules['policies.dispatch.adhoc.offer_timeout'])->toBe(['nullable', 'integer', 'min:10', 'max:120']) + ->and($rules['policies.customer.ordering.payment_methods.*'])->toBe(['string', 'max:32']) + ->and((string) $rules['policies.dispatch.adhoc.on_exhausted'][1])->toBe('in:keep_open,cancel') + ->and((string) $rules['policies.dispatch.adhoc.strategy'][2])->toContain('sequential', 'broadcast') + ->and($rules['policies.pricing.metering_starts_at'])->toBe(['nullable', 'string', 'max:64']) + ->and(array_keys($custom))->toContain('config.policies', 'config.policies.customer.interactions.chat') + ->and(array_filter(array_keys($custom), fn ($key) => !str_starts_with($key, 'config.policies')))->toBe([]); +}); + +test('policies describe each setting\'s type, default and choices for people configuring them', function () { + $adhoc = collect(OrderConfigPolicies::describe())->firstWhere('key', 'dispatch.adhoc'); + + expect($adhoc['label'])->toBe('Adhoc dispatch') + ->and($adhoc['defaults']['on_exhausted'])->toBe('keep_open') + ->and(array_column($adhoc['settings'], 'type', 'name'))->toBe([ + 'customer_orders' => 'boolean', + 'strategy' => 'choice', + 'offer_timeout' => 'number', + 'radius' => 'number', + 'on_exhausted' => 'choice', + ]) + ->and(array_column(orderConfigPoliciesSetting('dispatch.adhoc', 'strategy')['choices'], 'value'))->toContain('sequential', 'broadcast') + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'on_exhausted')['choices'])->toBe([ + ['value' => 'keep_open', 'label' => 'Keep the order open for the operator'], + ['value' => 'cancel', 'label' => 'Cancel the order'], + ]) + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'customer_orders'))->toBe(['name' => 'customer_orders', 'type' => 'boolean', 'default' => false, 'choices' => null]) + // Numbers carry the range their rules allow. + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'offer_timeout'))->toMatchArray(['type' => 'number', 'min' => 10, 'max' => 120]) + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'radius'))->toMatchArray(['min' => 100, 'max' => 200000]) + ->and(orderConfigPoliciesSetting('customer.ordering', 'payment_methods')['type'])->toBe('list') + ->and(orderConfigPoliciesSetting('customer.ordering', 'require_settlement')['type'])->toBe('list') + // An activity setting is a choice among the config's own activities. + ->and(orderConfigPoliciesSetting('customer.cancellation', 'allowed_until'))->toBe(['name' => 'allowed_until', 'type' => 'choice', 'default' => null, 'choices' => 'activity']) + ->and(orderConfigPoliciesSetting('pricing', 'metering_starts_at')['choices'])->toBe('activity'); +}); + +test('a config\'s policy reads one setting or a whole policy, with defaults and a fallback', function () { + $config = new OrderConfig(['policies' => ['dispatch' => ['adhoc' => ['strategy' => 'broadcast']]]]); + $empty = new OrderConfig(); + + expect($config->policy('dispatch.adhoc.strategy'))->toBe('broadcast') + ->and($config->policy('dispatch.adhoc.on_exhausted'))->toBe('keep_open') + ->and($config->policy('dispatch.matching'))->toBe(['vehicle_type' => false, 'exclude_busy_drivers' => false]) + ->and($config->policy('dispatch.adhoc.offer_timeout', 30))->toBe(30) + ->and($config->policy('nothing.here', 'fallback'))->toBe('fallback') + ->and($empty->resolvedPolicies())->toBe(OrderConfigPolicies::defaults()) + ->and($empty->policy('customer.interactions.chat'))->toBeFalse(); +}); + +test('a config drops an adhoc strategy that is not registered and keeps the offer timeout in range', function () { + $normalized = function (?array $policies) { + $config = new OrderConfig(); + $config->policies = $policies; + $config->normalizePolicies(); + + return $config->policies; + }; + + expect($normalized(['dispatch' => ['adhoc' => ['strategy' => 'lottery', 'offer_timeout' => 900]]]))->toBe(['dispatch' => ['adhoc' => ['strategy' => null, 'offer_timeout' => 120]]]) + ->and($normalized(['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => '3']]]))->toBe(['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => 10]]]) + ->and($normalized(['dispatch' => ['adhoc' => ['offer_timeout' => '']]]))->toBe(['dispatch' => ['adhoc' => ['offer_timeout' => '']]]) + ->and($normalized(['pricing' => ['reprice_on_completion' => true]]))->toBe(['pricing' => ['reprice_on_completion' => true]]) + ->and($normalized(null))->toBeNull(); +}); + +test('extensions register their own policies, and only real policies', function () { + OrderConfigPolicies::register(OrderConfigPoliciesTestInvoicingPolicy::class); + + expect(OrderConfigPolicies::get('billing.invoicing'))->toBeInstanceOf(OrderConfigPoliciesTestInvoicingPolicy::class) + ->and(OrderConfigPolicies::defaults()['billing']['invoicing'])->toBe(['auto_send' => false, 'note' => null, 'due_days' => 14]) + ->and(OrderConfigPolicies::resolve([])['billing']['invoicing']['due_days'])->toBe(14) + ->and(OrderConfigPolicies::rules()['policies.billing.invoicing.due_days'])->toBe(['nullable', 'integer']) + ->and(orderConfigPoliciesSetting('billing.invoicing', 'auto_send')['type'])->toBe('boolean') + ->and(orderConfigPoliciesSetting('billing.invoicing', 'note')['type'])->toBe('text') + ->and(orderConfigPoliciesSetting('billing.invoicing', 'due_days')['type'])->toBe('number') + ->and(fn () => OrderConfigPolicies::register(stdClass::class))->toThrow(InvalidArgumentException::class); +}); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php new file mode 100644 index 000000000..e084338e3 --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php @@ -0,0 +1,216 @@ + $code, + 'code' => $code, + 'color' => '#1f2937', + 'logic' => [], + 'events' => [], + 'status' => $status, + 'actions' => [], + 'details' => $details, + 'options' => [], + 'complete' => $complete, + 'entities' => [], + 'sequence' => 0, + 'activities' => $next, + 'pod_method' => 'scan', + 'require_pod' => false, + ]; +} + +/** The flow without the generated `internalId` of each activity. */ +function orderConfigTemplatesFlow(array $flow): array +{ + return array_map(fn ($activity) => Arr::except($activity, 'internalId'), $flow); +} + +test('the registry describes its templates and refuses unknown ones', function () { + expect(OrderConfigTemplates::describe())->toBe([ + [ + 'key' => 'transport', + 'name' => 'Transport', + 'description' => 'Default order configuration for transport', + 'steps' => ['Order Created', 'Order Dispatched', 'Order Started', 'Driver Enroute', 'Order Completed'], + 'summary' => ['steps' => 5, 'policies' => 0, 'triggers' => 0, 'custom_fields' => 0], + ], + [ + 'key' => 'passenger', + 'name' => 'Passenger', + 'description' => (new PassengerTemplate())->description(), + 'steps' => ['Trip requested', 'Finding a driver', 'Driver on the way', 'Driver has arrived', 'Trip in progress', 'Trip completed'], + 'summary' => ['steps' => count((new PassengerTemplate())->attributes()['flow']), 'policies' => 6, 'triggers' => count((new PassengerTemplate())->attributes()['triggers']) + array_sum(array_map(fn ($activity) => count($activity['actions']), (new PassengerTemplate())->attributes()['flow'])), 'custom_fields' => count((new PassengerTemplate())->customFields())], + ], + ]) + ->and(OrderConfigTemplates::has('passenger'))->toBeTrue() + ->and(OrderConfigTemplates::has('limousine'))->toBeFalse() + ->and(OrderConfigTemplates::has(null))->toBeFalse() + ->and(OrderConfigTemplates::get('transport'))->toBeInstanceOf(TransportTemplate::class) + ->and(OrderConfigTemplates::get('limousine'))->toBeNull() + ->and(fn () => OrderConfigTemplates::attributes('limousine'))->toThrow(InvalidArgumentException::class) + ->and(fn () => OrderConfigTemplates::register(stdClass::class))->toThrow(InvalidArgumentException::class); +}); + +test('the transport template is the default transport config it replaced', function () { + $attributes = OrderConfigTemplates::attributes('transport'); + + expect(Arr::except($attributes, 'flow'))->toBe([ + 'name' => 'Transport', + 'key' => 'transport', + 'namespace' => 'system:order-config:transport', + 'core_service' => 1, + 'status' => 'private', + 'version' => '0.0.1', + 'description' => 'Default order configuration for transport', + 'tags' => ['transport', 'delivery'], + 'entities' => [], + 'meta' => [], + ]) + ->and(array_keys($attributes['flow']))->toBe(['created', 'enroute', 'started', 'completed', 'dispatched']) + ->and(orderConfigTemplatesFlow($attributes['flow']))->toBe([ + 'created' => orderConfigTemplatesActivity('created', 'Order Created', 'New order was created.', ['dispatched']), + 'enroute' => orderConfigTemplatesActivity('enroute', 'Driver Enroute', 'Driver is en-route.', ['completed']), + 'started' => orderConfigTemplatesActivity('started', 'Order Started', 'Order has been started', ['enroute']), + 'completed' => orderConfigTemplatesActivity('completed', 'Order Completed', 'Order has been completed.', [], true), + 'dispatched' => orderConfigTemplatesActivity('dispatched', 'Order Dispatched', 'Order has been dispatched.', ['started']), + ]) + ->and(collect($attributes['flow'])->every(fn ($activity) => Str::isUuid($activity['internalId'])))->toBeTrue() + ->and((new TransportTemplate())->customFields())->toBe([]); +}); + +test('the passenger template is a strict flow ending in completed, canceled or no-show', function () { + $attributes = OrderConfigTemplates::attributes('passenger'); + $flow = $attributes['flow']; + + expect(Arr::only($attributes, ['name', 'key', 'namespace', 'core_service', 'status', 'version', 'tags', 'entities']))->toBe([ + 'name' => 'Passenger', + 'key' => 'passenger', + 'namespace' => 'system:order-config:passenger', + 'core_service' => 1, + 'status' => 'private', + 'version' => '0.0.1', + 'tags' => ['passenger', 'on-demand'], + 'entities' => [], + ]) + ->and($attributes['meta'])->toBe(['lifecycle' => ['initial' => 'created', 'completed' => 'completed', 'canceled' => 'canceled', 'terminal' => ['no_show'], 'strict_transitions' => true]]) + ->and(array_map(fn ($activity) => $activity['activities'], $flow))->toBe([ + 'created' => ['dispatched'], + 'dispatched' => ['started'], + 'started' => ['arrived'], + 'arrived' => ['in_progress', 'no_show'], + 'in_progress' => ['completed'], + 'completed' => [], + 'no_show' => [], + ]) + ->and(array_keys(array_filter($flow, fn ($activity) => $activity['complete'])))->toBe(['completed']) + ->and(array_map(fn ($activity) => array_column($activity['actions'], 'action'), $flow))->toBe([ + 'created' => [], + 'dispatched' => [], + 'started' => ['notify_customer', 'open_chat'], + 'arrived' => ['notify_customer'], + 'in_progress' => ['notify_customer'], + 'completed' => ['notify_customer', 'close_chat', 'send_invoice'], + 'no_show' => ['close_chat'], + ]) + ->and($flow['started']['actions'][0]['params'])->toBe(['title' => 'Your driver is on the way', 'message' => '{driver.first_name} accepted your trip.']); +}); + +test('the passenger template\'s policies offer orders one driver at a time, by vehicle type, and price them from the trip', function () { + $policies = OrderConfigTemplates::attributes('passenger')['policies']; + + expect($policies)->toBe([ + 'dispatch' => [ + 'adhoc' => ['customer_orders' => true, 'strategy' => 'sequential', 'offer_timeout' => 20, 'on_exhausted' => 'cancel'], + 'matching' => ['vehicle_type' => true, 'exclude_busy_drivers' => true], + ], + 'customer' => [ + 'ordering' => ['payment_methods' => ['cash', 'card'], 'require_quote' => true, 'require_settlement' => ['card']], + 'cancellation' => ['enabled' => true, 'allowed_until' => 'in_progress'], + 'interactions' => ['chat' => true, 'rating' => true, 'share_tracking' => true], + ], + 'pricing' => ['reprice_on_completion' => true, 'metering_starts_at' => 'in_progress'], + ]) + // Every setting it leaves out takes the policy's default. + ->and(OrderConfigPolicies::resolve($policies)['dispatch']['adhoc']['radius'])->toBeNull() + ->and(array_keys(OrderConfigPolicies::resolve($policies)))->toBe(['dispatch', 'customer', 'pricing']); +}); + +test('the passenger template\'s triggers tell the customer as the driver nears the pickup, when nobody is found, and when canceled', function () { + $triggers = OrderConfigTemplates::attributes('passenger')['triggers']; + + expect(array_column($triggers, 'event'))->toBe(['driver.approaching', 'dispatch.offer_exhausted', 'order.canceled', 'order.canceled']) + ->and(array_column($triggers, 'action'))->toBe(['notify_customer', 'notify_customer', 'notify_customer', 'close_chat']) + ->and($triggers[0]['options'])->toBe(['target' => 'pickup', 'distance' => 400]) + ->and($triggers[0]['when'])->toBe([['type' => 'and', 'conditions' => [['field' => 'status', 'operator' => 'equal', 'value' => 'started']]]]) + ->and($triggers[0]['params'])->toBe(['title' => 'Your driver is almost there', 'message' => '{driver.first_name} is about a minute away.']) + ->and($triggers[1]['params']['title'])->toBe('No driver found') + // The cancellation notice is skipped when the customer was already told nobody was found. + ->and($triggers[2]['when'])->toBe([['type' => 'and', 'conditions' => [['field' => 'dispatch_outcome', 'operator' => 'notEqual', 'value' => 'no_driver_found']]]]); +}); + +test('the passenger template asks how many people are travelling', function () { + expect((new PassengerTemplate())->customFields())->toBe([[ + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'default_value' => '1', + 'required' => false, + 'editable' => true, + 'validation_rules' => ['nullable', 'integer', 'min:1', 'max:50'], + 'help_text' => 'How many people are travelling.', + 'order' => 0, + ]]); +}); + +/** A template an extension might add. */ +class OrderConfigTemplatesFreightTemplate extends Fleetbase\FleetOps\Support\OrderConfig\Templates\Template +{ + protected string $key = 'freight'; + protected string $name = 'Freight'; + protected string $description = 'Pallets, picked up and delivered.'; + + public function attributes(): array + { + return ['tags' => ['freight'], 'flow' => ['created' => static::activity('created', 'Order Created', 'New order was created.')]]; + } +} + +test('extensions register their own templates by key, and an unknown template makes no config', function () { + $registry = new ReflectionProperty(OrderConfigTemplates::class, 'templates'); + $before = $registry->getValue(); + + try { + OrderConfigTemplates::register(OrderConfigTemplatesFreightTemplate::class); + + expect(OrderConfigTemplates::has('freight'))->toBeTrue() + ->and(OrderConfigTemplates::get('freight'))->toBeInstanceOf(OrderConfigTemplatesFreightTemplate::class) + ->and(array_column(OrderConfigTemplates::describe(), 'key'))->toBe(['transport', 'passenger', 'freight']) + ->and(Arr::only(OrderConfigTemplates::attributes('freight'), ['name', 'key', 'namespace', 'tags']))->toBe([ + 'name' => 'Freight', + 'key' => 'freight', + 'namespace' => 'system:order-config:freight', + 'tags' => ['freight'], + ]); + } finally { + $registry->setValue(null, $before); + } + + // Refused before any config is looked up or made. + expect(fn () => OrderConfigTemplates::create('limousine', new Fleetbase\Models\Company()))->toThrow(InvalidArgumentException::class, 'No order config template named limousine.') + ->and(OrderConfigTemplates::has('freight'))->toBeFalse(); +}); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigTriggersTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigTriggersTest.php new file mode 100644 index 000000000..5ea7256e6 --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigTriggersTest.php @@ -0,0 +1,244 @@ + 'Anything.']; + + public function handle(Order $order, array $params = [], array $context = []): void + { + OrderConfigTriggersTestRecorder::$ran[] = [$order->uuid, $params, $context]; + } +} + +class OrderConfigTriggersTestFailingAction extends Action +{ + protected string $name = 'explode'; + protected string $label = 'Explode'; + protected string $description = 'Always fails.'; + + public function handle(Order $order, array $params = [], array $context = []): void + { + throw new RuntimeException('boom'); + } +} + +function orderConfigTriggersBoot(): void +{ + app()->instance('log', new class { + public array $warnings = []; + + public function warning($message, array $context = []) + { + $this->warnings[] = $message; + } + + public function __call($method, $arguments) + { + return null; + } + }); + Illuminate\Support\Facades\Log::clearResolvedInstance('log'); + + OrderConfigActions::register(OrderConfigTriggersTestAction::class); + OrderConfigActions::register(OrderConfigTriggersTestFailingAction::class); + OrderConfigTriggers::$runImmediately = true; + OrderConfigTriggersTestRecorder::$ran = []; + OrderConfigTriggersTestRecorder::$queued = []; +} + +/** An order with its config already loaded, so triggers are read without a database. */ +function orderConfigTriggersOrder(array $triggers, array $attributes = []): Order +{ + $config = new OrderConfig(['triggers' => $triggers]); + $config->setAttribute('uuid', 'config-1'); + + $order = new Order(); + $order->setRawAttributes(array_merge(['uuid' => 'order-1', 'public_id' => 'order_one', 'order_config_uuid' => 'config-1', 'status' => 'started'], $attributes), true); + $order->setRelation('orderConfig', $config); + + return $order; +} + +function orderConfigTriggersStatusIs(string $status): array +{ + return [['type' => 'and', 'conditions' => [['field' => 'status', 'operator' => 'equal', 'value' => $status]]]]; +} + +test('an event runs the config\'s registered actions for that event, with their params and the event', function () { + orderConfigTriggersBoot(); + $order = orderConfigTriggersOrder([ + ['event' => OrderConfigTriggers::ORDER_COMPLETED, 'action' => 'record', 'params' => ['note' => 'first']], + ['event' => OrderConfigTriggers::ORDER_COMPLETED, 'action' => 'send_invoice'], + ['event' => OrderConfigTriggers::ORDER_COMPLETED, 'action' => 'record', 'params' => 'not a list'], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record'], + ['event' => OrderConfigTriggers::ORDER_COMPLETED], + 'not a trigger', + ]); + + $ran = OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_COMPLETED, ['source' => 'test']); + + expect($ran)->toBe(2) + ->and(OrderConfigTriggersTestRecorder::$ran)->toBe([ + ['order-1', ['note' => 'first'], ['event' => 'order.completed', 'source' => 'test']], + ['order-1', [], ['event' => 'order.completed', 'source' => 'test']], + ]) + ->and(OrderConfigTriggers::forEvent($order, OrderConfigTriggers::ORDER_CANCELED))->toHaveCount(1) + ->and(OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED))->toBe(0) + ->and(OrderConfigTriggers::EVENTS)->toBe(['order.created', 'order.completed', 'order.canceled', 'dispatch.offer_exhausted', 'driver.approaching']); +}); + +test('a trigger runs only when every one of its conditions passes', function () { + orderConfigTriggersBoot(); + $triggers = [ + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'while started'], 'when' => orderConfigTriggersStatusIs('started')], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'while arrived'], 'when' => orderConfigTriggersStatusIs('arrived')], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'both'], 'when' => [...orderConfigTriggersStatusIs('started'), ...orderConfigTriggersStatusIs('arrived')]], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'unreadable'], 'when' => [['type' => 'sometimes', 'conditions' => []]]], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'empty'], 'when' => []], + ]; + + $ran = OrderConfigTriggers::fire(orderConfigTriggersOrder($triggers), OrderConfigTriggers::ORDER_CANCELED); + + expect($ran)->toBe(2) + ->and(array_column(array_column(OrderConfigTriggersTestRecorder::$ran, 1), 'note'))->toBe(['while started', 'empty']) + ->and(app('log')->warnings)->toContain('Skipped an order config trigger whose conditions could not be read') + ->and(OrderConfigTriggers::passes(orderConfigTriggersOrder([]), ['when' => 'not a list']))->toBeTrue(); +}); + +test('reaching an activity runs that activity\'s actions, with the activity in their context', function () { + orderConfigTriggersBoot(); + $order = orderConfigTriggersOrder([]); + $activity = [ + 'code' => 'arrived', + 'status' => 'Driver has arrived', + 'details' => 'Waiting at the pickup.', + 'actions' => [['action' => 'record', 'params' => ['note' => 'arrived']], ['action' => 'record', 'when' => orderConfigTriggersStatusIs('completed')]], + ]; + + expect(OrderConfigTriggers::activity($order, $activity))->toBe(1) + ->and(OrderConfigTriggersTestRecorder::$ran)->toBe([ + ['order-1', ['note' => 'arrived'], ['event' => 'order.activity', 'activity' => ['code' => 'arrived', 'status' => 'Driver has arrived', 'details' => 'Waiting at the pickup.']]], + ]) + ->and(OrderConfigTriggers::activity($order, null))->toBe(0) + ->and(OrderConfigTriggers::activity($order, new Fleetbase\FleetOps\Flow\Activity(['code' => 'quiet'])))->toBe(0); +}); + +test('an order without a config of its own runs no triggers', function () { + orderConfigTriggersBoot(); + $order = new Order(); + $order->setRawAttributes(['uuid' => 'order-2', 'order_config_uuid' => null, 'status' => 'completed'], true); + + expect($order->currentConfig())->toBeNull() + ->and(OrderConfigTriggers::forEvent($order, OrderConfigTriggers::ORDER_COMPLETED))->toBe([]) + ->and(OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_COMPLETED))->toBe(0) + ->and(OrderConfigTriggers::driverMoved(new Driver(), $order))->toBe(0) + ->and(OrderConfigTriggers::driverMoved(new Driver(), null))->toBe(0); +}); + +test('actions are queued unless asked to run now, and a failing action is logged and not counted', function () { + orderConfigTriggersBoot(); + $order = orderConfigTriggersOrder([ + ['event' => OrderConfigTriggers::ORDER_CREATED, 'action' => 'record', 'params' => ['note' => 'later']], + ['event' => OrderConfigTriggers::ORDER_CREATED, 'action' => 'explode'], + ]); + + $failed = OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED); + + OrderConfigTriggers::$runImmediately = false; + $queued = OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED); + OrderConfigTriggers::$runImmediately = true; + $job = OrderConfigTriggersTestRecorder::$queued[0]; + + expect($failed)->toBe(1) + ->and(app('log')->warnings)->toBe(['An order config action failed']) + ->and($queued)->toBe(2) + ->and(OrderConfigTriggersTestRecorder::$queued)->toHaveCount(2) + ->and($job)->toBeInstanceOf(RunOrderConfigAction::class) + ->and([$job->orderUuid, $job->action, $job->params, $job->context])->toBe(['order-1', 'record', ['note' => 'later'], ['event' => 'order.created']]) + ->and(OrderConfigTriggersTestRecorder::$queued[1]->action)->toBe('explode') + ->and(OrderConfigTriggersTestRecorder::$ran)->toHaveCount(1); +}); + +test('the action registry lists the built-in actions and takes only real actions', function () { + orderConfigTriggersBoot(); + $described = collect(OrderConfigActions::describe())->keyBy('name'); + + expect(OrderConfigActions::names())->toContain('notify_customer', 'notify_driver', 'open_chat', 'close_chat', 'set_meta', 'cancel', 'record') + ->and(OrderConfigActions::has('notify_customer'))->toBeTrue() + ->and(OrderConfigActions::has('send_invoice'))->toBeFalse() + ->and(OrderConfigActions::has(null))->toBeFalse() + ->and(OrderConfigActions::get('send_invoice'))->toBeNull() + ->and(OrderConfigActions::get('record'))->toBeInstanceOf(OrderConfigTriggersTestAction::class) + ->and($described['notify_customer']['label'])->toBe('Notify customer') + ->and(array_keys($described['notify_customer']['parameters']))->toBe(['title', 'message']) + ->and(array_keys($described['set_meta']['parameters']))->toBe(['key', 'value']) + ->and($described['record'])->toBe(['name' => 'record', 'label' => 'Record', 'description' => 'Records that it ran.', 'parameters' => ['note' => 'Anything.']]) + ->and(fn () => OrderConfigActions::register(stdClass::class))->toThrow(InvalidArgumentException::class); +}); + +test('placeholders are filled from the order, its driver, customer and the activity', function () { + $order = new Order(); + $order->setRawAttributes(['uuid' => 'order-1', 'public_id' => 'order_one', 'status' => 'arrived'], true); + $order->setRelation('driverAssigned', new class extends Driver { + public function getNameAttribute() + { + return 'Chen Wei Tan'; + } + }); + $customer = new Contact(); + $customer->setRawAttributes(['name' => 'Sam Lee'], true); + $order->setRelation('customer', $customer); + $tracking = new TrackingNumber(); + $tracking->setRawAttributes(['tracking_number' => 'TRK1'], true); + $order->setRelation('trackingNumber', $tracking); + $context = ['activity' => ['status' => 'Driver has arrived', 'details' => 'Waiting.']]; + + $everything = Action::render('{driver.name}|{driver.first_name}|{customer.name}|{order.id}|{order.tracking_number}|{order.status}|{activity.status}|{activity.details}', $order, $context); + + $nobody = new Order(); + $nobody->setRawAttributes(['public_id' => 'order_two', 'driver_assigned_uuid' => null], true); + $nobody->setRelation('driverAssigned', null); + $nobody->setRelation('customer', null); + $nobody->setRelation('trackingNumber', null); + + expect($everything)->toBe('Chen Wei Tan|Chen|Sam Lee|order_one|TRK1|arrived|Driver has arrived|Waiting.') + ->and(Action::render('{ Driver.First_Name } is here', $order))->toBe('Chen is here') + ->and(Action::render('Hello {unknown.thing} there {activity.status}', $order))->toBe('Hello there') + ->and(Action::render(null, $order))->toBe('') + ->and(Action::render('', $order))->toBe('') + ->and(Action::render('{driver.first_name} accepted {order.id} for {customer.name}{order.tracking_number}', $nobody))->toBe('accepted order_two for') + ->and(Action::driverName($nobody))->toBeNull(); + + // Without the relation loaded and no driver assigned, nothing is looked up. + $unassigned = new Order(); + $unassigned->setRawAttributes(['driver_assigned_uuid' => null], true); + expect(Action::driverName($unassigned))->toBeNull(); +}); diff --git a/server/tests/Unit/Support/QuerySeamsTest.php b/server/tests/Unit/Support/QuerySeamsTest.php index 45dad48e8..fc8801da4 100644 --- a/server/tests/Unit/Support/QuerySeamsTest.php +++ b/server/tests/Unit/Support/QuerySeamsTest.php @@ -178,8 +178,7 @@ function fleetopsQuerySeamInvoke(object $instance, string $class, string $method $class = Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class; // The order query is bound to the named connection - expect(fleetopsQuerySeamInvoke($command, $class, 'newOrderQuery', ['mysql'])->get()->pluck('uuid')->all())->toBe(['order-adhoc-1']) - ->and(fleetopsQuerySeamInvoke($command, $class, 'newDriverQuery')->get()->pluck('uuid')->all())->toBe(['driver-adhoc-1']); + expect(fleetopsQuerySeamInvoke($command, $class, 'newOrderQuery', ['mysql'])->get()->pluck('uuid')->all())->toBe(['order-adhoc-1']); }); test('order finalization job seams resolve records and fire the ready event', function () { @@ -292,22 +291,20 @@ public function __call($method, $arguments) }); $connection->table('drivers')->insert([ // Online and in the order's company - ['uuid' => 'driver-near-1', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '1'], + ['uuid' => 'driver-near-1', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '1', 'status' => 'available'], // Online but another company - ['uuid' => 'driver-near-2', 'company_uuid' => 'company-other', 'user_uuid' => 'user-adhoc-b', 'online' => '1'], + ['uuid' => 'driver-near-2', 'company_uuid' => 'company-other', 'user_uuid' => 'user-adhoc-b', 'online' => '1', 'status' => 'available'], // Right company but offline - ['uuid' => 'driver-near-3', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '0'], + ['uuid' => 'driver-near-3', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '0', 'status' => 'available'], ]); $order = new Fleetbase\FleetOps\Models\Order(); $order->setRawAttributes(['uuid' => 'order-adhoc-near', 'company_uuid' => 'company-seam-1'], true); - $class = Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class; - $command = (new ReflectionClass($class))->newInstanceWithoutConstructor(); $pickup = new Fleetbase\LaravelMysqlSpatial\Types\Point(1.30, 103.80); // In testing mode the spatial predicates are skipped so the company and // online filters can be asserted on their own - $drivers = $command->getNearbyDriversForOrder($order, $pickup, 5000, true); + $drivers = Fleetbase\FleetOps\Support\DriverMatching::nearby($order, $pickup, true)->get(); expect($drivers->pluck('uuid')->all())->toBe(['driver-near-1']); }); diff --git a/server/tests/Unit/Support/SocketChannelsTest.php b/server/tests/Unit/Support/SocketChannelsTest.php index 25243e3b9..a2c99dda2 100644 --- a/server/tests/Unit/Support/SocketChannelsTest.php +++ b/server/tests/Unit/Support/SocketChannelsTest.php @@ -292,7 +292,7 @@ function socketChannelsCustomer(): SocketPrincipal expect(socketChannelsAllows($walker, 'vehicle.vehicles-a'))->toBeFalse(); }); -test('a customer reaches their own orders and the driver and vehicle of their active orders', function () { +test('a customer reaches their own orders and the vehicle of their active orders, never a driver', function () { socketChannelsBoot(); $customer = socketChannelsCustomer(); @@ -302,10 +302,10 @@ function socketChannelsCustomer(): SocketPrincipal ->and(socketChannelsAllows($customer, 'order.order-a2'))->toBeFalse() ->and(socketChannelsAllows($customer, 'order.orders-b'))->toBeFalse(); - // driver-a1 drives an active order of theirs; driver-a2 only a completed one. - expect(socketChannelsAllows($customer, 'driver.driver-a1'))->toBeTrue() - ->and(socketChannelsAllows($customer, 'driverAssigned.driver_a1'))->toBeTrue() - ->and(socketChannelsAllows($customer, 'driver.driver-a3'))->toBeTrue() + // Not even the driver of an active order of theirs: driver events carry the driver's phone. + expect(socketChannelsAllows($customer, 'driver.driver-a1'))->toBeFalse() + ->and(socketChannelsAllows($customer, 'driverAssigned.driver_a1'))->toBeFalse() + ->and(socketChannelsAllows($customer, 'driver.driver-a3'))->toBeFalse() ->and(socketChannelsAllows($customer, 'driver.driver-a2'))->toBeFalse(); // vehicle-a1 is assigned to an active order; vehicle-a3 is driven by an active order's driver. @@ -379,6 +379,39 @@ function socketChannelsCustomer(): SocketPrincipal expect(SocketChannels::driverPrincipal($request, $homeless))->toBeNull(); }); +test('a customer token gets the customer principal limited to their own records', function () { + socketChannelsBoot(); + $request = Request::create('/v1/socket/token', 'POST'); + $customer = new User(); + $customer->setRawAttributes(['uuid' => 'user-rider-a', 'company_uuid' => 'company-a', 'type' => 'customer'], true); + Fleetbase\FleetOps\Models\Contact::query()->insert(['uuid' => 'contact-rider-a', 'public_id' => 'contact_ridera', 'company_uuid' => 'company-a', 'user_uuid' => 'user-rider-a', 'type' => 'customer']); + + session(['company' => 'company-a']); + $principal = SocketChannels::customerPrincipal($request, $customer); + + expect($principal)->toBeInstanceOf(SocketPrincipal::class) + ->and($principal->kind)->toBe('customer') + ->and($principal->sub)->toBe('contact-rider-a') + ->and($principal->ids)->toBe(['contact-rider-a', 'contact_ridera', 'user-rider-a']) + ->and($principal->cid)->toBe('company-a') + ->and($principal->cpid)->toBe('company_a') + ->and($principal->adm)->toBeFalse(); + + // Another company's rider, an office user and a stranger object: no claim. + session(['company' => 'company-b']); + expect(SocketChannels::customerPrincipal($request, $customer))->toBeNull(); + + session(['company' => 'company-a']); + expect(SocketChannels::customerPrincipal($request, User::where('uuid', 'user-office-a')->first()))->toBeNull() + ->and(SocketChannels::customerPrincipal($request, (object) ['uuid' => 'user-rider-a']))->toBeNull() + ->and(SocketChannels::customerPrincipal($request, null))->toBeNull(); + + session(['company' => null]); + $homeless = new User(); + $homeless->setRawAttributes(['uuid' => 'user-rider-a', 'company_uuid' => null, 'type' => 'customer'], true); + expect(SocketChannels::customerPrincipal($request, $homeless))->toBeNull(); +}); + test('the service provider registers the fleetops channels when the registry is built', function () { socketChannelsBoot(); app()->forgetInstance(SocketChannelRegistry::class); diff --git a/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php b/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php index 50b4ce66b..807f3ebfe 100644 --- a/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php +++ b/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php @@ -196,7 +196,8 @@ function fleetopsTrackingSeedOrder(SQLiteConnection $connection, bool $withDrive ->and($context->stops)->toHaveCount(2) ->and($context->remainingStops)->toHaveCount(2) ->and($context->activeStop)->not->toBeNull() - ->and($context->warnings)->toContain('stale_driver_location'); + ->and($context->warnings)->toContain('stale_driver_location') + ->and($context->driverLocationAgeSeconds)->toBeInt()->toBeGreaterThanOrEqual(3600); }); test('context builder falls back to payload origin without a driver', function () { diff --git a/server/tests/UtilsContractsTest.php b/server/tests/UtilsContractsTest.php index 660e190c7..94d5e674d 100644 --- a/server/tests/UtilsContractsTest.php +++ b/server/tests/UtilsContractsTest.php @@ -10,7 +10,7 @@ function fleetOpsUtilsExpressionValue(Expression $expression): string { - return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar()) : (string) $expression; + return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar(new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')))) : (string) $expression; } test('utility coordinate validators accept only finite coordinate ranges', function () { diff --git a/tests/unit/controllers/settings/dispatch-test.js b/tests/unit/controllers/settings/dispatch-test.js new file mode 100644 index 000000000..02ac5249f --- /dev/null +++ b/tests/unit/controllers/settings/dispatch-test.js @@ -0,0 +1,100 @@ +import { module, test } from 'qunit'; +import { setupTest } from 'dummy/tests/helpers'; +import Service from '@ember/service'; + +const STRATEGIES = [ + { name: 'broadcast', label: 'Everyone nearby at once', description: 'Every nearby driver at once.' }, + { name: 'sequential', label: 'One driver at a time', description: 'The nearest driver first.' }, +]; + +module('Unit | Controller | settings/dispatch', function (hooks) { + setupTest(hooks); + + hooks.beforeEach(function () { + const calls = (this.calls = []); + this.owner.register( + 'service:fetch', + class extends Service { + get(url) { + calls.push(['get', url]); + return Promise.resolve({ adhoc_distance: 5000, adhoc_strategy: 'sequential', adhoc_offer_timeout: 25, strategies: STRATEGIES }); + } + + post(url, body) { + calls.push(['post', url, body]); + return Promise.resolve({ status: 'ok' }); + } + } + ); + const notified = (this.notified = []); + this.owner.register( + 'service:notifications', + class extends Service { + success(message) { + notified.push(['success', message]); + } + + serverError(error) { + notified.push(['error', error]); + } + } + ); + }); + + test('it loads the company defaults and the strategies to choose from', async function (assert) { + const controller = this.owner.lookup('controller:settings/dispatch'); + await controller.getSettings.last; + + assert.strictEqual(controller.adhocDistance, 5000); + assert.strictEqual(controller.adhocStrategy, 'sequential'); + assert.strictEqual(controller.adhocOfferTimeout, 25); + assert.strictEqual(controller.selectedStrategy.label, 'One driver at a time'); + assert.true(controller.usesOfferTimeout); + + controller.adhocStrategy = 'broadcast'; + assert.false(controller.usesOfferTimeout, 'everyone at once has no offer time'); + }); + + test('it saves the settings as numbers', async function (assert) { + const controller = this.owner.lookup('controller:settings/dispatch'); + await controller.getSettings.last; + + controller.adhocDistance = '8000'; + controller.adhocOfferTimeout = '30'; + controller.adhocStrategy = 'broadcast'; + await controller.saveSettings.perform(); + + assert.deepEqual(this.calls[this.calls.length - 1], [ + 'post', + 'fleet-ops/settings/adhoc-dispatch-settings', + { adhoc_distance: 8000, adhoc_strategy: 'broadcast', adhoc_offer_timeout: 30 }, + ]); + assert.strictEqual(this.notified[0][0], 'success'); + }); + + test('it lists the order configs that offer orders to drivers, and which set their own values', function (assert) { + const controller = this.owner.lookup('controller:settings/dispatch'); + controller.orderConfigs = [ + { id: '1', name: 'Passenger', policies: { dispatch: { adhoc: { customer_orders: true } } } }, + { id: '2', name: 'Shuttle', policies: { dispatch: { adhoc: { customer_orders: true, strategy: 'broadcast', offer_timeout: 45 } } } }, + { id: '3', name: 'Transport', policies: {} }, + ]; + + assert.deepEqual( + controller.adhocConfigs.map((config) => [config.name, config.own]), + [ + ['Passenger', false], + ['Shuttle', true], + ] + ); + assert.strictEqual(controller.overrideCount, 1); + }); + + test('it refuses an offer time outside 10 to 120 seconds', function (assert) { + const controller = this.owner.lookup('controller:settings/dispatch'); + controller.adhocOfferTimeout = 5; + assert.true(controller.timeoutInvalid); + controller.adhocOfferTimeout = 30; + assert.false(controller.timeoutInvalid); + }); +}); diff --git a/tests/unit/helpers/entity-size-test.js b/tests/unit/helpers/entity-size-test.js new file mode 100644 index 000000000..b1840dd0a --- /dev/null +++ b/tests/unit/helpers/entity-size-test.js @@ -0,0 +1,17 @@ +import { module, test } from 'qunit'; +import { setupTest } from 'dummy/tests/helpers'; + +module('Unit | Helper | entity-size and entity-weight', function (hooks) { + setupTest(hooks); + + test('they read size and weight with units, or fall back', function (assert) { + const size = this.owner.factoryFor('helper:entity-size').class; + const weight = this.owner.factoryFor('helper:entity-weight').class; + const entity = { length: 120, width: 80, height: 14.4, dimensions_unit: 'cm', weight: 2300, weight_unit: 'kg' }; + + assert.strictEqual(size.compute([entity, 'No size']), '120 × 80 × 14.4 cm'); + assert.strictEqual(weight.compute([entity, 'No weight']), `${(2300).toLocaleString()} kg`); + assert.strictEqual(size.compute([{ length: 1, width: 2 }, 'No size']), 'No size'); + assert.strictEqual(weight.compute([{}, 'No weight']), 'No weight'); + }); +}); diff --git a/tests/unit/utils/order-config-steps-test.js b/tests/unit/utils/order-config-steps-test.js new file mode 100644 index 000000000..049c1a5a2 --- /dev/null +++ b/tests/unit/utils/order-config-steps-test.js @@ -0,0 +1,38 @@ +import { module, test } from 'qunit'; +import orderConfigSteps from 'dummy/utils/order-config-steps'; + +const step = (code, status, activities = [], extra = {}) => ({ code, key: code, status, activities, ...extra }); + +module('Unit | Utility | order-config-steps', function () { + test('it orders steps from the first one, breadth first, marking branches', function (assert) { + const config = { + flow: { + completed: step('completed', 'Trip completed', [], { complete: true }), + no_show: step('no_show', 'No show'), + arrived: step('arrived', 'Arrived', ['in_progress', 'no_show']), + in_progress: step('in_progress', 'In progress', ['completed']), + created: step('created', 'Requested', ['arrived']), + }, + }; + const steps = orderConfigSteps(config); + + assert.deepEqual( + steps.map((s) => s.code), + ['created', 'arrived', 'in_progress', 'no_show', 'completed'] + ); + assert.strictEqual(steps.find((s) => s.code === 'no_show').branchFrom, 'arrived'); + assert.strictEqual(steps.find((s) => s.code === 'in_progress').branchFrom, null); + }); + + test('it starts at the lifecycle initial step and lists unreachable steps last', function (assert) { + const config = { + meta: { lifecycle: { initial: 'booked' } }, + flow: { orphan: step('orphan', 'Orphan'), booked: step('booked', 'Booked', ['done']), done: step('done', 'Done') }, + }; + + assert.deepEqual( + orderConfigSteps(config).map((s) => s.code), + ['booked', 'done', 'orphan'] + ); + }); +}); diff --git a/tests/unit/utils/sentence-parts-test.js b/tests/unit/utils/sentence-parts-test.js new file mode 100644 index 000000000..bd6f59041 --- /dev/null +++ b/tests/unit/utils/sentence-parts-test.js @@ -0,0 +1,34 @@ +import { module, test } from 'qunit'; +import sentenceParts from 'dummy/utils/sentence-parts'; + +// A stand-in for ember-intl: fills `{name}` placeholders like ICU does. +const intl = (sentences) => ({ + t(key, values = {}) { + return sentences[key].replace(/\{(\w+)\}/g, (match, name) => (values[name] === undefined ? match : String(values[name]))); + }, +}); + +module('Unit | Utility | sentence-parts', function () { + test('it splits a sentence into text and its controls, in reading order', function (assert) { + const strategy = { kind: 'choice', value: 'sequential' }; + const seconds = { kind: 'number', value: 20 }; + const parts = sentenceParts(intl({ s: 'Offer them to {strategy}, giving each driver {seconds} seconds to accept.' }), 's', { strategy, seconds }); + + assert.deepEqual(parts, [{ kind: 'text', text: 'Offer them to' }, strategy, { kind: 'text', text: ', giving each driver' }, seconds, { kind: 'text', text: 'seconds to accept.' }]); + }); + + test('it keeps the word order of the translation', function (assert) { + const choice = { kind: 'choice' }; + const parts = sentenceParts(intl({ s: '{choice} sind die Bestellungen.' }), 's', { choice }); + + assert.strictEqual(parts[0], choice); + assert.deepEqual(parts[1], { kind: 'text', text: 'sind die Bestellungen.' }); + }); + + test('it passes other values through to the translation', function (assert) { + const control = { kind: 'number' }; + const parts = sentenceParts(intl({ s: '{label}: {control}' }), 's', { control }, { label: 'Timeout' }); + + assert.deepEqual(parts, [{ kind: 'text', text: 'Timeout:' }, control]); + }); +}); diff --git a/translations/en-us.yaml b/translations/en-us.yaml index 5831cc86c..a7ced2218 100644 --- a/translations/en-us.yaml +++ b/translations/en-us.yaml @@ -106,6 +106,7 @@ menu: payments: Payments notifications: Notifications routing: Routing + dispatch: Dispatch map: Map custom-fields: Custom Fields order-board: Order Board @@ -1078,6 +1079,12 @@ order: add-waypoint: Add Waypoint add-waypoint-help-text: 'Use the `Add Waypoint` button to add more stops for this order. The Fleetbase routing engine will automatically optimize the route as each stop is added or removed.' adhoc-ping: Adhoc Ping Distance + adhoc-strategy: How to Offer It + adhoc-strategy-help-text: How this order is offered to drivers nearby. The default comes from the order config, then from Settings → Dispatch. + adhoc-strategy-default: Default + required-vehicle-type: Vehicle Type + required-vehicle-type-placeholder: Any vehicle type + required-vehicle-type-help-text: Only drivers whose vehicle is of this type are offered the order. adhoc-ping-help-text: This setting determines the adhoc distance to ping for this order, if unset it will fallback to the default setting. adhoc-ping-message: Distance must be in meters apply-service-rate: Apply service rate @@ -1252,12 +1259,146 @@ order-config-manager: uninstall-order-config: Uninstall Configuration uninstall-order-config-success-message: Extension {extensionName} uninstalled. select-order-config-to-start: Select or create an order config to start. + template: Start From + template-help-text: A ready-made configuration for one kind of operation, with its flow, policies and triggers. Change anything once it is created. + blank-template: Blank configuration tabs: + overview: Overview details: Details custom-fields: Custom Fields activity-flow: Activity Flow lifecycle: Lifecycle entities: Entities + policies: Policies + policies: + on-this-page: On this page + nav-defaults: defaults + nav-set: '{count} set' + nav-unsaved: '{count} unsaved' + legend-title: Reading this page + legend-default: 'Left alone: follows the default shown.' + legend-set: Set for this config. Reset brings back the default. + legend-click: Click any highlighted words to change them. + defaults-banner: 'Every policy here follows its default, so this config works like a standard Fleet-Ops order: your team assigns drivers and customers can cancel until it finishes. Change only what your operation needs.' + save-hint: Saved policies apply to new orders. Orders already running keep the policies they started with. + save-hint-errors: '{count, plural, one {Fix the highlighted setting to save.} other {Fix the highlighted settings to save.}}' + saved: Policies saved. New orders use them right away. + applies-when-offered: Applies only when customer orders are offered to nearby drivers. + offering: + title: How are orders offered to drivers? + nav: Offering to drivers + description: 'Whether customer orders go to drivers near the pickup, and how.' + customer-orders: + sentence: 'Orders customers place {choice}.' + wait: wait for an operator to assign them + offer: are offered to nearby drivers + customer-orders-aria: What happens to customer orders + customer-orders-help: Orders your team creates are always assigned or dispatched by your team. + strategy: + sentence: 'Offer them to {strategy}, giving each driver {seconds} seconds to accept.' + sequential: one driver at a time + broadcast: all nearby drivers at once + strategy-only: 'Offer them to {strategy}.' + strategy-aria: How orders are offered + seconds-aria: Seconds each driver has to accept + strategy-help: 'Left empty, these follow Settings → Dispatch: {strategy}, {seconds} seconds.' + radius: 'Look for drivers within {metres} metres of the pickup.' + radius-aria: Search radius in metres + radius-help: 'Left empty, this follows Settings → Dispatch ({metres} m).' + exhausted: + sentence: 'If no driver accepts, {choice}.' + keep-open: keep the order open for an operator + cancel: cancel the order + exhausted-aria: If no driver accepts + exhausted-help: Keeping it open lets your team assign it by hand. + drivers: + title: Which drivers can take them? + nav: Which drivers + description: Narrow down who an order is offered to. + vehicle: + sentence: 'Offer orders to drivers with {choice}.' + any: any vehicle + match: a vehicle that matches the service type + vehicle-aria: Vehicle matching + vehicle-help: The service type is the one the customer chose when ordering. + busy: + sentence: 'Drivers already on an order are {choice}.' + offered: still offered new orders + skipped: skipped + busy-aria: Busy drivers + busy-help: A driver is busy while any of their orders hasn’t reached a step that ends it. + ordering: + title: What do customers need to place an order? + nav: Ordering + description: For orders placed through a customer app or the customer API. + payment: 'Customers can pay by {methods}.' + payment-aria: Payment methods customers can choose + payment-empty: no choice + payment-help: 'Left empty, customers don’t choose how to pay.' + quote: + sentence: 'A price quote is {choice} before ordering.' + optional: optional + required: required + quote-aria: Quote before ordering + quote-help: Required means customers see and accept a price first. + settlement: 'Block new orders while an earlier order paid by {methods} is unpaid.' + settlement-aria: Payment methods that must be settled + settlement-empty: any method · never blocked + settlement-help: 'Usually card or bank transfer: cash is collected by the driver at the end.' + method: + cash: Cash + card: Card + bank_transfer: Bank transfer + wallet: Wallet + cancelling: + title: Can customers cancel? + nav: Cancelling + description: Customers canceling their own orders. + until: 'Customers {choice} their own orders until {step}.' + 'off': 'Customers {choice} their own orders. Your team still can.' + can: can cancel + cannot: can’t cancel + finishes: it finishes + reaches: 'it reaches {step}' + enabled-aria: Customers canceling + until-aria: Cancel until + cancelling-help: 'From that step on, only your team can cancel.' + interactions: + title: What can customers do with the driver? + nav: Customer and driver + description: Contact and feedback between a customer and the driver of their order. + sentence: 'Customers {message} the driver, {rate} them after completion, and {share} a live tracking link.' + message: + 'on': can message + 'off': can’t message + rate: + 'on': can rate + 'off': can’t rate + share: + 'on': can share + 'off': can’t share + message-aria: Messaging the driver + rate-aria: Rating the driver + share-aria: Sharing live tracking + interactions-help: The chat itself opens and closes with what happens at the steps you choose in Activity Flow. + price: + title: How is the price settled? + nav: Price + description: The final price once the order is complete. + reprice: 'On completion, {choice}, measured from {step}.' + no-reprice: 'On completion, {choice}.' + stands: the quoted price stands + recalculate: the price is recalculated from the actual distance and time + from-start: when the order starts + reprice-aria: Final price + from-aria: Measure from + price-help: Recalculating uses the service rate the order was quoted on and updates its invoice. + extension-badge: EXTENSION + extension-fallback: '{label}: {control}' + extension-on: 'on' + extension-off: 'off' + extension-none: not set + extension-aria: Setting details: details: Details name: Name @@ -1274,64 +1415,70 @@ order-config-manager: delete-body-message: Once this order config is deleted it will not be recoverable and you will lose all configurations. confirm-delete: Delete lifecycle: - title: Lifecycle - description: A configured lifecycle lets this order type start, complete and cancel at its own activities instead of the default dispatch lifecycle (created, dispatched, started, completed, canceled). - default-lifecycle: This order type uses the default dispatch lifecycle. Orders start at "created", can be dispatched to drivers and complete or cancel through the standard activities. - enable: Use a configured lifecycle - enable-help: Orders of this type start at the initial activity you choose and follow the activity flow instead of the dispatch lifecycle. - initial: Initial activity - initial-help: New orders of this type start here. Must be an activity in the flow. - completed: Completed activity - completed-help: Reaching this activity completes the order. - canceled: Canceled activity - canceled-help: Canceling an order moves it to this activity. - terminal: Terminal activities - terminal-help: No further transition is allowed after these. The completed and canceled activities are always terminal. - dispatch: Allow dispatch - dispatch-help: When off, orders of this type are never dispatched to drivers and the dispatch actions are refused. - strict-transitions: Strict transitions - strict-transitions-help: When on, an activity can only move to one of its configured next activities in the flow. - select-activity: Select activity - select-activities: Select activities - problems-title: Fix before saving - problem-initial-required: Choose the initial activity. - problem-no-activities: Add at least one activity. - problem-duplicate-code: 'An activity with the code "{code}" already exists.' - activities: Activities - activities-help: The statuses an order of this type can be in. Each activity lists the activities it can move to; the graph on the Activity Flow tab shows the same flow. Changes here are saved with the lifecycle. - activity-label: Label - activity-label-placeholder: e.g. Vehicle Assigned - activity-code: Code - activity-code-help: Stored status value. Derived from the label when left empty; cannot change once added. - activity-code-placeholder: e.g. vehicle_assigned - activity-details: Details - activity-details-placeholder: Shown with the activity in the timeline - activity-color: Colour - activity-next: Can move to - add-activity: Add activity - remove-activity: Remove activity - no-activities: No activities yet. Add the first one below; it becomes the initial activity. - blank-flow: Start from a blank flow - blank-flow-title: Remove all activities? - blank-flow-body: The default dispatch activities (created, dispatched, started, …) are removed so you can define your own. Nothing is saved until you click Save changes. - blank-flow-confirm: Remove activities - initial-short: initial - problem-missing-activity: '"{code}" is not an activity in the flow.' - summary: Summary - summary-initial: Orders start at - summary-completed: Completed at - summary-canceled: Canceled at - summary-terminal: Terminal - summary-dispatch: Dispatch - summary-strict: Strict transitions - 'yes': 'Yes' - 'no': 'No' - none: None - remove: Remove configured lifecycle - remove-title: Remove the configured lifecycle? - remove-body: Orders of this type will use the default dispatch lifecycle again. Existing orders keep their current status. - remove-confirm: Remove - saved: Lifecycle saved for {orderConfigName}. + title: How do orders start and end? + description: 'Which steps begin and finish an order, and how strictly orders follow the flow. The steps themselves are edited on Activity Flow.' + system-banner: 'Its steps come from a template, so how its orders start and end is read-only.' + mode: + sentence: 'Orders follow {choice}.' + standard: the standard dispatch steps + own: this config’s own steps + mode-aria: Which steps orders follow + mode-help-standard: 'Created → Dispatched → Started → Completed, or Canceled. Choose this config’s own steps to set where orders start and end.' + mode-help-own: Orders move through the steps on Activity Flow. + not-set: not set + initial: 'New orders start at {step}.' + initial-aria: Where new orders start + initial-help: 'Orders created by your team, customers or the API all begin here.' + completed: 'An order is complete when it reaches {step}.' + completed-aria: Step that completes the order + completed-help: Completing counts the order as done in reports and invoices. + canceled: 'Canceling an order moves it to {step}.' + canceled-aria: Step for canceled orders + canceled-help: Orders can be canceled from any step that hasn’t ended them. + terminal: 'These steps also end an order: {steps}' + terminal-aria: Other steps that end the order + terminal-none: none + terminal-help: An ended order can’t move again. The complete and cancel steps always end it. + dispatch: + sentence: 'Orders {choice}.' + 'on': can be dispatched to drivers + 'off': are never dispatched + dispatch-aria: Dispatch + dispatch-help: 'Turn dispatch off for orders that don’t need a driver, such as in-store pickups.' + strict: + sentence: 'An order can move {choice}.' + 'off': to any step + 'on': only along the flow’s arrows + strict-aria: Moving between steps + strict-help: Along the arrows stops drivers and your team skipping steps by mistake. + checks: Checks + check-completable: 'New orders can reach {step}' + check-no-dead-ends: Every step leads on or ends the order + check-dead-end: '{step} doesn’t lead anywhere' + check-dead-end-body: 'It has no next step and doesn’t end the order, so orders that reach it get stuck there.' + check-dead-end-fix: Make it end the order + problem-initial-required: Choose the step new orders start at. + problem-missing-activity: '“{code}” is not a step in the flow.' + save-blocked: Fix the highlighted rules to save. + save-hint: Orders already running keep their current status. New rules apply to their next status change. + saved: '{orderConfigName} lifecycle saved.' + at-a-glance: At a glance + glance-starts: Starts at + glance-along: Along the way + glance-ends: Ends at + glance-rules: Rules + glance-complete: complete + glance-canceled: canceled + glance-dispatched: Dispatched to drivers + glance-never-dispatched: Never dispatched + glance-strict: Follows the arrows + glance-any: Any step to any step + standard: + created: Created + dispatched: Dispatched + started: Started + completed: Completed + canceled: Canceled activity-flow: save-activity-flow: Save Activity Flow edit-activity-unique-code-warning: Activity code must be unique! @@ -1350,7 +1497,7 @@ order-config-manager: entities: new-custom-entity: New Custom Entity name: Name - description: Description + description: 'Things that often travel on this kind of order, such as containers, crates or pallets. Add one to an order’s payload in a click, with its size and weight already filled in.' type: Type length: Length width: Width @@ -1359,11 +1506,254 @@ order-config-manager: delete-custom-entity-title: Delete this custom entity? delete-custom-entity-body: Once this custom entity is deleted it will not be recoverable and you will lose all configurations. confirm-delete: Confirm + title: Entities + edit: 'Edit {name}' + no-size: No size + no-weight: No weight + empty-title: No entities on this config + empty-body: 'That’s fine: orders can still carry any item. Add entities for the things you move often, so nobody has to type their size and weight again.' + start-from: 'Start from:' + suggest: + pallet: Euro pallet + parcel: Small parcel + crate: Crate + container: 20 ft container + suitcase: Suitcase + name-placeholder: e.g. 20 ft container + name-help: Shown when adding it to an order. + name-required: Give the entity a name. + type-placeholder: e.g. Container + type-help: Groups entities in the picker. + description-placeholder: 'e.g. Standard dry container, weight when empty' + photo-help: Optional. Shown when picking it for an order. + photo-needs-name: Give the entity a name first. + size-help: Outside dimensions. Used for capacity and vehicle matching. + preview: When adding to an order’s payload + name-preview: Entity name + type-preview: Type types: no-order-installed: No order configurations installed! you-have-no-configs: You currently have no order configs installed, check at the extensions to install an order configuration to get started. view-extensions: View extensions + common: + default: Default + default-suffix: '{value} · default' + reset-to-default: Reset to default + unsaved: Unsaved + unsaved-changes: Unsaved changes + unsaved-count: '{count, plural, one {# unsaved change} other {# unsaved changes}}' + discard: Discard + save-changes: Save changes + add: + Add + edit: Edit + remove: Remove + remove-item: 'Remove {item}' + undo: Undo + done: Done + cancel: Cancel + only-if: Only if + or: or + system-title: System config. + system-banner: 'Made from a template, so it can’t be deleted and its steps are read-only. Its policies and what happens at each step can still be changed.' + readonly-title: View only. + readonly-banner: You can see how this config behaves but not change it. Ask an administrator for the “Update order configs” permission. + steps-readonly: Steps are read-only on this system config + number-range-error: 'Enter a number between {min} and {max}.' + new-config: + title: New order config + intro: 'Start from a template that already sets up the steps, policies and triggers for one kind of operation. You can change all of it afterwards.' + step-label: 'STEP {number}' + step-choose: Choose a starting point + step-name: Name it + selected: Selected + more-templates: 'More templates, such as parcel delivery and rental, will appear here as they’re added.' + preview-empty-title: Pick a template to see what it sets up + preview-empty-hint: Not sure? Transport fits most delivery and haulage work. + preview-title: 'What {template} sets up' + summary: '{steps, plural, =0 {No steps} one {# step} other {# steps}} · {policies, plural, =0 {policies at defaults} one {# policy} other {# policies}} · {triggers, plural, =0 {no triggers} one {# trigger} other {# triggers}}{fields, plural, =0 {} one { · # custom field} other { · # custom fields}}' + summary-blank: Standard steps · policies at defaults · no triggers + name: Name + name-help: Shown when creating orders. The key is made from it. + name-placeholder: e.g. Same-day delivery + name-placeholder-empty: Choose a starting point first + tags: Tags + tags-help: Optional. Helps you find configs later. + tags-placeholder: 'e.g. on-demand, city' + description: Description + create: Create config + create-from: 'Create from {template}' + templates: + transport: + name: Transport + description: 'Deliveries and haulage dispatched by your team, the default every company gets.' + name-placeholder: e.g. Same-day delivery + fact-1: Orders are assigned or dispatched by your team + fact-2: Every policy left at its Fleet-Ops default + fact-3: No automatic notifications yet + passenger: + name: Passenger + description: 'On-demand trips booked by customers, offered to nearby drivers and priced from the actual trip.' + name-placeholder: e.g. Airport shuttle + fact-1: Offered to one nearby driver at a time; canceled if nobody accepts + fact-2: 'Customers can cancel, message, rate and share; card trips settle before the next booking' + fact-3: Customer notified at each step; price recalculated on completion; adds a Passengers field + blank: + name: Blank + description: 'A configuration for a process you want to build yourself, step by step.' + name-placeholder: e.g. Equipment rental + fact-1: Starts with the standard steps; build your own in Activity Flow + fact-2: Every policy left at its Fleet-Ops default + fact-3: Add what happens at each step as you go + flow: + reset: Reset + click-a-step: Click a step to see and change what happens there. + order-events: Order events + legend: Legend + zoom-in: Zoom in + zoom-out: Zoom out + role-start: Start + role-complete: Completes order + role-end: Ends order + legend-notification: Notification + legend-chat: Chat + legend-invoice: Invoice + step: + sections: Step sections + kicker: 'Step {position} of {total}' + saved: Step saved. + tab-details: Details + tab-happens: 'What happens here · {count}' + tab-conditions: Conditions + when-reaches: 'When an order reaches {step}:' + then: Then + what-happens: What happens + choose-action: choose what happens + new: NEW + edited: Edited + no-action-error: Choose what should happen. + removed-note: removed when you save + every-time: Every time + only-if-count: '{count, plural, one {Only if # condition passes} other {Only if # conditions pass}}' + push-notification: Push notification + title: Title + title-placeholder: 'Leave empty to use: {status}' + title-placeholder-event: e.g. Your driver is almost there + message: Message + message-placeholder: Leave empty to use the step’s details + message-fallback: Uses the step’s details + insert: 'Insert:' + insert-token: 'Insert {token}' + preview: Preview with sample data + add-condition: Add a condition + condition-hint: Runs every time unless a condition is added. All conditions must pass. + add: Add something that happens here + quick-add: 'Quick add:' + empty: Nothing happens here yet. Orders just move on. + quick: + notify_customer: Notify customer + notify_driver: Notify driver + open_chat: Open chat + close_chat: Close chat + send_invoice: Send invoice + footnote: 'These run every time an order reaches this step, in this order, without holding the order up. For things that don’t belong to one step, such as an order being canceled, use Order events on the canvas.' + details-readonly: 'This step belongs to a system config or the standard dispatch steps, so its details are read-only.' + status-placeholder: e.g. Arrived at pickup + status-help: What customers and your team see. + code-placeholder: e.g. arrived + code-help: Used by the API and apps. + key-placeholder: e.g. arrived + details-placeholder: e.g. The driver is waiting at the pickup. + details-help: 'Shown in tracking, and used as a notification’s message when it has none of its own.' + completes-order: Completes the order + completes-order-help: Reaching this step marks the order complete. + requires-pod: Requires proof of delivery + requires-pod-help: 'The driver must capture proof, such as a photo or signature, to reach this step.' + developer-events: Developer events + developer-events-help: 'Webhook events sent when an order reaches this step, for integrations. For notifications and other actions, use What happens here.' + conditions-lead: 'Conditions decide whether an order can move to {step}, not what happens when it does.' + conditions-readonly: Read-only on system configs and the standard dispatch steps. + actions: + notify_customer: Notify the customer + notify_customer-description: Push notification to the customer’s app. + notify_driver: Notify the driver + notify_driver-description: Push notification to the driver’s app. + open_chat: Open the customer chat + open_chat-description: Customer and driver can message each other. + close_chat: Close the customer chat + close_chat-description: Ends the chat; its history is kept. + set_meta: Set order meta + set_meta-description: Store a value on the order for reports or integrations. + cancel: Cancel the order + cancel-description: Cancels with the reason you give. + events: + title: Order events + intro: 'What happens when something happens to an order outside its steps. For what happens when an order reaches a step, click the step.' + add: Add an order event + when: 'When {event}' + remove: Remove this order event + then-also: Then also… + empty: No order events yet. + empty-actions: Nothing happens yet. Add what should happen. + created: an order is created + created-menu: An order is created + created-description: 'As soon as it’s placed, by anyone.' + completed: an order is completed + completed-menu: An order is completed + completed-description: Whichever step completes it. + canceled: the order is canceled + canceled-menu: An order is canceled + canceled-description: 'By the customer, your team or a policy.' + exhausted: no driver accepts the order + exhausted-menu: No driver accepts the order + exhausted-description: Every nearby driver declined or let the offer run out. + approaching: 'When the driver is within {metres} metres of the {target}' + approaching-menu: The driver is approaching + approaching-description: Within a distance of the pickup or drop-off. + approaching-short: 'Driver within {metres} m of the {target}' + target-pickup: pickup + target-dropoff: drop-off + target-aria: Pickup or drop-off + distance-aria: Distance in metres + approaching-help: Checked as the driver’s location updates. Runs once per order. + approaching-help-dropoff: 'Checked as the driver’s location updates. Runs once per order, after pickup.' + save: Save order events + saved: Order events saved. + overview: + title: 'What happens to a {config} order' + readonly-hint: Read-only summary. Use the links to change anything. + before: Before the order is placed + edit-policies: Edit policies + edit-step: Edit what happens + edit-events: Edit order events + happens-here: Happens here + policies-apply: Policies that apply + nothing: Nothing + none: None + any-time: Any time + at-a-glance: At a glance + no-events: No order events. + has-condition: Only if its conditions pass + tag-completes: Completes the order + tag-ends: Ends the order + branch-from: 'Ends the order · branch from {step}' + rule-payment: 'Customers pay by {methods}' + rule-quote: Customers accept a price quote first + rule-settlement: 'Customers with an unpaid {methods} order can’t place a new one' + rule-interactions: 'Customers can {list}' + interaction-chat: message the driver + interaction-rating: rate the driver + interaction-share_tracking: share tracking + rule-offered: 'Offered to nearby drivers, not assigned by your team' + rule-vehicle: Only drivers whose vehicle matches the service type + rule-can-cancel: Customer can still cancel + rule-cannot-cancel: Customer can no longer cancel + rule-metering: Distance and time measured from here + rule-repriced: Price recalculated from the actual trip + rule-rating: Customer can rate the driver + glance-steps: '{count, plural, one {# step} other {# steps}} · {ends, plural, =0 {none end the order} one {# ends the order} other {# end the order}}' + glance-automatic: '{count, plural, =0 {Nothing happens automatically} one {# thing happens automatically} other {# things happen automatically}}' + glance-policies: '{count, plural, =0 {Every policy at its default} one {# policy setting changed from the defaults} other {# policy settings changed from the defaults}}' place: fields: details: Place Details @@ -2811,6 +3201,31 @@ route-list: more-waypoints: more waypoints settings: + dispatch: + title: Fleet-Ops Dispatch + adhoc-orders: Adhoc dispatch defaults + intro: Company-wide defaults for offering orders to nearby drivers. + override-banner: These apply to every order config that offers orders to nearby drivers and leaves these settings empty. An order config can set its own values on its Policies tab. + override-count: '{count, plural, one {# config sets its own values.} other {# configs set their own values.}}' + strategy: How orders are offered + strategy-placeholder: One driver at a time + strategy-help-text: 'One at a time offers the order to the nearest driver first, then the next if they decline or run out of time. All at once offers it to every nearby driver, and the first to accept gets it.' + offer-timeout: Time each driver has to accept + offer-timeout-placeholder: '20' + offer-timeout-help-text: Between 10 and 120. Leave empty for 20 seconds. + offer-timeout-error: Enter a number between 10 and 120. + ping-radius: Search radius around the pickup + ping-radius-placeholder: '6000' + ping-radius-help-text: 'Drivers farther from the pickup aren’t offered the order. Leave empty for 6,000 m.' + seconds: seconds + metres: metres + section-configs: Order configs that offer orders to drivers + uses-defaults: Uses these defaults + sets-own: 'Sets its own: {settings}' + setting-strategy: how orders are offered + setting-offer_timeout: time to accept + setting-radius: search radius + saved: Dispatch settings saved. telematics: telematics-settings: Telematics Settings intro: Choose how long your organization keeps device events and position history within the limits set by your system administrator.