File size: 5,894 Bytes
021e065
 
 
 
 
 
 
 
5c7593f
 
 
021e065
 
 
 
 
5c7593f
 
021e065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
713eeda
af72f78
 
 
 
 
 
5c7593f
 
 
5338d4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
713eeda
 
021e065
 
5c7593f
021e065
 
 
 
 
5c7593f
 
021e065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c7593f
 
 
021e065
 
5c7593f
 
 
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
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
// Typed API client — all calls go through here

const BASE = import.meta.env.VITE_API_BASE

async function request(method, path, body = null) {
  // Use dynamic import or grab from window if needed, 
  // but we can also just import the store:
  const { useAuthStore } = await import('../store/authStore.js')
  const authState = useAuthStore.getState()
  const token = authState.token
  const role = authState.user?.role
  
  const res = await fetch(`${BASE}${path}`, {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` }),
      ...(role && { 'x-role': role })
    },
    body: body ? JSON.stringify(body) : null
  })
  
  if (!res.ok) {
    if (res.status === 401 && !path.includes('/auth/login')) {
      useAuthStore.getState().clearAuth()
      window.location.href = '/login'
      return
    }
    const errorData = await res.json().catch(() => ({}))
    throw new Error(errorData.detail || 'Request failed')
  }
  
  return res.json()
}

export const api = {
  // Auth
  login: (phone, pin) =>
    request('POST', '/auth/login', { phone, pin }),

  forgotPin: (phone) =>
    request('POST', '/auth/forgot-pin', { phone }),

  resetPin: (phone, otp, new_pin) =>
    request('POST', '/auth/reset-pin', { phone, otp, new_pin }),

  updateUserType: (user_type) =>
    request('PATCH', '/auth/user-type', { user_type }),

  uploadDocument: async (file) => {
    const { useAuthStore } = await import('../store/authStore.js')
    const token = useAuthStore.getState().token
    
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await fetch(`${BASE}/documents/ocr`, {
      method: 'POST',
      headers: {
        ...(token && { 'Authorization': `Bearer ${token}` })
      },
      body: formData
    })
    
    if (!res.ok) {
      const errorData = await res.json().catch(() => ({}))
      throw new Error(errorData.detail || 'Upload failed')
    }
    
    return res.json()
  },

  register: (name, phone, pin, user_type = 'personal', consent = false) =>
    request('POST', '/auth/register', { name, phone, pin, user_type, consent_data_storage: consent }),
  
  // Chat
  process: async (query, address, flavor, country, conversationId = null) => {
    const response = await request('POST', '/process', {
      user_query: query,
      user_address: address,
      user_name: 'User',
      flavor: flavor.toUpperCase(),
      country_code: country,
      conversation_id: conversationId
    })
    
    if (response && response.status === 'queued') {
      const taskId = response.task_id
      return new Promise((resolve, reject) => {
        let wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        let wsHost = window.location.host
        let wsUrl
        
        if (BASE && BASE.startsWith('http')) {
          const url = new URL(BASE)
          wsProto = url.protocol === 'https:' ? 'wss:' : 'ws:'
          wsHost = url.host
          wsUrl = `${wsProto}//${wsHost}${url.pathname}/ws/tasks/${taskId}`
        } else {
          const pathPrefix = BASE || '/api'
          wsUrl = `${wsProto}//${wsHost}${pathPrefix}/ws/tasks/${taskId}`
        }
        
        let completed = false
        const socket = new WebSocket(wsUrl)
        
        socket.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data)
            if (data.status === 'completed') {
              completed = true
              socket.close()
              resolve(data.result)
            } else if (data.status === 'failed') {
              completed = true
              socket.close()
              reject(new Error(data.error || 'Deep reasoning task failed'))
            }
          } catch (err) {
            completed = true
            socket.close()
            reject(err)
          }
        }
        
        socket.onerror = (error) => {
          if (!completed) {
            completed = true
            reject(error)
          }
        }
        
        socket.onclose = () => {
          if (!completed) {
            reject(new Error('WebSocket connection closed prematurely'))
          }
        }
      })
    }
    
    return response
  },
  
  listChats: () =>
    request('GET', '/chats'),
  
  getChatMessages: (id) =>
    request('GET', `/chats/${id}/messages`),
  
  pinChat: (id) =>
    request('PATCH', `/chats/${id}/pin`),
    
  deleteChat: (id) =>
    request('DELETE', `/chats/${id}`),
  
  // Projects
  listProjects: () =>
    request('GET', '/projects'),
  
  createProject: (data) =>
    request('POST', '/projects', data),
  
  // Memory
  recallMemory: () =>
    request('GET', '/memory/recall'),
    
  listFacts: () =>
    request('GET', '/memory/facts'),
    
  saveFact: (category, key, value) =>
    request('POST', '/memory/facts', { category, key, value }),
    
  deleteFact: (category, key) =>
    request('DELETE', `/memory/facts?category=${encodeURIComponent(category)}&key=${encodeURIComponent(key)}`),
  
  // Files
  listFiles: () =>
    request('GET', '/files'),
    
  getFileToken: (filename) =>
    request('GET', `/files/token/${encodeURIComponent(filename)}`),
    
  // Goals
  listGoals: () =>
    request('GET', '/goals'),
  
  createGoal: (data) =>
    request('POST', '/goals', data),
  
  deleteGoal: (id) =>
    request('DELETE', `/goals/${id}`),
    
  // Institutional
  institutional: {
    getPortfolioRisk: () => request('GET', '/institutional/v1/risk/portfolio'),
    getTrades: () => request('GET', '/institutional/v1/trades'),
    getLogs: () => request('GET', '/institutional/v1/logs'),
    getApprovals: () => request('GET', '/institutional/v1/approvals'),
    getManifest: (orgId) => request('GET', `/institutional/v1/manifest?org_id=${orgId}`),
    getEntityContext: (entityId) => request('GET', `/institutional/v1/context/${entityId}`)
  }
}