Skip to content

Modular logistics and supply chain operating system (LSOS)

43.3 KB
Raw Blame
// scripts/ci/mint-api-key.php
//
// CI helper: mint a working Fleetbase public-API key against a booted stack.
//
// This file is NOT a standalone script. It is base64-encoded and eval()'d inside
// `php artisan tinker --execute="eval(base64_decode('...'));"`. Piping a file that
// begins with a <?php tag to tinker triggers a PsySH parse error ("unexpected '<'"),
// so this snippet intentionally OMITS the opening <?php tag and uses fully-qualified
// class names instead of `use` statements.
//
// It idempotently creates an organization + owner user + a live API credential and
// prints the flb_live_ key. The key is generated by ApiCredentialObserver on insert,
// so the credential MUST be created through the Eloquent model, then reloaded. The
// company must have an owner or the public-API middleware rejects the key (401).
//
// It also prints the organization's public_id, which the collection needs for requests
// that address an organization by id (Onboard, Switch Driver Organization).
//
// Finally it seeds the Customers folder's fixtures. Those requests need a verification
// code, and codes are six random digits delivered only by email/SMS — a collection run
// cannot obtain one unaided. Rather than adding a bypass to the API, we pre-create the
// customer and the exact VerificationCode rows the three code-checking endpoints look
// for. See the CUSTOMER FIXTURES block below.
//
// The four customer values are read from the environment so the action that injects
// {{verification_code}} into the collection run is the single source of truth (it passes
// them with `docker compose exec -e`). The fallbacks below match the action's input
// defaults so this script still works when run by hand for local verification.

try {
    $company = \Fleetbase\Models\Company::firstOrCreate(['name' => 'CI Contract Org']);

    $user = \Fleetbase\Models\User::where('email', '[email protected]')->first();
    if (!$user) {
        $user               = new \Fleetbase\Models\User();
        $user->name         = 'CI Contract User';
        $user->email        = '[email protected]';
        $user->company_uuid = $company->uuid;
        $user->type         = 'user';
        $user->status       = 'active';
        $user->password     = 'CiContract1!' . bin2hex(random_bytes(6));
        $user->save();
    }

    if (empty($company->owner_uuid)) {
        $company->setOwner($user, true);
        $company->save();
    }

    // test_mode=false => flb_live_ key stored on the default (mysql) connection.
    $credential = \Fleetbase\Models\ApiCredential::firstOrCreate(
        ['company_uuid' => $company->uuid, 'name' => 'CI Contract Key'],
        ['user_uuid' => $user->uuid, 'test_mode' => false]
    );

    echo PHP_EOL . 'MINTED_API_KEY=' . $credential->fresh()->key . PHP_EOL;

    // Feeds the collection's {{organization_id}}. Requests that take an organization in
    // the path expect the public_id (company_xxxxxxxxxx), not the uuid.
    echo 'MINTED_COMPANY_ID=' . $company->public_id . PHP_EOL;

    // The organizations listing (GET /v1/organizations) sits behind
    // AuthenticatePlatformApiToken rather than an org API credential, and answers 401
    // to an flb_live_ key. Only the hash is persisted, so the plaintext cannot be read
    // back — rotating is the only way to learn a usable token. Safe here because this
    // script only ever runs against a throwaway CI stack; do not run it against an
    // install whose platform token is already in use.
    $platformToken = \Fleetbase\Support\PlatformApi::rotateToken();
    echo 'MINTED_PLATFORM_TOKEN=' . $platformToken . PHP_EOL;

    /* ============================================================
     | CUSTOMER FIXTURES (Fleetbase API / Customers)
     * ============================================================ */

    $customerIdentity = getenv('CI_CUSTOMER_IDENTITY') ?: '[email protected]';
    $customerPhone    = getenv('CI_CUSTOMER_PHONE') ?: '+15555550123';
    $customerPassword = getenv('CI_CUSTOMER_PASSWORD') ?: 'CiCustomerPassw0rd!';
    $customerCode     = getenv('CI_CUSTOMER_VERIFICATION_CODE') ?: '000000';

    // The customer User. Seeding it (rather than letting Request Customer Creation Code
    // create the stub) buys three things the run depends on:
    //   * a known password, so Login Customer can authenticate;
    //   * a known phone, so Request Customer Login SMS resolves a user instead of
    //     400ing with "No customer with this phone number found";
    //   * a stable uuid, so the `fleetops_customer_login` code below can be scoped to
    //     the subject that CustomerController::verifyCode looks it up by.
    // Deliberately no Contact row — Create a Customer must still create that itself.
    $customer = \Fleetbase\Models\User::where('email', $customerIdentity)->withoutGlobalScopes()->first();
    if (!$customer) {
        $customer               = new \Fleetbase\Models\User();
        $customer->email        = $customerIdentity;
        $customer->company_uuid = $company->uuid;
    }
    // Reassert every field on reruns so a mutated row (Update Authenticated Customer
    // rewrites name/email/phone; Reset Customer Password rewrites the password) is
    // restored to the state the collection expects.
    $customer->name   = 'Jane Customer';
    $customer->phone  = $customerPhone;
    $customer->type   = 'customer';
    $customer->status = 'active';
    // `password` is guarded against mass assignment; direct assignment runs the
    // setPasswordAttribute mutator, which hashes it.
    $customer->password = $customerPassword;
    $customer->save();

    // The three VerificationCode rows, one per code-checking endpoint. Each is matched
    // by a different set of columns, so all three are required:
    //
    //   for=fleetops_create_customer         CustomerController::create matches
    //                                        code + for + meta->identity
    //   for=fleetops_customer_login          ::verifyCode matches subject_uuid + code + for
    //   for=fleetops_customer_password_reset ::resetPassword matches code + for + meta->identity
    //
    // `000000` sits outside VerificationCode's mt_rand(100000, 999999) range, so a seeded
    // code can never collide with a genuine one.
    $seedVerificationCode = function (string $for, array $meta = []) use ($customer, $customerCode) {
        // Clear prior rows for this subject/purpose so reruns are deterministic.
        // ExpiryScope hides expired rows from a normal query, so drop global scopes to
        // be sure leftovers from an earlier run are really gone.
        \Fleetbase\Models\VerificationCode::withoutGlobalScopes()
            ->where(['subject_uuid' => $customer->uuid, 'for' => $for])
            ->delete();

        // generateFor(save: false) sets `for` and the polymorphic subject via
        // HasSubject::setSubject (subject_type is the FQCN).
        $code             = \Fleetbase\Models\VerificationCode::generateFor($customer, $for, false);
        $code->expires_at = \Illuminate\Support\Carbon::now()->addDay();
        $code->meta       = $meta;
        $code->status     = 'active';
        $code->save();

        // VerificationCode::boot() registers a `creating` hook that unconditionally
        // overwrites `code` with mt_rand(100000, 999999), so the known value cannot be
        // set on insert. `creating` does not fire on update — assign and save again.
        $code->code = $customerCode;
        $code->save();

        return $code;
    };

    $seedVerificationCode('fleetops_create_customer', ['identity' => $customerIdentity]);
    $seedVerificationCode('fleetops_customer_login');
    $seedVerificationCode('fleetops_customer_password_reset', ['identity' => $customerIdentity]);

    // The Storefront customer endpoints run the same flows against the same User but
    // scope their codes under their own `for` values, so the fleetops rows above do not
    // satisfy them. Matched exactly as each controller looks them up:
    //
    //   storefront_login             ::verifyCode        subject_uuid + code + for
    //   storefront_create_customer   ::create            code + for + meta->identity
    //   storefront_account_closure   ::confirmClosure    code + for + meta->identity
    $seedVerificationCode('storefront_login');
    // Filed under the PHONE, not the email: confirmAccountClosure computes the identity it
    // looks up as `$user->phone ?? $user->email`, and the seeded customer has a phone. A
    // code filed under the email was never found — "Invalid verification code provided!".
    $seedVerificationCode('storefront_account_closure', ['identity' => $customerPhone]);

    // Create a Customer needs an identity with NO existing contact: the request validates
    // `email` with Rule::unique('contacts'), and by the time it runs the seeded customer's
    // contact exists — "The email has already been taken." So the creation code is filed
    // under a second identity reserved for exactly that, and deliberately left without a
    // contact of its own.
    $newCustomerIdentity = getenv('CI_NEW_CUSTOMER_IDENTITY') ?: '[email protected]';

    \Fleetbase\Models\VerificationCode::withoutGlobalScopes()
        ->where(['subject_uuid' => $customer->uuid, 'for' => 'storefront_create_customer'])
        ->delete();
    $createCode             = \Fleetbase\Models\VerificationCode::generateFor($customer, 'storefront_create_customer', false);
    $createCode->expires_at = \Illuminate\Support\Carbon::now()->addDay();
    $createCode->meta       = ['identity' => $newCustomerIdentity];
    $createCode->status     = 'active';
    $createCode->save();
    $createCode->code       = $customerCode;
    $createCode->save();

    echo 'SEEDED_NEW_CUSTOMER_IDENTITY=' . $newCustomerIdentity . PHP_EOL;

    // The Storefront API authenticates with a store/network key, not an organization
    // API credential: SetStorefrontSession rejects any bearer token that does not start
    // with "store" or "network", so the flb_live_ key above can never authenticate a
    // Storefront request. Seed a store so the Storefront collection has a usable key.
    // Guarded because the extension is not installed in every stack.
    if (class_exists(\Fleetbase\Storefront\Models\Store::class)) {
        $store = \Fleetbase\Storefront\Models\Store::where([
            'company_uuid' => $company->uuid,
            'name'         => 'CI Contract Store',
        ])->first();

        if (!$store) {
            // Store::boot() sets `key` to 'store_' . md5(...) on creating, so the key
            // exists only after the insert — it cannot be supplied.
            $store = \Fleetbase\Storefront\Models\Store::create([
                'company_uuid'    => $company->uuid,
                'created_by_uuid' => $user->uuid,
                'name'            => 'CI Contract Store',
                'description'     => 'Seeded by the API contract run.',
                'currency'        => 'USD',
                'online'          => 1,
            ]);
        }

        echo 'MINTED_STOREFRONT_KEY=' . $store->fresh()->key . PHP_EOL;
        echo 'MINTED_STOREFRONT_ID=' . $store->public_id . PHP_EOL;
    } else {
        echo 'MINTED_STOREFRONT_KEY=' . PHP_EOL;
    }

    /* ============================================================
     | DRIVER FIXTURES (Fleetbase API / Drivers)
     * ============================================================ */

    // Login Driver resolves a User by phone OR email that HAS a related driver:
    //   User::where(phone = static::phone($identity))->orWhere('email', $identity)
    //       ->whereHas('driver')
    // so the User alone is not enough — a Driver row scoped to the same company is
    // required or every driver auth request fails before it reaches a password check.
    $driverIdentity = getenv('CI_DRIVER_IDENTITY') ?: '[email protected]';
    $driverPhone    = getenv('CI_DRIVER_PHONE') ?: '+15555550124';
    $driverPassword = getenv('CI_DRIVER_PASSWORD') ?: 'CiDriverPassw0rd!';

    $driverUser = \Fleetbase\Models\User::where('email', $driverIdentity)->withoutGlobalScopes()->first();
    if (!$driverUser) {
        $driverUser               = new \Fleetbase\Models\User();
        $driverUser->email        = $driverIdentity;
        $driverUser->company_uuid = $company->uuid;
    }
    // Reasserted on every run: Switch Driver Organization and the profile updates mutate
    // these, and the collection expects a known starting state.
    $driverUser->name   = 'Casey Driver';
    $driverUser->phone  = $driverPhone;
    $driverUser->type   = 'user';
    $driverUser->status = 'active';
    $driverUser->password = $driverPassword;
    $driverUser->save();

    if (class_exists(\Fleetbase\FleetOps\Models\Driver::class)) {
        $driverRecord = \Fleetbase\FleetOps\Models\Driver::withoutGlobalScopes()
            ->where(['user_uuid' => $driverUser->uuid, 'company_uuid' => $company->uuid])
            ->first();

        if (!$driverRecord) {
            $driverRecord = \Fleetbase\FleetOps\Models\Driver::create([
                'user_uuid'    => $driverUser->uuid,
                'company_uuid' => $company->uuid,
                'status'       => 'active',
                'online'       => 0,
            ]);
        }

        echo 'SEEDED_DRIVER_ID=' . $driverRecord->fresh()->public_id . PHP_EOL;

        // POST /v1/drivers/register-device (the route with no {id}) resolves the driver
        // from $request->user(). Under `fleetbase.api` that is the API credential's owner,
        // not the driver seeded above — so the route is unreachable unless the credential
        // owner is itself a driver. That is a real configuration (an owner-operator), and
        // it is the only way an org-key contract run can exercise the tokenless route.
        \Fleetbase\FleetOps\Models\Driver::firstOrCreate(
            ['user_uuid' => $user->uuid, 'company_uuid' => $company->uuid],
            ['status' => 'active', 'online' => 0]
        );
    } else {
        echo '::warning::FleetOps not installed; driver fixtures skipped.' . PHP_EOL;
    }

    // verifyCode defaults `for` to driver_login and matches on subject + code + for,
    // mirroring the customer login code above.
    \Fleetbase\Models\VerificationCode::withoutGlobalScopes()
        ->where(['subject_uuid' => $driverUser->uuid, 'for' => 'driver_login'])
        ->delete();
    $driverCode             = \Fleetbase\Models\VerificationCode::generateFor($driverUser, 'driver_login', false);
    $driverCode->expires_at = \Illuminate\Support\Carbon::now()->addDay();
    $driverCode->status     = 'active';
    $driverCode->save();
    $driverCode->code = $customerCode;
    $driverCode->save();

    // DriverController::resetPassword matches subject_uuid + code + for, and its
    // `for` is driver_password_reset — a login code will not satisfy it, so the
    // reset flow needs a row of its own exactly as the customer reset does.
    \Fleetbase\Models\VerificationCode::withoutGlobalScopes()
        ->where(['subject_uuid' => $driverUser->uuid, 'for' => 'driver_password_reset'])
        ->delete();
    $driverResetCode             = \Fleetbase\Models\VerificationCode::generateFor($driverUser, 'driver_password_reset', false);
    $driverResetCode->expires_at = \Illuminate\Support\Carbon::now()->addDay();
    $driverResetCode->status     = 'active';
    $driverResetCode->save();
    $driverResetCode->code = $customerCode;
    $driverResetCode->save();

    /* ============================================================
     | SECOND ORGANIZATION (Switch Driver Organization)
     * ============================================================ */

    // switchOrganization rejects a switch to the org the driver is already in, and then
    // requires a CompanyUser row proving membership of the target. Neither can be created
    // through the public API, so the seeded driver is given a second organization here:
    // a company, a CompanyUser row, and a driver profile in it.
    //
    // The collection's other driver requests use {{driver_id}} from Create a Driver, whose
    // user belongs to one company only — hence a separate {{multi_org_driver_id}} for the
    // one request that needs two.
    $secondCompany = \Fleetbase\Models\Company::firstOrCreate(['name' => 'CI Contract Org (Secondary)']);
    if (empty($secondCompany->owner_uuid)) {
        $secondCompany->setOwner($user, true);
        $secondCompany->save();
    }

    \Fleetbase\Models\CompanyUser::firstOrCreate([
        'company_uuid' => $secondCompany->uuid,
        'user_uuid'    => $driverUser->uuid,
    ], ['status' => 'active']);

    if (class_exists(\Fleetbase\FleetOps\Models\Driver::class)) {
        \Fleetbase\FleetOps\Models\Driver::firstOrCreate(
            ['user_uuid' => $driverUser->uuid, 'company_uuid' => $secondCompany->uuid],
            ['status' => 'active', 'online' => 0]
        );
    }

    echo 'SEEDED_SECONDARY_ORGANIZATION_ID=' . $secondCompany->public_id . PHP_EOL;

    echo 'SEEDED_DRIVER_IDENTITY=' . $driverIdentity . PHP_EOL;
    echo 'SEEDED_DRIVER_PHONE=' . $driverPhone . PHP_EOL;

    /* ============================================================
     | INSPECTION FORM (Fleetbase API / Inspections)
     * ============================================================ */

    // The driver inspection endpoints (fleetops#319, postman#60) list published forms
    // and submit against one. Forms are authored and published from the console — no
    // consumable route creates one — so a contract run has to seed it. Organisation-wide
    // (`subject_uuid` null) so it applies to whatever vehicle the collection creates.
    // Guarded: the model exists only once the FleetOps release that carries inspections
    // is installed; earlier stacks skip it and the six requests are the postman run's
    // problem, not this script's.
    if (class_exists(\Fleetbase\FleetOps\Models\InspectionForm::class)) {
        $inspectionForm = \Fleetbase\FleetOps\Models\InspectionForm::withoutGlobalScopes()
            ->where(['company_uuid' => $company->uuid, 'name' => 'CI Contract Pre-trip'])
            ->first();

        if (!$inspectionForm) {
            $inspectionForm = new \Fleetbase\FleetOps\Models\InspectionForm();
            $inspectionForm->company_uuid    = $company->uuid;
            $inspectionForm->created_by_uuid = $user->uuid;
            $inspectionForm->name            = 'CI Contract Pre-trip';
        }

        // Reasserted on every run: the listing filters on `status=published` AND a
        // `published_at`, and the submit path counts failures from these two items.
        $inspectionForm->description  = 'Seeded by the API contract run.';
        $inspectionForm->type         = 'pre_trip';
        $inspectionForm->frequency    = 'pre_trip';
        $inspectionForm->status       = 'published';
        $inspectionForm->published_at = $inspectionForm->published_at ?? \Illuminate\Support\Carbon::now();
        $inspectionForm->subject_type = null;
        $inspectionForm->subject_uuid = null;
        $inspectionForm->items        = [
            ['key' => 'brakes', 'label' => 'Brakes', 'category' => 'Brakes', 'required' => true, 'severity' => 'critical'],
            ['key' => 'lights', 'label' => 'Lights and indicators', 'category' => 'Lights', 'required' => true, 'severity' => 'medium'],
        ];
        $inspectionForm->settings     = [
            'create_issue_on_failure'      => true,
            'create_work_order_on_failure' => true,
        ];
        $inspectionForm->save();

        echo 'SEEDED_INSPECTION_FORM_ID=' . $inspectionForm->fresh()->public_id . PHP_EOL;

        /* --------------------------------------------------------
         | Inspection form field groups (custom-field system)
         * -------------------------------------------------------- */

        // The second cut of inspections stops treating a form as a flat JSON `items`
        // list and builds it out of the platform's custom-field system: a form's groups
        // are Category rows (`for = custom_field_group`, owned by the form) and its
        // fields are CustomField rows (`for = fleetops_inspection_form`, subject = the
        // form). `items` above is left in place so a stack on the first cut still has a
        // submittable form; the groups below are what the second cut reads.
        //
        // Guarded twice over. The two constants only exist on the FleetOps release that
        // carries the second cut, so they are read through `defined()` with the literal
        // values as the fallback — referencing an undefined class constant is a fatal
        // error, not a catchable one, and would take the whole seed with it. Category
        // and CustomField ship with core-api, but they are checked too so this block
        // degrades the same way the form itself does rather than half-running.
        $groupFor = defined('\Fleetbase\FleetOps\Models\InspectionForm::GROUP_FOR')
            ? \Fleetbase\FleetOps\Models\InspectionForm::GROUP_FOR
            : 'custom_field_group';
        $fieldFor = defined('\Fleetbase\FleetOps\Models\InspectionForm::FIELD_FOR')
            ? \Fleetbase\FleetOps\Models\InspectionForm::FIELD_FOR
            : 'fleetops_inspection_form';

        if (class_exists(\Fleetbase\Models\Category::class) && class_exists(\Fleetbase\Models\CustomField::class)) {
            // The morph value both sides key on. Taken from the model rather than
            // hardcoded so a morph map, if one is ever registered, is respected.
            $formType = $inspectionForm->getMorphClass();

            // Two groups: what the driver walks around and checks, then what they read
            // off the dash and sign. `grid_size` is how many columns the group renders
            // its fields in — the checks pair up two-across, the meter and the signature
            // want the full width.
            $inspectionGroups = [
                [
                    'name'        => 'Exterior and Safety',
                    'description' => 'Walk-around checks completed before the vehicle moves.',
                    'order'       => 1,
                    'meta'        => ['grid_size' => 2],
                    'fields'      => [
                        [
                            'name'      => 'brakes',
                            'label'     => 'Brakes',
                            'type'      => 'pass-fail',
                            'required'  => true,
                            'order'     => 1,
                            'help_text' => 'Service and park brake, including air loss on an air-braked unit.',
                            'meta'      => [
                                'severity'                => 'critical',
                                'require_photo_on_fail'   => true,
                                'require_comment_on_fail' => true,
                                'unsafe_on_fail'          => true,
                                'instructions'            => 'Pump the pedal and hold. Fail on any pull, sponginess or audible leak.',
                            ],
                        ],
                        [
                            'name'      => 'lights',
                            'label'     => 'Lights and indicators',
                            'type'      => 'pass-fail',
                            'required'  => true,
                            'order'     => 2,
                            'help_text' => 'Head, tail, brake, hazard and both indicators.',
                            'meta'      => [
                                'severity'                => 'medium',
                                'require_photo_on_fail'   => true,
                                'require_comment_on_fail' => true,
                                'unsafe_on_fail'          => false,
                                'instructions'            => 'Walk the vehicle with the hazards on, then check brake lights with a second person.',
                            ],
                        ],
                        [
                            'name'      => 'damage_notes',
                            'label'     => 'Damage or defects noted',
                            'type'      => 'textarea',
                            'required'  => false,
                            'order'     => 3,
                            'help_text' => 'Anything the checks above do not already cover.',
                            'meta'      => [],
                        ],
                    ],
                ],
                [
                    'name'        => 'Meter and Sign-off',
                    'description' => 'Readings taken from the cab, then the driver declaration.',
                    'order'       => 2,
                    'meta'        => ['grid_size' => 1],
                    'fields'      => [
                        [
                            'name'      => 'odometer',
                            'label'     => 'Odometer reading',
                            'type'      => 'number',
                            'required'  => true,
                            'order'     => 1,
                            'help_text' => 'Whole kilometres as shown on the dash.',
                            // `role: odometer` is what marks this as the meter the
                            // submission reads back onto the vehicle, rather than just
                            // another number on the form.
                            'meta'      => ['unit' => 'km', 'role' => 'odometer'],
                        ],
                        [
                            'name'      => 'driver_signature',
                            'label'     => 'Driver signature',
                            'type'      => 'signature',
                            'required'  => true,
                            'order'     => 2,
                            'help_text' => 'I confirm the checks above were carried out and recorded honestly.',
                            'meta'      => [],
                        ],
                    ],
                ],
            ];

            $seededGroupIds = [];

            foreach ($inspectionGroups as $groupDefinition) {
                // Idempotent the same way every other fixture here is: look the row up on
                // the tuple that identifies it, reassert its attributes, save. A re-run
                // updates in place instead of stacking a second copy of every group.
                $group = \Fleetbase\Models\Category::withoutGlobalScopes()
                    ->where([
                        'company_uuid' => $company->uuid,
                        'owner_uuid'   => $inspectionForm->uuid,
                        'owner_type'   => $formType,
                        'for'          => $groupFor,
                        'name'         => $groupDefinition['name'],
                    ])
                    ->first();

                if (!$group) {
                    $group = new \Fleetbase\Models\Category();
                    $group->company_uuid = $company->uuid;
                    $group->owner_uuid   = $inspectionForm->uuid;
                    $group->owner_type   = $formType;
                    $group->for          = $groupFor;
                    $group->name         = $groupDefinition['name'];
                }

                $group->description = $groupDefinition['description'];
                $group->order       = $groupDefinition['order'];
                $group->meta        = $groupDefinition['meta'];
                $group->save();

                $seededGroupIds[] = $group->fresh()->public_id;

                foreach ($groupDefinition['fields'] as $fieldDefinition) {
                    $field = \Fleetbase\Models\CustomField::withoutGlobalScopes()
                        ->where([
                            'company_uuid' => $company->uuid,
                            'subject_uuid' => $inspectionForm->uuid,
                            'subject_type' => $formType,
                            'for'          => $fieldFor,
                            'name'         => $fieldDefinition['name'],
                        ])
                        ->first();

                    if (!$field) {
                        $field = new \Fleetbase\Models\CustomField();
                        $field->company_uuid = $company->uuid;
                        $field->subject_uuid = $inspectionForm->uuid;
                        $field->subject_type = $formType;
                        $field->for          = $fieldFor;
                        $field->name         = $fieldDefinition['name'];
                    }

                    // Reasserted every run, category_uuid included: a field that was
                    // seeded into the other group on an earlier revision of this list
                    // gets moved rather than duplicated.
                    $field->category_uuid = $group->uuid;
                    $field->label         = $fieldDefinition['label'];
                    $field->type          = $fieldDefinition['type'];
                    $field->required      = $fieldDefinition['required'];
                    $field->editable      = true;
                    $field->order         = $fieldDefinition['order'];
                    $field->help_text     = $fieldDefinition['help_text'];
                    $field->meta          = $fieldDefinition['meta'];
                    $field->save();
                }
            }

            echo 'SEEDED_INSPECTION_FORM_GROUP_IDS=' . implode(',', $seededGroupIds) . PHP_EOL;
        } else {
            echo '::warning::Custom field models unavailable; inspection form groups skipped.' . PHP_EOL;
            echo 'SEEDED_INSPECTION_FORM_GROUP_IDS=' . PHP_EOL;
        }
    } else {
        echo 'SEEDED_INSPECTION_FORM_ID=' . PHP_EOL;
        echo 'SEEDED_INSPECTION_FORM_GROUP_IDS=' . PHP_EOL;
    }

    /* ============================================================
     | FOOD TRUCK (Storefront)
     * ============================================================ */

    // Retrieve Food Truck answered "Food Truck resource not found." because the store has
    // none — Query Food Trucks returned [] and nothing could set {{food_truck_id}}. A food
    // truck is a vehicle bound to a store, so both are seeded. The vehicle carries an
    // explicit location: `location` is a spatial column, and the same NOT NULL default
    // that broke sensor and fuel report creation applies here.
    if (isset($store) && class_exists(\Fleetbase\Storefront\Models\FoodTruck::class)) {
        $truckVehicle = \Fleetbase\FleetOps\Models\Vehicle::withoutGlobalScopes()
            ->where(['company_uuid' => $company->uuid, 'plate_number' => 'CI-TRUCK-1'])
            ->first();

        if (!$truckVehicle) {
            $truckVehicle = \Fleetbase\FleetOps\Models\Vehicle::create([
                'company_uuid' => $company->uuid,
                'plate_number' => 'CI-TRUCK-1',
                'make'         => 'Contract',
                'model'        => 'Food Truck',
                'year'         => 2026,
                'status'       => 'active',
                // Both are NOT NULL without a default. `location` is the spatial column
                // that already broke sensor and fuel report creation; `online` is the same
                // trap one column over, and it aborted the whole seed.
                'online'       => 0,
                'location'     => new \Fleetbase\LaravelMysqlSpatial\Types\Point(1.3521, 103.8198),
            ]);
        }

        $foodTruck = \Fleetbase\Storefront\Models\FoodTruck::withoutGlobalScopes()
            ->where(['store_uuid' => $store->uuid, 'vehicle_uuid' => $truckVehicle->uuid])
            ->first();

        if (!$foodTruck) {
            $foodTruck = \Fleetbase\Storefront\Models\FoodTruck::create([
                'company_uuid'    => $company->uuid,
                'created_by_uuid' => $user->uuid,
                'store_uuid'      => $store->uuid,
                'vehicle_uuid'    => $truckVehicle->uuid,
                'status'          => 'active',
            ]);
        }

        echo 'SEEDED_FOOD_TRUCK=' . $foodTruck->fresh()->public_id . PHP_EOL;
    }

    /* ============================================================
     | NETWORK (Storefront network-scoped endpoints)
     * ============================================================ */

    // List Network Stores answered "Stores cannot have stores!" because the contract
    // authenticates with a STORE key, and the network endpoints require a network session.
    // Network::boot() generates `key = 'network_' . md5(...)` on insert exactly like Store,
    // so a seeded network yields a usable key; the collection's network requests send it
    // instead of the store key.
    if (isset($store) && class_exists(\Fleetbase\Storefront\Models\Network::class)) {
        $network = \Fleetbase\Storefront\Models\Network::withoutGlobalScopes()
            ->where(['company_uuid' => $company->uuid, 'name' => 'CI Contract Network'])
            ->first();

        if (!$network) {
            $network = \Fleetbase\Storefront\Models\Network::create([
                'company_uuid'    => $company->uuid,
                'created_by_uuid' => $user->uuid,
                'name'            => 'CI Contract Network',
                'description'     => 'Seeded by the API contract run.',
                'currency'        => 'USD',
                'online'          => 1,
            ]);
        }

        // Without a member store the listing is empty and proves nothing.
        $network->addStore($store);

        echo 'MINTED_NETWORK_KEY=' . $network->fresh()->key . PHP_EOL;
        echo 'MINTED_NETWORK_ID=' . $network->public_id . PHP_EOL;
    }

    /* ============================================================
     | STORE LOCATION (Storefront)
     * ============================================================ */

    // Retrieve Location answered 404 because the store has no locations at all — List
    // Locations returned [] and nothing could set {{location_id}}. A store location is
    // also what a real storefront sends as the delivery quote's `origin`.
    if (isset($store) && class_exists(\Fleetbase\Storefront\Models\StoreLocation::class)) {
        $storeLocation = \Fleetbase\Storefront\Models\StoreLocation::withoutGlobalScopes()
            ->where(['store_uuid' => $store->uuid, 'name' => 'CI Contract Location'])
            ->first();

        if (!$storeLocation) {
            // The location needs a Place to point at. createFromCoordinates persists one
            // scoped to the company, which is what StoreLocation::place expects.
            $place = \Fleetbase\FleetOps\Models\Place::createFromCoordinates(
                new \Fleetbase\LaravelMysqlSpatial\Types\Point(1.3521, 103.8198),
                ['company_uuid' => $company->uuid, 'name' => 'CI Contract Location'],
                true
            );

            $storeLocation = \Fleetbase\Storefront\Models\StoreLocation::create([
                'store_uuid'      => $store->uuid,
                'created_by_uuid' => $user->uuid,
                'place_uuid'      => $place->uuid,
                'name'            => 'CI Contract Location',
            ]);
        }

        echo 'SEEDED_STORE_LOCATION=' . $storeLocation->fresh()->public_id . PHP_EOL;
    }

    /* ============================================================
     | SERVICE RATE (Storefront delivery quotes)
     * ============================================================ */

    // Retrieve a Delivery Service Quote answered "No service rates available!". The
    // storefront quote asks ServiceRate::getServicableForPlaces() for rates matching the
    // order config key and the cart's currency, then filters by geography: a rate with a
    // service area or a zone is only servicable when the destination falls inside it.
    //
    // A rate with NEITHER skips both containment checks and is servicable everywhere,
    // which is what a contract run wants — the quote is then exercised without depending
    // on a seeded polygon that the collection's coordinates happen to fall inside.
    if (class_exists(\Fleetbase\FleetOps\Models\ServiceRate::class)) {
        $serviceRate = \Fleetbase\FleetOps\Models\ServiceRate::withoutGlobalScopes()
            ->where(['company_uuid' => $company->uuid, 'service_name' => 'CI Contract Flat Rate'])
            ->first();

        if (!$serviceRate) {
            $serviceRate = \Fleetbase\FleetOps\Models\ServiceRate::create([
                'company_uuid'            => $company->uuid,
                'service_name'            => 'CI Contract Flat Rate',
                // Matches Storefront::getSessionOrderConfig()'s default key, which is what
                // the quote filters `service_type` on.
                'service_type'            => 'storefront',
                'rate_calculation_method' => 'fixed_rate',
                'base_fee'                => 500,
                // Must match the cart's currency — the query lowercases and compares it.
                'currency'                => 'USD',
                'duration_terms'          => 'Same day',
                'estimated_days'          => 1,
            ]);
        }

        echo 'SEEDED_SERVICE_RATE=' . $serviceRate->fresh()->public_id . PHP_EOL;
    }

    /* ============================================================
     | STRIPE TEST GATEWAY (Storefront checkout + Ledger top-up)
     * ============================================================ */

    // Stripe is configured by a Gateway ROW, not by env vars: Storefront resolves it with
    // Storefront::findGateway('stripe') scoped to the store, then reads
    // $gateway->config->secret_key. With no row the checkout chain answers
    // "Stripe not setup." and the ledger top-up answers "No query results for Gateway".
    //
    // Both values come from the CI environment and are TEST-mode by contract — the action
    // passes STRIPE_TEST_KEY / STRIPE_TEST_SECRET. Nothing is seeded when the secret is
    // absent, so a fork without the org secrets still runs everything else.
    $stripePublishable = getenv('CI_STRIPE_PUBLISHABLE_KEY') ?: '';
    $stripeSecret      = getenv('CI_STRIPE_SECRET_KEY') ?: '';

    if ($stripeSecret && isset($store) && class_exists(\Fleetbase\Storefront\Models\Gateway::class)) {
        $storefrontGateway = \Fleetbase\Storefront\Models\Gateway::withoutGlobalScopes()
            ->where(['owner_uuid' => $store->uuid, 'code' => 'stripe'])
            ->first();

        if (!$storefrontGateway) {
            $storefrontGateway               = new \Fleetbase\Storefront\Models\Gateway();
            $storefrontGateway->company_uuid = $company->uuid;
            $storefrontGateway->owner_uuid   = $store->uuid;
            // Assigned through the mutator, which runs Utils::getMutationType() — every
            // other writer in the package sets it this way, and storing the FQCN directly
            // produces a value findGateway's owner scoping will not match.
            $storefrontGateway->owner_type   = 'storefront:store';
            $storefrontGateway->code         = 'stripe';
            $storefrontGateway->type         = 'stripe';
        }

        $storefrontGateway->created_by_uuid = $user->uuid;
        $storefrontGateway->name            = 'CI Contract Stripe (test mode)';
        $storefrontGateway->sandbox         = true;
        $storefrontGateway->config          = [
            'public_key' => $stripePublishable,
            'secret_key' => $stripeSecret,
        ];
        $storefrontGateway->save();

        echo 'SEEDED_STOREFRONT_GATEWAY=' . $storefrontGateway->fresh()->public_id . PHP_EOL;
    }

    if ($stripeSecret && class_exists(\Fleetbase\Ledger\Models\Gateway::class)) {
        // A different model with a different shape: keyed by `driver` rather than `code`,
        // and its Stripe driver reads `publishable_key` where Storefront reads
        // `public_key`. Seeding one does not seed the other.
        $ledgerGateway = \Fleetbase\Ledger\Models\Gateway::withoutGlobalScopes()
            ->where(['company_uuid' => $company->uuid, 'driver' => 'stripe'])
            ->first();

        if (!$ledgerGateway) {
            $ledgerGateway               = new \Fleetbase\Ledger\Models\Gateway();
            $ledgerGateway->company_uuid = $company->uuid;
            $ledgerGateway->driver       = 'stripe';
        }

        $ledgerGateway->created_by_uuid = $user->uuid;
        $ledgerGateway->name            = 'CI Contract Stripe (test mode)';
        $ledgerGateway->is_sandbox      = true;
        $ledgerGateway->environment     = 'sandbox';
        $ledgerGateway->status          = 'active';
        $ledgerGateway->config          = [
            'publishable_key' => $stripePublishable,
            'secret_key'      => $stripeSecret,
        ];
        $ledgerGateway->save();

        echo 'SEEDED_LEDGER_GATEWAY=' . $ledgerGateway->fresh()->public_id . PHP_EOL;
    }

    if (!$stripeSecret) {
        echo '::notice::No Stripe test secret provided; gateway-backed requests will report the gateway as unconfigured.' . PHP_EOL;
    }

    /* ============================================================
     | LEDGER INVOICE FIXTURE (Fleetbase Ledger API / Public Invoices)
     * ============================================================ */

    // The three public-invoice endpoints are addressed by an invoice public_id, and
    // {{invoice_public_id}} is set by nothing — no request in the collection creates an
    // invoice, because the public API exposes no invoice-creation endpoint. Seeding one
    // is the only way to reach them.
    //
    // Status is deliberately NOT 'draft': PublicInvoiceController::show answers 403 for
    // draft invoices ("not yet available"), so a draft would exercise the guard rather
    // than the endpoint. 'sent' also lets show() transition it to 'viewed' on first
    // access, which is the behaviour worth covering.
    if (class_exists(\Fleetbase\Ledger\Models\Invoice::class)) {
        $invoice = \Fleetbase\Ledger\Models\Invoice::withoutGlobalScopes()
            ->where(['company_uuid' => $company->uuid, 'number' => 'CI-CONTRACT-0001'])
            ->first();

        if (!$invoice) {
            $invoice = \Fleetbase\Ledger\Models\Invoice::create([
                'company_uuid'    => $company->uuid,
                'created_by_uuid' => $user->uuid,
                'number'          => 'CI-CONTRACT-0001',
                'date'            => \Illuminate\Support\Carbon::now()->toDateString(),
                'due_date'        => \Illuminate\Support\Carbon::now()->addDays(30)->toDateString(),
                'subtotal'        => 10000,
                'tax'             => 0,
                'total_amount'    => 10000,
                'amount_paid'     => 0,
                'balance'         => 10000,
                'currency'        => 'USD',
                'status'          => 'sent',
                'notes'           => 'Seeded by the API contract run.',
            ]);
        }

        // Reasserted on reruns: show() flips `sent` to `viewed` on first access, and a
        // later run would otherwise start from whatever the previous one left behind.
        $invoice->status    = 'sent';
        $invoice->viewed_at = null;
        $invoice->save();

        echo 'SEEDED_INVOICE_ID=' . $invoice->fresh()->public_id . PHP_EOL;
    } else {
        echo '::warning::Ledger not installed; the invoice fixture was skipped.' . PHP_EOL;
    }

    echo 'SEEDED_CUSTOMER_IDENTITY=' . $customerIdentity . PHP_EOL;
    echo 'SEEDED_CUSTOMER_PHONE=' . $customerPhone . PHP_EOL;
    echo 'SEEDED_VERIFICATION_CODE=' . $customerCode . PHP_EOL;
} catch (\Throwable $e) {
    echo PHP_EOL . 'MINT_ERROR: ' . get_class($e) . ': ' . $e->getMessage() . PHP_EOL;
    echo $e->getFile() . ':' . $e->getLine() . PHP_EOL;
}