Nexus upgrade design and refresh
This commit is contained in:
937
modules/mining-checker/src/Domain/AnalyticsService.php
Normal file
937
modules/mining-checker/src/Domain/AnalyticsService.php
Normal file
@@ -0,0 +1,937 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Modules\MiningChecker\Domain;
|
||||
|
||||
use Modules\MiningChecker\Support\ApiException;
|
||||
|
||||
final class AnalyticsService
|
||||
{
|
||||
private ?FxService $fx;
|
||||
|
||||
public function __construct(?FxService $fx = null)
|
||||
{
|
||||
$this->fx = $fx;
|
||||
}
|
||||
|
||||
public function enrichMeasurements(array $measurements, array $settings): array
|
||||
{
|
||||
$baselineCoins = (float) ($settings['baseline_coins_total'] ?? 0.0);
|
||||
$baselineAt = (string) ($settings['baseline_measured_at'] ?? '');
|
||||
$costPlans = is_array($settings['cost_plans'] ?? null) ? $settings['cost_plans'] : [];
|
||||
$payouts = is_array($settings['payouts'] ?? null) ? $settings['payouts'] : [];
|
||||
$measurementRates = is_array($settings['measurement_rates'] ?? null) ? $settings['measurement_rates'] : [];
|
||||
|
||||
$baselineTs = $this->utcTimestamp($baselineAt);
|
||||
$previous = null;
|
||||
$previousIntervalRate = null;
|
||||
$result = [];
|
||||
$payoutIndex = 0;
|
||||
$cumulativePayouts = 0.0;
|
||||
$latestPriceByCurrency = [];
|
||||
|
||||
foreach ($measurements as $row) {
|
||||
$measuredTs = $this->utcTimestamp((string) $row['measured_at']);
|
||||
while (isset($payouts[$payoutIndex])) {
|
||||
$payoutTs = $this->utcTimestamp((string) ($payouts[$payoutIndex]['payout_at'] ?? ''));
|
||||
if ($payoutTs <= 0 || $payoutTs > $measuredTs) {
|
||||
break;
|
||||
}
|
||||
|
||||
$cumulativePayouts += (float) ($payouts[$payoutIndex]['coins_amount'] ?? 0);
|
||||
$payoutIndex++;
|
||||
}
|
||||
|
||||
$visibleCoinsTotal = (float) $row['coins_total'];
|
||||
$effectiveCoinsTotal = $visibleCoinsTotal + $cumulativePayouts;
|
||||
$growth = $effectiveCoinsTotal - $baselineCoins;
|
||||
$hoursSinceBaseline = $baselineTs > 0 && $measuredTs > $baselineTs ? ($measuredTs - $baselineTs) / 3600 : 0.0;
|
||||
$perHourSinceBaseline = $hoursSinceBaseline > 0 ? $growth / $hoursSinceBaseline : null;
|
||||
$perDaySinceBaseline = $perHourSinceBaseline !== null ? $perHourSinceBaseline * 24 : null;
|
||||
|
||||
$intervalHours = null;
|
||||
$intervalGrowth = null;
|
||||
$perHourInterval = null;
|
||||
$perDayInterval = null;
|
||||
|
||||
if (is_array($previous)) {
|
||||
$intervalHours = max(0.0, ($measuredTs - ($this->utcTimestamp((string) $previous['measured_at']) ?: $measuredTs)) / 3600);
|
||||
$intervalGrowth = $effectiveCoinsTotal - (float) ($previous['coins_total_effective'] ?? $previous['coins_total']);
|
||||
$perHourInterval = $intervalHours > 0 ? $intervalGrowth / $intervalHours : null;
|
||||
$perDayInterval = $perHourInterval !== null ? $perHourInterval * 24 : null;
|
||||
}
|
||||
|
||||
$trendLabel = 'stabil';
|
||||
if ($perHourInterval !== null && $previousIntervalRate !== null) {
|
||||
$delta = $perHourInterval - $previousIntervalRate;
|
||||
$threshold = max(abs($previousIntervalRate) * 0.05, 0.01);
|
||||
if ($delta > $threshold) {
|
||||
$trendLabel = 'steigend';
|
||||
} elseif ($delta < -$threshold) {
|
||||
$trendLabel = 'fallend';
|
||||
}
|
||||
}
|
||||
|
||||
$rawPrice = isset($row['price_per_coin']) && $row['price_per_coin'] !== null ? (float) $row['price_per_coin'] : null;
|
||||
$rawPriceCurrency = $row['price_currency'] ?: null;
|
||||
|
||||
if ($rawPrice !== null && $rawPriceCurrency !== null) {
|
||||
$latestPriceByCurrency[(string) $rawPriceCurrency] = $rawPrice;
|
||||
}
|
||||
|
||||
$measurementDerivedPrices = $this->measurementDerivedPrices($measurementRates, (int) ($row['id'] ?? 0));
|
||||
foreach ($measurementDerivedPrices as $derivedCurrency => $derivedPrice) {
|
||||
$latestPriceByCurrency[$derivedCurrency] = $derivedPrice;
|
||||
}
|
||||
|
||||
$priceCurrency = $rawPriceCurrency !== null
|
||||
? (string) $rawPriceCurrency
|
||||
: $this->preferredPriceCurrency($latestPriceByCurrency, $measurementDerivedPrices);
|
||||
$price = $rawPrice;
|
||||
if ($price === null && $priceCurrency !== null && isset($measurementDerivedPrices[$priceCurrency])) {
|
||||
$price = (float) $measurementDerivedPrices[$priceCurrency];
|
||||
}
|
||||
if ($price === null && $priceCurrency !== null && isset($latestPriceByCurrency[$priceCurrency])) {
|
||||
$price = (float) $latestPriceByCurrency[$priceCurrency];
|
||||
}
|
||||
if ($price === null) {
|
||||
foreach (['USD', 'EUR'] as $fallbackCurrency) {
|
||||
$fxPrice = $this->convertAmount(1.0, 'DOGE', $fallbackCurrency);
|
||||
if ($fxPrice !== null && $fxPrice > 0) {
|
||||
$latestPriceByCurrency[$fallbackCurrency] = $fxPrice;
|
||||
}
|
||||
}
|
||||
$priceCurrency = $priceCurrency ?? $this->preferredPriceCurrency($latestPriceByCurrency, $measurementDerivedPrices);
|
||||
if ($priceCurrency !== null && isset($latestPriceByCurrency[$priceCurrency])) {
|
||||
$price = (float) $latestPriceByCurrency[$priceCurrency];
|
||||
}
|
||||
}
|
||||
|
||||
$effectiveDailyCost = $this->effectiveDailyCost($costPlans, $measuredTs, $priceCurrency);
|
||||
$currentValue = $price !== null ? $visibleCoinsTotal * $price : null;
|
||||
$currentValueEffective = $price !== null ? $effectiveCoinsTotal * $price : null;
|
||||
$theoreticalDailyRevenue = ($price !== null && $perDayInterval !== null) ? $perDayInterval * $price : null;
|
||||
$theoreticalDailyProfit = (
|
||||
$theoreticalDailyRevenue !== null &&
|
||||
$effectiveDailyCost !== null
|
||||
) ? $theoreticalDailyRevenue - $effectiveDailyCost : null;
|
||||
$breakEvenPricePerCoin = (
|
||||
$effectiveDailyCost !== null &&
|
||||
$perDayInterval !== null &&
|
||||
$perDayInterval > 0
|
||||
) ? $effectiveDailyCost / $perDayInterval : null;
|
||||
$profitMarginPercent = (
|
||||
$theoreticalDailyRevenue !== null &&
|
||||
$theoreticalDailyRevenue > 0 &&
|
||||
$theoreticalDailyProfit !== null
|
||||
) ? ($theoreticalDailyProfit / $theoreticalDailyRevenue) * 100 : null;
|
||||
|
||||
$normalizedFlags = $row['ocr_flags'];
|
||||
if (is_string($normalizedFlags) && $normalizedFlags !== '') {
|
||||
$decoded = json_decode($normalizedFlags, true);
|
||||
$normalizedFlags = is_array($decoded) ? $decoded : [$normalizedFlags];
|
||||
}
|
||||
|
||||
$result[] = array_merge($row, [
|
||||
'coins_total_visible' => $this->roundOrNull($visibleCoinsTotal, 6),
|
||||
'coins_total_effective' => $this->roundOrNull($effectiveCoinsTotal, 6),
|
||||
'payouts_cumulative' => $this->roundOrNull($cumulativePayouts, 6),
|
||||
'growth_since_baseline' => $this->roundOrNull($growth, 6),
|
||||
'hours_since_baseline' => $this->roundOrNull($hoursSinceBaseline, 4),
|
||||
'doge_per_hour_since_baseline' => $this->roundOrNull($perHourSinceBaseline, 6),
|
||||
'doge_per_day_since_baseline' => $this->roundOrNull($perDaySinceBaseline, 6),
|
||||
'interval_hours' => $this->roundOrNull($intervalHours, 4),
|
||||
'interval_growth' => $this->roundOrNull($intervalGrowth, 6),
|
||||
'doge_per_hour_interval' => $this->roundOrNull($perHourInterval, 6),
|
||||
'doge_per_day_interval' => $this->roundOrNull($perDayInterval, 6),
|
||||
'trend_label' => $trendLabel,
|
||||
'effective_price_per_coin' => $this->roundOrNull($price, 8),
|
||||
'effective_price_currency' => $priceCurrency,
|
||||
'price_is_fallback' => $rawPrice === null && $price !== null,
|
||||
'current_value' => $this->roundOrNull($currentValue, 8),
|
||||
'current_value_effective' => $this->roundOrNull($currentValueEffective, 8),
|
||||
'effective_daily_cost' => $this->roundOrNull($effectiveDailyCost, 8),
|
||||
'theoretical_daily_revenue' => $this->roundOrNull($theoreticalDailyRevenue, 8),
|
||||
'theoretical_daily_profit' => $this->roundOrNull($theoreticalDailyProfit, 8),
|
||||
'break_even_price_per_coin' => $this->roundOrNull($breakEvenPricePerCoin, 8),
|
||||
'profit_margin_percent' => $this->roundOrNull($profitMarginPercent, 4),
|
||||
'measured_date' => substr((string) $row['measured_at'], 0, 10),
|
||||
'ocr_flags' => is_array($normalizedFlags) ? $normalizedFlags : [],
|
||||
]);
|
||||
|
||||
if ($perHourInterval !== null) {
|
||||
$previousIntervalRate = $perHourInterval;
|
||||
}
|
||||
$previous = $row;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function buildSummary(array $measurements, array $settings, array $targets): array
|
||||
{
|
||||
if ($measurements === []) {
|
||||
return [
|
||||
'latest_measurement' => null,
|
||||
'baseline' => $settings,
|
||||
'targets' => [],
|
||||
'payouts' => [],
|
||||
'miner_offers' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$latest = $measurements[array_key_last($measurements)];
|
||||
$latestPriceByCurrency = [];
|
||||
foreach ($measurements as $measurement) {
|
||||
if ($measurement['price_per_coin'] !== null && $measurement['price_currency'] !== null) {
|
||||
$latestPriceByCurrency[(string) $measurement['price_currency']] = (float) $measurement['price_per_coin'];
|
||||
}
|
||||
}
|
||||
|
||||
$payouts = is_array($settings['payouts'] ?? null) ? $settings['payouts'] : [];
|
||||
$purchasedMiners = is_array($settings['purchased_miners'] ?? null) ? $settings['purchased_miners'] : [];
|
||||
$minerOffers = is_array($settings['miner_offers'] ?? null) ? $settings['miner_offers'] : [];
|
||||
$currentHashrateMh = $this->totalHashrateMh(array_merge(
|
||||
is_array($settings['cost_plans'] ?? null) ? $settings['cost_plans'] : [],
|
||||
$purchasedMiners
|
||||
));
|
||||
$offerSummary = [];
|
||||
foreach ($minerOffers as $offer) {
|
||||
$offerSummary[] = $this->evaluateMinerOffer($offer, $latest, $latestPriceByCurrency, $currentHashrateMh, $settings);
|
||||
}
|
||||
|
||||
$targetSummary = [];
|
||||
foreach ($targets as $target) {
|
||||
$currency = (string) $target['currency'];
|
||||
$targetAmount = is_numeric($target['target_amount_fiat'] ?? null) ? (float) $target['target_amount_fiat'] : null;
|
||||
$linkedOffer = null;
|
||||
if (is_numeric($target['miner_offer_id'] ?? null)) {
|
||||
foreach ($offerSummary as $offer) {
|
||||
if ((int) ($offer['id'] ?? 0) === (int) $target['miner_offer_id']) {
|
||||
$linkedOffer = $offer;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (is_array($linkedOffer)) {
|
||||
$currency = (string) ($linkedOffer['reference_price_currency'] ?? $linkedOffer['effective_price_currency'] ?? $currency);
|
||||
$targetAmount = is_numeric($linkedOffer['reference_price_amount'] ?? null)
|
||||
? (float) $linkedOffer['reference_price_amount']
|
||||
: (is_numeric($linkedOffer['effective_price_amount'] ?? null) ? (float) $linkedOffer['effective_price_amount'] : $targetAmount);
|
||||
}
|
||||
|
||||
$price = $latestPriceByCurrency[$currency] ?? $this->convertLatestPrice($latestPriceByCurrency, $currency);
|
||||
$requiredDoge = ($price && $targetAmount !== null) ? $targetAmount / $price : null;
|
||||
$remainingDoge = $requiredDoge !== null ? $requiredDoge - (float) ($latest['coins_total_effective'] ?? $latest['coins_total']) : null;
|
||||
$remainingDays = (
|
||||
$remainingDoge !== null &&
|
||||
$latest['doge_per_day_interval'] !== null &&
|
||||
(float) $latest['doge_per_day_interval'] > 0
|
||||
) ? $remainingDoge / (float) $latest['doge_per_day_interval'] : null;
|
||||
$targetEtaAt = null;
|
||||
if ($remainingDays !== null) {
|
||||
if ($remainingDays <= 0) {
|
||||
$targetEtaAt = (string) ($latest['measured_at'] ?? '');
|
||||
} elseif (!empty($latest['measured_at'])) {
|
||||
try {
|
||||
$targetEtaAt = $this->formatUtcTimestamp(
|
||||
$this->utcTimestamp((string) $latest['measured_at']) + (int) round($remainingDays * 86400)
|
||||
);
|
||||
} catch (\Throwable) {
|
||||
$targetEtaAt = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$targetSummary[] = array_merge($target, [
|
||||
'effective_target_amount_fiat' => $this->roundOrNull($targetAmount, 2),
|
||||
'effective_currency' => $currency,
|
||||
'linked_offer_id' => $linkedOffer['id'] ?? ($target['miner_offer_id'] ?? null),
|
||||
'linked_offer_label' => $linkedOffer['label'] ?? null,
|
||||
'latest_price_for_currency' => $price,
|
||||
'required_doge' => $this->roundOrNull($requiredDoge, 6),
|
||||
'remaining_doge' => $this->roundOrNull($remainingDoge, 6),
|
||||
'remaining_days' => $this->roundOrNull($remainingDays, 4),
|
||||
'target_eta_at' => $targetEtaAt,
|
||||
'status' => $remainingDoge !== null && $remainingDoge <= 0 ? 'reached' : 'open',
|
||||
]);
|
||||
}
|
||||
|
||||
$latestCurrency = (string) ($latest['effective_price_currency'] ?? $latest['price_currency'] ?? '');
|
||||
$investedCapital = $latestCurrency !== ''
|
||||
? $this->totalInvestmentBasis(
|
||||
is_array($settings['cost_plans'] ?? null) ? $settings['cost_plans'] : [],
|
||||
$purchasedMiners,
|
||||
$this->utcTimestamp((string) ($latest['measured_at'] ?? '')),
|
||||
$latestCurrency
|
||||
)
|
||||
: null;
|
||||
$currentDailyRevenue = is_numeric($latest['theoretical_daily_revenue'] ?? null) ? (float) $latest['theoretical_daily_revenue'] : null;
|
||||
$breakEvenRemainingAmount = $investedCapital;
|
||||
$breakEvenDaysOverall = (
|
||||
$investedCapital !== null &&
|
||||
$currentDailyRevenue !== null &&
|
||||
$currentDailyRevenue > 0
|
||||
) ? ($investedCapital / $currentDailyRevenue) : null;
|
||||
$latestSummary = array_merge($latest, [
|
||||
'invested_capital' => $this->roundOrNull($investedCapital, 8),
|
||||
'break_even_remaining_amount' => $this->roundOrNull($breakEvenRemainingAmount, 8),
|
||||
'break_even_days_overall' => $this->roundOrNull($breakEvenDaysOverall, 4),
|
||||
]);
|
||||
$currentProjection = $this->projectPerformance(
|
||||
is_array($settings['cost_plans'] ?? null) ? $settings['cost_plans'] : [],
|
||||
$purchasedMiners,
|
||||
$latestSummary,
|
||||
730
|
||||
);
|
||||
$latestSummary = array_merge($latestSummary, [
|
||||
'projection_days' => $currentProjection['days'],
|
||||
'projection_two_year_revenue' => $this->roundOrNull($currentProjection['revenue'], 8),
|
||||
'projection_two_year_cost' => $this->roundOrNull($currentProjection['cost'], 8),
|
||||
'projection_two_year_profit' => $this->roundOrNull($currentProjection['profit'], 8),
|
||||
]);
|
||||
$offerSummary = array_map(
|
||||
fn (array $offer): array => $this->enrichOfferScenario(
|
||||
$offer,
|
||||
$latestSummary,
|
||||
$currentHashrateMh,
|
||||
is_array($settings['cost_plans'] ?? null) ? $settings['cost_plans'] : [],
|
||||
$purchasedMiners
|
||||
),
|
||||
$offerSummary
|
||||
);
|
||||
|
||||
return [
|
||||
'latest_measurement' => $latestSummary,
|
||||
'baseline' => $settings,
|
||||
'targets' => $targetSummary,
|
||||
'payouts' => [
|
||||
'total_count' => count($payouts),
|
||||
'total_coins' => $this->roundOrNull(array_sum(array_map(static fn (array $payout): float => (float) ($payout['coins_amount'] ?? 0), $payouts)), 6),
|
||||
'current_visible_coins' => $this->roundOrNull((float) ($latest['coins_total_visible'] ?? $latest['coins_total']), 6),
|
||||
'current_effective_coins' => $this->roundOrNull((float) ($latest['coins_total_effective'] ?? $latest['coins_total']), 6),
|
||||
],
|
||||
'current_hashrate_mh' => $this->roundOrNull($currentHashrateMh, 4),
|
||||
'miner_offers' => $offerSummary,
|
||||
];
|
||||
}
|
||||
|
||||
public function dashboardData(array $measurements, string $xField, string $yField, string $aggregation, array $filters = []): array
|
||||
{
|
||||
$allowedX = ['measured_at', 'measured_date', 'source', 'price_currency', 'trend_label'];
|
||||
$allowedY = [
|
||||
'coins_total',
|
||||
'price_per_coin',
|
||||
'growth_since_baseline',
|
||||
'doge_per_hour_since_baseline',
|
||||
'doge_per_day_since_baseline',
|
||||
'doge_per_hour_interval',
|
||||
'doge_per_day_interval',
|
||||
'current_value',
|
||||
'theoretical_daily_revenue',
|
||||
'theoretical_daily_profit',
|
||||
];
|
||||
|
||||
if (!in_array($xField, $allowedX, true) || !in_array($yField, $allowedY, true)) {
|
||||
throw new ApiException('Dashboard-Felder sind nicht erlaubt.', 422, ['x_field' => $xField, 'y_field' => $yField]);
|
||||
}
|
||||
|
||||
$filtered = array_values(array_filter($measurements, static function (array $row) use ($filters): bool {
|
||||
if (!empty($filters['source']) && $row['source'] !== $filters['source']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!empty($filters['currency']) && $row['price_currency'] !== $filters['currency']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!empty($filters['date_from']) && (string) $row['measured_at'] < (string) $filters['date_from']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!empty($filters['date_to']) && (string) $row['measured_at'] > (string) $filters['date_to']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}));
|
||||
|
||||
if ($aggregation === 'none') {
|
||||
return array_map(static fn (array $row): array => [
|
||||
'x' => $row[$xField] ?? null,
|
||||
'y' => $row[$yField] ?? null,
|
||||
'row' => $row,
|
||||
], $filtered);
|
||||
}
|
||||
|
||||
$groups = [];
|
||||
foreach ($filtered as $row) {
|
||||
$key = (string) ($row[$xField] ?? 'unknown');
|
||||
$groups[$key][] = $row;
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($groups as $key => $rows) {
|
||||
$values = array_values(array_filter(array_map(static fn (array $row) => $row[$yField] ?? null, $rows), static fn ($value): bool => $value !== null));
|
||||
$aggregated = match ($aggregation) {
|
||||
'avg' => $values === [] ? null : array_sum($values) / count($values),
|
||||
'sum' => $values === [] ? null : array_sum($values),
|
||||
'min' => $values === [] ? null : min($values),
|
||||
'max' => $values === [] ? null : max($values),
|
||||
'count' => count($rows),
|
||||
'latest' => $rows[array_key_last($rows)][$yField] ?? null,
|
||||
default => null,
|
||||
};
|
||||
|
||||
$result[] = [
|
||||
'x' => $key,
|
||||
'y' => $this->roundOrNull(is_numeric($aggregated) ? (float) $aggregated : null, 6),
|
||||
'points' => count($rows),
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function roundOrNull(?float $value, int $precision): ?float
|
||||
{
|
||||
return $value === null ? null : round($value, $precision);
|
||||
}
|
||||
|
||||
private function effectiveDailyCost(array $costPlans, int $measurementTs, ?string $currency): ?float
|
||||
{
|
||||
if ($currency === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$dailyTotal = 0.0;
|
||||
$matched = false;
|
||||
foreach ($costPlans as $plan) {
|
||||
if (empty($plan['is_active'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$startTs = $this->utcTimestamp((string) ($plan['starts_at'] ?? ''));
|
||||
$runtimeMonths = (int) ($plan['runtime_months'] ?? 0);
|
||||
if ($startTs <= 0 || $runtimeMonths <= 0 || $measurementTs < $startTs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$runtimeDays = $runtimeMonths * 30.4375;
|
||||
$endTs = (int) round($startTs + ($runtimeDays * 86400));
|
||||
$isCovered = !empty($plan['auto_renew']) || $measurementTs <= $endTs;
|
||||
if (!$isCovered) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$planDailyCost = (float) $plan['total_cost_amount'] / $runtimeDays;
|
||||
$convertedDailyCost = $this->convertAmount(
|
||||
$planDailyCost,
|
||||
(string) ($plan['currency'] ?? ''),
|
||||
$currency
|
||||
);
|
||||
if ($convertedDailyCost === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$matched = true;
|
||||
$dailyTotal += $convertedDailyCost;
|
||||
}
|
||||
|
||||
return $matched ? $dailyTotal : null;
|
||||
}
|
||||
|
||||
private function convertLatestPrice(array $latestPriceByCurrency, string $targetCurrency): ?float
|
||||
{
|
||||
foreach ($latestPriceByCurrency as $sourceCurrency => $price) {
|
||||
$converted = $this->convertAmount((float) $price, (string) $sourceCurrency, $targetCurrency);
|
||||
if ($converted !== null) {
|
||||
return $converted;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function preferredPriceCurrency(array $latestPriceByCurrency, array $measurementDerivedPrices = []): ?string
|
||||
{
|
||||
foreach (['USD', 'EUR', 'DOGE'] as $preferredCurrency) {
|
||||
if (array_key_exists($preferredCurrency, $latestPriceByCurrency)) {
|
||||
return $preferredCurrency;
|
||||
}
|
||||
if (array_key_exists($preferredCurrency, $measurementDerivedPrices)) {
|
||||
return $preferredCurrency;
|
||||
}
|
||||
}
|
||||
|
||||
$first = array_key_first($latestPriceByCurrency);
|
||||
if (is_string($first)) {
|
||||
return $first;
|
||||
}
|
||||
|
||||
$derivedFirst = array_key_first($measurementDerivedPrices);
|
||||
return is_string($derivedFirst) ? $derivedFirst : null;
|
||||
}
|
||||
|
||||
private function measurementDerivedPrices(array $measurementRates, int $measurementId): array
|
||||
{
|
||||
if ($measurementId <= 0 || $measurementRates === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$prices = [];
|
||||
foreach ($measurementRates as $row) {
|
||||
if ((int) ($row['measurement_id'] ?? 0) !== $measurementId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$baseCurrency = strtoupper(trim((string) ($row['base_currency'] ?? '')));
|
||||
$quoteCurrency = strtoupper(trim((string) ($row['target_currency'] ?? $row['quote_currency'] ?? '')));
|
||||
$rate = is_numeric($row['rate'] ?? null) ? (float) $row['rate'] : null;
|
||||
|
||||
if ($baseCurrency !== 'DOGE' || $quoteCurrency === '' || $rate === null || $rate <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$prices[$quoteCurrency] = $rate;
|
||||
}
|
||||
|
||||
return $prices;
|
||||
}
|
||||
|
||||
private function convertAmount(?float $amount, ?string $fromCurrency, ?string $toCurrency): ?float
|
||||
{
|
||||
if ($amount === null || $fromCurrency === null || $toCurrency === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$from = strtoupper(trim($fromCurrency));
|
||||
$to = strtoupper(trim($toCurrency));
|
||||
if ($from === '' || $to === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($from === $to) {
|
||||
return $amount;
|
||||
}
|
||||
|
||||
if ($this->fx === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->fx->convert($amount, $from, $to);
|
||||
}
|
||||
|
||||
private function totalHashrateMh(array $entries): float
|
||||
{
|
||||
$total = 0.0;
|
||||
foreach ($entries as $entry) {
|
||||
if (array_key_exists('is_active', $entry) && empty($entry['is_active'])) {
|
||||
continue;
|
||||
}
|
||||
if (!$this->entryIsCovered($entry, null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$total += $this->normalizeHashrateMh($entry['mining_speed_value'] ?? null, $entry['mining_speed_unit'] ?? null);
|
||||
$total += $this->normalizeHashrateMh($entry['bonus_speed_value'] ?? null, $entry['bonus_speed_unit'] ?? null);
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
||||
private function totalPurchasedMinerCost(array $purchasedMiners, string $targetCurrency, ?int $measurementTs = null): ?float
|
||||
{
|
||||
$target = strtoupper(trim($targetCurrency));
|
||||
if ($target === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$total = 0.0;
|
||||
$matched = false;
|
||||
foreach ($purchasedMiners as $miner) {
|
||||
if (array_key_exists('is_active', $miner) && empty($miner['is_active'])) {
|
||||
continue;
|
||||
}
|
||||
if (!$this->entryIsCovered($miner, $measurementTs > 0 ? $measurementTs : null, 'purchased_at')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$amount = is_numeric($miner['total_cost_amount'] ?? null) ? (float) $miner['total_cost_amount'] : null;
|
||||
$currency = strtoupper(trim((string) ($miner['currency'] ?? '')));
|
||||
if ($amount === null || $amount <= 0 || $currency === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$converted = $this->convertAmount($amount, $currency, $target);
|
||||
if ($converted === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$matched = true;
|
||||
$total += $converted;
|
||||
}
|
||||
|
||||
return $matched ? $total : null;
|
||||
}
|
||||
|
||||
private function totalInvestmentBasis(array $costPlans, array $purchasedMiners, int $measurementTs, string $targetCurrency): ?float
|
||||
{
|
||||
$target = strtoupper(trim($targetCurrency));
|
||||
if ($target === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$total = 0.0;
|
||||
$matched = false;
|
||||
|
||||
$purchasedTotal = $this->totalPurchasedMinerCost($purchasedMiners, $target, $measurementTs);
|
||||
if ($purchasedTotal !== null) {
|
||||
$matched = true;
|
||||
$total += $purchasedTotal;
|
||||
}
|
||||
|
||||
foreach ($costPlans as $plan) {
|
||||
if (empty($plan['is_active'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$startTs = $this->utcTimestamp((string) ($plan['starts_at'] ?? ''));
|
||||
$runtimeMonths = (int) ($plan['runtime_months'] ?? 0);
|
||||
if ($startTs <= 0 || $runtimeMonths <= 0 || ($measurementTs > 0 && $measurementTs < $startTs)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$runtimeDays = $runtimeMonths * 30.4375;
|
||||
$endTs = (int) round($startTs + ($runtimeDays * 86400));
|
||||
$isCovered = !empty($plan['auto_renew']) || $measurementTs <= 0 || $measurementTs <= $endTs;
|
||||
if (!$isCovered) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$amount = is_numeric($plan['total_cost_amount'] ?? null) ? (float) $plan['total_cost_amount'] : null;
|
||||
$currency = strtoupper(trim((string) ($plan['currency'] ?? '')));
|
||||
if ($amount === null || $amount <= 0 || $currency === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$converted = $this->convertAmount($amount, $currency, $target);
|
||||
if ($converted === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$matched = true;
|
||||
$total += $converted;
|
||||
}
|
||||
|
||||
return $matched ? $total : null;
|
||||
}
|
||||
|
||||
private function entryIsCovered(array $entry, ?int $measurementTs = null, string $startField = 'starts_at'): bool
|
||||
{
|
||||
$runtimeMonths = (int) ($entry['runtime_months'] ?? 0);
|
||||
if ($runtimeMonths <= 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$startTs = $this->utcTimestamp((string) ($entry[$startField] ?? ''));
|
||||
if ($startTs <= 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$checkTs = $measurementTs ?? time();
|
||||
if ($checkTs < $startTs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$runtimeDays = $runtimeMonths * 30.4375;
|
||||
$endTs = (int) round($startTs + ($runtimeDays * 86400));
|
||||
return !empty($entry['auto_renew']) || $checkTs <= $endTs;
|
||||
}
|
||||
|
||||
private function normalizeHashrateMh(mixed $value, mixed $unit): float
|
||||
{
|
||||
if (!is_numeric($value) || !is_string($unit) || trim($unit) === '') {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$numeric = (float) $value;
|
||||
return match (trim($unit)) {
|
||||
'MH/s' => $numeric,
|
||||
'kH/s' => $numeric / 1000,
|
||||
default => 0.0,
|
||||
};
|
||||
}
|
||||
|
||||
private function evaluateMinerOffer(array $offer, array $latest, array $latestPriceByCurrency, float $currentHashrateMh, array $settings): array
|
||||
{
|
||||
$offerHashrateMh = $this->normalizeHashrateMh($offer['mining_speed_value'] ?? null, $offer['mining_speed_unit'] ?? null)
|
||||
+ $this->normalizeHashrateMh($offer['bonus_speed_value'] ?? null, $offer['bonus_speed_unit'] ?? null);
|
||||
|
||||
$paymentType = (string) ($offer['payment_type'] ?? '');
|
||||
if ($paymentType === '') {
|
||||
$paymentType = !empty($offer['price_currency']) && in_array(strtoupper((string) $offer['price_currency']), ['ADA','ARB','BNB','BTC','DAI','DOGE','DOT','ETH','LINK','LTC','SOL','USDC','USDT','XRP'], true)
|
||||
? 'crypto'
|
||||
: 'fiat';
|
||||
}
|
||||
$basePriceAmount = is_numeric($offer['base_price_amount'] ?? null)
|
||||
? (float) $offer['base_price_amount']
|
||||
: (is_numeric($offer['reference_price_amount'] ?? null)
|
||||
? (float) $offer['reference_price_amount']
|
||||
: (is_numeric($offer['usd_reference_amount'] ?? null)
|
||||
? (float) $offer['usd_reference_amount']
|
||||
: (is_numeric($offer['price_amount'] ?? null) ? (float) $offer['price_amount'] : null)));
|
||||
$basePriceCurrency = (string) ($offer['base_price_currency'] ?? $offer['reference_price_currency'] ?? (is_numeric($offer['usd_reference_amount'] ?? null) ? 'USD' : ($offer['price_currency'] ?? '')));
|
||||
$effectivePriceCurrency = $paymentType === 'crypto'
|
||||
? (string) ($settings['crypto_currency'] ?? 'DOGE')
|
||||
: $basePriceCurrency;
|
||||
$effectivePriceAmount = $basePriceAmount;
|
||||
if ($basePriceAmount !== null && $basePriceAmount > 0 && $basePriceCurrency !== '' && $effectivePriceCurrency !== '' && strtoupper($basePriceCurrency) !== strtoupper($effectivePriceCurrency)) {
|
||||
$convertedReference = $this->convertAmount($basePriceAmount, $basePriceCurrency, $effectivePriceCurrency);
|
||||
if ($convertedReference !== null && $convertedReference > 0) {
|
||||
$effectivePriceAmount = $convertedReference;
|
||||
}
|
||||
}
|
||||
$referencePriceAmount = $basePriceAmount;
|
||||
$referencePriceCurrency = $basePriceCurrency !== '' ? $basePriceCurrency : null;
|
||||
|
||||
$expectedDogePerDay = null;
|
||||
if ($currentHashrateMh > 0 && $offerHashrateMh > 0 && is_numeric($latest['doge_per_day_interval'] ?? null)) {
|
||||
$expectedDogePerDay = ((float) $latest['doge_per_day_interval'] / $currentHashrateMh) * $offerHashrateMh;
|
||||
}
|
||||
|
||||
$offerCurrencyPrice = $effectivePriceCurrency !== '' ? ($latestPriceByCurrency[$effectivePriceCurrency] ?? $this->convertLatestPrice($latestPriceByCurrency, $effectivePriceCurrency)) : null;
|
||||
$expectedDailyRevenue = ($expectedDogePerDay !== null && $offerCurrencyPrice !== null)
|
||||
? $expectedDogePerDay * $offerCurrencyPrice
|
||||
: null;
|
||||
$breakEvenDays = ($effectivePriceAmount !== null && $expectedDailyRevenue !== null && $expectedDailyRevenue > 0)
|
||||
? $effectivePriceAmount / $expectedDailyRevenue
|
||||
: null;
|
||||
|
||||
$recommendation = 'keine Basis';
|
||||
if ($breakEvenDays !== null) {
|
||||
if ($breakEvenDays <= 180) {
|
||||
$recommendation = 'lohnt eher';
|
||||
} elseif ($breakEvenDays <= 365) {
|
||||
$recommendation = 'abwaegen';
|
||||
} else {
|
||||
$recommendation = 'eher warten';
|
||||
}
|
||||
}
|
||||
|
||||
return array_merge($offer, [
|
||||
'payment_type' => $paymentType,
|
||||
'base_price_amount' => $this->roundOrNull($basePriceAmount, 8),
|
||||
'base_price_currency' => $basePriceCurrency !== '' ? $basePriceCurrency : null,
|
||||
'offer_hashrate_mh' => $this->roundOrNull($offerHashrateMh, 4),
|
||||
'effective_price_amount' => $this->roundOrNull($effectivePriceAmount, 8),
|
||||
'effective_price_currency' => $effectivePriceCurrency,
|
||||
'reference_price_amount' => $this->roundOrNull($referencePriceAmount, 8),
|
||||
'reference_price_currency' => $referencePriceCurrency !== '' ? $referencePriceCurrency : null,
|
||||
'expected_doge_per_day' => $this->roundOrNull($expectedDogePerDay, 6),
|
||||
'expected_daily_revenue' => $this->roundOrNull($expectedDailyRevenue, 8),
|
||||
'break_even_days' => $this->roundOrNull($breakEvenDays, 2),
|
||||
'recommendation' => $recommendation,
|
||||
]);
|
||||
}
|
||||
|
||||
private function enrichOfferScenario(array $offer, array $latest, float $currentHashrateMh, array $costPlans, array $purchasedMiners): array
|
||||
{
|
||||
$latestCurrency = (string) ($latest['effective_price_currency'] ?? $latest['price_currency'] ?? '');
|
||||
$currentDogePerDay = is_numeric($latest['doge_per_day_interval'] ?? null) ? (float) $latest['doge_per_day_interval'] : null;
|
||||
$currentDailyProfit = is_numeric($latest['theoretical_daily_profit'] ?? null) ? (float) $latest['theoretical_daily_profit'] : null;
|
||||
$currentDailyCost = is_numeric($latest['effective_daily_cost'] ?? null) ? (float) $latest['effective_daily_cost'] : null;
|
||||
$investedCapital = is_numeric($latest['invested_capital'] ?? null) ? (float) $latest['invested_capital'] : null;
|
||||
$effectivePricePerCoin = is_numeric($latest['effective_price_per_coin'] ?? null) ? (float) $latest['effective_price_per_coin'] : null;
|
||||
$expectedDogePerDay = is_numeric($offer['expected_doge_per_day'] ?? null) ? (float) $offer['expected_doge_per_day'] : null;
|
||||
$offerPriceAmount = is_numeric($offer['effective_price_amount'] ?? null) ? (float) $offer['effective_price_amount'] : null;
|
||||
$offerPriceCurrency = (string) ($offer['effective_price_currency'] ?? '');
|
||||
|
||||
$scenarioOfferCost = (
|
||||
$offerPriceAmount !== null &&
|
||||
$offerPriceCurrency !== '' &&
|
||||
$latestCurrency !== ''
|
||||
) ? $this->convertAmount($offerPriceAmount, $offerPriceCurrency, $latestCurrency) : null;
|
||||
$scenarioDogePerDay = (
|
||||
$currentDogePerDay !== null &&
|
||||
$expectedDogePerDay !== null
|
||||
) ? ($currentDogePerDay + $expectedDogePerDay) : null;
|
||||
$scenarioDailyRevenue = (
|
||||
$scenarioDogePerDay !== null &&
|
||||
$effectivePricePerCoin !== null
|
||||
) ? ($scenarioDogePerDay * $effectivePricePerCoin) : null;
|
||||
$scenarioDailyProfit = (
|
||||
$scenarioDailyRevenue !== null &&
|
||||
$currentDailyCost !== null
|
||||
) ? ($scenarioDailyRevenue - $currentDailyCost) : null;
|
||||
$scenarioInvestedCapital = (
|
||||
$investedCapital !== null &&
|
||||
$scenarioOfferCost !== null
|
||||
) ? ($investedCapital + $scenarioOfferCost) : null;
|
||||
$scenarioRemainingAmount = $scenarioInvestedCapital;
|
||||
$scenarioBreakEvenDays = (
|
||||
$scenarioInvestedCapital !== null &&
|
||||
$scenarioDailyRevenue !== null &&
|
||||
$scenarioDailyRevenue > 0
|
||||
) ? ($scenarioInvestedCapital / $scenarioDailyRevenue) : null;
|
||||
$scenarioDate = null;
|
||||
$measuredTs = $this->utcTimestamp((string) ($latest['measured_at'] ?? ''));
|
||||
if ($measuredTs > 0 && $scenarioBreakEvenDays !== null) {
|
||||
$scenarioDate = $this->formatUtcTimestamp((int) round($measuredTs + ($scenarioBreakEvenDays * 86400)));
|
||||
}
|
||||
|
||||
$scenarioPurchasedMiners = $purchasedMiners;
|
||||
if ($scenarioOfferCost !== null && $latestCurrency !== '') {
|
||||
$scenarioPurchasedMiners[] = [
|
||||
'purchased_at' => $latest['measured_at'] ?? $this->currentUtcDateTime(),
|
||||
'runtime_months' => $offer['runtime_months'] ?? null,
|
||||
'mining_speed_value' => $offer['mining_speed_value'] ?? null,
|
||||
'mining_speed_unit' => $offer['mining_speed_unit'] ?? null,
|
||||
'bonus_speed_value' => $offer['bonus_speed_value'] ?? null,
|
||||
'bonus_speed_unit' => $offer['bonus_speed_unit'] ?? null,
|
||||
'total_cost_amount' => $scenarioOfferCost,
|
||||
'currency' => $latestCurrency,
|
||||
'auto_renew' => !empty($offer['auto_renew']) ? 1 : 0,
|
||||
'is_active' => 1,
|
||||
];
|
||||
}
|
||||
|
||||
$currentProjection = $this->projectPerformance($costPlans, $purchasedMiners, $latest, 730);
|
||||
$scenarioProjection = $this->projectPerformance($costPlans, $scenarioPurchasedMiners, $latest, 730);
|
||||
|
||||
return array_merge($offer, [
|
||||
'scenario_currency' => $latestCurrency !== '' ? $latestCurrency : null,
|
||||
'scenario_current_hashrate_mh' => $this->roundOrNull($currentHashrateMh, 4),
|
||||
'scenario_hashrate_mh' => $this->roundOrNull($currentHashrateMh + (float) ($offer['offer_hashrate_mh'] ?? 0), 4),
|
||||
'scenario_current_doge_per_day' => $this->roundOrNull($currentDogePerDay, 6),
|
||||
'scenario_doge_per_day' => $this->roundOrNull($scenarioDogePerDay, 6),
|
||||
'scenario_current_daily_profit' => $this->roundOrNull($currentDailyProfit, 8),
|
||||
'scenario_daily_profit' => $this->roundOrNull($scenarioDailyProfit, 8),
|
||||
'scenario_daily_profit_delta' => (
|
||||
$scenarioDailyProfit !== null &&
|
||||
$currentDailyProfit !== null
|
||||
) ? $this->roundOrNull($scenarioDailyProfit - $currentDailyProfit, 8) : null,
|
||||
'scenario_current_invested_capital' => $this->roundOrNull($investedCapital, 8),
|
||||
'scenario_invested_capital' => $this->roundOrNull($scenarioInvestedCapital, 8),
|
||||
'scenario_offer_cost' => $this->roundOrNull($scenarioOfferCost, 8),
|
||||
'scenario_break_even_remaining_amount' => $this->roundOrNull($scenarioRemainingAmount, 8),
|
||||
'scenario_break_even_days' => $this->roundOrNull($scenarioBreakEvenDays, 4),
|
||||
'scenario_break_even_date' => $scenarioDate,
|
||||
'scenario_projection_days' => $scenarioProjection['days'],
|
||||
'scenario_current_two_year_profit' => $this->roundOrNull($currentProjection['profit'], 8),
|
||||
'scenario_two_year_profit' => $this->roundOrNull($scenarioProjection['profit'], 8),
|
||||
'scenario_two_year_profit_delta' => (
|
||||
$scenarioProjection['profit'] !== null &&
|
||||
$currentProjection['profit'] !== null
|
||||
) ? $this->roundOrNull($scenarioProjection['profit'] - $currentProjection['profit'], 8) : null,
|
||||
'scenario_two_year_revenue' => $this->roundOrNull($scenarioProjection['revenue'], 8),
|
||||
'scenario_two_year_cost' => $this->roundOrNull($scenarioProjection['cost'], 8),
|
||||
]);
|
||||
}
|
||||
|
||||
private function projectPerformance(array $costPlans, array $purchasedMiners, array $latest, int $days): array
|
||||
{
|
||||
$currency = strtoupper(trim((string) ($latest['effective_price_currency'] ?? $latest['price_currency'] ?? '')));
|
||||
$pricePerCoin = is_numeric($latest['effective_price_per_coin'] ?? null) ? (float) $latest['effective_price_per_coin'] : null;
|
||||
$dogePerDay = is_numeric($latest['doge_per_day_interval'] ?? null) ? (float) $latest['doge_per_day_interval'] : null;
|
||||
$currentHashrateMh = $this->totalHashrateMh(array_merge($costPlans, $purchasedMiners));
|
||||
$baseTs = $this->utcTimestamp((string) ($latest['measured_at'] ?? ''));
|
||||
if ($baseTs <= 0) {
|
||||
$baseTs = $this->utcTimestamp($this->currentUtcDateTime());
|
||||
}
|
||||
|
||||
if ($currency === '' || $pricePerCoin === null || $dogePerDay === null || $currentHashrateMh <= 0 || $days <= 0) {
|
||||
return ['days' => $days, 'revenue' => null, 'cost' => null, 'profit' => null];
|
||||
}
|
||||
|
||||
$dogePerDayPerMh = $dogePerDay / $currentHashrateMh;
|
||||
$revenue = 0.0;
|
||||
$cost = 0.0;
|
||||
|
||||
for ($day = 0; $day < $days; $day++) {
|
||||
$checkTs = $baseTs + ($day * 86400);
|
||||
$activeHashrate = 0.0;
|
||||
|
||||
foreach ($costPlans as $plan) {
|
||||
if (empty($plan['is_active']) || !$this->entryIsCovered($plan, $checkTs)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$activeHashrate += $this->normalizeHashrateMh($plan['mining_speed_value'] ?? null, $plan['mining_speed_unit'] ?? null);
|
||||
$activeHashrate += $this->normalizeHashrateMh($plan['bonus_speed_value'] ?? null, $plan['bonus_speed_unit'] ?? null);
|
||||
|
||||
$runtimeMonths = (int) ($plan['runtime_months'] ?? 0);
|
||||
if ($runtimeMonths > 0 && is_numeric($plan['total_cost_amount'] ?? null)) {
|
||||
$runtimeDays = $runtimeMonths * 30.4375;
|
||||
$dailyCost = $this->convertAmount((float) $plan['total_cost_amount'] / $runtimeDays, (string) ($plan['currency'] ?? ''), $currency);
|
||||
if ($dailyCost !== null) {
|
||||
$cost += $dailyCost;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($purchasedMiners as $miner) {
|
||||
if ((array_key_exists('is_active', $miner) && empty($miner['is_active'])) || !$this->entryIsCovered($miner, $checkTs, 'purchased_at')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$activeHashrate += $this->normalizeHashrateMh($miner['mining_speed_value'] ?? null, $miner['mining_speed_unit'] ?? null);
|
||||
$activeHashrate += $this->normalizeHashrateMh($miner['bonus_speed_value'] ?? null, $miner['bonus_speed_unit'] ?? null);
|
||||
|
||||
$runtimeMonths = (int) ($miner['runtime_months'] ?? 0);
|
||||
if ($runtimeMonths > 0 && is_numeric($miner['total_cost_amount'] ?? null)) {
|
||||
$runtimeDays = $runtimeMonths * 30.4375;
|
||||
$dailyCost = $this->convertAmount((float) $miner['total_cost_amount'] / $runtimeDays, (string) ($miner['currency'] ?? ''), $currency);
|
||||
if ($dailyCost !== null) {
|
||||
$cost += $dailyCost;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$revenue += $activeHashrate * $dogePerDayPerMh * $pricePerCoin;
|
||||
}
|
||||
|
||||
return [
|
||||
'days' => $days,
|
||||
'revenue' => $revenue,
|
||||
'cost' => $cost,
|
||||
'profit' => $revenue - $cost,
|
||||
];
|
||||
}
|
||||
|
||||
private function utcTimestamp(?string $value): int
|
||||
{
|
||||
$normalized = trim((string) $value);
|
||||
if ($normalized === '') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$utc = new \DateTimeZone('UTC');
|
||||
$formats = ['Y-m-d H:i:s', 'Y-m-d H:i', \DateTimeInterface::ATOM];
|
||||
foreach ($formats as $format) {
|
||||
$date = \DateTimeImmutable::createFromFormat($format, $normalized, $utc);
|
||||
if ($date instanceof \DateTimeImmutable) {
|
||||
return $date->getTimestamp();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return (new \DateTimeImmutable($normalized, $utc))->getTimestamp();
|
||||
} catch (\Throwable) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private function formatUtcTimestamp(int $timestamp): string
|
||||
{
|
||||
return (new \DateTimeImmutable('@' . $timestamp))
|
||||
->setTimezone(new \DateTimeZone('UTC'))
|
||||
->format('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
private function currentUtcDateTime(): string
|
||||
{
|
||||
return $this->formatUtcTimestamp(time());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user