#!/usr/bin/env python3 """ Comprehensive End-to-End Test for DMH Pharmacy Dashboard: PO Number Approval & Item Code Management Tests all 13 steps defined in Section 11. """ import os import sys import json import sqlite3 import threading from http.server import HTTPServer, BaseHTTPRequestHandler from werkzeug.security import generate_password_hash # Ensure test uses app.py from app import app, get_db, ensure_po_approval_tables # Setup Mock Webhook Server to capture n8n webhook calls webhook_requests = [] webhook_response_code = 200 class MockWebhookHandler(BaseHTTPRequestHandler): def do_POST(self): content_length = int(self.headers.get('Content-Length', 0)) post_data = self.rfile.read(content_length) try: payload = json.loads(post_data.decode('utf-8')) except Exception: payload = post_data.decode('utf-8') webhook_requests.append({ 'path': self.path, 'headers': dict(self.headers), 'payload': payload }) self.send_response(webhook_response_code) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps({'received': True, 'status': 'ok'}).encode('utf-8')) def log_message(self, format, *args): pass # Quiet logging def start_mock_webhook_server(port=9988): server = HTTPServer(('127.0.0.1', port), MockWebhookHandler) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() return server def run_tests(): global webhook_response_code print("=" * 70) print("๐Ÿงช STARTING DMH PO NUMBER APPROVAL & ITEM CODE VERIFICATION") print("=" * 70) # 1. Start mock webhook server mock_port = 9988 mock_server = start_mock_webhook_server(mock_port) mock_webhook_url = f"http://127.0.0.1:{mock_port}/webhook/dmh-po-approval" os.environ['DMH_PO_APPROVAL_WEBHOOK_URL'] = mock_webhook_url print(f"โœ… Mock n8n Webhook Server running on {mock_webhook_url}") # 2. Setup test client and test user app.config['TESTING'] = True client = app.test_client() # Create/ensure a test pharmacy user in DB conn = get_db() cursor = conn.cursor() cursor.execute("SELECT id FROM users WHERE username = 'pharmacy_tester'") existing_user = cursor.fetchone() if not existing_user: cursor.execute( "INSERT INTO users (username, email, password, is_active, is_admin) VALUES (?, ?, ?, 1, 0)", ('pharmacy_tester', 'tester@dmh.org', generate_password_hash('TestPass123!')) ) conn.commit() user_id = cursor.lastrowid else: user_id = existing_user['id'] conn.close() # Log in session for test client with client.session_transaction() as sess: sess['user_id'] = user_id sess['username'] = 'pharmacy_tester' print(f"โœ… Authenticated as test user (id={user_id}, username='pharmacy_tester')") # ------------------------------------------------------------- # Step 1 & 2: Condition 3 identification & Auto-submission # (PO number missing/empty AND item code missing from invoice) # ------------------------------------------------------------- print("\n--- Testing Step 1 & 2: Condition 3 Identification ---") mock_invoice_data = { 'invoice_id': 'INV-TEST-2026-001', 'invoice_number': 'INV-TEST-2026-001', 'vendor_name': 'Apex Pharma Distributors', 'invoice_date': '2026-11-20', 'po_number': '', # MISSING PO 'items': [ { 'description': 'UNKNOWN MEDICATION XYZ 500MG', 'quantity': 100, 'unit_price': 45.50, 'item_code': '', 'item_code_source': 'not_found', # MISSING ITEM CODE 'in_csv': False } ] } # Store extraction in extractions table conn = get_db() cursor = conn.cursor() cursor.execute( "INSERT INTO extractions (user_id, invoice_id, filename, extraction_data) VALUES (?, ?, ?, ?)", (user_id, 'INV-TEST-2026-001', 'test_invoice_cond3.pdf', json.dumps(mock_invoice_data)) ) conn.commit() extraction_id = cursor.lastrowid conn.close() # Submit to PO approval queue (mimics upload auto-submit logic) submit_resp = client.post('/api/po-approval/submit', json={ 'extraction_id': extraction_id, 'invoice_number': 'INV-TEST-2026-001', 'vendor_name': 'Apex Pharma Distributors', 'invoice_date': '2026-11-20', 'invoice_filename': 'test_invoice_cond3.pdf', 'po_number_original': '' }) assert submit_resp.status_code in (200, 201), f"Submit failed: {submit_resp.data}" submit_data = submit_resp.get_json() po_invoice_id = submit_data['po_invoice_id'] print(f"โœ… Condition 3 record queued in po_approval_invoices with ID: {po_invoice_id}") # Test duplicate submission prevention dup_resp = client.post('/api/po-approval/submit', json={ 'extraction_id': extraction_id, 'invoice_number': 'INV-TEST-2026-001', 'vendor_name': 'Apex Pharma Distributors', 'invoice_date': '2026-11-20', 'invoice_filename': 'test_invoice_cond3.pdf', 'po_number_original': '' }) dup_data = dup_resp.get_json() assert dup_data.get('duplicate') is True and dup_data.get('po_invoice_id') == po_invoice_id print("โœ… Duplicate submission prevention verified") # ------------------------------------------------------------- # Step 3: Pending PO Number Approval List # ------------------------------------------------------------- print("\n--- Testing Step 3: Pending PO Approval Listing ---") pending_resp = client.get('/api/po-approval/pending') assert pending_resp.status_code == 200 pending_list = pending_resp.get_json()['data'] matching_pending = [p for p in pending_list if p['id'] == po_invoice_id] assert len(matching_pending) == 1, "Invoice not found in pending list!" p_item = matching_pending[0] assert p_item['invoice_number'] == 'INV-TEST-2026-001' assert p_item['vendor_name'] == 'Apex Pharma Distributors' assert p_item['approval_status'] == 'pending' print(f"โœ… Invoice correctly listed in Pending PO Approvals ({p_item['invoice_number']})") # ------------------------------------------------------------- # Step 4: Invoice Details and Line Items # ------------------------------------------------------------- print("\n--- Testing Step 4: Invoice Details & Items ---") detail_resp = client.get(f'/api/po-approval/invoice/{po_invoice_id}') assert detail_resp.status_code == 200 detail_data = detail_resp.get_json() assert detail_data['data']['invoice_number'] == 'INV-TEST-2026-001' assert len(detail_data['items']) == 1 assert detail_data['items'][0]['description'] == 'UNKNOWN MEDICATION XYZ 500MG' print(f"โœ… Invoice details retrieved with {len(detail_data['items'])} line items") # ------------------------------------------------------------- # Step 5 & 6: Validation, Manual PO Entry and Approval # ------------------------------------------------------------- print("\n--- Testing Step 5 & 6: Validation and Manual PO Approval ---") # Test empty PO rejection empty_po_resp = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': ' '}) assert empty_po_resp.status_code == 400 print("โœ… Empty PO Number correctly rejected (HTTP 400)") # Clear captured webhook requests webhook_requests.clear() webhook_response_code = 200 # Submit valid PO approval test_po_num = "PO-DMH-98765" approve_resp = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': test_po_num}) assert approve_resp.status_code == 200 appr_res = approve_resp.get_json() assert appr_res['success'] is True assert appr_res['approval_status'] == 'approved' assert appr_res['webhook_status'] == 'success' print(f"โœ… Approval submitted successfully with PO: {test_po_num}") # ------------------------------------------------------------- # Step 7 & 8: Verify DB persistence & Audit fields # ------------------------------------------------------------- print("\n--- Testing Step 7 & 8: Database Persistence & User Audit ---") conn = get_db() cursor = conn.cursor() cursor.execute("SELECT * FROM po_approval_invoices WHERE id = ?", (po_invoice_id,)) inv_row = cursor.fetchone() assert inv_row['approval_status'] == 'approved' assert inv_row['po_number_approved'] == test_po_num assert inv_row['approved_by'] == user_id assert inv_row['approved_at'] is not None cursor.execute("SELECT * FROM po_approval_history WHERE po_invoice_id = ?", (po_invoice_id,)) hist_rows = cursor.fetchall() assert len(hist_rows) >= 1 latest_hist = hist_rows[-1] assert latest_hist['po_number_approved'] == test_po_num assert latest_hist['approved_by'] == user_id assert latest_hist['approved_by_username'] == 'pharmacy_tester' assert latest_hist['webhook_status'] == 'success' conn.close() print(f"โœ… Database verified: PO={inv_row['po_number_approved']}, user_id={inv_row['approved_by']}, time={inv_row['approved_at']}") # ------------------------------------------------------------- # Step 9 & 10: Verify n8n Webhook Trigger & Payload # ------------------------------------------------------------- print("\n--- Testing Step 9 & 10: n8n Webhook Payload & Status ---") assert len(webhook_requests) == 1, f"Expected 1 webhook call, got {len(webhook_requests)}" wh_call = webhook_requests[0] expected_payload = { "event": "po_number_approved", "invoice_id": po_invoice_id, "invoice_number": "INV-TEST-2026-001", "approved_po_number": test_po_num, "approved_by": user_id, "approval_status": "approved" } assert wh_call['payload'] == expected_payload, f"Payload mismatch: {wh_call['payload']} vs {expected_payload}" print(f"โœ… Webhook payload verified: {json.dumps(wh_call['payload'], indent=2)}") # Test duplicate approval blocked dup_appr = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': 'PO-ANOTHER'}) assert dup_appr.status_code == 409 print("โœ… Duplicate approval prevented (HTTP 409)") # ------------------------------------------------------------- # Step 11: PO Approval History Audit Trail # ------------------------------------------------------------- print("\n--- Testing Step 11: PO Approval History Verification ---") hist_resp = client.get('/api/po-approval/history?status=approved') assert hist_resp.status_code == 200 hist_list = hist_resp.get_json()['data'] found_in_history = [h for h in hist_list if h['po_invoice_id'] == po_invoice_id] assert len(found_in_history) >= 1 print(f"โœ… History listing verified ({len(found_in_history)} record(s) for this invoice)") # ------------------------------------------------------------- # Step 12: Webhook Failure and Safe Retry # ------------------------------------------------------------- print("\n--- Testing Step 12: Webhook Failure & Retry Logic ---") # Create another test invoice for failure test conn = get_db() cursor = conn.cursor() cursor.execute( "INSERT INTO extractions (user_id, invoice_id, filename, extraction_data) VALUES (?, ?, ?, ?)", (user_id, 'INV-TEST-FAIL-002', 'test_fail.pdf', json.dumps(mock_invoice_data)) ) fail_ext_id = cursor.lastrowid cursor.execute(''' INSERT INTO po_approval_invoices (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original) VALUES (?, 'INV-TEST-FAIL-002', 'Beta Med', '2026-11-21', 'test_fail.pdf', '') ''', (fail_ext_id,)) fail_po_id = cursor.lastrowid conn.commit() conn.close() # Simulate webhook failure (HTTP 500 from webhook server) webhook_response_code = 500 fail_approve_resp = client.post(f'/api/po-approval/{fail_po_id}/approve', json={'po_number': 'PO-FAIL-111'}) assert fail_approve_resp.status_code == 200 fail_data = fail_approve_resp.get_json() assert fail_data['approval_status'] == 'approved' assert fail_data['webhook_status'] == 'failed' print("โœ… Approved record preserved even when webhook returns HTTP 500 (safe failure)") # Retrieve history record ID for retry conn = get_db() cursor = conn.cursor() cursor.execute("SELECT id FROM po_approval_history WHERE po_invoice_id = ?", (fail_po_id,)) fail_hist_id = cursor.fetchone()['id'] conn.close() # Test retry with webhook server restored to HTTP 200 webhook_response_code = 200 retry_resp = client.post(f'/api/po-approval/{fail_hist_id}/retry-webhook') assert retry_resp.status_code == 200 retry_data = retry_resp.get_json() assert retry_data['webhook_status'] == 'success' print("โœ… Webhook retry succeeded and updated history status to 'success'") # Test rejection flow conn = get_db() cursor = conn.cursor() cursor.execute(''' INSERT INTO po_approval_invoices (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original) VALUES (?, 'INV-TEST-REJECT-003', 'Gamma Supplies', '2026-11-22', 'test_rej.pdf', '') ''', (fail_ext_id,)) rej_po_id = cursor.lastrowid conn.commit() conn.close() rej_resp = client.post(f'/api/po-approval/{rej_po_id}/reject', json={'notes': 'Wrong vendor invoice'}) assert rej_resp.status_code == 200 assert rej_resp.get_json()['approval_status'] == 'rejected' print("โœ… Rejection flow verified") # ------------------------------------------------------------- # Step 13: Existing Item Code Management Logic Continues Working # ------------------------------------------------------------- print("\n--- Testing Step 13: Existing Item Code Management ---") cat_resp = client.get('/api/catalog?per_page=5') assert cat_resp.status_code == 200 cat_data = cat_resp.get_json() assert cat_data['success'] is True assert cat_data['total'] > 0 print(f"โœ… Catalog browsing active: {cat_data['total']} item codes available") auto_resp = client.get('/api/catalog/autocomplete?q=para') assert auto_resp.status_code == 200 auto_data = auto_resp.get_json() assert auto_data['success'] is True print(f"โœ… Catalog autocomplete active: returned {len(auto_data['data'])} suggestions") cats_resp = client.get('/api/catalog/categories') assert cats_resp.status_code == 200 print(f"โœ… Catalog categories active: {len(cats_resp.get_json()['data'])} categories") pending_items_resp = client.get('/api/pending-items') assert pending_items_resp.status_code == 200 print("โœ… Existing Item Code pending approval queue active") print("\n" + "=" * 70) print("๐ŸŽ‰ ALL 13 TEST STEPS PASSED SUCCESSFULLY!") print("=" * 70) if __name__ == '__main__': run_tests()