diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c7c66e..88c0e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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/` returns it. A request without the field keeps the note already saved. diff --git a/app/static/js/calendar.js b/app/static/js/calendar.js index 8e6b8f9..9d0341f 100644 --- a/app/static/js/calendar.js +++ b/app/static/js/calendar.js @@ -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) }) : ''; diff --git a/app/templates/calendar.html b/app/templates/calendar.html index 1e2b86a..c2732b5 100644 --- a/app/templates/calendar.html +++ b/app/templates/calendar.html @@ -61,6 +61,7 @@

+
{{ _('An exit earlier than the entry ends the next day.') }}
diff --git a/app/translations/es/LC_MESSAGES/messages.mo b/app/translations/es/LC_MESSAGES/messages.mo index 837070e..e6c7de8 100644 Binary files a/app/translations/es/LC_MESSAGES/messages.mo and b/app/translations/es/LC_MESSAGES/messages.mo differ diff --git a/app/translations/es/LC_MESSAGES/messages.po b/app/translations/es/LC_MESSAGES/messages.po index ec21dd3..33a0552 100644 --- a/app/translations/es/LC_MESSAGES/messages.po +++ b/app/translations/es/LC_MESSAGES/messages.po @@ -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 \n" "Language: es\n" @@ -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" @@ -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" @@ -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" diff --git a/app/translations/messages.pot b/app/translations/messages.pot index bf919f9..29604b6 100644 --- a/app/translations/messages.pot +++ b/app/translations/messages.pot @@ -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 \n" "Language-Team: LANGUAGE \n" @@ -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 "" @@ -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" @@ -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" @@ -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 "" @@ -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" @@ -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" diff --git a/app/utils/time_calculator.py b/app/utils/time_calculator.py index 8694b79..d0df42b 100644 --- a/app/utils/time_calculator.py +++ b/app/utils/time_calculator.py @@ -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 diff --git a/app/utils/validators.py b/app/utils/validators.py index ff2f1a5..1b4b1d5 100644 --- a/app/utils/validators.py +++ b/app/utils/validators.py @@ -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"): @@ -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, "" diff --git a/tests/test_day_logic.py b/tests/test_day_logic.py index 622dadc..6708dd9 100644 --- a/tests/test_day_logic.py +++ b/tests/test_day_logic.py @@ -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"), ] diff --git a/tests/test_i18n.py b/tests/test_i18n.py index c01418a..e60421e 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -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" ) diff --git a/tests/test_routes.py b/tests/test_routes.py index 307d85a..c5ebec5 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -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, } diff --git a/tests/test_screens.py b/tests/test_screens.py index 28147cf..04e63aa 100644 --- a/tests/test_screens.py +++ b/tests/test_screens.py @@ -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 diff --git a/tests/test_utils.py b/tests/test_utils.py index c2effe8..aa6469a 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -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")) @@ -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 = [] @@ -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"))