Files
chat/client/flutter/lib/providers/invite_provider.dart
2026-04-25 16:36:34 +08:00

136 lines
3.3 KiB
Dart

import 'package:flutter/material.dart';
import 'package:sales_chat/models/group.dart';
import 'package:sales_chat/models/invite.dart';
import 'package:sales_chat/services/api_service.dart';
class InviteProvider with ChangeNotifier {
final ApiService _apiService;
List<Invite> _invites = [];
Invite? _selectedInvite;
InviteStats? _selectedInviteStats;
List<Group> _availableGroups = [];
bool _isLoading = false;
bool _isCreating = false;
String? _error;
InviteProvider(this._apiService);
List<Invite> get invites => _invites;
Invite? get selectedInvite => _selectedInvite;
InviteStats? get selectedInviteStats => _selectedInviteStats;
List<Group> get availableGroups => _availableGroups;
bool get isLoading => _isLoading;
bool get isCreating => _isCreating;
String? get error => _error;
Future<void> loadInvites() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_invites = await _apiService.getMyInvites();
_isLoading = false;
notifyListeners();
} catch (e) {
_error = 'Failed to load invite list';
_isLoading = false;
notifyListeners();
}
}
Future<void> loadAvailableGroups(List<Group> groups) async {
_availableGroups = groups;
notifyListeners();
}
Future<Invite?> createInvite({
required String groupId,
int? expiresInDays,
}) async {
_isCreating = true;
_error = null;
notifyListeners();
try {
final invite = await _apiService.createInvite(
groupId: groupId,
expiresInDays: expiresInDays,
);
_invites.insert(0, invite);
_isCreating = false;
notifyListeners();
return invite;
} catch (e) {
_error = 'Failed to create invite';
_isCreating = false;
notifyListeners();
return null;
}
}
Future<void> selectInvite(Invite invite) async {
_selectedInvite = invite;
notifyListeners();
await loadInviteStats(invite.code);
}
Future<void> loadInviteStats(String code) async {
try {
_selectedInviteStats = await _apiService.getInviteStats(code);
notifyListeners();
} catch (e) {
// Handle error silently
}
}
Future<void> deactivateInvite(String code) async {
try {
await _apiService.deactivateInvite(code);
final index = _invites.indexWhere((i) => i.code == code);
if (index != -1) {
final invite = _invites[index];
_invites[index] = Invite(
id: invite.id,
code: invite.code,
salesId: invite.salesId,
groupId: invite.groupId,
link: invite.link,
qrCodeUrl: invite.qrCodeUrl,
createdAt: invite.createdAt,
expiresAt: invite.expiresAt,
clickCount: invite.clickCount,
scanCount: invite.scanCount,
joinCount: invite.joinCount,
status: 'inactive',
);
}
if (_selectedInvite?.code == code) {
_selectedInvite = null;
_selectedInviteStats = null;
}
notifyListeners();
} catch (e) {
_error = 'Failed to deactivate invite';
notifyListeners();
}
}
void clearError() {
_error = null;
notifyListeners();
}
void clearSelection() {
_selectedInvite = null;
_selectedInviteStats = null;
notifyListeners();
}
}