Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- Shifts that cross midnight: a time range whose exit is earlier than its entry ends the next day (22:00 - 06:00 is 8 hours) and counts for the day it started. Only the range that starts last can end after midnight. The day panel says so and its preview counts those hours.

### Changed
- A time range with the same entry and exit is rejected ("Exit time must be different from entry time"). Before, any exit earlier than the entry was an error.

### Fixed
- `POST /entry` saves the day's `observation` (it was silently dropped) and `GET /entry/<date>` returns it. A request without the field keeps the note already saved.

Expand Down
6 changes: 4 additions & 2 deletions app/static/js/calendar.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,12 @@ document.addEventListener('DOMContentLoaded', function () {
function updateWorkedPreview() {
let total = 0;
collectEntries().forEach(e => {
if (e.entry && e.exit && e.exit > e.entry) {
if (e.entry && e.exit && e.exit !== e.entry) {
const [h1, m1] = e.entry.split(':').map(Number);
const [h2, m2] = e.exit.split(':').map(Number);
total += (h2 * 60 + m2 - h1 * 60 - m1) / 60;
let minutes = h2 * 60 + m2 - h1 * 60 - m1;
if (minutes < 0) minutes += 24 * 60; // ends the next day
total += minutes / 60;
}
});
document.getElementById('workedPreview').textContent = total ? t('worked', { hours: formatHours(total) }) : '';
Expand Down
1 change: 1 addition & 0 deletions app/templates/calendar.html
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ <h2 class="offcanvas-title h5" id="dayPanelTitle"></h2>
<button type="button" class="btn btn-link btn-sm px-0" id="addTimeRow">
{{ icon('plus', 'me-1') }} {{ _('Add time range') }}
</button>
<div class="form-text">{{ _('An exit earlier than the entry ends the next day.') }}</div>
<div class="form-text" id="workedPreview"></div>
</div>

Expand Down
Binary file modified app/translations/es/LC_MESSAGES/messages.mo
Binary file not shown.
15 changes: 12 additions & 3 deletions app/translations/es/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2026-10-03 06:28-0300\n"
"POT-Creation-Date: 2026-10-04 15:23-0300\n"
"PO-Revision-Date: 2026-10-03 01:51-0300\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: es\n"
Expand Down Expand Up @@ -72,6 +72,9 @@ msgstr "Agregar"
msgid "Add time range"
msgstr "Agregar rango horario"

msgid "An exit earlier than the entry ends the next day."
msgstr "Una salida anterior a la entrada termina al día siguiente."

msgid "Another code with this name already exists"
msgstr "Ya existe otro código con ese nombre"

Expand Down Expand Up @@ -194,8 +197,8 @@ msgstr "Salida"
msgid "Exit time"
msgstr "Hora de salida"

msgid "Exit time must be after entry time"
msgstr "La salida tiene que ser posterior a la entrada"
msgid "Exit time must be different from entry time"
msgstr "La salida tiene que ser distinta de la entrada"

msgid "File"
msgstr "Archivo"
Expand Down Expand Up @@ -309,6 +312,12 @@ msgstr "No hay horarios para el día laboral"
msgid "Observation"
msgstr "Observación"

msgid "Only one time range can end after midnight"
msgstr "Solo un rango horario puede terminar después de la medianoche"

msgid "Only the last time range of the day can end after midnight"
msgstr "Solo el último rango horario del día puede terminar después de la medianoche"

msgid "Password"
msgstr "Contraseña"

Expand Down
25 changes: 16 additions & 9 deletions app/translations/messages.pot
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2026-10-03 06:28-0300\n"
"POT-Creation-Date: 2026-10-04 15:23-0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
Expand Down Expand Up @@ -71,6 +71,9 @@ msgstr ""
msgid "Add time range"
msgstr ""

msgid "An exit earlier than the entry ends the next day."
msgstr ""

msgid "Another code with this name already exists"
msgstr ""

Expand All @@ -89,9 +92,7 @@ msgstr ""
msgid "Cannot delete code, it is currently in use."
msgstr ""

msgid ""
"Click a day to edit it. Drag across days, or Shift+click, to change "
"several at once."
msgid "Click a day to edit it. Drag across days, or Shift+click, to change several at once."
msgstr ""

msgid "Close"
Expand Down Expand Up @@ -193,7 +194,7 @@ msgstr ""
msgid "Exit time"
msgstr ""

msgid "Exit time must be after entry time"
msgid "Exit time must be different from entry time"
msgstr ""

msgid "File"
Expand Down Expand Up @@ -308,6 +309,12 @@ msgstr ""
msgid "Observation"
msgstr ""

msgid "Only one time range can end after midnight"
msgstr ""

msgid "Only the last time range of the day can end after midnight"
msgstr ""

msgid "Password"
msgstr ""

Expand Down Expand Up @@ -396,8 +403,8 @@ msgid "Type"
msgstr ""

msgid ""
"Types of absence you can assign to a day (vacation, sick leave...). "
"Renaming a code also renames it on the days that use it."
"Types of absence you can assign to a day (vacation, sick leave...). Renaming a code also renames "
"it on the days that use it."
msgstr ""

msgid "Unknown absence code"
Expand All @@ -410,8 +417,8 @@ msgid "Unsupported file type"
msgstr ""

msgid ""
"Upload a PDF or Excel report (xlsx) with date, entry, exit and "
"observation columns. You will see a preview before anything is saved."
"Upload a PDF or Excel report (xlsx) with date, entry, exit and observation columns. You will see "
"a preview before anything is saved."
msgstr ""

msgid "Upload and preview"
Expand Down
10 changes: 8 additions & 2 deletions app/utils/time_calculator.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
from datetime import datetime
from datetime import datetime, timedelta
from typing import Dict, List


def calculate_daily_hours(entries: List[Dict[str, str]]) -> float:
"""Calculate total hours worked in a day based on time entries."""
"""Calculate total hours worked in a day based on time entries.

An exit earlier than its entry ends the next day (a shift that crosses
midnight); its hours count for the day the shift started.
"""
total_hours: float = 0.0
for entry in entries:
if entry["exit"] and entry["entry"]:
entry_time = datetime.strptime(entry["entry"], "%H:%M")
exit_time = datetime.strptime(entry["exit"], "%H:%M")
diff = exit_time - entry_time
if diff < timedelta(0):
diff += timedelta(days=1)
total_hours += diff.total_seconds() / 3600
return total_hours

Expand Down
22 changes: 18 additions & 4 deletions app/utils/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,16 @@ def validate_time_format(time_str: str) -> bool:


def validate_entries(entries: list) -> tuple[bool, str]:
"""Validate a list of time entries."""
"""Validate a list of time entries.

An exit earlier than its entry means the range ends the next day. Only the
range that starts last can do that: any range after it would overlap.
"""
if not entries:
return False, _("No entries provided")

starts = []
overnight_start = None
for entry in entries:
# Check if both entry and exit times are provided
if not entry.get("entry") or not entry.get("exit"):
Expand All @@ -40,12 +46,20 @@ def validate_entries(entries: list) -> tuple[bool, str]:
try:
entry_time = datetime.strptime(entry["entry"], "%H:%M")
exit_time = datetime.strptime(entry["exit"], "%H:%M")

if exit_time <= entry_time:
return False, _("Exit time must be after entry time")
except ValueError:
return False, _("Invalid time values")

if exit_time == entry_time:
return False, _("Exit time must be different from entry time")
if exit_time < entry_time:
if overnight_start is not None:
return False, _("Only one time range can end after midnight")
overnight_start = entry_time
starts.append(entry_time)

if overnight_start is not None and overnight_start < max(starts):
return False, _("Only the last time range of the day can end after midnight")

return True, ""


Expand Down
2 changes: 1 addition & 1 deletion tests/test_day_logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def test_parse_flags_invalid_times(app, tmp_path):
from app.services.importer.protocol import ImportResult

records = [
TimeEntryRecord(date="2025-03-17", entry_time="17:00", exit_time="09:00"),
TimeEntryRecord(date="2025-03-17", entry_time="09:00", exit_time="09:00"),
TimeEntryRecord(date="2025-03-18", entry_time="09:00"),
TimeEntryRecord(date="2025-03-19", entry_time="09:00", exit_time="17:00"),
]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ def test_api_errors_follow_language(client, default_employee_id):
client.post("/lang/es")
response = client.put(
"/api/days/2025-03-17",
json={"kind": "work", "entries": [{"entry": "13:00", "exit": "09:00"}]},
json={"kind": "work", "entries": [{"entry": "09:00", "exit": "09:00"}]},
)
assert (
response.get_json()["error"] == "La salida tiene que ser posterior a la entrada"
response.get_json()["error"] == "La salida tiene que ser distinta de la entrada"
)


Expand Down
2 changes: 1 addition & 1 deletion tests/test_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def test_manual_entry_route_post_invalid(self):
"date": "2025-03-16",
"employee_id": 1,
"entries": [
{"entry": "17:00", "exit": "09:00"} # Exit before entry (invalid)
{"entry": "09:00", "exit": "09:00"} # Exit equal to entry (invalid)
],
"absence_code": None,
}
Expand Down
2 changes: 1 addition & 1 deletion tests/test_screens.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def test_save_work_day_with_observation(self, client, default_employee_id):
def test_save_rejects_bad_times(self, client, default_employee_id):
response = client.put(
"/api/days/2025-03-17",
json={"kind": "work", "entries": [{"entry": "13:00", "exit": "09:00"}]},
json={"kind": "work", "entries": [{"entry": "09:00", "exit": "09:00"}]},
)
assert response.status_code == 400

Expand Down
48 changes: 45 additions & 3 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ def test_calculate_daily_hours(self):
entries = [{"entry": "", "exit": ""}]
self.assertEqual(calculate_daily_hours(entries), 0.0)

def test_calculate_daily_hours_across_midnight(self):
# The exit is earlier than the entry: the range ends the next day
self.assertEqual(
calculate_daily_hours([{"entry": "22:00", "exit": "06:00"}]), 8.0
)
entries = [
{"entry": "14:00", "exit": "18:00"},
{"entry": "22:30", "exit": "00:15"},
]
self.assertEqual(calculate_daily_hours(entries), 5.75)

def test_validate_time_format(self):
# Valid time formats
self.assertTrue(validate_time_format("09:00"))
Expand All @@ -51,11 +62,11 @@ def test_validate_entries(self):
is_valid, _ = validate_entries(entries)
self.assertTrue(is_valid)

# Invalid entries - exit before entry
entries = [{"entry": "09:00", "exit": "08:00"}]
# Invalid entries - exit equal to entry
entries = [{"entry": "09:00", "exit": "09:00"}]
is_valid, error = validate_entries(entries)
self.assertFalse(is_valid)
self.assertEqual(error, "Exit time must be after entry time")
self.assertEqual(error, "Exit time must be different from entry time")

# Invalid entries - empty
entries = []
Expand All @@ -69,6 +80,37 @@ def test_validate_entries(self):
self.assertFalse(is_valid)
self.assertIn("time", error.lower())

def test_validate_entries_across_midnight(self):
# A range that ends the next day is valid when it starts last
entries = [
{"entry": "14:00", "exit": "18:00"},
{"entry": "22:00", "exit": "02:00"},
]
self.assertTrue(validate_entries(entries)[0])

# Order in the list does not matter, the start time does
self.assertTrue(validate_entries(list(reversed(entries)))[0])

# A range that starts after the overnight one would overlap it
entries = [
{"entry": "20:00", "exit": "01:00"},
{"entry": "21:00", "exit": "22:00"},
]
is_valid, error = validate_entries(entries)
self.assertFalse(is_valid)
self.assertEqual(
error, "Only the last time range of the day can end after midnight"
)

# Two ranges cannot both end the next day
entries = [
{"entry": "20:00", "exit": "01:00"},
{"entry": "23:00", "exit": "02:00"},
]
is_valid, error = validate_entries(entries)
self.assertFalse(is_valid)
self.assertEqual(error, "Only one time range can end after midnight")

def test_validate_date(self):
# Valid date formats
self.assertTrue(validate_date("2025-03-16"))
Expand Down
Loading