Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
test(console): finish the models tier and cover the 2FA and notifications controllers
Ronald A. Richardson62ac7c1903b1
diff --git a/console/tests/unit/controllers/auth/two-fa-test.js b/console/tests/unit/controllers/auth/two-fa-test.jsindex 83ce5e08..5ae6b85c 100644--- a/console/tests/unit/controllers/auth/two-fa-test.js+++ b/console/tests/unit/controllers/auth/two-fa-test.js@@ -1,6 +1,7 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';import Service from '@ember/service';+import { settled } from '@ember/test-helpers';module('Unit | Controller | auth/two-fa', function (hooks) {setupTest(hooks);@@ -43,3 +44,181 @@ module('Unit | Controller | auth/two-fa', function (hooks) {assert.true(this.owner.lookup('service:notifications').errored, 'reports an invalid-session error');});});++module('Unit | Controller | auth/two-fa | verification flow', function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.posted = [];+ this.postResponse = { authToken: 'auth-token' };+ this.postRejectsWith = null;+ const context = this;++ class FetchStub extends Service {+ post(path, payload) {+ context.posted.push({ path, payload });+ return context.postRejectsWith ? Promise.reject(context.postRejectsWith) : Promise.resolve(context.postResponse);+ }+ }+ class NotificationsStub extends Service {+ errors = [];+ successes = [];+ infos = [];+ error(message) {+ this.errors.push(message);+ }+ success(message) {+ this.successes.push(message);+ }+ info(message) {+ this.infos.push(message);+ }+ }+ class SessionStub extends Service {+ authenticated = [];+ authenticate(authenticator, credentials) {+ this.authenticated.push({ authenticator, credentials });+ return Promise.resolve();+ }+ }++ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:session', SessionStub);++ this.build = () => {+ const controller = this.owner.lookup('controller:auth/two-fa');+ this.transitions = [];+ Object.defineProperty(controller.router, 'transitionTo', {+ configurable: true,+ value: (routeName) => {+ this.transitions.push(routeName);+ return Promise.resolve(routeName);+ },+ });+ return controller;+ };+ this.notifications = () => this.owner.lookup('service:notifications');+ });++ test('verifyCode posts the code, authenticates and lands in the console', async function (assert) {+ const controller = this.build();+ controller.token = 'tok';+ controller.clientToken = 'client-tok';+ controller.identity = '[email protected]';+ controller.verificationCode = '123456';++ await controller.verifyCode();++ assert.deepEqual(this.posted, [{ path: 'two-fa/verify', payload: { token: 'tok', code: '123456', clientToken: 'client-tok', identity: '[email protected]' } }]);+ assert.deepEqual(this.owner.lookup('service:session').authenticated, [+ { authenticator: 'authenticator:fleetbase', credentials: { authToken: 'auth-token', identity: '[email protected]' } },+ ]);+ assert.deepEqual(this.transitions, ['console']);+ assert.strictEqual(this.notifications().successes.length, 1, 'success is reported');+ });++ test('verifyCode prevents the form from submitting itself', async function (assert) {+ const controller = this.build();+ controller.clientToken = 'client-tok';+ let prevented = false;++ await controller.verifyCode({ preventDefault: () => (prevented = true) });++ assert.true(prevented);+ });++ test('an expired code is reported as information rather than an error', async function (assert) {+ this.postRejectsWith = new Error('Verification code has expired');+ const controller = this.build();+ controller.clientToken = 'client-tok';++ await controller.verifyCode();++ assert.strictEqual(this.notifications().infos.length, 1, 'the user is told the code lapsed');+ assert.strictEqual(this.notifications().errors.length, 0, 'and it is not framed as a failure');+ assert.deepEqual(this.transitions, [], 'nothing navigates');+ });++ test('any other verification failure is reported as an error', async function (assert) {+ this.postRejectsWith = new Error('invalid code');+ const controller = this.build();+ controller.clientToken = 'client-tok';++ await controller.verifyCode();++ assert.strictEqual(this.notifications().errors.length, 1);+ assert.strictEqual(this.notifications().infos.length, 0);+ });++ test('handleOtpInput stores the code and immediately verifies it', async function (assert) {+ const controller = this.build();+ controller.clientToken = 'client-tok';++ controller.handleOtpInput('654321');++ assert.strictEqual(controller.verificationCode, '654321');+ await settled();+ assert.strictEqual(this.posted.at(-1).payload.code, '654321', 'the entered code is submitted without a further click');+ });++ test('resendCode restarts the countdown with the new client token', async function (assert) {+ const expiry = new Date('2026-03-01T12:00:00');+ this.postResponse = { clientToken: btoa(`2026-03-01T12:00:00|session`) };+ const controller = this.build();+ controller.identity = '[email protected]';+ controller.token = 'tok';+ controller.isCodeExpired = true;++ await controller.resendCode();++ assert.deepEqual(this.posted, [{ path: 'two-fa/resend', payload: { identity: '[email protected]', token: 'tok' } }]);+ assert.strictEqual(controller.clientToken, this.postResponse.clientToken);+ assert.true(controller.countdownReady, 'the countdown restarts');+ assert.false(controller.isCodeExpired, 'and the expiry flag is cleared');+ assert.true(controller.twoFactorSessionExpiresAfter instanceof Date, 'the new expiry is decoded');+ assert.strictEqual(this.notifications().successes.length, 1);+ assert.ok(expiry instanceof Date);+ });++ test('a resend that returns no client token is reported as a failure', async function (assert) {+ this.postResponse = {};+ const controller = this.build();++ await controller.resendCode();++ assert.strictEqual(this.notifications().errors.length, 1);+ assert.false(controller.countdownReady, 'the countdown stays stopped');+ });++ test('a failed resend request is reported as a failure', async function (assert) {+ this.postRejectsWith = new Error('resend unavailable');+ const controller = this.build();++ await controller.resendCode();++ assert.strictEqual(this.notifications().errors.length, 1);+ assert.false(controller.countdownReady);+ });++ test('cancelTwoFactor invalidates the session and returns to login', async function (assert) {+ const controller = this.build();+ controller.identity = '[email protected]';+ controller.token = 'tok';++ await controller.cancelTwoFactor();++ assert.deepEqual(this.posted, [{ path: 'two-fa/invalidate', payload: { identity: '[email protected]', token: 'tok' } }]);+ assert.deepEqual(this.transitions, ['auth.login']);+ });++ test('convertUtcToClientTime shifts a UTC stamp by the local offset', function (assert) {+ const controller = this.build();+ const utc = '2026-03-01T12:00:00Z';++ const converted = controller.convertUtcToClientTime(utc);++ assert.true(converted instanceof Date);+ assert.strictEqual(converted.getTime(), new Date(utc).getTime() - new Date().getTimezoneOffset() * 60 * 1000);+ });+});diff --git a/console/tests/unit/controllers/console/notifications-test.js b/console/tests/unit/controllers/console/notifications-test.jsindex 5fc381c2..14d28e05 100644--- a/console/tests/unit/controllers/console/notifications-test.js+++ b/console/tests/unit/controllers/console/notifications-test.js@@ -1,5 +1,6 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';+import Service from '@ember/service';module('Unit | Controller | console/notifications', function (hooks) {setupTest(hooks);@@ -34,3 +35,165 @@ module('Unit | Controller | console/notifications', function (hooks) {assert.deepEqual(controller.selected, [], 'clears when all are already selected');});});++module('Unit | Controller | console/notifications | bulk actions', function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.requests = [];+ this.rejectsWith = null;+ const context = this;++ class FetchStub extends Service {+ delete(path, payload) {+ context.requests.push({ method: 'delete', path, payload });+ return context.rejectsWith ? Promise.reject(context.rejectsWith) : Promise.resolve({ ok: true });+ }+ put(path, payload) {+ context.requests.push({ method: 'put', path, payload });+ return context.rejectsWith ? Promise.reject(context.rejectsWith) : Promise.resolve({ ok: true });+ }+ }+ class NotificationsStub extends Service {+ successes = [];+ infos = [];+ serverErrors = [];+ success(message) {+ this.successes.push(message);+ }+ info(message) {+ this.infos.push(message);+ }+ serverError(error) {+ this.serverErrors.push(error);+ }+ }+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);++ // The universe singleton cannot be swapped, so record what the controller publishes+ // on the instance it is actually handed. `on` must be neutralised before lookup,+ // since the constructor subscribes immediately.+ const universe = this.owner.lookup('service:universe');+ this.published = [];+ Object.defineProperty(universe, 'on', { configurable: true, value: () => {} });+ Object.defineProperty(universe, 'trigger', {+ configurable: true,+ value: (event, payload) => this.published.push({ event, payload }),+ });++ this.build = () => {+ const controller = this.owner.lookup('controller:console/notifications');+ this.refreshes = 0;+ Object.defineProperty(controller.router, 'refresh', {+ configurable: true,+ value: () => {+ this.refreshes++;+ return 'refreshed';+ },+ });+ return controller;+ };+ this.notifications = () => this.owner.lookup('service:notifications');+ });++ test('the controller starts on the first page, newest first', function (assert) {+ const controller = this.build();++ assert.strictEqual(controller.page, 1);+ assert.strictEqual(controller.limit, 20);+ assert.strictEqual(controller.sort, '-created_at', 'newest notifications lead');+ assert.deepEqual(controller.selected, []);+ });++ test('the constructor refreshes the list when a notification arrives', function (assert) {+ const universe = this.owner.lookup('service:universe');+ let subscribed;+ Object.defineProperty(universe, 'on', {+ configurable: true,+ value: (event, handler) => (subscribed = { event, handler }),+ });++ const controller = this.build();++ assert.strictEqual(subscribed.event, 'notification.received');+ subscribed.handler();+ assert.strictEqual(this.refreshes, 1, 'an incoming notification reloads the page');+ assert.ok(controller);+ });++ test('delete removes the selected notifications and announces it', async function (assert) {+ const controller = this.build();+ const selected = [{ id: 'n_1' }, { id: 'n_2' }];+ controller.selected.pushObjects(selected);++ await controller.delete();++ assert.deepEqual(this.requests, [{ method: 'delete', path: 'notifications/bulk-delete', payload: { notifications: ['n_1', 'n_2'] } }]);+ assert.deepEqual(this.notifications().successes, ['2 notifications deleted']);+ assert.strictEqual(this.published[0].event, 'notifications.deleted');+ assert.deepEqual(this.published[0].payload, selected, 'the deleted rows are published for other views');+ assert.deepEqual(controller.selected, [], 'the selection is cleared');+ assert.strictEqual(this.refreshes, 1);+ });++ test('a failed delete is reported and the selection is kept', async function (assert) {+ const failure = new Error('bulk delete failed');+ this.rejectsWith = failure;+ const controller = this.build();+ controller.selected.pushObject({ id: 'n_1' });++ await controller.delete();++ assert.deepEqual(this.notifications().serverErrors, [failure]);+ assert.strictEqual(controller.selected.length, 1, 'nothing was cleared, so the user can retry');+ assert.strictEqual(this.refreshes, 0);+ });++ test('read only marks the unread notifications in the selection', async function (assert) {+ const controller = this.build();+ controller.selected.pushObjects([+ { id: 'n_1', unread: true },+ { id: 'n_2', unread: false },+ { id: 'n_3', unread: true },+ ]);++ await controller.read();++ assert.deepEqual(this.requests, [{ method: 'put', path: 'notifications/mark-as-read', payload: { notifications: ['n_1', 'n_3'] } }]);+ assert.deepEqual(this.notifications().successes, ['2 notifications marked as read'], 'the already-read one is not counted');+ assert.strictEqual(this.published[0].event, 'notifications.read');+ assert.deepEqual(controller.selected, []);+ assert.strictEqual(this.refreshes, 1);+ });++ test('a failed read is reported and the selection is kept', async function (assert) {+ const failure = new Error('mark as read failed');+ this.rejectsWith = failure;+ const controller = this.build();+ controller.selected.pushObject({ id: 'n_1', unread: true });++ await controller.read();++ assert.deepEqual(this.notifications().serverErrors, [failure]);+ assert.strictEqual(controller.selected.length, 1);+ });++ test('markNotificationAsRead marks one row and announces it', async function (assert) {+ const controller = this.build();+ let marked = 0;+ const notification = {+ id: 'n_1',+ markAsRead: () => {+ marked++;+ return Promise.resolve();+ },+ };++ await controller.markNotificationAsRead(notification);++ assert.strictEqual(marked, 1);+ assert.deepEqual(this.notifications().infos, ['Notification marked as read.']);+ assert.deepEqual(this.published[0], { event: 'notifications.read', payload: [notification] });+ });+});diff --git a/console/tests/unit/models/alert-test.js b/console/tests/unit/models/alert-test.jsindex f52736ee..8a0053e1 100644--- a/console/tests/unit/models/alert-test.js+++ b/console/tests/unit/models/alert-test.js@@ -1,4 +1,5 @@import { module, test } from 'qunit';+import { format } from 'date-fns';import { setupTest } from '@fleetbase/console/tests/helpers';import { subMinutes } from 'date-fns';@@ -181,3 +182,60 @@ module('Unit | Model | alert', function (hooks) {assert.strictEqual(this.alert({ context: {}, rule: { threshold: 5 } }).thresholdExceeded, null);});});++module('Unit | Model | alert | duration formatting', function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.store = this.owner.lookup('service:store');+ // These three getters read derived minute counts the model does not declare as+ // attributes, so each case needs its own record — assigning would not invalidate+ // the @computed that already cached a value.+ this.withMinutes = (property, minutes) => {+ const alert = this.store.createRecord('alert');+ Object.defineProperty(alert, property, { configurable: true, value: minutes });+ return alert;+ };+ });++ test('acknowledgment duration is shown in minutes, hours or days', function (assert) {+ assert.strictEqual(this.withMinutes('acknowledgmentDurationMinutes', 0).acknowledgmentDurationFormatted, null, 'nothing to report');+ assert.strictEqual(this.withMinutes('acknowledgmentDurationMinutes', 45).acknowledgmentDurationFormatted, '45m');+ assert.strictEqual(this.withMinutes('acknowledgmentDurationMinutes', 150).acknowledgmentDurationFormatted, '2h 30m');+ assert.strictEqual(this.withMinutes('acknowledgmentDurationMinutes', 1560).acknowledgmentDurationFormatted, '1d 2h');+ });++ test('resolution duration is shown in minutes, hours or days', function (assert) {+ assert.strictEqual(this.withMinutes('resolutionDurationMinutes', 0).resolutionDurationFormatted, null);+ assert.strictEqual(this.withMinutes('resolutionDurationMinutes', 5).resolutionDurationFormatted, '5m');+ assert.strictEqual(this.withMinutes('resolutionDurationMinutes', 90).resolutionDurationFormatted, '1h 30m');+ assert.strictEqual(this.withMinutes('resolutionDurationMinutes', 2880).resolutionDurationFormatted, '2d 0h');+ });++ test('age is shown in minutes, hours or days', function (assert) {+ assert.strictEqual(this.withMinutes('ageMinutes', 30).ageFormatted, '30m');+ assert.strictEqual(this.withMinutes('ageMinutes', 61).ageFormatted, '1h 1m');+ assert.strictEqual(this.withMinutes('ageMinutes', 4321).ageFormatted, '3d 0h');+ });++ test('an unrecognised urgency falls back to the low styling', function (assert) {+ const low = this.store.createRecord('alert');+ Object.defineProperty(low, 'urgencyLevel', { configurable: true, value: 'low' });++ const unknown = this.store.createRecord('alert');+ Object.defineProperty(unknown, 'urgencyLevel', { configurable: true, value: 'not-a-level' });++ assert.strictEqual(unknown.urgencyBadgeClass, low.urgencyBadgeClass, 'unknown urgencies are styled as low');+ });++ test('the created and updated getters read as relative durations', function (assert) {+ const alert = this.store.createRecord('alert', {+ created_at: new Date('2026-01-15T10:30:00Z'),+ updated_at: new Date('2026-02-20T08:05:00Z'),+ });++ assert.ok(alert.createdAgo.endsWith(' ago'), `createdAgo reads as a duration (got ${alert.createdAgo})`);+ assert.ok(alert.updatedAgo.endsWith(' ago'), `updatedAgo reads as a duration (got ${alert.updatedAgo})`);+ assert.strictEqual(alert.updatedAt, format(new Date('2026-02-20T08:05:00Z'), 'yyyy-MM-dd HH:mm'));+ });+});diff --git a/console/tests/unit/models/category-test.js b/console/tests/unit/models/category-test.jsindex 5046a4e7..f5bdd49c 100644--- a/console/tests/unit/models/category-test.js+++ b/console/tests/unit/models/category-test.js@@ -22,3 +22,15 @@ module('Unit | Model | category | customerId', function (hooks) {assert.strictEqual(store.createRecord('category', { public_id: 'category_xyz' }).customerId, 'category_xyz', 'ids that are not contacts are left alone');});});++module('Unit | Model | category | editing state', function (hooks) {+ setupTest(hooks);++ test('a category starts with no custom fields and not in edit mode', function (assert) {+ const category = this.owner.lookup('service:store').createRecord('category');++ assert.deepEqual(category.customFields, [], 'no custom fields are attached yet');+ assert.false(category.isEditing, 'and it is not being edited');+ assert.strictEqual(category.parent_category, undefined, 'nor nested under a parent');+ });+});diff --git a/console/tests/unit/models/chat-message-test.js b/console/tests/unit/models/chat-message-test.jsindex 5775b8aa..5e2cb1c1 100644--- a/console/tests/unit/models/chat-message-test.js+++ b/console/tests/unit/models/chat-message-test.js@@ -1,5 +1,6 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';+import { format, formatDistanceToNow } from 'date-fns';module('Unit | Model | chat-message', function (hooks) {setupTest(hooks);@@ -28,3 +29,18 @@ module('Unit | Model | chat-message', function (hooks) {assert.strictEqual(msg.createdAt, null);});});++module('Unit | Model | chat-message | timestamps', function (hooks) {+ setupTest(hooks);++ test('the timestamp getters format both dates and read as suffixed durations', function (assert) {+ const created = new Date('2026-01-15T10:30:00Z');+ const updated = new Date('2026-02-20T08:05:00Z');+ const message = this.owner.lookup('service:store').createRecord('chat-message', { created_at: created, updated_at: updated });++ assert.strictEqual(message.createdAt, format(created, 'PP HH:mm'));+ assert.strictEqual(message.updatedAt, format(updated, 'PP HH:mm'));+ assert.strictEqual(message.createdAgo, formatDistanceToNow(created, { addSuffix: true }));+ assert.strictEqual(message.updatedAgo, formatDistanceToNow(updated, { addSuffix: true }));+ });+});diff --git a/console/tests/unit/models/notification-test.js b/console/tests/unit/models/notification-test.jsindex c3c62260..acc3de9a 100644--- a/console/tests/unit/models/notification-test.js+++ b/console/tests/unit/models/notification-test.js@@ -1,7 +1,7 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';-import { format } from 'date-fns';+import { format, formatDistanceToNow } from 'date-fns';module('Unit | Model | notification', function (hooks) {setupTest(hooks);@@ -68,3 +68,15 @@ module('Unit | Model | notification | read state', function (hooks) {assert.strictEqual(notification.read_at.getTime(), readAt.getTime(), 'the original read time is kept');});});++module('Unit | Model | notification | created timestamps', function (hooks) {+ setupTest(hooks);++ test('createdAt and createdAgo describe when the notification arrived', function (assert) {+ const created = new Date('2026-01-15T10:30:00Z');+ const notification = this.owner.lookup('service:store').createRecord('notification', { created_at: created });++ assert.strictEqual(notification.createdAt, format(created, 'yyyy-MM-dd HH:mm'));+ assert.strictEqual(notification.createdAgo, formatDistanceToNow(created));+ });+});diff --git a/console/tests/unit/models/user-test.js b/console/tests/unit/models/user-test.jsindex fe3a416f..eeb48bf4 100644--- a/console/tests/unit/models/user-test.js+++ b/console/tests/unit/models/user-test.js@@ -1,5 +1,6 @@import { module, test } from 'qunit';import { setupTest } from '@fleetbase/console/tests/helpers';+import { format, formatDistanceToNow } from 'date-fns';import Service from '@ember/service';module('Unit | Model | user', function (hooks) {@@ -169,3 +170,16 @@ module('Unit | Model | user', function (hooks) {assert.deepEqual(this.calls.at(-1), { method: 'post', path: 'users/resend-invite', payload: { user: 'user_1' } });});});++module('Unit | Model | user | timestamps', function (hooks) {+ setupTest(hooks);++ test('the short updated stamp and the relative created stamp are exposed', function (assert) {+ const created = new Date('2026-01-15T10:30:00Z');+ const updated = new Date('2026-02-20T08:05:00Z');+ const user = this.owner.lookup('service:store').createRecord('user', { created_at: created, updated_at: updated });++ assert.strictEqual(user.updatedAtShort, format(updated, 'PP'));+ assert.strictEqual(user.createdAgo, formatDistanceToNow(created));+ });+});