Skip to content

Self-hosted project management for devs and their clients: tickets, time tracking, docs and meetings, with an AI assistant that cites its sources. AGPL-3.0.

Book time on REST by the rule MCP books by (REST R6)

Guido Boyke1965d4f4cdc9
diff --git a/.github/workflows/guards.yml b/.github/workflows/guards.yml
index 73d4737..400d18b 100644
--- a/.github/workflows/guards.yml
+++ b/.github/workflows/guards.yml
@@ -291,6 +291,7 @@ jobs:
spec/requests/api/v1/error_codes_spec.rb
spec/requests/api/v1/idempotency_spec.rb
spec/requests/api/v1/capabilities_spec.rb
+ spec/requests/api/v1/time_session_booking_spec.rb
spec/models/codebase_import_mapping_spec.rb
spec/services/codebase_import/time_session_importer_spec.rb
spec/services/codebase_import/duplicate_prevention_spec.rb
diff --git a/CLAUDE.md b/CLAUDE.md
index 39f3085..48a309b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -809,6 +809,16 @@ feature by feature):
pinned against the routes both ways (`spec/requests/api/v1/capabilities_spec.rb`): a new
endpoint adds its line there. Additive changes bump the minor.
+`POST /api/v1/tickets/:ticket_id/time_sessions` books by the rule the MCP tool
+`create_time_session` books by (REST R6, 2026-10-29; feature `time_sessions.book` in
+`/me`): `TimeSessions::Booking` refuses no duration, both `duration_string` and
+`duration_minutes`, and an `occurred_on` that is no ISO 8601 date or timestamp (422
+`validation_failed`/`invalid_input`, inside the read gate), dates the booking as the
+calendar day in the token owner's profile zone (stored as midnight; absent = today there),
+and writes through `Actors::SaveTimeSession`. Rights stay in the controller. A booking
+writes no activity and no notification; it touches the ticket's `updated_at`. Guard:
+`spec/requests/api/v1/time_session_booking_spec.rb`.
+
`GET /api/v1/time_sessions/open` lists the person's own open hours within the token's
reach, organisations AND projects, and only the rows the web time list shows them
(`TimeSessions::ViewingScope`). A booking on a ticket they cannot read keeps its row and
diff --git a/app/controllers/api/v1/time_sessions_controller.rb b/app/controllers/api/v1/time_sessions_controller.rb
index e13ff0b..fd54b24 100644
--- a/app/controllers/api/v1/time_sessions_controller.rb
+++ b/app/controllers/api/v1/time_sessions_controller.rb
@@ -57,39 +57,33 @@ module Api
end
# POST /api/v1/tickets/:ticket_id/time_sessions
+ # Books by the rule the MCP tool create_time_session books by
+ # (TimeSessions::Booking): the day in the token owner's zone, one duration,
+ # the write through Actors::SaveTimeSession. The input is checked inside
+ # the read gate, so a refusal of it only ever answers for a ticket the
+ # token can read and tells nothing the 404 does not.
def create
- with_readable_ticket(params[:ticket_id]) do |ticket, project|
- session = build_session(ticket, project)
+ with_readable_ticket(params[:ticket_id]) do |ticket, _project|
+ booking = TimeSessions::Booking.parse(actor: current_user, **session_params.to_h.symbolize_keys)
+ next render_booking_refusal(booking.refusal) if booking.refused?
+
+ session = booking.build(ticket: ticket)
authorize session, :create?
- if session.save
- render json: { data: TimeSessions::Serializer.row(session) }, status: :created
+ result = booking.save(session)
+ if result.success?
+ render json: { data: TimeSessions::Serializer.row(result.resource) }, status: :created
else
- render_error(error: 'validation_failed', errors: session.errors.full_messages, status: :unprocessable_entity)
+ render_error(error: result.code, errors: result.errors, status: :unprocessable_entity)
end
end
end
private
- def build_session(ticket, project)
- ts = TimeSession.new(
- ticket: ticket,
- project: project,
- organisation: project.organisation,
- creator: current_user,
- occurred_on: parsed_occurred_on,
- description: session_params[:description],
- customer_description: session_params[:customer_description]
- )
-
- if session_params[:duration_string].present?
- ts.duration_string = session_params[:duration_string]
- elsif session_params[:duration_minutes].present?
- ts.duration = session_params[:duration_minutes].to_i
- end
-
- ts
+ def render_booking_refusal(refusal)
+ render_error(error: 'validation_failed', errors: [I18n.t("services.time_session_booking.#{refusal}")],
+ status: :unprocessable_entity)
end
def session_params
@@ -99,15 +93,6 @@ module Api
)
end
- def parsed_occurred_on
- raw = session_params[:occurred_on]
- return Time.current if raw.blank?
-
- Time.zone.parse(raw.to_s) || Time.current
- rescue ArgumentError
- Time.current
- end
-
def paginate(relation)
total = relation.count
page = page_param
diff --git a/app/services/CLAUDE.md b/app/services/CLAUDE.md
index ca0b8df..cc3f4b5 100644
--- a/app/services/CLAUDE.md
+++ b/app/services/CLAUDE.md
@@ -1,4 +1,4 @@
-# Karte: app/services (Stand: 2026-10-28)
+# Karte: app/services (Stand: 2026-10-29)
**Entry-Point-Konvention für NEUE Services: `Klass.call(**kwargs)`** (Klassenmethode; eine
Instanz-`#call`-Implementierung dahinter ist erlaubt). Pflicht: mindestens 1 Kommentarzeile
@@ -37,7 +37,12 @@ Verzeichnis-Übersicht (Auswahl):
sechstes Mal von Hand zu schreiben. `bucket_totals.rb` ist der
zweite Besitzer daneben: die Aggregation in die drei Abrechnungs-Töpfe, in EINER Query,
geteilt von `SummarizeTimeSessions` und dem Report-Panel des Assistenten — die
- Einordnung selbst bleibt `TimeSession.billing_bucket_for`. `date_bound.rb` ist der
+ Einordnung selbst bleibt `TimeSession.billing_bucket_for`. `booking.rb` (seit 29.10.2026,
+ REST R6) ist die EINE Regel einer Zeitbuchung per Token: das MCP-Werkzeug
+ `create_time_session` und `POST /api/v1/tickets/:ticket_id/time_sessions` buchen beide
+ hier durch (Dauer Pflicht und nur eine, `occurred_on` als Kalendertag in der Profilzone,
+ Schreiben über `Actors::SaveTimeSession`); Rechte prüfen die Hüllen zwischen `parse`,
+ `build` und `save`, die Texte der Ablehnungen auch. `date_bound.rb` ist der
dritte: die EINE Antwort auf „ist das eine Datumsgrenze, die ich der Datenbank geben
darf". `empty_reason.rb` ist der vierte: WARUM die Zeitenliste leer ist. Drop-one, ein
`EXISTS` je aktivem Filter und nur, wenn die Liste schon leer ist; „aktiv" fragt es am
diff --git a/app/services/api/v1/capabilities.rb b/app/services/api/v1/capabilities.rb
index 3663649..181aa94 100644
--- a/app/services/api/v1/capabilities.rb
+++ b/app/services/api/v1/capabilities.rb
@@ -15,7 +15,7 @@ module Api
module Capabilities
# Minor for an additive change (a new endpoint, field or capability), major
# never: an existing name, field or meaning does not change.
- API_VERSION = '1.1.0'
+ API_VERSION = '1.2.0'
# name => [verb, path as the router spells it]
ENDPOINTS = {
@@ -40,8 +40,11 @@ module Api
}.freeze
# Abilities that are not one endpoint: `idempotency` (the Idempotency-Key
- # header on every write, D7) and `error_codes` (`code` on every error body, D6).
- FEATURES = %w[idempotency error_codes].freeze
+ # header on every write, D7), `error_codes` (`code` on every error body, D6)
+ # and `time_sessions.book` (time_sessions.create books by the rule the MCP
+ # tool books by, TimeSessions::Booking: the day in the owner's zone, one
+ # duration, unusable input refused; R6).
+ FEATURES = %w[idempotency error_codes time_sessions.book].freeze
def self.names
(ENDPOINTS.keys + FEATURES).sort
diff --git a/app/services/lalabase/CLAUDE.md b/app/services/lalabase/CLAUDE.md
index 08929c4..efc7a7a 100644
--- a/app/services/lalabase/CLAUDE.md
+++ b/app/services/lalabase/CLAUDE.md
@@ -1,4 +1,4 @@
-# Karte: app/services/lalabase (Stand: 2026-10-28)
+# Karte: app/services/lalabase (Stand: 2026-10-29)
AI/RAG-Domäne (Produktname „Lalabase"): alles rund um LLM-Aufrufe, Embeddings und
Codebase-Verständnis.
@@ -36,7 +36,9 @@ Codebase-Verständnis.
im `:mcp`-Set, record-mode; `list_notifications`, `mark_notification_read`). Die Inbox-
Zeilen kommen aus `Notifications::InboxQuery` + `Serializer`, geteilt mit der HTTP-API.
Schreibende Werkzeuge gibt es nur im `:mcp`-Set: `create_ticket`, `post_comment`,
- `create_time_session`, `mark_notification_read`, `update_ticket`. `post_comment` schreibt
+ `create_time_session`, `mark_notification_read`, `update_ticket`. `create_time_session`
+ bucht über `TimeSessions::Booking`, dieselbe Regel wie die HTTP-API (seit 29.10.2026,
+ REST R6); im Werkzeug bleiben nur Argumente, Rechte und die Texte. `post_comment` schreibt
über `Actors::SavePost` wie das Web-Formular (Activity `post_added`, Benachrichtigungen,
Embedding); ein nacktes `Post#save` löste bis zum 10.10.2026 nichts davon aus, in
`Api::V1::PostsController` ebenso. `update_ticket`
diff --git a/app/services/lalabase/tools/create_time_session.rb b/app/services/lalabase/tools/create_time_session.rb
index b63d998..6538403 100644
--- a/app/services/lalabase/tools/create_time_session.rb
+++ b/app/services/lalabase/tools/create_time_session.rb
@@ -2,9 +2,10 @@
module Lalabase
module Tools
- # Books time on a ticket through Actors::SaveTimeSession, the write seam the
- # web form uses (billed guards, one transaction), and answers the row the
- # HTTP API answers (TimeSessions::Serializer, D4). Inbox workflow S2.
+ # Books time on a ticket by the rule the HTTP API books by
+ # (TimeSessions::Booking: the duration, the day, the write through
+ # Actors::SaveTimeSession) and answers the row the HTTP API answers
+ # (TimeSessions::Serializer, D4). Inbox workflow S2.
#
# Mutating (D3): blocked for a read-only PAT. Record-mode (D7): authorizes
# the ticket (:show?) and the session (:create?, TimeSessionPolicy: the
@@ -12,13 +13,8 @@ module Lalabase
# duration takes the form the web form takes ("1:30", "90", "1.5") or plain
# minutes.
#
- # occurred_on is a calendar DATE for billing: the web form stores midnight of
- # the picked date and every list and report buckets by that date, so a
- # booking is dated in the actor's profile time zone (User#time_zone) and
- # stored as that date's midnight, like the form. Absent means today in that
- # zone; a timestamp is read as the date it falls on there (a call at 00:30
- # Berlin belongs to that Berlin day, not to the UTC day before), its time
- # of day is dropped.
+ # occurred_on is a calendar DATE for billing, dated in the actor's profile
+ # time zone; the rule is TimeSessions::Booking's.
class CreateTimeSession < Base
def self.requires_actor?
true
@@ -63,6 +59,14 @@ module Lalabase
}
end
+ # Refusal texts of this surface (TimeSessions::Booking::REFUSALS), unchanged
+ # since the tool's first answer.
+ REFUSAL_TEXT = {
+ duration_missing: 'duration or duration_minutes is required',
+ both_durations: 'give either duration or duration_minutes, not both',
+ occurred_on_invalid: 'invalid occurred_on (expected an ISO 8601 date or timestamp)'
+ }.freeze
+
def self.execute(args:, context:)
return Result.new(error: 'project context missing') if context.project.nil?
@@ -70,11 +74,15 @@ module Lalabase
ticket_id = args[:ticket_id].to_s.strip
return Result.invalid_input('ticket_id is required') if ticket_id.empty?
return Result.invalid_input('invalid ticket_id format') unless ticket_id.match?(UUID_FORMAT)
- return Result.invalid_input('duration or duration_minutes is required') unless duration_given?(args)
- return Result.invalid_input('give either duration or duration_minutes, not both') if both_durations?(args)
- occurred_on = occurred_on_for(args, context.actor)
- return Result.invalid_input('invalid occurred_on (expected an ISO 8601 date or timestamp)') if occurred_on.nil?
+ # The booking rule is shared with the HTTP API (TimeSessions::Booking);
+ # it refuses unusable input before the ticket is touched.
+ booking = TimeSessions::Booking.parse(
+ actor: context.actor, duration_string: args[:duration], duration_minutes: args[:duration_minutes],
+ occurred_on: args[:occurred_on], description: args[:description],
+ customer_description: args[:customer_description]
+ )
+ return Result.invalid_input(REFUSAL_TEXT.fetch(booking.refusal)) if booking.refused?
# Inside the read scope: a ticket the caller may not read answers like a
# missing one (Base.readable_tickets).
@@ -84,57 +92,14 @@ module Lalabase
# Two checks, as in post_comment: :show? proves the actor may see the
# ticket at all, :create? proves the time permission in the project.
authorize!(context, ticket, :show?)
- session = build_session(ticket, context, args, occurred_on)
+ session = booking.build(ticket: ticket)
authorize!(context, session, :create?)
- result = Actors::SaveTimeSession.call(
- time_session: session, attributes: {},
- group_change: { requested: false, group: nil }, current_user: context.actor
- )
+ result = booking.save(session)
return Result.new(error: "booking failed: #{Array(result.errors).join(', ')}") unless result.success?
json_result(TimeSessions::Serializer.row(result.resource))
end
-
- def self.duration_given?(args)
- args[:duration].to_s.strip.present? || args[:duration_minutes].present?
- end
- private_class_method :duration_given?
-
- # Two durations would mean one silently wins; refused instead.
- def self.both_durations?(args)
- args[:duration].to_s.strip.present? && args[:duration_minutes].present?
- end
- private_class_method :both_durations?
-
- # The booking date as midnight in the app zone (the form's spelling,
- # Organisations::TimeSessionsController#ensure_valid_occurred_on): absent
- # means today in the actor's zone; a timestamp is the date it falls on
- # there; unusable means nil, which the caller refuses.
- def self.occurred_on_for(args, actor)
- zone = actor.time_zone
- raw = args[:occurred_on].to_s.strip
- return zone.today.in_time_zone if raw.empty?
-
- Lalabase::IsoTimestamp.parse(raw)&.in_time_zone(zone)&.to_date&.in_time_zone
- end
- private_class_method :occurred_on_for
-
- def self.build_session(ticket, context, args, occurred_on)
- session = TimeSession.new(
- ticket: ticket, project: context.project, organisation: context.organisation,
- creator: context.actor, occurred_on: occurred_on,
- description: args[:description].to_s.presence,
- customer_description: args[:customer_description].to_s.presence
- )
- if args[:duration].to_s.strip.present?
- session.duration_string = args[:duration].to_s
- else
- session.duration = args[:duration_minutes].to_i
- end
- session
- end
- private_class_method :build_session
end
end
end
diff --git a/app/services/time_sessions/booking.rb b/app/services/time_sessions/booking.rb
new file mode 100644
index 0000000..68e08b3
--- /dev/null
+++ b/app/services/time_sessions/booking.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+# The one rule of a time booking through a token: the MCP tool
+# create_time_session and POST /api/v1/tickets/:ticket_id/time_sessions both
+# book through it, so the two surfaces cannot drift apart again (before, REST
+# saved raw, dated a booking "now" and let one duration silently win).
+#
+# Entry point: parse
+#
+# Three steps, because the callers authorize in between: `parse` refuses
+# unusable input before any ticket is touched, `build` makes the unsaved
+# booking on a ticket the caller has found readable, and `save` writes it
+# through Actors::SaveTimeSession (billed guards, one transaction) once the
+# caller has authorized the booking itself (:create?, the project's time
+# permission). Rights stay with the callers; this object holds none.
+#
+# occurred_on is a calendar DAY for billing: the web form stores midnight of
+# the picked day and every list and report buckets by that day. A booking is
+# therefore dated in the actor's profile zone (User#time_zone) and stored as
+# that day's midnight. Absent means today there; a timestamp is the day it
+# falls on there (00:30 in Berlin belongs to that Berlin day, not to the UTC
+# day before), a timestamp without an offset is read as UTC; a plain date is
+# that day.
+module TimeSessions
+ class Booking
+ # Why `parse` turns an input away. Each caller words it for its surface.
+ REFUSALS = %i[duration_missing both_durations occurred_on_invalid].freeze
+
+ PLAIN_DATE = /\A\d{4}-\d{2}-\d{2}\z/
+
+ attr_reader :refusal
+
+ def self.parse(actor:, duration_string: nil, duration_minutes: nil, occurred_on: nil,
+ description: nil, customer_description: nil)
+ new(actor: actor, duration_string: duration_string.to_s.strip.presence,
+ duration_minutes: duration_minutes.presence, occurred_on: occurred_on,
+ description: description, customer_description: customer_description)
+ end
+
+ def initialize(actor:, duration_string:, duration_minutes:, occurred_on:, description:, customer_description:)
+ @actor = actor
+ @duration_string = duration_string
+ @duration_minutes = duration_minutes
+ @description = description.to_s.strip.presence && description.to_s
+ @customer_description = customer_description.to_s.strip.presence && customer_description.to_s
+ @refusal = refusal_for(occurred_on)
+ end
+
+ def refused?
+ end
+
+ # The unsaved booking on `ticket`, in the ticket's project and organisation.
+ def build(ticket:)
+ raise ArgumentError, "refused booking: #{@refusal}" if refused?
+
+ session = TimeSession.new(
+ ticket: ticket, project: ticket.project, organisation: ticket.organisation,
+ creator: @actor, occurred_on: @day,
+ description: @description, customer_description: @customer_description
+ )
+ if @duration_string
+ session.duration_string = @duration_string
+ else
+ session.duration = @duration_minutes.to_i
+ end
+ session
+ end
+
+ # => Actors::BaseActor::Result. A model refusal (a duration over a day, a
+ # duration that is no time) comes back as :validation_failed, nothing written.
+ def save(session)
+ Actors::SaveTimeSession.call(
+ time_session: session, attributes: {},
+ group_change: { requested: false, group: nil }, current_user: @actor
+ )
+ end
+
+ private
+
+ # The duration first, then the date, the order the MCP tool always answered in.
+ def refusal_for(occurred_on)
+ return :duration_missing if @duration_string.nil? && @duration_minutes.nil?
+ return :both_durations if @duration_string && @duration_minutes
+
+ @day = day_for(occurred_on)
+ :occurred_on_invalid if @day.nil?
+ end
+
+ # Midnight (app zone) of the booking's day, or nil for input that is no date.
+ def day_for(raw)
+ raw = raw.to_s.strip
+ zone = @actor.time_zone
+ return zone.today.in_time_zone if raw.empty?
+
+ parsed = Lalabase::IsoTimestamp.parse(raw)
+ return nil if parsed.nil?
+
+ day = raw.match?(PLAIN_DATE) ? parsed.to_date : parsed.in_time_zone(zone).to_date
+ day.in_time_zone
+ end
+ end
+end
diff --git a/config/locales/services.de.yml b/config/locales/services.de.yml
index 0254f2d..47ef8fb 100644
--- a/config/locales/services.de.yml
+++ b/config/locales/services.de.yml
@@ -96,6 +96,12 @@ de:
generic_error: "Die Zeit-Session konnte nicht gespeichert werden. Bitte versuchen Sie es später erneut."
meeting_moved: "Das Meeting liegt inzwischen in einem anderen Projekt. Bitte buchen Sie die Zeit dort."
moved_meanwhile: "Die Zeit-Session liegt inzwischen in einem anderen Projekt. Bitte laden Sie die Seite neu."
+ # The refusals of a time booking through a token (TimeSessions::Booking),
+ # as the HTTP API answers them; the MCP tool keeps its own English texts.
+ time_session_booking:
+ duration_missing: "Bitte geben Sie eine Dauer an (duration_string oder duration_minutes)."
+ both_durations: "Bitte geben Sie die Dauer entweder als duration_string oder als duration_minutes an, nicht beides."
+ occurred_on_invalid: "Das Datum (occurred_on) ist kein ISO-8601-Datum und kein ISO-8601-Zeitstempel."
bulk_customer_description_generator:
empty_result: "Zeit-Session %{id}: Die KI hat keine Beschreibung geliefert."
embedding_reprocessing:
diff --git a/config/locales/services.en.yml b/config/locales/services.en.yml
index 8f9f1ce..4f96729 100644
--- a/config/locales/services.en.yml
+++ b/config/locales/services.en.yml
@@ -96,6 +96,12 @@ en:
generic_error: "The time session could not be saved. Please try again later."
meeting_moved: "The meeting is in another project now. Please book the time there."
moved_meanwhile: "The time session is in another project now. Please reload the page."
+ # The refusals of a time booking through a token (TimeSessions::Booking),
+ # as the HTTP API answers them; the MCP tool keeps its own English texts.
+ time_session_booking:
+ duration_missing: "Give a duration (duration_string or duration_minutes)."
+ both_durations: "Give the duration either as duration_string or as duration_minutes, not both."
+ occurred_on_invalid: "The date (occurred_on) is no ISO 8601 date or timestamp."
bulk_customer_description_generator:
empty_result: "Time session %{id}: The AI returned no description."
embedding_reprocessing:
diff --git a/spec/contracts/mcp_contract_recorder.rb b/spec/contracts/mcp_contract_recorder.rb
index e878264..a5b9ac1 100644
--- a/spec/contracts/mcp_contract_recorder.rb
+++ b/spec/contracts/mcp_contract_recorder.rb
@@ -467,7 +467,44 @@ module McpContract
# answer per error code, then a write with an Idempotency-Key, its replay
# and the key reused with another body.
'errors' => rest_error_calls,
- 'idempotency' => rest_idempotency_calls
+ 'idempotency' => rest_idempotency_calls,
+ # REST R6, appended last: its bookings land on the login ticket after
+ # every answer above, without advancing the clock. Anna's time right on
+ # the website comes from time_report_calls; the archive has none.
+ 'POST /api/v1/tickets/:ticket_id/time_sessions' => rest_booking_calls
+ }
+ end
+
+ def rest_booking_calls
+ # Spelled out, not a loop: each request from its own line (Prosopite).
+ path = ->(ticket) { "/api/v1/tickets/#{id(ticket)}/time_sessions" }
+ login = path.call(:login_ticket)
+ once = { time_session: { duration_string: '0:15', description: 'Per REST, einmal.' } }
+ key = 'contract-rest-book-1'
+ {
+ 'ok_minutes_text' => rest_send(:post, :write, login, params: { time_session: { duration_string: '30' } }),
+ 'ok_hours_text' => rest_send(:post, :write, login,
+ params: { time_session: { duration_string: '1:30', occurred_on: '2026-01-04',
+ description: 'Vertrag' } }),
+ 'ok_minutes' => rest_send(:post, :write, login, params: { time_session: { duration_minutes: 45 } }),
+ 'invalid_input_no_duration' => rest_send(:post, :write, login, params: { time_session: { description: 'x' } }),
+ 'invalid_input_both_durations' => rest_send(:post, :write, login,
+ params: { time_session: { duration_string: '30',
+ duration_minutes: 30 } }),
+ 'invalid_input_date' => rest_send(:post, :write, login,
+ params: { time_session: { duration_string: '30', occurred_on: '05.01.2026' } }),
+ 'invalid_input_over_a_day' => rest_send(:post, :write, login, params: { time_session: { duration_string: '24:01' } }),
+ 'not_found' => rest_send(:post, :write, path.call(:missing), params: { time_session: { duration_string: '30' } }),
+ # No read access to the ticket: answered like a missing one.
+ 'hidden' => rest_send(:post, :write, path.call(:hidden_ticket), params: { time_session: { duration_string: '30' } }),
+ # Anna reads the archive's tickets but has no time right there.
+ 'forbidden' => rest_send(:post, :write, path.call(:archived_ticket),
+ params: { time_session: { duration_string: '30' } }),
+ 'read_only' => rest_send(:post, :read, login, params: { time_session: { duration_string: '30' } }),
+ 'idempotency_first' => rest_send(:post, :write, login, params: once, key: key),
+ 'idempotency_replay' => rest_send(:post, :write, login, params: once, key: key),
+ 'idempotency_mismatch' => rest_send(:post, :write, login, params: { time_session: { duration_string: '0:20' } },
+ key: key)
}
end
diff --git a/spec/fixtures/mcp_contract.json b/spec/fixtures/mcp_contract.json
index c46a8d5..d750464 100644
--- a/spec/fixtures/mcp_contract.json
+++ b/spec/fixtures/mcp_contract.json
@@ -1,9 +1,9 @@
{
"header": {
"regenerate": "RAILS_ENV=test bin/rails mcp:contract",
- "core_commit": "5efde7ed1c730d059eb559e15fab95ef35ccf129",
+ "core_commit": "5e88fdcd65b8203ec30951a5391789eaf863777c",
"core_dirty": true,
- "contract_sha256": "3fcc755d77e87d2762e975e0d111d8d5065f461277229f1a83d7bac370a672fb"
+ "contract_sha256": "ec5e63e1481227b1792970b89b434fb18976a3582fcedd233d8ba2381a7cc088"
},
"contract": {
"mcp": {
@@ -2992,7 +2992,7 @@
"all_projects": true
}
],
- "api_version": "1.1.0",
+ "api_version": "1.2.0",
"capabilities": [
"error_codes",
"idempotency",
@@ -3011,6 +3011,7 @@
"tickets.list",
"tickets.show",
"tickets.update",
+ "time_sessions.book",
"time_sessions.create",
"time_sessions.list",
"time_sessions.open"
@@ -3049,7 +3050,7 @@
"all_projects": true
}
],
- "api_version": "1.1.0",
+ "api_version": "1.2.0",
"capabilities": [
"error_codes",
"idempotency",
@@ -3068,6 +3069,7 @@
"tickets.list",
"tickets.show",
"tickets.update",
+ "time_sessions.book",
"time_sessions.create",
"time_sessions.list",
"time_sessions.open"
@@ -3591,6 +3593,361 @@
}
}
}
+ },
+ "POST /api/v1/tickets/:ticket_id/time_sessions": {
+ "ok_minutes_text": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "30"
+ }
+ }
+ },
+ "response": {
+ "status": 201,
+ "body": {
+ "data": {
+ "id": "<generated-id-8>",
+ "ticket_id": "00000000-0000-4000-8000-000000000041",
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ "occurred_on": "2026-01-05T00:00:00Z",
+ "duration_minutes": 30,
+ "description": null,
+ "customer_description": null,
+ "billed": false,
+ "billed_at": null,
+ "created_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "ok_hours_text": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "1:30",
+ "occurred_on": "2026-01-04",
+ "description": "Vertrag"
+ }
+ }
+ },
+ "response": {
+ "status": 201,
+ "body": {
+ "data": {
+ "id": "<generated-id-9>",
+ "ticket_id": "00000000-0000-4000-8000-000000000041",
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ "occurred_on": "2026-01-04T00:00:00Z",
+ "duration_minutes": 90,
+ "description": "Vertrag",
+ "customer_description": null,
+ "billed": false,
+ "billed_at": null,
+ "created_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "ok_minutes": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_minutes": 45
+ }
+ }
+ },
+ "response": {
+ "status": 201,
+ "body": {
+ "data": {
+ "id": "<generated-id-10>",
+ "ticket_id": "00000000-0000-4000-8000-000000000041",
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ "occurred_on": "2026-01-05T00:00:00Z",
+ "duration_minutes": 45,
+ "description": null,
+ "customer_description": null,
+ "billed": false,
+ "billed_at": null,
+ "created_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "invalid_input_no_duration": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "description": "x"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Bitte geben Sie eine Dauer an (duration_string oder duration_minutes)."
+ ]
+ }
+ }
+ },
+ "invalid_input_both_durations": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "30",
+ "duration_minutes": 30
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Bitte geben Sie die Dauer entweder als duration_string oder als duration_minutes an, nicht beides."
+ ]
+ }
+ }
+ },
+ "invalid_input_date": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "30",
+ "occurred_on": "05.01.2026"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Das Datum (occurred_on) ist kein ISO-8601-Datum und kein ISO-8601-Zeitstempel."
+ ]
+ }
+ }
+ },
+ "invalid_input_over_a_day": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "24:01"
+ }
+ }
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "validation_failed",
+ "code": "invalid_input",
+ "errors": [
+ "Dauer darf höchstens 1440 Minuten (24 Stunden) betragen"
+ ]
+ }
+ }
+ },
+ "not_found": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000999/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "30"
+ }
+ }
+ },
+ "response": {
+ "status": 404,
+ "body": {
+ "error": "not_found",
+ "code": "not_found"
+ }
+ }
+ },
+ "hidden": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000043/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "30"
+ }
+ }
+ },
+ "response": {
+ "status": 404,
+ "body": {
+ "error": "not_found",
+ "code": "not_found"
+ }
+ }
+ },
+ "forbidden": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000044/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "30"
+ }
+ }
+ },
+ "response": {
+ "status": 403,
+ "body": {
+ "error": "forbidden",
+ "code": "forbidden"
+ }
+ }
+ },
+ "read_only": {
+ "token": "read",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "30"
+ }
+ }
+ },
+ "response": {
+ "status": 403,
+ "body": {
+ "error": "forbidden",
+ "code": "read_only"
+ }
+ }
+ },
+ "idempotency_first": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "0:15",
+ "description": "Per REST, einmal."
+ }
+ },
+ "idempotency_key": "contract-rest-book-1"
+ },
+ "response": {
+ "status": 201,
+ "body": {
+ "data": {
+ "id": "<generated-id-11>",
+ "ticket_id": "00000000-0000-4000-8000-000000000041",
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ "occurred_on": "2026-01-05T00:00:00Z",
+ "duration_minutes": 15,
+ "description": "Per REST, einmal.",
+ "customer_description": null,
+ "billed": false,
+ "billed_at": null,
+ "created_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "idempotency_replay": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "0:15",
+ "description": "Per REST, einmal."
+ }
+ },
+ "idempotency_key": "contract-rest-book-1"
+ },
+ "response": {
+ "status": 201,
+ "body": {
+ "data": {
+ "id": "<generated-id-11>",
+ "ticket_id": "00000000-0000-4000-8000-000000000041",
+ "creator": {
+ "id": "00000000-0000-4000-8000-000000000011",
+ "name": "Anna Albers"
+ },
+ "occurred_on": "2026-01-05T00:00:00Z",
+ "duration_minutes": 15,
+ "description": "Per REST, einmal.",
+ "customer_description": null,
+ "billed": false,
+ "billed_at": null,
+ "created_at": "2026-01-05T09:36:00Z"
+ }
+ }
+ }
+ },
+ "idempotency_mismatch": {
+ "token": "write",
+ "request": {
+ "method": "POST",
+ "path": "/api/v1/tickets/00000000-0000-4000-8000-000000000041/time_sessions",
+ "params": {
+ "time_session": {
+ "duration_string": "0:20"
+ }
+ },
+ "idempotency_key": "contract-rest-book-1"
+ },
+ "response": {
+ "status": 422,
+ "body": {
+ "error": "idempotency_key_reused",
+ "code": "invalid_input",
+ "message": "idempotency_key already used with different parameters"
+ }
+ }
+ }
}
}
}
diff --git a/spec/requests/api/v1/capabilities_spec.rb b/spec/requests/api/v1/capabilities_spec.rb
index 6526449..6df8f4c 100644
--- a/spec/requests/api/v1/capabilities_spec.rb
+++ b/spec/requests/api/v1/capabilities_spec.rb
@@ -33,7 +33,7 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request do
it 'names the API version and the capabilities beside the existing fields' do
data = me(token(read_only: false))
- expect(data['api_version']).to eq('1.1.0')
+ expect(data['api_version']).to eq('1.2.0')
expect(data['capabilities']).to eq(Api::V1::Capabilities.names)
expect(data.keys).to include('user', 'token', 'scoped_organisations')
end
@@ -46,7 +46,7 @@ RSpec.describe 'API V1 capabilities', :ci_guard, type: :request do
expect(Api::V1::Capabilities.names).to include(
'me.show', 'organisations.list', 'projects.list', 'tickets.list', 'tickets.create', 'tickets.show',
'tickets.update', 'tickets.attachments', 'posts.create', 'time_sessions.create',
- 'notifications.list', 'notifications.mark_as_read', 'idempotency', 'error_codes'
+ 'notifications.list', 'notifications.mark_as_read', 'idempotency', 'error_codes', 'time_sessions.book'
)
end
diff --git a/spec/requests/api/v1/time_session_booking_spec.rb b/spec/requests/api/v1/time_session_booking_spec.rb
new file mode 100644
index 0000000..c93bd26
--- /dev/null
+++ b/spec/requests/api/v1/time_session_booking_spec.rb
@@ -0,0 +1,206 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: POST /api/v1/tickets/:ticket_id/time_sessions books by the rule the MCP
+# tool create_time_session books by (TimeSessions::Booking, cli_rest_plan R6).
+# Type: Request spec.
+# Why: The terminal client books time over REST. Before R6 REST saved raw (no
+# billed guards), dated a booking "now" instead of the day in the person's
+# zone, read an unusable date as "now" and let duration_string silently win
+# over duration_minutes. A booking is money: the day decides the invoice.
+RSpec.describe 'API V1 time booking', :ci_guard, type: :request do
+ include ActiveSupport::Testing::TimeHelpers
+
+ let(:organisation) { create(:organisation) }
+ let(:user) { create(:user, timezone: 'Europe/Berlin', language_preference: 'en') }
+ let(:role) { create(:role, organisation: organisation) }
+ let(:project) { ActsAsTenant.with_tenant(organisation) { create(:project, organisation: organisation) } }
+ let(:ticket) do
+ ActsAsTenant.with_tenant(organisation) { create(:ticket, project: project, organisation: organisation, creator: user) }
+ end
+ let(:read_only) { false }
+ let(:pat) do
+ pat = build(:personal_access_token, user: user, organisations: [organisation], read_only: read_only)
+ pat.token_hash = nil
+ pat.token_prefix = nil
+ pat.generate_token!
+ pat
+ end
+
+ before do
+ ActsAsTenant.with_tenant(organisation) do
+ create(:membership, user: user, organisation: organisation, role: role, active: true)
+ create(:project_permission, user: user, project: project, tickets_access: :read_write)
+ create(:time_session_permission, user: user, project: project, can_create_own: true)
+ end
+ end
+
+ def book(ticket_id: ticket.id, **time_session)
+ post "/api/v1/tickets/#{ticket_id}/time_sessions", params: { time_session: time_session },
+ headers: { 'Authorization' => "Bearer #{pat.token}" }
+ end
+
+ def body
+ JSON.parse(response.body)
+ end
+
+ def bookings
+ ActsAsTenant.without_tenant { TimeSession.where(ticket_id: ticket.id).count }
+ end
+
+ def booked
+ ActsAsTenant.without_tenant { TimeSession.find(body.dig('data', 'id')) }
+ end
+
+ describe 'the duration' do
+ { { duration_string: '30' } => 30, { duration_string: '1:30' } => 90, { duration_string: '1.5' } => 90,
+ { duration_minutes: 45 } => 45, { duration_string: '24:00' } => 1440 }.each do |input, minutes|
+ it "books #{input.inspect} as #{minutes} minutes" do
+ book(**input)
+ expect(response).to have_http_status(:created)
+ expect(body.dig('data', 'duration_minutes')).to eq(minutes)
+ end
+ end
+
+ it 'refuses both durations instead of letting one win, writing nothing' do
+ expect { book(duration_string: '1:30', duration_minutes: 45) }.not_to(change { bookings })
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to eq('error' => 'validation_failed', 'code' => 'invalid_input',
+ 'errors' => [I18n.t('services.time_session_booking.both_durations', locale: :en)])
+ end
+
+ it 'refuses a booking without a duration, writing nothing' do
+ expect { book(description: 'x') }.not_to(change { bookings })
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to include('error' => 'validation_failed', 'code' => 'invalid_input')
+ expect(body['errors']).to eq([I18n.t('services.time_session_booking.duration_missing', locale: :en)])
+ end
+
+ { duration_string: '24:01', duration_minutes: 1441 }.each do |key, too_long|
+ it "refuses more than a day (#{key} #{too_long}), writing nothing" do
+ expect { book(key => too_long) }.not_to(change { bookings })
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to include('error' => 'validation_failed', 'code' => 'invalid_input')
+ end
+ end
+
+ it 'answers the refusal in the token owner language' do
+ user.update!(language_preference: 'de')
+ book(duration_string: '1:30', duration_minutes: 45)
+ expect(body['errors']).to eq([I18n.t('services.time_session_booking.both_durations', locale: :de)])
+ end
+ end
+
+ describe 'the day (a calendar day in the profile zone, stored as midnight)' do
+ it 'defaults to today in the profile zone, also right after midnight there' do
+ travel_to Time.utc(2026, 8, 19, 22, 30) do # 00:30 on Aug 20 in Berlin
+ book(duration_minutes: 30)
+ end
+ expect(response).to have_http_status(:created)
+ expect(booked.occurred_on).to eq(Time.zone.parse('2026-08-20 00:00'))
+ expect(body.dig('data', 'occurred_on')).to eq(Time.zone.parse('2026-08-20 00:00').iso8601)
+ end
+
+ it 'takes the day a timestamp falls on in the profile zone' do
+ book(duration_minutes: 30, occurred_on: '2026-08-20T00:30:00+02:00')
+ expect(booked.occurred_on).to eq(Time.zone.parse('2026-08-20 00:00'))
+ book(duration_minutes: 30, occurred_on: '2026-05-20T10:00:00Z')
+ expect(booked.occurred_on).to eq(Time.zone.parse('2026-05-20 00:00'))
+ end
+
+ it 'takes a plain date as that day' do
+ book(duration_minutes: 30, occurred_on: '2026-08-20')
+ expect(booked.occurred_on).to eq(Time.zone.parse('2026-08-20 00:00'))
+ end
+
+ %w[gestern 05.01.2026 2026-02-30].push('2026-10-29 10:00').each do |raw|
+ it "refuses the unreadable date #{raw.inspect} instead of booking now, writing nothing" do
+ expect { book(duration_minutes: 30, occurred_on: raw) }.not_to(change { bookings })
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to eq('error' => 'validation_failed', 'code' => 'invalid_input',
+ 'errors' => [I18n.t('services.time_session_booking.occurred_on_invalid', locale: :en)])
+ end
+ end
+ end
+
+ it 'writes through Actors::SaveTimeSession' do
+ expect(Actors::SaveTimeSession).to receive(:call).and_call_original
+ book(duration_minutes: 30)
+ expect(response).to have_http_status(:created)
+ end
+
+ it 'answers an actor refusal with its code, writing nothing' do
+ allow(Actors::SaveTimeSession).to receive(:call)
+ .and_return(Actors::BaseActor::Result.new(success: false, errors: ['nope'], code: :group_billed))
+ book(duration_minutes: 30)
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(body).to eq('error' => 'group_billed', 'code' => 'refused', 'reason' => 'group_billed', 'errors' => ['nope'])
+ end
+
+ it 'books the same row the MCP tool books for the same input' do
+ input = { duration_string: '1:30', occurred_on: '2026-08-20T00:30:00+02:00', description: 'Fixed the login' }
+ book(**input)
+ rest = booked
+
+ context = Lalabase::Tools::Context.new(actor: user, organisation: organisation, project: project,
+ authorization: Lalabase::Tools::AuthorizationRecorder.new)
+ mcp_args = { ticket_id: ticket.id, duration: input[:duration_string], occurred_on: input[:occurred_on],
+ description: input[:description] }
+ mcp = ActsAsTenant.with_tenant(organisation) do
+ TimeSession.find(JSON.parse(Lalabase::Tools::CreateTimeSession.execute(args: mcp_args, context: context).content)['id'])
+ end
+
+ fields = %i[occurred_on duration description customer_description creator_id ticket_id project_id organisation_id]
+ expect(mcp.slice(*fields)).to eq(rest.slice(*fields))
+ end
+
+ # What a client reloads after a booking (cli_rest_plan K6): the booking is no
+ # activity and notifies nobody; it touches the ticket's updated_at.
+ it 'writes no activity and no notification, and touches the ticket' do
+ ActsAsTenant.with_tenant(organisation) { ticket.update_column(:updated_at, 1.day.ago) }
+ expect { book(duration_minutes: 30) }
+ .not_to(change { ActsAsTenant.without_tenant { [Activity.count, Notification.count] } })
+ expect(response).to have_http_status(:created)
+ expect(ActsAsTenant.without_tenant { ticket.reload.updated_at }).to be > 1.minute.ago
+ end
+
+ describe 'who may book' do
+ it 'answers a missing and a hidden ticket the same, writing nothing' do
+ book(ticket_id: SecureRandom.uuid, duration_minutes: 30)
+ missing = [response.status, response.body]
+
+ ActsAsTenant.with_tenant(organisation) { ProjectPermission.where(user: user, project: project).destroy_all }
+ expect { book(duration_minutes: 30) }.not_to(change { bookings })
+ expect([response.status, response.body]).to eq(missing)
+ expect(missing.first).to eq(404)
+ end
+
+ # The input is checked inside the read gate: a refusal of the input only for
+ # a ticket the token can read, so it tells nothing the 404 does not.
+ it 'answers a hidden ticket with unusable input like a missing one' do
+ book(ticket_id: SecureRandom.uuid, duration_string: '1:30', duration_minutes: 45)
+ missing = [response.status, response.body]
+ ActsAsTenant.with_tenant(organisation) { ProjectPermission.where(user: user, project: project).destroy_all }
+ book(duration_string: '1:30', duration_minutes: 45)
+ expect([response.status, response.body]).to eq(missing)
+ end
+
+ it 'refuses a booking without the time permission in the project, writing nothing' do
+ ActsAsTenant.with_tenant(organisation) { TimeSessionPermission.where(user: user).destroy_all }
+ expect { book(duration_minutes: 30) }.not_to(change { bookings })
+ expect(response).to have_http_status(:forbidden)
+ expect(body).to include('error' => 'forbidden', 'code' => 'forbidden')
+ end
+
+ context 'with a read-only token' do
+ let(:read_only) { true }
+
+ it 'refuses, writing nothing' do
+ expect { book(duration_minutes: 30) }.not_to(change { bookings })
+ expect(response).to have_http_status(:forbidden)
+ expect(body).to eq('error' => 'forbidden', 'code' => 'read_only')
+ end
+ end
+ end
+end
diff --git a/spec/requests/api/v1/write_endpoints_spec.rb b/spec/requests/api/v1/write_endpoints_spec.rb
index 4fff37f..4f741ba 100644
--- a/spec/requests/api/v1/write_endpoints_spec.rb
+++ b/spec/requests/api/v1/write_endpoints_spec.rb
@@ -204,10 +204,10 @@ RSpec.describe 'API V1 Write Endpoints', :ci_guard, type: :request do
user.update!(language_preference: 'de')
I18n.locale = :en
post "/api/v1/tickets/#{ticket.id}/time_sessions",
- params: { time_session: { occurred_on: '2026-05-20T10:00:00Z' } },
+ params: { time_session: { occurred_on: '2026-05-20T10:00:00Z', duration_minutes: 0 } },
headers: auth_headers
expect(response).to have_http_status(:unprocessable_content)
- expect(JSON.parse(response.body)['errors'].join).to include('muss ausgefüllt werden')
+ expect(JSON.parse(response.body)['errors'].join).to include('muss größer als 0 sein')
expect(I18n.locale).to eq(:en)
ensure
I18n.locale = I18n.default_locale
diff --git a/spec/services/time_sessions/booking_spec.rb b/spec/services/time_sessions/booking_spec.rb
new file mode 100644
index 0000000..783b77e
--- /dev/null
+++ b/spec/services/time_sessions/booking_spec.rb
@@ -0,0 +1,144 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+# What: TimeSessions::Booking, the one rule of a time booking through a token.
+# Type: Service spec.
+# Why: The MCP tool create_time_session and POST /api/v1/tickets/:id/time_sessions
+# both book through it (cli_rest_plan R6, D5). A booking is money: the day it
+# lands on decides the invoice, one duration must never silently win over the
+# other, and the write must go through Actors::SaveTimeSession (billed guards,
+# one transaction), never a raw save.
+RSpec.describe TimeSessions::Booking do
+ include ActiveSupport::Testing::TimeHelpers
+
+ let(:organisation) { create(:organisation) }
+ let(:project) { create(:project, organisation: organisation) }
+ let(:actor) { create(:user, timezone: 'Europe/Berlin') }
+ let(:ticket) { create(:ticket, project: project, organisation: organisation, creator: create(:user)) }
+
+ before { ActsAsTenant.current_tenant = organisation }
+ after { ActsAsTenant.current_tenant = nil }
+
+ def parse(**input)
+ described_class.parse(actor: actor, **input)
+ end
+
+ describe 'refusals' do
+ it 'refuses a booking without a duration' do
+ expect(parse.refusal).to eq(:duration_missing)
+ expect(parse(duration_string: ' ').refusal).to eq(:duration_missing)
+ expect(parse(duration_minutes: '').refusal).to eq(:duration_missing)
+ end
+
+ it 'refuses both durations instead of letting one win' do
+ expect(parse(duration_string: '1:30', duration_minutes: 45).refusal).to eq(:both_durations)
+ expect(parse(duration_string: '1:30', duration_minutes: '45').refusal).to eq(:both_durations)
+ end
+
+ it 'refuses an occurred_on it cannot read' do
+ %w[gestern 05.01.2026 2026-02-30 10000-01-01].push('2026-10-29 10:00').each do |raw|
+ expect(parse(duration_string: '30', occurred_on: raw).refusal).to eq(:occurred_on_invalid), raw
+ end
+ end
+
+ it 'checks the duration before the date' do
+ expect(parse(occurred_on: 'gestern').refusal).to eq(:duration_missing)
+ end
+
+ it 'accepts a usable input' do
+ booking = parse(duration_string: '30')
+ expect(booking.refused?).to be false
+ expect(booking.refusal).to be_nil
+ end
+ end
+
+ describe 'the booking date (a calendar day in the actor zone, stored as midnight)' do
+ def day_of(**input)
+ parse(duration_string: '30', **input).build(ticket: ticket).occurred_on
+ end
+
+ it 'defaults to today in the actor zone, also right after midnight there' do
+ travel_to Time.utc(2026, 8, 19, 22, 30) do # 00:30 on Aug 20 in Berlin
+ expect(day_of).to eq(Time.zone.parse('2026-08-20 00:00'))
+ end
+ end
+
+ it 'takes the day a timestamp falls on in the actor zone' do
+ expect(day_of(occurred_on: '2026-08-20T00:30:00+02:00')).to eq(Time.zone.parse('2026-08-20 00:00'))
+ expect(day_of(occurred_on: '2026-08-19T22:30:00Z')).to eq(Time.zone.parse('2026-08-20 00:00'))
+ expect(day_of(occurred_on: '2026-08-19T21:59:00Z')).to eq(Time.zone.parse('2026-08-19 00:00'))
+ end
+
+ it 'reads a timestamp without an offset as UTC' do
+ expect(day_of(occurred_on: '2026-08-19T22:30:00')).to eq(Time.zone.parse('2026-08-20 00:00'))
+ end
+
+ it 'takes a plain date as that day' do
+ expect(day_of(occurred_on: '2026-08-20')).to eq(Time.zone.parse('2026-08-20 00:00'))
+ end
+
+ it 'follows the actor profile zone' do
+ actor.update!(timezone: 'America/New_York')
+ expect(day_of(occurred_on: '2026-08-20T02:00:00Z')).to eq(Time.zone.parse('2026-08-19 00:00'))
+ end
+
+ # A plain date names the day itself. Read as UTC midnight and then moved into
+ # a zone west of UTC, it would land on the day before.
+ it 'takes a plain date as that day in a zone west of UTC too' do
+ actor.update!(timezone: 'America/New_York')
+ expect(day_of(occurred_on: '2026-08-20')).to eq(Time.zone.parse('2026-08-20 00:00'))
+ end
+ end
+
+ describe '#build' do
+ it 'builds an unsaved booking on the ticket, as the actor' do
+ session = parse(duration_string: '1:30', description: 'Fixed it', customer_description: 'Login')
+ .build(ticket: ticket)
+ expect(session).to be_new_record
+ expect(session).to have_attributes(ticket: ticket, project: project, organisation: organisation,
+ creator: actor, description: 'Fixed it', customer_description: 'Login')
+ end
+
+ it 'takes the duration as text or as minutes' do
+ { { duration_string: '30' } => 30, { duration_string: '1:30' } => 90, { duration_string: '1.5' } => 90,
+ { duration_minutes: 45 } => 45, { duration_minutes: '45' } => 45 }.each do |input, minutes|
+ session = parse(**input).build(ticket: ticket)
+ session.valid?
+ expect(session.duration).to eq(minutes), input.inspect
+ end
+ end
+
+ it 'stores blank descriptions as none' do
+ session = parse(duration_string: '30', description: '', customer_description: ' ').build(ticket: ticket)
+ expect(session.description).to be_nil
+ expect(session.customer_description).to be_nil
+ end
+ end
+
+ describe '#save' do
+ it 'writes through Actors::SaveTimeSession, without a group change' do
+ booking = parse(duration_string: '30')
+ session = booking.build(ticket: ticket)
+ expect(Actors::SaveTimeSession).to receive(:call)
+ .with(time_session: session, attributes: {}, group_change: { requested: false, group: nil },
+ current_user: actor).and_call_original
+ result = booking.save(session)
+ expect(result.success?).to be true
+ expect(result.resource).to be_persisted
+ end
+
+ it 'answers the model refusal for a duration over a day, writing nothing' do
+ booking = parse(duration_string: '24:01')
+ result = nil
+ expect { result = booking.save(booking.build(ticket: ticket)) }.not_to change(TimeSession, :count)
+ expect(result.success?).to be false
+ expect(result.code).to eq(:validation_failed)
+ end
+
+ it 'books a full day' do
+ booking = parse(duration_string: '24:00')
+ expect(booking.save(booking.build(ticket: ticket)).success?).to be true
+ end
+ end
+end