-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend_test.py
More file actions
6689 lines (5549 loc) · 306 KB
/
backend_test.py
File metadata and controls
6689 lines (5549 loc) · 306 KB
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Backend API Test Suite for Distribution Management System
Tests Invoice Management and Consumption Tracking APIs
"""
import requests
import json
import sys
from datetime import datetime
import uuid
# Configuration
BASE_URL = "https://warehouse-distro.preview.emergentagent.com/api"
# Test Users
TEST_USERS = {
"admin": {"username": "admin", "password": "admin123"},
"accounting": {"username": "muhasebe", "password": "muhasebe123"},
"plasiyer": {"username": "plasiyer1", "password": "plasiyer123"},
"customer": {"username": "musteri2", "password": "musteri223"}
}
class APITester:
def __init__(self):
self.tokens = {}
self.test_results = []
self.failed_tests = []
self.uploaded_invoice_id = None
def log_test(self, test_name, success, details=""):
"""Log test result"""
status = "✅ PASS" if success else "❌ FAIL"
print(f"{status}: {test_name}")
if details:
print(f" Details: {details}")
self.test_results.append({
"test": test_name,
"success": success,
"details": details
})
if not success:
self.failed_tests.append(test_name)
def login_user(self, user_type):
"""Login and get token for user type"""
try:
user_creds = TEST_USERS[user_type]
response = requests.post(
f"{BASE_URL}/auth/login",
json=user_creds,
timeout=30
)
if response.status_code == 200:
data = response.json()
token = data.get("access_token")
if token:
self.tokens[user_type] = token
self.log_test(f"Login {user_type}", True, f"Token obtained")
return True
else:
self.log_test(f"Login {user_type}", False, "No token in response")
return False
else:
self.log_test(f"Login {user_type}", False, f"Status: {response.status_code}, Response: {response.text}")
return False
except Exception as e:
self.log_test(f"Login {user_type}", False, f"Exception: {str(e)}")
return False
def get_headers(self, user_type):
"""Get authorization headers for user type"""
token = self.tokens.get(user_type)
if not token:
return None
return {"Authorization": f"Bearer {token}"}
def test_sales_agent_warehouse_order(self):
"""Test POST /api/salesagent/warehouse-order"""
headers = self.get_headers("plasiyer")
if not headers:
self.log_test("Sales Agent Warehouse Order", False, "No plasiyer token")
return
# First get products to create a valid order
try:
products_response = requests.get(f"{BASE_URL}/products", headers=headers, timeout=30)
if products_response.status_code != 200:
self.log_test("Sales Agent Warehouse Order", False, "Could not fetch products")
return
products = products_response.json()
if not products:
self.log_test("Sales Agent Warehouse Order", False, "No products available")
return
# Create order with first product
product = products[0]
order_data = {
"customer_id": "plasiyer-self", # Will be overridden by API
"channel_type": "logistics",
"products": [
{
"product_id": product["id"],
"product_name": product["name"],
"units": 24,
"cases": 2,
"unit_price": product.get("logistics_price", 10.0),
"total_price": 24 * product.get("logistics_price", 10.0)
}
],
"notes": "Test warehouse order from plasiyer"
}
response = requests.post(
f"{BASE_URL}/salesagent/warehouse-order",
json=order_data,
headers=headers,
timeout=30
)
if response.status_code == 200:
order = response.json()
if order.get("order_number", "").startswith("WHS-"):
self.log_test("Sales Agent Warehouse Order", True, f"Order created: {order.get('order_number')}")
else:
self.log_test("Sales Agent Warehouse Order", False, "Order number doesn't start with WHS-")
else:
self.log_test("Sales Agent Warehouse Order", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Sales Agent Warehouse Order", False, f"Exception: {str(e)}")
def test_sales_agent_my_customers(self):
"""Test GET /api/salesagent/my-customers"""
headers = self.get_headers("plasiyer")
if not headers:
self.log_test("Sales Agent My Customers", False, "No plasiyer token")
return
try:
response = requests.get(
f"{BASE_URL}/salesagent/my-customers",
headers=headers,
timeout=30
)
if response.status_code == 200:
customers = response.json()
if isinstance(customers, list):
self.log_test("Sales Agent My Customers", True, f"Found {len(customers)} customers")
# Check structure of first customer if exists
if customers:
customer = customers[0]
required_fields = ["route", "customer", "order_count"]
missing_fields = [field for field in required_fields if field not in customer]
if missing_fields:
self.log_test("Sales Agent My Customers Structure", False, f"Missing fields: {missing_fields}")
else:
self.log_test("Sales Agent My Customers Structure", True, "All required fields present")
else:
self.log_test("Sales Agent My Customers", False, "Response is not a list")
else:
self.log_test("Sales Agent My Customers", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Sales Agent My Customers", False, f"Exception: {str(e)}")
def test_sales_agent_my_routes(self):
"""Test GET /api/salesagent/my-routes"""
headers = self.get_headers("plasiyer")
if not headers:
self.log_test("Sales Agent My Routes", False, "No plasiyer token")
return
try:
response = requests.get(
f"{BASE_URL}/salesagent/my-routes",
headers=headers,
timeout=30
)
if response.status_code == 200:
routes = response.json()
if isinstance(routes, list):
self.log_test("Sales Agent My Routes", True, f"Found {len(routes)} routes")
# Check structure of first route if exists
if routes:
route = routes[0]
required_fields = ["id", "sales_agent_id", "customer_id", "delivery_day"]
missing_fields = [field for field in required_fields if field not in route]
if missing_fields:
self.log_test("Sales Agent My Routes Structure", False, f"Missing fields: {missing_fields}")
else:
self.log_test("Sales Agent My Routes Structure", True, "All required fields present")
else:
self.log_test("Sales Agent My Routes", False, "Response is not a list")
else:
self.log_test("Sales Agent My Routes", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Sales Agent My Routes", False, f"Exception: {str(e)}")
def test_sales_agent_stats(self):
"""Test GET /api/salesagent/stats"""
headers = self.get_headers("plasiyer")
if not headers:
self.log_test("Sales Agent Stats", False, "No plasiyer token")
return
try:
response = requests.get(
f"{BASE_URL}/salesagent/stats",
headers=headers,
timeout=30
)
if response.status_code == 200:
stats = response.json()
if isinstance(stats, dict):
required_fields = ["my_customers_count", "my_warehouse_orders", "customer_orders", "total_orders"]
missing_fields = [field for field in required_fields if field not in stats]
if missing_fields:
self.log_test("Sales Agent Stats", False, f"Missing fields: {missing_fields}")
else:
self.log_test("Sales Agent Stats", True, f"Stats: {stats}")
else:
self.log_test("Sales Agent Stats", False, "Response is not a dict")
else:
self.log_test("Sales Agent Stats", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Sales Agent Stats", False, f"Exception: {str(e)}")
def test_sales_routes_create(self):
"""Test POST /api/sales-routes"""
headers = self.get_headers("admin")
if not headers:
self.log_test("Sales Routes Create", False, "No admin token")
return
try:
# Get a sales agent and customer for the route
users_response = requests.get(f"{BASE_URL}/auth/me", headers=headers, timeout=30)
route_data = {
"sales_agent_id": str(uuid.uuid4()), # Test with dummy ID
"customer_id": str(uuid.uuid4()), # Test with dummy ID
"delivery_day": "monday",
"route_order": 1,
"notes": "Test route creation"
}
response = requests.post(
f"{BASE_URL}/sales-routes",
json=route_data,
headers=headers,
timeout=30
)
if response.status_code == 200:
route = response.json()
if route.get("id") and route.get("delivery_day") == "monday":
self.log_test("Sales Routes Create", True, f"Route created with ID: {route.get('id')}")
else:
self.log_test("Sales Routes Create", False, "Invalid route response structure")
else:
self.log_test("Sales Routes Create", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Sales Routes Create", False, f"Exception: {str(e)}")
def test_sales_routes_list(self):
"""Test GET /api/sales-routes"""
headers = self.get_headers("admin")
if not headers:
self.log_test("Sales Routes List", False, "No admin token")
return
try:
response = requests.get(
f"{BASE_URL}/sales-routes",
headers=headers,
timeout=30
)
if response.status_code == 200:
routes = response.json()
if isinstance(routes, list):
self.log_test("Sales Routes List", True, f"Found {len(routes)} routes")
# Check structure if routes exist
if routes:
route = routes[0]
required_fields = ["id", "sales_agent_id", "customer_id", "delivery_day"]
missing_fields = [field for field in required_fields if field not in route]
if missing_fields:
self.log_test("Sales Routes List Structure", False, f"Missing fields: {missing_fields}")
else:
self.log_test("Sales Routes List Structure", True, "All required fields present")
else:
self.log_test("Sales Routes List", False, "Response is not a list")
else:
self.log_test("Sales Routes List", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Sales Routes List", False, f"Exception: {str(e)}")
def test_customer_delivery_day(self):
"""Test GET /api/sales-routes/customer/{customer_id}"""
headers = self.get_headers("customer")
if not headers:
self.log_test("Customer Delivery Day", False, "No customer token")
return
try:
# First get customer info to get customer ID
me_response = requests.get(f"{BASE_URL}/auth/me", headers=headers, timeout=30)
if me_response.status_code != 200:
self.log_test("Customer Delivery Day", False, "Could not get customer info")
return
customer_info = me_response.json()
customer_id = customer_info.get("id")
if not customer_id:
self.log_test("Customer Delivery Day", False, "No customer ID found")
return
response = requests.get(
f"{BASE_URL}/sales-routes/customer/{customer_id}",
headers=headers,
timeout=30
)
if response.status_code == 200:
delivery_info = response.json()
if isinstance(delivery_info, dict):
if "delivery_day" in delivery_info:
self.log_test("Customer Delivery Day", True, f"Delivery day: {delivery_info.get('delivery_day')}")
else:
self.log_test("Customer Delivery Day", False, "No delivery_day field in response")
else:
self.log_test("Customer Delivery Day", False, "Response is not a dict")
else:
self.log_test("Customer Delivery Day", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Customer Delivery Day", False, f"Exception: {str(e)}")
# ========== NEW INVOICE API TESTS ==========
def test_sed_invoice_upload(self):
"""Test SED HTML Invoice Upload and Parsing"""
headers = self.get_headers("accounting")
if not headers:
self.log_test("SED Invoice Upload", False, "No accounting token")
return
# Fetch SED HTML content from URL
try:
import requests as req_lib
html_response = req_lib.get("https://customer-assets.emergentagent.com/job_c21b56fa-eb45-48e4-8eca-74c5ff09f9b2/artifacts/nf1rxoc2_SED2025000000078.html", timeout=30)
if html_response.status_code != 200:
self.log_test("SED Invoice Upload", False, f"Failed to fetch HTML: {html_response.status_code}")
return
sed_html_content = html_response.text
invoice_data = {
"html_content": sed_html_content
}
response = requests.post(
f"{BASE_URL}/invoices/upload",
json=invoice_data,
headers=headers,
timeout=30
)
if response.status_code == 200:
result = response.json()
invoice_id = result.get("invoice_id")
if invoice_id:
self.log_test("SED Invoice Upload", True, f"SED Invoice uploaded: {invoice_id}")
# Store invoice ID for detailed validation
self.uploaded_invoice_id = invoice_id
# Now validate the parsed data
self.validate_sed_invoice_parsing(invoice_id, headers)
else:
self.log_test("SED Invoice Upload", False, "No invoice_id in response")
else:
self.log_test("SED Invoice Upload", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("SED Invoice Upload", False, f"Exception: {str(e)}")
def validate_sed_invoice_parsing(self, invoice_id, headers):
"""Validate SED invoice parsing results"""
try:
# Get invoice details
response = requests.get(
f"{BASE_URL}/invoices/{invoice_id}",
headers=headers,
timeout=30
)
if response.status_code != 200:
self.log_test("SED Invoice Parsing Validation", False, f"Failed to get invoice details: {response.status_code}")
return
invoice = response.json()
# Expected values for SED2025000000078
expected_customer_name = "YÖRÜKOĞLU SÜT VE ÜRÜNLERİ SANAYİ TİCARET ANONİM ŞİRKETİ"
expected_tax_id = "9830366087"
expected_invoice_number = "SED2025000000078"
expected_invoice_date = "27 10 2025"
expected_product_count = 9
expected_grand_total = "47.395,61"
# Validate customer name
if invoice.get("customer_name") == expected_customer_name:
self.log_test("SED Customer Name Parsing", True, f"Correct: {invoice.get('customer_name')}")
else:
self.log_test("SED Customer Name Parsing", False, f"Expected: {expected_customer_name}, Got: {invoice.get('customer_name')}")
# Validate tax ID
if invoice.get("customer_tax_id") == expected_tax_id:
self.log_test("SED Tax ID Parsing", True, f"Correct: {invoice.get('customer_tax_id')}")
else:
self.log_test("SED Tax ID Parsing", False, f"Expected: {expected_tax_id}, Got: {invoice.get('customer_tax_id')}")
# Validate invoice number
if invoice.get("invoice_number") == expected_invoice_number:
self.log_test("SED Invoice Number Parsing", True, f"Correct: {invoice.get('invoice_number')}")
else:
self.log_test("SED Invoice Number Parsing", False, f"Expected: {expected_invoice_number}, Got: {invoice.get('invoice_number')}")
# Validate invoice date
if invoice.get("invoice_date") == expected_invoice_date:
self.log_test("SED Invoice Date Parsing", True, f"Correct: {invoice.get('invoice_date')}")
else:
self.log_test("SED Invoice Date Parsing", False, f"Expected: {expected_invoice_date}, Got: {invoice.get('invoice_date')}")
# Validate product count
products = invoice.get("products", [])
if len(products) == expected_product_count:
self.log_test("SED Product Count Parsing", True, f"Correct: {len(products)} products")
else:
self.log_test("SED Product Count Parsing", False, f"Expected: {expected_product_count}, Got: {len(products)}")
# Validate specific products
expected_products = [
{"name": "SÜZME YOĞURT 10 KG.", "quantity": 9},
{"name": "YARIM YAĞLI YOĞURT 10 KG.", "quantity": 5},
{"name": "KÖY PEYNİRİ 4 KG.", "quantity": 3}
]
for expected_product in expected_products:
found = False
for product in products:
if (expected_product["name"] in product.get("product_name", "") and
product.get("quantity") == expected_product["quantity"]):
found = True
break
if found:
self.log_test(f"SED Product '{expected_product['name']}' Parsing", True, f"Found with quantity {expected_product['quantity']}")
else:
self.log_test(f"SED Product '{expected_product['name']}' Parsing", False, f"Not found or incorrect quantity")
# Validate grand total
if invoice.get("grand_total") == expected_grand_total:
self.log_test("SED Grand Total Parsing", True, f"Correct: {invoice.get('grand_total')}")
else:
self.log_test("SED Grand Total Parsing", False, f"Expected: {expected_grand_total}, Got: {invoice.get('grand_total')}")
except Exception as e:
self.log_test("SED Invoice Parsing Validation", False, f"Exception: {str(e)}")
def test_invoice_upload(self):
"""Test POST /api/invoices/upload"""
headers = self.get_headers("accounting")
if not headers:
self.log_test("Invoice Upload", False, "No accounting token")
return
# Sample HTML invoice content
sample_html = """
<html>
<body>
<h1>FATURA</h1>
<p>Fatura No: EE12025000004134</p>
<p>Tarih: 15 01 2025</p>
<p>Vergi No: 1234567890</p>
<table>
<tr><td>Ürün</td><td>Miktar</td><td>Fiyat</td></tr>
<tr><td>Coca Cola 330ml</td><td>24</td><td>120,00 TL</td></tr>
<tr><td>Fanta 330ml</td><td>12</td><td>60,00 TL</td></tr>
</table>
<p>Toplam: 180,00 TL</p>
</body>
</html>
"""
try:
invoice_data = {
"html_content": sample_html
}
response = requests.post(
f"{BASE_URL}/invoices/upload",
json=invoice_data,
headers=headers,
timeout=30
)
if response.status_code == 200:
result = response.json()
if result.get("invoice_id"):
self.log_test("Invoice Upload", True, f"Invoice uploaded: {result.get('invoice_id')}")
# Store invoice ID for later tests
self.uploaded_invoice_id = result.get("invoice_id")
else:
self.log_test("Invoice Upload", False, "No invoice_id in response")
else:
self.log_test("Invoice Upload", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Invoice Upload", False, f"Exception: {str(e)}")
def test_get_all_invoices(self):
"""Test GET /api/invoices/all/list"""
headers = self.get_headers("accounting")
if not headers:
self.log_test("Get All Invoices", False, "No accounting token")
return
try:
response = requests.get(
f"{BASE_URL}/invoices/all/list",
headers=headers,
timeout=30
)
if response.status_code == 200:
invoices = response.json()
if isinstance(invoices, list):
self.log_test("Get All Invoices", True, f"Found {len(invoices)} invoices")
# Check structure if invoices exist
if invoices:
invoice = invoices[0]
required_fields = ["id", "invoice_number", "invoice_date", "grand_total"]
missing_fields = [field for field in required_fields if field not in invoice]
if missing_fields:
self.log_test("Get All Invoices Structure", False, f"Missing fields: {missing_fields}")
else:
self.log_test("Get All Invoices Structure", True, "All required fields present")
else:
self.log_test("Get All Invoices", False, "Response is not a list")
else:
self.log_test("Get All Invoices", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Get All Invoices", False, f"Exception: {str(e)}")
def test_get_my_invoices(self):
"""Test GET /api/invoices/my-invoices"""
headers = self.get_headers("customer")
if not headers:
self.log_test("Get My Invoices", False, "No customer token")
return
try:
response = requests.get(
f"{BASE_URL}/invoices/my-invoices",
headers=headers,
timeout=30
)
if response.status_code == 200:
invoices = response.json()
if isinstance(invoices, list):
self.log_test("Get My Invoices", True, f"Customer has {len(invoices)} invoices")
else:
self.log_test("Get My Invoices", False, "Response is not a list")
else:
self.log_test("Get My Invoices", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Get My Invoices", False, f"Exception: {str(e)}")
def test_get_invoice_detail(self):
"""Test GET /api/invoices/{invoice_id}"""
if not hasattr(self, 'uploaded_invoice_id'):
self.log_test("Get Invoice Detail", False, "No uploaded invoice ID available")
return
headers = self.get_headers("accounting")
if not headers:
self.log_test("Get Invoice Detail", False, "No accounting token")
return
try:
response = requests.get(
f"{BASE_URL}/invoices/{self.uploaded_invoice_id}",
headers=headers,
timeout=30
)
if response.status_code == 200:
invoice = response.json()
if isinstance(invoice, dict):
required_fields = ["id", "invoice_number", "html_content", "grand_total"]
missing_fields = [field for field in required_fields if field not in invoice]
if missing_fields:
self.log_test("Get Invoice Detail", False, f"Missing fields: {missing_fields}")
else:
self.log_test("Get Invoice Detail", True, f"Invoice detail retrieved: {invoice.get('invoice_number')}")
else:
self.log_test("Get Invoice Detail", False, "Response is not a dict")
else:
self.log_test("Get Invoice Detail", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Get Invoice Detail", False, f"Exception: {str(e)}")
# ========== NEW CONSUMPTION API TESTS ==========
def test_consumption_calculate(self):
"""Test POST /api/consumption/calculate"""
headers = self.get_headers("admin")
if not headers:
self.log_test("Consumption Calculate", False, "No admin token")
return
try:
response = requests.post(
f"{BASE_URL}/consumption/calculate",
headers=headers,
timeout=30
)
if response.status_code == 200:
result = response.json()
if isinstance(result, dict):
if "records_processed" in result:
self.log_test("Consumption Calculate", True, f"Processed {result.get('records_processed')} records")
else:
self.log_test("Consumption Calculate", False, "No records_processed field")
else:
self.log_test("Consumption Calculate", False, "Response is not a dict")
else:
self.log_test("Consumption Calculate", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Consumption Calculate", False, f"Exception: {str(e)}")
def test_get_my_consumption(self):
"""Test GET /api/consumption/my-consumption"""
headers = self.get_headers("customer")
if not headers:
self.log_test("Get My Consumption", False, "No customer token")
return
try:
# Test monthly consumption
response = requests.get(
f"{BASE_URL}/consumption/my-consumption?period_type=monthly",
headers=headers,
timeout=30
)
if response.status_code == 200:
consumption = response.json()
if isinstance(consumption, list):
self.log_test("Get My Consumption", True, f"Customer has {len(consumption)} consumption records")
# Check structure if records exist
if consumption:
record = consumption[0]
required_fields = ["product_name", "weekly_avg", "monthly_avg", "last_order_date"]
missing_fields = [field for field in required_fields if field not in record]
if missing_fields:
self.log_test("Get My Consumption Structure", False, f"Missing fields: {missing_fields}")
else:
self.log_test("Get My Consumption Structure", True, "All required fields present")
else:
self.log_test("Get My Consumption", False, "Response is not a list")
else:
self.log_test("Get My Consumption", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Get My Consumption", False, f"Exception: {str(e)}")
def test_get_customer_consumption(self):
"""Test GET /api/consumption/customer/{customer_id}"""
headers = self.get_headers("admin")
if not headers:
self.log_test("Get Customer Consumption", False, "No admin token")
return
try:
# First get a customer ID
customer_headers = self.get_headers("customer")
if customer_headers:
me_response = requests.get(f"{BASE_URL}/auth/me", headers=customer_headers, timeout=30)
if me_response.status_code == 200:
customer_info = me_response.json()
customer_id = customer_info.get("id")
if customer_id:
response = requests.get(
f"{BASE_URL}/consumption/customer/{customer_id}?period_type=weekly",
headers=headers,
timeout=30
)
if response.status_code == 200:
consumption = response.json()
if isinstance(consumption, list):
self.log_test("Get Customer Consumption", True, f"Customer has {len(consumption)} consumption records")
else:
self.log_test("Get Customer Consumption", False, "Response is not a list")
else:
self.log_test("Get Customer Consumption", False, f"Status: {response.status_code}, Response: {response.text}")
else:
self.log_test("Get Customer Consumption", False, "No customer ID found")
else:
self.log_test("Get Customer Consumption", False, "Could not get customer info")
else:
self.log_test("Get Customer Consumption", False, "No customer token for ID lookup")
except Exception as e:
self.log_test("Get Customer Consumption", False, f"Exception: {str(e)}")
def test_customer_lookup_existing(self):
"""Test GET /api/customers/lookup/{tax_id} - Existing Customer"""
headers = self.get_headers("accounting")
if not headers:
self.log_test("Customer Lookup - Existing", False, "No accounting token")
return
try:
# Use the tax ID from previous test (1234567890 from review request)
test_tax_id = "1234567890"
response = requests.get(
f"{BASE_URL}/customers/lookup/{test_tax_id}",
headers=headers,
timeout=30
)
if response.status_code == 200:
result = response.json()
# Validate response structure
expected_fields = ["found", "customer_name", "customer_tax_id", "email", "phone", "address"]
missing_fields = [field for field in expected_fields if field not in result]
if missing_fields:
self.log_test("Customer Lookup - Existing", False, f"Missing response fields: {missing_fields}")
return
# Validate expected values from review request
if result.get("found") != True:
self.log_test("Customer Lookup - Existing", False, f"found should be true, got: {result.get('found')}")
return
if result.get("customer_tax_id") != test_tax_id:
self.log_test("Customer Lookup - Existing", False, f"Wrong tax ID: expected {test_tax_id}, got {result.get('customer_tax_id')}")
return
self.log_test("Customer Lookup - Existing", True,
f"Found customer: {result.get('customer_name')} (Tax ID: {result.get('customer_tax_id')})")
else:
self.log_test("Customer Lookup - Existing", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Customer Lookup - Existing", False, f"Exception: {str(e)}")
def test_customer_lookup_not_found(self):
"""Test GET /api/customers/lookup/{tax_id} - Non-existing Customer"""
headers = self.get_headers("accounting")
if not headers:
self.log_test("Customer Lookup - Not Found", False, "No accounting token")
return
try:
# Use a truly non-existing tax ID
import time
test_tax_id = f"8888888{int(time.time()) % 1000:03d}"
response = requests.get(
f"{BASE_URL}/customers/lookup/{test_tax_id}",
headers=headers,
timeout=30
)
if response.status_code == 404:
result = response.json()
expected_detail = "Bu vergi numarası ile kayıtlı müşteri bulunamadı"
if result.get("detail") == expected_detail:
self.log_test("Customer Lookup - Not Found", True, f"Correct 404 response: {result.get('detail')}")
else:
self.log_test("Customer Lookup - Not Found", False, f"Wrong error message: {result.get('detail')}")
else:
self.log_test("Customer Lookup - Not Found", False, f"Expected 404, got: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Customer Lookup - Not Found", False, f"Exception: {str(e)}")
def test_manual_invoice_new_categories(self):
"""Test Manuel Fatura Giriş - Yeni Kategoriler ile Ürünler"""
headers = self.get_headers("accounting")
if not headers:
self.log_test("Manual Invoice - New Categories", False, "No accounting token")
return
try:
# Generate unique tax ID and product codes for this test run
import time
timestamp = int(time.time()) % 10000
unique_tax_id = f"555555{timestamp:04d}"
# Test data from review request with new categories
invoice_data = {
"customer": {
"customer_name": "YENİ TEST MÜŞTERİ LTD",
"customer_tax_id": unique_tax_id,
"address": "Yeni Adres",
"email": "yeni@test.com",
"phone": "0312 999 88 77"
},
"invoice_number": "TEST2025000002",
"invoice_date": "2025-01-16",
"products": [
{
"product_code": f"YOG{timestamp:03d}",
"product_name": "KREMALI YOĞURT 1 KG",
"category": "Yoğurt",
"quantity": 50,
"unit": "ADET",
"unit_price": "25.00",
"total": "1250.00"
},
{
"product_code": f"AYR{timestamp:03d}",
"product_name": "AYRAN 200 ML",
"category": "Ayran",
"quantity": 100,
"unit": "ADET",
"unit_price": "5.00",
"total": "500.00"
},
{
"product_code": f"KAS{timestamp:03d}",
"product_name": "TAZE KAŞAR 500 GR",
"category": "Kaşar",
"quantity": 20,
"unit": "ADET",
"unit_price": "150.00",
"total": "3000.00"
},
{
"product_code": f"TER{timestamp:03d}",
"product_name": "TEREYAĞ 250 GR",
"category": "Tereyağı",
"quantity": 30,
"unit": "ADET",
"unit_price": "80.00",
"total": "2400.00"
},
{
"product_code": f"KRE{timestamp:03d}",
"product_name": "ŞEFİN KREMASI 200 ML",
"category": "Krema",
"quantity": 25,
"unit": "ADET",
"unit_price": "35.00",
"total": "875.00"
}
],
"subtotal": "8025.00",
"total_discount": "0",
"total_tax": "80.25",
"grand_total": "8105.25"
}
response = requests.post(
f"{BASE_URL}/invoices/manual-entry",
json=invoice_data,
headers=headers,
timeout=30
)
if response.status_code == 200:
result = response.json()
# Validate response structure
expected_fields = ["message", "invoice_id", "customer_created", "customer_username", "customer_password", "products_created"]
missing_fields = [field for field in expected_fields if field not in result]
if missing_fields:
self.log_test("Manual Invoice - New Categories", False, f"Missing response fields: {missing_fields}")
return
# Validate response values
if result.get("message") != "Manuel fatura başarıyla oluşturuldu":
self.log_test("Manual Invoice - New Categories", False, f"Wrong message: {result.get('message')}")
return
if result.get("customer_created") != True:
self.log_test("Manual Invoice - New Categories", False, f"customer_created should be true for new customer, got: {result.get('customer_created')}")
return
if not result.get("customer_username") or not result.get("customer_password"):
self.log_test("Manual Invoice - New Categories", False, "Missing customer credentials")
return
expected_products = ["KREMALI YOĞURT 1 KG", "AYRAN 200 ML", "TAZE KAŞAR 500 GR", "TEREYAĞ 250 GR", "ŞEFİN KREMASI 200 ML"]
if result.get("products_created") != expected_products:
self.log_test("Manual Invoice - New Categories", False, f"Wrong products created: {result.get('products_created')}")
return
# Store for later tests
self.new_customer_username = result.get("customer_username")
self.new_customer_password = result.get("customer_password")
self.new_invoice_id = result.get("invoice_id")
self.test_tax_id = unique_tax_id # Store for existing customer test
self.log_test("Manual Invoice - New Categories", True,
f"Invoice: {result.get('invoice_id')}, Customer: {result.get('customer_username')}/{result.get('customer_password')}, Products: {len(result.get('products_created', []))}")
else:
self.log_test("Manual Invoice - New Categories", False, f"Status: {response.status_code}, Response: {response.text}")
except Exception as e:
self.log_test("Manual Invoice - New Categories", False, f"Exception: {str(e)}")
def test_manual_invoice_entry_new_customer(self):
"""Test Manuel Fatura Giriş - Yeni Müşteri + Yeni Ürünler (Legacy Test)"""
headers = self.get_headers("accounting")
if not headers:
self.log_test("Manual Invoice Entry - New Customer", False, "No accounting token")
return
try:
# Generate unique tax ID and product codes for this test run
import time
timestamp = int(time.time()) % 10000
unique_tax_id = f"123456{timestamp:04d}"
product_code_1 = f"TEST{timestamp:03d}01"
product_code_2 = f"TEST{timestamp:03d}02"
# Test data from review request
invoice_data = {
"customer": {
"customer_name": "TEST GIDA SANAYİ VE TİCARET LTD ŞTİ",
"customer_tax_id": unique_tax_id,
"address": "Test Mahallesi, Test Sokak No:1, Ankara",
"email": "info@testgida.com",
"phone": "0312 555 12 34"
},
"invoice_number": "TEST2025000001",
"invoice_date": "2025-01-15",
"products": [
{
"product_code": product_code_1,
"product_name": "TEST SÜZME YOĞURT 5 KG",
"category": "Süt Ürünleri",
"quantity": 10,
"unit": "ADET",
"unit_price": "500.00",
"total": "5000.00"
},
{
"product_code": product_code_2,
"product_name": "TEST BEYAZ PEYNİR 1 KG",
"category": "Peynir",
"quantity": 20,
"unit": "ADET",
"unit_price": "300.00",
"total": "6000.00"
}
],
"subtotal": "11000.00",
"total_discount": "0",