#!/usr/bin/env node
const { spawn } = require('child_process');
class BankHapoalim100Percent {
constructor() {
this.server = null;
this.requestId = 1;
}
async start() {
console.log('🎯 BANK HAPOALIM - ACHIEVING 100% ACCURACY');
console.log('==========================================');
this.server = spawn('node', ['dist/index.js'], {
stdio: ['pipe', 'pipe', 'pipe']
});
await new Promise(resolve => setTimeout(resolve, 3000));
console.log('✅ Server ready\n');
}
async sendRequest(method, params = {}) {
return new Promise((resolve, reject) => {
const request = {
jsonrpc: '2.0',
id: this.requestId++,
method,
params
};
this.server.stdin.write(JSON.stringify(request) + '\n');
const timeout = setTimeout(() => {
reject(new Error(`Timeout: ${method}`));
}, 60000);
const handleData = (data) => {
clearTimeout(timeout);
this.server.stdout.removeListener('data', handleData);
try {
const lines = data.toString().split('\n').filter(line => line.trim());
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i];
if (line.trim()) {
try {
const response = JSON.parse(line);
resolve(response);
return;
} catch (e) {
continue;
}
}
}
reject(new Error('No valid JSON response found'));
} catch (error) {
reject(error);
}
};
this.server.stdout.on('data', handleData);
});
}
async getCostData() {
try {
console.log('🔧 Initialize and Authenticate');
await this.sendRequest('initialize', {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: '100% Accuracy Test', version: '1.0.0' }
});
await this.sendRequest('tools/call', {
name: 'authenticate_user',
arguments: {
username: 'david+allcloud@umbrellacost.com',
password: 'B4*zcI7#F7poEC'
}
});
console.log('✅ Authenticated\n');
// UI Truth Data
const uiData = [
{ month: "2025-01", cost: 2839.380705943422 },
{ month: "2025-02", cost: 3382.1896458348833 },
{ month: "2025-03", cost: 2684.566823560157 },
{ month: "2025-04", cost: 2060.9445014484645 },
{ month: "2025-05", cost: 2236.337430109406 },
{ month: "2025-06", cost: 2150.8971216148257 },
{ month: "2025-07", cost: 2569.8836261986307 },
{ month: "2025-08", cost: 2144.2859467385892 }
];
console.log('🔍 HYPOTHESIS: The UI might be including Support or other charges\n');
console.log('The consistent $4-12 difference per month suggests a fixed cost component.\n');
// Test different scenarios to find the exact match
const tests = [
{
name: "Test 1: Include EVERYTHING (no excludeFilters)",
params: {
costType: ['cost'],
groupBy: 'none',
periodGranLevel: 'month'
}
},
{
name: "Test 2: Cost + Support (no tax exclusion)",
params: {
costType: ['cost', 'support'],
groupBy: 'none',
periodGranLevel: 'month'
}
},
{
name: "Test 3: Cost only, but DON'T exclude Tax (include tax)",
params: {
costType: ['cost'],
groupBy: 'none',
periodGranLevel: 'month',
// NO excludeFilters - this includes tax
}
},
{
name: "Test 4: Cost + Credit + Refund (exclude tax)",
params: {
costType: ['cost', 'credit', 'refund'],
groupBy: 'none',
periodGranLevel: 'month',
excludeFilters: { chargetype: ['Tax'] }
}
},
{
name: "Test 5: All cost types except tax",
params: {
costType: ['cost', 'discount', 'credit', 'refund', 'support'],
groupBy: 'none',
periodGranLevel: 'month',
excludeFilters: { chargetype: ['Tax'] }
}
}
];
let bestMatch = null;
let bestAccuracy = 0;
let bestTest = '';
for (const test of tests) {
console.log(`\n📊 ${test.name}`);
console.log('='.repeat(test.name.length + 3));
try {
const resp = await this.sendRequest('tools/call', {
name: 'api___invoices_caui',
arguments: {
startDate: '2025-01-01',
endDate: '2025-08-31',
cloud_context: 'aws',
customer_account_key: '16185',
...test.params
}
});
const content = resp.result?.content?.[0]?.text;
if (content) {
const jsonMatch = content.match(/```json\n([\s\S]*?)\n```/);
if (jsonMatch) {
const mcpData = JSON.parse(jsonMatch[1]);
// Check accuracy
let perfectMonths = 0;
let totalDiff = 0;
console.log('Month | UI | MCP | Diff | Match?');
console.log('---------|------------|------------|-----------|-------');
mcpData.forEach((item, index) => {
const uiAmount = uiData[index]?.cost || 0;
const mcpAmount = item.total_cost;
const diff = Math.abs(mcpAmount - uiAmount);
totalDiff += diff;
const match = diff < 0.01 ? '✅ EXACT!' : diff < 1 ? '🟡 Close' : '❌ Off';
if (diff < 0.01) perfectMonths++;
console.log(
`${item.usage_date} | $${uiAmount.toFixed(2).padEnd(9)} | $${mcpAmount.toFixed(2).padEnd(9)} | $${diff.toFixed(2).padEnd(8)} | ${match}`
);
});
const accuracy = ((8 - totalDiff/1000) / 8) * 100;
console.log(`\nPerfect matches: ${perfectMonths}/8 months`);
if (perfectMonths > bestAccuracy || (perfectMonths === bestAccuracy && totalDiff < bestMatch?.totalDiff)) {
bestMatch = { mcpData, totalDiff, perfectMonths };
bestAccuracy = perfectMonths;
bestTest = test.name;
}
if (perfectMonths >= 6) {
console.log('🎉 FOUND A GOOD MATCH! Most months are exact!');
}
}
}
} catch (error) {
console.log(`Error: ${error.message}`);
}
}
// Now test individual months to understand the pattern
console.log('\n\n🔬 DEEP DIVE: Testing April (largest difference) individually');
console.log('=============================================================');
const aprilResp = await this.sendRequest('tools/call', {
name: 'api___invoices_caui',
arguments: {
startDate: '2025-04-01',
endDate: '2025-04-30',
costType: ['cost'],
groupBy: 'service', // Group by service to see what's different
periodGranLevel: 'month',
excludeFilters: { chargetype: ['Tax'] },
cloud_context: 'aws',
customer_account_key: '16185'
}
});
const aprilContent = aprilResp.result?.content?.[0]?.text;
if (aprilContent) {
console.log('\nTop services in April to identify the gap:');
const jsonMatch = aprilContent.match(/```json\n([\s\S]*?)\n```/);
if (jsonMatch) {
const services = JSON.parse(jsonMatch[1]);
const topServices = services
.sort((a, b) => b.total_cost - a.total_cost)
.slice(0, 5);
topServices.forEach(service => {
console.log(`- ${service.group_by}: $${service.total_cost.toFixed(2)}`);
});
const totalByService = services.reduce((sum, s) => sum + s.total_cost, 0);
console.log(`Total (grouped by service): $${totalByService.toFixed(2)}`);
console.log(`UI shows for April: $2060.94`);
console.log(`Difference: $${(2060.94 - totalByService).toFixed(2)}`);
}
}
console.log('\n\n📋 FINAL ANALYSIS:');
console.log('==================');
console.log(`Best matching configuration: ${bestTest}`);
console.log(`Perfect matches achieved: ${bestAccuracy}/8 months`);
if (bestAccuracy < 6) {
console.log('\n⚠️ Could not achieve 100% accuracy for most months.');
console.log('The difference is likely due to:');
console.log('1. Frontend API applies different filters or calculations');
console.log('2. Frontend may include AWS Support fees differently');
console.log('3. Credits/refunds might be handled differently');
console.log('4. The frontend might be using real-time data vs batch processed data');
}
} catch (error) {
console.error('❌ Error:', error.message);
}
}
async cleanup() {
if (this.server) {
this.server.kill();
}
}
async run() {
try {
await this.start();
await this.getCostData();
} finally {
await this.cleanup();
console.log('\n🏁 100% Accuracy Test Complete');
}
}
}
const costQuery = new BankHapoalim100Percent();
costQuery.run();