MemberFileService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Storage;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Http\UploadedFile;
  6. use Exception;
  7. class MemberFileService
  8. {
  9. /**
  10. * The storage disk to use for file operations
  11. */
  12. private $disk;
  13. /**
  14. * Allowed file extensions for different file types
  15. */
  16. private const ALLOWED_IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif'];
  17. private const ALLOWED_DOCUMENT_EXTENSIONS = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];
  18. /**
  19. * Maximum file sizes in KB
  20. */
  21. private const MAX_IMAGE_SIZE = 2048; // 2MB
  22. private const MAX_DOCUMENT_SIZE = 10240; // 10MB
  23. /**
  24. * Constructor
  25. */
  26. public function __construct()
  27. {
  28. $this->disk = Storage::disk('s3');
  29. }
  30. /**
  31. * Upload member profile image
  32. *
  33. * @param UploadedFile $imageFile
  34. * @param int $memberId
  35. * @return string
  36. * @throws Exception
  37. */
  38. public function uploadProfileImage(UploadedFile $imageFile, int $memberId): string
  39. {
  40. try {
  41. $currentClient = session('currentClient', 'default');
  42. // Validate file
  43. $this->validateFile($imageFile, 'image');
  44. // Delete existing profile image
  45. $this->deleteExistingProfileImage($memberId);
  46. // Create new filename
  47. $extension = strtolower($imageFile->getClientOriginalExtension());
  48. $filename = 'profile_' . $memberId . '_' . time() . '.' . $extension;
  49. // Upload to S3
  50. $s3Path = $currentClient . '/members/' . $memberId . '/images/' . $filename;
  51. $uploaded = $this->disk->putFileAs(
  52. $currentClient . '/members/' . $memberId . '/images',
  53. $imageFile,
  54. $filename,
  55. 'private'
  56. );
  57. if (!$uploaded) {
  58. throw new Exception('Failed to upload profile image to S3');
  59. }
  60. Log::info("Profile image uploaded", [
  61. 'member_id' => $memberId,
  62. 'path' => $s3Path,
  63. 'size' => $imageFile->getSize()
  64. ]);
  65. return $s3Path;
  66. } catch (Exception $e) {
  67. Log::error("Error uploading profile image", [
  68. 'member_id' => $memberId,
  69. 'error' => $e->getMessage()
  70. ]);
  71. throw $e;
  72. }
  73. }
  74. /**
  75. * Upload single document file
  76. *
  77. * @param UploadedFile $documentFile
  78. * @param int $memberId
  79. * @param string $documentType ('self', 'father', 'mother')
  80. * @return string
  81. * @throws Exception
  82. */
  83. public function uploadDocument(UploadedFile $documentFile, int $memberId, string $documentType = 'self'): string
  84. {
  85. try {
  86. $currentClient = session('currentClient', 'default');
  87. // Validate file
  88. $this->validateFile($documentFile, 'document');
  89. // Create filename
  90. $originalName = pathinfo($documentFile->getClientOriginalName(), PATHINFO_FILENAME);
  91. $extension = strtolower($documentFile->getClientOriginalExtension());
  92. $filename = $documentType . '_' . $originalName . '_' . time() . '.' . $extension;
  93. // Upload to S3
  94. $s3Path = $currentClient . '/members/' . $memberId . '/documents/' . $filename;
  95. $uploaded = $this->disk->putFileAs(
  96. $currentClient . '/members/' . $memberId . '/documents',
  97. $documentFile,
  98. $filename,
  99. 'private'
  100. );
  101. if (!$uploaded) {
  102. throw new Exception('Failed to upload document to S3: ' . $originalName);
  103. }
  104. Log::info("Document uploaded", [
  105. 'member_id' => $memberId,
  106. 'type' => $documentType,
  107. 'path' => $s3Path,
  108. 'original_name' => $documentFile->getClientOriginalName()
  109. ]);
  110. return $s3Path;
  111. } catch (Exception $e) {
  112. Log::error("Error uploading document", [
  113. 'member_id' => $memberId,
  114. 'type' => $documentType,
  115. 'error' => $e->getMessage()
  116. ]);
  117. throw $e;
  118. }
  119. }
  120. /**
  121. * Upload certificate file
  122. *
  123. * @param UploadedFile $certificateFile
  124. * @param int $memberId
  125. * @return string
  126. * @throws Exception
  127. */
  128. public function uploadCertificate(UploadedFile $certificateFile, int $memberId): string
  129. {
  130. try {
  131. $currentClient = session('currentClient', 'default');
  132. // Validate file
  133. $this->validateFile($certificateFile, 'document');
  134. // Create filename
  135. $extension = strtolower($certificateFile->getClientOriginalExtension());
  136. $filename = 'certificate_' . $memberId . '_' . time() . '.' . $extension;
  137. // Upload to S3
  138. $s3Path = $currentClient . '/members/' . $memberId . '/certificates/' . $filename;
  139. $uploaded = $this->disk->putFileAs(
  140. $currentClient . '/members/' . $memberId . '/certificates',
  141. $certificateFile,
  142. $filename,
  143. 'private'
  144. );
  145. if (!$uploaded) {
  146. throw new Exception('Failed to upload certificate to S3');
  147. }
  148. Log::info("Certificate uploaded", [
  149. 'member_id' => $memberId,
  150. 'path' => $s3Path,
  151. 'size' => $certificateFile->getSize()
  152. ]);
  153. return $s3Path;
  154. } catch (Exception $e) {
  155. Log::error("Error uploading certificate", [
  156. 'member_id' => $memberId,
  157. 'error' => $e->getMessage()
  158. ]);
  159. throw $e;
  160. }
  161. }
  162. /**
  163. * Get file URL for display
  164. *
  165. * @param string $filePath
  166. * @param string $expiresIn
  167. * @return string|null
  168. */
  169. public function getFileUrl(string $filePath, string $expiresIn = '+1 hour'): ?string
  170. {
  171. if (!$filePath) {
  172. return null;
  173. }
  174. // Handle legacy local paths - return asset URL
  175. if (!$this->isS3Path($filePath)) {
  176. return asset('storage/' . $filePath);
  177. }
  178. try {
  179. if (!$this->disk->exists($filePath)) {
  180. Log::warning("File not found", ['path' => $filePath]);
  181. return null;
  182. }
  183. return $this->disk->temporaryUrl($filePath, now()->add($expiresIn));
  184. } catch (Exception $e) {
  185. Log::error("Error generating file URL", [
  186. 'path' => $filePath,
  187. 'error' => $e->getMessage()
  188. ]);
  189. return null;
  190. }
  191. }
  192. /**
  193. * Delete file from S3
  194. *
  195. * @param string $filePath
  196. * @return bool
  197. */
  198. public function deleteFile(string $filePath): bool
  199. {
  200. // Don't try to delete local files
  201. if (!$this->isS3Path($filePath)) {
  202. return false;
  203. }
  204. try {
  205. if ($this->disk->exists($filePath)) {
  206. $this->disk->delete($filePath);
  207. Log::info("File deleted", ['path' => $filePath]);
  208. return true;
  209. }
  210. return false;
  211. } catch (Exception $e) {
  212. Log::error("Error deleting file", [
  213. 'path' => $filePath,
  214. 'error' => $e->getMessage()
  215. ]);
  216. return false;
  217. }
  218. }
  219. /**
  220. * Check if path is S3 path
  221. */
  222. private function isS3Path(string $path): bool
  223. {
  224. return strpos($path, '/members/') !== false ||
  225. strpos($path, session('currentClient', 'default')) === 0;
  226. }
  227. /**
  228. * Delete existing profile image for member
  229. *
  230. * @param int $memberId
  231. */
  232. private function deleteExistingProfileImage(int $memberId): void
  233. {
  234. try {
  235. $currentClient = session('currentClient', 'default');
  236. $imagePath = $currentClient . '/members/' . $memberId . '/images/';
  237. // List all files in the member's image directory
  238. $files = $this->disk->files($imagePath);
  239. foreach ($files as $file) {
  240. if (strpos(basename($file), 'profile_' . $memberId) === 0) {
  241. $this->disk->delete($file);
  242. Log::info("Deleted existing profile image", [
  243. 'member_id' => $memberId,
  244. 'file' => $file
  245. ]);
  246. }
  247. }
  248. } catch (Exception $e) {
  249. Log::warning("Error deleting existing profile image", [
  250. 'member_id' => $memberId,
  251. 'error' => $e->getMessage()
  252. ]);
  253. }
  254. }
  255. /**
  256. * Validate uploaded file
  257. *
  258. * @param UploadedFile $file
  259. * @param string $type ('image' or 'document')
  260. * @throws Exception
  261. */
  262. private function validateFile(UploadedFile $file, string $type): void
  263. {
  264. // Check if file is valid
  265. if (!$file->isValid()) {
  266. throw new Exception('Invalid file upload');
  267. }
  268. $extension = strtolower($file->getClientOriginalExtension());
  269. $allowedExtensions = $type === 'image' ? self::ALLOWED_IMAGE_EXTENSIONS : self::ALLOWED_DOCUMENT_EXTENSIONS;
  270. $maxSize = $type === 'image' ? self::MAX_IMAGE_SIZE : self::MAX_DOCUMENT_SIZE;
  271. // Check file extension
  272. if (!in_array($extension, $allowedExtensions)) {
  273. throw new Exception("File type not allowed. Allowed types: " . implode(', ', $allowedExtensions));
  274. }
  275. // Check file size
  276. if ($file->getSize() > ($maxSize * 1024)) {
  277. throw new Exception("File size exceeds maximum allowed size of {$maxSize}KB");
  278. }
  279. // Check mime type for images
  280. if ($type === 'image') {
  281. $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
  282. if (!in_array($file->getMimeType(), $allowedMimeTypes)) {
  283. throw new Exception('Invalid image file type');
  284. }
  285. }
  286. }
  287. /**
  288. * Create member folder structure in S3
  289. *
  290. * @param int $memberId
  291. */
  292. public function createMemberFolders(int $memberId): void
  293. {
  294. try {
  295. $currentClient = session('currentClient', 'default');
  296. $folders = [
  297. $currentClient . '/members/' . $memberId . '/images/.gitkeep',
  298. $currentClient . '/members/' . $memberId . '/documents/.gitkeep',
  299. $currentClient . '/members/' . $memberId . '/certificates/.gitkeep'
  300. ];
  301. foreach ($folders as $folder) {
  302. if (!$this->disk->exists($folder)) {
  303. $this->disk->put($folder, '');
  304. }
  305. }
  306. Log::info("Created member folder structure", ['member_id' => $memberId]);
  307. } catch (Exception $e) {
  308. Log::error("Error creating member folders", [
  309. 'member_id' => $memberId,
  310. 'error' => $e->getMessage()
  311. ]);
  312. }
  313. }
  314. /**
  315. * Get file info
  316. *
  317. * @param string $filePath
  318. * @return array|null
  319. */
  320. public function getFileInfo(string $filePath): ?array
  321. {
  322. if (!$filePath) {
  323. return null;
  324. }
  325. // Handle legacy local paths
  326. if (!$this->isS3Path($filePath)) {
  327. $localPath = storage_path('app/public/' . $filePath);
  328. if (file_exists($localPath)) {
  329. return [
  330. 'path' => $filePath,
  331. 'name' => basename($filePath),
  332. 'size' => filesize($localPath),
  333. 'last_modified' => filemtime($localPath),
  334. 'url' => $this->getFileUrl($filePath),
  335. 'exists' => true,
  336. 'storage_type' => 'local'
  337. ];
  338. }
  339. return null;
  340. }
  341. if (!$this->disk->exists($filePath)) {
  342. return null;
  343. }
  344. try {
  345. return [
  346. 'path' => $filePath,
  347. 'name' => basename($filePath),
  348. 'size' => $this->disk->size($filePath),
  349. 'last_modified' => $this->disk->lastModified($filePath),
  350. 'url' => $this->getFileUrl($filePath),
  351. 'exists' => true,
  352. 'storage_type' => 's3'
  353. ];
  354. } catch (Exception $e) {
  355. Log::error("Error getting file info", [
  356. 'path' => $filePath,
  357. 'error' => $e->getMessage()
  358. ]);
  359. return null;
  360. }
  361. }
  362. }