Go to file
Maciej Pienczyn eaac876ec2
Some checks are pending
NordaBiz Tests / Unit & Integration Tests (push) Waiting to run
NordaBiz Tests / E2E Tests (Playwright) (push) Blocked by required conditions
NordaBiz Tests / Smoke Tests (Production) (push) Blocked by required conditions
NordaBiz Tests / Send Failure Notification (push) Blocked by required conditions
feat(calendar): multi-day events + **bold** w opisach wydarzeń
- norda_events: kolumna event_date_end (NULLABLE, check constraint >= event_date)
- NordaEvent: property is_multi_day, date_range_display; is_past uwzględnia koniec
- Admin (new/edit): pole "Data zakończenia" w formularzu
- Calendar grid: wydarzenie wielodniowe wyświetla się na każdym dniu zakresu
- Upcoming/past filter: używa COALESCE(end, date) — 2-dniowe zostaje w Upcoming
  do swojego ostatniego dnia
- event.html: "Termin" + zakres dla wielodniowych; ICS/Google end date z dateEnd
- Lekki markdown dla opisów: tylko **bold** → <strong> (audyt: tylko event #60)

Zero wpływu na 42 istniejące wydarzenia (NULL == stare zachowanie).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 17:52:31 +02:00
_Claude_Mail_Management refactor: Update tagline from "Katalog Firm Członkowskich" to "Platforma Networkingu" 2026-01-14 11:35:58 +01:00
.claude chore: usuń stare gitlinki worktreeów (martwe, praca dawno na master) 2026-04-15 07:14:53 +02:00
.github/workflows fix: Fix smoke tests and E2E fixture scope issues 2026-02-02 08:04:55 +01:00
blueprints feat(calendar): multi-day events + **bold** w opisach wydarzeń 2026-04-15 17:52:31 +02:00
data feat(membership): add membership_status, resignation_date, fee_included_in_parent 2026-03-31 11:11:56 +02:00
database feat(calendar): multi-day events + **bold** w opisach wydarzeń 2026-04-15 17:52:31 +02:00
docs docs: aktualizacja architektury po migracji na OVH VPS + e-deklaracja w roadmap 2026-04-15 07:00:14 +02:00
downloaded claude-mem plugin v10.3.3 2026-02-23 10:33:26 +01:00
helpers feat: multi-company switcher backend (helper, context processor, switch endpoint, session init) 2026-04-10 13:52:27 +02:00
migrations Initial commit 2026-01-01 14:01:49 +01:00
mockups feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
node_modules claude-mem plugin v10.3.3 2026-02-23 10:33:26 +01:00
reports feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
scripts feat(notifications): D.2+D.3 — forum, broadcasty Izby, wydarzenia, cron 24h 2026-04-14 18:20:38 +02:00
services chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
static chore: logo 5 firm + .gitignore dla worktrees i narzędzi AI 2026-04-15 07:08:04 +02:00
templates feat(calendar): multi-day events + **bold** w opisach wydarzeń 2026-04-15 17:52:31 +02:00
tests chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
utils feat(notifications): D.2+D.3 — forum, broadcasty Izby, wydarzenia, cron 24h 2026-04-14 18:20:38 +02:00
.coveragerc fix: Add missing user-agents dependency and lower coverage threshold 2026-02-02 07:55:52 +01:00
.env.example auto-claude: 4.1 - Add clear comments in .env.example explaining DATABASE_URL and PGPASSWORD 2026-01-10 13:00:47 +01:00
.gitignore chore: logo 5 firm + .gitignore dla worktrees i narzędzi AI 2026-04-15 07:08:04 +02:00
.pre-commit-config.yaml feat: Add pre-commit hooks, CI badge, and release notes v1.24.0 2026-02-02 10:48:29 +01:00
AGENTS.md feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
app.py feat(push): Web Push (VAPID + pywebpush) dla prywatnych wiadomości 2026-04-14 16:56:49 +02:00
app.py.backup.security.20260109_150801 fix: Handle NULL views_count in forum and classifieds 2026-01-11 06:03:13 +01:00
app.py.backup.users.20260109_163618 fix: Handle NULL views_count in forum and classifieds 2026-01-11 06:03:13 +01:00
ARCHITECTURE_CROSS_CHECK_REPORT.md feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
ARCHITECTURE_VERIFICATION_REPORT.md fix: Handle NULL views_count in forum and classifieds 2026-01-11 06:03:13 +01:00
audit_ai_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
benchmark_service.py feat(audit): Phase 4 - AI sentiment analysis + competitor benchmarking 2026-02-08 11:53:59 +01:00
ceidg_api_service.py fix: Add dataRozpoczecia key lookup for CEIDG business start date 2026-02-18 15:11:27 +01:00
CHANGELOG.md fix: Track CHANGELOG.md in git (was incorrectly ignored) 2026-01-09 06:44:14 +01:00
CLAUDE.md fix(deploy): OVH VPS now uses git pull instead of rsync 2026-04-07 00:34:06 +02:00
company_matcher.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
competitor_monitoring_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
config.py refactor(phase1): Extract blueprints for reports, contacts, classifieds, calendar 2026-01-27 10:10:45 +01:00
context_builder.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
CREDENTIAL_VERIFICATION_REPORT.md feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
crux_service.py feat(audit): Phase 1 - YouTube API, CrUX field data, security headers, image formats 2026-02-08 11:32:03 +01:00
database.py feat(calendar): multi-day events + **bold** w opisach wydarzeń 2026-04-15 17:52:31 +02:00
deploy.sh Sync local repo with production state 2026-01-06 22:23:28 +01:00
deployment_checklist.md feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
DIAGRAM_VERIFICATION_REPORT.md feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
docker-compose.yml feat(contacts): Modal "Dodaj z AI" + widoki grupowanie/tabela 2026-01-27 08:52:35 +01:00
email_service.py feat(email): one-click unsubscribe w mailach powiadomień (RFC 8058) 2026-04-14 17:56:36 +02:00
extensions.py refactor(phase2a): Extract auth + public blueprints with Alias Bridge 2026-01-31 07:28:18 +01:00
facebook_graph_service.py chore(facebook): migrate to *_media_view metrics (Meta deprecation 2026-06-30) 2026-04-14 12:59:45 +02:00
feedback_learning_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
file_upload_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
gbp_audit_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
gbp_management_service.py feat(oauth): Add OAuth integration UI, API clients, and audit enrichment (Phase 3) 2026-02-08 15:55:02 +01:00
gbp_performance_service.py feat(api): Expand Google API coverage to ~100% (GBP Performance + GSC extensions) 2026-02-09 12:05:08 +01:00
gemini_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
google_places_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
it_audit_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
krs_api_service.py feat: Add Biała Lista VAT integration for NIP→KRS lookup 2026-02-01 14:32:36 +01:00
krs_audit_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
logo_fetch_service.py fix: handle empty class list in logo image scanner 2026-02-20 19:05:32 +01:00
memory_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
message_upload_service.py feat(messages): add message upload service for file attachments 2026-03-11 17:35:31 +01:00
norda_knowledge_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
nordabiz_chat.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
NordaBiznesHub-PitchDeck.pptx refactor: Update tagline from "Katalog Firm Członkowskich" to "Platforma Networkingu" 2026-01-14 11:35:58 +01:00
oauth_service.py fix: add openid email scopes to Google OAuth for account identification 2026-03-11 08:26:49 +01:00
pyproject.toml feat: Add pre-commit hooks, CI badge, and release notes v1.24.0 2026-02-02 10:48:29 +01:00
README.md feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
redis_service.py feat(messages): add Redis service for pub/sub and presence 2026-03-27 12:59:21 +01:00
requirements.txt feat(push): Web Push (VAPID + pywebpush) dla prywatnych wiadomości 2026-04-14 16:56:49 +02:00
run_ai_quality_tests.py refactor: Rebranding i aktualizacja modelu AI 2026-01-29 14:08:39 +01:00
run_migration.py feat: AI learning from feedback + v1.12.0 2026-01-11 10:51:08 +01:00
search_console_service.py feat(api): Expand Google API coverage to ~100% (GBP Performance + GSC extensions) 2026-02-09 12:05:08 +01:00
search_service.py fix(security): Resolve 1 HIGH and 7 MEDIUM vulnerabilities from code review 2026-02-06 05:25:18 +01:00
security_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
sensitive_data_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
smart_router.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
social_media_found.json Initial commit 2026-01-01 14:01:49 +01:00
test_database_url_validation.py auto-claude: 5.1 - Test that all updated Python scripts provide clear error messages when DATABASE_URL is not set 2026-01-10 13:10:09 +01:00
test_diagrams.md feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
TEST_RESULTS_SHELL_SCRIPTS.md auto-claude: 5.2 - Test that view_maturity_results.sh provides clear error message when PGPASSWORD is not set 2026-01-10 13:13:13 +01:00
TEST_RESULTS.md auto-claude: 5.1 - Test that all updated Python scripts provide clear error messages when DATABASE_URL is not set 2026-01-10 13:10:09 +01:00
test_runtime_errors.py auto-claude: 5.1 - Test that all updated Python scripts provide clear error messages when DATABASE_URL is not set 2026-01-10 13:10:09 +01:00
twitter_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
update_social_media.py feat: Add URL normalization and inline audit sections 2026-01-11 23:07:03 +01:00
verify_all_companies_data.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
verify_architecture_accuracy.py feat: migrate prod docs to OVH VPS + UTC→Warsaw timezone in all templates 2026-04-06 13:41:53 +02:00
verify_diagrams.py fix: Handle NULL views_count in forum and classifieds 2026-01-11 06:03:13 +01:00
view_maturity_results.sh auto-claude: 3.1 - Replace hardcoded PGPASSWORD with environment variable 2026-01-10 12:58:57 +01:00
youtube_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00
zopk_content_scraper.py fix: add local image caching for ZOPK news thumbnails 2026-03-15 09:08:03 +01:00
zopk_knowledge_service.py fix: ZOPK knowledge base image display and data quality issues 2026-03-15 08:57:41 +01:00
zopk_news_service.py chore: update Author to Maciej Pienczyn, InPi sp. z o.o. across all files 2026-04-10 08:20:47 +02:00

Norda Biznes Partner

CI/CD

Production-ready Flask web application providing a business directory and networking platform for members of the Norda Biznes association from Wejherowo and surrounding area.

🚀 Status: LIVE in production since 2025-11-23 🌐 URL: https://nordabiznes.pl 📊 Coverage: 80 member companies (100% of Norda Biznes membership)


Table of Contents


Quick Start

For experienced developers who want to get running immediately:

# 1. Clone and setup
git clone https://github.com/pienczyn/nordabiz.git
cd nordabiz
python3 -m venv venv && source venv/bin/activate
pip install -r requirements.txt

# 2. Start PostgreSQL (Docker)
docker compose up -d

# 3. Initialize database
docker exec -i nordabiz-postgres psql -U nordabiz_app -d nordabiz < database/schema.sql

# 4. Configure environment
cp .env.example .env
# Edit .env and add your API keys (see Development Environment Setup for details)

# 5. Run the application
python3 app.py

# 6. Open http://localhost:5000

Required API Keys:

For detailed setup instructions, see Development Environment Setup.


Overview

Norda Biznes Partner is a Flask-powered web platform built with PostgreSQL, featuring AI-driven search capabilities, comprehensive company profiles, and administrative tools for managing member data. The platform integrates Google Gemini AI for intelligent company recommendations, automated news monitoring via Brave Search API, and comprehensive SEO/social media auditing tools.

Key Capabilities:

  • Company Directory - Complete catalog of 80 member companies with verified data
  • AI Chat Assistant - Google Gemini 3 Flash-powered conversational search
  • Advanced Search - Multi-mode search with FTS, fuzzy matching, and synonym expansion
  • Admin Panels - News moderation, SEO audit, social media tracking, GBP/IT audits
  • User Authentication - Secure login with email confirmation and role-based access
  • RESTful API - JSON endpoints for programmatic access to company data

Technology Stack

Backend

  • Python 3.9+ - Core programming language
  • Flask 3.0.0 - Web application framework
  • SQLAlchemy 2.0.23 - ORM and database abstraction layer
  • PostgreSQL - Primary relational database (production and development)
  • Gunicorn - WSGI HTTP server for production deployment

Security & Authentication

  • Flask-Login 0.6.3 - User session management and authentication
  • Flask-WTF 1.2.1 - CSRF protection and form validation
  • Flask-Limiter 3.5.0 - Rate limiting (200 req/day, 50 req/hour)

AI & Machine Learning

  • Google Gemini AI (google-generativeai 0.3.2)
    • Models: gemini-3-flash-preview (default), gemini-3-pro-preview (advanced)
    • Features: Multi-turn conversations, context-aware recommendations, AI-powered search
    • Limits: Free tier (200 requests/day)

External API Integrations

  1. Google Gemini AI - Conversational AI and company recommendations
  2. Google PageSpeed Insights - SEO and performance analysis (25,000 req/day)
  3. Google Maps/Places - Business verification and geocoding
  4. Microsoft Graph API - Email service (OAuth2 with MSAL)
  5. KRS Open API - Polish business registry data
  6. Brave Search API - News monitoring and company mentions (2,000 req/month)

Frontend

  • Jinja2 - Server-side HTML template rendering (30+ templates)
  • CSS3 - Custom styling with Fluent Design System inspiration
  • Vanilla JavaScript (ES6+) - Dynamic UI interactions, AJAX, form validation
  • No external frameworks - Custom UI components (modals, toasts, cards, tables)

SEO & Web Analysis

  • BeautifulSoup4 4.12.3 - HTML parsing and meta tag extraction
  • lxml 5.1.0 - Fast XML/HTML processing with XPath support
  • python-whois 0.9.4 - Domain information and WHOIS lookup

Infrastructure & Deployment

  • Nginx Proxy Manager - Reverse proxy on R11-REVPROXY-01 (10.22.68.250)
  • Let's Encrypt - SSL/TLS certificates with auto-renewal
  • Docker - PostgreSQL container for local development
  • systemd - Service management (nordabiznes.service)
  • Git - Version control (GitHub + Gitea internal)

Database

  • PostgreSQL - Primary database with advanced features:
    • Full-text search (FTS) with tsvector
    • Fuzzy matching with pg_trgm extension
    • JSONB for flexible data storage
    • 20+ tables (Company, User, Chat, News, Social Media, SEO, etc.)
    • psycopg2-binary 2.9.9 adapter

Utilities

  • Flask-Mail 0.9.1 - Email functionality
  • requests 2.31.0 - HTTP client for external API calls
  • feedparser 6.0.10 - RSS/Atom feed parsing
  • python-dotenv 1.0.0 - Environment variable management

Features

User-Facing Features

🏢 Company Directory & Catalog

  • 80 member companies with 100% coverage of Norda Biznes membership
  • 6 business categories: IT, Construction, Services, Production, Trade, Other
  • Comprehensive company profiles with verified data (NIP, REGON, KRS)
  • Detailed information: Contact details, services, competencies, social media presence
  • Website technical analysis for each company
  • Data quality levels: Basic, enhanced, and complete profiles

🔍 Advanced Search & Discovery

  • Multi-mode search system with AI-powered capabilities
  • Direct lookup: NIP/REGON exact matching
  • Keyword search: Company name, description, services, competencies
  • Synonym expansion: Automatic keyword expansion (e.g., "strony" → www, web, portal)
  • Full-text search: PostgreSQL FTS with tsvector indexing
  • Fuzzy matching: pg_trgm for typo tolerance
  • Weighted scoring: Prioritized results by relevance

💬 AI Chat Assistant

  • Conversational AI powered by Google Gemini 3 Flash
  • Context-aware recommendations for company discovery
  • Multi-turn conversations with full history tracking
  • Answer questions about member companies and services
  • Find companies by service, competency, or business need
  • Quality assurance: 15 test cases with 70% pass threshold
  • Rate limiting: 200 requests/day, 50 requests/hour

🔐 User Authentication & Accounts

  • Secure registration with email confirmation
  • User profiles with company affiliation tracking
  • Password reset functionality
  • Session management with Flask-Login
  • CSRF protection on all forms
  • Role-based access (user vs admin)

🔔 Notifications System

  • Real-time notifications for user activity
  • Notification types: New news, news approved/rejected
  • JSON API for programmatic access
  • Unread count tracking

Admin Features (Requires Admin Access)

📰 News Monitoring & Moderation

  • Automated news monitoring via Brave Search API
  • AI-powered relevance scoring (0.0-1.0) with Google Gemini
  • News categorization: News mentions, press releases, awards
  • Admin moderation dashboard with approve/reject workflow
  • Bulk actions for efficient moderation
  • Display on company profiles for approved news

📱 Social Media Audit

  • Track 6 platforms: Facebook, Instagram, LinkedIn, YouTube, TikTok, Twitter/X
  • Profile verification and validation
  • Activity monitoring: Last checked, followers count
  • Missing profile identification for outreach opportunities
  • Current coverage: 115 profiles across 53 companies (66% coverage)
  • Batch audit processing for efficiency

🎯 SEO Dashboard & Audit

  • Comprehensive SEO audits using Google PageSpeed Insights API
  • Performance scoring (0-100) for each company website
  • Accessibility scoring for WCAG compliance
  • Best practices scoring for web standards
  • On-page SEO analysis: Meta tags, headings, images
  • Technical SEO checks: robots.txt, sitemap, canonical tags
  • Historical tracking of SEO improvements
  • Batch processing with rate limiting (25,000 req/day)

🏪 Google Business Profile (GBP) Audit

  • Field-by-field completeness checking
  • Weighted scoring algorithm (100 points total)
  • AI-powered recommendations via Google Gemini
  • Historical tracking of profile improvements
  • Photo requirements analysis

💻 IT Infrastructure Audit

  • Security posture scoring (50% weight)
  • Collaboration readiness assessment (30% weight)
  • Completeness scoring (20% weight)
  • Maturity level classification
  • Cross-company collaboration matching
  • Security elements: EDR, MFA, Firewall, Backup, DR, VPN, Monitoring

💬 Forum Management

  • Discussion forum for member engagement
  • Topic and reply moderation
  • Community discussions

📅 Calendar Management

  • Events and meetings calendar
  • Event creation and management
  • Member calendar access

👥 User Management

  • User account administration
  • Permission management
  • Admin role assignment

Technical Features

🔌 RESTful API

  • JSON endpoints for programmatic access:
    • GET /api/companies - Companies list
    • GET /api/verify-nip - NIP verification
    • GET /api/notifications - User notifications
    • GET /health - Health check
  • Authentication required for protected endpoints

🛡️ Security & Rate Limiting

  • Flask-Login for session management
  • Flask-WTF for CSRF protection on all forms
  • Flask-Limiter for rate limiting (200 req/day, 50 req/hour)
  • Secure password hashing
  • SQL injection protection via SQLAlchemy ORM
  • XSS protection via Jinja2 auto-escaping
  • API key management via environment variables

🗄️ Database Architecture

  • PostgreSQL primary database with 20+ tables
  • SQLAlchemy 2.0 ORM with advanced features
  • Full-text search with tsvector indexing
  • Fuzzy matching with pg_trgm extension
  • JSONB support for flexible data storage
  • Migration system for schema versioning

🌍 Multi-Environment Deployment

  • Development: PostgreSQL via Docker (localhost:5433)
  • Production: OVH VPS (57.128.200.27, inpi-vps-waw01)
  • Staging reverse proxy: NPM on R11-REVPROXY-01
  • SSL/TLS: Let's Encrypt with auto-renewal
  • Domain: nordabiznes.pl (DNS in OVH)
  • WSGI: Gunicorn production server

🔗 External API Integrations

  • Google Gemini AI - Conversational AI (200 req/day)
  • Google PageSpeed Insights - SEO audits (25,000 req/day)
  • Google Maps/Places - Business verification
  • Microsoft Graph API - Email service
  • KRS Open API - Polish business registry
  • Brave Search API - News monitoring (2,000 req/month)

Data Verification & Quality Control

  • NIP verification via KRS API
  • REGON validation
  • KRS number verification
  • Data completeness checks
  • Quality levels: Basic, enhanced, complete
  • Automated verification scripts

🧪 AI Quality Testing Framework

  • Automated AI response evaluation
  • 15 test cases in 8 business categories
  • 70% pass threshold for quality assurance
  • JSON-based test configuration
  • Detailed evaluation reports

Project Structure

nordabiz/
├── app.py                      # Main Flask application (routes, auth, API)
├── database.py                 # SQLAlchemy models (20+ tables)
├── gemini_service.py           # Google Gemini AI integration
├── nordabiz_chat.py            # AI chat engine with company context
├── search_service.py           # Unified search (FTS, fuzzy, synonyms)
├── email_service.py            # Microsoft Graph email integration
├── krs_api_service.py          # Polish business registry API
├── gbp_audit_service.py        # Google Business Profile audit
├── it_audit_service.py         # IT infrastructure audit
├── templates/                  # Jinja2 HTML templates (30+ files)
│   ├── base.html               # Base template with navigation and auth
│   ├── index.html              # Company directory listing
│   ├── company_detail.html     # Detailed company profile page
│   ├── chat.html               # AI chat interface
│   ├── admin/                  # Admin dashboards and tools (15 files)
│   ├── auth/                   # Authentication flows (5 files)
│   ├── forum/                  # Community forum (3 files)
│   ├── calendar/               # Events calendar (4 files)
│   ├── messages/               # Private messaging (4 files)
│   └── errors/                 # Error pages (404, 500)
├── static/                     # Static assets (CSS, images)
│   ├── css/                    # Fluent Design stylesheets
│   │   ├── microsoft-fluent.css
│   │   └── fluent-nordabiz.css
│   └── img/companies/          # Company logos (80 images)
├── database/                   # Database schemas and migrations
│   ├── schema.sql              # Main PostgreSQL schema
│   ├── README.md               # Database documentation
│   └── migrations/             # Versioned migrations (6 files)
├── scripts/                    # Production automation scripts
│   ├── seo_audit.py            # SEO audit tool (PageSpeed Insights)
│   ├── social_media_audit.py   # Social media presence audit
│   ├── seo_analyzer.py         # On-page SEO analysis
│   └── company-data-collector.js  # Node.js web scraper
├── tests/                      # Test suite (7 files)
│   ├── ai_quality_evaluator.py # AI testing framework
│   ├── ai_quality_test_cases.json  # 15 test cases in 8 categories
│   ├── test_admin_seo_dashboard.py
│   ├── test_gbp_audit_field_checks.py
│   ├── test_it_audit_collaboration.py
│   └── test_social_media_audit.py
├── data/                       # Source data files
│   ├── companies-basic.json    # 80 company profiles
│   └── data-sources.md         # Data source documentation
├── requirements.txt            # Python dependencies (16 packages)
├── docker-compose.yml          # PostgreSQL development database
├── .env.example                # Environment variables template
├── CLAUDE.md                   # Project documentation for AI
└── deployment_checklist.md     # Production deployment guide

Development Environment Setup

Follow these steps to set up the development environment on your local machine.

Prerequisites

  • Python 3.9+ - Core programming language
  • PostgreSQL 15+ - Database (via Docker or native installation)
  • Git - Version control
  • Docker (optional) - For containerized PostgreSQL

Installation Steps

1. Clone the Repository

git clone https://github.com/pienczyn/nordabiz.git
cd nordabiz

2. Create Virtual Environment

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate

# On Windows:
venv\Scripts\activate

3. Install Python Dependencies

pip install -r requirements.txt

This will install all required packages including:

  • Flask 3.0.0 (web framework)
  • SQLAlchemy 2.0.23 (ORM)
  • psycopg2-binary 2.9.9 (PostgreSQL adapter)
  • google-generativeai 0.3.2 (Gemini AI)
  • Flask-Login, Flask-WTF, Flask-Limiter (security)
  • And more (see requirements.txt for complete list)

4. Set Up PostgreSQL Database

Option A: Using Docker (Recommended for Development)

# Start PostgreSQL container
docker compose up -d

# Verify container is running
docker ps | grep nordabiz-postgres

This creates a PostgreSQL 15 database on localhost:5433 with:

  • Database: nordabiz
  • User: nordabiz_app
  • Password: dev_password

Option B: Native PostgreSQL Installation

# Install PostgreSQL (example for Ubuntu/Debian)
sudo apt install postgresql-15 postgresql-contrib-15

# Create database and user
sudo -u postgres psql
CREATE DATABASE nordabiz;
CREATE USER nordabiz_app WITH PASSWORD 'your_password_here';
GRANT ALL PRIVILEGES ON DATABASE nordabiz TO nordabiz_app;
\q

5. Initialize Database Schema

# Apply schema (Docker setup)
docker exec -i nordabiz-postgres psql -U nordabiz_app -d nordabiz < database/schema.sql

# Or for native PostgreSQL
psql -U nordabiz_app -d nordabiz -h localhost < database/schema.sql

6. Configure Environment Variables

Create .env file in the project root:

cp .env.example .env

Edit .env and configure the following variables:

# Flask Configuration
SECRET_KEY=your-super-secret-key-change-this
FLASK_ENV=development

# Server Configuration
PORT=5000
HOST=0.0.0.0

# Database Configuration (for Docker setup)
DATABASE_URL=postgresql://nordabiz_app:dev_password@localhost:5433/nordabiz

# Google Gemini API (required for AI chat)
GOOGLE_GEMINI_API_KEY=your_gemini_api_key_here

# Google PageSpeed Insights API (optional, for SEO audits)
GOOGLE_PAGESPEED_API_KEY=your_pagespeed_api_key_here

# Google Places API (optional, for GBP audits)
GOOGLE_PLACES_API_KEY=your_places_api_key_here

# Email Configuration (optional, for user verification)
MAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
MAIL_USE_TLS=True
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password_here
MAIL_DEFAULT_SENDER=noreply@norda-biznes.info

# Application URLs
APP_URL=http://localhost:5000
VERIFY_EMAIL_URL=http://localhost:5000/verify-email

Getting API Keys:

7. Run the Application

# Ensure virtual environment is activated
source venv/bin/activate  # or venv\Scripts\activate on Windows

# Run Flask development server
python3 app.py

The application will start on http://localhost:5000

Default ports:

  • Flask app: 5000 (or 5001 if 5000 is occupied)
  • PostgreSQL (Docker): 5433 (mapped from container's 5432)

8. Verify Installation

Open your browser and navigate to:

Development Workflow

# Start PostgreSQL (if using Docker)
docker compose up -d

# Activate virtual environment
source venv/bin/activate

# Run application
python3 app.py

# In another terminal: Run tests
python -m pytest tests/

# Stop PostgreSQL when done
docker compose down

Troubleshooting

Database Connection Issues:

# Check PostgreSQL is running (Docker)
docker ps | grep nordabiz-postgres

# Check PostgreSQL logs
docker logs nordabiz-postgres

# Restart PostgreSQL container
docker compose restart

Port Already in Use:

# Change PORT in .env file
PORT=5001

# Or stop conflicting service
lsof -ti:5000 | xargs kill -9

Missing Dependencies:

# Reinstall all dependencies
pip install -r requirements.txt --force-reinstall

Database Schema Issues:

# Reset database (Docker)
docker compose down -v  # WARNING: Deletes all data!
docker compose up -d
docker exec -i nordabiz-postgres psql -U nordabiz_app -d nordabiz < database/schema.sql

For more detailed database setup and management, see database/README.md.

Testing & Quality Assurance

The Norda Biznes Partner includes a comprehensive testing framework to ensure code quality, AI accuracy, and feature reliability. The test suite covers unit tests for individual components and specialized AI quality evaluation.

Test Suite Overview

The tests/ directory contains the following test modules:

tests/
├── ai_quality_evaluator.py          # AI testing framework
├── ai_quality_test_cases.json       # 15 test cases in 8 categories
├── test_admin_seo_dashboard.py      # SEO dashboard functionality tests
├── test_gbp_audit_field_checks.py   # Google Business Profile audit tests
├── test_it_audit_collaboration.py   # IT infrastructure audit tests
├── test_seo_audit.py                # SEO audit service tests
├── test_social_media_audit.py       # Social media audit tests
└── results/                         # Test results and reports (generated)

Running Tests

AI Quality Tests

The AI Quality Testing Framework evaluates the accuracy and relevance of AI chat responses using predefined test cases.

Basic Usage:

# Run all AI quality tests (standard output)
python run_ai_quality_tests.py

# Run with verbose output showing details for each test
python run_ai_quality_tests.py --verbose
# or
python run_ai_quality_tests.py -v

# Run with verbose output AND save results to JSON file
python run_ai_quality_tests.py -v -s

# Run only high-priority test cases (quick validation)
python run_ai_quality_tests.py -q

Test Results:

Test results are displayed in the console and optionally saved to tests/results/ directory with timestamps:

  • ai_quality_report_20260110_143000.json - Detailed test results with scores and metrics

AI Test Categories:

The AI quality tests cover 8 business categories with 15 test cases:

  1. IT/Web Development - Testing recommendations for IT services, web development
  2. Services/Legal - Legal services, law firms
  3. Services/Accounting - Accounting, bookkeeping services
  4. Production/Metal - Metal production, manufacturing
  5. Construction - Construction companies, contractors
  6. HVAC - Heating, ventilation, air conditioning
  7. Energy/Renewable - Renewable energy, solar panels
  8. IT/Security - IT security, cybersecurity services

Quality Thresholds:

  • Pass Threshold: 70% - Tests must achieve at least 70% accuracy to pass
  • Scoring: Each test case is scored 0.0-1.0 based on:
    • Company relevance (did it find the right companies?)
    • Response accuracy (is the information correct?)
    • Context understanding (did it understand the query intent?)

Unit Tests

Run unit tests for specific components using pytest:

# Run all unit tests
python -m pytest tests/

# Run specific test file
python -m pytest tests/test_admin_seo_dashboard.py

# Run with verbose output
python -m pytest tests/ -v

# Run with coverage report
python -m pytest tests/ --cov=.

Manual Testing in Production

⚠️ IMPORTANT: Always use test accounts for production verification.

Test Accounts:

Account Email Purpose
Test User test@nordabiznes.pl Test user-facing features (directory, search, chat)
Test Admin testadmin@nordabiznes.pl Test admin features (moderation, audits, management)

Testing Workflow:

  1. User Features:

    • Company directory browsing
    • Search functionality
    • AI chat conversations
    • User registration and authentication
    • Notifications
  2. Admin Features:

    • News moderation (/admin/news)
    • SEO dashboard (/admin/seo)
    • Social media audit (/admin/social-media)
    • GBP audit (/admin/gbp-audit)
    • IT audit (/admin/it-audit)
    • User management (/admin/users)

Quality Assurance Process

Pre-Deployment QA Checklist

Before deploying to production, ensure all quality checks pass:

  1. Code Quality:

    # Check Python syntax
    python -m py_compile app.py
    
    # Check all Python files
    find . -name "*.py" -exec python -m py_compile {} \;
    
  2. AI Quality:

    # Run AI quality tests with 70% pass threshold
    python run_ai_quality_tests.py -v
    # Expected: Pass rate ≥ 70%
    
  3. Unit Tests:

    # Run all unit tests
    python -m pytest tests/ -v
    # Expected: All tests pass
    
  4. Database Integrity:

    # Verify database schema (development)
    psql -U nordabiz_app -d nordabiz -h localhost -p 5433 -c "\dt"
    
    # Check for data quality issues
    python verify_all_companies_data.py
    
  5. API Endpoints:

    # Test health endpoint
    curl http://localhost:5000/health
    # Expected: {"status": "healthy"}
    
    # Test companies API
    curl http://localhost:5000/api/companies | jq '.total'
    # Expected: 80
    

Continuous Quality Monitoring

Development:

  • Run AI quality tests after chat engine modifications
  • Run unit tests after feature changes
  • Verify test account functionality weekly

Production:

  • Monitor health endpoint: https://nordabiznes.pl/health
  • Review application logs: sudo journalctl -u nordabiznes -f
  • Track AI chat analytics: /admin/chat-analytics
  • Monitor rate limits and API usage

Test Coverage

Current test coverage by feature area:

Feature Area Test Coverage Test Files
AI Chat Engine Comprehensive ai_quality_evaluator.py, ai_quality_test_cases.json
SEO Audit Comprehensive test_admin_seo_dashboard.py, test_seo_audit.py
GBP Audit Comprehensive test_gbp_audit_field_checks.py
IT Audit Comprehensive test_it_audit_collaboration.py
Social Media Audit Comprehensive test_social_media_audit.py
Search Service ⚠️ Manual Testing SearchService integration tests needed
Authentication ⚠️ Manual Testing User registration/login flow tests needed
API Endpoints ⚠️ Manual Testing API integration tests needed

Adding New Tests

AI Quality Test Cases

To add a new AI quality test case, edit tests/ai_quality_test_cases.json:

{
  "test_id": "new_test_01",
  "category": "Services/Consulting",
  "priority": "high",
  "query": "Szukam firmy doradczej w Wejherowie",
  "expected_companies": [
    "Firma A",
    "Firma B"
  ],
  "notes": "Testing consulting service recommendations"
}

Unit Tests

Create a new test file in tests/ following the pattern:

"""
Test module for [feature name]
"""
import pytest
from database import SessionLocal, init_db
# Import modules to test

def test_feature_functionality():
    """Test basic feature functionality"""
    # Arrange
    db = SessionLocal()

    # Act
    result = feature_function()

    # Assert
    assert result is not None
    assert result.status == "success"

    db.close()

Troubleshooting Tests

AI Tests Failing:

# Check Gemini API key is configured
grep GOOGLE_GEMINI_API_KEY .env

# Verify database has companies data
python -c "from database import SessionLocal, Company; db = SessionLocal(); print(db.query(Company).count())"
# Expected: 80

Database Connection Errors:

# Ensure PostgreSQL is running
docker ps | grep nordabiz-postgres

# Test database connection
psql -U nordabiz_app -d nordabiz -h localhost -p 5433 -c "SELECT 1;"

Import Errors:

# Ensure all dependencies are installed
pip install -r requirements.txt

# Verify virtual environment is activated
which python
# Expected: /path/to/nordabiz/venv/bin/python

For detailed test implementation and examples, see the tests/ directory and individual test modules.

Deployment & Production

The application is live in production at https://nordabiznes.pl since November 23, 2025.

Production Environment

Component Details
Server OVH VPS inpi-vps-waw01 (IP: 57.128.200.27)
Database PostgreSQL 15 on 57.128.200.27 (localhost:5432)
Reverse Proxy Not used for production (direct DNS). NPM (10.22.68.250) serves staging only
Domain nordabiznes.pl (DNS managed via OVH)
SSL/TLS Let's Encrypt with automatic renewal
WSGI Server Gunicorn
Service Manager systemd (nordabiznes.service)
Application Path /var/www/nordabiznes
Application User www-data

Git Repositories

The project maintains two Git remotes for redundancy and deployment:

Remote Repository Purpose
origin (GitHub) git@github.com:pienczyn/nordabiz.git Cloud backup, public access, CI/CD ready
inpi (Gitea) git@10.22.68.180:maciejpi/nordabiz.git Internal backup

Gitea Access: https://10.22.68.180:3000/ (requires HTTPS)

Deployment Workflow

┌─────────────┐   git push    ┌─────────────┐
│ Development │ ────────────► │   GitHub    │  (cloud backup)
│   (Local)   │               └─────────────┘
└──────┬──────┘
       │  rsync
       ▼
┌─────────────┐
│  OVH VPS    │  (57.128.200.27)
│ Production  │
└─────────────┘

Deployment Steps

1. Push Changes from Development:

# Push to GitHub (and optionally Gitea)
git push origin master && git push inpi master

2. Deploy to Production (via rsync — no .git on server):

# Rsync to production server (from local dev machine)
rsync -avz --exclude='.git' --exclude='venv' --exclude='.env' \
  ./ maciejpi@57.128.200.27:/var/www/nordabiznes/

# SSH to restart
ssh maciejpi@57.128.200.27 "sudo systemctl reload nordabiznes"

# Verify deployment
curl -I https://nordabiznes.pl/health
# Expected: HTTP/2 200

Pre-Deployment Checklist

Before deploying to production, always:

  1. Test locally - Verify changes work in development environment
  2. Syntax check - Run python -m py_compile app.py to check for syntax errors
  3. Database migrations - Apply any schema changes to production database
  4. Environment variables - Ensure new .env variables are configured on production
  5. Dependencies - Update requirements.txt if new packages were added

For comprehensive deployment procedures, see deployment_checklist.md.

Production Configuration

Network Configuration:

Production traffic goes directly to OVH VPS (57.128.200.27) — DNS A record points there. NPM (10.22.68.250) is used only for staging (staging.nordabiznes.pl).

Environment Variables:

Production uses similar .env configuration as development, but with production-specific values:

  • FLASK_ENV=production
  • DATABASE_URL=postgresql://nordabiz_app:***@localhost:5432/nordabiz
  • APP_URL=https://nordabiznes.pl
  • Production API keys (Google Gemini, PageSpeed, Places, etc.)

Production Monitoring & Maintenance

Service Management:

# Check service status
sudo systemctl status nordabiznes

# View application logs
sudo journalctl -u nordabiznes -f

# Restart service
sudo systemctl restart nordabiznes

# Stop service
sudo systemctl stop nordabiznes

# Start service
sudo systemctl start nordabiznes

Database Backup:

Production server (OVH VPS) uses local pg_dump backups with offsite sync to PBS (10.22.68.127).

Health Check:

The application provides a health endpoint for monitoring:

Production Access

SSH Access:

# Always SSH as maciejpi user (NOT root!)
ssh maciejpi@57.128.200.27

Test Accounts:

For testing functionality in production:

Account Email Role
Test User test@nordabiznes.pl Regular user (company directory, search, chat)
Test Admin testadmin@nordabiznes.pl Administrator (admin panels, moderation)

⚠️ IMPORTANT: Always use test accounts for production verification. Never test with real user accounts.

Troubleshooting Production Issues

Application Not Responding:

# Check if service is running
sudo systemctl status nordabiznes

# Check application logs for errors
sudo journalctl -u nordabiznes -n 100

# Restart service
sudo systemctl restart nordabiznes

Database Connection Issues:

# Check PostgreSQL is running
sudo systemctl status postgresql

# Test database connectivity
psql -U nordabiz_app -d nordabiz -h localhost -c "SELECT 1;"

Redirect Loop / 502 Errors:

Verify NPM proxy configuration forwards to port 5000:

curl -I https://nordabiznes.pl/health

If issues persist, check NPM configuration on R11-REVPROXY-01 (Proxy Host ID: 27).

For detailed incident reports and troubleshooting guides, see docs/INCIDENT_REPORT_20260102.md.

API Documentation

The Norda Biznes Partner provides a comprehensive RESTful API for programmatic access to company data, user management, and administrative functions. All API endpoints return JSON responses.

Base URL

  • Development: http://localhost:5000
  • Production: https://nordabiznes.pl

Authentication

API endpoints requiring authentication expect a valid session cookie (session). Users must be logged in via the web interface or obtain a session through the login endpoint.

Public API Endpoints

These endpoints are accessible without authentication:

Endpoint Method Description Response
/health GET Health check endpoint for monitoring {"status": "healthy"}
/api/companies GET Retrieve list of all companies with filtering options Array of company objects with full details
/api/verify-nip POST Verify NIP number via KRS API Company data or error message
/api/verify-krs GET/POST Verify KRS number and retrieve company data KRS registry information
/api/model-info GET Get information about AI model configuration Model name, version, capabilities
/api/check-email POST Check if email address is already registered {"exists": true/false}

Example - Get Companies:

curl https://nordabiznes.pl/api/companies

Example - Verify NIP:

curl -X POST https://nordabiznes.pl/api/verify-nip \
  -H "Content-Type: application/json" \
  -d '{"nip": "5882436505"}'

User API Endpoints

These endpoints require user authentication (regular or admin):

Chat & NordaGPT

Endpoint Method Description
/api/chat/start POST Start a new AI chat conversation
/api/chat/<conversation_id>/message POST Send a message in an existing conversation
/api/chat/<conversation_id>/history GET Retrieve conversation history
/api/chat/feedback POST Submit feedback on AI chat response (thumbs up/down)

Example - Start Chat:

curl -X POST https://nordabiznes.pl/api/chat/start \
  -H "Content-Type: application/json" \
  -H "Cookie: session=YOUR_SESSION" \
  -d '{"message": "Szukam firm IT w Wejherowie"}'

Notifications

Endpoint Method Description
/api/notifications GET Get user notifications (new news, approvals, etc.)
/api/notifications/<notification_id>/read POST Mark specific notification as read
/api/notifications/read-all POST Mark all notifications as read
/api/notifications/unread-count GET Get count of unread notifications

Example - Get Notifications:

curl https://nordabiznes.pl/api/notifications \
  -H "Cookie: session=YOUR_SESSION"

Messages

Endpoint Method Description
/api/messages/unread-count GET Get count of unread private messages

Recommendations

Endpoint Method Description
/api/recommendations/<company_id> GET Get recommendations for a company
/api/recommendations/create POST Create a new recommendation
/api/recommendations/<rec_id>/edit POST Edit existing recommendation
/api/recommendations/<rec_id>/delete POST Delete a recommendation

Admin API Endpoints

These endpoints require admin privileges (is_admin=True):

SEO Audits

Endpoint Method Description
/api/seo/audit GET Get all SEO audit results
/api/seo/audit/<slug> GET Get SEO audit for specific company
/api/seo/audit POST Trigger new SEO audit for company

Example - Trigger SEO Audit:

curl -X POST https://nordabiznes.pl/api/seo/audit \
  -H "Content-Type: application/json" \
  -H "Cookie: session=YOUR_ADMIN_SESSION" \
  -d '{"company_id": 26, "url": "https://example.com"}'

Google Business Profile Audits

Endpoint Method Description
/api/gbp/audit/health GET Check GBP audit service health
/api/gbp/audit GET Get all GBP audit results
/api/gbp/audit/<slug> GET Get GBP audit for specific company
/api/gbp/audit POST Trigger new GBP audit

Social Media Audits

Endpoint Method Description
/api/social/audit POST Trigger social media profile audit

IT Infrastructure Audits

Endpoint Method Description
/api/it-audit/matches/<company_id> GET Get collaboration matches for company
/api/it-audit/history/<company_id> GET Get IT audit history for company
/api/it-audit/export GET Export IT audit data (CSV format)

User Management

Endpoint Method Description
/api/admin/users/ai-parse POST Parse user data from natural language using AI
/api/admin/users/bulk-create POST Create multiple users from parsed data

Analytics & Monitoring

Endpoint Method Description
/api/admin/chat-stats GET Get AI chat usage statistics
/api/admin/logs GET Retrieve application logs
/api/admin/logs/stream GET Stream application logs (SSE)
/api/admin/logs/clear POST Clear application logs
/api/admin/test-log POST Generate test log entry

Company Refresh Endpoint

Endpoint Method Description Auth Required
/api/company/<company_id>/refresh-krs POST Refresh company data from KRS registry User (company owner or admin)

Rate Limiting

The API implements rate limiting to ensure fair usage:

  • Global limit: 200 requests per day per IP
  • Burst limit: 50 requests per hour per IP
  • AI Chat: 200 requests per day (Google Gemini free tier)
  • SEO Audits: 25,000 requests per day (Google PageSpeed Insights free tier)
  • News Monitoring: 2,000 requests per month (Brave Search API free tier)

Error Responses

All API endpoints return standard HTTP status codes:

Status Code Meaning
200 Success - Request completed successfully
201 Created - Resource created successfully
400 Bad Request - Invalid parameters or missing required fields
401 Unauthorized - Authentication required
403 Forbidden - Insufficient permissions (admin required)
404 Not Found - Resource does not exist
429 Too Many Requests - Rate limit exceeded
500 Internal Server Error - Server error occurred

Error Response Format:

{
  "error": "Error message",
  "details": "Additional error details (optional)"
}

API Response Examples

Success Response - Company List:

{
  "companies": [
    {
      "id": 1,
      "name": "PIXLAB Sp. z o.o.",
      "slug": "pixlab-sp-z-o-o",
      "category": "IT",
      "description": "Innowacyjne rozwiązania IT...",
      "nip": "5882436505",
      "website": "https://pixlab.pl",
      "email": "biuro@pixlab.pl",
      "phone": "+48 58 xxx xx xx",
      "city": "Wejherowo",
      "services": ["Strony WWW", "Aplikacje webowe"],
      "competencies": ["Python", "Flask", "React"]
    }
  ],
  "total": 80
}

Success Response - SEO Audit:

{
  "company_id": 26,
  "company_name": "PIXLAB Sp. z o.o.",
  "url": "https://pixlab.pl",
  "seo_score": 92,
  "performance_score": 88,
  "accessibility_score": 95,
  "best_practices_score": 90,
  "audited_at": "2026-01-10T10:30:00Z"
}

Error Response - Authentication Required:

{
  "error": "Authentication required",
  "details": "Please log in to access this endpoint"
}

Web Interface Endpoints

In addition to JSON API endpoints, the application provides web interface routes:

Public Routes

  • / - Company directory listing
  • /company/<slug> - Company profile page
  • /search - Search interface
  • /chat - AI chat interface
  • /aktualnosci - News feed
  • /forum - Discussion forum
  • /kalendarz - Events calendar
  • /tablica - Classifieds board
  • /nowi-czlonkowie - New members

Authentication Routes

  • /register - User registration
  • /login - User login
  • /logout - User logout
  • /forgot-password - Password recovery
  • /reset-password/<token> - Password reset
  • /verify-email/<token> - Email verification
  • /resend-verification - Resend verification email

User Dashboard Routes

  • /dashboard - User dashboard
  • /wiadomosci - Private messages
  • /company/<slug>/recommend - Submit recommendation

Admin Dashboard Routes

  • /admin/news - News moderation panel
  • /admin/seo - SEO audit dashboard
  • /admin/gbp-audit - Google Business Profile audit
  • /admin/social-media - Social media audit
  • /admin/social-audit - Social media batch audit
  • /admin/it-audit - IT infrastructure audit
  • /admin/forum - Forum management
  • /admin/kalendarz - Calendar management
  • /admin/users - User management
  • /admin/fees - Membership fees management
  • /admin/recommendations - Recommendations moderation
  • /admin/chat-analytics - AI chat analytics
  • /admin/digital-maturity - Digital maturity assessment
  • /admin/debug - Debug panel

Audit Detail Routes

  • /audit/seo/<slug> - SEO audit details for company
  • /audit/social/<slug> - Social media audit details
  • /audit/gbp/<slug> - GBP audit details
  • /audit/it/<slug> - IT audit details

API Best Practices

  1. Always check the /health endpoint before making API calls to ensure the service is available
  2. Implement exponential backoff for rate-limited requests
  3. Cache responses when appropriate to reduce API load
  4. Use HTTPS in production for secure communication
  5. Handle errors gracefully and provide meaningful error messages to users
  6. Log API requests for debugging and monitoring purposes

Further Documentation

For detailed information about specific features:

  • AI Chat: See nordabiz_chat.py and tests/ai_quality_test_cases.json
  • Search System: See search_service.py for SearchService implementation
  • Database Schema: See database/schema.sql and database.py
  • External APIs: See CLAUDE.md for integration details

Common Commands Reference

Quick reference for frequently used development, testing, and deployment commands.

Development Commands

# Start development environment
source venv/bin/activate              # Activate virtual environment
docker compose up -d                  # Start PostgreSQL container
python3 app.py                        # Run Flask development server

# Stop development environment
docker compose down                   # Stop PostgreSQL container
deactivate                            # Deactivate virtual environment

Database Commands

# Database management
docker exec -i nordabiz-postgres psql -U nordabiz_app -d nordabiz < database/schema.sql  # Apply schema
psql -U nordabiz_app -d nordabiz -h localhost -p 5433 -c "\dt"                          # List tables
psql -U nordabiz_app -d nordabiz -h localhost -p 5433 -c "SELECT COUNT(*) FROM companies;"  # Count companies

# Database reset (⚠️ WARNING: Deletes all data!)
docker compose down -v                # Remove volumes
docker compose up -d                  # Recreate database
docker exec -i nordabiz-postgres psql -U nordabiz_app -d nordabiz < database/schema.sql  # Reapply schema

Testing Commands

# Run AI quality tests
python run_ai_quality_tests.py         # Standard output
python run_ai_quality_tests.py -v      # Verbose mode
python run_ai_quality_tests.py -v -s   # Verbose + save results
python run_ai_quality_tests.py -q      # Quick (high-priority only)

# Run unit tests
python -m pytest tests/                            # All tests
python -m pytest tests/test_admin_seo_dashboard.py # Specific test
python -m pytest tests/ -v                         # Verbose output
python -m pytest tests/ --cov=.                    # With coverage

# Data verification
python verify_all_companies_data.py    # Check data quality

Git & Deployment Commands

# Development: Push to both remotes
git push origin master && git push inpi master

# Production: Deploy to server (rsync, no .git on server)
rsync -avz --exclude='.git' --exclude='venv' --exclude='.env' ./ maciejpi@57.128.200.27:/var/www/nordabiznes/
ssh maciejpi@57.128.200.27 "sudo systemctl reload nordabiznes"
curl -I https://nordabiznes.pl/health  # Verify deployment

Production Service Management

# Service control (on production server)
sudo systemctl status nordabiznes      # Check status
sudo systemctl restart nordabiznes     # Restart service
sudo systemctl start nordabiznes       # Start service
sudo systemctl stop nordabiznes        # Stop service

# View logs
sudo journalctl -u nordabiznes -f      # Follow logs (live)
sudo journalctl -u nordabiznes -n 100  # Last 100 entries

Health & Monitoring Commands

# Check application health
curl http://localhost:5000/health                    # Local
curl -I https://nordabiznes.pl/health                # Production

# Test API endpoints
curl http://localhost:5000/api/companies | jq '.total'          # Count companies
curl http://localhost:5000/api/model-info | jq '.model_name'    # Check AI model

# Check database connectivity
psql -U nordabiz_app -d nordabiz -h localhost -p 5433 -c "SELECT 1;"  # Development
psql -U nordabiz_app -d nordabiz -h localhost -c "SELECT 1;"          # Production

Audit Scripts

# Run audit scripts
cd scripts/
python seo_audit.py --company-id 26                    # Single company SEO audit
python seo_audit.py --batch 1-10                       # Batch SEO audit
python social_media_audit.py --company-id 26           # Social media audit

Pre-Deployment Checklist Commands

# Before deployment, run these checks:
python -m py_compile app.py                            # Syntax check
python run_ai_quality_tests.py -v                      # AI quality (≥70%)
python -m pytest tests/ -v                             # Unit tests
python verify_all_companies_data.py                    # Data integrity
curl http://localhost:5000/health                      # Health check

For more detailed command documentation, see CLAUDE.md and deployment_checklist.md.

Contributing

We welcome contributions to improve the Norda Biznes Partner platform! Here's how you can help.

Development Workflow

  1. Fork and clone the repository
  2. Create a feature branch: git checkout -b feature/your-feature-name
  3. Make your changes following our code conventions (see below)
  4. Test thoroughly:
    • Run AI quality tests: python run_ai_quality_tests.py -v
    • Run unit tests: python -m pytest tests/ -v
    • Verify manually in browser
  5. Commit your changes: Use clear, descriptive commit messages
  6. Push to your fork: git push origin feature/your-feature-name
  7. Create a Pull Request with detailed description of changes

Code Conventions

Python Code:

  • Follow PEP 8 style guide
  • Use 4 spaces for indentation (no tabs)
  • Type hints where appropriate
  • Docstrings for all functions and classes
  • No print statements in production code (use app.logger)

Jinja2 Templates:

  • IMPORTANT: The {% block extra_js %} in base.html is already inside a <script> tag
  • DO NOT add your own <script> tags inside extra_js blocks (causes nesting errors)
  • Correct: {% block extra_js %}function foo() {...}{% endblock %}
  • Wrong: {% block extra_js %}<script>function foo() {...}</script>{% endblock %}

Database Changes:

  • Never edit production database directly
  • Always test on development database (Docker on port 5433) first
  • Create migration scripts for schema changes in database/migrations/
  • Grant permissions after creating new tables/sequences:
    GRANT ALL ON TABLE table_name TO nordabiz_app;
    GRANT USAGE, SELECT ON SEQUENCE sequence_name TO nordabiz_app;
    

Git Commits:

  • Use descriptive commit messages
  • Format: "category: brief description" (e.g., "fix: Correct SEO scoring algorithm")
  • Reference issue numbers when applicable: "feat: Add GBP audit dashboard (#123)"

Testing Requirements

All contributions must include appropriate tests:

  • New features: Add AI quality test cases to tests/ai_quality_test_cases.json if AI-related
  • Bug fixes: Add regression tests to prevent future occurrences
  • API changes: Update API documentation in README.md
  • All tests must pass before PR can be merged (≥70% AI quality threshold)

Code Review Process

  1. All pull requests require review before merging
  2. Automated checks must pass (syntax, tests)
  3. Maintainers will review code for:
    • Code quality and conventions
    • Test coverage
    • Documentation updates
    • Security considerations
  4. Address review feedback promptly
  5. Once approved, maintainers will merge

Documentation

When adding or modifying features:

  • Update README.md if user-facing changes
  • Update CLAUDE.md if architectural changes
  • Add inline code comments for complex logic
  • Update API documentation if endpoints change
  • Update deployment_checklist.md if deployment process changes

Questions or Need Help?

Troubleshooting

Comprehensive troubleshooting guide for common issues.

Development Environment Issues

Database Connection Errors

Problem: Cannot connect to PostgreSQL database

# Check if PostgreSQL container is running
docker ps | grep nordabiz-postgres

# If not running, start it
docker compose up -d

# Check logs for errors
docker logs nordabiz-postgres

# Test connection manually
psql -U nordabiz_app -d nordabiz -h localhost -p 5433 -c "SELECT 1;"

Problem: "FATAL: password authentication failed"

# Ensure you're using the correct credentials from docker-compose.yml
# Development: nordabiz_app / dev_password on port 5433
# Check your .env file DATABASE_URL matches docker-compose.yml

Port Already in Use

Problem: Flask fails to start - port 5000 in use

# Option 1: Find and kill process using port 5000
lsof -ti:5000 | xargs kill -9

# Option 2: Use different port in .env
echo "PORT=5001" >> .env
python3 app.py

Missing Dependencies

Problem: ImportError or ModuleNotFoundError

# Ensure virtual environment is activated
source venv/bin/activate  # or venv\Scripts\activate on Windows
which python  # Should show path to venv/bin/python

# Reinstall all dependencies
pip install -r requirements.txt --force-reinstall

# If specific package fails, try upgrading pip first
pip install --upgrade pip
pip install -r requirements.txt

Database Schema Issues

Problem: Missing tables or schema errors

# Reset database (⚠️ WARNING: Deletes all data!)
docker compose down -v
docker compose up -d
docker exec -i nordabiz-postgres psql -U nordabiz_app -d nordabiz < database/schema.sql

# Verify tables exist
psql -U nordabiz_app -d nordabiz -h localhost -p 5433 -c "\dt"

Testing Issues

AI Tests Failing

Problem: AI quality tests below 70% threshold

# Check Gemini API key is configured
grep GOOGLE_GEMINI_API_KEY .env

# Verify database has companies data
python -c "from database import SessionLocal, Company; db = SessionLocal(); print(f'Companies: {db.query(Company).count()}'); db.close()"
# Expected: 80 companies

# Check API rate limits (200 req/day)
# Wait if limit exceeded, or use different API key

Problem: Import errors in tests

# Ensure all dependencies installed
pip install -r requirements.txt

# Verify virtual environment activated
which python  # Should point to venv/bin/python

# Try running from project root
cd /path/to/nordabiz
python run_ai_quality_tests.py -v

Production Issues

Application Not Responding

Problem: nordabiznes.pl not loading

# SSH to production server (OVH VPS)
ssh maciejpi@57.128.200.27

# Check service status
sudo systemctl status nordabiznes

# If stopped, start it
sudo systemctl start nordabiznes

# Check logs for errors
sudo journalctl -u nordabiznes -n 100

# Restart if needed
sudo systemctl restart nordabiznes

# Verify health
curl -I https://nordabiznes.pl/health

Redirect Loop / 502 Errors

Problem: Browser shows redirect loop or 502 Bad Gateway

Cause: NPM proxy forwarding to wrong port (80 instead of 5000)

Solution:

  1. Access Nginx Proxy Manager: http://10.22.68.250:81
  2. Find Proxy Host for nordabiznes.pl (ID: 27)
  3. Verify Forward Port is 5000 (NOT 80)
  4. Save and test: curl -I https://nordabiznes.pl/health

See docs/INCIDENT_REPORT_20260102.md for detailed incident analysis.

Database Connection Issues in Production

Problem: Application can't connect to database

# Check PostgreSQL is running
sudo systemctl status postgresql

# Test connection
psql -U nordabiz_app -d nordabiz -h localhost -c "SELECT 1;"

# Check logs
sudo journalctl -u postgresql -n 50

# Restart if needed
sudo systemctl restart postgresql

Permission Denied Errors

Problem: Git pull or file write errors

Cause: Running commands as wrong user

Solution:

# SSH as maciejpi (NOT root!)
ssh maciejpi@57.128.200.27

API & External Service Issues

Google API Errors

Problem: Gemini/PageSpeed/Places API errors

# Check API keys are configured
grep GOOGLE .env

# Verify API key validity at:
# - Gemini: https://ai.google.dev/
# - PageSpeed: https://developers.google.com/speed/docs/insights/v5/get-started
# - Places: https://console.cloud.google.com/apis/credentials

# Check rate limits:
# - Gemini: 200 requests/day
# - PageSpeed: 25,000 requests/day
# - Places: $200/month credit

Problem: "Invalid API key" errors

Solution: Regenerate API key in Google Cloud Console and update .env

Common Error Messages

Error Cause Solution
sqlalchemy.exc.OperationalError Database not accessible Check PostgreSQL is running, verify credentials
werkzeug.exceptions.NotFound Route doesn't exist Check URL path, verify route in app.py
jinja2.exceptions.TemplateNotFound Missing template file Verify template exists in templates/ directory
InFailedSqlTransaction Database transaction failed Check database logs, ensure rollback after errors
flask_limiter.errors.RateLimitExceeded Too many requests Wait for rate limit reset, or increase limits

Getting Additional Help

If issues persist after trying these solutions:

  1. Check documentation: CLAUDE.md has extensive troubleshooting
  2. Review logs:
    • Development: Check Flask console output
    • Production: sudo journalctl -u nordabiznes -n 200
  3. Database logs: docker logs nordabiz-postgres (dev) or sudo journalctl -u postgresql (prod)
  4. Check health endpoint: curl -I https://nordabiznes.pl/health
  5. Contact support: biuro@norda-biznes.info

For detailed database troubleshooting, see database/README.md.

Resources & Documentation

Additional documentation and resources for developers.

Project Documentation

Document Description Location
CLAUDE.md Comprehensive project documentation for AI and developers CLAUDE.md
deployment_checklist.md Production deployment procedures deployment_checklist.md
database/README.md Database schema and management guide database/README.md
database/schema.sql Complete PostgreSQL schema database/schema.sql
data/data-sources.md Data source documentation data/data-sources.md

Incident Reports

Report Date Description
INCIDENT_REPORT_20260102.md 2026-01-02 NPM proxy redirect loop incident

Key Files Reference

Core Application:

  • app.py - Main Flask application (routes, authentication, admin panels)
  • database.py - SQLAlchemy models (20+ tables)
  • requirements.txt - Python dependencies (16 packages)

Service Modules:

  • gemini_service.py - Google Gemini AI integration
  • nordabiz_chat.py - AI chat engine with company context
  • search_service.py - Unified search service (FTS, fuzzy, synonyms)
  • email_service.py - Microsoft Graph email integration
  • krs_api_service.py - Polish business registry API
  • gbp_audit_service.py - Google Business Profile audit
  • it_audit_service.py - IT infrastructure audit

Configuration:

  • .env.example - Environment variables template
  • docker-compose.yml - PostgreSQL development database
  • .gitignore - Git ignore patterns

Testing:

  • run_ai_quality_tests.py - AI quality test runner
  • tests/ai_quality_test_cases.json - 15 test cases in 8 categories
  • tests/ai_quality_evaluator.py - AI testing framework

External Resources

API Documentation:

Technology Documentation:

Git Repositories

Repository URL Purpose
GitHub (origin) https://github.com/pienczyn/nordabiz Cloud backup, public access
Gitea (inpi) https://10.22.68.180:3000/maciejpi/nordabiz Internal backup, deployment source

Production Environment

  • Server: OVH VPS inpi-vps-waw01 (IP: 57.128.200.27)
  • URL: https://nordabiznes.pl
  • Status: LIVE since 2025-11-23

For production access and monitoring, see Deployment & Production.

Roadmap & Future Enhancements

While the platform is fully functional and in production, the following features are planned for future releases:

Enhanced Company Profiles

  • Photo galleries for company showcases
  • Product/service catalog with detailed descriptions
  • Company achievements and awards timeline
  • Employee directory and team profiles

Networking & Collaboration

  • Direct messaging system between member companies
  • Collaboration opportunities board
  • Joint project proposals and consortium building
  • Recommendation and referral system

B2B Marketplace

  • Dedicated marketplace for B2B offers
  • Business partner matching algorithm
  • RFP/RFQ posting and bidding system
  • Contract management tools

Analytics & Reporting

  • Company analytics dashboard
  • Member engagement metrics
  • Platform usage statistics
  • Custom reporting tools

Integration & Automation

  • Newsletter system for member updates
  • CRM integration capabilities
  • Automated data enrichment workflows
  • Third-party service integrations

Note: Features are prioritized based on member feedback and business value. See CLAUDE.md for detailed roadmap planning.


Contact

Norda Biznes - Regionalna Izba Przedsiębiorców


License

Project created for Norda Biznes - Regional Chamber of Entrepreneurs

© 2025 Norda Biznes. All rights reserved.