zmiany w serwowaniu js

This commit is contained in:
Mateusz Gruszczyński
2025-07-05 00:06:53 +02:00
parent 93f0fb0f33
commit 74244fd877
5 changed files with 49 additions and 65 deletions

90
app.py
View File

@ -72,9 +72,9 @@ class Expense(db.Model):
added_at = db.Column(db.DateTime, default=datetime.utcnow)
receipt_filename = db.Column(db.String(255), nullable=True)
@static_bp.route('/static/js/live.js')
def serve_live_js():
response = send_from_directory('static/js', 'live.js')
@static_bp.route('/static/js/<path:filename>')
def serve_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
@ -106,18 +106,15 @@ def inject_time():
def inject_has_authorized_cookie():
return {'has_authorized_cookie': 'authorized' in request.cookies}
@app.before_request
def require_system_password():
if 'authorized' not in request.cookies \
and request.endpoint != 'system_auth' \
and not request.endpoint.startswith('static') \
and not request.endpoint.startswith('login'):
# Jeśli wchodzi na '/', nie dodawaj next
if request.path == '/':
return redirect(url_for('system_auth'))
else:
# W innym przypadku poprawiamy URL jak wcześniej
from urllib.parse import urlparse, urlunparse
parsed = urlparse(request.url)
fixed_url = urlunparse(parsed._replace(netloc=request.host))
@ -135,7 +132,6 @@ def file_mtime_filter(path):
def filesizeformat_filter(path):
try:
size = os.path.getsize(path)
# Jeśli chcesz dokładniejszy format, np. KB, MB
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024.0:
return f"{size:.1f} {unit}"
@ -144,30 +140,6 @@ def filesizeformat_filter(path):
except Exception:
return "N/A"
@app.route('/system-auth', methods=['GET', 'POST'])
def system_auth():
next_page = request.args.get('next') or url_for('index_guest')
if request.method == 'POST':
if request.form['password'] == SYSTEM_PASSWORD:
db.create_all()
if not User.query.filter_by(is_admin=True).first():
admin_user = User(
username=DEFAULT_ADMIN_USERNAME,
password_hash=generate_password_hash(DEFAULT_ADMIN_PASSWORD),
is_admin=True
)
db.session.add(admin_user)
db.session.commit()
flash(f'Utworzono konto administratora: login={DEFAULT_ADMIN_USERNAME}, hasło={DEFAULT_ADMIN_PASSWORD}')
resp = redirect(next_page)
resp.set_cookie('authorized', AUTHORIZED_COOKIE_VALUE)
return resp
flash('Nieprawidłowe hasło do systemu','danger')
return render_template('system_auth.html')
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@ -191,7 +163,6 @@ def index_guest():
(ShoppingList.expires_at == None) | (ShoppingList.expires_at > now)
).order_by(ShoppingList.created_at.desc()).all()
# Publiczne listy innych użytkowników
public_lists = ShoppingList.query.filter(
ShoppingList.is_public == True,
ShoppingList.owner_id != current_user.id,
@ -206,7 +177,6 @@ def index_guest():
ShoppingList.is_archived == False
).order_by(ShoppingList.created_at.desc()).all()
# Liczenie produktów i wydatków
for l in user_lists + public_lists:
items = Item.query.filter_by(list_id=l.id).all()
l.total_count = len(items)
@ -214,7 +184,30 @@ def index_guest():
expenses = Expense.query.filter_by(list_id=l.id).all()
l.total_expense = sum(e.amount for e in expenses)
return render_template("index.html", user_lists=user_lists, public_lists=public_lists)
return render_template("main.html", user_lists=user_lists, public_lists=public_lists)
@app.route('/system-auth', methods=['GET', 'POST'])
def system_auth():
next_page = request.args.get('next') or url_for('index_guest')
if request.method == 'POST':
if request.form['password'] == SYSTEM_PASSWORD:
db.create_all()
if not User.query.filter_by(is_admin=True).first():
admin_user = User(
username=DEFAULT_ADMIN_USERNAME,
password_hash=generate_password_hash(DEFAULT_ADMIN_PASSWORD),
is_admin=True
)
db.session.add(admin_user)
db.session.commit()
flash(f'Utworzono konto administratora: login={DEFAULT_ADMIN_USERNAME}, hasło={DEFAULT_ADMIN_PASSWORD}')
resp = redirect(next_page)
resp.set_cookie('authorized', AUTHORIZED_COOKIE_VALUE)
return resp
flash('Nieprawidłowe hasło do systemu','danger')
return render_template('system_auth.html')
@app.route('/archive_my_list/<int:list_id>')
@login_required
@ -431,15 +424,6 @@ def uploaded_file(filename):
response.headers.pop('Pragma', None)
return response
# chyba do usuniecia przeniesione na eventy socket.io
@app.route('/update-note/<int:item_id>', methods=['POST'])
def update_note(item_id):
item = Item.query.get_or_404(item_id)
note = request.form.get('note')
item.note = note
db.session.commit()
return {'success': True}
@app.route('/admin')
@login_required
def admin_panel():
@ -450,8 +434,6 @@ def admin_panel():
list_count = ShoppingList.query.count()
item_count = Item.query.count()
all_lists = ShoppingList.query.options(db.joinedload(ShoppingList.owner)).all()
# Pobierz folder uploadów
all_files = os.listdir(app.config['UPLOAD_FOLDER'])
enriched_lists = []
@ -476,7 +458,6 @@ def admin_panel():
'total_expense': total_expense
})
# Najczęściej kupowane produkty
top_products = (
db.session.query(Item.name, func.count(Item.id).label('count'))
.filter(Item.purchased == True)
@ -487,8 +468,6 @@ def admin_panel():
)
purchased_items_count = Item.query.filter_by(purchased=True).count()
# Podsumowanie wydatków
total_expense_sum = db.session.query(func.sum(Expense.amount)).scalar() or 0
current_year = datetime.utcnow().year
@ -519,7 +498,6 @@ def admin_panel():
month_expense_sum=month_expense_sum,
)
@app.route('/admin/delete_list/<int:list_id>')
@login_required
def delete_list(list_id):
@ -595,7 +573,6 @@ def delete_user(user_id):
flash('Użytkownik usunięty', 'success')
return redirect(url_for('list_users'))
@app.route('/admin/receipts')
@login_required
def admin_receipts():
@ -622,7 +599,6 @@ def delete_receipt(filename):
flash('Plik nie istnieje', 'danger')
return redirect(url_for('admin_receipts'))
@app.route('/admin/delete_selected_lists', methods=['POST'])
@login_required
def delete_selected_lists():
@ -659,7 +635,6 @@ def delete_all_items():
flash('Usunięto wszystkie produkty', 'success')
return redirect(url_for('admin_panel'))
@app.route('/admin/edit_list/<int:list_id>', methods=['GET', 'POST'])
@login_required
def edit_list(list_id):
@ -720,6 +695,16 @@ def edit_list(list_id):
return render_template('admin/edit_list.html', list=l, total_expense=total_expense, users=users)
# chyba do usuniecia przeniesione na eventy socket.io
@app.route('/update-note/<int:item_id>', methods=['POST'])
def update_note(item_id):
item = Item.query.get_or_404(item_id)
note = request.form.get('note')
item.note = note
db.session.commit()
return {'success': True}
# =========================================================================================
# SOCKET.IO
# =========================================================================================
@ -860,7 +845,6 @@ def handle_add_expense(data):
'total': total
}, to=str(list_id))
@app.cli.command('create_db')
def create_db():
db.create_all()

View File

@ -9,9 +9,11 @@
<link rel="icon" type="image/svg+xml" href="{{ url_for('favicon') }}">
<script src="https://cdn.socket.io/4.6.1/socket.io.min.js"></script>
<script src="{{ url_for('static_bp.serve_live_js') }}?v={{ time.time() | int }}"></script>
<script src="{{ url_for('static', filename='js/toasts.js') }}"></script>
<script src="{{ url_for('static', filename='js/hide_list.js') }}"></script>
<script src="{{ url_for('static_bp.serve_js', filename='live.js') }}"></script>
<script src="{{ url_for('static_bp.serve_js', filename='toasts.js') }}"></script>
<script src="{{ url_for('static_bp.serve_js', filename='hide_list.js') }}"></script>
</head>
<body class="bg-dark text-white">

View File

@ -3,15 +3,13 @@
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap">
<h2 class="mb-2">
Lista: <strong>{{ list.title }}</strong>
{% if list.is_archived %}
<span class="badge bg-secondary ms-2">(Archiwalna)</span>
{% endif %}</h2>
<h2 class="mb-2">
Lista: <strong>{{ list.title }}</strong>
{% if list.is_archived %}
<span class="badge bg-secondary ms-2">(Archiwalna)</span>
{% endif %}
</h2>
<a href="/" class="btn btn-outline-secondary">← Powrót do list</a>
<a href="/" class="btn btn-outline-secondary">← Powrót do list</a>
</div>
<div id="share-card" class="card bg-dark text-white mb-4">

View File

@ -118,7 +118,7 @@
setupList(LIST_ID, 'Gość');
</script>
<script src="{{ url_for('static', filename='js/list_guest.js') }}"></script>
<script src="{{ url_for('static_bp.serve_js', filename='list_guest.js') }}"></script>
<style>
.large-checkbox {