Add date/time formatting options.

This commit is contained in:
2025-07-02 16:36:23 +02:00
committed by Jens Luedicke
parent 197ffde545
commit f641be6026
5 changed files with 356 additions and 21 deletions

70
app.py
View File

@@ -137,7 +137,9 @@ def run_migrations():
('additional_break_threshold_hours', "ALTER TABLE work_config ADD COLUMN additional_break_threshold_hours FLOAT DEFAULT 9.0"),
('user_id', "ALTER TABLE work_config ADD COLUMN user_id INTEGER"),
('time_rounding_minutes', "ALTER TABLE work_config ADD COLUMN time_rounding_minutes INTEGER DEFAULT 0"),
('round_to_nearest', "ALTER TABLE work_config ADD COLUMN round_to_nearest BOOLEAN DEFAULT 1")
('round_to_nearest', "ALTER TABLE work_config ADD COLUMN round_to_nearest BOOLEAN DEFAULT 1"),
('time_format_24h', "ALTER TABLE work_config ADD COLUMN time_format_24h BOOLEAN DEFAULT 1"),
('date_format', "ALTER TABLE work_config ADD COLUMN date_format VARCHAR(20) DEFAULT 'ISO'")
]
for column_name, sql_command in work_config_migrations:
@@ -499,6 +501,56 @@ def inject_globals():
'current_year': datetime.now().year
}
# Template filters for date/time formatting
@app.template_filter('format_date')
def format_date_filter(dt):
"""Format date according to user preferences."""
if not dt or not g.user:
return dt.strftime('%Y-%m-%d') if dt else ''
from time_utils import format_date_by_preference, get_user_format_settings
date_format, _ = get_user_format_settings(g.user)
return format_date_by_preference(dt, date_format)
@app.template_filter('format_time')
def format_time_filter(dt):
"""Format time according to user preferences."""
if not dt or not g.user:
return dt.strftime('%H:%M:%S') if dt else ''
from time_utils import format_time_by_preference, get_user_format_settings
_, time_format_24h = get_user_format_settings(g.user)
return format_time_by_preference(dt, time_format_24h)
@app.template_filter('format_time_short')
def format_time_short_filter(dt):
"""Format time without seconds according to user preferences."""
if not dt or not g.user:
return dt.strftime('%H:%M') if dt else ''
from time_utils import format_time_short_by_preference, get_user_format_settings
_, time_format_24h = get_user_format_settings(g.user)
return format_time_short_by_preference(dt, time_format_24h)
@app.template_filter('format_datetime')
def format_datetime_filter(dt):
"""Format datetime according to user preferences."""
if not dt or not g.user:
return dt.strftime('%Y-%m-%d %H:%M:%S') if dt else ''
from time_utils import format_datetime_by_preference, get_user_format_settings
date_format, time_format_24h = get_user_format_settings(g.user)
return format_datetime_by_preference(dt, date_format, time_format_24h)
@app.template_filter('format_duration')
def format_duration_filter(duration_seconds):
"""Format duration in readable format."""
if duration_seconds is None:
return '00:00:00'
from time_utils import format_duration_readable
return format_duration_readable(duration_seconds)
# Authentication decorator
def login_required(f):
@wraps(f)
@@ -1352,9 +1404,13 @@ def arrive():
db.session.add(new_entry)
db.session.commit()
# Format response with user preferences
from time_utils import format_datetime_by_preference, get_user_format_settings
date_format, time_format_24h = get_user_format_settings(g.user)
return jsonify({
'id': new_entry.id,
'arrival_time': new_entry.arrival_time.strftime('%Y-%m-%d %H:%M:%S'),
'arrival_time': format_datetime_by_preference(new_entry.arrival_time, date_format, time_format_24h),
'project': {
'id': new_entry.project.id,
'code': new_entry.project.code,
@@ -1465,6 +1521,10 @@ def config():
config.time_rounding_minutes = int(request.form.get('time_rounding_minutes', 0))
config.round_to_nearest = 'round_to_nearest' in request.form
# Update date/time format settings
config.time_format_24h = 'time_format_24h' in request.form
config.date_format = request.form.get('date_format', 'ISO')
db.session.commit()
flash('Configuration updated successfully!', 'success')
return redirect(url_for('config'))
@@ -1472,10 +1532,12 @@ def config():
flash('Please enter valid numbers for all fields', 'error')
# Import time utils for display options
from time_utils import get_available_rounding_options
from time_utils import get_available_rounding_options, get_available_date_formats
rounding_options = get_available_rounding_options()
date_format_options = get_available_date_formats()
return render_template('config.html', title='Configuration', config=config, rounding_options=rounding_options)
return render_template('config.html', title='Configuration', config=config,
rounding_options=rounding_options, date_format_options=date_format_options)
@app.route('/api/delete/<int:entry_id>', methods=['DELETE'])
@login_required

View File

@@ -243,6 +243,10 @@ class WorkConfig(db.Model):
time_rounding_minutes = db.Column(db.Integer, default=0) # 0 = no rounding, 15 = 15 min, 30 = 30 min
round_to_nearest = db.Column(db.Boolean, default=True) # True = round to nearest, False = round up
# Date/time format settings
time_format_24h = db.Column(db.Boolean, default=True) # True = 24h, False = 12h (AM/PM)
date_format = db.Column(db.String(20), default='ISO') # ISO, US, EU, etc.
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)

View File

@@ -46,6 +46,43 @@
</div>
</div>
<div class="form-section">
<h3>Display Format Settings</h3>
<p class="section-description">
Customize how dates and times are displayed throughout the application.
</p>
<div class="form-group">
<label for="date_format">Date Format:</label>
<select id="date_format" name="date_format">
{% for value, label, example in date_format_options %}
<option value="{{ value }}" {% if config.date_format == value %}selected{% endif %}>
{{ label }}
</option>
{% endfor %}
</select>
<small>Choose how dates are displayed</small>
</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox"
id="time_format_24h"
name="time_format_24h"
{% if config.time_format_24h %}checked{% endif %}>
<label for="time_format_24h">Use 24-hour time format</label>
<small>If unchecked, will use 12-hour format with AM/PM</small>
</div>
</div>
<div class="format-example" id="format-example">
<h4>Example:</h4>
<div id="format-example-text">
<!-- JavaScript will populate this -->
</div>
</div>
</div>
<div class="form-section">
<h3>Time Rounding Settings</h3>
<p class="section-description">
@@ -89,11 +126,59 @@
<script>
document.addEventListener('DOMContentLoaded', function() {
const dateFormatSelect = document.getElementById('date_format');
const timeFormat24hCheckbox = document.getElementById('time_format_24h');
const formatExampleDiv = document.getElementById('format-example-text');
const roundingSelect = document.getElementById('time_rounding_minutes');
const roundToNearestCheckbox = document.getElementById('round_to_nearest');
const exampleDiv = document.getElementById('example-text');
function updateExample() {
function updateFormatExample() {
const dateFormat = dateFormatSelect.value;
const timeFormat24h = timeFormat24hCheckbox.checked;
// Create a sample date for demonstration
const sampleDate = new Date(2024, 11, 25, 14, 30, 45); // Dec 25, 2024, 2:30:45 PM
let dateExample = '';
let timeExample = '';
// Format date examples
switch(dateFormat) {
case 'ISO':
dateExample = '2024-12-25';
break;
case 'US':
dateExample = '12/25/2024';
break;
case 'EU':
case 'UK':
dateExample = '25/12/2024';
break;
case 'Readable':
dateExample = 'Dec 25, 2024';
break;
case 'Full':
dateExample = 'December 25, 2024';
break;
}
// Format time examples
if (timeFormat24h) {
timeExample = '14:30:45';
} else {
timeExample = '2:30:45 PM';
}
formatExampleDiv.innerHTML = `
<strong>Date:</strong> ${dateExample}<br>
<strong>Time:</strong> ${timeExample}<br>
<strong>Combined:</strong> ${dateExample} ${timeExample}
`;
}
function updateRoundingExample() {
const interval = parseInt(roundingSelect.value);
const roundToNearest = roundToNearestCheckbox.checked;
@@ -142,12 +227,15 @@ document.addEventListener('DOMContentLoaded', function() {
exampleDiv.innerHTML = exampleText;
}
// Update example when settings change
roundingSelect.addEventListener('change', updateExample);
roundToNearestCheckbox.addEventListener('change', updateExample);
// Update examples when settings change
dateFormatSelect.addEventListener('change', updateFormatExample);
timeFormat24hCheckbox.addEventListener('change', updateFormatExample);
roundingSelect.addEventListener('change', updateRoundingExample);
roundToNearestCheckbox.addEventListener('change', updateRoundingExample);
// Initial example
updateExample();
// Initial examples
updateFormatExample();
updateRoundingExample();
});
</script>
@@ -186,5 +274,18 @@ document.addEventListener('DOMContentLoaded', function() {
margin-top: 0;
color: #2e7d32;
}
.format-example {
background: #e3f2fd;
padding: 1rem;
border-radius: 6px;
margin-top: 1rem;
border-left: 4px solid #2196f3;
}
.format-example h4 {
margin-top: 0;
color: #1976d2;
}
</style>
{% endblock %}

View File

@@ -19,7 +19,7 @@ Please <a href="{{ url_for('login') }}">login</a> or <a href="{{ url_for('regist
{% if active_entry %}
<div class="active-timer">
<h3>Currently Working</h3>
<p>Started at: {{ active_entry.arrival_time.strftime('%Y-%m-%d %H:%M:%S') }}</p>
<p>Started at: {{ active_entry.arrival_time|format_datetime }}</p>
{% if active_entry.project %}
<p class="project-info">Project: <strong>{{ active_entry.project.code }} - {{ active_entry.project.name }}</strong></p>
{% endif %}
@@ -29,11 +29,11 @@ Please <a href="{{ url_for('login') }}">login</a> or <a href="{{ url_for('regist
data-paused="{{ 'true' if active_entry.is_paused else 'false' }}">00:00:00</div>
{% if active_entry.is_paused %}
<p class="break-info">On break since {{ active_entry.pause_start_time.strftime('%H:%M:%S') }}</p>
<p class="break-info">On break since {{ active_entry.pause_start_time|format_time }}</p>
{% endif %}
{% if active_entry.total_break_duration > 0 %}
<p class="break-total">Total break time: {{ '%d:%02d:%02d'|format(active_entry.total_break_duration//3600, (active_entry.total_break_duration%3600)//60, active_entry.total_break_duration%60) }}</p>
<p class="break-total">Total break time: {{ active_entry.total_break_duration|format_duration }}</p>
{% endif %}
<div class="button-group">
@@ -85,7 +85,7 @@ Please <a href="{{ url_for('login') }}">login</a> or <a href="{{ url_for('regist
<tbody>
{% for entry in history %}
<tr data-entry-id="{{ entry.id }}">
<td>{{ entry.arrival_time.strftime('%Y-%m-%d') }}</td>
<td>{{ entry.arrival_time|format_date }}</td>
<td>
{% if entry.project %}
<span class="project-tag">{{ entry.project.code }}</span>
@@ -94,10 +94,10 @@ Please <a href="{{ url_for('login') }}">login</a> or <a href="{{ url_for('regist
<em>No project</em>
{% endif %}
</td>
<td>{{ entry.arrival_time.strftime('%H:%M:%S') }}</td>
<td>{{ entry.departure_time.strftime('%H:%M:%S') if entry.departure_time else 'Active' }}</td>
<td>{{ '%d:%02d:%02d'|format(entry.duration//3600, (entry.duration%3600)//60, entry.duration%60) if entry.duration is not none else 'In progress' }}</td>
<td>{{ '%d:%02d:%02d'|format(entry.total_break_duration//3600, (entry.total_break_duration%3600)//60, entry.total_break_duration%60) if entry.total_break_duration is not none else '00:00:00' }}</td>
<td>{{ entry.arrival_time|format_time }}</td>
<td>{{ entry.departure_time|format_time if entry.departure_time else 'Active' }}</td>
<td>{{ entry.duration|format_duration if entry.duration is not none else 'In progress' }}</td>
<td>{{ entry.total_break_duration|format_duration if entry.total_break_duration is not none else '0m' }}</td>
<td>
{% if entry.departure_time and not active_entry %}
<button class="resume-work-btn" data-id="{{ entry.id }}">Resume Work</button>
@@ -298,8 +298,8 @@ Please <a href="{{ url_for('login') }}">login</a> or <a href="{{ url_for('regist
// Get date and time from the row
const dateStr = cells[0].textContent.trim();
const arrivalTimeStr = cells[1].textContent.trim();
const departureTimeStr = cells[2].textContent.trim();
const arrivalTimeStr = cells[2].textContent.trim(); // arrival time is now in column 2
const departureTimeStr = cells[3].textContent.trim(); // departure time is now in column 3
// Set values in the form
document.getElementById('edit-entry-id').value = entryId;

View File

@@ -157,3 +157,171 @@ def get_available_rounding_options():
(30, "30 minutes"),
(60, "1 hour")
]
# Date/Time Formatting Functions
def get_available_date_formats():
"""
Get the available date format options.
Returns:
list: List of tuples (value, label, example)
"""
return [
('ISO', 'ISO Format (YYYY-MM-DD)', '2024-12-25'),
('US', 'US Format (MM/DD/YYYY)', '12/25/2024'),
('EU', 'European Format (DD/MM/YYYY)', '25/12/2024'),
('UK', 'UK Format (DD/MM/YYYY)', '25/12/2024'),
('Readable', 'Readable Format (Dec 25, 2024)', 'Dec 25, 2024'),
('Full', 'Full Format (December 25, 2024)', 'December 25, 2024')
]
def format_date_by_preference(dt, date_format='ISO'):
"""
Format a date according to user preference.
Args:
dt (datetime): The datetime to format
date_format (str): The format preference
Returns:
str: Formatted date string
"""
if dt is None:
return ''
format_map = {
'ISO': '%Y-%m-%d',
'US': '%m/%d/%Y',
'EU': '%d/%m/%Y',
'UK': '%d/%m/%Y',
'Readable': '%b %d, %Y',
'Full': '%B %d, %Y'
}
format_string = format_map.get(date_format, '%Y-%m-%d')
return dt.strftime(format_string)
def format_time_by_preference(dt, time_format_24h=True):
"""
Format a time according to user preference.
Args:
dt (datetime): The datetime to format
time_format_24h (bool): True for 24h format, False for 12h (AM/PM)
Returns:
str: Formatted time string
"""
if dt is None:
return ''
if time_format_24h:
return dt.strftime('%H:%M:%S')
else:
return dt.strftime('%I:%M:%S %p')
def format_datetime_by_preference(dt, date_format='ISO', time_format_24h=True):
"""
Format a datetime according to user preferences.
Args:
dt (datetime): The datetime to format
date_format (str): The date format preference
time_format_24h (bool): True for 24h format, False for 12h (AM/PM)
Returns:
str: Formatted datetime string
"""
if dt is None:
return ''
date_part = format_date_by_preference(dt, date_format)
time_part = format_time_by_preference(dt, time_format_24h)
return f"{date_part} {time_part}"
def format_time_short_by_preference(dt, time_format_24h=True):
"""
Format a time without seconds according to user preference.
Args:
dt (datetime): The datetime to format
time_format_24h (bool): True for 24h format, False for 12h (AM/PM)
Returns:
str: Formatted time string (without seconds)
"""
if dt is None:
return ''
if time_format_24h:
return dt.strftime('%H:%M')
else:
return dt.strftime('%I:%M %p')
def get_user_format_settings(user):
"""
Get the date/time format settings for a user.
Args:
user: The user object
Returns:
tuple: (date_format, time_format_24h)
"""
work_config = user.work_config
if work_config:
return work_config.date_format or 'ISO', work_config.time_format_24h
else:
return 'ISO', True # Default: ISO date format, 24h time
def format_duration_readable(duration_seconds):
"""
Format duration in a readable format (e.g., "2h 30m").
Args:
duration_seconds (int): Duration in seconds
Returns:
str: Formatted duration string
"""
if duration_seconds is None or duration_seconds == 0:
return '0m'
hours = duration_seconds // 3600
minutes = (duration_seconds % 3600) // 60
seconds = duration_seconds % 60
parts = []
if hours > 0:
parts.append(f"{hours}h")
if minutes > 0:
parts.append(f"{minutes}m")
if seconds > 0 and hours == 0: # Only show seconds if less than an hour
parts.append(f"{seconds}s")
return ' '.join(parts) if parts else '0m'
def format_duration_decimal(duration_seconds):
"""
Format duration as decimal hours (e.g., "2.5" for 2h 30m).
Args:
duration_seconds (int): Duration in seconds
Returns:
str: Formatted duration as decimal hours
"""
if duration_seconds is None:
return '0.00'
hours = duration_seconds / 3600
return f"{hours:.2f}"