Compare commits

..

5 Commits

3 changed files with 79 additions and 101 deletions
+66 -94
View File
@@ -10248,74 +10248,58 @@ def get_period_times(booking_date, period_num):
"""---------------------------------------------------------Borrowing-----------------------------------------------------------------""" """---------------------------------------------------------Borrowing-----------------------------------------------------------------"""
@app.route('/my_borrowed_items') @app.route('/my_borrowed_items')
def my_borrowed_items(): def my_borrowed_items():
""" """
Zeigt alle vom aktuellen Benutzer ausgeliehenen und geplanten Objekte an. Zeigt alle vom aktuellen Benutzer ausgeliehenen und geplanten Objekte an.
Returns:
Response: Gerendertes Template mit den ausgeliehenen und geplanten Objekten des Benutzers
""" """
if 'username' not in session: if 'username' not in session:
flash('Bitte melden Sie sich an, um Ihre ausgeliehenen Objekte anzuzeigen', 'error') flash('Bitte melden Sie sich an, um Ihre ausgeliehenen Objekte anzuzeigen', 'error')
return redirect(url_for('login', next=request.path)) return redirect(url_for('login', next=request.path))
username = session['username'] username = session['username']
client = MongoClient(MONGODB_HOST, MONGODB_PORT) client = MongoClient(MONGODB_HOST, MONGODB_PORT)
db = client[MONGODB_DB] db = client[MONGODB_DB]
items_collection = db.items items_collection = db['items']
ausleihungen_collection = db.ausleihungen ausleihungen_collection = db['ausleihungen']
# Get current time for comparison all_ausleihungen = list(ausleihungen_collection.find({
current_time = datetime.datetime.now() 'Status': {'$in': ['active', 'planned']}
# Check if user is admin
user_is_admin = False
if 'is_admin' in session:
user_is_admin = session['is_admin']
# Get items currently borrowed by the user (where Verfuegbar=false and User=username)
borrowed_items = list(items_collection.find({'Verfuegbar': False, 'User': username}))
# Get active and planned ausleihungen for the user
active_ausleihungen = list(ausleihungen_collection.find({
'User': username,
'Status': 'active'
})) }))
planned_ausleihungen = list(ausleihungen_collection.find({
'User': username,
'Status': 'planned'
}))
# Process items
active_items = [] active_items = []
planned_items = [] planned_items = []
processed_item_ids = set() # Keep track of processed item IDs to avoid duplicates processed_item_ids = set()
# First, process items that are directly marked as borrowed by the user for appointment in all_ausleihungen:
for item in borrowed_items: raw_user = appointment.get('User', '')
# Convert ObjectId to string for template try:
item['_id'] = str(item['_id']) decrypted_user = decrypt_text(raw_user) if raw_user else ''
active_items.append(item) except Exception as e:
processed_item_ids.add(item['_id']) app.logger.error(f"Entschlüsselungsfehler: {e}")
decrypted_user = ''
# Process active appointments
for appointment in active_ausleihungen: if decrypted_user != username:
# Get the item ID from the appointment continue
item_id = appointment.get('Item') item_id = appointment.get('Item')
if not item_id:
if not item_id or str(item_id) in processed_item_ids: continue
continue # Skip if we already processed this item or no item ID
try:
# Get item details if isinstance(item_id, str):
item_obj = items_collection.find_one({'_id': ObjectId(item_id)}) query_id = ObjectId(item_id)
else:
query_id = item_id
item_obj = items_collection.find_one({'_id': query_id})
except Exception:
item_obj = None
if item_obj: if item_obj:
# Convert ObjectId to string for template
item_obj['_id'] = str(item_obj['_id']) item_obj['_id'] = str(item_obj['_id'])
# Add appointment data
item_obj['AppointmentData'] = { item_obj['AppointmentData'] = {
'id': str(appointment['_id']), 'id': str(appointment['_id']),
'start': appointment.get('Start'), 'start': appointment.get('Start'),
@@ -10324,55 +10308,43 @@ def my_borrowed_items():
'period': appointment.get('Period'), 'period': appointment.get('Period'),
'status': appointment.get('VerifiedStatus', appointment.get('Status')), 'status': appointment.get('VerifiedStatus', appointment.get('Status')),
} }
# Mark that this item is part of an active appointment status = appointment.get('Status')
item_obj['ActiveAppointment'] = True if status == 'active':
item_obj['ActiveAppointment'] = True
# Add to the list only if not already there if str(item_obj['_id']) not in processed_item_ids:
if str(item_obj['_id']) not in processed_item_ids: active_items.append(item_obj)
active_items.append(item_obj) processed_item_ids.add(str(item_obj['_id']))
processed_item_ids.add(str(item_obj['_id'])) elif status == 'planned':
planned_items.append(item_obj)
# Process planned appointments
for appointment in planned_ausleihungen: all_borrowed_items = list(items_collection.find({'Verfuegbar': False}))
item_id = appointment.get('Item') for item in all_borrowed_items:
raw_item_user = item.get('User', '')
if not item_id: try:
continue dec_item_user = decrypt_text(raw_item_user) if raw_item_user else ''
except Exception:
item_obj = items_collection.find_one({'_id': ObjectId(item_id)}) dec_item_user = ''
if item_obj: if dec_item_user == username and str(item['_id']) not in processed_item_ids:
item_obj['_id'] = str(item_obj['_id']) item['_id'] = str(item['_id'])
item['ActiveAppointment'] = True
# Add appointment data item['AppointmentData'] = {'status': 'active (no document)'}
item_obj['AppointmentData'] = { active_items.append(item)
'id': str(appointment['_id']), processed_item_ids.add(item['_id'])
'start': appointment.get('Start'),
'end': appointment.get('End'),
'notes': appointment.get('Notes'),
'period': appointment.get('Period'),
'status': appointment.get('Status'),
}
planned_items.append(item_obj)
client.close() client.close()
# DEBUG: Log what we're passing to the template # DEBUG Logging
app.logger.info(f"Passing {len(active_items)} active items and {len(planned_items)} planned items to template") app.logger.info(
if planned_items: f"Passing {len(active_items)} active items and {len(planned_items)} planned items to template for user {username}")
for i, item in enumerate(planned_items):
app.logger.info(f"Planned item {i+1}: {item['Name']}, Appointment ID: {item['AppointmentData']['id']}")
return render_template( return render_template(
'my_borrowed_items.html', 'my_borrowed_items.html',
items=active_items, items=active_items,
planned_items=planned_items, planned_items=planned_items
user_is_admin=user_is_admin
) )
@app.route('/api/push/vapid-key', methods=['GET']) @app.route('/api/push/vapid-key', methods=['GET'])
def get_vapid_key(): def get_vapid_key():
""" """
+8 -3
View File
@@ -476,8 +476,13 @@ def check_nm_pwd(username, password):
user_record = users.find_one(query) user_record = users.find_one(query)
if user_record is None: if user_record is None:
logger.warning("Kein Benutzer für %r in DB %r gefunden.", dp.encrypt_text(username), db_name) query = {'$or': [{'Username': username}, {'username': username}]}
return None user_record_fallback = users.find_one(query)
if user_record_fallback is None:
logger.warning("Kein Benutzer für %r in DB %r gefunden.", dp.encrypt_text(username), db_name)
return None
else:
user_record = user_record_fallback
stored_password = user_record.get('Password') or user_record.get('password') stored_password = user_record.get('Password') or user_record.get('password')
@@ -617,7 +622,7 @@ def get_user(username):
def find_in_db(database_name): def find_in_db(database_name):
db = client[database_name] db = client[database_name]
users = db['users'] users = db['users']
return users.find_one({'Username': dp.encrypt_text(username)}) or users.find_one({'username': dp.encrypt_text(username)}) return users.find_one({'Username': dp.encrypt_text(username)}) or users.find_one({'username': dp.encrypt_text(username)}) or users.find_one({'username': username}) or users.find_one({'Username': username})
tenant_db, tenant_id = _resolve_request_tenant_db() tenant_db, tenant_id = _resolve_request_tenant_db()
if tenant_db: if tenant_db:
+5 -4
View File
@@ -200,6 +200,7 @@ sys.path.insert(0, "/app")
sys.path.insert(0, "/app/Web") sys.path.insert(0, "/app/Web")
from Web.modules.database import settings from Web.modules.database import settings
from pymongo import MongoClient from pymongo import MongoClient
import Web.modules.inventarsystem.data_protection as dp
tenant_id = sys.argv[1].lower() tenant_id = sys.argv[1].lower()
mode = sys.argv[2] mode = sys.argv[2]
@@ -244,14 +245,14 @@ page_permissions = {
"manage_locations": True, "manage_locations": True,
} }
if db.users.count_documents({"Username": "admin"}) == 0: if db.users.count_documents({"Username": dp.encrypt_text("admin")}) == 0:
db.users.insert_one({ db.users.insert_one({
"Username": "admin", "Username": dp.encrypt_text("admin"),
"Password": hashed_pw_string, "Password": hashed_pw_string,
"Admin": True, "Admin": True,
"active_ausleihung": None, "active_ausleihung": None,
"name": "Admin", "name": dp.encrypt_text("Admin"),
"last_name": "User", "last_name": dp.encrypt_text("User"),
"IsStudent": False, "IsStudent": False,
"PermissionPreset": "full_access", "PermissionPreset": "full_access",
"ActionPermissions": action_permissions, "ActionPermissions": action_permissions,