This commit is contained in:
Ashwin 2025-12-17 19:30:33 +05:30
parent 99a1542fe1
commit 7b8225a293
4 changed files with 456 additions and 36 deletions

View file

@ -67,7 +67,7 @@ class ApiConfig {
static String get accounts => '$apiBaseUrl/accounts/';
/// Opportunities (deals) management
static String get opportunities => '$apiBaseUrl/opportunity/';
static String get opportunities => '$apiBaseUrl/opportunities/';
/// Tasks management
static String get tasks => '$apiBaseUrl/tasks/';

View file

@ -98,11 +98,13 @@ enum DealStage {
/// Get display name (alias for label)
String get displayName => label;
static DealStage fromString(String value) {
switch (value.toLowerCase().replaceAll('-', '').replaceAll('_', '')) {
static DealStage fromString(String? value) {
if (value == null) return DealStage.prospecting;
switch (value.toLowerCase().replaceAll('-', '').replaceAll('_', '').replaceAll(' ', '')) {
case 'prospecting':
return DealStage.prospecting;
case 'qualified':
case 'qualification': // Backend uses QUALIFICATION
return DealStage.qualified;
case 'proposal':
return DealStage.proposal;
@ -188,6 +190,125 @@ class Deal {
required this.updatedAt,
});
/// Factory constructor to create Deal from JSON (backend API)
factory Deal.fromJson(Map<String, dynamic> json) {
// Parse tags
List<String> parsedTags = [];
if (json['tags'] != null) {
final tagsList = json['tags'] as List<dynamic>? ?? [];
parsedTags = tagsList.map((t) {
if (t is Map<String, dynamic>) {
return t['name'] as String? ?? '';
}
return t.toString();
}).where((t) => t.isNotEmpty).toList();
}
// Parse assigned_to - get first person's email for display
String assignedToName = 'Unassigned';
if (json['assigned_to'] != null) {
final assignedList = json['assigned_to'] as List<dynamic>? ?? [];
if (assignedList.isNotEmpty) {
final first = assignedList.first;
if (first is Map<String, dynamic>) {
final email = first['user']?['email'] as String? ??
first['user__email'] as String? ?? '';
assignedToName = email.split('@').first;
if (assignedToName.isEmpty) assignedToName = 'Assigned';
}
}
}
// Parse account/company name
String companyName = 'No Account';
if (json['account'] != null && json['account'] is Map<String, dynamic>) {
companyName = json['account']['name'] as String? ?? 'No Account';
}
// Parse products/line_items
List<DealProduct> products = [];
if (json['line_items'] != null) {
final lineItems = json['line_items'] as List<dynamic>? ?? [];
products = lineItems.map((item) {
if (item is Map<String, dynamic>) {
// Parse quantity - can be num or string
int qty = 1;
if (item['quantity'] != null) {
if (item['quantity'] is num) {
qty = (item['quantity'] as num).toInt();
} else if (item['quantity'] is String) {
qty = int.tryParse(item['quantity'] as String) ?? 1;
}
}
// Parse unit_price - can be num or string
double price = 0.0;
if (item['unit_price'] != null) {
if (item['unit_price'] is num) {
price = (item['unit_price'] as num).toDouble();
} else if (item['unit_price'] is String) {
price = double.tryParse(item['unit_price'] as String) ?? 0.0;
}
}
return DealProduct(
id: item['id']?.toString() ?? '',
name: item['name'] as String? ?? '',
quantity: qty,
unitPrice: price,
);
}
return const DealProduct(id: '', name: '', quantity: 0, unitPrice: 0);
}).where((p) => p.id.isNotEmpty).toList();
}
// Parse close date
DateTime? closeDate;
if (json['closed_on'] != null) {
closeDate = DateTime.tryParse(json['closed_on'] as String);
}
// Parse amount - can be num or string
double amount = 0.0;
if (json['amount'] != null) {
if (json['amount'] is num) {
amount = (json['amount'] as num).toDouble();
} else if (json['amount'] is String) {
amount = double.tryParse(json['amount'] as String) ?? 0.0;
}
}
// Parse probability - can be num or string
int probability = 0;
if (json['probability'] != null) {
if (json['probability'] is num) {
probability = (json['probability'] as num).toInt();
} else if (json['probability'] is String) {
probability = int.tryParse(json['probability'] as String) ?? 0;
}
}
return Deal(
id: json['id']?.toString() ?? '',
title: json['name'] as String? ?? '',
value: amount,
stage: DealStage.fromString(json['stage'] as String?),
probability: probability,
closeDate: closeDate,
leadId: null, // API doesn't have lead reference directly
companyName: companyName,
products: products,
assignedTo: assignedToName,
priority: Priority.medium, // API doesn't have priority, default to medium
labels: parsedTags,
notes: json['description'] as String?,
createdAt: json['created_at'] != null
? DateTime.tryParse(json['created_at'] as String) ?? DateTime.now()
: DateTime.now(),
updatedAt: json['created_at'] != null
? DateTime.tryParse(json['created_at'] as String) ?? DateTime.now()
: DateTime.now(),
);
}
/// Get weighted value based on probability
double get weightedValue => value * (probability / 100);

View file

@ -0,0 +1,234 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../config/api_config.dart';
import '../data/models/deal.dart';
import '../services/api_service.dart';
/// Deals list state
class DealsState {
final List<Deal> deals;
final bool isLoading;
final String? error;
final int totalCount;
final bool hasMore;
final int currentOffset;
const DealsState({
this.deals = const [],
this.isLoading = false,
this.error,
this.totalCount = 0,
this.hasMore = true,
this.currentOffset = 0,
});
const DealsState.initial()
: deals = const [],
isLoading = false,
error = null,
totalCount = 0,
hasMore = true,
currentOffset = 0;
DealsState copyWith({
List<Deal>? deals,
bool? isLoading,
String? error,
int? totalCount,
bool? hasMore,
int? currentOffset,
bool clearError = false,
}) {
return DealsState(
deals: deals ?? this.deals,
isLoading: isLoading ?? this.isLoading,
error: clearError ? null : (error ?? this.error),
totalCount: totalCount ?? this.totalCount,
hasMore: hasMore ?? this.hasMore,
currentOffset: currentOffset ?? this.currentOffset,
);
}
}
/// Deals notifier for managing deals state
class DealsNotifier extends StateNotifier<DealsState> {
DealsNotifier() : super(const DealsState.initial());
final ApiService _apiService = ApiService();
static const int _pageSize = 20;
/// Fetch deals from API
Future<void> fetchDeals({
String? search,
String? stage,
bool refresh = false,
}) async {
if (state.isLoading) return;
if (refresh) {
state = state.copyWith(
currentOffset: 0,
hasMore: true,
clearError: true,
);
}
debugPrint('DealsNotifier: Fetching deals (offset: ${state.currentOffset})...');
state = state.copyWith(isLoading: true, clearError: true);
try {
// Build query parameters
final queryParams = <String, String>{
'limit': _pageSize.toString(),
'offset': state.currentOffset.toString(),
};
if (search != null && search.isNotEmpty) {
queryParams['name'] = search;
}
if (stage != null && stage.isNotEmpty) {
queryParams['stage'] = stage;
}
final url = Uri.parse(ApiConfig.opportunities).replace(queryParameters: queryParams).toString();
final response = await _apiService.get(url);
if (response.success && response.data != null) {
final data = response.data!;
debugPrint('DealsNotifier: API response keys: ${data.keys.toList()}');
debugPrint('DealsNotifier: Full response data: $data');
// Parse deals - handle different response formats
List<dynamic> dealsList = [];
int dealsCount = 0;
if (data['opportunities'] != null) {
dealsList = data['opportunities'] as List<dynamic>? ?? [];
dealsCount = data['opportunities_count'] as int? ?? dealsList.length;
debugPrint('DealsNotifier: Found opportunities key with ${dealsList.length} items');
} else if (data['results'] != null) {
// Handle paginated response format
dealsList = data['results'] as List<dynamic>? ?? [];
dealsCount = data['count'] as int? ?? dealsList.length;
debugPrint('DealsNotifier: Found results key with ${dealsList.length} items');
} else {
debugPrint('DealsNotifier: No opportunities or results key found!');
// Try to find any list in the response
for (final key in data.keys) {
if (data[key] is List) {
debugPrint('DealsNotifier: Found list at key "$key" with ${(data[key] as List).length} items');
}
}
}
debugPrint('DealsNotifier: Found ${dealsList.length} deals in response');
final newDeals = <Deal>[];
for (int i = 0; i < dealsList.length; i++) {
final item = dealsList[i];
try {
if (item is Map<String, dynamic>) {
debugPrint('DealsNotifier: Parsing deal $i: name=${item['name']}, stage=${item['stage']}');
final deal = Deal.fromJson(item);
debugPrint('DealsNotifier: Successfully parsed deal: ${deal.title} (stage: ${deal.stage})');
newDeals.add(deal);
} else {
debugPrint('DealsNotifier: Skipping non-map item at index $i: ${item.runtimeType}');
}
} catch (e, stack) {
debugPrint('DealsNotifier: Error parsing deal at index $i: $e');
debugPrint('DealsNotifier: Stack trace: $stack');
debugPrint('DealsNotifier: Deal data: $item');
}
}
// Update state
final updatedDeals = refresh ? newDeals : [...state.deals, ...newDeals];
state = state.copyWith(
deals: updatedDeals,
isLoading: false,
totalCount: dealsCount,
hasMore: newDeals.length >= _pageSize,
currentOffset: state.currentOffset + newDeals.length,
);
debugPrint('DealsNotifier: Loaded ${newDeals.length} deals (total: ${updatedDeals.length})');
} else {
state = state.copyWith(
isLoading: false,
error: response.message ?? 'Failed to load deals',
);
debugPrint('DealsNotifier: API error - ${response.message}');
}
} catch (e) {
debugPrint('DealsNotifier: Exception - $e');
state = state.copyWith(
isLoading: false,
error: 'Failed to load deals: ${e.toString()}',
);
}
}
/// Refresh deals (reset and fetch first page)
Future<void> refresh() async {
state = const DealsState.initial();
await fetchDeals(refresh: true);
}
/// Load more deals
Future<void> loadMore() async {
if (!state.hasMore || state.isLoading) return;
await fetchDeals();
}
/// Clear deals data
void clear() {
state = const DealsState.initial();
}
}
/// Deals provider
final dealsProvider = StateNotifierProvider<DealsNotifier, DealsState>((ref) {
return DealsNotifier();
});
/// Convenience providers
final dealsListProvider = Provider<List<Deal>>((ref) {
return ref.watch(dealsProvider).deals;
});
final dealsLoadingProvider = Provider<bool>((ref) {
return ref.watch(dealsProvider).isLoading;
});
final dealsErrorProvider = Provider<String?>((ref) {
return ref.watch(dealsProvider).error;
});
/// Grouped deals by stage providers
final dealsByStageProvider = Provider<Map<DealStage, List<Deal>>>((ref) {
final deals = ref.watch(dealsListProvider);
final Map<DealStage, List<Deal>> grouped = {};
for (final stage in DealStage.values) {
grouped[stage] = deals.where((deal) => deal.stage == stage).toList();
}
return grouped;
});
/// Pipeline value (active deals only)
final pipelineValueProvider = Provider<double>((ref) {
final deals = ref.watch(dealsListProvider);
return deals
.where((d) => !d.stage.isClosed)
.fold<double>(0, (sum, deal) => sum + deal.value);
});
/// Active deals count
final activeDealsCountProvider = Provider<int>((ref) {
final deals = ref.watch(dealsListProvider);
return deals.where((d) => !d.stage.isClosed).length;
});

View file

@ -1,9 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:lucide_icons/lucide_icons.dart';
import '../../core/theme/theme.dart';
import '../../data/models/models.dart';
import '../../data/mock/mock_data.dart';
import '../../providers/deals_provider.dart';
import '../../widgets/cards/deal_card.dart';
import '../../widgets/misc/kanban_column.dart';
import '../../widgets/common/common.dart';
@ -12,14 +13,14 @@ enum ViewMode { kanban, list }
/// Deals List Screen
/// Pipeline view with Kanban board or list layout
class DealsListScreen extends StatefulWidget {
class DealsListScreen extends ConsumerStatefulWidget {
const DealsListScreen({super.key});
@override
State<DealsListScreen> createState() => _DealsListScreenState();
ConsumerState<DealsListScreen> createState() => _DealsListScreenState();
}
class _DealsListScreenState extends State<DealsListScreen> {
class _DealsListScreenState extends ConsumerState<DealsListScreen> {
final TextEditingController _searchController = TextEditingController();
final ScrollController _kanbanScrollController = ScrollController();
@ -36,6 +37,15 @@ class _DealsListScreenState extends State<DealsListScreen> {
DealStage.closedWon,
];
@override
void initState() {
super.initState();
// Fetch deals on screen load
WidgetsBinding.instance.addPostFrameCallback((_) {
ref.read(dealsProvider.notifier).fetchDeals(refresh: true);
});
}
@override
void dispose() {
_searchController.dispose();
@ -44,7 +54,8 @@ class _DealsListScreenState extends State<DealsListScreen> {
}
List<Deal> get _filteredDeals {
var result = List<Deal>.from(MockData.deals);
final deals = ref.watch(dealsListProvider);
var result = List<Deal>.from(deals);
if (_searchQuery.isNotEmpty) {
final query = _searchQuery.toLowerCase();
@ -214,15 +225,8 @@ class _DealsListScreenState extends State<DealsListScreen> {
}
Widget _buildPipelineSummary() {
final totalValue = _filteredDeals
.where((d) =>
d.stage != DealStage.closedLost && d.stage != DealStage.closedWon)
.fold<double>(0, (sum, deal) => sum + deal.value);
final activeDeals = _filteredDeals
.where((d) =>
d.stage != DealStage.closedLost && d.stage != DealStage.closedWon)
.length;
final totalValue = ref.watch(pipelineValueProvider);
final activeDeals = ref.watch(activeDealsCountProvider);
return Container(
color: AppColors.surface,
@ -246,35 +250,96 @@ class _DealsListScreenState extends State<DealsListScreen> {
}
Widget _buildKanbanView() {
final isLoading = ref.watch(dealsLoadingProvider);
final error = ref.watch(dealsErrorProvider);
final screenWidth = MediaQuery.of(context).size.width;
final columnWidth = screenWidth * 0.85;
// Show loading indicator on first load
if (isLoading && _filteredDeals.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
// Show error if any
if (error != null && _filteredDeals.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(LucideIcons.alertCircle, size: 48, color: AppColors.danger500),
const SizedBox(height: 16),
Text(error, style: AppTypography.body.copyWith(color: AppColors.textSecondary)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => ref.read(dealsProvider.notifier).refresh(),
child: const Text('Retry'),
),
],
),
);
}
// RefreshIndicator needs vertical scroll, so wrap in CustomScrollView
return RefreshIndicator(
onRefresh: () async {
await Future.delayed(const Duration(seconds: 1));
await ref.read(dealsProvider.notifier).refresh();
},
child: SingleChildScrollView(
controller: _kanbanScrollController,
scrollDirection: Axis.horizontal,
physics: const PageScrollPhysics(),
padding: const EdgeInsets.fromLTRB(10, 12, 10, 100),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: _kanbanStages.map((stage) {
return KanbanColumn(
stage: stage,
deals: _dealsByStage[stage] ?? [],
width: columnWidth,
onDealTap: (deal) => context.push('/deals/${deal.id}'),
onDealMoved: _handleDealMoved,
);
}).toList(),
),
child: CustomScrollView(
physics: const AlwaysScrollableScrollPhysics(),
slivers: [
SliverFillRemaining(
child: SingleChildScrollView(
controller: _kanbanScrollController,
scrollDirection: Axis.horizontal,
physics: const PageScrollPhysics(),
padding: const EdgeInsets.fromLTRB(10, 12, 10, 100),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: _kanbanStages.map((stage) {
return KanbanColumn(
stage: stage,
deals: _dealsByStage[stage] ?? [],
width: columnWidth,
onDealTap: (deal) => context.push('/deals/${deal.id}'),
onDealMoved: _handleDealMoved,
);
}).toList(),
),
),
),
],
),
);
}
Widget _buildListView() {
final isLoading = ref.watch(dealsLoadingProvider);
final error = ref.watch(dealsErrorProvider);
// Show loading indicator on first load
if (isLoading && _filteredDeals.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
// Show error if any
if (error != null && _filteredDeals.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(LucideIcons.alertCircle, size: 48, color: AppColors.danger500),
const SizedBox(height: 16),
Text(error, style: AppTypography.body.copyWith(color: AppColors.textSecondary)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => ref.read(dealsProvider.notifier).refresh(),
child: const Text('Retry'),
),
],
),
);
}
if (_filteredDeals.isEmpty) {
return EmptyState(
icon: LucideIcons.briefcase,
@ -294,7 +359,7 @@ class _DealsListScreenState extends State<DealsListScreen> {
return RefreshIndicator(
onRefresh: () async {
await Future.delayed(const Duration(seconds: 1));
await ref.read(dealsProvider.notifier).refresh();
},
child: ListView.builder(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 100),