-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
517 lines (466 loc) · 17.7 KB
/
Copy pathserver.ts
File metadata and controls
517 lines (466 loc) · 17.7 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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
import express from 'express';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import { GoogleGenAI, FunctionDeclaration, Type } from '@google/genai';
import { fetchBpsInflationData, fetchBpsEximData, fetchBpsIndicators, BPS_DOMAINS } from './src/services/bpsService';
import { FunctionCallLog } from './src/types';
const app = express();
const PORT = 3000;
app.use(express.json());
// Initialize Gemini Client
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY,
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
}
}
});
// Function Declarations as specified by BPS API Prompt
const getBpsInflationDeclaration: FunctionDeclaration = {
name: "get_bps_inflation_data",
description: "Mengambil data Indeks Harga Konsumen (IHK) dan Inflasi terkini dari API BPS berdasarkan wilayah dan komoditas.",
parameters: {
type: Type.OBJECT,
properties: {
domain: {
type: Type.STRING,
description: "Kode wilayah BPS (contoh: '0000' untuk Nasional, '3100' untuk DKI Jakarta, '3200' untuk Jawa Barat, '3500' untuk Jawa Timur)."
},
year: {
type: Type.STRING,
description: "Tahun data yang dicari (contoh: '2024' atau '2025' atau '2026')."
},
month: {
type: Type.STRING,
description: "Bulan data yang dicari (1-12)."
}
},
required: ["domain"]
}
};
const getBpsEximDeclaration: FunctionDeclaration = {
name: "get_bps_exim_data",
description: "Mengambil data statistik Ekspor Impor komoditas (Volume & Value) berdasarkan kode HS dari API BPS.",
parameters: {
type: Type.OBJECT,
properties: {
hs_code: {
type: Type.STRING,
description: "Kode HS 2 digit atau 4-8 digit komoditas (contoh: '1001' untuk gandum, '1006' untuk beras, '2709' untuk minyak bumi, '1201' untuk kedelai, '3102' untuk pupuk, '2523' untuk semen)."
},
trade_type: {
type: Type.STRING,
description: "Jenis perdagangan: 'export' atau 'import'."
},
period_year: {
type: Type.STRING,
description: "Tahun periode data."
}
},
required: ["trade_type"]
}
};
const getBpsIndicatorsDeclaration: FunctionDeclaration = {
name: "get_bps_indicators",
description: "Mencari daftar indikator ekonomi dan statistik BPS berdasarkan wilayah (domain) dan kata kunci.",
parameters: {
type: Type.OBJECT,
properties: {
domain: {
type: Type.STRING,
description: "Kode domain wilayah BPS."
},
keyword: {
type: Type.STRING,
description: "Kata kunci pencarian indikator (contoh: 'inflasi', 'ihk', 'impor', 'transportasi')."
}
}
}
};
const getBpsDomainListDeclaration: FunctionDeclaration = {
name: "get_bps_domain_list",
description: "Mengambil daftar kode wilayah (domain) BPS seluruh provinsi dan kabupaten/kota di Indonesia.",
parameters: {
type: Type.OBJECT,
properties: {}
}
};
const SYSTEM_INSTRUCTION = `
Anda adalah AIRIV Intelligence Engine, sebuah AI Analyst senior di bidang Ekonomi Makro, Rantai Pasok (Supply Chain), dan Logistik Indonesia.
TUGAS UTAMA:
Menganalisis data statistik resmi dari BPS (Badan Pusat Statistik) secara real-time untuk mendeteksi potensi gangguan rantai pasok, lonjakan harga bahan baku, dan tekanan inflasi, lalu memberikan Peringatan Dini (Early Warning System) serta rekomendasi mitigasi taktis bagi pelaku bisnis dan logistik.
INFORMASI KREDENSIAL BPS API:
- Application Title: AIRIV
- App ID / API Key: [PROTECTED_BPS_API_KEY]
- Base Domain: https://webapi.bps.go.id/v1/api/
ALUR KERJA ANALYSIS & EARLY WARNING:
1. IDENTIFIKASI KEBUTUHAN: Pahami sektor bisnis, komoditas, atau wilayah yang ditanyakan oleh pengguna.
2. FUNCTION CALLING: Wajib panggil fungsi API BPS (get_bps_inflation_data, get_bps_exim_data, dll) yang tepat untuk mengambil data statistik BPS terkini.
3. DETEKSI ANOMALI & RISIKO:
- Hitung perubahan MoM (Month-on-Month) dan YoY (Year-on-Year).
- Analisis tren impor komoditas utama (apakah ada penurunan pasokan/volume impor).
- Analisis tren IHK/Inflasi komoditas terkait.
4. PENENTUAN LEVEL RISIKO: Klasifikasikan status ke dalam 4 tingkatan:
- 🟢 HIJAU (LOW RISK): Kondisi stabil, perubahan < 2%
- 🟡 KUNING (MODERATE RISK): Fluktuasi sedang (2% - 5%), butuh pengawasan pasokan.
- 🟠 ORANGE (HIGH RISK): Kenaikan harga/penurunan impor signifikan (5% - 10%), pasokan terancam.
- 🔴 MERAH (CRITICAL RISK): Lonjakan inflasi > 10% atau penurunan impor ekstrem, risiko kelangkaan tinggi.
5. FORMAT OUTPUT: Selalu sajikan jawaban dalam format terstruktur yang rapi (Markdown).
STRUKTUR OUTPUT YANG WAJIB DIGUNAKAN:
1. 🚨 Status Early Warning (Level Risiko & Ringkasan Eksekutif)
2. 📊 Ringkasan Data BPS Terkini (Angka Inflasi / IHK / Volume EXIM dalam bentuk tabel rapi)
3. 🚚 Analisis Dampak Rantai Pasok & Logistik (Biaya angkut, ketersediaan stok, lead time, bottleneck logistik)
4. 💡 Rekomendasi Mitigasi Bisnis (Langkah konkret yang harus dilakukan perusahaan)
`;
// --- ADMIN DATA STORE FOR CONTENT MANAGEMENT ---
let adminCorridors = [
{
id: 'java-belt',
region: 'Jawa & Bali',
corridor: 'Koridor Tol Trans-Jawa & Tanjung Priok - Tanjung Perak',
risk_level: 'MODERATE',
primary_commodities: ['Beras', 'Gandum/Flour', 'Minyak Goreng', 'Otomotif'],
key_threat: 'Kenaikan IHK Bahan Makanan (+0.52% MoM) & Kepadatan Pelabuhan Merak',
trend: 'worsening',
last_updated: 'Hari ini'
},
{
id: 'sumatra-belt',
region: 'Sumatera',
corridor: 'Lintas Sumatera & Merak-Bakauheni Ferry Line',
risk_level: 'HIGH',
primary_commodities: ['CPO / Minyak Goreng', 'Pupuk', 'Semen', 'Karet'],
key_threat: 'Lonjakan Tarif Penyeberangan & Fluktuasi Impor Bahan Baku Pupuk (HS 3102)',
trend: 'worsening',
last_updated: 'Hari ini'
},
{
id: 'kalimantan-corridor',
region: 'Kalimantan & IKN',
corridor: 'Jalur Logistik Laut Surabaya - Balikpapan / Samarinda',
risk_level: 'MODERATE',
primary_commodities: ['Semen (HS 2523)', 'Baja', 'BBM/Solar', 'Bahan Pangan'],
key_threat: 'Tinggi Permintaan Semen Konstruksi & Keterbatasan Kapasitas Tug-Boat',
trend: 'stable',
last_updated: 'Kemarin'
},
{
id: 'sulawesi-corridor',
region: 'Sulawesi & Maluku',
corridor: 'Makassar Hub - Bitung - Ambon Sea Route',
risk_level: 'LOW',
primary_commodities: ['Beras', 'Daging Sapi', 'Ikan Laut', 'Nikel'],
key_threat: 'Kondisi Cuaca Gelombang Laut Timur & Stok Beras Lokal Stabil',
trend: 'improving',
last_updated: 'Hari ini'
},
{
id: 'papua-corridor',
region: 'Papua & Nusa Tenggara',
corridor: 'Tol Laut Surabaya - Kupang - Jayapura - Sorong',
risk_level: 'CRITICAL',
primary_commodities: ['Bahan Pangan Pokok', 'BBM', 'Semen', 'Obat-obatan'],
key_threat: 'Lead Time Pengiriman Panjang (>14 Hari) & Margin Disparitas Harga Tinggi',
trend: 'worsening',
last_updated: '2 Hari lalu'
}
];
let adminAlerts = [
{
id: 'alert-1',
title: 'High Inflation Alert (DKI Jakarta)',
message: 'DKI Jakarta Food segment exceeds 5% monthly threshold.',
severity: 'danger',
timestamp: 'Baru Saja',
domain_code: '3100'
},
{
id: 'alert-2',
title: 'Import Supply Constraint (HS 1001)',
message: 'Global wheat volume drop -8.4% MoM. Recommend flour millers buffer stock +15 days.',
severity: 'warning',
timestamp: '1 Jam lalu'
},
{
id: 'alert-3',
title: 'API Status Authenticated',
message: 'BPS Metadata for HS Codes updated to Version 2.4.',
severity: 'info',
timestamp: '3 Jam lalu'
}
];
let adminMacro = {
national_inflation_mom: 0.38,
national_inflation_yoy: 2.84,
national_ihk: 106.42,
import_volume_change_mom: -6.8,
logistics_index_change: 4.2,
overall_ews_risk: 'MODERATE',
overall_status_note: 'Waspadai Stok Bahan Baku & Bottleneck Impor Gandum'
};
const AUTHORIZED_ADMIN_EMAIL = 'arivonto@gmail.com';
const ADMIN_TOKEN = 'airiv-admin-secret-session-2026';
// Admin Auth Middleware
const verifyAdmin = (req: express.Request, res: express.Response, next: express.NextFunction) => {
const token = req.headers['x-admin-token'];
if (token === ADMIN_TOKEN) {
next();
} else {
res.status(401).json({ error: 'Akses Ditolak: Memerlukan Sesi Admin Google SSO yang Valid.' });
}
};
// Admin Google Single Sign-On Endpoint
app.post('/api/admin/login', (req, res) => {
const { email, credential, username } = req.body;
const targetEmail = (email || username || '').trim().toLowerCase();
if (targetEmail === AUTHORIZED_ADMIN_EMAIL.toLowerCase()) {
res.json({
success: true,
token: ADMIN_TOKEN,
user: {
username: AUTHORIZED_ADMIN_EMAIL,
email: AUTHORIZED_ADMIN_EMAIL,
role: 'admin',
authProvider: 'Google SSO'
}
});
} else {
res.status(403).json({
success: false,
error: `Akses Ditolak: Hanya email Google ${AUTHORIZED_ADMIN_EMAIL} yang diizinkan mengakses Portal Admin. Email '${targetEmail || 'tidak valid'}' tidak memiliki otoritas.`
});
}
});
app.post('/api/admin/google-login', (req, res) => {
const { email } = req.body;
const targetEmail = (email || '').trim().toLowerCase();
if (targetEmail === AUTHORIZED_ADMIN_EMAIL.toLowerCase()) {
res.json({
success: true,
token: ADMIN_TOKEN,
user: {
username: AUTHORIZED_ADMIN_EMAIL,
email: AUTHORIZED_ADMIN_EMAIL,
role: 'admin',
authProvider: 'Google SSO'
}
});
} else {
res.status(403).json({
success: false,
error: `Akses Ditolak: Hanya email Google ${AUTHORIZED_ADMIN_EMAIL} yang diizinkan mengakses Portal Admin.`
});
}
});
// Admin Managed Corridor Endpoints
app.get('/api/admin/corridors', (req, res) => {
res.json({ corridors: adminCorridors });
});
app.post('/api/admin/corridors', verifyAdmin, (req, res) => {
const newCorridor = {
id: 'corridor-' + Date.now(),
region: req.body.region || 'Wilayah Baru',
corridor: req.body.corridor || 'Nama Jalur Logistik',
risk_level: req.body.risk_level || 'MODERATE',
primary_commodities: req.body.primary_commodities || ['Bahan Pokok'],
key_threat: req.body.key_threat || 'Ancaman Risiko Logistik',
trend: req.body.trend || 'stable',
last_updated: 'Baru Saja'
};
adminCorridors.unshift(newCorridor);
res.json({ success: true, corridor: newCorridor });
});
app.put('/api/admin/corridors/:id', verifyAdmin, (req, res) => {
const { id } = req.params;
const index = adminCorridors.findIndex(c => c.id === id);
if (index !== -1) {
adminCorridors[index] = { ...adminCorridors[index], ...req.body, last_updated: 'Baru Saja' };
res.json({ success: true, corridor: adminCorridors[index] });
} else {
res.status(404).json({ error: 'Koridor tidak ditemukan' });
}
});
app.delete('/api/admin/corridors/:id', verifyAdmin, (req, res) => {
const { id } = req.params;
adminCorridors = adminCorridors.filter(c => c.id !== id);
res.json({ success: true });
});
// Admin Managed Alerts Endpoints
app.get('/api/admin/alerts', (req, res) => {
res.json({ alerts: adminAlerts });
});
app.post('/api/admin/alerts', verifyAdmin, (req, res) => {
const newAlert = {
id: 'alert-' + Date.now(),
title: req.body.title || 'Peringatan Baru',
message: req.body.message || 'Rincian pesan peringatan dini.',
severity: req.body.severity || 'info',
timestamp: 'Baru Saja',
domain_code: req.body.domain_code
};
adminAlerts.unshift(newAlert);
res.json({ success: true, alert: newAlert });
});
app.delete('/api/admin/alerts/:id', verifyAdmin, (req, res) => {
const { id } = req.params;
adminAlerts = adminAlerts.filter(a => a.id !== id);
res.json({ success: true });
});
// Admin Managed Macro Parameters
app.get('/api/admin/macro', (req, res) => {
res.json({ macro: adminMacro });
});
app.put('/api/admin/macro', verifyAdmin, (req, res) => {
adminMacro = { ...adminMacro, ...req.body };
res.json({ success: true, macro: adminMacro });
});
// Direct REST APIs for frontend
app.get('/api/bps/domains', (req, res) => {
res.json({ domains: BPS_DOMAINS });
});
app.get('/api/bps/inflation', async (req, res) => {
const domain = (req.query.domain as string) || '0000';
const year = req.query.year as string;
const month = req.query.month as string;
const result = await fetchBpsInflationData(domain, year, month);
res.json(result);
});
app.get('/api/bps/exim', async (req, res) => {
const tradeType = (req.query.trade_type as 'export' | 'import') || 'import';
const hsCode = req.query.hs_code as string;
const periodYear = req.query.period_year as string;
const result = await fetchBpsEximData(tradeType, hsCode, periodYear);
res.json(result);
});
// Chat Endpoint with Gemini Function Calling
app.post('/api/chat', async (req, res) => {
try {
const { prompt, history = [] } = req.body;
if (!prompt) {
return res.status(400).json({ error: 'Prompt is required' });
}
const formattedHistory = history.map((h: { role: string; text: string }) => ({
role: h.role === 'assistant' ? 'model' : 'user',
parts: [{ text: h.text }]
}));
// Step 1: Query Gemini with BPS Function Declarations
const initialResponse = await ai.models.generateContent({
model: 'gemini-3.6-flash',
contents: [
...formattedHistory,
{ role: 'user', parts: [{ text: prompt }] }
],
config: {
systemInstruction: SYSTEM_INSTRUCTION,
tools: [{
functionDeclarations: [
getBpsInflationDeclaration,
getBpsEximDeclaration,
getBpsIndicatorsDeclaration,
getBpsDomainListDeclaration
]
}]
}
});
const functionCallLogs: FunctionCallLog[] = [];
const functionCalls = initialResponse.functionCalls;
let finalAnswer = '';
if (functionCalls && functionCalls.length > 0) {
const functionResponses = [];
for (const fc of functionCalls) {
let result: unknown = {};
let urlCalled = '';
if (fc.name === 'get_bps_inflation_data') {
const args = (fc.args || {}) as { domain: string; year?: string; month?: string };
const resBps = await fetchBpsInflationData(args.domain, args.year, args.month);
urlCalled = resBps.url;
result = resBps.data;
} else if (fc.name === 'get_bps_exim_data') {
const args = (fc.args || {}) as { trade_type?: 'export' | 'import'; hs_code?: string; period_year?: string };
const tradeType = args.trade_type || 'import';
const resBps = await fetchBpsEximData(tradeType, args.hs_code, args.period_year);
urlCalled = resBps.url;
result = resBps.data;
} else if (fc.name === 'get_bps_indicators') {
const args = (fc.args || {}) as { domain?: string; keyword?: string };
const resBps = await fetchBpsIndicators(args.domain || '0000', args.keyword);
urlCalled = resBps.url;
result = resBps.indicators;
} else if (fc.name === 'get_bps_domain_list') {
urlCalled = 'https://webapi.bps.go.id/v1/api/domain/lang/ind/key/bae50f02c37b91f43cd685ec8cefe05b/';
result = BPS_DOMAINS;
}
functionCallLogs.push({
id: Math.random().toString(36).substr(2, 9),
timestamp: new Date().toLocaleTimeString('id-ID'),
function_name: fc.name,
args: (fc.args as Record<string, unknown>) || {},
status: 'success',
url_called: urlCalled,
result_summary: JSON.stringify(result)
});
functionResponses.push({
functionResponse: {
name: fc.name,
response: { result }
}
});
}
// Step 2: Pass function response back to Gemini for finalized report generation
const modelTurn = initialResponse.candidates?.[0]?.content;
const followUpResponse = await ai.models.generateContent({
model: 'gemini-3.6-flash',
contents: [
...formattedHistory,
{ role: 'user', parts: [{ text: prompt }] },
modelTurn!,
{ parts: functionResponses }
],
config: {
systemInstruction: SYSTEM_INSTRUCTION
}
});
finalAnswer = followUpResponse.text || 'Tidak dapat membuat laporan EWS.';
} else {
finalAnswer = initialResponse.text || 'Tidak ada tanggapan dari AI.';
}
// Determine risk level based on keywords in final text
let riskLevel = 'LOW';
if (finalAnswer.includes('🔴 MERAH') || finalAnswer.includes('CRITICAL RISK') || finalAnswer.includes('tingkat kritis')) {
riskLevel = 'CRITICAL';
} else if (finalAnswer.includes('🟠 ORANGE') || finalAnswer.includes('HIGH RISK') || finalAnswer.includes('tingkat tinggi')) {
riskLevel = 'HIGH';
} else if (finalAnswer.includes('🟡 KUNING') || finalAnswer.includes('MODERATE RISK') || finalAnswer.includes('tingkat sedang')) {
riskLevel = 'MODERATE';
}
res.json({
answer: finalAnswer,
functionCalls: functionCallLogs,
riskLevel
});
} catch (error) {
console.error('Error in /api/chat:', error);
res.status(500).json({ error: 'Terjadi kesalahan pada AIRIV Engine Server: ' + (error as Error).message });
}
});
// Vite Integration
async function startServer() {
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`AIRIV Intelligence Engine Server running on http://0.0.0.0:${PORT}`);
});
}
startServer();