-
-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathTenantAwareExportJob.php
More file actions
93 lines (77 loc) · 2.56 KB
/
TenantAwareExportJob.php
File metadata and controls
93 lines (77 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace App\Jobs;
use Croustibat\FilamentJobsMonitor\Traits\QueueProgress;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
/**
* Example job demonstrating multi-tenancy support.
*
* The key requirement for multi-tenancy is the public `tenantId` property.
* When this property exists, the plugin will automatically:
* - Associate the job monitor record with the tenant
* - Filter the job list to show only jobs for the current tenant
*/
class TenantAwareExportJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, QueueProgress, SerializesModels;
/**
* Create a new job instance.
*
* @param int|string $tenantId Required for multi-tenancy - the ID of the tenant this job belongs to
* @param Collection $data The data to be exported
* @param string $filename The output filename
*/
public function __construct(
public int|string $tenantId,
protected Collection $data,
protected string $filename
) {
$this->data = $data->pluck('email', 'name');
}
/**
* Execute the job.
*/
public function handle(): void
{
$this->setProgress(0);
// Create a stream to write the CSV data to
$stream = fopen('php://temp', 'w+');
$total = $this->data->count();
$processed = 0;
// Write each item in the collection to the CSV stream
foreach ($this->data->toArray() as $key => $item) {
fputcsv($stream, [$key, $item]);
$processed++;
if ($total > 0) {
$this->setProgress((int) ($processed / $total * 80));
}
}
// Rewind the stream pointer to the beginning
rewind($stream);
// Read the contents of the stream into a string
$csv = stream_get_contents($stream);
// Close the stream
fclose($stream);
$this->setProgress(90);
// Save the CSV data to a file in storage
// In a real app, you might save to a tenant-specific path
Storage::put("exports/tenant-{$this->tenantId}/{$this->filename}", $csv);
$this->setProgress(100);
}
}
/*
* Usage example:
*
* use Filament\Facades\Filament;
*
* TenantAwareExportJob::dispatch(
* tenantId: Filament::getTenant()->id,
* data: User::all(),
* filename: 'users.csv'
* );
*/