Skip to content

Commit

Permalink
residents logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Kouhakouu committed Dec 23, 2024
1 parent 9a72c1c commit 9da9b48
Show file tree
Hide file tree
Showing 2 changed files with 295 additions and 32 deletions.
110 changes: 97 additions & 13 deletions lib/features/admin/data/admin_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ class AdminRepository {
throw Exception('Không lấy được UID của người dùng.');
}

// Chuẩn bị dữ liệu cho collection đích
// Chuẩn bị dữ liệu cho collection đích và thêm profileId
if (role == 'Cư dân') {
targetData = {
'fullName': queueData['fullName']['stringValue'],
Expand All @@ -115,6 +115,7 @@ class AdminRepository {
'apartmentNumber': int.parse(queueData['apartmentNumber']['integerValue']),
'email': email,
'status': 'Đã duyệt',
'profileId': uid, // Thêm profileId
};
} else if (role == 'Khách') {
targetData = {
Expand All @@ -126,6 +127,7 @@ class AdminRepository {
'email': email,
'jobTitle': queueData['jobTitle']['stringValue'],
'status': 'Đã duyệt',
'profileId': uid, // Thêm profileId
};
} else {
throw Exception('Vai trò không hợp lệ.');
Expand All @@ -146,6 +148,35 @@ class AdminRepository {
throw Exception('Phê duyệt thất bại khi tạo tài liệu trong $targetCollection.');
}

// Tạo profile document trong collection 'profiles' với documentId = profileId (uid)
Map<String, dynamic> profileData = {
'householdHead': _encodeField(''), // Initialize as empty string
'occupation': _encodeField(''), // Initialize as empty string
'emergencyContacts': _encodeField(<String>[]), // Empty array
'members': _encodeField(<Map<String, dynamic>>[]), // Empty array
'moveInDate': _encodeField(''), // Initialize as empty string
'moveOutDate': _encodeField(''), // Initialize as empty string
'vehicles': _encodeField(<Map<String, dynamic>>[]), // Empty array
'utilities': _encodeField(<String>[]), // Empty array
};

final profileUrl = 'https://firestore.googleapis.com/v1/projects/$projectId/databases/(default)/documents/profiles/$uid?key=$apiKey';

final profileResponse = await http.patch(
Uri.parse(profileUrl),
headers: {
'Authorization': 'Bearer $idToken',
'Content-Type': 'application/json',
},
body: jsonEncode({
'fields': profileData,
}),
);

if (profileResponse.statusCode != 200) {
throw Exception('Lỗi khi tạo profile: ${profileResponse.statusCode} ${profileResponse.body}');
}

// Xóa tài liệu từ 'queue'
bool deleteSuccess = await authService.deleteQueueDocument(queueDocName, idToken);
if (!deleteSuccess) {
Expand Down Expand Up @@ -200,6 +231,26 @@ class AdminRepository {
}
}

/// Fetches a profile document by profileId.
Future<Map<String, dynamic>> fetchProfile(String profileId, String idToken) async {
final url = 'https://firestore.googleapis.com/v1/projects/$projectId/databases/(default)/documents/profiles/$profileId?key=$apiKey';

final response = await http.get(
Uri.parse(url),
headers: {
'Authorization': 'Bearer $idToken',
'Content-Type': 'application/json',
},
);

if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return data['fields'] ?? {};
} else {
throw Exception('Lỗi khi lấy profile: ${response.statusCode} ${response.body}');
}
}

// Hàm cập nhật cư dân
Future<void> updateResident({
required String documentName, // Full path of the document
Expand Down Expand Up @@ -252,28 +303,61 @@ class AdminRepository {
}
}

// Hàm xóa cư dân
// Hàm xóa cư dân và profile tương ứng
Future<void> deleteResident({
required String documentName, // Full path of the document
required String documentName, // Full path of the resident document
required String idToken,
}) async {
// Construct the Firestore REST API URL for deleting the document
final url = 'https://firestore.googleapis.com/v1/$documentName?key=$apiKey';
// Step 1: Fetch the resident document to get profileId
final fetchUrl = 'https://firestore.googleapis.com/v1/$documentName?key=$apiKey';

// Send the DELETE request to Firestore
final response = await http.delete(
Uri.parse(url),
final fetchResponse = await http.get(
Uri.parse(fetchUrl),
headers: {
'Authorization': 'Bearer $idToken',
'Content-Type': 'application/json',
},
);

if (response.statusCode == 200 || response.statusCode == 204) {
// Deletion successful
return;
} else {
throw Exception('Lỗi khi xóa cư dân: ${response.statusCode} ${response.body}');
if (fetchResponse.statusCode != 200) {
throw Exception('Lỗi khi lấy thông tin cư dân để xóa: ${fetchResponse.statusCode} ${fetchResponse.body}');
}

final fetchData = jsonDecode(fetchResponse.body);
if (fetchData == null || !fetchData.containsKey('fields') || !fetchData['fields'].containsKey('profileId')) {
throw Exception('Không tìm thấy profileId trong tài liệu cư dân.');
}

String profileId = fetchData['fields']['profileId']['stringValue'];

// Step 2: Delete the profile document in 'profiles' collection
final deleteProfileUrl = 'https://firestore.googleapis.com/v1/projects/$projectId/databases/(default)/documents/profiles/$profileId?key=$apiKey';

final deleteProfileResponse = await http.delete(
Uri.parse(deleteProfileUrl),
headers: {
'Authorization': 'Bearer $idToken',
'Content-Type': 'application/json',
},
);

if (deleteProfileResponse.statusCode != 200 && deleteProfileResponse.statusCode != 204) {
throw Exception('Lỗi khi xóa profile: ${deleteProfileResponse.statusCode} ${deleteProfileResponse.body}');
}

// Step 3: Delete the resident document
final deleteResidentUrl = 'https://firestore.googleapis.com/v1/$documentName?key=$apiKey';

final deleteResidentResponse = await http.delete(
Uri.parse(deleteResidentUrl),
headers: {
'Authorization': 'Bearer $idToken',
'Content-Type': 'application/json',
},
);

if (deleteResidentResponse.statusCode != 200 && deleteResidentResponse.statusCode != 204) {
throw Exception('Lỗi khi xóa cư dân: ${deleteResidentResponse.statusCode} ${deleteResidentResponse.body}');
}
}

Expand Down
Loading

0 comments on commit 9da9b48

Please sign in to comment.