Business logic modules for domain-specific functionality
- Dokumentacja (INDEX)
- README
- Architektura
- API
- DSL
- System punkt贸w
- Compliance
- Roadmap
- Views Roadmap
- Mapa plik贸w projektu
ANALYTICA uses a modular architecture where each module provides:
- DSL Atoms - Operations callable from DSL pipelines
- API Routes - REST endpoints for direct access
- Calculators - Business logic utilities
| Module | Description | DSL Prefix |
|---|---|---|
| Budget | Budget management, variance analysis | budget.* |
| Investment | ROI, NPV, IRR calculations | investment.* |
| Forecast | Time series forecasting | forecast.* |
| Reports | Report generation | report.* |
| Alerts | Threshold monitoring | alert.* |
| Voice | Speech-to-text, NL鈫扗SL | voice.* |
| Deploy | Deployment & CI/CD | deploy.* |
Location: src/modules/budget/
- Budget creation and management
- Variance analysis (planned vs actual)
- Expense categorization
- Multi-scenario budgeting (optimistic/realistic/pessimistic)
Create a new budget.
budget.create(name="Q1 2025", scenario="realistic")Parameters:
name(str) - Budget nameperiod_start(str) - Start date (YYYY-MM-DD)period_end(str) - End date (YYYY-MM-DD)scenario(str) - One of: optimistic, realistic, pessimisticlines(list) - Budget line items
Calculate budget variance.
budget.variance(planned=100000, actual=95000)Parameters:
budget_id(str) - Existing budget ID, orplanned(float) - Planned amountactual(float) - Actual amount
Returns:
{
"planned": 100000,
"actual": 95000,
"variance": -5000,
"variance_percent": -5.0,
"status": "under"
}Categorize expenses automatically.
data.from_input() | budget.categorize()from src.modules.budget import BudgetCalculator, Budget, BudgetLine
from decimal import Decimal
# Calculate variance
result = BudgetCalculator.calculate_variance(
planned=Decimal("100000"),
actual=Decimal("95000")
)
# Create budget
budget = Budget(
id="budget_001",
name="Q1 2025",
period_start=date(2025, 1, 1),
period_end=date(2025, 3, 31),
)
budget.add_line(BudgetLine(
category="marketing",
name="Digital Ads",
planned=Decimal("50000"),
actual=Decimal("48000"),
))Location: src/modules/investment/
- ROI (Return on Investment) calculation
- NPV (Net Present Value) analysis
- IRR (Internal Rate of Return)
- Payback period calculation
- Risk assessment
Full investment analysis.
investment.analyze(
name="New Project",
initial_investment=100000,
discount_rate=0.12,
cash_flows=[30000, 40000, 50000, 60000]
)Returns:
{
"investment_id": "inv_abc12345",
"name": "New Project",
"roi": 80.0,
"npv": 15234.56,
"irr": 22.5,
"payback_period": 2.67,
"profitability_index": 1.15,
"risk_level": "low",
"recommendation": "proceed"
}Calculate ROI only.
investment.roi(initial_investment=100000, total_returns=180000)Calculate NPV.
investment.npv(
initial_investment=100000,
discount_rate=0.1,
cash_flows=[30000, 40000, 50000]
)Calculate Internal Rate of Return.
investment.irr(
initial_investment=100000,
cash_flows=[30000, 40000, 50000, 60000]
)Calculate payback period.
investment.payback(
initial_investment=100000,
cash_flows=[30000, 40000, 50000]
)from src.modules.investment import InvestmentCalculator
from decimal import Decimal
# Full analysis
result = InvestmentCalculator.calculate_npv(
initial_investment=Decimal("100000"),
cash_flows=[Decimal("30000"), Decimal("40000"), Decimal("50000")],
discount_rate=Decimal("0.12")
)
# IRR calculation
irr = InvestmentCalculator.calculate_irr(
initial_investment=Decimal("100000"),
cash_flows=[Decimal("30000"), Decimal("40000"), Decimal("50000"), Decimal("60000")]
)Location: src/modules/forecast/
- Moving average
- Exponential smoothing
- Linear trend analysis
- Multi-period forecasting
- Trend detection
Generate forecast predictions.
forecast.predict(data=[100, 110, 120, 130], periods=3, method="linear")Parameters:
data(list) - Historical data pointsperiods(int) - Number of periods to forecastmethod(str) - One of: linear, moving_average, exponential
Returns:
{
"method": "linear",
"historical_count": 4,
"predictions": [
{"period": 5, "value": 140.0, "lower_bound": 130.0, "upper_bound": 150.0},
{"period": 6, "value": 150.0, "lower_bound": 138.0, "upper_bound": 162.0},
{"period": 7, "value": 160.0, "lower_bound": 146.0, "upper_bound": 174.0}
],
"trend": "up"
}Analyze trend in data.
forecast.trend(data=[100, 110, 120, 130])Returns:
{
"trend": "up",
"slope": 10.0,
"intercept": 90.0,
"data_points": 4
}Apply smoothing to data.
forecast.smooth(data=[100, 120, 110, 130], method="exponential", alpha=0.3)from src.modules.forecast import ForecastCalculator, ForecastMethod
# Predict next 3 periods
predictions = ForecastCalculator.forecast_next(
data=[100.0, 110.0, 120.0, 130.0],
periods=3,
method=ForecastMethod.LINEAR
)
# Detect trend
trend = ForecastCalculator.detect_trend([100.0, 110.0, 120.0, 130.0])
# Returns: TrendDirection.UPLocation: src/modules/reports/
- Multiple output formats (PDF, Excel, HTML, JSON, CSV)
- Template-based reports
- Scheduled report generation
- Email/webhook distribution
Generate a report.
report.generate(template="executive_summary", format="html", title="Q1 Report")Parameters:
template(str) - Template IDformat(str) - Output format: html, json, csv, pdf, exceltitle(str) - Report titledata(dict) - Report data
Built-in Templates:
executive_summary- High-level overviewfinancial_report- Detailed financialsbudget_variance- Budget vs actual
Schedule recurring report.
report.schedule(template="executive_summary", frequency="weekly", recipients=["team@company.pl"])Frequencies: once, daily, weekly, monthly, quarterly
Send report to recipients.
report.send(report_id="report_123", recipients=["ceo@company.pl"], method="email")from src.modules.reports import ReportGenerator
# Generate HTML report
html = ReportGenerator.generate_html(
title="Q1 Summary",
data={
"summary": {"revenue": 1000000, "costs": 800000},
"key_metrics": {"growth": "15%", "margin": "20%"}
},
sections=["summary", "key_metrics"]
)Location: src/modules/alerts/
- Threshold-based alerts
- Anomaly detection
- Multi-channel notifications (email, webhook, Slack)
- Alert history
Check value against threshold.
alert.threshold(metric="expenses", value=150000, operator="gt", threshold=100000)Operators: gt, gte, lt, lte, eq, neq
Returns:
{
"metric": "expenses",
"value": 150000,
"threshold": 100000,
"triggered": true,
"message": "expenses (150000) exceeded threshold (100000)",
"alert_id": "alert_abc123"
}Create an alert rule.
alert.create(
name="Budget Alert",
metric="spending",
operator="gt",
threshold=50000,
severity="warning",
channels=["email"]
)Send alert notification.
alert.send(channel="email", recipient="admin@company.pl", message="Alert!")Detect anomaly in data.
alert.anomaly(values=[100, 102, 98, 101, 99], current=150)Returns:
{
"is_anomaly": true,
"current_value": 150,
"mean": 100.0,
"std": 1.58,
"lower_bound": 96.84,
"upper_bound": 103.16,
"deviation": 31.65
}from src.modules.alerts import AlertEngine, AlertRule, ComparisonOperator
# Check threshold
result = AlertEngine.check_threshold(
metric="budget",
value=150000,
operator="gt",
threshold=100000
)
# Detect anomaly
anomaly = AlertEngine.detect_anomaly(
values=[100.0, 102.0, 98.0, 101.0],
current=150.0,
std_multiplier=2.0
)Location: src/modules/voice/
- Speech-to-text transcription
- Voice command parsing
- Natural language to DSL conversion
- Support for Polish and English
Transcribe audio to text.
voice.transcribe(audio_url="https://...", language="pl")Parse voice text into structured command.
voice.parse(text="oblicz sum臋 sprzeda偶y")Returns:
{
"raw_text": "oblicz sum臋 sprzeda偶y",
"intent": "calculate",
"entities": {"matched_groups": ["oblicz", "sum臋", "sprzeda偶y"]},
"dsl": "metrics.sum(\"sprzeda偶y\")",
"confidence": 0.85
}Convert voice text directly to DSL.
voice.to_dsl(text="wygeneruj raport miesi臋czny")Returns:
{
"input": "wygeneruj raport miesi臋czny",
"dsl": "report.generate(\"miesi臋czny\")",
"intent": "report",
"confidence": 0.85,
"can_execute": true
}| Command Pattern | Generated DSL |
|---|---|
| "za艂aduj dane X" | data.load("X") |
| "oblicz sum臋 X" | metrics.sum("X") |
| "oblicz 艣redni膮 X" | metrics.avg("X") |
| "wygeneruj raport X" | report.generate("X") |
| "prognozuj X na N dni" | forecast.predict(N) |
| "ustaw alert X powy偶ej N" | alert.threshold("X", "gt", N) |
from src.modules.voice import VoiceCommandParser
# Parse Polish voice command
command = VoiceCommandParser.parse("oblicz sum臋 sprzeda偶y")
print(command.dsl) # metrics.sum("sprzeda偶y")
print(command.intent) # calculate
print(command.confidence) # 0.85Location: src/dsl/atoms/deploy.py
- Container deployment (Docker, Podman, Docker Compose)
- Kubernetes orchestration (K8s manifests, Helm charts)
- CI/CD pipeline generation (GitHub Actions, GitLab CI, Jenkins, CircleCI)
- Cloud platform deployment (AWS ECS/Lambda, Vercel, Netlify)
- Multi-platform targets (Web, Desktop, Mobile)
- URI-based application launching
Generate Docker deployment configuration.
deploy.docker(image="analytica/app", tag="latest", port=8000)
deploy.docker(dockerfile="Dockerfile.prod", build=true, env={"NODE_ENV": "production"})Parameters:
image(str) - Docker image nametag(str) - Image tag (default: "latest")port(int) - Exposed port (default: 8000)dockerfile(str) - Dockerfile path (default: "Dockerfile")env(dict) - Environment variablesvolumes(list) - Volume mounts
Returns:
{
"config": {
"type": "docker",
"image": "analytica/app:latest",
"commands": {
"build": "docker build -t analytica/app:latest -f Dockerfile .",
"run": "docker run -d -p 8000:8000 analytica/app:latest",
"push": "docker push analytica/app:latest"
}
},
"deploy": {"platform": "docker", "access_uri": "http://localhost:8000"}
}Generate Docker Compose configuration.
deploy.compose(services=["api", "db", "redis"], file="docker-compose.prod.yml")Generate Kubernetes deployment configuration.
deploy.kubernetes(namespace="prod", replicas=3, image="app:v1")
deploy.kubernetes(manifest="k8s/", ingress_host="app.example.com")Parameters:
namespace(str) - K8s namespace (default: "default")replicas(int) - Number of replicas (default: 1)image(str) - Container imagemanifest(str) - Manifest directory pathingress_host(str) - Ingress hostnameresources(dict) - Resource limits {"cpu": "100m", "memory": "128Mi"}
Generate Helm chart deployment.
deploy.helm(chart="analytica", release="prod", values="values-prod.yaml")Generate GitHub Actions workflow.
deploy.github_actions(workflow="deploy", triggers=["push", "pull_request"], branches=["main"])Parameters:
workflow(str) - Workflow nametriggers(list) - Event triggers: push, pull_request, schedulebranches(list) - Target branchesjobs(list) - Job names (default: ["build", "test", "deploy"])
Generate GitLab CI configuration.
deploy.gitlab_ci(stages=["build", "test", "deploy"])Generate Jenkins pipeline.
deploy.jenkins(pipeline="Jenkinsfile", agents=["docker"], stages=["Build", "Test", "Deploy"])Deploy to AWS (ECS, Lambda, EC2).
deploy.aws(service="ecs", cluster="prod", region="eu-central-1")
deploy.aws(service="lambda", function="handler")Deploy to Vercel.
deploy.vercel(project="my-app", prod=true)Deploy to Netlify.
deploy.netlify(site="my-site", prod=true)Configure web application deployment.
deploy.web(framework="react", build="npm run build", output="dist")Parameters:
framework(str) - Framework: react, vue, angular, sveltebuild(str) - Build commandoutput(str) - Output directory
Configure desktop application deployment.
deploy.desktop(framework="electron", platforms=["win", "mac", "linux"])
deploy.desktop(framework="tauri", release=true, url="http://localhost:18000")Parameters:
framework(str) - Framework: electron, tauriplatforms(list) - Target platforms: win, mac, linuxrelease(bool) - Build release versionurl(str) - Backend URL for the appproject_dir(str) - Project directory path
Returns:
{
"config": {
"type": "desktop",
"framework": "electron",
"commands": {
"dev": "npm run electron:dev",
"build": "npm run electron:build",
"build_win": "npm run electron:build -- --win"
}
},
"deploy": {
"platform": "desktop",
"launch_uri": "analytica://desktop/run?dir=/path&url=http://localhost:18000"
}
}Configure mobile application deployment.
deploy.mobile(framework="react-native", platforms=["ios", "android"])
deploy.mobile(framework="flutter", release=true)Launch deployed application using URI scheme.
deploy.launch(platform="desktop", dir="/path/to/project", url="http://localhost:18000")
deploy.launch(uri="analytica://desktop/run?dir=/tmp")Bundle DSL pipeline with runtime for standalone deployment.
deploy.bundle(target="standalone", include_runtime=true, minify=true)Export pipeline to DSL file.
deploy.export_dsl(path="pipelines/main.dsl", format="native")
deploy.export_dsl(path="pipelines/main.json", format="json")@pipeline deploy_app:
data.from_input()
| investment.analyze(discount_rate=0.12)
| view.card(value="npv", title="NPV", icon="馃挵")
| deploy.docker(image="analytica/app", tag="v1.0")
| deploy.kubernetes(namespace="prod", replicas=3)
| deploy.github_actions(workflow="deploy", triggers=["push"])from analytica import Pipeline
# Deploy to Docker + K8s
result = (Pipeline()
.data.load('sales.csv')
.metrics.sum('amount')
.deploy.docker(image='analytics', tag='v1')
.deploy.kubernetes(namespace='prod', replicas=2)
.execute())
# Generate CI/CD pipeline
result = (Pipeline()
.deploy.github_actions(workflow='ci', triggers=['push', 'pull_request'])
.execute())from src.modules import BaseModule
class MyModule(BaseModule):
name = "mymodule"
version = "1.0.0"
def get_routes(self) -> List[Any]:
"""Return FastAPI routes"""
return []
def get_atoms(self) -> Dict[str, Any]:
"""Return DSL atoms"""
return {
"mymodule.action": self.my_action,
}
def my_action(self, **kwargs):
"""Atom implementation"""
value = kwargs.get("value", kwargs.get("_arg0"))
return {"result": value * 2}from src.modules import register_module
from mymodule import MyModule
register_module(MyModule())Location: src/modules/views/ + src/dsl/atoms/implementations.py
DSL atoms for generating view specifications that can be rendered dynamically by the frontend.
- Generate chart, table, card, KPI views from DSL
- Automatic column detection for tables
- Multiple views in single pipeline
- Data preservation through view chain
Generate chart view specification.
data.from_input()
| view.chart(type="bar", x="month", y="sales", title="Sales Chart")Parameters:
type(str) - Chart type: bar, line, pie, area, scatter, donut, gaugex(str) - X-axis field namey(str) - Y-axis field nameseries(list) - Multiple series field namestitle(str) - Chart titlecolors(list) - Custom color palettelegend(bool) - Show legend (default: true)
Generate table view specification.
data.from_input()
| view.table(columns=["name", "amount", "date"], title="Transactions")Parameters:
columns(list) - Column names or specs (auto-detected if empty)title(str) - Table titlesortable(bool) - Enable sorting (default: true)filterable(bool) - Enable filtering (default: true)paginate(bool) - Enable pagination (default: true)page_size(int) - Rows per page (default: 10)
Generate metric card specification.
metrics.sum("amount")
| view.card(value="sum", title="Total Sales", icon="馃挵", style="success")Parameters:
value(str) - Field name for main valuetitle(str) - Card titleformat(str) - Value format: number, currency, percenticon(str) - Icon (emoji or icon name)style(str) - Card style: default, success, warning, danger, infotrend(str) - Field name for trend indicator
Generate KPI widget specification.
data.from_input()
| view.kpi(value="current", target="goal", title="Progress", icon="馃搱")Parameters:
value(str) - Field name for current valuetarget(str) - Field name for target valuetitle(str) - KPI titleformat(str) - Value formaticon(str) - Iconprogress(bool) - Show progress bar (default: true)
Generate grid layout specification.
view.grid(columns=3, gap=20)Parameters:
columns(int) - Number of columns (default: 2)gap(int) - Gap between items in pixels (default: 16)items(list) - List of view specifications
Generate complete dashboard specification.
view.dashboard(layout="grid", title="Sales Dashboard", refresh=30)Parameters:
layout(str) - Layout type: grid, flex, stackwidgets(list) - List of widget specificationstitle(str) - Dashboard titlerefresh(int) - Auto-refresh interval in seconds
Generate text/markdown view.
view.text(content="**Summary**: Total sales increased by 15%", format="markdown")Parameters:
content(str) - Text content (supports {{field}} placeholders)format(str) - Format type: text, markdown, htmltitle(str) - Title
Generate list view specification.
data.from_input()
| view.list(primary="name", secondary="description", icon="icon")Parameters:
primary(str) - Primary text fieldsecondary(str) - Secondary text fieldicon(str) - Icon field
data.from_input()
| view.card(value="total", title="Total Sales", icon="馃挵", style="success")
| view.chart(type="bar", x="month", y="sales", title="Monthly Sales")
| view.table(columns=["month", "sales", "growth"], title="Details")Result:
{
"data": [...],
"views": [
{"type": "card", "title": "Total Sales", ...},
{"type": "chart", "chart_type": "bar", ...},
{"type": "table", "columns": [...], ...}
]
}Views are rendered by view-renderer.js:
import { createViewRenderer } from '/ui/view-renderer.js';
const renderer = createViewRenderer('#container');
renderer.render(apiResponse);| Dokument | Opis |
|---|---|
| ARCHITECTURE.md | Architektura systemu |
| API.md | REST API reference |
| DSL.md | J臋zyk DSL - sk艂adnia, atomy |
| POINTS.md | System punkt贸w - cennik |
| ROADMAP.md | Plan rozwoju |
Last updated: 2025-01-01