File size: 31,486 Bytes
314f3d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
import pandas as pd
import numpy as np
import os
import re
from datetime import datetime
import logging

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class DataProcessor:
    def __init__(self, db_manager):
        self.db = db_manager
        self.product_mapping = self._create_product_mapping()
    
    def _create_product_mapping(self):
        """Create product mapping from database"""
        try:
            products_df = self.db.get_dataframe('products')
            return {row['product_name'].upper(): row['product_id'] for _, row in products_df.iterrows()}
        except Exception as e:
            logger.error(f"Error creating product mapping: {e}")
            return {}
    
    def process_excel_file(self, file_path):
        """Enhanced file processing with all data types"""
        try:
            file_name = os.path.basename(file_path)
            print(f"πŸš€ Processing file: {file_name}")
            
            excel_file = pd.ExcelFile(file_path)
            processed_sheets = 0
            
            for sheet_name in excel_file.sheet_names:
                df = pd.read_excel(file_path, sheet_name=sheet_name)
                df_clean = self._clean_dataframe(df)
                
                print(f"\nπŸ“Š Sheet: {sheet_name}")
                print(f"   Columns: {df_clean.columns.tolist()}")
                
                # Check all types with priority
                is_payment = self._is_payment_sheet(df_clean)
                is_sales = self._is_sales_sheet(df_clean)
                is_customer = self._is_customer_sheet(df_clean)
                is_distributor = self._is_distributor_sheet(df_clean)
                
                print(f"   Detection - Payment: {is_payment}, Sales: {is_sales}, Customer: {is_customer}, Distributor: {is_distributor}")
                
                processed = False
                if is_payment:
                    processed = self.process_payment_sheet(df_clean, file_name, sheet_name)
                elif is_sales:
                    processed = self.process_sales_sheet(df_clean, file_name, sheet_name)
                elif is_distributor:
                    processed = self.process_distributor_sheet(df_clean, file_name, sheet_name)
                elif is_customer:
                    processed = self.process_customer_sheet(df_clean, file_name, sheet_name)
                
                if processed:
                    processed_sheets += 1
                    print(f"   βœ… Successfully processed as detected type")
                else:
                    print(f"   ❌ Failed to process")
            
            print(f"\nπŸŽ‰ File processing complete: {processed_sheets}/{len(excel_file.sheet_names)} sheets processed")
            return processed_sheets > 0
            
        except Exception as e:
            print(f"πŸ’₯ Error processing file {file_path}: {e}")
            return False
    
    def _clean_dataframe(self, df):
        """Clean and prepare dataframe for processing"""
        # Remove completely empty rows and columns
        df = df.dropna(how='all').dropna(axis=1, how='all')
        
        # Reset index
        df = df.reset_index(drop=True)
        
        # Convert column names to string and clean them
        df.columns = [str(col).strip().upper() for col in df.columns]
        
        return df
    
    def _is_sales_sheet(self, df):
        """Check if sheet contains sales data"""
        required_columns = ['INVOICE', 'CUSTOMER', 'PRODUCT', 'QUANTITY', 'AMOUNT']
        existing_columns = [col for col in df.columns if any(req in col for req in required_columns)]
        return len(existing_columns) >= 3
    
    def _is_customer_sheet(self, df):
        """Check if sheet contains customer data"""
        required_columns = ['CUSTOMER', 'NAME', 'MOBILE', 'VILLAGE']
        existing_columns = [col for col in df.columns if any(req in col for req in required_columns)]
        return len(existing_columns) >= 2
    
    def _is_distributor_sheet(self, df):
        """Check if sheet contains distributor data"""
        required_columns = ['DISTRIBUTOR', 'MANTRI', 'SABHASAD']
        existing_columns = [col for col in df.columns if any(req in col for req in required_columns)]
        return len(existing_columns) >= 2
    
    def process_sales_sheet(self, df, file_name, sheet_name):
        """Process sales data from sheet"""
        try:
            processed_rows = 0
            
            for index, row in df.iterrows():
                try:
                    # Skip header rows and empty rows
                    if self._is_header_row(row) or pd.isna(row.iloc[0]):
                        continue
                    
                    # Extract sales data (adjust column indices based on your Excel structure)
                    invoice_no = str(row.iloc[0]) if len(row) > 0 else f"INV_{datetime.now().strftime('%Y%m%d%H%M%S')}_{index}"
                    customer_name = str(row.iloc[1]) if len(row) > 1 else "Unknown Customer"
                    product_name = str(row.iloc[2]) if len(row) > 2 else "Unknown Product"
                    quantity = self._safe_float(row.iloc[3]) if len(row) > 3 else 0
                    amount = self._safe_float(row.iloc[4]) if len(row) > 4 else 0
                    
                    # Get or create customer
                    customer_id = self._get_or_create_customer(customer_name, "", "", "", "")
                    
                    # Get product ID
                    product_id = self._get_product_id(product_name)
                    
                    if customer_id and product_id and quantity > 0:
                        # Create sale
                        sale_date = datetime.now().date()
                        sale_items = [{
                            'product_id': product_id,
                            'quantity': quantity,
                            'rate': amount / quantity if quantity > 0 else 0
                        }]
                        
                        self.db.add_sale(invoice_no, customer_id, sale_date, sale_items)
                        processed_rows += 1
                        
                except Exception as e:
                    logger.warning(f"Error processing row {index} in sales sheet: {e}")
                    continue
            
            logger.info(f"Processed {processed_rows} sales from {sheet_name}")
            return processed_rows > 0
            
        except Exception as e:
            logger.error(f"Error processing sales sheet: {e}")
            return False
    
    def process_customer_sheet(self, df, file_name, sheet_name):
        """Process customer data from sheet with duplicate handling"""
        try:
            processed_rows = 0
            duplicate_rows = 0
            error_rows = 0
            
            print(f"πŸ”„ Processing customer sheet: {sheet_name} with {len(df)} rows")
            
            for index, row in df.iterrows():
                try:
                    # Skip header rows and empty rows
                    if self._is_header_row(row) or pd.isna(row.iloc[0]):
                        continue
                    
                    # Extract customer data
                    customer_code = str(row.iloc[0]) if len(row) > 0 and pd.notna(row.iloc[0]) else None
                    name = str(row.iloc[1]) if len(row) > 1 and pd.notna(row.iloc[1]) else "Unknown"
                    mobile = str(row.iloc[2]) if len(row) > 2 and pd.notna(row.iloc[2]) else ""
                    
                    # Extract location - adjust indices based on your Excel structure
                    village = str(row.iloc[3]) if len(row) > 3 and pd.notna(row.iloc[3]) else ""
                    taluka = str(row.iloc[4]) if len(row) > 4 and pd.notna(row.iloc[4]) else ""
                    district = str(row.iloc[5]) if len(row) > 5 and pd.notna(row.iloc[5]) else ""
                    
                    # If village is combined with name, split them
                    if not village and "(" in name:
                        name_parts = name.split("(")
                        if len(name_parts) > 1:
                            name = name_parts[0].strip()
                            village = name_parts[1].replace(")", "").strip()
                    
                    # Skip if no name
                    if not name or name == "Unknown":
                        continue
                    
                    # Add customer to database (method now handles duplicates)
                    customer_id = self.db.add_customer(name, mobile, village, taluka, district, customer_code)
                    
                    if customer_id and customer_id != -1:
                        processed_rows += 1
                        if processed_rows % 50 == 0:  # Progress update
                            print(f"πŸ“Š Processed {processed_rows} customers...")
                    else:
                        duplicate_rows += 1
                        
                except Exception as e:
                    error_rows += 1
                    if error_rows <= 5:  # Only log first few errors
                        print(f"❌ Error in row {index}: {e}")
                    continue
            
            print(f"πŸŽ‰ Customer processing complete: {processed_rows} added, {duplicate_rows} duplicates, {error_rows} errors")
            return processed_rows > 0
            
        except Exception as e:
            print(f"πŸ’₯ Error processing customer sheet: {e}")
            return False
    
    def process_distributor_sheet(self, df, file_name, sheet_name):
        """Process distributor data from sheet"""
        try:
            processed_rows = 0
            
            # Clean the dataframe - convert column names to consistent format
            df.columns = [str(col).strip().upper() for col in df.columns]
            print(f"DEBUG: Processing distributor sheet with columns: {df.columns.tolist()}")
            
            for index, row in df.iterrows():
                try:
                    # Skip header rows and empty rows
                    if self._is_header_row(row) or pd.isna(row.iloc[0]):
                        print(f"DEBUG: Skipping row {index} - header or empty")
                        continue
                    
                    print(f"DEBUG: Processing row {index}")
                    
                    # Extract distributor data based on YOUR ACTUAL COLUMNS
                    # Map your Excel columns to database fields
                    name = self._extract_distributor_name(row)  # We'll use Village + Taluka as name
                    village = self._safe_get(row, 'Village', 1)
                    taluka = self._safe_get(row, 'Taluka', 2) 
                    district = self._safe_get(row, 'District', 3)
                    mantri_name = self._safe_get(row, 'Mantri_Name', 4)
                    mantri_mobile = self._safe_get(row, 'Mantri_Mobile', 5)
                    sabhasad_count = self._safe_get_int(row, 'Sabhasad', 6)
                    contact_in_group = self._safe_get_int(row, 'Contact_In_Group', 7)
                    
                    print(f"DEBUG: Extracted - Village: {village}, Taluka: {taluka}, Mantri: {mantri_name}")
                    
                    # Validate we have essential data
                    if not village or not taluka:
                        print(f"DEBUG: Skipping - missing village or taluka")
                        continue
                    
                    # Create distributor name from village + taluka
                    if not name:
                        name = f"{village} - {taluka}"
                    
                    # Add distributor to database with ALL fields
                    self.db.execute_query('''
                    INSERT OR REPLACE INTO distributors 
                    (name, village, taluka, district, mantri_name, mantri_mobile, sabhasad_count, contact_in_group)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ''', (name, village, taluka, district, mantri_name, mantri_mobile, sabhasad_count, contact_in_group))
                    
                    processed_rows += 1
                    print(f"DEBUG: Successfully added distributor: {name}")
                    
                except Exception as e:
                    logger.warning(f"Error processing row {index} in distributor sheet: {e}")
                    continue
            
            logger.info(f"Processed {processed_rows} distributors from {sheet_name}")
            return processed_rows > 0
            
        except Exception as e:
            logger.error(f"Error processing distributor sheet: {e}")
            return False

    def _extract_distributor_name(self, row):
        """Extract distributor name from village and taluka"""
        village = self._safe_get(row, 'Village', 1)
        taluka = self._safe_get(row, 'Taluka', 2)
        
        if village and taluka:
            return f"{village} - {taluka}"
        elif village:
            return village
        elif taluka:
            return taluka
        else:
            return "Unknown Distributor"

    def _safe_get(self, row, column_name, default_index):
        """Safely get value from row by column name or index"""
        try:
            # Try by column name first
            if column_name in row.index:
                value = row[column_name]
                if pd.isna(value):
                    return ""
                return str(value).strip()
            
            # Fallback to index
            if len(row) > default_index:
                value = row.iloc[default_index]
                if pd.isna(value):
                    return ""
                return str(value).strip()
            
            return ""
        except Exception:
            return ""

    def _safe_get_int(self, row, column_name, default_index):
        """Safely get integer value from row"""
        try:
            str_value = self._safe_get(row, column_name, default_index)
            if str_value and str_value.strip():
                return int(float(str_value))  # Handle both int and float strings
            return 0
        except (ValueError, TypeError):
            return 0
    
    def _is_header_row(self, row):
        """Check if row is a header row - updated for your data"""
        if len(row) == 0:
            return True
            
        first_value = str(row.iloc[0]) if pd.notna(row.iloc[0]) else ""
        first_value_upper = first_value.upper()
        
        # Header indicators for YOUR data
        header_indicators = [
            'DATE', 'VILLAGE', 'TALUKA', 'DISTRICT', 'MANTRI', 
            'SABHASAD', 'CONTACT', 'TOTAL', 'SR', 'NO', 'NAME'
        ]
        
        # If first value contains any header indicator, it's likely a header
        return any(indicator in first_value_upper for indicator in header_indicators)
        
    def _safe_float(self, value):
        """Safely convert value to float"""
        try:
            if pd.isna(value):
                return 0.0
            return float(value)
        except (ValueError, TypeError):
            return 0.0
    
    def _get_or_create_customer(self, name, mobile, village, taluka, district):
        """Get existing customer or create new one"""
        try:
            # Check if customer exists
            result = self.db.execute_query(
                'SELECT customer_id FROM customers WHERE name = ? AND mobile = ?', 
                (name, mobile)
            )
            
            if result:
                return result[0][0]
            else:
                # Create new customer
                customer_code = f"CUST_{datetime.now().strftime('%Y%m%d%H%M%S')}"
                self.db.add_customer(name, mobile, village, taluka, district, customer_code)
                
                # Get the new customer ID
                result = self.db.execute_query(
                    'SELECT customer_id FROM customers WHERE customer_code = ?', 
                    (customer_code,)
                )
                return result[0][0] if result else None
                
        except Exception as e:
            logger.error(f"Error getting/creating customer: {e}")
            return None
    
    def _get_product_id(self, product_name):
        """Get product ID from product name"""
        clean_name = product_name.upper().strip()
        return self.product_mapping.get(clean_name, None)
    
    def _extract_location_from_name(self, name):
        """Extract village and taluka from customer name"""
        name_upper = name.upper()
        
        locations = {
            'AMIYAD': ('Amiyad', ''),
            'AMVAD': ('Amvad', ''),
            'ANKALAV': ('', 'Ankalav'),
            'PETLAD': ('', 'Petlad'),
            'BORSAD': ('', 'Borsad'),
            'VADODARA': ('', 'Vadodara'),
            'ANAND': ('', 'Anand'),
            'NADIAD': ('', 'Nadiad')
        }
        
        village, taluka = "", ""
        for location, (v, t) in locations.items():
            if location in name_upper:
                if v: 
                    village = v
                if t: 
                    taluka = t
                break
        
        return village, taluka
    


    # Add to DataProcessor class in data_processor.py

    def _is_sales_sheet(self, df):
        """Enhanced sales sheet detection with better logging"""
        columns_lower = [str(col).lower() for col in df.columns]
        
        print(f"\nπŸ” ENHANCED SALES DETECTION:")
        print(f"   All columns: {columns_lower}")
        
        sales_indicators = [
            'invoice', 'sale', 'amount', 'product', 'quantity', 'rate', 
            'total', 'price', 'bill', 'payment', 'item', 'qty'
        ]
        
        found_indicators = []
        for indicator in sales_indicators:
            matching_cols = [col for col in columns_lower if indicator in col]
            if matching_cols:
                found_indicators.append((indicator, matching_cols))
        
        print(f"   Found sales indicators: {found_indicators}")
        
        score = len(found_indicators)
        print(f"   Sales detection score: {score}")
        
        return score >= 2

    def process_sales_sheet(self, df, file_name, sheet_name):
        """Enhanced sales data processing with better logging"""
        try:
            processed_rows = 0
            print(f"πŸ”„ Processing sales sheet: {sheet_name} with {len(df)} rows")
            
            for index, row in df.iterrows():
                try:
                    # Skip header rows and empty rows
                    if self._is_header_row(row) or pd.isna(row.iloc[0]):
                        continue
                    
                    print(f"πŸ”§ Processing row {index}")
                    
                    # Extract sales data with flexible column mapping
                    invoice_no = self._extract_sales_value(row, 'invoice', 0, f"INV_{datetime.now().strftime('%Y%m%d%H%M%S')}_{index}")
                    customer_name = self._extract_sales_value(row, 'customer', 1, "Unknown Customer")
                    product_name = self._extract_sales_value(row, 'product', 2, "Unknown Product")
                    quantity = self._safe_float(self._extract_sales_value(row, 'quantity', 3, 0))
                    amount = self._safe_float(self._extract_sales_value(row, 'amount', 4, 0))
                    
                    print(f"   Extracted - Invoice: '{invoice_no}', Customer: '{customer_name}', Product: '{product_name}', Qty: {quantity}, Amount: {amount}")
                    
                    # Validate essential data
                    if not customer_name or customer_name == "Unknown Customer":
                        print(f"   ⚠️ Skipping - invalid customer name")
                        continue
                    
                    if quantity <= 0:
                        print(f"   ⚠️ Skipping - invalid quantity: {quantity}")
                        continue
                    
                    if amount <= 0:
                        print(f"   ⚠️ Skipping - invalid amount: {amount}")
                        continue
                    
                    # Get or create customer
                    customer_id = self._get_or_create_customer(customer_name, "", "", "", "")
                    if not customer_id:
                        print(f"   ⚠️ Skipping - could not get/create customer")
                        continue
                    
                    # Get product ID
                    product_id = self._get_product_id(product_name)
                    if not product_id:
                        print(f"   ⚠️ Skipping - product not found: '{product_name}'")
                        print(f"   Available products: {list(self.product_mapping.keys())}")
                        continue
                    
                    # Calculate rate
                    rate = amount / quantity if quantity > 0 else 0
                    
                    # Create sale items
                    sale_date = datetime.now().date()
                    sale_items = [{
                        'product_id': product_id,
                        'quantity': quantity,
                        'rate': rate
                    }]
                    
                    # Generate proper invoice number
                    if not invoice_no or invoice_no.startswith('INV_'):
                        invoice_no = self.db.generate_invoice_number()
                    
                    print(f"   Creating sale - Customer ID: {customer_id}, Product ID: {product_id}")
                    
                    # Add sale to database
                    sale_id = self.db.add_sale(invoice_no, customer_id, sale_date, sale_items)
                    
                    if sale_id and sale_id > 0:
                        processed_rows += 1
                        print(f"   βœ… Successfully created sale ID: {sale_id}")
                    else:
                        print(f"   ❌ Failed to create sale")
                        
                except Exception as e:
                    print(f"   ❌ Error in row {index}: {e}")
                    import traceback
                    traceback.print_exc()
                    continue
            
            print(f"πŸŽ‰ Processed {processed_rows} sales from {sheet_name}")
            return processed_rows > 0
            
        except Exception as e:
            print(f"πŸ’₯ Error processing sales sheet: {e}")
            import traceback
            traceback.print_exc()
            return False
    def _extract_sales_value(self, row, field_name, default_index, default_value):
        """Extract sales values with flexible column matching"""
        # Try to find column by name
        for col_name in row.index:
            if field_name in str(col_name).lower():
                value = row[col_name]
                if pd.notna(value):
                    return str(value).strip()
        
        # Fallback to index
        if len(row) > default_index:
            value = row.iloc[default_index]
            if pd.notna(value):
                return str(value).strip()
        
        return default_value

    # Add to DataProcessor class

    def _is_payment_sheet(self, df):
        """Detect payment sheets"""
        columns_lower = [str(col).lower() for col in df.columns]
        
        payment_indicators = [
            'payment', 'paid', 'amount', 'invoice', 'date', 'method',
            'cash', 'gpay', 'cheque', 'bank', 'rrn', 'reference'
        ]
        
        score = sum(1 for indicator in payment_indicators 
                    if any(indicator in col for col in columns_lower))
        
        print(f"πŸ” Payment detection - Score: {score}, Columns: {columns_lower}")
        return score >= 2

    def process_payment_sheet(self, df, file_name, sheet_name):
        """Process payment data from sheet"""
        try:
            processed_rows = 0
            print(f"πŸ”„ Processing payment sheet: {sheet_name}")
            
            for index, row in df.iterrows():
                try:
                    if self._is_header_row(row) or pd.isna(row.iloc[0]):
                        continue
                    
                    # Extract payment data
                    invoice_no = self._extract_sales_value(row, 'invoice', 0, "")
                    amount = self._safe_float(self._extract_sales_value(row, 'amount', 1, 0))
                    payment_date = self._extract_sales_value(row, 'date', 2, datetime.now().date())
                    payment_method = self._extract_sales_value(row, 'method', 3, "Cash")
                    
                    if invoice_no and amount > 0:
                        # Find sale by invoice number
                        sale_result = self.db.execute_query(
                            'SELECT sale_id FROM sales WHERE invoice_no = ?',
                            (invoice_no,),
                            log_action=False
                        )
                        
                        if sale_result:
                            sale_id = sale_result[0][0]
                            
                            # Add payment
                            self.db.execute_query('''
                            INSERT INTO payments (sale_id, payment_date, payment_method, amount)
                            VALUES (?, ?, ?, ?)
                            ''', (sale_id, payment_date, payment_method, amount))
                            
                            processed_rows += 1
                            print(f"βœ… Processed payment for invoice {invoice_no}")
                    
                except Exception as e:
                    print(f"❌ Error processing payment row {index}: {e}")
                    continue
            
            print(f"πŸŽ‰ Processed {processed_rows} payments from {sheet_name}")
            return processed_rows > 0
            
        except Exception as e:
            print(f"πŸ’₯ Error processing payment sheet: {e}")
            return False


    def _is_customer_sheet(self, df):
        """Check if sheet contains customer data - IMPROVED"""
        columns_lower = [str(col).lower() for col in df.columns]
        
        customer_indicators = [
            'customer', 'name', 'mobile', 'phone', 'village', 'taluka', 
            'district', 'code', 'contact'
        ]
        
        score = sum(1 for indicator in customer_indicators 
                if any(indicator in col for col in columns_lower))
        
        print(f"πŸ” Customer sheet detection - Score: {score}, Columns: {columns_lower}")
        return score >= 2

    def _is_distributor_sheet(self, df):
        """Enhanced distributor sheet detection with better logging"""
        columns_lower = [str(col).lower() for col in df.columns]
        
        print(f"\nπŸ” ENHANCED DISTRIBUTOR DETECTION:")
        print(f"   All columns: {columns_lower}")
        
        distributor_indicators = [
            'distributor', 'mantri', 'sabhasad', 'contact_in_group',
            'village', 'taluka', 'district', 'leader', 'team', 'sabh'
        ]
        
        found_indicators = []
        for indicator in distributor_indicators:
            matching_cols = [col for col in columns_lower if indicator in col]
            if matching_cols:
                found_indicators.append((indicator, matching_cols))
        
        print(f"   Found indicators: {found_indicators}")
        
        score = len(found_indicators)
        print(f"   Detection score: {score}")
        
        # More flexible detection - lower threshold
        return score >= 1  # Even if we find just one indicator, try processing

    def process_single_sheet(self, df, sheet_name, file_name):
        """Process a single sheet with detailed logging"""
        print(f"πŸ”„ Processing sheet: {sheet_name} from {file_name}")
        
        if self._is_sales_sheet(df):
            print("βœ… Detected as SALES sheet")
            return self.process_sales_sheet(df, file_name, sheet_name)
        elif self._is_customer_sheet(df):
            print("βœ… Detected as CUSTOMER sheet") 
            return self.process_customer_sheet(df, file_name, sheet_name)
        elif self._is_distributor_sheet(df):
            print("βœ… Detected as DISTRIBUTOR sheet")
            return self.process_distributor_sheet(df, file_name, sheet_name)
        else:
            print("❓ Unknown sheet type - trying customer processing as fallback")
            return self.process_customer_sheet(df, file_name, sheet_name)
        
    def process_excel_file(self, file_path):
        """Enhanced file processing with all data types"""
        try:
            file_name = os.path.basename(file_path)
            print(f"πŸš€ Processing file: {file_name}")
            
            excel_file = pd.ExcelFile(file_path)
            processed_sheets = 0
            
            for sheet_name in excel_file.sheet_names:
                df = pd.read_excel(file_path, sheet_name=sheet_name)
                df_clean = self._clean_dataframe(df)
                
                print(f"\nπŸ“Š Sheet: {sheet_name}")
                print(f"   Columns: {df_clean.columns.tolist()}")
                
                # Check all types with priority
                is_payment = self._is_payment_sheet(df_clean)
                is_sales = self._is_sales_sheet(df_clean)
                is_customer = self._is_customer_sheet(df_clean)
                is_distributor = self._is_distributor_sheet(df_clean)
                
                print(f"   Detection - Payment: {is_payment}, Sales: {is_sales}, Customer: {is_customer}, Distributor: {is_distributor}")
                
                processed = False
                if is_payment:
                    print("   πŸ’³ Processing as PAYMENT sheet")
                    processed = self.process_payment_sheet(df_clean, file_name, sheet_name)
                elif is_sales:
                    print("   πŸ’° Processing as SALES sheet")
                    processed = self.process_sales_sheet(df_clean, file_name, sheet_name)
                elif is_distributor:
                    print("   🀝 Processing as DISTRIBUTOR sheet")
                    processed = self.process_distributor_sheet(df_clean, file_name, sheet_name)
                elif is_customer:
                    print("   πŸ‘₯ Processing as CUSTOMER sheet")
                    processed = self.process_customer_sheet(df_clean, file_name, sheet_name)
                else:
                    print("   ❓ Unknown sheet type")
                
                if processed:
                    processed_sheets += 1
                    print(f"   βœ… Successfully processed")
                else:
                    print(f"   ❌ Failed to process")
            
            print(f"\nπŸŽ‰ File processing complete: {processed_sheets}/{len(excel_file.sheet_names)} sheets processed")
            return processed_sheets > 0
            
        except Exception as e:
            print(f"πŸ’₯ Error processing file {file_path}: {e}")
            return False