Files
superport/lib/data/datasources/remote/warehouse_location_remote_datasource.dart
JiWoong Sul 731dcd816b
Some checks failed
Flutter Test & Quality Check / Test on macos-latest (push) Has been cancelled
Flutter Test & Quality Check / Test on ubuntu-latest (push) Has been cancelled
Flutter Test & Quality Check / Build APK (push) Has been cancelled
refactor: Repository 패턴 적용 및 Clean Architecture 완성
## 주요 변경사항

### 🏗️ Architecture
- Repository 패턴 전면 도입 (인터페이스/구현체 분리)
- Domain Layer에 Repository 인터페이스 정의
- Data Layer에 Repository 구현체 배치
- UseCase 의존성을 Service에서 Repository로 전환

### 📦 Dependency Injection
- GetIt 기반 DI Container 재구성 (lib/injection_container.dart)
- Repository 인터페이스와 구현체 등록
- Service와 Repository 공존 (마이그레이션 기간)

### 🔄 Migration Status
완료:
- License 모듈 (6개 UseCase)
- Warehouse Location 모듈 (5개 UseCase)

진행중:
- Auth 모듈 (2/5 UseCase)
- Company 모듈 (1/6 UseCase)

대기:
- User 모듈 (7개 UseCase)
- Equipment 모듈 (4개 UseCase)

### 🎯 Controller 통합
- 중복 Controller 제거 (with_usecase 버전)
- 단일 Controller로 통합
- UseCase 패턴 직접 적용

### 🧹 코드 정리
- 임시 파일 제거 (test_*.md, task.md)
- Node.js 아티팩트 제거 (package.json)
- 불필요한 테스트 파일 정리

###  테스트 개선
- Real API 중심 테스트 구조
- Mock 제거, 실제 API 엔드포인트 사용
- 통합 테스트 프레임워크 강화

## 기술적 영향
- 의존성 역전 원칙 적용
- 레이어 간 결합도 감소
- 테스트 용이성 향상
- 확장성 및 유지보수성 개선

## 다음 단계
1. User/Equipment 모듈 Repository 마이그레이션
2. Service Layer 점진적 제거
3. 캐싱 전략 구현
4. 성능 최적화
2025-08-11 20:14:10 +09:00

332 lines
11 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/core/constants/api_endpoints.dart';
import 'package:superport/core/errors/exceptions.dart';
import 'package:superport/data/datasources/remote/api_client.dart';
import 'package:superport/data/models/warehouse/warehouse_dto.dart';
abstract class WarehouseLocationRemoteDataSource {
Future<WarehouseLocationListDto> getWarehouseLocations({
int page = 1,
int perPage = 20,
String? search,
Map<String, dynamic>? filters,
});
Future<WarehouseLocationDto> getWarehouseLocationDetail(int id);
Future<WarehouseLocationDto> createWarehouseLocation(CreateWarehouseLocationRequest request);
Future<WarehouseLocationDto> updateWarehouseLocation(int id, UpdateWarehouseLocationRequest request);
Future<void> deleteWarehouseLocation(int id);
Future<WarehouseCapacityInfo> getWarehouseCapacity(int id);
Future<WarehouseEquipmentListDto> getWarehouseEquipment({
required int warehouseId,
int page = 1,
int perPage = 20,
});
// Repository에서 사용하는 추가 메서드들
Future<void> updateWarehouseLocationStatus(int id, bool isActive);
Future<bool> checkWarehouseHasEquipment(int id);
Future<bool> checkDuplicateWarehouseName(String name);
}
@LazySingleton(as: WarehouseLocationRemoteDataSource)
class WarehouseLocationRemoteDataSourceImpl implements WarehouseLocationRemoteDataSource {
final ApiClient _apiClient;
WarehouseLocationRemoteDataSourceImpl({
required ApiClient apiClient,
}) : _apiClient = apiClient;
@override
Future<WarehouseLocationListDto> getWarehouseLocations({
int page = 1,
int perPage = 20,
String? search,
Map<String, dynamic>? filters,
}) async {
try {
final queryParams = <String, dynamic>{
'page': page,
'per_page': perPage,
};
if (search != null && search.isNotEmpty) {
queryParams['search'] = search;
}
// 필터 적용
if (filters != null) {
filters.forEach((key, value) {
if (value != null) {
queryParams[key] = value;
}
});
}
final response = await _apiClient.get(
ApiEndpoints.warehouseLocations,
queryParameters: queryParams,
);
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
// API 응답이 배열인 경우와 객체인 경우를 모두 처리
final data = response.data['data'];
if (data is List) {
// 배열 응답을 WarehouseLocationListDto 형식으로 변환
final List<WarehouseLocationDto> warehouses = [];
for (int i = 0; i < data.length; i++) {
try {
final item = data[i];
debugPrint('📦 Parsing warehouse location item $i: ${item['name']}');
// null 검사 및 기본값 설정
final warehouseDto = WarehouseLocationDto.fromJson({
...item,
// 필수 필드 보장
'name': item['name'] ?? '',
'is_active': item['is_active'] ?? true,
'created_at': item['created_at'] ?? DateTime.now().toIso8601String(),
});
warehouses.add(warehouseDto);
} catch (e, stackTrace) {
debugPrint('❌ Error parsing warehouse location item $i: $e');
debugPrint('Item data: ${data[i]}');
debugPrint('Stack trace: $stackTrace');
// 파싱 실패한 항목은 건너뛰고 계속
continue;
}
}
final pagination = response.data['pagination'] ?? {};
return WarehouseLocationListDto(
items: warehouses,
total: pagination['total'] ?? warehouses.length,
page: pagination['page'] ?? page,
perPage: pagination['per_page'] ?? perPage,
totalPages: pagination['total_pages'] ?? 1,
);
} else if (data['items'] != null) {
// 이미 WarehouseLocationListDto 형식인 경우
return WarehouseLocationListDto.fromJson(data);
} else {
// 예상치 못한 형식인 경우
throw ApiException(
message: 'Unexpected response format for warehouse location list',
);
}
} else {
throw ApiException(
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse locations',
);
}
} catch (e) {
throw _handleError(e);
}
}
@override
Future<WarehouseLocationDto> getWarehouseLocationDetail(int id) async {
try {
final response = await _apiClient.get(
'${ApiEndpoints.warehouseLocations}/$id',
);
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
return WarehouseLocationDto.fromJson(response.data['data']);
} else {
throw ApiException(
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse location',
);
}
} catch (e) {
throw _handleError(e);
}
}
@override
Future<WarehouseLocationDto> createWarehouseLocation(CreateWarehouseLocationRequest request) async {
try {
final response = await _apiClient.post(
ApiEndpoints.warehouseLocations,
data: request.toJson(),
);
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
return WarehouseLocationDto.fromJson(response.data['data']);
} else {
throw ApiException(
message: response.data?['error']?['message'] ?? 'Failed to create warehouse location',
);
}
} catch (e) {
throw _handleError(e);
}
}
@override
Future<WarehouseLocationDto> updateWarehouseLocation(int id, UpdateWarehouseLocationRequest request) async {
try {
final response = await _apiClient.put(
'${ApiEndpoints.warehouseLocations}/$id',
data: request.toJson(),
);
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
return WarehouseLocationDto.fromJson(response.data['data']);
} else {
throw ApiException(
message: response.data?['error']?['message'] ?? 'Failed to update warehouse location',
);
}
} catch (e) {
throw _handleError(e);
}
}
@override
Future<void> deleteWarehouseLocation(int id) async {
try {
await _apiClient.delete(
'${ApiEndpoints.warehouseLocations}/$id',
);
} catch (e) {
throw _handleError(e);
}
}
@override
Future<WarehouseCapacityInfo> getWarehouseCapacity(int id) async {
try {
final response = await _apiClient.get(
'${ApiEndpoints.warehouseLocations}/$id/capacity',
);
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
return WarehouseCapacityInfo.fromJson(response.data['data']);
} else {
throw ApiException(
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse capacity',
);
}
} catch (e) {
throw _handleError(e);
}
}
@override
Future<WarehouseEquipmentListDto> getWarehouseEquipment({
required int warehouseId,
int page = 1,
int perPage = 20,
}) async {
try {
final queryParams = <String, dynamic>{
'page': page,
'per_page': perPage,
};
final response = await _apiClient.get(
'${ApiEndpoints.warehouseLocations}/$warehouseId/equipment',
queryParameters: queryParams,
);
if (response.data != null && response.data['success'] == true && response.data['data'] != null) {
final data = response.data['data'];
final pagination = response.data['pagination'] ?? {};
if (data is List) {
// 배열 응답을 WarehouseEquipmentListDto 형식으로 변환
final List<WarehouseEquipmentDto> equipment = [];
for (var item in data) {
try {
equipment.add(WarehouseEquipmentDto.fromJson(item));
} catch (e) {
debugPrint('❌ Error parsing warehouse equipment: $e');
debugPrint('Item data: $item');
continue;
}
}
return WarehouseEquipmentListDto(
items: equipment,
total: pagination['total'] ?? equipment.length,
page: pagination['page'] ?? page,
perPage: pagination['per_page'] ?? perPage,
totalPages: pagination['total_pages'] ?? 1,
);
} else {
// 이미 올바른 형식인 경우
return WarehouseEquipmentListDto.fromJson(data);
}
} else {
throw ApiException(
message: response.data?['error']?['message'] ?? 'Failed to fetch warehouse equipment',
);
}
} catch (e) {
throw _handleError(e);
}
}
// Repository에서 사용하는 추가 메서드들 구현
@override
Future<void> updateWarehouseLocationStatus(int id, bool isActive) async {
try {
await _apiClient.patch(
'${ApiEndpoints.warehouseLocations}/$id/status',
data: {'is_active': isActive},
);
} catch (e) {
throw _handleError(e);
}
}
@override
Future<bool> checkWarehouseHasEquipment(int id) async {
try {
final response = await _apiClient.get(
'${ApiEndpoints.warehouseLocations}/$id/has-equipment',
);
if (response.data != null && response.data['success'] == true) {
return response.data['data']['has_equipment'] ?? false;
}
return false;
} catch (e) {
// 오류 시 기본값 false 반환
debugPrint('📦 창고 장비 보유 여부 확인 중 오류: $e');
return false;
}
}
@override
Future<bool> checkDuplicateWarehouseName(String name) async {
try {
final response = await _apiClient.get(
'${ApiEndpoints.warehouseLocations}/check-duplicate',
queryParameters: {'name': name},
);
if (response.data != null && response.data['success'] == true) {
return response.data['data']['is_duplicate'] ?? false;
}
return false;
} catch (e) {
// 오류 시 기본값 false 반환 (중복이 아니라고 가정)
debugPrint('📦 중복 창고명 확인 중 오류: $e');
return false;
}
}
Exception _handleError(dynamic error) {
if (error is ApiException) {
return error;
}
return ApiException(
message: error.toString(),
);
}
}