@@ -217,28 +217,45 @@ public function fetch_current_month_to_date_costs( bool $force = false ): float
217217 */
218218 public function fetch_past_months_costs ( bool $ force = false ): float {
219219
220- $ cached_data = $ this ->feature_instance ->get_usage_data ();
221-
222- if ( ! empty ( $ cached_data ['months_total ' ] ) && ! $ force ) {
223- return $ cached_data ['months_total ' ];
224- }
225-
220+ $ cached_data = $ this ->feature_instance ->get_usage_data ();
226221 $ tz = wp_timezone ();
227222 $ now = new \DateTimeImmutable ( 'now ' , $ tz );
228223 $ current_year = (int ) $ now ->format ( 'Y ' );
229- $ current_month = (int ) $ now ->format ( 'm ' );
224+ $ last_month_date = $ now ->modify ( '-1 month ' );
225+ $ last_month = (int ) $ last_month_date ->format ( 'm ' );
226+ $ last_month_year = (int ) $ last_month_date ->format ( 'Y ' );
230227 $ all_month_pricing = [];
231228 $ usage_currency = 'USD ' ;
232229
233- for ( $ month = 1 ; $ month < $ current_month ; $ month ++ ) {
230+ // Year changed and current month is January, so no past months to fetch. It's will be handled by the past years costs fetch.
231+ if ( $ current_year !== $ last_month_year ) {
232+ $ cached_data ['months ' ] = [];
233+ $ cached_data ['months_total ' ] = 0.0 ;
234+ $ cached_data ['currency ' ] = $ usage_currency ;
235+ $ cached_data ['last_updated ' ] = time ();
236+
237+ $ this ->feature_instance ->set_usage_data ( $ cached_data );
238+
239+ return $ cached_data ['months_total ' ];
240+ }
241+
242+ if (
243+ ! empty ( $ cached_data ['months ' ][ $ last_month ] )
244+ && ! empty ( $ cached_data ['months_total ' ] )
245+ && ! $ force
246+ ) {
247+ return $ cached_data ['months_total ' ];
248+ }
249+
250+ for ( $ month = 1 ; $ month <= $ last_month ; $ month ++ ) {
234251 // If the month is already in the cached array, skip the API call.
235252 if ( isset ( $ cached_data ['months ' ][ $ month ] ) && ! $ force ) {
236253 $ all_month_pricing [ $ month ] = $ cached_data ['months ' ][ $ month ];
237254 continue ;
238255 }
239256
240- $ start_date = new \DateTimeImmutable ( $ current_year . '- ' . $ month . '-01 ' , $ tz );
241- $ end_date = new \DateTimeImmutable ( "$ current_year - $ month-01 last day of this month " , $ tz );
257+ $ start_date = new \DateTimeImmutable ( $ last_month_year . '- ' . $ month . '-01 ' , $ tz );
258+ $ end_date = new \DateTimeImmutable ( "$ last_month_year - $ month-01 last day of this month " , $ tz );
242259
243260 $ pricing = $ this ->fetch_period ( $ start_date ->getTimestamp (), $ end_date ->getTimestamp () );
244261
0 commit comments