Files
sam-api/app/Services/FileStorageService.php
권혁성 5448f0e57d deploy: 2026-03-12 배포
- feat: [barobill] 바로빌 카드/은행/홈택스 REST API 구현
- feat: [equipment] 설비관리 API 백엔드 구현
- feat: [payroll] 급여관리 계산 엔진 및 일괄 처리 API
- feat: [QMS] 점검표 템플릿 관리 + 로트심사 개선
- feat: [생산/출하] 수주 단위 출하 자동생성 + 상태 흐름 개선
- feat: [receiving] 입고 성적서 파일 연결
- feat: [견적] 제어기 타입 체계 변경
- feat: [email] 테넌트 메일 설정 마이그레이션 및 모델
- feat: [pmis] 시공관리 테이블 마이그레이션
- feat: [R2] 파일 업로드 커맨드 + filesystems 설정
- feat: [배포] Jenkinsfile 롤백 기능 추가
- fix: [approval] SAM API 규칙 준수 코드 개선
- fix: [account-codes] 계정과목 중복 데이터 정리
- fix: [payroll] 일괄 생성 시 삭제된 사용자 건너뛰기
- fix: [db] codebridge DB 분리 후 깨진 FK 제약조건 제거
- refactor: [barobill] 바로빌 연동 코드 전면 개선
2026-03-12 15:20:20 +09:00

350 lines
10 KiB
PHP

<?php
namespace App\Services;
use App\Models\Commons\File;
use App\Models\FileShareLink;
use App\Models\Folder;
use App\Models\Tenants\Tenant;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
/**
* New file storage system service (Phase 2 implementation)
* Uses: files table, folders table, Storage Facade, tenant disk
*/
class FileStorageService extends Service
{
/**
* Generate 64-bit random filename
*/
public static function generateStoredName(string $extension): string
{
return bin2hex(random_bytes(32)).'.'.$extension;
}
/**
* Upload file to temp folder
*/
public function upload(UploadedFile $file, ?string $description = null): File
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
// Check storage quota
$tenant = Tenant::findOrFail($tenantId);
$quotaCheck = $tenant->canUpload($file->getSize());
if (! $quotaCheck['allowed']) {
throw new \Exception($quotaCheck['message']);
}
// Generate stored name
$extension = $file->getClientOriginalExtension();
$storedName = self::generateStoredName($extension);
// Build temp path: /tenants/{tenant_id}/temp/{year}/{month}/{stored_name}
$date = now();
$tempPath = sprintf(
'%d/temp/%s/%s/%s',
$tenantId,
$date->format('Y'),
$date->format('m'),
$storedName
);
// Store file to R2 (Cloudflare R2, S3 compatible)
Storage::disk('r2')->put($tempPath, file_get_contents($file->getRealPath()), [
'ContentType' => $file->getMimeType(),
]);
// Determine file type
$mimeType = $file->getMimeType();
$fileType = $this->determineFileType($mimeType);
// Create DB record (file_path = R2 key path)
$fileRecord = File::create([
'tenant_id' => $tenantId,
'display_name' => $file->getClientOriginalName(),
'stored_name' => $storedName,
'file_path' => $tempPath,
'file_size' => $file->getSize(),
'mime_type' => $mimeType,
'file_type' => $fileType,
'is_temp' => true,
'folder_id' => null,
'description' => $description,
'uploaded_by' => $userId,
'created_by' => $userId,
]);
// Increment tenant storage
$tenant->incrementStorage($file->getSize());
return $fileRecord;
}
/**
* Move files from temp to folder
*/
public function moveToFolder(array $fileIds, int $folderId, ?int $documentId = null, ?string $documentType = null): array
{
$tenantId = $this->tenantId();
$folder = Folder::where('tenant_id', $tenantId)->findOrFail($folderId);
$movedFiles = [];
DB::transaction(function () use ($fileIds, $folder, $documentId, $documentType, &$movedFiles) {
foreach ($fileIds as $fileId) {
$file = File::where('tenant_id', $this->tenantId())
->where('is_temp', true)
->findOrFail($fileId);
// Move file
$file->moveToFolder($folder);
// Update document reference
if ($documentId && $documentType) {
$file->update([
'document_id' => $documentId,
'document_type' => $documentType,
]);
}
$movedFiles[] = $file->fresh();
}
});
return $movedFiles;
}
/**
* Get file by ID
*/
public function getFile(int $fileId): File
{
return File::where('tenant_id', $this->tenantId())->findOrFail($fileId);
}
/**
* List files with filters
*/
public function listFiles(array $filters = []): \Illuminate\Pagination\LengthAwarePaginator
{
$query = File::where('tenant_id', $this->tenantId())
->with(['folder', 'uploader']);
// Filter by folder
if (isset($filters['folder_id'])) {
$query->where('folder_id', $filters['folder_id']);
}
// Filter by temp
if (isset($filters['is_temp'])) {
$query->where('is_temp', $filters['is_temp']);
}
// Filter by document
if (isset($filters['document_id']) && isset($filters['document_type'])) {
$query->forDocument($filters['document_id'], $filters['document_type']);
}
// Exclude soft deleted by default
if (! isset($filters['with_trashed']) || ! $filters['with_trashed']) {
$query->whereNull('deleted_at');
}
return $query->orderBy('created_at', 'desc')
->paginate($filters['per_page'] ?? 20);
}
/**
* Get trash files
*/
public function getTrash(): \Illuminate\Pagination\LengthAwarePaginator
{
return File::where('tenant_id', $this->tenantId())
->onlyTrashed() // SoftDeletes: deleted_at IS NOT NULL인 항목만
->with(['folder', 'uploader'])
->orderBy('deleted_at', 'desc')
->paginate(20);
}
/**
* Soft delete file
*/
public function deleteFile(int $fileId): File
{
$userId = $this->apiUserId();
$file = $this->getFile($fileId);
DB::transaction(function () use ($file, $userId) {
// Soft delete
$file->softDeleteFile($userId);
// Log deletion
DB::table('file_deletion_logs')->insert([
'tenant_id' => $file->tenant_id,
'file_id' => $file->id,
'file_name' => $file->display_name,
'file_path' => $file->file_path,
'file_size' => $file->file_size,
'folder_id' => $file->folder_id,
'document_id' => $file->document_id,
'document_type' => $file->document_type,
'deleted_by' => $userId,
'deleted_at' => now(),
'deletion_type' => 'soft',
]);
});
return $file->fresh();
}
/**
* Restore file from trash
*/
public function restoreFile(int $fileId): File
{
$file = File::where('tenant_id', $this->tenantId())
->onlyTrashed() // SoftDeletes: 삭제된 항목만 조회
->findOrFail($fileId);
$file->restore();
$file->update(['deleted_by' => null]);
return $file;
}
/**
* Permanently delete file
*/
public function permanentDelete(int $fileId): void
{
$file = File::where('tenant_id', $this->tenantId())
->onlyTrashed() // SoftDeletes: 삭제된 항목만 조회
->findOrFail($fileId);
DB::transaction(function () use ($file) {
// Update deletion log
DB::table('file_deletion_logs')
->where('file_id', $file->id)
->where('deletion_type', 'soft')
->update(['deletion_type' => 'permanent']);
// Permanently delete
$file->permanentDelete();
});
}
/**
* Create share link
*/
public function createShareLink(int $fileId, ?int $expiryHours = 24): FileShareLink
{
$file = $this->getFile($fileId);
$userId = $this->apiUserId();
return FileShareLink::create([
'file_id' => $file->id,
'tenant_id' => $file->tenant_id,
'expires_at' => now()->addHours($expiryHours),
'created_by' => $userId,
]);
}
/**
* Get file by share token (no tenant context required)
*/
public static function getFileByShareToken(string $token): File
{
$link = FileShareLink::where('token', $token)
->valid()
->firstOrFail();
// Increment download count
$link->incrementDownloadCount(request()->ip());
return $link->file;
}
/**
* Get storage usage
*/
public function getStorageUsage(): array
{
$tenant = Tenant::findOrFail($this->tenantId());
// Folder usage
$folderUsage = DB::table('files')
->where('tenant_id', $this->tenantId())
->whereNull('deleted_at')
->whereNotNull('folder_id')
->selectRaw('folder_id, COUNT(*) as file_count, SUM(file_size) as total_size')
->groupBy('folder_id')
->get()
->map(function ($item) {
$folder = Folder::find($item->folder_id);
return [
'folder_id' => $item->folder_id,
'folder_name' => $folder->folder_name ?? 'Unknown',
'file_count' => $item->file_count,
'total_size' => $item->total_size,
'formatted_size' => $this->formatBytes($item->total_size),
];
});
return [
'storage_used' => $tenant->storage_used,
'storage_limit' => $tenant->storage_limit,
'storage_used_formatted' => $tenant->getStorageUsedFormatted(),
'storage_limit_formatted' => $tenant->getStorageLimitFormatted(),
'usage_percentage' => $tenant->getStorageUsagePercentage(),
'is_near_limit' => $tenant->isStorageNearLimit(),
'is_exceeded' => $tenant->isStorageExceeded(),
'grace_period_until' => $tenant->storage_grace_period_until,
'folder_usage' => $folderUsage,
];
}
/**
* Determine file type from MIME type
*/
private function determineFileType(string $mimeType): string
{
if (str_starts_with($mimeType, 'image/')) {
return 'image';
}
if (in_array($mimeType, [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'text/csv',
])) {
return 'excel';
}
if (in_array($mimeType, ['application/zip', 'application/x-rar-compressed'])) {
return 'archive';
}
return 'document';
}
/**
* Format bytes to human-readable
*/
private function formatBytes(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, 2).' '.$units[$pow];
}
}