Files
superport/lib/data/repositories/zipcode_repository.dart
JiWoong Sul df7dd8dacb
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
feat: 대규모 코드베이스 개선 - 백엔드 통합성 강화 및 UI 일관성 완성
- CLAUDE.md 대폭 개선: 개발 가이드라인 및 프로젝트 상태 문서화
- 백엔드 API 통합: 모든 엔티티 간 Foreign Key 관계 완벽 구현
- UI 일관성 강화: shadcn_ui 컴포넌트 표준화 적용
- 데이터 모델 개선: DTO 및 모델 클래스 백엔드 스키마와 100% 일치
- 사용자 관리: 회사 연결, 중복 검사, 입력 검증 기능 추가
- 창고 관리: 우편번호 연결, 중복 검사 기능 강화
- 회사 관리: 우편번호 연결, 중복 검사 로직 구현
- 장비 관리: 불필요한 카테고리 필드 제거, 벤더-모델 관계 정리
- 우편번호 시스템: 검색 다이얼로그 Provider 버그 수정

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-31 15:49:05 +09:00

206 lines
6.2 KiB
Dart

import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:superport/core/constants/api_endpoints.dart';
import 'package:superport/data/datasources/remote/api_client.dart';
import 'package:superport/data/models/zipcode_dto.dart';
abstract class ZipcodeRepository {
/// 우편번호 검색 (페이지네이션 지원)
Future<ZipcodeListResponse> search({
int page = 1,
int limit = 20,
String? search,
String? sido,
String? gu,
});
/// 우편번호로 정확한 주소 조회
Future<ZipcodeDto?> getByZipcode(int zipcode);
/// 시도별 구 목록 조회
Future<List<String>> getGuBySido(String sido);
/// 전체 시도 목록 조회
Future<List<String>> getAllSido();
}
@Injectable(as: ZipcodeRepository)
class ZipcodeRepositoryImpl implements ZipcodeRepository {
final ApiClient _apiClient;
ZipcodeRepositoryImpl(this._apiClient);
@override
Future<ZipcodeListResponse> search({
int page = 1,
int limit = 20,
String? search,
String? sido,
String? gu,
}) async {
try {
final queryParams = <String, dynamic>{
'page': page,
'limit': limit,
};
if (search != null && search.isNotEmpty) {
queryParams['search'] = search;
}
if (sido != null && sido.isNotEmpty) {
queryParams['sido'] = sido;
}
if (gu != null && gu.isNotEmpty) {
queryParams['gu'] = gu;
}
final response = await _apiClient.dio.get(
ApiEndpoints.zipcodes,
queryParameters: queryParams,
);
// API 응답 구조에 따라 파싱
if (response.data is Map<String, dynamic>) {
// 페이지네이션 응답 형식
return ZipcodeListResponse.fromJson(response.data);
} else if (response.data is List) {
// 배열 직접 반환 형식
final zipcodes = (response.data as List)
.map((json) => ZipcodeDto.fromJson(json))
.toList();
return ZipcodeListResponse(
items: zipcodes,
totalCount: zipcodes.length,
currentPage: page,
totalPages: 1,
);
} else {
throw Exception('예상치 못한 응답 형식입니다.');
}
} on DioException catch (e) {
throw _handleError(e);
}
}
@override
Future<ZipcodeDto?> getByZipcode(int zipcode) async {
try {
final response = await _apiClient.dio.get(
ApiEndpoints.zipcodes,
queryParameters: {
'zipcode': zipcode,
'limit': 1,
},
);
if (response.data is Map<String, dynamic>) {
final listResponse = ZipcodeListResponse.fromJson(response.data);
return listResponse.items.isNotEmpty ? listResponse.items.first : null;
}
return null;
} on DioException catch (e) {
throw _handleError(e);
}
}
@override
Future<List<String>> getGuBySido(String sido) async {
try {
final response = await _apiClient.dio.get(
ApiEndpoints.zipcodes,
queryParameters: {
'page': 1,
'sido': sido,
'limit': 1000, // 충분히 큰 값으로 모든 구 가져오기
},
);
if (response.data is Map<String, dynamic>) {
final listResponse = ZipcodeListResponse.fromJson(response.data);
// 중복 제거하고 구 목록만 추출
final guSet = <String>{};
for (final zipcode in listResponse.items) {
guSet.add(zipcode.gu);
}
final guList = guSet.toList()..sort();
return guList;
}
return [];
} on DioException catch (e) {
throw _handleError(e);
}
}
@override
Future<List<String>> getAllSido() async {
try {
final response = await _apiClient.dio.get(
ApiEndpoints.zipcodes,
queryParameters: {
'page': 1,
'limit': 1000, // 충분히 큰 값으로 모든 시도 가져오기
},
);
print('=== getAllSido API 응답 ===');
print('Status Code: ${response.statusCode}');
print('Response Type: ${response.data.runtimeType}');
if (response.data is Map<String, dynamic>) {
print('Response Data Keys: ${(response.data as Map).keys.toList()}');
final listResponse = ZipcodeListResponse.fromJson(response.data);
print('총 우편번호 데이터 개수: ${listResponse.items.length}');
print('전체 카운트: ${listResponse.totalCount}');
print('현재 페이지: ${listResponse.currentPage}');
print('총 페이지: ${listResponse.totalPages}');
// 첫 3개 아이템 출력
if (listResponse.items.isNotEmpty) {
print('첫 3개 우편번호 데이터:');
for (int i = 0; i < 3 && i < listResponse.items.length; i++) {
final item = listResponse.items[i];
print(' [$i] 우편번호: ${item.zipcode}, 시도: "${item.sido}", 구: "${item.gu}", 기타: "${item.etc}"');
}
}
// 중복 제거하고 시도 목록만 추출
final sidoSet = <String>{};
for (final zipcode in listResponse.items) {
sidoSet.add(zipcode.sido);
}
final sidoList = sidoSet.toList()..sort();
print('추출된 시도 목록: $sidoList');
print('시도 개수: ${sidoList.length}');
return sidoList;
}
print('예상치 못한 응답 형식');
return [];
} on DioException catch (e) {
print('getAllSido API 오류: ${e.message}');
throw _handleError(e);
}
}
Exception _handleError(DioException e) {
switch (e.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
return Exception('연결 시간이 초과되었습니다.');
case DioExceptionType.badResponse:
final statusCode = e.response?.statusCode;
final message = e.response?.data?['message'] ?? '서버 오류가 발생했습니다.';
return Exception('[$statusCode] $message');
case DioExceptionType.connectionError:
return Exception('네트워크 연결을 확인해주세요.');
default:
return Exception('알 수 없는 오류가 발생했습니다.');
}
}
}