diff --git a/.env.example b/.env.example index f8da826..ba00eff 100644 --- a/.env.example +++ b/.env.example @@ -20,4 +20,7 @@ AUTHORIZED_COOKIE_VALUE=twoj_wlasny_hash AUTH_COOKIE_MAX_AGE=86400 # dla compose -HEALTHCHECK_TOKEN=alamapsaikota123 \ No newline at end of file +HEALTHCHECK_TOKEN=alamapsaikota123 + +# sesja zalogowanego usera (domyślnie 7 dni) +SESSION_TIMEOUT_MINUTES=10080 \ No newline at end of file diff --git a/alters.txt b/alters.txt index fffe528..1731e50 100644 --- a/alters.txt +++ b/alters.txt @@ -28,6 +28,12 @@ ALTER TABLE shopping_list ADD COLUMN is_public BOOLEAN NOT NULL DEFAULT 1; # ilośc produktów ALTER TABLE item ADD COLUMN quantity INTEGER DEFAULT 1; -#licznik najczesciej kupowanych reczy +# licznik najczesciej kupowanych reczy ALTER TABLE suggested_product ADD COLUMN usage_count INTEGER DEFAULT 0; +# funkcja niekupione +ALTER TABLE item ADD COLUMN not_purchased_reason TEXT; +ALTER TABLE item ADD COLUMN not_purchased BOOLEAN DEFAULT 0; + +# funkcja sortowania +ALTER TABLE item ADD COLUMN position INTEGER DEFAULT 0; diff --git a/app.py b/app.py index 2403f1a..d4d6ec3 100644 --- a/app.py +++ b/app.py @@ -7,11 +7,33 @@ import sys import platform import psutil -from datetime import datetime, timedelta -from flask import Flask, render_template, redirect, url_for, request, flash, Blueprint, send_from_directory, request, abort, session, jsonify, make_response +from datetime import datetime, timedelta, UTC, timezone + +from flask import ( + Flask, + render_template, + redirect, + url_for, + request, + flash, + Blueprint, + send_from_directory, + request, + abort, + session, + jsonify, + make_response, +) from markupsafe import Markup from flask_sqlalchemy import SQLAlchemy -from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user +from flask_login import ( + LoginManager, + UserMixin, + login_user, + login_required, + logout_user, + current_user, +) from flask_compress import Compress from flask_socketio import SocketIO, emit, join_room from werkzeug.security import generate_password_hash, check_password_hash @@ -25,17 +47,22 @@ from functools import wraps app = Flask(__name__) app.config.from_object(Config) -app.config['COMPRESS_ALGORITHM'] = ['zstd', 'br', 'gzip', 'deflate'] -app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1) -SYSTEM_PASSWORD = app.config.get('SYSTEM_PASSWORD', 'changeme') -DEFAULT_ADMIN_USERNAME = app.config.get('DEFAULT_ADMIN_USERNAME', 'admin') -DEFAULT_ADMIN_PASSWORD = app.config.get('DEFAULT_ADMIN_PASSWORD', 'admin123') -UPLOAD_FOLDER = app.config.get('UPLOAD_FOLDER', 'uploads') -ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'} -AUTHORIZED_COOKIE_VALUE = app.config.get('AUTHORIZED_COOKIE_VALUE', '80d31cdfe63539c9') -AUTH_COOKIE_MAX_AGE = app.config.get('AUTH_COOKIE_MAX_AGE', 86400) -HEALTHCHECK_TOKEN = app.config.get('HEALTHCHECK_TOKEN', 'alamapsaikota1234') +ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif", "webp"} +SQLALCHEMY_ECHO = True + +SYSTEM_PASSWORD = app.config.get("SYSTEM_PASSWORD", "changeme") +DEFAULT_ADMIN_USERNAME = app.config.get("DEFAULT_ADMIN_USERNAME", "admin") +DEFAULT_ADMIN_PASSWORD = app.config.get("DEFAULT_ADMIN_PASSWORD", "admin123") +UPLOAD_FOLDER = app.config.get("UPLOAD_FOLDER", "uploads") +AUTHORIZED_COOKIE_VALUE = app.config.get("AUTHORIZED_COOKIE_VALUE", "80d31cdfe63539c9") +AUTH_COOKIE_MAX_AGE = app.config.get("AUTH_COOKIE_MAX_AGE", 86400) +HEALTHCHECK_TOKEN = app.config.get("HEALTHCHECK_TOKEN", "alamapsaikota1234") +SESSION_TIMEOUT_MINUTES = int(app.config.get("SESSION_TIMEOUT_MINUTES", 10080)) + +app.config["COMPRESS_ALGORITHM"] = ["zstd", "br", "gzip", "deflate"] +app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(minutes=SESSION_TIMEOUT_MINUTES) +app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1) os.makedirs(UPLOAD_FOLDER, exist_ok=True) @@ -46,65 +73,86 @@ TIME_WINDOW = 60 * 60 db = SQLAlchemy(app) socketio = SocketIO(app, async_mode="eventlet") login_manager = LoginManager(app) -login_manager.login_view = 'login' +login_manager.login_view = "login" # flask-compress compress = Compress() compress.init_app(app) -static_bp = Blueprint('static_bp', __name__) +static_bp = Blueprint("static_bp", __name__) # dla live active_users = {} + +def utcnow(): + return datetime.now(timezone.utc) + + class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(150), unique=True, nullable=False) password_hash = db.Column(db.String(150), nullable=False) is_admin = db.Column(db.Boolean, default=False) + class ShoppingList(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(150), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow) - owner_id = db.Column(db.Integer, db.ForeignKey('user.id')) + owner_id = db.Column(db.Integer, db.ForeignKey("user.id")) is_temporary = db.Column(db.Boolean, default=False) share_token = db.Column(db.String(64), unique=True, nullable=True) - expires_at = db.Column(db.DateTime, nullable=True) - owner = db.relationship('User', backref='lists', lazy=True) + # expires_at = db.Column(db.DateTime, nullable=True) + expires_at = db.Column(db.DateTime(timezone=True), nullable=True) + owner = db.relationship("User", backref="lists", lazy=True) is_archived = db.Column(db.Boolean, default=False) is_public = db.Column(db.Boolean, default=True) + + class Item(db.Model): id = db.Column(db.Integer, primary_key=True) - list_id = db.Column(db.Integer, db.ForeignKey('shopping_list.id')) + list_id = db.Column(db.Integer, db.ForeignKey("shopping_list.id")) name = db.Column(db.String(150), nullable=False) - added_at = db.Column(db.DateTime, default=datetime.utcnow) - added_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True) + # added_at = db.Column(db.DateTime, default=datetime.utcnow) + added_at = db.Column(db.DateTime, default=utcnow) + added_by = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=True) purchased = db.Column(db.Boolean, default=False) purchased_at = db.Column(db.DateTime, nullable=True) quantity = db.Column(db.Integer, default=1) note = db.Column(db.Text, nullable=True) + not_purchased = db.Column(db.Boolean, default=False) + not_purchased_reason = db.Column(db.Text, nullable=True) + position = db.Column(db.Integer, default=0) + class SuggestedProduct(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(150), unique=True, nullable=False) usage_count = db.Column(db.Integer, default=0) + + class Expense(db.Model): id = db.Column(db.Integer, primary_key=True) - list_id = db.Column(db.Integer, db.ForeignKey('shopping_list.id')) + list_id = db.Column(db.Integer, db.ForeignKey("shopping_list.id")) amount = db.Column(db.Float, nullable=False) added_at = db.Column(db.DateTime, default=datetime.utcnow) receipt_filename = db.Column(db.String(255), nullable=True) + list = db.relationship("ShoppingList", backref="expenses", lazy=True) + with app.app_context(): db.create_all() from werkzeug.security import generate_password_hash + admin = User.query.filter_by(is_admin=True).first() - username = app.config.get('DEFAULT_ADMIN_USERNAME', 'admin') - password = app.config.get('DEFAULT_ADMIN_PASSWORD', 'admin123') + username = app.config.get("DEFAULT_ADMIN_USERNAME", "admin") + password = app.config.get("DEFAULT_ADMIN_PASSWORD", "admin123") password_hash = generate_password_hash(password) if admin: - if admin.username != username or not check_password_hash(admin.password_hash, password): + if admin.username != username or not check_password_hash( + admin.password_hash, password + ): admin.username = username admin.password_hash = password_hash db.session.commit() @@ -113,68 +161,78 @@ with app.app_context(): db.session.add(admin) db.session.commit() -@static_bp.route('/static/js/') + +@static_bp.route("/static/js/") def serve_js(filename): - response = send_from_directory('static/js', filename) + response = send_from_directory("static/js", filename) response.cache_control.no_cache = True response.cache_control.no_store = True response.cache_control.must_revalidate = True - #response.expires = 0 - response.pragma = 'no-cache' - response.headers.pop('Content-Disposition', None) - response.headers.pop('Etag', None) + # response.expires = 0 + response.pragma = "no-cache" + response.headers.pop("Content-Disposition", None) + response.headers.pop("Etag", None) return response -@static_bp.route('/static/css/') + +@static_bp.route("/static/css/") def serve_css(filename): - response = send_from_directory('static/css', filename) - response.headers['Cache-Control'] = 'public, max-age=3600' - response.headers.pop('Content-Disposition', None) - response.headers.pop('Etag', None) + response = send_from_directory("static/css", filename) + response.headers["Cache-Control"] = "public, max-age=3600" + response.headers.pop("Content-Disposition", None) + response.headers.pop("Etag", None) return response -@static_bp.route('/static/lib/js/') + +@static_bp.route("/static/lib/js/") def serve_js_lib(filename): - response = send_from_directory('static/lib/js', filename) - response.headers['Cache-Control'] = 'public, max-age=604800' - response.headers.pop('Content-Disposition', None) - response.headers.pop('Etag', None) + response = send_from_directory("static/lib/js", filename) + response.headers["Cache-Control"] = "public, max-age=604800" + response.headers.pop("Content-Disposition", None) + response.headers.pop("Etag", None) return response + # CSS z cache na tydzień -@static_bp.route('/static/lib/css/') +@static_bp.route("/static/lib/css/") def serve_css_lib(filename): - response = send_from_directory('static/lib/css', filename) - response.headers['Cache-Control'] = 'public, max-age=604800' - response.headers.pop('Content-Disposition', None) - response.headers.pop('Etag', None) + response = send_from_directory("static/lib/css", filename) + response.headers["Cache-Control"] = "public, max-age=604800" + response.headers.pop("Content-Disposition", None) + response.headers.pop("Etag", None) return response + app.register_blueprint(static_bp) + def allowed_file(filename): - return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS + return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS + def get_list_details(list_id): shopping_list = ShoppingList.query.get_or_404(list_id) - items = Item.query.filter_by(list_id=list_id).all() + items = Item.query.filter_by(list_id=list_id).order_by(Item.position.asc()).all() receipt_pattern = f"list_{list_id}" - all_files = os.listdir(app.config['UPLOAD_FOLDER']) + all_files = os.listdir(app.config["UPLOAD_FOLDER"]) receipt_files = [f for f in all_files if receipt_pattern in f] expenses = Expense.query.filter_by(list_id=list_id).all() total_expense = sum(e.amount for e in expenses) return shopping_list, items, receipt_files, expenses, total_expense + def generate_share_token(length=8): """Generuje token do udostępniania. Parametr `length` to liczba znaków (domyślnie 4).""" return secrets.token_hex(length // 2) + def check_list_public(shopping_list): if not shopping_list.is_public: - flash('Ta lista nie jest publicznie dostępna', 'danger') + flash("Ta lista nie jest publicznie dostępna", "danger") return False return True + def enrich_list_data(l): items = Item.query.filter_by(list_id=l.id).all() l.total_count = len(items) @@ -183,33 +241,41 @@ def enrich_list_data(l): l.total_expense = sum(e.amount for e in expenses) return l + def save_resized_image(file, path: str, max_size=(2000, 2000)): img = Image.open(file) img.thumbnail(max_size) img.save(path) -def redirect_with_flash(message: str, category: str = 'info', endpoint: str = 'main_page'): + +def redirect_with_flash( + message: str, category: str = "info", endpoint: str = "main_page" +): flash(message, category) return redirect(url_for(endpoint)) + def admin_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.is_authenticated or not current_user.is_admin: - return redirect_with_flash('Brak uprawnień do tej sekcji.', 'danger') + return redirect_with_flash("Brak uprawnień do tej sekcji.", "danger") return f(*args, **kwargs) + return decorated_function + def get_progress(list_id): - items = Item.query.filter_by(list_id=list_id).all() + items = Item.query.filter_by(list_id=list_id).order_by(Item.position.asc()).all() total_count = len(items) purchased_count = len([i for i in items if i.purchased]) percent = (purchased_count / total_count * 100) if total_count > 0 else 0 return purchased_count, total_count, percent + def delete_receipts_for_list(list_id): receipt_pattern = f"list_{list_id}_" - upload_folder = app.config['UPLOAD_FOLDER'] + upload_folder = app.config["UPLOAD_FOLDER"] for filename in os.listdir(upload_folder): if filename.startswith(receipt_pattern): try: @@ -217,7 +283,8 @@ def delete_receipts_for_list(list_id): except Exception as e: print(f"Nie udało się usunąć pliku {filename}: {e}") -# zabezpieczenie logowani do systemy - błędne hasła + +# zabezpieczenie logowani do systemu - błędne hasła def is_ip_blocked(ip): now = time.time() attempts = failed_login_attempts[ip] @@ -225,6 +292,7 @@ def is_ip_blocked(ip): attempts.popleft() return len(attempts) >= MAX_ATTEMPTS + def register_failed_attempt(ip): now = time.time() attempts = failed_login_attempts[ip] @@ -232,37 +300,47 @@ def register_failed_attempt(ip): attempts.popleft() attempts.append(now) + def reset_failed_attempts(ip): failed_login_attempts[ip].clear() + def attempts_remaining(ip): attempts = failed_login_attempts[ip] return max(0, MAX_ATTEMPTS - len(attempts)) + + #################################################### + @login_manager.user_loader def load_user(user_id): - return User.query.get(int(user_id)) + # return User.query.get(int(user_id)) + return db.session.get(User, int(user_id)) + @app.context_processor def inject_time(): return dict(time=time) + @app.context_processor def inject_has_authorized_cookie(): - return {'has_authorized_cookie': 'authorized' in request.cookies} + return {"has_authorized_cookie": "authorized" in request.cookies} + @app.context_processor def inject_is_blocked(): ip = request.access_route[0] - return {'is_blocked': is_ip_blocked(ip)} + return {"is_blocked": is_ip_blocked(ip)} + @app.before_request def require_system_password(): endpoint = request.endpoint # Wyjątki: lib js/css zawsze przepuszczamy - if endpoint in ('static_bp.serve_js_lib', 'static_bp.serve_css_lib'): + if endpoint in ("static_bp.serve_js_lib", "static_bp.serve_css_lib"): return ip = request.access_route[0] @@ -272,46 +350,53 @@ def require_system_password(): if endpoint is None: return - if endpoint in ('system_auth', 'healthcheck'): + if endpoint in ("system_auth", "healthcheck"): return - if 'authorized' not in request.cookies and not endpoint.startswith('login') and endpoint != 'favicon': + if ( + "authorized" not in request.cookies + and not endpoint.startswith("login") + and endpoint != "favicon" + ): # Dla serve_js przepuszczamy tylko toasts.js - if endpoint == 'static_bp.serve_js': + if endpoint == "static_bp.serve_js": requested_file = request.view_args.get("filename", "") if requested_file == "toasts.js": return if requested_file.endswith(".js"): - return redirect(url_for('system_auth', next=request.url)) + return redirect(url_for("system_auth", next=request.url)) return # Blokujemy pozostałe static_bp - if endpoint.startswith('static_bp.'): + if endpoint.startswith("static_bp."): return - if request.path == '/': - return redirect(url_for('system_auth')) + if request.path == "/": + return redirect(url_for("system_auth")) from urllib.parse import urlparse, urlunparse + parsed = urlparse(request.url) fixed_url = urlunparse(parsed._replace(netloc=request.host)) - return redirect(url_for('system_auth', next=fixed_url)) + return redirect(url_for("system_auth", next=fixed_url)) -@app.template_filter('filemtime') +@app.template_filter("filemtime") def file_mtime_filter(path): try: t = os.path.getmtime(path) return datetime.fromtimestamp(t) except Exception: - return datetime.utcnow() + # return datetime.utcnow() + return datetime.now(timezone.utc) -@app.template_filter('filesizeformat') + +@app.template_filter("filesizeformat") def filesizeformat_filter(path): try: size = os.path.getsize(path) - for unit in ['B', 'KB', 'MB', 'GB']: + for unit in ["B", "KB", "MB", "GB"]: if size < 1024.0: return f"{size:.1f} {unit}" size /= 1024.0 @@ -319,203 +404,318 @@ def filesizeformat_filter(path): except Exception: return "N/A" + @app.errorhandler(404) def page_not_found(e): - return render_template( - 'errors.html', - code=404, - title="Strona nie znaleziona", - message="Ups! Podana strona nie istnieje lub została przeniesiona." - ), 404 + return ( + render_template( + "errors.html", + code=404, + title="Strona nie znaleziona", + message="Ups! Podana strona nie istnieje lub została przeniesiona.", + ), + 404, + ) + @app.errorhandler(403) def forbidden(e): - return render_template( - 'errors.html', - code=403, - title="Brak dostępu", - message="Nie masz uprawnień do wyświetlenia tej strony." - ), 403 + return ( + render_template( + "errors.html", + code=403, + title="Brak dostępu", + message="Nie masz uprawnień do wyświetlenia tej strony.", + ), + 403, + ) -@app.route('/favicon.ico') + +@app.route("/favicon.ico") def favicon_ico(): - return redirect(url_for('static', filename='favicon.svg')) + return redirect(url_for("static", filename="favicon.svg")) -@app.route('/favicon.svg') + +@app.route("/favicon.svg") def favicon(): - svg = ''' + svg = """ 🛒 - ''' - return svg, 200, {'Content-Type': 'image/svg+xml'} + """ + return svg, 200, {"Content-Type": "image/svg+xml"} -@app.route('/') + +@app.route("/") def main_page(): - now = datetime.utcnow() + # now = datetime.utcnow() + now = datetime.now(timezone.utc) if current_user.is_authenticated: - user_lists = ShoppingList.query.filter_by(owner_id=current_user.id, is_archived=False).filter( - (ShoppingList.expires_at == None) | (ShoppingList.expires_at > now) - ).order_by(ShoppingList.created_at.desc()).all() + user_lists = ( + ShoppingList.query.filter_by(owner_id=current_user.id, is_archived=False) + .filter((ShoppingList.expires_at == None) | (ShoppingList.expires_at > now)) + .order_by(ShoppingList.created_at.desc()) + .all() + ) - archived_lists = ShoppingList.query.filter_by(owner_id=current_user.id, is_archived=True).order_by(ShoppingList.created_at.desc()).all() + archived_lists = ( + ShoppingList.query.filter_by(owner_id=current_user.id, is_archived=True) + .order_by(ShoppingList.created_at.desc()) + .all() + ) - public_lists = ShoppingList.query.filter( - ShoppingList.is_public == True, - ShoppingList.owner_id != current_user.id, - ((ShoppingList.expires_at == None) | (ShoppingList.expires_at > now)), - ShoppingList.is_archived == False - ).order_by(ShoppingList.created_at.desc()).all() + public_lists = ( + ShoppingList.query.filter( + ShoppingList.is_public == True, + ShoppingList.owner_id != current_user.id, + ((ShoppingList.expires_at == None) | (ShoppingList.expires_at > now)), + ShoppingList.is_archived == False, + ) + .order_by(ShoppingList.created_at.desc()) + .all() + ) else: user_lists = [] archived_lists = [] - public_lists = ShoppingList.query.filter( - ShoppingList.is_public == True, - ((ShoppingList.expires_at == None) | (ShoppingList.expires_at > now)), - ShoppingList.is_archived == False - ).order_by(ShoppingList.created_at.desc()).all() + public_lists = ( + ShoppingList.query.filter( + ShoppingList.is_public == True, + ((ShoppingList.expires_at == None) | (ShoppingList.expires_at > now)), + ShoppingList.is_archived == False, + ) + .order_by(ShoppingList.created_at.desc()) + .all() + ) for l in user_lists + public_lists + archived_lists: enrich_list_data(l) - return render_template("main.html", user_lists=user_lists, public_lists=public_lists, archived_lists=archived_lists) + return render_template( + "main.html", + user_lists=user_lists, + public_lists=public_lists, + archived_lists=archived_lists, + ) -@app.route('/system-auth', methods=['GET', 'POST']) + +@app.route("/system-auth", methods=["GET", "POST"]) def system_auth(): - if current_user.is_authenticated or request.cookies.get('authorized') == AUTHORIZED_COOKIE_VALUE: - flash('Jesteś już zalogowany lub autoryzowany.', 'info') - return redirect(url_for('main_page')) + if ( + current_user.is_authenticated + or request.cookies.get("authorized") == AUTHORIZED_COOKIE_VALUE + ): + flash("Jesteś już zalogowany lub autoryzowany.", "info") + return redirect(url_for("main_page")) ip = request.access_route[0] - next_page = request.args.get('next') or url_for('main_page') + next_page = request.args.get("next") or url_for("main_page") if is_ip_blocked(ip): - flash('Przekroczono limit prób logowania. Dostęp zablokowany na 1 godzinę.', 'danger') - return render_template('system_auth.html'), 403 + flash( + "Przekroczono limit prób logowania. Dostęp zablokowany na 1 godzinę.", + "danger", + ) + return render_template("system_auth.html"), 403 - if request.method == 'POST': - if request.form['password'] == SYSTEM_PASSWORD: + if request.method == "POST": + if request.form["password"] == SYSTEM_PASSWORD: reset_failed_attempts(ip) resp = redirect(next_page) - max_age = app.config.get('AUTH_COOKIE_MAX_AGE', 86400) - resp.set_cookie('authorized', AUTHORIZED_COOKIE_VALUE, max_age=max_age) + max_age = app.config.get("AUTH_COOKIE_MAX_AGE", 86400) + resp.set_cookie("authorized", AUTHORIZED_COOKIE_VALUE, max_age=max_age) return resp else: register_failed_attempt(ip) if is_ip_blocked(ip): - flash('Przekroczono limit prób logowania. Dostęp zablokowany na 1 godzinę.', 'danger') - return render_template('system_auth.html'), 403 + flash( + "Przekroczono limit prób logowania. Dostęp zablokowany na 1 godzinę.", + "danger", + ) + return render_template("system_auth.html"), 403 remaining = attempts_remaining(ip) - flash(f'Nieprawidłowe hasło. Pozostało {remaining} prób.', 'warning') - return render_template('system_auth.html') + flash(f"Nieprawidłowe hasło. Pozostało {remaining} prób.", "warning") + return render_template("system_auth.html") -@app.route('/toggle_archive_list/') + +@app.route("/toggle_archive_list/") @login_required def toggle_archive_list(list_id): - l = ShoppingList.query.get_or_404(list_id) - if l.owner_id != current_user.id: - return redirect_with_flash('Nie masz uprawnień do tej listy', 'danger') + # l = ShoppingList.query.get_or_404(list_id) - archive = request.args.get('archive', 'true').lower() == 'true' + l = db.session.get(ShoppingList, list_id) + if l is None: + abort(404) + + if l.owner_id != current_user.id: + return redirect_with_flash("Nie masz uprawnień do tej listy", "danger") + + archive = request.args.get("archive", "true").lower() == "true" if archive: l.is_archived = True - flash(f'Lista „{l.title}” została zarchiwizowana.', 'success') + flash(f"Lista „{l.title}” została zarchiwizowana.", "success") else: l.is_archived = False - flash(f'Lista „{l.title}” została przywrócona.', 'success') + flash(f"Lista „{l.title}” została przywrócona.", "success") db.session.commit() - return redirect(url_for('main_page')) + return redirect(url_for("main_page")) -@app.route('/edit_my_list/', methods=['GET', 'POST']) + +@app.route("/edit_my_list/", methods=["GET", "POST"]) @login_required def edit_my_list(list_id): - l = ShoppingList.query.get_or_404(list_id) + l = db.session.get(ShoppingList, list_id) + if l is None: + abort(404) + if l.owner_id != current_user.id: - return redirect_with_flash('Nie masz uprawnień do tej listy', 'danger') + return redirect_with_flash("Nie masz uprawnień do tej listy", "danger") - if request.method == 'POST': - new_title = request.form.get('title') - if new_title and new_title.strip(): - l.title = new_title.strip() - db.session.commit() - flash('Zaktualizowano tytuł listy', 'success') - return redirect(url_for('main_page')) + if request.method == "POST": + new_title = request.form.get("title", "").strip() + is_public = "is_public" in request.form + is_temporary = "is_temporary" in request.form + is_archived = "is_archived" in request.form + + expires_date = request.form.get("expires_date") + expires_time = request.form.get("expires_time") + + # Walidacja tytułu + if not new_title: + flash("Podaj poprawny tytuł", "danger") + return redirect(url_for("edit_my_list", list_id=list_id)) + + l.title = new_title + l.is_public = is_public + l.is_temporary = is_temporary + l.is_archived = is_archived + + # Obsługa daty wygaśnięcia + if expires_date and expires_time: + try: + combined = f"{expires_date} {expires_time}" + expires_dt = datetime.strptime(combined, "%Y-%m-%d %H:%M") + l.expires_at = expires_dt.replace(tzinfo=timezone.utc) + except ValueError: + flash("Błędna data lub godzina wygasania", "danger") + return redirect(url_for("edit_my_list", list_id=list_id)) else: - flash('Podaj poprawny tytuł', 'danger') - return render_template('edit_my_list.html', list=l) + l.expires_at = None -@app.route('/toggle_visibility/', methods=['GET', 'POST']) + db.session.commit() + flash("Zaktualizowano dane listy", "success") + return redirect(url_for("main_page")) + + return render_template("edit_my_list.html", list=l) + + +@app.route("/delete_user_list/", methods=["POST"]) +@login_required +def delete_user_list(list_id): + l = db.session.get(ShoppingList, list_id) + if l is None or l.owner_id != current_user.id: + abort(403) + delete_receipts_for_list(list_id) + Item.query.filter_by(list_id=list_id).delete() + Expense.query.filter_by(list_id=list_id).delete() + db.session.delete(l) + db.session.commit() + flash("Lista została usunięta", "success") + return redirect(url_for("main_page")) + + +@app.route("/toggle_visibility/", methods=["GET", "POST"]) @login_required def toggle_visibility(list_id): - l = ShoppingList.query.get_or_404(list_id) + # l = ShoppingList.query.get_or_404(list_id) + + l = db.session.get(ShoppingList, list_id) + if l is None: + abort(404) + if l.owner_id != current_user.id: - if request.is_json or request.method == 'POST': - return {'error': 'Unauthorized'}, 403 - flash('Nie masz uprawnień do tej listy', 'danger') - return redirect(url_for('main_page')) + if request.is_json or request.method == "POST": + return {"error": "Unauthorized"}, 403 + flash("Nie masz uprawnień do tej listy", "danger") + return redirect(url_for("main_page")) l.is_public = not l.is_public db.session.commit() share_url = f"{request.url_root}share/{l.share_token}" - if request.is_json or request.method == 'POST': - return {'is_public': l.is_public, 'share_url': share_url} + if request.is_json or request.method == "POST": + return {"is_public": l.is_public, "share_url": share_url} if l.is_public: - flash('Lista została udostępniona publicznie', 'success') + flash("Lista została udostępniona publicznie", "success") else: - flash('Lista została ukryta przed gośćmi', 'info') + flash("Lista została ukryta przed gośćmi", "info") - return redirect(url_for('main_page')) + return redirect(url_for("main_page")) -from sqlalchemy import func -@app.route('/login', methods=['GET', 'POST']) +@app.route("/login", methods=["GET", "POST"]) def login(): - if request.method == 'POST': - username_input = request.form['username'].lower() + if request.method == "POST": + username_input = request.form["username"].lower() user = User.query.filter(func.lower(User.username) == username_input).first() - if user and check_password_hash(user.password_hash, request.form['password']): + if user and check_password_hash(user.password_hash, request.form["password"]): + session.permanent = True login_user(user) - flash('Zalogowano pomyślnie', 'success') - return redirect(url_for('main_page')) - flash('Nieprawidłowy login lub hasło', 'danger') - return render_template('login.html') + flash("Zalogowano pomyślnie", "success") + return redirect(url_for("main_page")) + flash("Nieprawidłowy login lub hasło", "danger") + return render_template("login.html") -@app.route('/logout') + +@app.route("/logout") @login_required def logout(): logout_user() - flash('Wylogowano pomyślnie', 'success') - return redirect(url_for('main_page')) + flash("Wylogowano pomyślnie", "success") + return redirect(url_for("main_page")) -@app.route('/create', methods=['POST']) + +@app.route("/create", methods=["POST"]) @login_required def create_list(): - title = request.form.get('title') - is_temporary = 'temporary' in request.form + title = request.form.get("title") + is_temporary = request.form.get("temporary") == "1" token = generate_share_token(8) - expires_at = datetime.utcnow() + timedelta(days=7) if is_temporary else None - new_list = ShoppingList(title=title, owner_id=current_user.id, is_temporary=is_temporary, share_token=token, expires_at=expires_at) + + # expires_at = datetime.utcnow() + timedelta(days=7) if is_temporary else None + expires_at = ( + datetime.now(timezone.utc) + timedelta(days=7) if is_temporary else None + ) + + new_list = ShoppingList( + title=title, + owner_id=current_user.id, + is_temporary=is_temporary, + share_token=token, + expires_at=expires_at, + ) db.session.add(new_list) db.session.commit() - flash('Utworzono nową listę', 'success') - return redirect(url_for('view_list', list_id=new_list.id)) + flash("Utworzono nową listę", "success") + return redirect(url_for("view_list", list_id=new_list.id)) -@app.route('/list/') + +@app.route("/list/") @login_required def view_list(list_id): - shopping_list, items, receipt_files, expenses, total_expense = get_list_details(list_id) + shopping_list, items, receipt_files, expenses, total_expense = get_list_details( + list_id + ) total_count = len(items) purchased_count = len([i for i in items if i.purchased]) percent = (purchased_count / total_count * 100) if total_count > 0 else 0 return render_template( - 'list.html', + "list.html", list=shopping_list, items=items, receipt_files=receipt_files, @@ -523,37 +723,114 @@ def view_list(list_id): purchased_count=purchased_count, percent=percent, expenses=expenses, - total_expense=total_expense + total_expense=total_expense, + is_share=False, ) -@app.route('/share/') -@app.route('/guest-list/') + +@app.route("/user_expenses") +@login_required +def user_expenses(): + from sqlalchemy.orm import joinedload + + expenses = ( + Expense.query.join(ShoppingList, Expense.list_id == ShoppingList.id) + .options(joinedload(Expense.list)) + .filter(ShoppingList.owner_id == current_user.id) + .order_by(Expense.added_at.desc()) + .all() + ) + + rows = [ + { + "title": e.list.title if e.list else "Nieznana", + "amount": e.amount, + "added_at": e.added_at, + } + for e in expenses + ] + + return render_template("user_expenses.html", expense_table=rows) + + +@app.route("/user/expenses_data") +@login_required +def user_expenses_data(): + range_type = request.args.get("range", "monthly") + start_date = request.args.get("start_date") + end_date = request.args.get("end_date") + + query = Expense.query.join(ShoppingList, Expense.list_id == ShoppingList.id).filter( + ShoppingList.owner_id == current_user.id + ) + + if start_date and end_date: + try: + start = datetime.strptime(start_date, "%Y-%m-%d") + end = datetime.strptime(end_date, "%Y-%m-%d") + timedelta(days=1) + query = query.filter(Expense.timestamp >= start, Expense.timestamp < end) + except ValueError: + return jsonify({"error": "Błędne daty"}), 400 + + expenses = query.all() + + grouped = defaultdict(float) + for e in expenses: + + # ts = e.added_at or datetime.utcnow() + ts = e.added_at or datetime.now(timezone.utc) + + if range_type == "monthly": + key = ts.strftime("%Y-%m") + elif range_type == "quarterly": + key = f"{ts.year}-Q{((ts.month - 1) // 3) + 1}" + elif range_type == "halfyearly": + key = f"{ts.year}-H{1 if ts.month <= 6 else 2}" + elif range_type == "yearly": + key = str(ts.year) + else: + key = ts.strftime("%Y-%m-%d") + grouped[key] += e.amount + + labels = sorted(grouped) + data = [round(grouped[label], 2) for label in labels] + return jsonify({"labels": labels, "expenses": data}) + + +@app.route("/share/") +@app.route("/guest-list/") def shared_list(token=None, list_id=None): if token: shopping_list = ShoppingList.query.filter_by(share_token=token).first_or_404() if not check_list_public(shopping_list): - return redirect(url_for('main_page')) + return redirect(url_for("main_page")) list_id = shopping_list.id - shopping_list, items, receipt_files, expenses, total_expense = get_list_details(list_id) + shopping_list, items, receipt_files, expenses, total_expense = get_list_details( + list_id + ) return render_template( - 'list_share.html', + "list_share.html", list=shopping_list, items=items, receipt_files=receipt_files, expenses=expenses, - total_expense=total_expense + total_expense=total_expense, + is_share=True, ) -@app.route('/copy/') + +@app.route("/copy/") @login_required def copy_list(list_id): original = ShoppingList.query.get_or_404(list_id) token = generate_share_token(8) - new_list = ShoppingList(title=original.title + ' (Kopia)', owner_id=current_user.id, share_token=token) + new_list = ShoppingList( + title=original.title + " (Kopia)", owner_id=current_user.id, share_token=token + ) db.session.add(new_list) db.session.commit() original_items = Item.query.filter_by(list_id=original.id).all() @@ -561,27 +838,37 @@ def copy_list(list_id): copy_item = Item(list_id=new_list.id, name=item.name) db.session.add(copy_item) db.session.commit() - flash('Skopiowano listę', 'success') - return redirect(url_for('view_list', list_id=new_list.id)) + flash("Skopiowano listę", "success") + return redirect(url_for("view_list", list_id=new_list.id)) -@app.route('/suggest_products') + +@app.route("/suggest_products") def suggest_products(): - query = request.args.get('q', '') + query = request.args.get("q", "") suggestions = [] if query: - suggestions = SuggestedProduct.query.filter(SuggestedProduct.name.ilike(f'%{query}%')).limit(5).all() - return {'suggestions': [s.name for s in suggestions]} + suggestions = ( + SuggestedProduct.query.filter(SuggestedProduct.name.ilike(f"%{query}%")) + .limit(5) + .all() + ) + return {"suggestions": [s.name for s in suggestions]} -@app.route('/all_products') + +@app.route("/all_products") def all_products(): - query = request.args.get('q', '') + query = request.args.get("q", "") top_products_query = SuggestedProduct.query if query: - top_products_query = top_products_query.filter(SuggestedProduct.name.ilike(f'%{query}%')) + top_products_query = top_products_query.filter( + SuggestedProduct.name.ilike(f"%{query}%") + ) top_products = ( - top_products_query - .order_by(SuggestedProduct.usage_count.desc(), SuggestedProduct.name.asc()) + top_products_query.order_by( + SuggestedProduct.usage_count.desc(), SuggestedProduct.name.asc() + ) + .distinct(SuggestedProduct.name) .limit(20) .all() ) @@ -589,21 +876,25 @@ def all_products(): top_names = [s.name for s in top_products] rest_query = SuggestedProduct.query if query: - rest_query = rest_query.filter(SuggestedProduct.name.ilike(f'%{query}%')) + rest_query = rest_query.filter(SuggestedProduct.name.ilike(f"%{query}%")) if top_names: rest_query = rest_query.filter(~SuggestedProduct.name.in_(top_names)) - rest_products = ( - rest_query - .order_by(SuggestedProduct.name.asc()) - .limit(200) - .all() - ) + rest_products = rest_query.order_by(SuggestedProduct.name.asc()).limit(200).all() all_names = top_names + [s.name for s in rest_products] - return {'allproducts': all_names} + seen = set() + unique_names = [] + for name in all_names: + name_lower = name.strip().lower() + if name_lower not in seen: + unique_names.append(name) + seen.add(name_lower) + + return {"allproducts": unique_names} + """ @app.route('/upload_receipt/', methods=['POST']) def upload_receipt(list_id): @@ -629,67 +920,98 @@ def upload_receipt(list_id): flash('Niedozwolony format pliku', 'danger') return redirect(request.referrer) """ -@app.route('/upload_receipt/', methods=['POST']) + +@app.route("/upload_receipt/", methods=["POST"]) def upload_receipt(list_id): - if 'receipt' not in request.files: - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - return jsonify({'success': False, 'message': 'Brak pliku'}), 400 - flash('Brak pliku', 'danger') + if "receipt" not in request.files: + if ( + request.is_json + or request.headers.get("X-Requested-With") == "XMLHttpRequest" + ): + return jsonify({"success": False, "message": "Brak pliku"}), 400 + flash("Brak pliku", "danger") return redirect(request.referrer) - file = request.files['receipt'] + file = request.files["receipt"] - if file.filename == '': - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - return jsonify({'success': False, 'message': 'Nie wybrano pliku'}), 400 - flash('Nie wybrano pliku', 'danger') + if file.filename == "": + if ( + request.is_json + or request.headers.get("X-Requested-With") == "XMLHttpRequest" + ): + return jsonify({"success": False, "message": "Nie wybrano pliku"}), 400 + flash("Nie wybrano pliku", "danger") return redirect(request.referrer) if file and allowed_file(file.filename): filename = secure_filename(file.filename) full_filename = f"list_{list_id}_{filename}" - file_path = os.path.join(app.config['UPLOAD_FOLDER'], full_filename) + file_path = os.path.join(app.config["UPLOAD_FOLDER"], full_filename) save_resized_image(file, file_path) - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - url = url_for('uploaded_file', filename=full_filename) + if ( + request.is_json + or request.headers.get("X-Requested-With") == "XMLHttpRequest" + ): + url = url_for("uploaded_file", filename=full_filename) - socketio.emit('receipt_added', {'url': url}, to=str(list_id)) + socketio.emit("receipt_added", {"url": url}, to=str(list_id)) - return jsonify({'success': True, 'url': url}) + return jsonify({"success": True, "url": url}) - flash('Wgrano paragon', 'success') + flash("Wgrano paragon", "success") return redirect(request.referrer) - if request.is_json or request.headers.get('X-Requested-With') == 'XMLHttpRequest': - return jsonify({'success': False, 'message': 'Niedozwolony format pliku'}), 400 - flash('Niedozwolony format pliku', 'danger') + if request.is_json or request.headers.get("X-Requested-With") == "XMLHttpRequest": + return jsonify({"success": False, "message": "Niedozwolony format pliku"}), 400 + flash("Niedozwolony format pliku", "danger") return redirect(request.referrer) -@app.route('/uploads/') +@app.route("/uploads/") def uploaded_file(filename): - response = send_from_directory(app.config['UPLOAD_FOLDER'], filename) - response.headers['Cache-Control'] = 'public, max-age=2592000, immutable' - response.headers.pop('Pragma', None) - response.headers.pop('Content-Disposition', None) + response = send_from_directory(app.config["UPLOAD_FOLDER"], filename) + response.headers["Cache-Control"] = "public, max-age=2592000, immutable" + response.headers.pop("Pragma", None) + response.headers.pop("Content-Disposition", None) mime, _ = mimetypes.guess_type(filename) if mime: - response.headers['Content-Type'] = mime + response.headers["Content-Type"] = mime return response -@app.route('/admin') + +@app.route("/reorder_items", methods=["POST"]) +@login_required +def reorder_items(): + data = request.get_json() + list_id = data.get("list_id") + order = data.get("order") + + for index, item_id in enumerate(order): + item = db.session.get(Item, item_id) + if item and item.list_id == list_id: + item.position = index + db.session.commit() + + socketio.emit( + "items_reordered", {"list_id": list_id, "order": order}, to=str(list_id) + ) + + return jsonify(success=True) + + +@app.route("/admin") @login_required @admin_required def admin_panel(): - - now = datetime.utcnow() + now = datetime.now(timezone.utc) + user_count = User.query.count() list_count = ShoppingList.query.count() item_count = Item.query.count() all_lists = ShoppingList.query.options(db.joinedload(ShoppingList.owner)).all() - all_files = os.listdir(app.config['UPLOAD_FOLDER']) + all_files = os.listdir(app.config["UPLOAD_FOLDER"]) enriched_lists = [] for l in all_lists: @@ -698,23 +1020,35 @@ def admin_panel(): total_count = l.total_count purchased_count = l.purchased_count percent = (purchased_count / total_count * 100) if total_count > 0 else 0 - comments_count = len([i for i in items if i.note and i.note.strip() != '']) + comments_count = len([i for i in items if i.note and i.note.strip() != ""]) receipt_pattern = f"list_{l.id}" receipt_files = [f for f in all_files if receipt_pattern in f] - enriched_lists.append({ - 'list': l, - 'total_count': total_count, - 'purchased_count': purchased_count, - 'percent': round(percent), - 'comments_count': comments_count, - 'receipts_count': len(receipt_files), - 'total_expense': l.total_expense - }) + # obliczenie czy wygasła + if l.is_temporary and l.expires_at: + expires_at = l.expires_at + if expires_at.tzinfo is None: + expires_at = expires_at.replace(tzinfo=timezone.utc) + is_expired = expires_at < now + else: + is_expired = False + + enriched_lists.append( + { + "list": l, + "total_count": total_count, + "purchased_count": purchased_count, + "percent": round(percent), + "comments_count": comments_count, + "receipts_count": len(receipt_files), + "total_expense": l.total_expense, + "expired": is_expired, + } + ) top_products = ( - db.session.query(Item.name, func.count(Item.id).label('count')) - .filter(Item.purchased == True) + db.session.query(Item.name, func.count(Item.id).label("count")) + .filter(Item.purchased.is_(True)) .group_by(Item.name) .order_by(func.count(Item.id).desc()) .limit(5) @@ -724,26 +1058,30 @@ def admin_panel(): purchased_items_count = Item.query.filter_by(purchased=True).count() total_expense_sum = db.session.query(func.sum(Expense.amount)).scalar() or 0 - current_year = datetime.utcnow().year + current_time = datetime.now(timezone.utc) + current_year = current_time.year + current_month = current_time.month + year_expense_sum = ( db.session.query(func.sum(Expense.amount)) - .filter(extract('year', Expense.added_at) == current_year) - .scalar() or 0 + .filter(extract("year", Expense.added_at) == current_year) + .scalar() + or 0 ) - current_month = datetime.utcnow().month month_expense_sum = ( db.session.query(func.sum(Expense.amount)) - .filter(extract('year', Expense.added_at) == current_year) - .filter(extract('month', Expense.added_at) == current_month) - .scalar() or 0 + .filter(extract("year", Expense.added_at) == current_year) + .filter(extract("month", Expense.added_at) == current_month) + .scalar() + or 0 ) process = psutil.Process(os.getpid()) app_mem = process.memory_info().rss // (1024 * 1024) # MB return render_template( - 'admin/admin_panel.html', + "admin/admin_panel.html", user_count=user_count, list_count=list_count, item_count=item_count, @@ -760,43 +1098,45 @@ def admin_panel(): ) -@app.route('/admin/delete_list/') +@app.route("/admin/delete_list/") @login_required @admin_required def delete_list(list_id): - + delete_receipts_for_list(list_id) list_to_delete = ShoppingList.query.get_or_404(list_id) Item.query.filter_by(list_id=list_to_delete.id).delete() Expense.query.filter_by(list_id=list_to_delete.id).delete() db.session.delete(list_to_delete) db.session.commit() - flash(f'Usunięto listę: {list_to_delete.title}', 'success') - return redirect(url_for('admin_panel')) + flash(f"Usunięto listę: {list_to_delete.title}", "success") + return redirect(url_for("admin_panel")) -@app.route('/admin/add_user', methods=['POST']) + +@app.route("/admin/add_user", methods=["POST"]) @login_required @admin_required def add_user(): - username = request.form['username'].lower() - password = request.form['password'] + username = request.form["username"].lower() + password = request.form["password"] if not username or not password: - flash('Wypełnij wszystkie pola', 'danger') - return redirect(url_for('list_users')) + flash("Wypełnij wszystkie pola", "danger") + return redirect(url_for("list_users")) if User.query.filter(func.lower(User.username) == username).first(): - flash('Użytkownik o takiej nazwie już istnieje', 'warning') - return redirect(url_for('list_users')) + flash("Użytkownik o takiej nazwie już istnieje", "warning") + return redirect(url_for("list_users")) hashed_password = generate_password_hash(password) new_user = User(username=username, password_hash=hashed_password) db.session.add(new_user) db.session.commit() - flash('Dodano nowego użytkownika', 'success') - return redirect(url_for('list_users')) + flash("Dodano nowego użytkownika", "success") + return redirect(url_for("list_users")) -@app.route('/admin/users') + +@app.route("/admin/users") @login_required @admin_required def list_users(): @@ -805,25 +1145,34 @@ def list_users(): list_count = ShoppingList.query.count() item_count = Item.query.count() activity_log = ["Utworzono listę: Zakupy weekendowe", "Dodano produkt: Mleko"] - return render_template('admin/user_management.html', users=users, user_count=user_count, list_count=list_count, item_count=item_count, activity_log=activity_log) + return render_template( + "admin/user_management.html", + users=users, + user_count=user_count, + list_count=list_count, + item_count=item_count, + activity_log=activity_log, + ) -@app.route('/admin/change_password/', methods=['POST']) + +@app.route("/admin/change_password/", methods=["POST"]) @login_required @admin_required def reset_password(user_id): user = User.query.get_or_404(user_id) - new_password = request.form['password'] + new_password = request.form["password"] if not new_password: - flash('Podaj nowe hasło', 'danger') - return redirect(url_for('list_users')) + flash("Podaj nowe hasło", "danger") + return redirect(url_for("list_users")) user.password_hash = generate_password_hash(new_password) db.session.commit() - flash(f'Hasło dla użytkownika {user.username} zostało zaktualizowane', 'success') - return redirect(url_for('list_users')) + flash(f"Hasło dla użytkownika {user.username} zostało zaktualizowane", "success") + return redirect(url_for("list_users")) -@app.route('/admin/delete_user/') + +@app.route("/admin/delete_user/") @login_required @admin_required def delete_user(user_id): @@ -832,19 +1181,20 @@ def delete_user(user_id): if user.is_admin: admin_count = User.query.filter_by(is_admin=True).count() if admin_count <= 1: - flash('Nie można usunąć ostatniego administratora.', 'danger') - return redirect(url_for('list_users')) + flash("Nie można usunąć ostatniego administratora.", "danger") + return redirect(url_for("list_users")) db.session.delete(user) db.session.commit() - flash('Użytkownik usunięty', 'success') - return redirect(url_for('list_users')) + flash("Użytkownik usunięty", "success") + return redirect(url_for("list_users")) -@app.route('/admin/receipts/') + +@app.route("/admin/receipts/") @login_required @admin_required def admin_receipts(id): - all_files = os.listdir(app.config['UPLOAD_FOLDER']) + all_files = os.listdir(app.config["UPLOAD_FOLDER"]) image_files = [f for f in all_files if allowed_file(f)] if id == "all": @@ -856,97 +1206,115 @@ def admin_receipts(id): filtered_files = [f for f in image_files if f.startswith(receipt_prefix)] except ValueError: flash("Nieprawidłowe ID listy.", "danger") - return redirect(url_for('admin_panel')) + return redirect(url_for("admin_panel")) return render_template( - 'admin/receipts.html', + "admin/receipts.html", image_files=filtered_files, - upload_folder=app.config['UPLOAD_FOLDER'] + upload_folder=app.config["UPLOAD_FOLDER"], ) -@app.route('/admin/delete_receipt/') + +@app.route("/admin/delete_receipt/") @login_required @admin_required def delete_receipt(filename): - file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) + file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) if os.path.exists(file_path): os.remove(file_path) - flash('Plik usunięty', 'success') + flash("Plik usunięty", "success") else: - flash('Plik nie istnieje', 'danger') - - next_url = request.args.get('next') + flash("Plik nie istnieje", "danger") + + next_url = request.args.get("next") if next_url: return redirect(next_url) - return redirect(url_for('admin_receipts')) + return redirect(url_for("admin_receipts")) -@app.route('/admin/delete_selected_lists', methods=['POST']) + +@app.route("/admin/delete_selected_lists", methods=["POST"]) @login_required @admin_required -def delete_selected_lists(): - ids = request.form.getlist('list_ids') +def delete_selected_lists(): + ids = request.form.getlist("list_ids") for list_id in ids: - lst = ShoppingList.query.get(int(list_id)) + + # lst = ShoppingList.query.get(int(list_id)) + lst = db.session.get(ShoppingList, int(list_id)) + if lst: delete_receipts_for_list(lst.id) Item.query.filter_by(list_id=lst.id).delete() Expense.query.filter_by(list_id=lst.id).delete() db.session.delete(lst) db.session.commit() - flash('Usunięto wybrane listy', 'success') - return redirect(url_for('admin_panel')) + flash("Usunięto wybrane listy", "success") + return redirect(url_for("admin_panel")) -@app.route('/admin/delete_all_items') -@login_required -@admin_required -def delete_all_items(): - Item.query.delete() - db.session.commit() - flash('Usunięto wszystkie produkty', 'success') - return redirect(url_for('admin_panel')) -@app.route('/admin/edit_list/', methods=['GET', 'POST']) +@app.route("/admin/edit_list/", methods=["GET", "POST"]) @login_required @admin_required def edit_list(list_id): - l = ShoppingList.query.get_or_404(list_id) + l = db.session.get(ShoppingList, list_id) + if l is None: + abort(404) + expenses = Expense.query.filter_by(list_id=list_id).all() total_expense = sum(e.amount for e in expenses) users = User.query.all() - items = Item.query.filter_by(list_id=list_id).order_by(Item.id.desc()).all() + items = ( + db.session.query(Item).filter_by(list_id=list_id).order_by(Item.id.desc()).all() + ) - # Pobranie listy plików paragonów receipt_pattern = f"list_{list_id}_" - all_files = os.listdir(app.config['UPLOAD_FOLDER']) + all_files = os.listdir(app.config["UPLOAD_FOLDER"]) receipts = [f for f in all_files if f.startswith(receipt_pattern)] - if request.method == 'POST': - action = request.form.get('action') + if request.method == "POST": + action = request.form.get("action") - if action == 'save': - new_title = request.form.get('title', '').strip() - new_amount_str = request.form.get('amount') - is_archived = 'archived' in request.form - is_public = 'public' in request.form - new_owner_id = request.form.get('owner_id') + if action == "save": + new_title = request.form.get("title", "").strip() + new_amount_str = request.form.get("amount") + is_archived = "archived" in request.form + is_public = "public" in request.form + is_temporary = "temporary" in request.form + new_owner_id = request.form.get("owner_id") + + expires_date = request.form.get("expires_date") + expires_time = request.form.get("expires_time") if new_title: l.title = new_title l.is_archived = is_archived l.is_public = is_public + l.is_temporary = is_temporary + + if expires_date and expires_time: + try: + combined_str = f"{expires_date} {expires_time}" + dt = datetime.strptime(combined_str, "%Y-%m-%d %H:%M") + l.expires_at = dt.replace(tzinfo=timezone.utc) + except ValueError: + flash("Niepoprawna data lub godzina wygasania", "danger") + return redirect(url_for("edit_list", list_id=list_id)) + else: + l.expires_at = None if new_owner_id: try: new_owner_id_int = int(new_owner_id) - if User.query.get(new_owner_id_int): + user_obj = db.session.get(User, new_owner_id_int) + if user_obj: l.owner_id = new_owner_id_int else: - flash('Wybrany użytkownik nie istnieje', 'danger') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Wybrany użytkownik nie istnieje", "danger") + return redirect(url_for("edit_list", list_id=list_id)) except ValueError: - flash('Niepoprawny ID użytkownika', 'danger') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Niepoprawny ID użytkownika", "danger") + return redirect(url_for("edit_list", list_id=list_id)) if new_amount_str: try: @@ -954,80 +1322,114 @@ def edit_list(list_id): for expense in expenses: db.session.delete(expense) db.session.commit() - new_expense = Expense(list_id=list_id, amount=new_amount) - db.session.add(new_expense) - db.session.commit() + db.session.add(Expense(list_id=list_id, amount=new_amount)) except ValueError: - flash('Niepoprawna kwota', 'danger') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Niepoprawna kwota", "danger") + return redirect(url_for("edit_list", list_id=list_id)) + db.session.add(l) db.session.commit() - flash('Zapisano zmiany listy', 'success') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Zapisano zmiany listy", "success") + return redirect(url_for("edit_list", list_id=list_id)) + + elif action == "add_item": + item_name = request.form.get("item_name", "").strip() + quantity_str = request.form.get("quantity", "1") - elif action == 'add_item': - item_name = request.form.get('item_name', '').strip() - quantity_str = request.form.get('quantity', '1') if not item_name: - flash('Podaj nazwę produktu', 'danger') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Podaj nazwę produktu", "danger") + return redirect(url_for("edit_list", list_id=list_id)) try: - quantity = int(quantity_str) - if quantity < 1: - quantity = 1 + quantity = max(1, int(quantity_str)) except ValueError: quantity = 1 - new_item = Item(list_id=list_id, name=item_name, quantity=quantity, added_by=current_user.id) - db.session.add(new_item) + db.session.add( + Item( + list_id=list_id, + name=item_name, + quantity=quantity, + added_by=current_user.id, + ) + ) - if not SuggestedProduct.query.filter(func.lower(SuggestedProduct.name) == item_name.lower()).first(): + exists = ( + db.session.query(SuggestedProduct) + .filter(func.lower(SuggestedProduct.name) == item_name.lower()) + .first() + ) + + if not exists: db.session.add(SuggestedProduct(name=item_name)) db.session.commit() - flash('Dodano produkt', 'success') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Dodano produkt", "success") + return redirect(url_for("edit_list", list_id=list_id)) - elif action == 'delete_item': - item_id = request.form.get('item_id') - item = Item.query.get(item_id) + elif action == "delete_item": + item = db.session.get(Item, request.form.get("item_id")) if item and item.list_id == list_id: db.session.delete(item) db.session.commit() - flash('Usunięto produkt', 'success') + flash("Usunięto produkt", "success") else: - flash('Nie znaleziono produktu', 'danger') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Nie znaleziono produktu", "danger") + return redirect(url_for("edit_list", list_id=list_id)) - elif action == 'toggle_purchased': - item_id = request.form.get('item_id') - item = Item.query.get(item_id) + elif action == "toggle_purchased": + item = db.session.get(Item, request.form.get("item_id")) if item and item.list_id == list_id: item.purchased = not item.purchased db.session.commit() - flash('Zmieniono status oznaczenia produktu', 'success') + flash("Zmieniono status oznaczenia produktu", "success") else: - flash('Nie znaleziono produktu', 'danger') - return redirect(url_for('edit_list', list_id=list_id)) + flash("Nie znaleziono produktu", "danger") + return redirect(url_for("edit_list", list_id=list_id)) + + elif action == "mark_not_purchased": + item = db.session.get(Item, request.form.get("item_id")) + if item and item.list_id == list_id: + item.not_purchased = True + item.purchased = False + item.purchased_at = None + db.session.commit() + flash("Oznaczono produkt jako niekupione", "success") + else: + flash("Nie znaleziono produktu", "danger") + return redirect(url_for("edit_list", list_id=list_id)) + + elif action == "unmark_not_purchased": + item = db.session.get(Item, request.form.get("item_id")) + if item and item.list_id == list_id: + item.not_purchased = False + item.not_purchased_reason = None + item.purchased = False + item.purchased_at = None + db.session.commit() + flash("Przywrócono produkt do listy", "success") + else: + flash("Nie znaleziono produktu", "danger") + return redirect(url_for("edit_list", list_id=list_id)) - # Przekazanie receipts do szablonu return render_template( - 'admin/edit_list.html', + "admin/edit_list.html", list=l, total_expense=total_expense, users=users, items=items, receipts=receipts, - upload_folder=app.config['UPLOAD_FOLDER'] + upload_folder=app.config["UPLOAD_FOLDER"], ) -@app.route('/admin/products') + +@app.route("/admin/products") @login_required @admin_required def list_products(): items = Item.query.order_by(Item.id.desc()).all() - users = User.query.all() + # users = User.query.all() + users = db.session.query(User).all() users_dict = {user.id: user.username for user in users} # Stabilne sortowanie sugestii @@ -1035,68 +1437,85 @@ def list_products(): suggestions_dict = {s.name.lower(): s for s in suggestions} return render_template( - 'admin/list_products.html', + "admin/list_products.html", items=items, users_dict=users_dict, - suggestions_dict=suggestions_dict + suggestions_dict=suggestions_dict, ) -@app.route('/admin/sync_suggestion/', methods=['POST']) + +@app.route("/admin/sync_suggestion/", methods=["POST"]) @login_required def sync_suggestion_ajax(item_id): if not current_user.is_admin: - return jsonify({'success': False, 'message': 'Brak uprawnień'}), 403 + return jsonify({"success": False, "message": "Brak uprawnień"}), 403 item = Item.query.get_or_404(item_id) - existing = SuggestedProduct.query.filter(func.lower(SuggestedProduct.name) == item.name.lower()).first() + existing = SuggestedProduct.query.filter( + func.lower(SuggestedProduct.name) == item.name.lower() + ).first() if not existing: new_suggestion = SuggestedProduct(name=item.name) db.session.add(new_suggestion) db.session.commit() - return jsonify({'success': True, 'message': f'Utworzono sugestię dla produktu: {item.name}'}) + return jsonify( + { + "success": True, + "message": f"Utworzono sugestię dla produktu: {item.name}", + } + ) else: - return jsonify({'success': True, 'message': f'Sugestia dla produktu „{item.name}” już istnieje.'}) + return jsonify( + { + "success": True, + "message": f"Sugestia dla produktu „{item.name}” już istnieje.", + } + ) -@app.route('/admin/delete_suggestion/', methods=['POST']) + +@app.route("/admin/delete_suggestion/", methods=["POST"]) @login_required def delete_suggestion_ajax(suggestion_id): if not current_user.is_admin: - return jsonify({'success': False, 'message': 'Brak uprawnień'}), 403 + return jsonify({"success": False, "message": "Brak uprawnień"}), 403 suggestion = SuggestedProduct.query.get_or_404(suggestion_id) db.session.delete(suggestion) db.session.commit() - return jsonify({'success': True, 'message': 'Sugestia została usunięta.'}) + return jsonify({"success": True, "message": "Sugestia została usunięta."}) -@app.route('/admin/expenses_data') + +@app.route("/admin/expenses_data") @login_required def admin_expenses_data(): if not current_user.is_admin: - return jsonify({'error': 'Brak uprawnień'}), 403 + return jsonify({"error": "Brak uprawnień"}), 403 - range_type = request.args.get('range', 'monthly') - start_date_str = request.args.get('start_date') - end_date_str = request.args.get('end_date') - now = datetime.utcnow() + range_type = request.args.get("range", "monthly") + start_date_str = request.args.get("start_date") + end_date_str = request.args.get("end_date") + + # now = datetime.utcnow() + now = datetime.now(timezone.utc) labels = [] expenses = [] if start_date_str and end_date_str: - start_date = datetime.strptime(start_date_str, '%Y-%m-%d') - end_date = datetime.strptime(end_date_str, '%Y-%m-%d') + start_date = datetime.strptime(start_date_str, "%Y-%m-%d") + end_date = datetime.strptime(end_date_str, "%Y-%m-%d") expenses_query = ( db.session.query( - extract('year', Expense.added_at).label('year'), - extract('month', Expense.added_at).label('month'), - func.sum(Expense.amount).label('total') + extract("year", Expense.added_at).label("year"), + extract("month", Expense.added_at).label("month"), + func.sum(Expense.amount).label("total"), ) .filter(Expense.added_at >= start_date, Expense.added_at <= end_date) - .group_by('year', 'month') - .order_by('year', 'month') + .group_by("year", "month") + .order_by("year", "month") .all() ) @@ -1105,138 +1524,163 @@ def admin_expenses_data(): labels.append(label) expenses.append(round(row.total, 2)) - response = make_response(jsonify({'labels': labels, 'expenses': expenses})) - response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0" + response = make_response(jsonify({"labels": labels, "expenses": expenses})) + response.headers["Cache-Control"] = ( + "no-store, no-cache, must-revalidate, max-age=0" + ) return response - if range_type == 'monthly': + if range_type == "monthly": for i in range(11, -1, -1): - year = (now - timedelta(days=i*30)).year - month = (now - timedelta(days=i*30)).month + year = (now - timedelta(days=i * 30)).year + month = (now - timedelta(days=i * 30)).month label = f"{month:02d}/{year}" labels.append(label) month_sum = ( db.session.query(func.sum(Expense.amount)) - .filter(extract('year', Expense.added_at) == year) - .filter(extract('month', Expense.added_at) == month) - .scalar() or 0 + .filter(extract("year", Expense.added_at) == year) + .filter(extract("month", Expense.added_at) == month) + .scalar() + or 0 ) expenses.append(round(month_sum, 2)) - elif range_type == 'quarterly': + elif range_type == "quarterly": for i in range(3, -1, -1): - quarter_start = now - timedelta(days=i*90) + quarter_start = now - timedelta(days=i * 90) year = quarter_start.year quarter = (quarter_start.month - 1) // 3 + 1 label = f"Q{quarter}/{year}" quarter_sum = ( db.session.query(func.sum(Expense.amount)) - .filter(extract('year', Expense.added_at) == year) - .filter((extract('month', Expense.added_at) - 1)//3 + 1 == quarter) - .scalar() or 0 + .filter(extract("year", Expense.added_at) == year) + .filter((extract("month", Expense.added_at) - 1) // 3 + 1 == quarter) + .scalar() + or 0 ) labels.append(label) expenses.append(round(quarter_sum, 2)) - elif range_type == 'halfyearly': + elif range_type == "halfyearly": for i in range(1, -1, -1): - half_start = now - timedelta(days=i*180) + half_start = now - timedelta(days=i * 180) year = half_start.year half = 1 if half_start.month <= 6 else 2 label = f"H{half}/{year}" half_sum = ( db.session.query(func.sum(Expense.amount)) - .filter(extract('year', Expense.added_at) == year) + .filter(extract("year", Expense.added_at) == year) .filter( - (extract('month', Expense.added_at) <= 6) if half == 1 else (extract('month', Expense.added_at) > 6) + (extract("month", Expense.added_at) <= 6) + if half == 1 + else (extract("month", Expense.added_at) > 6) ) - .scalar() or 0 + .scalar() + or 0 ) labels.append(label) expenses.append(round(half_sum, 2)) - elif range_type == 'yearly': + elif range_type == "yearly": for i in range(4, -1, -1): year = now.year - i label = str(year) year_sum = ( db.session.query(func.sum(Expense.amount)) - .filter(extract('year', Expense.added_at) == year) - .scalar() or 0 + .filter(extract("year", Expense.added_at) == year) + .scalar() + or 0 ) labels.append(label) expenses.append(round(year_sum, 2)) - response = make_response(jsonify({'labels': labels, 'expenses': expenses})) + response = make_response(jsonify({"labels": labels, "expenses": expenses})) response.headers["Cache-Control"] = "no-store, no-cache" return response -@app.route('/admin/promote_user/') + +@app.route("/admin/promote_user/") @login_required @admin_required def promote_user(user_id): user = User.query.get_or_404(user_id) user.is_admin = True db.session.commit() - flash(f'Użytkownik {user.username} został ustawiony jako admin.', 'success') - return redirect(url_for('list_users')) + flash(f"Użytkownik {user.username} został ustawiony jako admin.", "success") + return redirect(url_for("list_users")) -@app.route('/admin/demote_user/') + +@app.route("/admin/demote_user/") @login_required @admin_required def demote_user(user_id): user = User.query.get_or_404(user_id) - + if user.id == current_user.id: - flash('Nie możesz zdegradować samego siebie!', 'danger') - return redirect(url_for('list_users')) + flash("Nie możesz zdegradować samego siebie!", "danger") + return redirect(url_for("list_users")) admin_count = User.query.filter_by(is_admin=True).count() if admin_count <= 1 and user.is_admin: - flash('Nie można zdegradować. Musi pozostać co najmniej jeden administrator.', 'danger') - return redirect(url_for('list_users')) + flash( + "Nie można zdegradować. Musi pozostać co najmniej jeden administrator.", + "danger", + ) + return redirect(url_for("list_users")) user.is_admin = False db.session.commit() - flash(f'Użytkownik {user.username} został zdegradowany.', 'success') - return redirect(url_for('list_users')) + flash(f"Użytkownik {user.username} został zdegradowany.", "success") + return redirect(url_for("list_users")) -@app.route('/healthcheck') + +@app.route("/healthcheck") def healthcheck(): header_token = request.headers.get("X-Internal-Check") - correct_token = app.config.get('HEALTHCHECK_TOKEN') + correct_token = app.config.get("HEALTHCHECK_TOKEN") if header_token != correct_token: abort(404) - return 'OK', 200 + return "OK", 200 + # ========================================================================================= # SOCKET.IO # ========================================================================================= -@socketio.on('delete_item') + +@socketio.on("delete_item") def handle_delete_item(data): - item = Item.query.get(data['item_id']) + # item = Item.query.get(data["item_id"]) + item = db.session.get(Item, data["item_id"]) + if item: list_id = item.list_id db.session.delete(item) db.session.commit() - emit('item_deleted', {'item_id': item.id}, to=str(item.list_id)) + emit("item_deleted", {"item_id": item.id}, to=str(item.list_id)) purchased_count, total_count, percent = get_progress(list_id) - emit('progress_updated', { - 'purchased_count': purchased_count, - 'total_count': total_count, - 'percent': percent - }, to=str(list_id)) + emit( + "progress_updated", + { + "purchased_count": purchased_count, + "total_count": total_count, + "percent": percent, + }, + to=str(list_id), + ) -@socketio.on('edit_item') + +@socketio.on("edit_item") def handle_edit_item(data): - item = Item.query.get(data['item_id']) - new_name = data['new_name'] - new_quantity = data.get('new_quantity', item.quantity) + # item = Item.query.get(data["item_id"]) + item = db.session.get(Item, data["item_id"]) + + new_name = data["new_name"] + new_quantity = data.get("new_quantity", item.quantity) if item and new_name.strip(): item.name = new_name.strip() @@ -1252,45 +1696,50 @@ def handle_edit_item(data): db.session.commit() - emit('item_edited', { - 'item_id': item.id, - 'new_name': item.name, - 'new_quantity': item.quantity - }, to=str(item.list_id)) + emit( + "item_edited", + {"item_id": item.id, "new_name": item.name, "new_quantity": item.quantity}, + to=str(item.list_id), + ) -@socketio.on('join_list') + +@socketio.on("join_list") def handle_join(data): global active_users - room = str(data['room']) - username = data.get('username', 'Gość') + room = str(data["room"]) + username = data.get("username", "Gość") join_room(room) if room not in active_users: active_users[room] = set() active_users[room].add(username) - shopping_list = ShoppingList.query.get(int(data['room'])) + # shopping_list = ShoppingList.query.get(int(data["room"])) + shopping_list = db.session.get(ShoppingList, int(data["room"])) + list_title = shopping_list.title if shopping_list else "Twoja lista" - emit('user_joined', {'username': username}, to=room) - emit('user_list', {'users': list(active_users[room])}, to=room) - emit('joined_confirmation', {'room': room, 'list_title': list_title}) + emit("user_joined", {"username": username}, to=room) + emit("user_list", {"users": list(active_users[room])}, to=room) + emit("joined_confirmation", {"room": room, "list_title": list_title}) -@socketio.on('disconnect') + +@socketio.on("disconnect") def handle_disconnect(sid): global active_users username = current_user.username if current_user.is_authenticated else "Gość" for room, users in active_users.items(): if username in users: users.remove(username) - emit('user_left', {'username': username}, to=room) - emit('user_list', {'users': list(users)}, to=room) + emit("user_left", {"username": username}, to=room) + emit("user_list", {"users": list(users)}, to=room) -@socketio.on('add_item') + +@socketio.on("add_item") def handle_add_item(data): - list_id = data['list_id'] - name = data['name'] - quantity = data.get('quantity', 1) + list_id = data["list_id"] + name = data["name"].strip() + quantity = data.get("quantity", 1) try: quantity = int(quantity) @@ -1299,55 +1748,109 @@ def handle_add_item(data): except: quantity = 1 - new_item = Item( - list_id=list_id, - name=name, - quantity=quantity, - added_by=current_user.id if current_user.is_authenticated else None - ) - db.session.add(new_item) + existing_item = Item.query.filter( + Item.list_id == list_id, + func.lower(Item.name) == name.lower(), + Item.not_purchased == False, + ).first() - if not SuggestedProduct.query.filter_by(name=name).first(): - new_suggestion = SuggestedProduct(name=name) - db.session.add(new_suggestion) + if existing_item: + existing_item.quantity += quantity + db.session.commit() - db.session.commit() + emit( + "item_edited", + { + "item_id": existing_item.id, + "new_name": existing_item.name, + "new_quantity": existing_item.quantity, + }, + to=str(list_id), + ) + else: + max_position = ( + db.session.query(func.max(Item.position)) + .filter_by(list_id=list_id) + .scalar() + ) + if max_position is None: + max_position = 0 - emit('item_added', { - 'id': new_item.id, - 'name': new_item.name, - 'quantity': new_item.quantity, - 'added_by': current_user.username if current_user.is_authenticated else 'Gość' - }, to=str(list_id), include_self=True) + new_item = Item( + list_id=list_id, + name=name, + quantity=quantity, + position=max_position + 1, + added_by=current_user.id if current_user.is_authenticated else None, + ) + db.session.add(new_item) + + if not SuggestedProduct.query.filter( + func.lower(SuggestedProduct.name) == name.lower() + ).first(): + new_suggestion = SuggestedProduct(name=name) + db.session.add(new_suggestion) + + db.session.commit() + + emit( + "item_added", + { + "id": new_item.id, + "name": new_item.name, + "quantity": new_item.quantity, + "added_by": ( + current_user.username if current_user.is_authenticated else "Gość" + ), + }, + to=str(list_id), + include_self=True, + ) purchased_count, total_count, percent = get_progress(list_id) - emit('progress_updated', { - 'purchased_count': purchased_count, - 'total_count': total_count, - 'percent': percent - }, to=str(list_id)) + emit( + "progress_updated", + { + "purchased_count": purchased_count, + "total_count": total_count, + "percent": percent, + }, + to=str(list_id), + ) -@socketio.on('check_item') + +@socketio.on("check_item") def handle_check_item(data): - item = Item.query.get(data['item_id']) + # item = Item.query.get(data["item_id"]) + item = db.session.get(Item, data["item_id"]) + if item: item.purchased = True - item.purchased_at = datetime.utcnow() + # item.purchased_at = datetime.utcnow() + item.purchased_at = datetime.now(UTC) + db.session.commit() purchased_count, total_count, percent = get_progress(item.list_id) - emit('item_checked', {'item_id': item.id}, to=str(item.list_id)) - emit('progress_updated', { - 'purchased_count': purchased_count, - 'total_count': total_count, - 'percent': percent - }, to=str(item.list_id)) + emit("item_checked", {"item_id": item.id}, to=str(item.list_id)) + emit( + "progress_updated", + { + "purchased_count": purchased_count, + "total_count": total_count, + "percent": percent, + }, + to=str(item.list_id), + ) -@socketio.on('uncheck_item') + +@socketio.on("uncheck_item") def handle_uncheck_item(data): - item = Item.query.get(data['item_id']) + # item = Item.query.get(data["item_id"]) + item = db.session.get(Item, data["item_id"]) + if item: item.purchased = False item.purchased_at = None @@ -1355,55 +1858,98 @@ def handle_uncheck_item(data): purchased_count, total_count, percent = get_progress(item.list_id) - emit('item_unchecked', {'item_id': item.id}, to=str(item.list_id)) - emit('progress_updated', { - 'purchased_count': purchased_count, - 'total_count': total_count, - 'percent': percent - }, to=str(item.list_id)) + emit("item_unchecked", {"item_id": item.id}, to=str(item.list_id)) + emit( + "progress_updated", + { + "purchased_count": purchased_count, + "total_count": total_count, + "percent": percent, + }, + to=str(item.list_id), + ) -@socketio.on('request_full_list') + +@socketio.on("request_full_list") def handle_request_full_list(data): - list_id = data['list_id'] - items = Item.query.filter_by(list_id=list_id).all() + list_id = data["list_id"] + items = Item.query.filter_by(list_id=list_id).order_by(Item.position.asc()).all() items_data = [] for item in items: - items_data.append({ - 'id': item.id, - 'name': item.name, - 'quantity': item.quantity, - 'purchased': item.purchased, - 'note': item.note or '' - }) + items_data.append( + { + "id": item.id, + "name": item.name, + "quantity": item.quantity, + "purchased": item.purchased if not item.not_purchased else False, + "not_purchased": item.not_purchased, + "not_purchased_reason": item.not_purchased_reason, + "note": item.note or "", + } + ) - emit('full_list', {'items': items_data}, to=request.sid) + emit("full_list", {"items": items_data}, to=request.sid) -@socketio.on('update_note') + +@socketio.on("update_note") def handle_update_note(data): - item_id = data['item_id'] - note = data['note'] + item_id = data["item_id"] + note = data["note"] item = Item.query.get(item_id) if item: item.note = note - db.session.commit() - emit('note_updated', {'item_id': item_id, 'note': note}, to=str(item.list_id)) + db.session.commit() + emit("note_updated", {"item_id": item_id, "note": note}, to=str(item.list_id)) -@socketio.on('add_expense') + +@socketio.on("add_expense") def handle_add_expense(data): - list_id = data['list_id'] - amount = data['amount'] + list_id = data["list_id"] + amount = data["amount"] new_expense = Expense(list_id=list_id, amount=amount) db.session.add(new_expense) db.session.commit() - total = db.session.query(func.sum(Expense.amount)).filter_by(list_id=list_id).scalar() or 0 + total = ( + db.session.query(func.sum(Expense.amount)).filter_by(list_id=list_id).scalar() + or 0 + ) + + emit("expense_added", {"amount": amount, "total": total}, to=str(list_id)) + + +@socketio.on("mark_not_purchased") +def handle_mark_not_purchased(data): + # item = Item.query.get(data["item_id"]) + item = db.session.get(Item, data["item_id"]) + + reason = data.get("reason", "") + if item: + item.not_purchased = True + item.not_purchased_reason = reason + db.session.commit() + emit( + "item_marked_not_purchased", + {"item_id": item.id, "reason": reason}, + to=str(item.list_id), + ) + + +@socketio.on("unmark_not_purchased") +def handle_unmark_not_purchased(data): + # item = Item.query.get(data["item_id"]) + item = db.session.get(Item, data["item_id"]) + + if item: + item.not_purchased = False + item.purchased = False + item.purchased_at = None + item.not_purchased_reason = None + db.session.commit() + emit("item_unmarked_not_purchased", {"item_id": item.id}, to=str(item.list_id)) - emit('expense_added', { - 'amount': amount, - 'total': total - }, to=str(list_id)) """ @socketio.on('receipt_uploaded') def handle_receipt_uploaded(data): @@ -1414,10 +1960,12 @@ def handle_receipt_uploaded(data): 'url': url }, to=str(list_id), include_self=False) """ -@app.cli.command('create_db') + +@app.cli.command("create_db") def create_db(): db.create_all() - print('Database created.') + print("Database created.") -if __name__ == '__main__': - socketio.run(app, host='0.0.0.0', port=8000, debug=True) \ No newline at end of file + +if __name__ == "__main__": + socketio.run(app, host="0.0.0.0", port=8000, debug=True) diff --git a/config.py b/config.py index 68666d5..cfc93a2 100644 --- a/config.py +++ b/config.py @@ -10,4 +10,5 @@ class Config: UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER', 'uploads') AUTHORIZED_COOKIE_VALUE = os.environ.get('AUTHORIZED_COOKIE_VALUE', 'cookievalue') AUTH_COOKIE_MAX_AGE = int(os.environ.get('AUTH_COOKIE_MAX_AGE', 86400)) - HEALTHCHECK_TOKEN = os.environ.get('HEALTHCHECK_TOKEN', 'alamapsaikota1234') \ No newline at end of file + HEALTHCHECK_TOKEN = os.environ.get('HEALTHCHECK_TOKEN', 'alamapsaikota1234') + SESSION_TIMEOUT_MINUTES = int(os.environ.get('SESSION_TIMEOUT_MINUTES', 10080)) \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index ce6e0ac..bf68436 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,5 +21,6 @@ services: - AUTHORIZED_COOKIE_VALUE=${AUTHORIZED_COOKIE_VALUE} - AUTH_COOKIE_MAX_AGE=${AUTH_COOKIE_MAX_AGE} - HEALTHCHECK_TOKEN=${HEALTHCHECK_TOKEN} + - SESSION_TIMEOUT_MINUTES=${SESSION_TIMEOUT_MINUTES} volumes: - .:/app diff --git a/static/css/style.css b/static/css/style.css index 878f7e0..0e32abb 100644 --- a/static/css/style.css +++ b/static/css/style.css @@ -3,6 +3,7 @@ width: 1.5em; height: 1.5em; } + .clickable-item { cursor: pointer; } @@ -38,7 +39,8 @@ top: 50%; left: 50%; transform: translate(-50%, -50%); - pointer-events: none; /* klikalne przyciski obok paska nie ucierpią */ + pointer-events: none; + /* klikalne przyciski obok paska nie ucierpią */ white-space: nowrap; } @@ -53,7 +55,7 @@ /* --- Styl przycisku wyboru pliku --- */ input[type="file"]::file-selector-button { - background-color: #225d36; + background-color: #225d36; color: #fff; border: none; padding: 0.5em 1em; @@ -69,16 +71,19 @@ input[type="file"]::file-selector-button { color: #eaffea !important; border-color: #174428 !important; } + .alert-danger { background-color: #7a1f23 !important; color: #ffeaea !important; border-color: #531417 !important; } + .alert-info { background-color: #1d3a4d !important; color: #eaf6ff !important; border-color: #152837 !important; } + .alert-warning { background-color: #665c1e !important; color: #fffbe5 !important; @@ -86,35 +91,50 @@ input[type="file"]::file-selector-button { } /* Badge - kolory pasujące do ciemnych alertów */ -.badge.bg-success, .badge.text-bg-success { +.badge.bg-success, +.badge.text-bg-success { background-color: #225d36 !important; color: #eaffea !important; } -.badge.bg-danger, .badge.text-bg-danger { + +.badge.bg-danger, +.badge.text-bg-danger { background-color: #7a1f23 !important; color: #ffeaea !important; } -.badge.bg-info, .badge.text-bg-info { + +.badge.bg-info, +.badge.text-bg-info { background-color: #1d3a4d !important; color: #eaf6ff !important; } -.badge.bg-warning, .badge.text-bg-warning { + +.badge.bg-warning, +.badge.text-bg-warning { background-color: #665c1e !important; color: #fffbe5 !important; } -.badge.bg-secondary, .badge.text-bg-secondary { + +.badge.bg-secondary, +.badge.text-bg-secondary { background-color: #343a40 !important; color: #e2e3e5 !important; } -.badge.bg-primary, .badge.text-bg-primary { + +.badge.bg-primary, +.badge.text-bg-primary { background-color: #184076 !important; color: #e6f0ff !important; } -.badge.bg-light, .badge.text-bg-light { + +.badge.bg-light, +.badge.text-bg-light { background-color: #444950 !important; color: #f8f9fa !important; } -.badge.bg-dark, .badge.text-bg-dark { + +.badge.bg-dark, +.badge.text-bg-dark { background-color: #181a1b !important; color: #f8f9fa !important; } @@ -157,6 +177,7 @@ input[type="checkbox"].large-checkbox:disabled::before { opacity: 0.5; cursor: not-allowed; } + input[type="checkbox"].large-checkbox:disabled { cursor: not-allowed; } @@ -223,6 +244,7 @@ input.form-control { opacity: 0; transform: translateY(20px); } + to { opacity: 1; transform: translateY(0); @@ -232,11 +254,13 @@ input.form-control { #mass-add-list li.active { background: #198754 !important; color: #fff !important; - border: 1px solid #000000 !important; + border: 1px solid #000000 !important; } + #mass-add-list li { transition: background 0.2s; } + .quantity-input { width: 60px; background: #343a40; @@ -245,6 +269,7 @@ input.form-control { border-radius: 4px; text-align: center; } + .add-btn { margin-left: 10px; } @@ -256,6 +281,7 @@ input.form-control { justify-content: flex-end; gap: 4px; } + .list-group-item { display: flex; align-items: center; diff --git a/static/js/clickable_row.js b/static/js/clickable_row.js index a928fa5..955c80c 100644 --- a/static/js/clickable_row.js +++ b/static/js/clickable_row.js @@ -1,6 +1,6 @@ document.addEventListener("DOMContentLoaded", () => { document.querySelectorAll('.clickable-item').forEach(item => { - item.addEventListener('click', function(e) { + item.addEventListener('click', function (e) { if (!e.target.closest('button') && e.target.tagName.toLowerCase() !== 'input') { const checkbox = this.querySelector('input[type="checkbox"]'); diff --git a/static/js/confirm_delete.js b/static/js/confirm_delete.js new file mode 100644 index 0000000..edb0a69 --- /dev/null +++ b/static/js/confirm_delete.js @@ -0,0 +1,20 @@ +document.addEventListener("DOMContentLoaded", function () { + const input = document.getElementById('confirm-delete-input'); + const button = document.getElementById('confirm-delete-btn'); + let timer = null; + + input.addEventListener('input', function () { + button.disabled = true; + if (timer) clearTimeout(timer); + + if (input.value.trim().toLowerCase() === 'usuń') { + timer = setTimeout(() => { + button.disabled = false; + }, 2000); + } + }); + + button.addEventListener('click', function () { + document.getElementById('delete-form').submit(); + }); +}); \ No newline at end of file diff --git a/static/js/expenses.js b/static/js/expenses.js index 7b6b569..9c4b338 100644 --- a/static/js/expenses.js +++ b/static/js/expenses.js @@ -1,4 +1,4 @@ -document.addEventListener("DOMContentLoaded", function() { +document.addEventListener("DOMContentLoaded", function () { let expensesChart = null; const rangeLabel = document.getElementById("chartRangeLabel"); @@ -8,57 +8,57 @@ document.addEventListener("DOMContentLoaded", function() { url += `&start_date=${startDate}&end_date=${endDate}`; } - fetch(url, {cache: "no-store"}) - .then(response => response.json()) - .then(data => { - const ctx = document.getElementById('expensesChart').getContext('2d'); + fetch(url, { cache: "no-store" }) + .then(response => response.json()) + .then(data => { + const ctx = document.getElementById('expensesChart').getContext('2d'); - if (expensesChart) { - expensesChart.destroy(); - } + if (expensesChart) { + expensesChart.destroy(); + } - expensesChart = new Chart(ctx, { - type: 'bar', - data: { - labels: data.labels, - datasets: [{ - label: 'Suma wydatków [PLN]', - data: data.expenses, - backgroundColor: '#0d6efd' - }] - }, - options: { - scales: { - y: { - beginAtZero: true + expensesChart = new Chart(ctx, { + type: 'bar', + data: { + labels: data.labels, + datasets: [{ + label: 'Suma wydatków [PLN]', + data: data.expenses, + backgroundColor: '#0d6efd' + }] + }, + options: { + scales: { + y: { + beginAtZero: true + } } } + }); + + if (startDate && endDate) { + rangeLabel.textContent = `Widok: własny zakres (${startDate} → ${endDate})`; + } else { + let labelText = ""; + if (range === "monthly") labelText = "Widok: miesięczne"; + else if (range === "quarterly") labelText = "Widok: kwartalne"; + else if (range === "halfyearly") labelText = "Widok: półroczne"; + else if (range === "yearly") labelText = "Widok: roczne"; + rangeLabel.textContent = labelText; } + + }) + .catch(error => { + console.error("Błąd pobierania danych:", error); }); - - if (startDate && endDate) { - rangeLabel.textContent = `Widok: własny zakres (${startDate} → ${endDate})`; - } else { - let labelText = ""; - if (range === "monthly") labelText = "Widok: miesięczne"; - else if (range === "quarterly") labelText = "Widok: kwartalne"; - else if (range === "halfyearly") labelText = "Widok: półroczne"; - else if (range === "yearly") labelText = "Widok: roczne"; - rangeLabel.textContent = labelText; - } - - }) - .catch(error => { - console.error("Błąd pobierania danych:", error); - }); } - document.getElementById('loadExpensesBtn').addEventListener('click', function() { + document.getElementById('loadExpensesBtn').addEventListener('click', function () { loadExpenses(); }); document.querySelectorAll('.range-btn').forEach(btn => { - btn.addEventListener('click', function() { + btn.addEventListener('click', function () { document.querySelectorAll('.range-btn').forEach(b => b.classList.remove('active')); this.classList.add('active'); const range = this.getAttribute('data-range'); @@ -66,7 +66,7 @@ document.addEventListener("DOMContentLoaded", function() { }); }); - document.getElementById('customRangeBtn').addEventListener('click', function() { + document.getElementById('customRangeBtn').addEventListener('click', function () { const startDate = document.getElementById('startDate').value; const endDate = document.getElementById('endDate').value; if (startDate && endDate) { @@ -78,7 +78,7 @@ document.addEventListener("DOMContentLoaded", function() { }); }); -document.addEventListener("DOMContentLoaded", function() { +document.addEventListener("DOMContentLoaded", function () { const startDateInput = document.getElementById("startDate"); const endDateInput = document.getElementById("endDate"); diff --git a/static/js/functions.js b/static/js/functions.js index 45f6811..9d5cd7b 100644 --- a/static/js/functions.js +++ b/static/js/functions.js @@ -19,20 +19,6 @@ function updateItemState(itemId, isChecked) { applyHidePurchased(); } -/* function updateProgressBar() { - const items = document.querySelectorAll('#items li'); - const total = items.length; - const purchased = Array.from(items).filter(li => li.classList.contains('bg-success')).length; - const percent = total > 0 ? Math.round((purchased / total) * 100) : 0; - - const progressBar = document.getElementById('progress-bar'); - if (progressBar) { - progressBar.style.width = `${percent}%`; - progressBar.setAttribute('aria-valuenow', percent); - progressBar.textContent = `${percent}%`; - } -} */ - function updateProgressBar() { const items = document.querySelectorAll('#items li'); const total = items.length; @@ -193,7 +179,7 @@ function openList(link) { } function applyHidePurchased(isInit = false) { - console.log("applyHidePurchased: wywołana, isInit =", isInit); + //console.log("applyHidePurchased: wywołana, isInit =", isInit); const toggle = document.getElementById('hidePurchasedToggle'); if (!toggle) return; const hide = toggle.checked; @@ -231,7 +217,7 @@ function applyHidePurchased(isInit = false) { } function toggleVisibility(listId) { - fetch('/toggle_visibility/' + listId, {method: 'POST'}) + fetch('/toggle_visibility/' + listId, { method: 'POST' }) .then(response => response.json()) .then(data => { const shareHeader = document.getElementById('share-header'); @@ -254,6 +240,14 @@ function toggleVisibility(listId) { }); } +function markNotPurchasedModal(e, id) { + e.stopPropagation(); + const reason = prompt("Podaj powód oznaczenia jako niekupione:"); + if (reason !== null) { + socket.emit('mark_not_purchased', { item_id: id, reason: reason }); + } +} + function showToast(message, type = 'primary') { const toastContainer = document.getElementById('toast-container'); const toast = document.createElement('div'); @@ -279,6 +273,7 @@ function isListDifferent(oldItems, newItems) { } function updateListSmoothly(newItems) { + const itemsContainer = document.getElementById('items'); const existingItemsMap = new Map(); @@ -296,58 +291,62 @@ function updateListSmoothly(newItems) { quantityBadge = `x${item.quantity}`; } - if (li) { - const checkbox = li.querySelector('input[type="checkbox"]'); - if (checkbox) { - checkbox.checked = item.purchased; - checkbox.disabled = false; - } - - li.classList.remove('bg-success', 'text-white', 'item-not-checked', 'opacity-50'); - if (item.purchased) { - li.classList.add('bg-success', 'text-white'); - } else { - li.classList.add('item-not-checked'); - } - - const nameSpan = li.querySelector(`#name-${item.id}`); - const expectedName = `${item.name} ${quantityBadge}`.trim(); - if (nameSpan && nameSpan.innerHTML.trim() !== expectedName) { - nameSpan.innerHTML = expectedName; - } - - let noteEl = li.querySelector('small'); - if (item.note) { - if (!noteEl) { - const newNote = document.createElement('small'); - newNote.className = 'text-danger ms-4'; - newNote.innerHTML = `[ ${item.note} ]`; - nameSpan.insertAdjacentElement('afterend', newNote); - } else { - noteEl.innerHTML = `[ ${item.note} ]`; - } - } else if (noteEl) { - noteEl.remove(); - } - - const sp = li.querySelector('.spinner-border'); - if (sp) sp.remove(); - - } else { + if (!li) { li = document.createElement('li'); - li.className = `list-group-item d-flex justify-content-between align-items-center flex-wrap ${item.purchased ? 'bg-success text-white' : 'item-not-checked'}`; li.id = `item-${item.id}`; - - li.innerHTML = ` -
- - ${item.name} ${quantityBadge} - ${item.note ? `[ ${item.note} ]` : ''} -
- - `; } + // Klasy tła + li.className = `list-group-item d-flex justify-content-between align-items-center flex-wrap clickable-item ${item.purchased ? 'bg-success text-white' : + item.not_purchased ? 'bg-warning text-dark' : 'item-not-checked' + }`; + + // Wewnętrzny HTML + li.innerHTML = ` +
+ ${isSorting ? `` : ''} + ${!item.not_purchased ? ` + + ` : ` + 🚫 + `} + ${item.name} ${quantityBadge} + + ${item.note ? `[ ${item.note} ]` : ''} + ${item.not_purchased_reason ? `[ Powód: ${item.not_purchased_reason} ]` : ''} +
+
+ ${item.not_purchased ? ` + + ` : ` + + ${window.IS_SHARE ? ` + + ` : ''} + `} + ${!window.IS_SHARE ? ` + + + ` : ''} +
+ `; + fragment.appendChild(li); }); @@ -359,7 +358,8 @@ function updateListSmoothly(newItems) { applyHidePurchased(); } -document.addEventListener("DOMContentLoaded", function() { + +document.addEventListener("DOMContentLoaded", function () { const receiptSection = document.getElementById("receiptSection"); const toggleBtn = document.querySelector('[data-bs-target="#receiptSection"]'); @@ -378,14 +378,14 @@ document.addEventListener("DOMContentLoaded", function() { }); }); -document.addEventListener("DOMContentLoaded", function() { +document.addEventListener("DOMContentLoaded", function () { const toggle = document.getElementById('hidePurchasedToggle'); if (!toggle) return; const savedState = localStorage.getItem('hidePurchasedToggle'); toggle.checked = savedState === 'true'; applyHidePurchased(true); - toggle.addEventListener('change', function() { + toggle.addEventListener('change', function () { localStorage.setItem('hidePurchasedToggle', toggle.checked ? 'true' : 'false'); applyHidePurchased(); }); diff --git a/static/js/live.js b/static/js/live.js index bed3dbb..40be454 100644 --- a/static/js/live.js +++ b/static/js/live.js @@ -7,11 +7,11 @@ function toggleEmptyPlaceholder() { // prawdziwe
  • to te z data‑name lub id="item‑…" const hasRealItems = list.querySelector('li[data-name], li[id^="item-"]') !== null; - const placeholder = document.getElementById('empty-placeholder'); + const placeholder = document.getElementById('empty-placeholder'); if (!hasRealItems && !placeholder) { - const li = document.createElement('li'); - li.id = 'empty-placeholder'; + const li = document.createElement('li'); + li.id = 'empty-placeholder'; li.className = 'list-group-item bg-dark text-secondary text-center w-100'; li.textContent = 'Brak produktów w tej liście.'; list.appendChild(li); @@ -132,30 +132,42 @@ function setupList(listId, username) { const li = document.createElement('li'); li.className = 'list-group-item d-flex justify-content-between align-items-center flex-wrap item-not-checked'; li.id = `item-${data.id}`; - + let quantityBadge = ''; if (data.quantity && data.quantity > 1) { quantityBadge = `x${data.quantity}`; } li.innerHTML = ` -
    - - ${data.name} ${quantityBadge} -
    -
    - - -
    - `; +
    + + ${data.name} ${quantityBadge} +
    +
    + + +
    + `; -// #### WERSJA Z NAPISAMI #### -// -// + // góra listy + //document.getElementById('items').prepend(li); + // dół listy document.getElementById('items').appendChild(li); - updateProgressBar(); toggleEmptyPlaceholder(); + + setTimeout(() => { + if (window.LIST_ID) { + socket.emit('request_full_list', { list_id: window.LIST_ID }); + } + }, 15000); + }); socket.on('item_deleted', data => { @@ -168,7 +180,7 @@ function setupList(listId, username) { toggleEmptyPlaceholder(); }); - socket.on('progress_updated', function(data) { + socket.on('progress_updated', function (data) { const progressBar = document.getElementById('progress-bar'); if (progressBar) { progressBar.style.width = data.percent + '%'; @@ -225,4 +237,8 @@ function setupList(listId, username) { window.LIST_ID = listId; window.usernameForReconnect = username; +} + +function unmarkNotPurchased(itemId) { + socket.emit('unmark_not_purchased', { item_id: itemId }); } \ No newline at end of file diff --git a/static/js/mass_add.js b/static/js/mass_add.js index 0265f35..495517e 100644 --- a/static/js/mass_add.js +++ b/static/js/mass_add.js @@ -2,11 +2,16 @@ document.addEventListener('DOMContentLoaded', function () { const modal = document.getElementById('massAddModal'); const productList = document.getElementById('mass-add-list'); + // Funkcja normalizacji (usuwa diakrytyki i zamienia na lowercase) + function normalize(str) { + return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase(); + } + modal.addEventListener('show.bs.modal', async function () { let addedProducts = new Set(); document.querySelectorAll('#items li').forEach(li => { if (li.dataset.name) { - addedProducts.add(li.dataset.name.toLowerCase()); + addedProducts.add(normalize(li.dataset.name)); } }); @@ -20,8 +25,7 @@ document.addEventListener('DOMContentLoaded', function () { const li = document.createElement('li'); li.className = 'list-group-item d-flex justify-content-between align-items-center bg-dark text-light'; - if (addedProducts.has(name.toLowerCase())) { - // Produkt już dodany — oznacz jako nieaktywny + if (addedProducts.has(normalize(name))) { const nameSpan = document.createElement('span'); nameSpan.textContent = name; li.appendChild(nameSpan); @@ -32,17 +36,14 @@ document.addEventListener('DOMContentLoaded', function () { badge.textContent = 'Dodano'; li.appendChild(badge); } else { - // Nazwa produktu const nameSpan = document.createElement('span'); nameSpan.textContent = name; nameSpan.style.flex = '1 1 auto'; li.appendChild(nameSpan); - // Kontener na minus, pole i plus const qtyWrapper = document.createElement('div'); qtyWrapper.className = 'd-flex align-items-center ms-2 quantity-controls'; - // Minus const minusBtn = document.createElement('button'); minusBtn.type = 'button'; minusBtn.className = 'btn btn-outline-light btn-sm px-2'; @@ -51,18 +52,15 @@ document.addEventListener('DOMContentLoaded', function () { qty.value = Math.max(1, parseInt(qty.value) - 1); }; - // Pole ilości const qty = document.createElement('input'); qty.type = 'number'; qty.min = 1; qty.value = 1; - qty.className = 'form-control text-center p-1'; - qty.classList.add('rounded'); + qty.className = 'form-control text-center p-1 rounded'; qty.style.width = '50px'; qty.style.margin = '0 2px'; qty.title = 'Ilość'; - // Plus const plusBtn = document.createElement('button'); plusBtn.type = 'button'; plusBtn.className = 'btn btn-outline-light btn-sm px-2'; @@ -75,7 +73,6 @@ document.addEventListener('DOMContentLoaded', function () { qtyWrapper.appendChild(qty); qtyWrapper.appendChild(plusBtn); - // Przycisk dodania const btn = document.createElement('button'); btn.className = 'btn btn-sm btn-primary ms-4'; btn.textContent = '+'; @@ -99,25 +96,19 @@ document.addEventListener('DOMContentLoaded', function () { document.querySelectorAll('#mass-add-list li').forEach(li => { const itemName = li.firstChild.textContent.trim(); - if (itemName === data.name && !li.classList.contains('opacity-50')) { - // Usuń wszystkie dzieci + if (normalize(itemName) === normalize(data.name) && !li.classList.contains('opacity-50')) { while (li.firstChild) { li.removeChild(li.firstChild); } - // Ustaw nazwę li.textContent = data.name; - - // Dodaj klasę wyszarzenia li.classList.add('opacity-50'); - // Dodaj badge const badge = document.createElement('span'); badge.className = 'badge bg-success ms-auto'; badge.textContent = 'Dodano'; li.appendChild(badge); - // Zablokuj kliknięcia li.onclick = null; } }); diff --git a/static/js/notes.js b/static/js/notes.js index 3ac767c..ed6a4c2 100644 --- a/static/js/notes.js +++ b/static/js/notes.js @@ -1,13 +1,13 @@ let currentItemId = null; -function openNoteModal(event, itemId) { +window.openNoteModal = function (event, itemId) { event.stopPropagation(); currentItemId = itemId; - const noteEl = document.querySelector(`#item-${itemId} small`); - document.getElementById('noteText').value = noteEl ? noteEl.innerText : ""; + const noteEl = document.querySelector(`#item-${itemId} small.text-danger`); + document.getElementById('noteText').value = noteEl ? noteEl.innerText.replace(/\[|\]|Powód:/g, "").trim() : ""; const modal = new bootstrap.Modal(document.getElementById('noteModal')); modal.show(); -} +}; function submitNote(e) { e.preventDefault(); @@ -20,3 +20,4 @@ function submitNote(e) { modal.hide(); } } + diff --git a/static/js/product_suggestion.js b/static/js/product_suggestion.js index b6bec5f..cde7cf7 100644 --- a/static/js/product_suggestion.js +++ b/static/js/product_suggestion.js @@ -1,4 +1,4 @@ -document.addEventListener("DOMContentLoaded", function() { +document.addEventListener("DOMContentLoaded", function () { // Odśwież eventy document.querySelectorAll('.sync-btn').forEach(btn => { btn.replaceWith(btn.cloneNode(true)); @@ -9,7 +9,7 @@ document.addEventListener("DOMContentLoaded", function() { // Synchronizacja sugestii document.querySelectorAll('.sync-btn').forEach(btn => { - btn.addEventListener('click', function(e) { + btn.addEventListener('click', function (e) { e.preventDefault(); const itemId = this.getAttribute('data-item-id'); @@ -22,28 +22,28 @@ document.addEventListener("DOMContentLoaded", function() { 'X-Requested-With': 'XMLHttpRequest' } }) - .then(response => response.json()) - .then(data => { - showToast(data.message, data.success ? 'success' : 'danger'); + .then(response => response.json()) + .then(data => { + showToast(data.message, data.success ? 'success' : 'danger'); - if (data.success) { - button.innerText = '✅ Zsynchronizowano'; - button.classList.remove('btn-outline-primary'); - button.classList.add('btn-success'); - } else { + if (data.success) { + button.innerText = '✅ Zsynchronizowano'; + button.classList.remove('btn-outline-primary'); + button.classList.add('btn-success'); + } else { + button.disabled = false; + } + }) + .catch(() => { + showToast('Błąd synchronizacji', 'danger'); button.disabled = false; - } - }) - .catch(() => { - showToast('Błąd synchronizacji', 'danger'); - button.disabled = false; - }); + }); }); }); // Usuwanie sugestii document.querySelectorAll('.delete-suggestion-btn').forEach(btn => { - btn.addEventListener('click', function(e) { + btn.addEventListener('click', function (e) { e.preventDefault(); const suggestionId = this.getAttribute('data-suggestion-id'); @@ -56,21 +56,21 @@ document.addEventListener("DOMContentLoaded", function() { 'X-Requested-With': 'XMLHttpRequest' } }) - .then(response => response.json()) - .then(data => { - showToast(data.message, data.success ? 'success' : 'danger'); + .then(response => response.json()) + .then(data => { + showToast(data.message, data.success ? 'success' : 'danger'); - if (data.success) { - const row = button.closest('tr'); - if (row) row.remove(); - } else { + if (data.success) { + const row = button.closest('tr'); + if (row) row.remove(); + } else { + button.disabled = false; + } + }) + .catch(() => { + showToast('Błąd usuwania sugestii', 'danger'); button.disabled = false; - } - }) - .catch(() => { - showToast('Błąd usuwania sugestii', 'danger'); - button.disabled = false; - }); + }); }); }); }); diff --git a/static/js/receipt_section.js b/static/js/receipt_section.js index 6681440..9f474e9 100644 --- a/static/js/receipt_section.js +++ b/static/js/receipt_section.js @@ -1,4 +1,4 @@ -document.addEventListener("DOMContentLoaded", function() { +document.addEventListener("DOMContentLoaded", function () { const receiptSection = document.getElementById("receiptSection"); const toggleBtn = document.querySelector('[data-bs-target="#receiptSection"]'); diff --git a/static/js/sockets.js b/static/js/sockets.js index 8cc9027..2a21f63 100644 --- a/static/js/sockets.js +++ b/static/js/sockets.js @@ -2,83 +2,83 @@ let didReceiveFirstFullList = false; // --- Automatyczny reconnect po powrocie do karty/przywróceniu internetu --- function reconnectIfNeeded() { - if (!socket.connected) { - socket.connect(); - } + if (!socket.connected) { + socket.connect(); + } } -document.addEventListener("visibilitychange", function() { - if (!document.hidden) { - reconnectIfNeeded(); - } +document.addEventListener("visibilitychange", function () { + if (!document.hidden) { + reconnectIfNeeded(); + } }); -window.addEventListener("focus", function() { - reconnectIfNeeded(); +window.addEventListener("focus", function () { + reconnectIfNeeded(); }); -window.addEventListener("online", function() { - reconnectIfNeeded(); +window.addEventListener("online", function () { + reconnectIfNeeded(); }); // --- Blokowanie checkboxów na czas reconnect --- function disableCheckboxes(disable) { - document.querySelectorAll('#items input[type="checkbox"]').forEach(cb => { - cb.disabled = disable; - }); + document.querySelectorAll('#items input[type="checkbox"]').forEach(cb => { + cb.disabled = disable; + }); } // --- Toasty przy rozłączeniu i połączeniu --- let firstConnect = true; let wasReconnected = false; // flaga do kontrolowania toasta -socket.on('connect', function() { - if (!firstConnect) { - //showToast('Połączono z serwerem!', 'info'); - disableCheckboxes(true); - wasReconnected = true; +socket.on('connect', function () { + if (!firstConnect) { + //showToast('Połączono z serwerem!', 'info'); + disableCheckboxes(true); + wasReconnected = true; - if (window.LIST_ID && window.usernameForReconnect) { - socket.emit('join_list', { room: window.LIST_ID, username: window.usernameForReconnect }); - } + if (window.LIST_ID && window.usernameForReconnect) { + socket.emit('join_list', { room: window.LIST_ID, username: window.usernameForReconnect }); } - firstConnect = false; + } + firstConnect = false; }); -socket.on('disconnect', function(reason) { - showToast('Utracono połączenie z serwerem...', 'warning'); - disableCheckboxes(true); +socket.on('disconnect', function (reason) { + showToast('Utracono połączenie z serwerem...', 'warning'); + disableCheckboxes(true); }); socket.off('joined_confirmation'); -socket.on('joined_confirmation', function(data) { - if (wasReconnected) { - showToast(`Lista: ${data.list_title} – ponownie dołączono.`, 'info'); - wasReconnected = false; - } - if (window.LIST_ID) { - socket.emit('request_full_list', { list_id: window.LIST_ID }); - } +socket.on('joined_confirmation', function (data) { + if (wasReconnected) { + showToast(`Lista: ${data.list_title} – ponownie dołączono.`, 'info'); + wasReconnected = false; + } + if (window.LIST_ID) { + socket.emit('request_full_list', { list_id: window.LIST_ID }); + } }); -socket.on('user_joined', function(data) { - showToast(`${data.username} dołączył do listy`, 'info'); +socket.on('user_joined', function (data) { + showToast(`${data.username} dołączył do listy`, 'info'); }); -socket.on('user_left', function(data) { - showToast(`${data.username} opuścił listę`, 'warning'); +socket.on('user_left', function (data) { + showToast(`${data.username} opuścił listę`, 'warning'); }); -socket.on('user_list', function(data) { - if (data.users.length > 0) { - const userList = data.users.join(', '); - showToast(`Obecni: ${userList}`, 'info'); - } +socket.on('user_list', function (data) { + if (data.users.length > 0) { + const userList = data.users.join(', '); + showToast(`Obecni: ${userList}`, 'info'); + } }); socket.on('receipt_added', function (data) { - + const gallery = document.getElementById("receiptGallery"); if (!gallery) return; @@ -103,6 +103,20 @@ socket.on('receipt_added', function (data) { } }); +socket.on("items_reordered", data => { + if (data.list_id !== window.LIST_ID) return; + + if (window.currentItems) { + window.currentItems = data.order.map(id => + window.currentItems.find(item => item.id === id) + ).filter(Boolean); + + updateListSmoothly(window.currentItems); + //showToast('Kolejność produktów zaktualizowana', 'info'); + } +}); + + socket.on('full_list', function (data) { const itemsContainer = document.getElementById('items'); @@ -112,6 +126,7 @@ socket.on('full_list', function (data) { const isDifferent = isListDifferent(oldItems, data.items); + window.currentItems = data.items; updateListSmoothly(data.items); toggleEmptyPlaceholder(); @@ -119,4 +134,12 @@ socket.on('full_list', function (data) { showToast('Lista została zaktualizowana', 'info'); } didReceiveFirstFullList = true; +}); + +socket.on('item_marked_not_purchased', data => { + socket.emit('request_full_list', { list_id: window.LIST_ID }); +}); + +socket.on('item_unmarked_not_purchased', data => { + socket.emit('request_full_list', { list_id: window.LIST_ID }); }); \ No newline at end of file diff --git a/static/js/sort_mode.js b/static/js/sort_mode.js new file mode 100644 index 0000000..0a91843 --- /dev/null +++ b/static/js/sort_mode.js @@ -0,0 +1,83 @@ +let sortable = null; +let isSorting = false; + +function enableSortMode() { + if (sortable || isSorting) return; + isSorting = true; + localStorage.setItem('sortModeEnabled', 'true'); + + const itemsContainer = document.getElementById('items'); + const listId = window.LIST_ID; + + if (!itemsContainer || !listId) return; + + sortable = Sortable.create(itemsContainer, { + animation: 150, + handle: '.drag-handle', + ghostClass: 'drag-ghost', + filter: 'input, button', + preventOnFilter: false, + onEnd: function () { + const order = Array.from(itemsContainer.children) + .map(li => parseInt(li.id.replace('item-', ''))) + .filter(id => !isNaN(id)); + + fetch('/reorder_items', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ list_id: listId, order }) + }).then(() => { + showToast('Zapisano nową kolejność', 'success'); + + if (window.currentItems) { + window.currentItems = order.map(id => + window.currentItems.find(item => item.id === id) + ); + updateListSmoothly(window.currentItems); + } + }); + } + }); + + const btn = document.getElementById('sort-toggle-btn'); + if (btn) { + btn.textContent = '✔️ Zakończ sortowanie'; + btn.classList.remove('btn-outline-warning'); + btn.classList.add('btn-outline-success'); + } + + if (window.currentItems) { + updateListSmoothly(window.currentItems); + } +} + +function disableSortMode() { + if (sortable) { + sortable.destroy(); + sortable = null; + } + isSorting = false; + localStorage.removeItem('sortModeEnabled'); + + const btn = document.getElementById('sort-toggle-btn'); + if (btn) { + btn.textContent = '✳️ Zmień kolejność'; + btn.classList.remove('btn-outline-success'); + btn.classList.add('btn-outline-warning'); + } + + if (window.currentItems) { + updateListSmoothly(window.currentItems); + } +} + +function toggleSortMode() { + isSorting ? disableSortMode() : enableSortMode(); +} + +document.addEventListener('DOMContentLoaded', () => { + const wasSorting = localStorage.getItem('sortModeEnabled') === 'true'; + if (wasSorting) { + enableSortMode(); + } +}); \ No newline at end of file diff --git a/static/js/toggle_button.js b/static/js/toggle_button.js index 5216365..d441f64 100644 --- a/static/js/toggle_button.js +++ b/static/js/toggle_button.js @@ -1,4 +1,4 @@ -document.addEventListener("DOMContentLoaded", function() { +document.addEventListener("DOMContentLoaded", function () { const toggleBtn = document.getElementById("tempToggle"); const hiddenInput = document.getElementById("temporaryHidden"); @@ -23,7 +23,7 @@ document.addEventListener("DOMContentLoaded", function() { updateToggle(active); // Obsługa kliknięcia - toggleBtn.addEventListener("click", function() { + toggleBtn.addEventListener("click", function () { active = !active; toggleBtn.setAttribute("data-active", active ? "1" : "0"); hiddenInput.value = active ? "1" : "0"; diff --git a/static/js/user_expenses.js b/static/js/user_expenses.js new file mode 100644 index 0000000..a029e70 --- /dev/null +++ b/static/js/user_expenses.js @@ -0,0 +1,90 @@ +document.addEventListener("DOMContentLoaded", function () { + let expensesChart = null; + const rangeLabel = document.getElementById("chartRangeLabel"); + + function loadExpenses(range = "monthly", startDate = null, endDate = null) { + let url = '/user/expenses_data?range=' + range; + if (startDate && endDate) { + url += `&start_date=${startDate}&end_date=${endDate}`; + } + + fetch(url, { cache: "no-store" }) + .then(response => response.json()) + .then(data => { + const ctx = document.getElementById('expensesChart').getContext('2d'); + + if (expensesChart) { + expensesChart.destroy(); + } + + expensesChart = new Chart(ctx, { + type: 'bar', + data: { + labels: data.labels, + datasets: [{ + label: 'Suma wydatków [PLN]', + data: data.expenses, + backgroundColor: '#0d6efd' + }] + }, + options: { + scales: { + y: { + beginAtZero: true + } + } + } + }); + + if (startDate && endDate) { + rangeLabel.textContent = `Widok: własny zakres (${startDate} → ${endDate})`; + } else { + let labelText = ""; + if (range === "monthly") labelText = "Widok: miesięczne"; + else if (range === "quarterly") labelText = "Widok: kwartalne"; + else if (range === "halfyearly") labelText = "Widok: półroczne"; + else if (range === "yearly") labelText = "Widok: roczne"; + rangeLabel.textContent = labelText; + } + + }) + .catch(error => { + console.error("Błąd pobierania danych:", error); + }); + } + + // Inicjalizacja zakresu dat + const startDateInput = document.getElementById("startDate"); + const endDateInput = document.getElementById("endDate"); + const today = new Date(); + const lastWeek = new Date(today); + lastWeek.setDate(today.getDate() - 7); + const formatDate = (d) => d.toISOString().split('T')[0]; + startDateInput.value = formatDate(lastWeek); + endDateInput.value = formatDate(today); + + // Załaduj początkowy widok + loadExpenses(); + + // Przycisk własnego zakresu + document.getElementById('customRangeBtn').addEventListener('click', function () { + const startDate = startDateInput.value; + const endDate = endDateInput.value; + if (startDate && endDate) { + document.querySelectorAll('.range-btn').forEach(b => b.classList.remove('active')); + loadExpenses('custom', startDate, endDate); + } else { + alert("Proszę wybrać obie daty!"); + } + }); + + // Zakresy predefiniowane + document.querySelectorAll('.range-btn').forEach(btn => { + btn.addEventListener('click', function () { + document.querySelectorAll('.range-btn').forEach(b => b.classList.remove('active')); + this.classList.add('active'); + const range = this.getAttribute('data-range'); + loadExpenses(range); + }); + }); +}); diff --git a/static/js/user_management.js b/static/js/user_management.js index 8327c93..eee0339 100644 --- a/static/js/user_management.js +++ b/static/js/user_management.js @@ -1,4 +1,4 @@ -document.addEventListener('DOMContentLoaded', function() { +document.addEventListener('DOMContentLoaded', function () { var resetPasswordModal = document.getElementById('resetPasswordModal'); resetPasswordModal.addEventListener('show.bs.modal', function (event) { var button = event.relatedTarget; diff --git a/static/lib/js/Sortable.min.js b/static/lib/js/Sortable.min.js new file mode 100644 index 0000000..95423a6 --- /dev/null +++ b/static/lib/js/Sortable.min.js @@ -0,0 +1,2 @@ +/*! Sortable 1.15.6 - MIT | git://github.com/SortableJS/Sortable.git */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Sortable=e()}(this,function(){"use strict";function e(e,t){var n,o=Object.keys(e);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(e),t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,n)),o}function I(o){for(var t=1;tt.length)&&(e=t.length);for(var n=0,o=new Array(e);n"===e[0]&&(e=e.substring(1)),t))try{if(t.matches)return t.matches(e);if(t.msMatchesSelector)return t.msMatchesSelector(e);if(t.webkitMatchesSelector)return t.webkitMatchesSelector(e)}catch(t){return}}function g(t){return t.host&&t!==document&&t.host.nodeType?t.host:t.parentNode}function P(t,e,n,o){if(t){n=n||document;do{if(null!=e&&(">"!==e[0]||t.parentNode===n)&&f(t,e)||o&&t===n)return t}while(t!==n&&(t=g(t)))}return null}var m,v=/\s+/g;function k(t,e,n){var o;t&&e&&(t.classList?t.classList[n?"add":"remove"](e):(o=(" "+t.className+" ").replace(v," ").replace(" "+e+" "," "),t.className=(o+(n?" "+e:"")).replace(v," ")))}function R(t,e,n){var o=t&&t.style;if(o){if(void 0===n)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(t,""):t.currentStyle&&(n=t.currentStyle),void 0===e?n:n[e];o[e=!(e in o||-1!==e.indexOf("webkit"))?"-webkit-"+e:e]=n+("string"==typeof n?"":"px")}}function b(t,e){var n="";if("string"==typeof t)n=t;else do{var o=R(t,"transform")}while(o&&"none"!==o&&(n=o+" "+n),!e&&(t=t.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function D(t,e,n){if(t){var o=t.getElementsByTagName(e),i=0,r=o.length;if(n)for(;i=n.left-e&&i<=n.right+e,e=r>=n.top-e&&r<=n.bottom+e;return o&&e?a=t:void 0}}),a);if(e){var n,o={};for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);o.target=o.rootEl=e,o.preventDefault=void 0,o.stopPropagation=void 0,e[K]._onDragOver(o)}}var i,r,a}function Ft(t){Z&&Z.parentNode[K]._isOutsideThisEl(t.target)}function jt(t,e){if(!t||!t.nodeType||1!==t.nodeType)throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(t));this.el=t,this.options=e=a({},e),t[K]=this;var n,o,i={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(t.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return kt(t,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(t,e){t.setData("Text",e.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:!1!==jt.supportPointer&&"PointerEvent"in window&&(!u||c),emptyInsertThreshold:5};for(n in z.initializePlugins(this,t,i),i)n in e||(e[n]=i[n]);for(o in Rt(e),this)"_"===o.charAt(0)&&"function"==typeof this[o]&&(this[o]=this[o].bind(this));this.nativeDraggable=!e.forceFallback&&It,this.nativeDraggable&&(this.options.touchStartThreshold=1),e.supportPointer?h(t,"pointerdown",this._onTapStart):(h(t,"mousedown",this._onTapStart),h(t,"touchstart",this._onTapStart)),this.nativeDraggable&&(h(t,"dragover",this),h(t,"dragenter",this)),St.push(this.el),e.store&&e.store.get&&this.sort(e.store.get(this)||[]),a(this,A())}function Ht(t,e,n,o,i,r,a,l){var s,c,u=t[K],d=u.options.onMove;return!window.CustomEvent||y||w?(s=document.createEvent("Event")).initEvent("move",!0,!0):s=new CustomEvent("move",{bubbles:!0,cancelable:!0}),s.to=e,s.from=t,s.dragged=n,s.draggedRect=o,s.related=i||e,s.relatedRect=r||X(e),s.willInsertAfter=l,s.originalEvent=a,t.dispatchEvent(s),c=d?d.call(u,s,a):c}function Lt(t){t.draggable=!1}function Kt(){xt=!1}function Wt(t){return setTimeout(t,0)}function zt(t){return clearTimeout(t)}jt.prototype={constructor:jt,_isOutsideThisEl:function(t){this.el.contains(t)||t===this.el||(vt=null)},_getDirection:function(t,e){return"function"==typeof this.options.direction?this.options.direction.call(this,t,e,Z):this.options.direction},_onTapStart:function(e){if(e.cancelable){var n=this,o=this.el,t=this.options,i=t.preventOnFilter,r=e.type,a=e.touches&&e.touches[0]||e.pointerType&&"touch"===e.pointerType&&e,l=(a||e).target,s=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||l,c=t.filter;if(!function(t){Ot.length=0;var e=t.getElementsByTagName("input"),n=e.length;for(;n--;){var o=e[n];o.checked&&Ot.push(o)}}(o),!Z&&!(/mousedown|pointerdown/.test(r)&&0!==e.button||t.disabled)&&!s.isContentEditable&&(this.nativeDraggable||!u||!l||"SELECT"!==l.tagName.toUpperCase())&&!((l=P(l,t.draggable,o,!1))&&l.animated||et===l)){if(it=j(l),at=j(l,t.draggable),"function"==typeof c){if(c.call(this,e,l,this))return V({sortable:n,rootEl:s,name:"filter",targetEl:l,toEl:o,fromEl:o}),U("filter",n,{evt:e}),void(i&&e.preventDefault())}else if(c=c&&c.split(",").some(function(t){if(t=P(s,t.trim(),o,!1))return V({sortable:n,rootEl:t,name:"filter",targetEl:l,fromEl:o,toEl:o}),U("filter",n,{evt:e}),!0}))return void(i&&e.preventDefault());t.handle&&!P(s,t.handle,o,!1)||this._prepareDragStart(e,a,l)}}},_prepareDragStart:function(t,e,n){var o,i=this,r=i.el,a=i.options,l=r.ownerDocument;n&&!Z&&n.parentNode===r&&(o=X(n),J=r,$=(Z=n).parentNode,tt=Z.nextSibling,et=n,st=a.group,ut={target:jt.dragged=Z,clientX:(e||t).clientX,clientY:(e||t).clientY},ft=ut.clientX-o.left,gt=ut.clientY-o.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,Z.style["will-change"]="all",o=function(){U("delayEnded",i,{evt:t}),jt.eventCanceled?i._onDrop():(i._disableDelayedDragEvents(),!s&&i.nativeDraggable&&(Z.draggable=!0),i._triggerDragStart(t,e),V({sortable:i,name:"choose",originalEvent:t}),k(Z,a.chosenClass,!0))},a.ignore.split(",").forEach(function(t){D(Z,t.trim(),Lt)}),h(l,"dragover",Bt),h(l,"mousemove",Bt),h(l,"touchmove",Bt),a.supportPointer?(h(l,"pointerup",i._onDrop),this.nativeDraggable||h(l,"pointercancel",i._onDrop)):(h(l,"mouseup",i._onDrop),h(l,"touchend",i._onDrop),h(l,"touchcancel",i._onDrop)),s&&this.nativeDraggable&&(this.options.touchStartThreshold=4,Z.draggable=!0),U("delayStart",this,{evt:t}),!a.delay||a.delayOnTouchOnly&&!e||this.nativeDraggable&&(w||y)?o():jt.eventCanceled?this._onDrop():(a.supportPointer?(h(l,"pointerup",i._disableDelayedDrag),h(l,"pointercancel",i._disableDelayedDrag)):(h(l,"mouseup",i._disableDelayedDrag),h(l,"touchend",i._disableDelayedDrag),h(l,"touchcancel",i._disableDelayedDrag)),h(l,"mousemove",i._delayedDragTouchMoveHandler),h(l,"touchmove",i._delayedDragTouchMoveHandler),a.supportPointer&&h(l,"pointermove",i._delayedDragTouchMoveHandler),i._dragStartTimer=setTimeout(o,a.delay)))},_delayedDragTouchMoveHandler:function(t){t=t.touches?t.touches[0]:t;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){Z&&Lt(Z),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;p(t,"mouseup",this._disableDelayedDrag),p(t,"touchend",this._disableDelayedDrag),p(t,"touchcancel",this._disableDelayedDrag),p(t,"pointerup",this._disableDelayedDrag),p(t,"pointercancel",this._disableDelayedDrag),p(t,"mousemove",this._delayedDragTouchMoveHandler),p(t,"touchmove",this._delayedDragTouchMoveHandler),p(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||"touch"==t.pointerType&&t,!this.nativeDraggable||e?this.options.supportPointer?h(document,"pointermove",this._onTouchMove):h(document,e?"touchmove":"mousemove",this._onTouchMove):(h(Z,"dragend",this),h(J,"dragstart",this._onDragStart));try{document.selection?Wt(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch(t){}},_dragStarted:function(t,e){var n;Dt=!1,J&&Z?(U("dragStarted",this,{evt:e}),this.nativeDraggable&&h(document,"dragover",Ft),n=this.options,t||k(Z,n.dragClass,!1),k(Z,n.ghostClass,!0),jt.active=this,t&&this._appendGhost(),V({sortable:this,name:"start",originalEvent:e})):this._nulling()},_emulateDragOver:function(){if(dt){this._lastX=dt.clientX,this._lastY=dt.clientY,Xt();for(var t=document.elementFromPoint(dt.clientX,dt.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(dt.clientX,dt.clientY))!==e;)e=t;if(Z.parentNode[K]._isOutsideThisEl(t),e)do{if(e[K])if(e[K]._onDragOver({clientX:dt.clientX,clientY:dt.clientY,target:t,rootEl:e})&&!this.options.dragoverBubble)break}while(e=g(t=e));Yt()}},_onTouchMove:function(t){if(ut){var e=this.options,n=e.fallbackTolerance,o=e.fallbackOffset,i=t.touches?t.touches[0]:t,r=Q&&b(Q,!0),a=Q&&r&&r.a,l=Q&&r&&r.d,e=At&&wt&&E(wt),a=(i.clientX-ut.clientX+o.x)/(a||1)+(e?e[0]-Tt[0]:0)/(a||1),l=(i.clientY-ut.clientY+o.y)/(l||1)+(e?e[1]-Tt[1]:0)/(l||1);if(!jt.active&&!Dt){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))E.right+10||S.clientY>x.bottom&&S.clientX>x.left:S.clientY>E.bottom+10||S.clientX>x.right&&S.clientY>x.top)||m.animated)){if(m&&(t=n,e=r,C=X(B((_=this).el,0,_.options,!0)),_=L(_.el,_.options,Q),e?t.clientX<_.left-10||t.clientY
    Funkcje: - @@ -20,18 +21,10 @@ 👥 Zarządzanie użytkownikami
  • - @@ -57,7 +50,7 @@
    🔥 Najczęściej kupowane produkty:
      {% for name, count in top_products %} -
    • {{ name }} — {{ count }}×
    • +
    • {{ name }} — {{ count }}×
    • {% endfor %}
    @@ -74,7 +67,8 @@
  • Obecny rok: {{ '%.2f'|format(year_expense_sum) }} PLN
  • Całkowite: {{ '%.2f'|format(total_expense_sum) }} PLN
  • - @@ -82,124 +76,125 @@ -

    📄 Wszystkie listy zakupowe

    -
    -
    - - - - - - - - - - - - - - - - - - - {% for e in enriched_lists %} - {% set l = e.list %} - - - - -
    IDTytułStatusUtworzonoWłaścicielProduktyWypełnienieKomentarzeParagonyWydatkiAkcje
    {{ l.id }} - {{ l.title }} - - {% if l.is_archived %} +

    📄 Wszystkie listy zakupowe

    + +
    + + + + + + + + + + + + + + + + + + + {% for e in enriched_lists %} + {% set l = e.list %} + + + + + - - + + - - - - - + + + + + - - - {% endfor %} - + {% endif %} + + + + {% endfor %} + -
    IDTytułStatusUtworzonoWłaścicielProduktyWypełnienieKomentarzeParagonyWydatkiAkcje
    {{ l.id }} + {{ l.title }} + + {% if l.is_archived %} Archiwalna - {% elif l.is_temporary and l.expires_at and l.expires_at < now %} + {% elif e.expired %} Wygasła - {% else %} + {% else %} Aktywna - {% endif %} - {{ l.created_at.strftime('%Y-%m-%d %H:%M') if l.created_at else '-' }} - {% if l.owner_id %} + {% endif %} + {{ l.created_at.strftime('%Y-%m-%d %H:%M') if l.created_at else '-' }} + {% if l.owner_id %} {{ l.owner_id }} / {{ l.owner.username if l.owner else 'Brak użytkownika' }} - {% else %} + {% else %} - - {% endif %} - {{ e.total_count }}{{ e.purchased_count }}/{{ e.total_count }} ({{ e.percent }}%){{ e.comments_count }}{{ e.receipts_count }} - {% if e.total_expense > 0 %} + {% endif %} + {{ e.total_count }}{{ e.purchased_count }}/{{ e.total_count }} ({{ e.percent }}%){{ e.comments_count }}{{ e.receipts_count }} + {% if e.total_expense > 0 %} {{ '%.2f'|format(e.total_expense) }} PLN - {% else %} + {% else %} - - {% endif %} - - ✏️ Edytuj - 🗑️ Usuń -
    + ✏️ Edytuj + 🗑️ Usuń +
    -
    - - +
    +
    + + -