File size: 8,933 Bytes
d491dc1 | 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 | /**
* HyperFlow 3.0 β API Service Layer
* Connects the React frontend to the FastAPI backend
* All endpoints proxied via Vite dev server β /api β http://localhost:8000
*/
const getBaseUrl = () => {
const override = localStorage.getItem('hyperflow_backend_url');
if (override) return override;
const envUrl = import.meta.env.VITE_BACKEND_URL;
if (envUrl) return envUrl;
if (typeof window !== 'undefined') {
const hn = window.location.hostname;
if (hn === 'localhost' || hn === '127.0.0.1') {
return 'http://127.0.0.1:8000';
}
}
return 'https://gaurav711-hyperflow.hf.space';
};
export function setBackendUrl(url) {
if (url) {
localStorage.setItem('hyperflow_backend_url', url.replace(/\/$/, ''));
} else {
localStorage.removeItem('hyperflow_backend_url');
}
}
export function getBackendUrl() {
return getBaseUrl();
}
async function apiFetch(path, options = {}) {
try {
const base = getBaseUrl();
const url = base ? `${base}${path}` : path;
const headers = { 'Content-Type': 'application/json', ...options.headers };
// Inject personal Swiggy token from localStorage if available
const personalToken = localStorage.getItem('swiggy_access_token');
if (personalToken) {
headers['Authorization'] = `Bearer ${personalToken}`;
}
const res = await fetch(url, {
headers,
...options,
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: res.statusText }));
throw new Error(err.detail || 'API error');
}
return res.json();
} catch (err) {
console.warn(`[API] ${path} failed (offline fallback):`, err.message);
return null; // caller uses null to fall back to local state
}
}
// βββ OAuth 2.1 + PKCE βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function fetchLoginUrl() {
return apiFetch('/api/v1/auth/login-url');
}
export async function exchangeCode(code, state) {
return apiFetch('/api/v1/auth/exchange', {
method: 'POST',
body: JSON.stringify({ code, state }),
});
}
// βββ Dark Store / Inventory βββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function fetchRestockAlerts(storeId = 'store_01') {
return apiFetch(`/api/v1/forecast/${storeId}/restock-alerts`);
}
export async function fetchForecast(storeId, skuId) {
return apiFetch(`/api/v1/forecast/${storeId}/${skuId}`);
}
export async function fetchAvailabilityMetrics(storeId = 'store_01') {
return apiFetch(`/api/v1/metrics/availability/${storeId}`);
}
export async function fetchProfitability(storeId) {
return apiFetch(`/api/v1/profitability/${storeId}`);
}
export async function fetchBumpRate() {
return apiFetch('/api/v1/metrics/bump-rate');
}
export async function fetchRobustness() {
return apiFetch('/api/v1/metrics/robustness');
}
export async function triggerRetrain() {
return apiFetch('/api/v1/ml/retrain', { method: 'POST' });
}
// βββ Inventory Reservation ββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function reserveInventory({ order_id, store_id, sku_id, qty_requested }) {
return apiFetch('/api/v1/orders/reserve', {
method: 'POST',
body: JSON.stringify({ order_id, store_id, sku_id, qty_requested }),
});
}
// βββ Restaurants & Coupons βββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function fetchRestaurants() {
return apiFetch('/api/v1/restaurants');
}
export async function fetchRestaurantMenu(restaurantId) {
return apiFetch(`/api/v1/restaurants/${restaurantId}/menu`);
}
export async function createRestaurant(data) {
return apiFetch('/api/v1/restaurants', {
method: 'POST',
body: JSON.stringify(data),
});
}
export async function fetchCoupons() {
return apiFetch('/api/v1/coupons');
}
export async function createCoupon(data) {
return apiFetch('/api/v1/coupons', {
method: 'POST',
body: JSON.stringify(data),
});
}
// βββ Dineout βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function fetchDineoutReservations() {
return apiFetch('/api/v1/dineout/reservations');
}
export async function reserveDineout({ hotel, time, party }) {
return apiFetch('/api/v1/dineout/reserve', {
method: 'POST',
body: JSON.stringify({ hotel, time, party }),
});
}
// βββ Expense Logs βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function fetchExpenseLogs() {
return apiFetch('/api/v1/user/expenses');
}
// βββ Festival Settings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export async function fetchFestivalSettings() {
return apiFetch('/api/v1/settings/festival');
}
export async function updateFestivalSettings(theme_name) {
return apiFetch(`/api/v1/settings/festival?theme_name=${theme_name}`, {
method: 'POST',
});
}
// βββ WebSocket Live Metrics βββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Opens a WebSocket connection to the live metrics stream.
* @param {function} onMessage - callback(data: object)
* @returns {WebSocket} - call .close() to disconnect
*/
export function connectLiveMetrics(onMessage) {
const base = getBaseUrl();
const wsBase = base
? base.replace(/^http/, 'ws')
: `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}`;
const ws = new WebSocket(`${wsBase}/ws/live-metrics`);
ws.onmessage = (e) => {
try {
onMessage(JSON.parse(e.data));
} catch {}
};
ws.onerror = (e) => console.warn('[WS] live-metrics error', e);
return ws;
}
// βββ Swiggy Food MCP Direct Tool Calls ββββββββββββββββββββββββββββββββββββββββ
export async function fetchFoodAddresses() {
return apiFetch('/api/v1/food/addresses');
}
export async function updateFoodCart({ addressId, items, couponCode }) {
return apiFetch('/api/v1/food/cart', {
method: 'POST',
body: JSON.stringify({ addressId, items, couponCode }),
});
}
export async function placeFoodOrder({ addressId, paymentMethod }) {
return apiFetch('/api/v1/food/orders', {
method: 'POST',
body: JSON.stringify({ addressId, paymentMethod }),
});
}
export async function trackFoodOrder(orderId) {
return apiFetch(`/api/v1/food/orders/${orderId}/track`);
}
// βββ HyperFlow 4.0 v2 Core Endpoints ββββββββββββββββββββββββββββββββββββββββββ
export async function fetchDemandOracle(addressId = 'default_address', lat = 20.3533, lng = 85.8333) {
return apiFetch(`/api/v2/oracle/demand?addressId=${addressId}&lat=${lat}&lng=${lng}`);
}
export async function predictRefund({ order_id, complaint_type, complaint_text, item_name, item_price }) {
return apiFetch('/api/v2/refund/predict', {
method: 'POST',
body: JSON.stringify({ order_id, complaint_type, complaint_text, item_name, item_price }),
});
}
export async function fetchDineoutSniper(latitude = 20.3533, longitude = 85.8333, cuisine = 'Buffet', date = '2026-07-25') {
return apiFetch(`/api/v2/dineout/sniper?latitude=${latitude}&longitude=${longitude}&cuisine=${cuisine}&date=${date}`);
}
export async function analyzeDispatch(store_location = [20.3533, 85.8333], orders_count = 5) {
return apiFetch('/api/v2/dispatch/analyze', {
method: 'POST',
body: JSON.stringify({ store_location, orders_count }),
});
}
export function connectETALive(orderId, onMessage) {
const base = getBaseUrl();
const wsBase = base
? base.replace(/^http/, 'ws')
: `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}`;
const token = localStorage.getItem('swiggy_access_token') || '';
const ws = new WebSocket(`${wsBase}/api/v2/ws/eta-live/${orderId}?token=${token}`);
ws.onmessage = (e) => {
try {
onMessage(JSON.parse(e.data));
} catch {}
};
ws.onerror = (e) => console.warn('[WS] eta-live error', e);
return ws;
}
|