This commit is contained in:
hackerESQ
2025-04-12 21:25:00 -05:00
parent 3eb9bad840
commit c691ee922a
+30 -32
View File
@@ -146,51 +146,46 @@ class CurrencyRate extends Model
dump('got currencies'); dump('got currencies');
// call api in chunks // call api in chunks
$rates = [];
foreach (collect($period)->chunk(500) as $chunk) { foreach (collect($period)->chunk(500) as $chunk) {
dump('calling frankf time series'); dump('calling frankf time series');
$chunkRates = Frankfurter::setSymbols($currencies)->timeSeries($chunk->min(), $chunk->max()); $chunkRates = Frankfurter::setSymbols($currencies)->timeSeries($chunk->min(), $chunk->max());
$rates = array_merge($rates, Arr::get($chunkRates, 'rates', [])); $rates = Arr::get($chunkRates, 'rates', []);
}
dump('done with frankf', count($rates)); // loop through each date
$updates = [];
// loop through each date foreach ($chunk as $date) {
$updates = [];
$datesWithRates = array_keys($rates);
sort($datesWithRates);
foreach ($period as $date) { $lookupDate = self::getNearestPastDate($date, $rates);
$lookupDate = self::getNearestPastDate($date, $datesWithRates); if (is_null($lookupDate)) {
continue;
}
// loop through each rate
foreach ($rates[$lookupDate->toDateString()] as $curr => $rate) {
// add to updates
$updates[] = [
'currency' => $curr,
'date' => $date->toDateString(),
'rate' => $rate,
'updated_at' => now()->toDateTimeString(),
'created_at' => now()->toDateTimeString(),
];
}
dump('inserting');
// persist
self::chunkInsert($updates);
if (is_null($lookupDate)) {
continue;
} }
// loop through each rate
foreach ($rates[$lookupDate->toDateString()] as $curr => $rate) {
// add to updates
$updates[] = [
'currency' => $curr,
'date' => $date->toDateString(),
'rate' => $rate,
'updated_at' => now()->toDateTimeString(),
'created_at' => now()->toDateTimeString(),
];
}
} }
dump('inserting');
// persist
self::chunkInsert($updates);
dump('done'); dump('done');
return collect($updates) return collect($updates)
@@ -205,11 +200,14 @@ class CurrencyRate extends Model
private static function getNearestPastDate(CarbonInterface $date, array $rates): ?CarbonInterface private static function getNearestPastDate(CarbonInterface $date, array $rates): ?CarbonInterface
{ {
$datesWithRates = array_keys($rates);
sort($datesWithRates);
// get rates or find closest valid rate (handles missing weekend rates) // get rates or find closest valid rate (handles missing weekend rates)
while (! isset($rates[$date->toDateString()])) { while (! isset($rates[$date->toDateString()])) {
// is this the start of a range that falls on a weekend? // is this the start of a range that falls on a weekend?
if ($date->lessThan($first_date = Carbon::parse($rates[0]))) { if ($date->lessThan($first_date = Carbon::parse($datesWithRates[0]))) {
$date = $first_date; $date = $first_date;
break; break;