Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
230 lines (203 loc) · 8.79 KB
/
Copy pathserver.ts
File metadata and controls
230 lines (203 loc) · 8.79 KB
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
import "dotenv/config";
import express from "express";
import { createServer as createViteServer } from "vite";
import { FPLService } from "./api/index";
const app = express();
const PORT = 3000;
async function startServer() {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
// Request Logging
app.use((req, res, next) => {
console.log(`[REQUEST] ${req.method} ${req.url}`);
next();
});
// Body parser for POST requests (support full multi-gameweek snapshot history)
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
// Local API Proxies to the Unified FPLService
// Vercel serverless function proxy for local dev
app.post("/api/create-checkout", async (req, res) => {
try {
const checkoutHandler = (await import("./api/create-checkout")).default;
await checkoutHandler(req, res);
} catch (error: any) {
console.error("Local Dev Checkout Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/user-profile", async (req, res) => {
try {
const handler = (await import("./api/user-profile")).default;
await handler(req, res);
} catch (error: any) {
console.error("Local Dev Profile Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/admin*", async (req, res) => {
try {
const adminHandler = (await import("./api/admin")).default;
await adminHandler(req as any, res as any);
} catch (error: any) {
console.error("Local Dev Admin Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/agent*", async (req, res) => {
try {
const handler = (await import("./api/index")).default;
await handler(req as any, res as any);
} catch (error: any) {
console.error("Local Dev Agent Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/snapshots*", async (req, res) => {
try {
const handler = (await import("./api/snapshots")).default;
await handler(req as any, res as any);
} catch (error: any) {
console.error("Local Dev Snapshots Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/decision-logs*", async (req, res) => {
try {
const handler = (await import("./api/decision-logs")).default;
await handler(req as any, res as any);
} catch (error: any) {
console.error("Local Dev Decision Logs Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.get("/api/user", async (req, res) => {
try {
const userId = req.query.userId as string;
// For local dev, hardcode your tier
const tier = userId === 'XpmBVLzU0ZOqmofB7RVXHN0HctI3' ? 'ai-agent' : 'free';
res.json({ tier });
} catch (error: any) {
console.error("Local Dev User Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/recommendations", async (req, res) => {
try {
const riskMode = ((req.query.riskMode || req.body?.riskMode) as string) || 'safe';
const budget = (req.query.budget || req.body?.budget) ? parseInt((req.query.budget || req.body?.budget) as string) : 1000;
const fuel = ((req.query.fuel || req.body?.fuel) as string) || 'fplform';
const userId = ((req.query.userId || req.body?.userId) as string) || 'unknown';
const tierParam = ((req.query.tier || req.body?.tier) as string) || 'ai-agent';
const tier = tierParam === 'ai-agent' ? 'ai-agent' : 'free';
const scenario = ((req.query.scenario === 'template' || req.body?.scenario === 'template') ? 'template' : 'quant') as 'quant' | 'template';
const lockedStr = (req.query.locked as string) || req.body?.locked || '';
const excludedStr = (req.query.excluded as string) || req.body?.excluded || '';
const lockedIds = Array.isArray(req.body?.lockedIds)
? req.body.lockedIds
: (lockedStr ? lockedStr.split(',').map((s: string) => parseInt(s.trim())).filter((n: number) => !isNaN(n)) : []);
const excludedIds = Array.isArray(req.body?.excludedIds)
? req.body.excludedIds
: (excludedStr ? excludedStr.split(',').map((s: string) => parseInt(s.trim())).filter((n: number) => !isNaN(n)) : []);
const skipComparison = req.query.skipComparison === 'true' || req.body?.skipComparison === true;
const targetGw = (req.query.gw || req.body?.gw) ? parseInt((req.query.gw || req.body?.gw) as string, 10) : undefined;
console.log(`[Local Dev] Recommendations: riskMode=${riskMode}, budget=${budget}, fuel=${fuel}, scenario=${scenario}, locked=${lockedIds.length}, excluded=${excludedIds.length}, tier=${tier}`);
const result = await FPLService.getRecommendations(
riskMode,
budget,
tier,
fuel,
scenario,
lockedIds,
excludedIds,
targetGw,
skipComparison
);
res.json(result);
} catch (error: any) {
console.error("Local Dev Recommendations Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/top-manager-insight", async (req, res) => {
try {
const rawGw = (req.query.gw || req.body?.gw) as string;
const targetGw = rawGw ? parseInt(rawGw, 10) : undefined;
let players: any[] = [];
let currentGw = 5;
try {
const baseData = await FPLService.getBaseData();
players = baseData.players || [];
currentGw = baseData.nextEventId || 5;
} catch (e: any) {
console.warn("[TopManagerInsight] BaseData fetch warning:", e.message);
}
const effectiveGw = (targetGw && !isNaN(targetGw)) ? targetGw : currentGw;
const { ManagerSnapshotService } = await import("./api/_lib/manager-snapshot-service");
let topManagerInsight;
try {
topManagerInsight = await ManagerSnapshotService.getDynamicTopManagerInsight(players, effectiveGw);
} catch (innerErr: any) {
console.warn(`[TopManagerInsight] Fallback disk loading for GW${effectiveGw}:`, innerErr.message);
topManagerInsight = await ManagerSnapshotService.getDynamicTopManagerInsight([], effectiveGw);
}
res.json({
success: true,
gameweek: effectiveGw,
topManagerInsight
});
} catch (error: any) {
console.error("Local Dev Top Manager Insight Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.all("/api/sync/:teamId", async (req, res) => {
try {
const { teamId } = req.params;
const riskMode = ((req.query.riskMode || req.body?.riskMode) as string) || 'safe';
const fuel = ((req.query.fuel || req.body?.fuel) as string) || 'fplform';
const tier = ((req.query.tier || req.body?.tier) as string) || 'free';
const targetGw = (req.query.gw || req.body?.gw) ? parseInt((req.query.gw || req.body?.gw) as string, 10) : undefined;
const scenario = ((req.query.scenario === 'template' || req.body?.scenario === 'template') ? 'template' : 'quant') as 'quant' | 'template';
console.log(`[Local Dev] Sync: teamId=${teamId}, riskMode=${riskMode}, fuel=${fuel}, scenario=${scenario}, tier=${tier}`);
const result = await FPLService.syncTeam(teamId, riskMode, tier, fuel, targetGw, scenario);
res.json(result);
} catch (error: any) {
console.error("Local Dev Sync Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.get("/api/live/:eventId", async (req, res) => {
try {
const { eventId } = req.params;
const axios = (await import('axios')).default;
const [liveRes, fixturesRes] = await Promise.all([
axios.get(`https://fantasy.premierleague.com/api/event/${eventId}/live/`, {
headers: { "User-Agent": "Mozilla/5.0" }
}),
axios.get(`https://fantasy.premierleague.com/api/fixtures/?event=${eventId}`, {
headers: { "User-Agent": "Mozilla/5.0" }
}).catch(() => ({ data: [] }))
]);
res.json({
elements: liveRes.data.elements,
fixtures: fixturesRes.data || []
});
} catch (error: any) {
console.error("Local Dev Live Error:", error.message);
res.status(500).json({ error: error.message });
}
});
app.get("/api/ping", (req, res) => {
res.json({ status: "ok", message: "Grand Cru Engine Online" });
});
// Serve data/ directory as static /data route (backtest results, CSV, etc.)
app.use('/data', express.static('data'));
app.use(vite.middlewares);
app.listen(PORT, "0.0.0.0", () => {
console.log(`[GRAND CRU] Development server running on http://localhost:${PORT}`);
});
}
startServer();