Initial commit - app-padrao-1.0

This commit is contained in:
Erik Silva
2025-12-19 23:29:24 -03:00
commit ec76d3d633
205 changed files with 13131 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
import 'package:hive/hive.dart';
part 'user_model.g.dart';
@HiveType(typeId: 0)
class UserModel extends HiveObject {
@HiveField(0)
final String id;
@HiveField(1)
final String email;
@HiveField(2)
final String passwordHash;
@HiveField(3)
final String barberName;
@HiveField(4)
final String barberShopName;
@HiveField(5)
final DateTime createdAt;
UserModel({
required this.id,
required this.email,
required this.passwordHash,
required this.barberName,
required this.barberShopName,
required this.createdAt,
});
UserModel copyWith({
String? id,
String? email,
String? passwordHash,
String? barberName,
String? barberShopName,
DateTime? createdAt,
}) {
return UserModel(
id: id ?? this.id,
email: email ?? this.email,
passwordHash: passwordHash ?? this.passwordHash,
barberName: barberName ?? this.barberName,
barberShopName: barberShopName ?? this.barberShopName,
createdAt: createdAt ?? this.createdAt,
);
}
}

View File

@@ -0,0 +1,56 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'user_model.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class UserModelAdapter extends TypeAdapter<UserModel> {
@override
final int typeId = 0;
@override
UserModel read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return UserModel(
id: fields[0] as String,
email: fields[1] as String,
passwordHash: fields[2] as String,
barberName: fields[3] as String,
barberShopName: fields[4] as String,
createdAt: fields[5] as DateTime,
);
}
@override
void write(BinaryWriter writer, UserModel obj) {
writer
..writeByte(6)
..writeByte(0)
..write(obj.id)
..writeByte(1)
..write(obj.email)
..writeByte(2)
..write(obj.passwordHash)
..writeByte(3)
..write(obj.barberName)
..writeByte(4)
..write(obj.barberShopName)
..writeByte(5)
..write(obj.createdAt);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is UserModelAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}

View File

@@ -0,0 +1,130 @@
import 'package:uuid/uuid.dart';
import 'package:barber_app/core/database/database_service.dart';
import 'package:barber_app/core/utils/password_utils.dart';
import 'package:barber_app/features/auth/data/models/user_model.dart';
import 'package:barber_app/features/settings/data/models/settings_model.dart';
class AuthRepository {
final _uuid = const Uuid();
// Registrar novo usuário
Future<UserModel?> register({
required String email,
required String password,
required String barberName,
required String barberShopName,
}) async {
try {
// Verifica se email já existe
final existingUser = DatabaseService.usersBoxInstance.values
.where((user) => user.email.toLowerCase() == email.toLowerCase())
.firstOrNull;
if (existingUser != null) {
throw Exception('E-mail já cadastrado');
}
final userId = _uuid.v4();
final user = UserModel(
id: userId,
email: email.toLowerCase().trim(),
passwordHash: PasswordUtils.hashPassword(password),
barberName: barberName.trim(),
barberShopName: barberShopName.trim(),
createdAt: DateTime.now(),
);
await DatabaseService.usersBoxInstance.put(userId, user);
// Cria configurações padrão
final settings = SettingsModel(userId: userId);
await DatabaseService.settingsBoxInstance.put(userId, settings);
// Define como usuário atual
await DatabaseService.setCurrentUserId(userId);
return user;
} catch (e) {
rethrow;
}
}
// Login
Future<UserModel?> login({
required String email,
required String password,
}) async {
try {
final user = DatabaseService.usersBoxInstance.values
.where((u) => u.email.toLowerCase() == email.toLowerCase().trim())
.firstOrNull;
if (user == null) {
throw Exception('Usuário não encontrado');
}
if (!PasswordUtils.verifyPassword(password, user.passwordHash)) {
throw Exception('Senha incorreta');
}
await DatabaseService.setCurrentUserId(user.id);
return user;
} catch (e) {
rethrow;
}
}
// Logout
Future<void> logout() async {
await DatabaseService.setCurrentUserId(null);
}
// Obter usuário atual
UserModel? getCurrentUser() {
final userId = DatabaseService.getCurrentUserId();
if (userId == null) return null;
return DatabaseService.usersBoxInstance.get(userId);
}
// Verificar se está logado
bool isLoggedIn() {
return DatabaseService.isLoggedIn();
}
// Atualizar perfil
Future<UserModel?> updateProfile({
required String barberName,
required String barberShopName,
}) async {
final currentUser = getCurrentUser();
if (currentUser == null) return null;
final updatedUser = currentUser.copyWith(
barberName: barberName.trim(),
barberShopName: barberShopName.trim(),
);
await DatabaseService.usersBoxInstance.put(currentUser.id, updatedUser);
return updatedUser;
}
// Alterar senha
Future<bool> changePassword({
required String currentPassword,
required String newPassword,
}) async {
final currentUser = getCurrentUser();
if (currentUser == null) return false;
if (!PasswordUtils.verifyPassword(currentPassword, currentUser.passwordHash)) {
throw Exception('Senha atual incorreta');
}
final updatedUser = currentUser.copyWith(
passwordHash: PasswordUtils.hashPassword(newPassword),
);
await DatabaseService.usersBoxInstance.put(currentUser.id, updatedUser);
return true;
}
}

View File

@@ -0,0 +1,156 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:barber_app/features/auth/data/models/user_model.dart';
import 'package:barber_app/features/auth/data/repositories/auth_repository.dart';
// Events
abstract class AuthEvent extends Equatable {
const AuthEvent();
@override
List<Object?> get props => [];
}
class AuthCheckRequested extends AuthEvent {}
class AuthLoginRequested extends AuthEvent {
final String email;
final String password;
const AuthLoginRequested({required this.email, required this.password});
@override
List<Object?> get props => [email, password];
}
class AuthRegisterRequested extends AuthEvent {
final String email;
final String password;
final String barberName;
final String barberShopName;
const AuthRegisterRequested({
required this.email,
required this.password,
required this.barberName,
required this.barberShopName,
});
@override
List<Object?> get props => [email, password, barberName, barberShopName];
}
class AuthLogoutRequested extends AuthEvent {}
// States
abstract class AuthState extends Equatable {
const AuthState();
@override
List<Object?> get props => [];
}
class AuthInitial extends AuthState {}
class AuthLoading extends AuthState {}
class AuthAuthenticated extends AuthState {
final UserModel user;
const AuthAuthenticated(this.user);
@override
List<Object?> get props => [user];
}
class AuthUnauthenticated extends AuthState {}
class AuthError extends AuthState {
final String message;
const AuthError(this.message);
@override
List<Object?> get props => [message];
}
// Bloc
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final AuthRepository _authRepository;
AuthBloc({required AuthRepository authRepository})
: _authRepository = authRepository,
super(AuthInitial()) {
on<AuthCheckRequested>(_onCheckRequested);
on<AuthLoginRequested>(_onLoginRequested);
on<AuthRegisterRequested>(_onRegisterRequested);
on<AuthLogoutRequested>(_onLogoutRequested);
}
Future<void> _onCheckRequested(
AuthCheckRequested event,
Emitter<AuthState> emit,
) async {
emit(AuthLoading());
try {
final user = _authRepository.getCurrentUser();
if (user != null) {
emit(AuthAuthenticated(user));
} else {
emit(AuthUnauthenticated());
}
} catch (e) {
emit(AuthUnauthenticated());
}
}
Future<void> _onLoginRequested(
AuthLoginRequested event,
Emitter<AuthState> emit,
) async {
emit(AuthLoading());
try {
final user = await _authRepository.login(
email: event.email,
password: event.password,
);
if (user != null) {
emit(AuthAuthenticated(user));
} else {
emit(const AuthError('Erro ao fazer login'));
}
} catch (e) {
emit(AuthError(e.toString().replaceAll('Exception: ', '')));
}
}
Future<void> _onRegisterRequested(
AuthRegisterRequested event,
Emitter<AuthState> emit,
) async {
emit(AuthLoading());
try {
final user = await _authRepository.register(
email: event.email,
password: event.password,
barberName: event.barberName,
barberShopName: event.barberShopName,
);
if (user != null) {
emit(AuthAuthenticated(user));
} else {
emit(const AuthError('Erro ao criar conta'));
}
} catch (e) {
emit(AuthError(e.toString().replaceAll('Exception: ', '')));
}
}
Future<void> _onLogoutRequested(
AuthLogoutRequested event,
Emitter<AuthState> emit,
) async {
await _authRepository.logout();
emit(AuthUnauthenticated());
}
}

View File

@@ -0,0 +1,257 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:barber_app/core/theme/app_theme.dart';
import 'package:barber_app/core/constants/app_strings.dart';
import 'package:barber_app/features/auth/presentation/bloc/auth_bloc.dart';
import 'package:barber_app/features/auth/presentation/pages/register_page.dart';
import 'package:barber_app/features/home/presentation/pages/home_page.dart';
import 'package:barber_app/shared/widgets/custom_text_field.dart';
import 'package:barber_app/shared/widgets/loading_button.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage>
with SingleTickerProviderStateMixin {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
bool _obscurePassword = true;
late AnimationController _animationController;
late Animation<double> _fadeAnimation;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 800),
);
_fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
);
_animationController.forward();
}
@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
_animationController.dispose();
super.dispose();
}
void _onLogin() {
if (_formKey.currentState?.validate() ?? false) {
context.read<AuthBloc>().add(
AuthLoginRequested(
email: _emailController.text,
password: _passwordController.text,
),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is AuthAuthenticated) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (_) => const HomePage()),
);
} else if (state is AuthError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.message),
backgroundColor: AppColors.error,
),
);
}
},
child: SafeArea(
child: FadeTransition(
opacity: _fadeAnimation,
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 60),
// Logo e título
_buildHeader(),
const SizedBox(height: 60),
// Campos de formulário
_buildForm(),
const SizedBox(height: 24),
// Botão de login
_buildLoginButton(),
const SizedBox(height: 16),
// Link para registro
_buildRegisterLink(),
],
),
),
),
),
),
),
);
}
Widget _buildHeader() {
return Column(
children: [
const SizedBox(height: 40),
// Ícone/Logo imersivo com brilho
Container(
width: 120,
height: 120,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: AppColors.goldGradient,
boxShadow: AppColors.premiumShadow,
border: Border.all(
color: Colors.white.withValues(alpha: 0.1),
width: 1.5,
),
),
child: const Center(
child: Icon(
Icons.content_cut_rounded,
size: 55,
color: Colors.black,
),
),
),
const SizedBox(height: 40),
Text(
'ELITE BARBER',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.w900,
fontFamily: 'Outfit',
letterSpacing: 4,
color: AppColors.textPrimary,
),
),
const SizedBox(height: 12),
Text(
'O PODER DA GESTÃO EM SUAS MÃOS',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w800,
letterSpacing: 2,
color: AppColors.primaryColor,
),
),
],
);
}
Widget _buildForm() {
return Column(
children: [
CustomTextField(
controller: _emailController,
label: AppStrings.email,
hint: 'seu@email.com',
keyboardType: TextInputType.emailAddress,
prefixIcon: Icons.email_outlined,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Informe o e-mail';
}
if (!value.contains('@')) {
return AppStrings.invalidEmail;
}
return null;
},
),
const SizedBox(height: 16),
CustomTextField(
controller: _passwordController,
label: AppStrings.password,
hint: '••••••',
obscureText: _obscurePassword,
prefixIcon: Icons.lock_outline,
suffixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility_off : Icons.visibility,
color: AppColors.textSecondary,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Informe a senha';
}
return null;
},
),
],
);
}
Widget _buildLoginButton() {
return BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: AppColors.primaryColor.withValues(alpha: 0.2),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: LoadingButton(
text: 'ENTRAR NO SISTEMA',
isLoading: state is AuthLoading,
onPressed: _onLogin,
),
);
},
);
}
Widget _buildRegisterLink() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Não tem uma conta? ',
style: TextStyle(color: AppColors.textSecondary),
),
TextButton(
onPressed: () {
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const RegisterPage()));
},
child: Text(
AppStrings.createAccount,
style: TextStyle(
color: AppColors.primaryColor,
fontWeight: FontWeight.bold,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,238 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:barber_app/core/theme/app_theme.dart';
import 'package:barber_app/core/constants/app_strings.dart';
import 'package:barber_app/features/auth/presentation/bloc/auth_bloc.dart';
import 'package:barber_app/features/home/presentation/pages/home_page.dart';
import 'package:barber_app/shared/widgets/custom_text_field.dart';
import 'package:barber_app/shared/widgets/loading_button.dart';
class RegisterPage extends StatefulWidget {
const RegisterPage({super.key});
@override
State<RegisterPage> createState() => _RegisterPageState();
}
class _RegisterPageState extends State<RegisterPage> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _confirmPasswordController = TextEditingController();
final _barberNameController = TextEditingController();
final _barberShopNameController = TextEditingController();
bool _obscurePassword = true;
bool _obscureConfirmPassword = true;
@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
_confirmPasswordController.dispose();
_barberNameController.dispose();
_barberShopNameController.dispose();
super.dispose();
}
void _onRegister() {
if (_formKey.currentState?.validate() ?? false) {
context.read<AuthBloc>().add(AuthRegisterRequested(
email: _emailController.text,
password: _passwordController.text,
barberName: _barberNameController.text,
barberShopName: _barberShopNameController.text,
));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(AppStrings.createAccount),
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () => Navigator.of(context).pop(),
),
),
body: BlocListener<AuthBloc, AuthState>(
listener: (context, state) {
if (state is AuthAuthenticated) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => const HomePage()),
(route) => false,
);
} else if (state is AuthError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.message),
backgroundColor: AppColors.error,
),
);
}
},
child: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 24),
// Dados da barbearia
_buildSectionTitle('Dados da Barbearia'),
const SizedBox(height: 16),
CustomTextField(
controller: _barberShopNameController,
label: AppStrings.barberShopName,
hint: 'Ex: Barbearia do João',
prefixIcon: Icons.store_outlined,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Informe o nome da barbearia';
}
return null;
},
),
const SizedBox(height: 16),
CustomTextField(
controller: _barberNameController,
label: AppStrings.barberName,
hint: 'Seu nome',
prefixIcon: Icons.person_outline,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Informe seu nome';
}
return null;
},
),
const SizedBox(height: 32),
// Dados de acesso
_buildSectionTitle('Dados de Acesso'),
const SizedBox(height: 16),
CustomTextField(
controller: _emailController,
label: AppStrings.email,
hint: 'seu@email.com',
keyboardType: TextInputType.emailAddress,
prefixIcon: Icons.email_outlined,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Informe o e-mail';
}
if (!value.contains('@')) {
return AppStrings.invalidEmail;
}
return null;
},
),
const SizedBox(height: 16),
CustomTextField(
controller: _passwordController,
label: AppStrings.password,
hint: 'Mínimo 6 caracteres',
obscureText: _obscurePassword,
prefixIcon: Icons.lock_outline,
suffixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility_off : Icons.visibility,
color: AppColors.textSecondary,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Informe a senha';
}
if (value.length < 6) {
return AppStrings.weakPassword;
}
return null;
},
),
const SizedBox(height: 16),
CustomTextField(
controller: _confirmPasswordController,
label: AppStrings.confirmPassword,
hint: 'Repita a senha',
obscureText: _obscureConfirmPassword,
prefixIcon: Icons.lock_outline,
suffixIcon: IconButton(
icon: Icon(
_obscureConfirmPassword ? Icons.visibility_off : Icons.visibility,
color: AppColors.textSecondary,
),
onPressed: () {
setState(() {
_obscureConfirmPassword = !_obscureConfirmPassword;
});
},
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Confirme a senha';
}
if (value != _passwordController.text) {
return AppStrings.passwordsDontMatch;
}
return null;
},
),
const SizedBox(height: 32),
// Botão de registro
BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
return LoadingButton(
text: AppStrings.createAccount,
isLoading: state is AuthLoading,
onPressed: _onRegister,
);
},
),
const SizedBox(height: 16),
// Link para login
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Já tem uma conta? ',
style: TextStyle(color: AppColors.textSecondary),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(
AppStrings.login,
style: TextStyle(
color: AppColors.primaryColor,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 24),
],
),
),
),
),
),
);
}
Widget _buildSectionTitle(String title) {
return Text(
title,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: AppColors.primaryColor,
fontWeight: FontWeight.bold,
),
);
}
}