Skip to content

Commit 3541e25

Browse files
committed
Add analytics data fetch in AnalyticsHubViewModel
1 parent 6c31951 commit 3541e25

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

WooCommerce/Classes/ViewRelated/Dashboard/Analytics Hub/AnalyticsHubViewModel.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ final class AnalyticsHubViewModel: ObservableObject {
1212
stores: StoresManager = ServiceLocator.stores) {
1313
self.siteID = siteID
1414
self.stores = stores
15+
16+
Task.init {
17+
do {
18+
try await retrieveOrderStats()
19+
} catch {
20+
DDLogWarn("⚠️ Error fetching analytics data: \(error)")
21+
}
22+
}
1523
}
1624

1725
/// Revenue Card ViewModel
@@ -48,3 +56,44 @@ final class AnalyticsHubViewModel: ObservableObject {
4856
///
4957
@Published private var previousOrderStats: OrderStatsV4? = nil
5058
}
59+
60+
private extension AnalyticsHubViewModel {
61+
62+
@MainActor
63+
func retrieveOrderStats() async throws {
64+
// TODO: get dates from the selected period
65+
let currentMonthDate = Date()
66+
let previousMonthDate = Calendar.current.date(byAdding: .month, value: -1, to: Date())!
67+
68+
async let currentPeriodRequest = retrieveStats(earliestDateToInclude: currentMonthDate.startOfMonth(timezone: .current),
69+
latestDateToInclude: currentMonthDate.endOfMonth(timezone: .current),
70+
forceRefresh: true)
71+
async let previousPeriodRequest = retrieveStats(earliestDateToInclude: previousMonthDate.startOfMonth(timezone: .current),
72+
latestDateToInclude: previousMonthDate.endOfMonth(timezone: .current),
73+
forceRefresh: true)
74+
let (currentPeriodStats, previousPeriodStats) = try await (currentPeriodRequest, previousPeriodRequest)
75+
self.currentOrderStats = currentPeriodStats
76+
self.previousOrderStats = previousPeriodStats
77+
}
78+
79+
@MainActor
80+
func retrieveStats(earliestDateToInclude: Date,
81+
latestDateToInclude: Date,
82+
forceRefresh: Bool) async throws -> OrderStatsV4 {
83+
try await withCheckedThrowingContinuation { continuation in
84+
// TODO: get unit and quantity from the selected period
85+
let unit: StatsGranularityV4 = .daily
86+
let quantity = 31
87+
88+
let action = StatsActionV4.retrieveCustomStats(siteID: siteID,
89+
unit: unit,
90+
earliestDateToInclude: earliestDateToInclude,
91+
latestDateToInclude: latestDateToInclude,
92+
quantity: quantity,
93+
forceRefresh: forceRefresh) { result in
94+
continuation.resume(with: result)
95+
}
96+
stores.dispatch(action)
97+
}
98+
}
99+
}

0 commit comments

Comments
 (0)