From bdcf29713210a7ada513c08d9297a5e3799976a3 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Sun, 15 Nov 2026 01:41:38 +0800 Subject: [PATCH 1/3] test(customers): add driver_ratings to the customer helper seams schema CustomerController eager-loads driverRating on customer orders since the passenger rides work, so the hand-built SQLite schema needs the table. --- .../tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php index 59e65aa74..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) { From bfe280132e752086f4428409381d8cd600855c16 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Sun, 15 Nov 2026 01:58:14 +0800 Subject: [PATCH 2/3] test(orders): give the nearby filters order_configs fixture its policies column The adhoc strategy moved from order_configs.adhoc_strategy into the policies JSON in the order config policies refactor. --- .../tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php index 09a20f049..c26e8a5ea 100644 --- a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php @@ -146,7 +146,7 @@ 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', 'adhoc_strategy'], + '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'], From 3f11a5366df50f71669b535f879bbd5ae4c5782d Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Sun, 15 Nov 2026 02:28:13 +0800 Subject: [PATCH 3/3] test(order-configs): cover the order config actions, custom fields, templates and endpoints The order config policies, triggers and templates work on release/v0.7.0 had no PHP CI run, so these lines were never measured: - the cancel, open chat and set meta actions, and notify driver with nothing to say - OrderCustomFields validate and apply - OrderUpdate's FCM and APN messages - the internal capabilities and create from template endpoints - the OrderConfig resource's custom fields - template registration and unknown template keys - Condition with collections and single values - custom field and payment method refusals on customer and API order creation, and dispatch refused by the config --- .../tests/ApiOrderControllerContractsTest.php | 21 ++ .../AdhocDispatchAndOrderConfigTest.php | 225 ++++++++++++++++++ .../Http/Api/OrderControllerCreateTest.php | 49 ++++ .../OrderConfigControllerContractsTest.php | 55 ++++- server/tests/FlowResourceTest.php | 10 + .../Resources/OrderConfigResourceTest.php | 52 ++++ .../OrderConfig/OrderConfigTemplatesTest.php | 38 +++ 7 files changed, 449 insertions(+), 1 deletion(-) 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/Feature/AdhocDispatchAndOrderConfigTest.php b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php index 124eb4a7a..7601fb99b 100644 --- a/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php +++ b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php @@ -14,10 +14,14 @@ use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\DriverRatings; use Fleetbase\FleetOps\Support\OrderChat; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\CancelOrder; use Fleetbase\FleetOps\Support\OrderConfig\Actions\NotifyCustomer; use Fleetbase\FleetOps\Support\OrderConfig\Actions\NotifyDriver; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\OpenChat; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\SetMeta; use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; +use Fleetbase\FleetOps\Support\OrderCustomFields; use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\OrderRepricing; use Fleetbase\LaravelMysqlSpatial\Types\Point; @@ -37,10 +41,55 @@ eval('namespace Fleetbase\Observers; function event($event = null, $payload = []) { return []; }'); } +// Settings read the company from the session store, which the harness keeps as a plain array. +if (!function_exists('Fleetbase\Models\session')) { + eval('namespace Fleetbase\Models; function session($key = null, $default = null) { if ($key === null) { return new class { public function has($k) { return \session($k) !== null; } public function get($k, $d = null) { return \session($k, $d); } public function missing($k) { return \session($k) === null; } }; } return \session($key, $default); }'); +} + if (!function_exists('Fleetbase\FleetOps\Support\event')) { eval('namespace Fleetbase\FleetOps\Support; function event($event = null) { if (\AdhocCfgRecorder::$failEvents) { throw new \RuntimeException(\'socket down\'); } \AdhocCfgRecorder::$events[] = $event; return $event; }'); } +/** + * Stands in for Laravel's validator, which this package doesn't install: it records what it was + * asked to check and applies the `required` and `integer` rules, naming fields by their attribute. + */ +class AdhocCfgValidator +{ + public static array $made = []; + + public function make($data = [], $rules = [], $messages = [], $attributes = []) + { + static::$made[] = ['data' => $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 = []; @@ -998,6 +1047,11 @@ function adhocCfgSeedOrder(SQLiteConnection $connection, array $order = []): Adh ->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 () { @@ -1128,6 +1182,112 @@ function adhocCfgSeedOrder(SQLiteConnection $connection, array $order = []): Adh ->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 { @@ -1600,3 +1760,68 @@ function adhocCfgJson($response): array ->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/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/Internal/OrderConfigControllerContractsTest.php b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php index 69bfcbfd4..8090c8708 100644 --- a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php @@ -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,47 @@ 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']) + ->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); +}); + +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/FlowResourceTest.php b/server/tests/FlowResourceTest.php index 85d60dc61..2e8a73d8f 100644 --- a/server/tests/FlowResourceTest.php +++ b/server/tests/FlowResourceTest.php @@ -173,6 +173,16 @@ function flowFixture(): array 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/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/Support/OrderConfig/OrderConfigTemplatesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php index 7d6491475..d71dd87fc 100644 --- a/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php @@ -164,3 +164,41 @@ function orderConfigTemplatesFlow(array $flow): array '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(); +});