Skip to content

Commit

Permalink
fix: call real api and fix problems
Browse files Browse the repository at this point in the history
  • Loading branch information
cevheri committed Dec 30, 2024
1 parent b34aa82 commit 1ae4601
Show file tree
Hide file tree
Showing 20 changed files with 156 additions and 75 deletions.
66 changes: 66 additions & 0 deletions assets/mock/GET_admin_users_authorities_pathParams.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
[
{
"id": "user-1",
"login": "admin",
"email": "[email protected]",
"firstName": "Admin",
"lastName": "User",
"activated": true,
"langKey": "en",
"createdBy": "system",
"createdDate": "2024-01-04T06:02:47.757Z",
"lastModifiedBy": "admin",
"lastModifiedDate": "2024-01-04T06:02:47.757Z",
"authorities": [
"ROLE_ADMIN", "ROLE_USER"
]
},
{
"id": "user-2",
"login": "new_user-2",
"firstName": "Mock new user First Name",
"lastName": "Mock new user Last Name",
"email": "[email protected]",
"activated": true,
"langKey": null,
"createdBy": "system",
"createdDate": null,
"lastModifiedBy": "admin",
"lastModifiedDate": "2024-01-04T06:02:47.757Z",
"authorities": [
"ROLE_ADMIN"
]
},
{
"id": "user-3",
"login": "new_user-3",
"firstName": "Mock new user First Name",
"lastName": "Mock new user Last Name",
"email": "[email protected]",
"activated": true,
"langKey": null,
"createdBy": "system",
"createdDate": null,
"lastModifiedBy": "admin",
"lastModifiedDate": "2024-01-04T06:02:47.757Z",
"authorities": [
"ROLE_ADMIN"
]
},
{
"id": "user-4",
"login": "new_user-4",
"firstName": "Mock new user First Name",
"lastName": "Mock new user Last Name",
"email": "[email protected]",
"activated": true,
"langKey": null,
"createdBy": "system",
"createdDate": null,
"lastModifiedBy": "admin",
"lastModifiedDate": "2024-01-04T06:02:47.757Z",
"authorities": [
"ROLE_ADMIN"
]
}
]
17 changes: 14 additions & 3 deletions lib/data/http_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,19 @@ class HttpUtils {
final http.Response response;
final headers = await HttpUtils.headers();
try {
final url = Uri.parse('${ProfileConstants.api}$endpoint');
response = await client.get(url, headers: headers).timeout(_timeout);
final String path;
if (pathParams != null) {
path = '${ProfileConstants.api}$endpoint/$pathParams';
}else {
path = '${ProfileConstants.api}$endpoint';
}
final url = Uri.parse(path);

if (queryParams != null) {
response = await client.get(url.replace(queryParameters: queryParams), headers: headers).timeout(_timeout);
} else {
response = await client.get(url, headers: headers).timeout(_timeout);
}
checkUnauthorizedAccess(endpoint, response);
} on SocketException {
throw FetchDataException(noInternetConnectionError);
Expand Down Expand Up @@ -323,7 +334,7 @@ class HttpUtils {
// @formatter:on
final filePath = endpoint.replaceAll("/", "_").replaceAll("-", "_");
if (pathParams != null) {
path += "/$httpMethod${filePath}pathParams.json";
path += "/$httpMethod${filePath}_pathParams.json";
} else if (queryParams != null) {
path += "/$httpMethod${filePath}_queryParams.json";
} else {
Expand Down
4 changes: 2 additions & 2 deletions lib/data/repository/authority_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class AuthorityRepository {
throw BadRequestException("Authority id null");
}
final pathParams = id;
final httpResponse = await HttpUtils.getRequest("/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.getRequest("/$_resource", pathParams: pathParams);
final response = Authority.fromJsonString(httpResponse.body);
_log.debug("END:getAuthority successful - response.body: {}", [response.toString()]);
return response;
Expand All @@ -48,7 +48,7 @@ class AuthorityRepository {
throw BadRequestException("Authority id null");
}
final pathParams = id;
final httpResponse = await HttpUtils.deleteRequest("/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.deleteRequest("/$_resource", pathParams: pathParams);
_log.debug("END:deleteAuthority successful - response status code: {}", [httpResponse.statusCode]);
}
}
4 changes: 2 additions & 2 deletions lib/data/repository/city_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class CityRepository {
throw BadRequestException("City id null");
}
final pathParams = id;
final httpResponse = await HttpUtils.getRequest("/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.getRequest("/$_resource", pathParams: pathParams);
var response = City.fromJsonString(httpResponse.body);
_log.debug("END:getCity successful - response.body: {}", [response.toString()]);
return response;
Expand All @@ -49,7 +49,7 @@ class CityRepository {
throw BadRequestException("City id null");
}
final pathParams = id;
final httpResponse = await HttpUtils.deleteRequest("/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.deleteRequest("/$_resource", pathParams: pathParams);
_log.debug("END:deleteCity successful - response status code: {}", [httpResponse.statusCode]);
}
}
6 changes: 3 additions & 3 deletions lib/data/repository/district_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class DistrictRepository {
throw BadRequestException("City id null");
}
final pathParams = cityId;
final httpResponse = await HttpUtils.getRequest("/$_resource/cities/", pathParams: pathParams);
final httpResponse = await HttpUtils.getRequest("/$_resource/cities", pathParams: pathParams);
final response = District.fromJsonStringList(httpResponse.body);
_log.debug("END:getDistrictsByCity successful - response list size: {}", [response.length]);
return response;
Expand Down Expand Up @@ -50,7 +50,7 @@ class DistrictRepository {
throw BadRequestException("District id null");
}
final pathParams = id;
final httpResponse = await HttpUtils.getRequest("/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.getRequest("/$_resource", pathParams: pathParams);
final response = District.fromJsonString(httpResponse.body);
_log.debug("END:getDistrict successful - response.body: {}", [response.toString()]);
return response;
Expand All @@ -62,7 +62,7 @@ class DistrictRepository {
throw BadRequestException("District id null");
}
final pathParams = id;
var httpResponse = await HttpUtils.deleteRequest("/$_resource/", pathParams: pathParams);
var httpResponse = await HttpUtils.deleteRequest("/$_resource", pathParams: pathParams);
_log.debug("END:deleteDistrict successful - response status code: {}", [httpResponse.statusCode]);
}
}
14 changes: 8 additions & 6 deletions lib/data/repository/user_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class UserRepository {
throw BadRequestException(userIdRequired);
}
final pathParams = id;
final httpResponse = await HttpUtils.getRequest("/admin/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.getRequest("/admin/$_resource", pathParams: pathParams);
final response = User.fromJsonString(httpResponse.body)!;
_log.debug("END:getUser successful - response.body: {}", [response.toString()]);
return response;
Expand All @@ -38,7 +38,7 @@ class UserRepository {
throw BadRequestException("User login is required");
}
final pathParams = login;
final httpResponse = await HttpUtils.getRequest("/admin/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.getRequest("/admin/$_resource", pathParams: pathParams);
final response = User.fromJsonString(httpResponse.body)!;
_log.debug("END:getUserByLogin successful - response.body: {}", [response.toString()]);
return response;
Expand Down Expand Up @@ -74,7 +74,7 @@ class UserRepository {
}

/// Retrieve all users method that retrieves all the users
Future<List<User?>> list({int page = 0, int size = 10, List<String> sort = const ["id,desc"]}) async {
Future<List<User>> list({int page = 0, int size = 10, List<String> sort = const ["id,desc"]}) async {
_log.debug("BEGIN:getUsers repository start - page: {}, size: {}, sort: {}", [page, size, sort]);
final queryParams = {"page": page.toString(), "size": size.toString(), "sort": sort.join("&sort=")};
final httpResponse = await HttpUtils.getRequest("/admin/$_resource", queryParams: queryParams);
Expand All @@ -86,8 +86,10 @@ class UserRepository {
/// Find user method that findUserByAuthorities a user
Future<List<User>> listByAuthority(int page, int size, String authority) async {
_log.debug("BEGIN:findUserByAuthority repository start - page: {}, size: {}, authority: {}", [page, size, authority]);
final queryParams = {"page": page.toString(), "size": size.toString(), "authority": authority};
final response = await HttpUtils.getRequest("/admin/$_resource/list", queryParams: queryParams);
final queryParams = {"page": page.toString(), "size": size.toString()};
final pathParams = authority;
final response = await HttpUtils.getRequest("/admin/$_resource/authorities",pathParams: pathParams, queryParams: queryParams);
// var r = response.body;
var result = JsonMapper.deserialize<List<User>>(response.body)!;
_log.debug("END:findUserByAuthority successful - response list size: {}", [result.length]);
return result;
Expand All @@ -110,7 +112,7 @@ class UserRepository {
throw BadRequestException(userIdRequired);
}
final pathParams = id;
final httpResponse = await HttpUtils.deleteRequest("/admin/$_resource/", pathParams: pathParams);
final httpResponse = await HttpUtils.deleteRequest("/admin/$_resource", pathParams: pathParams);
_log.debug("END:deleteUser successful - response status code: {}", [httpResponse.statusCode]);
}
}
2 changes: 1 addition & 1 deletion lib/main/main_prod.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import 'main_prod.mapper.g.dart' show initializeJsonMapper;
/// main entry point of PRODUCTION
void main() async {
// first configure the logger
AppLogger.configure(isProduction: true);
AppLogger.configure(isProduction: false);
final log = AppLogger.getLogger("main_prod.dart");

ProfileConstants.setEnvironment(Environment.prod);
Expand Down
4 changes: 0 additions & 4 deletions lib/presentation/common_blocs/account/account_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_bloc_advance/configuration/app_logger.dart';
import 'package:flutter_bloc_advance/configuration/local_storage.dart';

import '../../../data/models/user.dart';
import '../../../data/repository/account_repository.dart';
Expand Down Expand Up @@ -32,9 +31,6 @@ class AccountBloc extends Bloc<AccountEvent, AccountState> {

try {
User user = await _repository.getAccount();
await AppLocalStorage().save(StorageKeys.roles.name, user.authorities);
await AppLocalStorage().save(StorageKeys.username.name, user.login);

emit(state.copyWith(data: user, status: AccountStatus.success));
_log.debug("END: getAccount bloc: _onLoad success: {}", [user.toString()]);
} catch (e) {
Expand Down
6 changes: 0 additions & 6 deletions lib/presentation/common_widgets/drawer/drawer_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ class ApplicationDrawer extends StatelessWidget {
debugPrint("ApplicationDrawer build");
return BlocListener<DrawerBloc, DrawerState>(
listener: (context, state) {
//debugPrint("INITIAL - current language : ${AppLocalStorageCached.language}");
//debugPrint("DrawerBloc listener: ${state.status}");
if (state.isLogout) {
AppRouter().push(context, ApplicationRoutesConstants.login);
Expand All @@ -30,11 +29,9 @@ class ApplicationDrawer extends StatelessWidget {
builder: (context, state) {
final isDarkMode = state.theme == AdaptiveThemeMode.dark;

// debugPrint("BUILDER - current lang : ${AppLocalStorageCached.language}");
// debugPrint("BUILDER - state lang : ${state.language}");
//
//
// debugPrint("BUILDER - current theme : ${AppLocalStorageCached.theme}");
// debugPrint("BUILDER - state theme : ${state.theme}");

var isEnglish = state.language == 'en';
Expand All @@ -59,7 +56,6 @@ class ApplicationDrawer extends StatelessWidget {
onChanged: (value) {
//debugPrint("BEGIN:ON_PRESSED.value - ${value}");
final newTheme = value ? AdaptiveThemeMode.dark : AdaptiveThemeMode.light;
//debugPrint("BEGIN:ON_PRESSED - current theme : ${AppLocalStorageCached.theme}");
//debugPrint("BEGIN:ON_PRESSED - current newTheme : ${newTheme}");
context.read<DrawerBloc>().add(ChangeThemeEvent(theme: newTheme));
if (value) {
Expand All @@ -70,7 +66,6 @@ class ApplicationDrawer extends StatelessWidget {
Scaffold.of(context).closeDrawer();
AppRouter().push(context, ApplicationRoutesConstants.home);

//debugPrint("END:ON_PRESSED - current cached theme : ${AppLocalStorageCached.theme}");
},
),
SwitchListTile(
Expand All @@ -85,7 +80,6 @@ class ApplicationDrawer extends StatelessWidget {
context.read<DrawerBloc>().add(ChangeLanguageEvent(language: newLang));
AppRouter().push(context, ApplicationRoutesConstants.home);

//debugPrint("ON_PRESSED - current language : ${AppLocalStorageCached.language}");
},
),
_buildLogoutButton(context),
Expand Down
5 changes: 3 additions & 2 deletions lib/presentation/screen/components/authority_lov_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ class AuthorityDropdown extends StatelessWidget {
child: BlocBuilder<AuthorityBloc, AuthorityState>(
builder: (context, state) {
if (state is AuthorityLoadSuccessState) {
final authorities = ["", ...state.authorities];
return FormBuilderDropdown(
enabled: enabled,
name: 'authority',
decoration: InputDecoration(hintText: S.of(context).authorities),
items: state.authorities.map((role) => DropdownMenuItem(value: role, child: Text(role ?? ""))).toList(),
initialValue: state.authorities.first,
items: authorities.map((e) => DropdownMenuItem(value: e, child: Text(e ?? ""))).toList(),
initialValue: authorities.first,
);
}
return const SizedBox.shrink();
Expand Down
6 changes: 6 additions & 0 deletions lib/presentation/screen/login/bloc/login_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_bloc_advance/configuration/app_logger.dart';
import 'package:flutter_bloc_advance/configuration/local_storage.dart';
import 'package:flutter_bloc_advance/data/app_api_exception.dart';
import 'package:flutter_bloc_advance/data/repository/account_repository.dart';

import '../../../../data/models/user_jwt.dart';
import '../../../../data/repository/login_repository.dart';
Expand Down Expand Up @@ -46,6 +47,11 @@ class LoginBloc extends Bloc<LoginEvent, LoginState> {
_log.debug("onSubmit save storage token: {}", [token.idToken]);
await AppLocalStorage().save(StorageKeys.username.name, event.username);
_log.debug("onSubmit save storage username: {}", [event.username]);
final user = await AccountRepository().getAccount();
await AppLocalStorage().save(StorageKeys.roles.name, user.authorities);
_log.debug("onSubmit save storage roles: {}", [user.authorities]);


emit(LoginLoadedState(username: event.username, password: event.password));

_log.debug("END:onSubmit LoginFormSubmitted event success: {}", [token.toString()]);
Expand Down
22 changes: 14 additions & 8 deletions lib/presentation/screen/user/bloc/user_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -85,18 +85,24 @@ class UserBloc extends Bloc<UserEvent, UserState> {

/// Search a user by name or authority.
FutureOr<void> _onSearch(UserSearchEvent event, Emitter<UserState> emit) async {
_log.debug("BEGIN: onSearch UserSearch event: {}", [event.name]);
_log.debug("BEGIN: onSearch UserSearch event. name:{} authority: {}", [event.name, event.authority]);
emit(state.copyWith(status: UserStatus.loading));
try {
if (event.name == "") {
final entities = await _repository.listByAuthority(event.page, event.size, event.authority);
if ((event.name == null || event.name == "") && (event.authority == null || event.authority == "")) {
final entities = await _repository.list();
emit(state.copyWith(status: UserStatus.searchSuccess, userList: entities));
_log.debug("END:onSearch UserSearch event success content count: {}", [entities.length]);
}
if (event.name != "") {
final entities = await _repository.listByNameAndRole(event.page, event.size, event.name, event.authority);
_log.debug("END:onSearch UserSearch event success - list. content count: {}", [entities.length]);
return;
} else if (event.name != null && event.name!.isNotEmpty && event.authority != null && event.authority!.isNotEmpty) {
final entities = await _repository.listByNameAndRole(event.page, event.size, event.name!, event.authority!);
emit(state.copyWith(status: UserStatus.searchSuccess, userList: entities));
_log.debug("END:onSearch UserSearch event with name success content count: {}", [entities.length]);
_log.debug("END:onSearch UserSearch event with name success - name and authority content count: {}", [entities.length]);
return;
} else if (event.authority != null && event.authority!.isNotEmpty) {
final entities = await _repository.listByAuthority(event.page, event.size, event.authority!);
emit(state.copyWith(status: UserStatus.searchSuccess, userList: entities));
_log.debug("END:onSearch UserSearch event success authority - content count: {}", [entities.length]);
return;
}
} catch (e) {
emit(state.copyWith(status: UserStatus.failure, err: e.toString()));
Expand Down
8 changes: 4 additions & 4 deletions lib/presentation/screen/user/bloc/user_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ class UserEvent extends Equatable {
class UserSearchEvent extends UserEvent {
final int page;
final int size;
final String authority;
final String name;
final String? authority;
final String? name;

const UserSearchEvent({
this.page = 0,
this.size = 10,
this.authority = "",
this.name = "",
this.authority,
this.name,
});
}

Expand Down
8 changes: 4 additions & 4 deletions lib/presentation/screen/user/list/list_user_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,8 @@ class SearchActionButtons extends StatelessWidget {
UserSearchEvent(
page: int.parse(formKey.currentState!.fields['rangeStart']?.value),
size: int.parse(formKey.currentState!.fields['rangeEnd']?.value),
authority: formKey.currentState!.fields['authority']?.value ?? "-",
name: formKey.currentState!.fields['name']?.value ?? "",
authority: formKey.currentState!.fields['authority']?.value,
name: formKey.currentState!.fields['name']?.value,
),
);
}
Expand Down Expand Up @@ -560,8 +560,8 @@ class UserActionButtons extends StatelessWidget {
UserSearchEvent(
page: int.parse(formKey.currentState!.fields['rangeStart']?.value),
size: int.parse(formKey.currentState!.fields['rangeEnd']?.value),
authority: formKey.currentState!.fields['authority']?.value ?? "-",
name: formKey.currentState!.fields['name']?.value ?? "",
authority: formKey.currentState!.fields['authority']?.value,
name: formKey.currentState!.fields['name']?.value,
),
);
// }
Expand Down
Loading

0 comments on commit 1ae4601

Please sign in to comment.