File size: 7,055 Bytes
b35b5a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { useState } from "react";
import { useAppStore, Observation, StepResult, Case } from "@/store";

const AVAILABLE_CASES: Case[] = [
  { case_id: "CASE-A-001", task_type: "task_a", instruction: "Extract invoice fields from document" },
  { case_id: "CASE-A-002", task_type: "task_a", instruction: "Extract invoice fields from document" },
  { case_id: "CASE-A-003", task_type: "task_a", instruction: "Extract invoice fields from document" },
  { case_id: "CASE-A-004", task_type: "task_a", instruction: "Extract invoice fields from document" },
  { case_id: "CASE-B-001", task_type: "task_b", instruction: "Verify three-way match (Invoice, PO, Receipt)" },
  { case_id: "CASE-B-002", task_type: "task_b", instruction: "Verify three-way match (Invoice, PO, Receipt)" },
  { case_id: "CASE-B-003", task_type: "task_b", instruction: "Verify three-way match (Invoice, PO, Receipt)" },
  { case_id: "CASE-B-004", task_type: "task_b", instruction: "Verify three-way match (Invoice, PO, Receipt)" },
  { case_id: "CASE-B-005", task_type: "task_b", instruction: "Verify three-way match (Invoice, PO, Receipt)" },
  { case_id: "CASE-C-001", task_type: "task_c", instruction: "Detect duplicate invoice and verify bank account" },
  { case_id: "CASE-C-002", task_type: "task_c", instruction: "Detect duplicate invoice and verify bank account" },
  { case_id: "CASE-C-003", task_type: "task_c", instruction: "Detect duplicate invoice and verify bank account" },
  { case_id: "CASE-C-004", task_type: "task_c", instruction: "Detect duplicate invoice and verify bank account" },
  { case_id: "CASE-D-001", task_type: "task_d", instruction: "Full fraud investigation with email, vendor, bank, callback" },
  { case_id: "CASE-D-002", task_type: "task_d", instruction: "Full fraud investigation with email, vendor, bank, callback" },
  { case_id: "CASE-D-003", task_type: "task_d", instruction: "Full fraud investigation with email, vendor, bank, callback" },
  { case_id: "CASE-D-004", task_type: "task_d", instruction: "Full fraud investigation with email, vendor, bank, callback" },
  { case_id: "CASE-D-005", task_type: "task_d", instruction: "Full fraud investigation with email, vendor, bank, callback" },
  { case_id: "CASE-D-006", task_type: "task_d", instruction: "Full fraud investigation with email, vendor, bank, callback" },
  { case_id: "CASE-E-001", task_type: "task_e", instruction: "Campaign-level coordinated fraud detection" },
  { case_id: "CASE-E-002", task_type: "task_e", instruction: "Campaign-level coordinated fraud detection" },
];

const DEFAULT_CASES: Case[] = AVAILABLE_CASES;

export function useLedgerApi() {
  const { 
    apiUrl, 
    currentCaseId, 
    observation, 
    stepHistory,
    isLoading, 
    isSubmitting, 
    error,
    setCurrentCaseId,
    setObservation,
    addStepResult,
    clearHistory,
    setIsLoading,
    setIsSubmitting,
    setError,
  } = useAppStore();

  const reset = async (caseId: string) => {
    setIsLoading(true);
    setError(null);
    clearHistory();
    
    try {
      const response = await fetch(`${apiUrl}/reset`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ case_id: caseId }),
      });
      
      if (!response.ok) throw new Error(`Reset failed: ${response.status}`);
      
      const data = await response.json();
      const obs = data.observation as Observation;
      const result: StepResult = {
        observation: obs,
        reward: data.reward || 0,
        done: data.done || false,
        truncated: data.truncated || false,
        terminated: data.terminated || false,
        info: data.info || {},
      };
      
      setCurrentCaseId(caseId);
      setObservation(obs);
      addStepResult(result);
      
      return result;
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Unknown error";
      setError(msg);
      throw err;
    } finally {
      setIsLoading(false);
    }
  };

  const step = async (action: { action_type: string; payload?: Record<string, any> }) => {
    if (!currentCaseId) throw new Error("No active case. Call reset() first.");
    
    setIsLoading(true);
    setError(null);
    
    try {
      const response = await fetch(`${apiUrl}/step`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(action),
      });
      
      if (!response.ok) {
        const text = await response.text();
        throw new Error(`Step failed: ${response.status} - ${text}`);
      }
      
      const data = await response.json();
      const obs = data.observation as Observation;
      const result: StepResult = {
        observation: obs,
        reward: data.reward || 0,
        done: data.done || false,
        truncated: data.truncated || false,
        terminated: data.terminated || false,
        info: data.info || {},
      };
      
      setObservation(obs);
      addStepResult(result);
      
      return result;
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Unknown error";
      setError(msg);
      throw err;
    } finally {
      setIsLoading(false);
    }
  };

  const submitDecision = async (decision: string, confidence: number, reasonCodes: string[], policyChecks: Record<string, string>, evidenceMap: Record<string, any>) => {
    setIsSubmitting(true);
    setError(null);
    
    try {
      const response = await fetch(`${apiUrl}/step`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action_type: "submit_decision",
          payload: {
            decision,
            confidence,
            reason_codes: reasonCodes,
            policy_checks: policyChecks,
            evidence_map: evidenceMap,
          },
        }),
      });
      
      if (!response.ok) throw new Error(`Submit failed: ${response.status}`);
      
      const data = await response.json();
      const obs = data.observation as Observation;
      const result: StepResult = {
        observation: obs,
        reward: data.reward || 0,
        done: data.done || true,
        truncated: data.truncated || false,
        terminated: data.terminated || true,
        info: data.info || {},
      };
      
      setObservation(obs);
      addStepResult(result);
      
      return result;
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Unknown error";
      setError(msg);
      throw err;
    } finally {
      setIsSubmitting(false);
    }
  };

  const fetchInstitutionalMemory = async () => {
    try {
      const response = await fetch(`${apiUrl}/institutional-memory`);
      if (!response.ok) return null;
      return await response.json();
    } catch {
      return null;
    }
  };

  return {
    reset,
    step,
    submitDecision,
    fetchInstitutionalMemory,
    currentCaseId,
    observation,
    stepHistory,
    isLoading,
    isSubmitting,
    error,
    availableCases: DEFAULT_CASES,
  };
}