findOrFail($id); return response()->json([ 'error' => false, 'data' => [ 'attachments' => ServiceAttachment::where('service_id', $id)->latest()->get(), 'invoices' => $this->linkedInvoices(collect([$service])), ], ]); } public function uploadAttachment(Request $request, int $id): JsonResponse { Service::findOrFail($id); $audience = $request->validate([ 'file' => ServiceAttachment::UPLOAD_RULE, 'audience' => 'nullable|in:' . ServiceAttachment::AUDIENCE_ADMIN . ',' . ServiceAttachment::AUDIENCE_CUSTOMER, ])['audience'] ?? ServiceAttachment::AUDIENCE_ADMIN; $file = $request->file('file'); $attachment = ServiceAttachment::create([ 'service_id' => $id, 'audience' => $audience, 'filename' => $file->getClientOriginalName(), 'path' => $file->store("service-attachments/{$id}", 'public'), 'disk' => 'public', 'mime_type' => $file->getMimeType(), 'size' => $file->getSize(), 'uploaded_by' => $request->user()?->username ?? $request->user()?->name ?? 'admin', ]); return response()->json(['error' => false, 'message' => 'File uploaded successfully', 'data' => $attachment], 201); } public function deleteAttachment(int $id, int $attachmentId): JsonResponse { $attachment = ServiceAttachment::where('service_id', $id)->findOrFail($attachmentId); Storage::disk($attachment->disk)->delete($attachment->path); $attachment->delete(); return response()->json(['error' => false, 'message' => 'Attachment deleted']); } public function copyAttachmentToInvoice(Request $request, int $id, int $attachmentId): JsonResponse { $service = Service::with('orderItem')->findOrFail($id); $attachment = ServiceAttachment::where('service_id', $id)->findOrFail($attachmentId); $invoiceId = (int) $request->validate(['invoice_id' => 'required|integer'])['invoice_id']; $invoice = Invoice::ofServices([$service])->findOrFail($invoiceId); $path = "invoice-attachments/{$invoice->id}/" . basename($attachment->path); if (!Storage::disk('public')->exists($path)) { Storage::disk('public')->put($path, Storage::disk($attachment->disk)->readStream($attachment->path)); } $copy = InvoiceAttachment::firstOrCreate( ['invoice_id' => $invoice->id, 'path' => $path], [ 'type' => InvoiceAttachment::TYPE_DEPLOYMENT, 'filename' => $attachment->filename, 'disk' => 'public', 'mime_type' => $attachment->mime_type, 'size' => $attachment->size, 'uploaded_by' => $request->user()?->username ?? $request->user()?->name ?? 'admin', ], ); return response()->json(['error' => false, 'message' => 'Attachment copied to invoice', 'data' => $copy], 201); } }