Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,13 @@ Number template format: `<template>@<reset_type>[:<start>:<increment>]`
| `Order.OrderPaidAndOrderSentNotifications.Enable` | `false` | Use order paid/sent notifications |
| `Order.PaymentShipmentStatusChangedNotifications.Enable` | `false` | Use payment/shipment status notifications |

#### Dashboard Statistics Settings

| Setting | Default | Description |
|---------|---------|-------------|
| `Order.DashboardStatistics.Enable` | `true` | Enable or disable order statistics widgets on the main dashboard |
| `Order.DashboardStatistics.RangeMonths` | `12` | Number of months to include in dashboard statistics calculations |

## Architecture

### Project Structure
Expand Down
18 changes: 18 additions & 0 deletions src/VirtoCommerce.OrdersModule.Core/ModuleConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,22 @@ public static class General
DefaultValue = 20,
};

public static SettingDescriptor DashboardStatisticsEnabled { get; } = new SettingDescriptor
{
Name = "Order.DashboardStatistics.Enable",
GroupName = "Orders|General",
ValueType = SettingValueType.Boolean,
DefaultValue = true,
};

public static SettingDescriptor DashboardStatisticsRangeMonths { get; } = new SettingDescriptor
{
Name = "Order.DashboardStatistics.RangeMonths",
GroupName = "Orders|General",
ValueType = SettingValueType.PositiveInteger,
DefaultValue = 12,
};

public static IEnumerable<SettingDescriptor> AllSettings
{
get
Expand All @@ -310,6 +326,8 @@ public static IEnumerable<SettingDescriptor> AllSettings
yield return EventBasedPurchasedProductIndexation;
yield return PurchasedProductStoreFilter;
yield return MaxOrderDocumentCount;
yield return DashboardStatisticsEnabled;
yield return DashboardStatisticsRangeMonths;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,24 @@ public async Task<ActionResult> DeleteOrdersByIds([FromQuery] string[] ids)
return unauthorizedRequest ? Forbid() : NoContent();
}

/// <summary>
/// Get dashboard statistics settings
/// </summary>
[HttpGet]
[Route("~/api/order/dashboardStatistics/settings")]
[Authorize(ModuleConstants.Security.Permissions.ViewDashboardStatistics)]
public async Task<ActionResult<object>> GetDashboardStatisticsSettingsAsync()
{
var enabled = await settingsManager.GetValueAsync<bool>(ModuleConstants.Settings.General.DashboardStatisticsEnabled);
var rangeMonths = await settingsManager.GetValueAsync<int>(ModuleConstants.Settings.General.DashboardStatisticsRangeMonths);

return Ok(new
{
Enabled = enabled,
RangeMonths = rangeMonths
});
}

/// <summary>
/// Get a some order statistic information for Commerce manager dashboard
/// </summary>
Expand All @@ -500,7 +518,18 @@ public async Task<ActionResult> DeleteOrdersByIds([FromQuery] string[] ids)
[Authorize(ModuleConstants.Security.Permissions.ViewDashboardStatistics)]
public async Task<ActionResult<DashboardStatisticsResult>> GetDashboardStatisticsAsync([FromQuery] DateTime? start = null, [FromQuery] DateTime? end = null)
{
start ??= DateTime.UtcNow.AddYears(-1);
var dashboardEnabled = await settingsManager.GetValueAsync<bool>(ModuleConstants.Settings.General.DashboardStatisticsEnabled);
if (!dashboardEnabled)
{
return Ok(new DashboardStatisticsResult());
}

if (start == null)
{
var rangeMonths = await settingsManager.GetValueAsync<int>(ModuleConstants.Settings.General.DashboardStatisticsRangeMonths);
start = DateTime.UtcNow.AddMonths(-rangeMonths);
}

end ??= DateTime.UtcNow;

// Hack: to compensate for incorrect Local dates to UTC
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Maximale Anzahl von Unterdokumenten pro Bestellung",
"description": "Definiert die maximale Anzahl von Unterdokumenten (Zahlungen, Sendungen, Captures, Rückerstattungen usw.), die pro Bestellung erstellt oder gespeichert werden können. Dies gewährleistet Systemleistung, Speicheroptimierung und Datenkonsistenz. Bei Überschreitung dieser Grenze wird beim Speichern eine Ausnahme ausgelöst"
},
"Order.DashboardStatistics.Enable": {
"title": "Dashboard-Statistiken aktivieren",
"description": "Aktiviert oder deaktiviert die Bestellstatistik-Widgets auf dem Haupt-Dashboard"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Dashboard-Statistik Zeitraum (Monate)",
"description": "Definiert die Anzahl der Monate, die in die Dashboard-Statistikberechnungen einbezogen werden. Standard ist 12 Monate"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Maximum number of child documents per order",
"description": "Defines the maximum number of child documents (payments, shipments, captures, refunds, etc.) that can be created or stored per order. This ensures system performance, storage optimization, and data consistency. An exception will be thrown on save if this limit is exceeded"
},
"Order.DashboardStatistics.Enable": {
"title": "Enable dashboard statistics",
"description": "Turn on or off the order statistics dashboard widgets on the main dashboard"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Dashboard statistics range (months)",
"description": "Defines the number of months to include in the dashboard statistics calculations. Default is 12 months"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Número máximo de documentos secundarios por pedido",
"description": "Define el número máximo de documentos secundarios (pagos, envíos, capturas, reembolsos, etc.) que se pueden crear o almacenar por pedido. Esto garantiza el rendimiento del sistema, la optimización del almacenamiento y la consistencia de los datos. Se generará una excepción al guardar si se excede este límite"
},
"Order.DashboardStatistics.Enable": {
"title": "Habilitar estadísticas del panel",
"description": "Activa o desactiva los widgets de estadísticas de pedidos en el panel principal"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Período de estadísticas del panel (meses)",
"description": "Define el número de meses a incluir en los cálculos de estadísticas del panel. El valor predeterminado es 12 meses"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Nombre maximum de documents enfants par commande",
"description": "Définit le nombre maximum de documents enfants (paiements, expéditions, captures, remboursements, etc.) qui peuvent être créés ou stockés par commande. Cela garantit les performances du système, l'optimisation du stockage et la cohérence des données. Une exception sera levée lors de la sauvegarde si cette limite est dépassée"
},
"Order.DashboardStatistics.Enable": {
"title": "Activer les statistiques du tableau de bord",
"description": "Active ou désactive les widgets de statistiques de commandes sur le tableau de bord principal"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Période des statistiques du tableau de bord (mois)",
"description": "Définit le nombre de mois à inclure dans les calculs des statistiques du tableau de bord. La valeur par défaut est de 12 mois"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Numero massimo di documenti secondari per ordine",
"description": "Definisce il numero massimo di documenti secondari (pagamenti, spedizioni, acquisizioni, rimborsi, ecc.) che possono essere creati o memorizzati per ordine. Ciò garantisce le prestazioni del sistema, l'ottimizzazione dello storage e la coerenza dei dati. Verrà generata un'eccezione durante il salvataggio se questo limite viene superato"
},
"Order.DashboardStatistics.Enable": {
"title": "Abilita statistiche dashboard",
"description": "Attiva o disattiva i widget delle statistiche ordini sulla dashboard principale"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Intervallo statistiche dashboard (mesi)",
"description": "Definisce il numero di mesi da includere nei calcoli delle statistiche della dashboard. Il valore predefinito è 12 mesi"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "注文あたりの子ドキュメントの最大数",
"description": "注文ごとに作成または保存できる子ドキュメント(支払い、配送、キャプチャ、返金など)の最大数を定義します。これにより、システムパフォーマンス、ストレージの最適化、データの整合性が確保されます。この制限を超えた場合、保存時に例外がスローされます"
},
"Order.DashboardStatistics.Enable": {
"title": "ダッシュボード統計を有効にする",
"description": "メインダッシュボードの注文統計ウィジェットを有効または無効にします"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "ダッシュボード統計の範囲(月)",
"description": "ダッシュボード統計計算に含める月数を定義します。デフォルトは12ヶ月です"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Maksymalna liczba dokumentów podrzędnych na zamówienie",
"description": "Określa maksymalną liczbę dokumentów podrzędnych (płatności, przesyłki, przechwycenia, zwroty itp.), które można utworzyć lub przechowywać dla jednego zamówienia. Zapewnia to wydajność systemu, optymalizację przechowywania i spójność danych. Jeśli ten limit zostanie przekroczony, podczas zapisywania zostanie zgłoszony wyjątek"
},
"Order.DashboardStatistics.Enable": {
"title": "Włącz statystyki pulpitu",
"description": "Włącza lub wyłącza widżety statystyk zamówień na głównym pulpicie"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Zakres statystyk pulpitu (miesiące)",
"description": "Określa liczbę miesięcy do uwzględnienia w obliczeniach statystyk pulpitu. Domyślnie 12 miesięcy"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Número máximo de documentos secundários por pedido",
"description": "Define o número máximo de documentos secundários (pagamentos, remessas, capturas, reembolsos, etc.) que podem ser criados ou armazenados por pedido. Isso garante o desempenho do sistema, otimização de armazenamento e consistência de dados. Uma exceção será lançada ao salvar se este limite for excedido"
},
"Order.DashboardStatistics.Enable": {
"title": "Ativar estatísticas do painel",
"description": "Ativa ou desativa os widgets de estatísticas de pedidos no painel principal"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Período de estatísticas do painel (meses)",
"description": "Define o número de meses a incluir nos cálculos de estatísticas do painel. O padrão é 12 meses"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "Максимальное количество дочерних документов на заказ",
"description": "Определяет максимальное количество дочерних документов (платежи, отгрузки, захваты, возвраты и т.д.), которые могут быть созданы или сохранены для одного заказа. Это обеспечивает производительность системы, оптимизацию хранилища и согласованность данных. При превышении этого лимита при сохранении будет выброшено исключение"
},
"Order.DashboardStatistics.Enable": {
"title": "Включить статистику панели управления",
"description": "Включает или отключает виджеты статистики заказов на главной панели управления"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "Период статистики панели управления (месяцы)",
"description": "Определяет количество месяцев для расчета статистики панели управления. По умолчанию 12 месяцев"
}
},
"module": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@
"Order.MaxOrderDocumentCount": {
"title": "每个订单的最大子文档数量",
"description": "定义每个订单可以创建或存储的子文档(付款、发货、捕获、退款等)的最大数量。这确保了系统性能、存储优化和数据一致性。如果超过此限制,保存时将抛出异常"
},
"Order.DashboardStatistics.Enable": {
"title": "启用仪表板统计",
"description": "在主仪表板上启用或禁用订单统计小部件"
},
"Order.DashboardStatistics.RangeMonths": {
"title": "仪表板统计范围(月)",
"description": "定义仪表板统计计算中包含的月数。默认为12个月"
}
},
"module": {
Expand Down
5 changes: 1 addition & 4 deletions src/VirtoCommerce.OrdersModule.Web/Scripts/order.js
Original file line number Diff line number Diff line change
Expand Up @@ -745,11 +745,8 @@ angular.module(moduleName, [

if (authContext.isAuthenticated &&
authService.checkPermission('order:dashboardstatistics:view')) {
var now = new Date();
var startDate = new Date();
startDate.setFullYear(now.getFullYear() - 1);

customerOrders.getDashboardStatistics({ start: startDate, end: now }, function (data) {
customerOrders.getDashboardStatistics({}, function (data) {
// prepare statistics
var statisticsToChartRows = function (statsList, allCurrencies) {
var groupedQuarters = _.groupBy(statsList, function (stats) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ angular.module('virtoCommerce.orderModule')
recalculate: { method: 'PUT', url: 'api/order/customerOrders/recalculate' },
update: { method: 'PUT', url: 'api/order/customerOrders' },
getDashboardStatistics: { url: 'api/order/dashboardStatistics' },
getDashboardStatisticsSettings: { url: 'api/order/dashboardStatistics/settings' },
getOrderChanges: { method: 'GET', url: 'api/order/customerOrders/:id/changes', isArray: true },
searchOrderChanges: { method: 'POST', url: 'api/order/customerOrders/searchChanges' },
indexedSearch: { method: 'POST', url: 'api/order/customerOrders/indexed/search' },
Expand Down
Loading