import { z } from 'zod';
import { CompanyDatabase } from '../database/db.js';
import { readFileSync } from 'fs';
const ImportFinancialsSchema = z.object({
org_nr: z.string().describe("Organisasjonsnummer"),
year: z.number().describe("Regnskapsår"),
revenue: z.number().optional().describe("Omsetning (NOK)"),
profit: z.number().optional().describe("Resultat/overskudd (NOK)"),
assets: z.number().optional().describe("Sum eiendeler (NOK)"),
equity: z.number().optional().describe("Sum egenkapital (NOK)"),
employees: z.number().optional().describe("Antall ansatte"),
source: z.string().default('manual').describe("Datakilde (manual, proff, etc)")
});
const ImportFinancialsFromFileSchema = z.object({
file_path: z.string().describe("Sti til fil med regnskapsdata (CSV eller JSON)"),
format: z.enum(['csv', 'json']).describe("Filformat")
});
/**
* Import financial data manually
* Allows users to input financial data they've obtained from Proff.no, Brønnøysund, etc.
*/
export async function importFinancials(args: unknown, db: CompanyDatabase) {
const params = ImportFinancialsSchema.parse(args);
// Verify company exists
const company = await db.getCompany(params.org_nr);
if (!company) {
return {
content: [{
type: "text" as const,
text: `⚠️ Fant ikke selskap med org.nr ${params.org_nr} i databasen.\n\nSøk etter selskapet først med 'search_companies'.`
}]
};
}
// Insert financial snapshot
await db.insertFinancialSnapshot({
org_nr: params.org_nr,
year: params.year,
revenue: params.revenue || null,
profit: params.profit || null,
assets: params.assets || null,
equity: params.equity || null,
employees: params.employees || params.employees === 0 ? params.employees : company.employees_count,
source: params.source
});
const report = `
✅ REGNSKAPSDATA IMPORTERT: ${company.name}
📅 Regnskapsår: ${params.year}
📋 Org.nr: ${params.org_nr}
🔖 Kilde: ${params.source}
📊 IMPORTERTE TALL:
${params.revenue ? `💰 Omsetning: ${(params.revenue / 1000000).toFixed(1)}M NOK` : ''}
${params.profit ? `📈 Resultat: ${(params.profit / 1000000).toFixed(1)}M NOK` : ''}
${params.assets ? `🏢 Eiendeler: ${(params.assets / 1000000).toFixed(1)}M NOK` : ''}
${params.equity ? `💎 Egenkapital: ${(params.equity / 1000000).toFixed(1)}M NOK` : ''}
${params.employees ? `👥 Ansatte: ${params.employees}` : ''}
💡 NESTE STEG:
- Bruk 'analyze_financials' for å se risikoanalyse med disse dataene
- Importer flere år for trendanalyse
- Sammenlign med SSB bransjesnitt
ℹ️ Data lagret i lokal database og vil være tilgjengelig for alle analyser.
`;
return {
content: [{
type: "text" as const,
text: report
}]
};
}
/**
* Import financial data from CSV or JSON file
* Format: org_nr, year, revenue, profit, assets, equity, employees
*/
export async function importFinancialsFromFile(args: unknown, db: CompanyDatabase) {
const params = ImportFinancialsFromFileSchema.parse(args);
try {
const fileContent = readFileSync(params.file_path, 'utf-8');
let imported = 0;
let errors = 0;
if (params.format === 'csv') {
// Parse CSV
const lines = fileContent.split('\n');
const headers = lines[0].toLowerCase().split(',').map(h => h.trim());
for (let i = 1; i < lines.length; i++) {
if (!lines[i].trim()) continue;
const values = lines[i].split(',');
const row: any = {};
headers.forEach((header, idx) => {
row[header] = values[idx]?.trim();
});
try {
await db.insertFinancialSnapshot({
org_nr: row.org_nr || row.organisasjonsnummer,
year: parseInt(row.year || row.år),
revenue: row.revenue || row.omsetning ? parseFloat(row.revenue || row.omsetning) : null,
profit: row.profit || row.resultat ? parseFloat(row.profit || row.resultat) : null,
assets: row.assets || row.eiendeler ? parseFloat(row.assets || row.eiendeler) : null,
equity: row.equity || row.egenkapital ? parseFloat(row.equity || row.egenkapital) : null,
employees: row.employees || row.ansatte ? parseInt(row.employees || row.ansatte) : null,
source: 'file_import'
});
imported++;
} catch (error) {
console.error('Error importing row:', error);
errors++;
}
}
} else if (params.format === 'json') {
// Parse JSON
const data = JSON.parse(fileContent);
const records = Array.isArray(data) ? data : [data];
for (const record of records) {
try {
await db.insertFinancialSnapshot({
org_nr: record.org_nr || record.organisasjonsnummer,
year: record.year || record.år,
revenue: record.revenue || record.omsetning,
profit: record.profit || record.resultat,
assets: record.assets || record.eiendeler,
equity: record.equity || record.egenkapital,
employees: record.employees || record.ansatte,
source: 'file_import'
});
imported++;
} catch (error) {
console.error('Error importing record:', error);
errors++;
}
}
}
return {
content: [{
type: "text" as const,
text: `
✅ FILIMPORT FULLFØRT
📁 Fil: ${params.file_path}
📋 Format: ${params.format.toUpperCase()}
📊 RESULTATER:
✅ Importert: ${imported} regnskapsposter
${errors > 0 ? `⚠️ Feil: ${errors} poster` : ''}
💡 Importerte data er nå tilgjengelig i alle analyser.
Bruk 'analyze_financials' for å se risikoanalyse med reelle tall.
`
}]
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [{
type: "text" as const,
text: `❌ Feil ved import: ${errorMessage}\n\nSjekk at filen eksisterer og har riktig format.`
}],
isError: true
};
}
}