|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Modules\Finance\Http\Controllers; |
| 4 | + |
| 5 | +use App\Http\Controllers\Controller; |
| 6 | +use App\Modules\Finance\Models\Attachment; |
| 7 | +use Illuminate\Http\RedirectResponse; |
| 8 | +use Illuminate\Http\Request; |
| 9 | +use Illuminate\Http\Response; |
| 10 | +use Illuminate\Support\Facades\Storage; |
| 11 | + |
| 12 | +class AttachmentController extends Controller |
| 13 | +{ |
| 14 | + private array $allowedModels = [ |
| 15 | + 'invoices' => \App\Modules\Finance\Models\Invoice::class, |
| 16 | + 'bills' => \App\Modules\Finance\Models\Bill::class, |
| 17 | + 'expense-claims' => \App\Modules\HR\Models\ExpenseClaim::class, |
| 18 | + 'projects' => \App\Modules\Finance\Models\Project::class, |
| 19 | + ]; |
| 20 | + |
| 21 | + public function store(Request $request, string $modelType, int $modelId): RedirectResponse |
| 22 | + { |
| 23 | + abort_unless(array_key_exists($modelType, $this->allowedModels), 404); |
| 24 | + |
| 25 | + $this->authorize('create', Attachment::class); |
| 26 | + |
| 27 | + $request->validate([ |
| 28 | + 'file' => 'required|file|max:20480|mimes:pdf,png,jpg,jpeg,webp,gif,csv,xlsx,docx,doc', |
| 29 | + ]); |
| 30 | + |
| 31 | + $modelClass = $this->allowedModels[$modelType]; |
| 32 | + $model = $modelClass::findOrFail($modelId); |
| 33 | + |
| 34 | + $file = $request->file('file'); |
| 35 | + $path = $file->store("attachments/{$modelType}/{$modelId}", 'local'); |
| 36 | + |
| 37 | + Attachment::create([ |
| 38 | + 'tenant_id' => auth()->user()->tenant_id, |
| 39 | + 'attachable_type' => $modelClass, |
| 40 | + 'attachable_id' => $modelId, |
| 41 | + 'filename' => $file->getClientOriginalName(), |
| 42 | + 'disk' => 'local', |
| 43 | + 'path' => $path, |
| 44 | + 'mime_type' => $file->getMimeType(), |
| 45 | + 'size' => $file->getSize(), |
| 46 | + 'uploaded_by' => auth()->id(), |
| 47 | + ]); |
| 48 | + |
| 49 | + return back()->with('success', 'File attached.'); |
| 50 | + } |
| 51 | + |
| 52 | + public function download(Attachment $attachment): Response|\Symfony\Component\HttpFoundation\StreamedResponse |
| 53 | + { |
| 54 | + $this->authorize('view', $attachment); |
| 55 | + |
| 56 | + abort_unless(Storage::disk($attachment->disk)->exists($attachment->path), 404); |
| 57 | + |
| 58 | + return Storage::disk($attachment->disk)->download($attachment->path, $attachment->filename); |
| 59 | + } |
| 60 | + |
| 61 | + public function destroy(Attachment $attachment): RedirectResponse |
| 62 | + { |
| 63 | + $this->authorize('delete', $attachment); |
| 64 | + |
| 65 | + Storage::disk($attachment->disk)->delete($attachment->path); |
| 66 | + $attachment->delete(); |
| 67 | + |
| 68 | + return back()->with('success', 'Attachment deleted.'); |
| 69 | + } |
| 70 | +} |
0 commit comments