| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Hooks\Handlers; |
| 4 |
|
| 5 |
use FluentCart\App\Services\Report\RetentionSnapshotService; |
| 6 |
|
| 7 |
class RetentionSnapshotHandler |
| 8 |
{ |
| 9 |
/** |
| 10 |
* Register Action Scheduler hooks |
| 11 |
*/ |
| 12 |
public function register() |
| 13 |
{ |
| 14 |
add_action('fluent_cart_generate_retention_snapshots', [$this, 'generateSnapshots'], 10, 2); |
| 15 |
} |
| 16 |
|
| 17 |
/** |
| 18 |
* Action Scheduler callback to generate retention snapshots |
| 19 |
* |
| 20 |
* @param array $args ['product_id' => int|null] |
| 21 |
*/ |
| 22 |
public function generateSnapshots($productId = null, $jobId = null) |
| 23 |
{ |
| 24 |
// Update job status to running |
| 25 |
if ($jobId) { |
| 26 |
update_option('fluent_cart_snapshot_job_' . $jobId, [ |
| 27 |
'status' => 'running', |
| 28 |
'started_at' => current_time('mysql'), |
| 29 |
'product_id' => $productId, |
| 30 |
]); |
| 31 |
} |
| 32 |
|
| 33 |
try { |
| 34 |
// Run the snapshot generation |
| 35 |
$service = new RetentionSnapshotService(); |
| 36 |
$result = $service->generate($productId, null); |
| 37 |
|
| 38 |
// Update job status with results |
| 39 |
if ($jobId) { |
| 40 |
update_option('fluent_cart_snapshot_job_' . $jobId, [ |
| 41 |
'status' => $result['success'] ? 'completed' : 'failed', |
| 42 |
'started_at' => current_time('mysql'), |
| 43 |
'completed_at' => current_time('mysql'), |
| 44 |
'product_id' => $productId, |
| 45 |
'message' => $result['message'], |
| 46 |
'stats' => $result['stats'] ?? [], |
| 47 |
]); |
| 48 |
} |
| 49 |
|
| 50 |
} catch (\Exception $e) { |
| 51 |
// Update job status with error |
| 52 |
if ($jobId) { |
| 53 |
update_option('fluent_cart_snapshot_job_' . $jobId, [ |
| 54 |
'status' => 'failed', |
| 55 |
'started_at' => current_time('mysql'), |
| 56 |
'completed_at' => current_time('mysql'), |
| 57 |
'product_id' => $productId, |
| 58 |
'message' => $e->getMessage(), |
| 59 |
'stats' => [], |
| 60 |
]); |
| 61 |
} |
| 62 |
|
| 63 |
error_log('FluentCart: Retention snapshot generation error - ' . $e->getMessage()); |
| 64 |
throw $e; // Re-throw so Action Scheduler marks it as failed |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
|