fix a bunch is settings

This commit is contained in:
2025-05-30 20:32:40 +02:00
parent 43f29f9a46
commit c09a5c758e
10 changed files with 172 additions and 148 deletions

Binary file not shown.

View File

@@ -56,4 +56,18 @@ class ConversationForm(FlaskForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(ConversationForm, self).__init__(*args, **kwargs) super(ConversationForm, self).__init__(*args, **kwargs)
self.members.choices = [(u.id, f"{u.username} {u.last_name}") for u in User.query.filter_by(is_active=True).all()] self.members.choices = [(u.id, f"{u.username} {u.last_name}") for u in User.query.filter_by(is_active=True).all()]
class CompanySettingsForm(FlaskForm):
company_name = StringField('Company Name', validators=[Optional(), Length(max=100)])
company_website = StringField('Website', validators=[Optional(), Length(max=200)])
company_email = StringField('Email', validators=[Optional(), Email(), Length(max=100)])
company_phone = StringField('Phone', validators=[Optional(), Length(max=20)])
company_address = StringField('Address', validators=[Optional(), Length(max=200)])
company_city = StringField('City', validators=[Optional(), Length(max=100)])
company_state = StringField('State', validators=[Optional(), Length(max=100)])
company_zip = StringField('ZIP Code', validators=[Optional(), Length(max=20)])
company_country = StringField('Country', validators=[Optional(), Length(max=100)])
company_description = TextAreaField('Description', validators=[Optional()])
company_industry = StringField('Industry', validators=[Optional(), Length(max=100)])
company_logo = FileField('Company Logo', validators=[FileAllowed(['jpg', 'jpeg', 'png', 'gif'], 'Images only!')])

View File

@@ -9,6 +9,7 @@ from datetime import datetime, timedelta
import logging import logging
import sys import sys
import time import time
from forms import CompanySettingsForm
# Set up logging to show in console # Set up logging to show in console
logging.basicConfig( logging.basicConfig(
@@ -407,54 +408,61 @@ def init_routes(main_bp):
flash('Only administrators can access settings.', 'error') flash('Only administrators can access settings.', 'error')
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
site_settings = SiteSettings.get_settings() # Get active tab from URL or default to colors
active_tab = request.args.get('tab', 'colors') active_tab = request.args.get('tab', 'colors')
# Get site settings
site_settings = SiteSettings.get_settings()
# Get events data if events tab is active # Get events data if events tab is active
events = None events = None
total_pages = 1 total_pages = 0
current_page = 1 current_page = 1
users = [] users = []
if active_tab == 'events': if active_tab == 'events':
# Get filter parameters # Get filter parameters
event_type = request.args.get('event_type') event_type = request.args.get('event_type', '')
date_range = request.args.get('date_range', '7d') date_range = request.args.get('date_range', '7d')
user_id = request.args.get('user_id') user_id = request.args.get('user_id', '')
page = request.args.get('page', 1, type=int) page = request.args.get('page', 1, type=int)
per_page = 50 per_page = 10
# Calculate date range
end_date = datetime.utcnow()
if date_range == '24h':
start_date = end_date - timedelta(days=1)
elif date_range == '7d':
start_date = end_date - timedelta(days=7)
elif date_range == '30d':
start_date = end_date - timedelta(days=30)
else:
start_date = None
# Build query # Build query
query = Event.query query = Event.query
# Apply filters
if event_type: if event_type:
query = query.filter_by(event_type=event_type) query = query.filter(Event.event_type == event_type)
if start_date:
query = query.filter(Event.timestamp >= start_date)
if user_id: if user_id:
query = query.filter_by(user_id=user_id) query = query.filter(Event.user_id == user_id)
if date_range:
# Get total count for pagination cutoff_date = datetime.utcnow() - timedelta(days=int(date_range[:-1]))
total_events = query.count() query = query.filter(Event.timestamp >= cutoff_date)
total_pages = (total_events + per_page - 1) // per_page
# Get paginated events # Get paginated events
events = query.order_by(Event.timestamp.desc()).paginate(page=page, per_page=per_page) events = query.order_by(Event.timestamp.desc()).paginate(page=page, per_page=per_page)
total_pages = events.pages
current_page = events.page
# Get all users for filter dropdown # Get all users for filter dropdown
users = User.query.order_by(User.username).all() users = User.query.order_by(User.username).all()
# Create form for company settings
company_form = CompanySettingsForm()
if request.method == 'GET':
company_form.company_name.data = site_settings.company_name
company_form.company_website.data = site_settings.company_website
company_form.company_email.data = site_settings.company_email
company_form.company_phone.data = site_settings.company_phone
company_form.company_address.data = site_settings.company_address
company_form.company_city.data = site_settings.company_city
company_form.company_state.data = site_settings.company_state
company_form.company_zip.data = site_settings.company_zip
company_form.company_country.data = site_settings.company_country
company_form.company_description.data = site_settings.company_description
company_form.company_industry.data = site_settings.company_industry
return render_template('settings/settings.html', return render_template('settings/settings.html',
primary_color=site_settings.primary_color, primary_color=site_settings.primary_color,
secondary_color=site_settings.secondary_color, secondary_color=site_settings.secondary_color,
@@ -464,7 +472,7 @@ def init_routes(main_bp):
total_pages=total_pages, total_pages=total_pages,
current_page=current_page, current_page=current_page,
users=users, users=users,
csrf_token=session.get('csrf_token')) form=company_form)
@main_bp.route('/settings/colors', methods=['POST']) @main_bp.route('/settings/colors', methods=['POST'])
@login_required @login_required
@@ -544,12 +552,17 @@ def init_routes(main_bp):
flash('Only administrators can update settings.', 'error') flash('Only administrators can update settings.', 'error')
return redirect(url_for('main.dashboard')) return redirect(url_for('main.dashboard'))
form = CompanySettingsForm()
if not form.validate():
flash('Please check the form for errors.', 'error')
return redirect(url_for('main.settings'))
site_settings = SiteSettings.get_settings() site_settings = SiteSettings.get_settings()
# Handle logo upload # Handle logo upload
if 'company_logo' in request.files: if form.company_logo.data:
logo_file = request.files['company_logo'] logo_file = form.company_logo.data
if logo_file and logo_file.filename: if logo_file.filename:
# Delete old logo if it exists # Delete old logo if it exists
if site_settings.company_logo: if site_settings.company_logo:
old_logo_path = os.path.join('static', 'uploads', 'company_logos', site_settings.company_logo) old_logo_path = os.path.join('static', 'uploads', 'company_logos', site_settings.company_logo)
@@ -565,17 +578,17 @@ def init_routes(main_bp):
site_settings.company_logo = filename site_settings.company_logo = filename
# Update all company fields # Update all company fields
site_settings.company_name = request.form.get('company_name') site_settings.company_name = form.company_name.data
site_settings.company_website = request.form.get('company_website') site_settings.company_website = form.company_website.data
site_settings.company_email = request.form.get('company_email') site_settings.company_email = form.company_email.data
site_settings.company_phone = request.form.get('company_phone') site_settings.company_phone = form.company_phone.data
site_settings.company_address = request.form.get('company_address') site_settings.company_address = form.company_address.data
site_settings.company_city = request.form.get('company_city') site_settings.company_city = form.company_city.data
site_settings.company_state = request.form.get('company_state') site_settings.company_state = form.company_state.data
site_settings.company_zip = request.form.get('company_zip') site_settings.company_zip = form.company_zip.data
site_settings.company_country = request.form.get('company_country') site_settings.company_country = form.company_country.data
site_settings.company_description = request.form.get('company_description') site_settings.company_description = form.company_description.data
site_settings.company_industry = request.form.get('company_industry') site_settings.company_industry = form.company_industry.data
try: try:
db.session.commit() db.session.commit()
@@ -599,7 +612,7 @@ def init_routes(main_bp):
'company_country': site_settings.company_country, 'company_country': site_settings.company_country,
'company_description': site_settings.company_description, 'company_description': site_settings.company_description,
'company_industry': site_settings.company_industry, 'company_industry': site_settings.company_industry,
'logo_updated': bool(request.files.get('company_logo')) 'logo_updated': bool(form.company_logo.data)
} }
} }
) )
@@ -607,10 +620,11 @@ def init_routes(main_bp):
flash('Company settings updated successfully!', 'success') flash('Company settings updated successfully!', 'success')
except Exception as e: except Exception as e:
logger.error(f"Error updating company settings: {str(e)}")
db.session.rollback() db.session.rollback()
flash('An error occurred while updating company settings.', 'error') flash('An error occurred while updating company settings.', 'error')
return redirect(url_for('main.settings', tab='general')) return redirect(url_for('main.settings'))
@main_bp.route('/dynamic-colors.css') @main_bp.route('/dynamic-colors.css')
def dynamic_colors(): def dynamic_colors():

View File

@@ -1,6 +1,6 @@
from flask import Blueprint, jsonify, request, abort from flask import Blueprint, jsonify, request, abort
from flask_login import login_required, current_user from flask_login import login_required, current_user
from models import db, Room, RoomFile, TrashedFile from models import db, Room, RoomFile, TrashedFile, UserStarredFile
from utils import user_has_permission, clean_path from utils import user_has_permission, clean_path
import os import os
from datetime import datetime from datetime import datetime
@@ -99,29 +99,34 @@ def permanently_delete_file(room_id, trash_id):
@trash_bp.route('/<int:room_id>/trash/empty', methods=['POST']) @trash_bp.route('/<int:room_id>/trash/empty', methods=['POST'])
@login_required @login_required
def empty_trash(room_id): def empty_trash(room_id):
room = Room.query.get_or_404(room_id) """Empty the trash for a specific room."""
if not user_has_permission(room, 'can_delete'): try:
abort(403) # Get all trashed files
trashed_files = TrashedFile.query.filter_by(room_id=room_id).all()
# Get all trashed files for this room
trashed_files = TrashedFile.query.filter_by(room_id=room_id).all() # Delete physical files first
room_files = RoomFile.query.filter_by(room_id=room_id, deleted=True).all() for file in trashed_files:
try:
# Delete physical files file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], str(room_id), file.name)
room_dir = os.path.join('/data/rooms', str(room_id))
for file in trashed_files + room_files:
try:
if file.type == 'file':
file_path = os.path.join(room_dir, file.original_path if hasattr(file, 'original_path') else file.path, file.name)
if os.path.exists(file_path): if os.path.exists(file_path):
os.remove(file_path) os.remove(file_path)
except Exception as e: except Exception as e:
print(f"Error deleting physical file {file.name}: {str(e)}") print(f"Error deleting physical file {file.name}: {str(e)}")
continue continue
# Delete all trashed files from both tables # Delete all starred file references for the trashed files
TrashedFile.query.filter_by(room_id=room_id).delete() room_files = RoomFile.query.filter_by(room_id=room_id, deleted=True).all()
RoomFile.query.filter_by(room_id=room_id, deleted=True).delete() for file in room_files:
db.session.commit() UserStarredFile.query.filter_by(file_id=file.id).delete()
return jsonify({'success': True}) # Delete all trashed files from both tables
TrashedFile.query.filter_by(room_id=room_id).delete()
RoomFile.query.filter_by(room_id=room_id, deleted=True).delete()
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
print(f"Error emptying trash: {str(e)}")
return jsonify({'success': False, 'error': str(e)}), 500

View File

@@ -392,7 +392,7 @@ export class FileManager {
*/ */
async downloadFile(filename, path = '') { async downloadFile(filename, path = '') {
console.log('[FileManager] Downloading file:', { filename, path }); console.log('[FileManager] Downloading file:', { filename, path });
const url = `/api/rooms/${this.roomManager.roomId}/files/${encodeURIComponent(filename)}`; let url = `/api/rooms/${this.roomManager.roomId}/files/${encodeURIComponent(filename)}`;
if (path) { if (path) {
url += `?path=${encodeURIComponent(path)}`; url += `?path=${encodeURIComponent(path)}`;
} }

View File

@@ -12,6 +12,7 @@ document.addEventListener('DOMContentLoaded', function() {
const primaryColorInput = document.getElementById('primaryColor'); const primaryColorInput = document.getElementById('primaryColor');
const secondaryColorInput = document.getElementById('secondaryColor'); const secondaryColorInput = document.getElementById('secondaryColor');
const colorSettingsForm = document.getElementById('colorSettingsForm'); const colorSettingsForm = document.getElementById('colorSettingsForm');
const companyInfoForm = document.getElementById('companyInfoForm');
// Get all tab buttons // Get all tab buttons
const settingsTabs = document.querySelectorAll('[data-bs-toggle="tab"]'); const settingsTabs = document.querySelectorAll('[data-bs-toggle="tab"]');
@@ -73,10 +74,14 @@ document.addEventListener('DOMContentLoaded', function() {
eventsTableBody.innerHTML = '<tr><td colspan="5" class="text-center">Loading events...</td></tr>'; eventsTableBody.innerHTML = '<tr><td colspan="5" class="text-center">Loading events...</td></tr>';
} }
// Get CSRF token
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
// Fetch events data // Fetch events data
fetch(`/settings/events?event_type=${eventType}&date_range=${dateRange}&user_id=${userId}&page=${page}`, { fetch(`/settings/events?event_type=${eventType}&date_range=${dateRange}&user_id=${userId}&page=${page}`, {
headers: { headers: {
'X-Requested-With': 'XMLHttpRequest' 'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': csrfToken
} }
}) })
.then(response => response.text()) .then(response => response.text())
@@ -303,11 +308,55 @@ document.addEventListener('DOMContentLoaded', function() {
// Handle form submission // Handle form submission
if (colorSettingsForm) { if (colorSettingsForm) {
colorSettingsForm.addEventListener('submit', function(e) { colorSettingsForm.addEventListener('submit', function(e) {
console.log('[Settings] Form submitted with values:', { e.preventDefault(); // Prevent default form submission
primary: primaryColorInput.value,
secondary: secondaryColorInput.value, const formData = new FormData(colorSettingsForm);
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'), const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
timestamp: new Date().toISOString()
fetch(colorSettingsForm.action, {
method: 'POST',
headers: {
'X-CSRF-Token': csrfToken
},
body: formData
})
.then(response => {
if (response.ok) {
window.location.reload(); // Reload to show updated colors
} else {
throw new Error('Failed to update colors');
}
})
.catch(error => {
console.error('Error updating colors:', error);
alert('Failed to update colors. Please try again.');
});
});
}
// Handle company info form submission
if (companyInfoForm) {
companyInfoForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(companyInfoForm);
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
formData.append('csrf_token', csrfToken);
fetch(companyInfoForm.action, {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
window.location.reload(); // Reload to show updated info
} else {
throw new Error('Failed to update company info');
}
})
.catch(error => {
console.error('Error updating company info:', error);
alert('Failed to update company info. Please try again.');
}); });
}); });
} }

View File

@@ -63,7 +63,7 @@
<!-- Company Info Tab --> <!-- Company Info Tab -->
<div class="tab-pane fade {% if active_tab == 'general' %}show active{% endif %}" id="general" role="tabpanel" aria-labelledby="general-tab"> <div class="tab-pane fade {% if active_tab == 'general' %}show active{% endif %}" id="general" role="tabpanel" aria-labelledby="general-tab">
{{ company_info_tab(site_settings, csrf_token) }} {{ company_info_tab(site_settings, form) }}
</div> </div>
<!-- Security Tab --> <!-- Security Tab -->

View File

@@ -1,11 +1,11 @@
{% macro company_info_tab(site_settings, csrf_token) %} {% macro company_info_tab(site_settings, form) %}
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
<!-- Company Settings Section --> <!-- Company Settings Section -->
<div class="card mb-4"> <div class="card mb-4">
<div class="card-body"> <div class="card-body">
<form method="POST" action="{{ url_for('main.update_company_settings') }}" enctype="multipart/form-data"> <form id="companyInfoForm" method="POST" action="{{ url_for('main.update_company_settings') }}" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}"> {{ form.csrf_token }}
<div class="row"> <div class="row">
<!-- Basic Information --> <!-- Basic Information -->
@@ -20,50 +20,26 @@
class="img-thumbnail" class="img-thumbnail"
style="max-height: 100px; max-width: 200px;"> style="max-height: 100px; max-width: 200px;">
{% endif %} {% endif %}
<input type="file" {{ form.company_logo(class="form-control", accept="image/*") }}
class="form-control"
id="company_logo"
name="company_logo"
accept="image/*">
</div> </div>
<div class="form-text">Upload your company logo. Recommended size: 200x100 pixels.</div> <div class="form-text">Upload your company logo. Recommended size: 200x100 pixels.</div>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="company_name" class="form-label">Company Name</label> <label for="company_name" class="form-label">Company Name</label>
<input type="text" {{ form.company_name(class="form-control", placeholder="Enter your company name") }}
class="form-control"
id="company_name"
name="company_name"
value="{{ site_settings.company_name or '' }}"
placeholder="Enter your company name">
<div class="form-text">This name will be displayed in the website title and navigation bar.</div> <div class="form-text">This name will be displayed in the website title and navigation bar.</div>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="company_website" class="form-label">Website</label> <label for="company_website" class="form-label">Website</label>
<input type="url" {{ form.company_website(class="form-control", placeholder="https://example.com") }}
class="form-control"
id="company_website"
name="company_website"
value="{{ site_settings.company_website or '' }}"
placeholder="https://example.com">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="company_email" class="form-label">Email</label> <label for="company_email" class="form-label">Email</label>
<input type="email" {{ form.company_email(class="form-control", placeholder="contact@company.com") }}
class="form-control"
id="company_email"
name="company_email"
value="{{ site_settings.company_email or '' }}"
placeholder="contact@company.com">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="company_phone" class="form-label">Phone</label> <label for="company_phone" class="form-label">Phone</label>
<input type="tel" {{ form.company_phone(class="form-control", placeholder="+1 (555) 123-4567") }}
class="form-control"
id="company_phone"
name="company_phone"
value="{{ site_settings.company_phone or '' }}"
placeholder="+1 (555) 123-4567">
</div> </div>
</div> </div>
@@ -72,50 +48,25 @@
<h6 class="mb-3">Address Information</h6> <h6 class="mb-3">Address Information</h6>
<div class="mb-3"> <div class="mb-3">
<label for="company_address" class="form-label">Street Address</label> <label for="company_address" class="form-label">Street Address</label>
<input type="text" {{ form.company_address(class="form-control", placeholder="123 Business Street") }}
class="form-control"
id="company_address"
name="company_address"
value="{{ site_settings.company_address or '' }}"
placeholder="123 Business Street">
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-6 mb-3"> <div class="col-md-6 mb-3">
<label for="company_city" class="form-label">City</label> <label for="company_city" class="form-label">City</label>
<input type="text" {{ form.company_city(class="form-control", placeholder="City") }}
class="form-control"
id="company_city"
name="company_city"
value="{{ site_settings.company_city or '' }}"
placeholder="City">
</div> </div>
<div class="col-md-3 mb-3"> <div class="col-md-3 mb-3">
<label for="company_state" class="form-label">State</label> <label for="company_state" class="form-label">State</label>
<input type="text" {{ form.company_state(class="form-control", placeholder="State") }}
class="form-control"
id="company_state"
name="company_state"
value="{{ site_settings.company_state or '' }}"
placeholder="State">
</div> </div>
<div class="col-md-3 mb-3"> <div class="col-md-3 mb-3">
<label for="company_zip" class="form-label">ZIP Code</label> <label for="company_zip" class="form-label">ZIP Code</label>
<input type="text" {{ form.company_zip(class="form-control", placeholder="ZIP") }}
class="form-control"
id="company_zip"
name="company_zip"
value="{{ site_settings.company_zip or '' }}"
placeholder="ZIP">
</div> </div>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="company_country" class="form-label">Country</label> <label for="company_country" class="form-label">Country</label>
<input type="text" {{ form.company_country(class="form-control", placeholder="Country") }}
class="form-control"
id="company_country"
name="company_country"
value="{{ site_settings.company_country or '' }}"
placeholder="Country">
</div> </div>
</div> </div>
@@ -124,20 +75,11 @@
<h6 class="mb-3">Additional Information</h6> <h6 class="mb-3">Additional Information</h6>
<div class="mb-3"> <div class="mb-3">
<label for="company_description" class="form-label">Company Description</label> <label for="company_description" class="form-label">Company Description</label>
<textarea class="form-control" {{ form.company_description(class="form-control", rows="3", placeholder="Brief description of your company") }}
id="company_description"
name="company_description"
rows="3"
placeholder="Brief description of your company">{{ site_settings.company_description or '' }}</textarea>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="company_industry" class="form-label">Industry</label> <label for="company_industry" class="form-label">Industry</label>
<input type="text" {{ form.company_industry(class="form-control", placeholder="e.g., Technology, Healthcare, Finance") }}
class="form-control"
id="company_industry"
name="company_industry"
value="{{ site_settings.company_industry or '' }}"
placeholder="e.g., Technology, Healthcare, Finance">
</div> </div>
</div> </div>
</div> </div>