File size: 9,453 Bytes
66d6b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# example_optimize.py
"""
Example usage of the Tax Optimization API
Demonstrates how to send transaction data and get optimization recommendations
"""
import requests
import json
from datetime import datetime, timedelta

# API endpoint (adjust if running on different host/port)
BASE_URL = "http://localhost:8000"
OPTIMIZE_ENDPOINT = f"{BASE_URL}/v1/optimize"

# Example: Individual with employment income
def example_employed_individual():
    """Example: Employed individual with salary and some deductions"""
    
    # Simulate 12 months of transactions
    transactions = []
    
    # Monthly salary (Jan - Dec 2025)
    for month in range(1, 13):
        date_str = f"2025-{month:02d}-28"
        
        # Salary credit
        transactions.append({
            "type": "credit",
            "amount": 500000,
            "narration": "SALARY PAYMENT FROM ABC COMPANY LTD",
            "date": date_str,
            "balance": 750000,
            "metadata": {
                "basic_salary": 300000,
                "housing_allowance": 120000,
                "transport_allowance": 60000,
                "bonus": 20000
            }
        })
        
        # Pension deduction (8% of basic = 24,000)
        transactions.append({
            "type": "debit",
            "amount": 24000,
            "narration": "PENSION CONTRIBUTION TO XYZ PFA RSA",
            "date": date_str,
            "balance": 726000
        })
        
        # NHF deduction (2.5% of basic = 7,500)
        transactions.append({
            "type": "debit",
            "amount": 7500,
            "narration": "NHF CONTRIBUTION DEDUCTION",
            "date": date_str,
            "balance": 718500
        })
    
    # Annual life insurance premium (paid in January)
    transactions.append({
        "type": "debit",
        "amount": 50000,
        "narration": "LIFE INSURANCE PREMIUM PAYMENT",
        "date": "2025-01-15",
        "balance": 700000
    })
    
    # Monthly rent payments
    for month in range(1, 13):
        transactions.append({
            "type": "debit",
            "amount": 150000,
            "narration": "RENT PAYMENT TO LANDLORD",
            "date": f"2025-{month:02d}-05",
            "balance": 550000
        })
    
    # Prepare request
    payload = {
        "user_id": "user_12345",
        "transactions": transactions,
        "taxpayer_profile": {
            "taxpayer_type": "individual",
            "employment_status": "employed",
            "location": "Lagos"
        },
        "tax_year": 2025,
        "tax_type": "PIT",
        "jurisdiction": "state"
    }
    
    print("=" * 80)
    print("EXAMPLE: Employed Individual Tax Optimization")
    print("=" * 80)
    print(f"\nSending {len(transactions)} transactions for analysis...")
    print(f"Annual gross income: ₦{500000 * 12:,.0f}")
    print(f"Current pension: ₦{24000 * 12:,.0f}/year")
    print(f"Current life insurance: ₦50,000/year")
    print(f"Annual rent paid: ₦{150000 * 12:,.0f}")
    
    # Send request
    try:
        response = requests.post(OPTIMIZE_ENDPOINT, json=payload, timeout=120)
        response.raise_for_status()
        
        result = response.json()
        
        # Display results
        print("\n" + "=" * 80)
        print("OPTIMIZATION RESULTS")
        print("=" * 80)
        
        print(f"\nTax Summary:")
        print(f"   Baseline Tax:           ₦{result['baseline_tax_liability']:,.2f}")
        print(f"   Optimized Tax:          ₦{result['optimized_tax_liability']:,.2f}")
        print(f"   Potential Savings:      ₦{result['total_potential_savings']:,.2f}")
        print(f"   Savings Percentage:     {result['savings_percentage']:.1f}%")
        
        print(f"\nIncome & Deductions:")
        print(f"   Total Annual Income:    ₦{result['total_annual_income']:,.2f}")
        print(f"   Current Deductions:")
        for key, value in result['current_deductions'].items():
            if key != 'total':
                print(f"      - {key.replace('_', ' ').title()}: ₦{value:,.2f}")
        print(f"      Total: ₦{result['current_deductions']['total']:,.2f}")
        
        print(f"\nRecommendations ({result['recommendation_count']}):")
        for i, rec in enumerate(result['recommendations'][:5], 1):
            print(f"\n   {i}. {rec['strategy_name']}")
            print(f"      Savings: ₦{rec['annual_tax_savings']:,.2f}")
            print(f"      Description: {rec['description']}")
            print(f"      Risk: {rec['risk_level'].upper()} | Complexity: {rec['complexity'].upper()}")
            if rec['implementation_steps']:
                print(f"      Next Steps:")
                for step in rec['implementation_steps'][:3]:
                    print(f"         • {step}")
        
        print(f"\nTransaction Analysis:")
        ts = result['transaction_summary']
        print(f"   Total Transactions:     {ts['total_transactions']}")
        print(f"   Categorized:            {ts['categorized']} ({ts.get('categorization_rate', 0)*100:.1f}%)")
        print(f"   High Confidence:        {ts['high_confidence']}")
        
        # Save full result to file
        with open("optimization_result_example.json", "w") as f:
            json.dump(result, f, indent=2)
        print(f"\n[SUCCESS] Full results saved to: optimization_result_example.json")
        
    except requests.exceptions.RequestException as e:
        print(f"\n[ERROR] {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Response: {e.response.text}")


def example_self_employed():
    """Example: Self-employed individual with business income"""
    
    transactions = []
    
    # Business income (irregular payments)
    business_payments = [
        ("2025-01-15", 800000, "CLIENT PAYMENT - PROJECT A"),
        ("2025-02-20", 1200000, "INVOICE PAYMENT - CLIENT B"),
        ("2025-03-10", 600000, "CONSULTING FEE - CLIENT C"),
        ("2025-04-25", 950000, "PROJECT PAYMENT - CLIENT D"),
        ("2025-06-15", 1100000, "SALES REVENUE - JUNE"),
        ("2025-08-30", 750000, "CLIENT PAYMENT - PROJECT E"),
        ("2025-10-12", 1300000, "INVOICE SETTLEMENT - CLIENT F"),
    ]
    
    for date_str, amount, narration in business_payments:
        transactions.append({
            "type": "credit",
            "amount": amount,
            "narration": narration,
            "date": date_str,
            "balance": amount
        })
    
    # Voluntary pension contributions
    for month in [1, 4, 7, 10]:
        transactions.append({
            "type": "debit",
            "amount": 100000,
            "narration": "VOLUNTARY PENSION CONTRIBUTION",
            "date": f"2025-{month:02d}-15",
            "balance": 500000
        })
    
    payload = {
        "user_id": "user_67890",
        "transactions": transactions,
        "taxpayer_profile": {
            "taxpayer_type": "individual",
            "employment_status": "self_employed",
            "location": "Abuja"
        },
        "tax_year": 2025,
        "tax_type": "PIT"
    }
    
    print("\n" + "=" * 80)
    print("EXAMPLE: Self-Employed Individual")
    print("=" * 80)
    
    try:
        response = requests.post(OPTIMIZE_ENDPOINT, json=payload, timeout=120)
        response.raise_for_status()
        result = response.json()
        
        print(f"\n[SUCCESS] Optimization completed!")
        print(f"   Baseline Tax: ₦{result['baseline_tax_liability']:,.2f}")
        print(f"   Potential Savings: ₦{result['total_potential_savings']:,.2f}")
        print(f"   Recommendations: {result['recommendation_count']}")
        
    except requests.exceptions.RequestException as e:
        print(f"\n[ERROR] {e}")


def example_minimal():
    """Minimal example with just a few transactions"""
    
    payload = {
        "user_id": "test_user",
        "transactions": [
            {
                "type": "credit",
                "amount": 400000,
                "narration": "MONTHLY SALARY",
                "date": "2025-01-31",
                "balance": 400000
            },
            {
                "type": "debit",
                "amount": 32000,
                "narration": "PENSION DEDUCTION",
                "date": "2025-01-31",
                "balance": 368000
            }
        ],
        "tax_year": 2025
    }
    
    print("\n" + "=" * 80)
    print("EXAMPLE: Minimal Transaction Set")
    print("=" * 80)
    
    try:
        response = requests.post(OPTIMIZE_ENDPOINT, json=payload, timeout=60)
        response.raise_for_status()
        result = response.json()
        
        print(f"\n[SUCCESS] Analysis completed!")
        print(f"   Income: ₦{result['total_annual_income']:,.2f}")
        print(f"   Tax: ₦{result['baseline_tax_liability']:,.2f}")
        print(f"   Savings Opportunity: ₦{result['total_potential_savings']:,.2f}")
        
    except requests.exceptions.RequestException as e:
        print(f"\n[ERROR] {e}")


if __name__ == "__main__":
    print("\nKaanta Tax Optimization API - Examples\n")
    print("Make sure the API is running: uvicorn orchestrator:app --reload --port 8000\n")
    
    # Run examples
    example_employed_individual()
    
    # Uncomment to run other examples:
    # example_self_employed()
    # example_minimal()
    
    print("\n" + "=" * 80)
    print("✅ Examples completed!")
    print("=" * 80)