Compare commits

13 Commits
test ... master

Author SHA1 Message Date
Mateusz Gruszczyński
6fc91198a0 switch to debian in docker 2026-03-20 09:48:42 +01:00
Mateusz Gruszczyński
92eb925c94 switch to debian in docker 2026-03-20 09:41:08 +01:00
Mateusz Gruszczyński
51da117ab4 switch to debian in docker 2026-03-20 09:40:56 +01:00
Mateusz Gruszczyński
419c6fd0b5 switch to debian in docker 2026-03-20 09:28:58 +01:00
Mateusz Gruszczyński
97f63bd852 push changes 2026-03-20 09:22:06 +01:00
Mateusz Gruszczyński
fca05e7a94 push changes 2026-03-20 09:20:17 +01:00
Mateusz Gruszczyński
2a59c4bf3e push changes 2026-03-20 09:14:00 +01:00
Mateusz Gruszczyński
ab411ba67c no-brand icon 2026-03-17 16:22:08 +01:00
Mateusz Gruszczyński
d8cb3613b3 change icon 2026-03-17 16:18:53 +01:00
Mateusz Gruszczyński
499a014e91 change icon 2026-03-17 16:06:12 +01:00
Mateusz Gruszczyński
20900b96d7 change icon 2026-03-17 16:02:47 +01:00
Mateusz Gruszczyński
247bb15ed6 fix 500 2026-03-17 14:37:15 +01:00
gru
ac44cc6b31 Merge pull request 'test' (#1) from test into master
Reviewed-on: #1
2026-03-13 23:33:36 +01:00
15 changed files with 271 additions and 60 deletions

View File

@@ -37,13 +37,26 @@ EXPOSE_PORT=8785
# Baza danych
# ================================
# Adres SQLAlchemy
#
# Wybór silnika bazy
# Dozwolone:
# - sqlite
# - pgsql
# - mysql
DB_ENGINE=sqlite
# Baza danych - dane
DB_HOST=postgres
DB_PORT=5432
DB_NAME=ksef
DB_USER=ksef
DB_PASSWORD=ksef
# Jeśli ustawisz DATABASE_URL ręcznie, ma priorytet nad DB_ENGINE/DB_*
# Przykłady:
# sqlite:///instance/app.db
# postgresql://user:pass@localhost/dbname
DATABASE_URL=sqlite:///instance/app.db
# postgresql+psycopg://ksef:ksef@postgres:5432/ksef
# mysql+pymysql://ksef:ksef@mysql:3306/ksef
DATABASE_URL=sqlite:///db/sqlite/app.db
# ================================
# Redis / Cache / Rate limit

1
.gitignore vendored
View File

@@ -26,3 +26,4 @@ storage/*
backups/*
certs/*
pdf/*
db/*

View File

@@ -1,30 +1,32 @@
FROM python:3.14-alpine
FROM python:3.14-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /app
RUN apk add --no-cache \
gcc musl-dev python3-dev \
\
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
build-essential \
python3-dev \
libffi-dev \
jpeg-dev \
zlib-dev \
\
cairo-dev \
pango-dev \
gdk-pixbuf-dev \
glib-dev \
freetype-dev \
fontconfig-dev \
\
pkgconfig
libjpeg62-turbo-dev \
zlib1g-dev \
libcairo2-dev \
libpango1.0-dev \
libgdk-pixbuf-2.0-dev \
libglib2.0-dev \
libfreetype6-dev \
libfontconfig1-dev \
pkg-config \
libpq-dev \
default-libmysqlclient-dev \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN mkdir -p instance storage/archive storage/pdf storage/backups
RUN mkdir -p db storage/archive storage/pdf storage/backups
CMD ["gunicorn", "-w", "1", "-k", "gthread", "--threads", "8", "-b", "0.0.0.0:5000", "run:app"]

View File

@@ -88,8 +88,6 @@ APP_DOMAIN=ksef.local:8785 ./deploy_docker.sh
## Konta
Nie ma już wymogu seedów do logowania. Użyj CLI:
```bash
flask --app run.py create-company
flask --app run.py create-user

View File

@@ -1,11 +1,12 @@
from dotenv import load_dotenv
import time
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask, render_template, request, url_for
from flask_login import current_user
from werkzeug.middleware.proxy_fix import ProxyFix
from dotenv import load_dotenv
from sqlalchemy import inspect, text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.exc import OperationalError, SQLAlchemyError
from werkzeug.middleware.proxy_fix import ProxyFix
from config import Config
from redis.exceptions import RedisError
from app.cli import register_cli
@@ -30,7 +31,25 @@ def _ensure_column(table_name: str, column_name: str, ddl: str):
db.session.commit()
def _wait_for_database(app, attempts: int = 30, delay: float = 1.0) -> bool:
for attempt in range(1, attempts + 1):
try:
with db.engine.connect() as conn:
conn.execute(text('SELECT 1'))
if attempt > 1:
app.logger.info('Database became available after %s attempt(s).', attempt)
return True
except OperationalError:
app.logger.warning('Database not ready yet (%s/%s). Waiting...', attempt, attempts)
time.sleep(delay)
return False
def _bootstrap_database(app):
if not _wait_for_database(app):
app.logger.error('Database is still unavailable after waiting. Skipping bootstrap.')
return
try:
db.create_all()
patches = [

View File

@@ -137,7 +137,8 @@ def index():
@bp.route('/switch-company/<int:company_id>')
@login_required
def switch_company(company_id):
CompanyService.set_active_company(company_id)
if not CompanyService.switch_company(company_id):
abort(403)
return redirect(url_for('dashboard.index'))

View File

@@ -54,3 +54,7 @@ class CompanyService:
session['current_company_id'] = company.id
except RuntimeError:
pass
@staticmethod
def set_active_company(company_id, user=None):
return CompanyService.switch_company(company_id, user=user)

View File

@@ -8,6 +8,7 @@ from pathlib import Path
import psutil
from flask import current_app
from sqlalchemy import inspect
from sqlalchemy.engine import make_url
from app.extensions import db
from app.models.audit_log import AuditLog
@@ -199,19 +200,52 @@ class SystemDataService:
continue
count = db.session.execute(db.select(db.func.count()).select_from(table)).scalar() or 0
table_rows.append({'table': table_name, 'rows': int(count)})
uri = current_app.config.get('SQLALCHEMY_DATABASE_URI', '')
sqlite_path = None
sqlite_size = None
db_driver = None
db_host = None
db_port = None
db_name = None
db_user = None
try:
url = make_url(uri)
db_driver = url.drivername
db_host = url.host
db_port = url.port
db_name = url.database
db_user = url.username
except Exception:
pass
if uri.startswith('sqlite:///') and not uri.endswith(':memory:'):
sqlite_path = uri.replace('sqlite:///', '', 1)
try:
sqlite_size = self._human_size(Path(sqlite_path).stat().st_size)
except FileNotFoundError:
sqlite_size = 'brak pliku'
if engine.name == 'sqlite':
db_label = 'SQLite'
elif engine.name == 'postgresql':
db_label = 'PostgreSQL'
elif engine.name == 'mysql':
db_label = 'MySQL'
else:
db_label = engine.name
table_rows_sorted = sorted(table_rows, key=lambda item: (-item['rows'], item['table']))
return {
'engine': engine.name,
'engine_label': db_label,
'driver': db_driver,
'uri': self._mask_uri(uri),
'host': db_host,
'port': db_port,
'database': db_name,
'username': db_user,
'tables_count': len(table_rows),
'sqlite_path': sqlite_path,
'sqlite_size': sqlite_size,

View File

@@ -12,11 +12,10 @@
<div class="row min-vh-100">
<div class="col-lg-6 login-hero d-none d-lg-flex">
<div class="login-hero-card">
<span class="brand-icon mb-4"><i class="fa-solid fa-file-invoice-dollar"></i></span>
<h1 class="mt-4 mb-3">KSeF Manager</h1>
<p class="lead text-secondary">Logowanie do panelu faktur, KSeF, powiadomień i konfiguracji administracyjnej.</p>
<p class="lead text-secondary">Logowanie do systemu <strong>KsEF Manager</strong>.</p>
<div class="login-feature-list">
<div><i class="fa-solid fa-check text-primary me-2"></i>Zarządzj fakturami w jednym miejscu</div>
<div><i class="fa-solid fa-check text-primary me-2"></i>Wystawiaj / odbieraj faktury w jednym meisjcu</div>
</div>
</div>
</div>

View File

@@ -13,7 +13,7 @@
<aside class="sidebar bg-body-tertiary border-end p-3">
<div class="mb-4">
<div class="d-flex align-items-center gap-2 mb-1">
<span class="brand-icon"><i class="fa-solid fa-file-invoice-dollar"></i></span>
<span class="brand-icon"><i class="fa-solid fa-file-invoice-invoice"></i></span>
<div>
<h5 class="mb-0">{{ app_name }}</h5>
<div class="small text-secondary">Panel KSeF i archiwum</div>

View File

@@ -1,18 +1,42 @@
import os
from pathlib import Path
from urllib.parse import quote_plus
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / '.env')
def _normalize_sqlalchemy_db_url(raw: str | None) -> str:
if not raw:
return f"sqlite:///{(BASE_DIR / 'instance' / 'app.db').resolve()}"
if raw.startswith('sqlite:///') and not raw.startswith('sqlite:////'):
rel = raw.replace('sqlite:///', '', 1)
return f"sqlite:///{(BASE_DIR / rel).resolve()}"
return raw
def _q(value: str) -> str:
return quote_plus(value or '')
def _build_db_url() -> str:
db_engine = os.getenv('DB_ENGINE', 'sqlite').strip().lower()
db_host = os.getenv('DB_HOST', 'localhost').strip()
db_port = os.getenv('DB_PORT', '').strip()
db_name = os.getenv('DB_NAME', 'ksef').strip()
db_user = os.getenv('DB_USER', '').strip()
db_password = os.getenv('DB_PASSWORD', '').strip()
if db_engine == 'sqlite':
return f"sqlite:///{(BASE_DIR / 'db' / 'sqlite' / 'app.db').resolve()}"
if db_engine in ('pgsql', 'postgres', 'postgresql'):
port = db_port or '5432'
return (
f"postgresql+psycopg://{_q(db_user)}:{_q(db_password)}"
f"@{db_host}:{port}/{_q(db_name)}"
)
if db_engine == 'mysql':
port = db_port or '3306'
return (
f"mysql+pymysql://{_q(db_user)}:{_q(db_password)}"
f"@{db_host}:{port}/{_q(db_name)}"
)
raise ValueError(f"Nieobsługiwany DB_ENGINE: {db_engine}")
def _path_from_env(name: str, default: Path) -> Path:
@@ -35,7 +59,7 @@ def _normalize_redis_url(raw: str | None) -> str:
class Config:
SECRET_KEY = os.getenv('SECRET_KEY', 'change-me-please')
APP_MASTER_KEY = os.getenv('APP_MASTER_KEY', SECRET_KEY)
SQLALCHEMY_DATABASE_URI = _normalize_sqlalchemy_db_url(os.getenv('DATABASE_URL'))
SQLALCHEMY_DATABASE_URI = _build_db_url()
SQLALCHEMY_TRACK_MODIFICATIONS = False
ARCHIVE_PATH = _path_from_env('ARCHIVE_PATH', BASE_DIR / 'storage' / 'archive')
PDF_PATH = _path_from_env('PDF_PATH', BASE_DIR / 'storage' / 'pdf')
@@ -55,8 +79,6 @@ class Config:
SESSION_COOKIE_HTTPONLY = True
REMEMBER_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
#CEIDG_API_URL = os.getenv('CEIDG_API_URL', 'https://dane.biznes.gov.pl/api/ceidg/v2/firmy')
#CEIDG_TEST_API_URL = os.getenv('CEIDG_TEST_API_URL', 'https://test-dane.biznes.gov.pl/api/ceidg/v2/firmy')
APP_FOOTER_TEXT = 'KSeF Manager · linuxiarz.pl · Mateusz Gruszczyński'

View File

@@ -1,10 +1,22 @@
#!/usr/bin/env sh
set -eu
DB_TARGET="${1:-sqlite}"
STACK_NAME="${STACK_NAME:-ksef_app}"
COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.yml}"
SSL_DIR="${SSL_DIR:-./deploy/caddy/ssl}"
if [ -f .env ]; then
set -a
. ./.env
set +a
fi
APP_DOMAIN="${APP_DOMAIN:-localhost}"
APP_EXTERNAL_SCHEME="${APP_EXTERNAL_SCHEME:-https}"
EXPOSE_PORT="${EXPOSE_PORT:-8785}"
CERT_FILE="${CERT_FILE:-${SSL_DIR}/server.crt}"
KEY_FILE="${KEY_FILE:-${SSL_DIR}/server.key}"
@@ -24,6 +36,38 @@ need_cmd openssl
mkdir -p "$SSL_DIR"
case "$DB_TARGET" in
sqlite)
export DB_ENGINE=sqlite
export DB_HOST=""
export DB_PORT=""
COMPOSE_PROFILES=""
mkdir -p ./db/sqlite
DB_PATH_INFO="./db/sqlite/app.db"
;;
pgsql|postgres|postgresql)
export DB_ENGINE=pgsql
export DB_HOST="${DB_HOST:-postgres}"
export DB_PORT="${DB_PORT:-5432}"
COMPOSE_PROFILES="pgsql"
mkdir -p ./db/pgsql
DB_PATH_INFO="./db/pgsql"
;;
mysql)
export DB_ENGINE=mysql
export DB_HOST="${DB_HOST:-mysql}"
export DB_PORT="${DB_PORT:-3306}"
COMPOSE_PROFILES="mysql"
mkdir -p ./db/mysql
DB_PATH_INFO="./db/mysql"
;;
*)
printf 'Nieznany typ bazy: %s\n' "$DB_TARGET" >&2
printf 'Użycie: ./deploy_docker.sh [sqlite|pgsql|mysql]\n' >&2
exit 1
;;
esac
if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
log "Nie znaleziono certyfikatu SSL w katalogu ${SSL_DIR}, tworzę self-signed cert..."
rm -f "$CERT_FILE" "$KEY_FILE"
@@ -38,22 +82,38 @@ else
log "Znaleziono istniejący certyfikat SSL w katalogu ${SSL_DIR}."
fi
log "Pobieram najnowsze obrazy bazowe..."
docker compose -f "$COMPOSE_FILE" pull
log "Wybrany silnik bazy: ${DB_ENGINE}"
log "Buduję obraz bez cache..."
docker compose -f "$COMPOSE_FILE" build --no-cache
if [ -n "$COMPOSE_PROFILES" ]; then
export COMPOSE_PROFILES
log "Aktywne profile Compose: ${COMPOSE_PROFILES}"
else
unset COMPOSE_PROFILES || true
log "Brak aktywnych profili Compose"
fi
log "Zatrzymuję aktualny stack..."
log "Pobieram najnowsze obrazy dla projektu ${STACK_NAME}..."
docker compose -p "$STACK_NAME" -f "$COMPOSE_FILE" pull
log "Zatrzymuję aktualny stack projektu ${STACK_NAME}..."
docker compose -p "$STACK_NAME" -f "$COMPOSE_FILE" stop || true
log "Usuwam osierocone kontenery i stare nieużywane obrazy..."
log "Usuwam kontenery i osierocone zasoby tylko dla projektu ${STACK_NAME}..."
docker compose -p "$STACK_NAME" -f "$COMPOSE_FILE" down --remove-orphans || true
docker image prune -af || true
docker builder prune -af || true
authoritative_stack="${STACK_NAME}"
log "Uruchamiam stack ${authoritative_stack}..."
log "Buduję obrazy projektu ${STACK_NAME} bez cache..."
docker compose -p "$STACK_NAME" -f "$COMPOSE_FILE" build --no-cache
log "Uruchamiam stack ${STACK_NAME}..."
docker compose -p "$STACK_NAME" -f "$COMPOSE_FILE" up -d
log "Deployment zakończony. Aplikacja powinna być dostępna pod https://${APP_DOMAIN}"
APP_URL="${APP_EXTERNAL_SCHEME}://${APP_DOMAIN}"
if [ -n "${EXPOSE_PORT:-}" ]; then
APP_URL="${APP_URL}:${EXPOSE_PORT}"
fi
log "Deployment zakończony."
log "Adres aplikacji: ${APP_URL}"
log "Port zewnętrzny: ${EXPOSE_PORT}"
log "Silnik bazy: ${DB_ENGINE}"
log "Ścieżka danych bazy: ${DB_PATH_INFO}"

View File

@@ -3,20 +3,74 @@ services:
build: .
env_file: [.env]
environment:
APP_PORT: 5000
APP_EXTERNAL_SCHEME: https
APP_PORT: ${APP_PORT:-5000}
APP_EXTERNAL_SCHEME: ${APP_EXTERNAL_SCHEME:-https}
APP_EXTERNAL_HOST: ${APP_DOMAIN:-localhost}
APP_EXTERNAL_PORT: ${EXPOSE_PORT:-8785}
TZ: ${APP_TIMEZONE:-Europe/Warsaw}
volumes:
- ./:/app
depends_on: [redis]
- ./db/sqlite:/app/db/sqlite
depends_on:
redis:
condition: service_healthy
postgres:
condition: service_healthy
required: false
mysql:
condition: service_healthy
required: false
restart: unless-stopped
redis:
image: redis:7-alpine
ports:
- "6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20
restart: unless-stopped
postgres:
image: postgres:18-alpine
profiles: ["pgsql"]
environment:
POSTGRES_DB: ${DB_NAME:-ksef}
POSTGRES_USER: ${DB_USER:-ksef}
POSTGRES_PASSWORD: ${DB_PASSWORD:-ksef}
TZ: ${APP_TIMEZONE:-Europe/Warsaw}
volumes:
- ./db/pgsql:/var/lib/postgresql
ports:
- "${DB_PORT:-5432}:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-ksef} -d ${DB_NAME:-ksef}"]
interval: 5s
timeout: 5s
retries: 20
restart: unless-stopped
mysql:
image: mysql:8.4
profiles: ["mysql"]
command: --default-authentication-plugin=mysql_native_password
environment:
MYSQL_DATABASE: ${DB_NAME:-ksef}
MYSQL_USER: ${DB_USER:-ksef}
MYSQL_PASSWORD: ${DB_PASSWORD:-ksef}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root}
TZ: ${APP_TIMEZONE:-Europe/Warsaw}
volumes:
- ./db/mysql:/var/lib/mysql
ports:
- "${DB_PORT:-3306}:3306"
healthcheck:
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -uroot -p${MYSQL_ROOT_PASSWORD:-root} --silent"]
interval: 5s
timeout: 5s
retries: 20
restart: unless-stopped
caddy:
@@ -33,7 +87,8 @@ services:
- ./deploy/caddy/ssl:/certs:ro
- caddy_data:/data
- caddy_config:/config
depends_on: [web]
depends_on:
- web
restart: unless-stopped
volumes:

View File

@@ -22,3 +22,4 @@ cryptography==45.0.0
xhtml2pdf==0.2.17
psutil
gunicorn==23.0.0
PyMySQL==1.1.1

View File

@@ -43,6 +43,8 @@ def test_admin_system_data_page(auth_client, monkeypatch):
assert 'Połączenie CEIDG' in body
assert 'Proces i health systemu' in body
assert 'Użytkownicy' in body
assert 'Typ bazy:' in body
assert 'Silnik SQLAlchemy:' in body
assert 'Diagnoza' not in body
assert 'Co sprawdzić' not in body