Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1bfe998906 | |||
| 3fdbadd454 | |||
| 110327b73e | |||
| d8cd1906b3 | |||
| b8a7d6c797 | |||
| ac3e48da3d | |||
| 5d9069e690 | |||
| 16f34a1425 | |||
| a12eea15d7 | |||
| 5ba5aea6f6 | |||
| 6e7d961a98 |
+3
-1
@@ -2,4 +2,6 @@ dist
|
||||
logs
|
||||
certs
|
||||
build
|
||||
.venv
|
||||
.venv
|
||||
__pycache__
|
||||
.pyc
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+262
-20
@@ -1123,6 +1123,8 @@ def update_appointment_statuses():
|
||||
|
||||
for appointment in appointments_to_check:
|
||||
old_status = appointment.get('Status')
|
||||
activation_user = str(appointment.get('User') or '').strip()
|
||||
activation_item_name = str(appointment.get('Item') or 'Termin')
|
||||
|
||||
# Aktuellen Status bestimmen
|
||||
new_status = au.get_current_status(appointment, log_changes=True, user='scheduler')
|
||||
@@ -1138,6 +1140,7 @@ def update_appointment_statuses():
|
||||
item_id_str = appointment.get('Item')
|
||||
conflict_detected = False
|
||||
conflict_note = ''
|
||||
item_name = item_id_str or 'Termin'
|
||||
if item_id_str:
|
||||
try:
|
||||
item_doc = items_col.find_one(
|
||||
@@ -1145,6 +1148,8 @@ def update_appointment_statuses():
|
||||
{'Verfuegbar': 1, 'User': 1, 'Name': 1, 'Exemplare': 1}
|
||||
)
|
||||
if item_doc:
|
||||
item_name = item_doc.get('Name', item_id_str)
|
||||
activation_item_name = item_name
|
||||
total_exemplare = int(item_doc.get('Exemplare', 1))
|
||||
# Count how many active (non-planned) borrows currently hold this item
|
||||
active_borrows = ausleihungen.count_documents({
|
||||
@@ -1191,8 +1196,46 @@ def update_appointment_statuses():
|
||||
updated_count += 1
|
||||
if new_status == 'active':
|
||||
activated_count += 1
|
||||
# Make item unshareable if no conflict is detected
|
||||
if old_status == 'planned' and appointment.get('Item') and not extra_fields.get('ConflictDetected', False):
|
||||
try:
|
||||
it.update_item_status(str(appointment.get('Item')), False, activation_user)
|
||||
except Exception as e:
|
||||
app.logger.warning(f"Could not update item status to False for {appointment['_id']}: {e}")
|
||||
|
||||
elif new_status == 'completed':
|
||||
completed_count += 1
|
||||
# Make item available again
|
||||
if appointment.get('Item'):
|
||||
try:
|
||||
it.update_item_status(str(appointment.get('Item')), True)
|
||||
except Exception as e:
|
||||
app.logger.warning(f"Could not update item status to True for {appointment['_id']}: {e}")
|
||||
|
||||
# Create activation notification even if another worker already updated the status.
|
||||
if old_status == 'planned' and new_status == 'active' and activation_user:
|
||||
try:
|
||||
_create_notification(
|
||||
db,
|
||||
audience='user',
|
||||
notif_type='appointment_activated',
|
||||
title='Reservierung ist jetzt aktiv',
|
||||
message=(
|
||||
f"Deine geplante Ausleihe für {activation_item_name} startet jetzt."
|
||||
),
|
||||
target_user=activation_user,
|
||||
reference={
|
||||
'appointment_id': str(appointment.get('_id')),
|
||||
'item_id': str(appointment.get('Item') or ''),
|
||||
'event': 'activated',
|
||||
},
|
||||
unique_key=f"appointment:activated:{appointment.get('_id')}",
|
||||
severity='info',
|
||||
)
|
||||
except Exception as notif_err:
|
||||
app.logger.warning(
|
||||
f"Failed to create activation notification for {appointment.get('_id')}: {notif_err}"
|
||||
)
|
||||
|
||||
client.close()
|
||||
|
||||
@@ -1204,17 +1247,70 @@ def update_appointment_statuses():
|
||||
except Exception as e:
|
||||
app.logger.error(f"Automatic appointment status update failed: {e}")
|
||||
|
||||
# Schedule jobs
|
||||
# Schedule jobs - only start scheduler if this is the main process or a single-worker deployment
|
||||
# This prevents race conditions in multi-worker Gunicorn environments
|
||||
scheduler = BackgroundScheduler()
|
||||
if cfg.SCHEDULER_ENABLED:
|
||||
scheduler.add_job(func=create_daily_backup, trigger="interval", hours=cfg.BACKUP_INTERVAL_HOURS)
|
||||
scheduler.add_job(func=update_appointment_statuses, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
|
||||
scheduler.add_job(func=create_return_reminders, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
|
||||
scheduler.start()
|
||||
_scheduler_initialized = False
|
||||
|
||||
def _initialize_scheduler():
|
||||
"""Initialize the background scheduler in a safe way for multi-worker deployments."""
|
||||
global _scheduler_initialized
|
||||
if _scheduler_initialized or not cfg.SCHEDULER_ENABLED:
|
||||
return
|
||||
|
||||
try:
|
||||
# For multi-worker Gunicorn, use a lock file to ensure only one instance starts the scheduler
|
||||
# Clean up any stale lock file from previous runs (older than 5 minutes)
|
||||
scheduler_lock_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.scheduler_lock')
|
||||
try:
|
||||
if os.path.exists(scheduler_lock_path):
|
||||
lock_age = time.time() - os.path.getmtime(scheduler_lock_path)
|
||||
if lock_age > 300: # 5 minutes - indicates a stale lock from a previous container run
|
||||
os.remove(scheduler_lock_path)
|
||||
app.logger.info(f"Removed stale scheduler lock file (age: {lock_age:.0f}s)")
|
||||
except Exception:
|
||||
pass # If we can't clean up, continue anyway
|
||||
|
||||
try:
|
||||
# Try to create the lock file - only succeeds if it doesn't exist
|
||||
lock_fd = os.open(scheduler_lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
|
||||
os.close(lock_fd)
|
||||
should_start = True
|
||||
except FileExistsError:
|
||||
should_start = False
|
||||
app.logger.warning("Scheduler lock exists - another process is already running the scheduler")
|
||||
|
||||
if should_start:
|
||||
scheduler.add_job(func=create_daily_backup, trigger="interval", hours=cfg.BACKUP_INTERVAL_HOURS)
|
||||
scheduler.add_job(func=update_appointment_statuses, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
|
||||
scheduler.add_job(func=create_return_reminders, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
|
||||
scheduler.start()
|
||||
_scheduler_initialized = True
|
||||
app.logger.info(f"Scheduler started successfully (interval={cfg.SCHEDULER_INTERVAL_MIN} min)")
|
||||
else:
|
||||
app.logger.info("Scheduler skipped - another worker instance is running it")
|
||||
except Exception as e:
|
||||
app.logger.error(f"Failed to initialize scheduler: {e}")
|
||||
_scheduler_initialized = False
|
||||
|
||||
# Initialize scheduler on app startup
|
||||
_initialize_scheduler()
|
||||
|
||||
# Register shutdown handler to stop scheduler when app is terminated
|
||||
import atexit
|
||||
atexit.register(lambda: scheduler.shutdown() if cfg.SCHEDULER_ENABLED else None)
|
||||
def _shutdown_scheduler():
|
||||
if cfg.SCHEDULER_ENABLED and _scheduler_initialized:
|
||||
try:
|
||||
scheduler.shutdown()
|
||||
lock_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.scheduler_lock')
|
||||
try:
|
||||
os.remove(lock_path)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
app.logger.error(f"Error during scheduler shutdown: {e}")
|
||||
|
||||
atexit.register(_shutdown_scheduler)
|
||||
|
||||
def allowed_file(filename, file_content=None, max_size_mb=cfg.MAX_UPLOAD_MB):
|
||||
"""
|
||||
@@ -4040,6 +4136,9 @@ def get_items():
|
||||
'Filter3': 1,
|
||||
'Ort': 1,
|
||||
'User': 1,
|
||||
'BlockedNow': 1,
|
||||
'Reservierbar': 1,
|
||||
'HasDamage': 1,
|
||||
'ItemType': 1,
|
||||
}
|
||||
|
||||
@@ -4183,6 +4282,83 @@ def get_item_json(id):
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
@app.route('/get_bookings')
|
||||
def get_bookings():
|
||||
"""Return calendar bookings for the current user session."""
|
||||
if 'username' not in session:
|
||||
return jsonify({'ok': False, 'error': 'unauthorized'}), 401
|
||||
|
||||
client = None
|
||||
try:
|
||||
username = session.get('username')
|
||||
start = request.args.get('start')
|
||||
end = request.args.get('end')
|
||||
|
||||
bookings = au.get_ausleihungen(status=['planned', 'active', 'completed'], start=start, end=end)
|
||||
|
||||
client = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db = client[MONGODB_DB]
|
||||
items_col = db['items']
|
||||
|
||||
result = []
|
||||
for booking in bookings:
|
||||
start_dt = booking.get('Start')
|
||||
if not start_dt:
|
||||
continue
|
||||
|
||||
end_dt = booking.get('End')
|
||||
if not end_dt and isinstance(start_dt, datetime.datetime):
|
||||
end_dt = start_dt + datetime.timedelta(minutes=45)
|
||||
elif not end_dt:
|
||||
end_dt = start_dt
|
||||
|
||||
item_id = str(booking.get('Item') or '')
|
||||
item_doc = None
|
||||
if item_id:
|
||||
try:
|
||||
item_doc = items_col.find_one({'_id': ObjectId(item_id)})
|
||||
except Exception:
|
||||
item_doc = None
|
||||
|
||||
item_name = item_id or 'Ausleihe'
|
||||
item_borrower = ''
|
||||
if item_doc:
|
||||
item_name = item_doc.get('Name') or item_doc.get('Code_4') or item_name
|
||||
borrower_info = item_doc.get('BorrowerInfo') or {}
|
||||
borrower_name = borrower_info.get('User') if isinstance(borrower_info, dict) else ''
|
||||
item_borrower = str(item_doc.get('User') or borrower_name or '')
|
||||
|
||||
status = booking.get('Status') or 'unknown'
|
||||
if status == 'active':
|
||||
status = 'current'
|
||||
|
||||
period = booking.get('Period')
|
||||
title = item_name
|
||||
if period:
|
||||
title = f"{title} - {period}. Std"
|
||||
|
||||
result.append({
|
||||
'id': str(booking.get('_id')),
|
||||
'title': title,
|
||||
'start': start_dt.isoformat() if isinstance(start_dt, datetime.datetime) else str(start_dt),
|
||||
'end': end_dt.isoformat() if isinstance(end_dt, datetime.datetime) else str(end_dt),
|
||||
'status': status,
|
||||
'itemId': item_id,
|
||||
'userName': str(booking.get('User') or ''),
|
||||
'notes': str(booking.get('Notes') or ''),
|
||||
'period': period,
|
||||
'isCurrentUser': str(booking.get('User') or '') == username,
|
||||
'itemBorrower': item_borrower,
|
||||
})
|
||||
|
||||
return jsonify({'ok': True, 'bookings': result})
|
||||
except Exception as e:
|
||||
return jsonify({'ok': False, 'error': str(e), 'bookings': []}), 500
|
||||
finally:
|
||||
if client:
|
||||
client.close()
|
||||
|
||||
|
||||
@app.route('/api/booking_conflicts')
|
||||
def api_booking_conflicts():
|
||||
"""
|
||||
@@ -6577,17 +6753,19 @@ def plan_booking():
|
||||
|
||||
try:
|
||||
# Extract form data
|
||||
item_id = html.escape(request.form.get('item_id'))
|
||||
start_date_str = html.escape(request.form.get('booking_date')) # Changed from start_date to booking_date
|
||||
end_date_str = html.escape(request.form.get('booking_end_date')) # Changed from end_date to booking_end_date
|
||||
period_start = html.escape(request.form.get('period_start'))
|
||||
period_end = html.escape(request.form.get('period_end'))
|
||||
notes = html.escape(request.form.get('notes', ''))
|
||||
booking_type = html.escape(request.form.get('booking_type', 'single'))
|
||||
item_id = (request.form.get('item_id') or '').strip()
|
||||
start_date_str = (request.form.get('booking_date') or request.form.get('start_date') or '').strip()
|
||||
end_date_str = (request.form.get('booking_end_date') or request.form.get('end_date') or '').strip()
|
||||
period_start = (request.form.get('period_start') or '').strip()
|
||||
period_end = (request.form.get('period_end') or '').strip()
|
||||
notes = html.escape(request.form.get('notes', '') or '')
|
||||
booking_type = (request.form.get('booking_type', 'single') or 'single').strip().lower()
|
||||
|
||||
# Validate inputs
|
||||
if not all([item_id, start_date_str, end_date_str, period_start]):
|
||||
if not all([item_id, start_date_str, period_start]):
|
||||
return {"success": False, "error": "Missing required fields"}, 400
|
||||
if not end_date_str:
|
||||
end_date_str = start_date_str
|
||||
|
||||
# Parse dates
|
||||
try:
|
||||
@@ -8857,8 +9035,7 @@ def my_borrowed_items():
|
||||
|
||||
planned_ausleihungen = list(ausleihungen_collection.find({
|
||||
'User': username,
|
||||
'Status': 'planned',
|
||||
'Start': {'$gt': current_time}
|
||||
'Status': 'planned'
|
||||
}))
|
||||
|
||||
# DEBUG: Log the number of planned appointments found
|
||||
@@ -9490,21 +9667,76 @@ def schedule_appointment():
|
||||
print(f"Error checking for booking conflicts: {e}")
|
||||
return jsonify({'success': False, 'message': f'Fehler beim Prüfen der Verfügbarkeit: {str(e)}'}), 500
|
||||
|
||||
# Create the appointment as a planned booking
|
||||
# Check if the appointment should already be active
|
||||
now = datetime.datetime.now()
|
||||
initial_status = 'active' if start_datetime <= now else 'planned'
|
||||
|
||||
# Create the appointment
|
||||
try:
|
||||
appointment_id = au.add_planned_booking(
|
||||
# Use add_ausleihung directly to set the correct initial status
|
||||
appointment_id = au.add_ausleihung(
|
||||
item_id=item_id,
|
||||
user=session['username'],
|
||||
start_date=start_datetime,
|
||||
end_date=end_datetime,
|
||||
notes=notes,
|
||||
status=initial_status,
|
||||
period=booking_period # Will be None for multi-day
|
||||
)
|
||||
|
||||
# If it became active immediately, log it and send a notification
|
||||
if initial_status == 'active' and appointment_id:
|
||||
app.logger.info(f"Appointment {appointment_id} scheduled retroactively as active.")
|
||||
|
||||
# Make the item unavailable since it is now actively borrowed
|
||||
try:
|
||||
it.update_item_status(item_id, False, session['username'])
|
||||
except Exception as update_err:
|
||||
app.logger.warning(f"Failed to update item status when retroactively activating: {update_err}")
|
||||
|
||||
# We can also notify the user right away
|
||||
item_name = item.get('Name', 'Unbekannt')
|
||||
|
||||
# Log audit event
|
||||
_append_audit_event_standalone(
|
||||
'ausleihung_started',
|
||||
{
|
||||
'borrow_id': str(appointment_id),
|
||||
'item_id': item_id,
|
||||
'item_name': item_name,
|
||||
'user': session['username'],
|
||||
'status_before': 'planned',
|
||||
'status_after': 'active'
|
||||
}
|
||||
)
|
||||
|
||||
# Send notification
|
||||
try:
|
||||
client_temp = MongoClient(MONGODB_HOST, MONGODB_PORT)
|
||||
db_temp = client_temp[MONGODB_DB]
|
||||
_create_notification(
|
||||
db_temp,
|
||||
audience='user',
|
||||
notif_type='appointment_activated',
|
||||
title='Reservierung ist jetzt aktiv',
|
||||
message=f"Deine geplante Ausleihe für {item_name} startet jetzt.",
|
||||
target_user=session['username'],
|
||||
reference={
|
||||
'appointment_id': str(appointment_id),
|
||||
'item_id': str(item_id),
|
||||
'event': 'activated',
|
||||
},
|
||||
unique_key=f"appointment:activated:{appointment_id}",
|
||||
severity='info'
|
||||
)
|
||||
client_temp.close()
|
||||
except Exception as notif_err:
|
||||
app.logger.error(f"Error sending immediate active notification: {notif_err}")
|
||||
|
||||
if not appointment_id:
|
||||
return jsonify({'success': False, 'message': 'Termin konnte nicht erstellt werden'}), 500
|
||||
except Exception as e:
|
||||
print(f"Error creating planned booking: {e}")
|
||||
print(f"Error creating booking: {e}")
|
||||
return jsonify({'success': False, 'message': f'Fehler beim Erstellen des Termins: {str(e)}'}), 500
|
||||
|
||||
# If we got this far, we have a valid appointment_id
|
||||
@@ -9591,6 +9823,16 @@ def cancel_ausleihung_route(id):
|
||||
if au.cancel_ausleihung(id):
|
||||
print(f"Successfully canceled ausleihung with ID: {id}")
|
||||
flash('Ausleihung wurde erfolgreich storniert', 'success')
|
||||
|
||||
# If the booking was already active, make the item available again
|
||||
item_id = str(ausleihung.get('Item')) if ausleihung.get('Item') is not None else None
|
||||
if ausleihung_status == 'active' and item_id:
|
||||
try:
|
||||
it.update_item_status(item_id, True)
|
||||
print(f"Restored availability of item {item_id} after active cancellation")
|
||||
except Exception as status_err:
|
||||
print(f"Warning: could not restore availability of item {item_id}: {status_err}")
|
||||
|
||||
_append_audit_event_standalone(
|
||||
'ausleihung_cancelled',
|
||||
{
|
||||
|
||||
+4
-2
@@ -287,15 +287,17 @@ def update_item_status(id, verfuegbar, user=None):
|
||||
'LastUpdated': datetime.datetime.now()
|
||||
}
|
||||
|
||||
update_query = {'$set': update_data}
|
||||
|
||||
if user is not None:
|
||||
update_data['User'] = user
|
||||
elif verfuegbar:
|
||||
# If item is being marked as available, clear the user field
|
||||
update_data['$unset'] = {'User': ""}
|
||||
update_query['$unset'] = {'User': ""}
|
||||
|
||||
result = items.update_one(
|
||||
{'_id': ObjectId(id)},
|
||||
{'$set': update_data}
|
||||
update_query
|
||||
)
|
||||
|
||||
client.close()
|
||||
|
||||
+101
-10
@@ -799,10 +799,8 @@
|
||||
}
|
||||
|
||||
function loadItems(offset = 0, append = false) {
|
||||
// Für Pages nach der ersten: Explizit vollständige Daten laden (light_mode=false)
|
||||
// Erste Page: light_mode wird automatisch enablet
|
||||
const lightModeParam = offset > 0 ? '&light_mode=false' : '';
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ITEMS_PAGE_SIZE}${lightModeParam}`)
|
||||
// Keep list payload lightweight; full details are fetched on-demand in openItemQuick.
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ITEMS_PAGE_SIZE}&light_mode=true`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const itemsContainer = document.querySelector('#items-container');
|
||||
@@ -1073,12 +1071,9 @@
|
||||
|
||||
// Stop event from bubbling up
|
||||
e.stopPropagation();
|
||||
|
||||
// Get full item data with correct image paths
|
||||
const modalItemData = {...item};
|
||||
modalItemData.Images = item.Images ? item.Images.map(img => "{{ url_for('uploaded_file', filename='') }}" + img) : [];
|
||||
|
||||
openItemModal(modalItemData);
|
||||
|
||||
// Always load full, up-to-date item details for the modal.
|
||||
openItemQuick(item._id);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -1414,6 +1409,76 @@
|
||||
}
|
||||
|
||||
function openItemModal(item) {
|
||||
const escapeHtml = (value) => String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
|
||||
const formatHistoryDate = (value) => {
|
||||
if (!value) return '-';
|
||||
const dt = new Date(value);
|
||||
if (Number.isNaN(dt.getTime())) {
|
||||
return escapeHtml(value);
|
||||
}
|
||||
return dt.toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||||
};
|
||||
|
||||
const damageReports = Array.isArray(item.DamageReports) ? item.DamageReports : [];
|
||||
const damageRepairs = Array.isArray(item.DamageRepairs) ? item.DamageRepairs : [];
|
||||
const damageHistoryEntries = [];
|
||||
|
||||
damageReports.forEach((report) => {
|
||||
damageHistoryEntries.push({
|
||||
type: 'report',
|
||||
rawDate: report?.reported_at || null,
|
||||
dateLabel: formatHistoryDate(report?.reported_at),
|
||||
actor: escapeHtml(report?.reported_by || '-'),
|
||||
description: escapeHtml(report?.description || 'Schaden gemeldet'),
|
||||
meta: '',
|
||||
});
|
||||
});
|
||||
|
||||
damageRepairs.forEach((repair) => {
|
||||
const resolvedReports = Array.isArray(repair?.resolved_reports) ? repair.resolved_reports : [];
|
||||
damageHistoryEntries.push({
|
||||
type: 'repair',
|
||||
rawDate: repair?.repaired_at || null,
|
||||
dateLabel: formatHistoryDate(repair?.repaired_at),
|
||||
actor: escapeHtml(repair?.repaired_by || '-'),
|
||||
description: 'Als repariert markiert',
|
||||
meta: `${resolvedReports.length} Meldung(en) abgeschlossen`,
|
||||
});
|
||||
});
|
||||
|
||||
damageHistoryEntries.sort((a, b) => {
|
||||
const ta = a.rawDate ? new Date(a.rawDate).getTime() : 0;
|
||||
const tb = b.rawDate ? new Date(b.rawDate).getTime() : 0;
|
||||
return (Number.isNaN(tb) ? 0 : tb) - (Number.isNaN(ta) ? 0 : ta);
|
||||
});
|
||||
|
||||
const damageHistoryHtml = damageHistoryEntries.length
|
||||
? damageHistoryEntries.map((entry) => {
|
||||
const badgeStyle = entry.type === 'repair'
|
||||
? 'background:#dcfce7;color:#166534;'
|
||||
: 'background:#fee2e2;color:#991b1b;';
|
||||
const badgeText = entry.type === 'repair' ? 'Repariert' : 'Schaden';
|
||||
const metaLine = entry.meta ? `<div style="font-size:0.84rem;color:#4b5563;">${escapeHtml(entry.meta)}</div>` : '';
|
||||
return `
|
||||
<div style="border:1px solid #dbe3ee;border-radius:8px;padding:10px;background:#fff;display:grid;gap:6px;">
|
||||
<div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
|
||||
<span style="display:inline-block;padding:2px 8px;border-radius:999px;font-size:0.75rem;font-weight:700;${badgeStyle}">${badgeText}</span>
|
||||
<span style="font-size:0.84rem;color:#475569;">${entry.dateLabel}</span>
|
||||
</div>
|
||||
<div style="font-size:0.9rem;color:#0f172a;"><strong>Von:</strong> ${entry.actor}</div>
|
||||
<div style="font-size:0.92rem;color:#1f2937;">${entry.description}</div>
|
||||
${metaLine}
|
||||
</div>
|
||||
`;
|
||||
}).join('')
|
||||
: '<div style="font-size:0.92rem;color:#64748b;">Keine Beschädigungs-Historie vorhanden.</div>';
|
||||
|
||||
// Get modal elements
|
||||
const modal = document.getElementById('item-modal');
|
||||
const modalContent = document.getElementById('modal-content-wrapper');
|
||||
@@ -1571,6 +1636,19 @@
|
||||
<div class="detail-value">${item.Beschreibung || '-'}</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-group full-width" style="margin-top:12px;">
|
||||
<div class="detail-label" style="font-weight:600; color:#374151;">Beschädigungs-Historie</div>
|
||||
<div class="detail-value">
|
||||
<button id="toggle-damage-history" class="calendar-toggle-btn" style="margin-bottom:12px; padding:10px 16px; border-radius:6px; background:#f3f4f6; border:1px solid #d1d5db; font-weight:500; cursor:pointer; display:inline-flex; align-items:center; gap:8px; transition:all 0.2s ease;">
|
||||
<span>🛠️</span>
|
||||
<span id="toggle-damage-history-text">Historie anzeigen</span>
|
||||
</button>
|
||||
<div id="damage-history-panel" style="display:none; margin-top:8px; border:1px solid #e7edf5; border-radius:10px; padding:12px; background:#f8fafc;">
|
||||
<div style="display:grid; gap:10px;">${damageHistoryHtml}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-group full-width" style="margin-top:14px; padding:12px; border:1px solid #e5e7eb; border-radius:10px; background:#fbfbfd; box-shadow: 0 1px 1px rgba(0,0,0,0.03);">
|
||||
<div class="detail-label" style="font-weight:600; color:#374151;">Verfügbarkeit prüfen</div>
|
||||
<div class="detail-value">
|
||||
@@ -1687,6 +1765,9 @@
|
||||
const detailsPanel = document.getElementById('calendar-day-details');
|
||||
const detailsDate = document.getElementById('cal-details-date');
|
||||
const detailsList = document.getElementById('cal-details-list');
|
||||
const damageToggleBtn = document.getElementById('toggle-damage-history');
|
||||
const damageHistoryPanel = document.getElementById('damage-history-panel');
|
||||
const damageToggleText = document.getElementById('toggle-damage-history-text');
|
||||
|
||||
let bookings = [];
|
||||
let currentDate = new Date();
|
||||
@@ -1847,6 +1928,16 @@
|
||||
renderCalendar();
|
||||
});
|
||||
|
||||
damageToggleBtn?.addEventListener('click', () => {
|
||||
const shouldOpen = damageHistoryPanel.style.display === 'none';
|
||||
damageHistoryPanel.style.display = shouldOpen ? 'block' : 'none';
|
||||
if (damageToggleText) {
|
||||
damageToggleText.textContent = shouldOpen ? 'Historie verbergen' : 'Historie anzeigen';
|
||||
}
|
||||
damageToggleBtn.style.background = shouldOpen ? '#e0e7ff' : '#f3f4f6';
|
||||
damageToggleBtn.style.borderColor = shouldOpen ? '#818cf8' : '#d1d5db';
|
||||
});
|
||||
|
||||
// Availability checker (user)
|
||||
const availDate = document.getElementById('avail-date');
|
||||
const availStart = document.getElementById('avail-start');
|
||||
|
||||
@@ -3415,10 +3415,8 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
}
|
||||
|
||||
function loadItems(offset = 0, append = false) {
|
||||
// Für Pages nach der ersten: Explizit vollständige Daten laden (light_mode=false)
|
||||
// Erste Page: light_mode wird automatisch enablet
|
||||
const lightModeParam = offset > 0 ? '&light_mode=false' : '';
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ADMIN_ITEMS_PAGE_SIZE}${lightModeParam}`)
|
||||
// Keep list payload lightweight; full details are fetched on-demand in openItemQuick.
|
||||
return fetch(`{{ url_for('get_items') }}?offset=${offset}&limit=${MAIN_ADMIN_ITEMS_PAGE_SIZE}&light_mode=true`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const itemsContainer = document.querySelector('#items-container');
|
||||
@@ -3592,6 +3590,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
}
|
||||
}
|
||||
const damageCount = Array.isArray(item.DamageReports) ? item.DamageReports.length : 0;
|
||||
const hasDamage = Boolean(item.HasDamage) || damageCount > 0;
|
||||
const groupedCount = Number(item.GroupedDisplayCount || 1);
|
||||
const availableGroupedCount = Number(item.AvailableGroupedCount ?? (item.Verfuegbar ? 1 : 0));
|
||||
const isGroupedItem = groupedCount > 1;
|
||||
@@ -3608,7 +3607,7 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
<p class="item-col-filter3"><strong>Thema:</strong> ${filter3Display}${filter3More}</p>
|
||||
<p class="item-col-code"><strong>Barcode:</strong> ${item.Code_4 || '-'}</p>
|
||||
<p class="item-col-count"><strong>Anzahl:</strong> ${groupedCount}</p>
|
||||
${damageCount > 0 ? `<div class="damage-badge">Schäden gemeldet: ${damageCount}</div>` : ''}
|
||||
${hasDamage ? `<div class="damage-badge">${damageCount > 0 ? `Schäden gemeldet: ${damageCount}` : 'Schäden gemeldet'}</div>` : ''}
|
||||
<div class="image-container">
|
||||
${imagesHtml}
|
||||
</div>
|
||||
@@ -3680,11 +3679,8 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
}
|
||||
|
||||
e.stopPropagation();
|
||||
|
||||
const modalItemData = {...item};
|
||||
modalItemData.Images = item.Images ? item.Images.map(img => "{{ url_for('uploaded_file', filename='') }}" + img) : [];
|
||||
|
||||
openItemModal(modalItemData);
|
||||
|
||||
openItemQuick(item._id);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -4004,6 +4000,22 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
applyFilters();
|
||||
}
|
||||
|
||||
// Open item modal with fresh details from backend.
|
||||
function openItemQuick(id) {
|
||||
fetch(`/get_item/${id}`)
|
||||
.then(response => response.json())
|
||||
.then(item => {
|
||||
if (item && !item.error) {
|
||||
openItemModal(item);
|
||||
} else {
|
||||
console.error('Item details could not be loaded:', item);
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Error loading item details:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function openEditModalForSelectedUnit(defaultItemId, selectId) {
|
||||
let targetItemId = defaultItemId;
|
||||
|
||||
@@ -4303,14 +4315,58 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
}
|
||||
|
||||
const damageReports = Array.isArray(item.DamageReports) ? item.DamageReports : [];
|
||||
const damageInfoHtml = damageReports.length > 0
|
||||
? `<ul class="damage-list">${damageReports.map(report => {
|
||||
const desc = escapeHtml(report?.description || '-');
|
||||
const by = escapeHtml(report?.reported_by || 'Unbekannt');
|
||||
const at = escapeHtml(formatDamageTimestamp(report?.reported_at));
|
||||
return `<li><strong>${at}</strong> durch ${by}<br>${desc}</li>`;
|
||||
}).join('')}</ul>`
|
||||
: 'Keine Schäden erfasst.';
|
||||
const damageRepairs = Array.isArray(item.DamageRepairs) ? item.DamageRepairs : [];
|
||||
const damageHistoryEntries = [];
|
||||
|
||||
damageReports.forEach(report => {
|
||||
damageHistoryEntries.push({
|
||||
type: 'report',
|
||||
timestamp: report?.reported_at || null,
|
||||
dateLabel: escapeHtml(formatDamageTimestamp(report?.reported_at)),
|
||||
actor: escapeHtml(report?.reported_by || 'Unbekannt'),
|
||||
description: escapeHtml(report?.description || 'Schaden gemeldet'),
|
||||
meta: '',
|
||||
});
|
||||
});
|
||||
|
||||
damageRepairs.forEach(repair => {
|
||||
const resolvedReports = Array.isArray(repair?.resolved_reports) ? repair.resolved_reports : [];
|
||||
damageHistoryEntries.push({
|
||||
type: 'repair',
|
||||
timestamp: repair?.repaired_at || null,
|
||||
dateLabel: escapeHtml(formatDamageTimestamp(repair?.repaired_at)),
|
||||
actor: escapeHtml(repair?.repaired_by || 'Unbekannt'),
|
||||
description: 'Als repariert markiert',
|
||||
meta: `${resolvedReports.length} Meldung(en) abgeschlossen`,
|
||||
});
|
||||
});
|
||||
|
||||
damageHistoryEntries.sort((a, b) => {
|
||||
const ta = a.timestamp ? new Date(a.timestamp).getTime() : 0;
|
||||
const tb = b.timestamp ? new Date(b.timestamp).getTime() : 0;
|
||||
return (Number.isNaN(tb) ? 0 : tb) - (Number.isNaN(ta) ? 0 : ta);
|
||||
});
|
||||
|
||||
const damageHistoryHtml = damageHistoryEntries.length > 0
|
||||
? damageHistoryEntries.map(entry => {
|
||||
const badgeStyle = entry.type === 'repair'
|
||||
? 'background:#dcfce7;color:#166534;'
|
||||
: 'background:#fee2e2;color:#991b1b;';
|
||||
const badgeText = entry.type === 'repair' ? 'Repariert' : 'Schaden';
|
||||
const metaLine = entry.meta ? `<div style="font-size:0.84rem;color:#4b5563;">${escapeHtml(entry.meta)}</div>` : '';
|
||||
return `
|
||||
<div style="border:1px solid #dbe3ee;border-radius:8px;padding:10px;background:#fff;display:grid;gap:6px;">
|
||||
<div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
|
||||
<span style="display:inline-block;padding:2px 8px;border-radius:999px;font-size:0.75rem;font-weight:700;${badgeStyle}">${badgeText}</span>
|
||||
<span style="font-size:0.84rem;color:#475569;">${entry.dateLabel}</span>
|
||||
</div>
|
||||
<div style="font-size:0.9rem;color:#0f172a;"><strong>Von:</strong> ${entry.actor}</div>
|
||||
<div style="font-size:0.92rem;color:#1f2937;">${entry.description}</div>
|
||||
${metaLine}
|
||||
</div>
|
||||
`;
|
||||
}).join('')
|
||||
: '<div style="font-size:0.92rem;color:#64748b;">Keine Beschädigungs-Historie vorhanden.</div>';
|
||||
|
||||
modalContent.innerHTML = `
|
||||
<h2>${item.Name}</h2>
|
||||
@@ -4385,9 +4441,17 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
<div class="detail-value">${item.Beschreibung || '-'}</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-group full-width">
|
||||
<div class="detail-label">Schäden:</div>
|
||||
<div class="detail-value">${damageInfoHtml}</div>
|
||||
<div class="detail-group full-width" style="margin-top:12px;">
|
||||
<div class="detail-label" style="font-weight:600; color:#374151;">Beschädigungs-Historie</div>
|
||||
<div class="detail-value">
|
||||
<button id="toggle-damage-history" class="calendar-toggle-btn" style="margin-bottom:12px; padding:10px 16px; border-radius:6px; background:#f3f4f6; border:1px solid #d1d5db; font-weight:500; cursor:pointer; display:inline-flex; align-items:center; gap:8px; transition:all 0.2s ease;">
|
||||
<span>🛠️</span>
|
||||
<span id="toggle-damage-history-text">Historie anzeigen</span>
|
||||
</button>
|
||||
<div id="damage-history-panel" style="display:none; margin-top:8px; border:1px solid #e7edf5; border-radius:10px; padding:12px; background:#f8fafc;">
|
||||
<div style="display:grid; gap:10px;">${damageHistoryHtml}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-group full-width" style="margin-top:12px; padding:10px; border:1px solid #e3e3e3; border-radius:8px;">
|
||||
@@ -4486,6 +4550,9 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
const detailsPanel = document.getElementById('calendar-day-details');
|
||||
const detailsDate = document.getElementById('cal-details-date');
|
||||
const detailsList = document.getElementById('cal-details-list');
|
||||
const damageToggleBtn = document.getElementById('toggle-damage-history');
|
||||
const damageHistoryPanel = document.getElementById('damage-history-panel');
|
||||
const damageToggleText = document.getElementById('toggle-damage-history-text');
|
||||
|
||||
let bookings = [];
|
||||
let currentDate = new Date();
|
||||
@@ -4645,6 +4712,16 @@ document.addEventListener('DOMContentLoaded', ()=>{
|
||||
renderCalendar();
|
||||
});
|
||||
|
||||
damageToggleBtn?.addEventListener('click', () => {
|
||||
const shouldOpen = damageHistoryPanel.style.display === 'none';
|
||||
damageHistoryPanel.style.display = shouldOpen ? 'block' : 'none';
|
||||
if (damageToggleText) {
|
||||
damageToggleText.textContent = shouldOpen ? 'Historie verbergen' : 'Historie anzeigen';
|
||||
}
|
||||
damageToggleBtn.style.background = shouldOpen ? '#e0e7ff' : '#f3f4f6';
|
||||
damageToggleBtn.style.borderColor = shouldOpen ? '#818cf8' : '#d1d5db';
|
||||
});
|
||||
|
||||
|
||||
// Availability checker
|
||||
const availDate = document.getElementById('avail-date');
|
||||
|
||||
+2
-1
@@ -4,7 +4,8 @@ services:
|
||||
container_name: inventarsystem-nginx
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- app
|
||||
app:
|
||||
condition: service_started
|
||||
ports:
|
||||
- "${INVENTAR_HTTP_PORT:-80}:80"
|
||||
- "${INVENTAR_HTTPS_PORT:-443}:443"
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
Gunicorn configuration for Inventarsystem.
|
||||
|
||||
This configuration ensures that:
|
||||
1. The BackgroundScheduler runs reliably in only one worker process
|
||||
2. Appointment status updates and reminders work correctly
|
||||
3. Multi-worker deployments don't cause race conditions
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Get project root
|
||||
PROJECT_ROOT = Path(__file__).parent
|
||||
|
||||
# Basic configuration
|
||||
bind = "unix:/tmp/inventarsystem.sock"
|
||||
workers = 1 # CRITICAL: Only 1 worker to prevent BackgroundScheduler race conditions
|
||||
worker_class = "sync"
|
||||
timeout = 60
|
||||
graceful_timeout = 20
|
||||
max_requests = 1000
|
||||
max_requests_jitter = 100
|
||||
|
||||
# Logging
|
||||
accesslog = str(PROJECT_ROOT / "logs" / "access.log")
|
||||
errorlog = str(PROJECT_ROOT / "logs" / "error.log")
|
||||
log_level = "info"
|
||||
capture_output = True
|
||||
|
||||
# Worker initialization hook to ensure scheduler starts only once
|
||||
def on_starting(server):
|
||||
"""Called just before the master process is initialized."""
|
||||
print("[GUNICORN] Starting Inventarsystem with scheduler support (1 worker only)")
|
||||
|
||||
def when_ready(server):
|
||||
"""Called just after the server is started."""
|
||||
print("[GUNICORN] Server is ready. Scheduler should be active in the single worker process.")
|
||||
|
||||
# Ensure the logs directory exists
|
||||
os.makedirs(PROJECT_ROOT / "logs", exist_ok=True)
|
||||
+35
-20
@@ -69,45 +69,60 @@ with open(compose_file, "r", encoding="utf-8") as f:
|
||||
|
||||
out = []
|
||||
in_app = False
|
||||
in_build = False
|
||||
image_set = False
|
||||
app_indent = None
|
||||
app_service_indent = None
|
||||
skip_build_block = False
|
||||
|
||||
def leading_spaces(text):
|
||||
return len(text) - len(text.lstrip(" "))
|
||||
|
||||
for line in lines:
|
||||
stripped = line.lstrip(" ")
|
||||
indent = len(line) - len(stripped)
|
||||
indent = leading_spaces(line)
|
||||
|
||||
if not in_app and re.match(r"^\s{2}app:\s*$", line):
|
||||
if not in_app and re.match(r"^\s*app:\s*$", line):
|
||||
in_app = True
|
||||
image_set = False
|
||||
app_indent = indent
|
||||
app_service_indent = None
|
||||
skip_build_block = False
|
||||
out.append(line)
|
||||
out.append(f" image: {target_image}\n")
|
||||
image_set = True
|
||||
continue
|
||||
|
||||
if in_app:
|
||||
if indent == 2 and re.match(r"^[A-Za-z0-9_-]+:\s*$", stripped):
|
||||
if app_service_indent is None and indent > app_indent:
|
||||
app_service_indent = indent
|
||||
|
||||
if indent <= app_indent and re.match(r"^[A-Za-z0-9_-]+:\s*$", stripped):
|
||||
in_app = False
|
||||
in_build = False
|
||||
app_indent = None
|
||||
app_service_indent = None
|
||||
skip_build_block = False
|
||||
|
||||
if in_app:
|
||||
if in_build:
|
||||
if indent > 4:
|
||||
continue
|
||||
in_build = False
|
||||
if app_service_indent is None:
|
||||
app_service_indent = indent
|
||||
|
||||
if re.match(r"^\s{4}build:\s*$", line):
|
||||
in_build = True
|
||||
if skip_build_block:
|
||||
if indent > app_service_indent:
|
||||
continue
|
||||
skip_build_block = False
|
||||
|
||||
if re.match(rf"^\s{{{app_service_indent}}}build:\s*$", line):
|
||||
skip_build_block = True
|
||||
continue
|
||||
|
||||
if re.match(r"^\s{4}image:\s*", line):
|
||||
if image_set:
|
||||
continue
|
||||
out.append(f" image: {target_image}\n")
|
||||
image_set = True
|
||||
if re.match(rf"^\s{{{app_service_indent}}}image:\s*", line):
|
||||
continue
|
||||
|
||||
if re.match(rf"^\s{{{app_service_indent}}}[A-Za-z0-9_-]+:\s*$", line):
|
||||
out.append(f"{' ' * app_service_indent}image: {target_image}\n")
|
||||
app_service_indent = None
|
||||
|
||||
out.append(line)
|
||||
|
||||
if in_app and app_service_indent is not None:
|
||||
out.append(f"{' ' * app_service_indent}image: {target_image}\n")
|
||||
|
||||
with open(compose_file, "w", encoding="utf-8") as f:
|
||||
f.writelines(out)
|
||||
PY
|
||||
|
||||
Reference in New Issue
Block a user