Compare commits

..

22 Commits

Author SHA1 Message Date
e634154fb3 fixed device endpoint 2025-02-20 13:31:31 +04:00
c0f59aba61 Merge pull request #98 from SyncrowIOT:SP-1186-FE-Cursor-Resets-After-Each-Character-When-Creating-a-Tag
fixed text theme of tag list
2025-02-20 11:48:36 +04:00
7ee7681e09 fixed theme 2025-02-20 11:47:58 +04:00
57c5f4752c fixed theme 2025-02-20 11:36:08 +04:00
ad4f2ae382 Merge pull request #96 from SyncrowIOT/SP-1186-FE-Cursor-Resets-After-Each-Character-When-Creating-a-Tag
fixed cursor issue
2025-02-20 11:29:03 +04:00
eafb811d2e fixed cursor issue 2025-02-20 11:26:30 +04:00
2d0dcc41df Merge pull request #93 from SyncrowIOT/bugfix/fix-get-user-endpoint
change endpoint
2025-02-19 17:54:19 +04:00
d89e3fac8e change endpoint 2025-02-19 17:53:20 +04:00
25acd67351 Bug fixes in the side tree 2025-02-19 02:13:14 +03:00
0c2a092f4d Added side tree to space model 2025-02-18 12:31:43 +03:00
b968b5a6eb Merge pull request #92 from SyncrowIOT/bugfix/change-project-cubit
Bugfix/change-project-cubit
2025-02-18 13:22:12 +04:00
05edc7641a removed project cubit from all classes 2025-02-18 12:56:51 +04:00
b8204f1015 changed project class to use shared preference 2025-02-18 12:56:25 +04:00
d87fec796b Merge pull request #91 from SyncrowIOT/add_space_name
spaceName
2025-02-17 12:56:47 +03:00
b00b0c82dc spaceName 2025-02-17 12:36:04 +03:00
0aa029a2fc Removed static space id and community id in the routine 2025-02-17 03:32:40 +03:00
dec3a25639 Merge pull request #90 from SyncrowIOT/feat/use-project-uuid-instead-of-hardcode
Feat/use project UUID instead of hardcode
2025-02-17 01:11:53 +03:00
581dcf7016 changed endpoint for get visitor password and access control 2025-02-16 23:32:46 +04:00
e1609309cf Added ProjectCubit as a dependency in blocs for managing project-level state. 2025-02-15 00:36:20 +04:00
da445e11aa Modified _fetchUserInfo to update the ProjectCubit with the retrieved user's project UUID. 2025-02-15 00:35:34 +04:00
55de7fab0f Introduced ProjectCubit to handle project-related state. 2025-02-15 00:34:38 +04:00
a623f1c723 Merge pull request #89 from SyncrowIOT/disable_edit
disable_edit_user
2025-02-06 11:17:14 +03:00
49 changed files with 946 additions and 493 deletions

View File

@ -20,15 +20,22 @@ class DialogTextfieldDropdown extends StatefulWidget {
class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> { class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
bool _isOpen = false; bool _isOpen = false;
late OverlayEntry _overlayEntry; OverlayEntry? _overlayEntry;
final TextEditingController _controller = TextEditingController(); final TextEditingController _controller = TextEditingController();
late List<String> _filteredItems; // Filtered items list final FocusNode _focusNode = FocusNode();
List<String> _filteredItems = [];
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_controller.text = widget.initialValue ?? 'Select Tag'; _controller.text = widget.initialValue ?? '';
_filteredItems = List.from(widget.items); // Initialize filtered items _filteredItems = List.from(widget.items);
_focusNode.addListener(() {
if (!_focusNode.hasFocus) {
_closeDropdown();
}
});
} }
void _toggleDropdown() { void _toggleDropdown() {
@ -41,14 +48,17 @@ class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
void _openDropdown() { void _openDropdown() {
_overlayEntry = _createOverlayEntry(); _overlayEntry = _createOverlayEntry();
Overlay.of(context).insert(_overlayEntry); Overlay.of(context).insert(_overlayEntry!);
_isOpen = true; _isOpen = true;
} }
void _closeDropdown() { void _closeDropdown() {
_overlayEntry.remove(); if (_isOpen && _overlayEntry != null) {
_overlayEntry!.remove();
_overlayEntry = null;
_isOpen = false; _isOpen = false;
} }
}
OverlayEntry _createOverlayEntry() { OverlayEntry _createOverlayEntry() {
final renderBox = context.findRenderObject() as RenderBox; final renderBox = context.findRenderObject() as RenderBox;
@ -58,9 +68,7 @@ class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
return OverlayEntry( return OverlayEntry(
builder: (context) { builder: (context) {
return GestureDetector( return GestureDetector(
onTap: () { onTap: _closeDropdown,
_closeDropdown();
},
behavior: HitTestBehavior.translucent, behavior: HitTestBehavior.translucent,
child: Stack( child: Stack(
children: [ children: [
@ -72,14 +80,15 @@ class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
elevation: 4.0, elevation: 4.0,
child: Container( child: Container(
color: ColorsManager.whiteColors, color: ColorsManager.whiteColors,
constraints: const BoxConstraints( constraints: const BoxConstraints(maxHeight: 200.0),
maxHeight: 200.0, child: StatefulBuilder(
), builder: (context, setStateDropdown) {
child: ListView.builder( return ListView.builder(
shrinkWrap: true, shrinkWrap: true,
itemCount: _filteredItems.length, itemCount: _filteredItems.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final item = _filteredItems[index]; final item = _filteredItems[index];
return Container( return Container(
decoration: const BoxDecoration( decoration: const BoxDecoration(
border: Border( border: Border(
@ -95,7 +104,8 @@ class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
.textTheme .textTheme
.bodyMedium .bodyMedium
?.copyWith( ?.copyWith(
color: ColorsManager.textPrimaryColor)), color: ColorsManager
.textPrimaryColor)),
onTap: () { onTap: () {
_controller.text = item; _controller.text = item;
widget.onSelected(item); widget.onSelected(item);
@ -108,6 +118,8 @@ class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
), ),
); );
}, },
);
},
), ),
), ),
), ),
@ -122,7 +134,8 @@ class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return GestureDetector( return GestureDetector(
onTap: _toggleDropdown, onTap: () => FocusScope.of(context).unfocus(),
behavior: HitTestBehavior.opaque,
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
decoration: BoxDecoration( decoration: BoxDecoration(
@ -135,23 +148,26 @@ class _DialogTextfieldDropdownState extends State<DialogTextfieldDropdown> {
Expanded( Expanded(
child: TextFormField( child: TextFormField(
controller: _controller, controller: _controller,
onChanged: (value) { focusNode: _focusNode,
setState(() { onFieldSubmitted: (value) {
_filteredItems = widget.items
.where((item) =>
item.toLowerCase().contains(value.toLowerCase()))
.toList(); // Filter items dynamically
});
widget.onSelected(value); widget.onSelected(value);
_closeDropdown();
},
onTapOutside: (event) {
widget.onSelected(_controller.text);
_closeDropdown();
}, },
style: Theme.of(context).textTheme.bodyMedium, style: Theme.of(context).textTheme.bodyMedium,
decoration: const InputDecoration( decoration: const InputDecoration(
hintText: 'Enter or Select tag', hintText: 'Enter or Select a tag',
border: InputBorder.none, border: InputBorder.none,
), ),
), ),
), ),
const Icon(Icons.arrow_drop_down), GestureDetector(
onTap: _toggleDropdown,
child: const Icon(Icons.arrow_drop_down),
),
], ],
), ),
), ),

View File

@ -3,18 +3,33 @@ import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
class CustomSearchBar extends StatelessWidget { class CustomSearchBar extends StatefulWidget {
final TextEditingController? controller; final TextEditingController? controller;
final String hintText; final String hintText;
final String? searchQuery;
final Function(String)? onSearchChanged; // Callback for search input changes final Function(String)? onSearchChanged; // Callback for search input changes
const CustomSearchBar({ const CustomSearchBar({
super.key, super.key,
this.controller, this.controller,
this.searchQuery = '',
this.hintText = 'Search', this.hintText = 'Search',
this.onSearchChanged, this.onSearchChanged,
}); });
@override
State<CustomSearchBar> createState() => _CustomSearchBarState();
}
class _CustomSearchBarState extends State<CustomSearchBar> {
@override
void dispose() {
if (widget.controller != null) {
widget.controller!.dispose();
}
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Container( return Container(
@ -36,16 +51,17 @@ class CustomSearchBar extends StatelessWidget {
decoration: BoxDecoration( decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
child: TextField( child: TextFormField(
controller: controller, controller: widget.controller,
initialValue: widget.searchQuery,
style: const TextStyle( style: const TextStyle(
color: Colors.black, color: Colors.black,
), ),
onChanged: onSearchChanged, // Call the callback on text change onChanged: widget.onSearchChanged, // Call the callback on text change
decoration: InputDecoration( decoration: InputDecoration(
filled: true, filled: true,
fillColor: ColorsManager.textFieldGreyColor, fillColor: ColorsManager.textFieldGreyColor,
hintText: hintText, hintText: widget.hintText,
hintStyle: Theme.of(context).textTheme.bodyLarge!.copyWith( hintStyle: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: ColorsManager.lightGrayColor, color: ColorsManager.lightGrayColor,
fontSize: 12, fontSize: 12,

View File

@ -1,25 +0,0 @@
import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
class SpacesSideTree extends StatefulWidget {
final List<CommunityModel> communities;
final String? selectedSpaceUuid;
const SpacesSideTree({
super.key,
required this.communities,
this.selectedSpaceUuid,
});
@override
State<SpacesSideTree> createState() => _SpacesSideTreeState();
}
class _SpacesSideTreeState extends State<SpacesSideTree> {
String _searchQuery = '';
String? _selectedSpaceUuid;
String? _selectedId;
@override
Widget build(BuildContext context) {
return const Placeholder();
}
}

View File

@ -13,6 +13,7 @@ import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.da
import 'package:syncrow_web/services/locator.dart'; import 'package:syncrow_web/services/locator.dart';
import 'package:syncrow_web/utils/app_routes.dart'; import 'package:syncrow_web/utils/app_routes.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart'; import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:syncrow_web/utils/navigation_service.dart';
import 'package:syncrow_web/utils/theme/theme.dart'; import 'package:syncrow_web/utils/theme/theme.dart';
Future<void> main() async { Future<void> main() async {
@ -26,9 +27,8 @@ Future<void> main() async {
} }
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
MyApp({
super.key, MyApp({super.key});
});
final GoRouter _router = GoRouter( final GoRouter _router = GoRouter(
initialLocation: RoutesConst.auth, initialLocation: RoutesConst.auth,
@ -70,6 +70,8 @@ class MyApp extends StatelessWidget {
PointerDeviceKind.unknown, PointerDeviceKind.unknown,
}, },
), ),
key: NavigationService.navigatorKey,
// scaffoldMessengerKey: NavigationService.snackbarKey,
theme: myTheme, theme: myTheme,
routerConfig: _router, routerConfig: _router,
)); ));

View File

@ -3,10 +3,14 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_event.dart'; import 'package:syncrow_web/pages/access_management/bloc/access_event.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_state.dart'; import 'package:syncrow_web/pages/access_management/bloc/access_state.dart';
import 'package:syncrow_web/pages/access_management/model/password_model.dart'; import 'package:syncrow_web/pages/access_management/model/password_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/hour_picker_dialog.dart'; import 'package:syncrow_web/pages/common/hour_picker_dialog.dart';
import 'package:syncrow_web/services/access_mang_api.dart'; import 'package:syncrow_web/services/access_mang_api.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/app_enum.dart'; import 'package:syncrow_web/utils/constants/app_enum.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
import 'package:syncrow_web/utils/snack_bar.dart'; import 'package:syncrow_web/utils/snack_bar.dart';
class AccessBloc extends Bloc<AccessEvent, AccessState> { class AccessBloc extends Bloc<AccessEvent, AccessState> {
@ -30,8 +34,9 @@ class AccessBloc extends Bloc<AccessEvent, AccessState> {
Future<void> _onFetchTableData( Future<void> _onFetchTableData(
FetchTableData event, Emitter<AccessState> emit) async { FetchTableData event, Emitter<AccessState> emit) async {
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
emit(AccessLoaded()); emit(AccessLoaded());
data = await AccessMangApi().fetchVisitorPassword(); data = await AccessMangApi().fetchVisitorPassword(projectUuid);
filteredData = data; filteredData = data;
updateTabsCount(); updateTabsCount();
emit(TableLoaded(data)); emit(TableLoaded(data));

View File

@ -3,6 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_bloc.dart'; import 'package:syncrow_web/pages/access_management/bloc/access_bloc.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_event.dart'; import 'package:syncrow_web/pages/access_management/bloc/access_event.dart';
import 'package:syncrow_web/pages/access_management/bloc/access_state.dart'; import 'package:syncrow_web/pages/access_management/bloc/access_state.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/common/buttons/search_reset_buttons.dart'; import 'package:syncrow_web/pages/common/buttons/search_reset_buttons.dart';
import 'package:syncrow_web/pages/common/custom_table.dart'; import 'package:syncrow_web/pages/common/custom_table.dart';
@ -27,7 +28,8 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
final isLargeScreen = isLargeScreenSize(context); final isLargeScreen = isLargeScreenSize(context);
final isSmallScreen = isSmallScreenSize(context); final isSmallScreen = isSmallScreenSize(context);
final isHalfMediumScreen = isHafMediumScreenSize(context); final isHalfMediumScreen = isHafMediumScreenSize(context);
final padding = isLargeScreen ? const EdgeInsets.all(30) : const EdgeInsets.all(15); final padding =
isLargeScreen ? const EdgeInsets.all(30) : const EdgeInsets.all(15);
return WebScaffold( return WebScaffold(
enableMenuSidebar: false, enableMenuSidebar: false,
@ -39,7 +41,8 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
), ),
rightBody: const NavigateHomeGridView(), rightBody: const NavigateHomeGridView(),
scaffoldBody: BlocProvider( scaffoldBody: BlocProvider(
create: (BuildContext context) => AccessBloc()..add(FetchTableData()), create: (BuildContext context) =>
AccessBloc()..add(FetchTableData()),
child: BlocConsumer<AccessBloc, AccessState>( child: BlocConsumer<AccessBloc, AccessState>(
listener: (context, state) {}, listener: (context, state) {},
builder: (context, state) { builder: (context, state) {
@ -93,11 +96,14 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
return [ return [
item.passwordName, item.passwordName,
item.passwordType.value, item.passwordType.value,
accessBloc.timestampToDate(item.effectiveTime), accessBloc
accessBloc.timestampToDate(item.invalidTime), .timestampToDate(item.effectiveTime),
accessBloc
.timestampToDate(item.invalidTime),
item.deviceName.toString(), item.deviceName.toString(),
item.authorizerEmail.toString(), item.authorizerEmail.toString(),
accessBloc.timestampToDate(item.invalidTime), accessBloc
.timestampToDate(item.invalidTime),
item.passwordStatus.value, item.passwordStatus.value,
]; ];
}).toList(), }).toList(),
@ -108,7 +114,8 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
}))); })));
} }
Wrap _buildVisitorAdminPasswords(BuildContext context, AccessBloc accessBloc) { Wrap _buildVisitorAdminPasswords(
BuildContext context, AccessBloc accessBloc) {
return Wrap( return Wrap(
spacing: 10, spacing: 10,
runSpacing: 10, runSpacing: 10,
@ -134,7 +141,8 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
borderRadius: 8, borderRadius: 8,
child: Text( child: Text(
'Create Visitor Password ', 'Create Visitor Password ',
style: context.textTheme.titleSmall!.copyWith(color: Colors.white, fontSize: 12), style: context.textTheme.titleSmall!
.copyWith(color: Colors.white, fontSize: 12),
)), )),
), ),
// Container( // Container(
@ -172,8 +180,10 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
description: '', description: '',
onSubmitted: (value) { onSubmitted: (value) {
accessBloc.add(FilterDataEvent( accessBloc.add(FilterDataEvent(
emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(), emailAuthorizer:
selectedTabIndex: BlocProvider.of<AccessBloc>(context).selectedIndex, accessBloc.emailAuthorizer.text.toLowerCase(),
selectedTabIndex:
BlocProvider.of<AccessBloc>(context).selectedIndex,
passwordName: accessBloc.passwordName.text.toLowerCase(), passwordName: accessBloc.passwordName.text.toLowerCase(),
startTime: accessBloc.effectiveTimeTimeStamp, startTime: accessBloc.effectiveTimeTimeStamp,
endTime: accessBloc.expirationTimeTimeStamp)); endTime: accessBloc.expirationTimeTimeStamp));
@ -191,8 +201,10 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
description: '', description: '',
onSubmitted: (value) { onSubmitted: (value) {
accessBloc.add(FilterDataEvent( accessBloc.add(FilterDataEvent(
emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(), emailAuthorizer:
selectedTabIndex: BlocProvider.of<AccessBloc>(context).selectedIndex, accessBloc.emailAuthorizer.text.toLowerCase(),
selectedTabIndex:
BlocProvider.of<AccessBloc>(context).selectedIndex,
passwordName: accessBloc.passwordName.text.toLowerCase(), passwordName: accessBloc.passwordName.text.toLowerCase(),
startTime: accessBloc.effectiveTimeTimeStamp, startTime: accessBloc.effectiveTimeTimeStamp,
endTime: accessBloc.expirationTimeTimeStamp)); endTime: accessBloc.expirationTimeTimeStamp));
@ -221,7 +233,8 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
onSearch: () { onSearch: () {
accessBloc.add(FilterDataEvent( accessBloc.add(FilterDataEvent(
emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(), emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(),
selectedTabIndex: BlocProvider.of<AccessBloc>(context).selectedIndex, selectedTabIndex:
BlocProvider.of<AccessBloc>(context).selectedIndex,
passwordName: accessBloc.passwordName.text.toLowerCase(), passwordName: accessBloc.passwordName.text.toLowerCase(),
startTime: accessBloc.effectiveTimeTimeStamp, startTime: accessBloc.effectiveTimeTimeStamp,
endTime: accessBloc.expirationTimeTimeStamp)); endTime: accessBloc.expirationTimeTimeStamp));
@ -249,8 +262,10 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
description: '', description: '',
onSubmitted: (value) { onSubmitted: (value) {
accessBloc.add(FilterDataEvent( accessBloc.add(FilterDataEvent(
emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(), emailAuthorizer:
selectedTabIndex: BlocProvider.of<AccessBloc>(context).selectedIndex, accessBloc.emailAuthorizer.text.toLowerCase(),
selectedTabIndex:
BlocProvider.of<AccessBloc>(context).selectedIndex,
passwordName: accessBloc.passwordName.text.toLowerCase(), passwordName: accessBloc.passwordName.text.toLowerCase(),
startTime: accessBloc.effectiveTimeTimeStamp, startTime: accessBloc.effectiveTimeTimeStamp,
endTime: accessBloc.expirationTimeTimeStamp)); endTime: accessBloc.expirationTimeTimeStamp));
@ -274,7 +289,8 @@ class AccessManagementPage extends StatelessWidget with HelperResponsiveLayout {
onSearch: () { onSearch: () {
accessBloc.add(FilterDataEvent( accessBloc.add(FilterDataEvent(
emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(), emailAuthorizer: accessBloc.emailAuthorizer.text.toLowerCase(),
selectedTabIndex: BlocProvider.of<AccessBloc>(context).selectedIndex, selectedTabIndex:
BlocProvider.of<AccessBloc>(context).selectedIndex,
passwordName: accessBloc.passwordName.text.toLowerCase(), passwordName: accessBloc.passwordName.text.toLowerCase(),
startTime: accessBloc.effectiveTimeTimeStamp, startTime: accessBloc.effectiveTimeTimeStamp,
endTime: accessBloc.expirationTimeTimeStamp)); endTime: accessBloc.expirationTimeTimeStamp));

View File

@ -9,6 +9,7 @@ import 'package:syncrow_web/pages/auth/model/login_with_email_model.dart';
import 'package:syncrow_web/pages/auth/model/region_model.dart'; import 'package:syncrow_web/pages/auth/model/region_model.dart';
import 'package:syncrow_web/pages/auth/model/token.dart'; import 'package:syncrow_web/pages/auth/model/token.dart';
import 'package:syncrow_web/pages/auth/model/user_model.dart'; import 'package:syncrow_web/pages/auth/model/user_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/services/auth_api.dart'; import 'package:syncrow_web/services/auth_api.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart'; import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart'; import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
@ -180,7 +181,6 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
return; return;
} }
if (token.accessTokenIsNotEmpty) { if (token.accessTokenIsNotEmpty) {
FlutterSecureStorage storage = const FlutterSecureStorage(); FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.write( await storage.write(
@ -442,8 +442,9 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
emit(LoginInitial()); emit(LoginInitial());
} }
static logout() { static Future<void> logout(BuildContext context) async {
const storage = FlutterSecureStorage(); final storage = FlutterSecureStorage();
ProjectManager.clearProjectUUID();
storage.deleteAll(); storage.deleteAll();
} }
} }

View File

@ -0,0 +1,27 @@
class Project {
final String uuid;
final String name;
final String description;
const Project({
required this.uuid,
required this.name,
required this.description,
});
factory Project.fromJson(Map<String, dynamic> json) {
return Project(
uuid: json['uuid'] as String,
name: json['name'] as String,
description: json['description'] as String,
);
}
Map<String, dynamic> toJson() {
return {
'uuid': uuid,
'name': name,
'description': description,
};
}
}

View File

@ -1,3 +1,4 @@
import 'package:syncrow_web/pages/auth/model/project_model.dart';
import 'package:syncrow_web/pages/auth/model/token.dart'; import 'package:syncrow_web/pages/auth/model/token.dart';
class UserModel { class UserModel {
@ -13,6 +14,7 @@ class UserModel {
final bool? hasAcceptedWebAgreement; final bool? hasAcceptedWebAgreement;
final DateTime? webAgreementAcceptedAt; final DateTime? webAgreementAcceptedAt;
final UserRole? role; final UserRole? role;
final Project? project;
UserModel({ UserModel({
required this.uuid, required this.uuid,
@ -26,6 +28,7 @@ class UserModel {
required this.hasAcceptedWebAgreement, required this.hasAcceptedWebAgreement,
required this.webAgreementAcceptedAt, required this.webAgreementAcceptedAt,
required this.role, required this.role,
required this.project,
}); });
factory UserModel.fromJson(Map<String, dynamic> json) { factory UserModel.fromJson(Map<String, dynamic> json) {
@ -43,6 +46,8 @@ class UserModel {
? DateTime.parse(json['webAgreementAcceptedAt']) ? DateTime.parse(json['webAgreementAcceptedAt'])
: null, : null,
role: json['role'] != null ? UserRole.fromJson(json['role']) : null, role: json['role'] != null ? UserRole.fromJson(json['role']) : null,
project:
json['project'] != null ? Project.fromJson(json['project']) : null,
); );
} }
@ -64,6 +69,7 @@ class UserModel {
phoneNumber: null, phoneNumber: null,
isEmailVerified: null, isEmailVerified: null,
isAgreementAccepted: null, isAgreementAccepted: null,
project: null
); );
} }

View File

@ -0,0 +1,19 @@
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
class ProjectManager {
static Future<String?> getProjectUUID() async {
final projectUuid = await SharedPreferencesHelper.readStringFromSP(
StringsManager.projectKey);
return projectUuid.isNotEmpty ? projectUuid : null;
}
static Future<void> setProjectUUID(String newUUID) async {
await SharedPreferencesHelper.saveStringToSP(
StringsManager.projectKey, newUUID);
}
static Future<void> clearProjectUUID() async {
await SharedPreferencesHelper.removeValueFromSP(StringsManager.projectKey);
}
}

View File

@ -1,14 +1,19 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/services/devices_mang_api.dart'; import 'package:syncrow_web/services/devices_mang_api.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
part 'device_managment_event.dart'; part 'device_managment_event.dart';
part 'device_managment_state.dart'; part 'device_managment_state.dart';
class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementState> { class DeviceManagementBloc
extends Bloc<DeviceManagementEvent, DeviceManagementState> {
int _selectedIndex = 0; int _selectedIndex = 0;
List<AllDevicesModel> _devices = []; List<AllDevicesModel> _devices = [];
int _onlineCount = 0; int _onlineCount = 0;
@ -31,19 +36,25 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
on<UpdateSelection>(_onUpdateSelection); on<UpdateSelection>(_onUpdateSelection);
} }
Future<void> _onFetchDevices(FetchDevices event, Emitter<DeviceManagementState> emit) async { Future<void> _onFetchDevices(
FetchDevices event, Emitter<DeviceManagementState> emit) async {
emit(DeviceManagementLoading()); emit(DeviceManagementLoading());
try { try {
List<AllDevicesModel> devices = []; List<AllDevicesModel> devices = [];
_devices.clear(); _devices.clear();
var spaceBloc = event.context.read<SpaceTreeBloc>(); var spaceBloc = event.context.read<SpaceTreeBloc>();
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
if (spaceBloc.state.selectedCommunities.isEmpty) { if (spaceBloc.state.selectedCommunities.isEmpty) {
devices = await DevicesManagementApi().fetchDevices('', ''); devices = await DevicesManagementApi()
.fetchDevices('', '', projectUuid );
} else { } else {
for (var community in spaceBloc.state.selectedCommunities) { for (var community in spaceBloc.state.selectedCommunities) {
List<String> spacesList = spaceBloc.state.selectedCommunityAndSpaces[community] ?? []; List<String> spacesList =
spaceBloc.state.selectedCommunityAndSpaces[community] ?? [];
for (var space in spacesList) { for (var space in spacesList) {
devices.addAll(await DevicesManagementApi().fetchDevices(community, space)); devices.addAll(await DevicesManagementApi().fetchDevices(
community, space, projectUuid));
} }
} }
} }
@ -66,7 +77,8 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
} }
} }
void _onFilterDevices(FilterDevices event, Emitter<DeviceManagementState> emit) async { void _onFilterDevices(
FilterDevices event, Emitter<DeviceManagementState> emit) async {
if (_devices.isNotEmpty) { if (_devices.isNotEmpty) {
_filteredDevices = List.from(_devices.where((device) { _filteredDevices = List.from(_devices.where((device) {
switch (event.filter) { switch (event.filter) {
@ -97,7 +109,8 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
} }
} }
Future<void> _onResetFilters(ResetFilters event, Emitter<DeviceManagementState> emit) async { Future<void> _onResetFilters(
ResetFilters event, Emitter<DeviceManagementState> emit) async {
currentProductName = ''; currentProductName = '';
_selectedDevices.clear(); _selectedDevices.clear();
_filteredDevices = List.from(_devices); _filteredDevices = List.from(_devices);
@ -113,7 +126,8 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
)); ));
} }
void _onResetSelectedDevices(ResetSelectedDevices event, Emitter<DeviceManagementState> emit) { void _onResetSelectedDevices(
ResetSelectedDevices event, Emitter<DeviceManagementState> emit) {
_selectedDevices.clear(); _selectedDevices.clear();
if (state is DeviceManagementLoaded) { if (state is DeviceManagementLoaded) {
@ -139,12 +153,14 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
} }
} }
void _onSelectedFilterChanged(SelectedFilterChanged event, Emitter<DeviceManagementState> emit) { void _onSelectedFilterChanged(
SelectedFilterChanged event, Emitter<DeviceManagementState> emit) {
_selectedIndex = event.selectedIndex; _selectedIndex = event.selectedIndex;
add(FilterDevices(_getFilterFromIndex(_selectedIndex))); add(FilterDevices(_getFilterFromIndex(_selectedIndex)));
} }
void _onSelectDevice(SelectDevice event, Emitter<DeviceManagementState> emit) { void _onSelectDevice(
SelectDevice event, Emitter<DeviceManagementState> emit) {
final selectedUuid = event.selectedDevice.uuid; final selectedUuid = event.selectedDevice.uuid;
if (_selectedDevices.any((device) => device.uuid == selectedUuid)) { if (_selectedDevices.any((device) => device.uuid == selectedUuid)) {
@ -155,7 +171,8 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
List<AllDevicesModel> clonedSelectedDevices = List.from(_selectedDevices); List<AllDevicesModel> clonedSelectedDevices = List.from(_selectedDevices);
bool isControlButtonEnabled = _checkIfControlButtonEnabled(clonedSelectedDevices); bool isControlButtonEnabled =
_checkIfControlButtonEnabled(clonedSelectedDevices);
if (state is DeviceManagementLoaded) { if (state is DeviceManagementLoaded) {
emit(DeviceManagementLoaded( emit(DeviceManagementLoaded(
@ -164,7 +181,8 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
onlineCount: _onlineCount, onlineCount: _onlineCount,
offlineCount: _offlineCount, offlineCount: _offlineCount,
lowBatteryCount: _lowBatteryCount, lowBatteryCount: _lowBatteryCount,
selectedDevice: clonedSelectedDevices.isNotEmpty ? clonedSelectedDevices : null, selectedDevice:
clonedSelectedDevices.isNotEmpty ? clonedSelectedDevices : null,
isControlButtonEnabled: isControlButtonEnabled, isControlButtonEnabled: isControlButtonEnabled,
)); ));
} else if (state is DeviceManagementFiltered) { } else if (state is DeviceManagementFiltered) {
@ -174,13 +192,15 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
onlineCount: _onlineCount, onlineCount: _onlineCount,
offlineCount: _offlineCount, offlineCount: _offlineCount,
lowBatteryCount: _lowBatteryCount, lowBatteryCount: _lowBatteryCount,
selectedDevice: clonedSelectedDevices.isNotEmpty ? clonedSelectedDevices : null, selectedDevice:
clonedSelectedDevices.isNotEmpty ? clonedSelectedDevices : null,
isControlButtonEnabled: isControlButtonEnabled, isControlButtonEnabled: isControlButtonEnabled,
)); ));
} }
} }
void _onUpdateSelection(UpdateSelection event, Emitter<DeviceManagementState> emit) { void _onUpdateSelection(
UpdateSelection event, Emitter<DeviceManagementState> emit) {
List<AllDevicesModel> selectedDevices = []; List<AllDevicesModel> selectedDevices = [];
List<AllDevicesModel> devicesToSelectFrom = []; List<AllDevicesModel> devicesToSelectFrom = [];
@ -223,7 +243,8 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
bool _checkIfControlButtonEnabled(List<AllDevicesModel> selectedDevices) { bool _checkIfControlButtonEnabled(List<AllDevicesModel> selectedDevices) {
if (selectedDevices.length > 1) { if (selectedDevices.length > 1) {
final productTypes = selectedDevices.map((device) => device.productType).toSet(); final productTypes =
selectedDevices.map((device) => device.productType).toSet();
return productTypes.length == 1; return productTypes.length == 1;
} else if (selectedDevices.length == 1) { } else if (selectedDevices.length == 1) {
return true; return true;
@ -234,8 +255,10 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
void _calculateDeviceCounts() { void _calculateDeviceCounts() {
_onlineCount = _devices.where((device) => device.online == true).length; _onlineCount = _devices.where((device) => device.online == true).length;
_offlineCount = _devices.where((device) => device.online == false).length; _offlineCount = _devices.where((device) => device.online == false).length;
_lowBatteryCount = _lowBatteryCount = _devices
_devices.where((device) => device.batteryLevel != null && device.batteryLevel! < 20).length; .where((device) =>
device.batteryLevel != null && device.batteryLevel! < 20)
.length;
} }
String _getFilterFromIndex(int index) { String _getFilterFromIndex(int index) {
@ -251,7 +274,8 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
} }
} }
void _onSearchDevices(SearchDevices event, Emitter<DeviceManagementState> emit) { void _onSearchDevices(
SearchDevices event, Emitter<DeviceManagementState> emit) {
if ((event.community == null || event.community!.isEmpty) && if ((event.community == null || event.community!.isEmpty) &&
(event.unitName == null || event.unitName!.isEmpty) && (event.unitName == null || event.unitName!.isEmpty) &&
(event.productName == null || event.productName!.isEmpty)) { (event.productName == null || event.productName!.isEmpty)) {
@ -280,22 +304,33 @@ class DeviceManagementBloc extends Bloc<DeviceManagementEvent, DeviceManagementS
final filteredDevices = devicesToSearch.where((device) { final filteredDevices = devicesToSearch.where((device) {
final matchesCommunity = event.community == null || final matchesCommunity = event.community == null ||
event.community!.isEmpty || event.community!.isEmpty ||
(device.community?.name?.toLowerCase().contains(event.community!.toLowerCase()) ?? (device.community?.name
?.toLowerCase()
.contains(event.community!.toLowerCase()) ??
false); false);
final matchesUnit = event.unitName == null || final matchesUnit = event.unitName == null ||
event.unitName!.isEmpty || event.unitName!.isEmpty ||
(device.spaces != null && (device.spaces != null &&
device.spaces!.isNotEmpty && device.spaces!.isNotEmpty &&
device.spaces![0].spaceName!.toLowerCase().contains(event.unitName!.toLowerCase())); device.spaces![0].spaceName!
.toLowerCase()
.contains(event.unitName!.toLowerCase()));
final matchesProductName = event.productName == null || final matchesProductName = event.productName == null ||
event.productName!.isEmpty || event.productName!.isEmpty ||
(device.name?.toLowerCase().contains(event.productName!.toLowerCase()) ?? false); (device.name
?.toLowerCase()
.contains(event.productName!.toLowerCase()) ??
false);
final matchesDeviceName = event.productName == null || final matchesDeviceName = event.productName == null ||
event.productName!.isEmpty || event.productName!.isEmpty ||
(device.categoryName?.toLowerCase().contains(event.productName!.toLowerCase()) ?? (device.categoryName
?.toLowerCase()
.contains(event.productName!.toLowerCase()) ??
false); false);
return matchesCommunity && matchesUnit && (matchesProductName || matchesDeviceName); return matchesCommunity &&
matchesUnit &&
(matchesProductName || matchesDeviceName);
}).toList(); }).toList();
emit(DeviceManagementFiltered( emit(DeviceManagementFiltered(

View File

@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/widgets/device_managment_body.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/widgets/device_managment_body.dart';
import 'package:syncrow_web/pages/device_managment/shared/navigate_home_grid_view.dart'; import 'package:syncrow_web/pages/device_managment/shared/navigate_home_grid_view.dart';
@ -19,7 +20,8 @@ class DeviceManagementPage extends StatelessWidget with HelperResponsiveLayout {
return MultiBlocProvider( return MultiBlocProvider(
providers: [ providers: [
BlocProvider( BlocProvider(
create: (context) => DeviceManagementBloc()..add(FetchDevices(context)), create: (context) =>
DeviceManagementBloc()..add(FetchDevices(context)),
), ),
], ],
child: WebScaffold( child: WebScaffold(
@ -41,6 +43,7 @@ class DeviceManagementPage extends StatelessWidget with HelperResponsiveLayout {
context context
.read<RoutineBloc>() .read<RoutineBloc>()
.add(const TriggerSwitchTabsEvent(isRoutineTab: false)); .add(const TriggerSwitchTabsEvent(isRoutineTab: false));
context.read<DeviceManagementBloc>().add(FetchDevices(context));
}, },
child: Text( child: Text(
'Devices', 'Devices',

View File

@ -2,8 +2,10 @@ 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';
import 'package:shared_preferences/shared_preferences.dart';
// import 'package:graphview/GraphView.dart'; // import 'package:graphview/GraphView.dart';
import 'package:syncrow_web/pages/auth/model/user_model.dart'; import 'package:syncrow_web/pages/auth/model/user_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/home/bloc/home_event.dart'; import 'package:syncrow_web/pages/home/bloc/home_event.dart';
import 'package:syncrow_web/pages/home/bloc/home_state.dart'; import 'package:syncrow_web/pages/home/bloc/home_state.dart';
import 'package:syncrow_web/pages/home/home_model/home_item_model.dart'; import 'package:syncrow_web/pages/home/home_model/home_item_model.dart';
@ -12,6 +14,8 @@ import 'package:syncrow_web/services/home_api.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart'; import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> { class HomeBloc extends Bloc<HomeEvent, HomeState> {
// final Graph graph = Graph()..isTree = true; // final Graph graph = Graph()..isTree = true;
@ -51,6 +55,10 @@ class HomeBloc extends Bloc<HomeEvent, HomeState> {
var uuid = var uuid =
await const FlutterSecureStorage().read(key: UserModel.userUuidKey); await const FlutterSecureStorage().read(key: UserModel.userUuidKey);
user = await HomeApi().fetchUserInfo(uuid); user = await HomeApi().fetchUserInfo(uuid);
if (user != null && user!.project != null) {
await ProjectManager.setProjectUUID(user!.project!.uuid);
}
add(FetchTermEvent()); add(FetchTermEvent());
add(FetchPolicyEvent()); add(FetchPolicyEvent());

View File

@ -1,7 +1,9 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_html/flutter_html.dart'; import 'package:flutter_html/flutter_html.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart'; import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/routes_const.dart'; import 'package:syncrow_web/utils/constants/routes_const.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
@ -162,7 +164,7 @@ class _AgreementAndPrivacyDialogState extends State<AgreementAndPrivacyDialog> {
children: [ children: [
InkWell( InkWell(
onTap: () { onTap: () {
AuthBloc.logout(); AuthBloc.logout(context);
context.go(RoutesConst.auth); context.go(RoutesConst.auth);
}, },
child: const Text("Cancel"), child: const Text("Cancel"),

View File

@ -1,5 +1,6 @@
import 'package:bloc/bloc.dart'; import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/custom_dialog.dart'; import 'package:syncrow_web/pages/common/custom_dialog.dart';
import 'package:syncrow_web/pages/roles_and_permission/model/edit_user_model.dart'; import 'package:syncrow_web/pages/roles_and_permission/model/edit_user_model.dart';
import 'package:syncrow_web/pages/roles_and_permission/model/role_type_model.dart'; import 'package:syncrow_web/pages/roles_and_permission/model/role_type_model.dart';
@ -12,6 +13,9 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model
import 'package:syncrow_web/services/space_mana_api.dart'; import 'package:syncrow_web/services/space_mana_api.dart';
import 'package:syncrow_web/services/user_permission.dart'; import 'package:syncrow_web/services/user_permission.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
class UsersBloc extends Bloc<UsersEvent, UsersState> { class UsersBloc extends Bloc<UsersEvent, UsersState> {
UsersBloc() : super(UsersInitial()) { UsersBloc() : super(UsersInitial()) {
@ -74,7 +78,10 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
Future<List<SpaceModel>> _fetchSpacesForCommunity( Future<List<SpaceModel>> _fetchSpacesForCommunity(
String communityUuid) async { String communityUuid) async {
return await CommunitySpaceManagementApi().getSpaceHierarchy(communityUuid); final projectUuid = await ProjectManager.getProjectUUID() ?? '';
return await CommunitySpaceManagementApi()
.getSpaceHierarchy(communityUuid, projectUuid);
} }
List<TreeNode> updatedCommunities = []; List<TreeNode> updatedCommunities = [];
@ -84,8 +91,10 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
LoadCommunityAndSpacesEvent event, Emitter<UsersState> emit) async { LoadCommunityAndSpacesEvent event, Emitter<UsersState> emit) async {
try { try {
emit(UsersLoadingState()); emit(UsersLoadingState());
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
List<CommunityModel> communities = List<CommunityModel> communities =
await CommunitySpaceManagementApi().fetchCommunities(); await CommunitySpaceManagementApi().fetchCommunities(projectUuid);
communityIds = communities.map((community) => community.uuid).toList(); communityIds = communities.map((community) => community.uuid).toList();
updatedCommunities = await Future.wait( updatedCommunities = await Future.wait(
communities.map((community) async { communities.map((community) async {
@ -328,6 +337,8 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
void _sendInvitUser(SendInviteUsers event, Emitter<UsersState> emit) async { void _sendInvitUser(SendInviteUsers event, Emitter<UsersState> emit) async {
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
emit(UsersLoadingState()); emit(UsersLoadingState());
List<String> selectedIds = getSelectedIds(updatedCommunities) List<String> selectedIds = getSelectedIds(updatedCommunities)
.where((id) => !communityIds.contains(id)) .where((id) => !communityIds.contains(id))
@ -341,7 +352,7 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
phoneNumber: phoneController.text, phoneNumber: phoneController.text,
roleUuid: roleSelected, roleUuid: roleSelected,
spaceUuids: selectedIds, spaceUuids: selectedIds,
); projectUuid: projectUuid);
if (res) { if (res) {
showCustomDialog( showCustomDialog(
@ -376,6 +387,7 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
List<String> selectedIds = getSelectedIds(updatedCommunities) List<String> selectedIds = getSelectedIds(updatedCommunities)
.where((id) => !communityIds.contains(id)) .where((id) => !communityIds.contains(id))
.toList(); .toList();
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
bool res = await UserPermissionApi().editInviteUser( bool res = await UserPermissionApi().editInviteUser(
userId: event.userId, userId: event.userId,
@ -385,7 +397,7 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
phoneNumber: phoneController.text, phoneNumber: phoneController.text,
roleUuid: roleSelected, roleUuid: roleSelected,
spaceUuids: selectedIds, spaceUuids: selectedIds,
); projectUuid: projectUuid);
if (res == true) { if (res == true) {
showCustomDialog( showCustomDialog(
barrierDismissible: false, barrierDismissible: false,
@ -490,8 +502,11 @@ class UsersBloc extends Bloc<UsersEvent, UsersState> {
emit(UsersLoadingState()); emit(UsersLoadingState());
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
if (event.uuid?.isNotEmpty ?? false) { if (event.uuid?.isNotEmpty ?? false) {
final res = await UserPermissionApi().fetchUserById(event.uuid); final res =
await UserPermissionApi().fetchUserById(event.uuid, projectUuid);
if (res != null) { if (res != null) {
// Populate the text controllers // Populate the text controllers

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart';

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart';

View File

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart';

View File

@ -1,10 +1,13 @@
import 'dart:async'; import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/roles_and_permission/model/roles_user_model.dart'; import 'package:syncrow_web/pages/roles_and_permission/model/roles_user_model.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart'; import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart';
import 'package:syncrow_web/services/user_permission.dart'; import 'package:syncrow_web/services/user_permission.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
class UserTableBloc extends Bloc<UserTableEvent, UserTableState> { class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
UserTableBloc() : super(TableInitial()) { UserTableBloc() : super(TableInitial()) {
@ -46,10 +49,12 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
Future<void> _getUsers(GetUsers event, Emitter<UserTableState> emit) async { Future<void> _getUsers(GetUsers event, Emitter<UserTableState> emit) async {
emit(UsersLoadingState()); emit(UsersLoadingState());
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
roleTypes.clear(); roleTypes.clear();
jobTitle.clear(); jobTitle.clear();
createdBy.clear(); createdBy.clear();
users = await UserPermissionApi().fetchUsers(); users = await UserPermissionApi().fetchUsers(projectUuid);
users.sort((a, b) { users.sort((a, b) {
final dateA = _parseDateTime(a.createdDate); final dateA = _parseDateTime(a.createdDate);
final dateB = _parseDateTime(b.createdDate); final dateB = _parseDateTime(b.createdDate);
@ -96,9 +101,11 @@ class UserTableBloc extends Bloc<UserTableEvent, UserTableState> {
Future<void> _changeUserStatus( Future<void> _changeUserStatus(
ChangeUserStatus event, Emitter<UserTableState> emit) async { ChangeUserStatus event, Emitter<UserTableState> emit) async {
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
emit(UsersLoadingState()); emit(UsersLoadingState());
bool res = await UserPermissionApi().changeUserStatusById( bool res = await UserPermissionApi().changeUserStatusById(event.userId,
event.userId, event.newStatus == "disabled" ? false : true); event.newStatus == "disabled" ? false : true, projectUuid);
if (res == true) { if (res == true) {
add(const GetUsers()); add(const GetUsers());
} }

View File

@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/device_managment/shared/navigate_home_grid_view.dart'; import 'package:syncrow_web/pages/device_managment/shared/navigate_home_grid_view.dart';
import 'package:syncrow_web/pages/roles_and_permission/bloc/roles_permission_bloc.dart'; import 'package:syncrow_web/pages/roles_and_permission/bloc/roles_permission_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/bloc/roles_permission_state.dart'; import 'package:syncrow_web/pages/roles_and_permission/bloc/roles_permission_state.dart';

View File

@ -3,6 +3,8 @@ import 'dart:async';
import 'package:bloc/bloc.dart'; import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart'; import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/routines/models/create_scene_and_autoamtion/create_automation_model.dart'; import 'package:syncrow_web/pages/routines/models/create_scene_and_autoamtion/create_automation_model.dart';
import 'package:syncrow_web/pages/routines/models/create_scene_and_autoamtion/create_scene_model.dart'; import 'package:syncrow_web/pages/routines/models/create_scene_and_autoamtion/create_scene_model.dart';
@ -10,17 +12,22 @@ import 'package:syncrow_web/pages/routines/models/delay/delay_fucntions.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart'; import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/routine_details_model.dart'; import 'package:syncrow_web/pages/routines/models/routine_details_model.dart';
import 'package:syncrow_web/pages/routines/models/routine_model.dart'; import 'package:syncrow_web/pages/routines/models/routine_model.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/services/devices_mang_api.dart'; import 'package:syncrow_web/services/devices_mang_api.dart';
import 'package:syncrow_web/services/routines_api.dart'; import 'package:syncrow_web/services/routines_api.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
import 'package:syncrow_web/utils/navigation_service.dart';
import 'package:syncrow_web/utils/snack_bar.dart'; import 'package:syncrow_web/utils/snack_bar.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
part 'routine_event.dart'; part 'routine_event.dart';
part 'routine_state.dart'; part 'routine_state.dart';
String spaceId = '25c96044-fadf-44bb-93c7-3c079e527ce6'; // String spaceId = '25c96044-fadf-44bb-93c7-3c079e527ce6';
String communityId = 'aff21a57-2f91-4e5c-b99b-0182c3ab65a9'; // String communityId = 'aff21a57-2f91-4e5c-b99b-0182c3ab65a9';
class RoutineBloc extends Bloc<RoutineEvent, RoutineState> { class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
RoutineBloc() : super(const RoutineState()) { RoutineBloc() : super(const RoutineState()) {
@ -54,11 +61,12 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
TriggerSwitchTabsEvent event, TriggerSwitchTabsEvent event,
Emitter<RoutineState> emit, Emitter<RoutineState> emit,
) { ) {
emit(state.copyWith(routineTab: event.isRoutineTab, createRoutineView: false)); emit(state.copyWith(
routineTab: event.isRoutineTab, createRoutineView: false));
add(ResetRoutineState()); add(ResetRoutineState());
if (event.isRoutineTab) { if (event.isRoutineTab) {
add(LoadScenes(spaceId, communityId)); add(const LoadScenes());
add(LoadAutomation(spaceId)); add(const LoadAutomation());
} }
} }
@ -80,8 +88,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
final updatedIfItems = List<Map<String, dynamic>>.from(state.ifItems); final updatedIfItems = List<Map<String, dynamic>>.from(state.ifItems);
// Find the index of the item in teh current itemsList // Find the index of the item in teh current itemsList
int index = int index = updatedIfItems.indexWhere(
updatedIfItems.indexWhere((map) => map['uniqueCustomId'] == event.item['uniqueCustomId']); (map) => map['uniqueCustomId'] == event.item['uniqueCustomId']);
// Replace the map if the index is valid // Replace the map if the index is valid
if (index != -1) { if (index != -1) {
updatedIfItems[index] = event.item; updatedIfItems[index] = event.item;
@ -90,18 +98,21 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
if (event.isTabToRun) { if (event.isTabToRun) {
emit(state.copyWith(ifItems: updatedIfItems, isTabToRun: true, isAutomation: false)); emit(state.copyWith(
ifItems: updatedIfItems, isTabToRun: true, isAutomation: false));
} else { } else {
emit(state.copyWith(ifItems: updatedIfItems, isTabToRun: false, isAutomation: true)); emit(state.copyWith(
ifItems: updatedIfItems, isTabToRun: false, isAutomation: true));
} }
} }
void _onAddToThenContainer(AddToThenContainer event, Emitter<RoutineState> emit) { void _onAddToThenContainer(
AddToThenContainer event, Emitter<RoutineState> emit) {
final currentItems = List<Map<String, dynamic>>.from(state.thenItems); final currentItems = List<Map<String, dynamic>>.from(state.thenItems);
// Find the index of the item in teh current itemsList // Find the index of the item in teh current itemsList
int index = int index = currentItems.indexWhere(
currentItems.indexWhere((map) => map['uniqueCustomId'] == event.item['uniqueCustomId']); (map) => map['uniqueCustomId'] == event.item['uniqueCustomId']);
// Replace the map if the index is valid // Replace the map if the index is valid
if (index != -1) { if (index != -1) {
currentItems[index] = event.item; currentItems[index] = event.item;
@ -112,22 +123,26 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
emit(state.copyWith(thenItems: currentItems)); emit(state.copyWith(thenItems: currentItems));
} }
void _onAddFunctionsToRoutine(AddFunctionToRoutine event, Emitter<RoutineState> emit) { void _onAddFunctionsToRoutine(
AddFunctionToRoutine event, Emitter<RoutineState> emit) {
try { try {
if (event.functions.isEmpty) return; if (event.functions.isEmpty) return;
List<DeviceFunctionData> selectedFunction = List<DeviceFunctionData>.from(event.functions); List<DeviceFunctionData> selectedFunction =
List<DeviceFunctionData>.from(event.functions);
Map<String, List<DeviceFunctionData>> currentSelectedFunctions = Map<String, List<DeviceFunctionData>> currentSelectedFunctions =
Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions); Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions);
if (currentSelectedFunctions.containsKey(event.uniqueCustomId)) { if (currentSelectedFunctions.containsKey(event.uniqueCustomId)) {
List<DeviceFunctionData> currentFunctions = List<DeviceFunctionData> currentFunctions =
List<DeviceFunctionData>.from(currentSelectedFunctions[event.uniqueCustomId] ?? []); List<DeviceFunctionData>.from(
currentSelectedFunctions[event.uniqueCustomId] ?? []);
List<String> functionCode = []; List<String> functionCode = [];
for (int i = 0; i < selectedFunction.length; i++) { for (int i = 0; i < selectedFunction.length; i++) {
for (int j = 0; j < currentFunctions.length; j++) { for (int j = 0; j < currentFunctions.length; j++) {
if (selectedFunction[i].functionCode == currentFunctions[j].functionCode) { if (selectedFunction[i].functionCode ==
currentFunctions[j].functionCode) {
currentFunctions[j] = selectedFunction[i]; currentFunctions[j] = selectedFunction[i];
if (!functionCode.contains(currentFunctions[j].functionCode)) { if (!functionCode.contains(currentFunctions[j].functionCode)) {
functionCode.add(currentFunctions[j].functionCode); functionCode.add(currentFunctions[j].functionCode);
@ -137,13 +152,15 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
for (int i = 0; i < functionCode.length; i++) { for (int i = 0; i < functionCode.length; i++) {
selectedFunction.removeWhere((code) => code.functionCode == functionCode[i]); selectedFunction
.removeWhere((code) => code.functionCode == functionCode[i]);
} }
currentSelectedFunctions[event.uniqueCustomId] = List.from(currentFunctions) currentSelectedFunctions[event.uniqueCustomId] =
..addAll(selectedFunction); List.from(currentFunctions)..addAll(selectedFunction);
} else { } else {
currentSelectedFunctions[event.uniqueCustomId] = List.from(event.functions); currentSelectedFunctions[event.uniqueCustomId] =
List.from(event.functions);
} }
emit(state.copyWith(selectedFunctions: currentSelectedFunctions)); emit(state.copyWith(selectedFunctions: currentSelectedFunctions));
@ -152,18 +169,24 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
} }
Future<void> _onLoadScenes(LoadScenes event, Emitter<RoutineState> emit) async { Future<void> _onLoadScenes(
LoadScenes event, Emitter<RoutineState> emit) async {
emit(state.copyWith(isLoading: true, errorMessage: null)); emit(state.copyWith(isLoading: true, errorMessage: null));
try {
spaceId = event.spaceId;
communityId = event.communityId;
List<ScenesModel> scenes = []; List<ScenesModel> scenes = [];
try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
if (communityId.isNotEmpty && spaceId.isNotEmpty) { BuildContext context = NavigationService.navigatorKey.currentContext!;
scenes = await SceneApi.getScenes(event.spaceId, event.communityId); var spaceBloc = context.read<SpaceTreeBloc>();
for (var communityId in spaceBloc.state.selectedCommunities) {
List<String> spacesList =
spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? [];
for (var spaceId in spacesList) {
scenes.addAll(
await SceneApi.getScenes(spaceId, communityId, projectUuid));
} }
}
emit(state.copyWith( emit(state.copyWith(
scenes: scenes, scenes: scenes,
isLoading: false, isLoading: false,
@ -174,18 +197,24 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
loadScenesErrorMessage: 'Failed to load scenes', loadScenesErrorMessage: 'Failed to load scenes',
errorMessage: '', errorMessage: '',
loadAutomationErrorMessage: '', loadAutomationErrorMessage: '',
scenes: [])); scenes: scenes));
} }
} }
Future<void> _onLoadAutomation(LoadAutomation event, Emitter<RoutineState> emit) async { Future<void> _onLoadAutomation(
LoadAutomation event, Emitter<RoutineState> emit) async {
emit(state.copyWith(isLoading: true, errorMessage: null)); emit(state.copyWith(isLoading: true, errorMessage: null));
List<ScenesModel> automations = [];
try { try {
spaceId = event.spaceId; BuildContext context = NavigationService.navigatorKey.currentContext!;
List<ScenesModel> automations = []; var spaceBloc = context.read<SpaceTreeBloc>();
if (spaceId.isNotEmpty) { for (var communityId in spaceBloc.state.selectedCommunities) {
automations = await SceneApi.getAutomation(event.spaceId); List<String> spacesList =
spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? [];
for (var spaceId in spacesList) {
automations.addAll(await SceneApi.getAutomation(spaceId));
}
} }
emit(state.copyWith( emit(state.copyWith(
automations: automations, automations: automations,
@ -197,18 +226,20 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
loadAutomationErrorMessage: 'Failed to load automations', loadAutomationErrorMessage: 'Failed to load automations',
errorMessage: '', errorMessage: '',
loadScenesErrorMessage: '', loadScenesErrorMessage: '',
automations: [])); automations: automations));
} }
} }
FutureOr<void> _onSearchRoutines(SearchRoutines event, Emitter<RoutineState> emit) async { FutureOr<void> _onSearchRoutines(
SearchRoutines event, Emitter<RoutineState> emit) async {
emit(state.copyWith(isLoading: true, errorMessage: null)); emit(state.copyWith(isLoading: true, errorMessage: null));
await Future.delayed(const Duration(seconds: 1)); await Future.delayed(const Duration(seconds: 1));
emit(state.copyWith(isLoading: false, errorMessage: null)); emit(state.copyWith(isLoading: false, errorMessage: null));
emit(state.copyWith(searchText: event.query)); emit(state.copyWith(searchText: event.query));
} }
FutureOr<void> _onAddSelectedIcon(AddSelectedIcon event, Emitter<RoutineState> emit) { FutureOr<void> _onAddSelectedIcon(
AddSelectedIcon event, Emitter<RoutineState> emit) {
emit(state.copyWith(selectedIcon: event.icon)); emit(state.copyWith(selectedIcon: event.icon));
} }
@ -222,7 +253,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
return actions.last['deviceId'] == 'delay'; return actions.last['deviceId'] == 'delay';
} }
Future<void> _onCreateScene(CreateSceneEvent event, Emitter<RoutineState> emit) async { Future<void> _onCreateScene(
CreateSceneEvent event, Emitter<RoutineState> emit) async {
try { try {
// Check if first action is delay // Check if first action is delay
// if (_isFirstActionDelay(state.thenItems)) { // if (_isFirstActionDelay(state.thenItems)) {
@ -235,7 +267,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
if (_isLastActionDelay(state.thenItems)) { if (_isLastActionDelay(state.thenItems)) {
emit(state.copyWith( emit(state.copyWith(
errorMessage: 'A delay condition cannot be the only or the last action', errorMessage:
'A delay condition cannot be the only or the last action',
isLoading: false, isLoading: false,
)); ));
return; return;
@ -280,8 +313,11 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
}); });
}).toList(); }).toList();
BuildContext context = NavigationService.navigatorKey.currentContext!;
var spaceBloc = context.read<SpaceTreeBloc>();
final createSceneModel = CreateSceneModel( final createSceneModel = CreateSceneModel(
spaceUuid: spaceId, spaceUuid: spaceBloc.state.selectedSpaces[0],
iconId: state.selectedIcon ?? '', iconId: state.selectedIcon ?? '',
showInDevice: true, showInDevice: true,
sceneName: state.routineName ?? '', sceneName: state.routineName ?? '',
@ -292,8 +328,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
final result = await SceneApi.createScene(createSceneModel); final result = await SceneApi.createScene(createSceneModel);
if (result['success']) { if (result['success']) {
add(ResetRoutineState()); add(ResetRoutineState());
add(LoadScenes(spaceId, communityId)); add(const LoadScenes());
add(LoadAutomation(spaceId)); add(const LoadAutomation());
} else { } else {
emit(state.copyWith( emit(state.copyWith(
isLoading: false, isLoading: false,
@ -308,7 +344,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
} }
Future<void> _onCreateAutomation(CreateAutomationEvent event, Emitter<RoutineState> emit) async { Future<void> _onCreateAutomation(
CreateAutomationEvent event, Emitter<RoutineState> emit) async {
try { try {
if (state.routineName == null || state.routineName!.isEmpty) { if (state.routineName == null || state.routineName!.isEmpty) {
emit(state.copyWith( emit(state.copyWith(
@ -329,7 +366,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
if (_isLastActionDelay(state.thenItems)) { if (_isLastActionDelay(state.thenItems)) {
emit(state.copyWith( emit(state.copyWith(
errorMessage: 'A delay condition cannot be the only or the last action', errorMessage:
'A delay condition cannot be the only or the last action',
isLoading: false, isLoading: false,
)); ));
CustomSnackBar.redSnackBar('Cannot have delay as the last action'); CustomSnackBar.redSnackBar('Cannot have delay as the last action');
@ -404,9 +442,11 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
); );
}); });
}).toList(); }).toList();
BuildContext context = NavigationService.navigatorKey.currentContext!;
var spaceBloc = context.read<SpaceTreeBloc>();
final createAutomationModel = CreateAutomationModel( final createAutomationModel = CreateAutomationModel(
spaceUuid: spaceId, spaceUuid: spaceBloc.state.selectedSpaces[0],
automationName: state.routineName ?? '', automationName: state.routineName ?? '',
decisionExpr: state.selectedAutomationOperator, decisionExpr: state.selectedAutomationOperator,
effectiveTime: EffectiveTime( effectiveTime: EffectiveTime(
@ -421,8 +461,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
final result = await SceneApi.createAutomation(createAutomationModel); final result = await SceneApi.createAutomation(createAutomationModel);
if (result['success']) { if (result['success']) {
add(ResetRoutineState()); add(ResetRoutineState());
add(LoadAutomation(spaceId)); add(const LoadAutomation());
add(LoadScenes(spaceId, communityId)); add(const LoadScenes());
} else { } else {
emit(state.copyWith( emit(state.copyWith(
isLoading: false, isLoading: false,
@ -439,17 +479,21 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
} }
FutureOr<void> _onRemoveDragCard(RemoveDragCard event, Emitter<RoutineState> emit) { FutureOr<void> _onRemoveDragCard(
RemoveDragCard event, Emitter<RoutineState> emit) {
if (event.isFromThen) { if (event.isFromThen) {
final thenItems = List<Map<String, dynamic>>.from(state.thenItems); final thenItems = List<Map<String, dynamic>>.from(state.thenItems);
final selectedFunctions = Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions); final selectedFunctions =
Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions);
thenItems.removeAt(event.index); thenItems.removeAt(event.index);
selectedFunctions.remove(event.key); selectedFunctions.remove(event.key);
emit(state.copyWith(thenItems: thenItems, selectedFunctions: selectedFunctions)); emit(state.copyWith(
thenItems: thenItems, selectedFunctions: selectedFunctions));
} else { } else {
final ifItems = List<Map<String, dynamic>>.from(state.ifItems); final ifItems = List<Map<String, dynamic>>.from(state.ifItems);
final selectedFunctions = Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions); final selectedFunctions =
Map<String, List<DeviceFunctionData>>.from(state.selectedFunctions);
ifItems.removeAt(event.index); ifItems.removeAt(event.index);
selectedFunctions.remove(event.key); selectedFunctions.remove(event.key);
@ -460,7 +504,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
isAutomation: false, isAutomation: false,
isTabToRun: false)); isTabToRun: false));
} else { } else {
emit(state.copyWith(ifItems: ifItems, selectedFunctions: selectedFunctions)); emit(state.copyWith(
ifItems: ifItems, selectedFunctions: selectedFunctions));
} }
} }
} }
@ -472,18 +517,23 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
)); ));
} }
FutureOr<void> _onEffectiveTimeEvent(EffectiveTimePeriodEvent event, Emitter<RoutineState> emit) { FutureOr<void> _onEffectiveTimeEvent(
EffectiveTimePeriodEvent event, Emitter<RoutineState> emit) {
emit(state.copyWith(effectiveTime: event.effectiveTime)); emit(state.copyWith(effectiveTime: event.effectiveTime));
} }
FutureOr<void> _onSetRoutineName(SetRoutineName event, Emitter<RoutineState> emit) { FutureOr<void> _onSetRoutineName(
SetRoutineName event, Emitter<RoutineState> emit) {
emit(state.copyWith( emit(state.copyWith(
routineName: event.name, routineName: event.name,
)); ));
} }
(List<Map<String, dynamic>>, List<Map<String, dynamic>>, Map<String, List<DeviceFunctionData>>) (
_createCardData( List<Map<String, dynamic>>,
List<Map<String, dynamic>>,
Map<String, List<DeviceFunctionData>>
) _createCardData(
List<RoutineAction> actions, List<RoutineAction> actions,
List<RoutineCondition>? conditions, List<RoutineCondition>? conditions,
Map<String, List<DeviceFunctionData>> currentFunctions, Map<String, List<DeviceFunctionData>> currentFunctions,
@ -516,7 +566,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
'deviceId': condition.entityId, 'deviceId': condition.entityId,
'title': matchingDevice.name ?? condition.entityId, 'title': matchingDevice.name ?? condition.entityId,
'productType': condition.entityType, 'productType': condition.entityType,
'imagePath': matchingDevice.getDefaultIcon(condition.entityType), 'imagePath':
matchingDevice.getDefaultIcon(condition.entityType),
}; };
final functions = matchingDevice.functions; final functions = matchingDevice.functions;
@ -552,8 +603,11 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
final cardData = { final cardData = {
'entityId': action.entityId, 'entityId': action.entityId,
'uniqueCustomId': const Uuid().v4(), 'uniqueCustomId': const Uuid().v4(),
'deviceId': action.actionExecutor == 'delay' ? 'delay' : action.entityId, 'deviceId':
'title': action.actionExecutor == 'delay' ? 'Delay' : (matchingDevice.name ?? 'Device'), action.actionExecutor == 'delay' ? 'delay' : action.entityId,
'title': action.actionExecutor == 'delay'
? 'Delay'
: (matchingDevice.name ?? 'Device'),
'productType': action.productType, 'productType': action.productType,
'imagePath': matchingDevice.getDefaultIcon(action.productType), 'imagePath': matchingDevice.getDefaultIcon(action.productType),
}; };
@ -596,7 +650,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
return (thenItems, ifItems, currentFunctions); return (thenItems, ifItems, currentFunctions);
} }
Future<void> _onGetSceneDetails(GetSceneDetails event, Emitter<RoutineState> emit) async { Future<void> _onGetSceneDetails(
GetSceneDetails event, Emitter<RoutineState> emit) async {
try { try {
emit(state.copyWith( emit(state.copyWith(
isLoading: true, isLoading: true,
@ -644,8 +699,10 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
if (!deviceCards.containsKey(deviceId)) { if (!deviceCards.containsKey(deviceId)) {
deviceCards[deviceId] = { deviceCards[deviceId] = {
'entityId': action.entityId, 'entityId': action.entityId,
'deviceId': action.actionExecutor == 'delay' ? 'delay' : action.entityId, 'deviceId':
'uniqueCustomId': action.type == 'automation' || action.actionExecutor == 'delay' action.actionExecutor == 'delay' ? 'delay' : action.entityId,
'uniqueCustomId':
action.type == 'automation' || action.actionExecutor == 'delay'
? const Uuid().v4() ? const Uuid().v4()
: action.entityId, : action.entityId,
'title': action.actionExecutor == 'delay' 'title': action.actionExecutor == 'delay'
@ -682,7 +739,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
), ),
); );
// emit(state.copyWith(automationActionExecutor: action.actionExecutor)); // emit(state.copyWith(automationActionExecutor: action.actionExecutor));
} else if (action.executorProperty != null && action.actionExecutor != 'delay') { } else if (action.executorProperty != null &&
action.actionExecutor != 'delay') {
if (!updatedFunctions.containsKey(uniqueCustomId)) { if (!updatedFunctions.containsKey(uniqueCustomId)) {
updatedFunctions[uniqueCustomId] = []; updatedFunctions[uniqueCustomId] = [];
} }
@ -754,7 +812,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
} }
FutureOr<void> _onResetRoutineState(ResetRoutineState event, Emitter<RoutineState> emit) { FutureOr<void> _onResetRoutineState(
ResetRoutineState event, Emitter<RoutineState> emit) {
emit(state.copyWith( emit(state.copyWith(
ifItems: [], ifItems: [],
thenItems: [], thenItems: [],
@ -778,17 +837,24 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
createRoutineView: false)); createRoutineView: false));
} }
FutureOr<void> _deleteScene(DeleteScene event, Emitter<RoutineState> emit) { FutureOr<void> _deleteScene(
DeleteScene event, Emitter<RoutineState> emit) async {
try { try {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(isLoading: true));
BuildContext context = NavigationService.navigatorKey.currentContext!;
var spaceBloc = context.read<SpaceTreeBloc>();
if (state.isTabToRun) { if (state.isTabToRun) {
SceneApi.deleteScene(unitUuid: spaceId, sceneId: state.sceneId ?? ''); await SceneApi.deleteScene(
unitUuid: spaceBloc.state.selectedSpaces[0],
sceneId: state.sceneId ?? '');
} else { } else {
SceneApi.deleteAutomation(unitUuid: spaceId, automationId: state.automationId ?? ''); await SceneApi.deleteAutomation(
unitUuid: spaceBloc.state.selectedSpaces[0],
automationId: state.automationId ?? '');
} }
add(LoadScenes(spaceId, communityId)); add(const LoadScenes());
add(LoadAutomation(spaceId)); add(const LoadAutomation());
add(ResetRoutineState()); add(ResetRoutineState());
emit(state.copyWith(isLoading: false, createRoutineView: false)); emit(state.copyWith(isLoading: false, createRoutineView: false));
} catch (e) { } catch (e) {
@ -813,10 +879,24 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
// } // }
// } // }
FutureOr<void> _fetchDevices(FetchDevicesInRoutine event, Emitter<RoutineState> emit) async { FutureOr<void> _fetchDevices(
FetchDevicesInRoutine event, Emitter<RoutineState> emit) async {
emit(state.copyWith(isLoading: true)); emit(state.copyWith(isLoading: true));
try { try {
final devices = await DevicesManagementApi().fetchDevices('', ''); final projectUuid = await ProjectManager.getProjectUUID() ?? '';
List<AllDevicesModel> devices = [];
BuildContext context = NavigationService.navigatorKey.currentContext!;
var spaceBloc = context.read<SpaceTreeBloc>();
for (var communityId in spaceBloc.state.selectedCommunities) {
List<String> spacesList =
spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? [];
for (var spaceId in spacesList) {
devices.addAll(await DevicesManagementApi()
.fetchDevices(communityId, spaceId, projectUuid));
}
}
emit(state.copyWith(isLoading: false, devices: devices)); emit(state.copyWith(isLoading: false, devices: devices));
} catch (e) { } catch (e) {
@ -824,7 +904,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
} }
FutureOr<void> _onUpdateScene(UpdateScene event, Emitter<RoutineState> emit) async { FutureOr<void> _onUpdateScene(
UpdateScene event, Emitter<RoutineState> emit) async {
try { try {
// Check if first action is delay // Check if first action is delay
// if (_isFirstActionDelay(state.thenItems)) { // if (_isFirstActionDelay(state.thenItems)) {
@ -838,7 +919,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
if (_isLastActionDelay(state.thenItems)) { if (_isLastActionDelay(state.thenItems)) {
emit(state.copyWith( emit(state.copyWith(
errorMessage: 'A delay condition cannot be the only or the last action', errorMessage:
'A delay condition cannot be the only or the last action',
isLoading: false, isLoading: false,
)); ));
return; return;
@ -891,11 +973,12 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
actions: actions, actions: actions,
); );
final result = await SceneApi.updateScene(createSceneModel, state.sceneId ?? ''); final result =
await SceneApi.updateScene(createSceneModel, state.sceneId ?? '');
if (result['success']) { if (result['success']) {
add(ResetRoutineState()); add(ResetRoutineState());
add(LoadScenes(spaceId, communityId)); add(const LoadScenes());
add(LoadAutomation(spaceId)); add(const LoadAutomation());
} else { } else {
emit(state.copyWith( emit(state.copyWith(
isLoading: false, isLoading: false,
@ -910,7 +993,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
} }
FutureOr<void> _onUpdateAutomation(UpdateAutomation event, Emitter<RoutineState> emit) async { FutureOr<void> _onUpdateAutomation(
UpdateAutomation event, Emitter<RoutineState> emit) async {
try { try {
if (state.routineName == null || state.routineName!.isEmpty) { if (state.routineName == null || state.routineName!.isEmpty) {
emit(state.copyWith( emit(state.copyWith(
@ -1005,8 +1089,11 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
}); });
}).toList(); }).toList();
BuildContext context = NavigationService.navigatorKey.currentContext!;
var spaceBloc = context.read<SpaceTreeBloc>();
final createAutomationModel = CreateAutomationModel( final createAutomationModel = CreateAutomationModel(
spaceUuid: spaceId, spaceUuid: spaceBloc.state.selectedSpaces[0],
automationName: state.routineName ?? '', automationName: state.routineName ?? '',
decisionExpr: state.selectedAutomationOperator, decisionExpr: state.selectedAutomationOperator,
effectiveTime: EffectiveTime( effectiveTime: EffectiveTime(
@ -1018,13 +1105,13 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
actions: actions, actions: actions,
); );
final result = final result = await SceneApi.updateAutomation(
await SceneApi.updateAutomation(createAutomationModel, state.automationId ?? ''); createAutomationModel, state.automationId ?? '');
if (result['success']) { if (result['success']) {
add(ResetRoutineState()); add(ResetRoutineState());
add(LoadAutomation(spaceId)); add(LoadAutomation());
add(LoadScenes(spaceId, communityId)); add(LoadScenes());
} else { } else {
emit(state.copyWith( emit(state.copyWith(
isLoading: false, isLoading: false,
@ -1052,7 +1139,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
thenItems: [], thenItems: [],
)); ));
final automationDetails = await SceneApi.getAutomationDetails(event.automationId); final automationDetails =
await SceneApi.getAutomationDetails(event.automationId);
final Map<String, Map<String, dynamic>> deviceIfCards = {}; final Map<String, Map<String, dynamic>> deviceIfCards = {};
final Map<String, Map<String, dynamic>> deviceThenCards = {}; final Map<String, Map<String, dynamic>> deviceThenCards = {};
@ -1120,13 +1208,15 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
), ),
); );
final deviceId = final deviceId = action.actionExecutor == 'delay'
action.actionExecutor == 'delay' ? '${action.entityId}_delay' : action.entityId; ? '${action.entityId}_delay'
: action.entityId;
if (!deviceThenCards.containsKey(deviceId)) { if (!deviceThenCards.containsKey(deviceId)) {
deviceThenCards[deviceId] = { deviceThenCards[deviceId] = {
'entityId': action.entityId, 'entityId': action.entityId,
'deviceId': action.actionExecutor == 'delay' ? 'delay' : action.entityId, 'deviceId':
action.actionExecutor == 'delay' ? 'delay' : action.entityId,
'uniqueCustomId': const Uuid().v4(), 'uniqueCustomId': const Uuid().v4(),
'title': action.actionExecutor == 'delay' 'title': action.actionExecutor == 'delay'
? 'Delay' ? 'Delay'
@ -1157,7 +1247,8 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
updatedFunctions[uniqueCustomId] = []; updatedFunctions[uniqueCustomId] = [];
} }
if (action.executorProperty != null && action.actionExecutor != 'delay') { if (action.executorProperty != null &&
action.actionExecutor != 'delay') {
final functions = matchingDevice.functions; final functions = matchingDevice.functions;
final functionCode = action.executorProperty!.functionCode; final functionCode = action.executorProperty!.functionCode;
for (var function in functions) { for (var function in functions) {
@ -1199,10 +1290,14 @@ class RoutineBloc extends Bloc<RoutineEvent, RoutineState> {
} }
} }
final ifItems = deviceIfCards.values.where((card) => card['type'] == 'condition').toList(); final ifItems = deviceIfCards.values
.where((card) => card['type'] == 'condition')
.toList();
final thenItems = deviceThenCards.values final thenItems = deviceThenCards.values
.where((card) => .where((card) =>
card['type'] == 'action' || card['type'] == 'automation' || card['type'] == 'scene') card['type'] == 'action' ||
card['type'] == 'automation' ||
card['type'] == 'scene')
.toList(); .toList();
emit(state.copyWith( emit(state.copyWith(

View File

@ -27,22 +27,24 @@ class AddToThenContainer extends RoutineEvent {
} }
class LoadScenes extends RoutineEvent { class LoadScenes extends RoutineEvent {
final String spaceId; // final String spaceId;
final String communityId; // final String communityId;
// final BuildContext context;
const LoadScenes(this.spaceId, this.communityId); const LoadScenes();
@override @override
List<Object> get props => [spaceId, communityId]; List<Object> get props => [];
} }
class LoadAutomation extends RoutineEvent { class LoadAutomation extends RoutineEvent {
final String spaceId; // final String spaceId;
// final BuildContext context;
const LoadAutomation(this.spaceId); const LoadAutomation();
@override @override
List<Object> get props => [spaceId]; List<Object> get props => [];
} }
class AddFunctionToRoutine extends RoutineEvent { class AddFunctionToRoutine extends RoutineEvent {

View File

@ -20,7 +20,7 @@ class _RoutinesViewState extends State<RoutinesView> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
context.read<RoutineBloc>().add(FetchDevicesInRoutine()); // context.read<RoutineBloc>().add(FetchDevicesInRoutine());
} }
@override @override
@ -32,9 +32,12 @@ class _RoutinesViewState extends State<RoutinesView> {
} }
return Row( return Row(
children: [ children: [
Expanded( Expanded(child: SpaceTreeView(
child: SpaceTreeView( onSelect: () {
onSelect: () {}, context.read<RoutineBloc>()
..add(const LoadScenes())
..add(const LoadAutomation());
},
)), )),
Expanded( Expanded(
flex: 4, flex: 4,
@ -59,8 +62,8 @@ class _RoutinesViewState extends State<RoutinesView> {
), ),
RoutineViewCard( RoutineViewCard(
onTap: () { onTap: () {
if (context.read<SpaceTreeBloc>().selectedCommunityId.isNotEmpty && if (context.read<SpaceTreeBloc>().state.selectedCommunities.length == 1 &&
context.read<SpaceTreeBloc>().selectedSpaceId.isNotEmpty) { context.read<SpaceTreeBloc>().state.selectedSpaces.length == 1) {
context.read<RoutineBloc>().add( context.read<RoutineBloc>().add(
(ResetRoutineState()), (ResetRoutineState()),
); );
@ -68,7 +71,18 @@ class _RoutinesViewState extends State<RoutinesView> {
const CreateNewRoutineViewEvent(createRoutineView: true), const CreateNewRoutineViewEvent(createRoutineView: true),
); );
} else { } else {
CustomSnackBar.redSnackBar('Please select a space'); ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
context.read<SpaceTreeBloc>().state.selectedSpaces.isEmpty
? 'Please select a space'
: 'Please select only one space to proceed'),
),
);
// CustomSnackBar.redSnackBar(
// context.read<SpaceTreeBloc>().state.selectedSpaces.isEmpty
// ? 'Please select a space'
// : 'Please select only one space to proceed');
} }
}, },
icon: Icons.add, icon: Icons.add,

View File

@ -20,10 +20,6 @@ class _FetchRoutineScenesState extends State<FetchRoutineScenesAutomation>
@override @override
void initState() { void initState() {
super.initState(); super.initState();
context.read<RoutineBloc>()
..add(LoadScenes(context.read<SpaceTreeBloc>().selectedSpaceId,
context.read<SpaceTreeBloc>().selectedCommunityId))
..add(LoadAutomation(context.read<SpaceTreeBloc>().selectedSpaceId));
} }
@override @override

View File

@ -4,9 +4,20 @@ import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_mo
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart'; import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/widgets/dragable_card.dart'; import 'package:syncrow_web/pages/routines/widgets/dragable_card.dart';
class RoutineDevices extends StatelessWidget { class RoutineDevices extends StatefulWidget {
const RoutineDevices({super.key}); const RoutineDevices({super.key});
@override
State<RoutineDevices> createState() => _RoutineDevicesState();
}
class _RoutineDevicesState extends State<RoutineDevices> {
@override
void initState() {
super.initState();
context.read<RoutineBloc>().add(FetchDevicesInRoutine());
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocBuilder<RoutineBloc, RoutineState>( return BlocBuilder<RoutineBloc, RoutineState>(

View File

@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart'; import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/widgets/dragable_card.dart'; import 'package:syncrow_web/pages/routines/widgets/dragable_card.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
class ScenesAndAutomations extends StatefulWidget { class ScenesAndAutomations extends StatefulWidget {
@ -19,9 +18,8 @@ class _ScenesAndAutomationsState extends State<ScenesAndAutomations> {
void initState() { void initState() {
super.initState(); super.initState();
context.read<RoutineBloc>() context.read<RoutineBloc>()
..add(LoadScenes(context.read<SpaceTreeBloc>().selectedSpaceId, ..add(const LoadScenes())
context.read<SpaceTreeBloc>().selectedCommunityId)) ..add(const LoadAutomation());
..add(LoadAutomation(context.read<SpaceTreeBloc>().selectedSpaceId));
} }
@override @override

View File

@ -1,4 +1,5 @@
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_state.dart'; import 'package:syncrow_web/pages/space_tree/bloc/space_tree_state.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
@ -6,9 +7,6 @@ import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model
import 'package:syncrow_web/services/space_mana_api.dart'; import 'package:syncrow_web/services/space_mana_api.dart';
class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> { class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
String selectedCommunityId = 'aff21a57-2f91-4e5c-b99b-0182c3ab65a9';
String selectedSpaceId = '25c96044-fadf-44bb-93c7-3c079e527ce6';
SpaceTreeBloc() : super(const SpaceTreeState()) { SpaceTreeBloc() : super(const SpaceTreeState()) {
on<InitialEvent>(_fetchSpaces); on<InitialEvent>(_fetchSpaces);
on<OnCommunityExpanded>(_onCommunityExpanded); on<OnCommunityExpanded>(_onCommunityExpanded);
@ -21,12 +19,15 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
_fetchSpaces(InitialEvent event, Emitter<SpaceTreeState> emit) async { _fetchSpaces(InitialEvent event, Emitter<SpaceTreeState> emit) async {
emit(SpaceTreeLoadingState()); emit(SpaceTreeLoadingState());
try { try {
List<CommunityModel> communities = await CommunitySpaceManagementApi().fetchCommunities(); final projectUuid = await ProjectManager.getProjectUUID() ?? '';
List<CommunityModel> communities =
await CommunitySpaceManagementApi().fetchCommunities(projectUuid);
List<CommunityModel> updatedCommunities = await Future.wait( List<CommunityModel> updatedCommunities = await Future.wait(
communities.map((community) async { communities.map((community) async {
List<SpaceModel> spaces = List<SpaceModel> spaces =
await CommunitySpaceManagementApi().getSpaceHierarchy(community.uuid); await CommunitySpaceManagementApi().getSpaceHierarchy(community.uuid, projectUuid);
return CommunityModel( return CommunityModel(
uuid: community.uuid, uuid: community.uuid,
@ -135,12 +136,12 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
!updatedSoldChecks.contains(event.spaceId)) { !updatedSoldChecks.contains(event.spaceId)) {
// First click: Select the space and all its children // First click: Select the space and all its children
updatedSelectedSpaces.add(event.spaceId); updatedSelectedSpaces.add(event.spaceId);
updatedSelectedCommunities.add(event.communityId); updatedSelectedCommunities.add(event.communityModel.uuid);
if (childrenIds.isNotEmpty) { if (childrenIds.isNotEmpty) {
updatedSelectedSpaces.addAll(childrenIds); updatedSelectedSpaces.addAll(childrenIds);
} }
List<String> spaces = _getThePathToChild(event.communityId, event.spaceId); List<String> spaces = _getThePathToChild(event.communityModel.uuid, event.spaceId);
for (String space in spaces) { for (String space in spaces) {
if (!updatedSelectedSpaces.contains(space) && !updatedSoldChecks.contains(space)) { if (!updatedSelectedSpaces.contains(space) && !updatedSoldChecks.contains(space)) {
updatedSoldChecks.add(space); updatedSoldChecks.add(space);
@ -161,20 +162,31 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
} }
updatedSoldChecks.remove(event.spaceId); updatedSoldChecks.remove(event.spaceId);
List<String> parents = _getThePathToChild(event.communityId, event.spaceId); List<String> parents =
if (!_parentSelected(parents, updatedSelectedSpaces)) { _getThePathToChild(event.communityModel.uuid, event.spaceId).toSet().toList();
if (updatedSelectedSpaces.isEmpty) {
updatedSoldChecks.removeWhere(parents.contains); updatedSoldChecks.removeWhere(parents.contains);
} updatedSelectedCommunities.remove(event.communityModel.uuid);
if (!_anySpacesSelectedInCommunity( } else {
event.communityId, updatedSelectedSpaces, updatedSoldChecks)) { // Check if any parent has selected children
updatedSelectedCommunities.remove(event.communityId); for (String space in parents) {
if (!_noChildrenSelected(event.communityModel, space, updatedSelectedSpaces, parents)) {
updatedSoldChecks.remove(space);
} }
} }
communityAndSpaces[event.communityId] = updatedSelectedSpaces; if (!_anySpacesSelectedInCommunity(
event.communityModel, updatedSelectedSpaces, updatedSoldChecks)) {
updatedSelectedCommunities.remove(event.communityModel.uuid);
}
}
}
communityAndSpaces[event.communityModel.uuid] = updatedSelectedSpaces;
emit(state.copyWith( emit(state.copyWith(
selectedCommunities: updatedSelectedCommunities, selectedCommunities: updatedSelectedCommunities.toSet().toList(),
selectedSpaces: updatedSelectedSpaces, selectedSpaces: updatedSelectedSpaces,
soldCheck: updatedSoldChecks, soldCheck: updatedSoldChecks,
selectedCommunityAndSpaces: communityAndSpaces)); selectedCommunityAndSpaces: communityAndSpaces));
@ -184,12 +196,24 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
} }
} }
_parentSelected(List<String> parents, List<String> selectedSpaces) { _noChildrenSelected(
for (String space in parents) { CommunityModel community, String spaceId, List<String> selectedSpaces, List<String> parents) {
if (selectedSpaces.contains(space)) { if (selectedSpaces.contains(spaceId)) {
return true;
}
List<SpaceModel> children = _getAllChildSpaces(community.spaces);
for (var child in children) {
if (spaceId == child.uuid) {
List<String> ids = _getAllChildIds(child.children);
for (var id in ids) {
if (selectedSpaces.contains(id)) {
return true; return true;
} }
} }
}
}
return false; return false;
} }
@ -209,7 +233,9 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
}).toList(); }).toList();
emit(state.copyWith( emit(state.copyWith(
filteredCommunity: filteredCommunity, isSearching: event.searchQuery.isNotEmpty)); filteredCommunity: filteredCommunity,
isSearching: event.searchQuery.isNotEmpty,
searchQuery: event.searchQuery));
} catch (e) { } catch (e) {
emit(const SpaceTreeErrorState('Something went wrong')); emit(const SpaceTreeErrorState('Something went wrong'));
} }
@ -230,14 +256,21 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
ids.add(child.uuid!); ids.add(child.uuid!);
ids.addAll(_getAllChildIds(child.children)); ids.addAll(_getAllChildIds(child.children));
} }
return ids; return ids.toSet().toList();
}
List<SpaceModel> _getAllChildSpaces(List<SpaceModel> spaces) {
List<SpaceModel> children = [];
for (var child in spaces) {
children.add(child);
children.addAll(_getAllChildSpaces(child.children));
}
return children;
} }
bool _anySpacesSelectedInCommunity( bool _anySpacesSelectedInCommunity(
String communityId, List<String> selectedSpaces, List<String> partialCheckedList) { CommunityModel community, List<String> selectedSpaces, List<String> partialCheckedList) {
bool result = false; bool result = false;
for (var community in state.communityList) {
if (community.uuid == communityId) {
List<String> ids = _getAllChildIds(community.spaces); List<String> ids = _getAllChildIds(community.spaces);
for (var id in ids) { for (var id in ids) {
result = selectedSpaces.contains(id) || partialCheckedList.contains(id); result = selectedSpaces.contains(id) || partialCheckedList.contains(id);
@ -245,8 +278,6 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
return result; return result;
} }
} }
}
}
return result; return result;
} }
@ -288,4 +319,9 @@ class SpaceTreeBloc extends Bloc<SpaceTreeEvent, SpaceTreeState> {
ids.removeLast(); ids.removeLast();
return []; return [];
} }
@override
Future<void> close() async {
super.close();
}
} }

View File

@ -1,4 +1,5 @@
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
class SpaceTreeEvent extends Equatable { class SpaceTreeEvent extends Equatable {
@ -49,14 +50,14 @@ class OnSpaceExpanded extends SpaceTreeEvent {
} }
class OnSpaceSelected extends SpaceTreeEvent { class OnSpaceSelected extends SpaceTreeEvent {
final String communityId;
final String spaceId; final String spaceId;
final List<SpaceModel> children; final List<SpaceModel> children;
final CommunityModel communityModel;
const OnSpaceSelected(this.communityId, this.spaceId, this.children); const OnSpaceSelected(this.communityModel, this.spaceId, this.children);
@override @override
List<Object> get props => [communityId, spaceId, children]; List<Object> get props => [communityModel, spaceId, children];
} }
class SearchQueryEvent extends SpaceTreeEvent { class SearchQueryEvent extends SpaceTreeEvent {

View File

@ -11,6 +11,7 @@ class SpaceTreeState extends Equatable {
final List<String> selectedSpaces; final List<String> selectedSpaces;
final List<String> soldCheck; final List<String> soldCheck;
final bool isSearching; final bool isSearching;
final String searchQuery;
const SpaceTreeState( const SpaceTreeState(
{this.communityList = const [], {this.communityList = const [],
@ -21,7 +22,8 @@ class SpaceTreeState extends Equatable {
this.selectedSpaces = const [], this.selectedSpaces = const [],
this.soldCheck = const [], this.soldCheck = const [],
this.isSearching = false, this.isSearching = false,
this.selectedCommunityAndSpaces = const {}}); this.selectedCommunityAndSpaces = const {},
this.searchQuery = ''});
SpaceTreeState copyWith( SpaceTreeState copyWith(
{List<CommunityModel>? communitiesList, {List<CommunityModel>? communitiesList,
@ -32,7 +34,8 @@ class SpaceTreeState extends Equatable {
List<String>? selectedSpaces, List<String>? selectedSpaces,
List<String>? soldCheck, List<String>? soldCheck,
bool? isSearching, bool? isSearching,
Map<String, List<String>>? selectedCommunityAndSpaces}) { Map<String, List<String>>? selectedCommunityAndSpaces,
String? searchQuery}) {
return SpaceTreeState( return SpaceTreeState(
communityList: communitiesList ?? this.communityList, communityList: communitiesList ?? this.communityList,
filteredCommunity: filteredCommunity ?? this.filteredCommunity, filteredCommunity: filteredCommunity ?? this.filteredCommunity,
@ -42,7 +45,8 @@ class SpaceTreeState extends Equatable {
selectedSpaces: selectedSpaces ?? this.selectedSpaces, selectedSpaces: selectedSpaces ?? this.selectedSpaces,
soldCheck: soldCheck ?? this.soldCheck, soldCheck: soldCheck ?? this.soldCheck,
isSearching: isSearching ?? this.isSearching, isSearching: isSearching ?? this.isSearching,
selectedCommunityAndSpaces: selectedCommunityAndSpaces ?? this.selectedCommunityAndSpaces); selectedCommunityAndSpaces: selectedCommunityAndSpaces ?? this.selectedCommunityAndSpaces,
searchQuery: searchQuery ?? this.searchQuery);
} }
@override @override
@ -55,7 +59,8 @@ class SpaceTreeState extends Equatable {
selectedSpaces, selectedSpaces,
soldCheck, soldCheck,
isSearching, isSearching,
selectedCommunityAndSpaces selectedCommunityAndSpaces,
searchQuery
]; ];
} }

View File

@ -39,6 +39,7 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
: Column( : Column(
children: [ children: [
CustomSearchBar( CustomSearchBar(
searchQuery: state.searchQuery,
onSearchChanged: (query) { onSearchChanged: (query) {
context.read<SpaceTreeBloc>().add(SearchQueryEvent(query)); context.read<SpaceTreeBloc>().add(SearchQueryEvent(query));
}, },
@ -99,8 +100,8 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
state.expandedSpaces.contains(space.uuid), state.expandedSpaces.contains(space.uuid),
onItemSelected: () { onItemSelected: () {
context.read<SpaceTreeBloc>().add( context.read<SpaceTreeBloc>().add(
OnSpaceSelected(community.uuid, OnSpaceSelected(community, space.uuid ?? '',
space.uuid ?? '', space.children)); space.children));
widget.onSelect(); widget.onSelect();
}, },
onExpansionChanged: () { onExpansionChanged: () {
@ -113,7 +114,7 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
state.soldCheck.contains(space.uuid), state.soldCheck.contains(space.uuid),
isSoldCheck: state.soldCheck.contains(space.uuid), isSoldCheck: state.soldCheck.contains(space.uuid),
children: _buildNestedSpaces( children: _buildNestedSpaces(
context, state, space, community.uuid), context, state, space, community),
); );
}).toList(), }).toList(),
), ),
@ -196,7 +197,7 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
} }
List<Widget> _buildNestedSpaces( List<Widget> _buildNestedSpaces(
BuildContext context, SpaceTreeState state, SpaceModel space, String communityId) { BuildContext context, SpaceTreeState state, SpaceModel space, CommunityModel community) {
return space.children.map((child) { return space.children.map((child) {
return CustomExpansionTileSpaceTree( return CustomExpansionTileSpaceTree(
isSelected: isSelected:
@ -207,13 +208,13 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
onItemSelected: () { onItemSelected: () {
context context
.read<SpaceTreeBloc>() .read<SpaceTreeBloc>()
.add(OnSpaceSelected(communityId, child.uuid ?? '', child.children)); .add(OnSpaceSelected(community, child.uuid ?? '', child.children));
widget.onSelect(); widget.onSelect();
}, },
onExpansionChanged: () { onExpansionChanged: () {
context.read<SpaceTreeBloc>().add(OnSpaceExpanded(communityId, child.uuid ?? '')); context.read<SpaceTreeBloc>().add(OnSpaceExpanded(community.uuid, child.uuid ?? ''));
}, },
children: _buildNestedSpaces(context, state, child, communityId), children: _buildNestedSpaces(context, state, child, community),
); );
}).toList(); }).toList();
} }

View File

@ -1,4 +1,8 @@
import 'dart:developer';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/create_subspace_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/create_subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
@ -14,6 +18,9 @@ import 'package:syncrow_web/services/product_api.dart';
import 'package:syncrow_web/services/space_mana_api.dart'; import 'package:syncrow_web/services/space_mana_api.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart'; import 'package:syncrow_web/services/space_model_mang_api.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart'; import 'package:syncrow_web/utils/constants/action_enum.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
class SpaceManagementBloc class SpaceManagementBloc
extends Bloc<SpaceManagementEvent, SpaceManagementState> { extends Bloc<SpaceManagementEvent, SpaceManagementState> {
@ -39,15 +46,23 @@ class SpaceManagementBloc
on<SpaceModelLoadEvent>(_onLoadSpaceModel); on<SpaceModelLoadEvent>(_onLoadSpaceModel);
} }
void _logEvent(String eventName) {
log('Event Triggered: $eventName');
}
void _onUpdateCommunity( void _onUpdateCommunity(
UpdateCommunityEvent event, UpdateCommunityEvent event,
Emitter<SpaceManagementState> emit, Emitter<SpaceManagementState> emit,
) async { ) async {
_logEvent('UpdateCommunityEvent');
final previousState = state; final previousState = state;
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
emit(SpaceManagementLoading()); emit(SpaceManagementLoading());
final success = final success = await _api.updateCommunity(
await _api.updateCommunity(event.communityUuid, event.name); event.communityUuid, event.name, projectUuid);
if (success) { if (success) {
if (previousState is SpaceManagementLoaded) { if (previousState is SpaceManagementLoaded) {
final updatedCommunities = final updatedCommunities =
@ -79,6 +94,8 @@ class SpaceManagementBloc
Future<List<SpaceTemplateModel>> fetchSpaceModels( Future<List<SpaceTemplateModel>> fetchSpaceModels(
SpaceManagementState previousState) async { SpaceManagementState previousState) async {
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
List<SpaceTemplateModel> allSpaces = []; List<SpaceTemplateModel> allSpaces = [];
List<SpaceTemplateModel> prevSpaceModels = []; List<SpaceTemplateModel> prevSpaceModels = [];
@ -95,7 +112,8 @@ class SpaceManagementBloc
int page = 1; int page = 1;
while (hasNext) { while (hasNext) {
final spaces = await _spaceModelApi.listSpaceModels(page: page); final spaces = await _spaceModelApi.listSpaceModels(
page: page, projectId: projectUuid);
if (spaces.isNotEmpty) { if (spaces.isNotEmpty) {
allSpaces.addAll(spaces); allSpaces.addAll(spaces);
page++; page++;
@ -103,7 +121,8 @@ class SpaceManagementBloc
hasNext = false; hasNext = false;
} }
} }
prevSpaceModels = await _spaceModelApi.listSpaceModels(page: 1); prevSpaceModels = await _spaceModelApi.listSpaceModels(
page: 1, projectId: projectUuid);
} }
return allSpaces; return allSpaces;
@ -132,7 +151,9 @@ class SpaceManagementBloc
Future<List<SpaceModel>> _fetchSpacesForCommunity( Future<List<SpaceModel>> _fetchSpacesForCommunity(
String communityUuid) async { String communityUuid) async {
return await _api.getSpaceHierarchy(communityUuid); final projectUuid = await ProjectManager.getProjectUUID() ?? '';
return await _api.getSpaceHierarchy(communityUuid, projectUuid);
} }
Future<void> _onNewCommunity( Future<void> _onNewCommunity(
@ -163,6 +184,8 @@ class SpaceManagementBloc
BlankStateEvent event, Emitter<SpaceManagementState> emit) async { BlankStateEvent event, Emitter<SpaceManagementState> emit) async {
try { try {
final previousState = state; final previousState = state;
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
var prevSpaceModels = await fetchSpaceModels(previousState); var prevSpaceModels = await fetchSpaceModels(previousState);
if (previousState is SpaceManagementLoaded || if (previousState is SpaceManagementLoaded ||
@ -176,7 +199,7 @@ class SpaceManagementBloc
return; return;
} }
final communities = await _api.fetchCommunities(); final communities = await _api.fetchCommunities(projectUuid);
final updatedCommunities = final updatedCommunities =
await Future.wait(communities.map((community) async { await Future.wait(communities.map((community) async {
final spaces = await _fetchSpacesForCommunity(community.uuid); final spaces = await _fetchSpacesForCommunity(community.uuid);
@ -206,11 +229,16 @@ class SpaceManagementBloc
LoadCommunityAndSpacesEvent event, LoadCommunityAndSpacesEvent event,
Emitter<SpaceManagementState> emit, Emitter<SpaceManagementState> emit,
) async { ) async {
_logEvent('LoadCommunityAndSpacesEvent');
var prevState = state; var prevState = state;
emit(SpaceManagementLoading()); emit(SpaceManagementLoading());
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
_onloadProducts(); _onloadProducts();
List<CommunityModel> communities = await _api.fetchCommunities(); List<CommunityModel> communities =
await _api.fetchCommunities(projectUuid);
List<CommunityModel> updatedCommunities = await Future.wait( List<CommunityModel> updatedCommunities = await Future.wait(
communities.map((community) async { communities.map((community) async {
@ -244,8 +272,10 @@ class SpaceManagementBloc
) async { ) async {
try { try {
emit(SpaceManagementLoading()); emit(SpaceManagementLoading());
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
final success = await _api.deleteCommunity(event.communityUuid); final success =
await _api.deleteCommunity(event.communityUuid, projectUuid);
if (success) { if (success) {
add(LoadCommunityAndSpacesEvent()); add(LoadCommunityAndSpacesEvent());
} else { } else {
@ -270,8 +300,10 @@ class SpaceManagementBloc
emit(SpaceManagementLoading()); emit(SpaceManagementLoading());
try { try {
CommunityModel? newCommunity = final projectUuid = await ProjectManager.getProjectUUID() ?? '';
await _api.createCommunity(event.name, event.description);
CommunityModel? newCommunity = await _api.createCommunity(
event.name, event.description, projectUuid);
var prevSpaceModels = await fetchSpaceModels(previousState); var prevSpaceModels = await fetchSpaceModels(previousState);
if (newCommunity != null) { if (newCommunity != null) {
@ -414,6 +446,7 @@ class SpaceManagementBloc
Future<List<SpaceModel>> saveSpacesHierarchically( Future<List<SpaceModel>> saveSpacesHierarchically(
List<SpaceModel> spaces, String communityUuid) async { List<SpaceModel> spaces, String communityUuid) async {
final orderedSpaces = flattenHierarchy(spaces); final orderedSpaces = flattenHierarchy(spaces);
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
final parentsToDelete = orderedSpaces.where((space) => final parentsToDelete = orderedSpaces.where((space) =>
space.status == SpaceStatus.deleted && space.status == SpaceStatus.deleted &&
@ -422,7 +455,7 @@ class SpaceManagementBloc
for (var parent in parentsToDelete) { for (var parent in parentsToDelete) {
try { try {
if (parent.uuid != null) { if (parent.uuid != null) {
await _api.deleteSpace(communityUuid, parent.uuid!); await _api.deleteSpace(communityUuid, parent.uuid!, projectUuid);
} }
} catch (e) { } catch (e) {
rethrow; rethrow;
@ -435,7 +468,8 @@ class SpaceManagementBloc
if (space.uuid != null && space.uuid!.isNotEmpty) { if (space.uuid != null && space.uuid!.isNotEmpty) {
List<TagModelUpdate> tagUpdates = []; List<TagModelUpdate> tagUpdates = [];
final prevSpace = await _api.getSpace(communityUuid, space.uuid!); final prevSpace =
await _api.getSpace(communityUuid, space.uuid!, projectUuid);
final List<UpdateSubspaceTemplateModel> subspaceUpdates = []; final List<UpdateSubspaceTemplateModel> subspaceUpdates = [];
final List<SubspaceModel>? prevSubspaces = prevSpace?.subspaces; final List<SubspaceModel>? prevSubspaces = prevSpace?.subspaces;
final List<SubspaceModel>? newSubspaces = space.subspaces; final List<SubspaceModel>? newSubspaces = space.subspaces;
@ -514,7 +548,7 @@ class SpaceManagementBloc
subspaces: subspaceUpdates, subspaces: subspaceUpdates,
tags: tagUpdates, tags: tagUpdates,
direction: space.incomingConnection?.direction, direction: space.incomingConnection?.direction,
); projectId: projectUuid);
} else { } else {
// Call create if the space does not have a UUID // Call create if the space does not have a UUID
final List<CreateTagBodyModel> tagBodyModels = space.tags != null final List<CreateTagBodyModel> tagBodyModels = space.tags != null
@ -543,7 +577,7 @@ class SpaceManagementBloc
spaceModelUuid: space.spaceModel?.uuid, spaceModelUuid: space.spaceModel?.uuid,
tags: tagBodyModels, tags: tagBodyModels,
subspaces: createSubspaceBodyModels, subspaces: createSubspaceBodyModels,
); projectId: projectUuid);
space.uuid = response?.uuid; space.uuid = response?.uuid;
} }
} catch (e) { } catch (e) {
@ -583,8 +617,10 @@ class SpaceManagementBloc
emit(SpaceManagementLoading()); emit(SpaceManagementLoading());
try { try {
var prevState = state; var prevState = state;
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
List<CommunityModel> communities = await _api.fetchCommunities(); List<CommunityModel> communities =
await _api.fetchCommunities(projectUuid);
List<CommunityModel> updatedCommunities = await Future.wait( List<CommunityModel> updatedCommunities = await Future.wait(
communities.map((community) async { communities.map((community) async {

View File

@ -28,8 +28,11 @@ class SpaceManagementPageState extends State<SpaceManagementPage> {
return MultiBlocProvider( return MultiBlocProvider(
providers: [ providers: [
BlocProvider( BlocProvider(
create: (_) => SpaceManagementBloc(_api, _productApi, _spaceModelApi) create: (_) => SpaceManagementBloc(
..add(LoadCommunityAndSpacesEvent()), _api,
_productApi,
_spaceModelApi,
)..add(LoadCommunityAndSpacesEvent()),
), ),
BlocProvider( BlocProvider(
create: (_) => CenterBodyBloc(), create: (_) => CenterBodyBloc(),

View File

@ -1,5 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/space_tree/view/space_tree_view.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart'; import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
@ -74,16 +75,11 @@ class _LoadedSpaceViewState extends State<LoadedSpaceView> {
return Stack( return Stack(
clipBehavior: Clip.none, clipBehavior: Clip.none,
children: [ children: [
Row(
children: [
SidebarWidget(
communities: widget.communities,
selectedSpaceUuid: widget.selectedSpace?.uuid ??
widget.selectedCommunity?.uuid ??
'',
),
widget.shouldNavigateToSpaceModelPage widget.shouldNavigateToSpaceModelPage
? Expanded( ? Row(
children: [
SizedBox(width: 300, child: SpaceTreeView(onSelect: () {})),
Expanded(
child: BlocProvider( child: BlocProvider(
create: (context) => SpaceModelBloc( create: (context) => SpaceModelBloc(
api: SpaceModelManagementApi(), api: SpaceModelManagementApi(),
@ -94,8 +90,17 @@ class _LoadedSpaceViewState extends State<LoadedSpaceView> {
onSpaceModelsUpdated: _onSpaceModelsUpdated, onSpaceModelsUpdated: _onSpaceModelsUpdated,
), ),
), ),
),
],
) )
: CommunityStructureArea( : Row(
children: [
SidebarWidget(
communities: widget.communities,
selectedSpaceUuid:
widget.selectedSpace?.uuid ?? widget.selectedCommunity?.uuid ?? '',
),
CommunityStructureArea(
selectedCommunity: widget.selectedCommunity, selectedCommunity: widget.selectedCommunity,
selectedSpace: widget.selectedSpace, selectedSpace: widget.selectedSpace,
spaces: widget.selectedCommunity?.spaces ?? [], spaces: widget.selectedCommunity?.spaces ?? [],

View File

@ -1,4 +1,5 @@
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_state.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/create_space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/create_space_template_body_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/create_space_template_body_model.dart';
@ -8,6 +9,9 @@ import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_model
import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/tag_update_model.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart'; import 'package:syncrow_web/services/space_model_mang_api.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart'; import 'package:syncrow_web/utils/constants/action_enum.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
class CreateSpaceModelBloc class CreateSpaceModelBloc
extends Bloc<CreateSpaceModelEvent, CreateSpaceModelState> { extends Bloc<CreateSpaceModelEvent, CreateSpaceModelState> {
@ -18,6 +22,8 @@ class CreateSpaceModelBloc
CreateSpaceModelBloc(this._api) : super(CreateSpaceModelInitial()) { CreateSpaceModelBloc(this._api) : super(CreateSpaceModelInitial()) {
on<CreateSpaceTemplate>((event, emit) async { on<CreateSpaceTemplate>((event, emit) async {
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
late SpaceTemplateModel spaceTemplate = event.spaceTemplate; late SpaceTemplateModel spaceTemplate = event.spaceTemplate;
final tagBodyModels = final tagBodyModels =
@ -40,7 +46,8 @@ class CreateSpaceModelBloc
tags: tagBodyModels, tags: tagBodyModels,
subspaceModels: subspaceTemplateBodyModels); subspaceModels: subspaceTemplateBodyModels);
final newSpaceTemplate = await _api.createSpaceModel(spaceModelBody); final newSpaceTemplate =
await _api.createSpaceModel(spaceModelBody, projectUuid);
spaceTemplate.uuid = newSpaceTemplate?.uuid ?? ''; spaceTemplate.uuid = newSpaceTemplate?.uuid ?? '';
if (newSpaceTemplate != null) { if (newSpaceTemplate != null) {
@ -201,9 +208,11 @@ class CreateSpaceModelBloc
on<ModifySpaceTemplate>((event, emit) async { on<ModifySpaceTemplate>((event, emit) async {
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
if (event.spaceTemplate.uuid != null) { if (event.spaceTemplate.uuid != null) {
final prevSpaceModel = final prevSpaceModel = await _api.getSpaceModel(
await _api.getSpaceModel(event.spaceTemplate.uuid ?? ''); event.spaceTemplate.uuid ?? '', projectUuid);
final newSpaceModel = event.updatedSpaceTemplate; final newSpaceModel = event.updatedSpaceTemplate;
String? spaceModelName; String? spaceModelName;
@ -287,7 +296,7 @@ class CreateSpaceModelBloc
subspaceModels: subspaceUpdates); subspaceModels: subspaceUpdates);
final res = await _api.updateSpaceModel( final res = await _api.updateSpaceModel(
spaceModelBody, prevSpaceModel?.uuid ?? ''); spaceModelBody, prevSpaceModel?.uuid ?? '', projectUuid);
if (res != null) { if (res != null) {
emit(CreateSpaceModelLoaded(newSpaceModel)); emit(CreateSpaceModelLoaded(newSpaceModel));

View File

@ -1,8 +1,12 @@
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_event.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_state.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/bloc/space_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart'; import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart'; import 'package:syncrow_web/services/space_model_mang_api.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
class SpaceModelBloc extends Bloc<SpaceModelEvent, SpaceModelState> { class SpaceModelBloc extends Bloc<SpaceModelEvent, SpaceModelState> {
final SpaceModelManagementApi api; final SpaceModelManagementApi api;
@ -18,10 +22,13 @@ class SpaceModelBloc extends Bloc<SpaceModelEvent, SpaceModelState> {
Future<void> _onCreateSpaceModel( Future<void> _onCreateSpaceModel(
CreateSpaceModel event, Emitter<SpaceModelState> emit) async { CreateSpaceModel event, Emitter<SpaceModelState> emit) async {
final currentState = state; final currentState = state;
if (currentState is SpaceModelLoaded) { if (currentState is SpaceModelLoaded) {
try { try {
final newSpaceModel = final projectUuid = await ProjectManager.getProjectUUID() ?? '';
await api.getSpaceModel(event.newSpaceModel.uuid ?? '');
final newSpaceModel = await api.getSpaceModel(
event.newSpaceModel.uuid ?? '', projectUuid);
if (newSpaceModel != null) { if (newSpaceModel != null) {
final updatedSpaceModels = final updatedSpaceModels =
@ -40,8 +47,10 @@ class SpaceModelBloc extends Bloc<SpaceModelEvent, SpaceModelState> {
final currentState = state; final currentState = state;
if (currentState is SpaceModelLoaded) { if (currentState is SpaceModelLoaded) {
try { try {
final projectUuid = await ProjectManager.getProjectUUID() ?? '';
final newSpaceModel = final newSpaceModel =
await api.getSpaceModel(event.spaceModelUuid ?? ''); await api.getSpaceModel(event.spaceModelUuid ?? '', projectUuid);
if (newSpaceModel != null) { if (newSpaceModel != null) {
final updatedSpaceModels = currentState.spaceModels.map((model) { final updatedSpaceModels = currentState.spaceModels.map((model) {
return model.uuid == event.spaceModelUuid ? newSpaceModel : model; return model.uuid == event.spaceModelUuid ? newSpaceModel : model;

View File

@ -50,7 +50,9 @@ class CreateSpaceModelDialog extends StatelessWidget {
width: screenWidth * 0.3, width: screenWidth * 0.3,
child: BlocProvider( child: BlocProvider(
create: (_) { create: (_) {
final bloc = CreateSpaceModelBloc(_spaceModelApi); final bloc = CreateSpaceModelBloc(
_spaceModelApi,
);
if (spaceModel != null) { if (spaceModel != null) {
bloc.add(UpdateSpaceTemplate(spaceModel!, otherSpaceModels)); bloc.add(UpdateSpaceTemplate(spaceModel!, otherSpaceModels));
} else { } else {

View File

@ -3,6 +3,7 @@ import 'package:dio/dio.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/custom_dialog.dart'; import 'package:syncrow_web/pages/common/custom_dialog.dart';
import 'package:syncrow_web/pages/common/hour_picker_dialog.dart'; import 'package:syncrow_web/pages/common/hour_picker_dialog.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_event.dart'; import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_event.dart';
@ -13,9 +14,14 @@ import 'package:syncrow_web/pages/visitor_password/model/schedule_model.dart';
import 'package:syncrow_web/services/access_mang_api.dart'; import 'package:syncrow_web/services/access_mang_api.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/constants/strings_manager.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart';
import 'package:syncrow_web/utils/helpers/shared_preferences_helper.dart';
import 'package:syncrow_web/utils/snack_bar.dart'; import 'package:syncrow_web/utils/snack_bar.dart';
class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordState> { class VisitorPasswordBloc
extends Bloc<VisitorPasswordEvent, VisitorPasswordState> {
VisitorPasswordBloc() : super(VisitorPasswordInitial()) { VisitorPasswordBloc() : super(VisitorPasswordInitial()) {
on<SelectUsageFrequency>(selectUsageFrequency); on<SelectUsageFrequency>(selectUsageFrequency);
on<FetchDevice>(_onFetchDevice); on<FetchDevice>(_onFetchDevice);
@ -38,7 +44,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
final TextEditingController deviceNameController = TextEditingController(); final TextEditingController deviceNameController = TextEditingController();
final TextEditingController deviceIdController = TextEditingController(); final TextEditingController deviceIdController = TextEditingController();
final TextEditingController unitNameController = TextEditingController(); final TextEditingController unitNameController = TextEditingController();
final TextEditingController virtualAddressController = TextEditingController(); final TextEditingController virtualAddressController =
TextEditingController();
List<String> selectedDevices = []; List<String> selectedDevices = [];
List<DeviceModel> data = []; List<DeviceModel> data = [];
@ -64,12 +71,14 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
String startTimeAccess = 'Start Time'; String startTimeAccess = 'Start Time';
String endTimeAccess = 'End Time'; String endTimeAccess = 'End Time';
PasswordStatus? passwordStatus; PasswordStatus? passwordStatus;
selectAccessType(SelectPasswordType event, Emitter<VisitorPasswordState> emit) { selectAccessType(
SelectPasswordType event, Emitter<VisitorPasswordState> emit) {
accessTypeSelected = event.type; accessTypeSelected = event.type;
emit(PasswordTypeSelected(event.type)); emit(PasswordTypeSelected(event.type));
} }
selectUsageFrequency(SelectUsageFrequency event, Emitter<VisitorPasswordState> emit) { selectUsageFrequency(
SelectUsageFrequency event, Emitter<VisitorPasswordState> emit) {
usageFrequencySelected = event.usageType; usageFrequencySelected = event.usageType;
emit(UsageFrequencySelected(event.usageType)); emit(UsageFrequencySelected(event.usageType));
} }
@ -116,10 +125,12 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
timePicked.minute, timePicked.minute,
); );
final selectedTimestamp = selectedDateTime.millisecondsSinceEpoch ~/ 1000; final selectedTimestamp =
selectedDateTime.millisecondsSinceEpoch ~/ 1000;
if (event.isStart) { if (event.isStart) {
if (expirationTimeTimeStamp != null && selectedTimestamp > expirationTimeTimeStamp!) { if (expirationTimeTimeStamp != null &&
selectedTimestamp > expirationTimeTimeStamp!) {
CustomSnackBar.displaySnackBar( CustomSnackBar.displaySnackBar(
'Effective Time cannot be later than Expiration Time.', 'Effective Time cannot be later than Expiration Time.',
); );
@ -128,7 +139,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
effectiveTimeTimeStamp = selectedTimestamp; effectiveTimeTimeStamp = selectedTimestamp;
startTimeAccess = selectedDateTime.toString().split('.').first; startTimeAccess = selectedDateTime.toString().split('.').first;
} else { } else {
if (effectiveTimeTimeStamp != null && selectedTimestamp < effectiveTimeTimeStamp!) { if (effectiveTimeTimeStamp != null &&
selectedTimestamp < effectiveTimeTimeStamp!) {
CustomSnackBar.displaySnackBar( CustomSnackBar.displaySnackBar(
'Expiration Time cannot be earlier than Effective Time.', 'Expiration Time cannot be earlier than Effective Time.',
); );
@ -143,7 +155,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
} }
} }
bool toggleRepeat(ToggleRepeatEvent event, Emitter<VisitorPasswordState> emit) { bool toggleRepeat(
ToggleRepeatEvent event, Emitter<VisitorPasswordState> emit) {
emit(LoadingInitialState()); emit(LoadingInitialState());
repeat = !repeat; repeat = !repeat;
emit(IsRepeatState(repeat: repeat)); emit(IsRepeatState(repeat: repeat));
@ -175,10 +188,13 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
emit(ChangeTimeState()); emit(ChangeTimeState());
} }
Future<void> _onFetchDevice(FetchDevice event, Emitter<VisitorPasswordState> emit) async { Future<void> _onFetchDevice(
FetchDevice event, Emitter<VisitorPasswordState> emit) async {
try { try {
emit(DeviceLoaded()); emit(DeviceLoaded());
data = await AccessMangApi().fetchDevices(); final projectUuid = await ProjectManager.getProjectUUID() ?? '';
data = await AccessMangApi().fetchDevices(projectUuid);
emit(TableLoaded(data)); emit(TableLoaded(data));
} catch (e) { } catch (e) {
emit(FailedState(e.toString())); emit(FailedState(e.toString()));
@ -186,8 +202,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
} }
//online password //online password
Future<void> postOnlineOneTimePassword( Future<void> postOnlineOneTimePassword(OnlineOneTimePasswordEvent event,
OnlineOneTimePasswordEvent event, Emitter<VisitorPasswordState> emit) async { Emitter<VisitorPasswordState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
generate7DigitNumber(); generate7DigitNumber();
@ -211,7 +227,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
} }
Future<void> postOnlineMultipleTimePassword( Future<void> postOnlineMultipleTimePassword(
OnlineMultipleTimePasswordEvent event, Emitter<VisitorPasswordState> emit) async { OnlineMultipleTimePasswordEvent event,
Emitter<VisitorPasswordState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
@ -221,7 +238,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
if (repeat) if (repeat)
Schedule( Schedule(
effectiveTime: getTimeFromDateTimeString(effectiveTime), effectiveTime: getTimeFromDateTimeString(effectiveTime),
invalidTime: getTimeFromDateTimeString(expirationTime).toString(), invalidTime:
getTimeFromDateTimeString(expirationTime).toString(),
workingDay: selectedDays, workingDay: selectedDays,
), ),
], ],
@ -244,13 +262,15 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
} }
//offline password //offline password
Future<void> postOfflineOneTimePassword( Future<void> postOfflineOneTimePassword(OfflineOneTimePasswordEvent event,
OfflineOneTimePasswordEvent event, Emitter<VisitorPasswordState> emit) async { Emitter<VisitorPasswordState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
await generate7DigitNumber(); await generate7DigitNumber();
var res = await AccessMangApi().postOffLineOneTime( var res = await AccessMangApi().postOffLineOneTime(
email: event.email, devicesUuid: selectedDevices, passwordName: event.passwordName); email: event.email,
devicesUuid: selectedDevices,
passwordName: event.passwordName);
if (res['statusCode'] == 201) { if (res['statusCode'] == 201) {
passwordStatus = PasswordStatus.fromJson(res['data']); passwordStatus = PasswordStatus.fromJson(res['data']);
emit(SuccessState()); emit(SuccessState());
@ -264,7 +284,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
} }
Future<void> postOfflineMultipleTimePassword( Future<void> postOfflineMultipleTimePassword(
OfflineMultipleTimePasswordEvent event, Emitter<VisitorPasswordState> emit) async { OfflineMultipleTimePasswordEvent event,
Emitter<VisitorPasswordState> emit) async {
try { try {
emit(LoadingInitialState()); emit(LoadingInitialState());
await generate7DigitNumber(); await generate7DigitNumber();
@ -287,7 +308,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
} }
} }
void selectDevice(SelectDeviceEvent event, Emitter<VisitorPasswordState> emit) { void selectDevice(
SelectDeviceEvent event, Emitter<VisitorPasswordState> emit) {
if (selectedDeviceIds.contains(event.deviceId)) { if (selectedDeviceIds.contains(event.deviceId)) {
selectedDeviceIds.remove(event.deviceId); selectedDeviceIds.remove(event.deviceId);
} else { } else {
@ -329,7 +351,8 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
add(UpdateFilteredDevicesEvent(filteredData)); add(UpdateFilteredDevicesEvent(filteredData));
} }
Stream<VisitorPasswordState> mapEventToState(VisitorPasswordEvent event) async* { Stream<VisitorPasswordState> mapEventToState(
VisitorPasswordEvent event) async* {
if (event is FetchDevice) { if (event is FetchDevice) {
} else if (event is UpdateFilteredDevicesEvent) { } else if (event is UpdateFilteredDevicesEvent) {
yield TableLoaded(event.filteredData); yield TableLoaded(event.filteredData);
@ -378,16 +401,20 @@ class VisitorPasswordBloc extends Bloc<VisitorPasswordEvent, VisitorPasswordStat
).millisecondsSinceEpoch ~/ ).millisecondsSinceEpoch ~/
1000; // Divide by 1000 to remove milliseconds 1000; // Divide by 1000 to remove milliseconds
if (event.isEffective) { if (event.isEffective) {
if (expirationTimeTimeStamp != null && selectedTimestamp > expirationTimeTimeStamp!) { if (expirationTimeTimeStamp != null &&
accessPeriodValidate = "Effective Time cannot be later than Expiration Time."; selectedTimestamp > expirationTimeTimeStamp!) {
accessPeriodValidate =
"Effective Time cannot be later than Expiration Time.";
} else { } else {
accessPeriodValidate = ''; accessPeriodValidate = '';
effectiveTime = selectedDateTime.toString().split('.').first; effectiveTime = selectedDateTime.toString().split('.').first;
effectiveTimeTimeStamp = selectedTimestamp; effectiveTimeTimeStamp = selectedTimestamp;
} }
} else { } else {
if (effectiveTimeTimeStamp != null && selectedTimestamp < effectiveTimeTimeStamp!) { if (effectiveTimeTimeStamp != null &&
accessPeriodValidate = 'Expiration Time cannot be earlier than Effective Time.'; selectedTimestamp < effectiveTimeTimeStamp!) {
accessPeriodValidate =
'Expiration Time cannot be earlier than Effective Time.';
} else { } else {
accessPeriodValidate = ''; accessPeriodValidate = '';
expirationTime = selectedDateTime.toString().split('.').first; expirationTime = selectedDateTime.toString().split('.').first;

View File

@ -23,6 +23,7 @@ class DeviceModel {
dynamic timeZone; dynamic timeZone;
dynamic updateTime; dynamic updateTime;
dynamic uuid; dynamic uuid;
dynamic spaceName;
DeviceModel({ DeviceModel({
required this.productUuid, required this.productUuid,
@ -45,6 +46,7 @@ class DeviceModel {
required this.timeZone, required this.timeZone,
required this.updateTime, required this.updateTime,
required this.uuid, required this.uuid,
required this.spaceName,
}); });
// Deserialize from JSON // Deserialize from JSON
@ -53,7 +55,8 @@ class DeviceModel {
DeviceType type = devicesTypesMap[json['productType']] ?? DeviceType.Other; DeviceType type = devicesTypesMap[json['productType']] ?? DeviceType.Other;
if (type == DeviceType.LightBulb) { if (type == DeviceType.LightBulb) {
tempIcon = Assets.lightBulb; tempIcon = Assets.lightBulb;
} else if (type == DeviceType.CeilingSensor || type == DeviceType.WallSensor) { } else if (type == DeviceType.CeilingSensor ||
type == DeviceType.WallSensor) {
tempIcon = Assets.sensors; tempIcon = Assets.sensors;
} else if (type == DeviceType.AC) { } else if (type == DeviceType.AC) {
tempIcon = Assets.ac; tempIcon = Assets.ac;
@ -102,6 +105,7 @@ class DeviceModel {
timeZone: json['timeZone'], timeZone: json['timeZone'],
updateTime: json['updateTime'], updateTime: json['updateTime'],
uuid: json['uuid'], uuid: json['uuid'],
spaceName: json['spaceName'],
); );
} }
@ -128,6 +132,7 @@ class DeviceModel {
'timeZone': timeZone, 'timeZone': timeZone,
'updateTime': updateTime, 'updateTime': updateTime,
'uuid': uuid, 'uuid': uuid,
'spaceName': spaceName
}; };
} }
} }

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/common/access_device_table.dart'; import 'package:syncrow_web/pages/common/access_device_table.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart'; import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart'; import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart';
@ -19,7 +20,8 @@ class AddDeviceDialog extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size; Size size = MediaQuery.of(context).size;
return BlocProvider( return BlocProvider(
create: (context) => VisitorPasswordBloc()..add(FetchDevice()), create: (context) =>
VisitorPasswordBloc()..add(FetchDevice()),
child: BlocBuilder<VisitorPasswordBloc, VisitorPasswordState>( child: BlocBuilder<VisitorPasswordBloc, VisitorPasswordState>(
builder: (BuildContext context, VisitorPasswordState state) { builder: (BuildContext context, VisitorPasswordState state) {
final visitorBloc = BlocProvider.of<VisitorPasswordBloc>(context); final visitorBloc = BlocProvider.of<VisitorPasswordBloc>(context);
@ -35,10 +37,10 @@ class AddDeviceDialog extends StatelessWidget {
backgroundColor: Colors.white, backgroundColor: Colors.white,
title: Text( title: Text(
'Add Accessible Device', 'Add Accessible Device',
style: Theme.of(context) style: Theme.of(context).textTheme.headlineLarge!.copyWith(
.textTheme fontWeight: FontWeight.w400,
.headlineLarge! fontSize: 24,
.copyWith(fontWeight: FontWeight.w400, fontSize: 24, color: Colors.black), color: Colors.black),
), ),
content: SizedBox( content: SizedBox(
height: MediaQuery.of(context).size.height / 1.7, height: MediaQuery.of(context).size.height / 1.7,
@ -68,7 +70,10 @@ class AddDeviceDialog extends StatelessWidget {
), ),
Text( Text(
'Only online accessible devices can be added', 'Only online accessible devices can be added',
style: Theme.of(context).textTheme.bodySmall!.copyWith( style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(
fontWeight: FontWeight.w400, fontWeight: FontWeight.w400,
fontSize: 12, fontSize: 12,
color: ColorsManager.grayColor), color: ColorsManager.grayColor),
@ -152,7 +157,8 @@ class AddDeviceDialog extends StatelessWidget {
visitorBloc.deviceNameController.clear(); visitorBloc.deviceNameController.clear();
visitorBloc.deviceIdController.clear(); visitorBloc.deviceIdController.clear();
visitorBloc.unitNameController.clear(); visitorBloc.unitNameController.clear();
visitorBloc.add(FetchDevice()); // Reset to original list visitorBloc.add(
FetchDevice()); // Reset to original list
}, },
), ),
), ),
@ -172,7 +178,8 @@ class AddDeviceDialog extends StatelessWidget {
selectAll: (p0) { selectAll: (p0) {
visitorBloc.selectedDeviceIds.clear(); visitorBloc.selectedDeviceIds.clear();
for (var item in state.data) { for (var item in state.data) {
visitorBloc.add(SelectDeviceEvent(item.uuid)); visitorBloc
.add(SelectDeviceEvent(item.uuid));
} }
}, },
onRowSelected: (index, isSelected, row) { onRowSelected: (index, isSelected, row) {
@ -193,7 +200,7 @@ class AddDeviceDialog extends StatelessWidget {
item.name.toString(), item.name.toString(),
item.uuid.toString(), item.uuid.toString(),
item.productType.toString(), item.productType.toString(),
'', item.spaceName.toString(),
item.online.value.toString(), item.online.value.toString(),
]; ];
}).toList(), }).toList(),

View File

@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/common/date_time_widget.dart'; import 'package:syncrow_web/pages/common/date_time_widget.dart';
import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart'; import 'package:syncrow_web/pages/common/text_field/custom_web_textfield.dart';

View File

@ -6,10 +6,10 @@ import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart'; import 'package:syncrow_web/utils/constants/api_const.dart';
class AccessMangApi { class AccessMangApi {
Future<List<PasswordModel>> fetchVisitorPassword() async { Future<List<PasswordModel>> fetchVisitorPassword(String projectId) async {
try { try {
final response = await HTTPService().get( final response = await HTTPService().get(
path: ApiEndpoints.visitorPassword, path: ApiEndpoints.visitorPassword.replaceAll('{projectId}', projectId),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
List<dynamic> jsonData = json; List<dynamic> jsonData = json;
@ -25,10 +25,10 @@ class AccessMangApi {
} }
} }
Future fetchDevices() async { Future fetchDevices(String projectId) async {
try { try {
final response = await HTTPService().get( final response = await HTTPService().get(
path: ApiEndpoints.getDevices, path: ApiEndpoints.getDevices.replaceAll('{projectId}', projectId),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
List<dynamic> jsonData = json; List<dynamic> jsonData = json;
@ -86,7 +86,8 @@ class AccessMangApi {
"invalidTime": invalidTime, "invalidTime": invalidTime,
}; };
if (scheduleList != null) { if (scheduleList != null) {
body["scheduleList"] = scheduleList.map((schedule) => schedule.toJson()).toList(); body["scheduleList"] =
scheduleList.map((schedule) => schedule.toJson()).toList();
} }
final response = await HTTPService().post( final response = await HTTPService().post(
path: ApiEndpoints.sendOnlineMultipleTime, path: ApiEndpoints.sendOnlineMultipleTime,
@ -105,7 +106,11 @@ class AccessMangApi {
{String? email, String? passwordName, List<String>? devicesUuid}) async { {String? email, String? passwordName, List<String>? devicesUuid}) async {
final response = await HTTPService().post( final response = await HTTPService().post(
path: ApiEndpoints.sendOffLineOneTime, path: ApiEndpoints.sendOffLineOneTime,
body: jsonEncode({"email": email, "passwordName": passwordName, "devicesUuid": devicesUuid}), body: jsonEncode({
"email": email,
"passwordName": passwordName,
"devicesUuid": devicesUuid
}),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json; return json;

View File

@ -12,15 +12,15 @@ import 'package:syncrow_web/utils/constants/api_const.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart'; import 'package:syncrow_web/utils/constants/temp_const.dart';
class DevicesManagementApi { class DevicesManagementApi {
Future<List<AllDevicesModel>> fetchDevices(String communityId, String spaceId) async { Future<List<AllDevicesModel>> fetchDevices(String communityId, String spaceId, String projectId) async {
try { try {
final response = await HTTPService().get( final response = await HTTPService().get(
path: communityId.isNotEmpty && spaceId.isNotEmpty path: communityId.isNotEmpty && spaceId.isNotEmpty
? ApiEndpoints.getSpaceDevices ? ApiEndpoints.getSpaceDevices
.replaceAll('{spaceUuid}', spaceId) .replaceAll('{spaceUuid}', spaceId)
.replaceAll('{communityUuid}', communityId) .replaceAll('{communityUuid}', communityId)
.replaceAll('{projectId}', TempConst.projectId) .replaceAll('{projectId}', projectId)
: ApiEndpoints.getAllDevices, : ApiEndpoints.getAllDevices.replaceAll('{projectId}', projectId),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
List<dynamic> jsonData = List<dynamic> jsonData =

View File

@ -12,7 +12,8 @@ class SceneApi {
static final HTTPService _httpService = HTTPService(); static final HTTPService _httpService = HTTPService();
// //create scene // //create scene
static Future<Map<String, dynamic>> createScene(CreateSceneModel createSceneModel) async { static Future<Map<String, dynamic>> createScene(
CreateSceneModel createSceneModel) async {
try { try {
debugPrint('create scene model: ${createSceneModel.toMap()}'); debugPrint('create scene model: ${createSceneModel.toMap()}');
final response = await _httpService.post( final response = await _httpService.post(
@ -69,14 +70,15 @@ class SceneApi {
//get scenes by community id and space id //get scenes by community id and space id
static Future<List<ScenesModel>> getScenes(String spaceId, String communityId, static Future<List<ScenesModel>> getScenes(
String spaceId, String communityId, String projectId,
{showInDevice = false}) async { {showInDevice = false}) async {
try { try {
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.getUnitScenes path: ApiEndpoints.getUnitScenes
.replaceAll('{spaceUuid}', spaceId) .replaceAll('{spaceUuid}', spaceId)
.replaceAll('{communityUuid}', communityId) .replaceAll('{communityUuid}', communityId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
queryParameters: {'showInHomePage': showInDevice}, queryParameters: {'showInHomePage': showInDevice},
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) { expectedResponseModel: (json) {
@ -100,7 +102,8 @@ class SceneApi {
static Future<List<ScenesModel>> getAutomation(String spaceId) async { static Future<List<ScenesModel>> getAutomation(String spaceId) async {
try { try {
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.getSpaceAutomation.replaceAll('{spaceUuid}', spaceId), path:
ApiEndpoints.getSpaceAutomation.replaceAll('{spaceUuid}', spaceId),
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) { expectedResponseModel: (json) {
List<ScenesModel> scenes = []; List<ScenesModel> scenes = [];
@ -130,10 +133,12 @@ class SceneApi {
// } // }
//automation details //automation details
static Future<RoutineDetailsModel> getAutomationDetails(String automationId) async { static Future<RoutineDetailsModel> getAutomationDetails(
String automationId) async {
try { try {
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.getAutomationDetails.replaceAll('{automationId}', automationId), path: ApiEndpoints.getAutomationDetails
.replaceAll('{automationId}', automationId),
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) => RoutineDetailsModel.fromMap(json), expectedResponseModel: (json) => RoutineDetailsModel.fromMap(json),
); );
@ -148,7 +153,8 @@ class SceneApi {
try { try {
final response = await _httpService.put( final response = await _httpService.put(
path: ApiEndpoints.updateScene.replaceAll('{sceneId}', sceneId), path: ApiEndpoints.updateScene.replaceAll('{sceneId}', sceneId),
body: createSceneModel.toJson(sceneId.isNotEmpty == true ? sceneId : null), body: createSceneModel
.toJson(sceneId.isNotEmpty == true ? sceneId : null),
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json; return json;
}, },
@ -160,11 +166,14 @@ class SceneApi {
} }
//update automation //update automation
static updateAutomation(CreateAutomationModel createAutomationModel, String automationId) async { static updateAutomation(
CreateAutomationModel createAutomationModel, String automationId) async {
try { try {
final response = await _httpService.put( final response = await _httpService.put(
path: ApiEndpoints.updateAutomation.replaceAll('{automationId}', automationId), path: ApiEndpoints.updateAutomation
body: createAutomationModel.toJson(automationId.isNotEmpty == true ? automationId : null), .replaceAll('{automationId}', automationId),
body: createAutomationModel
.toJson(automationId.isNotEmpty == true ? automationId : null),
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json; return json;
}, },
@ -181,7 +190,8 @@ class SceneApi {
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.getScene.replaceAll('{sceneId}', sceneId), path: ApiEndpoints.getScene.replaceAll('{sceneId}', sceneId),
showServerMessage: false, showServerMessage: false,
expectedResponseModel: (json) => RoutineDetailsModel.fromMap(json['data']), expectedResponseModel: (json) =>
RoutineDetailsModel.fromMap(json['data']),
); );
return response; return response;
} catch (e) { } catch (e) {
@ -190,7 +200,8 @@ class SceneApi {
} }
//delete Scene //delete Scene
static Future<bool> deleteScene({required String unitUuid, required String sceneId}) async { static Future<bool> deleteScene(
{required String unitUuid, required String sceneId}) async {
try { try {
final response = await _httpService.delete( final response = await _httpService.delete(
path: ApiEndpoints.deleteScene path: ApiEndpoints.deleteScene

View File

@ -13,7 +13,8 @@ import 'package:syncrow_web/utils/constants/temp_const.dart';
class CommunitySpaceManagementApi { class CommunitySpaceManagementApi {
// Community Management APIs // Community Management APIs
Future<List<CommunityModel>> fetchCommunities({int page = 1}) async { Future<List<CommunityModel>> fetchCommunities(String projectId,
{int page = 1}) async {
try { try {
List<CommunityModel> allCommunities = []; List<CommunityModel> allCommunities = [];
bool hasNext = true; bool hasNext = true;
@ -21,7 +22,7 @@ class CommunitySpaceManagementApi {
while (hasNext) { while (hasNext) {
await HTTPService().get( await HTTPService().get(
path: ApiEndpoints.getCommunityList path: ApiEndpoints.getCommunityList
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
queryParameters: {'page': page}, queryParameters: {'page': page},
expectedResponseModel: (json) { expectedResponseModel: (json) {
try { try {
@ -65,11 +66,10 @@ class CommunitySpaceManagementApi {
} }
Future<CommunityModel?> createCommunity( Future<CommunityModel?> createCommunity(
String name, String description) async { String name, String description, String projectId) async {
try { try {
final response = await HTTPService().post( final response = await HTTPService().post(
path: ApiEndpoints.createCommunity path: ApiEndpoints.createCommunity.replaceAll('{projectId}', projectId),
.replaceAll('{projectId}', TempConst.projectId),
body: { body: {
'name': name, 'name': name,
'description': description, 'description': description,
@ -85,12 +85,13 @@ class CommunitySpaceManagementApi {
} }
} }
Future<bool> updateCommunity(String communityId, String name) async { Future<bool> updateCommunity(
String communityId, String name, String projectId) async {
try { try {
final response = await HTTPService().put( final response = await HTTPService().put(
path: ApiEndpoints.updateCommunity path: ApiEndpoints.updateCommunity
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
body: { body: {
'name': name, 'name': name,
}, },
@ -105,12 +106,12 @@ class CommunitySpaceManagementApi {
} }
} }
Future<bool> deleteCommunity(String communityId) async { Future<bool> deleteCommunity(String communityId, String projectId) async {
try { try {
final response = await HTTPService().delete( final response = await HTTPService().delete(
path: ApiEndpoints.deleteCommunity path: ApiEndpoints.deleteCommunity
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json['success'] ?? false; return json['success'] ?? false;
}, },
@ -122,12 +123,13 @@ class CommunitySpaceManagementApi {
} }
} }
Future<SpacesResponse> fetchSpaces(String communityId) async { Future<SpacesResponse> fetchSpaces(
String communityId, String projectId) async {
try { try {
final response = await HTTPService().get( final response = await HTTPService().get(
path: ApiEndpoints.listSpaces path: ApiEndpoints.listSpaces
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
expectedResponseModel: (json) { expectedResponseModel: (json) {
return SpacesResponse.fromJson(json); return SpacesResponse.fromJson(json);
}, },
@ -148,13 +150,14 @@ class CommunitySpaceManagementApi {
} }
} }
Future<SpaceModel?> getSpace(String communityId, String spaceId) async { Future<SpaceModel?> getSpace(
String communityId, String spaceId, String projectId) async {
try { try {
final response = await HTTPService().get( final response = await HTTPService().get(
path: ApiEndpoints.getSpace path: ApiEndpoints.getSpace
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{spaceId}', spaceId) .replaceAll('{spaceId}', spaceId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
expectedResponseModel: (json) { expectedResponseModel: (json) {
return SpaceModel.fromJson(json['data']); return SpaceModel.fromJson(json['data']);
}, },
@ -176,7 +179,8 @@ class CommunitySpaceManagementApi {
String? spaceModelUuid, String? spaceModelUuid,
String? icon, String? icon,
List<CreateTagBodyModel>? tags, List<CreateTagBodyModel>? tags,
List<CreateSubspaceModel>? subspaces}) async { List<CreateSubspaceModel>? subspaces,
required String projectId}) async {
try { try {
final body = { final body = {
'spaceName': name, 'spaceName': name,
@ -199,7 +203,7 @@ class CommunitySpaceManagementApi {
final response = await HTTPService().post( final response = await HTTPService().post(
path: ApiEndpoints.createSpace path: ApiEndpoints.createSpace
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
body: body, body: body,
expectedResponseModel: (json) { expectedResponseModel: (json) {
return SpaceModel.fromJson(json['data']); return SpaceModel.fromJson(json['data']);
@ -212,8 +216,8 @@ class CommunitySpaceManagementApi {
} }
} }
Future<bool> updateSpace({ Future<bool> updateSpace(
required String communityId, {required String communityId,
required spaceId, required spaceId,
required String name, required String name,
String? parentId, String? parentId,
@ -223,7 +227,7 @@ class CommunitySpaceManagementApi {
required Offset position, required Offset position,
List<TagModelUpdate>? tags, List<TagModelUpdate>? tags,
List<UpdateSubspaceTemplateModel>? subspaces, List<UpdateSubspaceTemplateModel>? subspaces,
}) async { required String projectId}) async {
try { try {
final body = { final body = {
'spaceName': name, 'spaceName': name,
@ -243,7 +247,7 @@ class CommunitySpaceManagementApi {
path: ApiEndpoints.updateSpace path: ApiEndpoints.updateSpace
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{spaceId}', spaceId) .replaceAll('{spaceId}', spaceId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
body: body, body: body,
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json['success'] ?? false; return json['success'] ?? false;
@ -256,13 +260,14 @@ class CommunitySpaceManagementApi {
} }
} }
Future<bool> deleteSpace(String communityId, String spaceId) async { Future<bool> deleteSpace(
String communityId, String spaceId, String projectId) async {
try { try {
final response = await HTTPService().delete( final response = await HTTPService().delete(
path: ApiEndpoints.deleteSpace path: ApiEndpoints.deleteSpace
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{spaceId}', spaceId) .replaceAll('{spaceId}', spaceId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json['success'] ?? false; return json['success'] ?? false;
}, },
@ -274,12 +279,13 @@ class CommunitySpaceManagementApi {
} }
} }
Future<List<SpaceModel>> getSpaceHierarchy(String communityId) async { Future<List<SpaceModel>> getSpaceHierarchy(
String communityId, String projectId) async {
try { try {
final response = await HTTPService().get( final response = await HTTPService().get(
path: ApiEndpoints.getSpaceHierarchy path: ApiEndpoints.getSpaceHierarchy
.replaceAll('{communityId}', communityId) .replaceAll('{communityId}', communityId)
.replaceAll('{projectId}', TempConst.projectId), .replaceAll('{projectId}', projectId),
expectedResponseModel: (json) { expectedResponseModel: (json) {
final spaceModels = (json['data'] as List) final spaceModels = (json['data'] as List)
.map((spaceJson) => SpaceModel.fromJson(spaceJson)) .map((spaceJson) => SpaceModel.fromJson(spaceJson))

View File

@ -5,10 +5,10 @@ import 'package:syncrow_web/utils/constants/api_const.dart';
import 'package:syncrow_web/utils/constants/temp_const.dart'; import 'package:syncrow_web/utils/constants/temp_const.dart';
class SpaceModelManagementApi { class SpaceModelManagementApi {
Future<List<SpaceTemplateModel>> listSpaceModels({int page = 1}) async { Future<List<SpaceTemplateModel>> listSpaceModels(
{required String projectId, int page = 1}) async {
final response = await HTTPService().get( final response = await HTTPService().get(
path: ApiEndpoints.listSpaceModels path: ApiEndpoints.listSpaceModels.replaceAll('{projectId}', projectId),
.replaceAll('{projectId}', TempConst.projectId),
queryParameters: {'page': page}, queryParameters: {'page': page},
expectedResponseModel: (json) { expectedResponseModel: (json) {
List<dynamic> jsonData = json['data']; List<dynamic> jsonData = json['data'];
@ -21,10 +21,9 @@ class SpaceModelManagementApi {
} }
Future<SpaceTemplateModel?> createSpaceModel( Future<SpaceTemplateModel?> createSpaceModel(
CreateSpaceTemplateBodyModel spaceModel) async { CreateSpaceTemplateBodyModel spaceModel, String projectId) async {
final response = await HTTPService().post( final response = await HTTPService().post(
path: ApiEndpoints.createSpaceModel path: ApiEndpoints.createSpaceModel.replaceAll('{projectId}', projectId),
.replaceAll('{projectId}', TempConst.projectId),
showServerMessage: true, showServerMessage: true,
body: spaceModel.toJson(), body: spaceModel.toJson(),
expectedResponseModel: (json) { expectedResponseModel: (json) {
@ -34,12 +33,12 @@ class SpaceModelManagementApi {
return response; return response;
} }
Future<String?> updateSpaceModel(CreateSpaceTemplateBodyModel spaceModel,
Future<String?> updateSpaceModel( String spaceModelUuid, String projectId) async {
CreateSpaceTemplateBodyModel spaceModel, String spaceModelUuid) async {
final response = await HTTPService().put( final response = await HTTPService().put(
path: ApiEndpoints.updateSpaceModel path: ApiEndpoints.updateSpaceModel
.replaceAll('{projectId}', TempConst.projectId).replaceAll('{spaceModelUuid}', spaceModelUuid), .replaceAll('{projectId}', projectId)
.replaceAll('{spaceModelUuid}', spaceModelUuid),
body: spaceModel.toJson(), body: spaceModel.toJson(),
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json['message']; return json['message'];
@ -48,10 +47,11 @@ class SpaceModelManagementApi {
return response; return response;
} }
Future<SpaceTemplateModel?> getSpaceModel(String spaceModelUuid) async { Future<SpaceTemplateModel?> getSpaceModel(
String spaceModelUuid, String projectId) async {
final response = await HTTPService().get( final response = await HTTPService().get(
path: ApiEndpoints.getSpaceModel path: ApiEndpoints.getSpaceModel
.replaceAll('{projectId}', TempConst.projectId) .replaceAll('{projectId}', projectId)
.replaceAll('{spaceModelUuid}', spaceModelUuid), .replaceAll('{spaceModelUuid}', spaceModelUuid),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {

View File

@ -11,10 +11,10 @@ import 'package:syncrow_web/utils/constants/api_const.dart';
class UserPermissionApi { class UserPermissionApi {
static final HTTPService _httpService = HTTPService(); static final HTTPService _httpService = HTTPService();
Future<List<RolesUserModel>> fetchUsers() async { Future<List<RolesUserModel>> fetchUsers(String projectId) async {
try { try {
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.getUsers, path: ApiEndpoints.getUsers.replaceAll('{projectId}', projectId),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
debugPrint('fetchUsers Response: $json'); debugPrint('fetchUsers Response: $json');
@ -34,8 +34,9 @@ class UserPermissionApi {
path: ApiEndpoints.roleTypes, path: ApiEndpoints.roleTypes,
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
final List<RoleTypeModel> fetchedRoles = final List<RoleTypeModel> fetchedRoles = (json['data'] as List)
(json['data'] as List).map((item) => RoleTypeModel.fromJson(item)).toList(); .map((item) => RoleTypeModel.fromJson(item))
.toList();
return fetchedRoles; return fetchedRoles;
}, },
); );
@ -47,7 +48,9 @@ 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).map((data) => PermissionOption.fromJson(data)).toList(); return (json as List)
.map((data) => PermissionOption.fromJson(data))
.toList();
}, },
); );
return response ?? []; return response ?? [];
@ -61,6 +64,7 @@ class UserPermissionApi {
String? phoneNumber, String? phoneNumber,
String? roleUuid, String? roleUuid,
List<String>? spaceUuids, List<String>? spaceUuids,
required String projectUuid,
}) async { }) async {
try { try {
final body = <String, dynamic>{ final body = <String, dynamic>{
@ -70,7 +74,7 @@ class UserPermissionApi {
"jobTitle": jobTitle != '' ? jobTitle : null, "jobTitle": jobTitle != '' ? jobTitle : null,
"phoneNumber": phoneNumber != '' ? phoneNumber : null, "phoneNumber": phoneNumber != '' ? phoneNumber : null,
"roleUuid": roleUuid, "roleUuid": roleUuid,
"projectUuid": "0e62577c-06fa-41b9-8a92-99a21fbaf51c", "projectUuid": projectUuid,
"spaceUuids": spaceUuids, "spaceUuids": spaceUuids,
}; };
final response = await _httpService.post( final response = await _httpService.post(
@ -121,9 +125,11 @@ class UserPermissionApi {
} }
} }
Future<EditUserModel?> fetchUserById(userUuid) async { Future<EditUserModel?> fetchUserById(userUuid, String projectId) async {
final response = await _httpService.get( final response = await _httpService.get(
path: ApiEndpoints.getUserById.replaceAll("{userUuid}", userUuid), path: ApiEndpoints.getUserById
.replaceAll("{userUuid}", userUuid)
.replaceAll("{projectId}", projectId),
showServerMessage: true, showServerMessage: true,
expectedResponseModel: (json) { expectedResponseModel: (json) {
EditUserModel res = EditUserModel.fromJson(json['data']); EditUserModel res = EditUserModel.fromJson(json['data']);
@ -141,6 +147,7 @@ class UserPermissionApi {
String? phoneNumber, String? phoneNumber,
String? roleUuid, String? roleUuid,
List<String>? spaceUuids, List<String>? spaceUuids,
required String projectUuid,
}) async { }) async {
try { try {
final body = <String, dynamic>{ final body = <String, dynamic>{
@ -149,7 +156,7 @@ class UserPermissionApi {
"jobTitle": jobTitle != '' ? jobTitle : " ", "jobTitle": jobTitle != '' ? jobTitle : " ",
"phoneNumber": phoneNumber != '' ? phoneNumber : " ", "phoneNumber": phoneNumber != '' ? phoneNumber : " ",
"roleUuid": roleUuid, "roleUuid": roleUuid,
"projectUuid": "0e62577c-06fa-41b9-8a92-99a21fbaf51c", "projectUuid": projectUuid,
"spaceUuids": spaceUuids, "spaceUuids": spaceUuids,
}; };
final response = await _httpService.put( final response = await _httpService.put(
@ -186,15 +193,16 @@ class UserPermissionApi {
} }
} }
Future<bool> changeUserStatusById(userUuid, status) async { Future<bool> changeUserStatusById(userUuid, status, String projectUuid) async {
try { try {
Map<String, dynamic> bodya = { Map<String, dynamic> bodya = {
"disable": status, "disable": status,
"projectUuid": "0e62577c-06fa-41b9-8a92-99a21fbaf51c" "projectUuid": projectUuid
}; };
final response = await _httpService.put( final response = await _httpService.put(
path: ApiEndpoints.changeUserStatus.replaceAll("{invitedUserUuid}", userUuid), path: ApiEndpoints.changeUserStatus
.replaceAll("{invitedUserUuid}", userUuid),
body: bodya, body: bodya,
expectedResponseModel: (json) { expectedResponseModel: (json) {
return json['success']; return json['success'];

View File

@ -9,8 +9,8 @@ abstract class ApiEndpoints {
static const String sendOtp = '/authentication/user/send-otp'; static const String sendOtp = '/authentication/user/send-otp';
static const String verifyOtp = '/authentication/user/verify-otp'; static const String verifyOtp = '/authentication/user/verify-otp';
static const String getRegion = '/region'; static const String getRegion = '/region';
static const String visitorPassword = '/visitor-password'; static const String visitorPassword = '/projects/{projectId}/visitor-password';
static const String getDevices = '/visitor-password/devices'; static const String getDevices = '/projects/{projectId}/visitor-password/devices';
static const String sendOnlineOneTime = '/visitor-password/temporary-password/online/one-time'; static const String sendOnlineOneTime = '/visitor-password/temporary-password/online/one-time';
static const String sendOnlineMultipleTime = static const String sendOnlineMultipleTime =
@ -25,7 +25,7 @@ abstract class ApiEndpoints {
////// Devices Management //////////////// ////// Devices Management ////////////////
static const String getAllDevices = '/device'; static const String getAllDevices = '/projects/{projectId}/devices';
static const String getSpaceDevices = static const String getSpaceDevices =
'/projects/{projectId}/communities/{communityUuid}/spaces/{spaceUuid}/devices'; '/projects/{projectId}/communities/{communityUuid}/spaces/{spaceUuid}/devices';
static const String getDeviceStatus = '/device/{uuid}/functions/status'; static const String getDeviceStatus = '/device/{uuid}/functions/status';
@ -95,8 +95,8 @@ abstract class ApiEndpoints {
static const String inviteUser = '/invite-user'; static const String inviteUser = '/invite-user';
static const String checkEmail = '/invite-user/check-email'; static const String checkEmail = '/invite-user/check-email';
static const String getUsers = '/projects/${projectUuid}/user'; static const String getUsers = '/projects/{projectId}/user';
static const String getUserById = '/projects/${projectUuid}/user/{userUuid}'; static const String getUserById = '/projects/{projectId}/user/{userUuid}';
static const String editUser = '/invite-user/{inviteUserUuid}'; static const String editUser = '/invite-user/{inviteUserUuid}';
static const String deleteUser = '/invite-user/{inviteUserUuid}'; static const String deleteUser = '/invite-user/{inviteUserUuid}';
static const String changeUserStatus = '/invite-user/{invitedUserUuid}/disable'; static const String changeUserStatus = '/invite-user/{invitedUserUuid}/disable';

View File

@ -40,4 +40,5 @@ class StringsManager {
static const String firstLaunch = "firstLaunch"; static const String firstLaunch = "firstLaunch";
static const String deleteScene = 'Delete Scene'; static const String deleteScene = 'Delete Scene';
static const String deleteAutomation = 'Delete Automation'; static const String deleteAutomation = 'Delete Automation';
static const String projectKey = 'selected_project_uuid';
} }

View File

@ -1,8 +1,10 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart'; import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart'; import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/auth/model/user_model.dart'; import 'package:syncrow_web/pages/auth/model/user_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart'; import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/utils/color_manager.dart'; import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart'; import 'package:syncrow_web/utils/constants/assets.dart';
@ -218,7 +220,7 @@ class _UserDropdownMenuState extends State<UserDropdownMenu> {
), ),
GestureDetector( GestureDetector(
onTap: () { onTap: () {
AuthBloc.logout(); AuthBloc.logout(context);
context.go(RoutesConst.auth); context.go(RoutesConst.auth);
}, },
child: SizedBox( child: SizedBox(