diff --git a/.gitignore b/.gitignore index 9b7914c2..84b7abbc 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,3 @@ login-frontend/.env # macOS system files .DS_Store **/.DS_Store - -# App version config (environment-specific) -server/modules/app_version/config/appVersion.json diff --git a/frontend2/android/build/reports/problems/problems-report.html b/frontend2/android/build/reports/problems/problems-report.html new file mode 100644 index 00000000..6fdb9cae --- /dev/null +++ b/frontend2/android/build/reports/problems/problems-report.html @@ -0,0 +1,663 @@ + + + + + + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/frontend2/ios/Podfile.lock b/frontend2/ios/Podfile.lock index f4250342..7d21a7b0 100644 --- a/frontend2/ios/Podfile.lock +++ b/frontend2/ios/Podfile.lock @@ -206,9 +206,6 @@ PODS: - nanopb/encode (3.30910.0) - package_info_plus (0.4.5): - Flutter - - path_provider_foundation (0.0.1): - - Flutter - - FlutterMacOS - permission_handler_apple (9.3.0): - Flutter - PromisesObjC (2.4.0) @@ -245,7 +242,6 @@ DEPENDENCIES: - image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`) - mobile_scanner (from `.symlinks/plugins/mobile_scanner/darwin`) - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) - - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`) - permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`) - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) - sign_in_with_apple (from `.symlinks/plugins/sign_in_with_apple/ios`) @@ -312,8 +308,6 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/mobile_scanner/darwin" package_info_plus: :path: ".symlinks/plugins/package_info_plus/ios" - path_provider_foundation: - :path: ".symlinks/plugins/path_provider_foundation/darwin" permission_handler_apple: :path: ".symlinks/plugins/permission_handler_apple/ios" shared_preferences_foundation: @@ -363,7 +357,6 @@ SPEC CHECKSUMS: mobile_scanner: 9157936403f5a0644ca3779a38ff8404c5434a93 nanopb: fad817b59e0457d11a5dfbde799381cd727c1275 package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499 - path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880 permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 RecaptchaInterop: 11e0b637842dfb48308d242afc3f448062325aba @@ -372,7 +365,7 @@ SPEC CHECKSUMS: shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb sign_in_with_apple: c5dcc141574c8c54d5ac99dd2163c0c72ad22418 url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b - vibration: 69774ad57825b11c951ee4c46155f455d7a592ce + vibration: ca8104a8875b9c493e15b21b04e456befd0ff6eb PODFILE CHECKSUM: 97ddcef73896d7539563c5353be8805e465f2983 diff --git a/frontend2/lib/apis/room_cleaning/room_cleaning_api.dart b/frontend2/lib/apis/room_cleaning/room_cleaning_api.dart new file mode 100644 index 00000000..b69a662f --- /dev/null +++ b/frontend2/lib/apis/room_cleaning/room_cleaning_api.dart @@ -0,0 +1,290 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../constants/endpoint.dart'; + +class RoomCleaningSlotAvailability { + final String slot; + final String timeRange; + final int primaryCapacity; + final int bufferCapacity; + final int slotsLeft; + final int bufferSlotsLeft; + + RoomCleaningSlotAvailability({ + required this.slot, + required this.timeRange, + required this.primaryCapacity, + required this.bufferCapacity, + required this.slotsLeft, + required this.bufferSlotsLeft, + }); + + factory RoomCleaningSlotAvailability.fromJson(Map json) { + return RoomCleaningSlotAvailability( + slot: json['slot']?.toString() ?? '', + timeRange: json['timeRange']?.toString() ?? '', + primaryCapacity: (json['primaryCapacity'] as num?)?.toInt() ?? 0, + bufferCapacity: (json['bufferCapacity'] as num?)?.toInt() ?? 0, + slotsLeft: (json['slotsLeft'] as num?)?.toInt() ?? 0, + bufferSlotsLeft: (json['bufferSlotsLeft'] as num?)?.toInt() ?? 0, + ); + } +} + +class RoomCleaningDayAvailability { + final DateTime date; + final DateTime openTime; + final DateTime closeTime; + final List slots; + + RoomCleaningDayAvailability({ + required this.date, + required this.openTime, + required this.closeTime, + required this.slots, + }); + + factory RoomCleaningDayAvailability.fromJson(Map json) { + final slotsJson = (json['slots'] as List? ?? []); + // `date` from backend is a calendar date in IST; treat it as date-only. + final rawDate = json['date'] as String; + final dateOnly = rawDate.length >= 10 ? rawDate.substring(0, 10) : rawDate; + final parsedParts = dateOnly.split('-'); + final year = int.parse(parsedParts[0]); + final month = int.parse(parsedParts[1]); + final day = int.parse(parsedParts[2]); + + return RoomCleaningDayAvailability( + date: DateTime(year, month, day), + openTime: DateTime.parse(json['openTime'] as String), + closeTime: DateTime.parse(json['closeTime'] as String), + slots: slotsJson + .map((e) => RoomCleaningSlotAvailability.fromJson( + e as Map, + )) + .toList(), + ); + } +} + +class RoomCleaningAvailability { + final bool canBook; + final String hostelId; + final String? hostelName; + final DateTime now; + final List days; + + RoomCleaningAvailability({ + required this.canBook, + required this.hostelId, + required this.hostelName, + required this.now, + required this.days, + }); + + factory RoomCleaningAvailability.fromJson(Map json) { + final daysJson = (json['days'] as List? ?? []); + return RoomCleaningAvailability( + canBook: json['canBook'] == true, + hostelId: json['hostelId']?.toString() ?? '', + hostelName: json['hostelName']?.toString(), + now: DateTime.parse(json['now'] as String), + days: daysJson + .map((e) => RoomCleaningDayAvailability.fromJson( + e as Map, + )) + .toList(), + ); + } +} + +class RoomCleaningBooking { + final String id; + final DateTime bookingDate; + final String slot; + final String status; + final String? feedbackId; + final String? reason; + /// True when cancel is allowed (Booked/Buffered, future date, window open). + final bool canCancel; + + RoomCleaningBooking({ + required this.id, + required this.bookingDate, + required this.slot, + required this.status, + required this.feedbackId, + required this.reason, + required this.canCancel, + }); + + factory RoomCleaningBooking.fromJson(Map json) { + // Backend stores bookingDate as IST start-of-day in UTC (e.g. 2026-03-12T18:30:00Z == 13 Mar IST). + // Convert to an IST calendar date so the UI doesn't shift based on device timezone. + final rawBookingDate = json['bookingDate'] as String; + final parsed = DateTime.parse(rawBookingDate); + final ist = parsed.toUtc().add(const Duration(hours: 5, minutes: 30)); + final istDateOnly = DateTime(ist.year, ist.month, ist.day); + return RoomCleaningBooking( + id: json['_id']?.toString() ?? '', + bookingDate: istDateOnly, + slot: json['slot']?.toString() ?? '', + status: json['status']?.toString() ?? '', + feedbackId: json['feedbackId']?.toString(), + reason: json['reason']?.toString(), + canCancel: json['canCancel'] == true, + ); + } +} + +class RoomCleaningApi { + Future _getToken() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getString('access_token'); + } + + Future fetchAvailability() async { + final token = await _getToken(); + + final response = await http.get( + Uri.parse('$baseUrl/room-cleaning/availability'), + headers: { + 'Authorization': 'Bearer $token', + 'Content-Type': 'application/json', + }, + ); + + if (response.statusCode >= 200 && response.statusCode < 300) { + final data = json.decode(response.body) as Map; + return RoomCleaningAvailability.fromJson(data); + } else { + throw Exception( + 'Failed to fetch room cleaning availability (${response.statusCode})', + ); + } + } + + Future> bookSlot({ + required DateTime date, + required String slot, + }) async { + final token = await _getToken(); + + final response = await http.post( + Uri.parse('$baseUrl/room-cleaning/booking'), + headers: { + 'Authorization': 'Bearer $token', + 'Content-Type': 'application/json', + }, + body: json.encode({ + 'date': date.toIso8601String().split('T').first, + 'slot': slot, + }), + ); + + final body = response.body.isNotEmpty + ? json.decode(response.body) as Map + : {}; + + if (response.statusCode >= 200 && response.statusCode < 300) { + return body; + } else { + final msg = body['message']?.toString() ?? + 'Failed to create room cleaning booking'; + throw Exception(msg); + } + } + + Future> cancelBooking(String bookingId) async { + final token = await _getToken(); + + final response = await http.post( + Uri.parse('$baseUrl/room-cleaning/booking/cancel'), + headers: { + 'Authorization': 'Bearer $token', + 'Content-Type': 'application/json', + }, + body: json.encode({'bookingId': bookingId}), + ); + + final body = response.body.isNotEmpty + ? json.decode(response.body) as Map + : {}; + + if (response.statusCode >= 200 && response.statusCode < 300) { + return body; + } else { + final msg = body['message']?.toString() ?? + 'Failed to cancel room cleaning booking'; + throw Exception(msg); + } + } + + Future> getMyBookings() async { + final token = await _getToken(); + + final response = await http.get( + Uri.parse('$baseUrl/room-cleaning/booking/my'), + headers: { + 'Authorization': 'Bearer $token', + 'Content-Type': 'application/json', + }, + ); + + if (response.statusCode >= 200 && response.statusCode < 300) { + final data = json.decode(response.body) as Map; + final list = (data['bookings'] as List? ?? []); + return list + .map((e) => RoomCleaningBooking.fromJson( + e as Map, + )) + .toList(); + } else { + throw Exception( + 'Failed to fetch room cleaning bookings (${response.statusCode})', + ); + } + } + + Future> submitFeedback({ + required String bookingId, + required String reachedInSlot, + required String staffPoliteness, + required int satisfaction, + String? remarks, + }) async { + final token = await _getToken(); + + final response = await http.post( + Uri.parse('$baseUrl/room-cleaning/booking/feedback'), + headers: { + 'Authorization': 'Bearer $token', + 'Content-Type': 'application/json', + }, + body: json.encode({ + 'bookingId': bookingId, + 'reachedInSlot': reachedInSlot, + 'staffPoliteness': staffPoliteness, + 'satisfaction': satisfaction, + if (remarks != null && remarks.trim().isNotEmpty) + 'remarks': remarks.trim(), + }), + ); + + final body = response.body.isNotEmpty + ? json.decode(response.body) as Map + : {}; + + if (response.statusCode >= 200 && response.statusCode < 300) { + return body; + } else { + final msg = body['message']?.toString() ?? + 'Failed to submit room cleaning feedback'; + throw Exception(msg); + } + } +} + diff --git a/frontend2/lib/apis/users/user.dart b/frontend2/lib/apis/users/user.dart index 211dd019..8b6d76f5 100644 --- a/frontend2/lib/apis/users/user.dart +++ b/frontend2/lib/apis/users/user.dart @@ -143,9 +143,18 @@ Future?> fetchUserDetails() async { /// Fetch the user's profile picture (base64) from the backend and persist it in SharedPreferences /// Backend endpoint should return JSON like { "base64": "..." } or { "base64": "" } on failure/no-image Future fetchUserProfilePicture() async { - final header = await getAccessToken(); final prefs = await SharedPreferences.getInstance(); + // If we already have a cached profile picture, use it and skip the network call. + // This keeps app startup and navigation snappy; the cache is updated explicitly + // after successful uploads or when this function is forced to run before cache exists. + final cached = prefs.getString('profilePicture') ?? ''; + if (cached.isNotEmpty) { + return; + } + + final header = await getAccessToken(); + if (header == 'error') { // Not authenticated — clear any cached picture await prefs.setString('profilePicture', ''); diff --git a/frontend2/lib/constants/endpoint.dart b/frontend2/lib/constants/endpoint.dart index 26f23f62..54bd9085 100644 --- a/frontend2/lib/constants/endpoint.dart +++ b/frontend2/lib/constants/endpoint.dart @@ -61,3 +61,11 @@ class AppVersionEndpoints { static const String getAndroidVersion = "$baseUrl/app-version/android"; static const String getIosVersion = "$baseUrl/app-version/ios"; } + +class GalaEndpoints { + static const String upcoming = "$baseUrl/gala/upcoming"; + static String upcomingWithMenus(String hostelId) => + "$baseUrl/gala/upcoming-with-menus/$hostelId"; + static const String scanStatus = "$baseUrl/gala/scan-status"; + static const String scan = "$baseUrl/gala/scan"; +} diff --git a/frontend2/lib/main.dart b/frontend2/lib/main.dart index 64e27d18..ea3db07d 100644 --- a/frontend2/lib/main.dart +++ b/frontend2/lib/main.dart @@ -1,17 +1,13 @@ -import 'dart:io'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:firebase_core/firebase_core.dart'; -import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; -import 'package:frontend2/apis/authentication/login.dart'; -import 'package:frontend2/apis/mess/user_mess_info.dart'; -import 'package:frontend2/apis/users/user.dart'; +import 'package:frontend2/apis/authentication/login.dart' as auth; import 'package:frontend2/providers/feedback_provider.dart'; -import 'package:frontend2/providers/hostels.dart'; -import 'package:frontend2/screens/main_navigation_screen.dart'; +import 'package:frontend2/providers/room_cleaning_provider.dart'; import 'package:frontend2/screens/initial_setup_screen.dart'; +import 'package:frontend2/screens/main_navigation_screen.dart'; import 'package:frontend2/screens/login_screen.dart'; import 'package:frontend2/screens/mess_screen.dart'; import 'package:frontend2/utilities/notifications.dart'; @@ -21,57 +17,22 @@ import 'package:provider/provider.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); - - // Check device type and app version on startup - await VersionChecker.init(); - - // Check if update is required - final bool updateRequired = await VersionChecker.checkForUpdate(); - - final bool asLoggedIn = await isLoggedIn(); await Firebase.initializeApp(); - // initialize listeners & local notifications - //await listenNotifications(); - - // On iOS, wait a bit for AppDelegate to initialize and register for remote notifications - if (Platform.isIOS) { - await Future.delayed(const Duration(milliseconds: 1500)); - } - - // register token with backend (will also attach the refresh listener) - await registerFcmToken(); - - // Initialize Firebase Analytics - await FirebaseAnalytics.instance.setAnalyticsCollectionEnabled(true); - - HostelsNotifier.init(); - // Ensure prefs have latest isSetupDone from server before initializing provider - if (asLoggedIn) { - try { - await fetchUserDetails(); - // After fetching user metadata, fetch the profile picture bytes (base64) - // from the backend and cache it in SharedPreferences. - try { - await fetchUserProfilePicture(); - } catch (_) { - // ignore failures here; provider/init or UI will fallback to default - } - } catch (_) {} - } - ProfilePictureProvider.init(); - - await getUserMessInfo(); - - // NotificationNotifier.init(); // No longer needed - handled by listenNotifications() + // Phase 1: run while native splash is visible (single logo screen) + await VersionChecker.init(); + final updateRequired = await VersionChecker.checkForUpdate(); + final isLoggedIn = await auth.isLoggedIn(); + await ProfilePictureProvider.init(); runApp( MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => MessInfoProvider()), ChangeNotifierProvider(create: (_) => FeedbackProvider()), + ChangeNotifierProvider(create: (_) => RoomCleaningProvider()), ], - child: MyApp(isLoggedIn: asLoggedIn, updateRequired: updateRequired), + child: MyApp(isLoggedIn: isLoggedIn, updateRequired: updateRequired), ), ); } @@ -82,8 +43,11 @@ class MyApp extends StatefulWidget { final bool isLoggedIn; final bool updateRequired; - const MyApp( - {super.key, required this.isLoggedIn, required this.updateRequired}); + const MyApp({ + super.key, + required this.isLoggedIn, + required this.updateRequired, + }); @override State createState() => _MyAppState(); @@ -97,21 +61,8 @@ class _MyAppState extends State { @override void initState() { super.initState(); - - isLoggedIn().then((asLoggedIn) => {if (asLoggedIn) registerFcmToken()}); listenNotifications(); setNavigatorKey(navigatorKey); // Set global navigator key for notifications - - WidgetsBinding.instance.addPostFrameCallback((_) async { - // Show update dialog if required - if (widget.updateRequired) { - return; // Don't proceed with other initialization if update is required - } - - // This ensures it runs after the first frame - await context.read().fetchMessID(); - }); - _connectivity = Connectivity(); // Use `.map()` to transform the stream into a stream of ConnectivityResult @@ -163,14 +114,11 @@ class _MyAppState extends State { return MaterialApp( debugShowCheckedModeBanner: false, navigatorKey: navigatorKey, - home: widget.updateRequired ? const UpdateRequiredScreen() : (widget.isLoggedIn ? const MainNavigationScreen() : const LoginScreen()), - - //home: ProfileScreen(), builder: EasyLoading.init(), routes: { '/home': (context) => const MainNavigationScreen(), diff --git a/frontend2/lib/providers/room_cleaning_provider.dart b/frontend2/lib/providers/room_cleaning_provider.dart new file mode 100644 index 00000000..789d2f6f --- /dev/null +++ b/frontend2/lib/providers/room_cleaning_provider.dart @@ -0,0 +1,183 @@ +import 'package:flutter/material.dart'; + +import '../apis/room_cleaning/room_cleaning_api.dart'; + +class RoomCleaningActionResult { + final bool success; + final String message; + + RoomCleaningActionResult({ + required this.success, + required this.message, + }); +} + +class RoomCleaningProvider extends ChangeNotifier { + final RoomCleaningApi _api = RoomCleaningApi(); + + RoomCleaningAvailability? availability; + bool isAvailabilityLoading = false; + String? availabilityError; + + List myBookings = []; + bool isBookingsLoading = false; + String? bookingsError; + + String _normalizeBookingMessage(Object value) { + var raw = value.toString(); + if (raw.startsWith('Exception:')) { + raw = raw.substring('Exception:'.length).trimLeft(); + } + + if (raw.contains( + 'You can only have one room cleaning booking in any 14-day period.', + )) { + return 'You already have a room cleaning request in the last 14 days.'; + } + + if (raw.contains( + 'No capacity left for this slot on the selected date.', + )) { + return 'This slot is full. Please choose another time.'; + } + + if (raw.contains( + 'You already have a booking for this slot on this date in this hostel.', + )) { + return 'You have already booked this slot for this date.'; + } + + if (raw.contains('Failed to create room-cleaning booking') || + raw.contains('Failed to create room cleaning booking')) { + return 'Could not create your booking. Please try again.'; + } + + return raw; + } + + String _normalizeAvailabilityError(Object value) { + var raw = value.toString(); + if (raw.startsWith('Exception:')) { + raw = raw.substring('Exception:'.length).trimLeft(); + } + + // Common networking / base URL issues. + if (raw.contains('Connection refused') || + raw.contains('SocketException') || + raw.contains('Failed host lookup') || + raw.contains('ClientException with SocketException')) { + return 'Could not reach the server. Please check your internet connection and try again.'; + } + + return 'Something went wrong while loading room-cleaning availability. Please try again.\n\nDetails: $raw'; + } + + Future loadAvailability() async { + isAvailabilityLoading = true; + availabilityError = null; + notifyListeners(); + + try { + availability = await _api.fetchAvailability(); + } catch (e) { + availability = null; + availabilityError = _normalizeAvailabilityError(e); + } finally { + isAvailabilityLoading = false; + notifyListeners(); + } + } + + Future loadMyBookings() async { + isBookingsLoading = true; + bookingsError = null; + notifyListeners(); + + try { + myBookings = await _api.getMyBookings(); + } catch (e) { + myBookings = []; + bookingsError = e.toString(); + } finally { + isBookingsLoading = false; + notifyListeners(); + } + } + + Future bookSlot({ + required DateTime date, + required String slot, + }) async { + try { + final response = await _api.bookSlot(date: date, slot: slot); + // Refresh availability and bookings after a successful booking. + await Future.wait([ + loadAvailability(), + loadMyBookings(), + ]); + final msg = + response['message']?.toString() ?? 'Room cleaning booking created.'; + return RoomCleaningActionResult( + success: true, + message: _normalizeBookingMessage(msg), + ); + } catch (e) { + return RoomCleaningActionResult( + success: false, + message: _normalizeBookingMessage(e), + ); + } + } + + Future cancelBooking(String bookingId) async { + try { + final response = await _api.cancelBooking(bookingId); + await Future.wait([ + loadAvailability(), + loadMyBookings(), + ]); + final msg = response['message']?.toString() ?? + 'Room cleaning booking cancelled successfully.'; + return RoomCleaningActionResult( + success: true, + message: _normalizeBookingMessage(msg), + ); + } catch (e) { + return RoomCleaningActionResult( + success: false, + message: _normalizeBookingMessage(e), + ); + } + } + + Future submitFeedback({ + required String bookingId, + required String reachedInSlot, + required String staffPoliteness, + required int satisfaction, + String? remarks, + }) async { + try { + final response = await _api.submitFeedback( + bookingId: bookingId, + reachedInSlot: reachedInSlot, + staffPoliteness: staffPoliteness, + satisfaction: satisfaction, + remarks: remarks, + ); + await loadMyBookings(); + final msg = response['message']?.toString() ?? + 'Thank you for sharing your feedback.'; + return RoomCleaningActionResult( + success: true, + message: _normalizeBookingMessage(msg), + ); + } catch (e) { + return RoomCleaningActionResult( + success: false, + message: _normalizeBookingMessage(e), + ); + } + } +} + diff --git a/frontend2/lib/screens/gala_dinner_screen.dart b/frontend2/lib/screens/gala_dinner_screen.dart new file mode 100644 index 00000000..6904bf73 --- /dev/null +++ b/frontend2/lib/screens/gala_dinner_screen.dart @@ -0,0 +1,781 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:frontend2/apis/dio_client.dart'; +import 'package:frontend2/constants/endpoint.dart'; +import 'package:frontend2/apis/protected.dart'; +import 'package:frontend2/apis/users/user.dart'; +import 'package:frontend2/screens/gala_qr_scanner_screen.dart'; +import 'package:frontend2/widgets/common/hostel_name.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final _dio = DioClient().dio; + +class GalaDinnerScreen extends StatefulWidget { + const GalaDinnerScreen({super.key}); + + @override + State createState() => _GalaDinnerScreenState(); +} + +class _GalaDinnerScreenState extends State { + bool _loading = true; + Map? _menuData; + Map? _scanStatusData; + String? _error; + String? _hostelDisplayName; + + @override + void initState() { + super.initState(); + _fetchAll(); + } + + /// Backend Gala APIs expect Hostel ObjectId (24-char hex). GalaDinnerMenu.hostelId = Hostel._id (not Mess._id). + /// Prefer hostelID (getUserMessInfo) or currMess (users API = User.curr_subscribed_mess). Reject placeholders. + static bool _isValidObjectId(String? s) { + if (s == null || s.isEmpty) return false; + if (s == 'Not found' || s == 'Not provided') return false; + return RegExp(r'^[a-fA-F0-9]{24}$').hasMatch(s); + } + + Future _getHostelId() async { + final prefs = await SharedPreferences.getInstance(); + final hostelID = prefs.getString('hostelID'); + final currMess = prefs.getString('currMess'); + final hostelId = + _isValidObjectId(hostelID) ? hostelID : (_isValidObjectId(currMess) ? currMess : null); + if (kDebugMode) { + debugPrint('Gala: _getHostelId hostelID=$hostelID currMess=$currMess => hostelId=$hostelId'); + } + return hostelId; + } + + Future _fetchAll() async { + if (kDebugMode) debugPrint('Gala: _fetchAll start'); + setState(() { + _loading = true; + _error = null; + }); + try { + final token = await getAccessToken(); + if (kDebugMode) debugPrint('Gala: token present=${token != "error"}'); + if (token == 'error') { + setState(() { + _error = 'Please log in'; + _loading = false; + }); + return; + } + var hostelId = await _getHostelId(); + if (hostelId == null || hostelId.isEmpty) { + if (kDebugMode) debugPrint('Gala: no hostelId, fetching user details to populate currMess'); + try { + await fetchUserDetails(); + if (!mounted) return; + hostelId = await _getHostelId(); + } catch (_) {} + if (hostelId == null || hostelId.isEmpty) { + if (kDebugMode) debugPrint('Gala: no hostelId after fetch, showing error'); + setState(() { + _error = 'No hostel selected. Open Mess or Profile first to set your hostel.'; + _loading = false; + }); + return; + } + } + await Future.wait([ + _fetchUpcomingWithMenus(token, hostelId), + _fetchScanStatus(token), + ]); + if (!mounted) return; + final name = await calculateHostelAsync(hostelId); + if (!mounted) return; + if (kDebugMode) debugPrint('Gala: _fetchAll done menus=${_menuData != null} scanStatus=${_scanStatusData != null}'); + setState(() { + _loading = false; + _hostelDisplayName = name; + }); + } catch (e, st) { + if (kDebugMode) { + debugPrint('Gala: _fetchAll error=$e'); + debugPrint('Gala: stack=$st'); + if (e is DioException) { + debugPrint('Gala: DioException response=${e.response?.data} statusCode=${e.response?.statusCode}'); + } + } + if (!mounted) return; + setState(() { + _error = e is DioException + ? (e.response?.data is Map && e.response?.data['message'] != null + ? e.response!.data['message'] as String + : 'Failed to load') + : 'Failed to load'; + _loading = false; + }); + } + } + + Future _fetchUpcomingWithMenus(String token, String hostelId) async { + final url = GalaEndpoints.upcomingWithMenus(hostelId); + if (kDebugMode) debugPrint('Gala: GET upcoming-with-menus url=$url'); + final response = await _dio.get( + url, + options: Options(headers: {'Authorization': 'Bearer $token'}), + ); + if (kDebugMode) debugPrint('Gala: upcoming-with-menus status=${response.statusCode} hasGala=${response.data is Map && (response.data as Map)['galaDinner'] != null} menusCount=${response.data is Map ? ((response.data as Map)['menus'] as List?)?.length : 0}'); + if (mounted) { + setState(() { + _menuData = response.data is Map ? Map.from(response.data) : null; + }); + } + } + + Future _fetchScanStatus(String token) async { + if (kDebugMode) debugPrint('Gala: GET scan-status url=${GalaEndpoints.scanStatus}'); + final response = await _dio.get( + GalaEndpoints.scanStatus, + options: Options(headers: {'Authorization': 'Bearer $token'}), + ); + if (kDebugMode) debugPrint('Gala: scan-status status=${response.statusCode} hasScanLog=${response.data is Map && (response.data as Map)['scanLog'] != null}'); + if (mounted) { + setState(() { + _scanStatusData = response.data is Map ? Map.from(response.data) : null; + }); + } + } + + void _refetchScanStatus() async { + final token = await getAccessToken(); + if (token == 'error' || !mounted) return; + await _fetchScanStatus(token); + } + + /// Format gala date for display. Use local time so "7 Mar" picked in admin shows as 7 Mar + /// (backend may store as 6 Mar 18:30 UTC = 7 Mar 00:00 IST). + static String _formatDate(dynamic date) { + if (date == null) return ''; + final d = date is String ? DateTime.tryParse(date) : null; + if (d == null) return date.toString(); + final local = d.toLocal(); + return '${local.day} ${_month(local.month)} ${local.year}'; + } + + /// Formats "HH:mm" (e.g. "18:30") to "6:30 PM". Returns null if invalid or missing. + static String? _formatTimeDisplay(String? str) { + if (str == null || str.isEmpty) return null; + final match = RegExp(r'^(\d{1,2}):(\d{2})$').firstMatch(str.trim()); + if (match == null) return str; + final h = int.tryParse(match.group(1)!) ?? 0; + final m = match.group(2)!; + final h12 = h % 12; + final hDisplay = h12 == 0 ? 12 : h12; + final ampm = h < 12 ? 'AM' : 'PM'; + return '$hDisplay:$m $ampm'; + } + + static const List _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + static String _month(int m) => m >= 1 && m <= 12 ? _months[m - 1] : ''; + + bool _isScanned(String category) { + final log = _scanStatusData?['scanLog'] as Map?; + if (log == null) return false; + switch (category) { + case 'Starters': + return log['startersScanned'] == true; + case 'Main Course': + return log['mainCourseScanned'] == true; + case 'Desserts': + return log['dessertsScanned'] == true; + default: + return false; + } + } + + String? _getScannedTime(String category) { + final log = _scanStatusData?['scanLog'] as Map?; + if (log == null) return null; + switch (category) { + case 'Starters': + return log['startersTime'] as String?; + case 'Main Course': + return log['mainCourseTime'] as String?; + case 'Desserts': + return log['dessertsTime'] as String?; + default: + return null; + } + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Scaffold( + backgroundColor: Colors.white, + body: Center(child: CircularProgressIndicator()), + ); + } + if (_error != null) { + return Scaffold( + backgroundColor: Colors.white, + body: Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(_error!, textAlign: TextAlign.center), + const SizedBox(height: 16), + TextButton(onPressed: _fetchAll, child: const Text('Retry')), + ], + ), + ), + ), + ); + } + + final galaDinner = _menuData?['galaDinner'] as Map?; + final menus = _menuData?['menus'] as List? ?? []; + final hasGala = galaDinner != null && menus.isNotEmpty; + final dateStr = hasGala ? _formatDate(galaDinner['date']) : null; + + return Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: RefreshIndicator( + onRefresh: _fetchAll, + child: SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Gala Dinner', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 32, + fontWeight: FontWeight.w600, + color: Color(0xFF2E2F31), + ), + ), + if (hasGala) ...[ + const SizedBox(height: 12), + Card( + elevation: 1, + color: const Color(0xFFF7F7FB), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (dateStr != null) + Text( + dateStr, + style: const TextStyle( + fontSize: 15, + color: Color(0xFF676767), + ), + ), + const SizedBox(height: 10), + Text( + _hostelDisplayName != null && _hostelDisplayName != 'Unknown' + ? "${_hostelDisplayName!} Gala Dinner" + : 'Gala Dinner', + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w600, + color: Color(0xFF2E2F31), + ), + ), + const SizedBox(height: 6), + Text( + _hostelDisplayName != null && _hostelDisplayName != 'Unknown' + ? 'You are warmly invited to a special gala dinner at $_hostelDisplayName.' + : 'You are warmly invited to a special gala dinner.', + style: const TextStyle( + fontSize: 14, + color: Color(0xFF676767), + ), + ), + const SizedBox(height: 10), + Builder( + builder: (context) { + final starters = _formatTimeDisplay( + galaDinner['startersServingStartTime'] as String?); + final dinner = _formatTimeDisplay( + galaDinner['dinnerServingStartTime'] as String?); + + String line; + if (starters != null && dinner != null) { + line = 'Starters • $starters · Dinner • $dinner'; + } else if (starters != null) { + line = 'Starters • $starters'; + } else if (dinner != null) { + line = 'Dinner • $dinner'; + } else { + line = 'Serving times will be announced soon.'; + } + + return Text( + line, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + color: Color(0xFF4C4EDB), + ), + ); + }, + ), + ], + ), + ), + ), + const SizedBox(height: 18), + ], + _buildCourseBlocks(hasGala), + if (hasGala) ...[ + const SizedBox(height: 8), + const Text( + '*Please scan only while collecting your plate. Once scanned, it cannot be scanned again.', + style: TextStyle( + fontSize: 11, + color: Color(0xFF929292), + ), + ), + ], + const SizedBox(height: 24), + if (hasGala) + _buildMenuCards(menus) + else + Card( + elevation: 0.5, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Colors.grey.shade200), + ), + child: const Padding( + padding: EdgeInsets.all(20.0), + child: Center( + child: Text( + 'No upcoming Gala Dinner scheduled.', + style: TextStyle( + fontSize: 15, + color: Color(0xFF676767), + ), + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _buildCourseBlocks(bool hasGala) { + const categories = ['Starters', 'Main Course', 'Desserts']; + return Row( + children: categories.map((category) { + return Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4), + child: _buildCourseCard(category, hasGala), + ), + ); + }).toList(), + ); + } + + static IconData _iconForCategory(String category) { + switch (category) { + case 'Starters': + return Icons.soup_kitchen; + case 'Main Course': + return Icons.restaurant; + case 'Desserts': + return Icons.cake; + default: + return Icons.qr_code_scanner; + } + } + + static Color _iconBgForCategory(String category, bool hasGala) { + if (!hasGala) return Colors.grey.shade200; + switch (category) { + case 'Starters': + return const Color(0xFFE8F0FE); + case 'Main Course': + case 'Desserts': + return const Color(0xFFEDEDFB); + default: + return const Color(0xFFEDEDFB); + } + } + + Widget _buildCourseCard(String category, bool hasGala) { + final scanned = _isScanned(category); + final time = _getScannedTime(category); + const primaryBlue = Color(0xFF4C4EDB); + const textGrey = Color(0xFF676767); + + Widget content; + if (scanned) { + content = Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: Colors.green.shade500, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: Colors.green.withValues(alpha: 0.18), + blurRadius: 10, + offset: const Offset(0, 3), + ), + ], + ), + child: Icon( + _iconForCategory(category), + color: Colors.white, + size: 18, + ), + ), + const SizedBox(height: 10), + Text( + category, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: textGrey, + ), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + if (time != null && time.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + time, + style: TextStyle( + fontSize: 11, + color: Colors.grey.shade600, + ), + ), + ], + ], + ); + } else { + content = Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: _iconBgForCategory(category, hasGala), + shape: BoxShape.circle, + boxShadow: hasGala + ? [ + BoxShadow( + color: primaryBlue.withValues(alpha: 0.08), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ] + : null, + ), + child: Icon( + _iconForCategory(category), + color: hasGala ? primaryBlue : Colors.grey, + size: 18, + ), + ), + const SizedBox(height: 10), + Text( + category, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: hasGala ? const Color(0xFF2E2F31) : Colors.grey, + ), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + if (hasGala) ...[ + const SizedBox(height: 4), + const Text( + 'Tap to scan', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w500, + color: primaryBlue, + ), + ), + ], + ], + ); + } + + return Material( + color: Colors.transparent, + child: InkWell( + onTap: (!scanned && hasGala) + ? () async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => GalaQRScannerScreen(expectedCategory: category), + ), + ); + _refetchScanStatus(); + } + : null, + borderRadius: BorderRadius.circular(16), + child: Container( + padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 10), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16), + color: Colors.white, + border: Border.all( + color: scanned ? Colors.green.shade100 : const Color(0xFFE6E6E6), + width: 1, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.04), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + child: content, + ), + ), + ); + } + + /// Layout: Main Course full width, then Starters (half) | Desserts (half). + Widget _buildMenuCards(List menus) { + dynamic mainMenu; + dynamic startersMenu; + dynamic dessertsMenu; + for (final m in menus) { + final cat = m['category'] as String? ?? ''; + if (cat == 'Main Course') { + mainMenu = m; + } else if (cat == 'Starters') { + startersMenu = m; + } else if (cat == 'Desserts') { + dessertsMenu = m; + } + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (mainMenu != null) _buildMenuCard(mainMenu), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: startersMenu != null ? _buildMenuCard(startersMenu) : const SizedBox.shrink()), + const SizedBox(width: 8), + Expanded(child: dessertsMenu != null ? _buildMenuCard(dessertsMenu) : const SizedBox.shrink()), + ], + ), + ], + ); + } + + Widget _buildMenuCard(dynamic menu) { + final category = menu['category'] as String? ?? ''; + final items = menu['items'] as List? ?? []; + return _GalaMenuCard(category: category, items: items); + } +} + +/// Expandable/collapsible menu card matching Mess section style (dropdown). +class _GalaMenuCard extends StatefulWidget { + final String category; + final List items; + + const _GalaMenuCard({required this.category, required this.items}); + + @override + State<_GalaMenuCard> createState() => _GalaMenuCardState(); +} + +class _GalaMenuCardState extends State<_GalaMenuCard> { + bool _expanded = false; + + static const _sectionLabelStyle = TextStyle( + fontFamily: "Manrope_semibold", + fontSize: 12, + fontWeight: FontWeight.w600, + color: Color(0xFF676767), + ); + + Widget _buildItem(String name, [String? type]) { + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Flexible( + child: Text( + name, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFF2E2F31), + ), + ), + ), + if (type != null && type.isNotEmpty) + Text( + ' ($type)', + style: TextStyle(fontSize: 13, color: Colors.grey.shade600), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final isMainCourse = widget.category == 'Main Course'; + final dishItems = isMainCourse + ? widget.items.where((i) => (i['type'] as String? ?? '').toLowerCase() == 'dish').toList() + : []; + final breadsItems = isMainCourse + ? widget.items.where((i) => (i['type'] as String? ?? '').toLowerCase() == 'breads and rice').toList() + : []; + final othersItems = isMainCourse + ? widget.items.where((i) => (i['type'] as String? ?? '').toLowerCase() == 'others').toList() + : []; + + return AnimatedSize( + duration: const Duration(milliseconds: 250), + curve: Curves.easeInOut, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 6), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16), + color: const Color(0xFFFFFFFF), + border: Border.all(color: const Color(0xFFC5C5D1)), + ), + child: InkWell( + customBorder: Border.all(color: const Color(0xFFC5C5D1), width: 1), + borderRadius: BorderRadius.circular(16), + highlightColor: Colors.transparent, + hoverColor: Colors.transparent, + focusColor: Colors.transparent, + splashColor: Colors.transparent, + onTap: () => setState(() => _expanded = !_expanded), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + widget.category, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF676767), + ), + ), + ), + Icon( + _expanded ? Icons.expand_less : Icons.expand_more, + size: 20, + color: const Color(0xFF4C4EDB), + ), + ], + ), + if (_expanded) ...[ + const SizedBox(height: 12), + if (isMainCourse) _buildMainCourseContent(dishItems, breadsItems, othersItems) + else if (widget.items.isEmpty) + Text( + 'No items', + style: TextStyle(fontSize: 14, color: Colors.grey.shade600), + ) + else + ...widget.items.map((item) { + final name = item['name'] as String? ?? ''; + return _buildItem(name); + }), + ], + ], + ), + ), + ), + ), + ); + } + + Widget _buildMainCourseContent(List dish, List breads, List others) { + final hasAny = dish.isNotEmpty || breads.isNotEmpty || others.isNotEmpty; + if (!hasAny) { + return Text( + 'No items', + style: TextStyle(fontSize: 14, color: Colors.grey.shade600), + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text("DISH", style: _sectionLabelStyle), + ...dish.map((item) => _buildItem(item['name'] as String? ?? '')), + const Divider( + color: Color(0xFFE6E6E6), + thickness: 1.8, + height: 32, + ), + IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text("BREADS & RICE", style: _sectionLabelStyle), + ...breads.map((item) => _buildItem(item['name'] as String? ?? '')), + ], + ), + ), + const VerticalDivider( + color: Color(0xFFE6E6E6), + thickness: 1.8, + ), + Expanded( + child: Padding( + padding: const EdgeInsets.only(left: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text("OTHERS", style: _sectionLabelStyle), + ...others.map((item) => _buildItem(item['name'] as String? ?? '')), + ], + ), + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/frontend2/lib/screens/gala_qr_scanner_screen.dart b/frontend2/lib/screens/gala_qr_scanner_screen.dart new file mode 100644 index 00000000..4342bd75 --- /dev/null +++ b/frontend2/lib/screens/gala_qr_scanner_screen.dart @@ -0,0 +1,343 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:frontend2/apis/dio_client.dart'; +import 'package:frontend2/constants/endpoint.dart'; +import 'package:frontend2/screens/gala_scan_status_page.dart'; +import 'package:frontend2/widgets/common/cornerQR.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:dio/dio.dart'; +import 'package:vibration/vibration.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:frontend2/widgets/microsoft_required_dialog.dart'; + +final _dio = DioClient().dio; + +/// Expected category for this scanner: Starters, Main Course, or Desserts. +class GalaQRScannerScreen extends StatefulWidget { + final String expectedCategory; + + const GalaQRScannerScreen({super.key, required this.expectedCategory}); + + @override + State createState() => _GalaQRScannerScreenState(); +} + +class _GalaQRScannerScreenState extends State { + late MobileScannerController controller; + bool _hasScanned = false; + bool _isProcessing = false; + bool _cameraPermissionGranted = false; + bool _isCheckingPermission = false; + + @override + void initState() { + super.initState(); + controller = MobileScannerController( + detectionSpeed: DetectionSpeed.noDuplicates, + facing: CameraFacing.back, + torchEnabled: false, + autoStart: false, + ); + _checkMicrosoftLink().then((_) { + if (mounted) _initializeCameraPermission(); + }); + } + + Future _checkMicrosoftLink() async { + final prefs = await SharedPreferences.getInstance(); + final hasMicrosoftLinked = prefs.getBool('hasMicrosoftLinked') ?? false; + if (!hasMicrosoftLinked && mounted) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + showDialog( + context: context, + builder: (context) => const MicrosoftRequiredDialog( + featureName: 'Gala QR Scanning', + ), + ); + Navigator.pop(context); + } + }); + } + } + + Future _initializeCameraPermission() async { + setState(() => _isCheckingPermission = true); + final status = await Permission.camera.status; + if (!mounted) return; + setState(() { + _isCheckingPermission = false; + _cameraPermissionGranted = status.isGranted; + }); + bool hasPermission = status.isGranted; + if (status.isDenied) { + final result = await Permission.camera.request(); + if (mounted) { + setState(() => _cameraPermissionGranted = result.isGranted); + } + hasPermission = result.isGranted; + if (result.isPermanentlyDenied && mounted) { + _showPermissionDeniedDialog(); + } + } + // With autoStart: false, we must start the controller after permission is granted + if (hasPermission && mounted) { + await Future.delayed(const Duration(milliseconds: 300)); + if (!mounted) return; + try { + await controller.start(); + } catch (e) { + if (mounted) { + await Future.delayed(const Duration(milliseconds: 500)); + try { + await controller.start(); + } catch (_) {} + } + } + } + } + + void _showPermissionDeniedDialog() { + showDialog( + context: context, + barrierDismissible: false, + builder: (ctx) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + title: const Text('Camera Access Required', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)), + content: const Text( + 'Camera access is required to scan Gala QR codes. Please enable camera permission in Settings.', + style: TextStyle(fontSize: 14), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Cancel')), + ElevatedButton( + onPressed: () { + Navigator.pop(ctx); + openAppSettings(); + }, + style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF4C4EDB), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))), + child: const Text('Open Settings', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600)), + ), + ], + ), + ); + } + + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + Future _scanGala(String galaDinnerMenuId) async { + if (_isProcessing) return; + setState(() => _isProcessing = true); + final navigator = Navigator.of(context); + if (kDebugMode) debugPrint('GalaScan: expectedCategory=${widget.expectedCategory} galaDinnerMenuId=$galaDinnerMenuId'); + + try { + final prefs = await SharedPreferences.getInstance(); + final userId = prefs.getString('userId'); + final accessToken = prefs.getString('access_token'); + if (!mounted) return; + if (userId == null || accessToken == null) { + if (kDebugMode) debugPrint('GalaScan: missing userId or accessToken'); + setState(() => _isProcessing = false); + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Please log in'))); + return; + } + + if (kDebugMode) debugPrint('GalaScan: POST ${GalaEndpoints.scan}'); + final response = await _dio.post( + GalaEndpoints.scan, + data: { + 'userId': userId, + 'galaDinnerMenuId': galaDinnerMenuId, + 'expectedCategory': widget.expectedCategory, + }, + options: Options( + headers: { + 'Authorization': 'Bearer $accessToken', + 'Content-Type': 'application/json', + }, + ), + ); + if (kDebugMode) debugPrint('GalaScan: response status=${response.statusCode} success=${response.data is Map ? (response.data as Map)['success'] : null} message=${response.data is Map ? (response.data as Map)['message'] : null}'); + + final hasVib = await Vibration.hasVibrator(); + if (hasVib == true) Vibration.vibrate(duration: 100); + + if (!mounted) return; + navigator.push(MaterialPageRoute( + builder: (context) => GalaScanStatusPage(response: response), + )).then((_) { + if (mounted) { + setState(() { + _hasScanned = false; + _isProcessing = false; + }); + controller.start(); + } + }); + } catch (e) { + if (kDebugMode) { + debugPrint('GalaScan: error=$e'); + if (e is DioException) debugPrint('GalaScan: DioException status=${e.response?.statusCode} data=${e.response?.data}'); + } + if (!mounted) return; + String msg = 'Unknown error'; + if (e is DioException && e.response?.data is Map) { + final d = e.response!.data as Map; + msg = d['message']?.toString() ?? 'Server error'; + } else if (e is DioException) { + msg = e.message ?? 'Network error'; + } + navigator.push(MaterialPageRoute( + builder: (context) => GalaScanStatusPage( + response: Response( + requestOptions: RequestOptions(path: ''), + statusCode: e is DioException ? e.response?.statusCode ?? 400 : 400, + data: {'success': false, 'message': msg}, + ), + ), + )).then((_) { + if (mounted) { + setState(() { + _hasScanned = false; + _isProcessing = false; + }); + controller.start(); + } + }); + } + } + + void _onBarcodeDetected(BarcodeCapture capture) { + if (_hasScanned || _isProcessing) return; + setState(() => _hasScanned = true); + for (final barcode in capture.barcodes) { + final value = barcode.rawValue; + if (value != null && value.isNotEmpty) { + controller.stop(); + _scanGala(value); + break; + } + } + } + + @override + Widget build(BuildContext context) { + final title = widget.expectedCategory == 'Main Course' ? 'Main Course' : widget.expectedCategory; + return Scaffold( + backgroundColor: Colors.black, + appBar: AppBar( + title: Text(title), + backgroundColor: Colors.black, + foregroundColor: Colors.white, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.of(context).pop(), + ), + ), + body: !_cameraPermissionGranted + ? _buildPermissionOverlay() + : Stack( + children: [ + MobileScanner( + controller: controller, + onDetect: _onBarcodeDetected, + errorBuilder: (context, error) => Center( + child: Text( + 'Camera Error: ${error.errorDetails?.message ?? "Unknown"}', + style: const TextStyle(color: Colors.white), + ), + ), + ), + _buildScannerUI(), + if (_isProcessing) + Container( + color: Colors.black54, + child: const Center(child: CircularProgressIndicator(color: Color(0xFF4C4EDB))), + ), + ], + ), + ); + } + + Widget _buildPermissionOverlay() { + return Container( + color: Colors.black, + child: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 40), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.camera_alt_outlined, size: 80, color: Color(0xFF4C4EDB)), + const SizedBox(height: 32), + const Text('Camera Access Needed', style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.w600), textAlign: TextAlign.center), + const SizedBox(height: 16), + const Text('We need camera access to scan Gala QR codes.', style: TextStyle(color: Color.fromRGBO(255, 255, 255, 0.7), fontSize: 16), textAlign: TextAlign.center), + const SizedBox(height: 40), + _isCheckingPermission + ? const CircularProgressIndicator(color: Color(0xFF4C4EDB)) + : ElevatedButton( + onPressed: _initializeCameraPermission, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 14), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + ), + child: const Text('Continue', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + ), + ); + } + + Widget _buildScannerUI() { + return Column( + children: [ + const SizedBox(height: 80), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 40), + child: Text( + 'Scan ${widget.expectedCategory} QR', + style: const TextStyle(color: Color.fromRGBO(255, 255, 255, 0.9), fontSize: 22, fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + ), + ), + const SizedBox(height: 40), + Center( + child: SizedBox( + width: 250, + height: 250, + child: CustomPaint(size: const Size(250, 250), painter: CornerPainter()), + ), + ), + const SizedBox(height: 40), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 40), + child: Text( + 'Hold the QR code steady within the frame', + style: TextStyle(color: Colors.white, fontSize: 16), + textAlign: TextAlign.center, + ), + ), + const Spacer(), + Padding( + padding: const EdgeInsets.only(bottom: 40), + child: IconButton( + icon: const Icon(Icons.cameraswitch, color: Colors.white, size: 32), + onPressed: () => controller.switchCamera(), + tooltip: 'Switch Camera', + ), + ), + ], + ); + } +} diff --git a/frontend2/lib/screens/gala_scan_status_page.dart b/frontend2/lib/screens/gala_scan_status_page.dart new file mode 100644 index 00000000..76019747 --- /dev/null +++ b/frontend2/lib/screens/gala_scan_status_page.dart @@ -0,0 +1,247 @@ +import 'dart:convert'; + +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Shows success or failure after a Gala QR scan. "Go Back" pops twice to return to Gala Dinner tab. +class GalaScanStatusPage extends StatefulWidget { + final Response response; + + const GalaScanStatusPage({super.key, required this.response}); + + @override + State createState() => _GalaScanStatusPageState(); +} + +class _GalaScanStatusPageState extends State { + String profilePicture = ''; + + @override + void initState() { + super.initState(); + _loadProfilePicture(); + } + + Future _loadProfilePicture() async { + final prefs = await SharedPreferences.getInstance(); + setState(() { + profilePicture = prefs.getString('profilePicture') ?? ''; + }); + } + + @override + Widget build(BuildContext context) { + final data = widget.response.data is Map + ? Map.from(widget.response.data as Map) + : {}; + final success = data['success'] == true; + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: success ? _buildSuccess(context, data) : _buildFailed(context, data), + ), + ); + } + + Widget _buildSuccess(BuildContext context, Map data) { + final mealType = data['mealType'] ?? 'Course'; + final time = data['time'] ?? ''; + final userName = data['user']?['name'] ?? ''; + + return Column( + children: [ + const SizedBox(height: 60), + Container( + width: 120, + height: 120, + decoration: const BoxDecoration( + color: Color.fromRGBO(76, 175, 80, 0.2), + shape: BoxShape.circle, + ), + child: const Icon( + Icons.check_circle_outline_outlined, + color: Colors.green, + size: 80, + ), + ), + const SizedBox(height: 20), + const Text( + 'Scan Successful!', + style: TextStyle( + color: Colors.green, + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 40), + CircleAvatar( + radius: 80, + backgroundColor: Colors.grey[300], + backgroundImage: profilePicture.isNotEmpty + ? MemoryImage(base64Decode(profilePicture)) + : const AssetImage('assets/images/default_profile.png') + as ImageProvider, + ), + const SizedBox(height: 30), + if (userName.isNotEmpty) + Text( + userName, + style: const TextStyle( + color: Color(0xFF8183F1), + fontSize: 22, + ), + ), + if (userName.isNotEmpty) const SizedBox(height: 15), + Text( + mealType, + style: const TextStyle( + color: Color(0xFF929292), + fontSize: 22, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 10), + Text( + time, + style: const TextStyle( + color: Color(0xFF8183F1), + fontSize: 18, + ), + ), + const Spacer(), + Padding( + padding: const EdgeInsets.all(30), + child: SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pop(); + Navigator.of(context).pop(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF8183F1), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(25), + ), + ), + child: const Text( + 'Go Back', + style: TextStyle( + color: Colors.black, + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ), + ], + ); + } + + Widget _buildFailed(BuildContext context, Map data) { + final message = data['message']?.toString() ?? 'Scan failed'; + + return Column( + children: [ + const SizedBox(height: 60), + Container( + width: 120, + height: 120, + decoration: const BoxDecoration( + color: Color.fromRGBO(244, 67, 54, 0.2), + shape: BoxShape.circle, + ), + child: const Icon( + Icons.error_outline_outlined, + color: Colors.red, + size: 80, + ), + ), + const SizedBox(height: 20), + const Text( + 'Scan Failed!', + style: TextStyle( + color: Colors.red, + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 20), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 40), + child: Text( + message, + style: const TextStyle( + color: Color(0xFF929292), + fontSize: 18, + ), + textAlign: TextAlign.center, + ), + ), + const Spacer(), + Padding( + padding: const EdgeInsets.all(30), + child: Column( + children: [ + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pop(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF8183F1), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(25), + ), + ), + child: const Text( + 'Try Again', + style: TextStyle( + color: Colors.black, + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + const SizedBox(height: 15), + SizedBox( + width: double.infinity, + height: 50, + child: ElevatedButton( + onPressed: () { + Navigator.of(context).pop(); + Navigator.of(context).pop(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Colors.black, + side: const BorderSide( + color: Color(0xFF8183F1), + width: 2, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(25), + ), + ), + child: const Text( + 'Go Back', + style: TextStyle( + color: Color(0xFF8183F1), + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/frontend2/lib/screens/home_screen.dart b/frontend2/lib/screens/home_screen.dart index 6aee7ad1..ba4285cd 100644 --- a/frontend2/lib/screens/home_screen.dart +++ b/frontend2/lib/screens/home_screen.dart @@ -15,6 +15,8 @@ import '../utilities/startupitem.dart'; import '../widgets/alerts_card.dart'; import '../widgets/microsoft_required_dialog.dart'; import 'mess_preference.dart'; +import 'room_cleaning/room_cleaning.dart'; + class HomeScreen extends StatefulWidget { final void Function(int)? onNavigateToTab; @@ -102,6 +104,8 @@ class _HomeScreenState extends State { padding: const EdgeInsets.symmetric(vertical: 18.0), child: Row( children: [ + + /// SCAN QR Expanded( child: InkWell( borderRadius: BorderRadius.circular(18), @@ -111,49 +115,53 @@ class _HomeScreenState extends State { MaterialPageRoute(builder: (context) => const QrScan()), ); }, - child: Container( - height: 90, - decoration: BoxDecoration( - // color: const Color(0xFFF6F6F6), - color: const Color(0xFFFFFFFF), - borderRadius: BorderRadius.circular(18), - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Container( - width: 40, - height: 40, - decoration: const BoxDecoration( - color: Color(0xFF3754DB), - shape: BoxShape.circle, - ), - child: Center( - child: SvgPicture.asset( - 'assets/icon/qrscan.svg', - colorFilter: const ColorFilter.mode( - Colors.white, BlendMode.srcIn), - width: 22, - height: 22, - ), - ), - ), - const SizedBox(height: 8), - const Text( - "Scan QR", - style: TextStyle( - color: Colors.black, - fontWeight: FontWeight.w600, - fontSize: 15, - ), + child: _quickActionCard( + iconPath: 'assets/icon/qrscan.svg', + label: "Scan QR", + iconData: null, + ), + ), + ), + + const SizedBox(width: 12), + /// ROOM CLEANING + Expanded( + child: InkWell( + borderRadius: BorderRadius.circular(18), + onTap: () async { + final prefs = await SharedPreferences.getInstance(); + final hasMicrosoftLinked = + prefs.getBool('hasMicrosoftLinked') ?? false; + + if (!mounted) return; + + if (!hasMicrosoftLinked) { + showDialog( + context: context, + builder: (context) => const MicrosoftRequiredDialog( + featureName: 'Room Cleaning', ), - ], - ), + ); + return; + } + + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const RoomCleaningScreen(), + ), + ); + }, + child: _quickActionCard( + iconPath: 'assets/icon/cleaning.svg', + label: "Room Cleaning", + iconData: Icons.cleaning_services_rounded, ), ), ), - const SizedBox(width: 16), + + const SizedBox(width: 12), + /// MESS CHANGE Expanded( child: InkWell( borderRadius: BorderRadius.circular(18), @@ -176,51 +184,70 @@ class _HomeScreenState extends State { Navigator.push( context, - // MaterialPageRoute(builder: (context) => MessChangeScreen()), MaterialPageRoute( - builder: (context) => const MessChangePreferenceScreen()), + builder: (context) => + const MessChangePreferenceScreen(), + ), ); }, - child: Container( - height: 90, - decoration: BoxDecoration( - // color: const Color(0xFFF6F6F6), - color: const Color(0xFFFFFFFF), - borderRadius: BorderRadius.circular(18), - ), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Container( - width: 40, - height: 40, - decoration: const BoxDecoration( - color: Color(0xFF3754DB), - shape: BoxShape.circle, - ), - child: Center( - child: SvgPicture.asset( - 'assets/icon/messicon.svg', - colorFilter: const ColorFilter.mode( - Colors.white, BlendMode.srcIn), - width: 22, - height: 22, - ), - ), - ), - const SizedBox(height: 8), - const Text( - "Mess Change", - style: TextStyle( - color: Colors.black, - fontWeight: FontWeight.w600, - fontSize: 15, + child: _quickActionCard( + iconPath: 'assets/icon/messicon.svg', + label: "Mess Change", + iconData: null, + ), + ), + ), + ], + ), + ); + } + + Widget _quickActionCard({ + required String iconPath, + required String label, + IconData? iconData, + }) { + return Container( + height: 90, + decoration: BoxDecoration( + color: const Color(0xFFFFFFFF), + borderRadius: BorderRadius.circular(18), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 40, + height: 40, + decoration: const BoxDecoration( + color: Color(0xFF3754DB), + shape: BoxShape.circle, + ), + child: Center( + child: iconData != null + ? Icon( + iconData, + size: 22, + color: Colors.white, + ) + : SvgPicture.asset( + iconPath, + colorFilter: const ColorFilter.mode( + Colors.white, + BlendMode.srcIn, ), + width: 22, + height: 22, ), - ], - ), - ), + ), + ), + const SizedBox(height: 8), + Text( + label, + style: const TextStyle( + color: Colors.black, + fontWeight: FontWeight.w600, + fontSize: 15, ), ), ], @@ -228,6 +255,8 @@ class _HomeScreenState extends State { ); } + + Widget buildMessTodayCard() { return Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/frontend2/lib/screens/initial_setup_screen.dart b/frontend2/lib/screens/initial_setup_screen.dart index d86c84db..aa08753d 100644 --- a/frontend2/lib/screens/initial_setup_screen.dart +++ b/frontend2/lib/screens/initial_setup_screen.dart @@ -16,7 +16,7 @@ import 'package:frontend2/apis/users/user.dart'; class ProfilePictureProvider { static var profilePictureString = ValueNotifier(""); static var isSetupDone = ValueNotifier(false); - static void init() async { + static Future init() async { final prefs = await SharedPreferences.getInstance(); // Do NOT overwrite existing stored picture profilePictureString.value = prefs.getString("profilePicture") ?? ""; diff --git a/frontend2/lib/screens/main_navigation_screen.dart b/frontend2/lib/screens/main_navigation_screen.dart index adb4370c..356bd739 100644 --- a/frontend2/lib/screens/main_navigation_screen.dart +++ b/frontend2/lib/screens/main_navigation_screen.dart @@ -1,12 +1,23 @@ +import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; +import 'package:frontend2/apis/dio_client.dart'; +import 'package:frontend2/apis/mess/user_mess_info.dart'; +import 'package:frontend2/apis/users/user.dart'; +import 'package:frontend2/constants/endpoint.dart'; +import 'package:frontend2/providers/hostels.dart'; +import 'package:frontend2/screens/gala_dinner_screen.dart'; import 'package:frontend2/screens/initial_setup_screen.dart'; import 'package:frontend2/screens/mess_preference.dart'; import 'package:frontend2/screens/profile_screen.dart'; +import 'package:frontend2/utilities/notifications.dart'; +import 'package:frontend2/widgets/common/bottom_nav_bar.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:frontend2/utilities/startupitem.dart'; import 'home_screen.dart'; import 'mess_screen.dart'; -import '../utilities/notifications.dart'; -import '../widgets/common/bottom_nav_bar.dart'; +final _dio = DioClient().dio; class MainNavigationScreen extends StatefulWidget { const MainNavigationScreen({super.key}); @@ -17,6 +28,8 @@ class MainNavigationScreen extends StatefulWidget { class _MainNavigationScreenState extends State { int _selectedIndex = 0; + bool _showGalaTab = false; + bool _homeDataReady = false; void _handleNavTap(int index) { setState(() { @@ -27,9 +40,90 @@ class _MainNavigationScreenState extends State { @override void initState() { super.initState(); - // Listen for navigation from notifications + _resolveGalaTabVisibility(); tabNavigationNotifier.addListener(_onTabNavigationRequested); deepNavigationNotifier.addListener(_onDeepNavigationRequested); + _runPhase2AndPhase3(); + } + + /// Phase 2: fetch user details, mess info, profile picture (loader until done). + /// Phase 3: FCM, hostels, analytics, mess list (background). + Future _runPhase2AndPhase3() async { + // Phase 3 (background) – start immediately, don't block + _runPhase3Background(); + + // Phase 2 – must complete before hiding home loader + try { + await fetchUserDetails(); + } catch (_) {} + try { + await fetchUserProfilePicture(); + } catch (_) {} + try { + await getUserMessInfo(); + } catch (_) {} + if (mounted) setState(() => _homeDataReady = true); + } + + void _runPhase3Background() { + registerFcmToken(); + FirebaseAnalytics.instance.setAnalyticsCollectionEnabled(true); + HostelsNotifier.init(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read().fetchMessID(); + }); + } + + /// Gala tab: for SMC show when any upcoming gala; for non-SMC show only when + /// gala date is within 3 days (visible from galaDate-2 days through gala date). + Future _resolveGalaTabVisibility() async { + try { + final prefs = await SharedPreferences.getInstance(); + final isSMC = prefs.getBool('isSMC') ?? false; + final hasMicrosoftLinked = prefs.getBool('hasMicrosoftLinked') ?? false; + + // Only users who have linked their Microsoft (student) account + // should see the Gala tab at all. + if (!hasMicrosoftLinked) { + if (mounted) { + setState(() => _showGalaTab = false); + } + return; + } + + final response = await _dio.get(GalaEndpoints.upcoming); + final galaData = response.data; + final galaDateRaw = galaData is Map ? galaData['date'] : null; + if (galaDateRaw == null) { + if (mounted) setState(() => _showGalaTab = false); + return; + } + DateTime? galaDate; + if (galaDateRaw is String) { + galaDate = DateTime.tryParse(galaDateRaw)?.toLocal(); + } else if (galaDateRaw is DateTime) { + galaDate = galaDateRaw.toLocal(); + } + if (galaDate == null) { + if (mounted) setState(() => _showGalaTab = false); + return; + } + final galaDay = DateTime(galaDate.year, galaDate.month, galaDate.day); + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final daysUntil = galaDay.difference(today).inDays; + // Non-SMC: show only when 0 <= daysUntil <= 2 (i.e. within 3 days: today, tomorrow, day after) + final show = isSMC ? (daysUntil >= 0) : (daysUntil >= 0 && daysUntil <= 2); + if (mounted) { + setState(() { + _showGalaTab = show; + if (!show && _selectedIndex == 2) _selectedIndex = 0; + }); + } + } catch (_) { + if (mounted) setState(() => _showGalaTab = false); + } } void _onTabNavigationRequested() { @@ -87,23 +181,51 @@ class _MainNavigationScreenState extends State { final screens = [ HomeScreen(onNavigateToTab: _handleNavTap), const MessScreen(), + const GalaDinnerScreen(), ]; - return ValueListenableBuilder( - valueListenable: ProfilePictureProvider.isSetupDone, - builder: (context, setupDone, child) => Scaffold( - body: (setupDone == true) - ? IndexedStack( - index: _selectedIndex, - children: screens, - ) - : const InitialSetupScreen(), - bottomNavigationBar: (setupDone == true) - ? BottomNavBar( - currentIndex: _selectedIndex, - onTap: _handleNavTap, - ) - : const SizedBox(), - ), + return Stack( + children: [ + ValueListenableBuilder( + valueListenable: ProfilePictureProvider.isSetupDone, + builder: (context, setupDone, child) => Scaffold( + body: (setupDone == true) + ? IndexedStack( + index: _selectedIndex, + children: screens, + ) + : const InitialSetupScreen(), + bottomNavigationBar: (setupDone == true) + ? BottomNavBar( + currentIndex: _selectedIndex, + onTap: _handleNavTap, + showGalaTab: _showGalaTab, + ) + : const SizedBox(), + ), + ), + if (!_homeDataReady) + Positioned.fill( + child: Container( + color: Colors.white, + child: const Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text( + 'Loading...', + style: TextStyle( + fontSize: 14, + color: Color(0xFF676767), + ), + ), + ], + ), + ), + ), + ), + ], ); } } diff --git a/frontend2/lib/screens/room_cleaning/room_cleaning.dart b/frontend2/lib/screens/room_cleaning/room_cleaning.dart new file mode 100644 index 00000000..39e91653 --- /dev/null +++ b/frontend2/lib/screens/room_cleaning/room_cleaning.dart @@ -0,0 +1,1420 @@ +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../providers/room_cleaning_provider.dart'; +import '../../apis/room_cleaning/room_cleaning_api.dart'; + +/// Slot letter to time range for display (replaces "Slot A" etc. with timing). +const Map _slotTimeRange = { + 'A': '12:00–14:00', + 'B': '14:00–16:00', + 'C': '16:00–18:00', + 'D': '18:00–20:00', +}; + +class RoomCleaningScreen extends StatelessWidget { + const RoomCleaningScreen({super.key}); + + @override + Widget build(BuildContext context) { + return DefaultTabController( + length: 2, + child: Builder( + builder: (context) { + // Kick off initial loads after first frame. + WidgetsBinding.instance.addPostFrameCallback((_) { + final provider = + Provider.of(context, listen: false); + provider.loadAvailability(); + provider.loadMyBookings(); + }); + + return Scaffold( + backgroundColor: Colors.white, + appBar: AppBar( + backgroundColor: Colors.white, + foregroundColor: Colors.black, + elevation: 0, + title: const Text( + 'Room Cleaning', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 18, + color: Colors.black, + ), + ), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(44), + child: Container( + alignment: Alignment.centerLeft, + child: const TabBar( + labelColor: Color(0xFF3754DB), + unselectedLabelColor: Color(0xFF6B7280), + indicatorColor: Color(0xFF3754DB), + indicatorSize: TabBarIndicatorSize.label, + labelStyle: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + ), + unselectedLabelStyle: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w500, + fontSize: 14, + ), + tabs: [ + Tab(text: 'Book Slot'), + Tab(text: 'My Bookings'), + ], + ), + ), + ), + ), + body: const TabBarView( + children: [ + _BookSlotTab(), + _MyBookingsTab(), + ], + ), + ); + }, + ), + ); + } +} + +class _BookSlotTab extends StatefulWidget { + const _BookSlotTab(); + + @override + State<_BookSlotTab> createState() => _BookSlotTabState(); +} + +class _BookSlotTabState extends State<_BookSlotTab> { + final Set _expandedIndices = {0}; + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, provider, _) { + if (provider.isAvailabilityLoading) { + return const Center(child: CircularProgressIndicator()); + } + + final availability = provider.availability; + + if (provider.availabilityError != null) { + return Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const Icon( + Icons.wifi_off_rounded, + size: 40, + color: Color(0xFF9CA3AF), + ), + const SizedBox(height: 12), + const Text( + 'Unable to load room-cleaning info', + textAlign: TextAlign.center, + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 15, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 8), + Text( + provider.availabilityError!, + textAlign: TextAlign.center, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + const SizedBox(height: 16), + ElevatedButton( + onPressed: () { + Provider.of(context, listen: false) + .loadAvailability(); + }, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF3754DB), + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 10, + ), + ), + child: const Text( + 'Retry', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + ), + ], + ), + ); + } + + if (availability == null) { + return const Center(child: Text('No availability data.')); + } + + final days = availability.days; + + if (days.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + availability.canBook + ? 'No days are open for booking right now.' + : 'You already have a room cleaning booking in the last 2 weeks.', + textAlign: TextAlign.center, + ), + ), + ); + } + + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!availability.canBook) + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Expanded( + child: Text( + 'You already have a booking in the last 2 weeks.', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + ), + ), + ), + TextButton( + onPressed: () { + final controller = DefaultTabController.of(context); + controller.animateTo(1); + }, + child: const Text('View Bookings →'), + ), + ], + ), + ), + // Custom accordion-style dropdowns that match app cards. + Column( + children: [ + for (var i = 0; i < days.length; i++) + _DayCard( + day: days[i], + isExpanded: _expandedIndices.contains(i), + onToggle: () { + setState(() { + if (_expandedIndices.contains(i)) { + _expandedIndices.remove(i); + } else { + _expandedIndices.add(i); + } + }); + }, + canBook: availability.canBook, + ), + ], + ), + ], + ), + ), + ); + }, + ); + } +} + +class _DayCard extends StatelessWidget { + final RoomCleaningDayAvailability day; + final bool isExpanded; + final VoidCallback onToggle; + final bool canBook; + + const _DayCard({ + required this.day, + required this.isExpanded, + required this.onToggle, + required this.canBook, + }); + + @override + Widget build(BuildContext context) { + final dateLabel = DateFormat('EEE, MMM d').format(day.date); + + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.02), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Column( + children: [ + InkWell( + borderRadius: BorderRadius.circular(16), + onTap: onToggle, + child: Padding( + padding: + const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0), + child: Row( + children: [ + Expanded( + child: Text( + dateLabel, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Colors.black, + ), + ), + ), + Icon( + isExpanded + ? Icons.keyboard_arrow_up_rounded + : Icons.keyboard_arrow_down_rounded, + color: const Color(0xFF6B7280), + ), + ], + ), + ), + ), + if (isExpanded) + const Divider( + height: 1, + color: Color(0xFFE5E7EB), + ), + if (isExpanded) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 12.0, + vertical: 8.0, + ), + child: Column( + children: day.slots + .map( + (slot) => _SlotTile( + day: day, + slot: slot, + canBook: canBook, + ), + ) + .toList(), + ), + ), + ], + ), + ); + } +} + +class _SlotTile extends StatelessWidget { + final RoomCleaningDayAvailability day; + final RoomCleaningSlotAvailability slot; + final bool canBook; + + const _SlotTile({ + required this.day, + required this.slot, + required this.canBook, + }); + + Future _handleBook(BuildContext context) async { + if (!canBook) return; + + final provider = Provider.of(context, listen: false); + + // Load default room & phone from profile (SharedPreferences). + final prefs = await SharedPreferences.getInstance(); + final initialRoom = prefs.getString('roomNumber') ?? ''; + final initialPhone = prefs.getString('phoneNumber') ?? ''; + + final roomController = TextEditingController(text: initialRoom); + final phoneController = TextEditingController(text: initialPhone); + + final dateLabel = DateFormat('EEE, MMM d').format(day.date); + final heading = '$dateLabel • ${slot.timeRange}'; + + String? localError; + + final shouldBook = await showDialog( + context: context, + barrierColor: Colors.black26, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setState) { + return AlertDialog( + backgroundColor: Colors.white, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(18), + ), + titlePadding: const EdgeInsets.only( + left: 20, right: 20, top: 20, bottom: 8), + contentPadding: + const EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 8), + actionsPadding: const EdgeInsets.only( + left: 20, right: 20, bottom: 16, top: 8), + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Confirm room cleaning slot', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 17, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 4), + Text( + heading, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + ], + ), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFFF9FAFB), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: const Color(0xFFE5E7EB), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: const [ + _InstructionBullet( + text: + 'Please verify your room number and phone number before confirming this booking.', + ), + _InstructionBullet( + text: + 'You can place at most one room cleaning request in any 2‑week period (roughly twice a month).', + ), + _InstructionBullet( + text: + 'If you choose a buffer slot, the request may or may not be fulfilled depending on staff availability.', + ), + _InstructionBullet( + text: + 'Make sure you are present in your room during the selected time slot.', + ), + ], + ), + ), + const SizedBox(height: 16), + const Text( + 'Room number', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w500, + fontSize: 13, + color: Color(0xFF374151), + ), + ), + const SizedBox(height: 6), + TextField( + controller: roomController, + decoration: InputDecoration( + hintText: 'Enter your room number', + isDense: true, + filled: true, + fillColor: const Color(0xFFF9FAFB), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 12, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFF3754DB), + width: 1.5, + ), + ), + ), + ), + const SizedBox(height: 12), + const Text( + 'Phone number', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w500, + fontSize: 13, + color: Color(0xFF374151), + ), + ), + const SizedBox(height: 6), + TextField( + controller: phoneController, + keyboardType: TextInputType.phone, + decoration: InputDecoration( + hintText: 'Enter your phone number', + isDense: true, + filled: true, + fillColor: const Color(0xFFF9FAFB), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 12, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFF3754DB), + width: 1.5, + ), + ), + ), + ), + if (localError != null) ...[ + const SizedBox(height: 8), + Text( + localError!, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFFDC2626), + ), + ), + ], + ], + ), + ), + actions: [ + OutlinedButton( + onPressed: () { + Navigator.of(dialogContext).pop(false); + }, + style: OutlinedButton.styleFrom( + foregroundColor: const Color(0xFF6B7280), + side: const BorderSide(color: Color(0xFF9CA3AF)), + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + child: const Text( + 'Go Back', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + ), + const SizedBox(width: 10), + ElevatedButton( + onPressed: () { + final room = roomController.text.trim(); + final phone = phoneController.text.trim(); + if (room.isEmpty || phone.isEmpty) { + setState(() { + localError = + 'Please fill both room number and phone number.'; + }); + return; + } + Navigator.of(dialogContext).pop(true); + }, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF3754DB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 20, vertical: 10), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + elevation: 0, + ), + child: const Text( + 'Book Slot', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + ), + ], + ); + }, + ); + }, + ); + + if (shouldBook == true) { + // Persist the latest values so profile and future bookings see them. + await prefs.setString('roomNumber', roomController.text.trim()); + await prefs.setString('phoneNumber', phoneController.text.trim()); + } + + if (shouldBook != true) return; + + final result = await provider.bookSlot( + date: day.date, + slot: slot.slot, + ); + + if (!context.mounted) return; + + _showRoomCleaningSnackBar( + context, + result.message, + isError: !result.success, + ); + + if (result.success) { + await provider.loadMyBookings(); + if (!context.mounted) return; + DefaultTabController.of(context).animateTo(1); + } + } + + @override + Widget build(BuildContext context) { + final hasPrimary = slot.slotsLeft > 0; + final hasBuffer = slot.bufferSlotsLeft > 0; + + final isBookable = canBook && (hasPrimary || hasBuffer); + + return Container( + margin: const EdgeInsets.symmetric(vertical: 6.0), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: const Color(0xFFE5E7EB)), + ), + child: ListTile( + onTap: isBookable ? () => _handleBook(context) : null, + title: Text( + slot.timeRange, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Colors.black, + ), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (hasPrimary) + _pill( + label: '${slot.slotsLeft} Left', + color: Colors.green.shade600, + ) + else if (hasBuffer) + _pill( + label: '${slot.bufferSlotsLeft} Buffer Left', + color: Colors.orange.shade600, + ) + else + _pill( + label: 'Full', + color: Colors.red.shade600, + ), + ], + ), + ), + ); + } + + Widget _pill({required String label, required Color color}) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: color.withOpacity(0.1), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: color), + ), + child: Text( + label, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ); + } +} + +class _InstructionBullet extends StatelessWidget { + final String text; + + const _InstructionBullet({required this.text}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 6.0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '• ', + style: TextStyle( + fontSize: 13, + color: const Color(0xFF6B7280), + height: 1.4, + ), + ), + Expanded( + child: Text( + text, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + height: 1.4, + color: Color(0xFF374151), + ), + ), + ), + ], + ), + ); + } +} + +class _MyBookingsTab extends StatelessWidget { + const _MyBookingsTab(); + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, provider, _) { + if (provider.isBookingsLoading) { + return const Center(child: CircularProgressIndicator()); + } + + if (provider.bookingsError != null) { + return Center( + child: Text( + 'Failed to load bookings:\n${provider.bookingsError}', + textAlign: TextAlign.center, + ), + ); + } + + final bookings = provider.myBookings; + if (bookings.isEmpty) { + return const Center(child: Text('No room cleaning bookings yet.')); + } + + return RefreshIndicator( + onRefresh: provider.loadMyBookings, + child: ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), + itemCount: bookings.length, + itemBuilder: (context, index) { + final booking = bookings[index]; + final dateLabel = + DateFormat('EEE, MMM d').format(booking.bookingDate); + final status = booking.status; + final hasFeedback = + booking.feedbackId != null && booking.feedbackId!.isNotEmpty; + + final statusColor = switch (status) { + 'Cleaned' => Colors.green, + 'Booked' || 'Buffered' => Colors.blue, + 'Cancelled' => Colors.grey, + 'CouldNotBeCleaned' => Colors.red, + _ => Colors.black, + }; + final statusLabel = + status == 'CouldNotBeCleaned' ? 'Not Cleaned' : status; + + final canCancel = booking.canCancel; + + String? subtitle; + if (status == 'Cleaned') { + subtitle = 'Room cleaning completed for this slot.'; + } else if (status == 'Cancelled') { + subtitle = 'You cancelled this booking.'; + } else if (status == 'CouldNotBeCleaned') { + final reason = booking.reason ?? ''; + switch (reason) { + case 'Student Did Not Respond': + subtitle = + 'The room cleaner couldn’t reach you during this slot (room was locked or you didn’t respond).'; + break; + case 'Student Asked To Cancel': + subtitle = 'You asked to cancel this room cleaning.'; + break; + case 'Room Cleaners Not Available': + subtitle = + 'Room cleaners weren’t available during this slot.'; + break; + default: + subtitle = 'This room cleaning could not be completed.'; + } + } + + return Container( + margin: const EdgeInsets.only(bottom: 14), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.04), + blurRadius: 10, + offset: const Offset(0, 2), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(16), + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Status accent bar + Container( + width: 4, + decoration: BoxDecoration( + color: statusColor, + borderRadius: const BorderRadius.horizontal( + left: Radius.circular(16), + ), + ), + ), + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + // Top row: date + status chip + Row( + crossAxisAlignment: + CrossAxisAlignment.center, + children: [ + Icon( + Icons.calendar_today_rounded, + size: 16, + color: const Color(0xFF6B7280), + ), + const SizedBox(width: 6), + Text( + dateLabel, + style: const TextStyle( + fontFamily: + 'OpenSans_regular', + fontWeight: FontWeight.w700, + fontSize: 15, + color: Color(0xFF111827), + ), + ), + const Spacer(), + Container( + padding: + const EdgeInsets.symmetric( + horizontal: 10, + vertical: 5, + ), + decoration: BoxDecoration( + color: statusColor + .withOpacity(0.14), + borderRadius: + BorderRadius.circular( + 999), + ), + child: Text( + statusLabel, + style: TextStyle( + fontFamily: + 'OpenSans_regular', + color: statusColor, + fontWeight: FontWeight.w600, + fontSize: 12, + ), + ), + ), + ], + ), + const SizedBox(height: 6), + Row( + children: [ + Icon( + Icons.schedule_rounded, + size: 16, + color: const Color(0xFF6B7280), + ), + const SizedBox(width: 6), + Text( + _slotTimeRange[booking.slot] ?? + 'Slot ${booking.slot}', + style: const TextStyle( + fontFamily: + 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + ], + ), + ], + ), + ), + if ((status == 'Cleaned' && !hasFeedback) || + canCancel) ...[ + const SizedBox(width: 12), + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: + CrossAxisAlignment.end, + children: [ + if (status == 'Cleaned' && + !hasFeedback) + OutlinedButton.icon( + onPressed: () async { + await _showFeedbackDialog( + context, booking.id); + }, + icon: const Icon( + Icons.rate_review_outlined, + size: 16, + ), + label: const Text( + 'Feedback', + style: TextStyle( + fontFamily: + 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 12, + ), + ), + style: OutlinedButton.styleFrom( + foregroundColor: + const Color(0xFF4C4EDB), + side: const BorderSide( + color: Color(0xFF4C4EDB), + ), + padding: + const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), + minimumSize: Size.zero, + tapTargetSize: + MaterialTapTargetSize + .shrinkWrap, + ), + ), + if (canCancel) + OutlinedButton.icon( + onPressed: () async { + final result = await Provider + .of( + context, + listen: false) + .cancelBooking(booking.id); + if (!context.mounted) return; + _showRoomCleaningSnackBar( + context, + result.message, + isError: !result.success, + ); + }, + icon: const Icon( + Icons.close_rounded, + size: 16, + ), + label: const Text( + 'Cancel', + style: TextStyle( + fontFamily: + 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 12, + ), + ), + style: OutlinedButton.styleFrom( + foregroundColor: + const Color(0xFF6B7280), + side: const BorderSide( + color: Color(0xFF9CA3AF), + ), + padding: + const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), + minimumSize: Size.zero, + tapTargetSize: + MaterialTapTargetSize + .shrinkWrap, + ), + ), + ], + ), + ], + ], + ), + if (subtitle != null) ...[ + const SizedBox(height: 10), + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + decoration: BoxDecoration( + color: const Color(0xFFF9FAFB), + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: const Color(0xFFF3F4F6), + ), + ), + child: Text( + subtitle, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + height: 1.4, + color: Color(0xFF6B7280), + ), + ), + ), + ], + ], + ), + ), + ), + ], + ), + ), + ), + ); + }, + ), + ); + }, + ); + } +} + +class _FeedbackChip extends StatelessWidget { + final String label; + final bool selected; + final VoidCallback onTap; + + const _FeedbackChip({ + required this.label, + required this.selected, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return Material( + color: Colors.transparent, + borderRadius: BorderRadius.circular(999), + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(999), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: selected ? const Color(0xFF4C4EDB) : Colors.white, + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: + selected ? const Color(0xFF4C4EDB) : const Color(0xFFE5E7EB), + width: selected ? 0 : 1, + ), + ), + child: Text( + label, + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 13, + color: selected ? Colors.white : const Color(0xFF6B7280), + ), + ), + ), + ), + ); + } +} + +Future _showFeedbackDialog( + BuildContext context, + String bookingId, +) async { + String reachedInSlot = 'Yes'; + String staffPoliteness = 'Yes'; + int satisfaction = 5; + final remarksController = TextEditingController(); + + final result = await showDialog( + context: context, + builder: (dialogContext) { + return StatefulBuilder( + builder: (context, setState) { + return AlertDialog( + backgroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + contentPadding: const EdgeInsets.fromLTRB(20, 20, 20, 8), + title: const Text( + 'Room cleaning feedback', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w700, + fontSize: 18, + color: Color(0xFF111827), + ), + ), + titlePadding: const EdgeInsets.fromLTRB(20, 20, 20, 0), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Did the staff visit during your selected slot?', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 10), + Wrap( + spacing: 10, + runSpacing: 8, + children: [ + for (final value in ['Yes', 'No']) + _FeedbackChip( + label: value, + selected: reachedInSlot == value, + onTap: () => setState(() => reachedInSlot = value), + ), + ], + ), + const SizedBox(height: 20), + const Text( + 'Was the staff polite and professional?', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 10), + Wrap( + spacing: 10, + runSpacing: 8, + children: [ + for (final value in ['Yes', 'No']) + _FeedbackChip( + label: value, + selected: staffPoliteness == value, + onTap: () => setState(() => staffPoliteness = value), + ), + ], + ), + const SizedBox(height: 20), + const Text( + 'Overall, how satisfied are you?', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 10), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: List.generate(5, (index) { + final value = index + 1; + final selected = satisfaction == value; + return GestureDetector( + onTap: () => setState(() => satisfaction = value), + child: Container( + width: 40, + height: 40, + alignment: Alignment.center, + decoration: BoxDecoration( + color: selected + ? const Color(0xFF4C4EDB) + : const Color(0xFFF3F4F6), + border: Border.all( + color: selected + ? const Color(0xFF4C4EDB) + : const Color(0xFFE5E7EB), + width: selected ? 0 : 1, + ), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + '$value', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 14, + fontWeight: + selected ? FontWeight.w600 : FontWeight.w500, + color: selected + ? Colors.white + : const Color(0xFF6B7280), + ), + ), + ), + ); + }), + ), + const SizedBox(height: 20), + const Text( + 'Additional comments (optional)', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + const SizedBox(height: 8), + TextField( + controller: remarksController, + maxLines: 3, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 14, + color: Color(0xFF111827), + ), + decoration: InputDecoration( + hintText: 'Anything else you would like us to know?', + hintStyle: const TextStyle( + fontFamily: 'OpenSans_regular', + color: Color(0xFF9CA3AF), + fontSize: 14, + ), + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 12, + ), + filled: true, + fillColor: Colors.white, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: Color(0xFFE5E7EB)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide(color: Color(0xFFE5E7EB)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide( + color: Color(0xFF4C4EDB), + width: 1.5, + ), + ), + ), + ), + ], + ), + ), + actionsPadding: const EdgeInsets.fromLTRB(20, 16, 20, 20), + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + style: TextButton.styleFrom( + foregroundColor: const Color(0xFF6B7280), + padding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + ), + child: const Text( + 'Skip', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + ), + const SizedBox(width: 8), + ElevatedButton( + onPressed: () => Navigator.of(dialogContext).pop(true), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + padding: + const EdgeInsets.symmetric(horizontal: 20, vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + elevation: 0, + ), + child: const Text( + 'Submit', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + ), + ], + ); + }, + ); + }, + ); + + if (result != true || !context.mounted) return; + + final provider = Provider.of(context, listen: false); + final action = await provider.submitFeedback( + bookingId: bookingId, + reachedInSlot: reachedInSlot, + staffPoliteness: staffPoliteness, + satisfaction: satisfaction, + remarks: remarksController.text, + ); + + _showRoomCleaningSnackBar( + context, + action.message, + isError: !action.success, + ); +} + +void _showRoomCleaningSnackBar( + BuildContext context, + String message, { + bool isError = false, +}) { + final theme = Theme.of(context); + final backgroundColor = isError + ? const Color(0xFFFFF1F2) + : const Color(0xFFECFEF3); // soft red / soft green + final borderColor = + isError ? const Color(0xFFDC2626) : const Color(0xFF16A34A); + final icon = isError ? Icons.error_outline : Icons.check_circle_outline; + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + behavior: SnackBarBehavior.floating, + backgroundColor: Colors.transparent, + elevation: 0, + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + content: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: borderColor), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Icon( + icon, + size: 20, + color: borderColor, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + message, + style: theme.textTheme.bodyMedium?.copyWith( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: const Color(0xFF111827), + ), + ), + ), + ], + ), + ), + ), + ); +} diff --git a/frontend2/lib/screens/settings_screen.dart b/frontend2/lib/screens/settings_screen.dart index 9a47ee95..119e8e59 100644 --- a/frontend2/lib/screens/settings_screen.dart +++ b/frontend2/lib/screens/settings_screen.dart @@ -1,9 +1,5 @@ import 'package:flutter/material.dart'; -import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:frontend2/apis/authentication/login.dart'; -import 'package:frontend2/apis/users/user.dart'; -import 'package:frontend2/screens/login_screen.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -72,273 +68,6 @@ class _SettingsScreenState extends State { ); } - void _showDeleteAccountDialog(BuildContext context) { - final TextEditingController confirmController = TextEditingController(); - bool isDeleting = false; - String? deleteErrorMessage; - - showDialog( - context: context, - barrierDismissible: false, - builder: (BuildContext dialogContext) { - return StatefulBuilder( - builder: (context, setState) { - return AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(14), - ), - title: const Text( - 'Delete Account', - style: TextStyle( - fontSize: 20, - fontWeight: FontWeight.w600, - ), - ), - content: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Text( - 'Are you sure you want to delete your account?', - style: TextStyle( - fontSize: 15, - color: Colors.black87, - height: 1.4, - ), - ), - const SizedBox(height: 20), - const Text( - 'This action will:', - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 12), - _buildBulletPoint( - 'Delete your profile and personal information'), - const SizedBox(height: 6), - _buildBulletPoint( - 'Anonymize your hostel and mess subscription data'), - const SizedBox(height: 6), - _buildBulletPoint( - 'Anonymize your historical feedback and scan logs'), - const SizedBox(height: 20), - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Icon( - Icons.warning_amber_rounded, - color: Colors.red[400], - size: 20, - ), - const SizedBox(width: 8), - Expanded( - child: Text( - 'This action cannot be undone.', - style: TextStyle( - fontSize: 14, - color: Colors.red[400], - fontWeight: FontWeight.w500, - ), - ), - ), - ], - ), - const SizedBox(height: 20), - const Text( - 'To confirm, please type "DELETE" below:', - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - ), - ), - const SizedBox(height: 10), - TextField( - controller: confirmController, - enabled: !isDeleting, - style: const TextStyle(fontSize: 15), - decoration: InputDecoration( - hintText: 'Type DELETE to confirm', - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(8), - ), - contentPadding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 12, - ), - ), - onChanged: (value) { - setState(() { - deleteErrorMessage = null; - }); - }, - ), - if (deleteErrorMessage != null) ...[ - const SizedBox(height: 8), - Text( - deleteErrorMessage!, - style: TextStyle( - fontSize: 12.5, - color: Colors.red[600], - height: 1.4, - ), - ), - ], - ], - ), - ), - actions: [ - TextButton( - onPressed: isDeleting - ? null - : () { - Navigator.of(dialogContext).pop(); - }, - child: Text( - 'Cancel', - style: TextStyle( - color: Colors.grey[700], - fontSize: 16, - fontWeight: FontWeight.w500, - ), - ), - ), - ElevatedButton( - onPressed: isDeleting || confirmController.text != 'DELETE' - ? null - : () async { - setState(() { - isDeleting = true; - }); - - try { - await deleteUserAccount(); - if (!dialogContext.mounted) return; - Navigator.of(dialogContext).pop(); - // Clear local data and logout - final prefs = await SharedPreferences.getInstance(); - await prefs.clear(); - if (!context.mounted) return; - Navigator.of(context).pushAndRemoveUntil( - MaterialPageRoute( - builder: (context) => const LoginScreen(), - ), - (route) => false, - ); - if (!context.mounted) return; - EasyLoading.showSuccess( - 'Account deleted successfully'); - } catch (e) { - setState(() { - isDeleting = false; - final rawMessage = e - .toString() - .replaceFirst('Exception: ', '') - .trim(); - - deleteErrorMessage = - 'Request failed. Please ensure the following:\n' - '- You do not have any active mess change requests.\n' - '- You are not an SMC member.'; - }); - if (!dialogContext.mounted) return; - debugPrint('Delete account error: $e'); - } - }, - style: ButtonStyle( - backgroundColor: WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.disabled)) { - return Colors.grey[300]!; - } - if (confirmController.text == 'DELETE') { - return Colors.red[400]!; - } - return Colors.grey[300]!; - }, - ), - foregroundColor: WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.disabled)) { - return Colors.grey[600]!; - } - if (confirmController.text == 'DELETE') { - return Colors.white; - } - return Colors.grey[600]!; - }, - ), - padding: WidgetStateProperty.all( - const EdgeInsets.symmetric(horizontal: 20, vertical: 12), - ), - shape: WidgetStateProperty.all( - RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - ), - ), - elevation: WidgetStateProperty.all(0), - ), - child: isDeleting - ? const SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator( - strokeWidth: 2.5, - valueColor: - AlwaysStoppedAnimation(Colors.white), - ), - ) - : const Text( - 'Delete Account', - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - ), - ), - ), - ], - ); - }, - ); - }, - ); - } - - Widget _buildBulletPoint(String text) { - return Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.only(top: 7, right: 12), - child: Container( - width: 6, - height: 6, - margin: const EdgeInsets.only(top: 0), - decoration: BoxDecoration( - color: Colors.grey[600], - shape: BoxShape.circle, - ), - ), - ), - Expanded( - child: Padding( - padding: const EdgeInsets.only(top: 0), - child: Text( - text, - style: const TextStyle( - fontSize: 14, - color: Colors.black87, - height: 1.4, - ), - ), - ), - ), - ], - ); - } - Future _openPrivacyPolicy() async { const url = 'https://hab.codingclub.in/privacy'; final uri = Uri.parse(url); @@ -496,46 +225,6 @@ class _SettingsScreenState extends State { ), ), - // Account Section - Padding( - padding: const EdgeInsets.only(top: 32, left: 16, right: 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: - const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Text( - 'Account', - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: Colors.grey[600], - letterSpacing: -0.5, - ), - ), - ), - Container( - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(10), - ), - child: ListTile( - leading: Icon(Icons.delete_outline, - size: 22, color: Colors.red[400]), - title: Text( - 'Delete Account', - style: TextStyle(color: Colors.red[400]), - ), - trailing: Icon(Icons.chevron_right, - color: Colors.grey[400], size: 20), - onTap: () => _showDeleteAccountDialog(context), - ), - ), - ], - ), - ), - // Logout Section Padding( padding: diff --git a/frontend2/lib/utilities/version_checker.dart b/frontend2/lib/utilities/version_checker.dart index cd5ab67d..81aaca03 100644 --- a/frontend2/lib/utilities/version_checker.dart +++ b/frontend2/lib/utilities/version_checker.dart @@ -127,8 +127,12 @@ class VersionChecker { // Pad with zeros if lengths differ final maxLength = v1Parts.length > v2Parts.length ? v1Parts.length : v2Parts.length; - while (v1Parts.length < maxLength) v1Parts.add(0); - while (v2Parts.length < maxLength) v2Parts.add(0); + while (v1Parts.length < maxLength) { + v1Parts.add(0); + } + while (v2Parts.length < maxLength) { + v2Parts.add(0); + } // Compare each part for (int i = 0; i < maxLength; i++) { @@ -138,8 +142,9 @@ class VersionChecker { return 0; // Equal } catch (e) { - if (kDebugMode) + if (kDebugMode) { debugPrint('Error comparing versions $version1 vs $version2: $e'); + } return 0; // Default to equal if error } } diff --git a/frontend2/lib/widgets/common/bottom_nav_bar.dart b/frontend2/lib/widgets/common/bottom_nav_bar.dart index fff3eb80..2afdcdb6 100644 --- a/frontend2/lib/widgets/common/bottom_nav_bar.dart +++ b/frontend2/lib/widgets/common/bottom_nav_bar.dart @@ -3,11 +3,14 @@ import 'package:flutter/material.dart'; class BottomNavBar extends StatelessWidget { final int currentIndex; final Function(int) onTap; + /// When false, only Home and Mess are shown; Gala Dinner tab is hidden. + final bool showGalaTab; const BottomNavBar({ super.key, required this.currentIndex, required this.onTap, + this.showGalaTab = true, }); @override @@ -98,6 +101,35 @@ class BottomNavBar extends StatelessWidget { ), ), ), + if (showGalaTab) + Expanded( + child: InkWell( + onTap: () { + onTap(2); + }, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.celebration, + size: 22, + color: currentIndex == 2 + ? const Color(0xFF4C4EDB) + : const Color(0xFF676767), + ), + const SizedBox(height: 3), + Text( + "Gala Dinner", + style: TextStyle( + fontSize: 12, + color: currentIndex == 2 + ? const Color(0xFF4C4EDB) + : const Color(0xFF676767)), + ) + ], + ), + ), + ), ], ), ), diff --git a/frontend2/macos/Flutter/GeneratedPluginRegistrant.swift b/frontend2/macos/Flutter/GeneratedPluginRegistrant.swift index 71cc0fe6..a595e77c 100644 --- a/frontend2/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/frontend2/macos/Flutter/GeneratedPluginRegistrant.swift @@ -19,7 +19,6 @@ import flutter_web_auth_2 import google_sign_in_ios import mobile_scanner import package_info_plus -import path_provider_foundation import shared_preferences_foundation import sign_in_with_apple import url_launcher_macos @@ -40,7 +39,6 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FLTGoogleSignInPlugin.register(with: registry.registrar(forPlugin: "FLTGoogleSignInPlugin")) MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) - PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SignInWithApplePlugin.register(with: registry.registrar(forPlugin: "SignInWithApplePlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) diff --git a/frontend2/pubspec.lock b/frontend2/pubspec.lock index 5f3ed86c..30428a46 100644 --- a/frontend2/pubspec.lock +++ b/frontend2/pubspec.lock @@ -81,6 +81,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" collection: dependency: transitive description: @@ -109,10 +117,10 @@ packages: dependency: transitive description: name: cross_file - sha256: "701dcfc06da0882883a2657c445103380e53e647060ad8d9dfb710c100996608" + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" url: "https://pub.dev" source: hosted - version: "0.3.5+1" + version: "0.3.5+2" crypto: dependency: transitive description: @@ -133,10 +141,10 @@ packages: dependency: transitive description: name: dbus - sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "0.7.12" desktop_webview_window: dependency: transitive description: @@ -165,10 +173,10 @@ packages: dependency: "direct main" description: name: dio - sha256: d90ee57923d1828ac14e492ca49440f65477f4bb1263575900be731a3dac66a9 + sha256: b9d46faecab38fc8cc286f80bc4d61a3bb5d4ac49e51ed877b4d6706efe57b25 url: "https://pub.dev" source: hosted - version: "5.9.0" + version: "5.9.1" dio_web_adapter: dependency: transitive description: @@ -213,10 +221,10 @@ packages: dependency: transitive description: name: ffi - sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.2.0" file: dependency: transitive description: @@ -504,6 +512,14 @@ packages: description: flutter source: sdk version: "0.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" google_identity_services_web: dependency: transitive description: @@ -568,6 +584,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "7a08a0d684cb3b8fb604b78455d5d352f502b68079f7b80b831c62220ab0a4f6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" http: dependency: "direct main" description: @@ -588,10 +612,10 @@ packages: dependency: transitive description: name: image - sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" + sha256: "492bd52f6c4fbb6ee41f781ff27765ce5f627910e1e0cbecfa3d9add5562604c" url: "https://pub.dev" source: hosted - version: "4.5.4" + version: "4.7.2" image_picker: dependency: "direct main" description: @@ -604,10 +628,10 @@ packages: dependency: transitive description: name: image_picker_android - sha256: "5e9bf126c37c117cf8094215373c6d561117a3cfb50ebc5add1a61dc6e224677" + sha256: "518a16108529fc18657a3e6dde4a043dc465d16596d20ab2abd49a4cac2e703d" url: "https://pub.dev" source: hosted - version: "0.8.13+10" + version: "0.8.13+13" image_picker_for_web: dependency: transitive description: @@ -620,10 +644,10 @@ packages: dependency: transitive description: name: image_picker_ios - sha256: "997d100ce1dda5b1ba4085194c5e36c9f8a1fb7987f6a36ab677a344cd2dc986" + sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 url: "https://pub.dev" source: hosted - version: "0.8.13+2" + version: "0.8.13+6" image_picker_linux: dependency: transitive description: @@ -668,10 +692,10 @@ packages: dependency: transitive description: name: json_annotation - sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + sha256: "805fa86df56383000f640384b282ce0cb8431f1a7a2396de92fb66186d8c57df" url: "https://pub.dev" source: hosted - version: "4.9.0" + version: "4.10.0" leak_tracker: dependency: transitive description: @@ -704,6 +728,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" lottie: dependency: "direct main" description: @@ -760,6 +792,14 @@ packages: url: "https://pub.dev" source: hosted version: "7.1.4" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "89e83885ba09da5fdf2cdacc8002a712ca238c28b7f717910b34bcd27b0d03ac" + url: "https://pub.dev" + source: hosted + version: "0.17.4" nested: dependency: transitive description: @@ -776,6 +816,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.5.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" package_info_plus: dependency: "direct main" description: @@ -828,10 +876,10 @@ packages: dependency: transitive description: name: path_provider_foundation - sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4" + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" url: "https://pub.dev" source: hosted - version: "2.5.1" + version: "2.6.0" path_provider_linux: dependency: transitive description: @@ -908,10 +956,10 @@ packages: dependency: transitive description: name: petitparser - sha256: "1a97266a94f7350d30ae522c0af07890c70b8e62c71e8e3920d1db4d23c057d1" + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" url: "https://pub.dev" source: hosted - version: "7.0.1" + version: "7.0.2" platform: dependency: transitive description: @@ -944,6 +992,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.5+1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" qr: dependency: transitive description: @@ -964,18 +1020,18 @@ packages: dependency: "direct main" description: name: shared_preferences - sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" url: "https://pub.dev" source: hosted - version: "2.5.3" + version: "2.5.4" shared_preferences_android: dependency: transitive description: name: shared_preferences_android - sha256: "46a46fd64659eff15f4638bbe19de43f9483f0e0bf024a9fb6b3582064bacc7b" + sha256: cbc40be9be1c5af4dab4d6e0de4d5d3729e6f3d65b89d21e1815d57705644a6f url: "https://pub.dev" source: hosted - version: "2.4.17" + version: "2.4.20" shared_preferences_foundation: dependency: transitive description: @@ -1049,10 +1105,10 @@ packages: dependency: transitive description: name: source_span - sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" url: "https://pub.dev" source: hosted - version: "1.10.1" + version: "1.10.2" stack_trace: dependency: transitive description: @@ -1129,10 +1185,10 @@ packages: dependency: transitive description: name: url_launcher_ios - sha256: cfde38aa257dae62ffe79c87fab20165dfdf6988c1d31b58ebf59b9106062aad + sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" url: "https://pub.dev" source: hosted - version: "6.3.6" + version: "6.4.1" url_launcher_linux: dependency: transitive description: @@ -1161,10 +1217,10 @@ packages: dependency: transitive description: name: url_launcher_web - sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.2" url_launcher_windows: dependency: transitive description: @@ -1193,10 +1249,10 @@ packages: dependency: transitive description: name: vector_graphics_compiler - sha256: d354a7ec6931e6047785f4db12a1f61ec3d43b207fc0790f863818543f8ff0dc + sha256: "201e876b5d52753626af64b6359cd13ac6011b80728731428fd34bc840f71c9b" url: "https://pub.dev" source: hosted - version: "1.1.19" + version: "1.1.20" vector_math: dependency: transitive description: @@ -1209,10 +1265,10 @@ packages: dependency: "direct main" description: name: vibration - sha256: "1fd51cb0f91c6d512734ca0e282dd87fbc7f389b6da5f03c77709ba2cf8fa901" + sha256: "3cbdf4c93b469ec27b212c8dd0c720f85acc1186a68d08b56087f4e32b4c8e20" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.1.6" vibration_platform_interface: dependency: transitive description: @@ -1286,5 +1342,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.9.0 <4.0.0" - flutter: ">=3.35.0" + dart: ">=3.10.3 <4.0.0" + flutter: ">=3.38.4" diff --git a/frontend2/pubspec.yaml b/frontend2/pubspec.yaml index e7cc7243..518edb72 100644 --- a/frontend2/pubspec.yaml +++ b/frontend2/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.1.0+15 +version: 2.2.0+11 environment: sdk: ^3.5.4 diff --git a/hab-frontend/package-lock.json b/hab-frontend/package-lock.json index 789a2525..77e37311 100644 --- a/hab-frontend/package-lock.json +++ b/hab-frontend/package-lock.json @@ -8,6 +8,7 @@ "name": "hab-frontend", "version": "0.0.0", "dependencies": { + "@ant-design/v5-patch-for-react-19": "^1.0.3", "@tailwindcss/vite": "^4.1.10", "antd": "^5.26.1", "axios": "^1.10.0", @@ -145,6 +146,20 @@ "react": ">=16.9.0" } }, + "node_modules/@ant-design/v5-patch-for-react-19": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@ant-design/v5-patch-for-react-19/-/v5-patch-for-react-19-1.0.3.tgz", + "integrity": "sha512-iWfZuSUl5kuhqLUw7jJXUQFMMkM7XpW7apmKzQBQHU0cpifYW4A79xIBt9YVO5IBajKpPG5UKP87Ft7Yrw1p/w==", + "license": "MIT", + "engines": { + "node": ">=12.x" + }, + "peerDependencies": { + "antd": ">=5.22.6", + "react": ">=19.0.0", + "react-dom": ">=19.0.0" + } + }, "node_modules/@babel/code-frame": { "version": "7.27.1", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", diff --git a/hab-frontend/package.json b/hab-frontend/package.json index 8872eb61..e94c3dca 100644 --- a/hab-frontend/package.json +++ b/hab-frontend/package.json @@ -10,6 +10,7 @@ "preview": "vite preview" }, "dependencies": { + "@ant-design/v5-patch-for-react-19": "^1.0.3", "@tailwindcss/vite": "^4.1.10", "antd": "^5.26.1", "axios": "^1.10.0", diff --git a/hab-frontend/src/App.jsx b/hab-frontend/src/App.jsx index 42fd7802..e158c1a3 100644 --- a/hab-frontend/src/App.jsx +++ b/hab-frontend/src/App.jsx @@ -8,6 +8,8 @@ import Students from "./pages/Students"; import HostelForm from "./pages/HostelForm"; import HostelPage from "./pages/HostelPage"; import MessChangePage from "./pages/MessChangePage.jsx"; +import GalaDinnerPage from "./pages/GalaDinnerPage.jsx"; +import GalaDinnerDetailPage from "./pages/GalaDinnerDetailPage.jsx"; import Notifications from "./pages/Notifications.jsx"; import CreateMess from "./components/CreateMess"; import MessDetails from "./components/MessDetails"; @@ -77,6 +79,14 @@ function App() { path="/mess/changeapplication" element={} /> + } + /> + } + /> {/** Allocate Hostel and Profile Settings moved into Students page; routes removed */} {/* Feedback Control page removed from router (now embedded in Caterers when needed) */} {/** Feedback Leaderboard merged into Caterers; route removed */} diff --git a/hab-frontend/src/components/Sidebar.jsx b/hab-frontend/src/components/Sidebar.jsx index 80365a88..8123d6cb 100644 --- a/hab-frontend/src/components/Sidebar.jsx +++ b/hab-frontend/src/components/Sidebar.jsx @@ -11,6 +11,7 @@ import { SettingOutlined, BookOutlined, NotificationOutlined, + GiftOutlined, } from "@ant-design/icons"; const Sidebar = ({ collapsed = false, onToggle }) => { @@ -27,7 +28,12 @@ const Sidebar = ({ collapsed = false, onToggle }) => { path: "/mess/changeapplication", icon: , }, - // Feedback Control removed from sidebar per request + { + key: "6", + name: "Gala Dinner", + path: "/gala-dinner", + icon: , + }, { key: "7", name: "Send Notifications", diff --git a/hab-frontend/src/main.jsx b/hab-frontend/src/main.jsx index b9a1a6de..4f0bd5c0 100644 --- a/hab-frontend/src/main.jsx +++ b/hab-frontend/src/main.jsx @@ -1,3 +1,4 @@ +import '@ant-design/v5-patch-for-react-19' import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import './index.css' diff --git a/hab-frontend/src/pages/GalaDinnerDetailPage.jsx b/hab-frontend/src/pages/GalaDinnerDetailPage.jsx new file mode 100644 index 00000000..f7ceb41e --- /dev/null +++ b/hab-frontend/src/pages/GalaDinnerDetailPage.jsx @@ -0,0 +1,204 @@ +import React, { useState, useEffect, useMemo } from "react"; +import { useParams, useNavigate } from "react-router-dom"; +import { BACKEND_URL } from "../apis/server"; +import { Typography, Select, Card, Row, Col, Statistic, Spin, Button } from "antd"; +import { ArrowLeftOutlined } from "@ant-design/icons"; +import dayjs from "dayjs"; + +const { Title, Text } = Typography; + +function formatTimeDisplay(str) { + if (!str || typeof str !== "string") return "—"; + const match = str.trim().match(/^(\d{1,2}):(\d{2})$/); + if (!match) return str; + const h = parseInt(match[1], 10); + const m = match[2]; + const h12 = h % 12 || 12; + const ampm = h < 12 ? "AM" : "PM"; + return `${h12}:${m} ${ampm}`; +} + +export default function GalaDinnerDetailPage() { + const { galaDinnerId } = useParams(); + const navigate = useNavigate(); + const token = + localStorage.getItem("admin_token") || localStorage.getItem("token"); + const authHeaders = useMemo( + () => (token ? { Authorization: `Bearer ${token}` } : {}), + [token] + ); + + const [hostels, setHostels] = useState([]); + const [hostelsLoading, setHostelsLoading] = useState(true); + const [selectedHostelId, setSelectedHostelId] = useState(null); + const [detail, setDetail] = useState(null); + const [detailLoading, setDetailLoading] = useState(false); + + useEffect(() => { + const fetchHostels = async () => { + try { + setHostelsLoading(true); + const response = await fetch(`${BACKEND_URL}/hostel/allhostel`, { + headers: { ...authHeaders }, + }); + if (!response.ok) throw new Error("Fetch failed"); + const data = await response.json(); + setHostels(Array.isArray(data) ? data : []); + if (data?.length > 0 && !selectedHostelId) { + setSelectedHostelId(data[0]._id); + } + } catch (err) { + console.error("Failed to fetch hostels:", err); + setHostels([]); + } finally { + setHostelsLoading(false); + } + }; + fetchHostels(); + }, [token]); + + useEffect(() => { + if (!galaDinnerId || !selectedHostelId) { + setDetail(null); + return; + } + const fetchDetail = async () => { + try { + setDetailLoading(true); + const response = await fetch( + `${BACKEND_URL}/gala/${galaDinnerId}/detail?hostelId=${selectedHostelId}`, + { headers: { ...authHeaders } } + ); + if (!response.ok) throw new Error("Fetch failed"); + const data = await response.json(); + setDetail(data); + } catch (err) { + console.error("Failed to fetch detail:", err); + setDetail(null); + } finally { + setDetailLoading(false); + } + }; + fetchDetail(); + }, [galaDinnerId, selectedHostelId, token]); + + const hostelOptions = hostels.map((h) => ({ + value: h._id, + label: h.hostel_name || h._id, + })); + + return ( +
+
+ +
+ +
+ + Gala Dinner Details + +
+ Hostel: + setSecretaryEmail(e.target.value)} + placeholder="secretary@iitg.ac.in" + className="w-full border border-gray-300 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" + /> +

+ Optional: email of the hostel secretary for reference and contact. +

+
+ +
+ + setHostelPassword(e.target.value)} + required + className="w-full border border-gray-300 rounded-md px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500" + /> +

+ This password will be used by the hostel in HABit HQ. It is stored + securely (hashed) on the server. +

+
+
)} - {activeTab === "caterer" && ( + {activeTab === "boarders" && ( -
-
-

- Caterer Information -

-
- - {loading ? ( -
-
-
- ) : catererInfo ? ( -
- {/* Info rows similar to HostelPage details */} -
-
-
- Caterer -
-
- {catererInfo.catererName || "N/A"} -
-
-
-
- Hostel -
-
- {catererInfo.hostelName || "N/A"} -
-
-
-
- Rating -
-
- {catererInfo.rating ?? "N/A"} -
-
-
- -
-
-
Contact
-
- {catererInfo.contact || "N/A"} -
-
-
-
Address
-
- {catererInfo.address || "N/A"} -
-
-
-
- Complaints -
-
- {(catererInfo.complaints && - catererInfo.complaints.length) || - 0} -
-
-
-
- ) : ( -

No caterer assigned

+
+

Boarders

+ {boarders.length > 0 && ( + )}
- - )} - - {activeTab === "boarders" && ( - -

Boarders

{loading ? (
@@ -359,6 +515,9 @@ const Dashboard = () => { Email + + Phone Number + Room Number @@ -379,6 +538,9 @@ const Dashboard = () => { {boarder.email} + + {boarder.phoneNumber} + {boarder.roomNumber} @@ -396,80 +558,427 @@ const Dashboard = () => { {activeTab === "subscribers" && ( -

Mess Subscribers

+
+

Mess Subscribers

+ {messSubscribers.length > 0 && ( + + )} +
{loading ? (
) : ( -
- - - - - - - - - - - - {messSubscribers.map((sub) => ( - - - - - - +
+ {/* Caterer info summary for this mess */} +
+
+
+ Caterer +
+
+ {user?.hostel_name || "Hostel"} Mess +
+
+ {Array.isArray(messSubscribers) && + messSubscribers.length > 0 && ( +
+
+
+ Rating +
+
+ {messSubscribers[0].rating ?? "N/A"} +
+
+
+
+ Ranking +
+
+ {messSubscribers[0].ranking ?? "N/A"} +
+
+
+ )} +
+ +
+
- Name - - Roll Number - - Current Hostel - - Subscribed Mess - - Room Number -
- {sub.name} - - {sub.rollNumber} - - {sub.currentHostel} - {sub.isDifferentHostel && ( - ⚠️ - )} - - {sub.currentSubscribedMess} - - {sub.roomNumber} -
+ + + + + + + - ))} - -
+ Name + + Roll Number + + Current Hostel + + Subscribed Mess + + Phone Number +
+ + + {messSubscribers.map((sub) => ( + + + {sub.name} + + + {sub.rollNumber} + + + {sub.currentHostel} + {sub.isDifferentHostel && ( + + ⚠️ + + )} + + + {sub.currentSubscribedMess} + + + {sub.phoneNumber} + + + ))} + + +
)}
)} - {activeTab === "bill" && user && ( - - )} + {activeTab === "cleaners" && ( + +
+
+

+ Room Cleaners +

+ +
+ + {cleanerFormOpen && ( +
+
+

+ {editingCleanerId ? "Edit Cleaner" : "Add New Cleaner"} +

+ +
+ +
+
+ + setNewCleanerName(e.target.value)} + /> +
+ +
+ +
+ {["A", "B", "C", "D"].map((slot) => ( + + ))} +
+
+ +
+ + +
+
+
+ )} + + {loading && cleaners.length === 0 ? ( +
+
+
+ ) : cleaners.length === 0 ? ( +

+ No cleaners configured yet. Click “Add Cleaner” to create + the first cleaner. +

+ ) : ( +
+
+
+ + +
+
- {activeTab === "notifications" && } + {selectedCleaner && ( +
+
+
+
+ {selectedCleaner.name} +
+
+ Slots:{" "} + {Array.isArray(selectedCleaner.slots) && + selectedCleaner.slots.length > 0 + ? selectedCleaner.slots + .slice() + .sort() + .join(", ") + : "—"} +
+
+
+ + +
+
+
+ )} + +
+
+
+
+ Assigned bookings +
+
+ Shows bookings assigned to the selected cleaner for the chosen date. +
+
+
+ + +
+
+ + {rcBookingsLoading ? ( +
+
+
+ ) : rcBookingsError ? ( +

{rcBookingsError}

+ ) : !selectedCleanerId ? ( +

+ Select a cleaner to view bookings. +

+ ) : bookingsForCleaner.length === 0 ? ( +

+ No bookings assigned to this cleaner for {bookingsDate}. +

+ ) : ( +
+ + + + + + + + + + {bookingsForCleaner.map((b) => ( + + + + + + ))} + +
+ Room + + Slot + + Status +
+ {b.roomNumber || "—"} + + {b.timeRange || `Slot ${b.slot || "—"}`} + + {b.status || "—"} +
+
+ )} +
+
+ )} +
+ + )} {activeTab === "smc" && ( -

SMC Management

+
+

SMC Management

+ setSmcSearch(e.target.value)} + placeholder="Search by name or roll..." + className="w-64 px-3 py-1.5 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" + /> +
{loading ? (
@@ -499,7 +1008,16 @@ const Dashboard = () => { - {smcMembers.map((member) => ( + {smcMembers + .filter((member) => { + if (!smcSearch.trim()) return true; + const q = smcSearch.toLowerCase(); + return ( + member.name?.toLowerCase().includes(q) || + member.rollNumber?.toLowerCase().includes(q) + ); + }) + .map((member) => ( {member.name} @@ -519,7 +1037,7 @@ const Dashboard = () => { - ))} + ))}
@@ -548,10 +1066,18 @@ const Dashboard = () => { {boarders - .filter( - (b) => - !smcMembers.find((smc) => smc._id === b._id) - ) + .filter((b) => { + const notSmc = !smcMembers.find( + (smc) => smc._id === b._id + ); + if (!notSmc) return false; + if (!smcSearch.trim()) return true; + const q = smcSearch.toLowerCase(); + return ( + b.name?.toLowerCase().includes(q) || + b.rollNumber?.toLowerCase().includes(q) + ); + }) .map((boarder) => ( diff --git a/mess_frontend/.gitignore b/mess_frontend/.gitignore new file mode 100644 index 00000000..3820a95c --- /dev/null +++ b/mess_frontend/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/mess_frontend/.metadata b/mess_frontend/.metadata new file mode 100644 index 00000000..41a19796 --- /dev/null +++ b/mess_frontend/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "8b872868494e429d94fa06dca855c306438b22c0" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: android + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: ios + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: linux + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: macos + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: web + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: windows + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/mess_frontend/README.md b/mess_frontend/README.md new file mode 100644 index 00000000..9e05ed03 --- /dev/null +++ b/mess_frontend/README.md @@ -0,0 +1,16 @@ +# mess_frontend + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/mess_frontend/analysis_options.yaml b/mess_frontend/analysis_options.yaml new file mode 100644 index 00000000..0d290213 --- /dev/null +++ b/mess_frontend/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/mess_frontend/android/.gitignore b/mess_frontend/android/.gitignore new file mode 100644 index 00000000..be3943c9 --- /dev/null +++ b/mess_frontend/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/mess_frontend/android/.kotlin/sessions/kotlin-compiler-11073426253774034954.salive b/mess_frontend/android/.kotlin/sessions/kotlin-compiler-11073426253774034954.salive new file mode 100644 index 00000000..e69de29b diff --git a/mess_frontend/android/app/build.gradle.kts b/mess_frontend/android/app/build.gradle.kts new file mode 100644 index 00000000..21a70be9 --- /dev/null +++ b/mess_frontend/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.mess_frontend" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.mess_frontend" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/mess_frontend/android/app/src/debug/AndroidManifest.xml b/mess_frontend/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000..399f6981 --- /dev/null +++ b/mess_frontend/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/mess_frontend/android/app/src/main/AndroidManifest.xml b/mess_frontend/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..7101d9e7 --- /dev/null +++ b/mess_frontend/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/mess_frontend/android/app/src/main/kotlin/com/example/mess_frontend/MainActivity.kt b/mess_frontend/android/app/src/main/kotlin/com/example/mess_frontend/MainActivity.kt new file mode 100644 index 00000000..ae3e0307 --- /dev/null +++ b/mess_frontend/android/app/src/main/kotlin/com/example/mess_frontend/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.mess_frontend + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/mess_frontend/android/app/src/main/res/drawable-v21/launch_background.xml b/mess_frontend/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 00000000..f74085f3 --- /dev/null +++ b/mess_frontend/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/mess_frontend/android/app/src/main/res/drawable/launch_background.xml b/mess_frontend/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 00000000..304732f8 --- /dev/null +++ b/mess_frontend/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/mess_frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/mess_frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..a8436a5d Binary files /dev/null and b/mess_frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/mess_frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/mess_frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..184d8452 Binary files /dev/null and b/mess_frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/mess_frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/mess_frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..8ff1368a Binary files /dev/null and b/mess_frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/mess_frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/mess_frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..618794dc Binary files /dev/null and b/mess_frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/mess_frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/mess_frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..46ddbdde Binary files /dev/null and b/mess_frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/mess_frontend/android/app/src/main/res/values-night/styles.xml b/mess_frontend/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 00000000..06952be7 --- /dev/null +++ b/mess_frontend/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/mess_frontend/android/app/src/main/res/values/styles.xml b/mess_frontend/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..cb1ef880 --- /dev/null +++ b/mess_frontend/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/mess_frontend/android/app/src/profile/AndroidManifest.xml b/mess_frontend/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 00000000..399f6981 --- /dev/null +++ b/mess_frontend/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/mess_frontend/android/build.gradle.kts b/mess_frontend/android/build.gradle.kts new file mode 100644 index 00000000..dbee657b --- /dev/null +++ b/mess_frontend/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/mess_frontend/android/gradle.properties b/mess_frontend/android/gradle.properties new file mode 100644 index 00000000..fbee1d8c --- /dev/null +++ b/mess_frontend/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/mess_frontend/android/gradle/wrapper/gradle-wrapper.properties b/mess_frontend/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..e4ef43fb --- /dev/null +++ b/mess_frontend/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/mess_frontend/android/settings.gradle.kts b/mess_frontend/android/settings.gradle.kts new file mode 100644 index 00000000..ca7fe065 --- /dev/null +++ b/mess_frontend/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/mess_frontend/assets/icon/Handlogo.png b/mess_frontend/assets/icon/Handlogo.png new file mode 100644 index 00000000..2cc4e58c Binary files /dev/null and b/mess_frontend/assets/icon/Handlogo.png differ diff --git a/mess_frontend/assets/sounds/scan.wav b/mess_frontend/assets/sounds/scan.wav new file mode 100644 index 00000000..f118ac5d Binary files /dev/null and b/mess_frontend/assets/sounds/scan.wav differ diff --git a/mess_frontend/ios/.gitignore b/mess_frontend/ios/.gitignore new file mode 100644 index 00000000..7a7f9873 --- /dev/null +++ b/mess_frontend/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/mess_frontend/ios/Flutter/AppFrameworkInfo.plist b/mess_frontend/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 00000000..1dc6cf76 --- /dev/null +++ b/mess_frontend/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 13.0 + + diff --git a/mess_frontend/ios/Flutter/Debug.xcconfig b/mess_frontend/ios/Flutter/Debug.xcconfig new file mode 100644 index 00000000..ec97fc6f --- /dev/null +++ b/mess_frontend/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/mess_frontend/ios/Flutter/Release.xcconfig b/mess_frontend/ios/Flutter/Release.xcconfig new file mode 100644 index 00000000..c4855bfe --- /dev/null +++ b/mess_frontend/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/mess_frontend/ios/Podfile b/mess_frontend/ios/Podfile new file mode 100644 index 00000000..620e46eb --- /dev/null +++ b/mess_frontend/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '13.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/mess_frontend/ios/Podfile.lock b/mess_frontend/ios/Podfile.lock new file mode 100644 index 00000000..ebac1028 --- /dev/null +++ b/mess_frontend/ios/Podfile.lock @@ -0,0 +1,23 @@ +PODS: + - Flutter (1.0.0) + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - Flutter (from `Flutter`) + - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + shared_preferences_foundation: + :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + +SPEC CHECKSUMS: + Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 + shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb + +PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e + +COCOAPODS: 1.16.2 diff --git a/mess_frontend/ios/Runner.xcodeproj/project.pbxproj b/mess_frontend/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..6404cb1d --- /dev/null +++ b/mess_frontend/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,731 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 627E4D44C394EEBBA51DB830 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6DB901E43BBDBF231657711D /* Pods_RunnerTests.framework */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + DB4A56BCA63157A1D0ED6E53 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DBD920BFD5A9EAC29B3616A /* Pods_Runner.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 1DBD920BFD5A9EAC29B3616A /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2DE56D06C9FE8D417AB48DA7 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 5FCD7C811139487A735220F7 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 6DB901E43BBDBF231657711D /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 712381E3ECA7941A1FFC90C3 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 948B4826AFEADF68F46B6065 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + B6D7A3E19024E422CD3DEE03 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + F95AB029FBBC11DD9AF90C5E /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + DB4A56BCA63157A1D0ED6E53 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C76EB07175EAFADB6E3F41FF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 627E4D44C394EEBBA51DB830 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2E77C3734FF4103A9935A376 /* Pods */ = { + isa = PBXGroup; + children = ( + 2DE56D06C9FE8D417AB48DA7 /* Pods-Runner.debug.xcconfig */, + 5FCD7C811139487A735220F7 /* Pods-Runner.release.xcconfig */, + 948B4826AFEADF68F46B6065 /* Pods-Runner.profile.xcconfig */, + F95AB029FBBC11DD9AF90C5E /* Pods-RunnerTests.debug.xcconfig */, + 712381E3ECA7941A1FFC90C3 /* Pods-RunnerTests.release.xcconfig */, + B6D7A3E19024E422CD3DEE03 /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + 314EDD2B42D100E6333B85AA /* Frameworks */ = { + isa = PBXGroup; + children = ( + 1DBD920BFD5A9EAC29B3616A /* Pods_Runner.framework */, + 6DB901E43BBDBF231657711D /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 2E77C3734FF4103A9935A376 /* Pods */, + 314EDD2B42D100E6333B85AA /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 7BA02D0A26A70A3518631134 /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + C76EB07175EAFADB6E3F41FF /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 280BB0F5591524EEEA14BCD5 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + BD915759282617B60E56C56D /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 280BB0F5591524EEEA14BCD5 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 7BA02D0A26A70A3518631134 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; + BD915759282617B60E56C56D /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 52G3FPFMR8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F95AB029FBBC11DD9AF90C5E /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 712381E3ECA7941A1FFC90C3 /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B6D7A3E19024E422CD3DEE03 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 52G3FPFMR8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 52G3FPFMR8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/mess_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/mess_frontend/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/mess_frontend/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..e3773d42 --- /dev/null +++ b/mess_frontend/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mess_frontend/ios/Runner.xcworkspace/contents.xcworkspacedata b/mess_frontend/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..21a3cc14 --- /dev/null +++ b/mess_frontend/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/mess_frontend/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mess_frontend/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/mess_frontend/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mess_frontend/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/mess_frontend/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/mess_frontend/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/mess_frontend/ios/Runner/AppDelegate.swift b/mess_frontend/ios/Runner/AppDelegate.swift new file mode 100644 index 00000000..62666446 --- /dev/null +++ b/mess_frontend/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..d0d98aa1 --- /dev/null +++ b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1 @@ +{"images":[{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@3x.png","scale":"3x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@3x.png","scale":"3x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@3x.png","scale":"3x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@1x.png","scale":"1x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@3x.png","scale":"3x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@1x.png","scale":"1x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@1x.png","scale":"1x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@1x.png","scale":"1x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@2x.png","scale":"2x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@1x.png","scale":"1x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@2x.png","scale":"2x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@1x.png","scale":"1x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@2x.png","scale":"2x"},{"size":"83.5x83.5","idiom":"ipad","filename":"Icon-App-83.5x83.5@2x.png","scale":"2x"},{"size":"1024x1024","idiom":"ios-marketing","filename":"Icon-App-1024x1024@1x.png","scale":"1x"}],"info":{"version":1,"author":"xcode"}} \ No newline at end of file diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 00000000..f0faa489 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 00000000..6aad567e Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 00000000..e6be850e Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 00000000..ebbbfa98 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 00000000..be5099f7 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 00000000..c03b6fbb Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 00000000..882cef43 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 00000000..e6be850e Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 00000000..d0c36219 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 00000000..c1c88235 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 00000000..88be13f2 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 00000000..837927c9 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 00000000..32c20d2e Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 00000000..d591b415 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 00000000..c1c88235 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 00000000..3125eab8 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 00000000..a8436a5d Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 00000000..618794dc Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 00000000..bc612080 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 00000000..230587d4 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 00000000..d3fcf250 Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 00000000..0bedcf2f --- /dev/null +++ b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 00000000..89c2725b --- /dev/null +++ b/mess_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/mess_frontend/ios/Runner/Base.lproj/LaunchScreen.storyboard b/mess_frontend/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..f2e259c7 --- /dev/null +++ b/mess_frontend/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mess_frontend/ios/Runner/Base.lproj/Main.storyboard b/mess_frontend/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 00000000..f3c28516 --- /dev/null +++ b/mess_frontend/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mess_frontend/ios/Runner/Info.plist b/mess_frontend/ios/Runner/Info.plist new file mode 100644 index 00000000..670a863a --- /dev/null +++ b/mess_frontend/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + HABit HQ + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + HABit HQ + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/mess_frontend/ios/Runner/Runner-Bridging-Header.h b/mess_frontend/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 00000000..308a2a56 --- /dev/null +++ b/mess_frontend/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/mess_frontend/ios/RunnerTests/RunnerTests.swift b/mess_frontend/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..86a7c3b1 --- /dev/null +++ b/mess_frontend/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/mess_frontend/lib/apis/manager_api.dart b/mess_frontend/lib/apis/manager_api.dart new file mode 100644 index 00000000..cb43eeec --- /dev/null +++ b/mess_frontend/lib/apis/manager_api.dart @@ -0,0 +1,126 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; + +import '../constants/endpoint.dart'; + +class ManagerApi { + ManagerApi._(); + + /// Shared Dio client with verbose logging to help debug real-device issues. + static final Dio _dio = Dio() + ..interceptors.add( + LogInterceptor( + request: true, + requestBody: true, + responseBody: true, + responseHeader: false, + error: true, + logPrint: (obj) => debugPrint('[DIO] $obj'), + ), + ); + + static Map _authHeaders(String token) => { + 'Authorization': 'Bearer $token', + }; + + static Future> fetchHostels() async { + debugPrint( + '[ManagerApi] Fetching hostels from ${HostelEndpoints.allHostels} ...'); + try { + final response = await _dio.get(HostelEndpoints.allHostels); + debugPrint( + '[ManagerApi] /hostel/all -> status=${response.statusCode}, dataType=${response.data.runtimeType}'); + final data = response.data as List; + final hostels = data + .map((raw) => (raw as Map)['hostel_name'] as String) + .toList(); + debugPrint('[ManagerApi] Parsed ${hostels.length} hostels: $hostels'); + return hostels; + } catch (e, st) { + debugPrint('[ManagerApi] fetchHostels error: $e'); + debugPrint('[ManagerApi] fetchHostels stack: $st'); + rethrow; + } + } + + static Future> loginManager({ + required String hostelName, + required String password, + }) async { + debugPrint( + '[ManagerApi] Login manager: hostel=$hostelName url=${AuthEndpoints.managerLogin}'); + final response = await _dio.post( + AuthEndpoints.managerLogin, + data: { + 'hostelName': hostelName, + 'password': password, + }, + ); + debugPrint( + '[ManagerApi] /auth/manager/login -> status=${response.statusCode}, data=${response.data}'); + return response.data as Map; + } + + static Future> fetchTodayMessSummary( + String token, + ) async { + final response = await _dio.get( + MessManagerEndpoints.todaySummary, + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + static Future> fetchGalaSummary(String token) async { + final response = await _dio.get( + GalaManagerEndpoints.summary, + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + static Future hasTodayGala(String token) async { + final data = await fetchGalaSummary(token); + return data['galaDinner'] != null; + } + + static Future> fetchUserProfileForManager({ + required String token, + required String userId, + }) async { + final response = await _dio.get( + MessManagerEndpoints.userProfile(userId), + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + static Future fetchUserProfilePictureForManager({ + required String token, + required String userId, + }) async { + final response = await _dio.get>( + MessManagerEndpoints.userProfilePicture(userId), + options: Options( + headers: _authHeaders(token), + responseType: ResponseType.bytes, + validateStatus: (code) => code != null && code < 500, + ), + ); + + if (response.statusCode == 200) { + // If server returned JSON instead of bytes, skip. + final contentType = response.headers.value('content-type') ?? ''; + if (contentType.contains('application/json')) { + return null; + } + final data = response.data; + if (data == null) return null; + return Uint8List.fromList(data); + } + + // 404 or 403 etc. → treat as no picture. + return null; + } +} + diff --git a/mess_frontend/lib/constants/endpoint.dart b/mess_frontend/lib/constants/endpoint.dart new file mode 100644 index 00000000..b7970143 --- /dev/null +++ b/mess_frontend/lib/constants/endpoint.dart @@ -0,0 +1,33 @@ +// Base API URL for the mess manager app. +// Point this at the same gateway the main app uses. +const String baseUrl = 'https://hab.codingclub.in/api'; + +class AuthEndpoints { + static const String managerLogin = '$baseUrl/auth/manager/login'; +} + +class HostelEndpoints { + static const String allHostels = '$baseUrl/hostel/all'; +} + +class GalaManagerEndpoints { + static const String summary = '$baseUrl/gala/manager/summary'; + + // WebSocket endpoint for live Gala scan logs (to be implemented server-side). + static String wsUrl(String token) => + 'wss://hab.codingclub.in/api/gala/manager/scan-logs?token=$token'; +} + +class MessManagerEndpoints { + static const String todaySummary = '$baseUrl/logs/manager/today'; + static String userProfile(String userId) => '$baseUrl/users/manager/$userId'; + static String userProfilePicture(String userId) => + '$baseUrl/profile/picture/manager/$userId'; + static String mealScanLogsWs(String meal, String token) => + 'wss://hab.codingclub.in/api/mess/manager/scan-logs?meal=$meal&token=$token'; +} + +class HqAppVersionEndpoints { + // HABit HQ (manager app) Android version info + static const String getAndroidVersion = '$baseUrl/hq-app-version/android'; +} diff --git a/mess_frontend/lib/constants/themes.dart b/mess_frontend/lib/constants/themes.dart new file mode 100644 index 00000000..6a88062c --- /dev/null +++ b/mess_frontend/lib/constants/themes.dart @@ -0,0 +1,120 @@ +import 'package:flutter/material.dart'; + +class Themes { + static const kYellow = Color.fromRGBO(254, 207, 111, 1); + static final theme = ThemeData( + useMaterial3: true, + primaryColor: kYellow, + scaffoldBackgroundColor: Colors.white, + fontFamily: 'ProximaNova', + splashColor: kYellow, + textTheme: const TextTheme( + labelMedium: TextStyle( + color: Colors.white, + fontWeight: FontWeight.w800, + fontSize: 16, + ), + labelSmall: TextStyle( + fontSize: 14.0, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + displayLarge: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.white, + fontSize: 28, + ), + displayMedium: TextStyle( + fontWeight: FontWeight.w800, + color: Colors.white, + fontSize: 24, + ), + displaySmall: TextStyle( + fontSize: 20.0, + fontWeight: FontWeight.w400, + color: Colors.white, + ), + bodySmall: TextStyle( + fontWeight: FontWeight.w400, + color: Colors.white, + fontSize: 12, + ), + bodyMedium: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + bodyLarge: TextStyle( + fontSize: 20.0, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + colorScheme: ColorScheme.fromSwatch().copyWith( + secondary: Colors.black, + ), + ); + + static const darkTextTheme = TextTheme( + displayMedium: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 18.0, + ), + displayLarge: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 24.0, + ), + displaySmall: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 12.0, + ), + bodyMedium: TextStyle( + fontWeight: FontWeight.w400, + color: Colors.black, + fontSize: 14.0, + ), + bodySmall: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w400, + color: Colors.black, + ), + labelSmall: TextStyle( + fontWeight: FontWeight.w800, + color: Colors.black, + fontSize: 10.0, + ), + labelLarge: TextStyle( + fontFamily: "ProximaNova", + fontSize: 16, + fontWeight: FontWeight.w700, + color: Colors.black, + ), + labelMedium: TextStyle( + fontWeight: FontWeight.w800, + color: Colors.black, + fontSize: 14.0, + ), + bodyLarge: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 14.0, + ), + ); + + static const feedbackColor = Color.fromRGBO(46, 47, 49, 1); +} + +const List habitColors = [ + Color.fromRGBO(219, 206, 255, 1), + Color.fromRGBO(219, 206, 255, 1), + Color.fromRGBO(255, 167, 212, 1), + Color.fromRGBO(255, 167, 212, 1), + Color.fromRGBO(111, 143, 254, 1), + Color.fromRGBO(111, 143, 254, 1), + Color.fromRGBO(237, 244, 146, 1), + Color.fromRGBO(237, 244, 146, 1), +]; + diff --git a/mess_frontend/lib/main.dart b/mess_frontend/lib/main.dart new file mode 100644 index 00000000..de048c38 --- /dev/null +++ b/mess_frontend/lib/main.dart @@ -0,0 +1,2725 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +import 'apis/manager_api.dart'; +import 'constants/endpoint.dart'; +import 'constants/themes.dart'; +import 'utilities/hq_version_checker.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Check device type and app version on startup (same flow as frontend2) + await HqVersionChecker.init(); + final bool updateRequired = await HqVersionChecker.checkForUpdate(); + + runApp(MessManagerApp(updateRequired: updateRequired)); +} + +// ---- App root (same pattern as frontend2 MyApp) ---- + +class MessManagerApp extends StatelessWidget { + final bool updateRequired; + + const MessManagerApp({super.key, required this.updateRequired}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'HABit HQ', + theme: Themes.theme.copyWith( + inputDecorationTheme: const InputDecorationTheme( + filled: true, + fillColor: Color(0xFFF9FAFB), + border: OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(12)), + borderSide: BorderSide(color: Color(0xFFE5E7EB)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(12)), + borderSide: BorderSide(color: Color(0xFFE5E7EB)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(12)), + borderSide: BorderSide(color: Color(0xFF4C4EDB), width: 1.5), + ), + hintStyle: TextStyle(color: Color(0xFF6B7280), fontSize: 14), + ), + ), + home: updateRequired + ? const UpdateRequiredScreen() + : const MessManagerLoginScreen(), + ); + } +} + +// ---- Update required screen (same UI as frontend2 UpdateRequiredScreen) ---- + +class UpdateRequiredScreen extends StatelessWidget { + const UpdateRequiredScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + width: double.infinity, + height: double.infinity, + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Color(0xFF0B1220), + Color(0xFF0F172A), + ], + ), + ), + child: Center( + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 24), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x1A000000), + blurRadius: 16, + offset: Offset(0, 8), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Update Required', + style: TextStyle( + color: Color(0xFF2563EB), + fontSize: 14, + fontWeight: FontWeight.w700, + letterSpacing: 0.2, + ), + ), + const SizedBox(height: 8), + Text( + HqVersionChecker.updateMessage, + style: const TextStyle( + color: Color(0xFF1A1A2E), + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerRight, + child: ElevatedButton( + onPressed: () => HqVersionChecker.openStore(), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + elevation: 0, + ), + child: const Text( + 'Update', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } +} + +// ---- Login screen: hostel dropdown + password ---- + +class MessManagerLoginScreen extends StatefulWidget { + const MessManagerLoginScreen({super.key}); + + @override + State createState() => _MessManagerLoginScreenState(); +} + +class _MessManagerLoginScreenState extends State { + final TextEditingController _passwordController = TextEditingController(); + final ValueNotifier> _hostels = ValueNotifier>( + [], + ); + String? _selectedHostel; + bool _loadingHostels = true; + bool _loggingIn = false; + + @override + void initState() { + super.initState(); + _loadHostels(); + } + + Future _loadHostels() async { + final prefs = await SharedPreferences.getInstance(); + try { + // Debug logging to understand real-device behaviour + debugPrint( + '[MessManagerLogin] Starting _loadHostels; endpoint=${HostelEndpoints.allHostels}'); + final hostels = await ManagerApi.fetchHostels(); + debugPrint( + '[MessManagerLogin] _loadHostels success, got ${hostels.length} hostels'); + if (!mounted) return; + _hostels.value = hostels; + await prefs.setStringList('mm_hostels', hostels); + setState(() { + _loadingHostels = false; + if (hostels.isNotEmpty) _selectedHostel ??= hostels.first; + }); + return; + } catch (e, st) { + debugPrint('[MessManagerLogin] _loadHostels error: $e'); + debugPrint('[MessManagerLogin] stack: $st'); + // Fallback to cached hostels if API fails + final cached = prefs.getStringList('mm_hostels'); + if (cached != null && cached.isNotEmpty) { + if (!mounted) return; + _hostels.value = cached; + setState(() { + _loadingHostels = false; + if (cached.isNotEmpty) _selectedHostel ??= cached.first; + }); + debugPrint( + '[MessManagerLogin] Using cached hostels (${cached.length})'); + return; + } + } + + if (!mounted) return; + setState(() { + _loadingHostels = false; + }); + } + + @override + void dispose() { + _passwordController.dispose(); + _hostels.dispose(); + super.dispose(); + } + + Future _login() async { + final messenger = ScaffoldMessenger.of(context); + debugPrint( + '[MessManagerLogin] _login tapped; selectedHostel=$_selectedHostel, ' + 'passwordLength=${_passwordController.text.trim().length}', + ); + + if (_selectedHostel == null || _selectedHostel!.isEmpty) { + messenger.showSnackBar( + const SnackBar(content: Text('Please select a hostel')), + ); + return; + } + if (_passwordController.text.trim().isEmpty) { + messenger.showSnackBar( + const SnackBar(content: Text('Please enter the hostel password')), + ); + return; + } + + setState(() { + _loggingIn = true; + }); + + try { + debugPrint( + '[MessManagerLogin] Calling ManagerApi.loginManager for ' + 'hostel=$_selectedHostel', + ); + final data = await ManagerApi.loginManager( + hostelName: _selectedHostel!, + password: _passwordController.text.trim(), + ); + final success = data['success'] == true; + final token = data['token']?.toString(); + + if (!success || token == null) { + final msg = + data['message']?.toString() ?? 'Invalid hostel or password.'; + messenger.showSnackBar(SnackBar(content: Text(msg))); + setState(() { + _loggingIn = false; + }); + return; + } + + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('mm_hostelName', _selectedHostel!); + await prefs.setString('mm_token', token); + + if (!mounted) return; + Navigator.of(context).pushReplacement( + MaterialPageRoute( + builder: (_) => ManagerHomeScreen( + hostelName: _selectedHostel!, + authToken: token, + ), + ), + ); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text('Login failed: $e'))); + setState(() { + _loggingIn = false; + }); + } + } + + @override + Widget build(BuildContext context) { + final size = MediaQuery.of(context).size; + return Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 32), + const Text( + 'HABit HQ', + style: TextStyle( + color: Color(0xFF2E2F31), + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 8), + const Text( + 'Select your hostel and enter the manager password to view mess & Gala Dinner scans.', + style: TextStyle( + color: Color(0xFF4B5563), + fontSize: 14, + ), + ), + SizedBox(height: size.height * 0.04), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 20, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x14000000), + blurRadius: 12, + offset: Offset(0, 6), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Hostel', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 8), + if (_loadingHostels) + const Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: CircularProgressIndicator(), + ), + ) + else + ValueListenableBuilder>( + valueListenable: _hostels, + builder: (context, hostels, _) { + debugPrint( + '[MessManagerLogin] Dropdown builder: ' + 'loading=$_loadingHostels, ' + 'hostelCount=${hostels.length}, ' + 'selectedHostel=$_selectedHostel', + ); + return Theme( + data: Theme.of(context) + .copyWith(canvasColor: Colors.white), + child: DropdownButtonFormField( + initialValue: _selectedHostel, + decoration: InputDecoration( + filled: true, + fillColor: const Color(0xFFF9FAFB), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + ), + dropdownColor: Colors.white, + borderRadius: BorderRadius.circular(12), + iconEnabledColor: const Color(0xFF111827), + iconDisabledColor: const Color(0xFF9CA3AF), + style: const TextStyle( + fontSize: 14, + color: Color(0xFF111827), + ), + items: hostels + .map( + (h) => DropdownMenuItem( + value: h, + child: Text( + h, + style: const TextStyle( + fontSize: 14, + color: Color(0xFF111827), + ), + ), + ), + ) + .toList(), + onChanged: (value) { + setState(() { + _selectedHostel = value; + }); + }, + hint: const Text( + 'Select hostel', + style: TextStyle( + fontSize: 14, + color: Color(0xFF6B7280), + ), + ), + ), + ); + }, + ), + const SizedBox(height: 16), + const Text( + 'Password', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 8), + TextField( + controller: _passwordController, + obscureText: true, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 14, + ), + cursorColor: const Color(0xFF4C4EDB), + decoration: InputDecoration( + filled: true, + fillColor: const Color(0xFFF9FAFB), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + hintText: 'Enter hostel password', + ), + ), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + height: 48, + child: ElevatedButton( + onPressed: _loggingIn ? null : _login, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + child: _loggingIn + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2.5, + valueColor: AlwaysStoppedAnimation( + Colors.white, + ), + ), + ) + : const Text( + 'Continue', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } +} + +// ---- Model + logs screen (read-only, WebSocket) ---- + +class GalaScanLog { + final String userId; + final String userName; + final String rollNumber; + final String mealType; + final String time; + final bool alreadyScanned; + + GalaScanLog({ + required this.userId, + required this.userName, + required this.rollNumber, + required this.mealType, + required this.time, + required this.alreadyScanned, + }); + + factory GalaScanLog.fromJson(Map json) { + final user = json['user'] is Map + ? json['user'] as Map + : {}; + return GalaScanLog( + userId: user['_id']?.toString() ?? '', + userName: user['name']?.toString() ?? '', + rollNumber: user['rollNumber']?.toString() ?? '', + mealType: json['mealType']?.toString() ?? '', + time: json['time']?.toString() ?? '', + alreadyScanned: json['alreadyScanned'] == true, + ); + } +} + +/// Manager home with bottom navigation: Today Mess, Gala Dinner. +class ManagerHomeScreen extends StatefulWidget { + final String hostelName; + final String authToken; + + const ManagerHomeScreen({ + super.key, + required this.hostelName, + required this.authToken, + }); + + @override + State createState() => _ManagerHomeScreenState(); +} + +class _ManagerHomeScreenState extends State { + int _currentIndex = 0; + bool _galaInitialized = false; + + @override + Widget build(BuildContext context) { + final screens = [ + TodayMessScreen( + hostelName: widget.hostelName, + authToken: widget.authToken, + ), + // Lazily create GalaSummaryScreen only after the Gala tab is visited + if (_galaInitialized) + GalaSummaryScreen( + hostelName: widget.hostelName, + authToken: widget.authToken, + ) + else + const SizedBox.shrink(), + ]; + + final items = [ + const BottomNavigationBarItem( + icon: Icon(Icons.restaurant), + label: 'Today Mess', + ), + const BottomNavigationBarItem( + icon: Icon(Icons.celebration), + label: 'Gala Dinner', + ), + ]; + + return Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: IndexedStack( + index: _currentIndex, + children: screens, + ), + ), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _currentIndex, + items: items, + onTap: (index) { + setState(() { + if (index == 1) { + _galaInitialized = true; + } + _currentIndex = index; + }); + }, + selectedItemColor: const Color(0xFF111827), + unselectedItemColor: const Color(0xFF9CA3AF), + backgroundColor: Colors.white, + type: BottomNavigationBarType.fixed, + ), + ); + } +} + +// ---- Today Mess summary screen (auto-refreshing) ---- + +class TodayMessScreen extends StatefulWidget { + final String hostelName; + final String authToken; + + const TodayMessScreen({ + super.key, + required this.hostelName, + required this.authToken, + }); + + @override + State createState() => _TodayMessScreenState(); +} + +class _TodayMessScreenState extends State { + bool _loading = true; + String? _error; + List<_RecentEntry> _breakfastEntries = const []; + List<_RecentEntry> _lunchEntries = const []; + List<_RecentEntry> _dinnerEntries = const []; + Timer? _timer; + Map _totals = const { + 'breakfast': 0, + 'lunch': 0, + 'dinner': 0, + }; + + void _startTimer() { + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 5), (_) => _fetch()); + } + + Future _openMealLogs(BuildContext context, String meal) async { + // Temporarily stop polling while on the dedicated screen. + _timer?.cancel(); + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => MessMealScanLogsScreen( + hostelName: widget.hostelName, + authToken: widget.authToken, + meal: meal, + ), + ), + ); + if (mounted) { + _startTimer(); + _fetch(); + } + } + + @override + void initState() { + super.initState(); + _fetch(); + // Poll every 5 seconds so new scans appear automatically. + _startTimer(); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + Future _fetch() async { + try { + final data = await ManagerApi.fetchTodayMessSummary(widget.authToken); + final recentMap = + (data['recent'] as Map? ?? {}); + + final totalsMap = + (data['totals'] as Map? ?? {}); + + List<_RecentEntry> breakfast = _mapRecent(recentMap['breakfast']); + List<_RecentEntry> lunch = _mapRecent(recentMap['lunch']); + List<_RecentEntry> dinner = _mapRecent(recentMap['dinner']); + + int compareByTime(_RecentEntry a, _RecentEntry b) { + final ta = _parseScanTimeForSort(a.time); + final tb = _parseScanTimeForSort(b.time); + return tb.compareTo(ta); // newest first + } + + breakfast.sort(compareByTime); + lunch.sort(compareByTime); + dinner.sort(compareByTime); + + if (!mounted) return; + setState(() { + _breakfastEntries = breakfast; + _lunchEntries = lunch; + _dinnerEntries = dinner; + _totals = { + 'breakfast': (totalsMap['breakfast'] as int?) ?? 0, + 'lunch': (totalsMap['lunch'] as int?) ?? 0, + 'dinner': (totalsMap['dinner'] as int?) ?? 0, + }; + _error = null; + _loading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _error = e.toString(); + _loading = false; + }); + } + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Center(child: CircularProgressIndicator()); + } + if (_error != null) { + return _ErrorState( + message: 'Failed to load today\'s scans.\n$_error', + ); + } + + // Merge all meals for "recent" view (limited to 20) + final allMerged = <_RecentEntry>[ + ..._breakfastEntries, + ..._lunchEntries, + ..._dinnerEntries, + ]; + allMerged.sort((a, b) { + final ta = _parseScanTimeForSort(a.time); + final tb = _parseScanTimeForSort(b.time); + return tb.compareTo(ta); + }); + final visibleEntries = + allMerged.length > 20 ? allMerged.take(20).toList() : allMerged; + + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Today\'s Mess', + style: TextStyle( + color: Color(0xFF2E2F31), + fontSize: 20, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 4), + Text( + widget.hostelName, + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + const SizedBox(height: 16), + const Text( + 'Total Scans', + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: GestureDetector( + onTap: () => _openMealLogs(context, 'Breakfast'), + child: _TotalPill( + label: 'Breakfast', + count: _totals['breakfast'] ?? 0, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: GestureDetector( + onTap: () => _openMealLogs(context, 'Lunch'), + child: _TotalPill( + label: 'Lunch', + count: _totals['lunch'] ?? 0, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: GestureDetector( + onTap: () => _openMealLogs(context, 'Dinner'), + child: _TotalPill( + label: 'Dinner', + count: _totals['dinner'] ?? 0, + ), + ), + ), + ], + ), + const SizedBox(height: 16), + const Text( + 'Recent Scans', + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 8), + ], + ), + ), + const Divider( + color: Color(0xFFE5E7EB), + height: 1, + ), + Expanded( + child: visibleEntries.isEmpty + ? const Center( + child: Text( + 'No scans yet for today.\nNew scans will appear here instantly.', + textAlign: TextAlign.center, + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + ) + : ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + itemCount: visibleEntries.length, + itemBuilder: (context, index) { + final entry = visibleEntries[index]; + return GestureDetector( + onTap: entry.userId.isEmpty + ? null + : () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => ManagerUserProfileScreen( + userId: entry.userId, + authToken: widget.authToken, + ), + ), + ); + }, + child: _RecentScanCard(entry: entry), + ); + }, + ), + ), + ], + ); + } +} + +// ---- Gala Dinner summary screen ---- + +class GalaSummaryScreen extends StatefulWidget { + final String hostelName; + final String authToken; + + const GalaSummaryScreen({ + super.key, + required this.hostelName, + required this.authToken, + }); + + @override + State createState() => _GalaSummaryScreenState(); +} + +class _GalaSummaryScreenState extends State { + bool _loading = true; + String? _error; + List<_RecentEntry> _startersEntries = const []; + List<_RecentEntry> _mainCourseEntries = const []; + List<_RecentEntry> _dessertsEntries = const []; + Timer? _timer; + Map _totals = const { + 'starters': 0, + 'mainCourse': 0, + 'desserts': 0, + }; + bool _hasGalaToday = false; + + void _startTimer() { + _timer?.cancel(); + _timer = Timer.periodic(const Duration(seconds: 5), (_) => _fetch()); + } + + Future _openCourseLogs(BuildContext context, String course) async { + _timer?.cancel(); + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => GalaCourseScanLogsScreen( + hostelName: widget.hostelName, + authToken: widget.authToken, + course: course, + ), + ), + ); + if (mounted) { + _startTimer(); + _fetch(); + } + } + + @override + void initState() { + super.initState(); + _fetch(); + _startTimer(); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + Future _fetch() async { + try { + final data = await ManagerApi.fetchGalaSummary(widget.authToken); + final gala = data['galaDinner']; + if (gala == null) { + if (!mounted) return; + setState(() { + _loading = false; + _error = null; + _hasGalaToday = false; + _startersEntries = const []; + _mainCourseEntries = const []; + _dessertsEntries = const []; + _totals = const { + 'starters': 0, + 'mainCourse': 0, + 'desserts': 0, + }; + }); + return; + } + + final recentMap = + (data['recent'] as Map? ?? {}); + final totalsMap = + (data['totals'] as Map? ?? {}); + + List<_RecentEntry> starters = _mapRecent(recentMap['starters']); + List<_RecentEntry> main = _mapRecent(recentMap['mainCourse']); + List<_RecentEntry> desserts = _mapRecent(recentMap['desserts']); + + int compareByTime(_RecentEntry a, _RecentEntry b) { + final ta = _parseScanTimeForSort(a.time); + final tb = _parseScanTimeForSort(b.time); + return tb.compareTo(ta); // newest first + } + + starters.sort(compareByTime); + main.sort(compareByTime); + desserts.sort(compareByTime); + + if (!mounted) return; + setState(() { + _startersEntries = starters; + _mainCourseEntries = main; + _dessertsEntries = desserts; + _totals = { + 'starters': (totalsMap['starters'] as int?) ?? 0, + 'mainCourse': (totalsMap['mainCourse'] as int?) ?? 0, + 'desserts': (totalsMap['desserts'] as int?) ?? 0, + }; + _hasGalaToday = true; + _error = null; + _loading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _error = e.toString(); + _loading = false; + }); + } + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Center(child: CircularProgressIndicator()); + } + if (_error != null) { + return _ErrorState( + message: 'Failed to load Gala Dinner scans.\n$_error', + ); + } + if (!_hasGalaToday) { + return const Center( + child: Text( + 'No Gala Dinner Scheduled for Today', + textAlign: TextAlign.center, + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 14, + ), + ), + ); + } + + final allMerged = <_RecentEntry>[ + ..._startersEntries, + ..._mainCourseEntries, + ..._dessertsEntries, + ]; + allMerged.sort((a, b) { + final ta = _parseScanTimeForSort(a.time); + final tb = _parseScanTimeForSort(b.time); + return tb.compareTo(ta); + }); + final visibleEntries = + allMerged.length > 20 ? allMerged.take(20).toList() : allMerged; + + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Gala Dinner', + style: TextStyle( + color: Color(0xFF2E2F31), + fontSize: 20, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 4), + Text( + widget.hostelName, + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + const SizedBox(height: 16), + const Text( + 'Total Scans', + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: GestureDetector( + onTap: () => _openCourseLogs(context, 'Starters'), + child: _TotalPill( + label: 'Starters', + count: _totals['starters'] ?? 0, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: GestureDetector( + onTap: () => _openCourseLogs(context, 'Main Course'), + child: _TotalPill( + label: 'Main', + count: _totals['mainCourse'] ?? 0, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: GestureDetector( + onTap: () => _openCourseLogs(context, 'Desserts'), + child: _TotalPill( + label: 'Desserts', + count: _totals['desserts'] ?? 0, + ), + ), + ), + ], + ), + const SizedBox(height: 16), + const Text( + 'Recent Scans', + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + const Divider( + color: Color(0xFFE5E7EB), + height: 1, + ), + Expanded( + child: visibleEntries.isEmpty + ? const Center( + child: Text( + 'No Gala Dinner scans yet for today.\nNew scans will appear here instantly.', + textAlign: TextAlign.center, + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + ) + : ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + itemCount: visibleEntries.length, + itemBuilder: (context, index) { + final entry = visibleEntries[index]; + return GestureDetector( + onTap: () { + if (entry.userId.isEmpty) return; + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => ManagerUserProfileScreen( + userId: entry.userId, + authToken: widget.authToken, + ), + ), + ); + }, + child: _RecentScanCard(entry: entry), + ); + }, + ), + ), + ], + ); + } +} + +// ---- Shared UI helpers ---- + +class _SectionData { + final String label; + final List<_RecentEntry> entries; + final String emptyText; + + const _SectionData({ + required this.label, + required this.entries, + required this.emptyText, + }); +} + +class _RecentEntry { + final String name; + final String rollNumber; + final String time; + final String userId; + + const _RecentEntry({ + required this.name, + required this.rollNumber, + required this.time, + required this.userId, + }); +} + +List<_RecentEntry> _mapRecent(dynamic raw) { + if (raw is! List) return const []; + return raw.map<_RecentEntry>((item) { + final m = item as Map; + return _RecentEntry( + name: (m['name'] ?? '') as String, + rollNumber: (m['rollNumber'] ?? '') as String, + time: (m['time'] ?? '') as String, + userId: (m['userId'] ?? '') as String, + ); + }).toList(); +} + +String _formatScanTime(String raw) { + // Try strict ISO parsing first. Convert to local timezone so that + // ISO strings like "2026-03-05T10:15:00.000Z" (UTC) show as IST on device. + final dt = DateTime.tryParse(raw)?.toLocal(); + if (dt != null) { + final h = dt.hour.toString().padLeft(2, '0'); + final m = dt.minute.toString().padLeft(2, '0'); + return '$h:$m'; + } + + // Fallback: extract the first HH:mm substring from arbitrary text. + final regex = RegExp(r'(\d{1,2}:\d{2})'); + final match = regex.firstMatch(raw); + if (match != null) { + return match.group(1)!; + } + + // Last resort: return as-is. + return raw; +} + +DateTime _parseScanTimeForSort(String raw) { + // Prefer strict ISO timestamps if available. + final iso = DateTime.tryParse(raw); + if (iso != null) return iso; + + // Otherwise, try to extract HH:mm and treat it as "today" in local time. + final regex = RegExp(r'(\d{1,2}):(\d{2})'); + final match = regex.firstMatch(raw); + if (match != null) { + final h = int.tryParse(match.group(1)!); + final m = int.tryParse(match.group(2)!); + if (h != null && m != null) { + final now = DateTime.now(); + return DateTime(now.year, now.month, now.day, h, m); + } + } + + // Fallback very old date so invalid timestamps sink to the bottom. + return DateTime.fromMillisecondsSinceEpoch(0); +} + +// ignore: unused_element +class _ScansLayout extends StatelessWidget { + final String title; + final String subtitle; + final Map totals; + final List<_SectionData> sections; + + const _ScansLayout({ + required this.title, + required this.subtitle, + required this.totals, + required this.sections, + }); + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + color: Color(0xFF2E2F31), + fontSize: 20, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 4), + Text( + subtitle, + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: totals.entries.map((e) { + return _TotalPill( + label: e.key, + count: (e.value as int?) ?? 0, + ); + }).toList(), + ), + ], + ), + ), + const Divider( + color: Color(0xFFE5E7EB), + height: 1, + ), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + itemCount: sections.length, + itemBuilder: (context, index) { + final section = sections[index]; + return _SectionCard(section: section); + }, + ), + ), + ], + ); + } +} + +class _TotalPill extends StatelessWidget { + final String label; + final int count; + + const _TotalPill({required this.label, required this.count}); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: const [ + BoxShadow( + color: Color(0x08000000), + blurRadius: 6, + offset: Offset(0, 2), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 4), + Text( + '$count', + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 18, + fontWeight: FontWeight.w700, + ), + ), + ], + ), + ); + } +} + +class _SectionCard extends StatelessWidget { + final _SectionData section; + + const _SectionCard({required this.section}); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: 12), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: const [ + BoxShadow( + color: Color(0x08000000), + blurRadius: 10, + offset: Offset(0, 4), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + section.label, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 8), + if (section.entries.isEmpty) + Text( + section.emptyText, + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ) + else + Column( + children: section.entries.map((e) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + e.name.isEmpty ? 'Unknown' : e.name, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 14, + fontWeight: FontWeight.w500, + ), + ), + if (e.rollNumber.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + e.rollNumber, + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 12, + ), + ), + ), + ], + ), + ), + const SizedBox(width: 8), + Text( + e.time, + style: const TextStyle( + color: Color(0xFF4C4EDB), + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ); + }).toList(), + ), + ], + ), + ); + } +} + +class _RecentScanCard extends StatelessWidget { + final _RecentEntry entry; + final int? index; + final bool showIndex; + + const _RecentScanCard({ + required this.entry, + this.index, + this.showIndex = false, + }); + + @override + Widget build(BuildContext context) { + final displayName = + entry.name.isEmpty ? 'Unknown' : entry.name.trim(); + + return Container( + margin: const EdgeInsets.only(bottom: 10), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: const [ + BoxShadow( + color: Color(0x08000000), + blurRadius: 8, + offset: Offset(0, 3), + ), + ], + ), + child: Row( + children: [ + if (showIndex && index != null) ...[ + Text( + '${index!}.', + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(width: 8), + ], + Expanded( + child: Text( + displayName, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 14, + fontWeight: FontWeight.w500, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 8), + Text( + _formatScanTime(entry.time), + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 12, + fontWeight: FontWeight.w500, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ); + } +} + +// ---- Live Mess meal scan logs (WebSocket) ---- + +class MessMealScanLogsScreen extends StatefulWidget { + final String hostelName; + final String authToken; + final String meal; // "Breakfast" | "Lunch" | "Dinner" + + const MessMealScanLogsScreen({ + super.key, + required this.hostelName, + required this.authToken, + required this.meal, + }); + + @override + State createState() => + _MessMealScanLogsScreenState(); +} + +class _MessMealScanLogsScreenState extends State { + final List<_RecentEntry> _logs = []; + WebSocketChannel? _channel; + StreamSubscription? _subscription; + bool _connecting = true; + String? _connectionError; + Timer? _pollTimer; + bool _initialLoading = true; + + @override + void initState() { + super.initState(); + _loadInitialLogs(); + _connectWebSocket(); + _startPolling(); + } + + @override + void dispose() { + _subscription?.cancel(); + _channel?.sink.close(); + _pollTimer?.cancel(); + super.dispose(); + } + + Future _loadInitialLogs() async { + try { + final summary = + await ManagerApi.fetchTodayMessSummary(widget.authToken); + final recent = + summary['recent'] as Map? ?? {}; + + String key; + switch (widget.meal.toLowerCase()) { + case 'breakfast': + key = 'breakfast'; + break; + case 'lunch': + key = 'lunch'; + break; + default: + key = 'dinner'; + } + + final list = recent[key] as List? ?? const []; + final entries = list.map((raw) { + final m = raw as Map; + return _RecentEntry( + name: (m['name'] ?? '') as String, + rollNumber: (m['rollNumber'] ?? '') as String, + time: (m['time'] ?? '') as String, + userId: (m['userId'] ?? '') as String, + ); + }).toList(); + + if (!mounted) return; + setState(() { + _logs + ..clear() + ..addAll(entries); + _initialLoading = false; + }); + } catch (_) { + // Ignore initial load errors; screen will still work live via WebSocket. + if (!mounted) return; + setState(() { + _initialLoading = false; + }); + } + } + + void _startPolling() { + _pollTimer?.cancel(); + _pollTimer = Timer.periodic(const Duration(seconds: 5), (_) { + _loadInitialLogs(); + }); + } + + void _connectWebSocket() { + setState(() { + _connecting = true; + _connectionError = null; + }); + + final uri = Uri.parse( + MessManagerEndpoints.mealScanLogsWs(widget.meal, widget.authToken), + ); + debugPrint( + '[MessMealScanLogs] Connecting WS for meal=${widget.meal} -> $uri'); + + try { + final channel = WebSocketChannel.connect(uri); + _channel = channel; + + setState(() { + _connecting = false; + }); + + _subscription = channel.stream.listen( + (event) { + try { + debugPrint( + '[MessMealScanLogs] WS message for ${widget.meal}: $event'); + final data = jsonDecode(event as String) as Map; + final user = data['user'] as Map? ?? {}; + final name = (user['name'] ?? '') as String; + final roll = (user['rollNumber'] ?? '') as String; + final time = (data['time'] ?? '') as String; + final userId = (user['_id'] ?? '') as String; + + final entry = _RecentEntry( + name: name, + rollNumber: roll, + time: time, + userId: userId, + ); + + setState(() { + _logs.insert(0, entry); + if (_logs.length > 200) { + _logs.removeRange(200, _logs.length); + } + }); + } catch (e) { + setState(() { + _connectionError = 'Failed to parse scan log: $e'; + }); + } + }, + onError: (error) { + if (!mounted) return; + debugPrint( + '[MessMealScanLogs] WS error for ${widget.meal}: $error'); + setState(() { + _connectionError = 'Connection error: $error'; + }); + }, + onDone: () { + if (!mounted) return; + debugPrint( + '[MessMealScanLogs] WS done for ${widget.meal} (closed by server/client)'); + setState(() { + _connectionError ??= 'Connection closed'; + }); + }, + ); + } catch (e) { + setState(() { + _connecting = false; + _connectionError = 'Failed to connect: $e'; + }); + } + } + + @override + Widget build(BuildContext context) { + final title = '${widget.meal} Scans'; + + return Scaffold( + backgroundColor: Colors.white, + appBar: AppBar( + title: Text( + title, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: Colors.white, + foregroundColor: const Color(0xFF111827), + elevation: 0, + ), + body: _initialLoading + ? const Center( + child: CircularProgressIndicator(), + ) + : Column( + children: [ + // Show a small "connecting" banner only while establishing + // the WebSocket connection and only when we already have logs. + // If there are no logs yet, we just rely on the empty state. + if (_logs.isNotEmpty && _connecting) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 12), + child: Row( + children: const [ + SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ), + SizedBox(width: 10), + Expanded( + child: Text( + 'Connecting to live scans...', + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + ), + ], + ), + ), + Expanded( + child: _logs.isEmpty + ? const Center( + child: Text( + 'No scans yet.\nNew scans will appear here instantly.', + textAlign: TextAlign.center, + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 14, + ), + ), + ) + : ListView.builder( + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 8), + itemCount: _logs.length, + itemBuilder: (context, index) { + final entry = _logs[index]; + final number = _logs.length - index; + return GestureDetector( + onTap: entry.userId.isEmpty + ? null + : () { + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => + ManagerUserProfileScreen( + userId: entry.userId, + authToken: widget.authToken, + ), + ), + ); + }, + child: _RecentScanCard( + entry: entry, + index: number, + showIndex: true, + ), + ); + }, + ), + ), + ], + ), + ); + } +} + +// ---- Live Gala course scan logs (per course) ---- + +class GalaCourseScanLogsScreen extends StatefulWidget { + final String hostelName; + final String authToken; + final String course; // "Starters" | "Main Course" | "Desserts" + + const GalaCourseScanLogsScreen({ + super.key, + required this.hostelName, + required this.authToken, + required this.course, + }); + + @override + State createState() => + _GalaCourseScanLogsScreenState(); +} + +class _GalaCourseScanLogsScreenState extends State { + final List<_RecentEntry> _logs = []; + WebSocketChannel? _channel; + StreamSubscription? _subscription; + bool _connecting = true; + String? _connectionError; + Timer? _pollTimer; + bool _initialLoading = true; + + @override + void initState() { + super.initState(); + _loadInitialLogs(); + _connectWebSocket(); + _startPolling(); + } + + @override + void dispose() { + _subscription?.cancel(); + _channel?.sink.close(); + _pollTimer?.cancel(); + super.dispose(); + } + + String _recentKeyForCourse() { + final lower = widget.course.toLowerCase(); + if (lower.startsWith('starter')) return 'starters'; + if (lower.startsWith('main')) return 'mainCourse'; + return 'desserts'; + } + + Future _loadInitialLogs() async { + try { + final summary = + await ManagerApi.fetchGalaSummary(widget.authToken); + final recent = + summary['recent'] as Map? ?? {}; + + final key = _recentKeyForCourse(); + final list = recent[key] as List? ?? const []; + final entries = list.map((raw) { + final m = raw as Map; + return _RecentEntry( + name: (m['name'] ?? '') as String, + rollNumber: (m['rollNumber'] ?? '') as String, + time: (m['time'] ?? '') as String, + userId: (m['userId'] ?? '') as String, + ); + }).toList(); + + entries.sort((a, b) { + final ta = _parseScanTimeForSort(a.time); + final tb = _parseScanTimeForSort(b.time); + return tb.compareTo(ta); + }); + + if (!mounted) return; + setState(() { + _logs + ..clear() + ..addAll(entries); + _initialLoading = false; + }); + } catch (_) { + // Ignore errors; live WS + polling will keep trying. + if (!mounted) return; + setState(() { + _initialLoading = false; + }); + } + } + + void _startPolling() { + _pollTimer?.cancel(); + _pollTimer = Timer.periodic(const Duration(seconds: 5), (_) { + _loadInitialLogs(); + }); + } + + void _connectWebSocket() { + setState(() { + _connecting = true; + _connectionError = null; + }); + + final uri = Uri.parse(GalaManagerEndpoints.wsUrl(widget.authToken)); + debugPrint( + '[GalaCourseLogs] Connecting WS for course=${widget.course} -> $uri'); + + try { + final channel = WebSocketChannel.connect(uri); + _channel = channel; + + setState(() { + _connecting = false; + }); + + _subscription = channel.stream.listen( + (event) { + try { + debugPrint( + '[GalaCourseLogs] WS message for ${widget.course}: $event'); + final data = jsonDecode(event as String) as Map; + final log = GalaScanLog.fromJson(data); + + // Only keep logs for this course + if (log.mealType != widget.course) { + return; + } + + final entry = _RecentEntry( + name: log.userName, + rollNumber: log.rollNumber, + time: log.time, + userId: log.userId, + ); + + setState(() { + _logs.insert(0, entry); + if (_logs.length > 200) { + _logs.removeRange(200, _logs.length); + } + }); + } catch (e) { + debugPrint( + '[GalaCourseLogs] Failed to parse WS scan log for ${widget.course}: $e'); + setState(() { + _connectionError = 'Failed to parse scan log: $e'; + }); + } + }, + onError: (error) { + if (!mounted) return; + debugPrint( + '[GalaCourseLogs] WS error for ${widget.course}: $error'); + setState(() { + _connectionError = 'Connection error: $error'; + }); + }, + onDone: () { + if (!mounted) return; + debugPrint( + '[GalaCourseLogs] WS done for ${widget.course} (closed by server/client)'); + setState(() { + _connectionError ??= 'Connection closed'; + }); + }, + ); + } catch (e) { + debugPrint( + '[GalaCourseLogs] Failed to connect WS for ${widget.course}: $e'); + setState(() { + _connecting = false; + _connectionError = 'Failed to connect: $e'; + }); + } + } + + @override + Widget build(BuildContext context) { + final title = '${widget.course} Scans'; + + return Scaffold( + backgroundColor: Colors.white, + appBar: AppBar( + title: Text( + title, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: Colors.white, + foregroundColor: const Color(0xFF111827), + elevation: 0, + ), + body: _initialLoading + ? const Center( + child: CircularProgressIndicator(), + ) + : Column( + children: [ + // Match Today Mess meal logs: show a small connecting banner + // only while establishing the WS connection, and only when + // there are already some logs on screen. + if (_logs.isNotEmpty && _connecting) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, vertical: 12), + child: Row( + children: const [ + SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ), + SizedBox(width: 10), + Expanded( + child: Text( + 'Connecting to live scans...', + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + ), + ], + ), + ), + const Divider( + color: Color(0xFFE5E7EB), + height: 1, + ), + Expanded( + child: _logs.isEmpty + ? const Center( + child: Text( + 'No scans yet.\nNew scans will appear here instantly.', + textAlign: TextAlign.center, + style: TextStyle( + color: Color(0xFF6B7280), + fontSize: 13, + ), + ), + ) + : ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 16), + itemCount: _logs.length, + itemBuilder: (context, index) { + final entry = _logs[index]; + final number = _logs.length - index; + return GestureDetector( + onTap: () { + if (entry.userId.isEmpty) return; + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => ManagerUserProfileScreen( + userId: entry.userId, + authToken: widget.authToken, + ), + ), + ); + }, + child: _RecentScanCard( + entry: entry, + index: number, + showIndex: true, + ), + ); + }, + ), + ), + ], + ), + ); + } +} + +class _ErrorState extends StatelessWidget { + final String message; + + const _ErrorState({required this.message}); + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Text( + // Always show a friendly, generic error rather than + // leaking raw backend or network error details. + 'No Internet connection.', + style: const TextStyle( + color: Color(0xFFB91C1C), + fontSize: 14, + ), + textAlign: TextAlign.center, + ), + ), + ); + } +} + +// ignore: unused_element +class _EmptyState extends StatelessWidget { + final String message; + + const _EmptyState({required this.message}); + + @override + Widget build(BuildContext context) { + return Center( + child: Text( + message, + style: const TextStyle( + color: Color(0xFF6B7280), + fontSize: 14, + ), + textAlign: TextAlign.center, + ), + ); + } +} + +// ---- Manager user profile screen ---- + +class ManagerUserProfileScreen extends StatefulWidget { + final String userId; + final String authToken; + + const ManagerUserProfileScreen({ + super.key, + required this.userId, + required this.authToken, + }); + + @override + State createState() => + _ManagerUserProfileScreenState(); +} + +class _ManagerProfileData { + final Map profile; + final Uint8List? pictureBytes; + + _ManagerProfileData({ + required this.profile, + required this.pictureBytes, + }); +} + +class _ManagerUserProfileScreenState extends State { + late Future<_ManagerProfileData> _future; + + @override + void initState() { + super.initState(); + _future = _load(); + } + + Future<_ManagerProfileData> _load() async { + final profile = await ManagerApi.fetchUserProfileForManager( + token: widget.authToken, + userId: widget.userId, + ); + final picture = await ManagerApi.fetchUserProfilePictureForManager( + token: widget.authToken, + userId: widget.userId, + ); + return _ManagerProfileData(profile: profile, pictureBytes: picture); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + appBar: AppBar( + title: const Text( + 'Profile', + style: TextStyle( + color: Color(0xFF111827), + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + backgroundColor: Colors.white, + foregroundColor: const Color(0xFF111827), + elevation: 0, + ), + body: FutureBuilder<_ManagerProfileData>( + future: _future, + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CircularProgressIndicator()); + } + if (snapshot.hasError) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Text( + 'Failed to load profile.\n${snapshot.error}', + style: const TextStyle( + color: Color(0xFFB91C1C), + fontSize: 14, + ), + textAlign: TextAlign.center, + ), + ), + ); + } + + final data = snapshot.data!; + final profile = data.profile; + final bytes = data.pictureBytes; + + final name = (profile['name'] ?? 'Unknown') as String; + final roll = (profile['rollNumber'] ?? '') as String; + final hostel = (profile['hostelName'] ?? '') as String; + final mess = (profile['messName'] ?? '') as String; + + final initial = name.isNotEmpty ? name.trim()[0].toUpperCase() : '?'; + final hasImage = bytes != null && bytes.isNotEmpty; + + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + CircleAvatar( + radius: 100, + backgroundColor: const Color(0xFFE5E7EB), + backgroundImage: hasImage ? MemoryImage(bytes) : null, + child: !hasImage + ? Text( + initial, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 32, + fontWeight: FontWeight.w600, + ), + ) + : null, + ), + const SizedBox(height: 12), + Text( + name, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 24), + _ProfileFieldRow( + icon: Icons.badge_outlined, + label: 'Roll Number', + value: roll, + ), + _ProfileFieldRow( + icon: Icons.restaurant_outlined, + label: 'Current Mess', + value: mess, + ), + _ProfileFieldRow( + icon: Icons.home_outlined, + label: 'Hostel', + value: hostel, + ), + ], + ), + ); + }, + ), + ); + } +} + +class _ProfileFieldRow extends StatelessWidget { + final IconData icon; + final String label; + final String value; + + const _ProfileFieldRow({ + required this.icon, + required this.label, + required this.value, + }); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + icon, + size: 20, + color: const Color(0xFF6B7280), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + color: Color(0xFF9CA3AF), + fontSize: 12, + ), + ), + const SizedBox(height: 2), + Text( + value.isEmpty ? '-' : value, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 14, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + +class GalaScanLogsScreen extends StatefulWidget { + final String hostelName; + final String authToken; + + const GalaScanLogsScreen({ + super.key, + required this.hostelName, + required this.authToken, + }); + + @override + State createState() => _GalaScanLogsScreenState(); +} + +class _GalaScanLogsScreenState extends State + with SingleTickerProviderStateMixin { + late TabController _tabController; + WebSocketChannel? _channel; + StreamSubscription? _subscription; + + final List _startersLogs = []; + final List _mainCourseLogs = []; + final List _dessertsLogs = []; + + bool _connecting = true; + String? _connectionError; + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 3, vsync: this); + _connectWebSocket(); + } + + @override + void dispose() { + _subscription?.cancel(); + _channel?.sink.close(); + _tabController.dispose(); + super.dispose(); + } + + void _connectWebSocket() { + setState(() { + _connecting = true; + _connectionError = null; + }); + + final uri = Uri.parse(GalaManagerEndpoints.wsUrl(widget.authToken)); + + final channel = WebSocketChannel.connect(uri); + _channel = channel; + + _subscription = channel.stream.listen( + (event) { + try { + final data = jsonDecode(event as String) as Map; + final log = GalaScanLog.fromJson(data); + setState(() { + _connecting = false; + _addLog(log); + }); + } catch (e) { + setState(() { + _connectionError = 'Failed to parse scan log: $e'; + _connecting = false; + }); + } + }, + onError: (error) { + if (!mounted) return; + setState(() { + _connectionError = 'Connection error: $error'; + _connecting = false; + }); + }, + onDone: () { + if (!mounted) return; + setState(() { + _connecting = false; + _connectionError ??= 'Connection closed'; + }); + }, + ); + } + + void _addLog(GalaScanLog log) { + List target; + switch (log.mealType) { + case 'Starters': + target = _startersLogs; + break; + case 'Main Course': + target = _mainCourseLogs; + break; + case 'Desserts': + target = _dessertsLogs; + break; + default: + target = _mainCourseLogs; + } + target.insert(0, log); + if (target.length > 200) { + target.removeRange(200, target.length); + } + } + + void _clearLogs() { + setState(() { + _startersLogs.clear(); + _mainCourseLogs.clear(); + _dessertsLogs.clear(); + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + backgroundColor: const Color(0xFF0D1D40), + foregroundColor: Colors.white, + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Gala Dinner Scans', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + Text( + widget.hostelName, + style: const TextStyle(fontSize: 13, color: Colors.white70), + ), + ], + ), + actions: [ + IconButton( + tooltip: 'Clear logs', + onPressed: _clearLogs, + icon: const Icon(Icons.delete_outline), + ), + ], + bottom: TabBar( + controller: _tabController, + tabs: [ + Tab( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Starters'), + const SizedBox(width: 6), + _buildCountChip(_startersLogs.length), + ], + ), + ), + Tab( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Main'), + const SizedBox(width: 6), + _buildCountChip(_mainCourseLogs.length), + ], + ), + ), + Tab( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('Desserts'), + const SizedBox(width: 6), + _buildCountChip(_dessertsLogs.length), + ], + ), + ), + ], + ), + ), + body: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF0B1220), Color(0xFF0F172A)], + ), + ), + child: SafeArea( + child: Column( + children: [ + if (_connecting || _connectionError != null) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + child: Row( + children: [ + if (_connecting) + const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + valueColor: AlwaysStoppedAnimation( + Color(0xFF22C55E), + ), + ), + ) + else + const Icon( + Icons.error_outline, + color: Color(0xFFF97316), + size: 20, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + _connecting + ? 'Connecting to live scan stream...' + : _connectionError ?? 'Connection closed', + style: const TextStyle( + color: Colors.white, + fontSize: 13, + ), + ), + ), + if (!_connecting) + TextButton( + onPressed: _connectWebSocket, + child: const Text( + 'Reconnect', + style: TextStyle( + color: Color(0xFF60A5FA), + fontSize: 13, + ), + ), + ), + ], + ), + ), + Expanded( + child: TabBarView( + controller: _tabController, + children: [ + _buildLogList(_startersLogs, 'Starters'), + _buildLogList(_mainCourseLogs, 'Main Course'), + _buildLogList(_dessertsLogs, 'Desserts'), + ], + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildCountChip(int count) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: const Color(0xFF4B5563), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + '$count', + style: const TextStyle( + fontSize: 11, + color: Colors.white, + fontWeight: FontWeight.w600, + ), + ), + ); + } + + Widget _buildLogList(List logs, String category) { + if (logs.isEmpty) { + return Center( + child: Text( + 'No $category scans yet.\nNew scans will appear here instantly.', + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white70, fontSize: 14), + ), + ); + } + + return ListView.builder( + padding: const EdgeInsets.all(12), + itemCount: logs.length, + itemBuilder: (context, index) { + final log = logs[index]; + final isDuplicate = log.alreadyScanned; + return Container( + margin: const EdgeInsets.only(bottom: 10), + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: const Color(0xFF111827), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: isDuplicate + ? const Color(0xFFF97316) + : const Color(0xFF22C55E), + width: 1, + ), + ), + child: Row( + children: [ + Container( + width: 36, + height: 36, + decoration: BoxDecoration( + color: isDuplicate + ? const Color(0xFF7C2D12) + : const Color(0xFF14532D), + borderRadius: BorderRadius.circular(999), + ), + child: Icon( + isDuplicate ? Icons.warning_amber_rounded : Icons.check, + color: Colors.white, + size: 20, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + log.userName.isEmpty ? 'Unknown' : log.userName, + style: const TextStyle( + color: Colors.white, + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + if (log.rollNumber.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + log.rollNumber, + style: const TextStyle( + color: Color(0xFF9CA3AF), + fontSize: 12, + ), + ), + ), + ], + ), + ), + const SizedBox(width: 12), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + log.time, + style: const TextStyle( + color: Colors.white, + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 4), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + decoration: BoxDecoration( + color: isDuplicate + ? const Color(0xFF7C2D12) + : const Color(0xFF14532D), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + isDuplicate ? 'Duplicate' : 'New', + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ], + ), + ); + }, + ); + } +} diff --git a/mess_frontend/lib/utilities/hq_version_checker.dart b/mess_frontend/lib/utilities/hq_version_checker.dart new file mode 100644 index 00000000..492a75aa --- /dev/null +++ b/mess_frontend/lib/utilities/hq_version_checker.dart @@ -0,0 +1,213 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import 'package:dio/dio.dart'; + +import '../constants/endpoint.dart'; + +/// HQ app version check: v1 only. If app version < minVersionv1 → force update (no skip). +/// Structure mirrors frontend2 VersionChecker; only check logic is v1-only. +class HqVersionChecker { + static String? _appVersion; + static String? _buildNumber; + static String? _deviceType; + static bool _updateRequired = false; + static String? _storeUrl; + static String? _updateMessage; + + static String getDeviceType() { + if (kIsWeb) { + return 'Web'; + } else if (Platform.isAndroid) { + return 'Android'; + } else if (Platform.isIOS) { + return 'iOS'; + } else if (Platform.isMacOS) { + return 'macOS'; + } else if (Platform.isWindows) { + return 'Windows'; + } else if (Platform.isLinux) { + return 'Linux'; + } else { + return 'Unknown'; + } + } + + static Future init() async { + _deviceType = getDeviceType(); + + // Get app version info + final packageInfo = await PackageInfo.fromPlatform(); + _appVersion = packageInfo.version; + _buildNumber = packageInfo.buildNumber; + } + + /// Check version against server: v1 only. If app version < minVersionv1 → force update. + static Future checkForUpdate() async { + try { + if (_deviceType != 'Android' && _deviceType != 'iOS') { + return false; + } + + // HQ is Android-only; skip check on iOS for consistency with getDeviceType + if (_deviceType != 'Android') { + return false; + } + + final dio = Dio(); + final response = await dio.get(HqAppVersionEndpoints.getAndroidVersion); + + if (response.statusCode == 200 && response.data['success'] == true) { + final data = response.data['data']; + + final String minVersionv1 = + data['minVersionv1'] as String? ?? data['minHQversion'] as String? ?? '1.0.0'; + _storeUrl = data['storeUrl'] as String?; + _updateMessage = data['updateMessage'] as String?; + + if (_compareVersions(_appVersion!, minVersionv1) >= 0) { + _updateRequired = false; + return false; + } else { + _updateRequired = true; + return true; + } + } + + return false; + } catch (e) { + if (kDebugMode) debugPrint('HqVersionChecker error: $e'); + _updateRequired = false; + return false; + } + } + + /// Compare two versions semantically + /// Returns: -1 if version1 < version2 + /// 0 if version1 == version2 + /// 1 if version1 > version2 + static int _compareVersions(String version1, String version2) { + try { + final v1Parts = version1.split('.').map((e) => int.parse(e)).toList(); + final v2Parts = version2.split('.').map((e) => int.parse(e)).toList(); + + final maxLength = + v1Parts.length > v2Parts.length ? v1Parts.length : v2Parts.length; + while (v1Parts.length < maxLength) { + v1Parts.add(0); + } + while (v2Parts.length < maxLength) { + v2Parts.add(0); + } + + for (int i = 0; i < maxLength; i++) { + if (v1Parts[i] < v2Parts[i]) { + return -1; + } + if (v1Parts[i] > v2Parts[i]) { + return 1; + } + } + + return 0; + } catch (e) { + if (kDebugMode) { + debugPrint('Error comparing versions $version1 vs $version2: $e'); + } + return 0; + } + } + + /// Show update required dialog (same UI as frontend2 VersionChecker.showUpdateDialog) + static Future showUpdateDialog(BuildContext context) async { + await showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext context) { + return PopScope( + canPop: false, + child: Dialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + backgroundColor: Colors.white, + elevation: 10, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + _updateMessage ?? 'Update available. Please update.', + style: const TextStyle( + color: Color(0xFF1A1A2E), + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerRight, + child: ElevatedButton( + onPressed: () => _openStore(), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + elevation: 0, + ), + child: const Text( + 'Update', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ), + ); + }, + ); + } + + /// Open store URL + static Future _openStore() async { + if (_storeUrl != null) { + final uri = Uri.parse(_storeUrl!); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + } + + static Future openStore() async { + await _openStore(); + } + + // Getters (same as frontend2) + static String get appVersion => _appVersion ?? 'Unknown'; + static String get buildNumber => _buildNumber ?? 'Unknown'; + static String get deviceType => _deviceType ?? 'Unknown'; + static String get fullVersion => '$appVersion+$buildNumber'; + static bool get updateRequired => _updateRequired; + static String? get storeUrl => _storeUrl; + static String get updateMessage => + _updateMessage ?? 'Update available. Please update.'; +} diff --git a/mess_frontend/linux/.gitignore b/mess_frontend/linux/.gitignore new file mode 100644 index 00000000..d3896c98 --- /dev/null +++ b/mess_frontend/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/mess_frontend/linux/CMakeLists.txt b/mess_frontend/linux/CMakeLists.txt new file mode 100644 index 00000000..3e62b124 --- /dev/null +++ b/mess_frontend/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "mess_frontend") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.mess_frontend") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/mess_frontend/linux/flutter/CMakeLists.txt b/mess_frontend/linux/flutter/CMakeLists.txt new file mode 100644 index 00000000..d5bd0164 --- /dev/null +++ b/mess_frontend/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/mess_frontend/linux/flutter/generated_plugin_registrant.cc b/mess_frontend/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000..cc10c4da --- /dev/null +++ b/mess_frontend/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); + audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/mess_frontend/linux/flutter/generated_plugin_registrant.h b/mess_frontend/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..e0f0a47b --- /dev/null +++ b/mess_frontend/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/mess_frontend/linux/flutter/generated_plugins.cmake b/mess_frontend/linux/flutter/generated_plugins.cmake new file mode 100644 index 00000000..8e2a1900 --- /dev/null +++ b/mess_frontend/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_linux + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/mess_frontend/linux/runner/CMakeLists.txt b/mess_frontend/linux/runner/CMakeLists.txt new file mode 100644 index 00000000..e97dabc7 --- /dev/null +++ b/mess_frontend/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/mess_frontend/linux/runner/main.cc b/mess_frontend/linux/runner/main.cc new file mode 100644 index 00000000..e7c5c543 --- /dev/null +++ b/mess_frontend/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/mess_frontend/linux/runner/my_application.cc b/mess_frontend/linux/runner/my_application.cc new file mode 100644 index 00000000..522d4164 --- /dev/null +++ b/mess_frontend/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "mess_frontend"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "mess_frontend"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/mess_frontend/linux/runner/my_application.h b/mess_frontend/linux/runner/my_application.h new file mode 100644 index 00000000..db16367a --- /dev/null +++ b/mess_frontend/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/mess_frontend/macos/.gitignore b/mess_frontend/macos/.gitignore new file mode 100644 index 00000000..746adbb6 --- /dev/null +++ b/mess_frontend/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/mess_frontend/macos/Flutter/Flutter-Debug.xcconfig b/mess_frontend/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 00000000..4b81f9b2 --- /dev/null +++ b/mess_frontend/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/mess_frontend/macos/Flutter/Flutter-Release.xcconfig b/mess_frontend/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 00000000..5caa9d15 --- /dev/null +++ b/mess_frontend/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/mess_frontend/macos/Flutter/GeneratedPluginRegistrant.swift b/mess_frontend/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 00000000..d0541c0c --- /dev/null +++ b/mess_frontend/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import audioplayers_darwin +import package_info_plus +import shared_preferences_foundation +import url_launcher_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin")) + FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) +} diff --git a/mess_frontend/macos/Podfile b/mess_frontend/macos/Podfile new file mode 100644 index 00000000..ff5ddb3b --- /dev/null +++ b/mess_frontend/macos/Podfile @@ -0,0 +1,42 @@ +platform :osx, '10.15' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/mess_frontend/macos/Podfile.lock b/mess_frontend/macos/Podfile.lock new file mode 100644 index 00000000..449db3fc --- /dev/null +++ b/mess_frontend/macos/Podfile.lock @@ -0,0 +1,30 @@ +PODS: + - audioplayers_darwin (0.0.1): + - Flutter + - FlutterMacOS + - FlutterMacOS (1.0.0) + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - audioplayers_darwin (from `Flutter/ephemeral/.symlinks/plugins/audioplayers_darwin/darwin`) + - FlutterMacOS (from `Flutter/ephemeral`) + - shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`) + +EXTERNAL SOURCES: + audioplayers_darwin: + :path: Flutter/ephemeral/.symlinks/plugins/audioplayers_darwin/darwin + FlutterMacOS: + :path: Flutter/ephemeral + shared_preferences_foundation: + :path: Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin + +SPEC CHECKSUMS: + audioplayers_darwin: 835ced6edd4c9fc8ebb0a7cc9e294a91d99917d5 + FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1 + shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb + +PODFILE CHECKSUM: 54d867c82ac51cbd61b565781b9fada492027009 + +COCOAPODS: 1.16.2 diff --git a/mess_frontend/macos/Runner.xcodeproj/project.pbxproj b/mess_frontend/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..5d9f2a56 --- /dev/null +++ b/mess_frontend/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,801 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + EB0980FD7AC429B7BB372F88 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D445986CEEBEB6C5E56DAB64 /* Pods_RunnerTests.framework */; }; + F5239EA87DABAA56AA978589 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0869C5C8A566C860D42E30C9 /* Pods_Runner.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 0869C5C8A566C860D42E30C9 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* mess_frontend.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = mess_frontend.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 4B2D40C66325AE65D6C79121 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 62E4DC9D9D26478C9565F4AA /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 6AB390010D9A2A79153CE42C /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 8864A353B75CC842F26FD99E /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + B4B0DCD2D12FFB23BAEF842C /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + CF008994D85606A91192D6C9 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + D445986CEEBEB6C5E56DAB64 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + EB0980FD7AC429B7BB372F88 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F5239EA87DABAA56AA978589 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + B009A70C888E5A9721DF42CC /* Pods */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* mess_frontend.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + B009A70C888E5A9721DF42CC /* Pods */ = { + isa = PBXGroup; + children = ( + 8864A353B75CC842F26FD99E /* Pods-Runner.debug.xcconfig */, + 62E4DC9D9D26478C9565F4AA /* Pods-Runner.release.xcconfig */, + 4B2D40C66325AE65D6C79121 /* Pods-Runner.profile.xcconfig */, + B4B0DCD2D12FFB23BAEF842C /* Pods-RunnerTests.debug.xcconfig */, + CF008994D85606A91192D6C9 /* Pods-RunnerTests.release.xcconfig */, + 6AB390010D9A2A79153CE42C /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 0869C5C8A566C860D42E30C9 /* Pods_Runner.framework */, + D445986CEEBEB6C5E56DAB64 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + C6AB7A7A755B9612FA210BAC /* [CP] Check Pods Manifest.lock */, + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 228563C6A5CFC59380628EC4 /* [CP] Check Pods Manifest.lock */, + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + 5C76829834E792207F432A8F /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* mess_frontend.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 228563C6A5CFC59380628EC4 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; + 5C76829834E792207F432A8F /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + C6AB7A7A755B9612FA210BAC /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B4B0DCD2D12FFB23BAEF842C /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/mess_frontend.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/mess_frontend"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = CF008994D85606A91192D6C9 /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/mess_frontend.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/mess_frontend"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6AB390010D9A2A79153CE42C /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/mess_frontend.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/mess_frontend"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/mess_frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mess_frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/mess_frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mess_frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/mess_frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..61a453b4 --- /dev/null +++ b/mess_frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mess_frontend/macos/Runner.xcworkspace/contents.xcworkspacedata b/mess_frontend/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..21a3cc14 --- /dev/null +++ b/mess_frontend/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/mess_frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mess_frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/mess_frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mess_frontend/macos/Runner/AppDelegate.swift b/mess_frontend/macos/Runner/AppDelegate.swift new file mode 100644 index 00000000..b3c17614 --- /dev/null +++ b/mess_frontend/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..a2ec33f1 --- /dev/null +++ b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 00000000..82b6f9d9 Binary files /dev/null and b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 00000000..13b35eba Binary files /dev/null and b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 00000000..0a3f5fa4 Binary files /dev/null and b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 00000000..bdb57226 Binary files /dev/null and b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 00000000..f083318e Binary files /dev/null and b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 00000000..326c0e72 Binary files /dev/null and b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 00000000..2f1632cf Binary files /dev/null and b/mess_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/mess_frontend/macos/Runner/Base.lproj/MainMenu.xib b/mess_frontend/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 00000000..80e867a4 --- /dev/null +++ b/mess_frontend/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mess_frontend/macos/Runner/Configs/AppInfo.xcconfig b/mess_frontend/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 00000000..e1892a8c --- /dev/null +++ b/mess_frontend/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = mess_frontend + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.messFrontend + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/mess_frontend/macos/Runner/Configs/Debug.xcconfig b/mess_frontend/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 00000000..36b0fd94 --- /dev/null +++ b/mess_frontend/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/mess_frontend/macos/Runner/Configs/Release.xcconfig b/mess_frontend/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 00000000..dff4f495 --- /dev/null +++ b/mess_frontend/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/mess_frontend/macos/Runner/Configs/Warnings.xcconfig b/mess_frontend/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 00000000..42bcbf47 --- /dev/null +++ b/mess_frontend/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/mess_frontend/macos/Runner/DebugProfile.entitlements b/mess_frontend/macos/Runner/DebugProfile.entitlements new file mode 100644 index 00000000..dddb8a30 --- /dev/null +++ b/mess_frontend/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/mess_frontend/macos/Runner/Info.plist b/mess_frontend/macos/Runner/Info.plist new file mode 100644 index 00000000..4789daa6 --- /dev/null +++ b/mess_frontend/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/mess_frontend/macos/Runner/MainFlutterWindow.swift b/mess_frontend/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 00000000..3cc05eb2 --- /dev/null +++ b/mess_frontend/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/mess_frontend/macos/Runner/Release.entitlements b/mess_frontend/macos/Runner/Release.entitlements new file mode 100644 index 00000000..852fa1a4 --- /dev/null +++ b/mess_frontend/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/mess_frontend/macos/RunnerTests/RunnerTests.swift b/mess_frontend/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..61f3bd1f --- /dev/null +++ b/mess_frontend/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/mess_frontend/pubspec.lock b/mess_frontend/pubspec.lock new file mode 100644 index 00000000..efe1a9cf --- /dev/null +++ b/mess_frontend/pubspec.lock @@ -0,0 +1,754 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + audioplayers: + dependency: "direct main" + description: + name: audioplayers + sha256: a72dd459d1a48f61a6fb9c0134dba26597c9236af40639ff0eb70eb4e0baab70 + url: "https://pub.dev" + source: hosted + version: "6.6.0" + audioplayers_android: + dependency: transitive + description: + name: audioplayers_android + sha256: "60a6728277228413a85755bd3ffd6fab98f6555608923813ce383b190a360605" + url: "https://pub.dev" + source: hosted + version: "5.2.1" + audioplayers_darwin: + dependency: transitive + description: + name: audioplayers_darwin + sha256: c994b3bb3a921e4904ac40e013fbc94488e824fd7c1de6326f549943b0b44a91 + url: "https://pub.dev" + source: hosted + version: "6.4.0" + audioplayers_linux: + dependency: transitive + description: + name: audioplayers_linux + sha256: f75bce1ce864170ef5e6a2c6a61cd3339e1a17ce11e99a25bae4474ea491d001 + url: "https://pub.dev" + source: hosted + version: "4.2.1" + audioplayers_platform_interface: + dependency: transitive + description: + name: audioplayers_platform_interface + sha256: "0e2f6a919ab56d0fec272e801abc07b26ae7f31980f912f24af4748763e5a656" + url: "https://pub.dev" + source: hosted + version: "7.1.1" + audioplayers_web: + dependency: transitive + description: + name: audioplayers_web + sha256: faa8fa6587f996a6f604433b53af44c57a1407d4fe8dff5766cf63d6875e8de9 + url: "https://pub.dev" + source: hosted + version: "5.2.0" + audioplayers_windows: + dependency: transitive + description: + name: audioplayers_windows + sha256: bafff2b38b6f6d331887558ba6e0a01c9c208d9dbb3ad0005234db065122a734 + url: "https://pub.dev" + source: hosted + version: "4.3.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dio: + dependency: "direct main" + description: + name: dio + sha256: aff32c08f92787a557dd5c0145ac91536481831a01b4648136373cddb0e64f8c + url: "https://pub.dev" + source: hosted + version: "5.9.2" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "2f9e64323a7c3c7ef69567d5c800424a11f8337b8b228bad02524c9fb3c1f340" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7" + url: "https://pub.dev" + source: hosted + version: "0.14.4" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + hooks: + dependency: transitive + description: + name: hooks + sha256: "7a08a0d684cb3b8fb604b78455d5d352f502b68079f7b80b831c62220ab0a4f6" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + url: "https://pub.dev" + source: hosted + version: "4.8.0" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: cb09e7dac6210041fad964ed7fbee004f14258b4eca4040f72d1234062ace4c8 + url: "https://pub.dev" + source: hosted + version: "4.11.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "89e83885ba09da5fdf2cdacc8002a712ca238c28b7f717910b34bcd27b0d03ac" + url: "https://pub.dev" + source: hosted + version: "0.17.4" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968" + url: "https://pub.dev" + source: hosted + version: "8.3.1" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e + url: "https://pub.dev" + source: hosted + version: "2.2.22" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + posix: + dependency: transitive + description: + name: posix + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "8374d6200ab33ac99031a852eba4c8eb2170c4bf20778b3e2c9eccb45384fb41" + url: "https://pub.dev" + source: hosted + version: "2.4.21" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + url: "https://pub.dev" + source: hosted + version: "0.7.7" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "767344bf3063897b5cf0db830e94f904528e6dd50a6dfaf839f0abf509009611" + url: "https://pub.dev" + source: hosted + version: "6.3.28" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f + url: "https://pub.dev" + source: hosted + version: "2.4.2" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + url: "https://pub.dev" + source: hosted + version: "4.5.3" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + url: "https://pub.dev" + source: hosted + version: "15.0.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: "direct main" + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.10.7 <4.0.0" + flutter: ">=3.38.4" diff --git a/mess_frontend/pubspec.yaml b/mess_frontend/pubspec.yaml new file mode 100644 index 00000000..5fcf6c03 --- /dev/null +++ b/mess_frontend/pubspec.yaml @@ -0,0 +1,105 @@ +name: mess_frontend +description: "HABit HQ – Mess manager dashboard." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.10.7 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + dio: ^5.8.0+1 + shared_preferences: ^2.3.2 + web_socket_channel: ^3.0.3 + audioplayers: ^6.1.0 + package_info_plus: ^8.1.3 + url_launcher: ^6.3.1 + +dev_dependencies: + flutter_test: + sdk: flutter + + flutter_launcher_icons: ^0.14.4 + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + assets: + - assets/sounds/scan.wav + - assets/icon/Handlogo.png + +flutter_launcher_icons: + android: true + ios: false + image_path: "assets/icon/Handlogo.png" + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/mess_frontend/test/widget_test.dart b/mess_frontend/test/widget_test.dart new file mode 100644 index 00000000..74da69d0 --- /dev/null +++ b/mess_frontend/test/widget_test.dart @@ -0,0 +1,23 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:mess_frontend/main.dart'; + +void main() { + testWidgets('App smoke test', (WidgetTester tester) async { + // Build the app with a placeholder updateRequired (test runs before async main). + await tester.pumpWidget( + const MessManagerApp(updateRequired: false), + ); + + // Should show login screen (hostel dropdown, etc.) + expect(find.byType(MaterialApp), findsOneWidget); + }); +} diff --git a/mess_frontend/web/favicon.png b/mess_frontend/web/favicon.png new file mode 100644 index 00000000..8aaa46ac Binary files /dev/null and b/mess_frontend/web/favicon.png differ diff --git a/mess_frontend/web/icons/Icon-192.png b/mess_frontend/web/icons/Icon-192.png new file mode 100644 index 00000000..b749bfef Binary files /dev/null and b/mess_frontend/web/icons/Icon-192.png differ diff --git a/mess_frontend/web/icons/Icon-512.png b/mess_frontend/web/icons/Icon-512.png new file mode 100644 index 00000000..88cfd48d Binary files /dev/null and b/mess_frontend/web/icons/Icon-512.png differ diff --git a/mess_frontend/web/icons/Icon-maskable-192.png b/mess_frontend/web/icons/Icon-maskable-192.png new file mode 100644 index 00000000..eb9b4d76 Binary files /dev/null and b/mess_frontend/web/icons/Icon-maskable-192.png differ diff --git a/mess_frontend/web/icons/Icon-maskable-512.png b/mess_frontend/web/icons/Icon-maskable-512.png new file mode 100644 index 00000000..d69c5669 Binary files /dev/null and b/mess_frontend/web/icons/Icon-maskable-512.png differ diff --git a/mess_frontend/web/index.html b/mess_frontend/web/index.html new file mode 100644 index 00000000..4286fd44 --- /dev/null +++ b/mess_frontend/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + mess_frontend + + + + + + diff --git a/mess_frontend/web/manifest.json b/mess_frontend/web/manifest.json new file mode 100644 index 00000000..ccfe703b --- /dev/null +++ b/mess_frontend/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "mess_frontend", + "short_name": "mess_frontend", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/mess_frontend/windows/.gitignore b/mess_frontend/windows/.gitignore new file mode 100644 index 00000000..d492d0d9 --- /dev/null +++ b/mess_frontend/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/mess_frontend/windows/CMakeLists.txt b/mess_frontend/windows/CMakeLists.txt new file mode 100644 index 00000000..5be2e700 --- /dev/null +++ b/mess_frontend/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(mess_frontend LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "mess_frontend") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/mess_frontend/windows/flutter/CMakeLists.txt b/mess_frontend/windows/flutter/CMakeLists.txt new file mode 100644 index 00000000..903f4899 --- /dev/null +++ b/mess_frontend/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/mess_frontend/windows/flutter/generated_plugin_registrant.cc b/mess_frontend/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000..43d432f5 --- /dev/null +++ b/mess_frontend/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + AudioplayersWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/mess_frontend/windows/flutter/generated_plugin_registrant.h b/mess_frontend/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..dc139d85 --- /dev/null +++ b/mess_frontend/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/mess_frontend/windows/flutter/generated_plugins.cmake b/mess_frontend/windows/flutter/generated_plugins.cmake new file mode 100644 index 00000000..17726131 --- /dev/null +++ b/mess_frontend/windows/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + audioplayers_windows + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/mess_frontend/windows/runner/CMakeLists.txt b/mess_frontend/windows/runner/CMakeLists.txt new file mode 100644 index 00000000..394917c0 --- /dev/null +++ b/mess_frontend/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/mess_frontend/windows/runner/Runner.rc b/mess_frontend/windows/runner/Runner.rc new file mode 100644 index 00000000..570df8cd --- /dev/null +++ b/mess_frontend/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "mess_frontend" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "mess_frontend" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "mess_frontend.exe" "\0" + VALUE "ProductName", "mess_frontend" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/mess_frontend/windows/runner/flutter_window.cpp b/mess_frontend/windows/runner/flutter_window.cpp new file mode 100644 index 00000000..955ee303 --- /dev/null +++ b/mess_frontend/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/mess_frontend/windows/runner/flutter_window.h b/mess_frontend/windows/runner/flutter_window.h new file mode 100644 index 00000000..6da0652f --- /dev/null +++ b/mess_frontend/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/mess_frontend/windows/runner/main.cpp b/mess_frontend/windows/runner/main.cpp new file mode 100644 index 00000000..3b9f85d5 --- /dev/null +++ b/mess_frontend/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"mess_frontend", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/mess_frontend/windows/runner/resource.h b/mess_frontend/windows/runner/resource.h new file mode 100644 index 00000000..66a65d1e --- /dev/null +++ b/mess_frontend/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/mess_frontend/windows/runner/resources/app_icon.ico b/mess_frontend/windows/runner/resources/app_icon.ico new file mode 100644 index 00000000..c04e20ca Binary files /dev/null and b/mess_frontend/windows/runner/resources/app_icon.ico differ diff --git a/mess_frontend/windows/runner/runner.exe.manifest b/mess_frontend/windows/runner/runner.exe.manifest new file mode 100644 index 00000000..153653e8 --- /dev/null +++ b/mess_frontend/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/mess_frontend/windows/runner/utils.cpp b/mess_frontend/windows/runner/utils.cpp new file mode 100644 index 00000000..3a0b4651 --- /dev/null +++ b/mess_frontend/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/mess_frontend/windows/runner/utils.h b/mess_frontend/windows/runner/utils.h new file mode 100644 index 00000000..3879d547 --- /dev/null +++ b/mess_frontend/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/mess_frontend/windows/runner/win32_window.cpp b/mess_frontend/windows/runner/win32_window.cpp new file mode 100644 index 00000000..60608d0f --- /dev/null +++ b/mess_frontend/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/mess_frontend/windows/runner/win32_window.h b/mess_frontend/windows/runner/win32_window.h new file mode 100644 index 00000000..e901dde6 --- /dev/null +++ b/mess_frontend/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/rc_frontend/.gitignore b/rc_frontend/.gitignore new file mode 100644 index 00000000..3820a95c --- /dev/null +++ b/rc_frontend/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/rc_frontend/.metadata b/rc_frontend/.metadata new file mode 100644 index 00000000..41a19796 --- /dev/null +++ b/rc_frontend/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "8b872868494e429d94fa06dca855c306438b22c0" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: android + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: ios + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: linux + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: macos + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: web + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + - platform: windows + create_revision: 8b872868494e429d94fa06dca855c306438b22c0 + base_revision: 8b872868494e429d94fa06dca855c306438b22c0 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/rc_frontend/README.md b/rc_frontend/README.md new file mode 100644 index 00000000..b513350d --- /dev/null +++ b/rc_frontend/README.md @@ -0,0 +1,16 @@ +# rc_frontend + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/rc_frontend/analysis_options.yaml b/rc_frontend/analysis_options.yaml new file mode 100644 index 00000000..0d290213 --- /dev/null +++ b/rc_frontend/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/rc_frontend/android/.gitignore b/rc_frontend/android/.gitignore new file mode 100644 index 00000000..be3943c9 --- /dev/null +++ b/rc_frontend/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/rc_frontend/android/app/build.gradle.kts b/rc_frontend/android/app/build.gradle.kts new file mode 100644 index 00000000..8e7fb72c --- /dev/null +++ b/rc_frontend/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.rc_frontend" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.rc_frontend" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/rc_frontend/android/app/src/debug/AndroidManifest.xml b/rc_frontend/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 00000000..399f6981 --- /dev/null +++ b/rc_frontend/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/rc_frontend/android/app/src/main/AndroidManifest.xml b/rc_frontend/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..0e4ac360 --- /dev/null +++ b/rc_frontend/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/rc_frontend/android/app/src/main/kotlin/com/example/rc_frontend/MainActivity.kt b/rc_frontend/android/app/src/main/kotlin/com/example/rc_frontend/MainActivity.kt new file mode 100644 index 00000000..6cf740ac --- /dev/null +++ b/rc_frontend/android/app/src/main/kotlin/com/example/rc_frontend/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.rc_frontend + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/rc_frontend/android/app/src/main/res/drawable-v21/launch_background.xml b/rc_frontend/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 00000000..f74085f3 --- /dev/null +++ b/rc_frontend/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/rc_frontend/android/app/src/main/res/drawable/launch_background.xml b/rc_frontend/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 00000000..304732f8 --- /dev/null +++ b/rc_frontend/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/rc_frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/rc_frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000..db77bb4b Binary files /dev/null and b/rc_frontend/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/rc_frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/rc_frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000..17987b79 Binary files /dev/null and b/rc_frontend/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/rc_frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/rc_frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000..09d43914 Binary files /dev/null and b/rc_frontend/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/rc_frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/rc_frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000..d5f1c8d3 Binary files /dev/null and b/rc_frontend/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/rc_frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/rc_frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000..4d6372ee Binary files /dev/null and b/rc_frontend/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/rc_frontend/android/app/src/main/res/values-night/styles.xml b/rc_frontend/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 00000000..06952be7 --- /dev/null +++ b/rc_frontend/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/rc_frontend/android/app/src/main/res/values/styles.xml b/rc_frontend/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..cb1ef880 --- /dev/null +++ b/rc_frontend/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/rc_frontend/android/app/src/profile/AndroidManifest.xml b/rc_frontend/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 00000000..399f6981 --- /dev/null +++ b/rc_frontend/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/rc_frontend/android/build.gradle.kts b/rc_frontend/android/build.gradle.kts new file mode 100644 index 00000000..dbee657b --- /dev/null +++ b/rc_frontend/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/rc_frontend/android/gradle.properties b/rc_frontend/android/gradle.properties new file mode 100644 index 00000000..fbee1d8c --- /dev/null +++ b/rc_frontend/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/rc_frontend/android/gradle/wrapper/gradle-wrapper.properties b/rc_frontend/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..e4ef43fb --- /dev/null +++ b/rc_frontend/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/rc_frontend/android/settings.gradle.kts b/rc_frontend/android/settings.gradle.kts new file mode 100644 index 00000000..ca7fe065 --- /dev/null +++ b/rc_frontend/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/rc_frontend/ios/.gitignore b/rc_frontend/ios/.gitignore new file mode 100644 index 00000000..7a7f9873 --- /dev/null +++ b/rc_frontend/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/rc_frontend/ios/Flutter/AppFrameworkInfo.plist b/rc_frontend/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 00000000..1dc6cf76 --- /dev/null +++ b/rc_frontend/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 13.0 + + diff --git a/rc_frontend/ios/Flutter/Debug.xcconfig b/rc_frontend/ios/Flutter/Debug.xcconfig new file mode 100644 index 00000000..ec97fc6f --- /dev/null +++ b/rc_frontend/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/rc_frontend/ios/Flutter/Release.xcconfig b/rc_frontend/ios/Flutter/Release.xcconfig new file mode 100644 index 00000000..c4855bfe --- /dev/null +++ b/rc_frontend/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/rc_frontend/ios/Podfile b/rc_frontend/ios/Podfile new file mode 100644 index 00000000..620e46eb --- /dev/null +++ b/rc_frontend/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '13.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/rc_frontend/ios/Podfile.lock b/rc_frontend/ios/Podfile.lock new file mode 100644 index 00000000..4a086ac5 --- /dev/null +++ b/rc_frontend/ios/Podfile.lock @@ -0,0 +1,41 @@ +PODS: + - Flutter (1.0.0) + - package_info_plus (0.4.5): + - Flutter + - share_plus (0.0.1): + - Flutter + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + - url_launcher_ios (0.0.1): + - Flutter + +DEPENDENCIES: + - Flutter (from `Flutter`) + - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) + - share_plus (from `.symlinks/plugins/share_plus/ios`) + - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + package_info_plus: + :path: ".symlinks/plugins/package_info_plus/ios" + share_plus: + :path: ".symlinks/plugins/share_plus/ios" + shared_preferences_foundation: + :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + url_launcher_ios: + :path: ".symlinks/plugins/url_launcher_ios/ios" + +SPEC CHECKSUMS: + Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467 + package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499 + share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a + shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb + url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b + +PODFILE CHECKSUM: 3c63482e143d1b91d2d2560aee9fb04ecc74ac7e + +COCOAPODS: 1.16.2 diff --git a/rc_frontend/ios/Runner.xcodeproj/project.pbxproj b/rc_frontend/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..b465daea --- /dev/null +++ b/rc_frontend/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,731 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 936CAF387D6545D586A532A0 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F61B232AA6588FF05392E932 /* Pods_RunnerTests.framework */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + BB458F2FEAE10D5590E7315C /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A0034A487483BD675699BDFD /* Pods_Runner.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 4D899C59D86466F1AFAC403E /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 521230A6F072B2507BA76299 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A0034A487483BD675699BDFD /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AFBE5E8F963961C1F9B9F9B6 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + C7CA8A1CD4D2321D762AE24B /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + D0C25BA9E2FA8F5E1692BC52 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + D384388CE0F07F60B1B5EC7C /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + F61B232AA6588FF05392E932 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BB458F2FEAE10D5590E7315C /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E8EB73C6B777006E0D36BD74 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 936CAF387D6545D586A532A0 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 36203715213FBE3C5CC657FB /* Pods */ = { + isa = PBXGroup; + children = ( + 4D899C59D86466F1AFAC403E /* Pods-Runner.debug.xcconfig */, + C7CA8A1CD4D2321D762AE24B /* Pods-Runner.release.xcconfig */, + AFBE5E8F963961C1F9B9F9B6 /* Pods-Runner.profile.xcconfig */, + 521230A6F072B2507BA76299 /* Pods-RunnerTests.debug.xcconfig */, + D384388CE0F07F60B1B5EC7C /* Pods-RunnerTests.release.xcconfig */, + D0C25BA9E2FA8F5E1692BC52 /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + 885490DA8431A951C0B8B315 /* Frameworks */ = { + isa = PBXGroup; + children = ( + A0034A487483BD675699BDFD /* Pods_Runner.framework */, + F61B232AA6588FF05392E932 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 36203715213FBE3C5CC657FB /* Pods */, + 885490DA8431A951C0B8B315 /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 36DBECBC449B1D5F1FB6E32A /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + E8EB73C6B777006E0D36BD74 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9C35FDF504D574B7FCD7A852 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 72857E73232FAA0E2ADBE346 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 36DBECBC449B1D5F1FB6E32A /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 72857E73232FAA0E2ADBE346 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; + 9C35FDF504D574B7FCD7A852 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 52G3FPFMR8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 521230A6F072B2507BA76299 /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D384388CE0F07F60B1B5EC7C /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D0C25BA9E2FA8F5E1692BC52 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 52G3FPFMR8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 52G3FPFMR8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/rc_frontend/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/rc_frontend/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/rc_frontend/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..e3773d42 --- /dev/null +++ b/rc_frontend/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/rc_frontend/ios/Runner.xcworkspace/contents.xcworkspacedata b/rc_frontend/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..21a3cc14 --- /dev/null +++ b/rc_frontend/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/rc_frontend/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/rc_frontend/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/rc_frontend/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/rc_frontend/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/rc_frontend/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/rc_frontend/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/rc_frontend/ios/Runner/AppDelegate.swift b/rc_frontend/ios/Runner/AppDelegate.swift new file mode 100644 index 00000000..62666446 --- /dev/null +++ b/rc_frontend/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..d36b1fab --- /dev/null +++ b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 00000000..dc9ada47 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 00000000..7353c41e Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 00000000..797d452e Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 00000000..6ed2d933 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 00000000..4cd7b009 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 00000000..fe730945 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 00000000..321773cd Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 00000000..797d452e Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 00000000..502f463a Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 00000000..0ec30343 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 00000000..0ec30343 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 00000000..e9f5fea2 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 00000000..84ac32ae Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 00000000..8953cba0 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 00000000..0467bf12 Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 00000000..0bedcf2f --- /dev/null +++ b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 00000000..89c2725b --- /dev/null +++ b/rc_frontend/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/rc_frontend/ios/Runner/Base.lproj/LaunchScreen.storyboard b/rc_frontend/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..f2e259c7 --- /dev/null +++ b/rc_frontend/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/rc_frontend/ios/Runner/Base.lproj/Main.storyboard b/rc_frontend/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 00000000..f3c28516 --- /dev/null +++ b/rc_frontend/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/rc_frontend/ios/Runner/Info.plist b/rc_frontend/ios/Runner/Info.plist new file mode 100644 index 00000000..8554be3b --- /dev/null +++ b/rc_frontend/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Rc Frontend + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + rc_frontend + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/rc_frontend/ios/Runner/Runner-Bridging-Header.h b/rc_frontend/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 00000000..308a2a56 --- /dev/null +++ b/rc_frontend/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/rc_frontend/ios/RunnerTests/RunnerTests.swift b/rc_frontend/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..86a7c3b1 --- /dev/null +++ b/rc_frontend/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/rc_frontend/lib/apis/manager_api.dart b/rc_frontend/lib/apis/manager_api.dart new file mode 100644 index 00000000..be40042c --- /dev/null +++ b/rc_frontend/lib/apis/manager_api.dart @@ -0,0 +1,192 @@ +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart'; + +import '../constants/endpoint.dart'; + +class ManagerApi { + ManagerApi._(); + + /// Shared Dio client with verbose logging to help debug real-device issues. + static final Dio _dio = (Dio() + ..options.validateStatus = (code) => code != null && code < 500) + ..interceptors.add( + LogInterceptor( + request: true, + requestBody: true, + responseBody: true, + responseHeader: false, + error: true, + logPrint: (obj) => debugPrint('[DIO] $obj'), + ), + ); + + static Map _authHeaders(String token) => { + 'Authorization': 'Bearer $token', + }; + + static Future> fetchHostels() async { + debugPrint( + '[ManagerApi] Fetching hostels from ${HostelEndpoints.allHostels} ...'); + try { + final response = await _dio.get(HostelEndpoints.allHostels); + debugPrint( + '[ManagerApi] /hostel/all -> status=${response.statusCode}, dataType=${response.data.runtimeType}'); + final data = response.data as List; + final hostels = data + .map((raw) => (raw as Map)['hostel_name'] as String) + .toList(); + debugPrint('[ManagerApi] Parsed ${hostels.length} hostels: $hostels'); + return hostels; + } catch (e, st) { + debugPrint('[ManagerApi] fetchHostels error: $e'); + debugPrint('[ManagerApi] fetchHostels stack: $st'); + rethrow; + } + } + + static Future> loginManager({ + required String hostelName, + required String password, + }) async { + debugPrint( + '[ManagerApi] Login manager: hostel=$hostelName url=${AuthEndpoints.managerLogin}'); + final response = await _dio.post( + AuthEndpoints.managerLogin, + data: { + 'hostelName': hostelName, + 'password': password, + }, + ); + debugPrint( + '[ManagerApi] /auth/manager/login -> status=${response.statusCode}, data=${response.data}'); + return response.data as Map; + } + + static Future> fetchTodayMessSummary( + String token, + ) async { + final response = await _dio.get( + MessManagerEndpoints.todaySummary, + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + static Future> fetchGalaSummary(String token) async { + final response = await _dio.get( + GalaManagerEndpoints.summary, + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + static Future hasTodayGala(String token) async { + final data = await fetchGalaSummary(token); + return data['galaDinner'] != null; + } + + static Future> fetchUserProfileForManager({ + required String token, + required String userId, + }) async { + final response = await _dio.get( + MessManagerEndpoints.userProfile(userId), + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + static Future fetchUserProfilePictureForManager({ + required String token, + required String userId, + }) async { + final response = await _dio.get>( + MessManagerEndpoints.userProfilePicture(userId), + options: Options( + headers: _authHeaders(token), + responseType: ResponseType.bytes, + validateStatus: (code) => code != null && code < 500, + ), + ); + + if (response.statusCode == 200) { + // If server returned JSON instead of bytes, skip. + final contentType = response.headers.value('content-type') ?? ''; + if (contentType.contains('application/json')) { + return null; + } + final data = response.data; + if (data == null) return null; + return Uint8List.fromList(data); + } + + // 404 or 403 etc. → treat as no picture. + return null; + } + + /// GET tomorrow's room-cleaning bookings for the manager's hostel. + /// Returns { bookings: [ { _id, roomNumber, slot, timeRange, assignedTo } ], totalCleaners }. + static Future> fetchRcTomorrow( + String token, [ + String? date, + ]) async { + final uri = date != null + ? Uri.parse(RcEndpoints.tomorrow).replace(queryParameters: {'date': date}) + : Uri.parse(RcEndpoints.tomorrow); + final response = await _dio.get( + uri.toString(), + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + /// POST room-cleaning assignments for tomorrow. + /// Body: { date?: 'YYYY-MM-DD', assignments: [ { bookingId, assignedTo } ] }. + static Future> postRcTomorrowAssign( + String token, { + String? date, + required List> assignments, + }) async { + final body = { + 'assignments': assignments, + }; + if (date != null) body['date'] = date; + final response = await _dio.post( + RcEndpoints.tomorrowAssign, + data: body, + options: Options(headers: _authHeaders(token)), + ); + return response.data as Map; + } + + /// POST to finalize booking statuses for a given date (e.g. Yesterday). + /// Body: { date: 'YYYY-MM-DD', updates: [ { bookingId, status, reason? } ] }. + static Future> postRcFinalizeStatuses( + String token, { + required String date, + required List> updates, + }) async { + final body = { + 'date': date, + 'updates': updates, + }; + final response = await _dio.post( + RcEndpoints.finalizeStatuses, + data: body, + options: Options(headers: _authHeaders(token)), + ); + if (response.statusCode == 200) { + return response.data as Map; + } + + final data = response.data; + final serverMessage = data is Map && data['message'] != null + ? data['message'].toString() + : data?.toString(); + throw Exception( + 'Finalize failed (status ${response.statusCode}). ' + '${serverMessage ?? 'If you just added the endpoint, restart the backend server.'}', + ); + } +} + diff --git a/rc_frontend/lib/constants/endpoint.dart b/rc_frontend/lib/constants/endpoint.dart new file mode 100644 index 00000000..1cd01132 --- /dev/null +++ b/rc_frontend/lib/constants/endpoint.dart @@ -0,0 +1,41 @@ +// Base API URL for the mess manager app. +// Point this at the same gateway the main app uses. +const String baseUrl = 'http://localhost:3000/api'; + +class AuthEndpoints { + static const String managerLogin = '$baseUrl/auth/manager/login'; +} + +class HostelEndpoints { + static const String allHostels = '$baseUrl/hostel/all'; +} + +class GalaManagerEndpoints { + static const String summary = '$baseUrl/gala/manager/summary'; + + // WebSocket endpoint for live Gala scan logs (to be implemented server-side). + static String wsUrl(String token) => + 'wss://hab.codingclub.in/api/gala/manager/scan-logs?token=$token'; +} + +class MessManagerEndpoints { + static const String todaySummary = '$baseUrl/logs/manager/today'; + static String userProfile(String userId) => '$baseUrl/users/manager/$userId'; + static String userProfilePicture(String userId) => + '$baseUrl/profile/picture/manager/$userId'; + static String mealScanLogsWs(String meal, String token) => + 'wss://hab.codingclub.in/api/mess/manager/scan-logs?meal=$meal&token=$token'; +} + +class HqAppVersionEndpoints { + // HABit HQ (manager app) Android version info + static const String getAndroidVersion = '$baseUrl/hq-app-version/android'; +} + +class RcEndpoints { + static const String tomorrow = '$baseUrl/room-cleaning/rc/tomorrow'; + static const String tomorrowAssign = + '$baseUrl/room-cleaning/rc/tomorrow/assign'; + static const String finalizeStatuses = + '$baseUrl/room-cleaning/rc/status/finalize'; +} diff --git a/rc_frontend/lib/constants/themes.dart b/rc_frontend/lib/constants/themes.dart new file mode 100644 index 00000000..6a88062c --- /dev/null +++ b/rc_frontend/lib/constants/themes.dart @@ -0,0 +1,120 @@ +import 'package:flutter/material.dart'; + +class Themes { + static const kYellow = Color.fromRGBO(254, 207, 111, 1); + static final theme = ThemeData( + useMaterial3: true, + primaryColor: kYellow, + scaffoldBackgroundColor: Colors.white, + fontFamily: 'ProximaNova', + splashColor: kYellow, + textTheme: const TextTheme( + labelMedium: TextStyle( + color: Colors.white, + fontWeight: FontWeight.w800, + fontSize: 16, + ), + labelSmall: TextStyle( + fontSize: 14.0, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + displayLarge: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.white, + fontSize: 28, + ), + displayMedium: TextStyle( + fontWeight: FontWeight.w800, + color: Colors.white, + fontSize: 24, + ), + displaySmall: TextStyle( + fontSize: 20.0, + fontWeight: FontWeight.w400, + color: Colors.white, + ), + bodySmall: TextStyle( + fontWeight: FontWeight.w400, + color: Colors.white, + fontSize: 12, + ), + bodyMedium: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + bodyLarge: TextStyle( + fontSize: 20.0, + fontWeight: FontWeight.w700, + color: Colors.white, + ), + ), + colorScheme: ColorScheme.fromSwatch().copyWith( + secondary: Colors.black, + ), + ); + + static const darkTextTheme = TextTheme( + displayMedium: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 18.0, + ), + displayLarge: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 24.0, + ), + displaySmall: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 12.0, + ), + bodyMedium: TextStyle( + fontWeight: FontWeight.w400, + color: Colors.black, + fontSize: 14.0, + ), + bodySmall: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w400, + color: Colors.black, + ), + labelSmall: TextStyle( + fontWeight: FontWeight.w800, + color: Colors.black, + fontSize: 10.0, + ), + labelLarge: TextStyle( + fontFamily: "ProximaNova", + fontSize: 16, + fontWeight: FontWeight.w700, + color: Colors.black, + ), + labelMedium: TextStyle( + fontWeight: FontWeight.w800, + color: Colors.black, + fontSize: 14.0, + ), + bodyLarge: TextStyle( + fontWeight: FontWeight.w700, + color: Colors.black, + fontSize: 14.0, + ), + ); + + static const feedbackColor = Color.fromRGBO(46, 47, 49, 1); +} + +const List habitColors = [ + Color.fromRGBO(219, 206, 255, 1), + Color.fromRGBO(219, 206, 255, 1), + Color.fromRGBO(255, 167, 212, 1), + Color.fromRGBO(255, 167, 212, 1), + Color.fromRGBO(111, 143, 254, 1), + Color.fromRGBO(111, 143, 254, 1), + Color.fromRGBO(237, 244, 146, 1), + Color.fromRGBO(237, 244, 146, 1), +]; + diff --git a/rc_frontend/lib/main.dart b/rc_frontend/lib/main.dart new file mode 100644 index 00000000..38ef4b7a --- /dev/null +++ b/rc_frontend/lib/main.dart @@ -0,0 +1,2197 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:share_plus/share_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'apis/manager_api.dart'; +import 'constants/themes.dart'; +import 'utilities/hq_version_checker.dart'; + +/// Slot letter to time range for display (replaces "Slot A" etc. with timing). +const Map _rcSlotTimeRange = { + 'A': '12:00–14:00', + 'B': '14:00–16:00', + 'C': '16:00–18:00', + 'D': '18:00–20:00', +}; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + await HqVersionChecker.init(); + final bool updateRequired = await HqVersionChecker.checkForUpdate(); + + runApp(HabitRcApp(updateRequired: updateRequired)); +} + +class HabitRcApp extends StatelessWidget { + final bool updateRequired; + + const HabitRcApp({super.key, required this.updateRequired}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'HABit RC', + theme: Themes.theme, + home: updateRequired + ? const RcUpdateRequiredScreen() + : const RcLoginScreen(), + ); + } +} + +class RcUpdateRequiredScreen extends StatelessWidget { + const RcUpdateRequiredScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Container( + width: double.infinity, + height: double.infinity, + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Color(0xFF0B1220), + Color(0xFF0F172A), + ], + ), + ), + child: Center( + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 24), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x1A000000), + blurRadius: 16, + offset: Offset(0, 8), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Update Required', + style: TextStyle( + color: Color(0xFF2563EB), + fontSize: 14, + fontWeight: FontWeight.w700, + letterSpacing: 0.2, + ), + ), + const SizedBox(height: 8), + Text( + HqVersionChecker.updateMessage, + style: const TextStyle( + color: Color(0xFF1A1A2E), + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerRight, + child: ElevatedButton( + onPressed: () => HqVersionChecker.openStore(), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + elevation: 0, + ), + child: const Text( + 'Update', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } +} + +class RcLoginScreen extends StatefulWidget { + const RcLoginScreen({super.key}); + + @override + State createState() => _RcLoginScreenState(); +} + +class _RcLoginScreenState extends State { + final TextEditingController _passwordController = TextEditingController(); + final ValueNotifier> _hostels = + ValueNotifier>([]); + String? _selectedHostel; + bool _loadingHostels = true; + bool _loggingIn = false; + + @override + void initState() { + super.initState(); + _loadHostels(); + } + + Future _loadHostels() async { + final prefs = await SharedPreferences.getInstance(); + try { + final hostels = await ManagerApi.fetchHostels(); + if (!mounted) return; + _hostels.value = hostels; + await prefs.setStringList('rc_hostels', hostels); + setState(() { + _loadingHostels = false; + if (hostels.isNotEmpty) _selectedHostel ??= hostels.first; + }); + return; + } catch (_) { + final cached = prefs.getStringList('rc_hostels'); + if (cached != null && cached.isNotEmpty) { + if (!mounted) return; + _hostels.value = cached; + setState(() { + _loadingHostels = false; + if (cached.isNotEmpty) _selectedHostel ??= cached.first; + }); + return; + } + } + + if (!mounted) return; + setState(() { + _loadingHostels = false; + }); + } + + @override + void dispose() { + _passwordController.dispose(); + _hostels.dispose(); + super.dispose(); + } + + Future _login() async { + final messenger = ScaffoldMessenger.of(context); + + if (_selectedHostel == null || _selectedHostel!.isEmpty) { + messenger.showSnackBar( + const SnackBar(content: Text('Please select a hostel')), + ); + return; + } + if (_passwordController.text.trim().isEmpty) { + messenger.showSnackBar( + const SnackBar(content: Text('Please enter the hostel password')), + ); + return; + } + + setState(() { + _loggingIn = true; + }); + + try { + final data = await ManagerApi.loginManager( + hostelName: _selectedHostel!, + password: _passwordController.text.trim(), + ); + final success = data['success'] == true; + final token = data['token']?.toString(); + + if (!success || token == null) { + final msg = + data['message']?.toString() ?? 'Invalid hostel or password.'; + messenger.showSnackBar(SnackBar(content: Text(msg))); + setState(() { + _loggingIn = false; + }); + return; + } + + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('rc_hostelName', _selectedHostel!); + await prefs.setString('rc_token', token); + + if (!mounted) return; + Navigator.of(context).pushReplacement( + MaterialPageRoute( + builder: (_) => RcHomeScreen( + hostelName: _selectedHostel!, + authToken: token, + ), + ), + ); + } catch (e) { + messenger.showSnackBar(SnackBar(content: Text('Login failed: $e'))); + setState(() { + _loggingIn = false; + }); + } + } + + @override + Widget build(BuildContext context) { + final size = MediaQuery.of(context).size; + return Scaffold( + backgroundColor: Colors.white, + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 32), + const Text( + 'HABit RC', + style: TextStyle( + color: Color(0xFF2E2F31), + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 8), + const Text( + 'Select your hostel and enter the manager password to access room-cleaning dashboard.', + style: TextStyle( + color: Color(0xFF4B5563), + fontSize: 14, + ), + ), + SizedBox(height: size.height * 0.04), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 20, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + boxShadow: const [ + BoxShadow( + color: Color(0x14000000), + blurRadius: 12, + offset: Offset(0, 6), + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Hostel', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 8), + if (_loadingHostels) + const Center( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: CircularProgressIndicator(), + ), + ) + else + ValueListenableBuilder>( + valueListenable: _hostels, + builder: (context, hostels, _) { + return Theme( + data: Theme.of(context) + .copyWith(canvasColor: Colors.white), + child: DropdownButtonFormField( + initialValue: _selectedHostel, + decoration: InputDecoration( + filled: true, + fillColor: const Color(0xFFF9FAFB), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + ), + dropdownColor: Colors.white, + borderRadius: BorderRadius.circular(12), + iconEnabledColor: const Color(0xFF111827), + iconDisabledColor: const Color(0xFF9CA3AF), + style: const TextStyle( + fontSize: 14, + color: Color(0xFF111827), + ), + items: hostels + .map( + (h) => DropdownMenuItem( + value: h, + child: Text( + h, + style: const TextStyle( + fontSize: 14, + color: Color(0xFF111827), + ), + ), + ), + ) + .toList(), + onChanged: (value) { + setState(() { + _selectedHostel = value; + }); + }, + hint: const Text( + 'Select hostel', + style: TextStyle( + fontSize: 14, + color: Color(0xFF6B7280), + ), + ), + ), + ); + }, + ), + const SizedBox(height: 16), + const Text( + 'Password', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Color(0xFF111827), + ), + ), + const SizedBox(height: 8), + TextField( + controller: _passwordController, + obscureText: true, + style: const TextStyle( + color: Color(0xFF111827), + fontSize: 14, + ), + cursorColor: const Color(0xFF4C4EDB), + decoration: InputDecoration( + filled: true, + fillColor: const Color(0xFFF9FAFB), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + hintText: 'Enter hostel password', + hintStyle: const TextStyle( + fontSize: 14, + color: Color(0xFF9CA3AF), + ), + ), + ), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + height: 48, + child: ElevatedButton( + onPressed: _loggingIn ? null : _login, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + child: _loggingIn + ? const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator( + strokeWidth: 2.5, + valueColor: AlwaysStoppedAnimation( + Colors.white, + ), + ), + ) + : const Text( + 'Continue', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ); + } +} + +class RcHomeScreen extends StatelessWidget { + final String hostelName; + final String authToken; + + const RcHomeScreen({ + super.key, + required this.hostelName, + required this.authToken, + }); + + @override + Widget build(BuildContext context) { + return _RcHomeScaffold( + hostelName: hostelName, + authToken: authToken, + ); + } +} + +class _RcHomeScaffold extends StatefulWidget { + final String hostelName; + final String authToken; + + const _RcHomeScaffold({ + required this.hostelName, + required this.authToken, + }); + + @override + State<_RcHomeScaffold> createState() => _RcHomeScaffoldState(); +} + +class _RcHomeScaffoldState extends State<_RcHomeScaffold> { + int _currentIndex = 1; // default to Today + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + appBar: AppBar( + backgroundColor: Colors.white, + foregroundColor: Colors.black, + elevation: 0, + title: Text( + 'HABit RC • ${widget.hostelName}', + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 18, + color: Colors.black, + ), + ), + ), + body: IndexedStack( + index: _currentIndex, + children: [ + _RcYesterdayTab(authToken: widget.authToken), + _RcTodayTab(authToken: widget.authToken), + _RcAssignTab(authToken: widget.authToken), + ], + ), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _currentIndex, + onTap: (index) { + setState(() { + _currentIndex = index; + }); + }, + selectedItemColor: const Color(0xFF4C4EDB), + unselectedItemColor: const Color(0xFF6B7280), + showUnselectedLabels: true, + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.arrow_back_ios_new_rounded, size: 18), + label: 'Yesterday', + ), + BottomNavigationBarItem( + icon: Icon(Icons.today_rounded), + label: 'Today', + ), + BottomNavigationBarItem( + icon: Icon(Icons.arrow_forward_ios_rounded, size: 18), + label: 'Tomorrow', + ), + ], + ), + ); + } +} + +class _RcYesterdayTab extends StatefulWidget { + final String authToken; + + const _RcYesterdayTab({required this.authToken}); + + @override + State<_RcYesterdayTab> createState() => _RcYesterdayTabState(); +} + +class _RcYesterdayTabState extends State<_RcYesterdayTab> { + int _totalCleaners = 0; + List> _bookings = []; + bool _loading = true; + String? _loadError; + + /// null = Unassigned, else 1..N + int? _selectedCleaner; + + /// bookingId -> status choice (default "Select") + final Map _statusByBookingId = {}; + + static const List _statusOptions = [ + 'Select', + 'Cleaned', + 'Room Locked', + 'Student Did Not Respond', + 'Student Asked To Cancel', + 'Room Cleaners Not Available', + ]; + + String get _yesterdayDateParam { + final t = DateTime.now().subtract(const Duration(days: 1)); + return '${t.year.toString().padLeft(4, '0')}-${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')}'; + } + + Future _loadYesterday() async { + setState(() { + _loading = true; + _loadError = null; + }); + try { + final data = await ManagerApi.fetchRcTomorrow( + widget.authToken, + _yesterdayDateParam, + ); + final list = (data['bookings'] as List?) + ?.map((e) => Map.from(e as Map)) + .toList() ?? + []; + final n = (data['totalCleaners'] as num?)?.toInt() ?? 0; + + // Ensure every booking has a default "Select" choice. + for (final b in list) { + final id = b['_id']?.toString(); + if (id == null || id.isEmpty) continue; + _statusByBookingId.putIfAbsent(id, () => 'Select'); + } + + setState(() { + _bookings = list; + _totalCleaners = n; + _loading = false; + _loadError = null; + if (_selectedCleaner == null && _totalCleaners > 0) { + _selectedCleaner = 1; + } + }); + } catch (e) { + setState(() { + _loading = false; + _loadError = e.toString(); + }); + } + } + + bool get _canFinalizeSelectedCleaner { + final filtered = _filteredBookings; + if (filtered.isEmpty) return false; + for (final b in filtered) { + final id = b['_id']?.toString(); + if (id == null || id.isEmpty) return false; + final v = _statusByBookingId[id] ?? 'Select'; + if (v == 'Select') return false; + } + return true; + } + + Map? _mapUiStatusToBackend(String ui) { + switch (ui) { + case 'Cleaned': + return {'status': 'Cleaned'}; + case 'Room Locked': + case 'Student Did Not Respond': + return { + 'status': 'CouldNotBeCleaned', + 'reason': 'Student Did Not Respond', + }; + case 'Student Asked To Cancel': + return { + 'status': 'CouldNotBeCleaned', + 'reason': 'Student Asked To Cancel', + }; + case 'Room Cleaners Not Available': + return { + 'status': 'CouldNotBeCleaned', + 'reason': 'Room Cleaners Not Available', + }; + default: + return null; + } + } + + Future _finalizeSelected() async { + if (!_canFinalizeSelectedCleaner) return; + + final filtered = _filteredBookings; + final updates = >[]; + + for (final b in filtered) { + final id = b['_id']?.toString(); + if (id == null || id.isEmpty) continue; + final uiValue = _statusByBookingId[id] ?? 'Select'; + final mapped = _mapUiStatusToBackend(uiValue); + if (mapped == null) continue; + updates.add({ + 'bookingId': id, + ...mapped, + }); + } + + try { + final data = await ManagerApi.postRcFinalizeStatuses( + widget.authToken, + date: _yesterdayDateParam, + updates: updates, + ); + if (!mounted) return; + final updated = (data['updated'] as num?)?.toInt() ?? 0; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Finalized ${updates.length} bookings (updated: $updated)'), + backgroundColor: const Color(0xFF4C4EDB), + ), + ); + await _loadYesterday(); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to finalize: $e'), + backgroundColor: Colors.red, + ), + ); + } + } + + List> get _filteredBookings { + return _bookings.where((b) { + final a = b['assignedTo']; + final assigned = (a is int) ? a : (a is num ? a.toInt() : null); + if (_selectedCleaner == null) return assigned == null; + return assigned == _selectedCleaner; + }).toList(); + } + + @override + void initState() { + super.initState(); + _loadYesterday(); + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Center(child: CircularProgressIndicator()); + } + + if (_loadError != null) { + return Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Failed to load yesterday\'s schedule:\n$_loadError', + textAlign: TextAlign.center, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + const SizedBox(height: 12), + TextButton( + onPressed: _loadYesterday, + child: const Text('Retry'), + ), + ], + ), + ), + ); + } + + final filtered = _filteredBookings; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Yesterday', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Color(0xFF111827), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFE5E7EB)), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: _selectedCleaner, + items: [ + const DropdownMenuItem( + value: null, + child: Text( + 'Unassigned', + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF111827), + ), + ), + ), + ...List.generate(_totalCleaners, (i) { + final n = i + 1; + return DropdownMenuItem( + value: n, + child: Text( + 'Cleaner $n', + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF111827), + ), + ), + ); + }), + ], + onChanged: (value) => setState(() => _selectedCleaner = value), + icon: const Icon( + Icons.keyboard_arrow_down_rounded, + size: 18, + color: Color(0xFF6B7280), + ), + dropdownColor: Colors.white, + borderRadius: BorderRadius.circular(10), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 8), + Expanded( + child: filtered.isEmpty + ? const Center( + child: Text( + 'No bookings in this view.', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + ) + : ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 0), + itemCount: filtered.length, + itemBuilder: (context, index) { + final b = filtered[index]; + final id = b['_id']?.toString() ?? ''; + final room = b['roomNumber']?.toString() ?? '—'; + final slot = b['slot']?.toString() ?? ''; + final timeRange = b['timeRange']?.toString(); + final slotLabel = (timeRange != null && timeRange.isNotEmpty) + ? timeRange + : 'Slot $slot'; + final value = _statusByBookingId[id] ?? 'Select'; + final finalized = + b['statusFinalizedAt'] != null; + + return _RcYesterdayRow( + room: room.startsWith('Room ') ? room : 'Room $room', + slotLabel: slotLabel, + value: value, + finalized: finalized, + options: _statusOptions, + onChanged: (v) { + setState(() => _statusByBookingId[id] = v); + }, + ); + }, + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + child: SizedBox( + width: double.infinity, + height: 46, + child: ElevatedButton( + onPressed: _canFinalizeSelectedCleaner ? _finalizeSelected : null, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + child: const Text( + 'Finalize', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 15, + ), + ), + ), + ), + ), + ], + ); + } +} + +class _RcYesterdayRow extends StatelessWidget { + final String room; + final String slotLabel; + final String value; + final bool finalized; + final List options; + final ValueChanged onChanged; + + const _RcYesterdayRow({ + required this.room, + required this.slotLabel, + required this.value, + required this.finalized, + required this.options, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + final isSelect = value == 'Select'; + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: finalized ? const Color(0xFFF9FAFB) : Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.02), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + room, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Colors.black, + ), + ), + const SizedBox(height: 2), + Text( + slotLabel, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + ], + ), + ), + const SizedBox(width: 12), + Flexible( + flex: 0, + child: ConstrainedBox( + constraints: const BoxConstraints(minWidth: 160, maxWidth: 240), + child: DropdownButtonFormField( + value: value, + disabledHint: Text( + value, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + items: options + .map( + (opt) => DropdownMenuItem( + value: opt, + child: Text( + opt, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: opt == 'Select' + ? const Color(0xFF6B7280) + : const Color(0xFF111827), + ), + ), + ), + ) + .toList(), + selectedItemBuilder: (context) => options + .map( + (opt) => Align( + alignment: Alignment.centerLeft, + child: Text( + opt, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: opt == 'Select' + ? const Color(0xFF6B7280) + : const Color(0xFF111827), + ), + ), + ), + ) + .toList(), + onChanged: finalized + ? null + : (v) { + if (v == null) return; + onChanged(v); + }, + decoration: InputDecoration( + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 8, + ), + filled: true, + fillColor: finalized + ? const Color(0xFFF3F4F6) + : (isSelect ? const Color(0xFFF9FAFB) : Colors.white), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Color(0xFFE5E7EB)), + ), + ), + dropdownColor: Colors.white, + borderRadius: BorderRadius.circular(10), + icon: const Icon( + Icons.keyboard_arrow_down_rounded, + size: 18, + color: Color(0xFF6B7280), + ), + isExpanded: true, + ), + ), + ), + ], + ), + ), + ); + } +} + +class _RcTodayTab extends StatefulWidget { + final String authToken; + + const _RcTodayTab({required this.authToken}); + + @override + State<_RcTodayTab> createState() => _RcTodayTabState(); +} + +class _RcTodayTabState extends State<_RcTodayTab> { + int _totalCleaners = 0; + List> _bookings = []; + bool _loading = true; + String? _loadError; + + /// null = Unassigned, else 1..N + int? _selectedCleaner; + + String get _todayDateParam { + final t = DateTime.now(); + return '${t.year.toString().padLeft(4, '0')}-${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')}'; + } + + Future _loadToday() async { + setState(() { + _loading = true; + _loadError = null; + }); + try { + final data = await ManagerApi.fetchRcTomorrow( + widget.authToken, + _todayDateParam, + ); + final list = (data['bookings'] as List?) + ?.map((e) => Map.from(e as Map)) + .toList() ?? + []; + final n = (data['totalCleaners'] as num?)?.toInt() ?? 0; + setState(() { + _bookings = list; + _totalCleaners = n; + _loading = false; + _loadError = null; + }); + } catch (e) { + setState(() { + _loading = false; + _loadError = e.toString(); + }); + } + } + + @override + void initState() { + super.initState(); + _loadToday(); + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Center(child: CircularProgressIndicator()); + } + + if (_loadError != null) { + return Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Failed to load today\'s schedule:\n$_loadError', + textAlign: TextAlign.center, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + const SizedBox(height: 12), + TextButton( + onPressed: _loadToday, + child: const Text('Retry'), + ), + ], + ), + ), + ); + } + + final filtered = _bookings.where((b) { + final a = b['assignedTo']; + final assigned = (a is int) ? a : (a is num ? a.toInt() : null); + if (_selectedCleaner == null) return assigned == null; + return assigned == _selectedCleaner; + }).toList(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Today', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Color(0xFF111827), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFFE5E7EB)), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: _selectedCleaner, + items: [ + const DropdownMenuItem( + value: null, + child: Text( + 'Unassigned', + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF111827), + ), + ), + ), + ...List.generate(_totalCleaners, (i) { + final n = i + 1; + return DropdownMenuItem( + value: n, + child: Text( + 'Cleaner $n', + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF111827), + ), + ), + ); + }), + ], + onChanged: (value) => setState(() => _selectedCleaner = value), + icon: const Icon( + Icons.keyboard_arrow_down_rounded, + size: 18, + color: Color(0xFF6B7280), + ), + dropdownColor: Colors.white, + borderRadius: BorderRadius.circular(10), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 8), + Expanded( + child: filtered.isEmpty + ? const Center( + child: Text( + 'No bookings in this view.', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + ) + : ListView.builder( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + itemCount: filtered.length, + itemBuilder: (context, index) { + final b = filtered[index]; + final room = b['roomNumber']?.toString() ?? '—'; + final slot = b['slot']?.toString() ?? ''; + final timeRange = b['timeRange']?.toString(); + final slotLabel = (timeRange != null && timeRange.isNotEmpty) + ? timeRange + : 'Slot $slot'; + return _RcScheduleRow( + title: room.startsWith('Room ') ? room : 'Room $room', + subtitle: slotLabel, + ); + }, + ), + ), + ], + ); + } +} + +class _RcScheduleRow extends StatelessWidget { + final String title; + final String subtitle; + + const _RcScheduleRow({ + required this.title, + required this.subtitle, + }); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.02), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Colors.black, + ), + ), + const SizedBox(height: 4), + Text( + subtitle, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + ], + ), + ), + ); + } +} + +class _RcBookingRow extends StatefulWidget { + final String title; + final String subtitle; + + const _RcBookingRow({ + required this.title, + required this.subtitle, + }); + + @override + State<_RcBookingRow> createState() => _RcBookingRowState(); +} + +class _RcBookingRowState extends State<_RcBookingRow> { + String _selectedStatus = 'Cleaned'; + + static const _options = [ + 'Cleaned', + 'Room Locked', + 'Student Did not Respond', + 'Student Cancelled', + 'Room Cleaner Not Available', + ]; + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.02), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.title, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Colors.black, + ), + ), + const SizedBox(height: 4), + Text( + widget.subtitle, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + ], + ), + ), + const SizedBox(width: 12), + SizedBox( + width: 190, + child: DropdownButtonFormField( + value: _selectedStatus, + items: _options + .map( + (opt) => DropdownMenuItem( + value: opt, + child: Text( + opt, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF111827), + ), + ), + ), + ) + .toList(), + onChanged: (value) { + if (value == null) return; + setState(() { + _selectedStatus = value; + }); + }, + decoration: InputDecoration( + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 8, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + ), + dropdownColor: Colors.white, + borderRadius: BorderRadius.circular(10), + icon: const Icon( + Icons.keyboard_arrow_down_rounded, + size: 18, + color: Color(0xFF6B7280), + ), + ), + ), + ], + ), + ), + ); + } +} + +class _RcAssignTab extends StatefulWidget { + final String authToken; + + const _RcAssignTab({required this.authToken}); + + @override + State<_RcAssignTab> createState() => _RcAssignTabState(); +} + +class _RcAssignTabState extends State<_RcAssignTab> { + int _totalCleaners = 0; + List> _bookings = []; + List _assignments = []; + /// Last saved/loaded state; when _assignments != _savedAssignments, show Save instead of Share. + List _savedAssignments = []; + bool _loading = true; + String? _loadError; + bool _saving = false; + bool _sharingPdf = false; + bool _summaryExpanded = false; + bool _confirmedSlotsExpanded = true; + bool _bufferSlotsExpanded = true; + + bool get _hasAllocationChange { + if (_assignments.length != _savedAssignments.length) return true; + for (var i = 0; i < _assignments.length; i++) { + if (_assignments[i] != _savedAssignments[i]) return true; + } + return false; + } + + bool get _allConfirmedAssigned { + for (var i = 0; i < _bookings.length; i++) { + final status = _bookings[i]['status']?.toString(); + if (status == 'Buffered') continue; + if (_assignments.length <= i || _assignments[i] == null) return false; + } + return true; + } + + /// Tomorrow's date for PDF (local date + 1 day). + String get _tomorrowDateStr { + final t = DateTime.now().add(const Duration(days: 1)); + return '${t.day.toString().padLeft(2, '0')}-${t.month.toString().padLeft(2, '0')}-${t.year}'; + } + + Future _generateAndSharePdf() async { + if (_sharingPdf || _bookings.isEmpty) return; + setState(() => _sharingPdf = true); + try { + final dateStr = _tomorrowDateStr; + final pdf = pw.Document(); + int pagesAdded = 0; + + for (int cleanerNo = 1; cleanerNo <= _totalCleaners; cleanerNo++) { + final rows = >[]; + int slNo = 0; + for (var i = 0; i < _bookings.length; i++) { + if (_assignments[i] != cleanerNo) continue; + slNo++; + final b = _bookings[i]; + final slotTime = b['timeRange']?.toString() ?? ''; + final roomNumber = b['roomNumber']?.toString() ?? '—'; + final phoneNumber = b['phoneNumber']?.toString() ?? '—'; + rows.add([ + slNo.toString(), + slotTime, + roomNumber, + phoneNumber, + '', // Signature column left blank + ]); + } + if (rows.isEmpty) continue; + + pagesAdded++; + pdf.addPage( + pw.Page( + pageFormat: PdfPageFormat.a4, + margin: const pw.EdgeInsets.all(24), + build: (pw.Context context) { + return pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + pw.Text( + 'Date: $dateStr', + style: pw.TextStyle( + fontSize: 14, + fontWeight: pw.FontWeight.bold, + ), + ), + pw.SizedBox(height: 8), + pw.Text( + 'Room Cleaner $cleanerNo', + style: pw.TextStyle( + fontSize: 16, + fontWeight: pw.FontWeight.bold, + ), + ), + pw.SizedBox(height: 16), + pw.Table( + border: pw.TableBorder.all(color: PdfColors.grey800), + columnWidths: { + 0: const pw.FlexColumnWidth(1), + 1: const pw.FlexColumnWidth(2), + 2: const pw.FlexColumnWidth(2), + 3: const pw.FlexColumnWidth(2.5), + 4: const pw.FlexColumnWidth(2), + }, + children: [ + pw.TableRow( + decoration: const pw.BoxDecoration( + color: PdfColors.grey300, + ), + children: [ + _cell('Sl.No'), + _cell('Slot Time'), + _cell('Room Number'), + _cell('Phone Number'), + _cell('Signature'), + ], + ), + ...rows.map( + (row) => pw.TableRow( + children: row.map((s) => _cell(s)).toList(), + ), + ), + ], + ), + ], + ); + }, + ), + ); + } + + if (pagesAdded == 0) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text( + 'No assignments to export. Assign bookings to room cleaners first.', + ), + ), + ); + } + return; + } + + final bytes = await pdf.save(); + final dir = await getTemporaryDirectory(); + final file = File('${dir.path}/room_cleaning_$dateStr.pdf'); + await file.writeAsBytes(bytes); + + if (mounted) { + await Share.shareXFiles( + [XFile(file.path)], + text: 'Room cleaning schedule - $dateStr', + subject: 'Room cleaning schedule', + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to generate PDF: $e'), + backgroundColor: Colors.red, + ), + ); + } + } finally { + if (mounted) setState(() => _sharingPdf = false); + } + } + + pw.Widget _cell(String text) { + return pw.Padding( + padding: const pw.EdgeInsets.symmetric(horizontal: 6, vertical: 4), + child: pw.Text(text, style: const pw.TextStyle(fontSize: 10)), + ); + } + + Future _loadTomorrow() async { + setState(() { + _loading = true; + _loadError = null; + }); + try { + final data = await ManagerApi.fetchRcTomorrow(widget.authToken); + final list = (data['bookings'] as List?) + ?.map((e) => Map.from(e as Map)) + .toList() ?? + []; + final n = (data['totalCleaners'] as num?)?.toInt() ?? 0; + final assignments = list.map((b) { + final a = b['assignedTo']; + if (a == null) return null; + if (a is int) return a; + if (a is num) return a.toInt(); + return null; + }).toList(); + setState(() { + _bookings = list; + _totalCleaners = n; + _assignments = assignments; + _savedAssignments = List.from(assignments); + _loading = false; + _loadError = null; + }); + } catch (e) { + setState(() { + _loading = false; + _loadError = e.toString(); + }); + } + } + + @override + void initState() { + super.initState(); + _loadTomorrow(); + } + + Map> _buildCleanerSummary() { + final Map> summary = {}; + for (var i = 0; i < _bookings.length; i++) { + final cleaner = _assignments[i]; + if (cleaner == null) continue; + final slot = _bookings[i]['slot']?.toString() ?? ''; + summary.putIfAbsent(cleaner, () => {}); + summary[cleaner]!.update(slot, (value) => value + 1, ifAbsent: () => 1); + } + return summary; + } + + Future _saveAssignments() async { + if (_saving || _bookings.isEmpty) return; + setState(() => _saving = true); + try { + final assignments = >[]; + for (var i = 0; i < _bookings.length; i++) { + final id = _bookings[i]['_id']; + if (id == null) continue; + assignments.add({ + 'bookingId': id, + 'assignedTo': _assignments[i], + }); + } + await ManagerApi.postRcTomorrowAssign( + widget.authToken, + assignments: assignments, + ); + if (mounted) { + setState(() => _savedAssignments = List.from(_assignments)); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Assignments finalized'), + backgroundColor: Color(0xFF4C4EDB), + ), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to save: $e'), + backgroundColor: Colors.red, + ), + ); + } + } finally { + if (mounted) setState(() => _saving = false); + } + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const Center( + child: Padding( + padding: EdgeInsets.all(24), + child: CircularProgressIndicator(color: Color(0xFF4C4EDB)), + ), + ); + } + if (_loadError != null) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _loadError!, + style: const TextStyle(color: Colors.red), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + TextButton( + onPressed: _loadTomorrow, + child: const Text('Retry'), + ), + ], + ), + ), + ); + } + + final cleanerSummary = _buildCleanerSummary(); + final confirmedIndices = []; + final bufferIndices = []; + for (var i = 0; i < _bookings.length; i++) { + final status = _bookings[i]['status']?.toString(); + if (status == 'Buffered') { + bufferIndices.add(i); + } else { + confirmedIndices.add(i); + } + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header row: "Tomorrow" + Share or Save on the right + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + const Text( + 'Tomorrow', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 16, + color: Color(0xFF111827), + ), + ), + if (_hasAllocationChange || !_allConfirmedAssigned) + TextButton( + onPressed: (!_hasAllocationChange || !_allConfirmedAssigned || _saving) + ? null + : _saveAssignments, + child: Text( + 'Finalize', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: (!_hasAllocationChange || !_allConfirmedAssigned || _saving) + ? const Color(0xFF9CA3AF) + : const Color(0xFF4C4EDB), + ), + ), + ) + else + TextButton.icon( + onPressed: _sharingPdf ? null : _generateAndSharePdf, + icon: const FaIcon( + FontAwesomeIcons.whatsapp, + color: Color(0xFF25D366), + size: 18, + ), + label: const Text( + 'Share', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Color(0xFF111827), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 8), + // Summary as dropdown + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Material( + color: const Color(0xFFF9FAFB), + borderRadius: BorderRadius.circular(12), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE5E7EB)), + ), + child: ExpansionTile( + initiallyExpanded: _summaryExpanded, + onExpansionChanged: (v) => setState(() => _summaryExpanded = v), + tilePadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + childrenPadding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + title: const Text( + 'Summary', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 13, + color: Color(0xFF111827), + ), + ), + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: List.generate(_totalCleaners, (index) { + final cleanerNo = index + 1; + final bySlot = cleanerSummary[cleanerNo] ?? {}; + final total = bySlot.values.fold(0, (a, b) => a + b); + + final chips = ['A', 'B', 'C', 'D'] + .map((slot) { + final c = bySlot[slot] ?? 0; + final label = _rcSlotTimeRange[slot] ?? slot; + return {'label': label, 'count': c}; + }) + .where((m) => (m['count'] as int) > 0) + .toList(); + + return Container( + margin: const EdgeInsets.only(bottom: 10), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 10, + ), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE5E7EB)), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 86, + child: Text( + 'Cleaner $cleanerNo', + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + fontWeight: FontWeight.w700, + color: Color(0xFF111827), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Wrap( + spacing: 8, + runSpacing: 8, + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + decoration: BoxDecoration( + color: total > 0 + ? const Color(0xFFEEF2FF) + : const Color(0xFFF9FAFB), + borderRadius: BorderRadius.circular(999), + border: Border.all( + color: total > 0 + ? const Color(0xFFC7D2FE) + : const Color(0xFFE5E7EB), + ), + ), + child: Text( + 'Total · $total', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 11, + fontWeight: FontWeight.w700, + color: total > 0 + ? const Color(0xFF4C4EDB) + : const Color(0xFF6B7280), + ), + ), + ), + ...chips.map((m) { + final label = m['label'] as String; + final c = m['count'] as int; + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + decoration: BoxDecoration( + color: const Color(0xFFF9FAFB), + borderRadius: + BorderRadius.circular(999), + border: Border.all( + color: const Color(0xFFE5E7EB), + ), + ), + child: Text( + '$label · $c', + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 11, + fontWeight: FontWeight.w600, + color: Color(0xFF6B7280), + ), + ), + ); + }), + ], + ), + ), + ], + ), + ); + }), + ), + ], + ), + ), + ), + ), + const SizedBox(height: 8), + // Bookings: Confirmed Slots and Buffer Slots as dropdowns + Expanded( + child: ListView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 16), + children: [ + ExpansionTile( + initiallyExpanded: _confirmedSlotsExpanded, + onExpansionChanged: (v) => + setState(() => _confirmedSlotsExpanded = v), + tilePadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 0), + childrenPadding: const EdgeInsets.only(left: 4, right: 4, bottom: 8), + title: Text( + 'Confirmed Slots (${confirmedIndices.length})', + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Color(0xFF111827), + ), + ), + children: confirmedIndices.isEmpty + ? [ + const Padding( + padding: EdgeInsets.only(bottom: 8), + child: Text( + 'No confirmed bookings.', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + ), + ] + : confirmedIndices.map((index) { + final booking = _bookings[index]; + final room = booking['roomNumber']?.toString() ?? '—'; + final slot = booking['slot']?.toString() ?? ''; + final timeRange = booking['timeRange']?.toString(); + final slotLabel = (timeRange != null && timeRange.isNotEmpty) + ? timeRange + : 'Slot $slot'; + return _RcAssignRow( + room: room.startsWith('Room ') ? room : 'Room $room', + slotLabel: slotLabel, + totalCleaners: _totalCleaners, + value: _assignments[index], + onChanged: (value) { + setState(() => _assignments[index] = value); + }, + ); + }).toList(), + ), + ExpansionTile( + initiallyExpanded: _bufferSlotsExpanded, + onExpansionChanged: (v) => + setState(() => _bufferSlotsExpanded = v), + tilePadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 0), + childrenPadding: const EdgeInsets.only(left: 4, right: 4, bottom: 8), + title: Text( + 'Buffer Slots (${bufferIndices.length})', + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Color(0xFF111827), + ), + ), + children: bufferIndices.isEmpty + ? [ + const Padding( + padding: EdgeInsets.only(bottom: 8), + child: Text( + 'No buffer bookings.', + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + ), + ] + : bufferIndices.map((index) { + final booking = _bookings[index]; + final room = booking['roomNumber']?.toString() ?? '—'; + final slot = booking['slot']?.toString() ?? ''; + final timeRange = booking['timeRange']?.toString(); + final slotLabel = (timeRange != null && timeRange.isNotEmpty) + ? timeRange + : 'Slot $slot'; + return _RcAssignRow( + room: room.startsWith('Room ') ? room : 'Room $room', + slotLabel: slotLabel, + totalCleaners: _totalCleaners, + value: _assignments[index], + onChanged: (value) { + setState(() => _assignments[index] = value); + }, + ); + }).toList(), + ), + ], + ), + ), + ], + ); + } +} + +class _RcAssignRow extends StatelessWidget { + final String room; + final String slotLabel; + final int totalCleaners; + final int? value; + final ValueChanged onChanged; + + const _RcAssignRow({ + required this.room, + required this.slotLabel, + required this.totalCleaners, + required this.value, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return Container( + margin: const EdgeInsets.only(bottom: 12), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all(color: const Color(0xFFE5E7EB)), + boxShadow: [ + BoxShadow( + color: Colors.black.withOpacity(0.02), + blurRadius: 6, + offset: const Offset(0, 2), + ), + ], + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + room, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontWeight: FontWeight.w600, + fontSize: 14, + color: Colors.black, + ), + ), + const SizedBox(height: 2), + Text( + slotLabel, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 12, + color: Color(0xFF6B7280), + ), + ), + ], + ), + ), + const SizedBox(width: 12), + SizedBox( + width: 190, + child: DropdownButtonFormField( + value: value, + items: [ + const DropdownMenuItem( + value: null, + child: Text( + 'Unassigned', + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF6B7280), + ), + ), + ), + ...List.generate(totalCleaners, (index) { + final cleanerNo = index + 1; + return DropdownMenuItem( + value: cleanerNo, + child: Text( + 'Room Cleaner $cleanerNo', + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontFamily: 'OpenSans_regular', + fontSize: 13, + color: Color(0xFF111827), + ), + ), + ); + }), + ], + onChanged: onChanged, + decoration: InputDecoration( + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 8, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide( + color: Color(0xFFE5E7EB), + ), + ), + ), + dropdownColor: Colors.white, + borderRadius: BorderRadius.circular(10), + icon: const Icon( + Icons.keyboard_arrow_down_rounded, + size: 18, + color: Color(0xFF6B7280), + ), + ), + ), + ], + ), + ), + ); + } +} + diff --git a/rc_frontend/lib/utilities/hq_version_checker.dart b/rc_frontend/lib/utilities/hq_version_checker.dart new file mode 100644 index 00000000..492a75aa --- /dev/null +++ b/rc_frontend/lib/utilities/hq_version_checker.dart @@ -0,0 +1,213 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import 'package:dio/dio.dart'; + +import '../constants/endpoint.dart'; + +/// HQ app version check: v1 only. If app version < minVersionv1 → force update (no skip). +/// Structure mirrors frontend2 VersionChecker; only check logic is v1-only. +class HqVersionChecker { + static String? _appVersion; + static String? _buildNumber; + static String? _deviceType; + static bool _updateRequired = false; + static String? _storeUrl; + static String? _updateMessage; + + static String getDeviceType() { + if (kIsWeb) { + return 'Web'; + } else if (Platform.isAndroid) { + return 'Android'; + } else if (Platform.isIOS) { + return 'iOS'; + } else if (Platform.isMacOS) { + return 'macOS'; + } else if (Platform.isWindows) { + return 'Windows'; + } else if (Platform.isLinux) { + return 'Linux'; + } else { + return 'Unknown'; + } + } + + static Future init() async { + _deviceType = getDeviceType(); + + // Get app version info + final packageInfo = await PackageInfo.fromPlatform(); + _appVersion = packageInfo.version; + _buildNumber = packageInfo.buildNumber; + } + + /// Check version against server: v1 only. If app version < minVersionv1 → force update. + static Future checkForUpdate() async { + try { + if (_deviceType != 'Android' && _deviceType != 'iOS') { + return false; + } + + // HQ is Android-only; skip check on iOS for consistency with getDeviceType + if (_deviceType != 'Android') { + return false; + } + + final dio = Dio(); + final response = await dio.get(HqAppVersionEndpoints.getAndroidVersion); + + if (response.statusCode == 200 && response.data['success'] == true) { + final data = response.data['data']; + + final String minVersionv1 = + data['minVersionv1'] as String? ?? data['minHQversion'] as String? ?? '1.0.0'; + _storeUrl = data['storeUrl'] as String?; + _updateMessage = data['updateMessage'] as String?; + + if (_compareVersions(_appVersion!, minVersionv1) >= 0) { + _updateRequired = false; + return false; + } else { + _updateRequired = true; + return true; + } + } + + return false; + } catch (e) { + if (kDebugMode) debugPrint('HqVersionChecker error: $e'); + _updateRequired = false; + return false; + } + } + + /// Compare two versions semantically + /// Returns: -1 if version1 < version2 + /// 0 if version1 == version2 + /// 1 if version1 > version2 + static int _compareVersions(String version1, String version2) { + try { + final v1Parts = version1.split('.').map((e) => int.parse(e)).toList(); + final v2Parts = version2.split('.').map((e) => int.parse(e)).toList(); + + final maxLength = + v1Parts.length > v2Parts.length ? v1Parts.length : v2Parts.length; + while (v1Parts.length < maxLength) { + v1Parts.add(0); + } + while (v2Parts.length < maxLength) { + v2Parts.add(0); + } + + for (int i = 0; i < maxLength; i++) { + if (v1Parts[i] < v2Parts[i]) { + return -1; + } + if (v1Parts[i] > v2Parts[i]) { + return 1; + } + } + + return 0; + } catch (e) { + if (kDebugMode) { + debugPrint('Error comparing versions $version1 vs $version2: $e'); + } + return 0; + } + } + + /// Show update required dialog (same UI as frontend2 VersionChecker.showUpdateDialog) + static Future showUpdateDialog(BuildContext context) async { + await showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext context) { + return PopScope( + canPop: false, + child: Dialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + backgroundColor: Colors.white, + elevation: 10, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Align( + alignment: Alignment.centerLeft, + child: Text( + _updateMessage ?? 'Update available. Please update.', + style: const TextStyle( + color: Color(0xFF1A1A2E), + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerRight, + child: ElevatedButton( + onPressed: () => _openStore(), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF4C4EDB), + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + elevation: 0, + ), + child: const Text( + 'Update', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), + ), + ); + }, + ); + } + + /// Open store URL + static Future _openStore() async { + if (_storeUrl != null) { + final uri = Uri.parse(_storeUrl!); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } + } + + static Future openStore() async { + await _openStore(); + } + + // Getters (same as frontend2) + static String get appVersion => _appVersion ?? 'Unknown'; + static String get buildNumber => _buildNumber ?? 'Unknown'; + static String get deviceType => _deviceType ?? 'Unknown'; + static String get fullVersion => '$appVersion+$buildNumber'; + static bool get updateRequired => _updateRequired; + static String? get storeUrl => _storeUrl; + static String get updateMessage => + _updateMessage ?? 'Update available. Please update.'; +} diff --git a/rc_frontend/linux/.gitignore b/rc_frontend/linux/.gitignore new file mode 100644 index 00000000..d3896c98 --- /dev/null +++ b/rc_frontend/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/rc_frontend/linux/CMakeLists.txt b/rc_frontend/linux/CMakeLists.txt new file mode 100644 index 00000000..3aaf1a1b --- /dev/null +++ b/rc_frontend/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "rc_frontend") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.rc_frontend") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/rc_frontend/linux/flutter/CMakeLists.txt b/rc_frontend/linux/flutter/CMakeLists.txt new file mode 100644 index 00000000..d5bd0164 --- /dev/null +++ b/rc_frontend/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/rc_frontend/linux/flutter/generated_plugin_registrant.cc b/rc_frontend/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000..f6f23bfe --- /dev/null +++ b/rc_frontend/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/rc_frontend/linux/flutter/generated_plugin_registrant.h b/rc_frontend/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..e0f0a47b --- /dev/null +++ b/rc_frontend/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/rc_frontend/linux/flutter/generated_plugins.cmake b/rc_frontend/linux/flutter/generated_plugins.cmake new file mode 100644 index 00000000..f16b4c34 --- /dev/null +++ b/rc_frontend/linux/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/rc_frontend/linux/runner/CMakeLists.txt b/rc_frontend/linux/runner/CMakeLists.txt new file mode 100644 index 00000000..e97dabc7 --- /dev/null +++ b/rc_frontend/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/rc_frontend/linux/runner/main.cc b/rc_frontend/linux/runner/main.cc new file mode 100644 index 00000000..e7c5c543 --- /dev/null +++ b/rc_frontend/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/rc_frontend/linux/runner/my_application.cc b/rc_frontend/linux/runner/my_application.cc new file mode 100644 index 00000000..ea298c59 --- /dev/null +++ b/rc_frontend/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "rc_frontend"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "rc_frontend"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/rc_frontend/linux/runner/my_application.h b/rc_frontend/linux/runner/my_application.h new file mode 100644 index 00000000..db16367a --- /dev/null +++ b/rc_frontend/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/rc_frontend/macos/.gitignore b/rc_frontend/macos/.gitignore new file mode 100644 index 00000000..746adbb6 --- /dev/null +++ b/rc_frontend/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/rc_frontend/macos/Flutter/Flutter-Debug.xcconfig b/rc_frontend/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 00000000..4b81f9b2 --- /dev/null +++ b/rc_frontend/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/rc_frontend/macos/Flutter/Flutter-Release.xcconfig b/rc_frontend/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 00000000..5caa9d15 --- /dev/null +++ b/rc_frontend/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/rc_frontend/macos/Flutter/GeneratedPluginRegistrant.swift b/rc_frontend/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 00000000..6d5d0776 --- /dev/null +++ b/rc_frontend/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import package_info_plus +import share_plus +import shared_preferences_foundation +import url_launcher_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) + SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) +} diff --git a/rc_frontend/macos/Podfile b/rc_frontend/macos/Podfile new file mode 100644 index 00000000..ff5ddb3b --- /dev/null +++ b/rc_frontend/macos/Podfile @@ -0,0 +1,42 @@ +platform :osx, '10.15' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/rc_frontend/macos/Runner.xcodeproj/project.pbxproj b/rc_frontend/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..13fdc6a2 --- /dev/null +++ b/rc_frontend/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* rc_frontend.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "rc_frontend.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* rc_frontend.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* rc_frontend.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/rc_frontend.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/rc_frontend"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/rc_frontend.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/rc_frontend"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/rc_frontend.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/rc_frontend"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/rc_frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/rc_frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/rc_frontend/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/rc_frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/rc_frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..3ce5cc77 --- /dev/null +++ b/rc_frontend/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/rc_frontend/macos/Runner.xcworkspace/contents.xcworkspacedata b/rc_frontend/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..1d526a16 --- /dev/null +++ b/rc_frontend/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/rc_frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/rc_frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/rc_frontend/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/rc_frontend/macos/Runner/AppDelegate.swift b/rc_frontend/macos/Runner/AppDelegate.swift new file mode 100644 index 00000000..b3c17614 --- /dev/null +++ b/rc_frontend/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..a2ec33f1 --- /dev/null +++ b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 00000000..82b6f9d9 Binary files /dev/null and b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 00000000..13b35eba Binary files /dev/null and b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 00000000..0a3f5fa4 Binary files /dev/null and b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 00000000..bdb57226 Binary files /dev/null and b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 00000000..f083318e Binary files /dev/null and b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 00000000..326c0e72 Binary files /dev/null and b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 00000000..2f1632cf Binary files /dev/null and b/rc_frontend/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/rc_frontend/macos/Runner/Base.lproj/MainMenu.xib b/rc_frontend/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 00000000..80e867a4 --- /dev/null +++ b/rc_frontend/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/rc_frontend/macos/Runner/Configs/AppInfo.xcconfig b/rc_frontend/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 00000000..f83df97a --- /dev/null +++ b/rc_frontend/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = rc_frontend + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.rcFrontend + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/rc_frontend/macos/Runner/Configs/Debug.xcconfig b/rc_frontend/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 00000000..36b0fd94 --- /dev/null +++ b/rc_frontend/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/rc_frontend/macos/Runner/Configs/Release.xcconfig b/rc_frontend/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 00000000..dff4f495 --- /dev/null +++ b/rc_frontend/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/rc_frontend/macos/Runner/Configs/Warnings.xcconfig b/rc_frontend/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 00000000..42bcbf47 --- /dev/null +++ b/rc_frontend/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/rc_frontend/macos/Runner/DebugProfile.entitlements b/rc_frontend/macos/Runner/DebugProfile.entitlements new file mode 100644 index 00000000..dddb8a30 --- /dev/null +++ b/rc_frontend/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/rc_frontend/macos/Runner/Info.plist b/rc_frontend/macos/Runner/Info.plist new file mode 100644 index 00000000..4789daa6 --- /dev/null +++ b/rc_frontend/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/rc_frontend/macos/Runner/MainFlutterWindow.swift b/rc_frontend/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 00000000..3cc05eb2 --- /dev/null +++ b/rc_frontend/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/rc_frontend/macos/Runner/Release.entitlements b/rc_frontend/macos/Runner/Release.entitlements new file mode 100644 index 00000000..852fa1a4 --- /dev/null +++ b/rc_frontend/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/rc_frontend/macos/RunnerTests/RunnerTests.swift b/rc_frontend/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..61f3bd1f --- /dev/null +++ b/rc_frontend/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/rc_frontend/pubspec.lock b/rc_frontend/pubspec.lock new file mode 100644 index 00000000..12579a0e --- /dev/null +++ b/rc_frontend/pubspec.lock @@ -0,0 +1,706 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + barcode: + dependency: transitive + description: + name: barcode + sha256: "7b6729c37e3b7f34233e2318d866e8c48ddb46c1f7ad01ff7bb2a8de1da2b9f4" + url: "https://pub.dev" + source: hosted + version: "2.2.9" + bidi: + dependency: transitive + description: + name: bidi + sha256: "77f475165e94b261745cf1032c751e2032b8ed92ccb2bf5716036db79320637d" + url: "https://pub.dev" + source: hosted + version: "2.0.13" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + url: "https://pub.dev" + source: hosted + version: "0.3.5+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dio: + dependency: "direct main" + description: + name: dio + sha256: aff32c08f92787a557dd5c0145ac91536481831a01b4648136373cddb0e64f8c + url: "https://pub.dev" + source: hosted + version: "5.9.2" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "2f9e64323a7c3c7ef69567d5c800424a11f8337b8b228bad02524c9fb3c1f340" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + font_awesome_flutter: + dependency: "direct main" + description: + name: font_awesome_flutter + sha256: b9011df3a1fa02993630b8fb83526368cf2206a711259830325bab2f1d2a4eb0 + url: "https://pub.dev" + source: hosted + version: "10.12.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + hooks: + dependency: transitive + description: + name: hooks + sha256: e79ed1e8e1929bc6ecb6ec85f0cb519c887aa5b423705ded0d0f2d9226def388 + url: "https://pub.dev" + source: hosted + version: "1.0.2" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" + url: "https://pub.dev" + source: hosted + version: "4.5.4" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "92b2ca62c8bd2b8d2f267cdfccf9bfbdb7322f778f8f91b3ce5b5cda23a3899f" + url: "https://pub.dev" + source: hosted + version: "0.17.5" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + url: "https://pub.dev" + source: hosted + version: "9.3.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968" + url: "https://pub.dev" + source: hosted + version: "8.3.1" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e + url: "https://pub.dev" + source: hosted + version: "2.2.22" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + pdf: + dependency: "direct main" + description: + name: pdf + sha256: "28eacad99bffcce2e05bba24e50153890ad0255294f4dd78a17075a2ba5c8416" + url: "https://pub.dev" + source: hosted + version: "3.11.3" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + posix: + dependency: transitive + description: + name: posix + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + url: "https://pub.dev" + source: hosted + version: "6.5.0" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + qr: + dependency: transitive + description: + name: qr + sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: fce43200aa03ea87b91ce4c3ac79f0cecd52e2a7a56c7a4185023c271fbfa6da + url: "https://pub.dev" + source: hosted + version: "10.1.4" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: cc012a23fc2d479854e6c80150696c4a5f5bb62cb89af4de1c505cf78d0a5d0b + url: "https://pub.dev" + source: hosted + version: "5.0.2" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "8374d6200ab33ac99031a852eba4c8eb2170c4bf20778b3e2c9eccb45384fb41" + url: "https://pub.dev" + source: hosted + version: "2.4.21" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + url: "https://pub.dev" + source: hosted + version: "0.7.7" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "767344bf3063897b5cf0db830e94f904528e6dd50a6dfaf839f0abf509009611" + url: "https://pub.dev" + source: hosted + version: "6.3.28" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "580fe5dfb51671ae38191d316e027f6b76272b026370708c2d898799750a02b0" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: d5e14138b3bc193a0f63c10a53c94b91d399df0512b1f29b94a043db7482384a + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "368adf46f71ad3c21b8f06614adb38346f193f3a59ba8fe9a2fd74133070ba18" + url: "https://pub.dev" + source: hosted + version: "3.2.5" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: d0412fcf4c6b31ecfdb7762359b7206ffba3bbffd396c6d9f9c4616ece476c1f + url: "https://pub.dev" + source: hosted + version: "2.4.2" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "712c70ab1b99744ff066053cbe3e80c73332b38d46e5e945c98689b2e66fc15f" + url: "https://pub.dev" + source: hosted + version: "3.1.5" + uuid: + dependency: transitive + description: + name: uuid + sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + url: "https://pub.dev" + source: hosted + version: "4.5.3" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + url: "https://pub.dev" + source: hosted + version: "15.0.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + win32: + dependency: transitive + description: + name: win32 + sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + url: "https://pub.dev" + source: hosted + version: "5.15.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.dev" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.10.7 <4.0.0" + flutter: ">=3.38.4" diff --git a/rc_frontend/pubspec.yaml b/rc_frontend/pubspec.yaml new file mode 100644 index 00000000..f76dc226 --- /dev/null +++ b/rc_frontend/pubspec.yaml @@ -0,0 +1,97 @@ +name: rc_frontend +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.10.7 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + dio: ^5.8.0+1 + shared_preferences: ^2.3.2 + package_info_plus: ^8.1.3 + url_launcher: ^6.3.1 + pdf: ^3.10.7 + path_provider: ^2.1.2 + share_plus: ^10.1.3 + font_awesome_flutter: ^10.7.0 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/rc_frontend/test/widget_test.dart b/rc_frontend/test/widget_test.dart new file mode 100644 index 00000000..72a282d9 --- /dev/null +++ b/rc_frontend/test/widget_test.dart @@ -0,0 +1,30 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:rc_frontend/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that our counter starts at 0. + expect(find.text('0'), findsOneWidget); + expect(find.text('1'), findsNothing); + + // Tap the '+' icon and trigger a frame. + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + // Verify that our counter has incremented. + expect(find.text('0'), findsNothing); + expect(find.text('1'), findsOneWidget); + }); +} diff --git a/rc_frontend/web/favicon.png b/rc_frontend/web/favicon.png new file mode 100644 index 00000000..8aaa46ac Binary files /dev/null and b/rc_frontend/web/favicon.png differ diff --git a/rc_frontend/web/icons/Icon-192.png b/rc_frontend/web/icons/Icon-192.png new file mode 100644 index 00000000..b749bfef Binary files /dev/null and b/rc_frontend/web/icons/Icon-192.png differ diff --git a/rc_frontend/web/icons/Icon-512.png b/rc_frontend/web/icons/Icon-512.png new file mode 100644 index 00000000..88cfd48d Binary files /dev/null and b/rc_frontend/web/icons/Icon-512.png differ diff --git a/rc_frontend/web/icons/Icon-maskable-192.png b/rc_frontend/web/icons/Icon-maskable-192.png new file mode 100644 index 00000000..eb9b4d76 Binary files /dev/null and b/rc_frontend/web/icons/Icon-maskable-192.png differ diff --git a/rc_frontend/web/icons/Icon-maskable-512.png b/rc_frontend/web/icons/Icon-maskable-512.png new file mode 100644 index 00000000..d69c5669 Binary files /dev/null and b/rc_frontend/web/icons/Icon-maskable-512.png differ diff --git a/rc_frontend/web/index.html b/rc_frontend/web/index.html new file mode 100644 index 00000000..98418425 --- /dev/null +++ b/rc_frontend/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + rc_frontend + + + + + + diff --git a/rc_frontend/web/manifest.json b/rc_frontend/web/manifest.json new file mode 100644 index 00000000..b734ac5a --- /dev/null +++ b/rc_frontend/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "rc_frontend", + "short_name": "rc_frontend", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/rc_frontend/windows/.gitignore b/rc_frontend/windows/.gitignore new file mode 100644 index 00000000..d492d0d9 --- /dev/null +++ b/rc_frontend/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/rc_frontend/windows/CMakeLists.txt b/rc_frontend/windows/CMakeLists.txt new file mode 100644 index 00000000..e0f3e0e3 --- /dev/null +++ b/rc_frontend/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(rc_frontend LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "rc_frontend") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/rc_frontend/windows/flutter/CMakeLists.txt b/rc_frontend/windows/flutter/CMakeLists.txt new file mode 100644 index 00000000..903f4899 --- /dev/null +++ b/rc_frontend/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/rc_frontend/windows/flutter/generated_plugin_registrant.cc b/rc_frontend/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 00000000..c3384ec5 --- /dev/null +++ b/rc_frontend/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + SharePlusWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); +} diff --git a/rc_frontend/windows/flutter/generated_plugin_registrant.h b/rc_frontend/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 00000000..dc139d85 --- /dev/null +++ b/rc_frontend/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/rc_frontend/windows/flutter/generated_plugins.cmake b/rc_frontend/windows/flutter/generated_plugins.cmake new file mode 100644 index 00000000..01d38362 --- /dev/null +++ b/rc_frontend/windows/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + share_plus + url_launcher_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/rc_frontend/windows/runner/CMakeLists.txt b/rc_frontend/windows/runner/CMakeLists.txt new file mode 100644 index 00000000..394917c0 --- /dev/null +++ b/rc_frontend/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/rc_frontend/windows/runner/Runner.rc b/rc_frontend/windows/runner/Runner.rc new file mode 100644 index 00000000..cb98cca4 --- /dev/null +++ b/rc_frontend/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "rc_frontend" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "rc_frontend" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "rc_frontend.exe" "\0" + VALUE "ProductName", "rc_frontend" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/rc_frontend/windows/runner/flutter_window.cpp b/rc_frontend/windows/runner/flutter_window.cpp new file mode 100644 index 00000000..955ee303 --- /dev/null +++ b/rc_frontend/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/rc_frontend/windows/runner/flutter_window.h b/rc_frontend/windows/runner/flutter_window.h new file mode 100644 index 00000000..6da0652f --- /dev/null +++ b/rc_frontend/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/rc_frontend/windows/runner/main.cpp b/rc_frontend/windows/runner/main.cpp new file mode 100644 index 00000000..8b4c2288 --- /dev/null +++ b/rc_frontend/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"rc_frontend", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/rc_frontend/windows/runner/resource.h b/rc_frontend/windows/runner/resource.h new file mode 100644 index 00000000..66a65d1e --- /dev/null +++ b/rc_frontend/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/rc_frontend/windows/runner/resources/app_icon.ico b/rc_frontend/windows/runner/resources/app_icon.ico new file mode 100644 index 00000000..c04e20ca Binary files /dev/null and b/rc_frontend/windows/runner/resources/app_icon.ico differ diff --git a/rc_frontend/windows/runner/runner.exe.manifest b/rc_frontend/windows/runner/runner.exe.manifest new file mode 100644 index 00000000..153653e8 --- /dev/null +++ b/rc_frontend/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/rc_frontend/windows/runner/utils.cpp b/rc_frontend/windows/runner/utils.cpp new file mode 100644 index 00000000..3a0b4651 --- /dev/null +++ b/rc_frontend/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/rc_frontend/windows/runner/utils.h b/rc_frontend/windows/runner/utils.h new file mode 100644 index 00000000..3879d547 --- /dev/null +++ b/rc_frontend/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/rc_frontend/windows/runner/win32_window.cpp b/rc_frontend/windows/runner/win32_window.cpp new file mode 100644 index 00000000..60608d0f --- /dev/null +++ b/rc_frontend/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/rc_frontend/windows/runner/win32_window.h b/rc_frontend/windows/runner/win32_window.h new file mode 100644 index 00000000..e901dde6 --- /dev/null +++ b/rc_frontend/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/server/.gitignore b/server/.gitignore index 6303063f..45511baa 100644 --- a/server/.gitignore +++ b/server/.gitignore @@ -2,4 +2,8 @@ node_modules/ .env .secrets/ -modules/notification/serviceAccountKey.json \ No newline at end of file +modules/notification/serviceAccountKey.json + +# App version config (environment-specific) +modules/app_version/config/appVersion.json +modules/app_version/config/hqAppVersion.json \ No newline at end of file diff --git a/server/ecosystem.config.js b/server/ecosystem.config.js index a56c5592..36717fc6 100644 --- a/server/ecosystem.config.js +++ b/server/ecosystem.config.js @@ -1,17 +1,28 @@ module.exports = { - apps : [{ - name : "gateway", - script : "./index.js", - env: { PORT: 3000 } - }, { - name : "api-v1", - script : "./index.js", // Relative to cwd - cwd: "./v1", // Sets the "Current Working Directory" so imports work - env: { PORT: 3001 } - }, { - name : "api-v2", - script : "./index.js", // Relative to cwd - cwd: "./v2", - env: { PORT: 3002 } - }] -} + apps: [ + { + name: "gateway", + script: "./index.js", + cwd: __dirname, + env: { PORT: 3000 }, + max_memory_restart: "512M", + }, + { + name: "api-v1", + script: "./index.js", // Relative to cwd + cwd: "./v1", // Sets the "Current Working Directory" so imports work + instances: "max", // Uses all available CPU cores + exec_mode: "cluster", // Enables multi-threading + watch: false, + env: { PORT: 3001 }, + max_memory_restart: "1G", // Restart if a worker exceeds 1GB (helps recover from memory leaks) + }, + { + name: "api-v2", + script: "./index.js", // Relative to cwd + cwd: "./v2", + env: { PORT: 3002 }, + max_memory_restart: "512M", + }, + ], +}; diff --git a/server/index.js b/server/index.js index 5c7eecc9..37a24645 100644 --- a/server/index.js +++ b/server/index.js @@ -1,9 +1,14 @@ // server/index.js (The Gateway) require("dotenv").config(); +const { installProcessHandlers } = require("./processHandlers.js"); +installProcessHandlers(); const express = require("express"); const { createProxyMiddleware } = require("http-proxy-middleware"); const cors = require("cors"); -const appVersionRoute = require("./modules/app_version/appVersionRoute.js"); +const { + appVersionRouter, + hqAppVersionRouter, +} = require("./modules/app_version/appVersionRoute.js"); const app = express(); const PORT = process.env.PORT || 3000; // The public port @@ -63,8 +68,9 @@ const selectProxyTarget = (req) => { return targets.v1; }; -// 2.5. Centralized App Version Route (Before Proxy) -app.use("/api/app-version", appVersionRoute); +// 2.5. Centralized App Version Routes (Before Proxy) +app.use("/api/app-version", appVersionRouter); +app.use("/api/hq-app-version", hqAppVersionRouter); // 3. Proxy Setup - http-proxy-middleware automatically handles multipart/form-data streaming const apiProxy = createProxyMiddleware({ @@ -80,8 +86,8 @@ const apiProxy = createProxyMiddleware({ // 4. Forward everything to the proxy (but don't parse body - proxy handles it) app.use("/", apiProxy); -app.listen(PORT, () => { - console.log(`🚀 Gateway running on PORT ${PORT}`); +app.listen(PORT, '0.0.0.0', () => { + console.log(`🚀 Gateway running on PORT ${PORT} (0.0.0.0)`); console.log(` -> V1 (Legacy) upstream: ${targets.v1}`); console.log(` -> V2 (New) upstream: ${targets.v2}`); }); diff --git a/server/modules/app_version/appVersionController.js b/server/modules/app_version/appVersionController.js index bee9f88a..41e1ed2d 100644 --- a/server/modules/app_version/appVersionController.js +++ b/server/modules/app_version/appVersionController.js @@ -1,15 +1,16 @@ const fs = require("fs"); const path = require("path"); -// Common config file - same directory -const configPath = path.join(__dirname, "./config/appVersion.json"); +// Common config files - same directory +const mainConfigPath = path.join(__dirname, "./config/appVersion.json"); +const hqConfigPath = path.join(__dirname, "./config/hqAppVersion.json"); /** - * Read version config from JSON file + * Read main HABit app version config */ const getVersionConfig = () => { try { - const data = fs.readFileSync(configPath, "utf8"); + const data = fs.readFileSync(mainConfigPath, "utf8"); return JSON.parse(data); } catch (error) { console.error("Error reading version config:", error); @@ -31,11 +32,12 @@ const getVersionConfig = () => { }; /** - * Save version config to JSON file + * Save main HABit app version config */ const saveVersionConfig = (config) => { try { - fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); + fs.mkdirSync(path.dirname(mainConfigPath), { recursive: true }); + fs.writeFileSync(mainConfigPath, JSON.stringify(config, null, 2)); return true; } catch (error) { console.error("Error saving version config:", error); @@ -43,6 +45,40 @@ const saveVersionConfig = (config) => { } }; +/** + * Read HABit HQ (manager app) version config + */ +const getHqVersionConfig = () => { + try { + const data = fs.readFileSync(hqConfigPath, "utf8"); + return JSON.parse(data); + } catch (error) { + console.error("Error reading HQ version config:", error); + // Default skeleton: v1 only, force update when below minVersionv1 (Android only for HQ) + return { + android: { + minVersionv1: "1.0.0", + storeUrl: "", + updateMessage: "A new version is available. Please update to continue.", + }, + }; + } +}; + +/** + * Save HABit HQ (manager app) version config + */ +const saveHqVersionConfig = (config) => { + try { + fs.mkdirSync(path.dirname(hqConfigPath), { recursive: true }); + fs.writeFileSync(hqConfigPath, JSON.stringify(config, null, 2)); + return true; + } catch (error) { + console.error("Error saving HQ version config:", error); + return false; + } +}; + /** * Get version info for a specific platform (returns both v1 and v2) */ @@ -152,8 +188,115 @@ const getAllVersionInfo = (req, res) => { } }; +/** + * Get HABit HQ version info (Android only) + */ +const getHqVersionInfo = (req, res) => { + try { + const { platform } = req.params; + if (platform.toLowerCase() !== "android") { + return res.status(400).json({ + success: false, + message: "Invalid platform. HABit HQ supports only 'android'.", + }); + } + + const config = getHqVersionConfig(); + const platformConfig = config.android || {}; + + return res.status(200).json({ + success: true, + data: { + platform: "android", + minVersionv1: platformConfig.minVersionv1, + storeUrl: platformConfig.storeUrl, + updateMessage: platformConfig.updateMessage, + // If app version < minVersionv1, client must force update (no optional skip) + forceUpdate: true, + minHQversion: platformConfig.minVersionv1, + }, + }); + } catch (error) { + console.error("Error fetching HQ version info:", error); + return res.status(500).json({ + success: false, + message: "Failed to fetch HABit HQ version info", + error: error.message, + }); + } +}; + +/** + * Update HABit HQ version info (Android only, admin) + */ +const updateHqVersionInfo = (req, res) => { + try { + const { platform } = req.params; + if (platform.toLowerCase() !== "android") { + return res.status(400).json({ + success: false, + message: "Invalid platform. HABit HQ supports only 'android'.", + }); + } + + const { minVersionv1, storeUrl, updateMessage } = req.body; + + const config = getHqVersionConfig(); + if (!config.android) { + config.android = {}; + } + + if (minVersionv1) config.android.minVersionv1 = minVersionv1; + if (storeUrl) config.android.storeUrl = storeUrl; + if (updateMessage) config.android.updateMessage = updateMessage; + + if (saveHqVersionConfig(config)) { + return res.status(200).json({ + success: true, + message: "HABit HQ version info updated successfully", + data: config.android, + }); + } else { + return res.status(500).json({ + success: false, + message: "Failed to save HABit HQ version config", + }); + } + } catch (error) { + console.error("Error updating HQ version info:", error); + return res.status(500).json({ + success: false, + message: "Failed to update HABit HQ version info", + error: error.message, + }); + } +}; + +/** + * Get all HABit HQ version info + */ +const getAllHqVersionInfo = (req, res) => { + try { + const config = getHqVersionConfig(); + return res.status(200).json({ + success: true, + data: config, + }); + } catch (error) { + console.error("Error fetching all HQ version info:", error); + return res.status(500).json({ + success: false, + message: "Failed to fetch HABit HQ version info", + error: error.message, + }); + } +}; + module.exports = { getVersionInfo, updateVersionInfo, getAllVersionInfo, + getHqVersionInfo, + updateHqVersionInfo, + getAllHqVersionInfo, }; diff --git a/server/modules/app_version/appVersionRoute.js b/server/modules/app_version/appVersionRoute.js index 7411ec2a..b3e024f4 100644 --- a/server/modules/app_version/appVersionRoute.js +++ b/server/modules/app_version/appVersionRoute.js @@ -1,36 +1,40 @@ const express = require("express"); -const router = express.Router(); +const appVersionRouter = express.Router(); +const hqAppVersionRouter = express.Router(); const { getVersionInfo, updateVersionInfo, getAllVersionInfo, + getHqVersionInfo, + updateHqVersionInfo, + getAllHqVersionInfo, } = require("./appVersionController"); /** - * @swagger - * /api/app-version/{platform}: - * get: - * summary: Get app version info for a platform - * tags: [App Version] - * parameters: - * - in: path - * name: platform - * required: true - * schema: - * type: string - * enum: [android, ios] - * description: The platform (android or ios) - * responses: - * 200: - * description: Version info retrieved successfully - * 400: - * description: Invalid platform - * 500: - * description: Server error + * HABit main app version routes + * Base path (gateway): /api/app-version + * + * GET /api/app-version/:platform + * PUT /api/app-version/:platform + * GET /api/app-version/ */ -router.get("/:platform", getVersionInfo); +appVersionRouter.get("/:platform", getVersionInfo); +appVersionRouter.put("/:platform", updateVersionInfo); +appVersionRouter.get("/", getAllVersionInfo); -router.put("/:platform", updateVersionInfo); -router.get("/", getAllVersionInfo); +/** + * HABit HQ (manager app) version routes + * Base path (gateway): /api/hq-app-version + * + * GET /api/hq-app-version/android + * PUT /api/hq-app-version/android + * GET /api/hq-app-version/ + */ +hqAppVersionRouter.get("/:platform", getHqVersionInfo); +hqAppVersionRouter.put("/:platform", updateHqVersionInfo); +hqAppVersionRouter.get("/", getAllHqVersionInfo); -module.exports = router; +module.exports = { + appVersionRouter, + hqAppVersionRouter, +}; diff --git a/server/processHandlers.js b/server/processHandlers.js new file mode 100644 index 00000000..4300fb16 --- /dev/null +++ b/server/processHandlers.js @@ -0,0 +1,22 @@ +/** + * Process-level error handlers to prevent silent crashes in production. + * Require this once at the top of each entry point (gateway, v1, v2). + * + * Without these, a single unhandled promise rejection or uncaught exception + * will exit the Node process; PM2 will restart it, but the app will keep + * stopping until the root cause is fixed. + */ +function installProcessHandlers() { + process.on("unhandledRejection", (reason, promise) => { + console.error("[CRASH PREVENTION] Unhandled Rejection at:", promise, "reason:", reason); + // Don't exit - let the process keep running. Fix the code that caused this. + }); + + process.on("uncaughtException", (err) => { + console.error("[CRASH PREVENTION] Uncaught Exception:", err); + // Exit after logging so PM2 can restart a clean process. + process.exit(1); + }); +} + +module.exports = { installProcessHandlers }; diff --git a/server/v1/.DS_Store b/server/v1/.DS_Store index 1fda3cfa..832f3a2a 100644 Binary files a/server/v1/.DS_Store and b/server/v1/.DS_Store differ diff --git a/server/v1/index.js b/server/v1/index.js index 850c07d9..10eaaf91 100644 --- a/server/v1/index.js +++ b/server/v1/index.js @@ -2,6 +2,8 @@ //import authRoutes from "./modules/auth/auth.routes.js"; require("dotenv").config({ path: "../.env" }); +const { installProcessHandlers } = require("../processHandlers.js"); +installProcessHandlers(); console.log("MONGODB_URI from env:", process.env.MONGODB_URI); const authRoutes = require("./modules/auth/auth.routes.js"); const express = require("express"); @@ -14,11 +16,14 @@ const notificationRoute = require("./modules/notification/notificationRoute.js") const messRoute = require("./modules/mess/messRoute.js"); const logsRoute = require("./modules/mess/ScanLogsRoute.js"); const bugReportRoute = require("./modules/bug_report/bugReportRoute.js"); +const roomCleaningRoute = require("./modules/room_cleaning/roomCleaningRoute.js"); const cors = require("cors"); const bodyParser = require("body-parser"); +const compression = require("compression"); const { setDelegatedTokens, tokenFilePath, + initDelegatedGraphRedis, } = require("./utils/delegatedGraphAuth.js"); // New: build delegated auth URLs for starting consent @@ -44,28 +49,18 @@ function buildAuthorizeUrl() { const swaggerUi = require("swagger-ui-express"); const swaggerJsdoc = require("swagger-jsdoc"); -const { - wednesdayScheduler, - sundayScheduler, -} = require("./modules/hostel/hostelScheduler.js"); -const { - initializeFeedbackAutoScheduler, -} = require("./modules/feedback/autoFeedbackScheduler.js"); - -const { - initializeMessChangeAutoScheduler, -} = require("./modules/mess_change/autoMessChangeScheduler.js"); -const { - initializeGuestCleanupScheduler, -} = require("./modules/auth/autoGuestCleanupScheduler.js"); -const { - initializeAnonymizedUser, -} = require("./modules/user/anonymizedUserInit.js"); const messChangeRouter = require("./modules/mess_change/messchangeRoute.js"); +const galaRoute = require("./modules/gala/galaRoute.js"); require("dotenv").config(); const app = express(); app.use(bodyParser.json({ limit: "1mb" })); +app.use( + compression({ + level: 6, + threshold: 100, + }), +); const MONGOdb_uri = process.env.MONGODB_URI; const PORT = process.env.PORT || 3001; @@ -147,16 +142,44 @@ mongoose .then(() => { console.log("MongoDB connected"); - wednesdayScheduler(); - - sundayScheduler(); - - // Initialize automatic schedulers for feedback, mess change, and guest cleanup - initializeFeedbackAutoScheduler(); - initializeMessChangeAutoScheduler(); - initializeGuestCleanupScheduler(); + // Only run schedulers on the primary PM2 instance + if ( + process.env.NODE_APP_INSTANCE === "0" || + typeof process.env.NODE_APP_INSTANCE === "undefined" + ) { + console.log("Primary instance detected. Starting schedulers..."); + + const { + wednesdayScheduler, + sundayScheduler, + } = require("./modules/hostel/hostelScheduler.js"); + wednesdayScheduler(); + sundayScheduler(); + + // Initialize automatic schedulers for feedback, mess change, and guest cleanup + const { + initializeFeedbackAutoScheduler, + } = require("./modules/feedback/autoFeedbackScheduler.js"); + const { + initializeMessChangeAutoScheduler, + } = require("./modules/mess_change/autoMessChangeScheduler.js"); + const { + initializeGuestCleanupScheduler, + } = require("./modules/auth/autoGuestCleanupScheduler.js"); + + initializeFeedbackAutoScheduler(); + initializeMessChangeAutoScheduler(); + initializeGuestCleanupScheduler(); + } else { + console.log( + `Worker instance ${process.env.NODE_APP_INSTANCE} started. Schedulers disabled here.`, + ); + } // Initialize anonymized user for soft-deleted account references + const { + initializeAnonymizedUser, + } = require("./modules/user/anonymizedUserInit.js"); initializeAnonymizedUser(); }) .catch((err) => console.log(err)); @@ -209,6 +232,9 @@ app.use("/api/notification", notificationRoute); // Mess route app.use("/api/mess", messRoute); +// Gala Dinner route +app.use("/api/gala", galaRoute); + //mess change route app.use("/api/mess-change", messChangeRouter); @@ -222,6 +248,9 @@ app.use("/api/logs", logsRoute); // Bug report route app.use("/api/bug-report", bugReportRoute); +// Room cleaning availability route +app.use("/api/room-cleaning", roomCleaningRoute); + // Debug route: accept delegated tokens and save to disk for server use // WARNING: Protect this route in production (e.g., require admin auth, restrict IPs) app.post("/api/_debug/graph/delegated-token", async (req, res) => { @@ -296,8 +325,28 @@ app.get("/api/_debug/graph/callback", async (req, res) => { } }); -app.listen(PORT, () => { +// Global error handler (must be after all routes). Catches errors passed to next(err). +app.use((err, req, res, next) => { + console.error("[Express error]", err); + res.status(500).json({ message: "Internal server error" }); +}); + +const { initMessManagerWs } = require("./modules/mess/messManagerWs.js"); +const { initGalaManagerWs } = require("./modules/gala/galaManagerWs.js"); + +const server = app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); +// Initialize WebSocket servers for manager live scan logs +initMessManagerWs(server); +initGalaManagerWs(server); + +// Subscribe to Redis scan events so all cluster instances can broadcast to their local WS clients +const { initScanBroadcast } = require("./utils/scanBroadcast.js"); +initScanBroadcast(); + +// Connect to Redis and backfill delegated Graph token from disk so first request can use Redis +initDelegatedGraphRedis(); + module.exports = app; diff --git a/server/v1/middleware/authenticateJWT.js b/server/v1/middleware/authenticateJWT.js index 139c7349..df632537 100644 --- a/server/v1/middleware/authenticateJWT.js +++ b/server/v1/middleware/authenticateJWT.js @@ -104,9 +104,37 @@ const authenticateHabJWT = async (req, res, next) => { } }; +// Dedicated middleware for HABit HQ / mess-manager app. +// Validates a hostel JWT (same token as hostel frontend) and attaches +// the hostel document as `req.managerHostel`. +const authenticateMessManagerJWT = async (req, res, next) => { + let token; + + if (req.headers?.authorization) { + const authHeader = req.headers.authorization; + if (authHeader.startsWith("Bearer ")) { + token = authHeader.split(" ")[1]; + } + } + + if (!token) return next(new AppError(403, "Invalid token")); + + try { + const hostel = await Hostel.findByJWT(token); + if (!hostel) return next(new AppError(403, "Not Authenticated as manager")); + + req.managerHostel = hostel; + return next(); + } catch (err) { + console.error("Error verifying Mess Manager token:", err); + return next(new AppError(500, "Server error during authentication")); + } +}; + module.exports = { authenticateJWT, authenticateAdminJWT, authenticateUserOrAdminJWT, authenticateHabJWT, + authenticateMessManagerJWT, }; diff --git a/server/v1/modules/auth/auth.controller.js b/server/v1/modules/auth/auth.controller.js index 09e526a4..16105a43 100644 --- a/server/v1/modules/auth/auth.controller.js +++ b/server/v1/modules/auth/auth.controller.js @@ -3,6 +3,7 @@ const axios = require("axios"); const qs = require("querystring"); const jwt = require("jsonwebtoken"); const crypto = require("crypto"); +const bcrypt = require("bcrypt"); const AppError = require("../../utils/appError.js"); const { getUserFromToken, @@ -11,6 +12,7 @@ const { findUserWithAppleIdentifier, findUserWithGuestIdentifier, } = require("../user/userModel.js"); +const { Hostel } = require("../hostel/hostelModel.js"); const UserAllocHostel = require("../hostel/hostelAllocModel.js"); const { sendNotificationToUser, @@ -553,6 +555,52 @@ const guestLoginHandler = async (req, res, next) => { } }; +/** + * HABit HQ: Hostel manager login via password (no Microsoft OAuth). + * Body: { hostelName, password } + * Returns: { success, token, message? } + */ +const managerLoginHandler = async (req, res, next) => { + try { + const { hostelName, password } = req.body || {}; + + if (!hostelName || !password) { + return res.status(400).json({ + success: false, + message: "hostelName and password are required", + }); + } + + const hostel = await Hostel.findOne({ + hostel_name: hostelName, + }).select("+managerPasswordHash"); + + if (!hostel || !hostel.managerPasswordHash) { + return res.status(401).json({ + success: false, + message: "Invalid hostel or password", + }); + } + + const ok = await bcrypt.compare(String(password), hostel.managerPasswordHash); + if (!ok) { + return res.status(401).json({ + success: false, + message: "Invalid hostel or password", + }); + } + + const token = hostel.generateJWT(); + return res.status(200).json({ + success: true, + token, + }); + } catch (err) { + console.error("Error in managerLoginHandler:", err); + next(new AppError(500, "Manager login failed")); + } +}; + module.exports = { mobileRedirectHandler, webLoginHandler, @@ -561,4 +609,5 @@ module.exports = { guestLoginHandler, appleLoginHandler, linkMicrosoftAccount, + managerLoginHandler, }; diff --git a/server/v1/modules/auth/auth.routes.js b/server/v1/modules/auth/auth.routes.js index e6a1380e..11294c59 100644 --- a/server/v1/modules/auth/auth.routes.js +++ b/server/v1/modules/auth/auth.routes.js @@ -10,6 +10,7 @@ const { // meHandler, appleLoginHandler, linkMicrosoftAccount, + managerLoginHandler, } = require("./auth.controller.js"); const { authenticateJWT } = require("../../middleware/authenticateJWT.js"); @@ -93,6 +94,9 @@ router.get("/logout", logoutHandler); // Guest login router.post("/guest", guestLoginHandler); +// HABit HQ: hostel manager password login (returns hostel JWT) +router.post("/manager/login", managerLoginHandler); + // Apple Sign In router.post("/apple", appleLoginHandler); diff --git a/server/v1/modules/feedback/autoFeedbackScheduler.js b/server/v1/modules/feedback/autoFeedbackScheduler.js index 81fc4e98..d778f776 100644 --- a/server/v1/modules/feedback/autoFeedbackScheduler.js +++ b/server/v1/modules/feedback/autoFeedbackScheduler.js @@ -69,7 +69,7 @@ const scheduleFeedbackReminders = async () => { "Feedback Submission form will close in 12 hours", "All_Hostels", { redirectType: "mess_screen", isAlert: "true" } - ); + ).catch((err) => console.error("📢 12h feedback reminder send failed:", err)); console.log("📢 Sent 12h feedback reminder"); }); console.log( @@ -89,7 +89,7 @@ const scheduleFeedbackReminders = async () => { "Feedback Submission form will close in 2 hours", "All_Hostels", { redirectType: "mess_screen", isAlert: "true" } - ); + ).catch((err) => console.error("📢 2h feedback reminder send failed:", err)); console.log("📢 Sent 2h feedback reminder"); }); console.log( diff --git a/server/v1/modules/feedback/feedbackController.js b/server/v1/modules/feedback/feedbackController.js index df0b36e4..b688487c 100644 --- a/server/v1/modules/feedback/feedbackController.js +++ b/server/v1/modules/feedback/feedbackController.js @@ -7,6 +7,8 @@ const { FeedbackSettings } = require("./feedbackSettingsModel"); const { sendNotificationMessage, } = require("../notification/notificationController"); +const NodeCache = require("node-cache"); +const feedbackCache = new NodeCache({ stdTTL: 60 }); const ratingMap = { "Very Poor": 1, @@ -450,7 +452,7 @@ const enableFeedback = async (req, res) => { "Mess Feedback for this month is enabled", "All_Hostels", { redirectType: "mess_screen", isAlert: "true" }, - ); + ).catch((err) => console.error("Feedback enabled notification failed:", err)); return res.status(200).json({ message: "Feedback enabled", data: s }); } catch (e) { return res @@ -509,7 +511,7 @@ const enableFeedbackAutomatic = async () => { "Mess Feedback for this month is enabled", "All_Hostels", { redirectType: "mess_screen", isAlert: "true" }, - ); + ).catch((err) => console.error("Feedback enabled notification failed:", err)); console.log("✅ Feedback enabled automatically"); return { success: true, settings: s }; } catch (e) { @@ -545,6 +547,9 @@ const disableFeedbackAutomatic = async () => { // ========================================== const getFeedbackSettings = async (req, res) => { try { + const cachedSettings = feedbackCache.get("feedback_settings"); + if (cachedSettings) return res.status(200).json(cachedSettings); + let s = await FeedbackSettings.findOne(); if (s?.isEnabled && s.enabledAt) { const expiresAt = new Date( @@ -556,14 +561,16 @@ const getFeedbackSettings = async (req, res) => { await s.save(); } } - return res.status(200).json( - s || { - isEnabled: false, - enabledAt: null, - disabledAt: null, - currentWindowNumber: 1, - }, - ); + + const responseData = s || { + isEnabled: false, + enabledAt: null, + disabledAt: null, + currentWindowNumber: 1, + }; + + feedbackCache.set("feedback_settings", responseData); + return res.status(200).json(responseData); } catch (e) { return res.status(500).json({ message: "Failed to fetch settings", @@ -577,6 +584,9 @@ const getFeedbackSettings = async (req, res) => { // ========================================== const getFeedbackSettingsPublic = async (req, res) => { try { + const cachedSettings = feedbackCache.get("feedback_settings"); + if (cachedSettings) return res.status(200).json(cachedSettings); + let s = await FeedbackSettings.findOne(); if (s?.isEnabled && s.enabledAt) { const expiresAt = new Date( @@ -588,14 +598,16 @@ const getFeedbackSettingsPublic = async (req, res) => { await s.save(); } } - return res.status(200).json( - s || { - isEnabled: false, - enabledAt: null, - disabledAt: null, - currentWindowNumber: 1, - }, - ); + + const responseData = s || { + isEnabled: false, + enabledAt: null, + disabledAt: null, + currentWindowNumber: 1, + }; + + feedbackCache.set("feedback_settings", responseData); + return res.status(200).json(responseData); } catch (e) { return res.status(500).json({ message: "Failed to fetch settings", diff --git a/server/v1/modules/feedback/feedbackModel.js b/server/v1/modules/feedback/feedbackModel.js index 6c99885d..46c27d75 100644 --- a/server/v1/modules/feedback/feedbackModel.js +++ b/server/v1/modules/feedback/feedbackModel.js @@ -57,6 +57,9 @@ const feedbackSchema = new mongoose.Schema({ }, }); +feedbackSchema.index({ user: 1, feedbackWindowNumber: 1 }); +feedbackSchema.index({ feedbackWindowNumber: 1, caterer: 1 }); + const Feedback = mongoose.model("Feedback", feedbackSchema); module.exports = Feedback; diff --git a/server/v1/modules/gala/galaController.js b/server/v1/modules/gala/galaController.js new file mode 100644 index 00000000..5695c8c3 --- /dev/null +++ b/server/v1/modules/gala/galaController.js @@ -0,0 +1,801 @@ +const { GalaDinner } = require("./galaDinnerModel"); +const { GalaDinnerMenu, GALA_CATEGORIES } = require("./galaDinnerMenuModel"); +const { GalaDinnerScanLog } = require("./galaDinnerScanLogModel"); +const { Hostel } = require("../hostel/hostelModel"); +const { User } = require("../user/userModel"); +const { MenuItem } = require("../mess/menuItemModel"); +const { QR } = require("../qr/qrModel"); +const qrcode = require("qrcode"); +const { getCurrentTime } = require("../../utils/date.js"); + +const QR_CODE_DATA_URL_OPTIONS = { + width: 1024, + margin: 2, + type: "image/png", +}; + +/** + * HAB: Schedule a new Gala Dinner. Creates one GalaDinner and for each hostel + * 3 GalaDinnerMenus (Starters, Main Course, Desserts) each with a QR code. + */ +const scheduleGalaDinner = async (req, res) => { + try { + const { date, startersServingStartTime, dinnerServingStartTime } = req.body; + if (!date) { + return res.status(400).json({ message: "Date is required" }); + } + if (!startersServingStartTime || !dinnerServingStartTime) { + return res.status(400).json({ + message: "Starters serving start time and Dinner serving start time are required", + }); + } + const galaDate = new Date(date); + if (isNaN(galaDate.getTime())) { + return res.status(400).json({ message: "Invalid date" }); + } + + const y = galaDate.getUTCFullYear(); + const m = galaDate.getUTCMonth(); + const d = galaDate.getUTCDate(); + const startOfDay = new Date(Date.UTC(y, m, d, 0, 0, 0, 0)); + const endOfDay = new Date(Date.UTC(y, m, d, 23, 59, 59, 999)); + const existing = await GalaDinner.findOne({ + date: { $gte: startOfDay, $lte: endOfDay }, + }); + if (existing) { + return res.status(400).json({ + message: "A Gala Dinner is already scheduled on this date.", + }); + } + + const galaDinner = new GalaDinner({ + date: galaDate, + startersServingStartTime: String(startersServingStartTime).trim(), + dinnerServingStartTime: String(dinnerServingStartTime).trim(), + }); + await galaDinner.save(); + + const hostels = await Hostel.find(); + for (const hostel of hostels) { + for (const category of GALA_CATEGORIES) { + const menuDoc = new GalaDinnerMenu({ + galaDinnerId: galaDinner._id, + hostelId: hostel._id, + category, + }); + await menuDoc.save(); + + const qrPayload = menuDoc._id.toString(); + const qrDataUrl = await qrcode.toDataURL( + qrPayload, + QR_CODE_DATA_URL_OPTIONS + ); + const qrRecord = new QR({ + qr_string: qrPayload, + qr_base64: qrDataUrl, + }); + await qrRecord.save(); + + menuDoc.qrCode = qrRecord._id; + await menuDoc.save(); + } + } + + return res.status(201).json({ + message: "Gala Dinner scheduled successfully", + galaDinner: { + _id: galaDinner._id, + date: galaDinner.date, + startersServingStartTime: galaDinner.startersServingStartTime, + dinnerServingStartTime: galaDinner.dinnerServingStartTime, + hostelsCount: hostels.length, + }, + }); + } catch (error) { + console.error("scheduleGalaDinner:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * HAB: Delete a Gala Dinner and all related data (menus, items, scan logs, QRs). + */ +const deleteGalaDinner = async (req, res) => { + try { + const { galaDinnerId } = req.params; + if (!galaDinnerId) { + return res.status(400).json({ message: "Gala Dinner ID is required" }); + } + + const gala = await GalaDinner.findById(galaDinnerId); + if (!gala) { + return res.status(404).json({ message: "Gala Dinner not found" }); + } + + const menus = await GalaDinnerMenu.find({ galaDinnerId: gala._id }); + const menuIds = menus.map((m) => m._id); + const qrIds = menus.map((m) => m.qrCode).filter(Boolean); + + await MenuItem.deleteMany({ galaMenuId: { $in: menuIds } }); + await GalaDinnerScanLog.deleteMany({ galaDinnerId: gala._id }); + await GalaDinnerMenu.deleteMany({ galaDinnerId: gala._id }); + await QR.deleteMany({ _id: { $in: qrIds } }); + await GalaDinner.findByIdAndDelete(gala._id); + + return res.status(200).json({ message: "Gala Dinner cleared successfully" }); + } catch (error) { + console.error("deleteGalaDinner:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * HAB: Get Gala Dinner detail for a hostel: scan counts (Starters, Main Course, Dessert) + * and the 3 menus with items. + */ +const getGalaDinnerDetailForHostel = async (req, res) => { + try { + const { galaDinnerId } = req.params; + const hostelId = req.query.hostelId || req.params.hostelId; + if (!galaDinnerId || !hostelId) { + return res.status(400).json({ + message: "Gala Dinner ID and Hostel ID are required", + }); + } + + const gala = await GalaDinner.findById(galaDinnerId).lean(); + if (!gala) { + return res.status(404).json({ message: "Gala Dinner not found" }); + } + + const logs = await GalaDinnerScanLog.find({ + galaDinnerId, + }).lean(); + + const startersUserIds = logs.filter((l) => l.startersScanned).map((l) => l.userId); + const mainCourseUserIds = logs.filter((l) => l.mainCourseScanned).map((l) => l.userId); + const dessertsUserIds = logs.filter((l) => l.dessertsScanned).map((l) => l.userId); + + const [startersCount, mainCourseCount, dessertsCount] = await Promise.all([ + User.countDocuments({ + _id: { $in: startersUserIds }, + curr_subscribed_mess: hostelId, + }), + User.countDocuments({ + _id: { $in: mainCourseUserIds }, + curr_subscribed_mess: hostelId, + }), + User.countDocuments({ + _id: { $in: dessertsUserIds }, + curr_subscribed_mess: hostelId, + }), + ]); + + const menus = await GalaDinnerMenu.find({ + galaDinnerId, + hostelId, + }) + .populate("qrCode", "qr_base64 qr_string") + .lean(); + + const menusWithItems = await Promise.all( + menus.map(async (m) => { + const items = await MenuItem.find({ galaMenuId: m._id }).lean(); + return { ...m, items }; + }) + ); + + return res.status(200).json({ + galaDinner: gala, + hostelId, + scanStats: { + startersCount, + mainCourseCount, + dessertsCount, + }, + menus: menusWithItems, + }); + } catch (error) { + console.error("getGalaDinnerDetailForHostel:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * HAB: List all Gala Dinners (scheduled and completed), sorted by date desc. + */ +const listGalaDinners = async (req, res) => { + try { + const list = await GalaDinner.find() + .sort({ date: -1 }) + .lean(); + return res.status(200).json(list); + } catch (error) { + console.error("listGalaDinners:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * Get the next upcoming Gala Dinner (date >= today). For app and SMC. + */ +const getUpcomingGalaDinner = async (req, res) => { + try { + const now = new Date(); + const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + + const upcoming = await GalaDinner.findOne({ + date: { $gte: startOfToday }, + }) + .sort({ date: 1 }) + .lean(); + + if (!upcoming) { + return res.status(200).json(null); + } + return res.status(200).json(upcoming); + } catch (error) { + console.error("getUpcomingGalaDinner:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * Get upcoming Gala Dinner with 3 menus for a hostel (with QR and items). + * For SMC: hostelId from req.hostel (hostel token) or req.user.hostel (user token). + * For app: pass hostelId in query. + */ +const getUpcomingGalaWithMenusForHostel = async (req, res) => { + try { + const hostelId = + req.query.hostelId || + req.params.hostelId || + (req.hostel && req.hostel._id?.toString()) || + (req.user && req.user.hostel && req.user.hostel.toString()); + if (!hostelId) { + return res.status(400).json({ message: "Hostel ID is required" }); + } + + const now = new Date(); + const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + + const gala = await GalaDinner.findOne({ + date: { $gte: startOfToday }, + }) + .sort({ date: 1 }) + .lean(); + + if (!gala) { + return res.status(200).json({ galaDinner: null, menus: [] }); + } + + const menus = await GalaDinnerMenu.find({ + galaDinnerId: gala._id, + hostelId, + }) + .populate("qrCode", "qr_base64 qr_string") + .lean(); + + const menusWithItems = await Promise.all( + menus.map(async (m) => { + const items = await MenuItem.find({ galaMenuId: m._id }).lean(); + return { ...m, items }; + }) + ); + + return res.status(200).json({ + galaDinner: gala, + menus: menusWithItems, + }); + } catch (error) { + console.error("getUpcomingGalaWithMenusForHostel:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * App: Scan Gala QR. Body: { userId, galaDinnerMenuId, expectedCategory }. + * galaDinnerMenuId is the payload from the QR (GalaDinnerMenu._id). + * expectedCategory: "Starters" | "Main Course" | "Desserts". + */ +const { publishGalaScan } = require("../../utils/scanBroadcast.js"); + +const galaScan = async (req, res) => { + try { + const { userId, galaDinnerMenuId, expectedCategory } = req.body; + + if (!userId || !galaDinnerMenuId || !expectedCategory) { + return res.status(400).json({ + message: "userId, galaDinnerMenuId and expectedCategory are required", + success: false, + }); + } + + if (!GALA_CATEGORIES.includes(expectedCategory)) { + return res.status(400).json({ + message: "Invalid expectedCategory", + success: false, + }); + } + + const galaMenu = await GalaDinnerMenu.findById(galaDinnerMenuId).populate( + "galaDinnerId" + ); + if (!galaMenu) { + return res.status(404).json({ + message: "Invalid QR code", + success: false, + }); + } + + const user = await User.findById(userId); + if (!user) { + return res.status(404).json({ + message: "User not found", + success: false, + }); + } + + const userHostelId = user.curr_subscribed_mess?.toString(); + const menuHostelId = galaMenu.hostelId?.toString(); + if (!userHostelId || userHostelId !== menuHostelId) { + return res.status(400).json({ + message: "You are not subscribed to this hostel's Gala Dinner", + success: false, + }); + } + + if (galaMenu.category !== expectedCategory) { + return res.status(400).json({ + message: `Wrong QR: you scanned ${galaMenu.category} in ${expectedCategory} scanner`, + success: false, + }); + } + + const galaDinnerId = galaMenu.galaDinnerId._id || galaMenu.galaDinnerId; + + let log = await GalaDinnerScanLog.findOne({ + userId, + galaDinnerId, + }); + + if (!log) { + log = new GalaDinnerScanLog({ + userId, + galaDinnerId, + }); + } + + const timeStr = getCurrentTime(); + let alreadyScanned = false; + + if (expectedCategory === "Starters") { + if (log.startersScanned) alreadyScanned = true; + else { + log.startersScanned = true; + log.startersTime = timeStr; + } + } else if (expectedCategory === "Main Course") { + if (log.mainCourseScanned) alreadyScanned = true; + else { + log.mainCourseScanned = true; + log.mainCourseTime = timeStr; + } + } else { + if (log.dessertsScanned) alreadyScanned = true; + else { + log.dessertsScanned = true; + log.dessertsTime = timeStr; + } + } + + if (alreadyScanned) { + const existingTime = + expectedCategory === "Starters" + ? log.startersTime + : expectedCategory === "Main Course" + ? log.mainCourseTime + : log.dessertsTime; + return res.status(200).json({ + message: `Already scanned for ${expectedCategory}`, + success: false, + mealType: expectedCategory, + time: existingTime, + alreadyScanned: true, + }); + } + + await log.save(); + + // Broadcast to connected manager clients for this hostel (cluster-safe via Redis pub/sub when REDIS_URL is set) + try { + publishGalaScan({ + hostelId: menuHostelId, + mealType: expectedCategory, + user: { + _id: user._id, + name: user.name, + rollNumber: user.rollNumber, + }, + time: timeStr, + alreadyScanned: false, + }); + } catch (e) { + console.error("publishGalaScan failed:", e); + } + + return res.status(200).json({ + message: "Scan successful", + success: true, + mealType: expectedCategory, + time: timeStr, + alreadyScanned: false, + user: { + _id: user._id, + name: user.name, + rollNumber: user.rollNumber, + }, + }); + } catch (error) { + console.error("galaScan:", error); + return res.status(500).json({ + message: "Internal server error", + success: false, + error: error.message, + }); + } +}; + +/** + * App: Get scan status for a user and upcoming Gala Dinner (for tick + time). + */ +const getGalaScanStatus = async (req, res) => { + try { + const userId = + req.params.userId || + (req.user && req.user._id && req.user._id.toString()); + if (!userId) { + return res.status(400).json({ message: "UserId is required" }); + } + + const now = new Date(); + const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + + const gala = await GalaDinner.findOne({ + date: { $gte: startOfToday }, + }) + .sort({ date: 1 }) + .lean(); + + if (!gala) { + return res.status(200).json({ galaDinner: null, scanLog: null }); + } + + const scanLog = await GalaDinnerScanLog.findOne({ + userId, + galaDinnerId: gala._id, + }).lean(); + + return res.status(200).json({ + galaDinner: gala, + scanLog: scanLog || null, + }); + } catch (error) { + console.error("getGalaScanStatus:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * Mess-manager (HABit HQ): summary for the next upcoming Gala Dinner for the + * manager's hostel: total scans per course and recent scans per course. + * Requires authenticateMessManagerJWT to set req.managerHostel. + */ +const getManagerGalaSummary = async (req, res) => { + try { + const managerHostel = req.managerHostel; + if (!managerHostel) { + return res + .status(400) + .json({ message: "Manager hostel context not found" }); + } + + const hostelId = managerHostel._id.toString(); + + const now = new Date(); + const startOfToday = new Date( + now.getFullYear(), + now.getMonth(), + now.getDate(), + ); + const startOfTomorrow = new Date( + now.getFullYear(), + now.getMonth(), + now.getDate() + 1, + ); + + // Only consider Gala Dinner scheduled for "today" (manager app requirement) + const gala = await GalaDinner.findOne({ + date: { $gte: startOfToday, $lt: startOfTomorrow }, + }) + .sort({ date: 1 }) + .lean(); + + if (!gala) { + return res.status(200).json({ + galaDinner: null, + hostelId, + totals: { starters: 0, mainCourse: 0, desserts: 0 }, + recent: { starters: [], mainCourse: [], desserts: [] }, + }); + } + + // Fetch all scan logs for this gala, with user populated to filter by hostel. + const logs = await GalaDinnerScanLog.find({ + galaDinnerId: gala._id, + }) + .populate("userId", "name rollNumber curr_subscribed_mess") + .lean(); + + const totals = { starters: 0, mainCourse: 0, desserts: 0 }; + const recent = { + starters: [], + mainCourse: [], + desserts: [], + }; + + logs.forEach((log) => { + const user = log.userId || {}; + // Ensure this scan belongs to the manager's hostel. + if ( + !user.curr_subscribed_mess || + user.curr_subscribed_mess.toString() !== hostelId + ) { + return; + } + + const base = { + userId: user._id || user.id || log.userId, + name: user.name || "", + rollNumber: user.rollNumber || "", + }; + + if (log.startersScanned) { + totals.starters += 1; + if (log.startersTime) { + recent.starters.push({ + ...base, + time: log.startersTime, + }); + } + } + if (log.mainCourseScanned) { + totals.mainCourse += 1; + if (log.mainCourseTime) { + recent.mainCourse.push({ + ...base, + time: log.mainCourseTime, + }); + } + } + if (log.dessertsScanned) { + totals.desserts += 1; + if (log.dessertsTime) { + recent.desserts.push({ + ...base, + time: log.dessertsTime, + }); + } + } + }); + + const sortByTimeDesc = (arr) => + arr.sort((a, b) => new Date(b.time) - new Date(a.time)); + sortByTimeDesc(recent.starters); + sortByTimeDesc(recent.mainCourse); + sortByTimeDesc(recent.desserts); + + return res.status(200).json({ + galaDinner: gala, + hostelId, + totals, + recent, + }); + } catch (error) { + console.error("getManagerGalaSummary:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * SMC: Create a Gala menu item. Body: { galaMenuId, name, type }. + */ +const createGalaMenuItem = async (req, res) => { + try { + const { galaMenuId, name, type } = req.body; + if (!galaMenuId || !name || !type) { + return res.status(400).json({ + message: "galaMenuId, name and type are required", + }); + } + + const hostelId = + req.hostel?._id?.toString() || + (req.user?.hostel && req.user.hostel.toString()); + if (!hostelId) { + return res.status(403).json({ + message: "Unauthorized: SMC hostel context required", + }); + } + + const galaMenu = await GalaDinnerMenu.findOne({ + _id: galaMenuId, + hostelId, + }); + if (!galaMenu) { + return res.status(404).json({ + message: "Gala menu not found or not for your hostel", + }); + } + + const newItem = new MenuItem({ + galaMenuId, + name, + type, + }); + await newItem.save(); + + return res.status(201).json(newItem); + } catch (error) { + console.error("createGalaMenuItem:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * Get menu items for a single Gala menu (by galaDinnerMenuId). Used to refresh one menu after add/update/delete. + */ +const getGalaMenuItems = async (req, res) => { + try { + const { galaDinnerMenuId } = req.params; + if (!galaDinnerMenuId) { + return res.status(400).json({ message: "galaDinnerMenuId is required" }); + } + + const items = await MenuItem.find({ galaMenuId: galaDinnerMenuId }).lean(); + return res.status(200).json(items); + } catch (error) { + console.error("getGalaMenuItems:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * SMC: Update a Gala menu item. Body: { _Id, name?, type? }. + */ +const updateGalaMenuItem = async (req, res) => { + try { + const { _Id, name, type } = req.body; + if (!_Id) { + return res.status(400).json({ message: "_Id is required" }); + } + + const hostelId = + req.hostel?._id?.toString() || + (req.user?.hostel && req.user.hostel.toString()); + if (!hostelId) { + return res.status(403).json({ + message: "Unauthorized: SMC hostel context required", + }); + } + + const item = await MenuItem.findById(_Id); + if (!item || !item.galaMenuId) { + return res.status(404).json({ message: "Gala menu item not found" }); + } + + const galaMenu = await GalaDinnerMenu.findOne({ + _id: item.galaMenuId, + hostelId, + }); + if (!galaMenu) { + return res.status(403).json({ + message: "This menu item does not belong to your hostel", + }); + } + + if (name != null) item.name = name; + if (type != null) item.type = type; + await item.save(); + + return res.status(200).json({ + message: "Menu item updated successfully", + menuItem: item, + }); + } catch (error) { + console.error("updateGalaMenuItem:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +/** + * SMC: Delete a Gala menu item. + */ +const deleteGalaMenuItem = async (req, res) => { + try { + const _Id = req.body._Id || req.params._Id; + if (!_Id) { + return res.status(400).json({ message: "_Id is required" }); + } + + const hostelId = + req.hostel?._id?.toString() || + (req.user?.hostel && req.user.hostel.toString()); + if (!hostelId) { + return res.status(403).json({ + message: "Unauthorized: SMC hostel context required", + }); + } + + const item = await MenuItem.findById(_Id); + if (!item || !item.galaMenuId) { + return res.status(404).json({ message: "Gala menu item not found" }); + } + + const galaMenu = await GalaDinnerMenu.findOne({ + _id: item.galaMenuId, + hostelId, + }); + if (!galaMenu) { + return res.status(403).json({ + message: "This menu item does not belong to your hostel", + }); + } + + await MenuItem.findByIdAndDelete(_Id); + return res.status(200).json({ message: "Menu item deleted successfully" }); + } catch (error) { + console.error("deleteGalaMenuItem:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; + +module.exports = { + scheduleGalaDinner, + deleteGalaDinner, + listGalaDinners, + getGalaDinnerDetailForHostel, + getUpcomingGalaDinner, + getUpcomingGalaWithMenusForHostel, + galaScan, + getGalaScanStatus, + createGalaMenuItem, + getGalaMenuItems, + updateGalaMenuItem, + deleteGalaMenuItem, + getManagerGalaSummary, +}; diff --git a/server/v1/modules/gala/galaDinnerMenuModel.js b/server/v1/modules/gala/galaDinnerMenuModel.js new file mode 100644 index 00000000..c12c5b13 --- /dev/null +++ b/server/v1/modules/gala/galaDinnerMenuModel.js @@ -0,0 +1,32 @@ +const mongoose = require("mongoose"); + +const GALA_CATEGORIES = ["Starters", "Main Course", "Desserts"]; + +const galaDinnerMenuSchema = new mongoose.Schema({ + galaDinnerId: { + type: mongoose.Schema.Types.ObjectId, + ref: "GalaDinner", + required: true, + }, + hostelId: { + type: mongoose.Schema.Types.ObjectId, + ref: "Hostel", + required: true, + }, + category: { + type: String, + enum: GALA_CATEGORIES, + required: true, + }, + qrCode: { + type: mongoose.Schema.Types.ObjectId, + ref: "QR", + required: false, + }, +}); + +galaDinnerMenuSchema.index({ galaDinnerId: 1, hostelId: 1, category: 1 }, { unique: true }); + +const GalaDinnerMenu = mongoose.model("GalaDinnerMenu", galaDinnerMenuSchema); + +module.exports = { GalaDinnerMenu, GALA_CATEGORIES }; diff --git a/server/v1/modules/gala/galaDinnerModel.js b/server/v1/modules/gala/galaDinnerModel.js new file mode 100644 index 00000000..43c23357 --- /dev/null +++ b/server/v1/modules/gala/galaDinnerModel.js @@ -0,0 +1,17 @@ +const mongoose = require("mongoose"); + +const galaDinnerSchema = new mongoose.Schema( + { + date: { + type: Date, + required: true, + }, + startersServingStartTime: { type: String, trim: true }, + dinnerServingStartTime: { type: String, trim: true }, + }, + { timestamps: true } +); + +const GalaDinner = mongoose.model("GalaDinner", galaDinnerSchema); + +module.exports = { GalaDinner }; diff --git a/server/v1/modules/gala/galaDinnerScanLogModel.js b/server/v1/modules/gala/galaDinnerScanLogModel.js new file mode 100644 index 00000000..3f5de34b --- /dev/null +++ b/server/v1/modules/gala/galaDinnerScanLogModel.js @@ -0,0 +1,26 @@ +const mongoose = require("mongoose"); + +const galaDinnerScanLogSchema = new mongoose.Schema({ + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: true, + }, + galaDinnerId: { + type: mongoose.Schema.Types.ObjectId, + ref: "GalaDinner", + required: true, + }, + startersScanned: { type: Boolean, default: false }, + startersTime: { type: String, default: null }, + mainCourseScanned: { type: Boolean, default: false }, + mainCourseTime: { type: String, default: null }, + dessertsScanned: { type: Boolean, default: false }, + dessertsTime: { type: String, default: null }, +}); + +galaDinnerScanLogSchema.index({ userId: 1, galaDinnerId: 1 }, { unique: true }); + +const GalaDinnerScanLog = mongoose.model("GalaDinnerScanLog", galaDinnerScanLogSchema); + +module.exports = { GalaDinnerScanLog }; diff --git a/server/v1/modules/gala/galaManagerWs.js b/server/v1/modules/gala/galaManagerWs.js new file mode 100644 index 00000000..00838b36 --- /dev/null +++ b/server/v1/modules/gala/galaManagerWs.js @@ -0,0 +1,98 @@ +const url = require("url"); +const { WebSocketServer } = require("ws"); +const { Hostel } = require("../hostel/hostelModel.js"); + +// Connected gala manager clients per hostel +// Each entry: { ws, hostelId } +const galaManagerClients = new Set(); + +function initGalaManagerWs(server) { + const wss = new WebSocketServer({ + server, + path: "/api/gala/manager/scan-logs", + }); + + wss.on("connection", async (ws, req) => { + try { + const { query } = url.parse(req.url, true); + const token = query.token; + + if (!token) { + ws.close(1008, "Missing token"); + return; + } + + const hostel = await Hostel.findByJWT(token); + if (!hostel) { + ws.close(1008, "Invalid token"); + return; + } + + const clientInfo = { + ws, + hostelId: hostel._id.toString(), + }; + + galaManagerClients.add(clientInfo); + + ws.on("close", () => { + galaManagerClients.delete(clientInfo); + }); + + ws.on("error", () => { + galaManagerClients.delete(clientInfo); + }); + } catch (err) { + console.error("Error in Gala manager WS connection:", err); + try { + ws.close(1011, "Internal server error"); + } catch (_) {} + } + }); +} + +/** + * Broadcast a Gala scan event to all connected manager clients for a hostel. + * + * @param {Object} params + * @param {string} params.hostelId - Hostel ObjectId string + * @param {string} params.mealType - "Starters" | "Main Course" | "Desserts" + * @param {Object} params.user - {_id, name, rollNumber} + * @param {string} params.time - time string (e.g. "HH:mm") + * @param {boolean} params.alreadyScanned + */ +function broadcastGalaScanToManagers({ + hostelId, + mealType, + user, + time, + alreadyScanned, +}) { + if (!hostelId || !mealType || !user) return; + + const payload = JSON.stringify({ + mealType, + time, + alreadyScanned: !!alreadyScanned, + user: { + _id: user._id?.toString?.() || user._id || "", + name: user.name || "", + rollNumber: user.rollNumber || "", + }, + }); + + for (const client of galaManagerClients) { + if (client.hostelId !== hostelId) continue; + try { + client.ws.send(payload); + } catch (err) { + console.error("Failed to send WS Gala message to manager client:", err); + } + } +} + +module.exports = { + initGalaManagerWs, + broadcastGalaScanToManagers, +}; + diff --git a/server/v1/modules/gala/galaRoute.js b/server/v1/modules/gala/galaRoute.js new file mode 100644 index 00000000..979ea6bf --- /dev/null +++ b/server/v1/modules/gala/galaRoute.js @@ -0,0 +1,98 @@ +const express = require("express"); +const { + authenticateJWT, + authenticateHabJWT, + authenticateUserOrAdminJWT, + authenticateMessManagerJWT, +} = require("../../middleware/authenticateJWT.js"); +const { + requireMicrosoftAuth, +} = require("../../middleware/requireMicrosoftAuth.js"); +const { + scheduleGalaDinner, + deleteGalaDinner, + listGalaDinners, + getGalaDinnerDetailForHostel, + getUpcomingGalaDinner, + getUpcomingGalaWithMenusForHostel, + galaScan, + getGalaScanStatus, + createGalaMenuItem, + getGalaMenuItems, + updateGalaMenuItem, + deleteGalaMenuItem, + getManagerGalaSummary, +} = require("./galaController.js"); + +const galaRouter = express.Router(); + +// HAB only +galaRouter.post("/schedule", authenticateHabJWT, scheduleGalaDinner); +galaRouter.get("/list", authenticateHabJWT, listGalaDinners); + +// Mess-manager (HABit HQ): summary for upcoming gala for manager's hostel +galaRouter.get( + "/manager/summary", + authenticateMessManagerJWT, + getManagerGalaSummary, +); + +// Upcoming (static paths before /:galaDinnerId so they match correctly) +galaRouter.get("/upcoming", getUpcomingGalaDinner); + +// SMC: upcoming gala + 3 menus for their hostel (hostel from token) +galaRouter.get( + "/upcoming-with-menus", + authenticateUserOrAdminJWT, + getUpcomingGalaWithMenusForHostel +); + +// App: upcoming gala + 3 menus for a hostel (hostelId in path, user token) +galaRouter.get( + "/upcoming-with-menus/:hostelId", + authenticateJWT, + getUpcomingGalaWithMenusForHostel +); + +// App: scan Gala QR +galaRouter.post( + "/scan", + authenticateJWT, + requireMicrosoftAuth, + galaScan +); + +// App: get scan status for current user +galaRouter.get("/scan-status", authenticateJWT, getGalaScanStatus); + +// HAB: detail and delete (param routes last) +galaRouter.get( + "/:galaDinnerId/detail", + authenticateHabJWT, + getGalaDinnerDetailForHostel +); +galaRouter.delete("/:galaDinnerId", authenticateHabJWT, deleteGalaDinner); + +// SMC: Gala menu item CRUD +galaRouter.post( + "/menu/item", + authenticateUserOrAdminJWT, + createGalaMenuItem +); +galaRouter.get( + "/menu/:galaDinnerMenuId/items", + authenticateUserOrAdminJWT, + getGalaMenuItems +); +galaRouter.patch( + "/menu/item", + authenticateUserOrAdminJWT, + updateGalaMenuItem +); +galaRouter.delete( + "/menu/item", + authenticateUserOrAdminJWT, + deleteGalaMenuItem +); + +module.exports = galaRouter; diff --git a/server/v1/modules/hostel/hostelController.js b/server/v1/modules/hostel/hostelController.js index 8be34d3c..df9b64da 100644 --- a/server/v1/modules/hostel/hostelController.js +++ b/server/v1/modules/hostel/hostelController.js @@ -1,3 +1,4 @@ +const bcrypt = require("bcrypt"); const { User } = require("../user/userModel.js"); const { Hostel } = require("./hostelModel.js"); const { Mess } = require("../mess/messModel.js"); @@ -7,19 +8,35 @@ const { getCurrentDate } = require("../../utils/date.js"); const createHostel = async (req, res) => { try { - const { hostel_name, microsoft_email, secretary_email, curr_cap } = - req.body; + const { + hostel_name, + microsoft_email, + secretary_email, + curr_cap, + password, + } = req.body; if (!microsoft_email) { return res.status(400).json({ message: "Microsoft email is required" }); } - const hostel = await Hostel.create({ + const hostelData = { hostel_name, microsoft_email, secretary_email, curr_cap, - }); + }; + + // If an initial hostel password is provided, hash and store it securely. + if (password && typeof password === "string" && password.trim().length) { + const saltRounds = 10; + hostelData.managerPasswordHash = await bcrypt.hash( + password.trim(), + saltRounds, + ); + } + + const hostel = await Hostel.create(hostelData); return res .status(201) @@ -35,6 +52,41 @@ const createHostel = async (req, res) => { } }; +/** + * HAB: Set or update the password for a hostel (encrypted with bcrypt). + * Body: { hostelId, password } + */ +const setHostelPassword = async (req, res) => { + try { + const { hostelId, password } = req.body; + + if (!hostelId || !password || !String(password).trim().length) { + return res.status(400).json({ + message: "hostelId and a non-empty password are required", + }); + } + + const hostel = await Hostel.findById(hostelId); + if (!hostel) { + return res.status(404).json({ message: "Hostel not found" }); + } + + const saltRounds = 10; + hostel.managerPasswordHash = await bcrypt.hash( + String(password).trim(), + saltRounds, + ); + await hostel.save(); + + return res + .status(200) + .json({ message: "Hostel password set successfully" }); + } catch (err) { + console.log(err); + return res.status(500).json({ message: "Error setting hostel password" }); + } +}; + const getHostel = async (req, res) => { try { // Fetch the hostel with populated messId @@ -465,4 +517,5 @@ module.exports = { getSMCMembers, finalizeMessClosure, getMessClosureDate, + setHostelPassword, }; diff --git a/server/v1/modules/hostel/hostelModel.js b/server/v1/modules/hostel/hostelModel.js index 1cca5f45..79956436 100644 --- a/server/v1/modules/hostel/hostelModel.js +++ b/server/v1/modules/hostel/hostelModel.js @@ -90,6 +90,11 @@ const hostelSchema = new mongoose.Schema({ sparse: true, trim: true, }, + // Encrypted (hashed) password for hostel-level logins (e.g. HABit HQ). + managerPasswordHash: { + type: String, + select: false, + }, }); hostelSchema.methods.generateJWT = function () { diff --git a/server/v1/modules/hostel/hostelRoute.js b/server/v1/modules/hostel/hostelRoute.js index adfb43cc..72b6d155 100644 --- a/server/v1/modules/hostel/hostelRoute.js +++ b/server/v1/modules/hostel/hostelRoute.js @@ -1,6 +1,7 @@ const express = require("express"); const { authenticateJWT, + authenticateUserOrAdminJWT, authenticateHabJWT, authenticateAdminJWT, } = require("../../middleware/authenticateJWT.js"); @@ -139,7 +140,7 @@ hostelRouter.post("/", authenticateHabJWT, createHostel); * type: string * example: "Error occurred" */ -hostelRouter.get("/all/smc/:hostelId", authenticateJWT, getHostelbyId); +hostelRouter.get("/all/smc/:hostelId", authenticateUserOrAdminJWT, getHostelbyId); hostelRouter.get("/all/hab/:hostelId", authenticateHabJWT, getHostelbyId); hostelRouter.get("/get", authenticateAdminJWT, getHostel); @@ -209,4 +210,12 @@ hostelRouter.get( hostelRouter.get("/smc-members", authenticateAdminJWT, getSMCMembers); hostelRouter.post("/mark-smc", authenticateAdminJWT, markAsSMC); hostelRouter.post("/unmark-smc", authenticateAdminJWT, unmarkAsSMC); + +// HAB-only: set or update encrypted hostel password +const { setHostelPassword } = require("./hostelController.js"); +hostelRouter.post( + "/set-password", + authenticateHabJWT, + setHostelPassword, +); module.exports = hostelRouter; diff --git a/server/v1/modules/mess/ScanLogsController.js b/server/v1/modules/mess/ScanLogsController.js index 74e16d36..b476b041 100644 --- a/server/v1/modules/mess/ScanLogsController.js +++ b/server/v1/modules/mess/ScanLogsController.js @@ -1,65 +1,76 @@ const { ScanLogs } = require("./ScanLogsModel.js"); +const { getCurrentDate } = require("../../utils/date.js"); +const mongoose = require("mongoose"); //For getting count of people who have eaten breakfast, lunch and dinner const statsByDate = async (req, res) => { try { const date = req.params.date; const messid = req.query.messId; - let logs = {}; - if (!messid) { - logs = await ScanLogs.find({ date: date }); + + const matchStage = { date: date }; + if (messid) { + matchStage.messId = new mongoose.Types.ObjectId(messid); } - else { - logs = await ScanLogs.find({ date: date, messId: messid }); + + const aggregatedStats = await ScanLogs.aggregate([ + { $match: matchStage }, + { + $group: { + _id: "$messId", + breakfast: { $sum: { $cond: ["$breakfast", 1, 0] } }, + lunch: { $sum: { $cond: ["$lunch", 1, 0] } }, + dinner: { $sum: { $cond: ["$dinner", 1, 0] } }, + totalScans: { $sum: 1 }, + }, + }, + ]); + + const stats = { + total: 0, + breakfast: 0, + lunch: 0, + dinner: 0, + highest: ["", 0], + lowest: ["", 0], + }; + + if (aggregatedStats.length === 0) { + return res.status(200).json(stats); } - const stats = { total: 0, breakfast: 0, lunch: 0, dinner: 0, highest: ["",0], lowest: ["",0] }; - - //For finding highest and lowest attendance mess - const messwisestats = {}; - - logs.forEach((item) => { - if(!(item.messId in messwisestats)) messwisestats[item.messId] = [0,0]; - if (item.breakfast){ - ++messwisestats[item.messId][0]; - ++stats.breakfast; - } - if (item.lunch){ - ++messwisestats[item.messId][0]; - ++stats.lunch; - } - if (item.dinner){ - ++messwisestats[item.messId][0]; - ++stats.dinner; - } - ++stats.total; - ++messwisestats[item.messId][1] - }) - //looping through the messes to find highest and lowest - for(const key in messwisestats){ - const attendance = (messwisestats[key][0]/messwisestats[key][1]/3*100).toFixed(1); - if (!stats.highest[0]){ - stats.lowest[0] = key; stats.lowest[1] = attendance - stats.highest[0] = key; stats.highest[1] = attendance - } - else if (attendance > stats.highest[1]){ - stats.highest[0] = key; - stats.highest[1] = attendance + let highestAttendance = -1; + let lowestAttendance = 101; + + aggregatedStats.forEach((messStat) => { + stats.breakfast += messStat.breakfast; + stats.lunch += messStat.lunch; + stats.dinner += messStat.dinner; + stats.total += messStat.totalScans; + + // 3 possible meals per user per day + const attendanceNum = + ((messStat.breakfast + messStat.lunch + messStat.dinner) / + (messStat.totalScans * 3)) * + 100; + const attendanceStr = attendanceNum.toFixed(1); + + if (stats.highest[0] === "" || attendanceNum > highestAttendance) { + highestAttendance = attendanceNum; + stats.highest = [messStat._id.toString(), attendanceStr]; } - else if (attendance < stats.lowest[1]){ - stats.lowest[0] = key; - stats.lowest[1] = attendance; + if (stats.lowest[0] === "" || attendanceNum < lowestAttendance) { + lowestAttendance = attendanceNum; + stats.lowest = [messStat._id.toString(), attendanceStr]; } - } -console.log(stats) + }); + res.status(200).json(stats); - } - catch (error) { + } catch (error) { console.error(error); - console.log("hello") return res.status(500).json({ message: "Internal server error" }); } -} +}; //temporary function for creating sample logs const createLogs = async (req, res) => { @@ -69,13 +80,12 @@ const createLogs = async (req, res) => { res.status(200).json({ message: "Successfully inserted the data!", data: insertedlogs, - }) - } - catch (error) { + }); + } catch (error) { console.error(error); return res.status(500).json({ message: "Internal server error" }); } -} +}; //temporary function for deleting sample logs const deleteall = async (req, res) => { @@ -83,29 +93,117 @@ const deleteall = async (req, res) => { await ScanLogs.deleteMany(); res.status(200).json({ message: "Successfulyy deleted everything!", - }) - } - catch (error) { + }); + } catch (error) { console.error(error); return res.status(500).json({ message: "Internal server error" }); } -} +}; // Get total count of all scan logs const getTotalScanLogsCount = async (req, res) => { try { const totalCount = await ScanLogs.countDocuments({}); res.status(200).json({ total: totalCount }); - } - catch (error) { + } catch (error) { console.error(error); return res.status(500).json({ message: "Internal server error" }); } -} +}; + +// Mess-manager (HABit HQ): summary for today's scans for the manager's mess. +// Requires authenticateMessManagerJWT to set req.managerHostel with populated messId. +const getManagerTodaySummary = async (req, res) => { + try { + const managerHostel = req.managerHostel; + if (!managerHostel || !managerHostel.messId) { + return res + .status(400) + .json({ message: "Manager hostel or messId not found" }); + } + + const messId = + managerHostel.messId._id?.toString() || managerHostel.messId.toString(); + const today = getCurrentDate(); // "YYYY-MM-DD" + + const logs = await ScanLogs.find({ + date: today, + messId, + }) + .populate("userId", "name rollNumber") + .lean(); + + const totals = { breakfast: 0, lunch: 0, dinner: 0, total: 0 }; + const recent = { + breakfast: [], + lunch: [], + dinner: [], + }; + + logs.forEach((log) => { + const user = log.userId || {}; + const base = { + userId: user._id || user.id || log.userId, + name: user.name || "", + rollNumber: user.rollNumber || "", + }; + + if (log.breakfast) { + totals.breakfast += 1; + totals.total += 1; + if (log.breakfastTime) { + recent.breakfast.push({ + ...base, + time: log.breakfastTime, + }); + } + } + if (log.lunch) { + totals.lunch += 1; + totals.total += 1; + if (log.lunchTime) { + recent.lunch.push({ + ...base, + time: log.lunchTime, + }); + } + } + if (log.dinner) { + totals.dinner += 1; + totals.total += 1; + if (log.dinnerTime) { + recent.dinner.push({ + ...base, + time: log.dinnerTime, + }); + } + } + }); + + const sortByTimeDesc = (arr) => + arr.sort((a, b) => new Date(b.time) - new Date(a.time)); + sortByTimeDesc(recent.breakfast); + sortByTimeDesc(recent.lunch); + sortByTimeDesc(recent.dinner); + + return res.status(200).json({ + date: today, + messId, + totals, + recent, + }); + } catch (error) { + console.error("getManagerTodaySummary:", error); + return res + .status(500) + .json({ message: "Internal server error", error: error.message }); + } +}; module.exports = { statsByDate, createLogs, deleteall, - getTotalScanLogsCount -} \ No newline at end of file + getTotalScanLogsCount, + getManagerTodaySummary, +}; diff --git a/server/v1/modules/mess/ScanLogsModel.js b/server/v1/modules/mess/ScanLogsModel.js index 6e94951b..b66b6b4e 100644 --- a/server/v1/modules/mess/ScanLogsModel.js +++ b/server/v1/modules/mess/ScanLogsModel.js @@ -41,5 +41,8 @@ const scanLogsSchema = new mongoose.Schema({ }, }); +scanLogsSchema.index({ userId: 1, messId: 1, date: 1 }); +scanLogsSchema.index({ date: 1, messId: 1 }); + const ScanLogs = mongoose.model("ScanLogs", scanLogsSchema); module.exports = { ScanLogs }; diff --git a/server/v1/modules/mess/ScanLogsRoute.js b/server/v1/modules/mess/ScanLogsRoute.js index f41065cc..bb0b4a36 100644 --- a/server/v1/modules/mess/ScanLogsRoute.js +++ b/server/v1/modules/mess/ScanLogsRoute.js @@ -3,15 +3,25 @@ const express = require("express"); const { statsByDate, getTotalScanLogsCount, + getManagerTodaySummary, // createLogs, // deleteall } = require("./ScanLogsController"); -const { authenticateHabJWT } = require("../../middleware/authenticateJWT"); +const { + authenticateHabJWT, + authenticateMessManagerJWT, +} = require("../../middleware/authenticateJWT"); const scanLogsRouter = express.Router(); scanLogsRouter.get("/get/:date", authenticateHabJWT, statsByDate); scanLogsRouter.get("/total", authenticateHabJWT, getTotalScanLogsCount); +// Mess-manager (HABit HQ): today's summary for manager's mess +scanLogsRouter.get( + "/manager/today", + authenticateMessManagerJWT, + getManagerTodaySummary, +); // scanLogsRouter.post("/make", createLogs) // scanLogsRouter.delete("/delete", deleteall) diff --git a/server/v1/modules/mess/menuItemModel.js b/server/v1/modules/mess/menuItemModel.js index 4b2f78dc..c9328246 100644 --- a/server/v1/modules/mess/menuItemModel.js +++ b/server/v1/modules/mess/menuItemModel.js @@ -4,7 +4,12 @@ const menuItemSchema = new mongoose.Schema({ menuId: { type: mongoose.Schema.Types.ObjectId, ref: "Menu", - required: true, + required: false, + }, + galaMenuId: { + type: mongoose.Schema.Types.ObjectId, + ref: "GalaDinnerMenu", + required: false, }, name: { type: String, @@ -22,6 +27,17 @@ const menuItemSchema = new mongoose.Schema({ }, }); +// Exactly one of menuId or galaMenuId must be set +menuItemSchema.pre("validate", function (next) { + const hasMenu = !!this.menuId; + const hasGala = !!this.galaMenuId; + if (hasMenu === hasGala) { + next(new Error("MenuItem must have exactly one of menuId or galaMenuId")); + } else { + next(); + } +}); + const MenuItem = mongoose.model("MenuItem", menuItemSchema); module.exports = { MenuItem }; diff --git a/server/v1/modules/mess/menuModel.js b/server/v1/modules/mess/menuModel.js index 9730f24d..8d1acae8 100644 --- a/server/v1/modules/mess/menuModel.js +++ b/server/v1/modules/mess/menuModel.js @@ -44,6 +44,8 @@ const menuSchema = new mongoose.Schema({ ], }); +menuSchema.index({ messId: 1, day: 1, type: 1 }); + const Menu = mongoose.model("Menu", menuSchema); module.exports = { Menu }; diff --git a/server/v1/modules/mess/messAdminController.js b/server/v1/modules/mess/messAdminController.js index 18b7b713..b0321819 100644 --- a/server/v1/modules/mess/messAdminController.js +++ b/server/v1/modules/mess/messAdminController.js @@ -11,6 +11,9 @@ const { getCurrentDay, } = require("../../utils/date.js"); +const NodeCache = require("node-cache"); +const menuCache = new NodeCache({ stdTTL: 300 }); + const getMessMenuByDayForAdmin = async (req, res) => { try { const messId = req.params.messId; @@ -18,30 +21,44 @@ const getMessMenuByDayForAdmin = async (req, res) => { if (!messId || !day) { return res.status(400).json({ message: "Mess ID and day are required" }); } - const allMenus = await Menu.find({}); - const menu = await Menu.find({ messId: messId, day: day }); //FIX THIS! PUT MESS ID AS WELL - if (!menu || menu.length === 0) { - return res.status(200).json("DoesntExist"); - } - - const populatedMenus = []; - for (let i = 0; i < menu.length; i++) { - const menuObj = menu[i].toObject(); - const menuItems = menuObj.items; - const menuItemDetails = await MenuItem.find({ _id: { $in: menuItems } }); + const cacheKey = `menu_${messId}_${day}`; + let populatedMenus = menuCache.get(cacheKey); + + if (!populatedMenus) { + const menu = await Menu.find({ messId: messId, day: day }).sort({ startTime: 1 }); + if (!menu || menu.length === 0) { + return res.status(200).json("DoesntExist"); + } + + populatedMenus = await Promise.all( + menu.map(async (m) => { + const menuObj = m.toObject(); + const menuItems = menuObj.items; + const menuItemDetails = await MenuItem.find({ + _id: { $in: menuItems }, + }).lean(); + + menuObj.items = menuItemDetails; + return menuObj; + }) + ); + menuCache.set(cacheKey, populatedMenus); + } - const updatedMenuItems = menuItemDetails.map((item) => { - const itemObj = item.toObject(); - //itemObj.isLiked = item.likes.includes(userId); - return itemObj; + const specificMenus = populatedMenus.map((m) => { + const mClone = { ...m }; + mClone.items = m.items.map((item) => { + return { + ...item, + likesCount: item.likes ? item.likes.length : 0, + likes: undefined, + }; }); + return mClone; + }); - menuObj.items = updatedMenuItems; - populatedMenus.push(menuObj); - } - - return res.status(200).json(populatedMenus); + return res.status(200).json(specificMenus); } catch (error) { console.error(error); return res.status(500).json({ message: "Internal server error" }); @@ -202,28 +219,43 @@ const getMessMenuByDayForSMC = async (req, res) => { }); } - const menu = await Menu.find({ messId: messId, day: day }); - if (!menu || menu.length === 0) { - return res.status(200).json("DoesntExist"); + const cacheKey = `menu_${messId}_${day}`; + let populatedMenus = menuCache.get(cacheKey); + + if (!populatedMenus) { + const menu = await Menu.find({ messId: messId, day: day }).sort({ startTime: 1 }); + if (!menu || menu.length === 0) { + return res.status(200).json("DoesntExist"); + } + + populatedMenus = await Promise.all( + menu.map(async (m) => { + const menuObj = m.toObject(); + const menuItems = menuObj.items; + const menuItemDetails = await MenuItem.find({ + _id: { $in: menuItems }, + }).lean(); + + menuObj.items = menuItemDetails; + return menuObj; + }) + ); + menuCache.set(cacheKey, populatedMenus); } - const populatedMenus = []; - - for (let i = 0; i < menu.length; i++) { - const menuObj = menu[i].toObject(); - const menuItems = menuObj.items; - const menuItemDetails = await MenuItem.find({ _id: { $in: menuItems } }); - - const updatedMenuItems = menuItemDetails.map((item) => { - const itemObj = item.toObject(); - return itemObj; + const specificMenus = populatedMenus.map((m) => { + const mClone = { ...m }; + mClone.items = m.items.map((item) => { + return { + ...item, + likesCount: item.likes ? item.likes.length : 0, + likes: undefined, + }; }); + return mClone; + }); - menuObj.items = updatedMenuItems; - populatedMenus.push(menuObj); - } - - return res.status(200).json(populatedMenus); + return res.status(200).json(specificMenus); } catch (error) { console.error(error); return res.status(500).json({ message: "Internal server error" }); diff --git a/server/v1/modules/mess/messController.js b/server/v1/modules/mess/messController.js index 8afb0cf2..da5892c3 100644 --- a/server/v1/modules/mess/messController.js +++ b/server/v1/modules/mess/messController.js @@ -9,6 +9,10 @@ const { QR } = require("../qr/qrModel.js"); const qrcode = require("qrcode"); const { MessClosure } = require("../hostel/messClosureModel"); +const NodeCache = require("node-cache"); +const menuCache = new NodeCache({ stdTTL: 300 }); +const messInfoCache = new NodeCache({ stdTTL: 300 }); + const QR_CODE_DATA_URL_OPTIONS = { width: 1024, margin: 2, @@ -241,35 +245,47 @@ const getUserMessInfo = async (req, res) => { const getAllMessInfo = async (req, res) => { try { - const messes = await Mess.find(); + const cachedData = messInfoCache.get("all_mess_info"); + if (cachedData) { + return res.status(200).json(cachedData); + } - if (!messes || messes.length === 0) { + const messes = await Mess.find().lean(); + if (!messes || messes.length === 0) return res.status(404).json({ message: "No mess found" }); - } - const messesWithHostelName = await Promise.all( - messes.map(async (mess) => { - const messObj = mess.toObject(); - if (messObj.hostelId) { - const hostel = await Hostel.findById(messObj.hostelId); - messObj.hostelName = hostel ? hostel.hostel_name : null; - } else { - messObj.hostelName = null; - } + const userCounts = await User.aggregate([ + { $match: { curr_subscribed_mess: { $ne: null } } }, + { $group: { _id: "$curr_subscribed_mess", count: { $sum: 1 } } }, + ]); - // Ensure rating and ranking are always integers - messObj.rating = messObj.rating ? Math.round(messObj.rating) : 0; - messObj.ranking = messObj.ranking ? Math.round(messObj.ranking) : 0; + // Create a fast lookup map + const countMap = userCounts.reduce((acc, curr) => { + acc[curr._id.toString()] = curr.count; + return acc; + }, {}); + + const hostels = await Hostel.find({ + _id: { $in: messes.map((m) => m.hostelId).filter(Boolean) }, + }).lean(); + const hostelMap = hostels.reduce((acc, curr) => { + acc[curr._id.toString()] = curr.hostel_name; + return acc; + }, {}); + + const messesWithHostelName = messes.map((mess) => { + return { + ...mess, + hostelName: mess.hostelId + ? hostelMap[mess.hostelId.toString()] || null + : null, + rating: mess.rating ? Math.round(mess.rating) : 0, + ranking: mess.ranking ? Math.round(mess.ranking) : 0, + user_count: mess.hostelId ? countMap[mess.hostelId.toString()] || 0 : 0, + }; + }); - const userCount = await User.find({ - curr_subscribed_mess: messObj.hostelId, - }); - messObj.user_count = userCount.length; - - return messObj; - }), - ); - console.log("All messes with hostel names:", messesWithHostelName); + messInfoCache.set("all_mess_info", messesWithHostelName); return res.status(200).json(messesWithHostelName); } catch (error) { @@ -311,19 +327,58 @@ const getMessMenuByDay = async (req, res) => { return res.status(400).json({ message: "Mess ID and day are required" }); } - const menu = await Menu.find({ messId, day }).sort({ startTime: 1 }); - if (!menu || menu.length === 0) { - return res.status(404).json({ message: "Menu not found" }); - } + const cacheKey = `menu_${messId}_${day}`; + let populatedMenus = menuCache.get(cacheKey); + + if (!populatedMenus) { + const menu = await Menu.find({ messId, day }).sort({ startTime: 1 }); + if (!menu || menu.length === 0) { + return res.status(404).json({ message: "Menu not found" }); + } + + populatedMenus = await Promise.all( + menu.map(async (m) => { + const menuObj = m.toObject(); + const menuItems = menuObj.items; + const menuItemDetails = await MenuItem.find({ + _id: { $in: menuItems }, + }).lean(); + + menuObj.items = menuItemDetails; + return menuObj; + }), + ); + + menuCache.set(cacheKey, populatedMenus); + } + + // Apply user-specific logic (likes) to cached data + const userSpecificMenus = populatedMenus.map((m) => { + const mClone = { ...m }; + mClone.items = m.items.map((item) => { + return { + ...item, + isLiked: + item.likes && + item.likes.some((id) => id.toString() === userId.toString()), + likesCount: item.likes ? item.likes.length : 0, + likes: undefined, // Hide massive array + }; + }); + return mClone; + }); // Check if the mess is closed today const mess = await Mess.findById(messId); const currentDate = getCurrentDate(); const todayDate = new Date(currentDate); - const isClosed = await MessClosure.findOne({ - hostelId: mess.hostelId, - closureDate: todayDate, - }); + let isClosed = null; + if (mess && mess.hostelId) { + isClosed = await MessClosure.findOne({ + hostelId: mess.hostelId, + closureDate: todayDate, + }).lean(); + } if (isClosed) { return res.status(200).json({ @@ -332,24 +387,7 @@ const getMessMenuByDay = async (req, res) => { }); } - const populatedMenus = []; - - for (let i = 0; i < menu.length; i++) { - const menuObj = menu[i].toObject(); - const menuItems = menuObj.items; - const menuItemDetails = await MenuItem.find({ _id: { $in: menuItems } }); - - const updatedMenuItems = menuItemDetails.map((item) => { - const itemObj = item.toObject(); - itemObj.isLiked = item.likes.includes(userId); - return itemObj; - }); - - menuObj.items = updatedMenuItems; - populatedMenus.push(menuObj); - } - - return res.status(200).json(populatedMenus); + return res.status(200).json(userSpecificMenus); } catch (error) { console.error(error); return res.status(500).json({ message: "Internal server error" }); @@ -365,27 +403,45 @@ const getMessMenuByDayForAdminHAB = async (req, res) => { return res.status(400).json({ message: "Mess ID and day are required" }); } - const menu = await Menu.find({ messId, day }).sort({ startTime: 1 }); - if (!menu || menu.length === 0) { - return res.status(404).json({ message: "Menu not found" }); - } + const cacheKey = `menu_${messId}_${day}`; + let populatedMenus = menuCache.get(cacheKey); - const populatedMenus = []; - for (let i = 0; i < menu.length; i++) { - const menuObj = menu[i].toObject(); - const menuItems = menuObj.items; - const menuItemDetails = await MenuItem.find({ _id: { $in: menuItems } }); + if (!populatedMenus) { + const menu = await Menu.find({ messId, day }).sort({ startTime: 1 }); + if (!menu || menu.length === 0) { + return res.status(404).json({ message: "Menu not found" }); + } - const updatedMenuItems = menuItemDetails.map((item) => { - const itemObj = item.toObject(); - return itemObj; - }); + populatedMenus = await Promise.all( + menu.map(async (m) => { + const menuObj = m.toObject(); + const menuItems = menuObj.items; + const menuItemDetails = await MenuItem.find({ + _id: { $in: menuItems }, + }).lean(); + + menuObj.items = menuItemDetails; + return menuObj; + }), + ); - menuObj.items = updatedMenuItems; - populatedMenus.push(menuObj); + menuCache.set(cacheKey, populatedMenus); } - return res.status(200).json(populatedMenus); + // Apply formatting to cached data + const specificMenus = populatedMenus.map((m) => { + const mClone = { ...m }; + mClone.items = m.items.map((item) => { + return { + ...item, + likesCount: item.likes ? item.likes.length : 0, + likes: undefined, // Hide massive array + }; + }); + return mClone; + }); + + return res.status(200).json(specificMenus); } catch (error) { console.error(error); return res.status(500).json({ message: "Internal server error" }); @@ -535,7 +591,7 @@ const ScanMess = async (req, res) => { const closureRecord = await MessClosure.findOne({ hostelId: messInfo.hostelId, closureDate: new Date(currentDate), - }); + }).lean(); if (closureRecord) { return res.status(400).json({ message: "Scan failed: Mess is closed today.", @@ -543,14 +599,14 @@ const ScanMess = async (req, res) => { }); } - const user = await User.findById(userId); + const user = await User.findById(userId).lean(); if (!user) { return res .status(404) .json({ message: "User not found", success: false }); } - const hostel = await Hostel.findById(user.curr_subscribed_mess); + const hostel = await Hostel.findById(user.curr_subscribed_mess).lean(); if (!hostel) { return res .status(404) @@ -558,7 +614,7 @@ const ScanMess = async (req, res) => { } const messId = hostel.messId; - const userMess = await Mess.findById(messId); + const userMess = await Mess.findById(messId).lean(); if (!userMess) { return res .status(404) @@ -584,11 +640,15 @@ const ScanMess = async (req, res) => { }); } - const [breakfast, lunch, dinner] = await Promise.all([ - Menu.findOne({ messId, day: currentDay, type: "Breakfast" }), - Menu.findOne({ messId, day: currentDay, type: "Lunch" }), - Menu.findOne({ messId, day: currentDay, type: "Dinner" }), - ]); + const todayMenus = await Menu.find({ + messId, + day: currentDay, + type: { $in: ["Breakfast", "Lunch", "Dinner"] } + }).lean(); + + const breakfast = todayMenus.find((m) => m.type === "Breakfast"); + const lunch = todayMenus.find((m) => m.type === "Lunch"); + const dinner = todayMenus.find((m) => m.type === "Dinner"); let mealType = null; let alreadyScanned = false; @@ -665,6 +725,24 @@ const ScanMess = async (req, res) => { new Date().toLocaleString("en-US", { timeZone: "Asia/Kolkata" }), ); + // Broadcast to connected mess-manager WebSocket clients (cluster-safe via Redis pub/sub when REDIS_URL is set) + try { + const { publishMessScan } = require("../../utils/scanBroadcast.js"); + publishMessScan({ + hostelId: hostel._id.toString(), + messId: messId.toString(), + mealType, + user: { + _id: user._id, + name: user.name, + rollNumber: user.rollNumber, + }, + time: kolkataTime, + }); + } catch (e) { + console.error("Failed to broadcast mess scan to managers:", e); + } + return res.status(200).json({ message: "Scan successful", success: true, diff --git a/server/v1/modules/mess/messManagerWs.js b/server/v1/modules/mess/messManagerWs.js new file mode 100644 index 00000000..f7516f0e --- /dev/null +++ b/server/v1/modules/mess/messManagerWs.js @@ -0,0 +1,112 @@ +const url = require("url"); +const { WebSocketServer } = require("ws"); +const { Hostel } = require("../hostel/hostelModel.js"); + +// In-memory set of connected manager clients +// Each entry: { ws, hostelId, messId, meal } where meal is "breakfast" | "lunch" | "dinner" | null +const managerClients = new Set(); + +function normalizeMeal(meal) { + if (!meal) return null; + const lower = String(meal).toLowerCase(); + if (lower.startsWith("break")) return "breakfast"; + if (lower.startsWith("lunch")) return "lunch"; + if (lower.startsWith("dinn")) return "dinner"; + return null; +} + +function initMessManagerWs(server) { + const wss = new WebSocketServer({ + server, + path: "/api/mess/manager/scan-logs", + }); + + wss.on("connection", async (ws, req) => { + try { + const { query } = url.parse(req.url, true); + const token = query.token; + const mealParam = normalizeMeal(query.meal); + + if (!token) { + ws.close(1008, "Missing token"); + return; + } + + const hostel = await Hostel.findByJWT(token); + if (!hostel) { + ws.close(1008, "Invalid token"); + return; + } + + const hostelId = hostel._id.toString(); + const messId = hostel.messId ? hostel.messId.toString() : null; + + const clientInfo = { + ws, + hostelId, + messId, + meal: mealParam, // null = all meals + }; + + managerClients.add(clientInfo); + + ws.on("close", () => { + managerClients.delete(clientInfo); + }); + + ws.on("error", () => { + managerClients.delete(clientInfo); + }); + } catch (err) { + console.error("Error in Mess manager WS connection:", err); + try { + ws.close(1011, "Internal server error"); + } catch (_) {} + } + }); +} + +/** + * Broadcast a new scan event to all connected mess-manager clients. + * + * @param {Object} params + * @param {string} params.hostelId - Hostel ObjectId string + * @param {string|null} params.messId - Mess ObjectId string (optional) + * @param {string} params.mealType - "Breakfast" | "Lunch" | "Dinner" + * @param {Object} params.user - { _id, name, rollNumber } + * @param {Date|string} params.time - JS Date or ISO/string + */ +function broadcastMessScanToManagers({ hostelId, messId, mealType, user, time }) { + if (!hostelId || !mealType || !user) return; + const normalizedMeal = normalizeMeal(mealType); + const isoTime = + time instanceof Date ? time.toISOString() : String(time || new Date()); + + const payload = JSON.stringify({ + mealType, + time: isoTime, + user: { + _id: user._id?.toString?.() || user._id || "", + name: user.name || "", + rollNumber: user.rollNumber || "", + }, + }); + + for (const client of managerClients) { + if (client.hostelId !== hostelId) continue; + if (client.messId && messId && client.messId !== String(messId)) continue; + if (client.meal && client.meal !== normalizedMeal) continue; + + try { + client.ws.send(payload); + } catch (err) { + console.error("Failed to send WS message to manager client:", err); + } + } +} + +module.exports = { + initMessManagerWs, + broadcastMessScanToManagers, +}; + diff --git a/server/v1/modules/mess_change/autoMessChangeScheduler.js b/server/v1/modules/mess_change/autoMessChangeScheduler.js index 4c5c9060..da4118cc 100644 --- a/server/v1/modules/mess_change/autoMessChangeScheduler.js +++ b/server/v1/modules/mess_change/autoMessChangeScheduler.js @@ -72,7 +72,7 @@ const scheduleMessChangeReminders = async () => { "Mess change application form will close in 12 hours", "All_Hostels", { redirectType: "mess_change", isAlert: "true" } - ); + ).catch((err) => console.error("📢 12h mess change reminder send failed:", err)); console.log("📢 Sent 12h mess change reminder"); }); console.log( @@ -92,7 +92,7 @@ const scheduleMessChangeReminders = async () => { "Mess change application form will close in 2 hours", "All_Hostels", { redirectType: "mess_change", isAlert: "true" } - ); + ).catch((err) => console.error("📢 2h mess change reminder send failed:", err)); console.log("📢 Sent 2h mess change reminder"); }); console.log( diff --git a/server/v1/modules/mess_change/controllers/adminController.js b/server/v1/modules/mess_change/controllers/adminController.js index 55ebada6..531d28d3 100644 --- a/server/v1/modules/mess_change/controllers/adminController.js +++ b/server/v1/modules/mess_change/controllers/adminController.js @@ -78,7 +78,7 @@ const enableMessChange = async (req, res) => { "Mess Change for this month has been enabled", "All_Hostels", { redirectType: "mess_change", isAlert: "true" }, - ); + ).catch((err) => console.error("Mess change enabled notification failed:", err)); return res.status(200).json({ message: "Mess change enabled successfully", diff --git a/server/v1/modules/mess_change/controllers/processingController.js b/server/v1/modules/mess_change/controllers/processingController.js index 7d355bbe..714fac05 100644 --- a/server/v1/modules/mess_change/controllers/processingController.js +++ b/server/v1/modules/mess_change/controllers/processingController.js @@ -161,21 +161,32 @@ const processUsersInIterations = async (users, capacityTracker) => { * Reset all users back to hostel */ const resetAllUsersToHostel = async () => { - const allocations = await UserAllocHostel.find({}); + const allocations = await UserAllocHostel.find({}).lean(); + if (!allocations.length) return; - for (const allocation of allocations) { - allocation.current_subscribed_mess = allocation.hostel; - await allocation.save(); + const bulkAllocOps = allocations.map(alloc => ({ + updateOne: { + filter: { _id: alloc._id }, + update: { $set: { current_subscribed_mess: alloc.hostel } } + } + })); + if (bulkAllocOps.length > 0) { + await UserAllocHostel.bulkWrite(bulkAllocOps); + } - await User.updateOne( - { rollNumber: allocation.rollno }, - { + const bulkUserOps = allocations.map(alloc => ({ + updateOne: { + filter: { rollNumber: alloc.rollno }, + update: { $set: { - curr_subscribed_mess: allocation.hostel, + curr_subscribed_mess: alloc.hostel, got_mess_changed: false, }, }, - ); + }, + })); + if (bulkUserOps.length > 0) { + await User.bulkWrite(bulkUserOps); } }; @@ -309,7 +320,7 @@ const processAllMessChangeRequests = async (req, res) => { "Mess Change is Disabled", "All_Hostels", { redirectType: "mess_change", isAlert: "true" }, - ); + ).catch((err) => console.error("Mess change disabled notification failed:", err)); res.status(200).json({ message: `${acceptedUsers.length} accepted, ${rejectedUsers.length} rejected`, @@ -348,7 +359,7 @@ const rejectAllMessChangeRequests = async (req, res) => { "Mess Change is Disabled", "All_Hostels", { redirectType: "mess_change", isAlert: "true" }, - ); + ).catch((err) => console.error("Mess change disabled notification failed:", err)); res.status(200).json({ message: `Rejected ${users.length} pending requests. Mess change has been automatically disabled.`, diff --git a/server/v1/modules/mess_change/controllers/schedulerController.js b/server/v1/modules/mess_change/controllers/schedulerController.js index b93b53cc..74199765 100644 --- a/server/v1/modules/mess_change/controllers/schedulerController.js +++ b/server/v1/modules/mess_change/controllers/schedulerController.js @@ -29,7 +29,7 @@ const enableMessChangeAutomatic = async () => { "Mess Change is Enabled", "All_Hostels", { redirectType: "mess_change", isAlert: "true" } - ); + ).catch((err) => console.error("Mess change enabled notification failed:", err)); console.log("✅ Mess change enabled automatically"); return { success: true, settings }; diff --git a/server/v1/modules/notification/notificationController.js b/server/v1/modules/notification/notificationController.js index 35867913..b08ee382 100644 --- a/server/v1/modules/notification/notificationController.js +++ b/server/v1/modules/notification/notificationController.js @@ -117,7 +117,7 @@ const sendNotificationToUser = async (userId, title, body) => { const sendNotification = async (req, res) => { try { const { title, body, topic, isAlert } = req.body; - sendNotificationMessage(title, body, topic, {}, isAlert || false); + await sendNotificationMessage(title, body, topic, {}, isAlert || false); res.status(200).json({ message: "Notification sent" }); } catch (err) { console.error(err); diff --git a/server/v1/modules/profile/profileController.js b/server/v1/modules/profile/profileController.js index dac86e42..f128be19 100644 --- a/server/v1/modules/profile/profileController.js +++ b/server/v1/modules/profile/profileController.js @@ -249,10 +249,9 @@ async function setProfilePicture(req, res) { } } -// GET /api/profile/picture/get -async function getProfilePicture(req, res) { +// Internal helper: send profile picture bytes/URL for a given user document +async function sendProfilePictureForUser(user, res) { try { - const user = req.user; if (!user.profilePictureItemId && !user.profilePictureUrl) { return res.status(404).json({ message: "No profile picture set" }); } @@ -328,6 +327,56 @@ async function getProfilePicture(req, res) { } } +// GET /api/profile/picture/get (current authenticated user) +async function getProfilePicture(req, res) { + const user = req.user; + return sendProfilePictureForUser(user, res); +} + +// Mess-manager (HABit HQ): get profile picture for a mess user by userId +async function getProfilePictureForManager(req, res) { + try { + const managerHostel = req.managerHostel; + const { userId } = req.params; + + if (!managerHostel || !managerHostel._id) { + return res + .status(400) + .json({ message: "Manager hostel not found" }); + } + if (!userId) { + return res.status(400).json({ message: "Missing userId" }); + } + + const hostelId = managerHostel._id.toString(); + + const user = await User.findById(userId) + .select("profilePictureItemId profilePictureUrl curr_subscribed_mess") + .populate("curr_subscribed_mess", "hostel_name"); + + if (!user) { + return res.status(404).json({ message: "User not found" }); + } + + if ( + !user.curr_subscribed_mess || + user.curr_subscribed_mess._id.toString() !== hostelId + ) { + return res + .status(403) + .json({ message: "User does not belong to this mess" }); + } + + return sendProfilePictureForUser(user, res); + } catch (err) { + return res.status(500).json({ + message: "Failed to fetch profile picture", + error: err.message, + status: err.response?.status, + }); + } +} + // Mark setup complete for current user async function markSetupComplete(req, res) { try { @@ -346,4 +395,9 @@ async function markSetupComplete(req, res) { } } -module.exports = { setProfilePicture, getProfilePicture, markSetupComplete }; +module.exports = { + setProfilePicture, + getProfilePicture, + getProfilePictureForManager, + markSetupComplete, +}; diff --git a/server/v1/modules/profile/profileRoute.js b/server/v1/modules/profile/profileRoute.js index 3013c5d3..fa9c86c0 100644 --- a/server/v1/modules/profile/profileRoute.js +++ b/server/v1/modules/profile/profileRoute.js @@ -3,6 +3,7 @@ const multer = require("multer"); const { setProfilePicture, getProfilePicture, + getProfilePictureForManager, markSetupComplete, } = require("./profileController.js"); const { @@ -13,6 +14,7 @@ const { const { authenticateJWT, authenticateHabJWT, + authenticateMessManagerJWT, } = require("../../middleware/authenticateJWT.js"); const router = express.Router(); @@ -95,6 +97,13 @@ router.post( */ router.get("/picture/get", authenticateJWT, getProfilePicture); +// Mess-manager (HABit HQ): get profile picture for a user by ID +router.get( + "/picture/manager/:userId", + authenticateMessManagerJWT, + getProfilePictureForManager, +); + /** Mark setup complete */ router.post("/setup/complete", authenticateJWT, markSetupComplete); diff --git a/server/v1/modules/profile/profileSettingsController.js b/server/v1/modules/profile/profileSettingsController.js index 20201306..ef735309 100644 --- a/server/v1/modules/profile/profileSettingsController.js +++ b/server/v1/modules/profile/profileSettingsController.js @@ -29,7 +29,7 @@ async function enablePhotoChange(req, res) { "Profile Pic change is available", "All_Hostels", { redirectType: "profile", isAlert: "true" } - ); + ).catch((err) => console.error("Profile update notification failed:", err)); // Reset setup status for all users who completed it earlier const result = await User.updateMany( { isSetupDone: true }, @@ -60,7 +60,7 @@ async function disablePhotoChange(req, res) { "Profile Pic change is no longer available", "All_Hostels", { redirectType: "profile" } - ); + ).catch((err) => console.error("Profile update notification failed:", err)); return res .status(200) .json({ message: "Disabled", allowProfilePhotoChange: false }); diff --git a/server/v1/modules/room_cleaning/rcCleanerModel.js b/server/v1/modules/room_cleaning/rcCleanerModel.js new file mode 100644 index 00000000..e7473afe --- /dev/null +++ b/server/v1/modules/room_cleaning/rcCleanerModel.js @@ -0,0 +1,35 @@ +const mongoose = require("mongoose"); + +// Room cleaner configuration per hostel. +// Each cleaner can work in one or more fixed slots (A–D). + +const rcCleanerSchema = new mongoose.Schema( + { + hostelId: { + type: mongoose.Schema.Types.ObjectId, + ref: "Hostel", + required: true, + index: true, + }, + name: { + type: String, + required: true, + trim: true, + }, + slots: { + type: [String], + enum: ["A", "B", "C", "D"], + required: true, + validate: { + validator: (arr) => Array.isArray(arr) && arr.length > 0, + message: "Cleaner must be assigned to at least one slot", + }, + }, + }, + { timestamps: true }, +); + +const RcCleaner = mongoose.model("RcCleaner", rcCleanerSchema); + +module.exports = { RcCleaner }; + diff --git a/server/v1/modules/room_cleaning/roomCleaningBookingModel.js b/server/v1/modules/room_cleaning/roomCleaningBookingModel.js new file mode 100644 index 00000000..a5896111 --- /dev/null +++ b/server/v1/modules/room_cleaning/roomCleaningBookingModel.js @@ -0,0 +1,99 @@ +const mongoose = require("mongoose"); + +// Single collection for all room-cleaning bookings. +// Fields are derived from ROOM_CLEANING_FLOW.md. +// +// Migration note: If you see E11000 duplicate key on index +// "user_1_slot_1_requestedDate_1", that index is from an old schema (user, +// requestedDate). Drop it: run server/v1/scripts/dropRoomCleaningLegacyIndex.js +// once per environment (e.g. production/staging). + +const roomCleaningBookingSchema = new mongoose.Schema( + { + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: true, + index: true, + }, + hostelId: { + type: mongoose.Schema.Types.ObjectId, + ref: "Hostel", + required: true, + index: true, + }, + // Calendar date for which cleaning is requested (start-of-day). + bookingDate: { + type: Date, + required: true, + index: true, + }, + // Slot identifiers: A = 12–14, B = 14–16, C = 16–18, D = 18–20. + slot: { + type: String, + enum: ["A", "B", "C", "D"], + required: true, + index: true, + }, + // Optional assignment to a specific room cleaner (RcCleaner._id). + assignedTo: { + type: mongoose.Schema.Types.ObjectId, + ref: "RcCleaner", + default: null, + index: true, + }, + status: { + type: String, + enum: ["Booked", "Buffered", "Cancelled", "Cleaned", "CouldNotBeCleaned"], + default: "Booked", + index: true, + }, + // Reason is only meaningful when status === "CouldNotBeCleaned". + // Restrict to a fixed set of values to keep reporting consistent. + reason: { + type: String, + enum: [ + "Student Did Not Respond", + "Student Asked To Cancel", + "Room Cleaners Not Available", + ], + default: null, + }, + // Optional reference to rcFeedback document containing structured feedback + // for this booking (only after Cleaned). + feedbackId: { + type: mongoose.Schema.Types.ObjectId, + ref: "RcFeedback", + default: null, + index: true, + }, + // Manager finalization timestamp for yesterday/closeout flows. + // Once set, the booking status/reason should not be editable via manager finalize endpoint. + statusFinalizedAt: { + type: Date, + default: null, + index: true, + }, + }, + { timestamps: true }, +); + +// Prevent duplicate *active* booking for same user + date + slot (per hostel). +// Cancelled / CouldNotBeCleaned bookings should not block a new booking. +roomCleaningBookingSchema.index( + { userId: 1, hostelId: 1, bookingDate: 1, slot: 1 }, + { + unique: true, + partialFilterExpression: { + status: { $in: ["Booked", "Buffered", "Cleaned"] }, + }, + }, +); + +const RoomCleaningBooking = mongoose.model( + "RoomCleaningBooking", + roomCleaningBookingSchema, +); + +module.exports = { RoomCleaningBooking }; + diff --git a/server/v1/modules/room_cleaning/roomCleaningController.js b/server/v1/modules/room_cleaning/roomCleaningController.js new file mode 100644 index 00000000..fffc07fd --- /dev/null +++ b/server/v1/modules/room_cleaning/roomCleaningController.js @@ -0,0 +1,1197 @@ +const { RoomCleaningBooking } = require("./roomCleaningBookingModel"); +const { RcFeedback } = require("./roomCleaningFeedbackModel"); +const { RcCleaner } = require("./rcCleanerModel"); +const { Hostel } = require("../hostel/hostelModel"); +const { User } = require("../user/userModel"); + +// In-memory cache for per-hostel slot capacities. +// Shape: { [hostelId]: { value, expiresAt } } +const slotCapacityCache = Object.create(null); +const SLOT_CAPACITY_TTL_MS = 30 * 60 * 1000; // 30 minutes + +const SLOTS = [ + { id: "A", timeRange: "12:00-14:00" }, + { id: "B", timeRange: "14:00-16:00" }, + { id: "C", timeRange: "16:00-18:00" }, + { id: "D", timeRange: "18:00-20:00" }, +]; + +// IST helper: UTC+5:30 +const IST_OFFSET_MINUTES = 5.5 * 60; + +const getISTNow = () => { + const now = new Date(); + const utcMillis = now.getTime() + now.getTimezoneOffset() * 60000; + const istMillis = utcMillis + IST_OFFSET_MINUTES * 60000; + return new Date(istMillis); +}; + +const startOfDayIST = (dateInput) => { + const d = new Date(dateInput); + return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0); +}; + +const endOfDayIST = (dateInput) => { + const d = new Date(dateInput); + return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999); +}; + +/** + * Whether the booking window is currently open for the given booking date. + * Window for date D: open = (D-3) at 09:00 IST, close = end of (D-2) IST. + */ +function isBookingWindowOpen(bookingDate, now = getISTNow()) { + const d = startOfDayIST(bookingDate); + const openDay = new Date(d); + openDay.setDate(openDay.getDate() - 3); + const openTime = new Date( + openDay.getFullYear(), + openDay.getMonth(), + openDay.getDate(), + 9, + 0, + 0, + 0, + ); + const closeDay = new Date(d); + closeDay.setDate(closeDay.getDate() - 2); + const closeTime = endOfDayIST(closeDay); + return now >= openTime && now <= closeTime; +} + +// Shared helper to validate targetDate (D+2 or D+3), resolve hostel, +// and compute booking window. +async function resolveContext({ req, dateParam, allowWindowBypass = false }) { + if (!req.user?._id) { + const err = new Error("User not authenticated"); + err.statusCode = 401; + throw err; + } + + if (!dateParam) { + const err = new Error("Query/body field 'date' (YYYY-MM-DD) is required"); + err.statusCode = 400; + throw err; + } + + const parsed = new Date(dateParam); + if (Number.isNaN(parsed.getTime())) { + const err = new Error("Provided 'date' is invalid"); + err.statusCode = 400; + throw err; + } + + const targetDate = startOfDayIST(parsed); + const today = startOfDayIST(getISTNow()); + const msPerDay = 24 * 60 * 60 * 1000; + const diffDays = Math.round((targetDate - today) / msPerDay); + + if (diffDays !== 2 && diffDays !== 3) { + const err = new Error("You can only operate on D+2 or D+3 from today"); + err.statusCode = 400; + throw err; + } + + // Determine hostel: either from query/body or from user's hostel field. + let hostelId = req.query.hostelId || req.body.hostelId; + if (!hostelId) { + const user = await User.findById(req.user._id).select("hostel").lean(); + if (!user) { + const err = new Error("User not found"); + err.statusCode = 404; + throw err; + } + hostelId = user.hostel; + if (!hostelId) { + const err = new Error("User is not associated with any hostel"); + err.statusCode = 400; + throw err; + } + } + + const hostel = await Hostel.findById(hostelId) + .select("hostel_name") + .lean(); + if (!hostel) { + const err = new Error("Hostel not found"); + err.statusCode = 404; + throw err; + } + + const now = getISTNow(); + + const openDay = new Date(targetDate); + openDay.setDate(openDay.getDate() - 3); + const openTime = new Date( + openDay.getFullYear(), + openDay.getMonth(), + openDay.getDate(), + 9, + 0, + 0, + 0, + ); + + const closeDay = new Date(targetDate); + closeDay.setDate(closeDay.getDate() - 2); + const closeTime = endOfDayIST(closeDay); + + if (!allowWindowBypass && (now < openTime || now > closeTime)) { + const err = new Error("Booking window is not open for this date"); + err.statusCode = 400; + err.details = { openTime, closeTime }; + throw err; + } + + return { + targetDate, + hostelId, + hostel, + openTime, + closeTime, + now, + }; +} + +// Compute per-slot capacity based on RcCleaner configuration for a hostel. +// Returns an object: { A: { primaryCapacity, bufferCapacity }, ... }. +async function getSlotCapacitiesForHostel(hostelId) { + const cleaners = await RcCleaner.find({ hostelId }) + .select("slots") + .lean(); + + const counts = { A: 0, B: 0, C: 0, D: 0 }; + for (const c of cleaners) { + for (const s of c.slots || []) { + if (counts[s] != null) counts[s] += 1; + } + } + const capacities = {}; + for (const slotId of ["A", "B", "C", "D"]) { + const cleanersInSlot = counts[slotId] || 0; + const primaryCapacity = + cleanersInSlot === 0 ? 0 : Math.max(cleanersInSlot - 1, 0) * 3 * 2; + const bufferCapacity = cleanersInSlot === 0 ? 0 : 1 * 3 * 2; + capacities[slotId] = { primaryCapacity, bufferCapacity }; + } + return capacities; +} + +async function getCachedSlotCapacitiesForHostel(hostelId) { + const key = String(hostelId); + const cached = slotCapacityCache[key]; + const now = Date.now(); + if (cached && cached.expiresAt > now) { + return cached.value; + } + const value = await getSlotCapacitiesForHostel(hostelId); + slotCapacityCache[key] = { + value, + expiresAt: now + SLOT_CAPACITY_TTL_MS, + }; + return value; +} + +function invalidateSlotCapacityCache(hostelId) { + const key = String(hostelId); + if (slotCapacityCache[key]) { + delete slotCapacityCache[key]; + } +} + +/** + * GET /api/room-cleaning/availability + * + * Called when the user opens the room-cleaning page. + * - Only the user JWT is sent. + * - Computes which future days currently have the booking window open + * (according to the D+2 / D+3 rules). + * - For each such day, computes slot availability (primary + buffer). + */ +const getAvailability = async (req, res) => { + try { + if (!req.user?._id) { + return res.status(401).json({ message: "User not authenticated" }); + } + + // Resolve hostel purely from user's hostel field. + const user = await User.findById(req.user._id).select("hostel").lean(); + if (!user) { + return res.status(404).json({ message: "User not found" }); + } + if (!user.hostel) { + return res + .status(400) + .json({ message: "User is not associated with any hostel" }); + } + + const hostelId = user.hostel; + const hostel = await Hostel.findById(hostelId) + .select("hostel_name") + .lean(); + if (!hostel) { + return res.status(404).json({ message: "Hostel not found" }); + } + + const slotCapacities = await getCachedSlotCapacitiesForHostel(hostelId); + + const now = getISTNow(); + const today = startOfDayIST(now); + + // Global 14-day rule: if user has any Cleaned/Booked/Buffered booking + // in the 14-day window around D+3, they cannot create a new booking, + // but we still return availability so the UI can show disabled slots. + const dPlus3 = new Date(today); + dPlus3.setDate(dPlus3.getDate() + 3); + + const windowEnd = new Date(dPlus3); + windowEnd.setDate(windowEnd.getDate() + 1); // exclusive + const windowStart = new Date(dPlus3); + windowStart.setDate(windowStart.getDate() - 13); + + const recentCount = await RoomCleaningBooking.countDocuments({ + userId: req.user._id, + hostelId, + bookingDate: { $gte: windowStart, $lt: windowEnd }, + status: { $in: ["Booked", "Buffered", "Cleaned"] }, + }); + + // Candidate target days: D+2 and D+3 relative to today. + const deltas = [2, 3]; + const dayResults = []; + + for (const delta of deltas) { + const targetDate = new Date(today); + targetDate.setDate(targetDate.getDate() + delta); + + const openDay = new Date(targetDate); + openDay.setDate(openDay.getDate() - 3); + const openTime = new Date( + openDay.getFullYear(), + openDay.getMonth(), + openDay.getDate(), + 9, + 0, + 0, + 0, + ); + + const closeDay = new Date(targetDate); + closeDay.setDate(closeDay.getDate() - 2); + const closeTime = endOfDayIST(closeDay); + + if (now < openTime || now > closeTime) { + // Booking window not open for this specific target date. + continue; + } + + // Compute availability for this target date. + const bookings = await RoomCleaningBooking.find({ + hostelId, + bookingDate: targetDate, + status: { $in: ["Booked", "Buffered"] }, + }) + .select("slot status") + .lean(); + + const slots = SLOTS.map((slotMeta) => { + const slotId = slotMeta.id; + const forSlot = bookings.filter((b) => b.slot === slotId); + + const primaryUsed = forSlot.filter( + (b) => b.status === "Booked", + ).length; + const bufferUsed = forSlot.filter( + (b) => b.status === "Buffered", + ).length; + const { primaryCapacity, bufferCapacity } = + slotCapacities[slotId] || {}; + const slotsLeft = Math.max((primaryCapacity || 0) - primaryUsed, 0); + const bufferSlotsLeft = + slotsLeft > 0 + ? 0 + : Math.max((bufferCapacity || 0) - bufferUsed, 0); + + return { + slot: slotId, + timeRange: slotMeta.timeRange, + primaryCapacity, + bufferCapacity, + slotsLeft, + bufferSlotsLeft, + }; + }).filter( + (s) => + (s.primaryCapacity || 0) + (s.bufferCapacity || 0) > 0, + ); + + const dateIst = startOfDayIST(targetDate); + const yyyy = dateIst.getFullYear(); + const mm = String(dateIst.getMonth() + 1).padStart(2, "0"); + const dd = String(dateIst.getDate()).padStart(2, "0"); + const dateStr = `${yyyy}-${mm}-${dd}`; + + dayResults.push({ + // Calendar date in IST as YYYY-MM-DD string. + date: dateStr, + openTime, + closeTime, + slots, + }); + } + + return res.status(200).json({ + hostelId, + hostelName: hostel.hostel_name || null, + now, + canBook: recentCount === 0 && dayResults.length > 0, + days: dayResults, + }); + } catch (error) { + console.error("getAvailability error:", error); + return res.status(500).json({ + message: "Failed to fetch room-cleaning availability", + error: String(error.message || error), + }); + } +}; + +/** + * Hostel frontend: CRUD for RcCleaner + * All handlers assume authenticateMessManagerJWT has set req.managerHostel. + */ + +const getRcCleaners = async (req, res) => { + try { + const hostel = req.managerHostel; + if (!hostel) { + return res.status(403).json({ message: "Manager hostel not set" }); + } + + const cleaners = await RcCleaner.find({ hostelId: hostel._id }) + .sort({ createdAt: 1 }) + .lean(); + + return res.status(200).json({ + cleaners: cleaners.map((c) => ({ + _id: c._id, + name: c.name, + slots: c.slots, + })), + }); + } catch (err) { + console.error("getRcCleaners error:", err); + return res.status(500).json({ + message: "Failed to fetch room cleaners", + error: String(err?.message || err), + }); + } +}; + +const postRcCleaner = async (req, res) => { + try { + const hostel = req.managerHostel; + if (!hostel) { + return res.status(403).json({ message: "Manager hostel not set" }); + } + + const { name, slots } = req.body || {}; + if (!name || !Array.isArray(slots) || slots.length === 0) { + return res.status(400).json({ + message: "name and non-empty slots array are required", + }); + } + + const cleaner = await RcCleaner.create({ + hostelId: hostel._id, + name: String(name).trim(), + slots, + }); + + invalidateSlotCapacityCache(hostel._id); + + return res.status(201).json({ + cleaner: { + _id: cleaner._id, + name: cleaner.name, + slots: cleaner.slots, + }, + }); + } catch (err) { + console.error("postRcCleaner error:", err); + return res.status(500).json({ + message: "Failed to create room cleaner", + error: String(err?.message || err), + }); + } +}; + +const putRcCleaner = async (req, res) => { + try { + const hostel = req.managerHostel; + if (!hostel) { + return res.status(403).json({ message: "Manager hostel not set" }); + } + + const cleanerId = req.params.id; + if (!cleanerId) { + return res.status(400).json({ message: "Cleaner id is required" }); + } + + const { name, slots } = req.body || {}; + + const update = {}; + if (name != null) update.name = String(name).trim(); + if (Array.isArray(slots)) update.slots = slots; + + const cleaner = await RcCleaner.findOneAndUpdate( + { _id: cleanerId, hostelId: hostel._id }, + { $set: update }, + { new: true }, + ).lean(); + + if (!cleaner) { + return res.status(404).json({ message: "Cleaner not found" }); + } + + invalidateSlotCapacityCache(hostel._id); + + return res.status(200).json({ + cleaner: { + _id: cleaner._id, + name: cleaner.name, + slots: cleaner.slots, + }, + }); + } catch (err) { + console.error("putRcCleaner error:", err); + return res.status(500).json({ + message: "Failed to update room cleaner", + error: String(err?.message || err), + }); + } +}; + +const deleteRcCleaner = async (req, res) => { + try { + const hostel = req.managerHostel; + if (!hostel) { + return res.status(403).json({ message: "Manager hostel not set" }); + } + + const cleanerId = req.params.id; + if (!cleanerId) { + return res.status(400).json({ message: "Cleaner id is required" }); + } + + const cleaner = await RcCleaner.findOneAndDelete({ + _id: cleanerId, + hostelId: hostel._id, + }).lean(); + + if (!cleaner) { + return res.status(404).json({ message: "Cleaner not found" }); + } + + invalidateSlotCapacityCache(hostel._id); + + // Note: we intentionally do NOT clear existing RoomCleaningBooking.assignedTo + // references here; historical data can still point to deleted cleaners. + + return res.status(200).json({ message: "Cleaner deleted" }); + } catch (err) { + console.error("deleteRcCleaner error:", err); + return res.status(500).json({ + message: "Failed to delete room cleaner", + error: String(err?.message || err), + }); + } +}; + +/** + * POST /api/room-cleaning/booking + * + * Body: + * - date: YYYY-MM-DD (target booking date) + * - slot: "A" | "B" | "C" | "D" + * - hostelId (optional): override hostel; otherwise inferred from user.hostel + * + * Rules: + * - Same D+2/D+3 and booking window constraints as availability. + * - Per user, per hostel: at most 1 booking in any rolling 14-day window, + * considering statuses: Booked, Buffered, Cleaned. + * - Capacity check using primary and buffer capacities. + * - Creates booking with status "Booked" if primary slots left, + * otherwise "Buffered" if buffer slots left; otherwise rejects. + */ +const createBooking = async (req, res) => { + const session = await RoomCleaningBooking.startSession(); + session.startTransaction(); + + try { + const { slot } = req.body || {}; + + if (!SLOTS.some((s) => s.id === slot)) { + await session.abortTransaction(); + session.endSession(); + return res.status(400).json({ + message: 'Invalid slot. Expected one of "A", "B", "C", "D".', + }); + } + + const context = await resolveContext({ + req, + dateParam: req.body.date, + allowWindowBypass: false, + }); + + const { targetDate, hostelId, hostel } = context; + + const slotCapacities = await getCachedSlotCapacitiesForHostel(hostelId); + const { primaryCapacity = 0, bufferCapacity = 0 } = + slotCapacities[slot] || {}; + + // Enforce "1 booking every 14 days" rule (Booked, Buffered, Cleaned). + const windowEnd = new Date(targetDate); + windowEnd.setDate(windowEnd.getDate() + 1); // exclusive + const windowStart = new Date(targetDate); + windowStart.setDate(windowStart.getDate() - 13); + + const recentCount = await RoomCleaningBooking.countDocuments({ + userId: req.user._id, + hostelId, + bookingDate: { $gte: windowStart, $lt: windowEnd }, + status: { $in: ["Booked", "Buffered", "Cleaned"] }, + }).session(session); + + if (recentCount >= 1) { + await session.abortTransaction(); + session.endSession(); + return res.status(400).json({ + message: + "You can only have one room cleaning booking in any 14-day period.", + }); + } + + // Capacity check for the chosen slot on the target date. + const bookingsForSlot = await RoomCleaningBooking.find( + { + hostelId, + bookingDate: targetDate, + slot, + status: { $in: ["Booked", "Buffered"] }, + }, + "status", + { session }, + ).lean(); + + const primaryUsed = bookingsForSlot.filter( + (b) => b.status === "Booked", + ).length; + const bufferUsed = bookingsForSlot.filter( + (b) => b.status === "Buffered", + ).length; + + const slotsLeft = Math.max(primaryCapacity - primaryUsed, 0); + const bufferSlotsLeft = + slotsLeft > 0 ? 0 : Math.max(bufferCapacity - bufferUsed, 0); + + if (slotsLeft <= 0 && bufferSlotsLeft <= 0) { + await session.abortTransaction(); + session.endSession(); + return res.status(400).json({ + message: "No capacity left for this slot on the selected date.", + }); + } + + const status = slotsLeft > 0 ? "Booked" : "Buffered"; + + let booking; + try { + const created = await RoomCleaningBooking.create( + [ + { + userId: req.user._id, + hostelId, + bookingDate: targetDate, + slot, + status, + }, + ], + { session }, + ); + booking = created[0]; + } catch (err) { + if (err?.code === 11000) { + await session.abortTransaction(); + session.endSession(); + return res.status(409).json({ + message: + "You already have a booking for this slot on this date in this hostel.", + }); + } + throw err; + } + + await session.commitTransaction(); + session.endSession(); + + const finalSlotsLeft = + status === "Booked" ? Math.max(slotsLeft - 1, 0) : slotsLeft; + const finalBufferSlotsLeft = + status === "Buffered" + ? Math.max(bufferSlotsLeft - 1, 0) + : bufferSlotsLeft; + + return res.status(201).json({ + message: "Room cleaning booking created successfully.", + booking, + availability: { + hostelId, + hostelName: hostel.hostel_name || null, + date: targetDate, + slot, + primaryCapacity, + bufferCapacity, + slotsLeft: finalSlotsLeft, + bufferSlotsLeft: finalBufferSlotsLeft, + }, + }); + } catch (error) { + try { + await session.abortTransaction(); + } catch (e) { + // ignore + } + session.endSession(); + + const status = error.statusCode || 500; + if (status >= 500) { + console.error("createBooking error (transaction):", error); + } + return res.status(status).json({ + message: error.message || "Failed to create room-cleaning booking", + ...(error.details ? { details: error.details } : {}), + }); + } +}; + +/** + * POST /api/room-cleaning/booking/cancel + * + * Body: + * - bookingId: ObjectId + * + * Rules: + * - Only the booking owner can cancel. + * - Only future bookings (bookingDate > today) can be cancelled. + * - Only statuses Booked or Buffered can be cancelled. + * - Cancellation allowed only when the booking window for that date is open. + */ +const cancelBooking = async (req, res) => { + try { + const { bookingId } = req.body || {}; + if (!bookingId) { + return res + .status(400) + .json({ message: "Field 'bookingId' is required" }); + } + + if (!req.user?._id) { + return res.status(401).json({ message: "User not authenticated" }); + } + + const booking = await RoomCleaningBooking.findOne({ + _id: bookingId, + userId: req.user._id, + }); + + if (!booking) { + return res + .status(404) + .json({ message: "Booking not found for this user" }); + } + + if (!["Booked", "Buffered"].includes(booking.status)) { + return res.status(400).json({ + message: "Only Booked or Buffered bookings can be cancelled", + }); + } + + const today = startOfDayIST(getISTNow()); + const bookingDate = startOfDayIST(booking.bookingDate); + if (bookingDate <= today) { + return res.status(400).json({ + message: "Past or same-day bookings cannot be cancelled", + }); + } + + if (!isBookingWindowOpen(booking.bookingDate)) { + return res.status(400).json({ + message: + "Cancellation is only allowed while the booking window for this date is open", + }); + } + + booking.status = "Cancelled"; + await booking.save(); + + return res.status(200).json({ + message: "Room cleaning booking cancelled successfully", + booking, + }); + } catch (error) { + console.error("cancelBooking error:", error); + return res.status(500).json({ + message: "Failed to cancel room-cleaning booking", + error: String(error.message || error), + }); + } +}; + +/** + * GET /api/room-cleaning/booking/my + * + * Returns all room-cleaning bookings for the authenticated user, + * sorted by bookingDate desc then createdAt desc. + * Each booking includes canCancel: true only when status is Booked/Buffered, + * bookingDate is in the future, and the booking window for that date is open. + */ +const getMyBookings = async (req, res) => { + try { + if (!req.user?._id) { + return res.status(401).json({ message: "User not authenticated" }); + } + + const bookings = await RoomCleaningBooking.find({ + userId: req.user._id, + }) + .sort({ bookingDate: -1, createdAt: -1 }) + .select("_id bookingDate slot status hostelId feedbackId reason") + .lean(); + + const today = startOfDayIST(getISTNow()); + const list = bookings.map((b) => { + const bookingDate = startOfDayIST(b.bookingDate); + const future = bookingDate > today; + const cancellableStatus = + b.status === "Booked" || b.status === "Buffered"; + const windowOpen = future && isBookingWindowOpen(b.bookingDate); + const canCancel = cancellableStatus && future && windowOpen; + return { ...b, canCancel }; + }); + + return res.status(200).json({ bookings: list }); + } catch (error) { + console.error("getMyBookings error:", error); + return res.status(500).json({ + message: "Failed to fetch room-cleaning bookings", + error: String(error.message || error), + }); + } +}; + +/** + * POST /api/room-cleaning/booking/feedback + * + * Body: + * - bookingId: ObjectId + * - reachedInSlot: "Yes" | "No" | "NotSure" + * - staffPoliteness: "Yes" | "No" | "NotSure" + * - satisfaction: 1–5 + * - remarks?: string + */ +const submitFeedback = async (req, res) => { + try { + const { bookingId, reachedInSlot, staffPoliteness, satisfaction, remarks } = + req.body || {}; + + if (!bookingId) { + return res + .status(400) + .json({ message: "Field 'bookingId' is required" }); + } + + if (!req.user?._id) { + return res.status(401).json({ message: "User not authenticated" }); + } + + const booking = await RoomCleaningBooking.findOne({ + _id: bookingId, + userId: req.user._id, + }).lean(); + + if (!booking) { + return res + .status(404) + .json({ message: "Booking not found for this user" }); + } + + if (booking.status !== "Cleaned") { + return res.status(400).json({ + message: "Feedback can only be submitted for cleaned bookings", + }); + } + + if (booking.feedbackId) { + return res.status(400).json({ + message: "Feedback has already been submitted for this booking", + }); + } + + const allowedBinary = ["Yes", "No", "NotSure"]; + if (!allowedBinary.includes(reachedInSlot)) { + return res.status(400).json({ + message: + "Field 'reachedInSlot' must be one of Yes, No, NotSure", + }); + } + if (!allowedBinary.includes(staffPoliteness)) { + return res.status(400).json({ + message: + "Field 'staffPoliteness' must be one of Yes, No, NotSure", + }); + } + + const parsedSatisfaction = Number(satisfaction); + if ( + !Number.isFinite(parsedSatisfaction) || + parsedSatisfaction < 1 || + parsedSatisfaction > 5 + ) { + return res.status(400).json({ + message: "Field 'satisfaction' must be a number between 1 and 5", + }); + } + + const session = await RoomCleaningBooking.startSession(); + session.startTransaction(); + try { + const [feedbackDoc] = await RcFeedback.create( + [ + { + userId: req.user._id, + bookingId: booking._id, + hostelId: booking.hostelId, + reachedInSlot, + staffPoliteness, + satisfaction: parsedSatisfaction, + remarks: remarks ? String(remarks) : "", + }, + ], + { session }, + ); + + await RoomCleaningBooking.updateOne( + { _id: booking._id }, + { $set: { feedbackId: feedbackDoc._id } }, + { session }, + ); + + await session.commitTransaction(); + session.endSession(); + + return res.status(201).json({ + message: "Feedback submitted successfully", + feedbackId: feedbackDoc._id, + }); + } catch (err) { + await session.abortTransaction(); + session.endSession(); + if (err?.code === 11000) { + return res.status(409).json({ + message: "Feedback already exists for this booking", + }); + } + throw err; + } + } catch (error) { + console.error("submitFeedback error:", error); + return res.status(500).json({ + message: "Failed to submit room-cleaning feedback", + error: String(error.message || error), + }); + } +}; + +/** + * RC Manager: GET tomorrow's bookings for the manager's hostel. + * Requires authenticateMessManagerJWT (req.managerHostel). + * Query: date (optional) YYYY-MM-DD; default is tomorrow in IST. + * Returns: { bookings: [ { _id, roomNumber, slot, timeRange, assignedTo } ], totalCleaners } + */ +const getRcTomorrow = async (req, res) => { + try { + const hostel = req.managerHostel; + if (!hostel) { + return res.status(403).json({ message: "Manager hostel not set" }); + } + + const dateParam = req.query.date; + let tomorrowStart; + if (dateParam) { + const parsed = new Date(dateParam); + if (Number.isNaN(parsed.getTime())) { + return res.status(400).json({ message: "Invalid date" }); + } + tomorrowStart = startOfDayIST(parsed); + } else { + const now = getISTNow(); + const tomorrow = new Date(now); + tomorrow.setDate(tomorrow.getDate() + 1); + tomorrowStart = startOfDayIST(tomorrow); + } + + const bookings = await RoomCleaningBooking.find({ + hostelId: hostel._id, + bookingDate: tomorrowStart, + status: { $ne: "Cancelled" }, + }) + .sort({ slot: 1, createdAt: 1 }) + .select("_id userId slot assignedTo status statusFinalizedAt") + .lean(); + + const userIds = [...new Set(bookings.map((b) => b.userId).filter(Boolean))]; + const userMap = {}; + if (userIds.length > 0) { + const users = await User.find({ _id: { $in: userIds } }) + .select("_id roomNumber phoneNumber") + .lean(); + for (const u of users) { + const key = u._id.toString(); + userMap[key] = { + roomNumber: u.roomNumber != null ? String(u.roomNumber) : "—", + phoneNumber: u.phoneNumber != null ? String(u.phoneNumber) : "—", + }; + } + } + + const cleaners = await RcCleaner.find({ hostelId: hostel._id }) + .select("_id name slots") + .lean(); + const slotMap = Object.fromEntries(SLOTS.map((s) => [s.id, s.timeRange])); + const list = bookings.map((b) => { + const u = userMap[b.userId?.toString()]; + return { + _id: b._id, + roomNumber: u?.roomNumber ?? "—", + phoneNumber: u?.phoneNumber ?? "—", + slot: b.slot, + timeRange: slotMap[b.slot] || "", + assignedTo: b.assignedTo ?? null, + status: b.status ?? null, + statusFinalizedAt: b.statusFinalizedAt ?? null, + }; + }); + + return res.status(200).json({ + bookings: list, + cleaners: cleaners.map((c) => ({ + _id: c._id, + name: c.name, + slots: c.slots, + })), + }); + } catch (err) { + console.error("getRcTomorrow error:", err); + return res.status(500).json({ + message: "Failed to fetch tomorrow bookings", + error: String(err?.message || err), + }); + } +}; + +/** + * RC Manager: POST to save assignments for tomorrow. + * Requires authenticateMessManagerJWT. + * Body: { date? (YYYY-MM-DD), assignments: [ { bookingId, assignedTo } ] } + * assignedTo: cleanerId (RcCleaner._id) or null/omit for unassigned. + */ +const postRcTomorrowAssign = async (req, res) => { + try { + const hostel = req.managerHostel; + if (!hostel) { + return res.status(403).json({ message: "Manager hostel not set" }); + } + + const { date: dateParam, assignments } = req.body || {}; + if (!Array.isArray(assignments)) { + return res.status(400).json({ message: "assignments must be an array" }); + } + + let tomorrowStart; + if (dateParam) { + const parsed = new Date(dateParam); + if (Number.isNaN(parsed.getTime())) { + return res.status(400).json({ message: "Invalid date" }); + } + tomorrowStart = startOfDayIST(parsed); + } else { + const now = getISTNow(); + const tomorrow = new Date(now); + tomorrow.setDate(tomorrow.getDate() + 1); + tomorrowStart = startOfDayIST(tomorrow); + } + + const cleaners = await RcCleaner.find({ hostelId: hostel._id }) + .select("_id") + .lean(); + const cleanerIdSet = new Set(cleaners.map((c) => c._id.toString())); + + for (const item of assignments) { + const { bookingId, assignedTo } = item; + if (!bookingId) continue; + + const filter = { + _id: bookingId, + hostelId: hostel._id, + bookingDate: tomorrowStart, + }; + + if (assignedTo == null || assignedTo === "" || assignedTo === 0) { + await RoomCleaningBooking.updateOne(filter, { $unset: { assignedTo: 1 } }); + } else { + const cleanerId = String(assignedTo); + if (!cleanerIdSet.has(cleanerId)) { + return res.status(400).json({ + message: `assignedTo must be a valid RcCleaner id for booking ${bookingId}`, + }); + } + await RoomCleaningBooking.updateOne(filter, { + $set: { assignedTo: cleanerId }, + }); + } + } + + return res.status(200).json({ message: "Assignments saved" }); + } catch (err) { + console.error("postRcTomorrowAssign error:", err); + return res.status(500).json({ + message: "Failed to save assignments", + error: String(err?.message || err), + }); + } +}; + +/** + * RC Manager: POST to finalize booking statuses for a date. + * Requires authenticateMessManagerJWT. + * + * Body: + * { + * date: 'YYYY-MM-DD', // required + * updates: [ { bookingId, status, reason? } ] + * } + * + * Allowed status transitions (for manager finalization): + * - Cleaned (reason cleared) + * - CouldNotBeCleaned (requires reason in allowed set) + * + * Only updates bookings that belong to the manager hostel and match bookingDate. + */ +const postRcFinalizeStatuses = async (req, res) => { + try { + const hostel = req.managerHostel; + if (!hostel) { + return res.status(403).json({ message: "Manager hostel not set" }); + } + + const { date: dateParam, updates } = req.body || {}; + if (!dateParam) { + return res.status(400).json({ message: "date is required (YYYY-MM-DD)" }); + } + if (!Array.isArray(updates)) { + return res.status(400).json({ message: "updates must be an array" }); + } + + const parsed = new Date(dateParam); + if (Number.isNaN(parsed.getTime())) { + return res.status(400).json({ message: "Invalid date" }); + } + const targetDate = startOfDayIST(parsed); + + const allowedReasons = new Set([ + "Student Did Not Respond", + "Student Asked To Cancel", + "Room Cleaners Not Available", + ]); + + let updated = 0; + let locked = 0; + const now = new Date(); + + for (const item of updates) { + const { bookingId, status, reason } = item || {}; + if (!bookingId) continue; + if (!status) { + return res.status(400).json({ + message: `status is required for booking ${bookingId}`, + }); + } + + if (!["Cleaned", "CouldNotBeCleaned"].includes(status)) { + return res.status(400).json({ + message: `Invalid status "${status}" for booking ${bookingId}`, + }); + } + + const filter = { + _id: bookingId, + hostelId: hostel._id, + bookingDate: targetDate, + status: { $in: ["Booked", "Buffered", "Cleaned", "CouldNotBeCleaned"] }, + statusFinalizedAt: null, + }; + + if (status === "Cleaned") { + const r = await RoomCleaningBooking.updateOne(filter, { + $set: { status: "Cleaned", statusFinalizedAt: now }, + $unset: { reason: 1 }, + }); + if (r?.modifiedCount) updated += 1; + else locked += 1; + } else { + if (!reason || !allowedReasons.has(reason)) { + return res.status(400).json({ + message: `reason must be one of [${[...allowedReasons].join( + ", ", + )}] for booking ${bookingId}`, + }); + } + const r = await RoomCleaningBooking.updateOne(filter, { + $set: { status: "CouldNotBeCleaned", reason, statusFinalizedAt: now }, + }); + if (r?.modifiedCount) updated += 1; + else locked += 1; + } + } + + return res.status(200).json({ + message: "Statuses finalized", + updated, + locked, + }); + } catch (err) { + console.error("postRcFinalizeStatuses error:", err); + return res.status(500).json({ + message: "Failed to finalize statuses", + error: String(err?.message || err), + }); + } +}; + +module.exports = { + getAvailability, + createBooking, + cancelBooking, + getMyBookings, + submitFeedback, + getRcTomorrow, + postRcTomorrowAssign, + postRcFinalizeStatuses, + getRcCleaners, + postRcCleaner, + putRcCleaner, + deleteRcCleaner, +}; + diff --git a/server/v1/modules/room_cleaning/roomCleaningFeedbackModel.js b/server/v1/modules/room_cleaning/roomCleaningFeedbackModel.js new file mode 100644 index 00000000..bae2e102 --- /dev/null +++ b/server/v1/modules/room_cleaning/roomCleaningFeedbackModel.js @@ -0,0 +1,59 @@ +const mongoose = require("mongoose"); + +// Feedback for a single room-cleaning booking. +// Each RcFeedback document is linked from RoomCleaningBooking.feedbackId. + +const rcFeedbackSchema = new mongoose.Schema( + { + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: true, + index: true, + }, + bookingId: { + type: mongoose.Schema.Types.ObjectId, + ref: "RoomCleaningBooking", + required: true, + unique: true, + index: true, + }, + hostelId: { + type: mongoose.Schema.Types.ObjectId, + ref: "Hostel", + required: true, + index: true, + }, + // Q1: Did staff visit during the selected slot? + reachedInSlot: { + type: String, + enum: ["Yes", "No", "NotSure"], + required: true, + }, + // Q2: Was the staff polite/professional? + staffPoliteness: { + type: String, + enum: ["Yes", "No", "NotSure"], + required: true, + }, + // Q3: Overall satisfaction (1–5). + satisfaction: { + type: Number, + min: 1, + max: 5, + required: true, + }, + // Optional free-text remarks. + remarks: { + type: String, + trim: true, + default: "", + }, + }, + { timestamps: true }, +); + +const RcFeedback = mongoose.model("RcFeedback", rcFeedbackSchema); + +module.exports = { RcFeedback }; + diff --git a/server/v1/modules/room_cleaning/roomCleaningRoute.js b/server/v1/modules/room_cleaning/roomCleaningRoute.js new file mode 100644 index 00000000..d40063b9 --- /dev/null +++ b/server/v1/modules/room_cleaning/roomCleaningRoute.js @@ -0,0 +1,84 @@ +const express = require("express"); +const { + getAvailability, + createBooking, + cancelBooking, + getMyBookings, + submitFeedback, + getRcTomorrow, + postRcTomorrowAssign, + postRcFinalizeStatuses, + getRcCleaners, + postRcCleaner, + putRcCleaner, + deleteRcCleaner, +} = require("./roomCleaningController"); +const { + authenticateJWT, + authenticateMessManagerJWT, +} = require("../../middleware/authenticateJWT"); + +const roomCleaningRouter = express.Router(); + +// GET /api/room-cleaning/availability?date=YYYY-MM-DD[&hostelId=...] +roomCleaningRouter.get("/availability", authenticateJWT, getAvailability); + +// POST /api/room-cleaning/booking +roomCleaningRouter.post("/booking", authenticateJWT, createBooking); + +// POST /api/room-cleaning/booking/cancel +roomCleaningRouter.post("/booking/cancel", authenticateJWT, cancelBooking); + +// GET /api/room-cleaning/booking/my +roomCleaningRouter.get("/booking/my", authenticateJWT, getMyBookings); + +// POST /api/room-cleaning/booking/feedback +roomCleaningRouter.post( + "/booking/feedback", + authenticateJWT, + submitFeedback, +); + +// RC Manager (HABit RC app): tomorrow bookings and assignments +roomCleaningRouter.get( + "/rc/tomorrow", + authenticateMessManagerJWT, + getRcTomorrow, +); +roomCleaningRouter.post( + "/rc/tomorrow/assign", + authenticateMessManagerJWT, + postRcTomorrowAssign, +); + +// RC Manager (HABit RC app): finalize statuses for a date (e.g. Yesterday) +roomCleaningRouter.post( + "/rc/status/finalize", + authenticateMessManagerJWT, + postRcFinalizeStatuses, +); + +// Hostel frontend: manage room cleaners +roomCleaningRouter.get( + "/rc/cleaners", + authenticateMessManagerJWT, + getRcCleaners, +); +roomCleaningRouter.post( + "/rc/cleaners", + authenticateMessManagerJWT, + postRcCleaner, +); +roomCleaningRouter.put( + "/rc/cleaners/:id", + authenticateMessManagerJWT, + putRcCleaner, +); +roomCleaningRouter.delete( + "/rc/cleaners/:id", + authenticateMessManagerJWT, + deleteRcCleaner, +); + +module.exports = roomCleaningRouter; + diff --git a/server/v1/modules/user/userController.js b/server/v1/modules/user/userController.js index 5f8f904f..1e5d7d4c 100644 --- a/server/v1/modules/user/userController.js +++ b/server/v1/modules/user/userController.js @@ -175,33 +175,24 @@ const getUserComplaints = async (req, res) => { const getAllUsers = async (req, res) => { try { - const users = await User.find(); - - // Map over users and populate both hostel and mess names - const updatedUsers = await Promise.all( - users.map(async (user) => { - const hostelId = user.hostel; - const messId = user.curr_subscribed_mess; - let hostelName = null; - let messName = null; - - if (hostelId) { - const hostel = await Hostel.findById(hostelId); - hostelName = hostel ? hostel.hostel_name : null; - } - - if (messId) { - const mess = await Hostel.findById(messId); - messName = mess ? mess.hostel_name : null; - } - - const userObj = user.toObject(); - userObj.hostel_name = hostelName; - userObj.curr_subscribed_mess_name = messName; - - return userObj; - }), - ); + const users = await User.find().lean(); + const hostels = await Hostel.find().lean(); + + const hostelMap = hostels.reduce((acc, curr) => { + acc[curr._id.toString()] = curr.hostel_name; + return acc; + }, {}); + + const updatedUsers = users.map((user) => { + const hostelId = user.hostel ? user.hostel.toString() : null; + const messId = user.curr_subscribed_mess ? user.curr_subscribed_mess.toString() : null; + + return { + ...user, + hostel_name: hostelId ? hostelMap[hostelId] || null : null, + curr_subscribed_mess_name: messId ? hostelMap[messId] || null : null, + }; + }); res.status(200).json(updatedUsers); } catch (err) { @@ -220,6 +211,51 @@ const getUserCount = async (req, res) => { } }; +// Mess-manager (HABit HQ): get basic user profile by ID, restricted to users +// whose curr_subscribed_mess matches the manager's hostel (hostel _id). +const getUserForManager = async (req, res, next) => { + try { + const managerHostel = req.managerHostel; + const { userId } = req.params; + + if (!managerHostel || !managerHostel._id) { + return res + .status(400) + .json({ message: "Manager hostel not found" }); + } + if (!mongoose.Types.ObjectId.isValid(userId)) { + return res.status(400).json({ message: "Invalid userId" }); + } + + const hostelId = managerHostel._id.toString(); + + const user = await User.findById(userId) + .select( + "name rollNumber email roomNumber phoneNumber hostel curr_subscribed_mess", + ) + .populate("hostel", "hostel_name") + .populate("curr_subscribed_mess", "hostel_name"); + + if (!user) { + return res.status(404).json({ message: "User not found" }); + } + + return res.status(200).json({ + _id: user._id, + name: user.name, + rollNumber: user.rollNumber, + email: user.email, + roomNumber: user.roomNumber || "", + phoneNumber: user.phoneNumber || "", + hostelName: user.hostel?.hostel_name || "", + messName: user.curr_subscribed_mess?.hostel_name || "", + }); + } catch (err) { + console.error("getUserForManager error:", err); + return next(new AppError(500, "Failed to fetch user profile")); + } +}; + const getUsersByHostelForMess = async (req, res) => { try { const { hostelId } = req.params; @@ -405,4 +441,5 @@ module.exports = { getUserCount, getUsersByHostelForMess, deleteUserAccount, + getUserForManager, }; diff --git a/server/v1/modules/user/userModel.js b/server/v1/modules/user/userModel.js index eb18ded0..a729d5dd 100644 --- a/server/v1/modules/user/userModel.js +++ b/server/v1/modules/user/userModel.js @@ -143,10 +143,12 @@ const userSchema = new mongoose.Schema({ hostel: { type: mongoose.Schema.Types.ObjectId, ref: "Hostel", + index: true, }, curr_subscribed_mess: { type: mongoose.Schema.Types.ObjectId, ref: "Hostel", + index: true, default: function () { return this.hostel; }, @@ -193,6 +195,7 @@ const userSchema = new mongoose.Schema({ isSMC: { type: Boolean, default: false, + index: true, }, isSetupDone: { type: Boolean, diff --git a/server/v1/modules/user/userRoute.js b/server/v1/modules/user/userRoute.js index f71e952e..31951dce 100644 --- a/server/v1/modules/user/userRoute.js +++ b/server/v1/modules/user/userRoute.js @@ -3,6 +3,7 @@ const { authenticateJWT, authenticateHabJWT, authenticateUserOrAdminJWT, + authenticateMessManagerJWT, } = require("../../middleware/authenticateJWT.js"); const { @@ -11,6 +12,7 @@ const { getAllUsers, getUserCount, deleteUserAccount, + getUserForManager, } = require("./userController.js"); const userRouter = express.Router(); @@ -116,4 +118,11 @@ userRouter.delete("/account", authenticateJWT, deleteUserAccount); */ userRouter.get("/all/hab", authenticateHabJWT, getAllUsers); +// Mess-manager (HABit HQ): fetch user profile by ID +userRouter.get( + "/manager/:userId", + authenticateMessManagerJWT, + getUserForManager, +); + module.exports = userRouter; diff --git a/server/v1/package-lock.json b/server/v1/package-lock.json index 6af07f8b..4cb67550 100644 --- a/server/v1/package-lock.json +++ b/server/v1/package-lock.json @@ -15,6 +15,7 @@ "bcrypt": "^6.0.0", "bcryptjs": "^3.0.2", "cloudinary": "^2.7.0", + "compression": "^1.8.1", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "csv-parser": "^3.2.0", @@ -22,16 +23,20 @@ "enums": "^1.0.3", "express": "^4.21.0", "firebase-admin": "^13.4.0", + "ioredis": "^5.10.0", "jsonwebtoken": "^9.0.2", "mongoose": "^8.17.0", "multer": "^1.4.5-lts.1", + "node-cache": "^5.1.2", "node-schedule": "^2.1.1", "nodemailer": "^7.0.10", "papaparse": "^5.5.3", + "pdfkit": "^0.17.2", "qrcode": "^1.5.4", "server": "file:", "swagger-jsdoc": "^6.2.8", "swagger-ui-express": "^5.0.1", + "ws": "^8.19.0", "xlsx": "^0.18.5" }, "devDependencies": { @@ -568,6 +573,12 @@ "node": ">=12" } }, + "node_modules/@ioredis/commands": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.1.tgz", + "integrity": "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==", + "license": "MIT" + }, "node_modules/@js-sdsl/ordered-map": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", @@ -712,6 +723,15 @@ "hasInstallScript": true, "license": "Apache-2.0" }, + "node_modules/@swc/helpers": { + "version": "0.5.19", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.19.tgz", + "integrity": "sha512-QamiFeIK3txNjgUTNppE6MiG3p7TdninpZu0E0PbqVh1a9FNLT2FRhisaa4NcaX52XVhA5l7Pk58Ft7Sqi/2sA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, "node_modules/@tootallnate/once": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", @@ -1206,6 +1226,15 @@ "node": ">=8" } }, + "node_modules/brotli": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/brotli/-/brotli-1.3.3.tgz", + "integrity": "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.1.2" + } + }, "node_modules/bson": { "version": "6.10.4", "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz", @@ -1355,6 +1384,15 @@ "wrap-ansi": "^6.2.0" } }, + "node_modules/clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==", + "license": "MIT", + "engines": { + "node": ">=0.8" + } + }, "node_modules/cloudinary": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/cloudinary/-/cloudinary-2.7.0.tgz", @@ -1368,6 +1406,15 @@ "node": ">=9" } }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/codepage": { "version": "1.15.0", "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", @@ -1416,6 +1463,45 @@ "node": ">= 6" } }, + "node_modules/compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", + "license": "MIT", + "dependencies": { + "mime-db": ">= 1.43.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compression": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", + "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "compressible": "~2.0.18", + "debug": "2.6.9", + "negotiator": "~0.6.4", + "on-headers": "~1.1.0", + "safe-buffer": "5.2.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/compression/node_modules/negotiator": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz", + "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -1559,6 +1645,12 @@ "node": ">=12.0.0" } }, + "node_modules/crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==", + "license": "MIT" + }, "node_modules/csv-parser": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/csv-parser/-/csv-parser-3.2.0.tgz", @@ -1638,6 +1730,15 @@ "node": ">=0.4.0" } }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.10" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -1657,6 +1758,12 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/dfa": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz", + "integrity": "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==", + "license": "MIT" + }, "node_modules/dijkstrajs": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", @@ -1917,8 +2024,7 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "license": "MIT", - "optional": true + "license": "MIT" }, "node_modules/fast-xml-parser": { "version": "4.5.3", @@ -2053,6 +2159,23 @@ } } }, + "node_modules/fontkit": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/fontkit/-/fontkit-2.0.4.tgz", + "integrity": "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g==", + "license": "MIT", + "dependencies": { + "@swc/helpers": "^0.5.12", + "brotli": "^1.3.2", + "clone": "^2.1.2", + "dfa": "^1.2.0", + "fast-deep-equal": "^3.1.3", + "restructure": "^3.0.0", + "tiny-inflate": "^1.0.3", + "unicode-properties": "^1.4.0", + "unicode-trie": "^2.0.0" + } + }, "node_modules/form-data": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", @@ -2583,6 +2706,53 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ioredis": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.10.0.tgz", + "integrity": "sha512-HVBe9OFuqs+Z6n64q09PQvP1/R4Bm+30PAyyD4wIEqssh3v9L21QjCVk4kRLucMBcDokJTcLjsGeVRlq/nH6DA==", + "license": "MIT", + "dependencies": { + "@ioredis/commands": "1.5.1", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "node_modules/ioredis/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/ioredis/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", @@ -2722,6 +2892,13 @@ "url": "https://github.com/sponsors/panva" } }, + "node_modules/jpeg-exif": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/jpeg-exif/-/jpeg-exif-1.1.4.tgz", + "integrity": "sha512-a+bKEcCjtuW5WTdgeXFzswSrdqi0jk4XlEtZlx5A94wCoBpFjfFTbo/Tra5SpNCl/YFZPvcV1dJc+TAYeg6ROQ==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT" + }, "node_modules/js-yaml": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", @@ -2846,6 +3023,25 @@ "resolved": "https://registry.npmjs.org/limiter/-/limiter-1.1.5.tgz", "integrity": "sha512-FWWMIEOxz3GwUI4Ts/IvgVy6LPvoMPgjMdQ185nN6psJyBJ4yOpzqm695/h5umdLJg2vW3GR5iG11MAkR2AzJA==" }, + "node_modules/linebreak": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", + "integrity": "sha512-MHp03UImeVhB7XZtjd0E4n6+3xr5Dq/9xI/5FptGk5FrbDR3zagPa2DS6U8ks/3HjbKWG9Q1M2ufOzxV2qLYSQ==", + "license": "MIT", + "dependencies": { + "base64-js": "0.0.8", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/linebreak/node_modules/base64-js": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-0.0.8.tgz", + "integrity": "sha512-3XSA2cR/h/73EzlXXdU6YNycmYI7+kicTxks4eJg2g39biHR84slg2+des+p7iHYhbRg/udIS4TD53WabcOUkw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/locate-path": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", @@ -2877,6 +3073,12 @@ "integrity": "sha512-H5ZhCF25riFd9uB5UCkVKo61m3S/xZk1x4wA6yp/L3RFP6Z/eHH1ymQcGLo7J3GMPfm0V/7m1tryHuGVxpqEBQ==", "license": "MIT" }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", + "license": "MIT" + }, "node_modules/lodash.get": { "version": "4.4.2", "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", @@ -2890,6 +3092,12 @@ "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", "license": "MIT" }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", + "license": "MIT" + }, "node_modules/lodash.isboolean": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", @@ -3376,6 +3584,18 @@ "node": "^18 || ^20 || >= 21" } }, + "node_modules/node-cache": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/node-cache/-/node-cache-5.1.2.tgz", + "integrity": "sha512-t1QzWwnk4sjLWaQAS8CHgOJ+RAfmHpxFWmc36IWTiWHQfs0w5JDMBS1b1ZxQteo0vVVuWJvIUKHDkkeK7vIGCg==", + "license": "MIT", + "dependencies": { + "clone": "2.x" + }, + "engines": { + "node": ">= 8.0.0" + } + }, "node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", @@ -3546,6 +3766,15 @@ "node": ">= 0.8" } }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -3616,6 +3845,12 @@ "node": ">=6" } }, + "node_modules/pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==", + "license": "MIT" + }, "node_modules/papaparse": { "version": "5.5.3", "resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.5.3.tgz", @@ -3655,6 +3890,19 @@ "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", "license": "MIT" }, + "node_modules/pdfkit": { + "version": "0.17.2", + "resolved": "https://registry.npmjs.org/pdfkit/-/pdfkit-0.17.2.tgz", + "integrity": "sha512-UnwF5fXy08f0dnp4jchFYAROKMNTaPqb/xgR8GtCzIcqoTnbOqtp3bwKvO4688oHI6vzEEs8Q6vqqEnC5IUELw==", + "license": "MIT", + "dependencies": { + "crypto-js": "^4.2.0", + "fontkit": "^2.0.4", + "jpeg-exif": "^1.1.4", + "linebreak": "^1.1.0", + "png-js": "^1.0.0" + } + }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", @@ -3668,6 +3916,11 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/png-js": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/png-js/-/png-js-1.0.0.tgz", + "integrity": "sha512-k+YsbhpA9e+EFfKjTCH3VW6aoKlyNYI6NYdTfDL4CIvFnvsuO84ttonmZE7rc+v23SLTH8XX+5w/Ak9v0xGY4g==" + }, "node_modules/pngjs": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", @@ -3880,6 +4133,27 @@ "node": ">=8.10.0" } }, + "node_modules/redis-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "license": "MIT", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -3895,6 +4169,12 @@ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", "license": "ISC" }, + "node_modules/restructure": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/restructure/-/restructure-3.0.2.tgz", + "integrity": "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw==", + "license": "MIT" + }, "node_modules/retry": { "version": "0.13.1", "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", @@ -4158,6 +4438,12 @@ "node": ">=0.8" } }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", + "license": "MIT" + }, "node_modules/statuses": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", @@ -4415,6 +4701,12 @@ "uuid": "dist/bin/uuid" } }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "license": "MIT" + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -4491,6 +4783,26 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "license": "MIT" }, + "node_modules/unicode-properties": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/unicode-properties/-/unicode-properties-1.4.1.tgz", + "integrity": "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.0", + "unicode-trie": "^2.0.0" + } + }, + "node_modules/unicode-trie": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/unicode-trie/-/unicode-trie-2.0.0.tgz", + "integrity": "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ==", + "license": "MIT", + "dependencies": { + "pako": "^0.2.5", + "tiny-inflate": "^1.0.0" + } + }, "node_modules/unpipe": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", @@ -4625,6 +4937,27 @@ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", "license": "ISC" }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/xlsx": { "version": "0.18.5", "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", diff --git a/server/v1/package.json b/server/v1/package.json index d4289e66..dd4c486d 100644 --- a/server/v1/package.json +++ b/server/v1/package.json @@ -18,6 +18,7 @@ "bcrypt": "^6.0.0", "bcryptjs": "^3.0.2", "cloudinary": "^2.7.0", + "compression": "^1.8.1", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "csv-parser": "^3.2.0", @@ -25,16 +26,20 @@ "enums": "^1.0.3", "express": "^4.21.0", "firebase-admin": "^13.4.0", + "ioredis": "^5.10.0", "jsonwebtoken": "^9.0.2", "mongoose": "^8.17.0", "multer": "^1.4.5-lts.1", + "node-cache": "^5.1.2", "node-schedule": "^2.1.1", "nodemailer": "^7.0.10", "papaparse": "^5.5.3", + "pdfkit": "^0.17.2", "qrcode": "^1.5.4", "server": "file:", "swagger-jsdoc": "^6.2.8", "swagger-ui-express": "^5.0.1", + "ws": "^8.19.0", "xlsx": "^0.18.5" }, "devDependencies": { diff --git a/server/v1/utils/delegatedGraphAuth.js b/server/v1/utils/delegatedGraphAuth.js index 582e30ac..b5d4f84f 100644 --- a/server/v1/utils/delegatedGraphAuth.js +++ b/server/v1/utils/delegatedGraphAuth.js @@ -8,12 +8,55 @@ const tokenFilePath = process.env.GRAPH_DELEGATED_TOKEN_PATH || path.resolve(__dirname, "..", ".secrets", "graph_delegated_token.json"); +const REDIS_KEY_TOKEN = "hab:graph:delegated_token"; +const REDIS_KEY_LOCK = "hab:graph:delegated_refresh_lock"; +const LOCK_TTL_SEC = 25; +const VALIDITY_BUFFER_MS = 60_000; // consider valid until expires_at - 1 min + let inMemory = { access_token: null, refresh_token: null, expires_at: 0, // epoch ms }; +let redisClient = null; +let redisDisabled = false; + +function getRedisClient() { + if (redisDisabled) return null; + if (redisClient) return redisClient; + const url = process.env.REDIS_URL; + if (!url) return null; + try { + const Redis = require("ioredis"); + redisClient = new Redis(url, { + maxRetriesPerRequest: 0, + enableOfflineQueue: false, + retryStrategy: () => null, + }); + redisClient.on("error", (err) => { + if (redisDisabled) return; + redisDisabled = true; + if (redisClient) { + try { + redisClient.disconnect(); + } catch (_) {} + redisClient = null; + console.warn("[Graph Delegated] Redis unavailable:", err?.message || err?.code, "- using file+memory for token."); + } + }); + redisClient.once("ready", () => { + if (redisDisabled || !redisClient || redisClient.status !== "ready") return; + loadFromDisk().then(() => { + if (hasValidToken()) saveToRedis(); + }); + }); + return redisClient; + } catch (e) { + return null; + } +} + function tokenEndpoint() { const tenant = onedrive.authTenant || onedrive.tenantId || "common"; return `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`; @@ -23,22 +66,18 @@ async function ensureDir() { await fsp.mkdir(path.dirname(tokenFilePath), { recursive: true }); } +function isTokenValid(obj) { + if (!obj || !obj.access_token || !obj.expires_at) return false; + const now = Date.now(); + return now < Number(obj.expires_at) - VALIDITY_BUFFER_MS; +} + async function loadFromDisk() { try { const raw = await fsp.readFile(tokenFilePath, "utf8"); const json = JSON.parse(raw); if (json.access_token && json.refresh_token && json.expires_at) { inMemory = json; - console.log( - `[Graph Delegated] Loaded token from disk. Expires at: ${new Date( - inMemory.expires_at - ).toISOString()}` - ); - console.log( - `[Graph Delegated] Access token (first 24 chars): ${String( - inMemory.access_token - ).slice(0, 24)}...` - ); return true; } return false; @@ -57,23 +96,66 @@ async function saveToDisk() { ); } +/** Write current inMemory token to Redis so other instances see it. */ +async function saveToRedis() { + const redis = getRedisClient(); + if (!redis || redis.status !== "ready") return; + try { + await redis.set( + REDIS_KEY_TOKEN, + JSON.stringify({ + access_token: inMemory.access_token, + refresh_token: inMemory.refresh_token, + expires_at: inMemory.expires_at, + }) + ); + } catch (e) { + if (!redisDisabled) { + redisDisabled = true; + try { + redis.disconnect(); + } catch (_) {} + redisClient = null; + console.warn("[Graph Delegated] Redis write failed:", e?.message, "- using file+memory for token."); + } + } +} + +/** Try to get token from Redis. Returns token object or null. */ +async function loadFromRedis() { + const redis = getRedisClient(); + if (!redis || redis.status !== "ready") return null; + try { + const raw = await redis.get(REDIS_KEY_TOKEN); + if (!raw) return null; + return JSON.parse(raw); + } catch (e) { + return null; + } +} + +/** Try to acquire refresh lock. Returns true if we got it. */ +async function acquireRefreshLock() { + const redis = getRedisClient(); + if (!redis) return true; // no Redis => single instance, no lock needed + if (redis.status !== "ready") return false; + try { + const ok = await redis.set(REDIS_KEY_LOCK, "1", "EX", LOCK_TTL_SEC, "NX"); + return ok === "OK"; + } catch (e) { + return false; + } +} + function hasValidToken() { const now = Date.now(); return ( - Boolean(inMemory.access_token) && now < Number(inMemory.expires_at) - 60_000 + Boolean(inMemory.access_token) && + now < Number(inMemory.expires_at) - VALIDITY_BUFFER_MS ); } -async function refreshIfNeeded() { - if (hasValidToken()) return inMemory.access_token; - - // Try to load from disk if memory is empty or expired - if (!hasValidToken()) { - await loadFromDisk(); - if (hasValidToken()) return inMemory.access_token; - } - - // Need refresh +async function doRefresh() { if (!inMemory.refresh_token) { throw new Error( "No refresh_token available. Start delegated OAuth and save tokens." @@ -84,12 +166,10 @@ async function refreshIfNeeded() { const params = new URLSearchParams(); params.append("client_id", onedrive.clientId); if (onedrive.clientSecret) { - // If confidential client, include secret params.append("client_secret", onedrive.clientSecret); } params.append("grant_type", "refresh_token"); params.append("refresh_token", inMemory.refresh_token); - // Request the configured scopes const scopes = Array.isArray(onedrive.graphUserScopes) && onedrive.graphUserScopes.length ? onedrive.graphUserScopes.join(" ") @@ -103,7 +183,6 @@ async function refreshIfNeeded() { }); const data = resp.data || {}; if (!data.access_token) { - // Surface better diagnostics const hint = `Grant delegated consent for scopes [${scopes}] to app ${onedrive.clientId} and re-authenticate via /api/_debug/graph/start`; throw new Error( `Failed to refresh delegated token: ${data.error || "unknown_error"} ${ @@ -113,7 +192,7 @@ async function refreshIfNeeded() { } const expiresInSec = Number(data.expires_in || 3600); inMemory.access_token = data.access_token; - inMemory.refresh_token = data.refresh_token || inMemory.refresh_token; // rotate if provided + inMemory.refresh_token = data.refresh_token || inMemory.refresh_token; inMemory.expires_at = Date.now() + expiresInSec * 1000; console.log( @@ -121,28 +200,84 @@ async function refreshIfNeeded() { inMemory.expires_at ).toISOString()}` ); - console.log( - `[Graph Delegated] Access token (first 24 chars): ${String( - inMemory.access_token - ).slice(0, 24)}...` - ); await saveToDisk(); + await saveToRedis(); return inMemory.access_token; } +async function refreshIfNeeded() { + const redis = getRedisClient(); + + if (redis) { + // Cluster path: use Redis as source of truth + let tokenObj = await loadFromRedis(); + if (isTokenValid(tokenObj)) { + inMemory = tokenObj; + return tokenObj.access_token; + } + // Redis miss or expired: load from file so we have refresh_token, then re-check Redis + await loadFromDisk(); + tokenObj = await loadFromRedis(); + if (isTokenValid(tokenObj)) { + inMemory = tokenObj; + return tokenObj.access_token; + } + if (hasValidToken()) { + await saveToRedis(); + return inMemory.access_token; + } + // Need refresh: only one process should do it + const gotLock = await acquireRefreshLock(); + if (gotLock) { + if (!inMemory.refresh_token) await loadFromDisk(); + if (hasValidToken()) return inMemory.access_token; + return doRefresh(); + } + // Another process is refreshing: wait and re-read from Redis + for (let i = 0; i < 8; i++) { + await new Promise((r) => setTimeout(r, 800)); + tokenObj = await loadFromRedis(); + if (isTokenValid(tokenObj)) { + inMemory = tokenObj; + return tokenObj.access_token; + } + } + // Fallback: try refresh without lock (last resort) + if (!inMemory.refresh_token) await loadFromDisk(); + return doRefresh(); + } + + // No Redis: original single-instance behavior + if (hasValidToken()) return inMemory.access_token; + if (!hasValidToken()) { + await loadFromDisk(); + if (hasValidToken()) return inMemory.access_token; + } + return doRefresh(); +} + async function getDelegatedAccessToken() { return refreshIfNeeded(); } -// Helper for manual seeding via scripts if needed async function setDelegatedTokens({ access_token, refresh_token, expires_at }) { if (!access_token || !refresh_token || !expires_at) { throw new Error( "setDelegatedTokens requires access_token, refresh_token, expires_at (epoch ms)." ); } - inMemory = { access_token, refresh_token, expires_at: Number(expires_at) }; + inMemory = { + access_token, + refresh_token, + expires_at: Number(expires_at), + }; await saveToDisk(); + await saveToRedis(); +} + +/** Call at worker startup so Redis client connects and backfills from disk early. */ +function initDelegatedGraphRedis() { + getRedisClient(); } -module.exports = { getDelegatedAccessToken, setDelegatedTokens, tokenFilePath }; +module.exports = { getDelegatedAccessToken, setDelegatedTokens, tokenFilePath, initDelegatedGraphRedis }; diff --git a/server/v1/utils/scanBroadcast.js b/server/v1/utils/scanBroadcast.js new file mode 100644 index 00000000..d488f4a2 --- /dev/null +++ b/server/v1/utils/scanBroadcast.js @@ -0,0 +1,137 @@ +/** + * Cross-instance broadcast for scan events (cluster-safe). + * + * When REDIS_URL is set: publishes to Redis; every api-v1 instance subscribes + * and runs the local WebSocket broadcast. The instance that has the manager's + * connection will deliver the message. + * + * When REDIS_URL is not set: calls the local broadcast only (single-instance behavior). + */ + +const REDIS_CHANNEL_MESS = "hab:mess:scan"; +const REDIS_CHANNEL_GALA = "hab:gala:scan"; + +let redisPublisher = null; +let redisSubscriber = null; +let subscriberReady = false; +let redisDisabled = false; + +function getLocalBroadcasts() { + const { broadcastMessScanToManagers } = require("../modules/mess/messManagerWs.js"); + const { broadcastGalaScanToManagers } = require("../modules/gala/galaManagerWs.js"); + return { broadcastMessScanToManagers, broadcastGalaScanToManagers }; +} + +/** + * Publish mess scan event. With Redis: all instances receive and broadcast locally. + * Without Redis: only this process broadcasts. + */ +function publishMessScan(payload) { + const { broadcastMessScanToManagers } = getLocalBroadcasts(); + if (redisPublisher && redisPublisher.status === "ready") { + redisPublisher.publish(REDIS_CHANNEL_MESS, JSON.stringify(payload)).catch((err) => { + console.error("[scanBroadcast] Redis publish mess failed:", err); + broadcastMessScanToManagers(payload); + }); + } else { + broadcastMessScanToManagers(payload); + } +} + +/** + * Publish gala scan event. With Redis: all instances receive and broadcast locally. + * Without Redis: only this process broadcasts. + */ +function publishGalaScan(payload) { + const { broadcastGalaScanToManagers } = getLocalBroadcasts(); + if (redisPublisher && redisPublisher.status === "ready") { + redisPublisher.publish(REDIS_CHANNEL_GALA, JSON.stringify(payload)).catch((err) => { + console.error("[scanBroadcast] Redis publish gala failed:", err); + broadcastGalaScanToManagers(payload); + }); + } else { + broadcastGalaScanToManagers(payload); + } +} + +function disableRedis(reason) { + redisDisabled = true; + if (redisPublisher) { + try { + redisPublisher.disconnect(); + } catch (_) {} + redisPublisher = null; + } + if (redisSubscriber) { + try { + redisSubscriber.disconnect(); + } catch (_) {} + redisSubscriber = null; + } + console.warn("[scanBroadcast] Redis unavailable:", reason, "- using direct broadcast (single-instance)."); +} + +/** + * Initialize Redis client(s) and subscribe to scan channels. + * Call once after WebSocket servers are initialized (e.g. in index.js). + * No-op if REDIS_URL is not set. If Redis connection fails, falls back to direct broadcast without spamming errors. + */ +function initScanBroadcast() { + const redisUrl = process.env.REDIS_URL; + if (!redisUrl) { + return; + } + + try { + const Redis = require("ioredis"); + const opts = { maxRetriesPerRequest: 0, enableOfflineQueue: false, retryStrategy: () => null }; + + redisPublisher = new Redis(redisUrl, opts); + redisSubscriber = new Redis(redisUrl, opts); + + const onError = (err) => { + if (redisDisabled) return; + disableRedis(err?.message || err?.code || "connection failed"); + }; + + redisPublisher.on("error", onError); + redisSubscriber.on("error", onError); + + redisSubscriber.on("message", (channel, message) => { + const { broadcastMessScanToManagers, broadcastGalaScanToManagers } = getLocalBroadcasts(); + try { + const payload = JSON.parse(message); + if (channel === REDIS_CHANNEL_MESS) { + broadcastMessScanToManagers(payload); + } else if (channel === REDIS_CHANNEL_GALA) { + broadcastGalaScanToManagers(payload); + } + } catch (e) { + console.error("[scanBroadcast] Invalid message:", e); + } + }); + + redisSubscriber.once("ready", () => { + if (redisDisabled || !redisSubscriber) return; + redisSubscriber.subscribe(REDIS_CHANNEL_MESS, REDIS_CHANNEL_GALA, (err, count) => { + if (redisDisabled) return; + if (err) { + disableRedis(err.message || "subscribe failed"); + return; + } + subscriberReady = true; + console.log("[scanBroadcast] Subscribed to", REDIS_CHANNEL_MESS, REDIS_CHANNEL_GALA, "count:", count); + }); + }); + } catch (e) { + console.error("[scanBroadcast] Redis init failed (is ioredis installed?):", e); + redisPublisher = null; + redisSubscriber = null; + } +} + +module.exports = { + publishMessScan, + publishGalaScan, + initScanBroadcast, +}; diff --git a/server/v2/index.js b/server/v2/index.js index 619f3ce8..4b0ac49c 100644 --- a/server/v2/index.js +++ b/server/v2/index.js @@ -2,6 +2,8 @@ //import authRoutes from "./modules/auth/auth.routes.js"; require("dotenv").config({ path: "../.env" }); +const { installProcessHandlers } = require("../processHandlers.js"); +installProcessHandlers(); console.log("MONGODB_URI from env:", process.env.MONGODB_URI); const authRoutes = require("./modules/auth/auth.routes.js"); const express = require("express"); @@ -285,6 +287,12 @@ app.get("/api/_debug/graph/callback", async (req, res) => { } }); +// Global error handler (must be after all routes). Catches errors passed to next(err). +app.use((err, req, res, next) => { + console.error("[Express error]", err); + res.status(500).json({ message: "Internal server error" }); +}); + app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); diff --git a/server/v2/modules/auth/auth.controller.js b/server/v2/modules/auth/auth.controller.js index 044e07c7..6dabdc4e 100644 --- a/server/v2/modules/auth/auth.controller.js +++ b/server/v2/modules/auth/auth.controller.js @@ -10,9 +10,6 @@ const { findUserWithAppleIdentifier, } = require("../user/userModel.js"); const UserAllocHostel = require("../hostel/hostelAllocModel.js"); -const { - sendNotificationToUser, -} = require("../notification/notificationController.js"); require("dotenv").config(); const clientId = process.env.CLIENT_ID; @@ -73,7 +70,6 @@ const mobileRedirectHandler = async (req, res, next) => { ); let existingUser = await findUserWithEmail(userFromToken.data.mail); - let isFirstLogin = false; if (!existingUser) { const user = new User({ @@ -86,7 +82,6 @@ const mobileRedirectHandler = async (req, res, next) => { hasMicrosoftLinked: true, // Microsoft login = student account (surname exists) }); existingUser = await user.save(); - isFirstLogin = true; } else { // Microsoft login always means student account (surname exists), so always set hasMicrosoftLinked existingUser.email = userFromToken.data.mail; // Update email to Microsoft email @@ -100,18 +95,6 @@ const mobileRedirectHandler = async (req, res, next) => { const token = existingUser.generateJWT(); - if (isFirstLogin) { - try { - await sendNotificationToUser( - existingUser._id, - "Welcome to HAB App", - "Thanks for signing in! You will receive updates here." - ); - } catch (e) { - console.warn("Failed to send welcome notification", e); - } - } - return res.redirect( `iitghab://success?token=${token}&user=${encodeURIComponent( existingUser.email diff --git a/smc-frontend/src/components/GalaDinnerContent.jsx b/smc-frontend/src/components/GalaDinnerContent.jsx new file mode 100644 index 00000000..d4579844 --- /dev/null +++ b/smc-frontend/src/components/GalaDinnerContent.jsx @@ -0,0 +1,322 @@ +import React, { useState, useEffect, useCallback } from "react"; +import apiClient from "../apiClient"; +import { Plus, Edit3, Trash2, Download } from "lucide-react"; +import Card from "./ui/Card"; +import Button from "./ui/Button"; + +const CATEGORIES = ["Starters", "Main Course", "Desserts"]; +const ITEM_TYPES = ["Dish", "Breads and Rice", "Others"]; + +function formatDate(dateStr) { + if (!dateStr) return ""; + const d = new Date(dateStr); + return d.toLocaleDateString("en-IN", { + day: "numeric", + month: "short", + year: "numeric", + }); +} + +function formatTimeDisplay(str) { + if (!str || typeof str !== "string") return null; + const match = str.trim().match(/^(\d{1,2}):(\d{2})$/); + if (!match) return str; + const h = parseInt(match[1], 10); + const m = match[2]; + const h12 = h % 12 || 12; + const ampm = h < 12 ? "AM" : "PM"; + return `${h12}:${m} ${ampm}`; +} + +export default function GalaDinnerContent() { + const [data, setData] = useState({ + galaDinner: null, + menus: [], + }); + const [loading, setLoading] = useState(true); + const [addingTo, setAddingTo] = useState(null); + const [newItemName, setNewItemName] = useState(""); + const [newItemType, setNewItemType] = useState("Dish"); + const [editingId, setEditingId] = useState(null); + const [editingMenuId, setEditingMenuId] = useState(null); + const [editName, setEditName] = useState(""); + const [submitting, setSubmitting] = useState(false); + + const refreshMenuItems = useCallback(async (galaDinnerMenuId) => { + try { + const response = await apiClient.get( + `/gala/menu/${galaDinnerMenuId}/items` + ); + const items = response.data || []; + setData((prev) => ({ + ...prev, + menus: prev.menus.map((m) => + m._id === galaDinnerMenuId ? { ...m, items } : m + ), + })); + } catch (err) { + console.error("Failed to refresh menu items:", err); + } + }, []); + + const fetchGala = useCallback(async () => { + try { + setLoading(true); + const response = await apiClient.get("/gala/upcoming-with-menus"); + setData({ + galaDinner: response.data.galaDinner || null, + menus: response.data.menus || [], + }); + } catch (err) { + console.error("Failed to fetch Gala Dinner:", err); + setData({ galaDinner: null, menus: [] }); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + fetchGala(); + }, [fetchGala]); + + const handleAddItem = async (galaMenuId, category) => { + if (!newItemName.trim()) return; + const typeToSend = + category === "Main Course" ? newItemType : "Dish"; + try { + setSubmitting(true); + await apiClient.post("/gala/menu/item", { + galaMenuId, + name: newItemName.trim(), + type: typeToSend, + }); + setAddingTo(null); + setNewItemName(""); + setNewItemType("Dish"); + await refreshMenuItems(galaMenuId); + } catch (err) { + alert(err.response?.data?.message || "Failed to add item"); + } finally { + setSubmitting(false); + } + }; + + const handleUpdateItem = async () => { + if (!editingId || !editName.trim()) return; + const menuIdToRefresh = editingMenuId; + try { + setSubmitting(true); + await apiClient.patch("/gala/menu/item", { + _Id: editingId, + name: editName.trim(), + }); + setEditingId(null); + setEditingMenuId(null); + setEditName(""); + if (menuIdToRefresh) await refreshMenuItems(menuIdToRefresh); + } catch (err) { + alert(err.response?.data?.message || "Failed to update item"); + } finally { + setSubmitting(false); + } + }; + + const handleDeleteItem = async (itemId, galaMenuId) => { + if (!confirm("Delete this item?")) return; + try { + setSubmitting(true); + await apiClient.delete("/gala/menu/item", { data: { _Id: itemId } }); + if (galaMenuId) await refreshMenuItems(galaMenuId); + } catch (err) { + alert(err.response?.data?.message || "Failed to delete item"); + } finally { + setSubmitting(false); + } + }; + + if (loading) { + return ( +
+
+ Loading Gala Dinner... +
+ ); + } + + if (!data.galaDinner || !data.menus.length) { + return ( + +

Gala Dinner

+

No upcoming Gala Dinner scheduled.

+
+ ); + } + + return ( +
+ +

Gala Dinner

+

+ Date: {formatDate(data.galaDinner.date)} +

+ {(data.galaDinner.startersServingStartTime || data.galaDinner.dinnerServingStartTime) && ( +

+ Starters at {formatTimeDisplay(data.galaDinner.startersServingStartTime) || "—"} + {data.galaDinner.dinnerServingStartTime && ( + <> · Dinner at {formatTimeDisplay(data.galaDinner.dinnerServingStartTime)} + )} +

+ )} +
+ +
+ {data.menus.map((menu) => ( + +

+ {menu.category} +

+ + {menu.qrCode?.qr_base64 && ( +
+ {`QR + + + +
+ )} + +
    + {(menu.items || []).map((item) => ( +
  • + {editingId === item._id ? ( +
    + setEditName(e.target.value)} + className="flex-1 px-2 py-1 text-sm border border-gray-300 rounded" + autoFocus + /> + + +
    + ) : ( + <> + {item.name} + {item.type} +
    + + +
    + + )} +
  • + ))} +
+ + {addingTo === menu._id ? ( +
+ setNewItemName(e.target.value)} + className="px-2 py-1.5 text-sm border border-gray-300 rounded" + /> + {menu.category === "Main Course" && ( + + )} +
+ + +
+
+ ) : ( + + )} +
+ ))} +
+
+ ); +} diff --git a/smc-frontend/src/components/NotificationSender.jsx b/smc-frontend/src/components/NotificationSender.jsx index 2c852b87..f0c65cba 100644 --- a/smc-frontend/src/components/NotificationSender.jsx +++ b/smc-frontend/src/components/NotificationSender.jsx @@ -1,6 +1,5 @@ import React, { useState } from "react"; -import { API_BASE_URL } from "../apis"; -import axios from "axios"; +import apiClient from "../apiClient"; import Button from "./ui/Button"; import { useAuth } from "../context/AuthProvider"; @@ -29,8 +28,8 @@ const NotificationSender = () => { setSuccess(false); // Get hostel name from user's hostel - const response = await axios.get( - `${API_BASE_URL}/hostel/all/smc/${user.hostel}`, + const response = await apiClient.get( + `/hostel/all/smc/${user.hostel}`, ); const hostelName = response.data.hostel?.hostel_name?.replaceAll(" ", "_") || ""; @@ -40,7 +39,7 @@ const NotificationSender = () => { ? `Boarders_${hostelName}` : `Subscribers_${hostelName}`; - await axios.post(`${API_BASE_URL}/notification/send`, { + await apiClient.post("/notification/send", { title, body, topic, diff --git a/smc-frontend/src/pages/Dashboard.jsx b/smc-frontend/src/pages/Dashboard.jsx index ded18567..a752eabc 100644 --- a/smc-frontend/src/pages/Dashboard.jsx +++ b/smc-frontend/src/pages/Dashboard.jsx @@ -1,11 +1,12 @@ import { useAuth } from "../context/AuthProvider"; import React, { useState, useEffect, useCallback } from "react"; import Menu_content from "../components/Menu_content.jsx"; -import axios from "axios"; +import apiClient from "../apiClient"; import { API_BASE_URL } from "../apis"; import CreateMenuFallback from "../components/CreateMenuFallback.jsx"; -import { Menu, Download, LogOut, Bell } from "lucide-react"; +import { Menu, Download, LogOut, Bell, Gift } from "lucide-react"; import NotificationSender from "../components/NotificationSender"; +import GalaDinnerContent from "../components/GalaDinnerContent"; import Button from "../components/ui/Button"; import Card from "../components/ui/Card"; import Tabs from "../components/ui/Tabs"; @@ -52,8 +53,8 @@ export const Dashboard = () => { const getUserHostel = async () => { try { if (!user?.hostel) return null; - const response = await axios.get( - `${API_BASE_URL}/hostel/all/smc/${user.hostel}`, + const response = await apiClient.get( + `/hostel/all/smc/${user.hostel}`, ); return response.data.hostel; } catch (err) { @@ -82,8 +83,8 @@ export const Dashboard = () => { try { setIsLoading(true); - const response = await axios.post( - `${API_BASE_URL}/mess/menu/smc/${messId}`, + const response = await apiClient.post( + `/mess/menu/smc/${messId}`, { day: days[activeTab] }, ); @@ -181,7 +182,7 @@ export const Dashboard = () => { } try { - const response = await axios.get(`${API_BASE_URL}/mess/menu/download`, { + const response = await apiClient.get("/mess/menu/download", { params: { day: days[activeTab], messId: messId }, responseType: "blob", }); @@ -262,6 +263,19 @@ export const Dashboard = () => { {sidebarOpen && Menu Management} +