From 7b8225a293ab05d1bb6e7dbd613fca5af3e4dd0e Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Dec 2025 19:30:33 +0530 Subject: [PATCH] m9 --- mobile/lib/config/api_config.dart | 2 +- mobile/lib/data/models/deal.dart | 125 +++++++++- mobile/lib/providers/deals_provider.dart | 234 ++++++++++++++++++ .../lib/screens/deals/deals_list_screen.dart | 131 +++++++--- 4 files changed, 456 insertions(+), 36 deletions(-) create mode 100644 mobile/lib/providers/deals_provider.dart diff --git a/mobile/lib/config/api_config.dart b/mobile/lib/config/api_config.dart index fee9c1e4..50f47a3d 100644 --- a/mobile/lib/config/api_config.dart +++ b/mobile/lib/config/api_config.dart @@ -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/'; diff --git a/mobile/lib/data/models/deal.dart b/mobile/lib/data/models/deal.dart index d6d490f4..a46df481 100644 --- a/mobile/lib/data/models/deal.dart +++ b/mobile/lib/data/models/deal.dart @@ -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 json) { + // Parse tags + List parsedTags = []; + if (json['tags'] != null) { + final tagsList = json['tags'] as List? ?? []; + parsedTags = tagsList.map((t) { + if (t is Map) { + 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? ?? []; + if (assignedList.isNotEmpty) { + final first = assignedList.first; + if (first is Map) { + 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) { + companyName = json['account']['name'] as String? ?? 'No Account'; + } + + // Parse products/line_items + List products = []; + if (json['line_items'] != null) { + final lineItems = json['line_items'] as List? ?? []; + products = lineItems.map((item) { + if (item is Map) { + // 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); diff --git a/mobile/lib/providers/deals_provider.dart b/mobile/lib/providers/deals_provider.dart new file mode 100644 index 00000000..732ed0a1 --- /dev/null +++ b/mobile/lib/providers/deals_provider.dart @@ -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 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? 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 { + DealsNotifier() : super(const DealsState.initial()); + + final ApiService _apiService = ApiService(); + static const int _pageSize = 20; + + /// Fetch deals from API + Future 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 = { + '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 dealsList = []; + int dealsCount = 0; + + if (data['opportunities'] != null) { + dealsList = data['opportunities'] as List? ?? []; + 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? ?? []; + 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 = []; + for (int i = 0; i < dealsList.length; i++) { + final item = dealsList[i]; + try { + if (item is Map) { + 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 refresh() async { + state = const DealsState.initial(); + await fetchDeals(refresh: true); + } + + /// Load more deals + Future loadMore() async { + if (!state.hasMore || state.isLoading) return; + await fetchDeals(); + } + + /// Clear deals data + void clear() { + state = const DealsState.initial(); + } +} + +/// Deals provider +final dealsProvider = StateNotifierProvider((ref) { + return DealsNotifier(); +}); + +/// Convenience providers +final dealsListProvider = Provider>((ref) { + return ref.watch(dealsProvider).deals; +}); + +final dealsLoadingProvider = Provider((ref) { + return ref.watch(dealsProvider).isLoading; +}); + +final dealsErrorProvider = Provider((ref) { + return ref.watch(dealsProvider).error; +}); + +/// Grouped deals by stage providers +final dealsByStageProvider = Provider>>((ref) { + final deals = ref.watch(dealsListProvider); + final Map> 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((ref) { + final deals = ref.watch(dealsListProvider); + return deals + .where((d) => !d.stage.isClosed) + .fold(0, (sum, deal) => sum + deal.value); +}); + +/// Active deals count +final activeDealsCountProvider = Provider((ref) { + final deals = ref.watch(dealsListProvider); + return deals.where((d) => !d.stage.isClosed).length; +}); diff --git a/mobile/lib/screens/deals/deals_list_screen.dart b/mobile/lib/screens/deals/deals_list_screen.dart index f44a4983..8cfdeffb 100644 --- a/mobile/lib/screens/deals/deals_list_screen.dart +++ b/mobile/lib/screens/deals/deals_list_screen.dart @@ -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 createState() => _DealsListScreenState(); + ConsumerState createState() => _DealsListScreenState(); } -class _DealsListScreenState extends State { +class _DealsListScreenState extends ConsumerState { final TextEditingController _searchController = TextEditingController(); final ScrollController _kanbanScrollController = ScrollController(); @@ -36,6 +37,15 @@ class _DealsListScreenState extends State { 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 { } List get _filteredDeals { - var result = List.from(MockData.deals); + final deals = ref.watch(dealsListProvider); + var result = List.from(deals); if (_searchQuery.isNotEmpty) { final query = _searchQuery.toLowerCase(); @@ -214,15 +225,8 @@ class _DealsListScreenState extends State { } Widget _buildPipelineSummary() { - final totalValue = _filteredDeals - .where((d) => - d.stage != DealStage.closedLost && d.stage != DealStage.closedWon) - .fold(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 { } 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 { 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),