237 lines
7.9 KiB
Dart
237 lines
7.9 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
|
|
import '../../../app/app_services.dart';
|
|
import '../../../core/config/server_url_validator.dart';
|
|
import '../../../core/widgets/app_button.dart';
|
|
import '../../../core/widgets/error_view.dart';
|
|
import '../../../core/widgets/loading_view.dart';
|
|
import '../../../domain/entities/app_settings.dart';
|
|
|
|
class SettingsScreen extends StatefulWidget {
|
|
const SettingsScreen({required this.services, super.key});
|
|
|
|
final AppServices services;
|
|
|
|
@override
|
|
State<SettingsScreen> createState() => _SettingsScreenState();
|
|
}
|
|
|
|
class _SettingsScreenState extends State<SettingsScreen> {
|
|
final _formKey = GlobalKey<FormState>();
|
|
final _serverUrlController = TextEditingController();
|
|
final _identifierController = TextEditingController();
|
|
bool _loading = true;
|
|
bool _saving = false;
|
|
bool _testing = false;
|
|
Object? _loadError;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_loadSettings();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_serverUrlController.dispose();
|
|
_identifierController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
Future<void> _loadSettings() async {
|
|
setState(() {
|
|
_loading = true;
|
|
_loadError = null;
|
|
});
|
|
try {
|
|
final settings = await widget.services.settingsRepository.load();
|
|
if (!mounted) return;
|
|
_serverUrlController.text = settings?.serverUrl ?? '';
|
|
_identifierController.text = settings?.companyIdentifier ?? '';
|
|
setState(() => _loading = false);
|
|
} catch (error) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_loadError = error;
|
|
_loading = false;
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
String? _validateServerUrl(String? value) =>
|
|
ServerUrlValidator.validate(value ?? '');
|
|
|
|
String? _validateIdentifier(String? value) {
|
|
final identifier = value?.trim() ?? '';
|
|
if (identifier.isEmpty) return 'Informe o identificador da empresa.';
|
|
if (identifier.length > 14 ||
|
|
!RegExp(r'^[a-zA-Z0-9]+$').hasMatch(identifier)) {
|
|
return 'Use até 14 letras ou números.';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
AppSettings _formSettings() => AppSettings(
|
|
serverUrl: _serverUrlController.text.trim(),
|
|
companyIdentifier: _identifierController.text.trim(),
|
|
);
|
|
|
|
Future<void> _testConnection() async {
|
|
if (_testing || !_formKey.currentState!.validate()) return;
|
|
setState(() => _testing = true);
|
|
try {
|
|
final result = await widget.services.connectionTester.test(
|
|
Uri.parse(_serverUrlController.text.trim()),
|
|
);
|
|
if (mounted) _showMessage(result.message);
|
|
} catch (_) {
|
|
if (mounted) {
|
|
_showMessage('Não foi possível testar a conexão. Tente novamente.');
|
|
}
|
|
} finally {
|
|
if (mounted) setState(() => _testing = false);
|
|
}
|
|
}
|
|
|
|
Future<void> _save() async {
|
|
if (_saving || !_formKey.currentState!.validate()) return;
|
|
setState(() => _saving = true);
|
|
try {
|
|
final settings = _formSettings();
|
|
final previous = await widget.services.settingsRepository.load();
|
|
if (previous != settings) {
|
|
await widget.services.authRepository.logout();
|
|
}
|
|
await widget.services.settingsRepository.save(settings);
|
|
if (mounted) {
|
|
_showMessage('Configuração salva.');
|
|
Navigator.of(context).pop();
|
|
}
|
|
} catch (_) {
|
|
if (mounted) _showMessage('Não foi possível salvar a configuração.');
|
|
} finally {
|
|
if (mounted) setState(() => _saving = false);
|
|
}
|
|
}
|
|
|
|
void _showMessage(String message) {
|
|
ScaffoldMessenger.of(context)
|
|
..hideCurrentSnackBar()
|
|
..showSnackBar(SnackBar(content: Text(message)));
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
if (_loading) {
|
|
return const Scaffold(
|
|
body: LoadingView(message: 'Carregando configuração...'));
|
|
}
|
|
if (_loadError != null) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
automaticallyImplyLeading: false,
|
|
title: const Text('Configuração'),
|
|
),
|
|
body: ErrorView(
|
|
message: 'Não foi possível carregar a configuração.',
|
|
onRetry: _loadSettings,
|
|
),
|
|
);
|
|
}
|
|
|
|
final busy = _saving || _testing;
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
automaticallyImplyLeading: false,
|
|
title: const Text('Configuração'),
|
|
),
|
|
body: SafeArea(
|
|
child: Center(
|
|
child: SingleChildScrollView(
|
|
padding: const EdgeInsets.all(24),
|
|
child: ConstrainedBox(
|
|
constraints: const BoxConstraints(maxWidth: 520),
|
|
child: Form(
|
|
key: _formKey,
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
const SizedBox(height: 24),
|
|
TextFormField(
|
|
key: const Key('settings-server-url'),
|
|
controller: _serverUrlController,
|
|
enabled: !busy,
|
|
keyboardType: TextInputType.url,
|
|
textInputAction: TextInputAction.next,
|
|
autocorrect: false,
|
|
decoration: const InputDecoration(
|
|
labelText: 'Servidor (URL)',
|
|
hintText: 'https://odoo.exemplo.com',
|
|
helperText:
|
|
'Aceita HTTP e HTTPS. HTTP não criptografa os dados.',
|
|
prefixIcon: Icon(Icons.language),
|
|
),
|
|
validator: _validateServerUrl,
|
|
),
|
|
const SizedBox(height: 16),
|
|
TextFormField(
|
|
key: const Key('settings-company-identifier'),
|
|
controller: _identifierController,
|
|
enabled: !busy,
|
|
maxLength: 14,
|
|
textCapitalization: TextCapitalization.characters,
|
|
textInputAction: TextInputAction.done,
|
|
inputFormatters: [
|
|
FilteringTextInputFormatter.allow(
|
|
RegExp('[a-zA-Z0-9]')),
|
|
LengthLimitingTextInputFormatter(14),
|
|
],
|
|
decoration: const InputDecoration(
|
|
labelText: 'CNPJ',
|
|
prefixIcon: Icon(Icons.business_outlined),
|
|
),
|
|
validator: _validateIdentifier,
|
|
),
|
|
const SizedBox(height: 8),
|
|
OutlinedButton.icon(
|
|
key: const Key('test-connection-button'),
|
|
onPressed: busy ? null : _testConnection,
|
|
icon: _testing
|
|
? const SizedBox.square(
|
|
dimension: 18,
|
|
child: CircularProgressIndicator(strokeWidth: 2),
|
|
)
|
|
: const Icon(Icons.wifi_tethering),
|
|
label: const Text('Testar conexão'),
|
|
style: OutlinedButton.styleFrom(
|
|
minimumSize: const Size.fromHeight(52),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(height: 12),
|
|
AppButton(
|
|
label: _saving ? 'Salvando...' : 'Salvar',
|
|
icon: Icons.save_outlined,
|
|
onPressed: busy ? null : _save,
|
|
),
|
|
const SizedBox(height: 8),
|
|
TextButton(
|
|
onPressed:
|
|
busy ? null : () => Navigator.of(context).pop(),
|
|
child: const Text('Cancelar'),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|