File size: 3,910 Bytes
021e065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from backend.database.postgres.models import RequestLog, Conversation, ResponseLawLog, AuditLog
from core.state_machine import state_machine
from core.payment_gateway import payment_gateway
from core.sms_gateway import sms_gateway
from layers.layer_4_logic.invoicing_engine import invoicing_engine
from layers.layer_4_logic.inventory_manager import inventory_manager
from layers.layer_4_logic.dataset_builder import dataset_builder
from core.legal_intelligence import legal_intelligence
import uuid
import hashlib
from datetime import datetime

async def execute(query: str, user_hash: str, user_name: str, jurisdiction: str, language: str, db):
    """
    Refactored execute method for write layer.
    """
    return {"sms_sent": False, "invoice": None, "sms_confirmation": ""}

async def execute_actions(actions: list, context: dict, db):
    results = []
    for action in actions:
        if action['type'] == "record_sale":
            sale = action['data']
            inventory_manager.update_stock(
                sale['item'], sale['quantity'], 
                user_id=context['user_address']
            )
            invoice = invoicing_engine.generate_invoice(
                seller_name=f"{context['user_address']}'s Shop",
                items=sale['items'],
                total=sale['revenue'],
                user_id=context['user_address']
            )
            results.append({"type": "invoice", "data": invoice})
            
        elif action['type'] == "request_payment":
            data = action['data']
            res = await payment_gateway.request_payment(
                from_phone=data['phone'],
                amount=data['amount'],
                reference=str(uuid.uuid4())[:8],
                description="Payment Request",
                seller_name=context['user_address']
            )
            results.append({"type": "payment_request", "data": res})
            
        elif action['type'] == "send_receipt":
            data = action['data']
            # We would typically need the receipt text here
            # For now, placeholder
            res = sms_gateway.send_receipt(
                phone_number=data['phone'],
                receipt_text="Receipt from Senti"
            )
            results.append({"type": "sms", "data": res})
            
    return results

async def log_audit(query, domain_info, analysis, laws_applied, db, user_address, response_text, response_id):
    # Log to RequestLog
    req_log = RequestLog(
        api_key_id=0,
        endpoint="/process",
        country_code=domain_info.get('country_code', 'KE'),
        intent_detected=domain_info['primary_domain'],
        response_time_ms=0, # updated later
        status_code=200,
        timestamp=datetime.utcnow()
    )
    db.add(req_log)
    
    # Log to Conversation
    conv = Conversation(
        user_id=user_address,
        query=query,
        response=response_text,
        intent=domain_info['primary_domain'],
        country_code=domain_info.get('country_code', 'KE'),
        timestamp=datetime.utcnow()
    )
    db.add(conv)
    
    # Log to ResponseLawLog
    for rule in laws_applied:
        law_log = ResponseLawLog(
            id=str(uuid.uuid4()),
            response_id=response_id,
            rule_id=rule.rule_id,
            jurisdiction=rule.jurisdiction,
            domain=rule.domain,
            rule_version="1.0",
            source_url=rule.source_url,
            applied_at=datetime.utcnow(),
            disclaimer_applied=rule.requires_disclaimer,
            advice_restricted=rule.restricts_advice,
            calculation_used=domain_info['primary_domain'] in ["TAXATION", "LENDING"]
        )
        db.add(law_log)
    
    db.commit()

def record_consent(user_hash, language, db):
    from core.consent_engine import consent_engine
    return consent_engine.record_consent(user_hash, language, db)