Compare commits

..

14 Commits

Author SHA1 Message Date
c5f5992c18 disable_edit_user 2025-02-06 11:12:43 +03:00
98ad7090d8 Removed prints and unused code 2025-02-06 01:01:21 +03:00
ea08024b82 Merge pull request #87 from SyncrowIOT/bugfix/fix-tag-repeat
Bugfix/update-subspace-tag-value
2025-02-06 00:59:11 +03:00
f6d66185b3 updating tags inside subspace 2025-02-06 00:18:44 +04:00
ead5297ba1 Merge pull request #86 from SyncrowIOT/roles_permissions_bugs
Roles permissions bugs
2025-02-05 21:53:46 +03:00
9a6bf5cbaf privacy policy fixes 2025-02-05 18:16:09 +03:00
51fbe64209 fixes bugs 2025-02-05 16:53:36 +03:00
49fa80e7d8 Merge pull request #85 from SyncrowIOT/bugfix/fix-tag-repeat
Fixed tag repeat
2025-02-05 17:47:47 +04:00
1aa15e5dd6 fixed loading 2025-02-05 17:01:03 +04:00
962f2d6861 Fixed tgag repeat 2025-02-05 16:00:53 +04:00
bd6219f915 Merge pull request #84 from SyncrowIOT/side_tree
Enhanced the side tree design
2025-02-05 11:56:23 +03:00
132cafcaa2 Enhanced the side tree design 2025-02-05 11:52:44 +03:00
8862ad95f3 Merge pull request #83 from SyncrowIOT/bugfix/fix-issue-in-creating-space-with-duplicate
Bugfix/fix-issue-in-creating-space-with-duplicate
2025-02-05 12:09:38 +04:00
95cee89b4c Merge pull request #82 from SyncrowIOT/SP-951-FE-Link-Space-Model-Pop-Up
added edit space sibling conflict
2025-02-04 15:57:37 +04:00
21 changed files with 877 additions and 528 deletions

View File

@ -69,7 +69,7 @@ class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
}, },
)), )),
Expanded( Expanded(
flex: 3, flex: 4,
child: state is DeviceManagementLoading child: state is DeviceManagementLoading
? const Center(child: CircularProgressIndicator()) ? const Center(child: CircularProgressIndicator())
: Column( : Column(

View File

@ -1,3 +1,4 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
@ -51,6 +52,8 @@ class HomeBloc extends Bloc<HomeEvent, HomeState> {
await const FlutterSecureStorage().read(key: UserModel.userUuidKey); await const FlutterSecureStorage().read(key: UserModel.userUuidKey);
user = await HomeApi().fetchUserInfo(uuid); user = await HomeApi().fetchUserInfo(uuid);
add(FetchTermEvent()); add(FetchTermEvent());
add(FetchPolicyEvent());
emit(HomeInitial()); emit(HomeInitial());
} catch (e) { } catch (e) {
return; return;
@ -61,8 +64,9 @@ class HomeBloc extends Bloc<HomeEvent, HomeState> {
try { try {
emit(LoadingHome()); emit(LoadingHome());
terms = await HomeApi().fetchTerms(); terms = await HomeApi().fetchTerms();
add(FetchPolicyEvent()); emit(HomeInitial());
emit(PolicyAgreement());
// emit(PolicyAgreement());
} catch (e) { } catch (e) {
return; return;
} }
@ -72,8 +76,11 @@ class HomeBloc extends Bloc<HomeEvent, HomeState> {
try { try {
emit(LoadingHome()); emit(LoadingHome());
policy = await HomeApi().fetchPolicy(); policy = await HomeApi().fetchPolicy();
emit(PolicyAgreement()); debugPrint("Fetched policy: $policy");
// Emit a state to trigger the UI update
emit(HomeInitial());
} catch (e) { } catch (e) {
debugPrint("Error fetching policy: $e");
return; return;
} }
} }

View File

@ -9,103 +9,121 @@ import 'package:syncrow_web/pages/home/view/home_card.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/web_layout/web_scaffold.dart'; import 'package:syncrow_web/web_layout/web_scaffold.dart';
class HomeWebPage extends StatelessWidget { class HomeWebPage extends StatefulWidget {
const HomeWebPage({super.key}); const HomeWebPage({super.key});
@override
State<HomeWebPage> createState() => _HomeWebPageState();
}
class _HomeWebPageState extends State<HomeWebPage> {
// Flag to track whether the dialog is already shown.
bool _dialogShown = false;
@override
void initState() {
super.initState();
final homeBloc = BlocProvider.of<HomeBloc>(context);
homeBloc.add(FetchUserInfo());
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size; Size size = MediaQuery.of(context).size;
final homeBloc = BlocProvider.of<HomeBloc>(context); final homeBloc = BlocProvider.of<HomeBloc>(context);
return PopScope( return PopScope(
canPop: false, canPop: false,
onPopInvoked: (didPop) => false, onPopInvoked: (didPop) => false,
child: BlocConsumer<HomeBloc, HomeState>( child: BlocConsumer<HomeBloc, HomeState>(
listener: (BuildContext context, state) { listener: (BuildContext context, state) {
if (state is HomeInitial) { if (state is HomeInitial) {
if (homeBloc.user!.hasAcceptedWebAgreement == false) { if (homeBloc.user!.hasAcceptedWebAgreement == false && !_dialogShown) {
Future.delayed(const Duration(seconds: 2), () { _dialogShown = true; // Set the flag to true to indicate the dialog is showing.
showDialog( Future.delayed(const Duration(seconds: 1), () {
context: context, showDialog(
barrierDismissible: false, context: context,
builder: (BuildContext context) { barrierDismissible: false,
return AgreementAndPrivacyDialog( builder: (BuildContext context) {
terms: homeBloc.terms, return AgreementAndPrivacyDialog(
policy: homeBloc.policy, terms: homeBloc.terms,
); policy: homeBloc.policy,
}, );
).then((v) { },
if (v != null) { ).then((v) {
homeBloc.add(ConfirmUserAgreementEvent()); _dialogShown = false;
homeBloc.add(const FetchUserInfo()); if (v != null) {
} homeBloc.add(ConfirmUserAgreementEvent());
}); homeBloc.add(const FetchUserInfo());
}
}); });
} });
} }
}, }
builder: (context, state) { },
return WebScaffold( builder: (context, state) {
enableMenuSidebar: false, return WebScaffold(
appBarTitle: Row( enableMenuSidebar: false,
appBarTitle: Row(
children: [
SvgPicture.asset(
Assets.loginLogo,
width: 150,
),
],
),
scaffoldBody: SizedBox(
height: size.height,
width: size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
SvgPicture.asset( Column(
Assets.loginLogo, mainAxisAlignment: MainAxisAlignment.center,
width: 150, crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: size.height * 0.1),
Text(
'ACCESS YOUR APPS',
style: Theme.of(context)
.textTheme
.headlineLarge!
.copyWith(color: Colors.black, fontSize: 40),
),
const SizedBox(height: 30),
Expanded(
flex: 4,
child: SizedBox(
height: size.height * 0.6,
width: size.width * 0.68,
child: GridView.builder(
itemCount: 3, // Change this count if needed.
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // Adjust as needed.
crossAxisSpacing: 20.0,
mainAxisSpacing: 20.0,
childAspectRatio: 1.5,
),
itemBuilder: (context, index) {
return HomeCard(
index: index,
active: homeBloc.homeItems[index].active!,
name: homeBloc.homeItems[index].title!,
img: homeBloc.homeItems[index].icon!,
onTap: () => homeBloc.homeItems[index].onPress(context),
);
},
),
),
),
],
), ),
], ],
), ),
scaffoldBody: SizedBox( ),
height: size.height, );
width: size.width, },
child: Row( ),
mainAxisAlignment: MainAxisAlignment.center, );
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(height: size.height * 0.1),
Text(
'ACCESS YOUR APPS',
style: Theme.of(context)
.textTheme
.headlineLarge!
.copyWith(color: Colors.black, fontSize: 40),
),
const SizedBox(height: 30),
Expanded(
flex: 4,
child: SizedBox(
height: size.height * 0.6,
width: size.width * 0.68,
child: GridView.builder(
itemCount: 3, //8
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, //4
crossAxisSpacing: 20.0,
mainAxisSpacing: 20.0,
childAspectRatio: 1.5,
),
itemBuilder: (context, index) {
return HomeCard(
index: index,
active: homeBloc.homeItems[index].active!,
name: homeBloc.homeItems[index].title!,
img: homeBloc.homeItems[index].icon!,
onTap: () => homeBloc.homeItems[index].onPress(context),
);
},
),
),
),
],
),
],
),
),
);
},
));
} }
} }

View File

@ -79,7 +79,7 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
List<TreeNode> updatedCommunities = []; List<TreeNode> updatedCommunities = [];
List<TreeNode> spacesNodes = []; List<TreeNode> spacesNodes = [];
List<String> communityIds = []; List<String> communityIds = [];
_onLoadCommunityAndSpaces( _onLoadCommunityAndSpaces(
LoadCommunityAndSpacesEvent event, Emitter<UsersState> emit) async { LoadCommunityAndSpacesEvent event, Emitter<UsersState> emit) async {
try { try {
@ -102,12 +102,19 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
); );
}).toList(), }).toList(),
); );
originalCommunities = updatedCommunities;
emit(const SpacesLoadedState()); emit(const SpacesLoadedState());
} catch (e) { } catch (e) {
emit(ErrorState('Error loading communities and spaces: $e')); emit(ErrorState('Error loading communities and spaces: $e'));
} }
} }
// This variable holds the full original list.
List<TreeNode> originalCommunities = [];
// This variable holds the working list that may be filtered.
// Build tree nodes from your data model.
List<TreeNode> _buildTreeNodes(List<SpaceModel> spaces) { List<TreeNode> _buildTreeNodes(List<SpaceModel> spaces) {
return spaces.map((space) { return spaces.map((space) {
List<TreeNode> childNodes = List<TreeNode> childNodes =
@ -123,12 +130,39 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
}).toList(); }).toList();
} }
// Optional helper method to deep clone a TreeNode.
TreeNode _cloneNode(TreeNode node) {
return TreeNode(
uuid: node.uuid,
title: node.title,
isChecked: node.isChecked,
isHighlighted: node.isHighlighted,
isExpanded: node.isExpanded,
children: node.children.map(_cloneNode).toList(),
);
}
// Clone an entire list of tree nodes.
List<TreeNode> _cloneNodes(List<TreeNode> nodes) {
return nodes.map(_cloneNode).toList();
}
// Your search event handler.
void searchTreeNode(SearchAnode event, Emitter<UsersState> emit) { void searchTreeNode(SearchAnode event, Emitter<UsersState> emit) {
emit(UsersLoadingState()); emit(UsersLoadingState());
// If the search term is empty, restore the original list.
if (event.searchTerm!.isEmpty) { if (event.searchTerm!.isEmpty) {
// Clear any highlights on the restored copy.
updatedCommunities = _cloneNodes(originalCommunities);
_clearHighlights(updatedCommunities); _clearHighlights(updatedCommunities);
} else { } else {
_searchAndHighlightNodes(updatedCommunities, event.searchTerm!); // Start with a fresh clone of the original tree.
List<TreeNode> freshClone = _cloneNodes(originalCommunities);
_searchAndHighlightNodes(freshClone, event.searchTerm!);
updatedCommunities = _filterNodes(freshClone, event.searchTerm!);
} }
emit(ChangeStatusSteps()); emit(ChangeStatusSteps());
} }
@ -155,6 +189,91 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
return anyMatch; return anyMatch;
} }
List<TreeNode> _filterNodes(List<TreeNode> nodes, String searchTerm) {
List<TreeNode> filteredNodes = [];
for (var node in nodes) {
bool isMatch =
node.title.toLowerCase().contains(searchTerm.toLowerCase());
List<TreeNode> filteredChildren = _filterNodes(node.children, searchTerm);
if (isMatch || filteredChildren.isNotEmpty) {
node.isHighlighted = isMatch;
node.children = filteredChildren;
filteredNodes.add(node);
}
}
return filteredNodes;
}
// List<TreeNode> _buildTreeNodes(List<SpaceModel> spaces) {
// return spaces.map((space) {
// List<TreeNode> childNodes =
// space.children.isNotEmpty ? _buildTreeNodes(space.children) : [];
// return TreeNode(
// uuid: space.uuid!,
// title: space.name,
// isChecked: false,
// isHighlighted: false,
// isExpanded: childNodes.isNotEmpty,
// children: childNodes,
// );
// }).toList();
// }
// void searchTreeNode(SearchAnode event, Emitter<UsersState> emit) {
// emit(UsersLoadingState());
// if (event.searchTerm!.isEmpty) {
// _clearHighlights(updatedCommunities);
// } else {
// _searchAndHighlightNodes(updatedCommunities, event.searchTerm!);
// updatedCommunities = _filterNodes(updatedCommunities, event.searchTerm!);
// }
// emit(ChangeStatusSteps());
// }
// void _clearHighlights(List<TreeNode> nodes) {
// for (var node in nodes) {
// node.isHighlighted = false;
// if (node.children.isNotEmpty) {
// _clearHighlights(node.children);
// }
// }
// }
// bool _searchAndHighlightNodes(List<TreeNode> nodes, String searchTerm) {
// bool anyMatch = false;
// for (var node in nodes) {
// bool isMatch =
// node.title.toLowerCase().contains(searchTerm.toLowerCase());
// bool childMatch = _searchAndHighlightNodes(node.children, searchTerm);
// node.isHighlighted = isMatch || childMatch;
// anyMatch = anyMatch || node.isHighlighted;
// }
// return anyMatch;
// }
// List<TreeNode> _filterNodes(List<TreeNode> nodes, String searchTerm) {
// List<TreeNode> filteredNodes = [];
// for (var node in nodes) {
// // Check if the current node's title contains the search term.
// bool isMatch =
// node.title.toLowerCase().contains(searchTerm.toLowerCase());
// // Recursively filter the children.
// List<TreeNode> filteredChildren = _filterNodes(node.children, searchTerm);
// // If the current node is a match or any of its children are, include it.
// if (isMatch || filteredChildren.isNotEmpty) {
// // Optionally, update any properties (like isHighlighted) if you still need them.
// node.isHighlighted = isMatch;
// // Replace the children with the filtered ones.
// node.children = filteredChildren;
// filteredNodes.add(node);
// }
// }
// return filteredNodes;
// }
List<String> selectedIds = []; List<String> selectedIds = [];
List<String> getSelectedIds(List<TreeNode> nodes) { List<String> getSelectedIds(List<TreeNode> nodes) {
@ -221,7 +340,7 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
lastName: lastNameController.text, lastName: lastNameController.text,
phoneNumber: phoneController.text, phoneNumber: phoneController.text,
roleUuid: roleSelected, roleUuid: roleSelected,
spaceUuids: selectedIds, spaceUuids: selectedIds,
); );
if (res) { if (res) {
@ -251,12 +370,11 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
} }
} }
_editInviteUser(EditInviteUsers event, Emitter<UsersState> emit) async { _editInviteUser(EditInviteUsers event, Emitter<UsersState> emit) async {
try { try {
emit(UsersLoadingState()); emit(UsersLoadingState());
List<String> selectedIds = getSelectedIds(updatedCommunities) List<String> selectedIds = getSelectedIds(updatedCommunities)
.where((id) => !communityIds.contains(id)) .where((id) => !communityIds.contains(id))
.toList(); .toList();
bool res = await UserPermissionApi().editInviteUser( bool res = await UserPermissionApi().editInviteUser(

View File

@ -34,8 +34,7 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
return Dialog( return Dialog(
child: Container( child: Container(
decoration: const BoxDecoration( decoration: const BoxDecoration(
color: Colors.white, color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(20))),
borderRadius: BorderRadius.all(Radius.circular(20))),
width: 900, width: 900,
child: Column( child: Column(
children: [ children: [
@ -64,8 +63,7 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
children: [ children: [
_buildStep1Indicator(1, "Basics", _blocRole), _buildStep1Indicator(1, "Basics", _blocRole),
_buildStep2Indicator(2, "Spaces", _blocRole), _buildStep2Indicator(2, "Spaces", _blocRole),
_buildStep3Indicator( _buildStep3Indicator(3, "Role & Permissions", _blocRole),
3, "Role & Permissions", _blocRole),
], ],
), ),
), ),
@ -113,15 +111,12 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
if (currentStep < 3) { if (currentStep < 3) {
currentStep++; currentStep++;
if (currentStep == 2) { if (currentStep == 2) {
_blocRole.add( _blocRole.add(const CheckStepStatus(isEditUser: false));
const CheckStepStatus(isEditUser: false));
} else if (currentStep == 3) { } else if (currentStep == 3) {
_blocRole _blocRole.add(const CheckSpacesStepStatus());
.add(const CheckSpacesStepStatus());
} }
} else { } else {
_blocRole _blocRole.add(SendInviteUsers(context: context));
.add(SendInviteUsers(context: context));
} }
}); });
}, },
@ -129,11 +124,8 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
currentStep < 3 ? "Next" : "Save", currentStep < 3 ? "Next" : "Save",
style: TextStyle( style: TextStyle(
color: (_blocRole.isCompleteSpaces == false || color: (_blocRole.isCompleteSpaces == false ||
_blocRole.isCompleteBasics == _blocRole.isCompleteBasics == false ||
false || _blocRole.isCompleteRolePermissions == false) &&
_blocRole
.isCompleteRolePermissions ==
false) &&
currentStep == 3 currentStep == 3
? ColorsManager.grayColor ? ColorsManager.grayColor
: ColorsManager.secondaryColor), : ColorsManager.secondaryColor),
@ -204,12 +196,8 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
label, label,
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
color: currentStep == step color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor,
? ColorsManager.blackColor fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal,
: ColorsManager.greyColor,
fontWeight: currentStep == step
? FontWeight.bold
: FontWeight.normal,
), ),
), ),
], ],
@ -236,12 +224,16 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
setState(() { setState(() {
currentStep = step;
bloc.add(const CheckStepStatus(isEditUser: false)); bloc.add(const CheckStepStatus(isEditUser: false));
currentStep = step;
Future.delayed(const Duration(milliseconds: 500), () {
bloc.add(const CheckStepStatus(isEditUser: false));
});
if (step3 == 3) { if (step3 == 3) {
bloc.add(const CheckRoleStepStatus()); Future.delayed(const Duration(seconds: 1), () {
bloc.add(const CheckRoleStepStatus());
});
} }
}); });
}, },
child: Column( child: Column(
@ -268,12 +260,8 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
label, label,
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
color: currentStep == step color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor,
? ColorsManager.blackColor fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal,
: ColorsManager.greyColor,
fontWeight: currentStep == step
? FontWeight.bold
: FontWeight.normal,
), ),
), ),
], ],
@ -330,12 +318,8 @@ class _AddNewUserDialogState extends State<AddNewUserDialog> {
label, label,
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
color: currentStep == step color: currentStep == step ? ColorsManager.blackColor : ColorsManager.greyColor,
? ColorsManager.blackColor fontWeight: currentStep == step ? FontWeight.bold : FontWeight.normal,
: ColorsManager.greyColor,
fontWeight: currentStep == step
? FontWeight.bold
: FontWeight.normal,
), ),
), ),
], ],

View File

@ -46,117 +46,120 @@ class BasicsView extends StatelessWidget {
), ),
Row( Row(
children: [ children: [
SizedBox( Flexible(
width: MediaQuery.of(context).size.width * 0.18, child: SizedBox(
height: MediaQuery.of(context).size.width * 0.08, // width: MediaQuery.of(context).size.width * 0.18,
child: Column( height: MediaQuery.of(context).size.width * 0.08,
crossAxisAlignment: CrossAxisAlignment.start, child: Column(
children: [ crossAxisAlignment: CrossAxisAlignment.start,
SizedBox( children: [
child: Row( SizedBox(
children: [ child: Row(
const Text( children: [
" * ", const Text(
style: TextStyle( " * ",
color: ColorsManager.red, style: TextStyle(
fontWeight: FontWeight.w900, color: ColorsManager.red,
fontSize: 15, fontWeight: FontWeight.w900,
fontSize: 15,
),
), ),
), Text(
Text( 'First Name',
'First Name',
style: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400,
fontSize: 13,
),
),
],
)),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
style:
const TextStyle(color: ColorsManager.blackColor),
// onChanged: (value) {
// Future.delayed(const Duration(milliseconds: 200),
// () {
// _blocRole.add(const ValidateBasicsStep());
// });
// },
controller: _blocRole.firstNameController,
decoration: inputTextFormDeco(
hintText: "Enter first name",
).copyWith(
hintStyle: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400,
fontSize: 12,
color: ColorsManager.textGray),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Enter first name';
}
return null;
},
),
),
],
),
),
const SizedBox(width: 10),
SizedBox(
width: MediaQuery.of(context).size.width * 0.18,
height: MediaQuery.of(context).size.width * 0.08,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
child: Row(
children: [
const Text(
" * ",
style: TextStyle(
color: ColorsManager.red,
fontWeight: FontWeight.w900,
fontSize: 15,
),
),
Text('Last Name',
style: context.textTheme.bodyMedium?.copyWith( style: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400, fontWeight: FontWeight.w400,
fontSize: 13, fontSize: 13,
)), ),
], ),
)), ],
Padding( )),
padding: const EdgeInsets.all(8.0), Padding(
child: TextFormField( padding: const EdgeInsets.all(8.0),
// onChanged: (value) { child: TextFormField(
// Future.delayed(const Duration(milliseconds: 200), style: const TextStyle(
// () { color: ColorsManager.blackColor),
// _blocRole.add(ValidateBasicsStep()); // onChanged: (value) {
// }); // Future.delayed(const Duration(milliseconds: 200),
// }, // () {
controller: _blocRole.lastNameController, // _blocRole.add(const ValidateBasicsStep());
style: const TextStyle(color: Colors.black), // });
decoration: // },
inputTextFormDeco(hintText: "Enter last name") controller: _blocRole.firstNameController,
.copyWith( decoration: inputTextFormDeco(
hintStyle: context hintText: "Enter first name",
.textTheme.bodyMedium ).copyWith(
?.copyWith( hintStyle: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400, fontWeight: FontWeight.w400,
fontSize: 12, fontSize: 12,
color: ColorsManager.textGray)), color: ColorsManager.textGray),
validator: (value) { ),
if (value == null || value.isEmpty) { validator: (value) {
return 'Enter last name'; if (value == null || value.isEmpty) {
} return 'Enter first name';
return null; }
}, return null;
},
),
), ),
), ],
], ),
),
),
const SizedBox(width: 10),
Flexible(
child: SizedBox(
// width: MediaQuery.of(context).size.width * 0.18,
height: MediaQuery.of(context).size.width * 0.08,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
child: Row(
children: [
const Text(
" * ",
style: TextStyle(
color: ColorsManager.red,
fontWeight: FontWeight.w900,
fontSize: 15,
),
),
Text('Last Name',
style: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400,
fontSize: 13,
)),
],
)),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
// onChanged: (value) {
// Future.delayed(const Duration(milliseconds: 200),
// () {
// _blocRole.add(ValidateBasicsStep());
// });
// },
controller: _blocRole.lastNameController,
style: const TextStyle(color: Colors.black),
decoration:
inputTextFormDeco(hintText: "Enter last name")
.copyWith(
hintStyle: context.textTheme.bodyMedium
?.copyWith(
fontWeight: FontWeight.w400,
fontSize: 12,
color: ColorsManager.textGray)),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Enter last name';
}
return null;
},
),
),
],
),
), ),
), ),
], ],

View File

@ -27,7 +27,16 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
int currentPage = 1; int currentPage = 1;
List<RolesUserModel> users = []; List<RolesUserModel> users = [];
List<RolesUserModel> initialUsers = []; List<RolesUserModel> initialUsers = [];
List<RolesUserModel> totalUsersCount = [];
String currentSortOrder = ''; String currentSortOrder = '';
String currentSortJopTitle = '';
String currentSortRole = '';
String currentSortCreatedDate = '';
String currentSortStatus = '';
String currentSortCreatedBy = '';
String currentSortOrderDate = ''; String currentSortOrderDate = '';
List<String> roleTypes = []; List<String> roleTypes = [];
List<String> jobTitle = []; List<String> jobTitle = [];
@ -60,6 +69,7 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
jobTitle = jobTitle.toSet().toList(); jobTitle = jobTitle.toSet().toList();
createdBy = createdBy.toSet().toList(); createdBy = createdBy.toSet().toList();
_handlePageChange(ChangePage(1), emit); _handlePageChange(ChangePage(1), emit);
totalUsersCount = initialUsers;
add(ChangePage(currentPage)); add(ChangePage(currentPage));
emit(UsersLoadedState(users: users)); emit(UsersLoadedState(users: users));
} catch (e) { } catch (e) {
@ -91,26 +101,6 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
event.userId, event.newStatus == "disabled" ? false : true); event.userId, event.newStatus == "disabled" ? false : true);
if (res == true) { if (res == true) {
add(const GetUsers()); add(const GetUsers());
// users = users.map((user) {
// if (user.uuid == event.userId) {
// return RolesUserModel(
// uuid: user.uuid,
// createdAt: user.createdAt,
// email: user.email,
// firstName: user.firstName,
// lastName: user.lastName,
// roleType: user.roleType,
// status: event.newStatus,
// isEnabled: event.newStatus == "disabled" ? false : true,
// invitedBy: user.invitedBy,
// phoneNumber: user.phoneNumber,
// jobTitle: user.jobTitle,
// createdDate: user.createdDate,
// createdTime: user.createdTime,
// );
// }
// return user;
// }).toList();
} }
emit(UsersLoadedState(users: users)); emit(UsersLoadedState(users: users));
} catch (e) { } catch (e) {
@ -128,7 +118,6 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
emit(UsersLoadingState()); emit(UsersLoadingState());
currentSortOrder = ""; currentSortOrder = "";
users = List.from(users); users = List.from(users);
emit(UsersLoadedState(users: users));
} else { } else {
emit(UsersLoadingState()); emit(UsersLoadingState());
currentSortOrder = "Asc"; currentSortOrder = "Asc";
@ -136,8 +125,12 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
.toString() .toString()
.toLowerCase() .toLowerCase()
.compareTo(b.firstName.toString().toLowerCase())); .compareTo(b.firstName.toString().toLowerCase()));
emit(UsersLoadedState(users: users));
} }
currentSortJopTitle = '';
currentSortCreatedDate = '';
currentSortStatus = '';
currentSortCreatedBy = '';
emit(UsersLoadedState(users: users));
} }
void _toggleSortUsersByNameDesc( void _toggleSortUsersByNameDesc(
@ -150,13 +143,16 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
emit(UsersLoadingState()); emit(UsersLoadingState());
currentSortOrder = ""; currentSortOrder = "";
users = List.from(initialUsers); users = List.from(initialUsers);
emit(UsersLoadedState(users: users));
} else { } else {
emit(UsersLoadingState()); emit(UsersLoadingState());
currentSortOrder = "Desc"; currentSortOrder = "Desc";
users.sort((a, b) => b.firstName!.compareTo(a.firstName!)); users.sort((a, b) => b.firstName!.compareTo(a.firstName!));
emit(UsersLoadedState(users: users));
} }
currentSortJopTitle = '';
currentSortCreatedDate = '';
currentSortStatus = '';
currentSortCreatedBy = '';
emit(UsersLoadedState(users: users));
} }
void _toggleSortUsersByDateNewestToOldest( void _toggleSortUsersByDateNewestToOldest(
@ -222,6 +218,7 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
Future<void> _searchUsers( Future<void> _searchUsers(
SearchUsers event, Emitter<UserTableState> emit) async { SearchUsers event, Emitter<UserTableState> emit) async {
try { try {
emit(TableSearch());
final query = event.query.toLowerCase(); final query = event.query.toLowerCase();
final filteredUsers = initialUsers.where((user) { final filteredUsers = initialUsers.where((user) {
final fullName = "${user.firstName} ${user.lastName}".toLowerCase(); final fullName = "${user.firstName} ${user.lastName}".toLowerCase();
@ -250,7 +247,8 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
} }
void _handlePageChange(ChangePage event, Emitter<UserTableState> emit) { void _handlePageChange(ChangePage event, Emitter<UserTableState> emit) {
const itemsPerPage = 10; currentPage = event.pageNumber;
const itemsPerPage = 20;
final startIndex = (event.pageNumber - 1) * itemsPerPage; final startIndex = (event.pageNumber - 1) * itemsPerPage;
final endIndex = startIndex + itemsPerPage; final endIndex = startIndex + itemsPerPage;
if (startIndex >= users.length) { if (startIndex >= users.length) {
@ -287,9 +285,15 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
} else if (event.sortOrder == "Desc") { } else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc"; currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else { } else {}
currentSortOrder = ""; currentSortOrder = "";
} currentSortCreatedDate = '';
currentSortStatus = '';
currentSortCreatedBy = '';
currentSortJopTitle = '';
currentSortOrderDate = "";
totalUsersCount = filteredUsers;
emit(UsersLoadedState(users: filteredUsers)); emit(UsersLoadedState(users: filteredUsers));
} }
@ -311,9 +315,16 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
} else if (event.sortOrder == "Desc") { } else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc"; currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else { } else {}
currentSortOrder = ""; currentSortOrder = "";
} currentSortCreatedDate = '';
currentSortStatus = '';
currentSortCreatedBy = '';
currentSortRole = '';
currentSortOrderDate = "";
totalUsersCount = filteredUsers;
emit(UsersLoadedState(users: filteredUsers)); emit(UsersLoadedState(users: filteredUsers));
} }
@ -335,9 +346,15 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
} else if (event.sortOrder == "Desc") { } else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc"; currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else { } else {}
currentSortOrder = ""; currentSortOrder = '';
} currentSortRole = '';
currentSortCreatedDate = '';
currentSortStatus = '';
currentSortOrderDate = "";
totalUsersCount = filteredUsers;
emit(UsersLoadedState(users: filteredUsers)); emit(UsersLoadedState(users: filteredUsers));
} }
@ -371,14 +388,17 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
} else if (event.sortOrder == "Desc") { } else if (event.sortOrder == "Desc") {
currentSortOrder = "Desc"; currentSortOrder = "Desc";
filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!)); filteredUsers.sort((a, b) => b.firstName!.compareTo(a.firstName!));
} else { totalUsersCount = filteredUsers;
currentSortOrder = ""; } else {}
} currentSortOrder = '';
currentSortRole = '';
currentSortCreatedDate = '';
currentSortCreatedBy = '';
currentSortOrderDate = "";
emit(UsersLoadedState(users: filteredUsers)); emit(UsersLoadedState(users: filteredUsers));
} }
void _resetAllFilters(Emitter<UserTableState> emit) { void _resetAllFilters(Emitter<UserTableState> emit) {
selectedRoles.clear(); selectedRoles.clear();
selectedJobTitles.clear(); selectedJobTitles.clear();

View File

@ -9,7 +9,10 @@ final class TableInitial extends UserTableState {
@override @override
List<Object> get props => []; List<Object> get props => [];
} }
final class TableSearch extends UserTableState {
@override
List<Object> get props => [];
}
final class RolesLoadingState extends UserTableState { final class RolesLoadingState extends UserTableState {
@override @override
List<Object> get props => []; List<Object> get props => [];

View File

@ -25,7 +25,8 @@ class UsersPage extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final TextEditingController searchController = TextEditingController(); final TextEditingController searchController = TextEditingController();
Widget actionButton({required String title, required Function()? onTap}) { Widget actionButton(
{bool isActive = false, required String title, Function()? onTap}) {
return InkWell( return InkWell(
onTap: onTap, onTap: onTap,
child: Padding( child: Padding(
@ -33,9 +34,11 @@ class UsersPage extends StatelessWidget {
child: Text( child: Text(
title, title,
style: Theme.of(context).textTheme.bodySmall?.copyWith( style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: title == "Delete" color: isActive == false && title != "Delete"
? ColorsManager.red ? Colors.grey
: ColorsManager.spaceColor, : title == "Delete"
? ColorsManager.red
: ColorsManager.spaceColor,
fontWeight: FontWeight.w400, fontWeight: FontWeight.w400,
), ),
), ),
@ -129,9 +132,12 @@ class UsersPage extends StatelessWidget {
child: TextFormField( child: TextFormField(
controller: searchController, controller: searchController,
onChanged: (value) { onChanged: (value) {
context final bloc = context.read<UserTableBloc>();
.read<UserTableBloc>() bloc.add(FilterClearEvent());
.add(SearchUsers(value)); bloc.add(SearchUsers(value));
if (value == '') {
bloc.add(ChangePage(1));
}
}, },
style: const TextStyle(color: Colors.black), style: const TextStyle(color: Colors.black),
decoration: textBoxDecoration(radios: 15)!.copyWith( decoration: textBoxDecoration(radios: 15)!.copyWith(
@ -222,7 +228,7 @@ class UsersPage extends StatelessWidget {
list: _blocRole.jobTitle, list: _blocRole.jobTitle,
context: context, context: context,
checkboxStates: checkboxStates, checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder, isSelected: _blocRole.currentSortJopTitle,
onOkPressed: () { onOkPressed: () {
searchController.clear(); searchController.clear();
_blocRole.add(FilterClearEvent()); _blocRole.add(FilterClearEvent());
@ -233,14 +239,14 @@ class UsersPage extends StatelessWidget {
Navigator.of(context).pop(); Navigator.of(context).pop();
_blocRole.add(FilterUsersByJobEvent( _blocRole.add(FilterUsersByJobEvent(
selectedJob: selectedItems, selectedJob: selectedItems,
sortOrder: _blocRole.currentSortOrder, sortOrder: _blocRole.currentSortJopTitle,
)); ));
}, },
onSortAtoZ: (v) { onSortAtoZ: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortJopTitle = v;
}, },
onSortZtoA: (v) { onSortZtoA: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortJopTitle = v;
}, },
); );
} }
@ -263,7 +269,7 @@ class UsersPage extends StatelessWidget {
list: _blocRole.roleTypes, list: _blocRole.roleTypes,
context: context, context: context,
checkboxStates: checkboxStates, checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder, isSelected: _blocRole.currentSortRole,
onOkPressed: () { onOkPressed: () {
searchController.clear(); searchController.clear();
_blocRole.add(FilterClearEvent()); _blocRole.add(FilterClearEvent());
@ -275,13 +281,13 @@ class UsersPage extends StatelessWidget {
context.read<UserTableBloc>().add( context.read<UserTableBloc>().add(
FilterUsersByRoleEvent( FilterUsersByRoleEvent(
selectedRoles: selectedItems, selectedRoles: selectedItems,
sortOrder: _blocRole.currentSortOrder)); sortOrder: _blocRole.currentSortRole));
}, },
onSortAtoZ: (v) { onSortAtoZ: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortRole = v;
}, },
onSortZtoA: (v) { onSortZtoA: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortRole = v;
}, },
); );
} }
@ -319,7 +325,7 @@ class UsersPage extends StatelessWidget {
list: _blocRole.createdBy, list: _blocRole.createdBy,
context: context, context: context,
checkboxStates: checkboxStates, checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder, isSelected: _blocRole.currentSortCreatedBy,
onOkPressed: () { onOkPressed: () {
searchController.clear(); searchController.clear();
_blocRole.add(FilterClearEvent()); _blocRole.add(FilterClearEvent());
@ -330,13 +336,13 @@ class UsersPage extends StatelessWidget {
Navigator.of(context).pop(); Navigator.of(context).pop();
_blocRole.add(FilterUsersByCreatedEvent( _blocRole.add(FilterUsersByCreatedEvent(
selectedCreatedBy: selectedItems, selectedCreatedBy: selectedItems,
sortOrder: _blocRole.currentSortOrder)); sortOrder: _blocRole.currentSortCreatedBy));
}, },
onSortAtoZ: (v) { onSortAtoZ: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortCreatedBy = v;
}, },
onSortZtoA: (v) { onSortZtoA: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortCreatedBy = v;
}, },
); );
} }
@ -359,7 +365,7 @@ class UsersPage extends StatelessWidget {
list: _blocRole.status, list: _blocRole.status,
context: context, context: context,
checkboxStates: checkboxStates, checkboxStates: checkboxStates,
isSelected: _blocRole.currentSortOrder, isSelected: _blocRole.currentSortStatus,
onOkPressed: () { onOkPressed: () {
searchController.clear(); searchController.clear();
_blocRole.add(FilterClearEvent()); _blocRole.add(FilterClearEvent());
@ -370,13 +376,13 @@ class UsersPage extends StatelessWidget {
Navigator.of(context).pop(); Navigator.of(context).pop();
_blocRole.add(FilterUsersByDeActevateEvent( _blocRole.add(FilterUsersByDeActevateEvent(
selectedActivate: selectedItems, selectedActivate: selectedItems,
sortOrder: _blocRole.currentSortOrder)); sortOrder: _blocRole.currentSortStatus));
}, },
onSortAtoZ: (v) { onSortAtoZ: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortStatus = v;
}, },
onSortZtoA: (v) { onSortZtoA: (v) {
_blocRole.currentSortOrder = v; _blocRole.currentSortStatus = v;
}, },
); );
} }
@ -441,24 +447,30 @@ class UsersPage extends StatelessWidget {
), ),
Row( Row(
children: [ children: [
actionButton( user.isEnabled != false
title: "Edit", ? actionButton(
onTap: () { isActive: true,
showDialog( title: "Edit",
context: context, onTap: () {
barrierDismissible: false, showDialog(
builder: (BuildContext context) { context: context,
return EditUserDialog(userId: user.uuid); barrierDismissible: false,
}, builder: (BuildContext context) {
).then((v) { return EditUserDialog(
if (v != null) { userId: user.uuid);
if (v != null) { },
_blocRole.add(const GetUsers()); ).then((v) {
} if (v != null) {
} if (v != null) {
}); _blocRole.add(const GetUsers());
}, }
), }
});
},
)
: actionButton(
title: "Edit",
),
actionButton( actionButton(
title: "Delete", title: "Delete",
onTap: () { onTap: () {
@ -508,12 +520,11 @@ class UsersPage extends StatelessWidget {
const Icon(Icons.keyboard_double_arrow_right), const Icon(Icons.keyboard_double_arrow_right),
firstPageIcon: firstPageIcon:
const Icon(Icons.keyboard_double_arrow_left), const Icon(Icons.keyboard_double_arrow_left),
totalPages: (_blocRole.users.length / totalPages: (_blocRole.totalUsersCount.length /
_blocRole.itemsPerPage) _blocRole.itemsPerPage)
.ceil(), .ceil(),
currentPage: _blocRole.currentPage, currentPage: _blocRole.currentPage,
onPageChanged: (int pageNumber) { onPageChanged: (int pageNumber) {
_blocRole.currentPage = pageNumber;
context context
.read<UserTableBloc>() .read<UserTableBloc>()
.add(ChangePage(pageNumber)); .add(ChangePage(pageNumber));

View File

@ -33,64 +33,55 @@ class _RoutinesViewState extends State<RoutinesView> {
return Row( return Row(
children: [ children: [
Expanded( Expanded(
child: child: SpaceTreeView(
// SideSpacesView(
// onSelectAction: (String communityId, String spaceId) {
// // context.read<RoutineBloc>()
// // ..add(LoadScenes(spaceId, communityId))
// // ..add(LoadAutomation(spaceId));
// },
// )
SpaceTreeView(
onSelect: () {}, onSelect: () {},
)), )),
Expanded( Expanded(
flex: 3, flex: 4,
child: Padding( child: ListView(children: [
padding: const EdgeInsets.all(16), Container(
child: Row( padding: const EdgeInsets.all(16),
children: [ height: MediaQuery.sizeOf(context).height,
Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: [
Text( Text(
"Create New Routines", "Create New Routines",
style: Theme.of(context).textTheme.titleLarge?.copyWith( style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: ColorsManager.grayColor, color: ColorsManager.grayColor,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
const SizedBox( const SizedBox(
height: 10, height: 10,
), ),
RoutineViewCard( RoutineViewCard(
onTap: () { onTap: () {
if (context.read<SpaceTreeBloc>().selectedCommunityId.isNotEmpty && if (context.read<SpaceTreeBloc>().selectedCommunityId.isNotEmpty &&
context.read<SpaceTreeBloc>().selectedSpaceId.isNotEmpty) { context.read<SpaceTreeBloc>().selectedSpaceId.isNotEmpty) {
context.read<RoutineBloc>().add( context.read<RoutineBloc>().add(
(ResetRoutineState()), (ResetRoutineState()),
); );
BlocProvider.of<RoutineBloc>(context).add( BlocProvider.of<RoutineBloc>(context).add(
const CreateNewRoutineViewEvent(createRoutineView: true), const CreateNewRoutineViewEvent(createRoutineView: true),
); );
} else { } else {
CustomSnackBar.redSnackBar('Please select a space'); CustomSnackBar.redSnackBar('Please select a space');
} }
}, },
icon: Icons.add, icon: Icons.add,
textString: '', textString: '',
), ),
const SizedBox( const SizedBox(
height: 15, height: 15,
), ),
const Expanded(child: FetchRoutineScenesAutomation()), const Expanded(child: FetchRoutineScenesAutomation()),
], ],
), ),
],
), ),
), ]),
), ),
], ],
); );

View File

@ -10,10 +10,23 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/style.dart'; import 'package:syncrow_web/utils/style.dart';
class SpaceTreeView extends StatelessWidget { class SpaceTreeView extends StatefulWidget {
final Function onSelect; final Function onSelect;
const SpaceTreeView({required this.onSelect, super.key}); const SpaceTreeView({required this.onSelect, super.key});
@override
State<SpaceTreeView> createState() => _SpaceTreeViewState();
}
class _SpaceTreeViewState extends State<SpaceTreeView> {
final ScrollController _scrollController = ScrollController();
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocBuilder<SpaceTreeBloc, SpaceTreeState>(builder: (context, state) { return BlocBuilder<SpaceTreeBloc, SpaceTreeState>(builder: (context, state) {
@ -21,7 +34,6 @@ class SpaceTreeView extends StatelessWidget {
return Container( return Container(
height: MediaQuery.sizeOf(context).height, height: MediaQuery.sizeOf(context).height,
decoration: subSectionContainerDecoration, decoration: subSectionContainerDecoration,
// padding: const EdgeInsets.all(16.0),
child: state is SpaceTreeLoadingState child: state is SpaceTreeLoadingState
? const Center(child: CircularProgressIndicator()) ? const Center(child: CircularProgressIndicator())
: Column( : Column(
@ -33,67 +45,150 @@ class SpaceTreeView extends StatelessWidget {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Expanded( Expanded(
child: Padding( child: ListView(
padding: const EdgeInsets.all(8.0), shrinkWrap: true,
child: list.isEmpty scrollDirection: Axis.horizontal,
? Center( children: [
child: Text( Container(
'No results found', width: MediaQuery.sizeOf(context).width * 0.5,
style: Theme.of(context).textTheme.bodySmall!.copyWith( padding: const EdgeInsets.all(8.0),
color: ColorsManager.lightGrayColor, // Gray when not selected child: list.isEmpty
fontWeight: FontWeight.w400, ? Center(
child: Text(
'No results found',
style: Theme.of(context).textTheme.bodySmall!.copyWith(
color: ColorsManager.lightGrayColor,
fontWeight: FontWeight.w400,
),
),
)
: Scrollbar(
scrollbarOrientation: ScrollbarOrientation.left,
thumbVisibility: true,
controller: _scrollController,
child: Padding(
padding: const EdgeInsets.only(left: 16),
child: ListView(
controller: _scrollController,
shrinkWrap: true,
children: list
.map(
(community) => CustomExpansionTileSpaceTree(
title: community.name,
isSelected: state.selectedCommunities
.contains(community.uuid),
isSoldCheck: state.selectedCommunities
.contains(community.uuid),
onExpansionChanged: () {
context
.read<SpaceTreeBloc>()
.add(OnCommunityExpanded(community.uuid));
},
isExpanded: state.expandedCommunities
.contains(community.uuid),
onItemSelected: () {
context.read<SpaceTreeBloc>().add(
OnCommunitySelected(
community.uuid, community.spaces));
widget.onSelect();
},
children: community.spaces.map((space) {
return CustomExpansionTileSpaceTree(
title: space.name,
isExpanded:
state.expandedSpaces.contains(space.uuid),
onItemSelected: () {
context.read<SpaceTreeBloc>().add(
OnSpaceSelected(community.uuid,
space.uuid ?? '', space.children));
widget.onSelect();
},
onExpansionChanged: () {
context.read<SpaceTreeBloc>().add(
OnSpaceExpanded(
community.uuid, space.uuid ?? ''));
},
isSelected:
state.selectedSpaces.contains(space.uuid) ||
state.soldCheck.contains(space.uuid),
isSoldCheck: state.soldCheck.contains(space.uuid),
children: _buildNestedSpaces(
context, state, space, community.uuid),
);
}).toList(),
),
)
.toList(),
), ),
), ),
) ),
: ListView( ),
shrinkWrap: true, ],
children: list
.map(
(community) => CustomExpansionTileSpaceTree(
title: community.name,
isSelected:
state.selectedCommunities.contains(community.uuid),
isSoldCheck:
state.selectedCommunities.contains(community.uuid),
onExpansionChanged: () {
context
.read<SpaceTreeBloc>()
.add(OnCommunityExpanded(community.uuid));
},
isExpanded:
state.expandedCommunities.contains(community.uuid),
onItemSelected: () {
context.read<SpaceTreeBloc>().add(
OnCommunitySelected(community.uuid, community.spaces));
onSelect();
},
children: community.spaces.map((space) {
return CustomExpansionTileSpaceTree(
title: space.name,
isExpanded: state.expandedSpaces.contains(space.uuid),
onItemSelected: () {
context.read<SpaceTreeBloc>().add(OnSpaceSelected(
community.uuid, space.uuid ?? '', space.children));
onSelect();
},
onExpansionChanged: () {
context.read<SpaceTreeBloc>().add(
OnSpaceExpanded(community.uuid, space.uuid ?? ''));
},
isSelected: state.selectedSpaces.contains(space.uuid) ||
state.soldCheck.contains(space.uuid),
isSoldCheck: state.soldCheck.contains(space.uuid),
children: _buildNestedSpaces(
context, state, space, community.uuid),
);
}).toList(),
),
)
.toList(),
),
), ),
), ),
// Expanded(
// child: Padding(
// padding: const EdgeInsets.all(8.0),
// child: list.isEmpty
// ? Center(
// child: Text(
// 'No results found',
// style: Theme.of(context).textTheme.bodySmall!.copyWith(
// color: ColorsManager.lightGrayColor, // Gray when not selected
// fontWeight: FontWeight.w400,
// ),
// ),
// )
// : ListView(
// shrinkWrap: true,
// children: list
// .map(
// (community) => CustomExpansionTileSpaceTree(
// title: community.name,
// isSelected:
// state.selectedCommunities.contains(community.uuid),
// isSoldCheck:
// state.selectedCommunities.contains(community.uuid),
// onExpansionChanged: () {
// context
// .read<SpaceTreeBloc>()
// .add(OnCommunityExpanded(community.uuid));
// },
// isExpanded:
// state.expandedCommunities.contains(community.uuid),
// onItemSelected: () {
// context.read<SpaceTreeBloc>().add(
// OnCommunitySelected(community.uuid, community.spaces));
// onSelect();
// },
// children: community.spaces.map((space) {
// return CustomExpansionTileSpaceTree(
// title: space.name,
// isExpanded: state.expandedSpaces.contains(space.uuid),
// onItemSelected: () {
// context.read<SpaceTreeBloc>().add(OnSpaceSelected(
// community.uuid, space.uuid ?? '', space.children));
// onSelect();
// },
// onExpansionChanged: () {
// context.read<SpaceTreeBloc>().add(
// OnSpaceExpanded(community.uuid, space.uuid ?? ''));
// },
// isSelected: state.selectedSpaces.contains(space.uuid) ||
// state.soldCheck.contains(space.uuid),
// isSoldCheck: state.soldCheck.contains(space.uuid),
// children: _buildNestedSpaces(
// context, state, space, community.uuid),
// );
// }).toList(),
// ),
// )
// .toList(),
// ),
// ),
// ),
], ],
), ),
); );
@ -113,7 +208,7 @@ class SpaceTreeView extends StatelessWidget {
context context
.read<SpaceTreeBloc>() .read<SpaceTreeBloc>()
.add(OnSpaceSelected(communityId, child.uuid ?? '', child.children)); .add(OnSpaceSelected(communityId, child.uuid ?? '', child.children));
onSelect(); widget.onSelect();
}, },
onExpansionChanged: () { onExpansionChanged: () {
context.read<SpaceTreeBloc>().add(OnSpaceExpanded(communityId, child.uuid ?? '')); context.read<SpaceTreeBloc>().add(OnSpaceExpanded(communityId, child.uuid ?? ''));

View File

@ -42,20 +42,29 @@ class _LoadedSpaceViewState extends State<LoadedSpaceView> {
_spaceModels = List.from(widget.spaceModels ?? []); _spaceModels = List.from(widget.spaceModels ?? []);
} }
@override
@override @override
void didUpdateWidget(covariant LoadedSpaceView oldWidget) { void didUpdateWidget(covariant LoadedSpaceView oldWidget) {
super.didUpdateWidget(oldWidget); super.didUpdateWidget(oldWidget);
if (widget.spaceModels != oldWidget.spaceModels) { if (widget.spaceModels != oldWidget.spaceModels) {
setState(() { WidgetsBinding.instance.addPostFrameCallback((_) {
_spaceModels = List.from(widget.spaceModels ?? []); if (mounted) {
setState(() {
_spaceModels = List.from(widget.spaceModels ?? []);
});
}
}); });
} }
} }
void _onSpaceModelsUpdated(List<SpaceTemplateModel> updatedModels) { void _onSpaceModelsUpdated(List<SpaceTemplateModel> updatedModels) {
if (mounted && updatedModels != _spaceModels) { if (mounted && updatedModels != _spaceModels) {
setState(() { WidgetsBinding.instance.addPostFrameCallback((_) {
_spaceModels = updatedModels; if (mounted) {
setState(() {
_spaceModels = updatedModels;
});
}
}); });
} }
} }

View File

@ -4,7 +4,9 @@ import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_e
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart';
class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> { class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
AssignTagBloc() : super(AssignTagInitial()) { final List<String> allTags;
AssignTagBloc(this.allTags) : super(AssignTagInitial()) {
on<InitializeTags>((event, emit) { on<InitializeTags>((event, emit) {
final initialTags = event.initialTags ?? []; final initialTags = event.initialTags ?? [];
@ -16,25 +18,25 @@ class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
} }
} }
final allTags = <Tag>[]; final tags = <Tag>[];
for (var selectedProduct in event.addedProducts) { for (var selectedProduct in event.addedProducts) {
final existingCount = existingTagCounts[selectedProduct.productId] ?? 0; final existingCount = existingTagCounts[selectedProduct.productId] ?? 0;
if (selectedProduct.count == 0 || if (selectedProduct.count == 0 ||
selectedProduct.count <= existingCount) { selectedProduct.count <= existingCount) {
allTags.addAll(initialTags tags.addAll(initialTags
.where((tag) => tag.product?.uuid == selectedProduct.productId)); .where((tag) => tag.product?.uuid == selectedProduct.productId));
continue; continue;
} }
final missingCount = selectedProduct.count - existingCount; final missingCount = selectedProduct.count - existingCount;
allTags.addAll(initialTags tags.addAll(initialTags
.where((tag) => tag.product?.uuid == selectedProduct.productId)); .where((tag) => tag.product?.uuid == selectedProduct.productId));
if (missingCount > 0) { if (missingCount > 0) {
allTags.addAll(List.generate( tags.addAll(List.generate(
missingCount, missingCount,
(index) => Tag( (index) => Tag(
tag: '', tag: '',
@ -45,10 +47,14 @@ class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
} }
} }
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagLoaded( emit(AssignTagLoaded(
tags: allTags, tags: tags,
isSaveEnabled: _validateTags(allTags), updatedTags: updatedTags,
errorMessage: '')); isSaveEnabled: _validateTags(tags),
errorMessage: '',
));
}); });
on<UpdateTagEvent>((event, emit) { on<UpdateTagEvent>((event, emit) {
@ -56,10 +62,13 @@ class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) { if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) {
final tags = List<Tag>.from(currentState.tags); final tags = List<Tag>.from(currentState.tags);
tags[event.index].tag = event.tag; tags[event.index] = tags[event.index].copyWith(tag: event.tag);
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagLoaded( emit(AssignTagLoaded(
tags: tags, tags: tags,
updatedTags: updatedTags,
isSaveEnabled: _validateTags(tags), isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags), errorMessage: _getValidationError(tags),
)); ));
@ -72,12 +81,15 @@ class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) { if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) {
final tags = List<Tag>.from(currentState.tags); final tags = List<Tag>.from(currentState.tags);
// Use copyWith for immutability // Update the location
tags[event.index] = tags[event.index] =
tags[event.index].copyWith(location: event.location); tags[event.index].copyWith(location: event.location);
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagLoaded( emit(AssignTagLoaded(
tags: tags, tags: tags,
updatedTags: updatedTags,
isSaveEnabled: _validateTags(tags), isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags), errorMessage: _getValidationError(tags),
)); ));
@ -92,6 +104,7 @@ class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
emit(AssignTagLoaded( emit(AssignTagLoaded(
tags: tags, tags: tags,
updatedTags: _calculateAvailableTags(allTags, tags),
isSaveEnabled: _validateTags(tags), isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags), errorMessage: _getValidationError(tags),
)); ));
@ -102,38 +115,37 @@ class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
final currentState = state; final currentState = state;
if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) { if (currentState is AssignTagLoaded && currentState.tags.isNotEmpty) {
final updatedTags = List<Tag>.from(currentState.tags) final tags = List<Tag>.from(currentState.tags)
..remove(event.tagToDelete); ..remove(event.tagToDelete);
// Recalculate available tags
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagLoaded( emit(AssignTagLoaded(
tags: updatedTags, tags: tags,
isSaveEnabled: _validateTags(updatedTags), updatedTags: updatedTags,
errorMessage: _getValidationError(updatedTags), isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags),
)); ));
} else {
emit(const AssignTagLoaded(
tags: [],
isSaveEnabled: false,
errorMessage: 'Failed to delete tag'));
} }
}); });
} }
// Validate the tags for duplicates or empty values
bool _validateTags(List<Tag> tags) { bool _validateTags(List<Tag> tags) {
final uniqueTags = tags.map((tag) => tag.tag?.trim() ?? '').toSet(); final uniqueTags = tags.map((tag) => tag.tag?.trim() ?? '').toSet();
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty); final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty);
final isValid = uniqueTags.length == tags.length && !hasEmptyTag; return uniqueTags.length == tags.length && !hasEmptyTag;
return isValid;
} }
// Get validation error for duplicate tags
String? _getValidationError(List<Tag> tags) { String? _getValidationError(List<Tag> tags) {
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty); final nonEmptyTags = tags
if (hasEmptyTag) {
return 'Tags cannot be empty.';
}
final duplicateTags = tags
.map((tag) => tag.tag?.trim() ?? '') .map((tag) => tag.tag?.trim() ?? '')
.where((tag) => tag.isNotEmpty)
.toList();
final duplicateTags = nonEmptyTags
.fold<Map<String, int>>({}, (map, tag) { .fold<Map<String, int>>({}, (map, tag) {
map[tag] = (map[tag] ?? 0) + 1; map[tag] = (map[tag] ?? 0) + 1;
return map; return map;
@ -149,4 +161,15 @@ class AssignTagBloc extends Bloc<AssignTagEvent, AssignTagState> {
return null; return null;
} }
List<String> _calculateAvailableTags(List<String> allTags, List<Tag> tags) {
final selectedTags = tags
.where((tag) => (tag.tag?.trim().isNotEmpty ?? false))
.map((tag) => tag.tag!.trim())
.toSet();
final availableTags =
allTags.where((tag) => !selectedTags.contains(tag.trim())).toList();
return availableTags;
}
} }

View File

@ -1,6 +1,5 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model.dart';
abstract class AssignTagState extends Equatable { abstract class AssignTagState extends Equatable {
const AssignTagState(); const AssignTagState();
@ -15,17 +14,21 @@ class AssignTagLoading extends AssignTagState {}
class AssignTagLoaded extends AssignTagState { class AssignTagLoaded extends AssignTagState {
final List<Tag> tags; final List<Tag> tags;
final List<String> updatedTags;
final bool isSaveEnabled; final bool isSaveEnabled;
final String? errorMessage; final String? errorMessage;
const AssignTagLoaded({ const AssignTagLoaded({
required this.tags, required this.tags,
required this.isSaveEnabled, required this.isSaveEnabled,
required this.updatedTags,
required this.errorMessage, required this.errorMessage,
}); });
@override @override
List<Object> get props => [tags, isSaveEnabled, errorMessage ?? '']; List<Object> get props =>
[tags, updatedTags, isSaveEnabled, errorMessage ?? ''];
} }
class AssignTagError extends AssignTagState { class AssignTagError extends AssignTagState {

View File

@ -14,6 +14,7 @@ import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_e
import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart'; import 'package:syncrow_web/pages/spaces_management/assign_tag/bloc/assign_tag_state.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart'; import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:uuid/uuid.dart';
class AssignTagDialog extends StatelessWidget { class AssignTagDialog extends StatelessWidget {
final List<ProductModel>? products; final List<ProductModel>? products;
@ -47,7 +48,7 @@ class AssignTagDialog extends StatelessWidget {
..add('Main Space'); ..add('Main Space');
return BlocProvider( return BlocProvider(
create: (_) => AssignTagBloc() create: (_) => AssignTagBloc(allTags ?? [])
..add(InitializeTags( ..add(InitializeTags(
initialTags: initialTags, initialTags: initialTags,
addedProducts: addedProducts, addedProducts: addedProducts,
@ -119,8 +120,6 @@ class AssignTagDialog extends StatelessWidget {
: List.generate(state.tags.length, (index) { : List.generate(state.tags.length, (index) {
final tag = state.tags[index]; final tag = state.tags[index];
final controller = controllers[index]; final controller = controllers[index];
final availableTags = getAvailableTags(
allTags ?? [], state.tags, tag);
return DataRow( return DataRow(
cells: [ cells: [
@ -180,7 +179,9 @@ class AssignTagDialog extends StatelessWidget {
width: double width: double
.infinity, // Ensure full width for dropdown .infinity, // Ensure full width for dropdown
child: DialogTextfieldDropdown( child: DialogTextfieldDropdown(
items: availableTags, key: ValueKey(
'dropdown_${Uuid().v4()}_${index}'),
items: state.updatedTags,
initialValue: tag.tag, initialValue: tag.tag,
onSelected: (value) { onSelected: (value) {
controller.text = value; controller.text = value;
@ -306,15 +307,4 @@ class AssignTagDialog extends StatelessWidget {
), ),
); );
} }
List<String> getAvailableTags(
List<String> allTags, List<Tag> currentTags, Tag currentTag) {
List<String> availableTagsForTagModel = TagHelper.getAvailableTags<Tag>(
allTags: allTags,
currentTags: currentTags,
currentTag: currentTag,
getTag: (tag) => tag.tag ?? '',
);
return availableTagsForTagModel;
}
} }

View File

@ -5,7 +5,9 @@ import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model
class AssignTagModelBloc class AssignTagModelBloc
extends Bloc<AssignTagModelEvent, AssignTagModelState> { extends Bloc<AssignTagModelEvent, AssignTagModelState> {
AssignTagModelBloc() : super(AssignTagModelInitial()) { final List<String> allTags;
AssignTagModelBloc(this.allTags) : super(AssignTagModelInitial()) {
on<InitializeTagModels>((event, emit) { on<InitializeTagModels>((event, emit) {
final initialTags = event.initialTags ?? []; final initialTags = event.initialTags ?? [];
@ -17,25 +19,25 @@ class AssignTagModelBloc
} }
} }
final allTags = <TagModel>[]; final tags = <TagModel>[];
for (var selectedProduct in event.addedProducts) { for (var selectedProduct in event.addedProducts) {
final existingCount = existingTagCounts[selectedProduct.productId] ?? 0; final existingCount = existingTagCounts[selectedProduct.productId] ?? 0;
if (selectedProduct.count == 0 || if (selectedProduct.count == 0 ||
selectedProduct.count <= existingCount) { selectedProduct.count <= existingCount) {
allTags.addAll(initialTags tags.addAll(initialTags
.where((tag) => tag.product?.uuid == selectedProduct.productId)); .where((tag) => tag.product?.uuid == selectedProduct.productId));
continue; continue;
} }
final missingCount = selectedProduct.count - existingCount; final missingCount = selectedProduct.count - existingCount;
allTags.addAll(initialTags tags.addAll(initialTags
.where((tag) => tag.product?.uuid == selectedProduct.productId)); .where((tag) => tag.product?.uuid == selectedProduct.productId));
if (missingCount > 0) { if (missingCount > 0) {
allTags.addAll(List.generate( tags.addAll(List.generate(
missingCount, missingCount,
(index) => TagModel( (index) => TagModel(
tag: '', tag: '',
@ -46,9 +48,12 @@ class AssignTagModelBloc
} }
} }
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagModelLoaded( emit(AssignTagModelLoaded(
tags: allTags, tags: tags,
isSaveEnabled: _validateTags(allTags), updatedTags: updatedTags,
isSaveEnabled: _validateTags(tags),
errorMessage: '')); errorMessage: ''));
}); });
@ -57,9 +62,12 @@ class AssignTagModelBloc
if (currentState is AssignTagModelLoaded && if (currentState is AssignTagModelLoaded &&
currentState.tags.isNotEmpty) { currentState.tags.isNotEmpty) {
final tags = List<TagModel>.from(currentState.tags); final tags = List<TagModel>.from(currentState.tags);
tags[event.index].tag = event.tag; tags[event.index] = tags[event.index].copyWith(tag: event.tag);
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagModelLoaded( emit(AssignTagModelLoaded(
tags: tags, tags: tags,
updatedTags: updatedTags,
isSaveEnabled: _validateTags(tags), isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags), errorMessage: _getValidationError(tags),
)); ));
@ -77,9 +85,13 @@ class AssignTagModelBloc
tags[event.index] = tags[event.index] =
tags[event.index].copyWith(location: event.location); tags[event.index].copyWith(location: event.location);
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagModelLoaded( emit(AssignTagModelLoaded(
tags: tags, tags: tags,
updatedTags: updatedTags,
isSaveEnabled: _validateTags(tags), isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags),
)); ));
} }
}); });
@ -93,6 +105,7 @@ class AssignTagModelBloc
emit(AssignTagModelLoaded( emit(AssignTagModelLoaded(
tags: tags, tags: tags,
updatedTags: _calculateAvailableTags(allTags, tags),
isSaveEnabled: _validateTags(tags), isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags), errorMessage: _getValidationError(tags),
)); ));
@ -104,24 +117,22 @@ class AssignTagModelBloc
if (currentState is AssignTagModelLoaded && if (currentState is AssignTagModelLoaded &&
currentState.tags.isNotEmpty) { currentState.tags.isNotEmpty) {
final updatedTags = List<TagModel>.from(currentState.tags) final tags = List<TagModel>.from(currentState.tags)
..remove(event.tagToDelete); ..remove(event.tagToDelete);
final updatedTags = _calculateAvailableTags(allTags, tags);
emit(AssignTagModelLoaded( emit(AssignTagModelLoaded(
tags: updatedTags, tags: tags,
isSaveEnabled: _validateTags(updatedTags), updatedTags: updatedTags,
isSaveEnabled: _validateTags(tags),
errorMessage: _getValidationError(tags),
)); ));
} else { }
emit(const AssignTagModelLoaded(
tags: [],
isSaveEnabled: false,
));
}
}); });
} }
bool _validateTags(List<TagModel> tags) { bool _validateTags(List<TagModel> tags) {
final uniqueTags = tags.map((tag) => tag.tag?.trim() ?? '').toSet(); final uniqueTags = tags.map((tag) => tag.tag?.trim() ?? '').toSet();
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty); final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty);
final isValid = uniqueTags.length == tags.length && !hasEmptyTag; final isValid = uniqueTags.length == tags.length && !hasEmptyTag;
@ -129,14 +140,14 @@ class AssignTagModelBloc
} }
String? _getValidationError(List<TagModel> tags) { String? _getValidationError(List<TagModel> tags) {
final hasEmptyTag = tags.any((tag) => (tag.tag?.trim() ?? '').isEmpty);
if (hasEmptyTag) {
return 'Tags cannot be empty.';
}
// Check for duplicate tags // Check for duplicate tags
final duplicateTags = tags
final nonEmptyTags = tags
.map((tag) => tag.tag?.trim() ?? '') .map((tag) => tag.tag?.trim() ?? '')
.where((tag) => tag.isNotEmpty)
.toList();
final duplicateTags = nonEmptyTags
.fold<Map<String, int>>({}, (map, tag) { .fold<Map<String, int>>({}, (map, tag) {
map[tag] = (map[tag] ?? 0) + 1; map[tag] = (map[tag] ?? 0) + 1;
return map; return map;
@ -152,4 +163,16 @@ class AssignTagModelBloc
return null; return null;
} }
List<String> _calculateAvailableTags(
List<String> allTags, List<TagModel> tags) {
final selectedTags = tags
.where((tag) => (tag.tag?.trim().isNotEmpty ?? false))
.map((tag) => tag.tag!.trim())
.toSet();
final availableTags =
allTags.where((tag) => !selectedTags.contains(tag.trim())).toList();
return availableTags;
}
} }

View File

@ -17,14 +17,17 @@ class AssignTagModelLoaded extends AssignTagModelState {
final bool isSaveEnabled; final bool isSaveEnabled;
final String? errorMessage; final String? errorMessage;
final List<String> updatedTags;
const AssignTagModelLoaded({ const AssignTagModelLoaded({
required this.tags, required this.tags,
required this.isSaveEnabled, required this.isSaveEnabled,
required this.updatedTags,
this.errorMessage, this.errorMessage,
}); });
@override @override
List<Object?> get props => [tags, isSaveEnabled, errorMessage]; List<Object?> get props => [tags, updatedTags, isSaveEnabled, errorMessage];
} }
class AssignTagModelError extends AssignTagModelState { class AssignTagModelError extends AssignTagModelState {

View File

@ -16,6 +16,7 @@ import 'package:syncrow_web/pages/spaces_management/space_model/widgets/dialog/c
import 'package:syncrow_web/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart'; import 'package:syncrow_web/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart'; import 'package:syncrow_web/pages/spaces_management/helper/tag_helper.dart';
import 'package:uuid/uuid.dart';
class AssignTagModelsDialog extends StatelessWidget { class AssignTagModelsDialog extends StatelessWidget {
final List<ProductModel>? products; final List<ProductModel>? products;
@ -56,7 +57,7 @@ class AssignTagModelsDialog extends StatelessWidget {
..add('Main Space'); ..add('Main Space');
return BlocProvider( return BlocProvider(
create: (_) => AssignTagModelBloc() create: (_) => AssignTagModelBloc(allTags ?? [])
..add(InitializeTagModels( ..add(InitializeTagModels(
initialTags: initialTags, initialTags: initialTags,
addedProducts: addedProducts, addedProducts: addedProducts,
@ -134,9 +135,6 @@ class AssignTagModelsDialog extends StatelessWidget {
: List.generate(state.tags.length, (index) { : List.generate(state.tags.length, (index) {
final tag = state.tags[index]; final tag = state.tags[index];
final controller = controllers[index]; final controller = controllers[index];
final availableTags =
TagHelper.getAvailableTagModels(
allTags ?? [], state.tags, tag);
return DataRow( return DataRow(
cells: [ cells: [
@ -196,7 +194,9 @@ class AssignTagModelsDialog extends StatelessWidget {
width: double width: double
.infinity, // Ensure full width for dropdown .infinity, // Ensure full width for dropdown
child: DialogTextfieldDropdown( child: DialogTextfieldDropdown(
items: availableTags, key: ValueKey(
'dropdown_${Uuid().v4()}_${index}'),
items: state.updatedTags,
initialValue: tag.tag, initialValue: tag.tag,
onSelected: (value) { onSelected: (value) {
controller.text = value; controller.text = value;

View File

@ -299,7 +299,7 @@ class TagHelper {
static Map<String, dynamic> updateSubspaceTagModels( static Map<String, dynamic> updateSubspaceTagModels(
List<TagModel> updatedTags, List<SubspaceTemplateModel>? subspaces) { List<TagModel> updatedTags, List<SubspaceTemplateModel>? subspaces) {
return TagHelper.updateTags<TagModel>( final result = TagHelper.updateTags<TagModel>(
updatedTags: updatedTags, updatedTags: updatedTags,
subspaces: subspaces, subspaces: subspaces,
getInternalId: (tag) => tag.internalId, getInternalId: (tag) => tag.internalId,
@ -310,6 +310,34 @@ class TagHelper {
setSubspaceTags: (subspace, tags) => subspace.tags = tags, setSubspaceTags: (subspace, tags) => subspace.tags = tags,
checkTagExistInSubspace: checkTagExistInSubspaceModels, checkTagExistInSubspace: checkTagExistInSubspaceModels,
); );
final processedTags = result['updatedTags'] as List<TagModel>;
final processedSubspaces =
List<SubspaceTemplateModel>.from(result['subspaces'] as List<dynamic>);
for (var subspace in processedSubspaces) {
final subspaceTags = subspace.tags;
if (subspaceTags != null) {
for (int i = 0; i < subspaceTags.length; i++) {
final tag = subspaceTags[i];
// Find the updated tag inside processedTags
final changedTag = updatedTags.firstWhere(
(t) => t.internalId == tag.internalId,
orElse: () => tag,
);
if (changedTag.tag != tag.tag) {
subspaceTags[i] = changedTag.copyWith(tag: changedTag.tag);
}
}
}
subspace.tags = subspaceTags;
}
return {'updatedTags': processedTags, 'subspaces': processedSubspaces};
} }
static int? checkTagExistInSubspace(Tag tag, List<dynamic>? subspaces) { static int? checkTagExistInSubspace(Tag tag, List<dynamic>? subspaces) {
@ -328,7 +356,7 @@ class TagHelper {
static Map<String, dynamic> processTags( static Map<String, dynamic> processTags(
List<Tag> updatedTags, List<SubspaceModel>? subspaces) { List<Tag> updatedTags, List<SubspaceModel>? subspaces) {
return TagHelper.updateTags<Tag>( final result = TagHelper.updateTags<Tag>(
updatedTags: updatedTags, updatedTags: updatedTags,
subspaces: subspaces, subspaces: subspaces,
getInternalId: (tag) => tag.internalId, getInternalId: (tag) => tag.internalId,
@ -339,6 +367,33 @@ class TagHelper {
setSubspaceTags: (subspace, tags) => subspace.tags = tags, setSubspaceTags: (subspace, tags) => subspace.tags = tags,
checkTagExistInSubspace: checkTagExistInSubspace, checkTagExistInSubspace: checkTagExistInSubspace,
); );
final processedTags = result['updatedTags'] as List<Tag>;
final processedSubspaces =
List<SubspaceModel>.from(result['subspaces'] as List<dynamic>);
for (var subspace in processedSubspaces) {
final subspaceTags = subspace.tags;
if (subspaceTags != null) {
for (int i = 0; i < subspaceTags.length; i++) {
final tag = subspaceTags[i];
final changedTag = updatedTags.firstWhere(
(t) => t.internalId == tag.internalId,
orElse: () => tag,
);
if (changedTag.tag != tag.tag) {
subspaceTags[i] = changedTag.copyWith(tag: changedTag.tag);
}
}
}
subspace.tags = subspaceTags;
}
return {'updatedTags': processedTags, 'subspaces': processedSubspaces};
} }
static List<String> getAllTagValues( static List<String> getAllTagValues(

View File

@ -130,14 +130,14 @@ class CreateSpaceModelDialog extends StatelessWidget {
SubspaceModelCreate( SubspaceModelCreate(
subspaces: state.space.subspaceModels ?? [], subspaces: state.space.subspaceModels ?? [],
tags: state.space.tags ?? [], tags: state.space.tags ?? [],
onSpaceModelUpdate: (updatedSubspaces,updatedTags) { onSpaceModelUpdate: (updatedSubspaces, updatedTags) {
context context
.read<CreateSpaceModelBloc>() .read<CreateSpaceModelBloc>()
.add(AddSubspacesToSpaceTemplate(updatedSubspaces)); .add(AddSubspacesToSpaceTemplate(updatedSubspaces));
if(updatedTags!=null){ if (updatedTags != null) {
context context
.read<CreateSpaceModelBloc>() .read<CreateSpaceModelBloc>()
.add(AddTagsToSpaceTemplate(updatedTags)); .add(AddTagsToSpaceTemplate(updatedTags));
} }
}, },
), ),

View File

@ -34,9 +34,8 @@ class UserPermissionApi {
path: ApiEndpoints.roleTypes, path: ApiEndpoints.roleTypes,
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
final List<RoleTypeModel> fetchedRoles = (json['data'] as List) final List<RoleTypeModel> fetchedRoles =
.map((item) => RoleTypeModel.fromJson(item)) (json['data'] as List).map((item) => RoleTypeModel.fromJson(item)).toList();
.toList();
return fetchedRoles; return fetchedRoles;
}, },
); );
@ -48,9 +47,7 @@ class UserPermissionApi {
path: ApiEndpoints.permission.replaceAll("roleUuid", roleUuid), path: ApiEndpoints.permission.replaceAll("roleUuid", roleUuid),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
return (json as List) return (json as List).map((data) => PermissionOption.fromJson(data)).toList();
.map((data) => PermissionOption.fromJson(data))
.toList();
}, },
); );
return response ?? []; return response ?? [];
@ -88,7 +85,6 @@ class UserPermissionApi {
} }
}, },
); );
print('sendInviteUser=$body');
return response ?? []; return response ?? [];
} on DioException catch (e) { } on DioException catch (e) {
@ -196,12 +192,9 @@ class UserPermissionApi {
"disable": status, "disable": status,
"projectUuid": "0e62577c-06fa-41b9-8a92-99a21fbaf51c" "projectUuid": "0e62577c-06fa-41b9-8a92-99a21fbaf51c"
}; };
print('changeUserStatusById==$bodya');
print('changeUserStatusById==$userUuid');
final response = await _httpService.put( final response = await _httpService.put(
path: ApiEndpoints.changeUserStatus path: ApiEndpoints.changeUserStatus.replaceAll("{invitedUserUuid}", userUuid),
.replaceAll("{invitedUserUuid}", userUuid),
body: bodya, body: bodya,
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json['success']; return json['success'];