@fleetbase/ember-core 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -40,6 +40,11 @@ export default class CrudService extends Service {
40
40
  */
41
41
  @service store;
42
42
 
43
+ /**
44
+ * @service currentUser
45
+ */
46
+ @service currentUser;
47
+
43
48
  /**
44
49
  * Generic deletion modal with options
45
50
  *
@@ -198,25 +203,29 @@ export default class CrudService extends Service {
198
203
 
199
204
  // set the model uri endpoint
200
205
  const modelEndpoint = dasherize(pluralize(modelName));
206
+ const exportParams = options.params ?? {};
201
207
 
202
208
  this.modalsManager.show('modals/export-form', {
203
209
  title: `Export ${pluralize(modelName)}`,
204
210
  acceptButtonText: 'Download',
205
211
  modalClass: 'modal-sm',
212
+ format: 'xlsx',
206
213
  formatOptions: ['csv', 'xlsx', 'xls', 'html', 'pdf'],
207
214
  setFormat: ({ target }) => {
208
215
  this.modalsManager.setOption('format', target.value || null);
209
216
  },
210
217
  confirm: (modal, done) => {
211
- const format = modal.getOption('format') || 'xlsx';
218
+ const format = modal.getOption('format') ?? 'xlsx';
212
219
  modal.startLoading();
213
220
  return this.fetch
214
221
  .download(
215
222
  `${modelEndpoint}/export`,
216
223
  {
217
224
  format,
225
+ ...exportParams,
218
226
  },
219
227
  {
228
+ method: 'POST',
220
229
  fileName: `${modelEndpoint}-${formatDate(new Date(), 'yyyy-MM-dd-HH:mm')}.${format}`,
221
230
  }
222
231
  )
@@ -237,4 +246,109 @@ export default class CrudService extends Service {
237
246
  ...options,
238
247
  });
239
248
  }
249
+
250
+ /**
251
+ * Prompts a spreadsheet upload for an import process.
252
+ *
253
+ * @param {String} modelName
254
+ * @param {Object} [options={}]
255
+ * @memberof CrudService
256
+ */
257
+ @action import(modelName, options = {}) {
258
+ // always lowercase modelname
259
+ modelName = modelName.toLowerCase();
260
+
261
+ // set the model uri endpoint
262
+ const modelEndpoint = dasherize(pluralize(modelName));
263
+
264
+ // function to check if queue is empty
265
+ const checkQueue = () => {
266
+ const uploadQueue = this.modalsManager.getOption('uploadQueue');
267
+
268
+ if (uploadQueue.length) {
269
+ this.modalsManager.setOption('acceptButtonDisabled', false);
270
+ } else {
271
+ this.modalsManager.setOption('acceptButtonDisabled', true);
272
+ }
273
+ };
274
+
275
+ this.modalsManager.show('modals/import-form', {
276
+ title: `Import ${pluralize(modelName)} with spreadsheets`,
277
+ acceptButtonText: 'Start Import',
278
+ acceptButtonScheme: 'magic',
279
+ acceptButtonIcon: 'upload',
280
+ acceptButtonDisabled: true,
281
+ isProcessing: false,
282
+ uploadQueue: [],
283
+ fileQueueColumns: [
284
+ { name: 'Type', valuePath: 'extension', key: 'type' },
285
+ { name: 'File Name', valuePath: 'name', key: 'fileName' },
286
+ { name: 'File Size', valuePath: 'size', key: 'fileSize' },
287
+ { name: 'Upload Date', valuePath: 'file.lastModifiedDate', key: 'uploadDate' },
288
+ { name: '', valuePath: '', key: 'delete' },
289
+ ],
290
+ acceptedFileTypes: ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv'],
291
+ queueFile: (file) => {
292
+ const uploadQueue = this.modalsManager.getOption('uploadQueue');
293
+
294
+ uploadQueue.pushObject(file);
295
+ checkQueue();
296
+ },
297
+
298
+ removeFile: (file) => {
299
+ const { queue } = file;
300
+ const uploadQueue = this.modalsManager.getOption('uploadQueue');
301
+
302
+ uploadQueue.removeObject(file);
303
+ queue.remove(file);
304
+ checkQueue();
305
+ },
306
+ confirm: async (modal) => {
307
+ const uploadQueue = this.modalsManager.getOption('uploadQueue');
308
+ const uploadedFiles = [];
309
+ const uploadTask = (file) => {
310
+ return new Promise((resolve) => {
311
+ this.fetch.uploadFile.perform(
312
+ file,
313
+ {
314
+ path: `uploads/import-sources/${this.currentUser.companyId}/${modelEndpoint}`,
315
+ type: 'import-source',
316
+ },
317
+ (uploadedFile) => {
318
+ uploadedFiles.pushObject(uploadedFile);
319
+ resolve(uploadedFile);
320
+ }
321
+ );
322
+ });
323
+ };
324
+
325
+ if (!uploadQueue.length) {
326
+ return this.notifications.warning('No spreadsheets uploaded for import to process.');
327
+ }
328
+
329
+ modal.startLoading();
330
+ modal.setOption('acceptButtonText', 'Uploading...');
331
+
332
+ for (let i = 0; i < uploadQueue.length; i++) {
333
+ const file = uploadQueue.objectAt(i);
334
+ await uploadTask(file);
335
+ }
336
+
337
+ this.modalsManager.setOption('acceptButtonText', 'Processing...');
338
+ this.modalsManager.setOption('isProcessing', true);
339
+
340
+ const files = uploadedFiles.map((file) => file.id);
341
+
342
+ try {
343
+ const response = await this.fetch.post(`${modelEndpoint}/import`, { files });
344
+ if (typeof options.onImportCompleted === 'function') {
345
+ options.onImportCompleted(response, files);
346
+ }
347
+ } catch (error) {
348
+ return this.notifications.serverError(error);
349
+ }
350
+ },
351
+ ...options,
352
+ });
353
+ }
240
354
  }
@@ -15,6 +15,7 @@ import corslite from '../utils/corslite';
15
15
  import getMimeType from '../utils/get-mime-type';
16
16
  import download from '../utils/download';
17
17
  import getUserOptions from '../utils/get-user-options';
18
+ import isEmptyObject from '../utils/is-empty-object';
18
19
  import fetch from 'fetch';
19
20
 
20
21
  if (isBlank(config.API.host)) {
@@ -339,7 +340,7 @@ export default class FetchService extends Service {
339
340
  return this.cachedGet(...arguments);
340
341
  }
341
342
 
342
- const urlParams = !isBlank(query) ? new URLSearchParams(query).toString() : '';
343
+ const urlParams = !isEmptyObject(query) ? new URLSearchParams(query).toString() : '';
343
344
 
344
345
  return this.request(`${path}${urlParams ? '?' + urlParams : ''}`, 'GET', {}, options);
345
346
  }
@@ -506,7 +507,7 @@ export default class FetchService extends Service {
506
507
  let version = options?.version ?? 'v1';
507
508
  let host = options?.host ?? `https://${options?.subdomain ?? 'routing'}.fleetbase.io`;
508
509
  let route = coordinates.map((coords) => coords.join(',')).join(';');
509
- let params = !isBlank(query) ? new URLSearchParams(query).toString() : '';
510
+ let params = !isEmptyObject(query) ? new URLSearchParams(query).toString() : '';
510
511
  let path = `${host}/${service}/${version}/${profile}/${route}`;
511
512
  let url = `${path}${params ? '?' + params : ''}`;
512
513
 
@@ -598,13 +599,25 @@ export default class FetchService extends Service {
598
599
  */
599
600
  download(path, query = {}, options = {}) {
600
601
  const headers = Object.assign(this.getHeaders(), options.headers ?? {});
602
+ const method = options.method ?? 'GET';
603
+ const credentials = options.credentials ?? this.credentials;
604
+ const baseUrl = `${options.host || this.host}/${options.namespace || this.namespace}`;
605
+ const isReadOnlyRequest = ['GET', 'HEAD'].includes(method.toUpperCase());
606
+ const params = isReadOnlyRequest && !isEmptyObject(query) ? `?${new URLSearchParams(query).toString()}` : '';
607
+ const body = !isReadOnlyRequest ? JSON.stringify(query) : {};
608
+ const fetchOptions = {
609
+ method,
610
+ credentials,
611
+ headers,
612
+ };
613
+
614
+ // Only supply body to fetch if not GET or HEAD request
615
+ if (!isReadOnlyRequest) {
616
+ fetchOptions.body = body;
617
+ }
601
618
 
602
619
  return new Promise((resolve, reject) => {
603
- return fetch(`${options.host || this.host}/${options.namespace || this.namespace}/${path}?${!isBlank(query) ? new URLSearchParams(query).toString() : ''}`, {
604
- method: 'GET',
605
- credentials: options.credentials || this.credentials,
606
- headers,
607
- })
620
+ return fetch(`${baseUrl}/${path}${params}`, fetchOptions)
608
621
  .then((response) => {
609
622
  options.fileName = this.getFilenameFromResponse(response, options.fileName);
610
623
  options.mimeType = this.getMimeTypeFromResponse(response, options.mimeType);
@@ -75,9 +75,10 @@ export default class LoaderService extends Service {
75
75
  }
76
76
 
77
77
  const loadingMessage = typeof options.loadingMessage === 'string' ? options.loadingMessage : 'Loading...';
78
- const opacity = typeof options.opacity === 'number' ? options.opacity : 0.1;
78
+ const opacity = typeof options.opacity === 'number' ? options.opacity : 0;
79
79
  const isDarkMode = document.body.dataset.theme ? document.body.dataset.theme === 'dark' : true;
80
80
  const preserveTargetPosition = options.preserveTargetPosition === true;
81
+ const loaderContainerClass = options.loaderContainerClass ?? '';
81
82
 
82
83
  if (!preserveTargetPosition) {
83
84
  target.style.position = 'relative';
@@ -86,7 +87,7 @@ export default class LoaderService extends Service {
86
87
  let loader = document.createElement('div');
87
88
  loader.classList.add('overloader');
88
89
  loader.style.backgroundColor = isDarkMode ? `rgba(128, 128, 128, ${opacity})` : `rgba(249, 250, 251, ${opacity})`;
89
- loader.innerHTML = `<div class="flex items-center justify-center text-center">
90
+ loader.innerHTML = `<div class="loader-container flex items-center justify-center text-center ${loaderContainerClass}">
90
91
  <div>
91
92
  <svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" role="img" focusable="false" aria-hidden="true" data-icon="spinner-third" data-prefix="fad" id="ember240" class="svg-inline--fa fa-spinner-third fa-w-16 fa-spin ember-view text-sky-500 fa-spin-800ms mr-3"><g class="fa-group"><path class="fa-secondary" fill="currentColor" d="M478.71 364.58zm-22 6.11l-27.83-15.9a15.92 15.92 0 0 1-6.94-19.2A184 184 0 1 1 256 72c5.89 0 11.71.29 17.46.83-.74-.07-1.48-.15-2.23-.21-8.49-.69-15.23-7.31-15.23-15.83v-32a16 16 0 0 1 15.34-16C266.24 8.46 261.18 8 256 8 119 8 8 119 8 256s111 248 248 248c98 0 182.42-56.95 222.71-139.42-4.13 7.86-14.23 10.55-22 6.11z"></path><path class="fa-primary" fill="currentColor" d="M271.23 72.62c-8.49-.69-15.23-7.31-15.23-15.83V24.73c0-9.11 7.67-16.78 16.77-16.17C401.92 17.18 504 124.67 504 256a246 246 0 0 1-25 108.24c-4 8.17-14.37 11-22.26 6.45l-27.84-15.9c-7.41-4.23-9.83-13.35-6.2-21.07A182.53 182.53 0 0 0 440 256c0-96.49-74.27-175.63-168.77-183.38z"></path></g>
92
93
  </svg>
@@ -0,0 +1,3 @@
1
+ export default function isEmptyObject(obj) {
2
+ return Object.keys(obj).length === 0 && obj.constructor === Object;
3
+ }
@@ -0,0 +1 @@
1
+ export { default } from '@fleetbase/ember-core/utils/is-empty-object';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fleetbase/ember-core",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "description": "Provides all the core services, decorators and utilities for building a Fleetbase extension for the Console.",
5
5
  "keywords": [
6
6
  "fleetbase-core",