Files
Fleetbase-Mirror-Repo/console/app/controllers/onboard/index.js
2023-10-10 20:43:18 +08:00

141 lines
3.5 KiB
JavaScript

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { action, getProperties } from '@ember/object';
import OnboardValidations from '../../validations/onboard';
import lookupValidator from 'ember-changeset-validations';
import Changeset from 'ember-changeset';
export default class OnboardIndexController extends Controller {
/**
* Inject the `fetch` service
*
* @memberof OnboardIndexController
*/
@service fetch;
/**
* Inject the `session` service
*
* @memberof OnboardIndexController
*/
@service session;
/**
* Inject the `notifications` service
*
* @memberof OnboardIndexController
*/
@service notifications;
/**
* The name input field.
*
* @memberof OnboardIndexController
*/
@tracked name;
/**
* The email input field.
*
* @memberof OnboardIndexController
*/
@tracked email;
/**
* The phone input field.
*
* @memberof OnboardIndexController
*/
@tracked phone;
/**
* The organization_name input field.
*
* @memberof OnboardIndexController
*/
@tracked organization_name;
/**
* The password input field.
*
* @memberof OnboardIndexController
*/
@tracked password;
/**
* The name password confirmation field.
*
* @memberof OnboardIndexController
*/
@tracked password_confirmation;
/**
* The property for error message.
*
* @memberof OnboardIndexController
*/
@tracked error;
/**
* The loading state of the onboard request.
*
* @memberof OnboardIndexController
*/
@tracked isLoading = false;
/**
* The ready state for the form.
*
* @memberof OnboardIndexController
*/
@tracked readyToSubmit = false;
/**
* Start the onboard process.
*
* @return {Promise}
* @memberof OnboardIndexController
*/
@action async startOnboard(event) {
event.preventDefault();
// eslint-disable-next-line ember/no-get
const input = getProperties(this, 'name', 'email', 'phone', 'organization_name', 'password', 'password_confirmation');
const changeset = new Changeset(input, lookupValidator(OnboardValidations), OnboardValidations);
await changeset.validate();
if (changeset.get('isInvalid')) {
const errorMessage = changeset.errors.firstObject.validation.firstObject;
this.notifications.error(errorMessage);
return;
}
this.isLoading = true;
return this.fetch
.post('onboard/create-account', input)
.then((response) => {
if (response.status === 'success') {
this.session.isOnboarding().manuallyAuthenticate(response.token);
if (response.skipVerification === true) {
return this.transitionToRoute('console').then(() => {
this.notifications.success('Welcome to Fleetbase!');
});
}
return this.transitionToRoute('onboard.verify-email', { queryParams: { hello: response.session } });
}
})
.catch((error) => {
this.notifications.serverError(error);
})
.finally(() => {
this.isLoading = false;
});
}
}