@lipagas/storefront-engine
Version:
Headless Commerce & Marketplace Extension for Fleetbase
62 lines (49 loc) • 1.86 kB
JavaScript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { inject as service } from '@ember/service';
import { action, computed } from '@ember/object';
import { startOfMonth, endOfMonth, format } from 'date-fns';
export default class WidgetStorefrontMetricsComponent extends Component {
fetch;
storefront;
metrics = {
orders_count: 0,
customers_count: 0,
stores_count: 0,
earnings_sum: 0,
};
isLoading = true;
start = format(startOfMonth(new Date()), 'yyyy-MM-dd');
end = format(endOfMonth(new Date()), 'yyyy-MM-dd');
get title() {
return this.args.title || 'This Month';
}
async setupWidget() {
this.metrics = await this.fetchMetrics(this.start, this.end);
this.storefront.on('order.broadcasted', this.reloadMetrics);
this.storefront.on('storefront.changed', this.reloadMetrics);
}
async reloadMetrics() {
this.metrics = await this.fetchMetrics(this.start, this.end);
}
fetchMetrics(start, end) {
this.isLoading = true;
return new Promise((resolve) => {
const store = this.storefront?.activeStore?.id;
if (!store) {
this.isLoading = false;
return resolve(this.metrics);
}
this.fetch
.get('actions/metrics', { start, end, store }, { namespace: 'storefront/int/v1' })
.then((metrics) => {
this.isLoading = false;
resolve(metrics);
})
.catch(() => {
this.isLoading = false;
resolve(this.metrics);
});
});
}
}