Skip to content

Modular logistics and supply chain operating system (LSOS)

6.4 KB
Raw Blame
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { action, getProperties } from '@ember/object';
import { isBlank } from '@ember/utils';
import { task } from 'ember-concurrency';
import { onboardValidationsFor } from '../../validations/onboard';
import lookupValidator from 'ember-changeset-validations';
import Changeset from 'ember-changeset';

export default class OnboardingFormComponent extends Component {
    @service fetch;
    @service session;
    @service router;
    @service notifications;
    @service urlSearchParams;
    @service oauth;
    @tracked name;
    @tracked email;
    @tracked phone;
    @tracked organization_name;
    @tracked password;
    @tracked password_confirmation;
    @tracked error;

    /**
     * Whether the API offers this signup a free Fleetbase Hosted Routing key: only
     * the first admin of a self-hosted install, while ROUTING_AUTO_REGISTER is on
     * and no Valhalla server of the admin's own is configured.
     *
     * @var {Boolean}
     */
    @tracked offersHostedRouting = false;

    /**
     * The admin's choice, on by default. Sent as `hosted_routing`; the API only
     * registers when it is true.
     *
     * @var {Boolean}
     */
    @tracked hostedRouting = true;

    constructor() {
        super(...arguments);

        // A signup that began with "Continue with <provider>" arrives here carrying a
        // registration intent the API issued after verifying the identity. Prefill what
        // the provider told us and drop the password fields — the intent is the
        // credential. Everything else is still collected exactly as before.
        const registration = this.oauth.registration;

        if (registration?.intent) {
            this.oauthIntent = registration.intent;
            this.name = registration.prefill?.name ?? null;
            this.email = registration.prefill?.email ?? null;
            this.emailVerifiedByProvider = registration.prefill?.email_verified === true;
        }

        this.loadHostedRoutingOffer.perform();
    }

    @task *loadHostedRoutingOffer() {
        try {
            const { hosted_routing } = yield this.fetch.get('onboard/should-onboard', {}, { rawError: true });
            this.offersHostedRouting = hosted_routing === true;
        } catch {
            this.offersHostedRouting = false;
        }
    }

    @action toggleHostedRouting(value) {
        this.hostedRouting = value;
    }

    /**
     * The registration intent, when this signup started from a provider.
     *
     * @var {String|null}
     */
    @tracked oauthIntent = null;

    get hasOauthIntent() {
        return !isBlank(this.oauthIntent);
    }

    /**
     * Set once a provider button is pressed, while the browser leaves for the provider.
     *
     * @var {Boolean}
     */
    @tracked isStartingProvider = false;

    /**
     * Sign up with a provider. The same handshake as the login page's buttons, marked as
     * a sign-up: an unknown identity comes back here with the form prefilled, and one
     * that already has an account is signed in and told so.
     */
    @action continueWithProvider(provider) {
        if (this.isStartingProvider || !provider?.id) {
            return;
        }

        this.isStartingProvider = true;
        this.oauth.startAuthorization(provider.id, { intent: 'signup' });
    }

    /**
     * Whether the provider vouched for the email it gave us.
     *
     * @var {Boolean}
     */
    @tracked emailVerifiedByProvider = false;

    /**
     * An email the provider verified is locked: it is what lets the account skip email
     * verification. One the provider did not verify is only a suggestion, so the person
     * can change it, and whatever they enter is verified by code as usual.
     */
    get isEmailLocked() {
        return this.hasOauthIntent && this.emailVerifiedByProvider && !isBlank(this.email);
    }

    get requiredFields() {
        return this.hasOauthIntent ? ['name', 'email', 'phone', 'organization_name'] : ['name', 'email', 'phone', 'organization_name', 'password', 'password_confirmation'];
    }

    get filled() {
        // eslint-disable-next-line ember/no-get
        const input = getProperties(this, ...this.requiredFields);
        return Object.values(input).every((val) => !isBlank(val));
    }

    @task *onboard(event) {
        event?.preventDefault?.();

        // eslint-disable-next-line ember/no-get
        const input = getProperties(this, ...this.requiredFields);
        const validations = onboardValidationsFor({ hasOauthIntent: this.hasOauthIntent });
        const changeset = new Changeset(input, lookupValidator(validations), validations);

        yield changeset.validate();

        if (changeset.get('isInvalid')) {
            const errorMessage = changeset.errors.firstObject.validation.firstObject;

            this.notifications.error(errorMessage);
            return;
        }

        // Set user timezone
        input.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

        if (this.hasOauthIntent) {
            input.oauth_intent = this.oauthIntent;
        }

        if (this.offersHostedRouting) {
            input.hosted_routing = this.hostedRouting === true;
        }

        try {
            const { status, skipVerification, token, session } = yield this.fetch.post('onboard/create-account', input);
            if (status !== 'success') {
                this.notifications.error('Onboard failed');
                return;
            }

            // Single use: whether or not the rest of the wizard completes, this intent
            // is now spent server side and must not be replayed.
            this.oauth.clearRegistration();

            // save session
            this.args.context.persist('session', session);

            if (skipVerification === true && token) {
                // only manually authenticate if skip verification
                this.session.isOnboarding().manuallyAuthenticate(token);

                yield this.router.transitionTo('console');
                return this.notifications.success('Welcome to Fleetbase!');
            } else {
                this.args.orchestrator.next();
                this.urlSearchParams.setParamsToCurrentUrl({
                    step: this.args.orchestrator?.current?.id,
                    session,
                });
            }
        } catch (err) {
            this.notifications.serverError(err);
        }
    }
}