Compare commits

..

91 Commits

Author SHA1 Message Date
52608b1f35 fixed search query 2025-04-27 22:42:57 +04:00
0f56273d99 SP-1408 2025-04-27 12:10:38 +03:00
f30d7c0117 Merge pull request #158 from SyncrowIOT:bugfix/duplicate-space
Bugfix/duplicate-space
2025-04-27 11:13:07 +04:00
976d6e385a duplicated space 2025-04-27 11:12:03 +04:00
ff07e7509d fixed the issue in aligning child space 2025-04-26 16:04:41 +04:00
17a582ab99 Merge pull request #157 from SyncrowIOT/SP-1415 2025-04-25 10:50:06 +04:00
09fb604acc added filtering 2025-04-25 10:49:25 +04:00
2068df173d Merge pull request #155 from SyncrowIOT/SP-1441-rework-FE-On-routine-creation-page-When-the-user-drags-a-card-that-has-signs-and-selects-a-sign-without-a-number-then-confirms-the-value-appears-to-be-Null
Sp 1441 rework fe on routine creation page when the user drags a card that has signs and selects a sign without a number then confirms the value appears to be null
2025-04-24 16:25:39 +03:00
bfc2a381d2 Merge pull request #156 from SyncrowIOT/SP-1464-FE-implement-Batch-Control-Dialog
Sp 1464 fe implement batch control dialog
2025-04-24 16:25:17 +03:00
778257644d reduced debounce duration. 2025-04-24 15:13:10 +03:00
c8e540e938 Remove unnecessary event dispatch in FlushMountedPresenceSensorBlocFactory creation 2025-04-24 14:29:18 +03:00
ba20998067 disabled realtime on batch control. 2025-04-24 14:21:38 +03:00
75b0b24543 Add Flush Mounted Presence Sensor support and update event handling 2025-04-24 14:13:13 +03:00
c03b8f290c refactor function tap handlers to use RoutineTapFunctionHelper for improved code reuse and readability, and to remove code duplication. 2025-04-24 10:25:41 +03:00
2c684a9495 SP-1441 rework. 2025-04-23 16:58:50 +03:00
fbc45b465f Merge pull request #153 from SyncrowIOT/SP-1344-FE-Real-Time-Issues-Ceiling-Sensor-AC-and-Garage-Door-Sensor
Refactor widget lifecycle methods for temperature control and presenc…
2025-04-23 16:29:36 +03:00
c9c939c59f Merge pull request #154 from SyncrowIOT/Add-Flush-Mounted-Presence-Sensor-Single-Control
Add flush mounted presence sensor single control
2025-04-23 16:21:17 +03:00
e1a2465130 Fix deviceId assignment in FlushMountedPresenceSensorBlocFactory and update _listenToChanges method for async handling 2025-04-23 13:11:25 +03:00
86164e746a Refactor FlushMountedPresenceSensorBloc creation to use factory method and streamline dependency injection 2025-04-23 12:15:50 +03:00
4a5176cf22 Refactor presence update data handling for improved precision and scaling 2025-04-23 12:11:13 +03:00
2bb7a6950a Refactor debounce duration handling in BatchControlDevicesService and ControlDeviceService 2025-04-23 10:52:08 +03:00
46860619a0 Add bloc dependency to pubspec.yaml 2025-04-23 10:48:24 +03:00
d1bb7b129f Refactor widget lifecycle methods for temperature control and presence sensor 2025-04-23 10:46:56 +03:00
7adce3b94c Refactor _onFlushMountedPresenceSensorFetchBatchStatusEvent to use final for response variable 2025-04-23 10:44:44 +03:00
91f93d4395 Refactor FlushMountedPresenceSensorBloc to streamline device control logic and remove redundant code 2025-04-23 10:44:11 +03:00
42d6b64e58 Refactor FlushMountedPresenceSensorBloc to replace _runDeBouncer with _controlDevice for handling device control logic 2025-04-23 10:32:49 +03:00
b11d4186fb Add BatchControlDevicesService integration to FlushMountedPresenceSensorBloc and ControlView 2025-04-23 10:31:26 +03:00
24130be665 organized instances in bloc. 2025-04-23 10:26:55 +03:00
8c960bd5f1 created BatchControlDevicesService interface. 2025-04-23 10:26:17 +03:00
fb8ccdf0a6 Add FlushMountedPresenceSensorControlView for managing presence sensor settings 2025-04-23 10:24:38 +03:00
1975a1b6f4 created FlushMountedPresenceSensorBloc, events, and states for device management. 2025-04-23 10:24:14 +03:00
367d6717e7 Refactor PresenceUpdateData widget to support decimal values. 2025-04-23 10:23:28 +03:00
8c637e40ff Created FlushMountedPresenceSensorModel model. 2025-04-23 10:23:00 +03:00
05b3180510 Created ControlDeviceService interface and its remote and debounced implementation. 2025-04-23 10:22:41 +03:00
177a4711fe Synced main_dev and main_staging with main.dart 2025-04-22 03:39:27 +03:00
d7a37c6519 Removed flavor from Flutter run and build commands 2025-04-22 03:01:43 +03:00
b901791079 Update Flutter run and build commands, and added main_staging file 2025-04-22 02:33:50 +03:00
5d16555748 Merge pull request #151 from SyncrowIOT/SP-1447-FE-Invalid-Time-Limit-24h-Exceeding-Backend-Max-of-12h
SP-1447.
2025-04-21 18:59:57 +03:00
bd15f30b8a Merge pull request #150 from SyncrowIOT/SP-1440-FE-On-routine-creation-edit-Page-When-saving-a-routine-the-confirmation-pop-up-is-not-identical-to-design
Sp 1440 fe on routine creation edit page when saving a routine the confirmation pop up is not identical to design
2025-04-21 18:59:37 +03:00
5f2684bdf4 Merge pull request #152 from SyncrowIOT/SP-702-WEB-Username-Caching-After-Logout-Requires-Screen-Refresh
Sp 702 web username caching after logout requires screen refresh
2025-04-21 18:58:57 +03:00
b4ef22ef0a SP-702/ clears user data on logging out. 2025-04-21 14:23:40 +03:00
d8afb562eb SP-1447, set the limit of gangs countdown to be 12 hours instead of 24 hours. 2025-04-21 12:07:21 +03:00
67a164e6d2 modified divider color to match figma design. 2025-04-21 10:59:09 +03:00
cf20bdcd42 SP-1440 2025-04-21 10:57:46 +03:00
32b45ea5d7 Merge pull request #149 from SyncrowIOT/SP-1441-FE-On-routine-creation-page-When-the-user-drags-a-card-that-has-signs-and-selects-a-sign-without-a-number-then-confirms-the-value-appears-to-be-Null
Sp 1441 fe on routine creation page when the user drags a card that has signs and selects a sign without a number then confirms the value appears to be null
2025-04-21 10:32:38 +03:00
62fb8b3097 SP-1441 2025-04-21 10:28:44 +03:00
065bd33511 SP-1330. 2025-04-21 10:03:02 +03:00
b9ab782c01 Merge pull request #148 from SyncrowIOT/SP-1435-FE-On-routines-page-when-the-screen-height-is-decreased-or-is-small-the-scroll-area-for-routine-cards-is-not-fitting-the-whole-screen-width
Sp 1435 fe on routines page when the screen height is decreased or is small the scroll area for routine cards is not fitting the whole screen width
2025-04-21 09:49:08 +03:00
4d5adf948c Merge pull request #147 from SyncrowIOT/SP-1433-FE-Text-Alignment-Issue-in-UI-Component-in-adding-subspace-in-a-space
Sp 1433 fe text alignment issue in UI component in adding subspace in a space
2025-04-21 09:48:38 +03:00
e45f57ca03 SP-1441 2025-04-17 16:55:44 +03:00
84264391d9 progress towards matching the design of save routine dialog. 2025-04-17 16:14:26 +03:00
2e4f904d3a style: improve code formatting and readability in SaveRoutineHelper 2025-04-17 14:39:33 +03:00
c46cfb48a8 refactor: extract IF and THEN sections into separate methods for better readability 2025-04-17 14:38:04 +03:00
a0dd128557 matched design of Function and action in SaveRoutineHelper.showSaveRoutineDialog 2025-04-17 14:30:30 +03:00
34fa426163 submitting password field in login logs the user in. 2025-04-17 14:17:43 +03:00
1407c173b0 tapping bugfix. 2025-04-17 13:28:00 +03:00
9431eb79c1 Fix loading state handling and refactor scene/automation rendering in FetchRoutineScenesAutomation 2025-04-17 13:18:44 +03:00
70f1f39fce Improve loading state handling and in FetchRoutineScenesAutomation. 2025-04-17 13:13:48 +03:00
f912b41fd8 Refactor visibility handling for scenes and automations in FetchRoutineScenesAutomation 2025-04-17 13:12:09 +03:00
977875f1f2 SP-1435 2025-04-17 13:08:16 +03:00
8136804694 bugfix. 2025-04-17 12:18:09 +03:00
ce253b2034 Remove unused parameters from CreateSubSpaceDialog constructor 2025-04-17 11:27:37 +03:00
024fbcdb83 Refactor CreateSubSpaceDialog to convert to StatefulWidget and manage text controller lifecycle 2025-04-17 11:25:39 +03:00
a8430a7d3d Merge pull request #145 from SyncrowIOT/SP-1330-FE-Side-tree-text-breaks-incorrectly-causing-layout-issues
Sp 1330 fe side tree text breaks incorrectly causing layout issues
2025-04-17 09:49:33 +03:00
7ef6020dd8 Merge pull request #144 from SyncrowIOT/SP-1333-FE-set-barrier-dismissable-to-true
Sp 1333 fe set barrier dismissable to true
2025-04-17 09:49:11 +03:00
2a77483f46 Refactor CreateSubSpaceDialog to improve widget structure and readability 2025-04-17 09:45:14 +03:00
a6fc99443b Refactor CreateSubSpaceDialog layout for improved readability and maintainability 2025-04-17 09:38:54 +03:00
ae95d06482 Fix constructor parameter order in CreateSubSpaceDialog 2025-04-17 09:35:47 +03:00
18c886753d added trailing commas wherever neccessary in CreateSubSpaceDialog. 2025-04-17 09:35:33 +03:00
62bf4f2944 Refactor CreateSubSpaceDialog to use context extension for screen width calculations 2025-04-17 09:34:03 +03:00
726c173a76 SP-1433-FE-Text-Alignment-Issue-in-UI-Component-in-adding-subspace-in-a-space 2025-04-17 09:33:10 +03:00
d538b3667e Merge pull request #146 from SyncrowIOT/Fix-Factory-Reset-Model
Refactor FactoryResetModel and MainDoorSensorBatchView
2025-04-17 09:18:43 +03:00
72ae3b1727 Refactor FactoryResetModel and MainDoorSensorBatchView
- Refactor FactoryResetModel to include 'operationType' in toJson and toMap methods.
- Refactor MainDoorSensorBatchView to use BlocProvider and Builder for better state management.
2025-04-16 15:06:50 +03:00
9044645f95 remove screenWidth parameter from TagChipDisplay and use context.screenWidth instead. 2025-04-15 15:45:47 +03:00
7699453e6d moved styling of _buildChip up, and removed unnecessary SizedBox. 2025-04-15 15:43:50 +03:00
d1a21be983 removed else from TagChipDisplay.build 2025-04-15 15:35:24 +03:00
db8e5a4aa6 Refactor TagChipDisplay._groupedTags to enhance readabaility. 2025-04-15 15:32:31 +03:00
fa5bb350c3 refactor: replace spaceNameController with spaceName in TagChipDisplay. 2025-04-15 15:29:25 +03:00
920827d763 Removed unnecessary SizedBox from TagChipDisplay. 2025-04-15 15:28:12 +03:00
d3902d622e Moved constructor to be the first element in TagChipDisplay. 2025-04-15 15:27:45 +03:00
a4432656ab refactor: extract EditChip into a private method for improved readability 2025-04-15 15:27:04 +03:00
90e0d2f52b Extracted Chip into a private method. 2025-04-15 15:24:36 +03:00
08e5e17910 Extracted Add Devices button into a private method. 2025-04-15 15:23:36 +03:00
f57348e5cd converted to using expressions wherever possible in TagChipDisplay. 2025-04-15 15:13:47 +03:00
be168aed93 refactor: simplify tag checking logic to enhance readability. 2025-04-15 15:08:30 +03:00
a66784473f Replaced conditional with an if statement in TagChipDisplay. 2025-04-15 15:06:01 +03:00
c0a963ded5 refactor: use context extension for text theme. 2025-04-15 15:05:31 +03:00
7945cefe53 added trailing commas wherever necessary. 2025-04-15 15:05:06 +03:00
7d0e50fb1d removed unnecessary comments. 2025-04-15 15:03:27 +03:00
117f6190dd removed unnecessary BuildContext from TagChipDisplay constructor, sorted its properies, and converted to using super.key. 2025-04-15 15:02:58 +03:00
748c67fd8b SP-1333 2025-04-15 14:52:20 +03:00
56 changed files with 2640 additions and 1156 deletions

View File

@ -31,7 +31,7 @@ jobs:
run: flutter pub get
- name: Build Flutter Web App
run: flutter build web --release --dart-define=FLAVOR=production
run: flutter build web --web-renderer canvaskit -t lib/main.dart
- name: Build And Deploy
id: builddeploy

View File

@ -31,7 +31,7 @@ jobs:
run: flutter pub get
- name: Build Flutter Web App
run: flutter build web --release --dart-define=FLAVOR=development
run: flutter build web --web-renderer canvaskit -t lib/main_dev.dart
- name: Build And Deploy
id: builddeploy

33
.vscode/launch.json vendored
View File

@ -10,11 +10,12 @@
"type": "dart",
"args": [
"--dart-define",
"FLAVOR=development"
"-d",
"chrome",
"--web-port",
"3000",
"-t",
"lib/main_dev.dart",
],
"flutterMode": "debug"
@ -28,11 +29,12 @@
"type": "dart",
"args": [
"--dart-define",
"FLAVOR=staging"
"-d",
"chrome",
"--web-port",
"3000",
"-t",
"lib/main_staging.dart",
],
"flutterMode": "debug"
@ -46,11 +48,12 @@
"type": "dart",
"args": [
"--dart-define",
"FLAVOR=production"
"-d",
"chrome",
"--web-port",
"3000",
"-t",
"lib/main.dart",
],
"flutterMode": "debug"

View File

@ -16,7 +16,12 @@ samples, guidance on mobile development, and a full API reference.
## USEFUL COMMANDS
Run on chrome: flutter run -d chrome --dart-define=FLAVOR='ENV_NAME'
- Building for the Web
- CanvasKit
- `flutter build web --web-renderer canvaskit -t lib/main_dev.dart --output=build/web_dev` - build for DEVELOPMENT.
- `flutter build web --web-renderer canvaskit -t lib/main_staging.dart --output=build/web_stg` - build for STAGING.
- `flutter build web --web-renderer canvaskit -t lib/main.dart --output=build/web` - build for PRODUCTION.
- run command: `flutter run -d chrome --target=lib/main_dev.dart`
Build: flutter build web --release --dart-define=FLAVOR='ENV_NAME'

View File

@ -16,12 +16,12 @@ import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.da
import 'package:syncrow_web/services/locator.dart';
import 'package:syncrow_web/utils/app_routes.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';
Future<void> main() async {
try {
const environment =
String.fromEnvironment('FLAVOR', defaultValue: 'development');
const environment = String.fromEnvironment('FLAVOR', defaultValue: 'development');
await dotenv.load(fileName: '.env.$environment');
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
@ -33,9 +33,7 @@ Future<void> main() async {
}
class MyApp extends StatelessWidget {
MyApp({
super.key,
});
MyApp({super.key});
final GoRouter _router = GoRouter(
initialLocation: RoutesConst.auth,
@ -56,11 +54,10 @@ class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<CreateRoutineBloc>(
BlocProvider<CreateRoutineBloc>(
create: (context) => CreateRoutineBloc(),
),
BlocProvider(
create: (context) => HomeBloc()..add(const FetchUserInfo())),
BlocProvider(create: (context) => HomeBloc()..add(const FetchUserInfo())),
BlocProvider<VisitorPasswordBloc>(
create: (context) => VisitorPasswordBloc(),
),
@ -81,6 +78,8 @@ class MyApp extends StatelessWidget {
PointerDeviceKind.unknown,
},
),
key: NavigationService.navigatorKey,
// scaffoldMessengerKey: NavigationService.snackbarKey,
theme: myTheme,
routerConfig: _router,
));

87
lib/main_staging.dart Normal file
View File

@ -0,0 +1,87 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:go_router/go_router.dart';
import 'package:syncrow_web/firebase_options_prod.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/home/bloc/home_bloc.dart';
import 'package:syncrow_web/pages/home/bloc/home_event.dart';
import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart';
import 'package:syncrow_web/pages/visitor_password/bloc/visitor_password_bloc.dart';
import 'package:syncrow_web/services/locator.dart';
import 'package:syncrow_web/utils/app_routes.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';
Future<void> main() async {
try {
const environment = String.fromEnvironment('FLAVOR', defaultValue: 'staging');
await dotenv.load(fileName: '.env.$environment');
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptionsStaging.currentPlatform,
);
initialSetup();
} catch (_) {}
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
final GoRouter _router = GoRouter(
initialLocation: RoutesConst.auth,
routes: AppRoutes.getRoutes(),
redirect: (context, state) async {
String checkToken = await AuthBloc.getTokenAndValidate();
final loggedIn = checkToken == 'Success';
final goingToLogin = state.uri.toString() == RoutesConst.auth;
if (!loggedIn && !goingToLogin) return RoutesConst.auth;
if (loggedIn && goingToLogin) return RoutesConst.home;
return null;
},
);
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<CreateRoutineBloc>(
create: (context) => CreateRoutineBloc(),
),
BlocProvider(create: (context) => HomeBloc()..add(const FetchUserInfo())),
BlocProvider<VisitorPasswordBloc>(
create: (context) => VisitorPasswordBloc(),
),
BlocProvider<RoutineBloc>(
create: (context) => RoutineBloc(),
),
BlocProvider<SpaceTreeBloc>(
create: (context) => SpaceTreeBloc()..add(InitialEvent()),
),
],
child: MaterialApp.router(
debugShowCheckedModeBanner: false,
scrollBehavior: const MaterialScrollBehavior().copyWith(
dragDevices: {
PointerDeviceKind.mouse,
PointerDeviceKind.touch,
PointerDeviceKind.stylus,
PointerDeviceKind.unknown,
},
),
key: NavigationService.navigatorKey,
// scaffoldMessengerKey: NavigationService.snackbarKey,
theme: myTheme,
routerConfig: _router,
));
}
}

View File

@ -10,6 +10,7 @@ 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/user_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/home/bloc/home_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart';
import 'package:syncrow_web/services/auth_api.dart';
@ -432,9 +433,13 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
}
static Future<void> logout(BuildContext context) async {
final storage = FlutterSecureStorage();
ProjectManager.clearProjectUUID();
const storage = FlutterSecureStorage();
context.read<SpaceTreeBloc>().add(ClearAllData());
storage.deleteAll();
user = null;
context.read<HomeBloc>().user = null;
await Future.wait<void>([
ProjectManager.clearProjectUUID(),
storage.deleteAll(),
]);
}
}

View File

@ -55,12 +55,12 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
final isSmallScreen = isSmallScreenSize(context);
final isMediumScreen = isMediumScreenSize(context);
Size size = MediaQuery.of(context).size;
late ScrollController _scrollController;
_scrollController = ScrollController();
late ScrollController scrollController;
scrollController = ScrollController();
void _scrollToCenter() {
final double middlePosition = _scrollController.position.maxScrollExtent / 2;
_scrollController.animateTo(
void scrollToCenter() {
final double middlePosition = scrollController.position.maxScrollExtent / 2;
scrollController.animateTo(
middlePosition,
duration: const Duration(seconds: 1),
curve: Curves.easeInOut,
@ -68,7 +68,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
}
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToCenter();
scrollToCenter();
});
return Stack(
@ -76,7 +76,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
FirstLayer(
second: Center(
child: ListView(
controller: _scrollController,
controller: scrollController,
shrinkWrap: true,
children: [
Container(
@ -199,7 +199,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
width: size.width * 0.9,
child: DropdownButtonHideUnderline(
child: DropdownButton2<String>(
style: TextStyle(color: Colors.black),
style: const TextStyle(color: Colors.black),
isExpanded: true,
hint: Text(
'Select your region/country',
@ -336,6 +336,16 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
obscureText: loginBloc.obscureText,
keyboardType: TextInputType.visiblePassword,
controller: loginBloc.loginPasswordController,
onFieldSubmitted: (value) {
if (loginBloc.loginFormKey.currentState!.validate()) {
loginBloc.add(LoginButtonPressed(
username: loginBloc.loginEmailController.text,
password: value,
));
} else {
loginBloc.add(ChangeValidateEvent());
}
},
decoration: textBoxDecoration()!.copyWith(
hintText: 'At least 8 characters',
hintStyle: Theme.of(context)
@ -393,7 +403,7 @@ class _LoginWebPageState extends State<LoginWebPage> with HelperResponsiveLayout
Transform.scale(
scale: 1.2,
child: Checkbox(
fillColor: MaterialStateProperty.all<Color>(Colors.white),
fillColor: WidgetStateProperty.all<Color>(Colors.white),
activeColor: Colors.white,
value: loginBloc.isChecked,
checkColor: Colors.black,

View File

@ -60,7 +60,15 @@ class _CurrentTempState extends State<CurrentTemp> {
);
});
}
@override
void didUpdateWidget(CurrentTemp oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.tempSet != widget.tempSet) {
setState(() {
_adjustedValue = _initialAdjustedValue(widget.tempSet);
});
}
}
@override
void dispose() {
_debounce?.cancel();

View File

@ -9,6 +9,8 @@ import 'package:syncrow_web/pages/device_managment/curtain/view/curtain_batch_st
import 'package:syncrow_web/pages/device_managment/curtain/view/curtain_status_view.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/view/door_lock_batch_control_view.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/view/door_lock_control_view.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_batch_control_view.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/views/flush_mounted_presence_sensor_control_view.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/view/garage_door_batch_control_view.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/view/garage_door_control_view.dart';
import 'package:syncrow_web/pages/device_managment/gateway/view/gateway_batch_control.dart';
@ -104,6 +106,9 @@ mixin RouteControlsBasedCode {
);
case 'SOS':
return SosDeviceControlsView(device: device);
case 'NCPS':
return FlushMountedPresenceSensorControlView(device: device);
default:
return const SizedBox();
}
@ -194,6 +199,10 @@ mixin RouteControlsBasedCode {
return SOSBatchControlView(
deviceIds: devices.where((e) => (e.productType == 'SOS')).map((e) => e.uuid!).toList(),
);
case 'NCPS':
return FlushMountedPresenceSensorBatchControlView(
devicesIds: devices.where((e) => (e.productType == 'NCPS')).map((e) => e.uuid!).toList(),
);
default:
return const SizedBox();
}

View File

@ -19,6 +19,7 @@ class FactoryResetModel {
Map<String, dynamic> toJson() {
return {
'devicesUuid': devicesUuid,
'operationType': operationType,
};
}
@ -33,6 +34,7 @@ class FactoryResetModel {
Map<String, dynamic> toMap() {
return {
'devicesUuid': devicesUuid,
'operationType': operationType,
};
}
@ -56,3 +58,4 @@ class FactoryResetModel {
@override
int get hashCode => devicesUuid.hashCode;
}

View File

@ -108,7 +108,7 @@ class DeviceManagementPage extends StatelessWidget with HelperResponsiveLayout {
return DeviceManagementBody(
devices: deviceState.filteredDevices);
} else {
return const Center(child: Text('Error fetching Devices'));
return const DeviceManagementBody(devices: []);
}
},
);

View File

@ -16,7 +16,8 @@ import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dar
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLayout {
class CeilingSensorControlsView extends StatelessWidget
with HelperResponsiveLayout {
const CeilingSensorControlsView({super.key, required this.device});
final AllDevicesModel device;
@ -31,29 +32,35 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
..add(CeilingInitialEvent(device.uuid ?? '')),
child: BlocBuilder<CeilingSensorBloc, CeilingSensorState>(
builder: (context, state) {
if (state is CeilingLoadingInitialState || state is CeilingReportsLoadingState) {
if (state is CeilingLoadingInitialState ||
state is CeilingReportsLoadingState) {
return const Center(child: CircularProgressIndicator());
} else if (state is CeilingUpdateState) {
return _buildGridView(
context, state.ceilingSensorModel, isExtraLarge, isLarge, isMedium);
return _buildGridView(context, state.ceilingSensorModel,
isExtraLarge, isLarge, isMedium);
} else if (state is CeilingReportsState) {
return ReportsTable(
report: state.deviceReport,
onRowTap: (index) {},
onClose: () {
context.read<CeilingSensorBloc>().add(BackToCeilingGridViewEvent());
context
.read<CeilingSensorBloc>()
.add(BackToCeilingGridViewEvent());
},
);
} else if (state is ShowCeilingDescriptionState) {
return DescriptionView(
description: state.description,
onClose: () {
context.read<CeilingSensorBloc>().add(BackToCeilingGridViewEvent());
context
.read<CeilingSensorBloc>()
.add(BackToCeilingGridViewEvent());
},
);
} else if (state is CeilingReportsFailedState) {
final model = context.read<CeilingSensorBloc>().deviceStatus;
return _buildGridView(context, model, isExtraLarge, isLarge, isMedium);
return _buildGridView(
context, model, isExtraLarge, isLarge, isMedium);
}
return const Center(child: Text('Error fetching status'));
},
@ -61,8 +68,8 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
);
}
Widget _buildGridView(BuildContext context, CeilingSensorModel model, bool isExtraLarge,
bool isLarge, bool isMedium) {
Widget _buildGridView(BuildContext context, CeilingSensorModel model,
bool isExtraLarge, bool isLarge, bool isMedium) {
return GridView(
padding: const EdgeInsets.symmetric(horizontal: 50),
shrinkWrap: true,
@ -143,8 +150,8 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
),
GestureDetector(
onTap: () {
context.read<CeilingSensorBloc>().add(
GetCeilingDeviceReportsEvent(code: 'presence_state', deviceUuid: device.uuid!));
context.read<CeilingSensorBloc>().add(GetCeilingDeviceReportsEvent(
code: 'presence_state', deviceUuid: device.uuid!));
},
child: const PresenceStaticWidget(
icon: Assets.illuminanceRecordIcon,
@ -153,9 +160,8 @@ class CeilingSensorControlsView extends StatelessWidget with HelperResponsiveLay
),
GestureDetector(
onTap: () {
context
.read<CeilingSensorBloc>()
.add(GetCeilingDeviceReportsEvent(code: '', deviceUuid: device.uuid!));
context.read<CeilingSensorBloc>().add(GetCeilingDeviceReportsEvent(
code: '', deviceUuid: device.uuid!));
},
child: const PresenceStaticWidget(
icon: Assets.helpDescriptionIcon,

View File

@ -0,0 +1,250 @@
import 'dart:async';
import 'dart:developer';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_reports.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart';
import 'package:syncrow_web/services/batch_control_devices_service.dart';
import 'package:syncrow_web/services/control_device_service.dart';
import 'package:syncrow_web/services/devices_mang_api.dart';
part 'flush_mounted_presence_sensor_event.dart';
part 'flush_mounted_presence_sensor_state.dart';
class FlushMountedPresenceSensorBloc
extends Bloc<FlushMountedPresenceSensorEvent, FlushMountedPresenceSensorState> {
final String deviceId;
final ControlDeviceService controlDeviceService;
final BatchControlDevicesService batchControlDevicesService;
late FlushMountedPresenceSensorModel deviceStatus;
FlushMountedPresenceSensorBloc({
required this.deviceId,
required this.controlDeviceService,
required this.batchControlDevicesService,
}) : super(FlushMountedPresenceSensorInitialState()) {
on<FlushMountedPresenceSensorFetchStatusEvent>(
_onFlushMountedPresenceSensorFetchStatusEvent,
);
on<FlushMountedPresenceSensorFetchBatchStatusEvent>(
_onFlushMountedPresenceSensorFetchBatchStatusEvent);
on<FlushMountedPresenceSensorChangeValueEvent>(
_onFlushMountedPresenceSensorChangeValueEvent,
);
on<FlushMountedPresenceSensorBatchControlEvent>(
_onFlushMountedPresenceSensorBatchControlEvent,
);
on<FlushMountedPresenceSensorGetDeviceReportsEvent>(
_onFlushMountedPresenceSensorGetDeviceReportsEvent);
on<FlushMountedPresenceSensorShowDescriptionEvent>(
_onFlushMountedPresenceSensorShowDescriptionEvent,
);
on<FlushMountedPresenceSensorBackToGridViewEvent>(
_onFlushMountedPresenceSensorBackToGridViewEvent,
);
on<FlushMountedPresenceSensorFactoryResetEvent>(
_onFlushMountedPresenceSensorFactoryResetEvent,
);
on<FlushMountedPresenceSensorStatusUpdatedEvent>(
_onFlushMountedPresenceSensorStatusUpdatedEvent,
);
}
void _onFlushMountedPresenceSensorFetchStatusEvent(
FlushMountedPresenceSensorFetchStatusEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingInitialState());
try {
final response = await DevicesManagementApi().getDeviceStatus(deviceId);
deviceStatus = FlushMountedPresenceSensorModel.fromJson(response.status);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
_listenToChanges(deviceId);
} catch (e) {
emit(FlushMountedPresenceSensorFailedState(error: e.toString()));
return;
}
}
Future<void> _onFlushMountedPresenceSensorFetchBatchStatusEvent(
FlushMountedPresenceSensorFetchBatchStatusEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingInitialState());
try {
final response = await DevicesManagementApi().getBatchStatus(event.devicesIds);
deviceStatus = FlushMountedPresenceSensorModel.fromJson(response.status);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
} catch (e) {
emit(FlushMountedPresenceSensorFailedState(error: e.toString()));
}
}
void _listenToChanges(String deviceId) {
try {
final ref = FirebaseDatabase.instance.ref(
'device-status/$deviceId',
);
ref.onValue.listen((event) {
final eventsMap = event.snapshot.value as Map<dynamic, dynamic>;
List<Status> statusList = [];
eventsMap['status'].forEach((element) {
statusList.add(
Status(code: element['code'], value: element['value']),
);
});
deviceStatus = FlushMountedPresenceSensorModel.fromJson(statusList);
if (!isClosed) {
add(FlushMountedPresenceSensorStatusUpdatedEvent(deviceStatus));
}
});
} catch (_) {
log(
'Error listening to changes',
name: 'FlushMountedPresenceSensorBloc._listenToChanges',
);
}
}
void _onFlushMountedPresenceSensorChangeValueEvent(
FlushMountedPresenceSensorChangeValueEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingNewSate(model: deviceStatus));
_updateDeviceFunctionFromCode(event.code, event.value);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
try {
await controlDeviceService.controlDevice(
deviceUuid: deviceId,
status: Status(code: event.code, value: event.value),
);
} catch (_) {
await _reloadDeviceStatus();
}
}
Future<void> _onFlushMountedPresenceSensorBatchControlEvent(
FlushMountedPresenceSensorBatchControlEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingNewSate(model: deviceStatus));
_updateDeviceFunctionFromCode(event.code, event.value);
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
try {
await batchControlDevicesService.batchControlDevices(
uuids: event.deviceIds,
code: event.code,
value: event.value,
);
} catch (_) {
await _reloadDeviceStatus();
}
}
void _updateDeviceFunctionFromCode(String code, int value) {
switch (code) {
case FlushMountedPresenceSensorModel.codeFarDetection:
deviceStatus.farDetection = value;
break;
case FlushMountedPresenceSensorModel.codeSensitivity:
deviceStatus.sensitivity = value;
break;
case FlushMountedPresenceSensorModel.codeNoneDelay:
deviceStatus.noneDelay = value;
break;
case FlushMountedPresenceSensorModel.codePresenceDelay:
deviceStatus.presenceDelay = value;
break;
case FlushMountedPresenceSensorModel.codeNearDetection:
deviceStatus.nearDetection = value;
break;
case FlushMountedPresenceSensorModel.codeOccurDistReduce:
deviceStatus.occurDistReduce = value;
break;
case FlushMountedPresenceSensorModel.codeSensiReduce:
deviceStatus.sensiReduce = value;
break;
default:
return;
}
}
Future<void> _reloadDeviceStatus() async {
await Future.delayed(const Duration(milliseconds: 500), () {
add(FlushMountedPresenceSensorFetchStatusEvent());
});
}
Future<void> _onFlushMountedPresenceSensorGetDeviceReportsEvent(
FlushMountedPresenceSensorGetDeviceReportsEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorDeviceReportsLoadingState());
try {
await DevicesManagementApi.getDeviceReports(deviceId, event.code)
.then((value) {
emit(FlushMountedPresenceSensorDeviceReportsState(
deviceReport: value, code: event.code));
});
} catch (e) {
emit(FlushMountedPresenceSensorDeviceReportsFailedState(error: e.toString()));
return;
}
}
void _onFlushMountedPresenceSensorShowDescriptionEvent(
FlushMountedPresenceSensorShowDescriptionEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) {
emit(FlushMountedPresenceSensorShowDescriptionState(
description: event.description));
}
void _onFlushMountedPresenceSensorBackToGridViewEvent(
FlushMountedPresenceSensorBackToGridViewEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) {
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
}
Future<void> _onFlushMountedPresenceSensorFactoryResetEvent(
FlushMountedPresenceSensorFactoryResetEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) async {
emit(FlushMountedPresenceSensorLoadingNewSate(model: deviceStatus));
try {
final response = await DevicesManagementApi().factoryReset(
event.factoryReset,
event.deviceId,
);
if (!response) {
emit(
const FlushMountedPresenceSensorFailedState(
error: 'Something went wrong with factory reset, please try again',
),
);
} else {
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
}
} catch (e) {
emit(FlushMountedPresenceSensorFailedState(error: e.toString()));
}
}
void _onFlushMountedPresenceSensorStatusUpdatedEvent(
FlushMountedPresenceSensorStatusUpdatedEvent event,
Emitter<FlushMountedPresenceSensorState> emit,
) {
deviceStatus = event.model;
emit(FlushMountedPresenceSensorUpdateState(model: deviceStatus));
}
}

View File

@ -0,0 +1,94 @@
part of 'flush_mounted_presence_sensor_bloc.dart';
sealed class FlushMountedPresenceSensorEvent extends Equatable {
const FlushMountedPresenceSensorEvent();
@override
List<Object> get props => [];
}
class FlushMountedPresenceSensorFetchStatusEvent
extends FlushMountedPresenceSensorEvent {}
class FlushMountedPresenceSensorStatusUpdatedEvent
extends FlushMountedPresenceSensorEvent {
const FlushMountedPresenceSensorStatusUpdatedEvent(this.model);
final FlushMountedPresenceSensorModel model;
@override
List<Object> get props => [model];
}
class FlushMountedPresenceSensorChangeValueEvent
extends FlushMountedPresenceSensorEvent {
final int value;
final String code;
final bool isBatchControl;
const FlushMountedPresenceSensorChangeValueEvent({
required this.value,
required this.code,
this.isBatchControl = false,
});
@override
List<Object> get props => [value, code];
}
class FlushMountedPresenceSensorFetchBatchStatusEvent
extends FlushMountedPresenceSensorEvent {
final List<String> devicesIds;
const FlushMountedPresenceSensorFetchBatchStatusEvent(this.devicesIds);
@override
List<Object> get props => [devicesIds];
}
class FlushMountedPresenceSensorGetDeviceReportsEvent
extends FlushMountedPresenceSensorEvent {
final String deviceUuid;
final String code;
const FlushMountedPresenceSensorGetDeviceReportsEvent({
required this.deviceUuid,
required this.code,
});
@override
List<Object> get props => [deviceUuid, code];
}
class FlushMountedPresenceSensorShowDescriptionEvent
extends FlushMountedPresenceSensorEvent {
final String description;
const FlushMountedPresenceSensorShowDescriptionEvent({required this.description});
}
class FlushMountedPresenceSensorBackToGridViewEvent
extends FlushMountedPresenceSensorEvent {}
class FlushMountedPresenceSensorBatchControlEvent
extends FlushMountedPresenceSensorEvent {
final List<String> deviceIds;
final String code;
final dynamic value;
const FlushMountedPresenceSensorBatchControlEvent({
required this.deviceIds,
required this.code,
required this.value,
});
@override
List<Object> get props => [deviceIds, code, value];
}
class FlushMountedPresenceSensorFactoryResetEvent
extends FlushMountedPresenceSensorEvent {
final String deviceId;
final FactoryResetModel factoryReset;
const FlushMountedPresenceSensorFactoryResetEvent({
required this.deviceId,
required this.factoryReset,
});
}

View File

@ -0,0 +1,76 @@
part of 'flush_mounted_presence_sensor_bloc.dart';
sealed class FlushMountedPresenceSensorState extends Equatable {
const FlushMountedPresenceSensorState();
@override
List<Object> get props => [];
}
class FlushMountedPresenceSensorInitialState
extends FlushMountedPresenceSensorState {}
class FlushMountedPresenceSensorLoadingInitialState
extends FlushMountedPresenceSensorState {}
class FlushMountedPresenceSensorUpdateState extends FlushMountedPresenceSensorState {
final FlushMountedPresenceSensorModel model;
const FlushMountedPresenceSensorUpdateState({required this.model});
@override
List<Object> get props => [model];
}
class FlushMountedPresenceSensorLoadingNewSate
extends FlushMountedPresenceSensorState {
final FlushMountedPresenceSensorModel model;
const FlushMountedPresenceSensorLoadingNewSate({required this.model});
@override
List<Object> get props => [model];
}
class FlushMountedPresenceSensorFailedState extends FlushMountedPresenceSensorState {
final String error;
const FlushMountedPresenceSensorFailedState({required this.error});
@override
List<Object> get props => [error];
}
class FlushMountedPresenceSensorDeviceReportsLoadingState
extends FlushMountedPresenceSensorState {}
class FlushMountedPresenceSensorDeviceReportsState
extends FlushMountedPresenceSensorState {
const FlushMountedPresenceSensorDeviceReportsState({
required this.deviceReport,
required this.code,
});
final DeviceReport deviceReport;
final String code;
@override
List<Object> get props => [deviceReport, code];
}
class FlushMountedPresenceSensorDeviceReportsFailedState
extends FlushMountedPresenceSensorState {
const FlushMountedPresenceSensorDeviceReportsFailedState({required this.error});
final String error;
@override
List<Object> get props => [error];
}
class FlushMountedPresenceSensorShowDescriptionState
extends FlushMountedPresenceSensorState {
const FlushMountedPresenceSensorShowDescriptionState({required this.description});
final String description;
@override
List<Object> get props => [description];
}

View File

@ -0,0 +1,21 @@
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart';
import 'package:syncrow_web/services/batch_control_devices_service.dart';
import 'package:syncrow_web/services/control_device_service.dart';
abstract final class FlushMountedPresenceSensorBlocFactory {
const FlushMountedPresenceSensorBlocFactory._();
static FlushMountedPresenceSensorBloc create({
required String deviceId,
}) {
return FlushMountedPresenceSensorBloc(
deviceId: deviceId,
controlDeviceService: DebouncedControlDeviceService(
decoratee: RemoteControlDeviceService(),
),
batchControlDevicesService: DebouncedBatchControlDevicesService(
decoratee: RemoteBatchControlDevicesService(),
),
);
}
}

View File

@ -0,0 +1,99 @@
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
class FlushMountedPresenceSensorModel {
FlushMountedPresenceSensorModel({
required this.presenceState,
required this.farDetection,
required this.illuminance,
required this.sensitivity,
required this.occurDistReduce,
required this.noneDelay,
required this.presenceDelay,
required this.nearDetection,
required this.sensiReduce,
required this.checkingResult,
});
static const String codePresenceState = 'presence_state';
static const String codeSensitivity = 'sensitivity';
static const String codeNearDetection = 'near_detection';
static const String codeFarDetection = 'far_detection';
static const String codeCheckingResult = 'checking_result';
static const String codePresenceDelay = 'presence_delay';
static const String codeNoneDelay = 'none_delay';
static const String codeOccurDistReduce = 'occur_dist_reduce';
static const String codeIlluminance = 'illum_value';
static const String codeSensiReduce = 'sensi_reduce';
String presenceState;
int sensitivity;
int nearDetection;
int farDetection;
String checkingResult;
int presenceDelay;
int noneDelay;
int occurDistReduce;
int illuminance;
int sensiReduce;
factory FlushMountedPresenceSensorModel.fromJson(List<Status> jsonList) {
String presenceState = 'none';
int sensitivity = 0;
int nearDetection = 0;
int farDetection = 0;
String checkingResult = 'none';
int presenceDelay = 0;
int noneDelay = 0;
int occurDistReduce = 0;
int illuminance = 0;
int sensiReduce = 0;
for (var status in jsonList) {
switch (status.code) {
case codePresenceState:
presenceState = status.value ?? 'presence';
break;
case codeSensitivity:
sensitivity = status.value ?? 0;
break;
case codeNearDetection:
nearDetection = status.value ?? 0;
break;
case codeFarDetection:
farDetection = status.value ?? 0;
break;
case codeCheckingResult:
checkingResult = status.value ?? 'check_success';
break;
case codePresenceDelay:
presenceDelay = status.value ?? 0;
break;
case codeNoneDelay:
noneDelay = status.value ?? 0;
break;
case codeOccurDistReduce:
occurDistReduce = status.value ?? 0;
break;
case codeIlluminance:
illuminance = status.value ?? 0;
break;
case codeSensiReduce:
sensiReduce = status.value ?? 0;
break;
}
}
return FlushMountedPresenceSensorModel(
presenceState: presenceState,
sensitivity: sensitivity,
nearDetection: nearDetection,
farDetection: farDetection,
checkingResult: checkingResult,
presenceDelay: presenceDelay,
noneDelay: noneDelay,
occurDistReduce: occurDistReduce,
illuminance: illuminance,
sensiReduce: sensiReduce,
);
}
}

View File

@ -0,0 +1,183 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart';
import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_reset.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_update_data.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
class FlushMountedPresenceSensorBatchControlView extends StatelessWidget
with HelperResponsiveLayout {
const FlushMountedPresenceSensorBatchControlView({
required this.devicesIds,
super.key,
});
final List<String> devicesIds;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => FlushMountedPresenceSensorBlocFactory.create(
deviceId: devicesIds.first,
)..add(FlushMountedPresenceSensorFetchBatchStatusEvent(devicesIds)),
child: BlocBuilder<FlushMountedPresenceSensorBloc,
FlushMountedPresenceSensorState>(
builder: (context, state) {
if (state is FlushMountedPresenceSensorLoadingInitialState ||
state is FlushMountedPresenceSensorDeviceReportsLoadingState) {
return const Center(child: CircularProgressIndicator());
} else if (state is FlushMountedPresenceSensorUpdateState) {
return _buildGridView(context, state.model);
}
return const Center(child: Text('Error fetching status'));
},
),
);
}
Widget _buildGridView(
BuildContext context,
FlushMountedPresenceSensorModel model,
) {
final isExtraLarge = isExtraLargeScreenSize(context);
final isLarge = isLargeScreenSize(context);
final isMedium = isMediumScreenSize(context);
return GridView(
padding: const EdgeInsets.symmetric(horizontal: 50),
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: isLarge || isExtraLarge
? 3
: isMedium
? 2
: 1,
mainAxisExtent: 140,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
children: [
PresenceUpdateData(
value: model.sensitivity.toDouble(),
title: 'Sensitivity:',
minValue: 0,
maxValue: 9,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeSensitivity,
value: value,
),
),
),
PresenceUpdateData(
value: (model.nearDetection / 100).toDouble(),
title: 'Nearest Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeNearDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: (model.farDetection / 100).toDouble(),
title: 'Max Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeFarDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: model.presenceDelay.toDouble(),
title: 'Trigger Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codePresenceDelay,
value: value,
),
),
),
PresenceUpdateData(
value: model.occurDistReduce.toDouble(),
title: 'Indent Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeOccurDistReduce,
value: value,
),
),
),
PresenceUpdateData(
value: (model.sensiReduce.toDouble()),
title: 'Target Confirm Time:',
description: 's',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeSensiReduce,
value: value,
),
),
),
PresenceUpdateData(
value: ((model.noneDelay / 10).toDouble()),
description: 's',
title: 'Disappe Delay:',
minValue: 20,
maxValue: 300,
steps: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorBatchControlEvent(
deviceIds: devicesIds,
code: FlushMountedPresenceSensorModel.codeNoneDelay,
value: (value * 10).round(),
),
),
),
FactoryResetWidget(
callFactoryReset: () {
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorFactoryResetEvent(
deviceId: devicesIds.first,
factoryReset: FactoryResetModel(devicesUuid: devicesIds),
),
);
},
),
],
);
}
}

View File

@ -0,0 +1,217 @@
import 'package:flutter/material.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/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_display_data.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_status.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_update_data.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/description_view.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
class FlushMountedPresenceSensorControlView extends StatelessWidget
with HelperResponsiveLayout {
const FlushMountedPresenceSensorControlView({super.key, required this.device});
final AllDevicesModel device;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => FlushMountedPresenceSensorBlocFactory.create(
deviceId: device.uuid ?? '-1',
)..add(FlushMountedPresenceSensorFetchStatusEvent()),
child: BlocBuilder<FlushMountedPresenceSensorBloc,
FlushMountedPresenceSensorState>(
builder: (context, state) {
if (state is FlushMountedPresenceSensorLoadingInitialState ||
state is FlushMountedPresenceSensorDeviceReportsLoadingState) {
return const Center(child: CircularProgressIndicator());
} else if (state is FlushMountedPresenceSensorUpdateState) {
return _buildGridView(context, state.model);
} else if (state is FlushMountedPresenceSensorDeviceReportsState) {
return ReportsTable(
report: state.deviceReport,
thirdColumnTitle:
state.code == 'illuminance_value' ? "Value" : 'Status',
thirdColumnDescription:
state.code == 'illuminance_value' ? "Lux" : null,
onRowTap: (index) {},
onClose: () {
context
.read<FlushMountedPresenceSensorBloc>()
.add(FlushMountedPresenceSensorBackToGridViewEvent());
},
);
} else if (state is FlushMountedPresenceSensorShowDescriptionState) {
return DescriptionView(
description: state.description,
onClose: () {
context
.read<FlushMountedPresenceSensorBloc>()
.add(FlushMountedPresenceSensorBackToGridViewEvent());
},
);
} else if (state is FlushMountedPresenceSensorDeviceReportsFailedState) {
final model =
context.read<FlushMountedPresenceSensorBloc>().deviceStatus;
return _buildGridView(context, model);
}
return const Center(
child: Text('Error fetching status', textAlign: TextAlign.center),
);
},
),
);
}
Widget _buildGridView(
BuildContext context,
FlushMountedPresenceSensorModel model,
) {
final isExtraLarge = isExtraLargeScreenSize(context);
final isLarge = isLargeScreenSize(context);
final isMedium = isMediumScreenSize(context);
return GridView(
padding: const EdgeInsets.symmetric(horizontal: 50),
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: isLarge || isExtraLarge
? 3
: isMedium
? 2
: 1,
mainAxisExtent: 140,
crossAxisSpacing: 12,
mainAxisSpacing: 12,
),
children: [
PresenceState(
value: model.presenceState,
),
PresenceDisplayValue(
value: model.illuminance.toString(),
postfix: 'Lux',
description: 'Illuminance Value',
),
PresenceUpdateData(
value: model.sensitivity.toDouble(),
title: 'Sensitivity:',
minValue: 0,
maxValue: 9,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeSensitivity,
value: value,
),
),
),
PresenceUpdateData(
value: (model.nearDetection / 100).toDouble(),
title: 'Nearest Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeNearDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: (model.farDetection / 100).toDouble(),
title: 'Max Detect Dist:',
description: 'm',
minValue: 0.0,
maxValue: 9.5,
steps: 0.1,
valuesPercision: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeFarDetection,
value: (value * 100).toInt(),
),
),
),
PresenceUpdateData(
value: (model.presenceDelay.toDouble()),
title: 'Trigger Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codePresenceDelay,
value: value,
),
),
),
PresenceUpdateData(
value: (model.occurDistReduce.toDouble()),
title: 'Indent Level:',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeOccurDistReduce,
value: value,
),
),
),
PresenceUpdateData(
value: (model.sensiReduce.toDouble()),
title: 'Target Confirm Time:',
description: 's',
minValue: 0,
maxValue: 3,
steps: 1,
action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeSensiReduce,
value: value,
),
),
),
PresenceUpdateData(
value: ((model.noneDelay / 10).toDouble()),
description: 's',
title: 'Disappe Delay:',
minValue: 20,
maxValue: 300,
steps: 1,
action: (double value) =>
context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorChangeValueEvent(
code: FlushMountedPresenceSensorModel.codeNoneDelay,
value: (value * 10).round(),
),
),
),
GestureDetector(
onTap: () => context.read<FlushMountedPresenceSensorBloc>().add(
FlushMountedPresenceSensorGetDeviceReportsEvent(
code: 'presence_state',
deviceUuid: device.uuid!,
),
),
child: const PresenceStaticWidget(
icon: Assets.presenceRecordIcon,
description: 'Presence Record',
),
),
],
);
}
}

View File

@ -4,7 +4,6 @@ import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_re
import 'package:syncrow_web/pages/device_managment/main_door_sensor/bloc/main_door_sensor_bloc.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/bloc/main_door_sensor_event.dart';
import 'package:syncrow_web/pages/device_managment/shared/batch_control/factory_reset.dart';
// import 'package:syncrow_web/pages/device_managment/shared/batch_control/firmware_update.dart';
class MainDoorSensorBatchView extends StatelessWidget {
const MainDoorSensorBatchView({super.key, required this.devicesIds});
@ -13,35 +12,31 @@ class MainDoorSensorBatchView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// SizedBox(
// width: 170,
// height: 140,
// child: FirmwareUpdateWidget(
// deviceId: devicesIds.first,
// version: 12,
// ),
// ),
// const SizedBox(
// width: 12,
// ),
SizedBox(
width: 170,
height: 140,
child: FactoryResetWidget(
callFactoryReset: () {
BlocProvider.of<MainDoorSensorBloc>(context).add(
MainDoorSensorFactoryReset(
deviceId: devicesIds.first,
factoryReset: FactoryResetModel(devicesUuid: devicesIds),
return BlocProvider(
create: (context) => MainDoorSensorBloc(),
child: Builder(
builder: (innerContext) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 170,
height: 140,
child: FactoryResetWidget(
callFactoryReset: () {
BlocProvider.of<MainDoorSensorBloc>(innerContext).add(
MainDoorSensorFactoryReset(
deviceId: devicesIds.first,
factoryReset: FactoryResetModel(devicesUuid: devicesIds),
),
);
},
),
);
},
),
),
],
),
],
);
},
),
);
}
}

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_controls_container.dart';
import 'package:syncrow_web/pages/device_managment/shared/increament_decreament.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
class PresenceUpdateData extends StatefulWidget {
const PresenceUpdateData({
@ -13,6 +14,7 @@ class PresenceUpdateData extends StatefulWidget {
required this.maxValue,
required this.steps,
this.description,
this.valuesPercision = 0,
});
final String title;
@ -22,6 +24,7 @@ class PresenceUpdateData extends StatefulWidget {
final double steps;
final Function action;
final String? description;
final int valuesPercision;
@override
State<PresenceUpdateData> createState() => _CurrentTempState();
@ -45,7 +48,7 @@ class _CurrentTempState extends State<PresenceUpdateData> {
}
void _onValueChanged(double newValue) {
widget.action(newValue.toInt());
widget.action(newValue);
}
@override
@ -62,11 +65,14 @@ class _CurrentTempState extends State<PresenceUpdateData> {
children: [
Text(
widget.title,
style: Theme.of(context).textTheme.bodySmall!.copyWith(
color: ColorsManager.blackColor, fontWeight: FontWeight.w400, fontSize: 10),
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.blackColor,
fontWeight: FontWeight.w400,
fontSize: 10,
),
),
IncrementDecrementWidget(
value: widget.value.toString(),
value: widget.value.toStringAsFixed(widget.valuesPercision),
description: widget.description ?? '',
descriptionColor: ColorsManager.blackColor,
onIncrement: () {

View File

@ -84,6 +84,16 @@ class _PresenceUpdateDataState extends State<PresenceNoBodyTime> {
}
}
@override
void didUpdateWidget(PresenceNoBodyTime oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.value != widget.value) {
setState(() {
_currentValue = widget.value;
});
}
}
@override
Widget build(BuildContext context) {
return DeviceControlsContainer(

View File

@ -21,6 +21,7 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
on<ShowDescriptionEvent>(_showDescription);
on<BackToGridViewEvent>(_backToGridView);
on<WallSensorFactoryResetEvent>(_onFactoryReset);
on<WallSensorRealtimeUpdateEvent>(_onRealtimeUpdate);
}
void _fetchWallSensorStatus(
@ -30,7 +31,7 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
var response = await DevicesManagementApi().getDeviceStatus(deviceId);
deviceStatus = WallSensorModel.fromJson(response.status);
emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
_listenToChanges(emit, deviceId);
_listenToChanges(deviceId);
} catch (e) {
emit(WallSensorFailedState(error: e.toString()));
return;
@ -52,28 +53,27 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
}
}
_listenToChanges(Emitter<WallSensorState> emit, deviceId) {
try {
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$deviceId');
Stream<DatabaseEvent> stream = ref.onValue;
void _listenToChanges(String deviceId) {
DatabaseReference ref =
FirebaseDatabase.instance.ref('device-status/$deviceId');
ref.onValue.listen((DatabaseEvent event) {
final data = event.snapshot.value as Map<dynamic, dynamic>?;
if (data == null) return;
stream.listen((DatabaseEvent event) {
Map<dynamic, dynamic> usersMap =
event.snapshot.value as Map<dynamic, dynamic>;
List<Status> statusList = [];
final statusList = (data['status'] as List?)
?.map((e) => Status(code: e['code'], value: e['value']))
.toList();
usersMap['status'].forEach((element) {
statusList
.add(Status(code: element['code'], value: element['value']));
});
deviceStatus = WallSensorModel.fromJson(statusList);
emit(WallSensorLoadingNewSate(wallSensorModel: deviceStatus));
});
} catch (_) {}
if (statusList != null) {
final updatedDeviceStatus = WallSensorModel.fromJson(statusList);
if (!isClosed) {
add(WallSensorRealtimeUpdateEvent(updatedDeviceStatus));
}
}
});
}
void _changeValue(
WallSensorChangeValueEvent event, Emitter<WallSensorState> emit) async {
emit(WallSensorLoadingNewSate(wallSensorModel: deviceStatus));
@ -195,4 +195,12 @@ class WallSensorBloc extends Bloc<WallSensorEvent, WallSensorState> {
emit(WallSensorFailedState(error: e.toString()));
}
}
void _onRealtimeUpdate(
WallSensorRealtimeUpdateEvent event,
Emitter<WallSensorState> emit,
) {
deviceStatus = event.deviceStatus;
emit(WallSensorUpdateState(wallSensorModel: deviceStatus));
}
}

View File

@ -1,5 +1,6 @@
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/factory_reset_model.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/model/wall_sensor_model.dart';
abstract class WallSensorEvent extends Equatable {
const WallSensorEvent();
@ -70,3 +71,8 @@ class WallSensorFactoryResetEvent extends WallSensorEvent {
required this.factoryReset,
});
}
class WallSensorRealtimeUpdateEvent extends WallSensorEvent {
final WallSensorModel deviceStatus;
const WallSensorRealtimeUpdateEvent(this.deviceStatus);
}

View File

@ -5,7 +5,6 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
@ -15,13 +14,18 @@ class SaveRoutineHelper {
static Future<void> showSaveRoutineDialog(BuildContext context) async {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
builder: (context) {
return BlocBuilder<RoutineBloc, RoutineState>(
builder: (context, state) {
final selectedConditionLabel = state.selectedAutomationOperator == 'and'
? 'All Conditions are met'
: 'Any Condition is met';
return AlertDialog(
contentPadding: EdgeInsets.zero,
content: Container(
width: MediaQuery.sizeOf(context).width * 0.5,
width: context.screenWidth * 0.5,
height: 500,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
@ -29,99 +33,42 @@ class SaveRoutineHelper {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
DialogHeader('Create a scene: ${state.routineName ?? ""}'),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Left side - IF
Expanded(
child: ListView(
// crossAxisAlignment: CrossAxisAlignment.start,
shrinkWrap: true,
children: [
const Text(
'IF:',
style: TextStyle(
fontSize: 16,
),
),
const SizedBox(height: 8),
if (state.isTabToRun)
ListTile(
leading: SvgPicture.asset(
Assets.tabToRun,
width: 24,
height: 24,
),
title: const Text('Tab to run'),
),
if (state.isAutomation)
...state.ifItems.map((item) {
final functions =
state.selectedFunctions[item['uniqueCustomId']] ?? [];
return functionRow(item, context, functions);
}),
],
),
const SizedBox(height: 18),
Text(
'Create a scene: ${state.routineName ?? ""}',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity,
fontWeight: FontWeight.bold,
),
const SizedBox(width: 16),
// Right side - THEN items
Expanded(
child: ListView(
// crossAxisAlignment: CrossAxisAlignment.start,
shrinkWrap: true,
children: [
const Text(
'THEN:',
style: TextStyle(
fontSize: 16,
),
),
const SizedBox(height: 8),
...state.thenItems.map((item) {
final functions =
state.selectedFunctions[item['uniqueCustomId']] ?? [];
return functionRow(item, context, functions);
}),
],
),
const SizedBox(height: 18),
_buildDivider(),
_buildListsLabelRow(selectedConditionLabel),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.symmetric(
horizontal: 16,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
spacing: 24,
children: [
_buildIfConditions(state, context),
Container(
width: 1,
color: ColorsManager.greyColor.withValues(alpha: 0.8),
),
),
],
_buildThenActions(state, context),
],
),
),
),
// if (state.errorMessage != null || state.errorMessage!.isNotEmpty)
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: Text(
// state.errorMessage!,
// style: const TextStyle(color: Colors.red),
// ),
// ),
DialogFooter(
onCancel: () => Navigator.pop(context),
onConfirm: () async {
if (state.isAutomation) {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateAutomation());
} else {
context.read<RoutineBloc>().add(const CreateAutomationEvent());
}
} else {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateScene());
} else {
context.read<RoutineBloc>().add(const CreateSceneEvent());
}
}
// if (state.errorMessage == null || state.errorMessage!.isEmpty) {
Navigator.pop(context);
// }
},
isConfirmEnabled: true,
),
_buildDivider(),
const SizedBox(height: 8),
_buildDialogFooter(context, state),
const SizedBox(height: 8),
],
),
),
@ -132,8 +79,107 @@ class SaveRoutineHelper {
);
}
static Container _buildDivider() {
return Container(
height: 1,
width: double.infinity,
color: ColorsManager.greyColor,
);
}
static Widget _buildListsLabelRow(String selectedConditionLabel) {
const textStyle = TextStyle(
fontSize: 16,
);
return Container(
color: ColorsManager.backgroundColor.withValues(alpha: 0.5),
padding: const EdgeInsetsDirectional.all(20),
child: Row(
spacing: 16,
children: [
Expanded(child: Text('IF: $selectedConditionLabel', style: textStyle)),
const Expanded(child: Text('THEN:', style: textStyle)),
],
),
);
}
static Widget _buildDialogFooter(BuildContext context, RoutineState state) {
return Row(
spacing: 16,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
DialogFooterButton(
text: 'Cancel',
onTap: () => Navigator.pop(context),
),
DialogFooterButton(
text: 'Confirm',
onTap: () {
if (state.isAutomation) {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateAutomation());
} else {
context.read<RoutineBloc>().add(const CreateAutomationEvent());
}
} else {
if (state.isUpdate ?? false) {
context.read<RoutineBloc>().add(const UpdateScene());
} else {
context.read<RoutineBloc>().add(const CreateSceneEvent());
}
}
Navigator.pop(context);
},
textColor: ColorsManager.primaryColorWithOpacity,
),
],
);
}
static Widget _buildThenActions(RoutineState state, BuildContext context) {
return Expanded(
child: ListView(
// shrinkWrap: true,
children: state.thenItems.map((item) {
final functions = state.selectedFunctions[item['uniqueCustomId']] ?? [];
return functionRow(item, context, functions);
}).toList(),
),
);
}
static Widget _buildIfConditions(RoutineState state, BuildContext context) {
return Expanded(
child: ListView(
// shrinkWrap: true,
children: [
if (state.isTabToRun)
ListTile(
leading: SvgPicture.asset(
Assets.tabToRun,
width: 24,
height: 24,
),
title: const Text('Tab to run'),
),
if (state.isAutomation)
...state.ifItems.map((item) {
final functions =
state.selectedFunctions[item['uniqueCustomId']] ?? [];
return functionRow(item, context, functions);
}),
],
),
);
}
static Widget functionRow(
dynamic item, BuildContext context, List<DeviceFunctionData> functions) {
dynamic item,
BuildContext context,
List<DeviceFunctionData> functions,
) {
return Padding(
padding: const EdgeInsets.only(top: 6),
child: Row(
@ -142,19 +188,36 @@ class SaveRoutineHelper {
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
spacing: 8,
spacing: 17,
children: [
item['type'] == 'tap_to_run' || item['type'] == 'scene'
? Image.memory(
base64Decode(item['icon']),
width: 22,
height: 22,
)
: SvgPicture.asset(
item['imagePath'],
width: 22,
height: 22,
),
Container(
width: 22,
height: 22,
padding: const EdgeInsetsDirectional.all(4),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: ColorsManager.textFieldGreyColor,
border: Border.all(
color: ColorsManager.neutralGray,
width: 1.5,
),
),
child: Center(
child: item['type'] == 'tap_to_run' || item['type'] == 'scene'
? Image.memory(
base64Decode(item['icon']),
width: 12,
height: 22,
fit: BoxFit.scaleDown,
)
: SvgPicture.asset(
item['imagePath'],
width: 12,
height: 12,
fit: BoxFit.scaleDown,
),
),
),
Flexible(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
@ -166,19 +229,25 @@ class SaveRoutineHelper {
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: context.textTheme.bodySmall?.copyWith(
fontSize: 14,
fontSize: 15,
color: ColorsManager.textPrimaryColor,
),
),
Wrap(
runSpacing: 16,
spacing: 4,
children: functions
.map((f) => Text(
'${f.operationName}: ${f.value}',
style: context.textTheme.bodySmall
?.copyWith(color: ColorsManager.grayColor, fontSize: 8),
overflow: TextOverflow.ellipsis,
maxLines: 3,
))
.map(
(function) => Text(
'${function.operationName}: ${function.value}',
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.grayColor,
fontSize: 8,
),
overflow: TextOverflow.ellipsis,
maxLines: 3,
),
)
.toList(),
),
],
@ -197,7 +266,13 @@ class SaveRoutineHelper {
child: Row(
spacing: 2,
children: [
SizedBox(width: 8, height: 8, child: SvgPicture.asset(Assets.deviceTagIcon)),
SizedBox(
width: 8,
height: 8,
child: SvgPicture.asset(
Assets.deviceTagIcon,
),
),
Text(
item['tag'] ?? '',
textAlign: TextAlign.center,
@ -218,7 +293,12 @@ class SaveRoutineHelper {
spacing: 2,
children: [
SizedBox(
width: 8, height: 8, child: SvgPicture.asset(Assets.spaceLocationIcon)),
width: 8,
height: 8,
child: SvgPicture.asset(
Assets.spaceLocationIcon,
),
),
Text(
item['subSpace'] ?? '',
textAlign: TextAlign.center,

View File

@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_event.dart';
import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_event.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/create_new_routines/create_new_routines.dart';
import 'package:syncrow_web/pages/routines/view/create_new_routine_view.dart';
@ -9,6 +9,7 @@ import 'package:syncrow_web/pages/routines/widgets/main_routine_view/fetch_routi
import 'package:syncrow_web/pages/routines/widgets/main_routine_view/routine_view_card.dart';
import 'package:syncrow_web/pages/space_tree/view/space_tree_view.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
class RoutinesView extends StatefulWidget {
const RoutinesView({super.key});
@ -27,9 +28,10 @@ class _RoutinesViewState extends State<RoutinesView> {
if (result == null) return;
final communityId = result['community'];
final spaceId = result['space'];
final _bloc = BlocProvider.of<CreateRoutineBloc>(context);
final bloc = BlocProvider.of<CreateRoutineBloc>(context);
final routineBloc = context.read<RoutineBloc>();
_bloc.add(SaveCommunityIdAndSpaceIdEvent(communityID: communityId, spaceID: spaceId));
bloc.add(
SaveCommunityIdAndSpaceIdEvent(communityID: communityId, spaceID: spaceId));
await Future.delayed(const Duration(seconds: 1));
routineBloc.add(const CreateNewRoutineViewEvent(createRoutineView: true));
}
@ -54,43 +56,41 @@ class _RoutinesViewState extends State<RoutinesView> {
),
Expanded(
flex: 4,
child: ListView(
children: [
Container(
padding: const EdgeInsets.all(16),
height: MediaQuery.sizeOf(context).height,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Create New Routines",
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
RoutineViewCard(
isLoading: false,
onChanged: (v) {},
status: '',
spaceId: '',
automationId: '',
communityId: '',
sceneId: '',
cardType: '',
spaceName: '',
onTap: () => _handleRoutineCreation(context),
icon: Icons.add,
textString: '',
),
const SizedBox(height: 15),
const Expanded(child: FetchRoutineScenesAutomation()),
],
),
child: SizedBox(
height: context.screenHeight,
width: context.screenWidth,
child: SingleChildScrollView(
padding: const EdgeInsetsDirectional.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
spacing: 16,
children: [
Text(
"Create New Routines",
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.bold,
),
),
RoutineViewCard(
isLoading: false,
onChanged: (v) {},
status: '',
spaceId: '',
automationId: '',
communityId: '',
sceneId: '',
cardType: '',
spaceName: '',
onTap: () => _handleRoutineCreation(context),
icon: Icons.add,
textString: '',
),
const FetchRoutineScenesAutomation(),
],
),
const SizedBox(height: 50),
],
),
),
)
],

View File

@ -28,32 +28,40 @@ class DialogFooter extends StatelessWidget {
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_buildFooterButton(
context: context,
DialogFooterButton(
text: 'Cancel',
onTap: onCancel,
),
if (isConfirmEnabled) ...[
Container(width: 1, height: 50, color: ColorsManager.greyColor),
_buildFooterButton(
context: context,
DialogFooterButton(
text: 'Confirm',
onTap: onConfirm,
textColor:
isConfirmEnabled ? ColorsManager.primaryColorWithOpacity : Colors.red,
textColor: isConfirmEnabled
? ColorsManager.primaryColorWithOpacity
: Colors.red,
),
],
],
),
);
}
}
Widget _buildFooterButton({
required BuildContext context,
required String text,
required VoidCallback? onTap,
Color? textColor,
}) {
class DialogFooterButton extends StatelessWidget {
const DialogFooterButton({
required this.text,
required this.onTap,
this.textColor,
super.key,
});
final String text;
final VoidCallback? onTap;
final Color? textColor;
@override
Widget build(BuildContext context) {
return Expanded(
child: TextButton(
style: TextButton.styleFrom(

View File

@ -16,6 +16,7 @@ class DialogHeader extends StatelessWidget {
),
Text(
title,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity,
fontWeight: FontWeight.bold,

View File

@ -225,7 +225,7 @@ class DraggableCard extends StatelessWidget {
if (function.functionCode == 'temp_set' || function.functionCode == 'temp_current') {
return '${(function.value / 10).toStringAsFixed(0)}°C';
} else if (function.functionCode.contains('countdown')) {
final seconds = function.value.toInt();
final seconds = function.value?.toInt() ?? 0;
if (seconds >= 3600) {
final hours = (seconds / 3600).floor();
final remainingMinutes = ((seconds % 3600) / 60).floor();

View File

@ -8,211 +8,182 @@ import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
class FetchRoutineScenesAutomation extends StatefulWidget {
const FetchRoutineScenesAutomation({super.key});
@override
State<FetchRoutineScenesAutomation> createState() =>
_FetchRoutineScenesState();
}
class _FetchRoutineScenesState extends State<FetchRoutineScenesAutomation>
class FetchRoutineScenesAutomation extends StatelessWidget
with HelperResponsiveLayout {
@override
void initState() {
super.initState();
}
const FetchRoutineScenesAutomation({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<RoutineBloc, RoutineState>(
builder: (context, state) {
return state.isLoading
? const Center(
child: CircularProgressIndicator(),
)
: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Scenes (Tab to Run)",
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
if (state.scenes.isEmpty)
Text(
"No scenes found",
style: context.textTheme.bodyMedium?.copyWith(
color: ColorsManager.grayColor,
),
),
if (state.scenes.isNotEmpty)
SizedBox(
height: 200,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: state.scenes.length,
itemBuilder: (context, index) {
final scene = state.scenes[index];
final isLoading =
state.loadingSceneId == scene.id;
if (state.isLoading) return const Center(child: CircularProgressIndicator());
return Padding(
padding: EdgeInsets.only(
right:
isSmallScreenSize(context) ? 4.0 : 8.0,
),
child: Column(
children: [
RoutineViewCard(
isLoading: isLoading,
sceneOnTap: () {
context.read<RoutineBloc>().add(
SceneTrigger(
sceneId: scene.id,
name: scene.name));
},
status: state.scenes[index].status,
communityId:
state.scenes[index].communityId ??
'',
spaceId: state.scenes[index].spaceId,
sceneId:
state.scenes[index].sceneTuyaId!,
automationId: state.scenes[index].id,
cardType: 'scenes',
spaceName:
state.scenes[index].spaceName,
onTap: () {
BlocProvider.of<RoutineBloc>(context)
.add(
const CreateNewRoutineViewEvent(
createRoutineView: true),
);
context.read<RoutineBloc>().add(
GetSceneDetails(
sceneId:
state.scenes[index].id,
isTabToRun: true,
isUpdate: true,
),
);
},
textString: state.scenes[index].name,
icon: state.scenes[index].icon ??
Assets.logoHorizontal,
isFromScenes: true,
iconInBytes:
state.scenes[index].iconInBytes,
),
],
),
);
}),
),
const SizedBox(height: 10),
Text(
"Automations",
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 3),
if (state.automations.isEmpty)
Text(
"No automations found",
style: context.textTheme.bodyMedium?.copyWith(
color: ColorsManager.grayColor,
),
),
if (state.automations.isNotEmpty)
SizedBox(
height: 200,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: state.automations.length,
itemBuilder: (context, index) {
final isLoading = state.automations!
.contains(state.automations[index].id);
return Column(
children: [
Padding(
padding: EdgeInsets.only(
right: isSmallScreenSize(context)
? 4.0
: 8.0,
),
child: RoutineViewCard(
isLoading: isLoading,
onChanged: (v) {
context.read<RoutineBloc>().add(
UpdateAutomationStatus(
automationId: state
.automations[index].id,
automationStatusUpdate:
AutomationStatusUpdate(
spaceUuid: state
.automations[
index]
.spaceId,
isEnable: v),
communityId: state
.automations[index]
.communityId,
),
);
},
status: state.automations[index].status,
communityId: '',
spaceId:
state.automations[index].spaceId,
sceneId: '',
automationId:
state.automations[index].id,
cardType: 'automations',
spaceName:
state.automations[index].spaceName,
onTap: () {
BlocProvider.of<RoutineBloc>(context)
.add(
const CreateNewRoutineViewEvent(
createRoutineView: true),
);
context.read<RoutineBloc>().add(
GetAutomationDetails(
automationId: state
.automations[index].id,
isAutomation: true,
isUpdate: true),
);
},
textString:
state.automations[index].name,
icon: state.automations[index].icon ??
Assets.automation,
),
),
],
);
}),
),
],
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildListTitle(context, "Scenes (Tab to Run)"),
const SizedBox(height: 10),
Visibility(
visible: state.scenes.isNotEmpty,
replacement: _buildEmptyState(context, "No scenes found"),
child: SizedBox(
height: 200,
child: _buildScenes(state),
),
),
);
const SizedBox(height: 10),
_buildListTitle(context, "Automations"),
const SizedBox(height: 3),
Visibility(
visible: state.automations.isNotEmpty,
replacement: _buildEmptyState(context, "No automations found"),
child: SizedBox(
height: 200,
child: _buildAutomations(state),
),
)
],
),
),
);
},
);
}
Widget _buildAutomations(RoutineState state) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: state.automations.length,
itemBuilder: (context, index) {
final isLoading = state.automations.contains(state.automations[index].id);
return Column(
children: [
Padding(
padding: EdgeInsets.only(
right: isSmallScreenSize(context) ? 4.0 : 8.0,
),
child: RoutineViewCard(
isLoading: isLoading,
onChanged: (v) {
context.read<RoutineBloc>().add(
UpdateAutomationStatus(
automationId: state.automations[index].id,
automationStatusUpdate: AutomationStatusUpdate(
spaceUuid: state.automations[index].spaceId,
isEnable: v,
),
communityId: state.automations[index].communityId,
),
);
},
status: state.automations[index].status,
communityId: '',
spaceId: state.automations[index].spaceId,
sceneId: '',
automationId: state.automations[index].id,
cardType: 'automations',
spaceName: state.automations[index].spaceName,
onTap: () {
BlocProvider.of<RoutineBloc>(context).add(
const CreateNewRoutineViewEvent(
createRoutineView: true,
),
);
context.read<RoutineBloc>().add(
GetAutomationDetails(
automationId: state.automations[index].id,
isAutomation: true,
isUpdate: true,
),
);
},
textString: state.automations[index].name,
icon: state.automations[index].icon ?? Assets.automation,
),
),
],
);
},
);
}
Widget _buildScenes(RoutineState state) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: state.scenes.length,
itemBuilder: (context, index) {
final scene = state.scenes[index];
final isLoading = state.loadingSceneId == scene.id;
return Padding(
padding: EdgeInsets.only(
right: isSmallScreenSize(context) ? 4.0 : 8.0,
),
child: Column(
children: [
RoutineViewCard(
isLoading: isLoading,
sceneOnTap: () {
context.read<RoutineBloc>().add(
SceneTrigger(
sceneId: scene.id,
name: scene.name,
),
);
},
status: state.scenes[index].status,
communityId: state.scenes[index].communityId,
spaceId: state.scenes[index].spaceId,
sceneId: state.scenes[index].sceneTuyaId!,
automationId: state.scenes[index].id,
cardType: 'scenes',
spaceName: state.scenes[index].spaceName,
onTap: () {
BlocProvider.of<RoutineBloc>(context).add(
const CreateNewRoutineViewEvent(
createRoutineView: true,
),
);
context.read<RoutineBloc>().add(
GetSceneDetails(
sceneId: state.scenes[index].id,
isTabToRun: true,
isUpdate: true,
),
);
},
textString: state.scenes[index].name,
icon: state.scenes[index].icon ?? Assets.logoHorizontal,
isFromScenes: true,
iconInBytes: state.scenes[index].iconInBytes,
),
],
),
);
});
}
Widget _buildListTitle(BuildContext context, String title) {
return Text(
title,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.bold,
),
);
}
Widget _buildEmptyState(BuildContext context, String title) {
return Text(
title,
style: context.textTheme.bodyMedium?.copyWith(
color: ColorsManager.grayColor,
),
);
}
}

View File

@ -1,4 +1,5 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@ -66,7 +67,6 @@ class _RoutineViewCardState extends State<RoutineViewCard> {
@override
Widget build(BuildContext context) {
// Use widget.<mixinMethod> instead of just <mixinMethod>
final double cardWidth = widget.isSmallScreenSize(context)
? 120
: widget.isMediumScreenSize(context)
@ -127,22 +127,23 @@ class _RoutineViewCardState extends State<RoutineViewCard> {
)
else
CupertinoSwitch(
activeColor: ColorsManager.primaryColor,
activeTrackColor: ColorsManager.primaryColor,
value: widget.status == 'enable',
onChanged: widget.onChanged,
)
],
)
: const SizedBox(),
InkWell(
onTap: widget.onTap,
child: Column(
children: [
Center(
Column(
children: [
Center(
child: InkWell(
customBorder: const CircleBorder(),
onTap: widget.onTap,
child: Container(
decoration: BoxDecoration(
color: ColorsManager.graysColor,
borderRadius: BorderRadius.circular(120),
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager.greyColor,
width: 2.0,
@ -158,7 +159,8 @@ class _RoutineViewCardState extends State<RoutineViewCard> {
height: iconSize,
width: iconSize,
fit: BoxFit.contain,
errorBuilder: (context, error, stackTrace) => Image.asset(
errorBuilder: (context, error, stackTrace) =>
Image.asset(
Assets.logo,
height: iconSize,
width: iconSize,
@ -171,7 +173,8 @@ class _RoutineViewCardState extends State<RoutineViewCard> {
width: iconSize,
fit: BoxFit.contain,
)
: (widget.icon is String && widget.icon.endsWith('.svg'))
: (widget.icon is String &&
widget.icon.endsWith('.svg'))
? SvgPicture.asset(
height: iconSize,
width: iconSize,
@ -181,51 +184,54 @@ class _RoutineViewCardState extends State<RoutineViewCard> {
: Icon(
widget.icon,
color: ColorsManager.dialogBlueTitle,
size: widget.isSmallScreenSize(context) ? 30 : 40,
size: widget.isSmallScreenSize(context)
? 30
: 40,
),
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 3),
child: Column(
children: [
Text(
widget.textString,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.blackColor,
fontSize: widget.isSmallScreenSize(context) ? 10 : 12,
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 3),
child: Column(
children: [
Text(
widget.textString,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.blackColor,
fontSize: widget.isSmallScreenSize(context) ? 10 : 12,
),
if (widget.spaceName != '')
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SvgPicture.asset(
Assets.spaceLocationIcon,
fit: BoxFit.contain,
),
if (widget.spaceName != '')
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SvgPicture.asset(
Assets.spaceLocationIcon,
fit: BoxFit.contain,
),
Text(
widget.spaceName,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.blackColor,
fontSize:
widget.isSmallScreenSize(context) ? 10 : 12,
),
Text(
widget.spaceName,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.blackColor,
fontSize: widget.isSmallScreenSize(context) ? 10 : 12,
),
),
],
),
],
),
),
],
),
],
),
],
),
),
],
),
],
),

View File

@ -1,16 +1,17 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/models/ac/ac_function.dart';
import 'package:syncrow_web/pages/routines/models/ac/ac_operational_value.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
class ACHelper {
static Future<Map<String, dynamic>?> showACFunctionsDialog({
@ -74,13 +75,26 @@ class ACHelper {
child: _buildFunctionsList(
context: context,
acFunctions: acFunctions,
onFunctionSelected:
(functionCode, operationName) => context
.read<FunctionBloc>()
.add(SelectFunction(
functionCode: functionCode,
operationName: operationName,
)),
device: device,
onFunctionSelected: (functionCode, operationName) {
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: functionCode,
functionOperationName: operationName,
functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'temp_set',
'temp_current',
],
defaultValue: functionCode == 'temp_set'
? 200
: functionCode == 'temp_current'
? -100
: 0,
);
},
),
),
// Value selector
@ -139,6 +153,7 @@ class ACHelper {
required BuildContext context,
required List<ACFunction> acFunctions,
required Function(String, String) onFunctionSelected,
required AllDevicesModel? device,
}) {
return ListView.separated(
shrinkWrap: false,
@ -191,8 +206,9 @@ class ACHelper {
required String operationName,
bool? removeComparators,
}) {
final initialVal = selectedFunction == 'temp_set' ? 200 : -100;
if (selectedFunction == 'temp_set' || selectedFunction == 'temp_current') {
final initialValue = selectedFunctionData?.value ?? 250;
final initialValue = selectedFunctionData?.value ?? initialVal;
return _buildTemperatureSelector(
context: context,
initialValue: initialValue,
@ -205,8 +221,7 @@ class ACHelper {
);
}
final selectedFn =
acFunctions.firstWhere((f) => f.code == selectedFunction);
final selectedFn = acFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList(
@ -287,7 +302,9 @@ class ACHelper {
functionCode: selectCode,
operationName: operationName,
condition: conditions[index],
value: selectedFunctionData?.value,
value: selectedFunctionData?.value ?? selectCode == 'temp_set'
? 200
: -100,
valueDescription: selectedFunctionData?.valueDescription,
),
),
@ -302,8 +319,7 @@ class ACHelper {
minHeight: 40.0,
minWidth: 40.0,
),
isSelected:
conditions.map((c) => c == (currentCondition ?? "==")).toList(),
isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(),
);
}
@ -317,6 +333,7 @@ class ACHelper {
DeviceFunctionData? selectedFunctionData,
String selectCode,
) {
final initialVal = selectCode == 'temp_set' ? 200 : -100;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
@ -324,7 +341,7 @@ class ACHelper {
borderRadius: BorderRadius.circular(10),
),
child: Text(
'${(initialValue ?? 200) / 10}°C',
'${(initialValue ?? initialVal) / 10}°C',
style: context.textTheme.headlineMedium!.copyWith(
color: ColorsManager.primaryColorWithOpacity,
),
@ -397,9 +414,7 @@ class ACHelper {
style: context.textTheme.bodyMedium,
),
trailing: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected
? ColorsManager.primaryColorWithOpacity
@ -415,8 +430,7 @@ class ACHelper {
operationName: operationName,
value: value.value,
condition: selectedFunctionData?.condition,
valueDescription:
selectedFunctionData?.valueDescription,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);

View File

@ -131,7 +131,12 @@ class _CeilingSensorDialogState extends State<CeilingSensorDialog> {
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CpsFunctionsList(cpsFunctions: _cpsFunctions),
CpsFunctionsList(
cpsFunctions: _cpsFunctions,
device: widget.device,
selectedFunctionData: selectedFunctionData,
dialogType: widget.dialogType,
),
if (state.selectedFunction != null)
Expanded(
child: isToggleFunction

View File

@ -46,7 +46,7 @@ class CpsDialogSliderSelector extends StatelessWidget {
functionCode: selectedFunction,
operationName: operationName,
condition: condition,
value: selectedFunctionData.value,
value: selectedFunctionData.value ?? 0,
),
),
),

View File

@ -1,14 +1,24 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/routines/models/ceiling_presence_sensor_functions.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialog_function_list_tile.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
class CpsFunctionsList extends StatelessWidget {
const CpsFunctionsList({required this.cpsFunctions, super.key});
const CpsFunctionsList({
required this.cpsFunctions,
required this.device,
required this.selectedFunctionData,
required this.dialogType,
super.key,
});
final List<CpsFunctions> cpsFunctions;
final AllDevicesModel? device;
final DeviceFunctionData? selectedFunctionData;
final String dialogType;
@override
Widget build(BuildContext context) {
@ -26,12 +36,27 @@ class CpsFunctionsList extends StatelessWidget {
return RoutineDialogFunctionListTile(
iconPath: function.icon,
operationName: function.operationName,
onTap: () => context.read<FunctionBloc>().add(
SelectFunction(
functionCode: function.code,
operationName: function.operationName,
),
),
onTap: () => RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName: function.operationName,
functionValueDescription: selectedFunctionData?.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'static_max_dis',
'presence_reference',
'moving_reference',
'perceptual_boundary',
'moving_boundary',
'moving_rigger_time',
'moving_static_time',
'none_body_time',
'moving_max_dis',
'moving_range',
'presence_range',
if (dialogType == "IF") 'sensitivity',
],
),
);
},
),

View File

@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
abstract final class RoutineTapFunctionHelper {
const RoutineTapFunctionHelper._();
static void onTapFunction(
BuildContext context, {
required String functionCode,
required String functionOperationName,
required String? functionValueDescription,
required String? deviceUuid,
required List<String> codesToAddIntoFunctionsWithDefaultValue,
int defaultValue = 0,
}) {
final functionsBloc = context.read<FunctionBloc>();
functionsBloc.add(
SelectFunction(
functionCode: functionCode,
operationName: functionOperationName,
),
);
final addedFunctions = functionsBloc.state.addedFunctions;
final isFunctionAlreadyAdded = addedFunctions.any(
(e) => e.functionCode == functionCode,
);
final shouldAddFunction =
codesToAddIntoFunctionsWithDefaultValue.contains(functionCode);
if (!isFunctionAlreadyAdded && shouldAddFunction) {
context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
entityId: deviceUuid ?? '',
functionCode: functionCode,
operationName: functionOperationName,
value: defaultValue,
condition: '==',
valueDescription: functionValueDescription,
),
),
);
}
}
}

View File

@ -11,6 +11,7 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/one_gang_switch/
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -24,21 +25,23 @@ class OneGangSwitchHelper {
required String uniqueCustomId,
required bool removeComparetors,
}) async {
List<BaseSwitchFunction> oneGangFunctions = functions.whereType<BaseSwitchFunction>().toList();
List<BaseSwitchFunction> oneGangFunctions =
functions.whereType<BaseSwitchFunction>().toList();
return showDialog<Map<String, dynamic>?>(
context: context,
builder: (BuildContext context) {
return BlocProvider(
create: (_) => FunctionBloc()..add(InitializeFunctions(deviceSelectedFunctions ?? [])),
create: (_) => FunctionBloc()
..add(InitializeFunctions(deviceSelectedFunctions ?? [])),
child: AlertDialog(
contentPadding: EdgeInsets.zero,
content: BlocBuilder<FunctionBloc, FunctionBlocState>(
builder: (context, state) {
final selectedFunction = state.selectedFunction;
final selectedOperationName = state.selectedOperationName;
final selectedFunctionData =
state.addedFunctions.firstWhere((f) => f.functionCode == selectedFunction,
final selectedFunctionData = state.addedFunctions
.firstWhere((f) => f.functionCode == selectedFunction,
orElse: () => DeviceFunctionData(
entityId: '',
functionCode: selectedFunction ?? '',
@ -84,12 +87,19 @@ class OneGangSwitchHelper {
size: 16,
color: ColorsManager.textGray,
),
onTap: () {
context.read<FunctionBloc>().add(SelectFunction(
functionCode: function.code,
operationName: function.operationName,
));
},
onTap: () =>
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName:
function.operationName,
functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
],
),
);
},
),
@ -164,7 +174,7 @@ class OneGangSwitchHelper {
required bool removeComparetors,
}) {
if (selectedFunction == 'countdown_1') {
final initialValue = selectedFunctionData?.value ?? 200;
final initialValue = selectedFunctionData?.value ?? 0;
return _buildCountDownSelector(
context: context,
initialValue: initialValue,
@ -220,11 +230,11 @@ class OneGangSwitchHelper {
selectedFunctionData,
),
const SizedBox(height: 20),
_buildCountDownDisplay(
context, initialValue, device, operationName, selectedFunctionData, selectCode),
_buildCountDownDisplay(context, initialValue, device, operationName,
selectedFunctionData, selectCode),
const SizedBox(height: 20),
_buildCountDownSlider(
context, initialValue, device, operationName, selectedFunctionData, selectCode),
_buildCountDownSlider(context, initialValue, device, operationName,
selectedFunctionData, selectCode),
],
);
}
@ -250,7 +260,7 @@ class OneGangSwitchHelper {
functionCode: selectCode,
operationName: operationName,
condition: conditions[index],
value: selectedFunctionData?.value,
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
@ -301,21 +311,23 @@ class OneGangSwitchHelper {
DeviceFunctionData? selectedFunctionData,
String selectCode,
) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue(
icon: '',
description: "sec",
value: 0.0,
minValue: 0,
maxValue: 86400,
maxValue: twelveHoursInSeconds,
stepValue: 1,
);
return Slider(
value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions: (((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
divisions:
(((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
onChanged: (value) {
context.read<FunctionBloc>().add(
AddFunction(
@ -367,7 +379,9 @@ class OneGangSwitchHelper {
trailing: Icon(
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected ? ColorsManager.primaryColorWithOpacity : ColorsManager.textGray,
color: isSelected
? ColorsManager.primaryColorWithOpacity
: ColorsManager.textGray,
),
onTap: () {
if (!isSelected) {

View File

@ -10,6 +10,7 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/base_switch_func
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -85,15 +86,21 @@ class ThreeGangSwitchHelper {
size: 16,
color: ColorsManager.textGray,
),
onTap: () {
context
.read<FunctionBloc>()
.add(SelectFunction(
functionCode: function.code,
operationName:
function.operationName,
));
},
onTap: () =>
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName:
function.operationName,
functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
'countdown_2',
'countdown_3',
],
),
);
},
),
@ -170,7 +177,7 @@ class ThreeGangSwitchHelper {
if (selectedFunction == 'countdown_1' ||
selectedFunction == 'countdown_2' ||
selectedFunction == 'countdown_3') {
final initialValue = selectedFunctionData?.value ?? 200;
final initialValue = selectedFunctionData?.value ?? 0;
return _buildTemperatureSelector(
context: context,
initialValue: initialValue,
@ -183,8 +190,7 @@ class ThreeGangSwitchHelper {
);
}
final selectedFn =
switchFunctions.firstWhere((f) => f.code == selectedFunction);
final selectedFn = switchFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList(
@ -251,7 +257,7 @@ class ThreeGangSwitchHelper {
functionCode: selectCode,
operationName: operationName,
condition: conditions[index],
value: selectedFunctionData?.value,
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
@ -266,8 +272,7 @@ class ThreeGangSwitchHelper {
minHeight: 40.0,
minWidth: 40.0,
),
isSelected:
conditions.map((c) => c == (currentCondition ?? "==")).toList(),
isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(),
);
}
@ -303,22 +308,23 @@ class ThreeGangSwitchHelper {
DeviceFunctionData? selectedFunctionData,
String selectCode,
) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue(
icon: '',
description: "sec",
value: 0.0,
minValue: 0,
maxValue: 86400,
maxValue: twelveHoursInSeconds,
stepValue: 1,
);
return Slider(
value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions: (((operationalValues.maxValue ?? 0) -
(operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
divisions:
(((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
onChanged: (value) {
context.read<FunctionBloc>().add(
AddFunction(
@ -368,9 +374,7 @@ class ThreeGangSwitchHelper {
style: context.textTheme.bodyMedium,
),
trailing: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected
? ColorsManager.primaryColorWithOpacity
@ -386,8 +390,7 @@ class ThreeGangSwitchHelper {
operationName: operationName,
value: value.value,
condition: selectedFunctionData?.condition,
valueDescription:
selectedFunctionData?.valueDescription,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);

View File

@ -10,6 +10,7 @@ import 'package:syncrow_web/pages/routines/models/gang_switches/base_switch_func
import 'package:syncrow_web/pages/routines/models/gang_switches/switch_operational_value.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -85,15 +86,20 @@ class TwoGangSwitchHelper {
size: 16,
color: ColorsManager.textGray,
),
onTap: () {
context
.read<FunctionBloc>()
.add(SelectFunction(
functionCode: function.code,
operationName:
function.operationName,
));
},
onTap: () =>
RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName:
function.operationName,
functionValueDescription:
selectedFunctionData.valueDescription,
deviceUuid: device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'countdown_1',
'countdown_2',
],
),
);
},
),
@ -167,9 +173,8 @@ class TwoGangSwitchHelper {
required String operationName,
required bool removeComparetors,
}) {
if (selectedFunction == 'countdown_1' ||
selectedFunction == 'countdown_2') {
final initialValue = selectedFunctionData?.value ?? 200;
if (selectedFunction == 'countdown_1' || selectedFunction == 'countdown_2') {
final initialValue = selectedFunctionData?.value ?? 0;
return _buildTemperatureSelector(
context: context,
initialValue: initialValue,
@ -182,8 +187,7 @@ class TwoGangSwitchHelper {
);
}
final selectedFn =
switchFunctions.firstWhere((f) => f.code == selectedFunction);
final selectedFn = switchFunctions.firstWhere((f) => f.code == selectedFunction);
final values = selectedFn.getOperationalValues();
return _buildOperationalValuesList(
@ -250,7 +254,7 @@ class TwoGangSwitchHelper {
functionCode: selectCode,
operationName: operationName,
condition: conditions[index],
value: selectedFunctionData?.value,
value: selectedFunctionData?.value ?? 0,
valueDescription: selectedFunctionData?.valueDescription,
),
),
@ -265,8 +269,7 @@ class TwoGangSwitchHelper {
minHeight: 40.0,
minWidth: 40.0,
),
isSelected:
conditions.map((c) => c == (currentCondition ?? "==")).toList(),
isSelected: conditions.map((c) => c == (currentCondition ?? "==")).toList(),
children: conditions.map((c) => Text(c)).toList(),
);
}
@ -302,22 +305,23 @@ class TwoGangSwitchHelper {
DeviceFunctionData? selectedFunctionData,
String selectCode,
) {
const twelveHoursInSeconds = 43200.0;
final operationalValues = SwitchOperationalValue(
icon: '',
description: "sec",
value: 0.0,
minValue: 0,
maxValue: 86400,
maxValue: twelveHoursInSeconds,
stepValue: 1,
);
return Slider(
value: (initialValue ?? 0).toDouble(),
min: operationalValues.minValue?.toDouble() ?? 0.0,
max: operationalValues.maxValue?.toDouble() ?? 0.0,
divisions: (((operationalValues.maxValue ?? 0) -
(operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
divisions:
(((operationalValues.maxValue ?? 0) - (operationalValues.minValue ?? 0)) /
(operationalValues.stepValue ?? 1))
.round(),
onChanged: (value) {
context.read<FunctionBloc>().add(
AddFunction(
@ -367,9 +371,7 @@ class TwoGangSwitchHelper {
style: context.textTheme.bodyMedium,
),
trailing: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
size: 24,
color: isSelected
? ColorsManager.primaryColorWithOpacity
@ -385,8 +387,7 @@ class TwoGangSwitchHelper {
operationName: operationName,
value: value.value,
condition: selectedFunctionData?.condition,
valueDescription:
selectedFunctionData?.valueDescription,
valueDescription: selectedFunctionData?.valueDescription,
),
),
);

View File

@ -8,6 +8,7 @@ import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/wps/wps_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/wall_sensor/wps_value_selector_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -111,13 +112,23 @@ class _WallPresenceSensorState extends State<WallPresenceSensor> {
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildFunctionList(context),
_buildFunctionList(context, state),
if (state.selectedFunction != null) _buildValueSelector(context, state),
],
);
}
Widget _buildFunctionList(BuildContext context) {
Widget _buildFunctionList(BuildContext context, FunctionBlocState state) {
final selectedFunction = state.selectedFunction;
final selectedFunctionData = state.addedFunctions.firstWhere(
(f) => f.functionCode == selectedFunction,
orElse: () => DeviceFunctionData(
entityId: '',
functionCode: selectedFunction ?? '',
operationName: '',
value: null,
),
);
return SizedBox(
width: 360,
child: ListView.separated(
@ -149,12 +160,18 @@ class _WallPresenceSensorState extends State<WallPresenceSensor> {
size: 16,
color: ColorsManager.textGray,
),
onTap: () => context.read<FunctionBloc>().add(
SelectFunction(
functionCode: function.code,
operationName: function.operationName,
),
),
onTap: () => RoutineTapFunctionHelper.onTapFunction(
context,
functionCode: function.code,
functionOperationName: function.operationName,
functionValueDescription: selectedFunctionData.valueDescription,
deviceUuid: widget.device?.uuid,
codesToAddIntoFunctionsWithDefaultValue: [
'dis_current',
'presence_time',
'illuminance_value',
],
),
);
},
),

View File

@ -36,7 +36,7 @@ class WpsValueSelectorWidget extends StatelessWidget {
dialogType: dialogType,
sliderRange: sliderRange,
displayedValue: getDisplayText,
initialValue: functionData.value ?? 250,
initialValue: functionData.value ?? 0.0,
onConditionChanged: (condition) => context.read<FunctionBloc>().add(
AddFunction(
functionData: DeviceFunctionData(
@ -44,7 +44,7 @@ class WpsValueSelectorWidget extends StatelessWidget {
functionCode: selectedFunction,
operationName: functionData.operationName,
condition: condition,
value: functionData.value,
value: functionData.value ?? 0,
),
),
),
@ -87,7 +87,7 @@ class WpsValueSelectorWidget extends StatelessWidget {
final intValue = int.tryParse('${functionData.value ?? ''}');
return switch (functionData.functionCode) {
'presence_time' => '${intValue ?? '0'}',
'dis_current' => '${intValue ?? '250'}',
'dis_current' => '${intValue ?? '0'}',
'illuminance_value' => '${intValue ?? '0'}',
_ => '$intValue',
};

View File

@ -31,7 +31,7 @@ class CustomExpansionTileSpaceTree extends StatelessWidget {
children: [
Checkbox(
value: isSoldCheck ? null : isSelected,
onChanged: (value) => onItemSelected ?? () {},
onChanged: (value) => onItemSelected?.call(),
tristate: true,
side: WidgetStateBorderSide.resolveWith(
(states) => const BorderSide(color: ColorsManager.grayBorder),

View File

@ -41,14 +41,12 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
@override
Widget build(BuildContext context) {
return BlocBuilder<SpaceTreeBloc, SpaceTreeState>(builder: (context, state) {
final communities = state.searchQuery.isNotEmpty
? state.filteredCommunity
: state.communityList;
final communities =
state.searchQuery.isNotEmpty ? state.filteredCommunity : state.communityList;
return Container(
height: MediaQuery.sizeOf(context).height,
decoration: widget.isSide == true
? subSectionContainerDecoration.copyWith(
color: ColorsManager.whiteColors)
? subSectionContainerDecoration.copyWith(color: ColorsManager.whiteColors)
: const BoxDecoration(color: ColorsManager.whiteColors),
child: state is SpaceTreeLoadingState
? const Center(child: CircularProgressIndicator())
@ -81,12 +79,10 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
style: context.textTheme.bodyMedium?.copyWith(
color: ColorsManager.blackColor,
),
onChanged: (value) =>
context.read<SpaceTreeBloc>().add(
SearchQueryEvent(value),
),
decoration:
textBoxDecoration(radios: 20)?.copyWith(
onChanged: (value) => context.read<SpaceTreeBloc>().add(
SearchQueryEvent(value),
),
decoration: textBoxDecoration(radios: 20)?.copyWith(
fillColor: Colors.white,
suffixIcon: Padding(
padding: const EdgeInsets.only(right: 16),
@ -96,8 +92,7 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
height: 24,
),
),
hintStyle:
context.textTheme.bodyMedium?.copyWith(
hintStyle: context.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w400,
fontSize: 12,
color: ColorsManager.textGray,
@ -121,27 +116,30 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
child: state.isSearching
? const Center(child: CircularProgressIndicator())
: SidebarCommunitiesList(
onScrollToEnd: () => context.read<SpaceTreeBloc>().add(
PaginationEvent(
state.paginationModel,
state.communityList,
),
),
onScrollToEnd: () {
if (!state.paginationIsLoading) {
context.read<SpaceTreeBloc>().add(
PaginationEvent(
state.paginationModel,
state.communityList,
),
);
}
},
scrollController: _scrollController,
communities: communities,
itemBuilder: (context, index) {
return CustomExpansionTileSpaceTree(
title: communities[index].name,
isSelected: state.selectedCommunities
.contains(communities[index].uuid),
isSoldCheck: state.selectedCommunities
.contains(communities[index].uuid),
onExpansionChanged: () =>
context.read<SpaceTreeBloc>().add(
OnCommunityExpanded(
communities[index].uuid,
),
),
isSelected:
state.selectedCommunities.contains(communities[index].uuid),
isSoldCheck:
state.selectedCommunities.contains(communities[index].uuid),
onExpansionChanged: () => context.read<SpaceTreeBloc>().add(
OnCommunityExpanded(
communities[index].uuid,
),
),
isExpanded: state.expandedCommunities.contains(
communities[index].uuid,
),
@ -158,8 +156,7 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
(space) {
return CustomExpansionTileSpaceTree(
title: space.name,
isExpanded:
state.expandedSpaces.contains(space.uuid),
isExpanded: state.expandedSpaces.contains(space.uuid),
onItemSelected: () {
context.read<SpaceTreeBloc>().add(
OnSpaceSelected(
@ -170,18 +167,15 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
);
widget.onSelect();
},
onExpansionChanged: () =>
context.read<SpaceTreeBloc>().add(
OnSpaceExpanded(
communities[index].uuid,
space.uuid ?? '',
),
),
isSelected: state.selectedSpaces
.contains(space.uuid) ||
state.soldCheck.contains(space.uuid),
isSoldCheck:
onExpansionChanged: () => context.read<SpaceTreeBloc>().add(
OnSpaceExpanded(
communities[index].uuid,
space.uuid ?? '',
),
),
isSelected: state.selectedSpaces.contains(space.uuid) ||
state.soldCheck.contains(space.uuid),
isSoldCheck: state.soldCheck.contains(space.uuid),
children: _buildNestedSpaces(
context,
state,
@ -210,8 +204,8 @@ class _SpaceTreeViewState extends State<SpaceTreeView> {
) {
return space.children.map((child) {
return CustomExpansionTileSpaceTree(
isSelected: state.selectedSpaces.contains(child.uuid) ||
state.soldCheck.contains(child.uuid),
isSelected:
state.selectedSpaces.contains(child.uuid) || state.soldCheck.contains(child.uuid),
isSoldCheck: state.soldCheck.contains(child.uuid),
title: child.name,
isExpanded: state.expandedSpaces.contains(child.uuid),

View File

@ -1,4 +1,6 @@
// Flutter imports
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@ -336,6 +338,7 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
}
spaces.add(newSpace);
_updateNodePosition(newSpace, newSpace.position);
realignTree();
});
},
);
@ -450,7 +453,6 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
void _saveSpaces() {
if (widget.selectedCommunity == null) {
debugPrint("No community selected for saving spaces.");
return;
}
@ -530,35 +532,83 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
}
Offset getBalancedChildPosition(SpaceModel parent) {
int totalSiblings = parent.children.length + 1;
double totalWidth = (totalSiblings - 1) * 250; // Horizontal spacing
double startX = parent.position.dx - (totalWidth / 2);
const double nodeWidth = 200;
const double verticalGap = 180;
Offset position = Offset(startX + (parent.children.length * 250), parent.position.dy + 180);
if (parent.children.isEmpty) {
// First child → exactly center
return Offset(parent.position.dx, parent.position.dy + verticalGap);
} else {
// More children → arrange them spaced horizontally
double totalWidth = (parent.children.length) * (nodeWidth + 60);
double startX = parent.position.dx - (totalWidth / 2);
// Check for overlaps & adjust
while (spaces.any((s) => (s.position - position).distance < 250)) {
position = Offset(position.dx + 250, position.dy);
double childX = startX + (parent.children.length * (nodeWidth + 60));
return Offset(childX, parent.position.dy + verticalGap);
}
return position;
}
void realignTree() {
void updatePositions(SpaceModel node, double x, double y) {
node.position = Offset(x, y);
const double nodeWidth = 200;
const double nodeHeight = 100;
const double horizontalGap = 60;
const double verticalGap = 180;
const double rootGap = 400; // extra space between different roots
int numChildren = node.children.length;
double childStartX = x - ((numChildren - 1) * 250) / 2;
double canvasRightEdge = 1000;
double canvasBottomEdge = 1000;
for (int i = 0; i < numChildren; i++) {
updatePositions(node.children[i], childStartX + (i * 250), y + 180);
double calculateSubtreeWidth(SpaceModel node) {
if (node.children.isEmpty) return nodeWidth;
double totalWidth = 0;
for (var child in node.children) {
totalWidth += calculateSubtreeWidth(child) + horizontalGap;
}
return totalWidth - horizontalGap;
}
void layoutSubtree(SpaceModel node, double startX, double y) {
double subtreeWidth = calculateSubtreeWidth(node);
double centerX = startX + subtreeWidth / 2 - nodeWidth / 2;
node.position = Offset(centerX, y);
canvasRightEdge = max(canvasRightEdge, centerX + nodeWidth);
canvasBottomEdge = max(canvasBottomEdge, y + nodeHeight);
if (node.children.length == 1) {
final child = node.children.first;
layoutSubtree(child, centerX, y + verticalGap);
} else {
double childX = startX;
for (var child in node.children) {
double childWidth = calculateSubtreeWidth(child);
layoutSubtree(child, childX, y + verticalGap);
childX += childWidth + horizontalGap;
}
}
}
if (spaces.isNotEmpty) {
updatePositions(spaces.first, spaces.first.position.dx, spaces.first.position.dy);
// ⚡ New: layout each root separately
final List<SpaceModel> roots = spaces
.where((s) =>
s.parent == null &&
s.status != SpaceStatus.deleted &&
s.status != SpaceStatus.parentDeleted)
.toList();
double currentX = 100; // start some margin from left
double currentY = 100; // top margin
for (var root in roots) {
layoutSubtree(root, currentX, currentY);
double rootWidth = calculateSubtreeWidth(root);
currentX += rootWidth + rootGap;
}
setState(() {
canvasWidth = canvasRightEdge + 400;
canvasHeight = canvasBottomEdge + 400;
});
}
void _onDuplicate(BuildContext parentContext) {
@ -642,63 +692,19 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
}
void _duplicateSpace(SpaceModel space) {
final Map<SpaceModel, SpaceModel> originalToDuplicate = {};
double horizontalGap = 250.0; // Increased spacing
double verticalGap = 180.0; // Adjusted for better visualization
final double horizontalGap = 250.0;
final double verticalGap = 180.0;
final double nodeWidth = 200;
final double nodeHeight = 100;
final double breathingSpace = 300.0; // extra gap after original tree
print("🟢 Duplicating: ${space.name}");
/// **Find a new position ensuring no overlap**
Offset getBalancedChildPosition(SpaceModel parent) {
int totalSiblings = parent.children.length + 1;
double totalWidth = (totalSiblings - 1) * horizontalGap;
double startX = parent.position.dx - (totalWidth / 2);
Offset position = Offset(
startX + (parent.children.length * horizontalGap), parent.position.dy + verticalGap);
// **Check for overlaps & adjust**
while (spaces.any((s) => (s.position - position).distance < horizontalGap)) {
position = Offset(position.dx + horizontalGap, position.dy);
}
print("🔹 New position for ${parent.name}: (${position.dx}, ${position.dy})");
return position;
}
/// **Realign the entire tree after duplication**
void realignTree() {
void updatePositions(SpaceModel node, double x, double y) {
node.position = Offset(x, y);
print("✅ Adjusted ${node.name} to (${x}, ${y})");
int numChildren = node.children.length;
double childStartX = x - ((numChildren - 1) * horizontalGap) / 2;
for (int i = 0; i < numChildren; i++) {
updatePositions(node.children[i], childStartX + (i * horizontalGap), y + verticalGap);
}
}
if (spaces.isNotEmpty) {
print("🔄 Realigning tree...");
updatePositions(spaces.first, spaces.first.position.dx, spaces.first.position.dy);
}
}
/// **Recursive duplication logic**
/// Helper to recursively duplicate a node and its children
SpaceModel duplicateRecursive(SpaceModel original, SpaceModel? duplicatedParent) {
Offset newPosition = duplicatedParent == null
? Offset(original.position.dx + horizontalGap, original.position.dy)
: getBalancedChildPosition(duplicatedParent);
final duplicatedName = SpaceHelper.generateUniqueSpaceName(original.name, spaces);
print(
"🟡 Duplicating ${original.name}${duplicatedName} at (${newPosition.dx}, ${newPosition.dy})");
final duplicated = SpaceModel(
name: duplicatedName,
icon: original.icon,
position: newPosition,
position: Offset.zero,
isPrivate: original.isPrivate,
children: [],
status: SpaceStatus.newSpace,
@ -708,28 +714,20 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
tags: original.tags,
);
setState(() {
spaces.add(duplicated);
_updateNodePosition(duplicated, duplicated.position);
spaces.add(duplicated);
if (duplicatedParent != null) {
final newConnection = Connection(
startSpace: duplicatedParent,
endSpace: duplicated,
direction: "down",
);
connections.add(newConnection);
duplicated.incomingConnection = newConnection;
duplicatedParent.addOutgoingConnection(newConnection);
duplicatedParent.children.add(duplicated);
print("🔗 Created connection: ${duplicatedParent.name}${duplicated.name}");
}
if (duplicatedParent != null) {
final newConnection = Connection(
startSpace: duplicatedParent,
endSpace: duplicated,
direction: "down",
);
connections.add(newConnection);
duplicated.incomingConnection = newConnection;
duplicatedParent.addOutgoingConnection(newConnection);
duplicatedParent.children.add(duplicated);
}
// **Recalculate the whole tree to avoid overlaps**
realignTree();
});
// Recursively duplicate children
for (var child in original.children) {
duplicateRecursive(child, duplicated);
}
@ -737,21 +735,49 @@ class _CommunityStructureAreaState extends State<CommunityStructureArea> {
return duplicated;
}
/// **Handle root duplication**
if (space.parent == null) {
print("🟠 Duplicating root node: ${space.name}");
SpaceModel duplicatedRoot = duplicateRecursive(space, null);
/// Layout a subtree rooted at node
void layoutSubtree(SpaceModel node, double startX, double startY) {
double calculateSubtreeWidth(SpaceModel n) {
if (n.children.isEmpty) return nodeWidth;
double width = 0;
for (var child in n.children) {
width += calculateSubtreeWidth(child) + horizontalGap;
}
return width - horizontalGap;
}
setState(() {
spaces.add(duplicatedRoot);
realignTree();
});
void assignPositions(SpaceModel n, double x, double y) {
double subtreeWidth = calculateSubtreeWidth(n);
double centerX = x + subtreeWidth / 2 - nodeWidth / 2;
n.position = Offset(centerX, y);
print("✅ Root duplication successful: ${duplicatedRoot.name}");
} else {
duplicateRecursive(space, space.parent);
if (n.children.length == 1) {
assignPositions(n.children.first, centerX, y + verticalGap);
} else {
double childX = x;
for (var child in n.children) {
double childWidth = calculateSubtreeWidth(child);
assignPositions(child, childX, y + verticalGap);
childX += childWidth + horizontalGap;
}
}
}
double totalSubtreeWidth = calculateSubtreeWidth(node);
assignPositions(node, startX, startY);
}
print("🟢 Finished duplication process for: ${space.name}");
/// Actual duplication process
setState(() {
if (space.parent == null) {
// Duplicating a ROOT node
SpaceModel duplicatedRoot = duplicateRecursive(space, null);
realignTree();
} else {
// Duplicating a CHILD node inside its parent
SpaceModel duplicated = duplicateRecursive(space, space.parent);
realignTree();
}
});
}
}

View File

@ -592,8 +592,6 @@ class CreateSpaceDialogState extends State<CreateSpaceDialog> {
return CreateSubSpaceDialog(
spaceName: name,
dialogTitle: isEdit ? 'Edit Sub-space' : 'Create Sub-space',
spaceTags: spaceTags,
isEdit: isEdit,
products: products,
existingSubSpaces: existingSubSpaces,
onSave: (slectedSubspaces) {

View File

@ -1,8 +1,11 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/common/widgets/empty_search_result_widget.dart';
import 'package:syncrow_web/common/widgets/search_bar.dart';
import 'package:syncrow_web/common/widgets/sidebar_communities_list.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/bloc/space_management_event.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
@ -15,6 +18,8 @@ import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/cent
import 'package:syncrow_web/pages/spaces_management/structure_selector/bloc/center_body_event.dart';
import 'package:syncrow_web/utils/style.dart';
import '../../../space_tree/bloc/space_tree_event.dart';
class SidebarWidget extends StatefulWidget {
final List<CommunityModel> communities;
final String? selectedSpaceUuid;
@ -33,6 +38,7 @@ class SidebarWidget extends StatefulWidget {
class _SidebarWidgetState extends State<SidebarWidget> {
late final ScrollController _scrollController;
Timer? _debounce;
String _searchQuery = '';
String? _selectedSpaceUuid;
@ -40,17 +46,46 @@ class _SidebarWidgetState extends State<SidebarWidget> {
@override
void initState() {
_selectedId = widget.selectedSpaceUuid;
_scrollController = ScrollController();
super.initState();
_scrollController = ScrollController();
_scrollController.addListener(_onScroll);
_selectedId = widget.selectedSpaceUuid;
}
void _onScroll() {
if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) {
// Trigger pagination event
final bloc = context.read<SpaceTreeBloc>();
if (!bloc.state.paginationIsLoading && bloc.state.paginationModel?.hasNext == true) {
bloc.add(
PaginationEvent(
bloc.state.paginationModel!,
bloc.state.communityList,
),
);
}
}
}
@override
void dispose() {
_scrollController.removeListener(_onScroll);
_scrollController.dispose();
_debounce?.cancel();
super.dispose();
}
void _onSearchChanged(String query) {
if (_debounce?.isActive ?? false) _debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 500), () {
setState(() {
_searchQuery = query;
});
context.read<SpaceTreeBloc>().add(SearchQueryEvent(query));
});
}
@override
void didUpdateWidget(covariant SidebarWidget oldWidget) {
if (widget.selectedSpaceUuid != oldWidget.selectedSpaceUuid) {
@ -59,38 +94,6 @@ class _SidebarWidgetState extends State<SidebarWidget> {
super.didUpdateWidget(oldWidget);
}
List<CommunityModel> _filteredCommunities() {
if (_searchQuery.isEmpty) {
_selectedSpaceUuid = null;
return widget.communities;
}
return widget.communities.where((community) {
final containsQueryInCommunity =
community.name.toLowerCase().contains(_searchQuery.toLowerCase());
final containsQueryInSpaces = community.spaces.any((space) =>
_containsQuery(space: space, query: _searchQuery.toLowerCase()));
return containsQueryInCommunity || containsQueryInSpaces;
}).toList();
}
bool _containsQuery({
required SpaceModel space,
required String query,
}) {
final matchesSpace = space.name.toLowerCase().contains(query);
final matchesChildren = space.children.any(
(child) => _containsQuery(space: child, query: query),
);
if (matchesSpace || matchesChildren) {
_selectedSpaceUuid = space.uuid;
}
return matchesSpace || matchesChildren;
}
bool _isSpaceOrChildSelected(SpaceModel space) {
final isSpaceSelected = _selectedSpaceUuid == space.uuid;
final anySubSpaceIsSelected = space.children.any(_isSpaceOrChildSelected);
@ -101,7 +104,10 @@ class _SidebarWidgetState extends State<SidebarWidget> {
@override
Widget build(BuildContext context) {
final filteredCommunities = _filteredCommunities();
final spaceTreeState = context.watch<SpaceTreeBloc>().state;
final filteredCommunities = spaceTreeState.searchQuery.isNotEmpty
? spaceTreeState.filteredCommunity
: spaceTreeState.communityList;
return Container(
width: _width,
@ -112,7 +118,7 @@ class _SidebarWidgetState extends State<SidebarWidget> {
children: [
SidebarHeader(onAddCommunity: _onAddCommunity),
CustomSearchBar(
onSearchChanged: (query) => setState(() => _searchQuery = query),
onSearchChanged: _onSearchChanged,
),
const SizedBox(height: 16),
Expanded(
@ -120,14 +126,23 @@ class _SidebarWidgetState extends State<SidebarWidget> {
visible: filteredCommunities.isNotEmpty,
replacement: const EmptySearchResultWidget(),
child: SidebarCommunitiesList(
scrollController: _scrollController,
onScrollToEnd: () {},
communities: filteredCommunities,
itemBuilder: (context, index) => _buildCommunityTile(
context,
filteredCommunities[index],
),
),
scrollController: _scrollController,
onScrollToEnd: () {},
communities: filteredCommunities,
itemBuilder: (context, index) {
if (index == filteredCommunities.length) {
final spaceTreeState = context.read<SpaceTreeBloc>().state;
if (spaceTreeState.paginationIsLoading) {
return const Padding(
padding: EdgeInsets.all(8.0),
child: Center(child: CircularProgressIndicator()),
);
} else {
return const SizedBox.shrink();
}
}
return _buildCommunityTile(context, filteredCommunities[index]);
}),
),
),
],
@ -136,6 +151,17 @@ class _SidebarWidgetState extends State<SidebarWidget> {
}
Widget _buildCommunityTile(BuildContext context, CommunityModel community) {
final spaces = community.spaces
.where(
(space) =>
{
SpaceStatus.deleted,
SpaceStatus.parentDeleted,
}.contains(space.status) ==
false,
)
.map((space) => _buildSpaceTile(space: space, community: community))
.toList();
return CommunityTile(
title: community.name,
key: ValueKey(community.uuid),
@ -154,15 +180,7 @@ class _SidebarWidgetState extends State<SidebarWidget> {
);
},
onExpansionChanged: (title, expanded) {},
children: community.spaces
.where(
(space) => {
SpaceStatus.deleted,
SpaceStatus.parentDeleted,
}.contains(space.status),
)
.map((space) => _buildSpaceTile(space: space, community: community))
.toList(),
children: spaces,
);
}
@ -202,9 +220,8 @@ class _SidebarWidgetState extends State<SidebarWidget> {
);
}
void _onAddCommunity() => _selectedId?.isNotEmpty ?? true
? _clearSelection()
: _showCreateCommunityDialog();
void _onAddCommunity() =>
_selectedId?.isNotEmpty ?? true ? _clearSelection() : _showCreateCommunityDialog();
void _clearSelection() {
setState(() => _selectedId = '');

View File

@ -4,222 +4,204 @@ import 'package:syncrow_web/pages/common/buttons/cancel_button.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/product_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/tag.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_event.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace/bloc/subspace_state.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
class CreateSubSpaceDialog extends StatelessWidget {
final bool isEdit;
class CreateSubSpaceDialog extends StatefulWidget {
final String dialogTitle;
final List<SubspaceModel>? existingSubSpaces;
final String? spaceName;
final List<Tag>? spaceTags;
final List<ProductModel>? products;
final Function(List<SubspaceModel>?)? onSave;
final void Function(List<SubspaceModel>?)? onSave;
const CreateSubSpaceDialog(
{Key? key,
required this.isEdit,
required this.dialogTitle,
this.existingSubSpaces,
required this.spaceName,
required this.spaceTags,
required this.products,
required this.onSave})
: super(key: key);
const CreateSubSpaceDialog({
required this.dialogTitle,
required this.spaceName,
required this.products,
required this.onSave,
this.existingSubSpaces,
super.key,
});
@override
State<CreateSubSpaceDialog> createState() => _CreateSubSpaceDialogState();
}
class _CreateSubSpaceDialogState extends State<CreateSubSpaceDialog> {
late final TextEditingController _subspaceNameController;
@override
void initState() {
_subspaceNameController = TextEditingController();
super.initState();
}
@override
void dispose() {
_subspaceNameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
final textController = TextEditingController();
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
child: BlocProvider(
create: (_) {
final bloc = SubSpaceBloc();
if (existingSubSpaces != null) {
for (var subSpace in existingSubSpaces!) {
bloc.add(AddSubSpace(subSpace));
}
return BlocProvider(
create: (_) {
final bloc = SubSpaceBloc();
if (widget.existingSubSpaces != null) {
for (final subSpace in widget.existingSubSpaces ?? []) {
bloc.add(AddSubSpace(subSpace));
}
return bloc;
},
}
return bloc;
},
child: Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
child: BlocBuilder<SubSpaceBloc, SubSpaceState>(
builder: (context, state) {
return Container(
color: ColorsManager.whiteColors,
child: SizedBox(
width: screenWidth * 0.35,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
width: context.screenWidth * 0.35,
color: ColorsManager.whiteColors,
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
widget.dialogTitle,
style: context.textTheme.headlineLarge?.copyWith(
color: ColorsManager.blackColor,
),
),
const SizedBox(height: 16),
Container(
width: context.screenWidth * 0.35,
padding: const EdgeInsets.symmetric(
vertical: 10,
horizontal: 16,
),
decoration: BoxDecoration(
color: ColorsManager.boxColor,
borderRadius: BorderRadius.circular(10),
),
child: Wrap(
spacing: 8,
runSpacing: 8,
alignment: WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
dialogTitle,
style: Theme.of(context)
.textTheme
.headlineLarge
?.copyWith(color: ColorsManager.blackColor),
...state.subSpaces.asMap().entries.map(
(entry) {
final index = entry.key;
final subSpace = entry.value;
final lowerName = subSpace.subspaceName.toLowerCase();
final duplicateIndices = state.subSpaces
.asMap()
.entries
.where((e) =>
e.value.subspaceName.toLowerCase() == lowerName)
.map((e) => e.key)
.toList();
final isDuplicate = duplicateIndices.length > 1 &&
duplicateIndices.indexOf(index) != 0;
return SubspaceChip(
subSpace: SubspaceTemplateModel(
subspaceName: entry.value.subspaceName,
disabled: entry.value.disabled,
),
isDuplicate: isDuplicate,
onDeleted: () => context.read<SubSpaceBloc>().add(
RemoveSubSpace(subSpace),
),
);
},
),
const SizedBox(height: 16),
Container(
width: screenWidth * 0.35,
padding: const EdgeInsets.symmetric(
vertical: 10.0, horizontal: 16.0),
decoration: BoxDecoration(
color: ColorsManager.boxColor,
borderRadius: BorderRadius.circular(10),
),
child: Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
...state.subSpaces.asMap().entries.map(
(entry) {
final index = entry.key;
final subSpace = entry.value;
final lowerName =
subSpace.subspaceName.toLowerCase();
final duplicateIndices = state.subSpaces
.asMap()
.entries
.where((e) =>
e.value.subspaceName.toLowerCase() ==
lowerName)
.map((e) => e.key)
.toList();
final isDuplicate =
duplicateIndices.length > 1 &&
duplicateIndices.indexOf(index) != 0;
return Chip(
label: Text(subSpace.subspaceName,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color:
ColorsManager.spaceColor)),
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
side: BorderSide(
color: isDuplicate
? ColorsManager.red
: ColorsManager.transparentColor,
width: 0,
),
),
deleteIcon: Container(
width: 24,
height: 24,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: ColorsManager.lightGrayColor,
width: 1.5,
SizedBox(
width: 200,
child: TextField(
controller: _subspaceNameController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: state.subSpaces.isEmpty
? 'Please enter the name'
: null,
hintStyle: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.lightGrayColor,
),
),
onSubmitted: (value) {
final trimmedValue = value.trim();
if (trimmedValue.isNotEmpty) {
context.read<SubSpaceBloc>().add(
AddSubSpace(
SubspaceModel(
subspaceName: trimmedValue,
disabled: false,
),
),
child: const Icon(
Icons.close,
size: 16,
color: ColorsManager.lightGrayColor,
),
),
onDeleted: () => context
.read<SubSpaceBloc>()
.add(RemoveSubSpace(subSpace)),
);
},
),
SizedBox(
width: 200,
child: TextField(
controller: textController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: state.subSpaces.isEmpty
? 'Please enter the name'
: null,
hintStyle: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: ColorsManager
.lightGrayColor)),
onSubmitted: (value) {
if (value.trim().isNotEmpty) {
context.read<SubSpaceBloc>().add(
AddSubSpace(SubspaceModel(
subspaceName: value.trim(),
disabled: false)));
textController.clear();
}
},
style:
Theme.of(context).textTheme.bodyMedium),
),
],
);
_subspaceNameController.clear();
}
},
style: context.textTheme.bodyMedium,
),
),
if (state.errorMessage.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(state.errorMessage,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: ColorsManager.warningRed,
)),
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: CancelButton(
label: 'Cancel',
onPressed: () async {
Navigator.of(context).pop();
},
),
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
onPressed: (state.errorMessage.isNotEmpty)
? null
: () async {
final subSpaces = context
.read<SubSpaceBloc>()
.state
.subSpaces;
onSave!(subSpaces);
Navigator.of(context).pop();
},
backgroundColor: ColorsManager.secondaryColor,
borderRadius: 10,
foregroundColor: state.errorMessage.isNotEmpty
? ColorsManager.whiteColorsWithOpacity
: ColorsManager.whiteColors,
child: const Text('OK'),
),
),
],
),
],
),
),
));
if (state.errorMessage.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
state.errorMessage,
style: context.textTheme.bodySmall?.copyWith(
color: ColorsManager.warningRed,
),
),
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: CancelButton(
label: 'Cancel',
onPressed: () async {
Navigator.of(context).pop();
},
),
),
const SizedBox(width: 10),
Expanded(
child: DefaultButton(
onPressed: state.errorMessage.isEmpty
? () {
final subSpacesBloc = context.read<SubSpaceBloc>();
final subSpaces = subSpacesBloc.state.subSpaces;
widget.onSave?.call(subSpaces);
Navigator.of(context).pop();
}
: null,
backgroundColor: ColorsManager.secondaryColor,
borderRadius: 10,
foregroundColor: state.errorMessage.isNotEmpty
? ColorsManager.whiteColorsWithOpacity
: ColorsManager.whiteColors,
child: const Text('OK'),
),
),
],
),
],
),
);
},
),
),

View File

@ -1,4 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/widgets/subspace_chip.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/widgets/subspaces_textfield.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
@ -51,6 +54,9 @@ class CreateSubspaceModelChipsBox extends StatelessWidget {
return SubspaceChip(
subSpace: subSpace,
isDuplicate: isDuplicate,
onDeleted: () => context.read<SubSpaceModelBloc>().add(
RemoveSubSpaceModel(subSpace),
),
);
},
),

View File

@ -1,7 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
@ -11,10 +8,12 @@ class SubspaceChip extends StatelessWidget {
required this.subSpace,
required this.isDuplicate,
super.key,
required this.onDeleted,
});
final SubspaceTemplateModel subSpace;
final bool isDuplicate;
final void Function() onDeleted;
@override
Widget build(BuildContext context) {
@ -50,9 +49,7 @@ class SubspaceChip extends StatelessWidget {
),
),
),
onDeleted: () => context.read<SubSpaceModelBloc>().add(
RemoveSubSpaceModel(subSpace),
),
onDeleted: onDeleted,
);
}
}

View File

@ -145,13 +145,11 @@ class CreateSpaceModelDialog extends StatelessWidget {
),
const SizedBox(height: 10),
TagChipDisplay(
context,
screenWidth: screenWidth,
spaceModel: updatedSpaceModel,
products: products,
subspaces: subspaces,
allTags: allTags,
spaceNameController: spaceNameController,
spaceName: spaceNameController.text,
pageContext: pageContext,
otherSpaceModels: otherSpaceModels,
allSpaceModels: allSpaceModels,

View File

@ -10,139 +10,152 @@ import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_
import 'package:syncrow_web/pages/spaces_management/space_model/widgets/button_content_widget.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/views/add_device_type_model_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
class TagChipDisplay extends StatelessWidget {
final double screenWidth;
const TagChipDisplay({
required this.spaceModel,
required this.products,
required this.subspaces,
required this.allTags,
required this.spaceName,
required this.projectTags,
this.pageContext,
this.otherSpaceModels,
this.allSpaceModels,
super.key,
});
final SpaceTemplateModel? spaceModel;
final List<ProductModel>? products;
final List<SubspaceTemplateModel>? subspaces;
final List<String>? allTags;
final TextEditingController spaceNameController;
final String spaceName;
final BuildContext? pageContext;
final List<String>? otherSpaceModels;
final List<SpaceTemplateModel>? allSpaceModels;
final List<Tag> projectTags;
const TagChipDisplay(BuildContext context,
{Key? key,
required this.screenWidth,
required this.spaceModel,
required this.products,
required this.subspaces,
required this.allTags,
required this.spaceNameController,
this.pageContext,
this.otherSpaceModels,
this.allSpaceModels,
required this.projectTags})
: super(key: key);
Map<ProductModel, int> get _groupedTags {
final spaceTags = spaceModel?.tags ?? <Tag>[];
final subspaces = spaceModel?.subspaceModels ?? [];
final subspaceTags = subspaces.expand((e) => e.tags ?? <Tag>[]).toList();
return TagHelper.groupTags([...spaceTags, ...subspaceTags]);
}
@override
Widget build(BuildContext context) {
return (spaceModel?.tags?.isNotEmpty == true ||
spaceModel?.subspaceModels?.any((subspace) => subspace.tags?.isNotEmpty == true) ==
true)
? SizedBox(
width: screenWidth * 0.25,
child: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: ColorsManager.textFieldGreyColor,
width: 3.0, // Border width
),
),
child: Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
// Combine tags from spaceModel and subspaces
...TagHelper.groupTags([
...?spaceModel?.tags,
...?spaceModel?.subspaceModels?.expand((subspace) => subspace.tags ?? [])
]).entries.map(
(entry) => Chip(
avatar: SizedBox(
width: 24,
height: 24,
child: SvgPicture.asset(
entry.key.icon ?? 'assets/icons/gateway.svg',
fit: BoxFit.contain,
),
),
label: Text(
'x${entry.value}', // Show count
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: ColorsManager.spaceColor),
),
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(
color: ColorsManager.spaceColor,
),
),
),
),
EditChip(onTap: () async {
// Use the Navigator's context for showDialog
Navigator.of(context).pop();
final hasTags = spaceModel?.tags?.isNotEmpty ?? false;
final hasSubspaceTags =
spaceModel?.subspaceModels?.any((e) => e.tags?.isNotEmpty ?? false) ?? false;
await showDialog<bool>(
barrierDismissible: false,
context: context,
builder: (context) => AssignTagModelsDialog(
products: products,
allSpaceModels: allSpaceModels,
subspaces: subspaces,
pageContext: pageContext,
allTags: allTags,
spaceModel: spaceModel,
otherSpaceModels: otherSpaceModels,
initialTags: TagHelper.generateInitialTags(
subspaces: subspaces, spaceTagModels: spaceModel?.tags ?? []),
title: 'Edit Device',
addedProducts: TagHelper.createInitialSelectedProducts(
spaceModel?.tags ?? [], subspaces),
spaceName: spaceModel?.modelName ?? '',
projectTags: projectTags,
));
})
],
),
),
)
: TextButton(
onPressed: () async {
Navigator.of(context).pop();
if (hasTags || hasSubspaceTags) {
return Container(
width: context.screenWidth * 0.25,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: ColorsManager.textFieldGreyColor,
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: ColorsManager.textFieldGreyColor,
width: 3,
),
),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
..._groupedTags.entries.map((entry) => _buildChip(context, entry)),
_buildEditChip(context),
],
),
);
}
await showDialog<bool>(
barrierDismissible: false,
context: context,
builder: (context) => AddDeviceTypeModelWidget(
products: products,
subspaces: subspaces,
allTags: allTags,
spaceName: spaceNameController.text,
pageContext: pageContext,
isCreate: true,
spaceModel: spaceModel,
otherSpaceModels: otherSpaceModels,
projectTags: projectTags,
),
);
},
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
),
child: const ButtonContentWidget(
icon: Icons.add,
label: 'Add Devices',
),
);
return _buildAddDevicesButton(context);
}
Widget _buildEditChip(BuildContext context) {
return EditChip(
onTap: () => showDialog<void>(
context: context,
builder: (context) => AssignTagModelsDialog(
products: products,
allSpaceModels: allSpaceModels,
subspaces: subspaces,
pageContext: pageContext,
allTags: allTags,
spaceModel: spaceModel,
otherSpaceModels: otherSpaceModels,
initialTags: TagHelper.generateInitialTags(
subspaces: subspaces,
spaceTagModels: spaceModel?.tags ?? [],
),
title: 'Edit Device',
addedProducts: TagHelper.createInitialSelectedProducts(
spaceModel?.tags ?? [],
subspaces,
),
spaceName: spaceModel?.modelName ?? '',
projectTags: projectTags,
),
),
);
}
Widget _buildChip(
BuildContext context,
MapEntry<ProductModel, int> entry,
) {
return Chip(
backgroundColor: ColorsManager.whiteColors,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: const BorderSide(
color: ColorsManager.spaceColor,
),
),
avatar: SvgPicture.asset(
entry.key.icon ?? Assets.gateway,
fit: BoxFit.contain,
height: 24,
width: 24,
),
label: Text(
'${entry.value}',
style: context.textTheme.bodySmall!.copyWith(
color: ColorsManager.spaceColor,
),
),
);
}
Widget _buildAddDevicesButton(BuildContext context) {
return TextButton(
onPressed: () => showDialog<void>(
context: context,
builder: (context) => AddDeviceTypeModelWidget(
products: products,
subspaces: subspaces,
allTags: allTags,
spaceName: spaceName,
pageContext: pageContext,
isCreate: true,
spaceModel: spaceModel,
otherSpaceModels: otherSpaceModels,
projectTags: projectTags,
),
),
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
),
child: const ButtonContentWidget(
icon: Icons.add,
label: 'Add Devices',
),
);
}
}

View File

@ -0,0 +1,85 @@
import 'dart:developer';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';
abstract interface class BatchControlDevicesService {
Future<bool> batchControlDevices({
required List<String> uuids,
required String code,
required Object value,
});
}
final class RemoteBatchControlDevicesService implements BatchControlDevicesService {
@override
Future<bool> batchControlDevices({
required List<String> uuids,
required String code,
required Object value,
}) async {
try {
final body = {
'devicesUuid': uuids,
'code': code,
'value': value,
'operationType': 'COMMAND',
};
final response = await HTTPService().post(
path: ApiEndpoints.deviceBatchControl,
body: body,
showServerMessage: true,
expectedResponseModel: (json) => (json['success'] as bool?) ?? false,
);
return response;
} catch (e) {
log('Error fetching $e', name: 'BatchControlDevicesService');
return false;
}
}
}
final class DebouncedBatchControlDevicesService
implements BatchControlDevicesService {
final BatchControlDevicesService decoratee;
final Duration debounceDuration;
final _pendingRequests = <(List<String> uuids, String code, Object value)>[];
var _isProcessing = false;
DebouncedBatchControlDevicesService({
required this.decoratee,
this.debounceDuration = const Duration(milliseconds: 800),
});
@override
Future<bool> batchControlDevices({
required List<String> uuids,
required String code,
required Object value,
}) async {
_pendingRequests.add((uuids, code, value));
if (_isProcessing) return false;
_isProcessing = true;
await Future.delayed(debounceDuration);
final lastRequest = _pendingRequests.last;
_pendingRequests.clear();
try {
final (lastRequestUuids, lastRequestCode, lastRequestValue) = lastRequest;
return decoratee.batchControlDevices(
uuids: lastRequestUuids,
code: lastRequestCode,
value: lastRequestValue,
);
} finally {
_isProcessing = false;
}
}
}

View File

@ -0,0 +1,75 @@
import 'dart:developer';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/services/api/http_service.dart';
import 'package:syncrow_web/utils/constants/api_const.dart';
abstract interface class ControlDeviceService {
Future<bool> controlDevice({
required String deviceUuid,
required Status status,
});
}
final class RemoteControlDeviceService implements ControlDeviceService {
@override
Future<bool> controlDevice({
required String deviceUuid,
required Status status,
}) async {
try {
final response = await HTTPService().post(
path: ApiEndpoints.deviceControl.replaceAll('{uuid}', deviceUuid),
body: status.toMap(),
showServerMessage: true,
expectedResponseModel: (json) {
return (json['success'] as bool?) ?? false;
},
);
return response;
} catch (e) {
log('Error fetching $e', name: 'ControlDeviceService');
return false;
}
}
}
final class DebouncedControlDeviceService implements ControlDeviceService {
final ControlDeviceService decoratee;
final Duration debounceDuration;
DebouncedControlDeviceService({
required this.decoratee,
this.debounceDuration = const Duration(milliseconds: 800),
});
final _pendingRequests = <(String deviceUuid, Status status)>[];
var _isProcessing = false;
@override
Future<bool> controlDevice({
required String deviceUuid,
required Status status,
}) async {
_pendingRequests.add((deviceUuid, status));
if (_isProcessing) return false;
_isProcessing = true;
await Future.delayed(debounceDuration);
final lastRequest = _pendingRequests.last;
_pendingRequests.clear();
try {
final (lastRequestDeviceUuid, lastRequestStatus) = lastRequest;
return decoratee.controlDevice(
deviceUuid: lastRequestDeviceUuid,
status: lastRequestStatus,
);
} finally {
_isProcessing = false;
}
}
}

View File

@ -321,13 +321,14 @@ class DevicesManagementApi {
Future<bool> factoryReset(FactoryResetModel factoryReset, String uuid) async {
try {
final response = await HTTPService().post(
path: ApiEndpoints.factoryReset.replaceAll('{deviceUuid}', uuid),
path: ApiEndpoints.factoryReset,
body: factoryReset.toMap(),
showServerMessage: true,
expectedResponseModel: (json) {
return json['success'] ?? false;
},
);
return response;
} catch (e) {
debugPrint('Error fetching $e');

View File

@ -60,6 +60,7 @@ dependencies:
firebase_core: ^3.11.0
firebase_crashlytics: ^4.3.2
firebase_database: ^11.3.2
bloc: ^8.1.4
dev_dependencies: