feat: 파일 저장 시스템 DB 마이그레이션
- enhance_files_table: 이중 파일명 시스템 (display_name/stored_name), 폴더 관리, 문서 연결 지원
- create_folders_table: 동적 폴더 관리 시스템 (tenant별 커스터마이징 가능)
- 5개 stub 마이그레이션 생성 (file_share_links, file_deletion_logs, storage_usage_history, add_storage_columns_to_tenants)
- FolderSeeder stub 생성
- CURRENT_WORKS.md에 Phase 1 진행상황 문서화
fix: 파일 공유 및 삭제 기능 버그 수정
- ShareLinkRequest: PATH 파라미터 {id}를 file_id로 자동 병합
- routes/api.php: 공유 링크 다운로드를 auth.apikey 그룹 밖으로 이동 (인증 불필요)
- FileShareLink: File, Tenant 클래스 import 추가
- File 모델: softDeleteFile()에서 SoftDeletes의 delete() 메서드 사용
- FileStorageService: getTrash(), restoreFile(), permanentDelete()에서 onlyTrashed() 사용
- File 모델: Tenant 네임스페이스 수정 (App\Models\Tenants\Tenant)
refactor: Swagger 문서 정리 - File 태그를 Files로 통합
- FileApi.php의 모든 태그를 Files로 변경
- 구 파일 시스템 라우트 삭제 (prefix 'file')
- 구 FileController.php 삭제
- 신규 파일 저장소 시스템으로 완전 통합
fix: 모든 legacy 파일 컬럼 nullable 일괄 처리
- 5개 legacy 컬럼을 한 번에 nullable로 변경
* original_name, file_name, file_name_old (string)
* fileable_id, fileable_type (polymorphic)
- foreach 루프로 반복 작업 자동화
- 신규/기존 시스템 간 완전한 하위 호환성 확보
fix: legacy 파일 컬럼 nullable 처리 완료
- file_name, file_name_old 컬럼도 nullable로 변경
- 기존 시스템과 신규 시스템 간 완전한 하위 호환성 확보
- Legacy: original_name, file_name, file_name_old (nullable)
- New: display_name, stored_name (required)
fix: original_name 컬럼 nullable 처리
- original_name을 nullable로 변경하여 하위 호환성 유지
- 새 시스템에서는 display_name 사용, 기존 시스템은 original_name 사용 가능
fix: 파일 업로드 DB 컬럼 누락 및 메시지 구조 개선
- files 테이블에 감사 컬럼 추가 (created_by, updated_by, uploaded_by)
- ApiResponse::handle() 메시지 로직 개선 (접미사 제거)
- 다국어 지원을 위한 완성된 문장 구조 유지
- FileUploadRequest 파일 검증 규칙 수정
fix: 파일 저장소 버그 수정 및 신규 테넌트 폴더 자동 생성
- FolderSeeder 네임스페이스 수정 (App\Models\Tenant → App\Models\Tenants\Tenant)
- FileStorageController use 문 구문 오류 수정 (/ → \)
- TenantObserver에 신규 테넌트 기본 폴더 자동 생성 로직 추가
- 5개 기본 폴더 (생산관리, 품질관리, 회계, 인사, 일반)
- 에러 처리 및 로깅
- 회원가입 시 자동 실행
This commit is contained in:
@@ -2,15 +2,23 @@
|
||||
|
||||
namespace App\Models\Commons;
|
||||
|
||||
use App\Models\FileShareLink;
|
||||
use App\Models\Folder;
|
||||
use App\Models\Members\User;
|
||||
use App\Models\Tenants\Tenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* @mixin IdeHelperFile
|
||||
*/
|
||||
class File extends Model
|
||||
{
|
||||
use \App\Traits\BelongsToTenant;
|
||||
use \App\Traits\ModelTrait;
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'files';
|
||||
@@ -18,19 +26,71 @@ class File extends Model
|
||||
protected $fillable = [
|
||||
'tenant_id',
|
||||
'file_path',
|
||||
// Old fields (legacy support)
|
||||
'original_name',
|
||||
'file_name',
|
||||
'file_name_old',
|
||||
'fileable_id',
|
||||
'fileable_type',
|
||||
// New fields
|
||||
'display_name',
|
||||
'stored_name',
|
||||
'folder_id',
|
||||
'is_temp',
|
||||
'file_type',
|
||||
'document_id',
|
||||
'document_type',
|
||||
'file_size',
|
||||
'mime_type',
|
||||
'description',
|
||||
'fileable_id',
|
||||
'fileable_type',
|
||||
'uploaded_by',
|
||||
'deleted_by',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_temp' => 'boolean',
|
||||
'file_size' => 'integer',
|
||||
'deleted_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* 연관된 모델 (Polymorphic)
|
||||
* Get the tenant that owns the file
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the folder that contains this file
|
||||
*/
|
||||
public function folder(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Folder::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all share links for this file
|
||||
*/
|
||||
public function shareLinks(): HasMany
|
||||
{
|
||||
return $this->hasMany(FileShareLink::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the uploader (User)
|
||||
*/
|
||||
public function uploader(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'uploaded_by');
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy: 연관된 모델 (Polymorphic) - for backward compatibility
|
||||
*
|
||||
* @deprecated Use document_id and document_type instead
|
||||
*/
|
||||
public function fileable()
|
||||
{
|
||||
@@ -38,10 +98,134 @@ public function fileable()
|
||||
}
|
||||
|
||||
/**
|
||||
* 업로더 (User 등)
|
||||
* Get the full storage path
|
||||
*/
|
||||
public function uploader()
|
||||
public function getStoragePath(): string
|
||||
{
|
||||
return $this->belongsTo(User::class, 'uploaded_by');
|
||||
return Storage::disk('tenant')->path($this->file_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file exists in storage
|
||||
*/
|
||||
public function exists(): bool
|
||||
{
|
||||
return Storage::disk('tenant')->exists($this->file_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get download response
|
||||
*/
|
||||
public function download()
|
||||
{
|
||||
if (! $this->exists()) {
|
||||
abort(404, 'File not found in storage');
|
||||
}
|
||||
|
||||
return response()->download(
|
||||
$this->getStoragePath(),
|
||||
$this->display_name ?? $this->original_name
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move file from temp to folder
|
||||
*/
|
||||
public function moveToFolder(Folder $folder): bool
|
||||
{
|
||||
if (! $this->is_temp) {
|
||||
return false; // Already moved
|
||||
}
|
||||
|
||||
// New path: /tenants/{tenant_id}/{folder_key}/{year}/{month}/{stored_name}
|
||||
$date = now();
|
||||
$newPath = sprintf(
|
||||
'%d/%s/%s/%s/%s',
|
||||
$this->tenant_id,
|
||||
$folder->folder_key,
|
||||
$date->format('Y'),
|
||||
$date->format('m'),
|
||||
$this->stored_name ?? $this->file_name
|
||||
);
|
||||
|
||||
// Move physical file
|
||||
if (Storage::disk('tenant')->exists($this->file_path)) {
|
||||
Storage::disk('tenant')->move($this->file_path, $newPath);
|
||||
}
|
||||
|
||||
// Update DB
|
||||
$this->update([
|
||||
'file_path' => $newPath,
|
||||
'folder_id' => $folder->id,
|
||||
'is_temp' => false,
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete file (soft delete)
|
||||
*/
|
||||
public function softDeleteFile(int $userId): void
|
||||
{
|
||||
// Set deleted_by before soft delete
|
||||
$this->deleted_by = $userId;
|
||||
$this->save();
|
||||
|
||||
// Use SoftDeletes trait's delete() method
|
||||
$this->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Permanently delete file
|
||||
*/
|
||||
public function permanentDelete(): void
|
||||
{
|
||||
// Delete physical file
|
||||
if ($this->exists()) {
|
||||
Storage::disk('tenant')->delete($this->file_path);
|
||||
}
|
||||
|
||||
// Decrement tenant storage
|
||||
$tenant = Tenant::find($this->tenant_id);
|
||||
if ($tenant) {
|
||||
$tenant->decrement('storage_used', $this->file_size);
|
||||
}
|
||||
|
||||
// Force delete from DB
|
||||
$this->forceDelete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Temp files only
|
||||
*/
|
||||
public function scopeTemp($query)
|
||||
{
|
||||
return $query->where('is_temp', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Non-temp files only
|
||||
*/
|
||||
public function scopeNonTemp($query)
|
||||
{
|
||||
return $query->where('is_temp', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: By folder
|
||||
*/
|
||||
public function scopeInFolder($query, $folderId)
|
||||
{
|
||||
return $query->where('folder_id', $folderId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: By document
|
||||
*/
|
||||
public function scopeForDocument($query, int $documentId, string $documentType)
|
||||
{
|
||||
return $query->where('document_id', $documentId)
|
||||
->where('document_type', $documentType);
|
||||
}
|
||||
}
|
||||
|
||||
122
app/Models/FileShareLink.php
Normal file
122
app/Models/FileShareLink.php
Normal file
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Commons\File;
|
||||
use App\Models\Tenants\Tenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class FileShareLink extends Model
|
||||
{
|
||||
use \App\Traits\BelongsToTenant;
|
||||
|
||||
public $timestamps = false; // created_at만 사용
|
||||
|
||||
protected $fillable = [
|
||||
'file_id',
|
||||
'tenant_id',
|
||||
'token',
|
||||
'expires_at',
|
||||
'download_count',
|
||||
'max_downloads',
|
||||
'last_downloaded_at',
|
||||
'last_downloaded_ip',
|
||||
'created_by',
|
||||
'created_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'expires_at' => 'datetime',
|
||||
'last_downloaded_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'download_count' => 'integer',
|
||||
'max_downloads' => 'integer',
|
||||
];
|
||||
|
||||
/**
|
||||
* Boot method: Auto-generate token
|
||||
*/
|
||||
protected static function boot()
|
||||
{
|
||||
parent::boot();
|
||||
|
||||
static::creating(function ($model) {
|
||||
if (empty($model->token)) {
|
||||
$model->token = self::generateToken();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a unique 64-character token
|
||||
*/
|
||||
public static function generateToken(): string
|
||||
{
|
||||
return bin2hex(random_bytes(32)); // 64 chars
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file associated with this share link
|
||||
*/
|
||||
public function file(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(File::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tenant that owns the share link
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the link is expired
|
||||
*/
|
||||
public function isExpired(): bool
|
||||
{
|
||||
return $this->expires_at && $this->expires_at->isPast();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if download limit reached
|
||||
*/
|
||||
public function isDownloadLimitReached(): bool
|
||||
{
|
||||
return $this->max_downloads && $this->download_count >= $this->max_downloads;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the link is still valid
|
||||
*/
|
||||
public function isValid(): bool
|
||||
{
|
||||
return ! $this->isExpired() && ! $this->isDownloadLimitReached();
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment download count
|
||||
*/
|
||||
public function incrementDownloadCount(string $ip): void
|
||||
{
|
||||
$this->increment('download_count');
|
||||
$this->update([
|
||||
'last_downloaded_at' => now(),
|
||||
'last_downloaded_ip' => $ip,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Non-expired links
|
||||
*/
|
||||
public function scopeValid($query)
|
||||
{
|
||||
return $query->where('expires_at', '>', now())
|
||||
->where(function ($q) {
|
||||
$q->whereNull('max_downloads')
|
||||
->orWhereRaw('download_count < max_downloads');
|
||||
});
|
||||
}
|
||||
}
|
||||
63
app/Models/Folder.php
Normal file
63
app/Models/Folder.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Folder extends Model
|
||||
{
|
||||
use \App\Traits\BelongsToTenant;
|
||||
use \App\Traits\ModelTrait;
|
||||
|
||||
protected $fillable = [
|
||||
'tenant_id',
|
||||
'folder_key',
|
||||
'folder_name',
|
||||
'description',
|
||||
'display_order',
|
||||
'is_active',
|
||||
'icon',
|
||||
'color',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
'display_order' => 'integer',
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the tenant that owns the folder
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all files in this folder
|
||||
*/
|
||||
public function files(): HasMany
|
||||
{
|
||||
return $this->hasMany(File::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Active folders only
|
||||
*/
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope: Ordered by display_order
|
||||
*/
|
||||
public function scopeOrdered($query)
|
||||
{
|
||||
return $query->orderBy('display_order');
|
||||
}
|
||||
}
|
||||
@@ -119,4 +119,129 @@ public function files()
|
||||
{
|
||||
return $this->morphMany(File::class, 'fileable');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get storage usage percentage
|
||||
*/
|
||||
public function getStorageUsagePercentage(): float
|
||||
{
|
||||
if (! $this->storage_limit || $this->storage_limit == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return ($this->storage_used / $this->storage_limit) * 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if storage is near limit (90%)
|
||||
*/
|
||||
public function isStorageNearLimit(): bool
|
||||
{
|
||||
return $this->getStorageUsagePercentage() >= 90;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if storage quota exceeded
|
||||
*/
|
||||
public function isStorageExceeded(): bool
|
||||
{
|
||||
return $this->storage_used > $this->storage_limit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if in grace period
|
||||
*/
|
||||
public function isInGracePeriod(): bool
|
||||
{
|
||||
return $this->storage_grace_period_until && now()->lessThan($this->storage_grace_period_until);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if upload is allowed
|
||||
*/
|
||||
public function canUpload(int $fileSize = 0): array
|
||||
{
|
||||
$newUsage = $this->storage_used + $fileSize;
|
||||
|
||||
// Check if exceeds limit
|
||||
if ($newUsage > $this->storage_limit) {
|
||||
// Check grace period
|
||||
if ($this->isInGracePeriod()) {
|
||||
return [
|
||||
'allowed' => true,
|
||||
'warning' => true,
|
||||
'message' => __('file.storage_exceeded_grace_period', [
|
||||
'until' => $this->storage_grace_period_until->format('Y-m-d'),
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
// Grace period expired - block upload
|
||||
return [
|
||||
'allowed' => false,
|
||||
'message' => __('file.storage_quota_exceeded'),
|
||||
];
|
||||
}
|
||||
|
||||
// Check if near limit (90%)
|
||||
$percentage = ($newUsage / $this->storage_limit) * 100;
|
||||
if ($percentage >= 90 && ! $this->storage_warning_sent_at) {
|
||||
// Send warning (once)
|
||||
$this->update([
|
||||
'storage_warning_sent_at' => now(),
|
||||
'storage_grace_period_until' => now()->addDays(7),
|
||||
]);
|
||||
|
||||
// TODO: Dispatch email notification
|
||||
// dispatch(new SendStorageWarningEmail($this));
|
||||
}
|
||||
|
||||
return ['allowed' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Increment storage usage
|
||||
*/
|
||||
public function incrementStorage(int $bytes): void
|
||||
{
|
||||
$this->increment('storage_used', $bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrement storage usage
|
||||
*/
|
||||
public function decrementStorage(int $bytes): void
|
||||
{
|
||||
$this->decrement('storage_used', max(0, $bytes));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get human-readable storage used
|
||||
*/
|
||||
public function getStorageUsedFormatted(): string
|
||||
{
|
||||
return $this->formatBytes($this->storage_used);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get human-readable storage limit
|
||||
*/
|
||||
public function getStorageLimitFormatted(): string
|
||||
{
|
||||
return $this->formatBytes($this->storage_limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format bytes to human-readable string
|
||||
*/
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user