From c8c7e6dca29da87c5760cede00184153772f24d7 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 19:34:53 +0700 Subject: [PATCH 1/9] Feature/user profile (#30) * feat(UserProfile): build screen UserProfile # Conflicts: # src/lib/features/main/view/screens/main_screen.dart * feat: switch dark/light theme * fix: black color theme * fix: black theme in statistics screen * feat: add dark theme to auth screen * feat: apply dark theme for bottom navigation bar --- src/lib/core/theme/app_theme.dart | 87 ++++++++ src/lib/core/theme/auth_layout_template.dart | 155 ++++++++++---- src/lib/core/theme/custom_text_field.dart | 41 ++-- src/lib/core/theme/theme_provider.dart | 57 +++++ src/lib/core/widgets/custom_input_field.dart | 8 +- .../features/auth/otp_verification_view.dart | 65 +++--- .../view/forgot_password_view.dart | 66 ++++-- .../auth/presentation/view/login_view.dart | 70 ++++++- .../presentation/view/new_password_view.dart | 52 ++++- .../view/otp_verification_view.dart | 138 ++++++++---- .../auth/presentation/view/register_view.dart | 33 ++- .../main/view/screens/main_screen.dart | 44 +++- src/lib/features/note/view/focus_screen.dart | 165 ++++++++++++--- src/lib/features/note/view/focus_widget.dart | 196 ++++++++++++++---- .../view/screens/statistics_screen.dart | 149 ++++++++----- .../view/widgets/statistics_widgets.dart | 147 ++++++++++--- .../view/screens/create_task_screen.dart | 62 ++++-- .../tasks/view/screens/home_screen.dart | 67 +++++- .../view/screens/task_detail_screen.dart | 58 ++++-- .../tasks/view/widgets/task_widgets.dart | 48 +++-- .../user/model/user_profile_model.dart | 77 +++++++ .../features/user/service/user_service.dart | 19 ++ .../features/user/view/user_profile_view.dart | 156 ++++++++++++++ .../user/view/widgets/logout_button.dart | 46 ++++ .../user/view/widgets/profile_header.dart | 114 ++++++++++ .../user/view/widgets/settings_list_tile.dart | 58 ++++++ .../user/view/widgets/settings_section.dart | 39 ++++ .../features/user/view/widgets/stat_card.dart | 51 +++++ .../viewmodel/user_profile_viewmodel.dart | 110 ++++++++++ src/lib/main.dart | 34 +-- ...20260409084009_create_user_profile_rpc.sql | 58 ++++++ 31 files changed, 2082 insertions(+), 388 deletions(-) create mode 100644 src/lib/core/theme/app_theme.dart create mode 100644 src/lib/core/theme/theme_provider.dart create mode 100644 src/lib/features/user/model/user_profile_model.dart create mode 100644 src/lib/features/user/service/user_service.dart create mode 100644 src/lib/features/user/view/user_profile_view.dart create mode 100644 src/lib/features/user/view/widgets/logout_button.dart create mode 100644 src/lib/features/user/view/widgets/profile_header.dart create mode 100644 src/lib/features/user/view/widgets/settings_list_tile.dart create mode 100644 src/lib/features/user/view/widgets/settings_section.dart create mode 100644 src/lib/features/user/view/widgets/stat_card.dart create mode 100644 src/lib/features/user/viewmodel/user_profile_viewmodel.dart create mode 100644 supabase/migrations/20260409084009_create_user_profile_rpc.sql diff --git a/src/lib/core/theme/app_theme.dart b/src/lib/core/theme/app_theme.dart new file mode 100644 index 0000000..1da88ec --- /dev/null +++ b/src/lib/core/theme/app_theme.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; + +class AppTheme { + // ========================================================= + // ☀️ LIGHT THEME DICTIONARY + // Inherited from the legacy AppColors class + // ========================================================= + static final ThemeData lightTheme = ThemeData( + brightness: Brightness.light, + scaffoldBackgroundColor: const Color(0xFFF4F6F9), // Legacy: AppColors.background + + colorScheme: const ColorScheme.light( + // Brand Colors + primary: Color(0xFF5A8DF3), // Legacy: AppColors.primary + secondary: Color(0xFF4A90E2), // Legacy: AppColors.primaryBlue + + // Background & Surface Colors + // Note: 'background' is deprecated, scaffoldBackgroundColor handles the main background. + surface: Colors.white, // Legacy: AppColors.taskCardBg / white + surfaceContainerHighest: Color(0xFFE0F7FA), // Legacy: AppColors.backgroundBlue (Tinted background) + + // Text Colors + onSurface: Color(0xFF2D3440), // Legacy: AppColors.textDark + onSurfaceVariant: Color(0xFF757575), // Legacy: AppColors.grayText / textSecondary + + // Border & Status Colors + outline: Color(0xFFE2E8F0), // Legacy: AppColors.border + error: Colors.redAccent, // Legacy: AppColors.error + tertiary: Colors.green, // Using Tertiary for Success (Green) + ), + + appBarTheme: const AppBarTheme( + backgroundColor: Colors.transparent, + elevation: 0, + iconTheme: IconThemeData(color: Color(0xFF5A8DF3)), + titleTextStyle: TextStyle( + color: Color(0xFF5A8DF3), + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + + dividerTheme: const DividerThemeData(color: Color(0xFFE2E8F0)), + ); + + // ========================================================= + // 🌙 DARK THEME DICTIONARY + // Extracted from the provided Stitch Design System + // ========================================================= + static final ThemeData darkTheme = ThemeData( + brightness: Brightness.dark, + scaffoldBackgroundColor: const Color(0xFF0F172A), // Neutral Slate Dark + + colorScheme: const ColorScheme.dark( + // Brand Colors (Slightly brighter to stand out on dark background) + primary: Color(0xFF60A5FA), // Bright Blue + secondary: Color(0xFF61789A), // Slate Blue + + // Background & Surface Colors + // Note: 'background' is deprecated, scaffoldBackgroundColor handles the main background. + surface: Color(0xFF1E293B), // Slightly lighter than background, used for Cards + surfaceContainerHighest: Color(0xFF162032), // Dark mode counterpart for backgroundBlue + + // Text Colors + onSurface: Colors.white, // Primary text (White) + onSurfaceVariant: Color(0xFF94A3B8), // Secondary text (Light Slate) + + // Border, Status & Highlight Colors + outline: Color(0xFF334155), // Faint Card Border + error: Color(0xFFF87171), // Pinkish Red (Similar to Trash Icon) + tertiary: Color(0xFFD19900), // Mustard Yellow (Similar to Edit Pencil Icon) + ), + + appBarTheme: const AppBarTheme( + backgroundColor: Colors.transparent, + elevation: 0, + iconTheme: IconThemeData(color: Color(0xFF60A5FA)), + titleTextStyle: TextStyle( + color: Color(0xFF60A5FA), + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + + dividerTheme: const DividerThemeData(color: Color(0xFF334155)), + ); +} \ No newline at end of file diff --git a/src/lib/core/theme/auth_layout_template.dart b/src/lib/core/theme/auth_layout_template.dart index 88e796d..e001784 100644 --- a/src/lib/core/theme/auth_layout_template.dart +++ b/src/lib/core/theme/auth_layout_template.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'app_colors.dart'; /// The master layout template for all authentication screens. /// Handles the UI skeleton, loading states, backgrounds, and responsive scrolling. @@ -35,31 +34,59 @@ class AuthLayoutTemplate extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: Navigator.canPop(context) ? IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + ), + child: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), + ), onPressed: () => Navigator.pop(context), ) : null, ), - body: SafeArea( - child: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(24.0, 16.0, 24.0, 48.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - _buildHeader(), - const SizedBox(height: 32), - useCard ? _buildCardContainer() : _buildTransparentContainer(), - const SizedBox(height: 32), - if (footerContent != null) footerContent!, - ], + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(24.0, 16.0, 24.0, 48.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _buildHeader(context), + const SizedBox(height: 32), + useCard + ? _buildCardContainer(context) + : _buildTransparentContainer(context), + const SizedBox(height: 32), + if (footerContent != null) footerContent!, + ], + ), ), ), ), @@ -67,7 +94,9 @@ class AuthLayoutTemplate extends StatelessWidget { ); } - Widget _buildHeader() { + Widget _buildHeader(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Column( children: [ customHeaderIcon ?? @@ -75,37 +104,41 @@ class AuthLayoutTemplate extends StatelessWidget { width: 80, height: 80, decoration: BoxDecoration( - color: AppColors.white, + color: isDark ? const Color(0xFF1E2B47) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(24), boxShadow: [ BoxShadow( - color: AppColors.primary.withOpacity(0.1), + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.14), blurRadius: 20, offset: const Offset(0, 10), ), ], ), - child: const Center( - child: Icon(Icons.task_alt, size: 48, color: AppColors.primary), + child: Center( + child: Icon( + Icons.task_alt, + size: 48, + color: Theme.of(context).colorScheme.primary, + ), ), ), const SizedBox(height: 24), Text( title, - style: const TextStyle( + style: TextStyle( fontSize: 28, fontWeight: FontWeight.w800, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, letterSpacing: -0.5, ), ), const SizedBox(height: 8), Text( subtitle, - style: const TextStyle( + style: TextStyle( fontSize: 14, fontWeight: FontWeight.w500, - color: AppColors.textSecondary, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), textAlign: TextAlign.center, ), @@ -113,27 +146,33 @@ class AuthLayoutTemplate extends StatelessWidget { ); } - Widget _buildCardContainer() { + Widget _buildCardContainer(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Container( padding: const EdgeInsets.all(32), decoration: BoxDecoration( - color: AppColors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(32), + border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) : null, boxShadow: [ BoxShadow( - color: AppColors.primary.withOpacity(0.08), + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.12), blurRadius: 30, offset: const Offset(0, 10), ), ], ), - child: _buildFormElements(), + child: _buildFormElements(context), ); } - Widget _buildTransparentContainer() => _buildFormElements(); + Widget _buildTransparentContainer(BuildContext context) => + _buildFormElements(context); + + Widget _buildFormElements(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; - Widget _buildFormElements() { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -143,20 +182,24 @@ class AuthLayoutTemplate extends StatelessWidget { // Disable button if loading onPressed: isLoading ? null : onSubmit, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, - disabledBackgroundColor: AppColors.primary.withOpacity(0.6), + backgroundColor: Theme.of(context).colorScheme.primary, + disabledBackgroundColor: + Theme.of(context).colorScheme.primary.withValues(alpha: 0.6), padding: const EdgeInsets.symmetric(vertical: 20), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), - elevation: isLoading ? 0 : 4, + elevation: isLoading ? 0 : (isDark ? 8 : 4), + shadowColor: isDark + ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.35) + : null, ), child: isLoading - ? const SizedBox( + ? SizedBox( height: 20, width: 20, child: CircularProgressIndicator( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, strokeWidth: 2, ), ) @@ -165,16 +208,16 @@ class AuthLayoutTemplate extends StatelessWidget { children: [ Text( submitText, - style: const TextStyle( + style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, ), ), const SizedBox(width: 8), - const Icon( + Icon( Icons.arrow_forward, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, size: 20, ), ], @@ -182,9 +225,11 @@ class AuthLayoutTemplate extends StatelessWidget { ), if (showSocial) ...[ const SizedBox(height: 32), - const Row( + Row( children: [ - Expanded(child: Divider(color: AppColors.border)), + Expanded( + child: Divider(color: Theme.of(context).colorScheme.outline), + ), Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: Text( @@ -192,11 +237,13 @@ class AuthLayoutTemplate extends StatelessWidget { style: TextStyle( fontSize: 10, fontWeight: FontWeight.bold, - color: AppColors.textSecondary, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), ), - Expanded(child: Divider(color: AppColors.border)), + Expanded( + child: Divider(color: Theme.of(context).colorScheme.outline), + ), ], ), const SizedBox(height: 24), @@ -204,6 +251,16 @@ class AuthLayoutTemplate extends StatelessWidget { children: [ Expanded( child: OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.onSurface, + side: BorderSide(color: Theme.of(context).colorScheme.outline), + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.symmetric(vertical: 14), + ), onPressed: onGoogleTap, icon: const Icon( Icons.g_mobiledata, @@ -216,6 +273,16 @@ class AuthLayoutTemplate extends StatelessWidget { const SizedBox(width: 16), Expanded( child: OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.onSurface, + side: BorderSide(color: Theme.of(context).colorScheme.outline), + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + padding: const EdgeInsets.symmetric(vertical: 14), + ), onPressed: onFacebookTap, icon: const Icon(Icons.facebook, color: Color(0xFF1877F2)), label: const Text('Facebook'), diff --git a/src/lib/core/theme/custom_text_field.dart b/src/lib/core/theme/custom_text_field.dart index 7e98bcf..05a651d 100644 --- a/src/lib/core/theme/custom_text_field.dart +++ b/src/lib/core/theme/custom_text_field.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import 'app_colors.dart'; /// A highly reusable text input field component. class CustomTextField extends StatelessWidget { @@ -24,6 +23,8 @@ class CustomTextField extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Padding( padding: const EdgeInsets.only(bottom: 16), child: Column( @@ -36,7 +37,10 @@ class CustomTextField extends StatelessWidget { style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, - color: AppColors.textDark.withOpacity(0.6), + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: isDark ? 0.9 : 0.8), letterSpacing: 1, ), ), @@ -44,26 +48,29 @@ class CustomTextField extends StatelessWidget { TextFormField( controller: controller, obscureText: obscureText, - style: const TextStyle( - color: AppColors.textDark, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.w600, fontSize: 16, ), decoration: InputDecoration( hintText: hint, hintStyle: TextStyle( - color: AppColors.textDark.withOpacity(0.3), + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.65), fontWeight: FontWeight.w400, fontSize: 16, ), filled: true, - fillColor: AppColors.inputBackground, - prefixIcon: Icon(icon, color: AppColors.primary), + fillColor: isDark ? const Color(0xFF344765) : Theme.of(context).colorScheme.surface, + prefixIcon: Icon(icon, color: Theme.of(context).colorScheme.primary), suffixIcon: isPassword ? IconButton( icon: Icon( obscureText ? Icons.visibility_off : Icons.visibility, - color: Colors.grey, + color: Theme.of(context).colorScheme.onSurfaceVariant, ), onPressed: onToggleVisibility, ) @@ -73,18 +80,22 @@ class CustomTextField extends StatelessWidget { horizontal: 16, ), border: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), + borderRadius: BorderRadius.circular(24), borderSide: BorderSide.none, ), enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: const BorderSide(color: AppColors.border), + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide( + color: isDark + ? const Color(0xFF4A5F80) + : Theme.of(context).colorScheme.outline, + ), ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: const BorderSide( - color: AppColors.primary, - width: 2, + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide( + color: Theme.of(context).colorScheme.primary, + width: 1.5, ), ), ), diff --git a/src/lib/core/theme/theme_provider.dart b/src/lib/core/theme/theme_provider.dart new file mode 100644 index 0000000..d265fea --- /dev/null +++ b/src/lib/core/theme/theme_provider.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class ThemeProvider extends ChangeNotifier { + + static const String _themeKey = "theme_mode"; + + ThemeMode _themeMode = ThemeMode.light; + + ThemeMode get themeMode => _themeMode; + + ThemeProvider() { + _loadThemeFromPrefs(); + } + + // func change theme + void updateTheme(String appearance) { + final normalized = appearance.trim().toLowerCase(); + + if (normalized == 'dark') { + _themeMode = ThemeMode.dark; + } else if (normalized == 'light') { + _themeMode = ThemeMode.light; + } else { + _themeMode = ThemeMode.system; + } + + _saveThemeToPrefs( + _themeMode == ThemeMode.dark + ? 'Dark' + : _themeMode == ThemeMode.light + ? 'Light' + : 'System', + ); + notifyListeners(); + } + + Future _saveThemeToPrefs(String appearance) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_themeKey, appearance); + } + + // load theme when user open app + Future _loadThemeFromPrefs() async { + final prefs = await SharedPreferences.getInstance(); + final appearance = (prefs.getString(_themeKey) ?? 'Light').trim().toLowerCase(); + + if (appearance == 'dark') { + _themeMode = ThemeMode.dark; + } else if (appearance == 'system') { + _themeMode = ThemeMode.system; + } else { + _themeMode = ThemeMode.light; + } + notifyListeners(); + } +} \ No newline at end of file diff --git a/src/lib/core/widgets/custom_input_field.dart b/src/lib/core/widgets/custom_input_field.dart index 29bb775..3552a50 100644 --- a/src/lib/core/widgets/custom_input_field.dart +++ b/src/lib/core/widgets/custom_input_field.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../theme/app_colors.dart'; class CustomInputField extends StatelessWidget { final String label; @@ -32,8 +31,11 @@ class CustomInputField extends StatelessWidget { contentPadding: EdgeInsets.zero, enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Colors.black26)), - focusedBorder: const UnderlineInputBorder( - borderSide: BorderSide(color: AppColors.primaryBlue)), + focusedBorder: UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).colorScheme.primary, + ), + ), ), ), ], diff --git a/src/lib/features/auth/otp_verification_view.dart b/src/lib/features/auth/otp_verification_view.dart index 1f80d61..0f96ea4 100644 --- a/src/lib/features/auth/otp_verification_view.dart +++ b/src/lib/features/auth/otp_verification_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../core/theme/app_colors.dart'; import '../auth/viewmodels/auth_viewmodels.dart'; import '../auth/presentation/view/new_password_view.dart'; @@ -18,18 +17,21 @@ class _OtpVerificationViewState extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () => Navigator.pop(context), ), - title: const Text( + title: Text( 'OTP Verification', style: TextStyle( - color: AppColors.primary, + color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.bold, fontSize: 18, ), @@ -46,24 +48,26 @@ class _OtpVerificationViewState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Icon( + Icon( Icons.mark_email_read, size: 80, - color: AppColors.primary, + color: Theme.of(context).colorScheme.primary, ), const SizedBox(height: 32), - const Text( + Text( 'Enter 8-digit code', // Show correct 8-digit count style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), ), const SizedBox(height: 8), - const Text( + Text( 'The code has been sent to your email.', - style: TextStyle(color: AppColors.textSecondary), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), ), const SizedBox(height: 40), @@ -117,28 +121,28 @@ class _OtpVerificationViewState extends State { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(errorMessage), - backgroundColor: AppColors.error, + backgroundColor: Theme.of(context).colorScheme.error, ), ); } }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, + backgroundColor: Theme.of(context).colorScheme.primary, minimumSize: const Size(double.infinity, 56), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), ), child: _vm.isLoading - ? const CircularProgressIndicator( - color: AppColors.white, + ? CircularProgressIndicator( + color: Theme.of(context).colorScheme.surface, ) - : const Text( + : Text( 'CONFIRM', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, ), ), ), @@ -154,24 +158,31 @@ class _OtpVerificationViewState extends State { if (errorMessage == null) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( + SnackBar( content: Text('OTP code resent!'), - backgroundColor: AppColors.success, + backgroundColor: Theme.of(context).colorScheme.tertiary, ), ); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(errorMessage), - backgroundColor: AppColors.error, + backgroundColor: Theme.of(context).colorScheme.error, ), ); } }, - icon: const Icon(Icons.refresh, size: 18, color: AppColors.primary), - label: const Text( + icon: Icon( + Icons.refresh, + size: 18, + color: Theme.of(context).colorScheme.primary, + ), + label: Text( 'Resend code', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), ), ) ], @@ -190,9 +201,9 @@ class _OtpVerificationViewState extends State { width: boxWidth, // Use calculated width height: 48, decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppColors.border), + border: Border.all(color: Theme.of(context).colorScheme.outline), ), child: TextField( onChanged: (value) { @@ -205,10 +216,10 @@ class _OtpVerificationViewState extends State { FocusScope.of(context).previousFocus(); } }, - style: const TextStyle( + style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, - color: AppColors.textDark, + color: Theme.of(context).colorScheme.onSurface, ), keyboardType: TextInputType.number, textAlign: TextAlign.center, diff --git a/src/lib/features/auth/presentation/view/forgot_password_view.dart b/src/lib/features/auth/presentation/view/forgot_password_view.dart index bc105ca..8029cca 100644 --- a/src/lib/features/auth/presentation/view/forgot_password_view.dart +++ b/src/lib/features/auth/presentation/view/forgot_password_view.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -16,6 +15,8 @@ class _ForgotPasswordViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return AnimatedBuilder( animation: _vm, builder: (context, _) => AuthLayoutTemplate( @@ -26,12 +27,23 @@ class _ForgotPasswordViewState extends State { isLoading: _vm.isLoading, customHeaderIcon: Container( width: 120, height: 120, - decoration: const BoxDecoration( - color: AppColors.white, + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1B2A46) : Theme.of(context).colorScheme.surface, shape: BoxShape.circle, - boxShadow: [BoxShadow(color: Color(0xFFD1D9E6), blurRadius: 16)], + boxShadow: [ + BoxShadow( + color: isDark + ? Theme.of(context).colorScheme.primary.withValues(alpha: 0.22) + : const Color(0xFFD1D9E6), + blurRadius: 24, + ) + ], + ), + child: Icon( + Icons.lock_reset, + size: 64, + color: Theme.of(context).colorScheme.primary, ), - child: const Icon(Icons.lock_reset, size: 64, color: AppColors.primary), ), onSubmit: () async { FocusScope.of(context).unfocus(); // Đóng bàn phím @@ -45,7 +57,12 @@ class _ForgotPasswordViewState extends State { Navigator.push(context, MaterialPageRoute(builder: (_) => const OtpVerificationView())); } else { // Có lỗi (như nhập sai định dạng, spam nút) -> Vã cái lỗi màu đỏ ra - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: CustomTextField( @@ -54,15 +71,34 @@ class _ForgotPasswordViewState extends State { icon: Icons.mail, controller: _vm.emailCtrl, ), - footerContent: const Padding( - padding: EdgeInsets.only(bottom: 24.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.help, size: 16, color: AppColors.primary), - SizedBox(width: 4), - Text('Cần hỗ trợ? Liên hệ CSKH', style: TextStyle(color: AppColors.textSecondary, fontSize: 14, fontWeight: FontWeight.bold)), - ], + footerContent: Padding( + padding: const EdgeInsets.only(bottom: 24.0), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF111E37) : Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(999), + border: Border.all(color: Theme.of(context).colorScheme.outline), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.help, + size: 16, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'Cần hỗ trợ? Liên hệ CSKH', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + fontWeight: FontWeight.bold, + ), + ), + ], + ), ), ), ), diff --git a/src/lib/features/auth/presentation/view/login_view.dart b/src/lib/features/auth/presentation/view/login_view.dart index 8d39494..7807b4f 100644 --- a/src/lib/features/auth/presentation/view/login_view.dart +++ b/src/lib/features/auth/presentation/view/login_view.dart @@ -1,5 +1,4 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -28,13 +27,23 @@ class _LoginViewState extends State { onGoogleTap: () async { final error = await _vm.loginWithGoogle(); if (error != null && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, onFacebookTap: () async { final error = await _vm.loginWithFacebook(); if (error != null && context.mounted) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, onSubmit: () async { @@ -43,11 +52,21 @@ class _LoginViewState extends State { if (!context.mounted) return; if (errorMessage == null) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đăng nhập thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đăng nhập thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // If LoginView was pushed on top of AuthGate, pop back to root so MainScreen is visible. Navigator.of(context).popUntil((route) => route.isFirst); } else { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -60,28 +79,57 @@ class _LoginViewState extends State { ), TextButton( onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const ForgotPasswordView())), - child: const Text('Quên mật khẩu?', style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold)), + child: Text( + 'Quên mật khẩu?', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), ), ], ), - footerContent: _buildFooter('Chưa có tài khoản? ', 'Đăng ký ngay', () { + footerContent: _buildFooter( + context, + 'Chưa có tài khoản? ', + 'Đăng ký ngay', + () { Navigator.push(context, MaterialPageRoute(builder: (_) => const RegisterView())); - }), + }, + ), ), ); } - Widget _buildFooter(String text, String action, VoidCallback onTap) { + Widget _buildFooter( + BuildContext context, + String text, + String action, + VoidCallback onTap, + ) { return Padding( padding: const EdgeInsets.only(bottom: 24.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text(text, style: const TextStyle(color: AppColors.textSecondary, fontSize: 16)), + Text( + text, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 16, + ), + ), TextButton( onPressed: onTap, style: TextButton.styleFrom(minimumSize: const Size(50, 48)), - child: Text(action, style: const TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 16)), + child: Text( + action, + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), ), ], ), diff --git a/src/lib/features/auth/presentation/view/new_password_view.dart b/src/lib/features/auth/presentation/view/new_password_view.dart index dbe9bfc..64c6e84 100644 --- a/src/lib/features/auth/presentation/view/new_password_view.dart +++ b/src/lib/features/auth/presentation/view/new_password_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -16,6 +15,8 @@ class _NewPasswordViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return AnimatedBuilder( animation: _vm, builder: (context, _) => AuthLayoutTemplate( @@ -23,10 +24,14 @@ class _NewPasswordViewState extends State { subtitle: 'Mật khẩu mới phải khác với mật khẩu cũ', submitText: 'Cập nhật', isLoading: _vm.isLoading, - customHeaderIcon: const CircleAvatar( + customHeaderIcon: CircleAvatar( radius: 40, - backgroundColor: Color(0xFFEBF2FF), - child: Icon(Icons.lock_reset, size: 40, color: AppColors.primary), + backgroundColor: isDark ? const Color(0xFF213A63) : const Color(0xFFEBF2FF), + child: Icon( + Icons.lock_reset, + size: 40, + color: Theme.of(context).colorScheme.primary, + ), ), onSubmit: () async { FocusScope.of(context).unfocus(); @@ -37,12 +42,22 @@ class _NewPasswordViewState extends State { if (errorMessage == null) { // Null -> Thành công -> Báo xanh mướt - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đổi mật khẩu thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đổi mật khẩu thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // Cú đá chót: Xóa hết lịch sử trang, đá thẳng mặt về trang Login (isFirst) Navigator.popUntil(context, (route) => route.isFirst); } else { // Nếu lỗi do User nhập lệch pass -> Chửi - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -59,15 +74,30 @@ class _NewPasswordViewState extends State { Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: const Color(0xFFEBF2FF), + color: isDark + ? const Color(0xFF223A63) + : const Color(0xFFEBF2FF), borderRadius: BorderRadius.circular(12), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.25)) + : null, ), - child: const Row( + child: Row( children: [ - Icon(Icons.info, color: AppColors.primary, size: 16), - SizedBox(width: 8), + Icon( + Icons.info, + color: Theme.of(context).colorScheme.primary, + size: 16, + ), + const SizedBox(width: 8), Expanded( - child: Text('Mật khẩu tối thiểu 6 ký tự để đảm bảo an toàn.', style: TextStyle(fontSize: 12, color: AppColors.primary)), + child: Text( + 'Mật khẩu tối thiểu 6 ký tự để đảm bảo an toàn.', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.primary, + ), + ), ), ], ), diff --git a/src/lib/features/auth/presentation/view/otp_verification_view.dart b/src/lib/features/auth/presentation/view/otp_verification_view.dart index b8bb7b7..6bd64c8 100644 --- a/src/lib/features/auth/presentation/view/otp_verification_view.dart +++ b/src/lib/features/auth/presentation/view/otp_verification_view.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodels/auth_viewmodels.dart'; import 'new_password_view.dart'; @@ -15,40 +14,69 @@ class _OtpVerificationViewState extends State { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: AppColors.background, + backgroundColor: Theme.of(context).scaffoldBackgroundColor, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back, color: AppColors.primary), + icon: Icon( + Icons.arrow_back, + color: Theme.of(context).colorScheme.primary, + ), onPressed: () => Navigator.pop(context), ), - title: const Text( + title: Text( 'Xác thực OTP', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 18), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, + fontWeight: FontWeight.bold, + fontSize: 18, + ), ), centerTitle: true, ), - body: AnimatedBuilder( - animation: _vm, - builder: (context, child) { - return SafeArea( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.mark_email_read, size: 80, color: AppColors.primary), + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: AnimatedBuilder( + animation: _vm, + builder: (context, child) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + Icons.mark_email_read, + size: 80, + color: Theme.of(context).colorScheme.primary, + ), const SizedBox(height: 32), - const Text( + Text( 'Nhập mã 8 số', // Sửa chữ thành 8 số - style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: AppColors.textDark), + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), ), const SizedBox(height: 8), - const Text( + Text( 'Mã đã được gửi đến email của bạn.', - style: TextStyle(color: AppColors.textSecondary), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), ), const SizedBox(height: 40), @@ -73,20 +101,34 @@ class _OtpVerificationViewState extends State { ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error), + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), ); } }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primary, + backgroundColor: Theme.of(context).colorScheme.primary, minimumSize: const Size(double.infinity, 56), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + elevation: isDark ? 10 : null, + shadowColor: Theme.of(context) + .colorScheme + .primary + .withValues(alpha: 0.35), ), child: _vm.isLoading - ? const CircularProgressIndicator(color: AppColors.white) - : const Text( + ? CircularProgressIndicator( + color: Theme.of(context).colorScheme.surface, + ) + : Text( 'XÁC NHẬN', - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: AppColors.white), + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.surface, + ), ), ), const SizedBox(height: 16), @@ -98,25 +140,39 @@ class _OtpVerificationViewState extends State { if (errorMessage == null) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Đã gửi lại mã OTP!'), backgroundColor: AppColors.success), + SnackBar( + content: const Text('Đã gửi lại mã OTP!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), ); } else { ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error), + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), ); } }, - icon: const Icon(Icons.refresh, size: 18, color: AppColors.primary), - label: const Text( + icon: Icon( + Icons.refresh, + size: 18, + color: Theme.of(context).colorScheme.primary, + ), + label: Text( 'Gửi lại mã', - style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold), + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), ), ) - ], + ], + ), ), - ), - ); - } + ); + } + ), ), ); } @@ -125,9 +181,15 @@ class _OtpVerificationViewState extends State { return Container( width: 35, height: 48, // Thu nhỏ kích thước ô lại để nhét vừa 8 ô trên 1 dòng decoration: BoxDecoration( - color: AppColors.white, + color: Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF344765) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppColors.border), + border: Border.all( + color: Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF4A5F80) + : Theme.of(context).colorScheme.outline, + ), ), child: TextField( onChanged: (value) { @@ -137,7 +199,11 @@ class _OtpVerificationViewState extends State { if (value.isNotEmpty && index < 7) FocusScope.of(context).nextFocus(); if (value.isEmpty && index > 0) FocusScope.of(context).previousFocus(); }, - style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppColors.textDark), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), keyboardType: TextInputType.number, textAlign: TextAlign.center, inputFormatters: [ diff --git a/src/lib/features/auth/presentation/view/register_view.dart b/src/lib/features/auth/presentation/view/register_view.dart index 17dfc88..ddc3556 100644 --- a/src/lib/features/auth/presentation/view/register_view.dart +++ b/src/lib/features/auth/presentation/view/register_view.dart @@ -1,5 +1,5 @@ import 'package:flutter/material.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; import '../../../../core/theme/auth_layout_template.dart'; import '../../../../core/theme/custom_text_field.dart'; import '../viewmodels/auth_viewmodels.dart'; @@ -29,11 +29,21 @@ class _RegisterViewState extends State { if (!context.mounted) return; if (errorMessage == null) { - ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Đăng ký thành công!'), backgroundColor: AppColors.success)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: const Text('Đăng ký thành công!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), + ); // Return to the existing LoginView to avoid stacking duplicate login routes. Navigator.pop(context); } else { - ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(errorMessage), backgroundColor: AppColors.error)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(errorMessage), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); } }, formContent: Column( @@ -55,11 +65,24 @@ class _RegisterViewState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Text('Đã có tài khoản? ', style: TextStyle(color: AppColors.textSecondary, fontSize: 16)), + Text( + 'Đã có tài khoản? ', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 16, + ), + ), TextButton( onPressed: () => Navigator.pop(context), style: TextButton.styleFrom(minimumSize: const Size(50, 48)), - child: const Text('Đăng nhập', style: TextStyle(color: AppColors.primary, fontWeight: FontWeight.bold, fontSize: 16)), + child: Text( + 'Đăng nhập', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), ), ], ), diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index 8c8cffe..cb1c9d0 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -2,13 +2,15 @@ import 'package:flutter/material.dart'; import 'package:task_management_app/features/statistics/viewmodel/statistics_viewmodel.dart'; import 'package:task_management_app/features/tasks/view/screens/home_screen.dart'; import 'settings_screen.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/features/user/viewmodel/user_profile_viewmodel.dart'; import '../../../note/view/focus_screen.dart'; import '../../../note/viewmodel/focus_viewmodel.dart'; import '../../../statistics/view/screens/statistics_screen.dart'; // import '../../../tasks/view/screens/home_screen.dart'; import 'package:provider/provider.dart'; +import '../../../user/view/user_profile_view.dart'; + class MainScreen extends StatefulWidget { const MainScreen({super.key}); @@ -30,11 +32,17 @@ class _MainScreenState extends State { create: (_) => StatisticsViewmodel(), child: const StatisticsScreen(), ), + ChangeNotifierProvider( + create: (_) => UserProfileViewModel(useMockData: true)..loadProfile(), + child: const UserProfileView(), + ), const SettingsScreen(), ]; @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( extendBody: true, body: IndexedStack( @@ -44,7 +52,9 @@ class _MainScreenState extends State { bottomNavigationBar: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15), decoration: BoxDecoration( - color: Colors.white, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: const BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30)), boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 20, offset: const Offset(0, -5))], ), @@ -52,11 +62,11 @@ class _MainScreenState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ - _buildNavItem(Icons.checklist_rounded, 'Công việc', 0), - _buildNavItem(Icons.calendar_today_rounded, 'Lịch', 1), - _buildNavItem(Icons.timer_rounded, 'Tập trung', 2), - _buildNavItem(Icons.bar_chart_rounded, 'Thống kê', 3), - _buildNavItem(Icons.settings_rounded, 'Cài đặt', 4), + _buildNavItem(context, Icons.checklist_rounded, 'Công việc', 0), + _buildNavItem(context, Icons.calendar_today_rounded, 'Lịch', 1), + _buildNavItem(context, Icons.timer_rounded, 'Tập trung', 2), + _buildNavItem(context, Icons.bar_chart_rounded, 'Thống kê', 3), + _buildNavItem(context, Icons.person_2_rounded, 'Cá nhân', 4), ], ), ), @@ -64,7 +74,7 @@ class _MainScreenState extends State { ); } - Widget _buildNavItem(IconData icon, String label, int index) { + Widget _buildNavItem(BuildContext context, IconData icon, String label, int index) { bool isSelected = _currentIndex == index; return GestureDetector( @@ -74,20 +84,32 @@ class _MainScreenState extends State { curve: Curves.easeInOut, padding: EdgeInsets.symmetric(horizontal: isSelected ? 15 : 10, vertical: 10), decoration: BoxDecoration( - color: isSelected ? const Color(0xFFE8F0FE) : Colors.transparent, + color: isSelected + ? (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF23395D) + : const Color(0xFFE8F0FE)) + : Colors.transparent, borderRadius: BorderRadius.circular(15), ), child: Column( mainAxisSize: MainAxisSize.min, children: [ - Icon(icon, color: isSelected ? AppColors.primaryBlue : AppColors.grayText, size: 24), + Icon( + icon, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + size: 24, + ), const SizedBox(height: 4), Text( label, style: TextStyle( fontSize: 10, fontWeight: isSelected ? FontWeight.bold : FontWeight.normal, - color: isSelected ? AppColors.primaryBlue : AppColors.grayText, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, ), ) ], diff --git a/src/lib/features/note/view/focus_screen.dart b/src/lib/features/note/view/focus_screen.dart index 9349b49..2702c2d 100644 --- a/src/lib/features/note/view/focus_screen.dart +++ b/src/lib/features/note/view/focus_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodel/focus_viewmodel.dart'; import '../view/focus_widget.dart'; @@ -10,6 +9,7 @@ class FocusScreen extends StatelessWidget { // Shows the configuration dialog for timer and notification settings void _showSettingsDialog(BuildContext context) { final vm = context.read(); + final isDark = Theme.of(context).brightness == Brightness.dark; double currentPomodoro = (vm.pomodoroTime / 60).toDouble(); double currentBreak = (vm.shortBreakTime / 60).toDouble(); @@ -22,9 +22,16 @@ class FocusScreen extends StatelessWidget { return StatefulBuilder( builder: (context, setStateDialog) { return AlertDialog( - backgroundColor: Colors.white, + backgroundColor: + isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), - title: const Text('Cài đặt', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + title: Text( + 'Cài đặt', + style: TextStyle( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, @@ -34,36 +41,98 @@ class FocusScreen extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text('Pomodoro', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), - Text('${currentPomodoro.toInt()} phút', style: const TextStyle(color: AppColors.primaryBlue, fontWeight: FontWeight.bold)), + Text( + 'Pomodoro', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + '${currentPomodoro.toInt()} phút', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), ], ), - Slider(value: currentPomodoro, min: 5, max: 60, divisions: 55, activeColor: AppColors.primaryBlue, onChanged: (val) => setStateDialog(() => currentPomodoro = val)), + Slider( + value: currentPomodoro, + min: 5, + max: 60, + divisions: 55, + activeColor: Theme.of(context).colorScheme.primary, + onChanged: (val) => setStateDialog(() => currentPomodoro = val), + ), const SizedBox(height: 5), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text('Nghỉ ngắn', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text( + 'Nghỉ ngắn', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), Text('${currentBreak.toInt()} phút', style: const TextStyle(color: Colors.orange, fontWeight: FontWeight.bold)), ], ), - Slider(value: currentBreak, min: 1, max: 30, divisions: 29, activeColor: Colors.orange, onChanged: (val) => setStateDialog(() => currentBreak = val)), - const Divider(height: 30), + Slider( + value: currentBreak, + min: 1, + max: 30, + divisions: 29, + activeColor: Colors.orange, + onChanged: (val) => setStateDialog(() => currentBreak = val), + ), + Divider( + height: 30, + color: Theme.of(context).colorScheme.outline, + ), // --- Hardware Settings --- SwitchListTile( - title: const Text('Rung', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), - value: currentVibrate, activeColor: AppColors.primaryBlue, contentPadding: EdgeInsets.zero, + title: Text( + 'Rung', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + value: currentVibrate, + activeThumbColor: Theme.of(context).colorScheme.primary, + contentPadding: EdgeInsets.zero, onChanged: (val) => setStateDialog(() => currentVibrate = val), ), const SizedBox(height: 10), - const Text('Âm thanh', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), + Text( + 'Âm thanh', + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 10), Container( padding: const EdgeInsets.symmetric(horizontal: 15), - decoration: BoxDecoration(color: const Color(0xFFF4F6F9), borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(15), + ), child: DropdownButtonHideUnderline( child: DropdownButton( + dropdownColor: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, + style: TextStyle(color: Theme.of(context).colorScheme.onSurface), isExpanded: true, value: currentRingtone, items: const [ @@ -81,14 +150,24 @@ class FocusScreen extends StatelessWidget { ), ), actions: [ - TextButton(onPressed: () => Navigator.pop(context), child: const Text('Hủy', style: TextStyle(color: Colors.grey))), + TextButton( + onPressed: () => Navigator.pop(context), + child: Text( + 'Hủy', + style: + TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), ElevatedButton( onPressed: () { // Update settings in ViewModel vm.updateSettings(newPomodoroMinutes: currentPomodoro.toInt(), newBreakMinutes: currentBreak.toInt(), vibrate: currentVibrate, ringtone: currentRingtone); Navigator.pop(context); }, - style: ElevatedButton.styleFrom(backgroundColor: AppColors.primaryBlue, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10))), + style: ElevatedButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.primary, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), + ), child: const Text('Lưu', style: TextStyle(color: Colors.white)), ), ], @@ -101,29 +180,64 @@ class FocusScreen extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: const Color(0xFFF4F6F9), - body: SafeArea( - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ // --- Header --- Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Row( + Row( children: [ - CircleAvatar(radius: 22, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d')), - SizedBox(width: 15), - Text('Tập trung', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + const CircleAvatar( + radius: 22, + backgroundImage: + NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d'), + ), + const SizedBox(width: 15), + Text( + 'Tập trung', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), ], ), // Settings Icon GestureDetector( onTap: () => _showSettingsDialog(context), - child: Container(padding: const EdgeInsets.all(10), decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), child: const Icon(Icons.settings_outlined, color: AppColors.primaryBlue)), + child: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + shape: BoxShape.circle, + ), + child: Icon( + Icons.settings_outlined, + color: Theme.of(context).colorScheme.primary, + ), + ), ), ], ), @@ -142,6 +256,7 @@ class FocusScreen extends StatelessWidget { ), ), ), + ) ); } } \ No newline at end of file diff --git a/src/lib/features/note/view/focus_widget.dart b/src/lib/features/note/view/focus_widget.dart index 8037b4a..73fb73b 100644 --- a/src/lib/features/note/view/focus_widget.dart +++ b/src/lib/features/note/view/focus_widget.dart @@ -1,7 +1,6 @@ import 'dart:io'; // Import to display image files import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../viewmodel/focus_viewmodel.dart'; // --- Tab Selector Widget --- @@ -11,38 +10,62 @@ class FocusTabSelector extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( padding: const EdgeInsets.all(5), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF132544) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(20), - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 10)], + boxShadow: [ + BoxShadow(color: Colors.black.withValues(alpha: 0.10), blurRadius: 10) + ], ), child: Row( mainAxisSize: MainAxisSize.min, children: [ - _buildTabBtn('Pomodoro', vm.isPomodoroMode, () => vm.setMode(true)), - _buildTabBtn('Nghỉ ngắn', !vm.isPomodoroMode, () => vm.setMode(false)), + _buildTabBtn( + context, + 'Pomodoro', + vm.isPomodoroMode, + () => vm.setMode(true), + ), + _buildTabBtn( + context, + 'Nghỉ ngắn', + !vm.isPomodoroMode, + () => vm.setMode(false), + ), ], ), ); } - Widget _buildTabBtn(String label, bool isSelected, VoidCallback onTap) { + Widget _buildTabBtn( + BuildContext context, + String label, + bool isSelected, + VoidCallback onTap, + ) { return GestureDetector( onTap: onTap, child: AnimatedContainer( duration: const Duration(milliseconds: 200), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10), decoration: BoxDecoration( - color: isSelected ? AppColors.primaryBlue : Colors.transparent, + color: isSelected + ? (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF2A3D5D) + : Theme.of(context).colorScheme.primary) + : Colors.transparent, borderRadius: BorderRadius.circular(15), ), child: Text( label, style: TextStyle( - color: isSelected ? Colors.white : const Color(0xFF757575), + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.onSurfaceVariant, fontWeight: FontWeight.bold, fontSize: 14, ), @@ -59,13 +82,23 @@ class TimerDisplayWidget extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; + return Stack( alignment: Alignment.center, children: [ Container( width: 280, height: 280, - decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: Colors.white, width: 14)), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: isDark + ? const Color(0xFF182C4D) + : Theme.of(context).colorScheme.surface, + width: 14, + ), + ), ), SizedBox( width: 280, @@ -73,7 +106,7 @@ class TimerDisplayWidget extends StatelessWidget { child: CircularProgressIndicator( value: vm.progress, strokeWidth: 14, - color: AppColors.primaryBlue, + color: Theme.of(context).colorScheme.primary, backgroundColor: Colors.transparent, strokeCap: StrokeCap.round, ), @@ -82,21 +115,40 @@ class TimerDisplayWidget extends StatelessWidget { width: 210, height: 210, decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, shape: BoxShape.circle, - boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 20, offset: const Offset(0, 10))], + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.18), + blurRadius: 20, + offset: const Offset(0, 10), + ) + ], ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( vm.timeString, - style: const TextStyle(fontSize: 56, fontWeight: FontWeight.w900, color: Color(0xFF2C3E50), letterSpacing: -2), + style: TextStyle( + fontSize: 56, + fontWeight: FontWeight.w900, + color: Theme.of(context).colorScheme.onSurface, + letterSpacing: -2, + ), ), const SizedBox(height: 4), Text( vm.isPomodoroMode ? 'TẬP TRUNG' : 'NGHỈ NGƠI', - style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: AppColors.primaryBlue.withOpacity(0.8), letterSpacing: 2), + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Theme.of(context) + .colorScheme + .primary + .withValues(alpha: 0.85), + letterSpacing: 2, + ), ), ], ), @@ -113,13 +165,15 @@ class TimerControlsWidget extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; + return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ _buildControlBtn( icon: Icons.replay_rounded, - bgColor: Colors.white, - iconColor: const Color(0xFF757575), + bgColor: isDark ? const Color(0xFF1A2B4B) : Theme.of(context).colorScheme.surface, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, size: 60, onTap: vm.resetTimer, ), @@ -130,7 +184,9 @@ class TimerControlsWidget extends StatelessWidget { icon: vm.isRinging ? Icons.notifications_off_rounded // Muted bell icon : (vm.isRunning ? Icons.pause_rounded : Icons.play_arrow_rounded), - bgColor: vm.isRinging ? Colors.redAccent : AppColors.primaryBlue, + bgColor: vm.isRinging + ? Colors.redAccent + : Theme.of(context).colorScheme.primary, iconColor: Colors.white, size: 85, hasShadow: true, @@ -140,8 +196,8 @@ class TimerControlsWidget extends StatelessWidget { const SizedBox(width: 30), _buildControlBtn( icon: Icons.skip_next_rounded, - bgColor: Colors.white, - iconColor: const Color(0xFF757575), + bgColor: isDark ? const Color(0xFF1A2B4B) : Theme.of(context).colorScheme.surface, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, size: 60, onTap: vm.skipTimer, ), @@ -164,8 +220,18 @@ class TimerControlsWidget extends StatelessWidget { color: bgColor, shape: BoxShape.circle, boxShadow: [ - if (hasShadow) BoxShadow(color: bgColor.withOpacity(0.4), blurRadius: 20, offset: const Offset(0, 10)), - if (!hasShadow) BoxShadow(color: Colors.black.withOpacity(0.03), blurRadius: 10, offset: const Offset(0, 5)), + if (hasShadow) + BoxShadow( + color: bgColor.withValues(alpha: 0.40), + blurRadius: 20, + offset: const Offset(0, 10), + ), + if (!hasShadow) + BoxShadow( + color: Colors.black.withValues(alpha: 0.16), + blurRadius: 10, + offset: const Offset(0, 5), + ), ], ), child: Material( @@ -187,19 +253,40 @@ class QuickNoteCard extends StatelessWidget { @override Widget build(BuildContext context) { final vm = context.watch(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( width: double.infinity, padding: const EdgeInsets.all(25), - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(30)), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, + ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: const [ - Text('Ghi chú nhanh', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Đang thực hiện', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: AppColors.grayText)), + children: [ + Text( + 'Ghi chú nhanh', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + 'Đang thực hiện', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), const SizedBox(height: 15), @@ -208,7 +295,9 @@ class QuickNoteCard extends StatelessWidget { Container( padding: const EdgeInsets.all(15), decoration: BoxDecoration( - color: const Color(0xFFF4F6F9), + color: isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest, borderRadius: BorderRadius.circular(15), ), child: Column( @@ -219,12 +308,21 @@ class QuickNoteCard extends StatelessWidget { maxLines: 3, decoration: InputDecoration( hintText: 'Thêm ý tưởng, tiến độ, hình ảnh...', - hintStyle: TextStyle(color: Colors.grey.shade400, fontSize: 14), + hintStyle: TextStyle( + color: Theme.of(context) + .colorScheme + .onSurfaceVariant + .withValues(alpha: 0.70), + fontSize: 14, + ), border: InputBorder.none, isDense: true, contentPadding: EdgeInsets.zero, ), - style: const TextStyle(fontSize: 14, color: Color(0xFF2C3E50)), + style: TextStyle( + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + ), ), // SHOW IMAGE PREVIEW IF SELECTED @@ -277,12 +375,20 @@ class QuickNoteCard extends StatelessWidget { children: [ Row( children: [ - Icon(Icons.attach_file_rounded, color: Colors.grey.shade400, size: 22), + Icon( + Icons.attach_file_rounded, + color: Theme.of(context).colorScheme.onSurfaceVariant, + size: 22, + ), const SizedBox(width: 10), // IMAGE PICKER BUTTON GestureDetector( onTap: () => vm.pickImage(), - child: Icon(Icons.image_outlined, color: AppColors.primaryBlue, size: 22), + child: Icon( + Icons.image_outlined, + color: Theme.of(context).colorScheme.primary, + size: 22, + ), ), ], ), @@ -292,7 +398,7 @@ class QuickNoteCard extends StatelessWidget { context.read().addNote(); }, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), elevation: 0, @@ -304,7 +410,10 @@ class QuickNoteCard extends StatelessWidget { // --- LOCAL NOTE LIST WITH IMAGE SUPPORT --- if (vm.notes.isNotEmpty) ...[ - const Padding(padding: EdgeInsets.symmetric(vertical: 15), child: Divider(color: Color(0xFFE2E8F0), height: 1)), + Padding( + padding: const EdgeInsets.symmetric(vertical: 15), + child: Divider(color: Theme.of(context).colorScheme.outline, height: 1), + ), ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), @@ -315,7 +424,11 @@ class QuickNoteCard extends StatelessWidget { margin: const EdgeInsets.only(bottom: 12), padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: note.pinned ? const Color(0xFFFFF8E1) : const Color(0xFFF8FAFC), + color: note.pinned + ? (isDark ? const Color(0xFF4A3B17) : const Color(0xFFFFF8E1)) + : (isDark + ? const Color(0xFF12223D) + : Theme.of(context).colorScheme.surfaceContainerHighest), borderRadius: BorderRadius.circular(15), border: Border.all(color: note.pinned ? Colors.amber.shade200 : Colors.transparent), ), @@ -329,7 +442,13 @@ class QuickNoteCard extends StatelessWidget { margin: const EdgeInsets.only(top: 2, right: 12), width: 22, height: 22, - decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue, width: 2)), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: Theme.of(context).colorScheme.primary, + width: 2, + ), + ), ), ), // CONTENT (TEXT AND IMAGE) @@ -338,7 +457,14 @@ class QuickNoteCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (note.content.isNotEmpty) - Text(note.content, style: const TextStyle(fontSize: 14, color: Color(0xFF2C3E50), height: 1.4)), + Text( + note.content, + style: TextStyle( + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface, + height: 1.4, + ), + ), // DISPLAY ATTACHED IMAGE IN NOTE if (note.imagePath != null && note.imagePath!.isNotEmpty) ...[ diff --git a/src/lib/features/statistics/view/screens/statistics_screen.dart b/src/lib/features/statistics/view/screens/statistics_screen.dart index b8eb2b9..fd18a14 100644 --- a/src/lib/features/statistics/view/screens/statistics_screen.dart +++ b/src/lib/features/statistics/view/screens/statistics_screen.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../viewmodel/statistics_viewmodel.dart'; import '../widgets/statistics_widgets.dart'; @@ -29,21 +28,24 @@ class _StatisticsScreenState extends State { } - Icon _getIconForCategory(String category) { - switch (category) { - case 'Design': return const Icon(Icons.checklist_rtl_rounded, color: AppColors.primaryBlue); - case 'Research': return const Icon(Icons.timer_outlined, color: Color(0xFFE67E22)); - case 'Development': return const Icon(Icons.calendar_month_outlined, color: Color(0xFF9B59B6)); - default: return const Icon(Icons.task_alt_rounded, color: Colors.green); - } - } - @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Scaffold( - backgroundColor: const Color(0xFFF4F6F9), - body: Consumer( - builder: (context, viewModel, child) { + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + body: Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: Consumer( + builder: (context, viewModel, child) { if (viewModel.isLoading) { return const Center(child: CircularProgressIndicator()); @@ -63,34 +65,51 @@ class _StatisticsScreenState extends State { final currentTasks = data.recentTasks; - return SafeArea( - child: SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ + return SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ // --- Header --- - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Row( - children: [ - CircleAvatar( + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + const CircleAvatar( radius: 22, - backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=a042581f4e29026704d') - ), - SizedBox(width: 15), - Text('Thống kê', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - ], - ), + backgroundImage: NetworkImage( + 'https://i.pravatar.cc/150?u=a042581f4e29026704d', + ), + ), + const SizedBox(width: 15), + Text( + 'Thống kê', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + ], + ), Container( padding: const EdgeInsets.all(10), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: const Icon(Icons.notifications_none_rounded, color: AppColors.primaryBlue), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF172744) + : Theme.of(context).colorScheme.surface, + shape: BoxShape.circle, + ), + child: Icon( + Icons.notifications_none_rounded, + color: Theme.of(context).colorScheme.primary, + ), ) - ], - ), - const SizedBox(height: 30), + ], + ), + const SizedBox(height: 30), DailyProgressCard( @@ -114,25 +133,44 @@ class _StatisticsScreenState extends State { const SizedBox(height: 30), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text('Hoàn thành gần đây', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Xem tất cả', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: AppColors.primaryBlue)), - ], - ), - const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Hoàn thành gần đây', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + 'Xem tất cả', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.primary, + ), + ), + ], + ), + const SizedBox(height: 15), AnimatedSwitcher( duration: const Duration(milliseconds: 300), child: currentTasks.isEmpty ? Container( - key: const ValueKey('empty_state'), - padding: const EdgeInsets.all(30), - alignment: Alignment.center, - child: Text('Chưa có công việc nào hoàn thành gần đây.', - style: TextStyle(color: Colors.grey.shade500), textAlign: TextAlign.center), - ) + key: const ValueKey('empty_state'), + padding: const EdgeInsets.all(30), + alignment: Alignment.center, + child: Text( + 'Chưa có công việc nào hoàn thành gần đây.', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + textAlign: TextAlign.center, + ), + ) : Column( key: ValueKey('list_$_selectedDayIndex'), children: currentTasks.map((task) { @@ -148,12 +186,13 @@ class _StatisticsScreenState extends State { ), ), - const SizedBox(height: 80), - ], + const SizedBox(height: 80), + ], + ), ), - ), - ); - }, + ); + }, + ), ), ); } diff --git a/src/lib/features/statistics/view/widgets/statistics_widgets.dart b/src/lib/features/statistics/view/widgets/statistics_widgets.dart index a93344e..c0b6568 100644 --- a/src/lib/features/statistics/view/widgets/statistics_widgets.dart +++ b/src/lib/features/statistics/view/widgets/statistics_widgets.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:task_management_app/features/statistics/model/StatisticsModel.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../tasks/model/task_model.dart'; import '../../../tasks/view/screens/task_detail_screen.dart'; @@ -12,16 +11,28 @@ class DailyProgressCard extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return Container( width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Column( children: [ - const Text('Tiến độ hôm nay', style: TextStyle(color: AppColors.grayText, fontSize: 16, fontWeight: FontWeight.w600)), + Text( + 'Tiến độ hôm nay', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), const SizedBox(height: 20), SizedBox( height: 140, @@ -32,14 +43,30 @@ class DailyProgressCard extends StatelessWidget { CircularProgressIndicator( value: (total > 0) ? percentage / 100 : 0, strokeWidth: 12, - backgroundColor: AppColors.backgroundBlue, - valueColor: AlwaysStoppedAnimation(AppColors.primaryBlue), + backgroundColor: + Theme.of(context).colorScheme.surfaceContainerHighest, + valueColor: AlwaysStoppedAnimation( + Theme.of(context).colorScheme.primary, + ), ), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Text('$completed/$total', style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), - Text('Công việc', style: TextStyle(fontSize: 12, color: Colors.grey.shade500)), + Text( + '$completed/$total', + style: TextStyle( + fontSize: 32, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + Text( + 'Công việc', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ], @@ -49,10 +76,19 @@ class DailyProgressCard extends StatelessWidget { RichText( textAlign: TextAlign.center, text: TextSpan( - style: const TextStyle(fontSize: 16, color: Colors.black87), + style: TextStyle( + fontSize: 16, + color: Theme.of(context).colorScheme.onSurface, + ), children: [ const TextSpan(text: 'Tuyệt vời! Bạn đã hoàn thành '), - TextSpan(text: '${percentage.toInt()}%', style: const TextStyle(color: AppColors.primaryBlue, fontWeight: FontWeight.bold)), + TextSpan( + text: '${percentage.toInt()}%', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), const TextSpan(text: '\nmục tiêu.'), ], ), @@ -82,18 +118,24 @@ class WeeklyChartCard extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; final bool isPositive = growthPercentage >= 0; - final Color trendColor = isPositive ? const Color(0xFF2ECC71) : Colors.redAccent; - final Color trendBgColor = isPositive ? const Color(0xFFE9F7EF) : const Color(0xFFFFEBEE); + final Color trendColor = isPositive ? const Color(0xFF3DDC84) : Colors.redAccent; + final Color trendBgColor = isPositive + ? (isDark ? const Color(0xFF173B3D) : const Color(0xFFE9F7EF)) + : (isDark ? const Color(0xFF402129) : const Color(0xFFFFEBEE)); final String trendText = "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; return Container( width: double.infinity, padding: const EdgeInsets.all(25), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -105,9 +147,23 @@ class WeeklyChartCard extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - const Text('Tuần này', style: TextStyle(color: AppColors.grayText, fontSize: 14, fontWeight: FontWeight.w600)), + Text( + 'Tuần này', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), const SizedBox(height: 5), - Text('$thisWeekTotal Tasks', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + '$thisWeekTotal Tasks', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), ], ), Container( @@ -123,13 +179,13 @@ class WeeklyChartCard extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.end, children: [ - _buildBar('T2', weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, 0), - _buildBar('T3', weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, 1), - _buildBar('T4', weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, 2), - _buildBar('T5', weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, 3), - _buildBar('T6', weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, 4), - _buildBar('T7', weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, 5), - _buildBar('CN', weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, 6), + _buildBar(context, 'T2', weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, 0), + _buildBar(context, 'T3', weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, 1), + _buildBar(context, 'T4', weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, 2), + _buildBar(context, 'T5', weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, 3), + _buildBar(context, 'T6', weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, 4), + _buildBar(context, 'T7', weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, 5), + _buildBar(context, 'CN', weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, 6), ], ), ], @@ -137,7 +193,7 @@ class WeeklyChartCard extends StatelessWidget { ); } - Widget _buildBar(String label, double heightRatio, int index) { + Widget _buildBar(BuildContext context, String label, double heightRatio, int index) { bool isActive = index == selectedIndex; return GestureDetector( onTap: () => onDaySelected(index), @@ -149,12 +205,25 @@ class WeeklyChartCard extends StatelessWidget { width: 35, height: 100 * (heightRatio > 0 ? heightRatio : 0.1), // Tối thiểu 10% để cột không bị "biến mất" decoration: BoxDecoration( - color: isActive ? AppColors.primaryBlue : const Color(0xFFF5F7FA), + color: isActive + ? Theme.of(context).colorScheme.primary + : (Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF334764) + : const Color(0xFFF5F7FA)), borderRadius: BorderRadius.circular(8), ), ), const SizedBox(height: 10), - Text(label, style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: isActive ? AppColors.primaryBlue : AppColors.grayText)), + Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: isActive + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ); @@ -170,6 +239,7 @@ class CompletedTaskCard extends StatelessWidget { @override Widget build(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; final time = task.updatedAt; final hour = time.hour > 12 ? time.hour - 12 : (time.hour == 0 ? 12 : time.hour); @@ -206,14 +276,22 @@ class CompletedTaskCard extends StatelessWidget { margin: const EdgeInsets.only(bottom: 15), padding: const EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white, + color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), + border: isDark + ? Border.all(color: const Color(0xFF2A3E62), width: 1) + : null, ), child: Row( children: [ Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: const Color(0xFFF1F7FD), borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF23395D) + : const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(15), + ), child: icon, ), const SizedBox(width: 15), @@ -221,9 +299,22 @@ class CompletedTaskCard extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(task.title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))), + Text( + task.title, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 4), - Text(timeString, style: TextStyle(fontSize: 12, color: Colors.grey.shade500)), + Text( + timeString, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), ], ), ), diff --git a/src/lib/features/tasks/view/screens/create_task_screen.dart b/src/lib/features/tasks/view/screens/create_task_screen.dart index a7f22c9..43ad594 100644 --- a/src/lib/features/tasks/view/screens/create_task_screen.dart +++ b/src/lib/features/tasks/view/screens/create_task_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/custom_input_field.dart'; import '../widgets/task_widgets.dart'; @@ -22,14 +21,16 @@ class _CreateTaskScreenState extends State { @override Widget build(BuildContext context) { String formattedDate = DateFormat('EEEE, d MMMM').format(_selectedDate); + final isDark = Theme.of(context).brightness == Brightness.dark; return Scaffold( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, body: SafeArea( child: Column( children: [ Container( decoration: BoxDecoration( - color: Colors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: const BorderRadius.only( bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)), boxShadow: [ @@ -43,11 +44,20 @@ class _CreateTaskScreenState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( - icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black), + icon: Icon( + Icons.arrow_back_ios_new_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), onPressed: () => Navigator.pop(context), ), - const Icon(Icons.menu_rounded, color: Colors.black), - const Icon(Icons.assignment_outlined, color: Colors.black), + Icon( + Icons.menu_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), + Icon( + Icons.assignment_outlined, + color: Theme.of(context).colorScheme.onSurface, + ), ], ), ), @@ -77,12 +87,24 @@ class _CreateTaskScreenState extends State { label: Text(categories[index]), selected: isSelected, onSelected: (selected) => setState(() => _selectedCategoryIndex = selected ? index : 0), - backgroundColor: const Color(0xFFF1F7FD), - selectedColor: AppColors.primaryBlue, - labelStyle: TextStyle(color: isSelected ? Colors.white : AppColors.primaryBlue, fontSize: 14), + backgroundColor: isDark + ? Theme.of(context).colorScheme.surfaceContainerHighest + : const Color(0xFFF1F7FD), + selectedColor: Theme.of(context).colorScheme.primary, + labelStyle: TextStyle( + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.primary, + fontSize: 14, + ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), - side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), + side: BorderSide( + color: isDark + ? Theme.of(context).colorScheme.outline + : const Color(0xFFF1F7FD), + width: 1, + )), showCheckmark: false, ), ); @@ -108,9 +130,20 @@ class _CreateTaskScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(formattedDate, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + Text( + formattedDate, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 5), - Container(width: 150, height: 1, color: Colors.black26) + Container( + width: 150, + height: 1, + color: Theme.of(context).colorScheme.outline, + ) ], ), ) @@ -118,7 +151,10 @@ class _CreateTaskScreenState extends State { ), Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: AppColors.primaryBlue, borderRadius: BorderRadius.circular(15)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, + borderRadius: BorderRadius.circular(15), + ), child: const Icon(Icons.date_range_rounded, color: Colors.white), ) ], @@ -156,7 +192,7 @@ class _CreateTaskScreenState extends State { child: ElevatedButton( onPressed: () {}, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 15), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), diff --git a/src/lib/features/tasks/view/screens/home_screen.dart b/src/lib/features/tasks/view/screens/home_screen.dart index c30697a..0232c40 100644 --- a/src/lib/features/tasks/view/screens/home_screen.dart +++ b/src/lib/features/tasks/view/screens/home_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../model/task_model.dart'; import '../widgets/task_widgets.dart'; import 'create_task_screen.dart'; @@ -11,6 +10,7 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { String formattedDate = DateFormat('EEEE, d MMMM').format(DateTime.now()); + final isDark = Theme.of(context).brightness == Brightness.dark; // --- TẠO DỮ LIỆU GIẢ LẬP (MOCK DATA) --- final task1 = TaskModel( @@ -39,7 +39,10 @@ class HomeScreen extends StatelessWidget { children: [ Positioned( top: 0, left: 0, right: 0, height: 250, - child: ClipPath(clipper: TopWaveClipper(), child: Container(color: AppColors.primaryBlue)), + child: ClipPath( + clipper: TopWaveClipper(), + child: Container(color: Theme.of(context).colorScheme.primary), + ), ), SafeArea( child: Column( @@ -50,10 +53,20 @@ class HomeScreen extends StatelessWidget { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Icon(Icons.menu_rounded, color: Colors.black), + Icon( + Icons.menu_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), Row( children: [ - const Icon(Icons.notifications_none_rounded, color: Colors.black), + Icon( + Icons.notifications_none_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), const SizedBox(width: 15), const CircleAvatar( radius: 20, @@ -61,7 +74,12 @@ class HomeScreen extends StatelessWidget { ), const SizedBox(width: 10), IconButton( - icon: const Icon(Icons.add_rounded, color: Colors.black), + icon: Icon( + Icons.add_rounded, + color: isDark + ? Theme.of(context).colorScheme.surface + : Colors.black, + ), onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => const CreateTaskScreen())), ), ], @@ -73,7 +91,13 @@ class HomeScreen extends StatelessWidget { Container( width: double.infinity, margin: const EdgeInsets.symmetric(horizontal: 20), - decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(30)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.outline) + : null, + ), child: Padding( padding: const EdgeInsets.all(25.0), child: Column( @@ -85,7 +109,13 @@ class HomeScreen extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Today', style: Theme.of(context).textTheme.titleMedium), - Text(formattedDate, style: const TextStyle(color: AppColors.grayText, fontSize: 14)), + Text( + formattedDate, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: 14, + ), + ), ], ), const SizedBox(height: 20), @@ -121,8 +151,15 @@ class HomeScreen extends StatelessWidget { left: 30, child: Container( padding: const EdgeInsets.all(4), - decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle), - child: const Icon(Icons.add_rounded, size: 20, color: AppColors.primaryBlue), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surface, + shape: BoxShape.circle, + ), + child: Icon( + Icons.add_rounded, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), ), ) ], @@ -132,8 +169,16 @@ class HomeScreen extends StatelessWidget { task: task2, // Truyền task2 vào đây leading: Container( padding: const EdgeInsets.all(12), - decoration: BoxDecoration(color: const Color(0xFFF1F7FD), borderRadius: BorderRadius.circular(15)), - child: const Icon(Icons.call_outlined, color: AppColors.primaryBlue), + decoration: BoxDecoration( + color: isDark + ? Theme.of(context).colorScheme.surfaceContainerHighest + : const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(15), + ), + child: Icon( + Icons.call_outlined, + color: Theme.of(context).colorScheme.primary, + ), ), ), // ---------------------------------------- diff --git a/src/lib/features/tasks/view/screens/task_detail_screen.dart b/src/lib/features/tasks/view/screens/task_detail_screen.dart index 6297293..aa81264 100644 --- a/src/lib/features/tasks/view/screens/task_detail_screen.dart +++ b/src/lib/features/tasks/view/screens/task_detail_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; import '../widgets/task_widgets.dart'; // Contains TimePickerWidget @@ -51,7 +50,10 @@ class _TaskDetailScreenState extends State { // Show success message ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Task updated successfully!'), backgroundColor: Colors.green), + SnackBar( + content: const Text('Task updated successfully!'), + backgroundColor: Theme.of(context).colorScheme.tertiary, + ), ); // Return to the previous screen @@ -62,20 +64,30 @@ class _TaskDetailScreenState extends State { Widget build(BuildContext context) { // Format date for display String formattedDate = DateFormat('EEEE, d MMMM').format(widget.task.date); + final isDark = Theme.of(context).brightness == Brightness.dark; // Mock categories (Fetch from database later) List categories = ['Development', 'Research', 'Design', 'Backend']; return Scaffold( - backgroundColor: AppColors.backgroundBlue, + backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: IconButton( - icon: const Icon(Icons.arrow_back_ios_new_rounded, color: Colors.black), + icon: Icon( + Icons.arrow_back_ios_new_rounded, + color: Theme.of(context).colorScheme.onSurface, + ), onPressed: () => Navigator.pop(context), ), - title: const Text('Task Details', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold)), + title: Text( + 'Task Details', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, + fontWeight: FontWeight.bold, + ), + ), centerTitle: true, ), body: SafeArea( @@ -86,8 +98,11 @@ class _TaskDetailScreenState extends State { child: Container( margin: const EdgeInsets.all(20), decoration: BoxDecoration( - color: Colors.white, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), + border: isDark + ? Border.all(color: Theme.of(context).colorScheme.outline) + : null, boxShadow: [ BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 5)) ], @@ -120,12 +135,24 @@ class _TaskDetailScreenState extends State { onSelected: (selected) { if (selected) setState(() => _currentCategory = categories[index]); }, - backgroundColor: const Color(0xFFF1F7FD), - selectedColor: AppColors.primaryBlue, - labelStyle: TextStyle(color: isSelected ? Colors.white : AppColors.primaryBlue, fontSize: 14), + backgroundColor: isDark + ? Theme.of(context).colorScheme.surfaceContainerHighest + : const Color(0xFFF1F7FD), + selectedColor: Theme.of(context).colorScheme.primary, + labelStyle: TextStyle( + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.primary, + fontSize: 14, + ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), - side: const BorderSide(color: Color(0xFFF1F7FD), width: 1)), + side: BorderSide( + color: isDark + ? Theme.of(context).colorScheme.outline + : const Color(0xFFF1F7FD), + width: 1, + )), showCheckmark: false, ), ); @@ -137,7 +164,14 @@ class _TaskDetailScreenState extends State { // Display Task Date Text('Date', style: Theme.of(context).textTheme.labelLarge), const SizedBox(height: 5), - Text(formattedDate, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black)), + Text( + formattedDate, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), const SizedBox(height: 25), // Time Pickers for Start and End time @@ -177,7 +211,7 @@ class _TaskDetailScreenState extends State { child: ElevatedButton( onPressed: _saveChanges, style: ElevatedButton.styleFrom( - backgroundColor: AppColors.primaryBlue, + backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), diff --git a/src/lib/features/tasks/view/widgets/task_widgets.dart b/src/lib/features/tasks/view/widgets/task_widgets.dart index 20b453b..426d182 100644 --- a/src/lib/features/tasks/view/widgets/task_widgets.dart +++ b/src/lib/features/tasks/view/widgets/task_widgets.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -import '../../../../core/theme/app_colors.dart'; import '../../model/task_model.dart'; import '../screens/task_detail_screen.dart'; @@ -39,14 +38,22 @@ class DateBox extends StatelessWidget { Widget build(BuildContext context) { String day = DateFormat('d').format(date); String weekday = DateFormat('E').format(date).toUpperCase(); + final isDark = Theme.of(context).brightness == Brightness.dark; return Container( width: 55, margin: const EdgeInsets.only(right: 15), decoration: BoxDecoration( - color: isSelected ? AppColors.primaryBlue : Colors.white, + color: isSelected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(20), - border: Border.all(color: Colors.grey.shade300, width: 1), + border: Border.all( + color: isDark + ? Theme.of(context).colorScheme.outline + : Colors.grey.shade300, + width: 1, + ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -55,12 +62,16 @@ class DateBox extends StatelessWidget { style: TextStyle( fontSize: 22, fontWeight: FontWeight.bold, - color: isSelected ? Colors.white : Colors.black)), + color: isSelected + ? Colors.white + : Theme.of(context).colorScheme.onSurface)), const SizedBox(height: 5), Text(weekday, style: TextStyle( fontSize: 12, - color: isSelected ? AppColors.textLightBlue : AppColors.grayText)), + color: isSelected + ? Theme.of(context).colorScheme.secondary + : Theme.of(context).colorScheme.onSurfaceVariant)), ], ), ); @@ -105,7 +116,7 @@ class TaskCard extends StatelessWidget { child: Container( margin: const EdgeInsets.only(bottom: 20), decoration: BoxDecoration( - color: AppColors.taskCardBg, + color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), boxShadow: [ BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 5)) @@ -116,8 +127,8 @@ class TaskCard extends StatelessWidget { Positioned( left: 0, top: 25, bottom: 25, width: 4, child: Container( - decoration: const BoxDecoration( - color: AppColors.primaryBlue, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primary, borderRadius: BorderRadius.only(topRight: Radius.circular(5), bottomRight: Radius.circular(5))), ), ), @@ -139,7 +150,10 @@ class TaskCard extends StatelessWidget { ), Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), - decoration: BoxDecoration(color: AppColors.timeBoxBg, borderRadius: BorderRadius.circular(10)), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.secondary, + borderRadius: BorderRadius.circular(10), + ), child: Text(timeString, style: const TextStyle(color: Colors.white, fontSize: 12)), ), ], @@ -180,15 +194,21 @@ class TimePickerWidget extends StatelessWidget { Row( children: [ Text(formattedTime, - style: const TextStyle( - fontSize: 18, fontWeight: FontWeight.bold)), + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + )), const SizedBox(width: 5), - const Icon(Icons.keyboard_arrow_down_rounded, - color: AppColors.primaryBlue, size: 20) + Icon( + Icons.keyboard_arrow_down_rounded, + color: Theme.of(context).colorScheme.primary, + size: 20, + ) ], ), const SizedBox(height: 5), - Container(height: 1, color: Colors.black26) + Container(height: 1, color: Theme.of(context).colorScheme.outline) ], ), ); diff --git a/src/lib/features/user/model/user_profile_model.dart b/src/lib/features/user/model/user_profile_model.dart new file mode 100644 index 0000000..d378b4b --- /dev/null +++ b/src/lib/features/user/model/user_profile_model.dart @@ -0,0 +1,77 @@ +class UserProfileModel { + final String id; + final String name; + final int tasksDone; + final int streaks; + final String avatarUrl; + bool isNotificationEnabled; + String appearance; + + UserProfileModel({ + required this.id, + required this.name, + required this.tasksDone, + required this.streaks, + required this.avatarUrl, + this.isNotificationEnabled = true, + this.appearance = 'Light', + }); + + factory UserProfileModel.fromJson(Map json) { + int parseInt(dynamic value) { + if (value is int) return value; + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value) ?? 0; + return 0; + } + + return UserProfileModel( + id: json['id'] as String? ?? '', + name: + (json['name'] ?? json['full_name'] ?? json['username']) as String? ?? + 'Unknown User', + tasksDone: parseInt(json['tasksDone'] ?? json['tasks_done']), + streaks: parseInt(json['streaks'] ?? json['streak_count']), + avatarUrl: + (json['avatarUrl'] ?? json['avatar_url'] ?? json['avatar']) as String? ?? + '', + isNotificationEnabled: + (json['isNotificationEnabled'] ?? json['is_notification_enabled']) as bool? ?? + true, + appearance: (json['appearance'] ?? json['theme_mode']) as String? ?? 'Light', + ); + } + + + Map toJson() { + return { + 'id': id, + 'name': name, + 'tasksDone': tasksDone, + 'streaks': streaks, + 'avatarUrl': avatarUrl, + 'isNotificationEnabled': isNotificationEnabled, + 'appearance': appearance, + }; + } + + UserProfileModel copyWith({ + String? id, + String? name, + int? tasksDone, + int? streaks, + String? avatarUrl, + bool? isNotificationEnabled, + String? appearance, + }) { + return UserProfileModel( + id: id ?? this.id, + name: name ?? this.name, + tasksDone: tasksDone ?? this.tasksDone, + streaks: streaks ?? this.streaks, + avatarUrl: avatarUrl ?? this.avatarUrl, + isNotificationEnabled: isNotificationEnabled ?? this.isNotificationEnabled, + appearance: appearance ?? this.appearance, + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/service/user_service.dart b/src/lib/features/user/service/user_service.dart new file mode 100644 index 0000000..9a6c0d7 --- /dev/null +++ b/src/lib/features/user/service/user_service.dart @@ -0,0 +1,19 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/user_profile_model.dart'; + +class UserService { + final SupabaseClient _supabase = Supabase.instance.client; + /// Simulates fetching user profile data with a fake network delay + Future fetchUserProfile() async { + // Mimic API call delay for smooth state switching + try{ + final response = await _supabase.rpc('get_user_profile_stats'); + response['id'] = _supabase.auth.currentUser!.id; + return UserProfileModel.fromJson(response); + } + catch(e){ + throw Exception("Failed to fetch user profile: $e"); + } + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/user_profile_view.dart b/src/lib/features/user/view/user_profile_view.dart new file mode 100644 index 0000000..2e71926 --- /dev/null +++ b/src/lib/features/user/view/user_profile_view.dart @@ -0,0 +1,156 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../viewmodel/user_profile_viewmodel.dart'; +import 'widgets/profile_header.dart'; +import 'widgets/stat_card.dart'; +import 'widgets/settings_section.dart'; +import 'widgets/settings_list_tile.dart'; +import 'widgets/logout_button.dart'; + +class UserProfileView extends StatelessWidget { + const UserProfileView({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + appBar: AppBar( + backgroundColor: Theme.of(context).scaffoldBackgroundColor, + elevation: 0, + centerTitle: true, + scrolledUnderElevation: 0, + title: Text( + 'Profile', + style: TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.w800, + fontSize: 20, + ), + ), + actions: [ + IconButton( + icon: Icon( + Icons.settings, + color: Theme.of(context).colorScheme.primary, + ), + onPressed: () {}, + splashRadius: 24, + ), + ], + ), + body: Consumer( + builder: (context, vm, child) { + return AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + child: vm.isLoading + ? Center( + key: ValueKey('loading'), + child: CircularProgressIndicator( + color: Theme.of(context).colorScheme.primary, + ), + ) + : vm.user == null + ? const Center( + key: ValueKey('error'), + child: Text("Error loading profile"), + ) + : Builder( + builder: (innerContext) { + vm.syncThemeWithProfile(innerContext); + return _buildProfileContent(innerContext, vm); + }, + ), + ); + }, + ), + ); + } + + Widget _buildProfileContent(BuildContext context, UserProfileViewModel vm) { + final user = vm.user!; + return SingleChildScrollView( + key: const ValueKey('content'), + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.fromLTRB(24, 8, 24, 40), + child: Column( + children: [ + // 1. Header (Avatar & Name) + ProfileHeader(user: user), + const SizedBox(height: 32), + + // 2. Stats Row + Row( + children: [ + Expanded( + child: StatCard( + value: user.tasksDone.toString(), + label: 'Tasks Done', + onTap: () {}, + ), + ), + const SizedBox(width: 16), + Expanded( + child: StatCard( + value: user.streaks.toString(), + label: 'Streaks', + onTap: () {}, + ), + ), + ], + ), + const SizedBox(height: 32), + + SettingsSection( + title: 'Preferences', + children: [ + SettingsListTile( + icon: Icons.notifications, + title: 'Notifications', + iconBgColor: Theme.of(context).colorScheme.outline, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, + onTap: () => vm.toggleNotification(!user.isNotificationEnabled), + trailing: Switch( + value: user.isNotificationEnabled, + activeColor: Theme.of(context).colorScheme.surface, + activeTrackColor: Theme.of(context).colorScheme.primary, + inactiveThumbColor: + Theme.of(context).colorScheme.onSurfaceVariant, + inactiveTrackColor: Theme.of(context).colorScheme.outline, + onChanged: (val) => vm.toggleNotification(val), + ), + ), + Divider( + height: 1, + indent: 64, + endIndent: 24, + color: Theme.of(context).colorScheme.outline, + ), + SettingsListTile( + icon: Icons.dark_mode, + title: 'Appearance', + iconBgColor: Theme.of(context).colorScheme.outline, + iconColor: Theme.of(context).colorScheme.onSurfaceVariant, + trailing: Text( + user.appearance, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + onTap: () => vm.updateAppearance( + context, + user.appearance == 'Dark' ? 'Light' : 'Dark', + ), + ), + ], + ), + const SizedBox(height: 40), + + // 4. Logout Button + LogoutButton(onPressed: () => vm.logout(context)), + ], + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/logout_button.dart b/src/lib/features/user/view/widgets/logout_button.dart new file mode 100644 index 0000000..dd8fae1 --- /dev/null +++ b/src/lib/features/user/view/widgets/logout_button.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +class LogoutButton extends StatelessWidget { + final VoidCallback onPressed; + + const LogoutButton({super.key, required this.onPressed}); + + @override + Widget build(BuildContext context) { + final errorColor = Theme.of(context).colorScheme.error; + + return Material( + color: errorColor.withOpacity(0.05), + borderRadius: BorderRadius.circular(24), + child: InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(24), + splashColor: errorColor.withOpacity(0.1), + highlightColor: errorColor.withOpacity(0.05), + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 20), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + border: Border.all(color: errorColor.withOpacity(0.2)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.logout, color: errorColor, size: 22), + const SizedBox(width: 12), + Text( + 'Logout', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + color: errorColor, + ), + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/profile_header.dart b/src/lib/features/user/view/widgets/profile_header.dart new file mode 100644 index 0000000..2e61342 --- /dev/null +++ b/src/lib/features/user/view/widgets/profile_header.dart @@ -0,0 +1,114 @@ +import 'package:flutter/material.dart'; +import '../../model/user_profile_model.dart'; + +class ProfileHeader extends StatelessWidget { + final UserProfileModel user; + + const ProfileHeader({super.key, required this.user}); + + @override + Widget build(BuildContext context) { + final avatarUri = Uri.tryParse(user.avatarUrl.trim()); + final hasValidAvatar = + avatarUri != null && + (avatarUri.scheme == 'http' || avatarUri.scheme == 'https') && + avatarUri.host.isNotEmpty; + + return Column( + children: [ + Stack( + alignment: Alignment.bottomRight, + children: [ + // Rounded Square Avatar + Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(32), + boxShadow: [ + BoxShadow( + color: + Theme.of(context).colorScheme.primary.withValues(alpha: 0.15), + blurRadius: 20, + offset: const Offset(0, 10), + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(32), + child: hasValidAvatar + ? Image.network( + user.avatarUrl, + width: 120, + height: 120, + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => _buildFallbackAvatar(context), + // Smooth image loading transition + frameBuilder: + (context, child, frame, wasSynchronouslyLoaded) { + if (wasSynchronouslyLoaded) return child; + return AnimatedOpacity( + opacity: frame == null ? 0 : 1, + duration: const Duration(milliseconds: 500), + curve: Curves.easeOut, + child: child, + ); + }, + ) + : _buildFallbackAvatar(context), + ), + ), + // Edit Button with Ripple + Material( + color: Theme.of(context).colorScheme.primary, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: Theme.of(context).scaffoldBackgroundColor, + width: 4, + ), + ), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () { + // TODO: Handle Edit Profile action + }, + child: Padding( + padding: EdgeInsets.all(8.0), + child: Icon( + Icons.edit, + color: Theme.of(context).colorScheme.surface, + size: 20, + ), + ), + ), + ), + ], + ), + const SizedBox(height: 20), + + // Name Only + Text( + user.name, + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w800, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + // Badges row removed here + ], + ); + } + + Widget _buildFallbackAvatar(BuildContext context) { + return Container( + width: 120, + height: 120, + color: Theme.of(context).colorScheme.surfaceContainerHighest, + child: Icon( + Icons.person, + size: 64, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/settings_list_tile.dart b/src/lib/features/user/view/widgets/settings_list_tile.dart new file mode 100644 index 0000000..6d18666 --- /dev/null +++ b/src/lib/features/user/view/widgets/settings_list_tile.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; + +class SettingsListTile extends StatelessWidget { + final IconData icon; + final String title; + final Widget trailing; + final Color? iconBgColor; + final Color? iconColor; + final VoidCallback? onTap; + + const SettingsListTile({ + super.key, + required this.icon, + required this.title, + required this.trailing, + this.iconBgColor, + this.iconColor, + this.onTap, + }); + + @override + Widget build(BuildContext context) { + final resolvedIconBgColor = + iconBgColor ?? Theme.of(context).colorScheme.surfaceContainerHighest; + final resolvedIconColor = iconColor ?? Theme.of(context).colorScheme.primary; + + return InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: resolvedIconBgColor, + shape: BoxShape.circle, + ), + child: Icon(icon, color: resolvedIconColor, size: 22), + ), + const SizedBox(width: 16), + Expanded( + child: Text( + title, + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + ), + trailing, + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/settings_section.dart b/src/lib/features/user/view/widgets/settings_section.dart new file mode 100644 index 0000000..44cdff7 --- /dev/null +++ b/src/lib/features/user/view/widgets/settings_section.dart @@ -0,0 +1,39 @@ +import 'package:flutter/material.dart'; + +class SettingsSection extends StatelessWidget { + final String title; + final List children; + + const SettingsSection({super.key, required this.title, required this.children}); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(left: 16, bottom: 12), + child: Text( + title.toUpperCase(), + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurfaceVariant, + letterSpacing: 1.2, + ), + ), + ), + Material( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(24), + child: ClipRRect( + borderRadius: BorderRadius.circular(24), + child: Column( + children: children, + ), + ), + ), + ], + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/view/widgets/stat_card.dart b/src/lib/features/user/view/widgets/stat_card.dart new file mode 100644 index 0000000..e0fef26 --- /dev/null +++ b/src/lib/features/user/view/widgets/stat_card.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; + +class StatCard extends StatelessWidget { + final String value; + final String label; + final VoidCallback? onTap; + + const StatCard({super.key, required this.value, required this.label, this.onTap}); + + @override + Widget build(BuildContext context) { + return Material( + color: Theme.of(context).colorScheme.surface, + borderRadius: BorderRadius.circular(24), + elevation: 0, + child: InkWell( + onTap: onTap ?? () {}, // Interactive ripple effect + borderRadius: BorderRadius.circular(24), + child: Container( + padding: const EdgeInsets.symmetric(vertical: 24), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(24), + border: Border.all(color: Theme.of(context).colorScheme.outline.withOpacity(0.5)), + ), + child: Column( + children: [ + Text( + value, + style: TextStyle( + fontSize: 28, + fontWeight: FontWeight.w800, + color: Theme.of(context).colorScheme.primary, + ), + ), + const SizedBox(height: 4), + Text( + label.toUpperCase(), + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurfaceVariant, + letterSpacing: 1.2, + ), + ), + ], + ), + ), + ), + ); + } +} \ No newline at end of file diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart new file mode 100644 index 0000000..21b28c0 --- /dev/null +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; +import 'package:provider/provider.dart'; // Import thêm Provider + +import '../../../core/theme/theme_provider.dart'; +import '../../auth/presentation/view/auth_gate.dart'; +import '../model/user_profile_model.dart'; +import '../service/user_service.dart'; + +class UserProfileViewModel extends ChangeNotifier { + final UserService _userService = UserService(); + final _supabase = Supabase.instance.client; + final bool useMockData; + String? _lastAppliedAppearance; + + UserProfileViewModel({this.useMockData = true}); + + UserProfileModel? _user; + UserProfileModel? get user => _user; + + bool _isLoading = true; + bool get isLoading => _isLoading; + + /// Load profile data + Future loadProfile() async { + _isLoading = true; + notifyListeners(); + + try { + if (useMockData) { + await Future.delayed(const Duration(milliseconds: 400)); + _user = _buildMockUser(); + } else { + _user = await _userService.fetchUserProfile(); + } + _lastAppliedAppearance = null; + } catch (e) { + debugPrint("Error loading profile: $e"); + _user = _buildMockUser(); + } finally { + _isLoading = false; + notifyListeners(); + } + } + + UserProfileModel _buildMockUser() { + return UserProfileModel( + id: 'mock-user-001', + name: 'Alex Thompson', + // Valid URL so profile header can test normal network-avatar path. + avatarUrl: 'https://i.pravatar.cc/300?img=12', + appearance: 'Dark', + tasksDone: 24, + streaks: 12, + isNotificationEnabled: true, + ); + } + + /// Toggle notification preference + void toggleNotification(bool value) { + if (_user != null) { + _user!.isNotificationEnabled = value; + notifyListeners(); + } + } + + + void updateAppearance(BuildContext context, String newAppearance) { + if (_user != null) { + _user!.appearance = newAppearance; + _lastAppliedAppearance = newAppearance; + notifyListeners(); + + if (context.mounted) { + context.read().updateTheme(newAppearance); + } + } + } + + void syncThemeWithProfile(BuildContext context) { + if (_user == null) return; + if (_lastAppliedAppearance == _user!.appearance) return; + + _lastAppliedAppearance = _user!.appearance; + context.read().updateTheme(_user!.appearance); + } + + /// Logout + Future logout(BuildContext context) async { + try { + await _supabase.auth.signOut(); + debugPrint("Đã clear session trên Supabase."); + + if (context.mounted) { + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (context) => const AuthGate()), + (route) => false, + ); + } + + } catch (e) { + debugPrint("Lỗi đăng xuất: $e"); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Lỗi đăng xuất: $e')), + ); + } + } + } +} \ No newline at end of file diff --git a/src/lib/main.dart b/src/lib/main.dart index e0f3857..bcdb6be 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -1,12 +1,15 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/auth/presentation/view/auth_gate.dart'; +import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; import 'package:task_management_app/features/main/view/screens/main_screen.dart'; -import 'core/theme/app_colors.dart'; -import 'features/auth/presentation/view/login_view.dart'; -import 'features/auth/presentation/view/auth_gate.dart'; +import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; +import 'core/theme/theme_provider.dart'; + Future main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -28,7 +31,12 @@ Future main() async { SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle(statusBarColor: Colors.transparent)); - runApp(const TaskApp()); + runApp( + MultiProvider( + providers: [ + ChangeNotifierProvider(create: (_) => ThemeProvider()), + ], + child: const TaskApp())); } // 4. Create a global variable for ViewModel to call API quickly @@ -41,21 +49,13 @@ class TaskApp extends StatelessWidget { @override Widget build(BuildContext context) { + final themeProvider = Provider.of(context); return MaterialApp( title: 'Task Management App', - theme: ThemeData( - scaffoldBackgroundColor: AppColors.backgroundBlue, - primaryColor: AppColors.primaryBlue, - useMaterial3: true, - fontFamily: 'Montserrat', - textTheme: const TextTheme( - headlineMedium: TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Colors.black), - titleMedium: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black), - bodyMedium: TextStyle(fontSize: 14, color: AppColors.grayText), - labelLarge: TextStyle(fontSize: 16, color: AppColors.primaryBlue), - ), - ), - home: const AuthGate(), + themeMode: themeProvider.themeMode, + theme: AppTheme.lightTheme, // Bộ màu sáng ông vừa map xong + darkTheme: AppTheme.darkTheme, + home: const MainScreen(), debugShowCheckedModeBanner: false, ); } diff --git a/supabase/migrations/20260409084009_create_user_profile_rpc.sql b/supabase/migrations/20260409084009_create_user_profile_rpc.sql new file mode 100644 index 0000000..235c129 --- /dev/null +++ b/supabase/migrations/20260409084009_create_user_profile_rpc.sql @@ -0,0 +1,58 @@ +CREATE OR REPLACE FUNCTION get_user_profile_stats() +RETURNS JSON +LANGUAGE plpgsql +SECURITY INVOKER -- Chạy với quyền của user hiện tại (Tôn trọng RLS) +AS $$ +DECLARE + v_user_id UUID; + v_username TEXT; + v_avatar TEXT; + v_tasks_done INT; + v_current_streak INT; +BEGIN + v_user_id := auth.uid(); + + IF v_user_id IS NULL THEN + RAISE EXCEPTION 'User not authenticated'; + END IF; + + SELECT username, avatar INTO v_username, v_avatar + FROM public.profile + WHERE id = v_user_id; + + + SELECT COUNT(*) INTO v_tasks_done + FROM public.task + WHERE profile_id = v_user_id AND status = 1; + + + WITH completed_dates AS ( + -- Get the day that had task done + SELECT DISTINCT DATE(updated_at AT TIME ZONE 'UTC') AS task_date + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + ), + streak_groups AS ( + SELECT task_date, + task_date - (ROW_NUMBER() OVER (ORDER BY task_date))::INT AS grp + FROM completed_dates + ), + streak_counts AS ( + -- Calculate streak length for each group + SELECT grp, MAX(task_date) as end_date, COUNT(*) as streak_length + FROM streak_groups + GROUP BY grp + ) + -- get streak if the end date is within the yesterday + SELECT COALESCE(MAX(streak_length), 0) INTO v_current_streak + FROM streak_counts + WHERE end_date >= (CURRENT_DATE - INTERVAL '1 day'); + + RETURN json_build_object( + 'name', COALESCE(v_username, 'Unknown User'), + 'avatarUrl', COALESCE(v_avatar, ''), + 'tasksDone', COALESCE(v_tasks_done, 0), + 'streaks', COALESCE(v_current_streak, 0) + ); +END; +$$; \ No newline at end of file From 35f0285eeb2143b4159bf388ec1ab830d44da061 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Anh=20Ki=E1=BB=87t?= Date: Thu, 9 Apr 2026 21:38:05 +0700 Subject: [PATCH 2/9] feat(priority task):Implement priority and tag selection in task creation version 1 (#31) * feat(task): implement priority and tag selection features in task creation * Update README.md * Update README.md * Update README.md --------- Co-authored-by: Tran Quang Ha --- README.md | 32 +- src/lib/features/tasks/model/task_model.dart | 62 +++- .../view/screens/create_task_screen.dart | 157 +++++++-- .../tasks/view/screens/home_screen.dart | 323 +++++++++++++++--- .../tasks/view/widgets/priority_selector.dart | 65 ++++ .../tasks/view/widgets/tag_selector.dart | 60 ++++ .../tasks/viewmodel/task_viewmodel.dart | 106 ++++++ src/lib/main.dart | 14 +- 8 files changed, 711 insertions(+), 108 deletions(-) create mode 100644 src/lib/features/tasks/view/widgets/priority_selector.dart create mode 100644 src/lib/features/tasks/view/widgets/tag_selector.dart create mode 100644 src/lib/features/tasks/viewmodel/task_viewmodel.dart diff --git a/README.md b/README.md index a4e4753..2cd5439 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,11 @@ -# Task Management App - Life Organizer +## 📁 Chi tiết các file thay đổi -## 1. Introduction -This repository contains the source code for the **Task Management App (Life Organizer)**, developed as a project for the **SE346** course at the University of Information Technology - VNUHCM (UIT). +* **`task_model.dart`**: Thêm thuộc tính `Priority` và tích hợp `TagModel`. +* **`task_viewmodel.dart`**: Cập nhật logic xử lý trạng thái cho Provider. +* **`priority_selector.dart`**: Thêm UI Widget hỗ trợ chọn mức độ ưu tiên. +* **`tag_selector.dart`**: Thêm UI Widget hỗ trợ chọn các loại tag. +* **`create_task_screen.dart`**: Tích hợp 2 widget chọn Priority và Tag vào form tạo nhiệm vụ. +* **`main.dart`**: Đăng ký Provider mới cho hệ thống. +* **`home_screen.dart`**: Cập nhật giao diện, hiển thị danh sách task được nhóm theo mức độ ưu tiên. -Going beyond a traditional to-do list, this application is designed to be a comprehensive personal assistant. It helps users easily organize various life contexts, such as tracking utility bills, managing grocery shopping lists, building daily habits, and handling household chores efficiently. - -## 2. Authors -This project is built and maintained by a dedicated team of 4 members: -* [Trần Quang Hạ](https://github.com/tqha1011) -* [Nguyễn Lê Hoàng Hảo](https://github.com/hoanghaoz) -* [Nguyễn Anh Kiệt](https://github.com/anhkietbienhoa-crypto) -* [Nguyễn Trí Kiệt](https://github.com/Ender-Via) - -## 3. Tech Stack -The application is built with a focus on performance, security, and clean code principles, strictly following the **Feature-Based MVVM** architecture: -* **Frontend:** Flutter -* **Backend & Database:** Supabase (PostgreSQL, Auth, Row Level Security) -* **Code Quality & CI/CD:** GitHub Actions, SonarCloud - -## 4. Documentation -For a deeper dive into our system design and development workflows, please explore the attached documentation: -* [Flutter App Architecture](documentation/architecture/flutter-architecture.md) -* [Database Schema & ERD](documentation/architecture/database-schema.md) -* [Git & Conventional Commits Guidelines](documentation/guidelines/conventional-commit.md) \ No newline at end of file +image diff --git a/src/lib/features/tasks/model/task_model.dart b/src/lib/features/tasks/model/task_model.dart index 8158b08..a6a64fb 100644 --- a/src/lib/features/tasks/model/task_model.dart +++ b/src/lib/features/tasks/model/task_model.dart @@ -1,13 +1,69 @@ import 'package:flutter/material.dart'; +// ─── Priority Enum ─────────────────────────────────────────── +enum Priority { low, medium, high, urgent } + +extension PriorityExtension on Priority { + String get label { + switch (this) { + case Priority.low: + return 'Low'; + case Priority.medium: + return 'Medium'; + case Priority.high: + return 'High'; + case Priority.urgent: + return 'Urgent'; + } + } + + Color get color { + switch (this) { + case Priority.low: + return const Color(0xFF4CAF50); // xanh lá + case Priority.medium: + return const Color(0xFF2196F3); // xanh dương + case Priority.high: + return const Color(0xFFFF9800); // cam + case Priority.urgent: + return const Color(0xFFF44336); // đỏ + } + } + + IconData get icon { + switch (this) { + case Priority.low: + return Icons.flag_outlined; + case Priority.medium: + return Icons.flag; + case Priority.high: + return Icons.flag; + case Priority.urgent: + return Icons.flag; + } + } +} + +// ─── Tag Model ─────────────────────────────────────────────── +class TagModel { + final String id; + final String name; + final Color color; + + const TagModel({required this.id, required this.name, required this.color}); +} + +// ─── Task Model ────────────────────────────────────────────── class TaskModel { - final String id; // ID duy nhất để làm Hero tag và gọi API sau này + final String id; String title; String description; String category; TimeOfDay startTime; TimeOfDay endTime; DateTime date; + Priority priority; + List tags; TaskModel({ required this.id, @@ -17,5 +73,7 @@ class TaskModel { required this.startTime, required this.endTime, required this.date, + this.priority = Priority.medium, + this.tags = const [], }); -} \ No newline at end of file +} diff --git a/src/lib/features/tasks/view/screens/create_task_screen.dart b/src/lib/features/tasks/view/screens/create_task_screen.dart index 43ad594..311fd00 100644 --- a/src/lib/features/tasks/view/screens/create_task_screen.dart +++ b/src/lib/features/tasks/view/screens/create_task_screen.dart @@ -1,7 +1,13 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/custom_input_field.dart'; +import '../../model/task_model.dart'; +import '../../viewmodel/task_viewmodel.dart'; import '../widgets/task_widgets.dart'; +import '../widgets/priority_selector.dart'; +import '../widgets/tag_selector.dart'; class CreateTaskScreen extends StatefulWidget { const CreateTaskScreen({super.key}); @@ -11,8 +17,12 @@ class CreateTaskScreen extends StatefulWidget { } class _CreateTaskScreenState extends State { - final TextEditingController _nameController = TextEditingController(text: 'Team Meeting'); - final TextEditingController _descController = TextEditingController(text: 'Discuss all questions about new projects'); + final TextEditingController _nameController = TextEditingController( + text: 'Team Meeting', + ); + final TextEditingController _descController = TextEditingController( + text: 'Discuss all questions about new projects', + ); DateTime _selectedDate = DateTime.now(); TimeOfDay _startTime = const TimeOfDay(hour: 10, minute: 0); TimeOfDay _endTime = const TimeOfDay(hour: 11, minute: 0); @@ -28,15 +38,20 @@ class _CreateTaskScreenState extends State { body: SafeArea( child: Column( children: [ + // ─── Header ─────────────────────────────────────── Container( decoration: BoxDecoration( color: Theme.of(context).colorScheme.surface, borderRadius: const BorderRadius.only( - bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)), + bottomLeft: Radius.circular(30), + bottomRight: Radius.circular(30), + ), boxShadow: [ BoxShadow( - color: Colors.black.withValues(alpha: 0.05), - blurRadius: 10, offset: const Offset(0, 5)) + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, 5), + ), ], ), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15), @@ -61,17 +76,33 @@ class _CreateTaskScreenState extends State { ], ), ), + + // ─── Body ───────────────────────────────────────── Expanded( child: SingleChildScrollView( padding: const EdgeInsets.all(25.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Create New Task', style: Theme.of(context).textTheme.headlineMedium), + Text( + 'Create New Task', + style: Theme.of(context).textTheme.headlineMedium, + ), const SizedBox(height: 25), - CustomInputField(label: 'Task Name', hint: 'Enter task name', controller: _nameController), + + // Task Name + CustomInputField( + label: 'Task Name', + hint: 'Enter task name', + controller: _nameController, + ), const SizedBox(height: 20), - Text('Select Category', style: Theme.of(context).textTheme.labelLarge), + + // Category + Text( + 'Select Category', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 10), SizedBox( height: 40, @@ -79,7 +110,12 @@ class _CreateTaskScreenState extends State { scrollDirection: Axis.horizontal, itemCount: 4, itemBuilder: (context, index) { - List categories = ['Development', 'Research', 'Design', 'Backend']; + List categories = [ + 'Development', + 'Research', + 'Design', + 'Backend', + ]; bool isSelected = index == _selectedCategoryIndex; return Padding( padding: const EdgeInsets.only(right: 10), @@ -112,20 +148,38 @@ class _CreateTaskScreenState extends State { ), ), const SizedBox(height: 20), + + // ─── PRIORITY SELECTOR (MỚI) ────────────── + const PrioritySelector(), + const SizedBox(height: 20), + + // ─── TAG SELECTOR (MỚI) ─────────────────── + const TagSelector(), + const SizedBox(height: 20), + + // Date Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Date', style: Theme.of(context).textTheme.labelLarge), + Text( + 'Date', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), InkWell( onTap: () async { final DateTime? picked = await showDatePicker( - context: context, initialDate: _selectedDate, - firstDate: DateTime(2000), lastDate: DateTime(2100)); - if (picked != null) setState(() => _selectedDate = picked); + context: context, + initialDate: _selectedDate, + firstDate: DateTime(2000), + lastDate: DateTime(2100), + ); + if (picked != null) { + setState(() => _selectedDate = picked); + } }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -146,7 +200,7 @@ class _CreateTaskScreenState extends State { ) ], ), - ) + ), ], ), Container( @@ -160,15 +214,24 @@ class _CreateTaskScreenState extends State { ], ), const SizedBox(height: 25), + + // Time Row( children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Start time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'Start time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _startTime, onChanged: (newTime) => setState(() => _startTime = newTime)), + TimePickerWidget( + time: _startTime, + onChanged: (t) => + setState(() => _startTime = t), + ), ], ), ), @@ -177,27 +240,73 @@ class _CreateTaskScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('End time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'End time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _endTime, onChanged: (newTime) => setState(() => _endTime = newTime)), + TimePickerWidget( + time: _endTime, + onChanged: (t) => setState(() => _endTime = t), + ), ], ), ), ], ), const SizedBox(height: 25), - CustomInputField(label: 'Description', hint: 'Enter task description', controller: _descController, maxLines: 2), + + // Description + CustomInputField( + label: 'Description', + hint: 'Enter task description', + controller: _descController, + maxLines: 2, + ), const SizedBox(height: 40), + + // ─── Create Button ──────────────────────── Center( child: ElevatedButton( - onPressed: () {}, + onPressed: () { + final viewModel = context.read(); + final List categories = [ + 'Development', + 'Research', + 'Design', + 'Backend', + ]; + final newTask = TaskModel( + id: DateTime.now().millisecondsSinceEpoch + .toString(), + title: _nameController.text, + description: _descController.text, + category: categories[_selectedCategoryIndex], + startTime: _startTime, + endTime: _endTime, + date: _selectedDate, + priority: viewModel.selectedPriority, + tags: List.from(viewModel.selectedTags), + ); + viewModel.addTask(newTask); + viewModel.reset(); + Navigator.pop(context); + }, style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 15), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + padding: const EdgeInsets.symmetric( + horizontal: 100, + vertical: 15, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15), + ), + ), + child: const Text( + 'Create Task', + style: TextStyle(fontSize: 18), ), - child: const Text('Create Task', style: TextStyle(fontSize: 18)), ), ), ], @@ -209,4 +318,4 @@ class _CreateTaskScreenState extends State { ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/tasks/view/screens/home_screen.dart b/src/lib/features/tasks/view/screens/home_screen.dart index 0232c40..882458d 100644 --- a/src/lib/features/tasks/view/screens/home_screen.dart +++ b/src/lib/features/tasks/view/screens/home_screen.dart @@ -1,6 +1,9 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../../../core/theme/app_colors.dart'; import '../../model/task_model.dart'; +import '../../viewmodel/task_viewmodel.dart'; import '../widgets/task_widgets.dart'; import 'create_task_screen.dart'; @@ -10,46 +13,41 @@ class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { String formattedDate = DateFormat('EEEE, d MMMM').format(DateTime.now()); + final viewModel = context.watch(); final isDark = Theme.of(context).brightness == Brightness.dark; - // --- TẠO DỮ LIỆU GIẢ LẬP (MOCK DATA) --- - final task1 = TaskModel( - id: '1', // ID dùng để làm tag cho Hero Animation - title: 'Team Meeting', - description: 'Discuss all questions about new projects', - category: 'Development', - startTime: const TimeOfDay(hour: 10, minute: 0), - endTime: const TimeOfDay(hour: 11, minute: 0), - date: DateTime.now(), - ); - - final task2 = TaskModel( - id: '2', // ID phải khác nhau - title: 'Call the stylist', - description: 'Agree on an evening look', - category: 'Design', - startTime: const TimeOfDay(hour: 11, minute: 0), - endTime: const TimeOfDay(hour: 12, minute: 0), - date: DateTime.now(), - ); - // ---------------------------------------- + // Nhóm task theo priority + Map> grouped = {}; + for (var priority in Priority.values.reversed) { + final tasks = viewModel.tasks + .where((t) => t.priority == priority) + .toList(); + if (tasks.isNotEmpty) grouped[priority] = tasks; + } return Scaffold( body: Stack( children: [ Positioned( - top: 0, left: 0, right: 0, height: 250, + top: 0, + left: 0, + right: 0, + height: 250, child: ClipPath( clipper: TopWaveClipper(), - child: Container(color: Theme.of(context).colorScheme.primary), + child: Container(color: AppColors.primaryBlue), ), ), SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ + // ─── Header ─────────────────────────────────── Padding( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 10, + ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -70,7 +68,9 @@ class HomeScreen extends StatelessWidget { const SizedBox(width: 15), const CircleAvatar( radius: 20, - backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user1'), + backgroundImage: NetworkImage( + 'https://i.pravatar.cc/150?u=user1', + ), ), const SizedBox(width: 10), IconButton( @@ -87,7 +87,8 @@ class HomeScreen extends StatelessWidget { ], ), ), - const SizedBox(height: 10), + + // ─── Date Card ──────────────────────────────── Container( width: double.infinity, margin: const EdgeInsets.symmetric(horizontal: 20), @@ -103,7 +104,10 @@ class HomeScreen extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('My Task', style: Theme.of(context).textTheme.headlineMedium), + Text( + 'My Task', + style: Theme.of(context).textTheme.headlineMedium, + ), const SizedBox(height: 5), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -125,8 +129,13 @@ class HomeScreen extends StatelessWidget { scrollDirection: Axis.horizontal, itemCount: 10, itemBuilder: (context, index) { - DateTime date = DateTime.now().add(Duration(days: index)); - return DateBox(date: date, isSelected: index == 0); + DateTime date = DateTime.now().add( + Duration(days: index), + ); + return DateBox( + date: date, + isSelected: index == 0, + ); }, ), ), @@ -134,11 +143,40 @@ class HomeScreen extends StatelessWidget { ), ), ), - const SizedBox(height: 25), - Expanded( - child: ListView( - padding: const EdgeInsets.symmetric(horizontal: 20), + const SizedBox(height: 15), + + // ─── Filter Bar ─────────────────────────────── + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Row( children: [ + // Sort button + GestureDetector( + onTap: () => viewModel.toggleSortByPriority(), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 7, + ), + decoration: BoxDecoration( + color: viewModel.sortByPriority + ? AppColors.primaryBlue + : Colors.white, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: AppColors.primaryBlue, + width: 1, + ), + ), + child: Row( + children: [ + Icon( + Icons.sort, + size: 16, + color: viewModel.sortByPriority + ? Colors.white + : AppColors.primaryBlue, // --- SỬ DỤNG MOCK DATA VÀO TASKCARD --- TaskCard( task: task1, // Truyền task1 vào đây @@ -161,30 +199,138 @@ class HomeScreen extends StatelessWidget { color: Theme.of(context).colorScheme.primary, ), ), - ) - ], + const SizedBox(width: 5), + Text( + 'Sort', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: viewModel.sortByPriority + ? Colors.white + : AppColors.primaryBlue, + ), + ), + ], + ), ), ), - TaskCard( - task: task2, // Truyền task2 vào đây - leading: Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: isDark - ? Theme.of(context).colorScheme.surfaceContainerHighest - : const Color(0xFFF1F7FD), - borderRadius: BorderRadius.circular(15), - ), - child: Icon( - Icons.call_outlined, - color: Theme.of(context).colorScheme.primary, + const SizedBox(width: 8), + + // Filter theo priority + Expanded( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + // Chip "All" + _FilterChip( + label: 'All', + isSelected: viewModel.filterPriority == null, + color: AppColors.primaryBlue, + onTap: () => viewModel.setFilterPriority(null), + ), + const SizedBox(width: 8), + // Chip cho từng priority + ...Priority.values.map( + (p) => Padding( + padding: const EdgeInsets.only(right: 8), + child: _FilterChip( + label: p.label, + isSelected: viewModel.filterPriority == p, + color: p.color, + onTap: () => viewModel.setFilterPriority(p), + ), + ), + ), + ], ), ), ), - // ---------------------------------------- ], ), ), + const SizedBox(height: 10), + + // ─── Task List nhóm theo Priority ───────────── + Expanded( + child: grouped.isEmpty + ? _buildEmptyState() + : ListView( + padding: const EdgeInsets.symmetric(horizontal: 20), + children: grouped.entries.map((entry) { + final priority = entry.key; + final tasks = entry.value; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header nhóm + Padding( + padding: const EdgeInsets.only( + bottom: 10, + top: 5, + ), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Container( + width: 4, + height: 20, + decoration: BoxDecoration( + color: priority.color, + borderRadius: + BorderRadius.circular(2), + ), + ), + const SizedBox(width: 8), + Text( + _priorityGroupLabel(priority), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + Text( + '${tasks.length} task', + style: const TextStyle( + fontSize: 12, + color: AppColors.grayText, + ), + ), + ], + ), + ), + + // Danh sách task trong nhóm + ...tasks.map( + (task) => TaskCard( + task: task, + leading: Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: priority.color.withValues( + alpha: 0.1, + ), + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + priority.icon, + color: priority.color, + size: 22, + ), + ), + ), + ), + const SizedBox(height: 10), + ], + ); + }).toList(), + ), + ), ], ), ), @@ -192,4 +338,81 @@ class HomeScreen extends StatelessWidget { ), ); } -} \ No newline at end of file + + String _priorityGroupLabel(Priority priority) { + switch (priority) { + case Priority.urgent: + return 'Ưu tiên Khẩn cấp'; + case Priority.high: + return 'Ưu tiên Cao'; + case Priority.medium: + return 'Ưu tiên Trung bình'; + case Priority.low: + return 'Ưu tiên Thấp'; + } + } + + Widget _buildEmptyState() { + return const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.checklist_rounded, size: 60, color: AppColors.grayText), + SizedBox(height: 12), + Text( + 'Chưa có task nào', + style: TextStyle( + fontSize: 16, + color: AppColors.grayText, + fontWeight: FontWeight.w500, + ), + ), + SizedBox(height: 4), + Text( + 'Nhấn + để tạo task mới', + style: TextStyle(fontSize: 13, color: AppColors.grayText), + ), + ], + ), + ); + } +} + +// ─── Filter Chip Widget ────────────────────────────────────── +class _FilterChip extends StatelessWidget { + final String label; + final bool isSelected; + final Color color; + final VoidCallback onTap; + + const _FilterChip({ + required this.label, + required this.isSelected, + required this.color, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7), + decoration: BoxDecoration( + color: isSelected ? color : Colors.white, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: color, width: 1), + ), + child: Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: isSelected ? Colors.white : color, + ), + ), + ), + ); + } +} diff --git a/src/lib/features/tasks/view/widgets/priority_selector.dart b/src/lib/features/tasks/view/widgets/priority_selector.dart new file mode 100644 index 0000000..3beee4b --- /dev/null +++ b/src/lib/features/tasks/view/widgets/priority_selector.dart @@ -0,0 +1,65 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../model/task_model.dart'; +import '../../viewmodel/task_viewmodel.dart'; + +class PrioritySelector extends StatelessWidget { + const PrioritySelector({super.key}); + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Priority', style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 10), + Row( + children: Priority.values.map((priority) { + final isSelected = viewModel.selectedPriority == priority; + return Expanded( + child: Padding( + padding: const EdgeInsets.only(right: 8), + child: GestureDetector( + onTap: () => viewModel.setPriority(priority), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(vertical: 10), + decoration: BoxDecoration( + color: isSelected + ? priority.color + : const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: isSelected ? priority.color : Colors.transparent, + ), + ), + child: Column( + children: [ + Icon( + priority.icon, + color: isSelected ? Colors.white : priority.color, + size: 20, + ), + const SizedBox(height: 4), + Text( + priority.label, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: isSelected ? Colors.white : priority.color, + ), + ), + ], + ), + ), + ), + ), + ); + }).toList(), + ), + ], + ); + } +} diff --git a/src/lib/features/tasks/view/widgets/tag_selector.dart b/src/lib/features/tasks/view/widgets/tag_selector.dart new file mode 100644 index 0000000..0ac54be --- /dev/null +++ b/src/lib/features/tasks/view/widgets/tag_selector.dart @@ -0,0 +1,60 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../../viewmodel/task_viewmodel.dart'; + +class TagSelector extends StatelessWidget { + const TagSelector({super.key}); + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Tags', style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 8, + children: viewModel.availableTags.map((tag) { + final isSelected = viewModel.isTagSelected(tag); + return GestureDetector( + onTap: () => viewModel.toggleTag(tag), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + decoration: BoxDecoration( + color: isSelected + ? tag.color + : tag.color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon(Icons.check, color: Colors.white, size: 14), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected ? Colors.white : tag.color, + ), + ), + ], + ), + ), + ); + }).toList(), + ), + ], + ); + } +} diff --git a/src/lib/features/tasks/viewmodel/task_viewmodel.dart b/src/lib/features/tasks/viewmodel/task_viewmodel.dart new file mode 100644 index 0000000..0917473 --- /dev/null +++ b/src/lib/features/tasks/viewmodel/task_viewmodel.dart @@ -0,0 +1,106 @@ +import 'package:flutter/material.dart'; +import '../model/task_model.dart'; + +class TaskViewModel extends ChangeNotifier { + // ─── Danh sách tag có sẵn + final List availableTags = [ + TagModel(id: 'work', name: 'Work', color: const Color(0xFF2196F3)), + TagModel(id: 'study', name: 'Study', color: const Color(0xFF9C27B0)), + TagModel(id: 'personal', name: 'Personal', color: const Color(0xFF4CAF50)), + TagModel(id: 'project', name: 'Project', color: const Color(0xFFFF9800)), + ]; + + // ─── State khi đang tạo task + Priority _selectedPriority = Priority.medium; + final List _selectedTags = []; + + Priority get selectedPriority => _selectedPriority; + List get selectedTags => List.unmodifiable(_selectedTags); + + void setPriority(Priority priority) { + _selectedPriority = priority; + notifyListeners(); + } + + void toggleTag(TagModel tag) { + if (_selectedTags.any((t) => t.id == tag.id)) { + _selectedTags.removeWhere((t) => t.id == tag.id); + } else { + _selectedTags.add(tag); + } + notifyListeners(); + } + + bool isTagSelected(TagModel tag) => _selectedTags.any((t) => t.id == tag.id); + + void reset() { + _selectedPriority = Priority.medium; + _selectedTags.clear(); + notifyListeners(); + } + + // ─── Danh sách task + filter/sort ──────────────────────── + final List _tasks = []; + + List get tasks => _getFilteredAndSorted(); + + Priority? _filterPriority; + String? _filterTagId; + bool _sortByPriority = false; + + Priority? get filterPriority => _filterPriority; + String? get filterTagId => _filterTagId; + bool get sortByPriority => _sortByPriority; + + void setFilterPriority(Priority? priority) { + _filterPriority = priority; + notifyListeners(); + } + + void setFilterTag(String? tagId) { + _filterTagId = tagId; + notifyListeners(); + } + + void toggleSortByPriority() { + _sortByPriority = !_sortByPriority; + notifyListeners(); + } + + void addTask(TaskModel task) { + _tasks.add(task); + notifyListeners(); + } + + List _getFilteredAndSorted() { + List result = List.from(_tasks); + + // Lọc theo priority + if (_filterPriority != null) { + result = result.where((t) => t.priority == _filterPriority).toList(); + } + + // Lọc theo tag + if (_filterTagId != null) { + result = result + .where((t) => t.tags.any((tag) => tag.id == _filterTagId)) + .toList(); + } + + // Sắp xếp theo priority (urgent → high → medium → low) + if (_sortByPriority) { + const order = [ + Priority.urgent, + Priority.high, + Priority.medium, + Priority.low, + ]; + result.sort( + (a, b) => + order.indexOf(a.priority).compareTo(order.indexOf(b.priority)), + ); + } + + return result; + } +} diff --git a/src/lib/main.dart b/src/lib/main.dart index bcdb6be..c97c2fc 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -7,6 +7,8 @@ import 'package:task_management_app/features/main/view/screens/main_screen.dart' import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; +import 'package:provider/provider.dart'; +import 'features/tasks/viewmodel/task_viewmodel.dart'; import 'core/theme/theme_provider.dart'; @@ -14,6 +16,7 @@ import 'core/theme/theme_provider.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); + // Tải cấu hình từ file .env await dotenv.load(fileName: ".env"); String supabaseUrl = dotenv.env['SUPABASE_URL'] ?? ''; @@ -23,11 +26,7 @@ Future main() async { debugPrint('Error: SUPABASE_URL or SUPABASE_ANON_KEY is missing'); } - // 3. Khởi tạo kết nối Supabase - await Supabase.initialize( - url: supabaseUrl, - anonKey: supabaseAnonKey, - ); + await Supabase.initialize(url: supabaseUrl, anonKey: supabaseAnonKey); SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle(statusBarColor: Colors.transparent)); @@ -39,11 +38,8 @@ Future main() async { child: const TaskApp())); } -// 4. Create a global variable for ViewModel to call API quickly final supabase = Supabase.instance.client; - - class TaskApp extends StatelessWidget { const TaskApp({super.key}); @@ -59,4 +55,4 @@ class TaskApp extends StatelessWidget { debugShowCheckedModeBanner: false, ); } -} \ No newline at end of file +} From 5b59d35cd71cd183dd0e9adaa8cf5b484689596a Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Thu, 9 Apr 2026 22:17:58 +0700 Subject: [PATCH 3/9] Update README.md (#32) --- README.md | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 2cd5439..905bc91 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,25 @@ -## 📁 Chi tiết các file thay đổi +# Task Management App - Life Organizer -* **`task_model.dart`**: Thêm thuộc tính `Priority` và tích hợp `TagModel`. -* **`task_viewmodel.dart`**: Cập nhật logic xử lý trạng thái cho Provider. -* **`priority_selector.dart`**: Thêm UI Widget hỗ trợ chọn mức độ ưu tiên. -* **`tag_selector.dart`**: Thêm UI Widget hỗ trợ chọn các loại tag. -* **`create_task_screen.dart`**: Tích hợp 2 widget chọn Priority và Tag vào form tạo nhiệm vụ. -* **`main.dart`**: Đăng ký Provider mới cho hệ thống. -* **`home_screen.dart`**: Cập nhật giao diện, hiển thị danh sách task được nhóm theo mức độ ưu tiên. +## 1. Introduction +This repository contains the source code for the **Task Management App (Life Organizer)**, developed as a project for the **SE346** course at the University of Information Technology - VNUHCM (UIT). -image +Going beyond a traditional to-do list, this application is designed to be a comprehensive personal assistant. It helps users easily organize various life contexts, such as tracking utility bills, managing grocery shopping lists, building daily habits, and handling household chores efficiently. + +## 2. Authors +This project is built and maintained by a dedicated team of 4 members: +* [Trần Quang Hạ](https://github.com/tqha1011) +* [Nguyễn Lê Hoàng Hảo](https://github.com/hoanghaoz) +* [Nguyễn Anh Kiệt](https://github.com/anhkietbienhoa-crypto) +* [Nguyễn Trí Kiệt](https://github.com/Ender-Via) + +## 3. Tech Stack +The application is built with a focus on performance, security, and clean code principles, strictly following the **Feature-Based MVVM** architecture: +* **Frontend:** Flutter +* **Backend & Database:** Supabase (PostgreSQL, Auth, Row Level Security) +* **Code Quality & CI/CD:** GitHub Actions, SonarCloud + +## 4. Documentation +For a deeper dive into our system design and development workflows, please explore the attached documentation: +* [Flutter App Architecture](documentation/architecture/flutter-architecture.md) +* [Database Schema & ERD](documentation/architecture/database-schema.md) +* [Git & Conventional Commits Guidelines](documentation/guidelines/conventional-commit.md) From ae8e44cbb5319da7f354160e2d4eb957e25a8c60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Anh=20Ki=E1=BB=87t?= Date: Fri, 10 Apr 2026 09:44:52 +0700 Subject: [PATCH 4/9] feat: Priority selector and tag system verson2 (#33) * feat(task): implement priority and tag selection features in task creation * feat(tags): enhance tag management with custom tag creation and selection * Update README.md * Update README.md --- .../tasks/view/screens/home_screen.dart | 21 -- .../view/screens/task_detail_screen.dart | 228 +++++++++++++--- .../tasks/view/widgets/tag_selector.dart | 251 +++++++++++++++--- .../tasks/viewmodel/task_viewmodel.dart | 125 ++++++++- 4 files changed, 525 insertions(+), 100 deletions(-) diff --git a/src/lib/features/tasks/view/screens/home_screen.dart b/src/lib/features/tasks/view/screens/home_screen.dart index 882458d..f7702e3 100644 --- a/src/lib/features/tasks/view/screens/home_screen.dart +++ b/src/lib/features/tasks/view/screens/home_screen.dart @@ -177,27 +177,6 @@ class HomeScreen extends StatelessWidget { color: viewModel.sortByPriority ? Colors.white : AppColors.primaryBlue, - // --- SỬ DỤNG MOCK DATA VÀO TASKCARD --- - TaskCard( - task: task1, // Truyền task1 vào đây - leading: Stack( - children: [ - const CircleAvatar(radius: 15, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user2')), - const Positioned(left: 10, child: CircleAvatar(radius: 15, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user3'))), - const Positioned(left: 20, child: CircleAvatar(radius: 15, backgroundImage: NetworkImage('https://i.pravatar.cc/150?u=user4'))), - Positioned( - left: 30, - child: Container( - padding: const EdgeInsets.all(4), - decoration: BoxDecoration( - color: Theme.of(context).colorScheme.surface, - shape: BoxShape.circle, - ), - child: Icon( - Icons.add_rounded, - size: 20, - color: Theme.of(context).colorScheme.primary, - ), ), const SizedBox(width: 5), Text( diff --git a/src/lib/features/tasks/view/screens/task_detail_screen.dart b/src/lib/features/tasks/view/screens/task_detail_screen.dart index aa81264..fd2f832 100644 --- a/src/lib/features/tasks/view/screens/task_detail_screen.dart +++ b/src/lib/features/tasks/view/screens/task_detail_screen.dart @@ -1,12 +1,14 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; +import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; -import '../widgets/task_widgets.dart'; // Contains TimePickerWidget +import '../../viewmodel/task_viewmodel.dart'; +import '../widgets/task_widgets.dart'; class TaskDetailScreen extends StatefulWidget { final TaskModel task; - const TaskDetailScreen({super.key, required this.task}); @override @@ -19,50 +21,60 @@ class _TaskDetailScreenState extends State { late TimeOfDay _startTime; late TimeOfDay _endTime; late String _currentCategory; + late List _currentTags; @override void initState() { super.initState(); - // Initialize state variables with services from the passed task object _titleController = TextEditingController(text: widget.task.title); _descController = TextEditingController(text: widget.task.description); _startTime = widget.task.startTime; _endTime = widget.task.endTime; _currentCategory = widget.task.category; + _currentTags = List.from(widget.task.tags); } @override void dispose() { - // Dispose controllers to prevent memory leaks _titleController.dispose(); _descController.dispose(); super.dispose(); } + void _toggleTag(TagModel tag) { + setState(() { + if (_currentTags.any((t) => t.id == tag.id)) { + _currentTags.removeWhere((t) => t.id == tag.id); + } else { + _currentTags.add(tag); + } + }); + } + + bool _isTagSelected(TagModel tag) => _currentTags.any((t) => t.id == tag.id); + void _saveChanges() { - // Update the local model - // (Note: Later, this will call TaskViewModel -> TaskService -> your ASP.NET Core API to update the database) widget.task.title = _titleController.text; widget.task.description = _descController.text; widget.task.startTime = _startTime; widget.task.endTime = _endTime; widget.task.category = _currentCategory; - // Show success message + // Lưu tags mới vào task qua ViewModel + context.read().updateTaskTags(widget.task.id, _currentTags); + ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: const Text('Task updated successfully!'), backgroundColor: Theme.of(context).colorScheme.tertiary, ), ); - - // Return to the previous screen Navigator.pop(context); } @override Widget build(BuildContext context) { - // Format date for display + final viewModel = context.watch(); String formattedDate = DateFormat('EEEE, d MMMM').format(widget.task.date); final isDark = Theme.of(context).brightness == Brightness.dark; @@ -92,8 +104,8 @@ class _TaskDetailScreenState extends State { ), body: SafeArea( child: Hero( - tag: 'task_card_${widget.task.id}', // Must match the Hero tag in the Home/Statistics screen - child: Material( // Required inside Hero to prevent yellow underline text rendering issues + tag: 'task_card_${widget.task.id}', + child: Material( type: MaterialType.transparency, child: Container( margin: const EdgeInsets.all(20), @@ -104,7 +116,11 @@ class _TaskDetailScreenState extends State { ? Border.all(color: Theme.of(context).colorScheme.outline) : null, boxShadow: [ - BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 10, offset: const Offset(0, 5)) + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, 5), + ), ], ), child: SingleChildScrollView( @@ -112,28 +128,39 @@ class _TaskDetailScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - // Input for Task Name - CustomInputField(label: 'Task Name', hint: '', controller: _titleController), + // Task Name + CustomInputField( + label: 'Task Name', + hint: '', + controller: _titleController, + ), const SizedBox(height: 20), - Text('Category Tag', style: Theme.of(context).textTheme.labelLarge), + // Category + Text( + 'Category Tag', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 10), - - // Horizontal list of Category chips SizedBox( height: 40, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: categories.length, itemBuilder: (context, index) { - bool isSelected = categories[index] == _currentCategory; + bool isSelected = + categories[index] == _currentCategory; return Padding( padding: const EdgeInsets.only(right: 10), child: ChoiceChip( label: Text(categories[index]), selected: isSelected, onSelected: (selected) { - if (selected) setState(() => _currentCategory = categories[index]); + if (selected) { + setState( + () => _currentCategory = categories[index], + ); + } }, backgroundColor: isDark ? Theme.of(context).colorScheme.surfaceContainerHighest @@ -161,7 +188,7 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 25), - // Display Task Date + // Date Text('Date', style: Theme.of(context).textTheme.labelLarge), const SizedBox(height: 5), Text( @@ -174,16 +201,131 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 25), - // Time Pickers for Start and End time + // ─── Time Tags ──────────────────────────── + Text( + 'Thời gian', + style: Theme.of(context).textTheme.labelLarge, + ), + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 8, + children: viewModel.timeTags.map((tag) { + final isSelected = _isTagSelected(tag); + return GestureDetector( + onTap: () => _toggleTag(tag), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + decoration: BoxDecoration( + color: isSelected + ? tag.color + : tag.color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon( + Icons.check, + color: Colors.white, + size: 14, + ), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected + ? Colors.white + : tag.color, + ), + ), + ], + ), + ), + ); + }).toList(), + ), + const SizedBox(height: 20), + + // ─── Status Tags ────────────────────────── + Text( + 'Trạng thái', + style: Theme.of(context).textTheme.labelLarge, + ), + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 8, + children: viewModel.statusTags.map((tag) { + final isSelected = _isTagSelected(tag); + return GestureDetector( + onTap: () => _toggleTag(tag), + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + decoration: BoxDecoration( + color: isSelected + ? tag.color + : tag.color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon( + Icons.check, + color: Colors.white, + size: 14, + ), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected + ? Colors.white + : tag.color, + ), + ), + ], + ), + ), + ); + }).toList(), + ), + const SizedBox(height: 25), + + // Time Pickers Row( children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Start time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'Start time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _startTime, onChanged: (newTime) => setState(() => _startTime = newTime)), + TimePickerWidget( + time: _startTime, + onChanged: (t) => + setState(() => _startTime = t), + ), ], ), ), @@ -192,9 +334,15 @@ class _TaskDetailScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('End time', style: Theme.of(context).textTheme.labelLarge), + Text( + 'End time', + style: Theme.of(context).textTheme.labelLarge, + ), const SizedBox(height: 5), - TimePickerWidget(time: _endTime, onChanged: (newTime) => setState(() => _endTime = newTime)), + TimePickerWidget( + time: _endTime, + onChanged: (t) => setState(() => _endTime = t), + ), ], ), ), @@ -202,8 +350,13 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 25), - // Input for Description - CustomInputField(label: 'Description', hint: '', controller: _descController, maxLines: 3), + // Description + CustomInputField( + label: 'Description', + hint: '', + controller: _descController, + maxLines: 3, + ), const SizedBox(height: 40), // Save Button @@ -213,11 +366,22 @@ class _TaskDetailScreenState extends State { style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, - padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), + padding: const EdgeInsets.symmetric( + horizontal: 50, + vertical: 15, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(15), + ), minimumSize: const Size(double.infinity, 50), ), - child: const Text('Save Changes', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + child: const Text( + 'Save Changes', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), ), ), ], @@ -229,4 +393,4 @@ class _TaskDetailScreenState extends State { ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/tasks/view/widgets/tag_selector.dart b/src/lib/features/tasks/view/widgets/tag_selector.dart index 0ac54be..71c15b0 100644 --- a/src/lib/features/tasks/view/widgets/tag_selector.dart +++ b/src/lib/features/tasks/view/widgets/tag_selector.dart @@ -1,10 +1,62 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../../model/task_model.dart'; import '../../viewmodel/task_viewmodel.dart'; -class TagSelector extends StatelessWidget { +class TagSelector extends StatefulWidget { const TagSelector({super.key}); + @override + State createState() => _TagSelectorState(); +} + +class _TagSelectorState extends State { + final TextEditingController _customController = TextEditingController(); + + @override + void dispose() { + _customController.dispose(); + super.dispose(); + } + + void _showAddCustomDialog(BuildContext context, TaskViewModel viewModel) { + _customController.clear(); + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('Tạo tag mới'), + content: TextField( + controller: _customController, + maxLength: 12, + decoration: const InputDecoration( + hintText: 'Tên tag (tối đa 12 ký tự)', + border: OutlineInputBorder(), + ), + autofocus: true, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Huỷ'), + ), + ElevatedButton( + onPressed: () { + final error = viewModel.addCustomTag(_customController.text); + if (error != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(error), backgroundColor: Colors.red), + ); + } else { + Navigator.pop(context); + } + }, + child: const Text('Thêm'), + ), + ], + ), + ); + } + @override Widget build(BuildContext context) { final viewModel = context.watch(); @@ -13,48 +65,173 @@ class TagSelector extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Tags', style: Theme.of(context).textTheme.labelLarge), - const SizedBox(height: 10), + const SizedBox(height: 12), + + // ─── Nhóm 1: Loại công việc ─────────────────────── + _buildTagGroup( + label: 'Loại công việc', + tags: viewModel.workTypeTags, + viewModel: viewModel, + ), + const SizedBox(height: 12), + + // ─── Nhóm 2: Thời gian ──────────────────────────── + _buildTagGroup( + label: 'Thời gian', + tags: viewModel.timeTags, + viewModel: viewModel, + ), + const SizedBox(height: 12), + + // ─── Nhóm 3: Trạng thái ─────────────────────────── + _buildTagGroup( + label: 'Trạng thái', + tags: viewModel.statusTags, + viewModel: viewModel, + ), + const SizedBox(height: 12), + + // ─── Nhóm 4: Custom ─────────────────────────────── + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Custom', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Colors.black54, + ), + ), + // Nút thêm tag mới + if (viewModel.customTags.length < 5) + GestureDetector( + onTap: () => _showAddCustomDialog(context, viewModel), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 4, + ), + decoration: BoxDecoration( + color: const Color(0xFFF1F7FD), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Colors.blue.shade200), + ), + child: const Row( + children: [ + Icon(Icons.add, size: 14, color: Colors.blue), + SizedBox(width: 3), + Text( + 'Tạo tag', + style: TextStyle(fontSize: 12, color: Colors.blue), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 8), + + // Hiển thị custom tags đã tạo + viewModel.customTags.isEmpty + ? const Text( + 'Chưa có tag custom. Nhấn "Tạo tag" để thêm.', + style: TextStyle(fontSize: 12, color: Colors.black38), + ) + : Wrap( + spacing: 8, + runSpacing: 8, + children: viewModel.customTags + .map( + (tag) => _TagChip( + tag: tag, + isSelected: viewModel.isTagSelected(tag), + onTap: () => viewModel.toggleTag(tag), + ), + ) + .toList(), + ), + ], + ); + } + + Widget _buildTagGroup({ + required String label, + required List tags, + required TaskViewModel viewModel, + }) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Colors.black54, + ), + ), + const SizedBox(height: 6), Wrap( spacing: 8, runSpacing: 8, - children: viewModel.availableTags.map((tag) { - final isSelected = viewModel.isTagSelected(tag); - return GestureDetector( - onTap: () => viewModel.toggleTag(tag), - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - padding: const EdgeInsets.symmetric( - horizontal: 14, - vertical: 8, - ), - decoration: BoxDecoration( - color: isSelected - ? tag.color - : tag.color.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (isSelected) ...[ - const Icon(Icons.check, color: Colors.white, size: 14), - const SizedBox(width: 4), - ], - Text( - tag.name, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - color: isSelected ? Colors.white : tag.color, - ), - ), - ], + children: tags + .map( + (tag) => _TagChip( + tag: tag, + isSelected: viewModel.isTagSelected(tag), + onTap: () => viewModel.toggleTag(tag), ), - ), - ); - }).toList(), + ) + .toList(), ), ], ); } } + +// ─── Tag Chip Widget ───────────────────────────────────────── +class _TagChip extends StatelessWidget { + final TagModel tag; + final bool isSelected; + final VoidCallback onTap; + + const _TagChip({ + required this.tag, + required this.isSelected, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: isSelected ? tag.color : tag.color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon(Icons.check, color: Colors.white, size: 14), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected ? Colors.white : tag.color, + ), + ), + ], + ), + ), + ); + } +} diff --git a/src/lib/features/tasks/viewmodel/task_viewmodel.dart b/src/lib/features/tasks/viewmodel/task_viewmodel.dart index 0917473..347d2bc 100644 --- a/src/lib/features/tasks/viewmodel/task_viewmodel.dart +++ b/src/lib/features/tasks/viewmodel/task_viewmodel.dart @@ -1,16 +1,118 @@ +import 'dart:convert'; import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../model/task_model.dart'; class TaskViewModel extends ChangeNotifier { - // ─── Danh sách tag có sẵn - final List availableTags = [ + final List workTypeTags = [ TagModel(id: 'work', name: 'Work', color: const Color(0xFF2196F3)), TagModel(id: 'study', name: 'Study', color: const Color(0xFF9C27B0)), TagModel(id: 'personal', name: 'Personal', color: const Color(0xFF4CAF50)), TagModel(id: 'project', name: 'Project', color: const Color(0xFFFF9800)), ]; - // ─── State khi đang tạo task + final List timeTags = [ + TagModel(id: 'today', name: 'Today', color: const Color(0xFF00BCD4)), + TagModel(id: 'tomorrow', name: 'Tomorrow', color: const Color(0xFF3F51B5)), + TagModel( + id: 'this_week', + name: 'This Week', + color: const Color(0xFF009688), + ), + TagModel(id: 'later', name: 'Later', color: const Color(0xFF607D8B)), + ]; + + final List statusTags = [ + TagModel(id: 'pending', name: 'Pending', color: const Color(0xFFFF9800)), + TagModel( + id: 'in_progress', + name: 'In Progress', + color: const Color(0xFF2196F3), + ), + TagModel( + id: 'completed', + name: 'Completed', + color: const Color(0xFF4CAF50), + ), + TagModel( + id: 'cancelled', + name: 'Cancelled', + color: const Color(0xFF9E9E9E), + ), + ]; + + // ─── Custom Tags (lưu SharedPreferences) ──────────────── + List _customTags = []; + List get customTags => List.unmodifiable(_customTags); + + static const _customTagsKey = 'custom_tags'; + static const _maxCustomTags = 5; + static const _maxCustomTagLength = 12; + + TaskViewModel() { + _loadCustomTags(); + } + + Future _loadCustomTags() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_customTagsKey); + if (raw != null) { + final List decoded = jsonDecode(raw); + _customTags = decoded + .map( + (e) => TagModel( + id: e['id'], + name: e['name'], + color: Color(e['color']), + ), + ) + .toList(); + notifyListeners(); + } + } + + Future _saveCustomTags() async { + final prefs = await SharedPreferences.getInstance(); + final encoded = jsonEncode( + _customTags + .map((t) => {'id': t.id, 'name': t.name, 'color': t.color.toARGB32()}) + .toList(), + ); + await prefs.setString(_customTagsKey, encoded); + } + + // Trả về lỗi nếu có, null nếu thành công + String? addCustomTag(String name) { + name = name.trim(); + if (name.isEmpty) return 'Tên tag không được để trống'; + if (name.length > _maxCustomTagLength) + return 'Tối đa $_maxCustomTagLength ký tự'; + if (_customTags.length >= _maxCustomTags) + return 'Tối đa $_maxCustomTags tag custom'; + if (_customTags.any((t) => t.name.toLowerCase() == name.toLowerCase())) { + return 'Tag đã tồn tại'; + } + _customTags.add( + TagModel( + id: 'custom_${DateTime.now().millisecondsSinceEpoch}', + name: name, + color: _customTagColors[_customTags.length % _customTagColors.length], + ), + ); + _saveCustomTags(); + notifyListeners(); + return null; + } + + final List _customTagColors = const [ + Color(0xFFE91E63), + Color(0xFF673AB7), + Color(0xFF795548), + Color(0xFF009688), + Color(0xFFFF5722), + ]; + + // ─── State tạo task ───────────────────────────────────── Priority _selectedPriority = Priority.medium; final List _selectedTags = []; @@ -39,9 +141,8 @@ class TaskViewModel extends ChangeNotifier { notifyListeners(); } - // ─── Danh sách task + filter/sort ──────────────────────── + // ─── Task list + filter/sort ───────────────────────────── final List _tasks = []; - List get tasks => _getFilteredAndSorted(); Priority? _filterPriority; @@ -72,15 +173,20 @@ class TaskViewModel extends ChangeNotifier { notifyListeners(); } + // Cập nhật tag cho task đã tạo (dùng ở Task Detail) + void updateTaskTags(String taskId, List newTags) { + final index = _tasks.indexWhere((t) => t.id == taskId); + if (index != -1) { + _tasks[index].tags = newTags; + notifyListeners(); + } + } + List _getFilteredAndSorted() { List result = List.from(_tasks); - - // Lọc theo priority if (_filterPriority != null) { result = result.where((t) => t.priority == _filterPriority).toList(); } - - // Lọc theo tag if (_filterTagId != null) { result = result .where((t) => t.tags.any((tag) => tag.id == _filterTagId)) @@ -100,7 +206,6 @@ class TaskViewModel extends ChangeNotifier { order.indexOf(a.priority).compareTo(order.indexOf(b.priority)), ); } - return result; } } From 7a7788872dd3954067d4e9ec50f92f1cfb68ec59 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Fri, 10 Apr 2026 09:55:57 +0700 Subject: [PATCH 5/9] fix: error screen in main.dart (#34) --- .../statistics/model/StatisticsModel.dart | 4 ++-- .../features/tasks/view/screens/home_screen.dart | 15 ++------------- src/lib/main.dart | 9 +++++---- 3 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/lib/features/statistics/model/StatisticsModel.dart b/src/lib/features/statistics/model/StatisticsModel.dart index b6376e4..1e2a720 100644 --- a/src/lib/features/statistics/model/StatisticsModel.dart +++ b/src/lib/features/statistics/model/StatisticsModel.dart @@ -42,7 +42,7 @@ class UserStatisticsModel { final int thisWeekTotal; final double growthPercentage; final List recentTasks; - final List dailyCounts; // <--- THÊM DÒNG NÀY (Hứng mảng 7 ngày) + final List dailyCounts; UserStatisticsModel({ required this.today, @@ -50,7 +50,7 @@ class UserStatisticsModel { required this.thisWeekTotal, required this.growthPercentage, required this.recentTasks, - required this.dailyCounts, // <--- Cập nhật constructor + required this.dailyCounts, }); factory UserStatisticsModel.fromJson(Map json) { diff --git a/src/lib/features/tasks/view/screens/home_screen.dart b/src/lib/features/tasks/view/screens/home_screen.dart index f7702e3..7a9f9b0 100644 --- a/src/lib/features/tasks/view/screens/home_screen.dart +++ b/src/lib/features/tasks/view/screens/home_screen.dart @@ -178,20 +178,9 @@ class HomeScreen extends StatelessWidget { ? Colors.white : AppColors.primaryBlue, ), - const SizedBox(width: 5), - Text( - 'Sort', - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: viewModel.sortByPriority - ? Colors.white - : AppColors.primaryBlue, - ), - ), - ], + ] ), - ), + ) ), const SizedBox(width: 8), diff --git a/src/lib/main.dart b/src/lib/main.dart index c97c2fc..1ab3077 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -2,13 +2,11 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:task_management_app/features/auth/presentation/view/auth_gate.dart'; -import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; import 'package:task_management_app/features/main/view/screens/main_screen.dart'; +import 'package:task_management_app/features/tasks/viewmodel/task_viewmodel.dart'; import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; -import 'package:provider/provider.dart'; -import 'features/tasks/viewmodel/task_viewmodel.dart'; import 'core/theme/theme_provider.dart'; @@ -34,6 +32,9 @@ Future main() async { MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => ThemeProvider()), + ChangeNotifierProvider( + create: (_) => TaskViewModel(), + ), ], child: const TaskApp())); } @@ -51,7 +52,7 @@ class TaskApp extends StatelessWidget { themeMode: themeProvider.themeMode, theme: AppTheme.lightTheme, // Bộ màu sáng ông vừa map xong darkTheme: AppTheme.darkTheme, - home: const MainScreen(), + home: const AuthGate(), debugShowCheckedModeBanner: false, ); } From 986a56d058eb51470aee3fcaf5c07d80170c5da2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20L=C3=AA=20Ho=C3=A0ng=20H=E1=BA=A3o?= Date: Sun, 12 Apr 2026 18:41:28 +0700 Subject: [PATCH 6/9] Enhance authentication UI and implement Focus feature set (#35) * feat(core): add auth layout template, custom textfield and colors * feat(auth): implement viewmodels for auth flow (MVVM) * feat(auth): build complete auth UI screens (Login, Register, OTP, Passwords) * chore(main): set LoginView as initial route * refactor(auth) : delete .gitkeep * chore: update dependencies and pubspec.lock * refactor(auth): optimize registration logic, timezone handling, and form validation * feat(auth): update UI for login, registration, and forgot password screens * feat(tasks): update task management UI and statistics screen * chore: update main entry point and fix widget tests * chore: ignore devtools_options.yaml * chore: ignore devtools_options.yaml * style(login) : rewrite title for login view * feat(auth): configure android deep link for supabase oauth * refactor(ui): add social login callbacks to auth layout template * feat(auth): update oauth methods with redirect url and signout * feat(auth): implement AuthGate using StreamBuilder for session tracking * feat(viewmodel): add oauth logic and improve provider lifecycle * refactor(ui): migrate LoginView to Provider pattern * chore(main): set AuthGate as initial route and setup provider * feat: implement full Focus feature set - Added Pomodoro timer with Start/Reset/Skip logic. - Integrated local Quick Notes with Pin/Delete functionality. - Supported image attachments in notes using image_picker. - Added Focus settings: time duration, vibration, and ringtones. * fix (auth) : dispose TextEditingControllers to prevent memory leaks * refactor (alarm ) : create off alarm button when time out * fix: apply CodeRabbit auto-fixes Fixed 3 file(s) based on 4 unresolved review comments. Co-authored-by: CodeRabbit * fix(timer): prevent division by zero in progress calculation and sanitize negative settings input * fix(timer): prevent division by zero in progress calculation and sanitize negative settings input * fix(auth): unblock new-user login and add settings logout * refactor(LoginScreen) : compact all items to fit in screen to help users interface easily --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: CodeRabbit --- src/lib/core/theme/auth_layout_template.dart | 108 ++++++++++-------- .../auth/presentation/view/login_view.dart | 14 ++- .../auth/presentation/view/register_view.dart | 9 +- 3 files changed, 71 insertions(+), 60 deletions(-) diff --git a/src/lib/core/theme/auth_layout_template.dart b/src/lib/core/theme/auth_layout_template.dart index e001784..3146fc2 100644 --- a/src/lib/core/theme/auth_layout_template.dart +++ b/src/lib/core/theme/auth_layout_template.dart @@ -15,6 +15,7 @@ class AuthLayoutTemplate extends StatelessWidget { final Widget? footerContent; final VoidCallback? onGoogleTap; // Login with Google final VoidCallback? onFacebookTap; // Login with Facebook + final bool compactMode; const AuthLayoutTemplate({ super.key, @@ -30,6 +31,7 @@ class AuthLayoutTemplate extends StatelessWidget { this.footerContent, this.onGoogleTap, this.onFacebookTap, + this.compactMode = false, }); @override @@ -61,48 +63,54 @@ class AuthLayoutTemplate extends StatelessWidget { ) : null, ), - body: Container( - decoration: BoxDecoration( - gradient: isDark - ? const LinearGradient( - begin: Alignment.topCenter, - end: Alignment.bottomCenter, - colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], - ) - : null, - ), - child: SafeArea( - child: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.fromLTRB(24.0, 16.0, 24.0, 48.0), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - _buildHeader(context), - const SizedBox(height: 32), - useCard - ? _buildCardContainer(context) - : _buildTransparentContainer(context), - const SizedBox(height: 32), - if (footerContent != null) footerContent!, - ], + body: LayoutBuilder( + builder: (context, constraints) { + final isCompact = compactMode || constraints.maxHeight <= 780; + + return Container( + decoration: BoxDecoration( + gradient: isDark + ? const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [Color(0xFF08142D), Color(0xFF0B1A38), Color(0xFF0A1834)], + ) + : null, + ), + child: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: EdgeInsets.fromLTRB(20.0, isCompact ? 8.0 : 16.0, 20.0, isCompact ? 16.0 : 36.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _buildHeader(context, isCompact), + SizedBox(height: isCompact ? 16 : 28), + useCard + ? _buildCardContainer(context, isCompact) + : _buildTransparentContainer(context, isCompact), + SizedBox(height: isCompact ? 12 : 24), + if (footerContent != null) footerContent!, + ], + ), + ), ), ), - ), - ), + ); + }, ), ); } - Widget _buildHeader(BuildContext context) { + Widget _buildHeader(BuildContext context, bool isCompact) { final isDark = Theme.of(context).brightness == Brightness.dark; return Column( children: [ customHeaderIcon ?? Container( - width: 80, - height: 80, + width: isCompact ? 64 : 80, + height: isCompact ? 64 : 80, decoration: BoxDecoration( color: isDark ? const Color(0xFF1E2B47) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(24), @@ -117,26 +125,26 @@ class AuthLayoutTemplate extends StatelessWidget { child: Center( child: Icon( Icons.task_alt, - size: 48, + size: isCompact ? 36 : 48, color: Theme.of(context).colorScheme.primary, ), ), ), - const SizedBox(height: 24), + SizedBox(height: isCompact ? 12 : 24), Text( title, style: TextStyle( - fontSize: 28, + fontSize: isCompact ? 24 : 28, fontWeight: FontWeight.w800, color: Theme.of(context).colorScheme.onSurface, letterSpacing: -0.5, ), ), - const SizedBox(height: 8), + SizedBox(height: isCompact ? 4 : 8), Text( subtitle, style: TextStyle( - fontSize: 14, + fontSize: isCompact ? 13 : 14, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurfaceVariant, ), @@ -146,11 +154,11 @@ class AuthLayoutTemplate extends StatelessWidget { ); } - Widget _buildCardContainer(BuildContext context) { + Widget _buildCardContainer(BuildContext context, bool isCompact) { final isDark = Theme.of(context).brightness == Brightness.dark; return Container( - padding: const EdgeInsets.all(32), + padding: EdgeInsets.all(isCompact ? 20 : 32), decoration: BoxDecoration( color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(32), @@ -163,21 +171,21 @@ class AuthLayoutTemplate extends StatelessWidget { ), ], ), - child: _buildFormElements(context), + child: _buildFormElements(context, isCompact), ); } - Widget _buildTransparentContainer(BuildContext context) => - _buildFormElements(context); + Widget _buildTransparentContainer(BuildContext context, bool isCompact) => + _buildFormElements(context, isCompact); - Widget _buildFormElements(BuildContext context) { + Widget _buildFormElements(BuildContext context, bool isCompact) { final isDark = Theme.of(context).brightness == Brightness.dark; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ formContent, - const SizedBox(height: 16), + SizedBox(height: isCompact ? 12 : 16), ElevatedButton( // Disable button if loading onPressed: isLoading ? null : onSubmit, @@ -185,7 +193,7 @@ class AuthLayoutTemplate extends StatelessWidget { backgroundColor: Theme.of(context).colorScheme.primary, disabledBackgroundColor: Theme.of(context).colorScheme.primary.withValues(alpha: 0.6), - padding: const EdgeInsets.symmetric(vertical: 20), + padding: EdgeInsets.symmetric(vertical: isCompact ? 14 : 20), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), @@ -209,7 +217,7 @@ class AuthLayoutTemplate extends StatelessWidget { Text( submitText, style: TextStyle( - fontSize: 16, + fontSize: isCompact ? 15 : 16, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.surface, ), @@ -224,14 +232,14 @@ class AuthLayoutTemplate extends StatelessWidget { ), ), if (showSocial) ...[ - const SizedBox(height: 32), + SizedBox(height: isCompact ? 16 : 32), Row( children: [ Expanded( child: Divider(color: Theme.of(context).colorScheme.outline), ), Padding( - padding: EdgeInsets.symmetric(horizontal: 16), + padding: EdgeInsets.symmetric(horizontal: isCompact ? 12 : 16), child: Text( 'OR', style: TextStyle( @@ -246,7 +254,7 @@ class AuthLayoutTemplate extends StatelessWidget { ), ], ), - const SizedBox(height: 24), + SizedBox(height: isCompact ? 12 : 24), Row( children: [ Expanded( @@ -259,7 +267,7 @@ class AuthLayoutTemplate extends StatelessWidget { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), - padding: const EdgeInsets.symmetric(vertical: 14), + padding: EdgeInsets.symmetric(vertical: isCompact ? 10 : 14), ), onPressed: onGoogleTap, icon: const Icon( @@ -270,7 +278,7 @@ class AuthLayoutTemplate extends StatelessWidget { label: const Text('Google'), ), ), - const SizedBox(width: 16), + SizedBox(width: isCompact ? 10 : 16), Expanded( child: OutlinedButton.icon( style: OutlinedButton.styleFrom( @@ -281,7 +289,7 @@ class AuthLayoutTemplate extends StatelessWidget { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), - padding: const EdgeInsets.symmetric(vertical: 14), + padding: EdgeInsets.symmetric(vertical: isCompact ? 10 : 14), ), onPressed: onFacebookTap, icon: const Icon(Icons.facebook, color: Color(0xFF1877F2)), diff --git a/src/lib/features/auth/presentation/view/login_view.dart b/src/lib/features/auth/presentation/view/login_view.dart index 7807b4f..c315fd9 100644 --- a/src/lib/features/auth/presentation/view/login_view.dart +++ b/src/lib/features/auth/presentation/view/login_view.dart @@ -22,6 +22,7 @@ class _LoginViewState extends State { title: 'Task Management', subtitle: 'Chào mừng trở lại!', submitText: 'Đăng nhập', + compactMode: true, isLoading: _vm.isLoading, showSocial: true, onGoogleTap: () async { @@ -79,6 +80,7 @@ class _LoginViewState extends State { ), TextButton( onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const ForgotPasswordView())), + style: TextButton.styleFrom(minimumSize: const Size(50, 40), padding: const EdgeInsets.symmetric(horizontal: 4)), child: Text( 'Quên mật khẩu?', style: TextStyle( @@ -94,8 +96,8 @@ class _LoginViewState extends State { 'Chưa có tài khoản? ', 'Đăng ký ngay', () { - Navigator.push(context, MaterialPageRoute(builder: (_) => const RegisterView())); - }, + Navigator.push(context, MaterialPageRoute(builder: (_) => const RegisterView())); + }, ), ), ); @@ -108,7 +110,7 @@ class _LoginViewState extends State { VoidCallback onTap, ) { return Padding( - padding: const EdgeInsets.only(bottom: 24.0), + padding: const EdgeInsets.only(bottom: 14.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ @@ -116,18 +118,18 @@ class _LoginViewState extends State { text, style: TextStyle( color: Theme.of(context).colorScheme.onSurfaceVariant, - fontSize: 16, + fontSize: 15, ), ), TextButton( onPressed: onTap, - style: TextButton.styleFrom(minimumSize: const Size(50, 48)), + style: TextButton.styleFrom(minimumSize: const Size(50, 40)), child: Text( action, style: TextStyle( color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.bold, - fontSize: 16, + fontSize: 15, ), ), ), diff --git a/src/lib/features/auth/presentation/view/register_view.dart b/src/lib/features/auth/presentation/view/register_view.dart index ddc3556..d5125d7 100644 --- a/src/lib/features/auth/presentation/view/register_view.dart +++ b/src/lib/features/auth/presentation/view/register_view.dart @@ -21,6 +21,7 @@ class _RegisterViewState extends State { title: 'Tạo tài khoản mới', subtitle: 'Bắt đầu quản lý công việc khoa học', submitText: 'Đăng ký', + compactMode: true, isLoading: _vm.isLoading, showSocial: true, onSubmit: () async { @@ -61,7 +62,7 @@ class _RegisterViewState extends State { ], ), footerContent: Padding( - padding: const EdgeInsets.only(bottom: 24.0), + padding: const EdgeInsets.only(bottom: 14.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ @@ -69,18 +70,18 @@ class _RegisterViewState extends State { 'Đã có tài khoản? ', style: TextStyle( color: Theme.of(context).colorScheme.onSurfaceVariant, - fontSize: 16, + fontSize: 15, ), ), TextButton( onPressed: () => Navigator.pop(context), - style: TextButton.styleFrom(minimumSize: const Size(50, 48)), + style: TextButton.styleFrom(minimumSize: const Size(50, 40)), child: Text( 'Đăng nhập', style: TextStyle( color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.bold, - fontSize: 16, + fontSize: 15, ), ), ), From c0755d9da8d3e0986d160cef800bdd97220cac2e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 13 Apr 2026 14:46:41 +0700 Subject: [PATCH 7/9] build(deps)(deps): bump shared_preferences from 2.5.4 to 2.5.5 in /src (#36) Bumps [shared_preferences](https://github.com/flutter/packages/tree/main/packages/shared_preferences) from 2.5.4 to 2.5.5. - [Commits](https://github.com/flutter/packages/commits/shared_preferences-v2.5.5/packages/shared_preferences) --- updated-dependencies: - dependency-name: shared_preferences dependency-version: 2.5.5 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- src/pubspec.lock | 20 ++++++++++---------- src/pubspec.yaml | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/pubspec.lock b/src/pubspec.lock index 1b845aa..7a21b3a 100644 --- a/src/pubspec.lock +++ b/src/pubspec.lock @@ -53,10 +53,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" clock: dependency: transitive description: @@ -420,18 +420,18 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.19" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: @@ -604,10 +604,10 @@ packages: dependency: "direct main" description: name: shared_preferences - sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf url: "https://pub.dev" source: hosted - version: "2.5.4" + version: "2.5.5" shared_preferences_android: dependency: transitive description: @@ -729,10 +729,10 @@ packages: dependency: transitive description: name: test_api - sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" url: "https://pub.dev" source: hosted - version: "0.7.7" + version: "0.7.10" typed_data: dependency: transitive description: diff --git a/src/pubspec.yaml b/src/pubspec.yaml index 65c8e9c..fa7e071 100644 --- a/src/pubspec.yaml +++ b/src/pubspec.yaml @@ -41,7 +41,7 @@ dependencies: provider: ^6.1.5+1 flutter_ringtone_player: ^4.0.0+4 image_picker: ^1.2.1 - shared_preferences: ^2.2.2 + shared_preferences: ^2.5.5 dev_dependencies: flutter_test: From c4b702b05a2b0c10b764cf312419f6279009a8d5 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Fri, 17 Apr 2026 20:59:37 +0700 Subject: [PATCH 8/9] Feature/user profile (#37) * feat(UserProfile): build screen UserProfile # Conflicts: # src/lib/features/main/view/screens/main_screen.dart * feat: switch dark/light theme * fix: black color theme * fix: black theme in statistics screen * feat: add dark theme to auth screen * feat: apply dark theme for bottom navigation bar * feat(RPC): update RPC to get data for heatmap * feat(RPC): update new RPC to get data for heatmap * feat: integrate chatbot assistant * feat(chatbot): integrate create task, answer question for chatbot * feat: remove mock data and get data tags and categories from supabase --- .../core/utils/adaptive_color_extension.dart | 11 + .../category/model/category_model.dart | 52 ++++ .../repository/category_repository.dart | 26 ++ .../view/widgets/category_choice_chips.dart | 58 +++++ .../viewmodel/category_viewmodel.dart | 41 +++ .../chatbot/model/chatmessage_model.dart | 46 ++++ .../chatbot/services/chatbot_services.dart | 116 +++++++++ .../features/chatbot/view/chatbot_view.dart | 133 ++++++++++ .../chatbot/view/widgets/bot_avatar.dart | 28 +++ .../chatbot/view/widgets/chat_header.dart | 46 ++++ .../chatbot/view/widgets/day_separator.dart | 29 +++ .../view/widgets/message_composer.dart | 92 +++++++ .../chatbot/view/widgets/message_tile.dart | 122 +++++++++ .../view/widgets/typing_indicator.dart | 33 +++ .../chatbot/view/widgets/user_avatar.dart | 47 ++++ .../chatbot/viewmodel/chatbot_viewmodel.dart | 90 +++++++ .../main/view/screens/main_screen.dart | 71 ++++-- .../view/screens/statistics_screen.dart | 5 + .../view/widgets/statistics_widgets.dart | 176 ++++++++++--- src/lib/features/tag/model/tag_model.dart | 52 ++++ .../tag/repository/tag_repository.dart | 45 ++++ .../tag/view/widgets/tag_selector.dart | 194 +++++++++++++++ .../features/tag/viewmodel/tag_viewmodel.dart | 113 +++++++++ src/lib/features/tasks/model/task_model.dart | 14 +- .../view/screens/create_task_screen.dart | 105 ++++---- .../view/screens/task_detail_screen.dart | 146 +++-------- .../tasks/view/widgets/tag_selector.dart | 233 +----------------- .../tasks/viewmodel/task_viewmodel.dart | 128 +--------- .../user/model/user_profile_model.dart | 43 +++- .../features/user/service/user_service.dart | 7 + .../features/user/view/user_profile_view.dart | 120 +++++++-- .../viewmodel/user_profile_viewmodel.dart | 34 ++- src/lib/main.dart | 9 + src/pubspec.lock | 32 ++- src/pubspec.yaml | 4 +- ...20260409084009_create_user_profile_rpc.sql | 2 +- ...1_update_user_profile_with_heatmap_rpc.sql | 66 +++++ .../20260417060333_chatbot_add_task_rpc.sql | 52 ++++ 38 files changed, 1995 insertions(+), 626 deletions(-) create mode 100644 src/lib/core/utils/adaptive_color_extension.dart create mode 100644 src/lib/features/category/model/category_model.dart create mode 100644 src/lib/features/category/repository/category_repository.dart create mode 100644 src/lib/features/category/view/widgets/category_choice_chips.dart create mode 100644 src/lib/features/category/viewmodel/category_viewmodel.dart create mode 100644 src/lib/features/chatbot/model/chatmessage_model.dart create mode 100644 src/lib/features/chatbot/services/chatbot_services.dart create mode 100644 src/lib/features/chatbot/view/chatbot_view.dart create mode 100644 src/lib/features/chatbot/view/widgets/bot_avatar.dart create mode 100644 src/lib/features/chatbot/view/widgets/chat_header.dart create mode 100644 src/lib/features/chatbot/view/widgets/day_separator.dart create mode 100644 src/lib/features/chatbot/view/widgets/message_composer.dart create mode 100644 src/lib/features/chatbot/view/widgets/message_tile.dart create mode 100644 src/lib/features/chatbot/view/widgets/typing_indicator.dart create mode 100644 src/lib/features/chatbot/view/widgets/user_avatar.dart create mode 100644 src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart create mode 100644 src/lib/features/tag/model/tag_model.dart create mode 100644 src/lib/features/tag/repository/tag_repository.dart create mode 100644 src/lib/features/tag/view/widgets/tag_selector.dart create mode 100644 src/lib/features/tag/viewmodel/tag_viewmodel.dart create mode 100644 supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql create mode 100644 supabase/migrations/20260417060333_chatbot_add_task_rpc.sql diff --git a/src/lib/core/utils/adaptive_color_extension.dart b/src/lib/core/utils/adaptive_color_extension.dart new file mode 100644 index 0000000..f5c022e --- /dev/null +++ b/src/lib/core/utils/adaptive_color_extension.dart @@ -0,0 +1,11 @@ +import 'package:flutter/material.dart'; + +extension AdaptiveColorExtension on Color { + Color toAdaptiveColor(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + if (!isDark) return this; + + return Color.lerp(this, Colors.white, 0.4) ?? this; + } +} + diff --git a/src/lib/features/category/model/category_model.dart b/src/lib/features/category/model/category_model.dart new file mode 100644 index 0000000..7bcef4f --- /dev/null +++ b/src/lib/features/category/model/category_model.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +class CategoryModel { + final int id; + final String name; + final String colorCode; + final String profileId; + + const CategoryModel({ + required this.id, + required this.name, + required this.colorCode, + required this.profileId, + }); + + Color get color => _parseHexColor(colorCode); + + factory CategoryModel.fromJson(Map json) { + return CategoryModel( + id: (json['id'] as num?)?.toInt() ?? 0, + name: json['name']?.toString() ?? '', + colorCode: json['color_code']?.toString() ?? '#5A8DF3', + profileId: json['profile_id']?.toString() ?? '', + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'color_code': colorCode, + 'profile_id': profileId, + }; + } + + static Color _parseHexColor(String value) { + var hex = value.trim().replaceFirst('#', ''); + if (hex.length == 6) { + hex = 'FF$hex'; + } + if (hex.length != 8) { + return const Color(0xFF5A8DF3); + } + + final parsed = int.tryParse(hex, radix: 16); + if (parsed == null) { + return const Color(0xFF5A8DF3); + } + return Color(parsed); + } +} + diff --git a/src/lib/features/category/repository/category_repository.dart b/src/lib/features/category/repository/category_repository.dart new file mode 100644 index 0000000..cbfeb93 --- /dev/null +++ b/src/lib/features/category/repository/category_repository.dart @@ -0,0 +1,26 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/category_model.dart'; + +class CategoryRepository { + final SupabaseClient _client; + + CategoryRepository({SupabaseClient? client}) + : _client = client ?? Supabase.instance.client; + + Future> fetchCategories() async { + final user = _client.auth.currentUser; + if (user == null) return []; + + final rows = await _client + .from('category') + .select('id, name, color_code, profile_id') + .eq('profile_id', user.id) + .order('name'); + + return (rows as List) + .map((e) => CategoryModel.fromJson(Map.from(e))) + .toList(); + } +} + diff --git a/src/lib/features/category/view/widgets/category_choice_chips.dart b/src/lib/features/category/view/widgets/category_choice_chips.dart new file mode 100644 index 0000000..e9ecf26 --- /dev/null +++ b/src/lib/features/category/view/widgets/category_choice_chips.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; + +import '../../model/category_model.dart'; + +class CategoryChoiceChips extends StatelessWidget { + const CategoryChoiceChips({ + super.key, + required this.categories, + required this.selectedCategoryId, + required this.onSelected, + }); + + final List categories; + final int? selectedCategoryId; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 40, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: categories.length, + itemBuilder: (context, index) { + final category = categories[index]; + final adaptiveColor = category.color.toAdaptiveColor(context); + final isSelected = category.id == selectedCategoryId; + return Padding( + padding: const EdgeInsets.only(right: 10), + child: ChoiceChip( + label: Text(category.name), + selected: isSelected, + onSelected: (selected) { + if (selected) onSelected(category); + }, + backgroundColor: adaptiveColor.withValues(alpha: 0.15), + selectedColor: adaptiveColor, + labelStyle: TextStyle( + color: isSelected ? Colors.white : adaptiveColor, + fontSize: 14, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + side: BorderSide( + color: adaptiveColor.withValues(alpha: 0.4), + width: 1, + ), + ), + showCheckmark: false, + ), + ); + }, + ), + ); + } +} + diff --git a/src/lib/features/category/viewmodel/category_viewmodel.dart b/src/lib/features/category/viewmodel/category_viewmodel.dart new file mode 100644 index 0000000..c9e1dc0 --- /dev/null +++ b/src/lib/features/category/viewmodel/category_viewmodel.dart @@ -0,0 +1,41 @@ +import 'package:flutter/foundation.dart'; + +import '../model/category_model.dart'; +import '../repository/category_repository.dart'; + +class CategoryViewModel extends ChangeNotifier { + final CategoryRepository _repository; + + CategoryViewModel({CategoryRepository? repository}) + : _repository = repository ?? CategoryRepository(); + + final List _categories = []; + + List get categories => List.unmodifiable(_categories); + + bool _isLoading = false; + bool get isLoading => _isLoading; + + String? _error; + String? get error => _error; + + Future loadCategories() async { + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final data = await _repository.fetchCategories(); + _categories + ..clear() + ..addAll(data); + } catch (e) { + _error = e.toString(); + _categories.clear(); + } finally { + _isLoading = false; + notifyListeners(); + } + } +} + diff --git a/src/lib/features/chatbot/model/chatmessage_model.dart b/src/lib/features/chatbot/model/chatmessage_model.dart new file mode 100644 index 0000000..2fb31ae --- /dev/null +++ b/src/lib/features/chatbot/model/chatmessage_model.dart @@ -0,0 +1,46 @@ +import 'dart:convert'; + +class ChatMessageModel { + final String text; + final bool isUser; + final DateTime timestamp; + + ChatMessageModel({ + required this.text, + required this.isUser, + DateTime? timestamp, + }) : timestamp = timestamp ?? DateTime.now(); + + factory ChatMessageModel.fromJson(Map json) { + final parsedTimestamp = + DateTime.tryParse(json['timestamp']?.toString() ?? '') ?? DateTime.now(); + + return ChatMessageModel( + text: json['text']?.toString() ?? '', + isUser: json['isUser'] as bool? ?? true, + timestamp: parsedTimestamp, + ); + } + + Map toJson() { + return { + 'text': text, + 'isUser': isUser, + 'timestamp': timestamp.toIso8601String(), + }; + } + + static String encodeList(List messages) { + return jsonEncode(messages.map((message) => message.toJson()).toList()); + } + + static List decodeList(String raw) { + final decoded = jsonDecode(raw); + if (decoded is! List) return []; + + return decoded + .whereType() + .map((item) => ChatMessageModel.fromJson(Map.from(item))) + .toList(); + } +} diff --git a/src/lib/features/chatbot/services/chatbot_services.dart b/src/lib/features/chatbot/services/chatbot_services.dart new file mode 100644 index 0000000..70a4f78 --- /dev/null +++ b/src/lib/features/chatbot/services/chatbot_services.dart @@ -0,0 +1,116 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:google_generative_ai/google_generative_ai.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class ChatBotAssistantService { + final String _apiKey = (dotenv.env['GEMINI_API_KEY'] ?? '').trim(); + GenerativeModel? _model; + ChatSession? _chatSession; + + ChatBotAssistantService() { + if (_apiKey.isEmpty) { + debugPrint("Forget to set GEMINI_API_KEY in .env file"); + return; + } + + _model = GenerativeModel( + apiKey: _apiKey, + model: 'gemini-2.5-flash', + tools: [ + Tool( + functionDeclarations: [ + FunctionDeclaration( + 'create_task_full', + 'Tạo một công việc mới. Hãy tự động trích xuất tên công việc, suy luận độ ưu tiên (1-Thấp, 2-Trung bình, 3-Cao) và các thẻ (tags) dựa trên câu nói của người dùng.', + Schema( + SchemaType.object, + properties: { + 'title': Schema( + SchemaType.string, + description: 'Tên công việc cần làm', + ), + 'priority': Schema( + SchemaType.integer, + description: + 'Độ ưu tiên: 1 (Thấp), 2 (Trung bình), 3 (Cao). Nếu người dùng không nói rõ, mặc định là 1.', + ), + 'tags': Schema( + SchemaType.array, + items: Schema(SchemaType.string), + description: + 'Danh sách các thẻ phân loại (ví dụ: ["Học tập", "Gấp", "Backend"]). Gửi mảng rỗng [] nếu không có.', + ), + }, + requiredProperties: ['title', 'priority', 'tags'], + ), + ), + ], + ), + ], + systemInstruction: Content.system( + 'Bạn là một chuyên gia quản lý thời gian và trợ lý năng suất cho ứng dụng Task Management. ' + 'Nhiệm vụ của bạn là đưa ra lời khuyên ngắn gọn (dưới 100 chữ), thực tế để giúp người dùng ' + 'hoàn thành công việc. Trả lời bằng tiếng Việt thân thiện, nhiệt tình. ' + 'Từ chối mọi câu hỏi không liên quan đến công việc hoặc quản lý thời gian.', + ), + ); + + _chatSession = _model!.startChat(); + } + + Future sendMessage(String userMessage) async { + if (_chatSession == null) { + return 'Chatbot chưa được cấu hình API key. Vui lòng kiểm tra file .env.'; + } + + try { + final response = await _chatSession!.sendMessage( + Content.text(userMessage), + ); + + if (response.functionCalls.isNotEmpty) { + final functionCall = response.functionCalls.first; + if (functionCall.name == 'create_task_full') { + final args = functionCall.args; + final title = args['title'] as String; + final priority = (args['priority'] as num?)?.toInt() ?? 1; + final rawTags = args['tags'] as List? ?? []; + final tags = rawTags.map((e) => e.toString()).toList(); + + final userId = Supabase.instance.client.auth.currentUser?.id; + if (userId == null) { + return 'Vui lòng đăng nhập để tạo công việc.'; + } + + final dbResponse = await Supabase.instance.client.rpc( + 'create_task_full', + params: { + 'p_title': title, + 'p_priority': priority, + 'p_profile_id': userId, + 'p_tag_names': tags, + }, + ); + + final isSuccess = dbResponse['success'] == true; + final functionResponse = await _chatSession!.sendMessage( + Content.functionResponse('create_task_full', { + 'status': isSuccess ? 'Thành công' : 'Thất bại', + }), + ); + return functionResponse.text ?? 'Đã xử lý xong yêu cầu của bạn!'; + } + } + return response.text ?? 'Xin lỗi, trợ lý đang bận xíu. Thử lại sau nhé!'; + } catch (e) { + final errorString = e.toString(); + if (errorString.contains('503')) { + return 'Bạn đợi vài phút rồi chat lại nhé!'; + } else if (errorString.contains('429')) { + return 'Bạn chat nhanh quá! Vui lòng chờ chút'; + } + return 'Lỗi kết nối AI: $e'; + } + } +} diff --git a/src/lib/features/chatbot/view/chatbot_view.dart b/src/lib/features/chatbot/view/chatbot_view.dart new file mode 100644 index 0000000..f5e104a --- /dev/null +++ b/src/lib/features/chatbot/view/chatbot_view.dart @@ -0,0 +1,133 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/chat_header.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/day_separator.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/message_composer.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/message_tile.dart'; +import 'package:task_management_app/features/chatbot/view/widgets/typing_indicator.dart'; + +import '../viewmodel/chatbot_viewmodel.dart'; + +class ChatBotView extends StatelessWidget { + const ChatBotView({super.key, this.userAvatarUrl}); + + final String? userAvatarUrl; + + @override + Widget build(BuildContext context) { + return ChangeNotifierProvider( + create: (_) => ChatBotViewModel(), + child: _ChatBotViewBody(userAvatarUrl: userAvatarUrl), + ); + } +} + +class _ChatBotViewBody extends StatefulWidget { + const _ChatBotViewBody({this.userAvatarUrl}); + + final String? userAvatarUrl; + + @override + State<_ChatBotViewBody> createState() => _ChatBotViewBodyState(); +} + +class _ChatBotViewBodyState extends State<_ChatBotViewBody> { + final TextEditingController _controller = TextEditingController(); + final ScrollController _scrollController = ScrollController(); + + void _scrollToBottom() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_scrollController.hasClients) { + _scrollController.animateTo( + _scrollController.position.maxScrollExtent, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOut, + ); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + _scrollController.dispose(); + super.dispose(); + } + + Future _sendMessage(ChatBotViewModel viewModel) async { + final text = _controller.text.trim(); + if (text.isEmpty || viewModel.isLoading) return; + + _controller.clear(); + _scrollToBottom(); + + await viewModel.sendMessage(text); + if (!mounted) return; + + _scrollToBottom(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Scaffold( + backgroundColor: theme.scaffoldBackgroundColor, + body: SafeArea( + child: Column( + children: [ + const ChatHeader(), + Divider(height: 1, color: scheme.outline.withValues(alpha: 0.4)), + Expanded( + child: Consumer( + builder: (context, viewModel, _) { + return ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 14, + ), + itemCount: viewModel.messages.length + 1, + itemBuilder: (context, index) { + if (index == 0) { + return const Padding( + padding: EdgeInsets.only(bottom: 16), + child: DaySeparator(label: 'Today'), + ); + } + + final message = viewModel.messages[index - 1]; + return MessageTile( + message: message, + userAvatarUrl: widget.userAvatarUrl, + ); + }, + ); + }, + ), + ), + Consumer( + builder: (context, viewModel, _) { + if (!viewModel.isLoading) return const SizedBox.shrink(); + return const Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 12), + child: TypingIndicator(), + ); + }, + ), + Consumer( + builder: (context, viewModel, _) { + return MessageComposer( + controller: _controller, + isSending: viewModel.isLoading, + onSend: () => _sendMessage(viewModel), + ); + }, + ), + ], + ), + ), + ); + } +} diff --git a/src/lib/features/chatbot/view/widgets/bot_avatar.dart b/src/lib/features/chatbot/view/widgets/bot_avatar.dart new file mode 100644 index 0000000..d689144 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/bot_avatar.dart @@ -0,0 +1,28 @@ +import 'package:flutter/material.dart'; + +class BotAvatar extends StatelessWidget { + const BotAvatar({super.key, required this.size}); + + final double size; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + + return Container( + width: size, + height: size, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: scheme.surfaceContainerHighest, + ), + alignment: Alignment.center, + child: Icon( + Icons.smart_toy_rounded, + size: size * 0.58, + color: scheme.primary, + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/chat_header.dart b/src/lib/features/chatbot/view/widgets/chat_header.dart new file mode 100644 index 0000000..35e83ff --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/chat_header.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +import 'bot_avatar.dart'; + +class ChatHeader extends StatelessWidget { + const ChatHeader({super.key}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 10), + child: Row( + children: [ + const BotAvatar(size: 48), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'TaskBot', + style: theme.textTheme.headlineSmall?.copyWith( + color: scheme.primary, + fontWeight: FontWeight.w800, + ), + ), + Text( + 'ONLINE AI ASSISTANT', + style: theme.textTheme.labelLarge?.copyWith( + color: scheme.tertiary, + letterSpacing: 0.6, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ], + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/day_separator.dart b/src/lib/features/chatbot/view/widgets/day_separator.dart new file mode 100644 index 0000000..351c129 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/day_separator.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; + +class DaySeparator extends StatelessWidget { + const DaySeparator({super.key, required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + label, + style: TextStyle( + color: scheme.onSurfaceVariant, + fontWeight: FontWeight.w600, + ), + ), + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/message_composer.dart b/src/lib/features/chatbot/view/widgets/message_composer.dart new file mode 100644 index 0000000..7b4988f --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/message_composer.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; + +class MessageComposer extends StatelessWidget { + const MessageComposer({ + super.key, + required this.controller, + required this.onSend, + required this.isSending, + }); + + final TextEditingController controller; + final VoidCallback onSend; + final bool isSending; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + + return SafeArea( + minimum: const EdgeInsets.fromLTRB(16, 0, 16, 14), + child: Container( + decoration: BoxDecoration( + color: scheme.surface, + borderRadius: BorderRadius.circular(22), + boxShadow: [ + BoxShadow( + color: scheme.shadow.withValues(alpha: 0.14), + blurRadius: 14, + offset: const Offset(0, 4), + ), + ], + ), + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), + child: Row( + children: [ + IconButton( + constraints: const BoxConstraints.tightFor(width: 40, height: 40), + padding: EdgeInsets.zero, + onPressed: () {}, + icon: Icon(Icons.add_circle, color: scheme.onSurfaceVariant), + ), + const SizedBox(width: 6), + Expanded( + child: TextField( + controller: controller, + textInputAction: TextInputAction.send, + enabled: !isSending, + onSubmitted: (_) => onSend(), + style: TextStyle(color: scheme.onSurface), + decoration: InputDecoration( + hintText: 'Type a message or ask for help...', + hintStyle: TextStyle(color: scheme.onSurfaceVariant), + border: InputBorder.none, + ), + ), + ), + IconButton( + constraints: const BoxConstraints.tightFor(width: 40, height: 40), + padding: EdgeInsets.zero, + onPressed: () {}, + icon: Icon(Icons.mic, color: scheme.onSurfaceVariant), + ), + const SizedBox(width: 6), + SizedBox( + width: 44, + height: 44, + child: ElevatedButton( + onPressed: isSending ? null : onSend, + style: ElevatedButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + padding: EdgeInsets.zero, + backgroundColor: scheme.primary, + foregroundColor: scheme.onPrimary, + ), + child: Icon( + Icons.send_rounded, + color: isSending + ? scheme.onPrimary.withValues(alpha: 0.7) + : scheme.onPrimary, + ), + ), + ), + ], + ), + ), + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/message_tile.dart b/src/lib/features/chatbot/view/widgets/message_tile.dart new file mode 100644 index 0000000..74546a2 --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/message_tile.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; + +import '../../model/chatmessage_model.dart'; +import 'bot_avatar.dart'; +import 'user_avatar.dart'; + +class MessageTile extends StatelessWidget { + const MessageTile({super.key, required this.message, this.userAvatarUrl}); + + final ChatMessageModel message; + final String? userAvatarUrl; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final isUser = message.isUser; + final crossAxis = isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start; + + return Padding( + padding: const EdgeInsets.only(bottom: 14), + child: LayoutBuilder( + builder: (context, constraints) { + final maxBubbleWidth = constraints.maxWidth * 0.72; + + Widget bubble() { + return ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxBubbleWidth), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + decoration: BoxDecoration( + color: isUser ? scheme.primary : scheme.surface, + borderRadius: BorderRadius.circular(20), + boxShadow: [ + BoxShadow( + color: scheme.shadow.withValues(alpha: 0.12), + blurRadius: 10, + offset: const Offset(0, 3), + ), + ], + ), + child: Text( + _breakLongTokens(message.text), + softWrap: true, + style: theme.textTheme.titleMedium?.copyWith( + height: 1.45, + color: isUser ? scheme.onPrimary : scheme.onSurface, + ), + ), + ), + ); + } + + return Column( + crossAxisAlignment: crossAxis, + children: [ + if (isUser) + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Align( + alignment: Alignment.centerRight, + child: bubble(), + ), + ), + const SizedBox(width: 10), + UserAvatar(size: 36, avatarUrl: userAvatarUrl), + ], + ) + else + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const BotAvatar(size: 36), + const SizedBox(width: 10), + Expanded( + child: Align( + alignment: Alignment.centerLeft, + child: bubble(), + ), + ), + ], + ), + const SizedBox(height: 6), + Padding( + padding: EdgeInsets.only(left: isUser ? 0 : 46, right: isUser ? 46 : 0), + child: Text( + _formatTime(context, message.timestamp), + style: theme.textTheme.bodyMedium?.copyWith( + color: scheme.onSurfaceVariant, + ), + ), + ), + ], + ); + }, + ), + ); + } + + String _formatTime(BuildContext context, DateTime time) { + final localTime = TimeOfDay.fromDateTime(time); + return MaterialLocalizations.of(context).formatTimeOfDay(localTime); + } + + String _breakLongTokens(String input) { + final tokenRegex = RegExp(r'\S{24,}'); + return input.replaceAllMapped(tokenRegex, (match) { + final token = match.group(0) ?? ''; + final buffer = StringBuffer(); + for (int i = 0; i < token.length; i++) { + buffer.write(token[i]); + if ((i + 1) % 12 == 0 && i + 1 < token.length) { + buffer.write('\u200B'); + } + } + return buffer.toString(); + }); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/typing_indicator.dart b/src/lib/features/chatbot/view/widgets/typing_indicator.dart new file mode 100644 index 0000000..a35d7cc --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/typing_indicator.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; + +import 'bot_avatar.dart'; + +class TypingIndicator extends StatelessWidget { + const TypingIndicator({super.key}); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Row( + children: [ + const BotAvatar(size: 34), + const SizedBox(width: 10), + Flexible( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: BoxDecoration( + color: scheme.surface, + borderRadius: BorderRadius.circular(16), + ), + child: Text( + 'TaskBot is typing...', + overflow: TextOverflow.ellipsis, + style: TextStyle(color: scheme.onSurfaceVariant), + ), + ), + ), + ], + ); + } +} + diff --git a/src/lib/features/chatbot/view/widgets/user_avatar.dart b/src/lib/features/chatbot/view/widgets/user_avatar.dart new file mode 100644 index 0000000..a8ae00b --- /dev/null +++ b/src/lib/features/chatbot/view/widgets/user_avatar.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class UserAvatar extends StatelessWidget { + const UserAvatar({super.key, required this.size, this.avatarUrl}); + + final double size; + final String? avatarUrl; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final fallbackUrl = + (Supabase.instance.client.auth.currentUser?.userMetadata?['avatar_url'] as String?)?.trim(); + final resolvedUrl = (avatarUrl ?? fallbackUrl ?? '').trim(); + final canLoadNetworkImage = _isValidHttpUrl(resolvedUrl); + + return Container( + width: size, + height: size, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: scheme.surfaceContainerHighest, + ), + clipBehavior: Clip.antiAlias, + child: canLoadNetworkImage + ? Image.network( + resolvedUrl, + fit: BoxFit.cover, + errorBuilder: (_, _, _) => Icon( + Icons.person, + size: size * 0.6, + color: scheme.primary, + ), + ) + : Icon(Icons.person, size: size * 0.6, color: scheme.primary), + ); + } + + bool _isValidHttpUrl(String value) { + if (value.isEmpty || value.length > 2048) return false; + final uri = Uri.tryParse(value); + if (uri == null) return false; + return uri.hasAbsolutePath && (uri.scheme == 'http' || uri.scheme == 'https'); + } +} + diff --git a/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart b/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart new file mode 100644 index 0000000..fd5a4d3 --- /dev/null +++ b/src/lib/features/chatbot/viewmodel/chatbot_viewmodel.dart @@ -0,0 +1,90 @@ +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../model/chatmessage_model.dart'; +import '../services/chatbot_services.dart'; + +class ChatBotViewModel extends ChangeNotifier { + static const String _historyKey = 'chatbot_history_v1'; + static const int _maxHistoryMessages = 200; + + final _aiService = ChatBotAssistantService(); + final List _messages = []; + + ChatBotViewModel() { + _loadHistory(); + } + + List _initialMessages() => [ + ChatMessageModel( + text: 'Chào bạn! Tôi là trợ lý năng suất. Hôm nay bạn cần tôi giúp gì?', + isUser: false, + ), + ]; + + List get messages => _messages; + + bool _isLoading = false; + + bool get isLoading => _isLoading; + + Future _loadHistory() async { + try { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_historyKey); + + if (raw == null || raw.trim().isEmpty) { + _messages + ..clear() + ..addAll(_initialMessages()); + await _saveHistory(); + } else { + final storedMessages = ChatMessageModel.decodeList(raw); + _messages + ..clear() + ..addAll( + storedMessages.isEmpty ? _initialMessages() : storedMessages, + ); + } + } catch (e) { + debugPrint('Error loading chatbot history: $e'); + _messages + ..clear() + ..addAll(_initialMessages()); + } + + notifyListeners(); + } + + Future _saveHistory() async { + try { + final prefs = await SharedPreferences.getInstance(); + if (_messages.length > _maxHistoryMessages) { + _messages.removeRange(0, _messages.length - _maxHistoryMessages); + } + await prefs.setString( + _historyKey, + ChatMessageModel.encodeList(_messages), + ); + } catch (e) { + debugPrint('Error saving chatbot history: $e'); + } + } + + Future sendMessage(String text) async { + final normalizedText = text.trim(); + if (normalizedText.isEmpty) return; + + _messages.add(ChatMessageModel(text: normalizedText, isUser: true)); + _isLoading = true; + notifyListeners(); + await _saveHistory(); + + final response = await _aiService.sendMessage(normalizedText); + + _messages.add(ChatMessageModel(text: response, isUser: false)); + _isLoading = false; + await _saveHistory(); + notifyListeners(); + } +} diff --git a/src/lib/features/main/view/screens/main_screen.dart b/src/lib/features/main/view/screens/main_screen.dart index cb1c9d0..50c09e3 100644 --- a/src/lib/features/main/view/screens/main_screen.dart +++ b/src/lib/features/main/view/screens/main_screen.dart @@ -1,15 +1,18 @@ import 'package:flutter/material.dart'; +// import '../../../tasks/view/screens/home_screen.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/chatbot/view/chatbot_view.dart'; import 'package:task_management_app/features/statistics/viewmodel/statistics_viewmodel.dart'; import 'package:task_management_app/features/tasks/view/screens/home_screen.dart'; -import 'settings_screen.dart'; import 'package:task_management_app/features/user/viewmodel/user_profile_viewmodel.dart'; + +import '../../../category/viewmodel/category_viewmodel.dart'; import '../../../note/view/focus_screen.dart'; import '../../../note/viewmodel/focus_viewmodel.dart'; import '../../../statistics/view/screens/statistics_screen.dart'; -// import '../../../tasks/view/screens/home_screen.dart'; -import 'package:provider/provider.dart'; - +import '../../../tag/viewmodel/tag_viewmodel.dart'; import '../../../user/view/user_profile_view.dart'; +import 'settings_screen.dart'; class MainScreen extends StatefulWidget { const MainScreen({super.key}); @@ -23,47 +26,63 @@ class _MainScreenState extends State { final List _screens = [ const Center(child: HomeScreen()), - const Center(child: Text('Màn hình Lịch')), + const ChatBotView(), ChangeNotifierProvider( create: (_) => FocusViewModel(), child: const FocusScreen(), ), ChangeNotifierProvider( - create: (_) => StatisticsViewmodel(), - child: const StatisticsScreen(), + create: (_) => StatisticsViewmodel(), + child: const StatisticsScreen(), ), ChangeNotifierProvider( - create: (_) => UserProfileViewModel(useMockData: true)..loadProfile(), - child: const UserProfileView(), + create: (_) => UserProfileViewModel(useMockData: true)..loadProfile(), + child: const UserProfileView(), ), const SettingsScreen(), ]; + @override + void initState() { + super.initState(); + + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().loadCategories(); + context.read().loadTags(); + }); + } + @override Widget build(BuildContext context) { final isDark = Theme.of(context).brightness == Brightness.dark; return Scaffold( extendBody: true, - body: IndexedStack( - index: _currentIndex, - children: _screens, - ), + body: IndexedStack(index: _currentIndex, children: _screens), bottomNavigationBar: Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15), decoration: BoxDecoration( color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, - borderRadius: const BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30)), - boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.05), blurRadius: 20, offset: const Offset(0, -5))], + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(30), + topRight: Radius.circular(30), + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 20, + offset: const Offset(0, -5), + ), + ], ), child: SafeArea( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ _buildNavItem(context, Icons.checklist_rounded, 'Công việc', 0), - _buildNavItem(context, Icons.calendar_today_rounded, 'Lịch', 1), + _buildNavItem(context, Icons.smart_toy_rounded, 'Chat', 1), _buildNavItem(context, Icons.timer_rounded, 'Tập trung', 2), _buildNavItem(context, Icons.bar_chart_rounded, 'Thống kê', 3), _buildNavItem(context, Icons.person_2_rounded, 'Cá nhân', 4), @@ -74,7 +93,12 @@ class _MainScreenState extends State { ); } - Widget _buildNavItem(BuildContext context, IconData icon, String label, int index) { + Widget _buildNavItem( + BuildContext context, + IconData icon, + String label, + int index, + ) { bool isSelected = _currentIndex == index; return GestureDetector( @@ -82,12 +106,15 @@ class _MainScreenState extends State { child: AnimatedContainer( duration: const Duration(milliseconds: 300), curve: Curves.easeInOut, - padding: EdgeInsets.symmetric(horizontal: isSelected ? 15 : 10, vertical: 10), + padding: EdgeInsets.symmetric( + horizontal: isSelected ? 15 : 10, + vertical: 10, + ), decoration: BoxDecoration( color: isSelected ? (Theme.of(context).brightness == Brightness.dark - ? const Color(0xFF23395D) - : const Color(0xFFE8F0FE)) + ? const Color(0xFF23395D) + : const Color(0xFFE8F0FE)) : Colors.transparent, borderRadius: BorderRadius.circular(15), ), @@ -111,10 +138,10 @@ class _MainScreenState extends State { ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.onSurfaceVariant, ), - ) + ), ], ), ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/statistics/view/screens/statistics_screen.dart b/src/lib/features/statistics/view/screens/statistics_screen.dart index fd18a14..f7bd920 100644 --- a/src/lib/features/statistics/view/screens/statistics_screen.dart +++ b/src/lib/features/statistics/view/screens/statistics_screen.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:provider/provider.dart'; import '../../viewmodel/statistics_viewmodel.dart'; @@ -23,6 +24,10 @@ class _StatisticsScreenState extends State { final userId = Supabase.instance.client.auth.currentUser?.id; if (userId != null) { context.read().getStatisticsData(userId); + final categoryViewModel = context.read(); + if (categoryViewModel.categories.isEmpty) { + categoryViewModel.loadCategories(); + } } }); } diff --git a/src/lib/features/statistics/view/widgets/statistics_widgets.dart b/src/lib/features/statistics/view/widgets/statistics_widgets.dart index c0b6568..e1e3598 100644 --- a/src/lib/features/statistics/view/widgets/statistics_widgets.dart +++ b/src/lib/features/statistics/view/widgets/statistics_widgets.dart @@ -1,5 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:task_management_app/features/statistics/model/StatisticsModel.dart'; + import '../../../tasks/model/task_model.dart'; import '../../../tasks/view/screens/task_detail_screen.dart'; @@ -7,7 +11,13 @@ class DailyProgressCard extends StatelessWidget { final int total; final int completed; final double percentage; - const DailyProgressCard({super.key, required this.total, required this.completed, required this.percentage}); + + const DailyProgressCard({ + super.key, + required this.total, + required this.completed, + required this.percentage, + }); @override Widget build(BuildContext context) { @@ -17,7 +27,9 @@ class DailyProgressCard extends StatelessWidget { width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20), decoration: BoxDecoration( - color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) @@ -43,8 +55,9 @@ class DailyProgressCard extends StatelessWidget { CircularProgressIndicator( value: (total > 0) ? percentage / 100 : 0, strokeWidth: 12, - backgroundColor: - Theme.of(context).colorScheme.surfaceContainerHighest, + backgroundColor: Theme.of( + context, + ).colorScheme.surfaceContainerHighest, valueColor: AlwaysStoppedAnimation( Theme.of(context).colorScheme.primary, ), @@ -99,7 +112,6 @@ class DailyProgressCard extends StatelessWidget { } } - class WeeklyChartCard extends StatelessWidget { final int selectedIndex; final int thisWeekTotal; @@ -121,17 +133,22 @@ class WeeklyChartCard extends StatelessWidget { final isDark = Theme.of(context).brightness == Brightness.dark; final bool isPositive = growthPercentage >= 0; - final Color trendColor = isPositive ? const Color(0xFF3DDC84) : Colors.redAccent; + final Color trendColor = isPositive + ? const Color(0xFF3DDC84) + : Colors.redAccent; final Color trendBgColor = isPositive ? (isDark ? const Color(0xFF173B3D) : const Color(0xFFE9F7EF)) : (isDark ? const Color(0xFF402129) : const Color(0xFFFFEBEE)); - final String trendText = "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; + final String trendText = + "${isPositive ? '+' : ''}$growthPercentage% vs tuần trước"; return Container( width: double.infinity, padding: const EdgeInsets.all(25), decoration: BoxDecoration( - color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(30), border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) @@ -167,9 +184,22 @@ class WeeklyChartCard extends StatelessWidget { ], ), Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), - decoration: BoxDecoration(color: trendBgColor, borderRadius: BorderRadius.circular(15)), - child: Text(trendText, style: TextStyle(color: trendColor, fontSize: 12, fontWeight: FontWeight.bold)), + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + decoration: BoxDecoration( + color: trendBgColor, + borderRadius: BorderRadius.circular(15), + ), + child: Text( + trendText, + style: TextStyle( + color: trendColor, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), ), ], ), @@ -178,14 +208,48 @@ class WeeklyChartCard extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ - - _buildBar(context, 'T2', weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, 0), - _buildBar(context, 'T3', weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, 1), - _buildBar(context, 'T4', weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, 2), - _buildBar(context, 'T5', weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, 3), - _buildBar(context, 'T6', weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, 4), - _buildBar(context, 'T7', weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, 5), - _buildBar(context, 'CN', weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, 6), + _buildBar( + context, + 'T2', + weeklyHeights.length > 0 ? weeklyHeights[0] : 0.1, + 0, + ), + _buildBar( + context, + 'T3', + weeklyHeights.length > 1 ? weeklyHeights[1] : 0.1, + 1, + ), + _buildBar( + context, + 'T4', + weeklyHeights.length > 2 ? weeklyHeights[2] : 0.1, + 2, + ), + _buildBar( + context, + 'T5', + weeklyHeights.length > 3 ? weeklyHeights[3] : 0.1, + 3, + ), + _buildBar( + context, + 'T6', + weeklyHeights.length > 4 ? weeklyHeights[4] : 0.1, + 4, + ), + _buildBar( + context, + 'T7', + weeklyHeights.length > 5 ? weeklyHeights[5] : 0.1, + 5, + ), + _buildBar( + context, + 'CN', + weeklyHeights.length > 6 ? weeklyHeights[6] : 0.1, + 6, + ), ], ), ], @@ -193,7 +257,12 @@ class WeeklyChartCard extends StatelessWidget { ); } - Widget _buildBar(BuildContext context, String label, double heightRatio, int index) { + Widget _buildBar( + BuildContext context, + String label, + double heightRatio, + int index, + ) { bool isActive = index == selectedIndex; return GestureDetector( onTap: () => onDaySelected(index), @@ -203,13 +272,13 @@ class WeeklyChartCard extends StatelessWidget { AnimatedContainer( duration: const Duration(milliseconds: 300), width: 35, - height: 100 * (heightRatio > 0 ? heightRatio : 0.1), // Tối thiểu 10% để cột không bị "biến mất" + height: 100 * (heightRatio > 0 ? heightRatio : 0.1), decoration: BoxDecoration( color: isActive ? Theme.of(context).colorScheme.primary : (Theme.of(context).brightness == Brightness.dark - ? const Color(0xFF334764) - : const Color(0xFFF5F7FA)), + ? const Color(0xFF334764) + : const Color(0xFFF5F7FA)), borderRadius: BorderRadius.circular(8), ), ), @@ -239,10 +308,22 @@ class CompletedTaskCard extends StatelessWidget { @override Widget build(BuildContext context) { + final categoryViewModel = context.watch(); final isDark = Theme.of(context).brightness == Brightness.dark; + final CategoryModel fallbackCategory = CategoryModel( + id: 0, + name: 'General', + colorCode: '#5A8DF3', + profileId: '', + ); + final CategoryModel category = categoryViewModel.categories.isNotEmpty + ? categoryViewModel.categories.first + : fallbackCategory; final time = task.updatedAt; - final hour = time.hour > 12 ? time.hour - 12 : (time.hour == 0 ? 12 : time.hour); + final hour = time.hour > 12 + ? time.hour - 12 + : (time.hour == 0 ? 12 : time.hour); final minute = time.minute.toString().padLeft(2, '0'); final period = time.hour >= 12 ? 'PM' : 'AM'; final timeString = 'Hoàn thành lúc $hour:$minute $period'; @@ -255,28 +336,41 @@ class CompletedTaskCard extends StatelessWidget { borderRadius: BorderRadius.circular(25), onTap: () { final mappedTask = TaskModel( - id: task.id.toString(), // Convert int to String if your TaskModel uses String IDs + id: task.id.toString(), + // Convert int to String if your TaskModel uses String IDs title: task.title, - description: 'Completed task details from Statistics.', // Default filler - category: 'Development', // Default filler - startTime: TimeOfDay(hour: task.updatedAt.hour, minute: task.updatedAt.minute), - endTime: TimeOfDay(hour: task.updatedAt.hour + 1, minute: task.updatedAt.minute), // Add 1 hour just for display + description: 'Completed task details from Statistics.', + category: category, + startTime: TimeOfDay( + hour: task.updatedAt.hour, + minute: task.updatedAt.minute, + ), + endTime: TimeOfDay( + hour: task.updatedAt.hour + 1, + minute: task.updatedAt.minute, + ), + // Add 1 hour just for display date: task.updatedAt, ); - Navigator.push(context, PageRouteBuilder( - transitionDuration: const Duration(milliseconds: 500), - pageBuilder: (_, __, ___) => TaskDetailScreen(task: mappedTask), - transitionsBuilder: (_, animation, __, child) { - return FadeTransition(opacity: animation, child: child); - }, - )); + Navigator.push( + context, + PageRouteBuilder( + transitionDuration: const Duration(milliseconds: 500), + pageBuilder: (_, __, ___) => TaskDetailScreen(task: mappedTask), + transitionsBuilder: (_, animation, __, child) { + return FadeTransition(opacity: animation, child: child); + }, + ), + ); }, child: Container( margin: const EdgeInsets.only(bottom: 15), padding: const EdgeInsets.all(20), decoration: BoxDecoration( - color: isDark ? const Color(0xFF1A2945) : Theme.of(context).colorScheme.surface, + color: isDark + ? const Color(0xFF1A2945) + : Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(25), border: isDark ? Border.all(color: const Color(0xFF2A3E62), width: 1) @@ -318,7 +412,11 @@ class CompletedTaskCard extends StatelessWidget { ], ), ), - const Icon(Icons.check_circle, color: Color(0xFF2ECC71), size: 28), + const Icon( + Icons.check_circle, + color: Color(0xFF2ECC71), + size: 28, + ), ], ), ), @@ -326,4 +424,4 @@ class CompletedTaskCard extends StatelessWidget { ), ); } -} \ No newline at end of file +} diff --git a/src/lib/features/tag/model/tag_model.dart b/src/lib/features/tag/model/tag_model.dart new file mode 100644 index 0000000..5f5fdb8 --- /dev/null +++ b/src/lib/features/tag/model/tag_model.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +class TagModel { + final int id; + final String name; + final String colorCode; + final String profileId; + + const TagModel({ + required this.id, + required this.name, + required this.colorCode, + required this.profileId, + }); + + Color get color => _parseHexColor(colorCode); + + factory TagModel.fromJson(Map json) { + return TagModel( + id: (json['id'] as num?)?.toInt() ?? 0, + name: json['name']?.toString() ?? '', + colorCode: json['color_code']?.toString() ?? '#4A90E2', + profileId: json['profile_id']?.toString() ?? '', + ); + } + + Map toJson() { + return { + 'id': id, + 'name': name, + 'color_code': colorCode, + 'profile_id': profileId, + }; + } + + static Color _parseHexColor(String value) { + var hex = value.trim().replaceFirst('#', ''); + if (hex.length == 6) { + hex = 'FF$hex'; + } + if (hex.length != 8) { + return const Color(0xFF4A90E2); + } + + final parsed = int.tryParse(hex, radix: 16); + if (parsed == null) { + return const Color(0xFF4A90E2); + } + return Color(parsed); + } +} + diff --git a/src/lib/features/tag/repository/tag_repository.dart b/src/lib/features/tag/repository/tag_repository.dart new file mode 100644 index 0000000..d2c9158 --- /dev/null +++ b/src/lib/features/tag/repository/tag_repository.dart @@ -0,0 +1,45 @@ +import 'package:supabase_flutter/supabase_flutter.dart'; + +import '../model/tag_model.dart'; + +class TagRepository { + final SupabaseClient _client; + + TagRepository({SupabaseClient? client}) + : _client = client ?? Supabase.instance.client; + + Future> fetchTags() async { + final user = _client.auth.currentUser; + if (user == null) return []; + + final rows = await _client + .from('tag') + .select('id, name, color_code, profile_id') + .eq('profile_id', user.id) + .order('name'); + + return (rows as List) + .map((e) => TagModel.fromJson(Map.from(e))) + .toList(); + } + + Future createCustomTag(String name, String colorCode) async { + final user = _client.auth.currentUser; + if (user == null) { + throw Exception('User is not authenticated'); + } + + final inserted = await _client + .from('tag') + .insert({ + 'name': name, + 'color_code': colorCode, + 'profile_id': user.id, + }) + .select('id, name, color_code, profile_id') + .single(); + + return TagModel.fromJson(Map.from(inserted)); + } +} + diff --git a/src/lib/features/tag/view/widgets/tag_selector.dart b/src/lib/features/tag/view/widgets/tag_selector.dart new file mode 100644 index 0000000..50753a6 --- /dev/null +++ b/src/lib/features/tag/view/widgets/tag_selector.dart @@ -0,0 +1,194 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + +import '../../viewmodel/tag_viewmodel.dart'; + +class TagSelector extends StatefulWidget { + const TagSelector({super.key}); + + @override + State createState() => _TagSelectorState(); +} + +class _TagSelectorState extends State { + final TextEditingController _customController = TextEditingController(); + + @override + void dispose() { + _customController.dispose(); + super.dispose(); + } + + void _showAddCustomDialog(BuildContext context, TagViewModel viewModel) { + _customController.clear(); + showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('Tạo tag mới'), + content: TextField( + controller: _customController, + maxLength: 12, + decoration: const InputDecoration( + hintText: 'Tên tag (tối đa 12 ký tự)', + border: OutlineInputBorder(), + ), + autofocus: true, + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Huỷ'), + ), + ElevatedButton( + onPressed: () async { + final error = await viewModel.addCustomTag(_customController.text); + if (!context.mounted) return; + + if (error != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(error), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); + } else { + Navigator.pop(context); + } + }, + child: const Text('Thêm'), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final viewModel = context.watch(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Tags', style: Theme.of(context).textTheme.labelLarge), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Custom', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + GestureDetector( + onTap: viewModel.isLoading + ? null + : () => _showAddCustomDialog(context, viewModel), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Theme.of(context).colorScheme.outline), + ), + child: Row( + children: [ + Icon( + Icons.add, + size: 14, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 3), + Text( + 'Tạo tag', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.primary, + ), + ), + ], + ), + ), + ), + ], + ), + const SizedBox(height: 8), + if (viewModel.tags.isEmpty) + Text( + 'Chưa có tag. Nhấn "Tạo tag" để thêm.', + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ) + else + Wrap( + spacing: 8, + runSpacing: 8, + children: viewModel.tags + .map( + (tag) => _TagChip( + tag: tag, + isSelected: viewModel.isTagSelected(tag), + onTap: () => viewModel.toggleTag(tag), + ), + ) + .toList(), + ), + ], + ); + } +} + +class _TagChip extends StatelessWidget { + const _TagChip({ + required this.tag, + required this.isSelected, + required this.onTap, + }); + + final TagModel tag; + final bool isSelected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final adaptiveTagColor = tag.color.toAdaptiveColor(context); + + return GestureDetector( + onTap: onTap, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: isSelected + ? adaptiveTagColor + : adaptiveTagColor.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isSelected) ...[ + const Icon(Icons.check, color: Colors.white, size: 14), + const SizedBox(width: 4), + ], + Text( + tag.name, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w500, + color: isSelected ? Colors.white : adaptiveTagColor, + ), + ), + ], + ), + ), + ); + } +} + diff --git a/src/lib/features/tag/viewmodel/tag_viewmodel.dart b/src/lib/features/tag/viewmodel/tag_viewmodel.dart new file mode 100644 index 0000000..d361c77 --- /dev/null +++ b/src/lib/features/tag/viewmodel/tag_viewmodel.dart @@ -0,0 +1,113 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../model/tag_model.dart'; +import '../repository/tag_repository.dart'; + +class TagViewModel extends ChangeNotifier { + static const int _maxCustomTagLength = 12; + + final TagRepository _repository; + + TagViewModel({TagRepository? repository}) + : _repository = repository ?? TagRepository(); + + final List _tags = []; + final Set _selectedTagIds = {}; + + List get tags => List.unmodifiable(_tags); + + List get selectedTags => + _tags.where((tag) => _selectedTagIds.contains(tag.id)).toList(); + + bool _isLoading = false; + bool get isLoading => _isLoading; + + String? _error; + String? get error => _error; + + Future loadTags() async { + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final data = await _repository.fetchTags(); + _tags + ..clear() + ..addAll(data); + _selectedTagIds.removeWhere((id) => !_tags.any((tag) => tag.id == id)); + } catch (e) { + _error = e.toString(); + _tags.clear(); + } finally { + _isLoading = false; + notifyListeners(); + } + } + + bool isTagSelected(TagModel tag) => _selectedTagIds.contains(tag.id); + + void toggleTag(TagModel tag) { + if (_selectedTagIds.contains(tag.id)) { + _selectedTagIds.remove(tag.id); + } else { + _selectedTagIds.add(tag.id); + } + notifyListeners(); + } + + void setSelectedTags(List tags) { + _selectedTagIds + ..clear() + ..addAll(tags.map((e) => e.id)); + notifyListeners(); + } + + void resetSelection() { + _selectedTagIds.clear(); + notifyListeners(); + } + + Future addCustomTag(String name) async { + final trimmed = name.trim(); + if (trimmed.isEmpty) return 'Tên tag không được để trống'; + if (trimmed.length > _maxCustomTagLength) { + return 'Tối đa $_maxCustomTagLength ký tự'; + } + if (_tags.any((t) => t.name.toLowerCase() == trimmed.toLowerCase())) { + return 'Tag đã tồn tại'; + } + + _isLoading = true; + _error = null; + notifyListeners(); + + try { + final colorCode = _generateColorCode(); + final created = await _repository.createCustomTag(trimmed, colorCode); + _tags.add(created); + _selectedTagIds.add(created.id); + return null; + } catch (e) { + _error = e.toString(); + return 'Không thể tạo tag. Vui lòng thử lại'; + } finally { + _isLoading = false; + notifyListeners(); + } + } + + String _generateColorCode() { + const palette = [ + '#E91E63', + '#673AB7', + '#795548', + '#009688', + '#FF5722', + '#4A90E2', + ]; + return palette[_tags.length % palette.length]; + } +} + diff --git a/src/lib/features/tasks/model/task_model.dart b/src/lib/features/tasks/model/task_model.dart index a6a64fb..3fa2db1 100644 --- a/src/lib/features/tasks/model/task_model.dart +++ b/src/lib/features/tasks/model/task_model.dart @@ -1,5 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + // ─── Priority Enum ─────────────────────────────────────────── enum Priority { low, medium, high, urgent } @@ -44,21 +47,12 @@ extension PriorityExtension on Priority { } } -// ─── Tag Model ─────────────────────────────────────────────── -class TagModel { - final String id; - final String name; - final Color color; - - const TagModel({required this.id, required this.name, required this.color}); -} - // ─── Task Model ────────────────────────────────────────────── class TaskModel { final String id; String title; String description; - String category; + CategoryModel category; TimeOfDay startTime; TimeOfDay endTime; DateTime date; diff --git a/src/lib/features/tasks/view/screens/create_task_screen.dart b/src/lib/features/tasks/view/screens/create_task_screen.dart index 311fd00..7e6fc3e 100644 --- a/src/lib/features/tasks/view/screens/create_task_screen.dart +++ b/src/lib/features/tasks/view/screens/create_task_screen.dart @@ -1,13 +1,16 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/features/category/view/widgets/category_choice_chips.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; +import 'package:task_management_app/features/tag/view/widgets/tag_selector.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; + import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; import '../../viewmodel/task_viewmodel.dart'; import '../widgets/task_widgets.dart'; import '../widgets/priority_selector.dart'; -import '../widgets/tag_selector.dart'; class CreateTaskScreen extends StatefulWidget { const CreateTaskScreen({super.key}); @@ -26,12 +29,28 @@ class _CreateTaskScreenState extends State { DateTime _selectedDate = DateTime.now(); TimeOfDay _startTime = const TimeOfDay(hour: 10, minute: 0); TimeOfDay _endTime = const TimeOfDay(hour: 11, minute: 0); - int _selectedCategoryIndex = 0; + int? _selectedCategoryId; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read().loadCategories(); + context.read().loadTags(); + }); + } @override Widget build(BuildContext context) { + final categoryViewModel = context.watch(); + final tagViewModel = context.watch(); String formattedDate = DateFormat('EEEE, d MMMM').format(_selectedDate); - final isDark = Theme.of(context).brightness == Brightness.dark; + final categories = categoryViewModel.categories; + + if (_selectedCategoryId == null && categories.isNotEmpty) { + _selectedCategoryId = categories.first.id; + } return Scaffold( backgroundColor: Theme.of(context).scaffoldBackgroundColor, @@ -105,47 +124,20 @@ class _CreateTaskScreenState extends State { ), const SizedBox(height: 10), SizedBox( - height: 40, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: 4, - itemBuilder: (context, index) { - List categories = [ - 'Development', - 'Research', - 'Design', - 'Backend', - ]; - bool isSelected = index == _selectedCategoryIndex; - return Padding( - padding: const EdgeInsets.only(right: 10), - child: ChoiceChip( - label: Text(categories[index]), - selected: isSelected, - onSelected: (selected) => setState(() => _selectedCategoryIndex = selected ? index : 0), - backgroundColor: isDark - ? Theme.of(context).colorScheme.surfaceContainerHighest - : const Color(0xFFF1F7FD), - selectedColor: Theme.of(context).colorScheme.primary, - labelStyle: TextStyle( - color: isSelected - ? Colors.white - : Theme.of(context).colorScheme.primary, - fontSize: 14, - ), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - side: BorderSide( - color: isDark - ? Theme.of(context).colorScheme.outline - : const Color(0xFFF1F7FD), - width: 1, - )), - showCheckmark: false, + child: categories.isEmpty + ? Text( + categoryViewModel.isLoading + ? 'Loading categories...' + : 'No categories found', + style: Theme.of(context).textTheme.bodyMedium, + ) + : CategoryChoiceChips( + categories: categories, + selectedCategoryId: _selectedCategoryId, + onSelected: (category) { + setState(() => _selectedCategoryId = category.id); + }, ), - ); - }, - ), ), const SizedBox(height: 20), @@ -270,26 +262,35 @@ class _CreateTaskScreenState extends State { child: ElevatedButton( onPressed: () { final viewModel = context.read(); - final List categories = [ - 'Development', - 'Research', - 'Design', - 'Backend', - ]; + if (categories.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please create a category first.'), + ), + ); + return; + } + + final selectedCategory = categories.firstWhere( + (category) => category.id == _selectedCategoryId, + orElse: () => categories.first, + ); + final newTask = TaskModel( id: DateTime.now().millisecondsSinceEpoch .toString(), title: _nameController.text, description: _descController.text, - category: categories[_selectedCategoryIndex], + category: selectedCategory, startTime: _startTime, endTime: _endTime, date: _selectedDate, priority: viewModel.selectedPriority, - tags: List.from(viewModel.selectedTags), + tags: List.from(tagViewModel.selectedTags), ); viewModel.addTask(newTask); viewModel.reset(); + context.read().resetSelection(); Navigator.pop(context); }, style: ElevatedButton.styleFrom( diff --git a/src/lib/features/tasks/view/screens/task_detail_screen.dart b/src/lib/features/tasks/view/screens/task_detail_screen.dart index fd2f832..54b628e 100644 --- a/src/lib/features/tasks/view/screens/task_detail_screen.dart +++ b/src/lib/features/tasks/view/screens/task_detail_screen.dart @@ -1,7 +1,13 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; -import '../../../../core/theme/app_colors.dart'; +import 'package:task_management_app/core/utils/adaptive_color_extension.dart'; +import 'package:task_management_app/features/category/model/category_model.dart'; +import 'package:task_management_app/features/category/view/widgets/category_choice_chips.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; + import '../../../../core/widgets/custom_input_field.dart'; import '../../model/task_model.dart'; import '../../viewmodel/task_viewmodel.dart'; @@ -20,7 +26,7 @@ class _TaskDetailScreenState extends State { late TextEditingController _descController; late TimeOfDay _startTime; late TimeOfDay _endTime; - late String _currentCategory; + late CategoryModel _currentCategory; late List _currentTags; @override @@ -32,6 +38,12 @@ class _TaskDetailScreenState extends State { _endTime = widget.task.endTime; _currentCategory = widget.task.category; _currentTags = List.from(widget.task.tags); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + context.read().loadCategories(); + context.read().loadTags(); + }); } @override @@ -74,12 +86,17 @@ class _TaskDetailScreenState extends State { @override Widget build(BuildContext context) { - final viewModel = context.watch(); + final categoryViewModel = context.watch(); + final tagViewModel = context.watch(); String formattedDate = DateFormat('EEEE, d MMMM').format(widget.task.date); final isDark = Theme.of(context).brightness == Brightness.dark; - // Mock categories (Fetch from database later) - List categories = ['Development', 'Research', 'Design', 'Backend']; + final categories = categoryViewModel.categories; + final tags = tagViewModel.tags; + + if (categories.isNotEmpty && !categories.any((c) => c.id == _currentCategory.id)) { + _currentCategory = categories.first; + } return Scaffold( backgroundColor: Theme.of(context).colorScheme.surfaceContainerHighest, @@ -143,48 +160,20 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 10), SizedBox( - height: 40, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: categories.length, - itemBuilder: (context, index) { - bool isSelected = - categories[index] == _currentCategory; - return Padding( - padding: const EdgeInsets.only(right: 10), - child: ChoiceChip( - label: Text(categories[index]), - selected: isSelected, - onSelected: (selected) { - if (selected) { - setState( - () => _currentCategory = categories[index], - ); - } + child: categories.isEmpty + ? Text( + categoryViewModel.isLoading + ? 'Loading categories...' + : 'No categories found', + style: Theme.of(context).textTheme.bodyMedium, + ) + : CategoryChoiceChips( + categories: categories, + selectedCategoryId: _currentCategory.id, + onSelected: (category) { + setState(() => _currentCategory = category); }, - backgroundColor: isDark - ? Theme.of(context).colorScheme.surfaceContainerHighest - : const Color(0xFFF1F7FD), - selectedColor: Theme.of(context).colorScheme.primary, - labelStyle: TextStyle( - color: isSelected - ? Colors.white - : Theme.of(context).colorScheme.primary, - fontSize: 14, - ), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10), - side: BorderSide( - color: isDark - ? Theme.of(context).colorScheme.outline - : const Color(0xFFF1F7FD), - width: 1, - )), - showCheckmark: false, ), - ); - }, - ), ), const SizedBox(height: 25), @@ -201,70 +190,17 @@ class _TaskDetailScreenState extends State { ), const SizedBox(height: 25), - // ─── Time Tags ──────────────────────────── - Text( - 'Thời gian', - style: Theme.of(context).textTheme.labelLarge, - ), - const SizedBox(height: 10), - Wrap( - spacing: 8, - runSpacing: 8, - children: viewModel.timeTags.map((tag) { - final isSelected = _isTagSelected(tag); - return GestureDetector( - onTap: () => _toggleTag(tag), - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - padding: const EdgeInsets.symmetric( - horizontal: 14, - vertical: 8, - ), - decoration: BoxDecoration( - color: isSelected - ? tag.color - : tag.color.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (isSelected) ...[ - const Icon( - Icons.check, - color: Colors.white, - size: 14, - ), - const SizedBox(width: 4), - ], - Text( - tag.name, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - color: isSelected - ? Colors.white - : tag.color, - ), - ), - ], - ), - ), - ); - }).toList(), - ), - const SizedBox(height: 20), - - // ─── Status Tags ────────────────────────── + // ─── Tags ───────────────────────────────── Text( - 'Trạng thái', + 'Tags', style: Theme.of(context).textTheme.labelLarge, ), const SizedBox(height: 10), Wrap( spacing: 8, runSpacing: 8, - children: viewModel.statusTags.map((tag) { + children: tags.map((tag) { + final adaptiveTagColor = tag.color.toAdaptiveColor(context); final isSelected = _isTagSelected(tag); return GestureDetector( onTap: () => _toggleTag(tag), @@ -276,8 +212,8 @@ class _TaskDetailScreenState extends State { ), decoration: BoxDecoration( color: isSelected - ? tag.color - : tag.color.withValues(alpha: 0.1), + ? adaptiveTagColor + : adaptiveTagColor.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(20), ), child: Row( @@ -298,7 +234,7 @@ class _TaskDetailScreenState extends State { fontWeight: FontWeight.w500, color: isSelected ? Colors.white - : tag.color, + : adaptiveTagColor, ), ), ], diff --git a/src/lib/features/tasks/view/widgets/tag_selector.dart b/src/lib/features/tasks/view/widgets/tag_selector.dart index 71c15b0..eee3cf6 100644 --- a/src/lib/features/tasks/view/widgets/tag_selector.dart +++ b/src/lib/features/tasks/view/widgets/tag_selector.dart @@ -1,237 +1,12 @@ import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; -import '../../model/task_model.dart'; -import '../../viewmodel/task_viewmodel.dart'; +import 'package:task_management_app/features/tag/view/widgets/tag_selector.dart' + as tag_feature; -class TagSelector extends StatefulWidget { +class TagSelector extends StatelessWidget { const TagSelector({super.key}); - @override - State createState() => _TagSelectorState(); -} - -class _TagSelectorState extends State { - final TextEditingController _customController = TextEditingController(); - - @override - void dispose() { - _customController.dispose(); - super.dispose(); - } - - void _showAddCustomDialog(BuildContext context, TaskViewModel viewModel) { - _customController.clear(); - showDialog( - context: context, - builder: (_) => AlertDialog( - title: const Text('Tạo tag mới'), - content: TextField( - controller: _customController, - maxLength: 12, - decoration: const InputDecoration( - hintText: 'Tên tag (tối đa 12 ký tự)', - border: OutlineInputBorder(), - ), - autofocus: true, - ), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context), - child: const Text('Huỷ'), - ), - ElevatedButton( - onPressed: () { - final error = viewModel.addCustomTag(_customController.text); - if (error != null) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text(error), backgroundColor: Colors.red), - ); - } else { - Navigator.pop(context); - } - }, - child: const Text('Thêm'), - ), - ], - ), - ); - } - - @override - Widget build(BuildContext context) { - final viewModel = context.watch(); - - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text('Tags', style: Theme.of(context).textTheme.labelLarge), - const SizedBox(height: 12), - - // ─── Nhóm 1: Loại công việc ─────────────────────── - _buildTagGroup( - label: 'Loại công việc', - tags: viewModel.workTypeTags, - viewModel: viewModel, - ), - const SizedBox(height: 12), - - // ─── Nhóm 2: Thời gian ──────────────────────────── - _buildTagGroup( - label: 'Thời gian', - tags: viewModel.timeTags, - viewModel: viewModel, - ), - const SizedBox(height: 12), - - // ─── Nhóm 3: Trạng thái ─────────────────────────── - _buildTagGroup( - label: 'Trạng thái', - tags: viewModel.statusTags, - viewModel: viewModel, - ), - const SizedBox(height: 12), - - // ─── Nhóm 4: Custom ─────────────────────────────── - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - const Text( - 'Custom', - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: Colors.black54, - ), - ), - // Nút thêm tag mới - if (viewModel.customTags.length < 5) - GestureDetector( - onTap: () => _showAddCustomDialog(context, viewModel), - child: Container( - padding: const EdgeInsets.symmetric( - horizontal: 10, - vertical: 4, - ), - decoration: BoxDecoration( - color: const Color(0xFFF1F7FD), - borderRadius: BorderRadius.circular(20), - border: Border.all(color: Colors.blue.shade200), - ), - child: const Row( - children: [ - Icon(Icons.add, size: 14, color: Colors.blue), - SizedBox(width: 3), - Text( - 'Tạo tag', - style: TextStyle(fontSize: 12, color: Colors.blue), - ), - ], - ), - ), - ), - ], - ), - const SizedBox(height: 8), - - // Hiển thị custom tags đã tạo - viewModel.customTags.isEmpty - ? const Text( - 'Chưa có tag custom. Nhấn "Tạo tag" để thêm.', - style: TextStyle(fontSize: 12, color: Colors.black38), - ) - : Wrap( - spacing: 8, - runSpacing: 8, - children: viewModel.customTags - .map( - (tag) => _TagChip( - tag: tag, - isSelected: viewModel.isTagSelected(tag), - onTap: () => viewModel.toggleTag(tag), - ), - ) - .toList(), - ), - ], - ); - } - - Widget _buildTagGroup({ - required String label, - required List tags, - required TaskViewModel viewModel, - }) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - label, - style: const TextStyle( - fontSize: 13, - fontWeight: FontWeight.w600, - color: Colors.black54, - ), - ), - const SizedBox(height: 6), - Wrap( - spacing: 8, - runSpacing: 8, - children: tags - .map( - (tag) => _TagChip( - tag: tag, - isSelected: viewModel.isTagSelected(tag), - onTap: () => viewModel.toggleTag(tag), - ), - ) - .toList(), - ), - ], - ); - } -} - -// ─── Tag Chip Widget ───────────────────────────────────────── -class _TagChip extends StatelessWidget { - final TagModel tag; - final bool isSelected; - final VoidCallback onTap; - - const _TagChip({ - required this.tag, - required this.isSelected, - required this.onTap, - }); - @override Widget build(BuildContext context) { - return GestureDetector( - onTap: onTap, - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), - decoration: BoxDecoration( - color: isSelected ? tag.color : tag.color.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (isSelected) ...[ - const Icon(Icons.check, color: Colors.white, size: 14), - const SizedBox(width: 4), - ], - Text( - tag.name, - style: TextStyle( - fontSize: 13, - fontWeight: FontWeight.w500, - color: isSelected ? Colors.white : tag.color, - ), - ), - ], - ), - ), - ); + return const tag_feature.TagSelector(); } } diff --git a/src/lib/features/tasks/viewmodel/task_viewmodel.dart b/src/lib/features/tasks/viewmodel/task_viewmodel.dart index 347d2bc..c943500 100644 --- a/src/lib/features/tasks/viewmodel/task_viewmodel.dart +++ b/src/lib/features/tasks/viewmodel/task_viewmodel.dart @@ -1,143 +1,21 @@ -import 'dart:convert'; import 'package:flutter/material.dart'; -import 'package:shared_preferences/shared_preferences.dart'; +import 'package:task_management_app/features/tag/model/tag_model.dart'; + import '../model/task_model.dart'; class TaskViewModel extends ChangeNotifier { - final List workTypeTags = [ - TagModel(id: 'work', name: 'Work', color: const Color(0xFF2196F3)), - TagModel(id: 'study', name: 'Study', color: const Color(0xFF9C27B0)), - TagModel(id: 'personal', name: 'Personal', color: const Color(0xFF4CAF50)), - TagModel(id: 'project', name: 'Project', color: const Color(0xFFFF9800)), - ]; - - final List timeTags = [ - TagModel(id: 'today', name: 'Today', color: const Color(0xFF00BCD4)), - TagModel(id: 'tomorrow', name: 'Tomorrow', color: const Color(0xFF3F51B5)), - TagModel( - id: 'this_week', - name: 'This Week', - color: const Color(0xFF009688), - ), - TagModel(id: 'later', name: 'Later', color: const Color(0xFF607D8B)), - ]; - - final List statusTags = [ - TagModel(id: 'pending', name: 'Pending', color: const Color(0xFFFF9800)), - TagModel( - id: 'in_progress', - name: 'In Progress', - color: const Color(0xFF2196F3), - ), - TagModel( - id: 'completed', - name: 'Completed', - color: const Color(0xFF4CAF50), - ), - TagModel( - id: 'cancelled', - name: 'Cancelled', - color: const Color(0xFF9E9E9E), - ), - ]; - - // ─── Custom Tags (lưu SharedPreferences) ──────────────── - List _customTags = []; - List get customTags => List.unmodifiable(_customTags); - - static const _customTagsKey = 'custom_tags'; - static const _maxCustomTags = 5; - static const _maxCustomTagLength = 12; - - TaskViewModel() { - _loadCustomTags(); - } - - Future _loadCustomTags() async { - final prefs = await SharedPreferences.getInstance(); - final raw = prefs.getString(_customTagsKey); - if (raw != null) { - final List decoded = jsonDecode(raw); - _customTags = decoded - .map( - (e) => TagModel( - id: e['id'], - name: e['name'], - color: Color(e['color']), - ), - ) - .toList(); - notifyListeners(); - } - } - - Future _saveCustomTags() async { - final prefs = await SharedPreferences.getInstance(); - final encoded = jsonEncode( - _customTags - .map((t) => {'id': t.id, 'name': t.name, 'color': t.color.toARGB32()}) - .toList(), - ); - await prefs.setString(_customTagsKey, encoded); - } - - // Trả về lỗi nếu có, null nếu thành công - String? addCustomTag(String name) { - name = name.trim(); - if (name.isEmpty) return 'Tên tag không được để trống'; - if (name.length > _maxCustomTagLength) - return 'Tối đa $_maxCustomTagLength ký tự'; - if (_customTags.length >= _maxCustomTags) - return 'Tối đa $_maxCustomTags tag custom'; - if (_customTags.any((t) => t.name.toLowerCase() == name.toLowerCase())) { - return 'Tag đã tồn tại'; - } - _customTags.add( - TagModel( - id: 'custom_${DateTime.now().millisecondsSinceEpoch}', - name: name, - color: _customTagColors[_customTags.length % _customTagColors.length], - ), - ); - _saveCustomTags(); - notifyListeners(); - return null; - } - - final List _customTagColors = const [ - Color(0xFFE91E63), - Color(0xFF673AB7), - Color(0xFF795548), - Color(0xFF009688), - Color(0xFFFF5722), - ]; - // ─── State tạo task ───────────────────────────────────── Priority _selectedPriority = Priority.medium; - final List _selectedTags = []; Priority get selectedPriority => _selectedPriority; - List get selectedTags => List.unmodifiable(_selectedTags); void setPriority(Priority priority) { _selectedPriority = priority; notifyListeners(); } - void toggleTag(TagModel tag) { - if (_selectedTags.any((t) => t.id == tag.id)) { - _selectedTags.removeWhere((t) => t.id == tag.id); - } else { - _selectedTags.add(tag); - } - notifyListeners(); - } - - bool isTagSelected(TagModel tag) => _selectedTags.any((t) => t.id == tag.id); - void reset() { _selectedPriority = Priority.medium; - _selectedTags.clear(); notifyListeners(); } @@ -189,7 +67,7 @@ class TaskViewModel extends ChangeNotifier { } if (_filterTagId != null) { result = result - .where((t) => t.tags.any((tag) => tag.id == _filterTagId)) + .where((t) => t.tags.any((tag) => tag.id.toString() == _filterTagId)) .toList(); } diff --git a/src/lib/features/user/model/user_profile_model.dart b/src/lib/features/user/model/user_profile_model.dart index d378b4b..6f0fd50 100644 --- a/src/lib/features/user/model/user_profile_model.dart +++ b/src/lib/features/user/model/user_profile_model.dart @@ -6,6 +6,7 @@ class UserProfileModel { final String avatarUrl; bool isNotificationEnabled; String appearance; + final Map heatmapData; UserProfileModel({ required this.id, @@ -15,6 +16,7 @@ class UserProfileModel { required this.avatarUrl, this.isNotificationEnabled = true, this.appearance = 'Light', + required this.heatmapData, }); factory UserProfileModel.fromJson(Map json) { @@ -25,25 +27,44 @@ class UserProfileModel { return 0; } + Map parseHeatmap = {}; + if (json['heatmapData'] != null) { + final Map rawHeatmap = json['heatmapData']; + rawHeatmap.forEach((dateString, count) { + try { + parseHeatmap[DateTime.parse(dateString)] = parseInt(count); + } catch (e) { + // skip error + } + }); + } return UserProfileModel( id: json['id'] as String? ?? '', name: (json['name'] ?? json['full_name'] ?? json['username']) as String? ?? - 'Unknown User', + 'Unknown User', tasksDone: parseInt(json['tasksDone'] ?? json['tasks_done']), streaks: parseInt(json['streaks'] ?? json['streak_count']), avatarUrl: - (json['avatarUrl'] ?? json['avatar_url'] ?? json['avatar']) as String? ?? - '', + (json['avatarUrl'] ?? json['avatar_url'] ?? json['avatar']) + as String? ?? + '', isNotificationEnabled: - (json['isNotificationEnabled'] ?? json['is_notification_enabled']) as bool? ?? - true, - appearance: (json['appearance'] ?? json['theme_mode']) as String? ?? 'Light', + (json['isNotificationEnabled'] ?? json['is_notification_enabled']) + as bool? ?? + true, + appearance: + (json['appearance'] ?? json['theme_mode']) as String? ?? 'Light', + + heatmapData: parseHeatmap, ); } - Map toJson() { + Map heatmapJson = {}; + heatmapData.forEach((date, count) { + heatmapJson[date.toIso8601String().split('T').first] = count; + }); return { 'id': id, 'name': name, @@ -52,6 +73,7 @@ class UserProfileModel { 'avatarUrl': avatarUrl, 'isNotificationEnabled': isNotificationEnabled, 'appearance': appearance, + 'heatmapData': heatmapJson, }; } @@ -63,6 +85,7 @@ class UserProfileModel { String? avatarUrl, bool? isNotificationEnabled, String? appearance, + Map? heatmapData, }) { return UserProfileModel( id: id ?? this.id, @@ -70,8 +93,10 @@ class UserProfileModel { tasksDone: tasksDone ?? this.tasksDone, streaks: streaks ?? this.streaks, avatarUrl: avatarUrl ?? this.avatarUrl, - isNotificationEnabled: isNotificationEnabled ?? this.isNotificationEnabled, + isNotificationEnabled: + isNotificationEnabled ?? this.isNotificationEnabled, appearance: appearance ?? this.appearance, + heatmapData: heatmapData ?? this.heatmapData, ); } -} \ No newline at end of file +} diff --git a/src/lib/features/user/service/user_service.dart b/src/lib/features/user/service/user_service.dart index 9a6c0d7..c38a2db 100644 --- a/src/lib/features/user/service/user_service.dart +++ b/src/lib/features/user/service/user_service.dart @@ -8,7 +8,14 @@ class UserService { Future fetchUserProfile() async { // Mimic API call delay for smooth state switching try{ + final user = _supabase.auth.currentUser; + if (user == null) { + throw Exception("Không tìm thấy phiên đăng nhập. Hãy đăng nhập lại"); + } final response = await _supabase.rpc('get_user_profile_stats'); + if(response == null){ + throw Exception("Không thể lấy thông tin người dùng. Hãy thử lại sau"); + } response['id'] = _supabase.auth.currentUser!.id; return UserProfileModel.fromJson(response); } diff --git a/src/lib/features/user/view/user_profile_view.dart b/src/lib/features/user/view/user_profile_view.dart index 2e71926..1e57bd2 100644 --- a/src/lib/features/user/view/user_profile_view.dart +++ b/src/lib/features/user/view/user_profile_view.dart @@ -1,11 +1,13 @@ import 'package:flutter/material.dart'; +import 'package:flutter_heatmap_calendar/flutter_heatmap_calendar.dart'; import 'package:provider/provider.dart'; + import '../viewmodel/user_profile_viewmodel.dart'; +import 'widgets/logout_button.dart'; import 'widgets/profile_header.dart'; -import 'widgets/stat_card.dart'; -import 'widgets/settings_section.dart'; import 'widgets/settings_list_tile.dart'; -import 'widgets/logout_button.dart'; +import 'widgets/settings_section.dart'; +import 'widgets/stat_card.dart'; class UserProfileView extends StatelessWidget { const UserProfileView({super.key}); @@ -44,16 +46,16 @@ class UserProfileView extends StatelessWidget { duration: const Duration(milliseconds: 300), child: vm.isLoading ? Center( - key: ValueKey('loading'), - child: CircularProgressIndicator( - color: Theme.of(context).colorScheme.primary, - ), - ) + key: const ValueKey('loading'), + child: CircularProgressIndicator( + color: Theme.of(context).colorScheme.primary, + ), + ) : vm.user == null ? const Center( - key: ValueKey('error'), - child: Text("Error loading profile"), - ) + key: ValueKey('error'), + child: Text("Error loading profile"), + ) : Builder( builder: (innerContext) { vm.syncThemeWithProfile(innerContext); @@ -93,7 +95,7 @@ class UserProfileView extends StatelessWidget { child: StatCard( value: user.streaks.toString(), label: 'Streaks', - onTap: () {}, + onTap: () => _showHeatmapBottomSheet(context, vm), ), ), ], @@ -113,8 +115,9 @@ class UserProfileView extends StatelessWidget { value: user.isNotificationEnabled, activeColor: Theme.of(context).colorScheme.surface, activeTrackColor: Theme.of(context).colorScheme.primary, - inactiveThumbColor: - Theme.of(context).colorScheme.onSurfaceVariant, + inactiveThumbColor: Theme.of( + context, + ).colorScheme.onSurfaceVariant, inactiveTrackColor: Theme.of(context).colorScheme.outline, onChanged: (val) => vm.toggleNotification(val), ), @@ -153,4 +156,91 @@ class UserProfileView extends StatelessWidget { ), ); } -} \ No newline at end of file + + void _showHeatmapBottomSheet(BuildContext context, UserProfileViewModel vm) { + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Theme.of(context).colorScheme.surface, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + builder: (bottomSheetContext) { + return SafeArea( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Container( + width: 40, + height: 4, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.outline, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + const SizedBox(height: 24), + + Text( + 'Bản đồ hoạt động', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.onSurface, + ), + ), + const SizedBox(height: 8), + Text( + 'Giữ vững phong độ nhé! 🔥', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 24), + + Center( + child: HeatMap( + datasets: vm.user!.heatmapData, + colorMode: ColorMode.opacity, + showText: false, + scrollable: true, + size: 30, + + colorsets: { + 1: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.2), + 3: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.4), + 5: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.6), + 7: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.8), + 9: Theme.of(context).colorScheme.primary, + }, + onClick: (value) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Đã hoàn thành $value công việc'), + behavior: SnackBarBehavior.floating, + ), + ); + }, + ), + ), + const SizedBox(height: 16), + ], + ), + ), + ); + }, + ); + } +} diff --git a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart index 21b28c0..df62fcd 100644 --- a/src/lib/features/user/viewmodel/user_profile_viewmodel.dart +++ b/src/lib/features/user/viewmodel/user_profile_viewmodel.dart @@ -36,7 +36,12 @@ class UserProfileViewModel extends ChangeNotifier { _lastAppliedAppearance = null; } catch (e) { debugPrint("Error loading profile: $e"); - _user = _buildMockUser(); + + if (useMockData) { + _user = _buildMockUser(); + } else { + _user = null; + } } finally { _isLoading = false; notifyListeners(); @@ -44,15 +49,26 @@ class UserProfileViewModel extends ChangeNotifier { } UserProfileModel _buildMockUser() { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + + final Map mockHeatmapData = { + today.subtract(const Duration(days: 1)): 3, + today.subtract(const Duration(days: 2)): 7, + today.subtract(const Duration(days: 3)): 4, + today.subtract(const Duration(days: 4)): 8, + today.subtract(const Duration(days: 5)): 2, + today.subtract(const Duration(days: 8)): 5, + }; return UserProfileModel( id: 'mock-user-001', name: 'Alex Thompson', - // Valid URL so profile header can test normal network-avatar path. avatarUrl: 'https://i.pravatar.cc/300?img=12', appearance: 'Dark', tasksDone: 24, streaks: 12, isNotificationEnabled: true, + heatmapData: mockHeatmapData, ); } @@ -64,7 +80,6 @@ class UserProfileViewModel extends ChangeNotifier { } } - void updateAppearance(BuildContext context, String newAppearance) { if (_user != null) { _user!.appearance = newAppearance; @@ -72,7 +87,7 @@ class UserProfileViewModel extends ChangeNotifier { notifyListeners(); if (context.mounted) { - context.read().updateTheme(newAppearance); + context.read().updateTheme(newAppearance); } } } @@ -94,17 +109,16 @@ class UserProfileViewModel extends ChangeNotifier { if (context.mounted) { Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => const AuthGate()), - (route) => false, + (route) => false, ); } - } catch (e) { debugPrint("Lỗi đăng xuất: $e"); if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Lỗi đăng xuất: $e')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Lỗi đăng xuất: $e'))); } } } -} \ No newline at end of file +} diff --git a/src/lib/main.dart b/src/lib/main.dart index 1ab3077..3be01b7 100644 --- a/src/lib/main.dart +++ b/src/lib/main.dart @@ -2,7 +2,10 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:task_management_app/features/auth/presentation/view/auth_gate.dart'; +import 'package:task_management_app/features/auth/presentation/view/login_view.dart'; +import 'package:task_management_app/features/category/viewmodel/category_viewmodel.dart'; import 'package:task_management_app/features/main/view/screens/main_screen.dart'; +import 'package:task_management_app/features/tag/viewmodel/tag_viewmodel.dart'; import 'package:task_management_app/features/tasks/viewmodel/task_viewmodel.dart'; import 'core/theme/app_theme.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -35,6 +38,12 @@ Future main() async { ChangeNotifierProvider( create: (_) => TaskViewModel(), ), + ChangeNotifierProvider( + create: (_) => CategoryViewModel(), + ), + ChangeNotifierProvider( + create: (_) => TagViewModel(), + ), ], child: const TaskApp())); } diff --git a/src/pubspec.lock b/src/pubspec.lock index 7a21b3a..72a5d4a 100644 --- a/src/pubspec.lock +++ b/src/pubspec.lock @@ -53,10 +53,10 @@ packages: dependency: transitive description: name: characters - sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 url: "https://pub.dev" source: hosted - version: "1.4.1" + version: "1.4.0" clock: dependency: transitive description: @@ -198,6 +198,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.0.0" + flutter_heatmap_calendar: + dependency: "direct main" + description: + name: flutter_heatmap_calendar + sha256: "0933071844cd604b938e38358984244292ba1ba8f4b4b6f0f091f5927a23e958" + url: "https://pub.dev" + source: hosted + version: "1.0.5" flutter_lints: dependency: "direct dev" description: @@ -256,6 +264,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.3" + google_generative_ai: + dependency: "direct main" + description: + name: google_generative_ai + sha256: "71f613d0247968992ad87a0eb21650a566869757442ba55a31a81be6746e0d1f" + url: "https://pub.dev" + source: hosted + version: "0.4.7" gotrue: dependency: transitive description: @@ -420,18 +436,18 @@ packages: dependency: transitive description: name: matcher - sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 url: "https://pub.dev" source: hosted - version: "0.12.19" + version: "0.12.17" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.13.0" + version: "0.11.1" meta: dependency: transitive description: @@ -729,10 +745,10 @@ packages: dependency: transitive description: name: test_api - sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 url: "https://pub.dev" source: hosted - version: "0.7.10" + version: "0.7.7" typed_data: dependency: transitive description: diff --git a/src/pubspec.yaml b/src/pubspec.yaml index fa7e071..9afc694 100644 --- a/src/pubspec.yaml +++ b/src/pubspec.yaml @@ -41,7 +41,9 @@ dependencies: provider: ^6.1.5+1 flutter_ringtone_player: ^4.0.0+4 image_picker: ^1.2.1 - shared_preferences: ^2.5.5 + shared_preferences: ^2.2.2 + flutter_heatmap_calendar: ^1.0.5 + google_generative_ai: ^0.4.7 dev_dependencies: flutter_test: diff --git a/supabase/migrations/20260409084009_create_user_profile_rpc.sql b/supabase/migrations/20260409084009_create_user_profile_rpc.sql index 235c129..cfc71d1 100644 --- a/supabase/migrations/20260409084009_create_user_profile_rpc.sql +++ b/supabase/migrations/20260409084009_create_user_profile_rpc.sql @@ -1,7 +1,7 @@ CREATE OR REPLACE FUNCTION get_user_profile_stats() RETURNS JSON LANGUAGE plpgsql -SECURITY INVOKER -- Chạy với quyền của user hiện tại (Tôn trọng RLS) +SECURITY INVOKER AS $$ DECLARE v_user_id UUID; diff --git a/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql b/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql new file mode 100644 index 0000000..aa82198 --- /dev/null +++ b/supabase/migrations/20260413084521_update_user_profile_with_heatmap_rpc.sql @@ -0,0 +1,66 @@ +CREATE OR REPLACE FUNCTION get_user_profile_stats(p_days INT DEFAULT 90) +RETURNS JSON +LANGUAGE plpgsql +SECURITY INVOKER +AS $$ +DECLARE + v_user_id UUID; + v_username TEXT; + v_avatar TEXT; + v_tasks_done INT; + v_current_streak INT; + v_heatmap_data JSON; +BEGIN + v_user_id := auth.uid(); + + IF v_user_id IS NULL THEN + RAISE EXCEPTION 'User not authenticated'; + END IF; + + SELECT username, avatar INTO v_username, v_avatar + FROM public.profile + WHERE id = v_user_id; + + SELECT COUNT(*) INTO v_tasks_done + FROM public.task + WHERE profile_id = v_user_id AND status = 1; + + -- Get task done per day for heatmap + SELECT json_object_agg(task_date::TEXT, task_count) INTO v_heatmap_data + FROM ( + SELECT DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') AS task_date, COUNT(*) AS task_count + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + AND updated_at >= ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Ho_Chi_Minh')::DATE - (p_days || ' days')::INTERVAL) + GROUP BY DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') + ) t; + + WITH completed_dates AS ( + SELECT DISTINCT DATE(updated_at AT TIME ZONE 'Asia/Ho_Chi_Minh') AS task_date + FROM public.task + WHERE profile_id = v_user_id AND status = 1 + ), + streak_groups AS ( + SELECT task_date, + task_date - (ROW_NUMBER() OVER (ORDER BY task_date))::INT AS grp + FROM completed_dates + ), + streak_counts AS ( + SELECT grp, MAX(task_date) as end_date, COUNT(*) as streak_length + FROM streak_groups + GROUP BY grp + ) + SELECT COALESCE(MAX(streak_length), 0) INTO v_current_streak + FROM streak_counts + WHERE end_date >= ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Ho_Chi_Minh')::DATE - INTERVAL '1 day'); + + + RETURN json_build_object( + 'name', COALESCE(v_username, 'Unknown User'), + 'avatarUrl', COALESCE(v_avatar, ''), + 'tasksDone', COALESCE(v_tasks_done, 0), + 'streaks', COALESCE(v_current_streak, 0), + 'heatmapData', COALESCE(v_heatmap_data, '{}'::JSON) + ); +END; +$$; \ No newline at end of file diff --git a/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql b/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql new file mode 100644 index 0000000..197e189 --- /dev/null +++ b/supabase/migrations/20260417060333_chatbot_add_task_rpc.sql @@ -0,0 +1,52 @@ +CREATE OR REPLACE FUNCTION create_task_full( + p_title TEXT, + p_priority INT4, + p_profile_id UUID, + p_tag_names TEXT[] +) +RETURNS JSON +LANGUAGE plpgsql +AS $$ +DECLARE + v_task_id INT8; + v_tag_name TEXT; + v_tag_id INT8; +BEGIN + + INSERT INTO task (title, priority, profile_id, status) + VALUES (p_title, p_priority, p_profile_id, 0) + RETURNING id INTO v_task_id; + + IF p_tag_names IS NOT NULL THEN + FOREACH v_tag_name IN ARRAY p_tag_names + LOOP + v_tag_name := trim(v_tag_name); + + IF v_tag_name != '' THEN + INSERT INTO tag (name, profile_id, color_code) + VALUES (v_tag_name, p_profile_id, '#6200EE') + ON CONFLICT (name, profile_id) + DO UPDATE SET name = EXCLUDED.name + RETURNING id INTO v_tag_id; + + + INSERT INTO task_tags (task_id, tag_id) + VALUES (v_task_id, v_tag_id) + ON CONFLICT DO NOTHING; + END IF; + END LOOP; + END IF; + + RETURN json_build_object( + 'success', true, + 'task_id', v_task_id, + 'message', 'Đã tạo task với priority ' || p_priority + ); + +EXCEPTION WHEN OTHERS THEN + RETURN json_build_object( + 'success', false, + 'error', SQLERRM + ); +END; +$$; \ No newline at end of file From 0757bd7f31b25de20a034bddd81d3b997fd5a607 Mon Sep 17 00:00:00 2001 From: Tran Quang Ha Date: Sat, 18 Apr 2026 19:03:48 +0700 Subject: [PATCH 9/9] feat: integrate chatbot's ability to create task --- .../chatbot/services/chatbot_services.dart | 35 ++++++++-- ...957_chatbot_add_task_with_category_rpc.sql | 64 +++++++++++++++++++ 2 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 supabase/migrations/20260418111957_chatbot_add_task_with_category_rpc.sql diff --git a/src/lib/features/chatbot/services/chatbot_services.dart b/src/lib/features/chatbot/services/chatbot_services.dart index 70a4f78..c37a31f 100644 --- a/src/lib/features/chatbot/services/chatbot_services.dart +++ b/src/lib/features/chatbot/services/chatbot_services.dart @@ -41,6 +41,21 @@ class ChatBotAssistantService { description: 'Danh sách các thẻ phân loại (ví dụ: ["Học tập", "Gấp", "Backend"]). Gửi mảng rỗng [] nếu không có.', ), + 'start_time': Schema( + SchemaType.string, + description: + 'Thời gian bắt đầu công việc theo định dạng ISO 8601 (VD: 2026-04-18T15:00:00Z). Nếu người dùng không nói, hãy bỏ qua hoặc để rỗng.', + ), + 'due_time': Schema( + SchemaType.string, + description: + 'Thời gian kết thúc (deadline) theo định dạng ISO 8601. Nếu không có, bỏ qua.', + ), + 'category_name': Schema( + SchemaType.string, + description: + 'Phân loại công việc vào 1 trong 4 nhóm: "Cá nhân", "Học tập", "Công việc", hoặc "Giải trí". Nếu không phân loại được, mặc định trả về "Cá nhân".', + ), }, requiredProperties: ['title', 'priority', 'tags'], ), @@ -77,26 +92,38 @@ class ChatBotAssistantService { final priority = (args['priority'] as num?)?.toInt() ?? 1; final rawTags = args['tags'] as List? ?? []; final tags = rawTags.map((e) => e.toString()).toList(); + final startTime = args['start_time'] as String?; + final dueTime = args['due_time'] as String?; final userId = Supabase.instance.client.auth.currentUser?.id; if (userId == null) { return 'Vui lòng đăng nhập để tạo công việc.'; } - + final categoryName = args['category_name'] as String? ?? 'Cá nhân'; final dbResponse = await Supabase.instance.client.rpc( 'create_task_full', params: { - 'p_title': title, - 'p_priority': priority, + 'p_title': args['title'], + 'p_priority': (args['priority'] as num?)?.toInt() ?? 1, 'p_profile_id': userId, - 'p_tag_names': tags, + 'p_tag_names': + (args['tags'] as List?)?.map((e) => e.toString()).toList() ?? + [], + 'p_category_name': categoryName, + 'p_start_time': args['start_time'], + 'p_due_time': args['due_time'], }, ); final isSuccess = dbResponse['success'] == true; + if (!isSuccess) { + debugPrint("Lỗi từ Supabase: ${dbResponse['error']}"); + } final functionResponse = await _chatSession!.sendMessage( Content.functionResponse('create_task_full', { 'status': isSuccess ? 'Thành công' : 'Thất bại', + + 'reason': isSuccess ? '' : dbResponse['error'].toString(), }), ); return functionResponse.text ?? 'Đã xử lý xong yêu cầu của bạn!'; diff --git a/supabase/migrations/20260418111957_chatbot_add_task_with_category_rpc.sql b/supabase/migrations/20260418111957_chatbot_add_task_with_category_rpc.sql new file mode 100644 index 0000000..8005f71 --- /dev/null +++ b/supabase/migrations/20260418111957_chatbot_add_task_with_category_rpc.sql @@ -0,0 +1,64 @@ +CREATE OR REPLACE FUNCTION create_task_full( + p_title TEXT, + p_priority INT4, + p_profile_id UUID, + p_tag_names TEXT[], + p_category_name TEXT, + p_start_time TIMESTAMPTZ default null, + p_due_time TIMESTAMPTZ default null +) +RETURNS JSON +LANGUAGE plpgsql +AS $$ +DECLARE + v_task_id INT8; + v_tag_name TEXT; + v_tag_id INT8; + v_category_id INT8; +BEGIN + SELECT id INTO v_category_id + FROM category + WHERE profile_id = p_profile_id AND name ILIKE p_category_name + LIMIT 1; + + IF v_category_id IS NULL THEN + SELECT id INTO v_category_id FROM category WHERE profile_id = p_profile_id AND name = 'Cá nhân' LIMIT 1; + END IF; + + INSERT INTO task (title, priority, profile_id, status, category_id,start_time,due_time) + VALUES (p_title, p_priority, p_profile_id, 0,v_category_id,p_start_time,p_due_time) + RETURNING id INTO v_task_id; + + IF p_tag_names IS NOT NULL THEN + FOREACH v_tag_name IN ARRAY p_tag_names + LOOP + v_tag_name := trim(v_tag_name); + + IF v_tag_name != '' THEN + INSERT INTO tag (name, profile_id, color_code) + VALUES (v_tag_name, p_profile_id, '#6200EE') + ON CONFLICT (name, profile_id) + DO UPDATE SET name = EXCLUDED.name + RETURNING id INTO v_tag_id; + + + INSERT INTO task_tags (task_id, tag_id) + VALUES (v_task_id, v_tag_id) + ON CONFLICT DO NOTHING; + END IF; + END LOOP; + END IF; + + RETURN json_build_object( + 'success', true, + 'task_id', v_task_id, + 'message', 'Đã tạo task với priority ' || p_priority + ); + +EXCEPTION WHEN OTHERS THEN + RETURN json_build_object( + 'success', false, + 'error', SQLERRM + ); +END; +$$; \ No newline at end of file