Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56b387a784 | |||
| 4011e61a63 | |||
| 2cb3aca27c | |||
| 77072d057a | |||
| 202eb78ae4 | |||
| bf59cd830c | |||
| 041e2159e7 | |||
| d64de50802 | |||
| 7843fe88e5 | |||
| 39b199d7e6 | |||
| 74495e56cb | |||
| 6ca1816c95 | |||
| 2d7d105ba3 | |||
| 41b9426670 | |||
| baf624c7a6 | |||
| d10570fc0c | |||
| 30f6d79f9e | |||
| 760a87ab99 | |||
| 7098751f7f | |||
| 1df2a1a730 | |||
| a52e35b52b | |||
| a36a9e8c19 | |||
| 68b165db7b | |||
| 2ad6e9d60e | |||
| a6cd64e3f9 | |||
| 371a00aff5 | |||
| c071235ad7 | |||
| 9bcf41bb1f |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -118,6 +118,7 @@ dist
|
||||
.template-preview-test-build/
|
||||
.import-test-build/
|
||||
webui/.component-test-build/
|
||||
webui/.calendar-picker-test-build/
|
||||
webui/.module-test-build/
|
||||
webui/.policy-test-build/
|
||||
webui/.template-preview-test-build/
|
||||
|
||||
22
README.md
22
README.md
@@ -1,5 +1,9 @@
|
||||
# govoplan-calendar
|
||||
|
||||
<!-- govoplan-repository-type:start -->
|
||||
**Repository type:** module (domain).
|
||||
<!-- govoplan-repository-type:end -->
|
||||
|
||||
GovOPlaN Calendar is the standalone calendar module. It provides tenant calendar collections, iCalendar/VEVENT event storage, a calendar WebUI, and integration boundaries for scheduling, tasks, mail, appointments, workflow, notifications, and external groupware.
|
||||
|
||||
## Ownership
|
||||
@@ -36,9 +40,21 @@ The first backend implementation stores VEVENT data in two layers:
|
||||
CalDAV sync is implemented as a calendar-owned backend primitive. A CalDAV source
|
||||
records the remote collection URL, sync token, ETag/ctag state, username,
|
||||
credential reference, sync interval, sync direction, and conflict policy.
|
||||
Credentials can be supplied transiently for manual sync, referenced from
|
||||
environment variables with `env:NAME`, stored through a platform secret provider
|
||||
when one is available, or stored as encrypted calendar-owned credentials.
|
||||
Credentials can be supplied transiently for manual sync. Persisted API-managed
|
||||
sources accept only a password or token: Calendar stores an opaque, tenant- and
|
||||
source-bound local reference, backed by the platform secret provider when one is
|
||||
available or by an encrypted calendar-owned credential otherwise. Caller-selected
|
||||
environment and external-provider references are rejected. Trusted deployment
|
||||
code may resolve an `env:NAME` reference only through the separate deployment
|
||||
configuration helper.
|
||||
|
||||
Deleting a source or its calendar immediately scrubs Calendar-owned ciphertext
|
||||
and provider references and emits non-secret audit evidence. If an external
|
||||
secret provider cannot confirm deletion, the operation fails closed without
|
||||
retiring the source or cancelling its queued work; retry is idempotent after a
|
||||
database rollback. Destructive module retirement first deletes and audits all
|
||||
active and legacy retained provider secrets and stops before table removal on
|
||||
provider failure.
|
||||
|
||||
Inbound sync uses CalDAV `calendar-query` for full sync and `sync-collection`
|
||||
when a sync token exists. It imports all VEVENT components in a resource and
|
||||
|
||||
@@ -24,10 +24,94 @@ The first standalone module provides:
|
||||
- API endpoints for listing calendars, creating/updating/deleting events, importing iCalendar, and exporting event ICS
|
||||
- free/busy API primitive with recurrence expansion for scheduling and appointment conflict checks
|
||||
- calendar-owned CalDAV sync sources with credential references, scheduled due-sync metadata, full/incremental inbound sync, two-way PUT/DELETE writes, and ETag conflict handling
|
||||
- a Calendar-owned durable desired-state outbox for two-way CalDAV writes. Event
|
||||
state and the exact external resource snapshot commit atomically; workers use
|
||||
deterministic hrefs, conditional requests, expiring leases, bounded
|
||||
exponential retry, and semantic GET reconciliation after ambiguous outcomes
|
||||
- WebUI views: month, week, workweek, day, and continuous week-row scrolling
|
||||
|
||||
The first implementation is not yet a full CalDAV network server. It is the internal calendar storage, sync, availability, and UI foundation on which Open-Xchange integration, richer recurrence editing, scheduling inbox/outbox behavior, and CalDAV server endpoints can be built.
|
||||
|
||||
## Outbound delivery operations
|
||||
|
||||
No event API or cross-module capability performs CalDAV network I/O inside the
|
||||
caller's transaction. A local mutation instead creates a
|
||||
`calendar_outbox_operations` row containing the exact desired ICS resource,
|
||||
target href, expected ETag, conflict-policy snapshot, and idempotency key.
|
||||
|
||||
The registered `govoplan.calendar.dispatch_outbox` worker commits an expiring
|
||||
lease before doing network I/O and commits each outcome independently. If a
|
||||
worker loses the database connection after a successful remote write, the next
|
||||
attempt reads the remote object and compares semantic ICS fingerprints. A
|
||||
matching PUT or an already absent DELETE completes successfully without a blind
|
||||
duplicate write. Pending updates for one href supersede older never-attempted
|
||||
rows; attempted predecessors are reconciled first, and updates queued behind an
|
||||
in-flight write inherit the ETag produced by that write. Delivery and inbound
|
||||
REPORT application take the same source-row lock,
|
||||
and only one operation per source is leased at a time. This deliberately trades
|
||||
per-source throughput for a simple ordering guarantee: a stale inbound report
|
||||
cannot land after a newer outbound result, and queued leases do not expire while
|
||||
waiting behind another network request for the same source.
|
||||
|
||||
Operators can list, dispatch, retry, reconcile, and discard tenant operations
|
||||
through the `/calendar/caldav/outbox` administration endpoints. Terminal ETag
|
||||
conflicts and exhausted retries remain the current local desired state and
|
||||
shield that resource from inbound overwrite until explicitly resolved.
|
||||
Discarding is the administrator's accept-remote transition: it is allowed only
|
||||
for the latest generation, atomically cancels its unresolved predecessor chain,
|
||||
marks the event projection as discarded, clears the sync token, and schedules a
|
||||
full inbound reconciliation so an unchanged remote object is not missed.
|
||||
|
||||
Disabling outbound delivery or switching to inbound-only is rejected while
|
||||
unresolved desired state exists; retirement is the explicit exception and
|
||||
cancels unresolved work. Endpoint/calendar changes also require no active event
|
||||
bindings or unresolved delivery. Credential rotation does not discard committed
|
||||
desired state. Public event mutation cannot set sync-owned source hrefs, kinds,
|
||||
or ETags. Deleting a synchronized collection or retiring its source is a local
|
||||
unlink: it never deletes the remote collection or its remaining remote events.
|
||||
The unlink immediately scrubs Calendar-owned credential ciphertext and external
|
||||
provider references and audits the deletion. External provider failure blocks
|
||||
retirement before queued work is changed; a later retry tolerates a provider
|
||||
secret already removed by an earlier attempt whose database transaction rolled
|
||||
back. Provider errors and audit details never contain credential values or
|
||||
secret references.
|
||||
The current singular ownership model permits one active sync source per
|
||||
calendar; multi-source fan-in will require per-event source routing. Celery beat
|
||||
triggers recovery every minute, while root-transaction after-commit dispatch
|
||||
provides the normal low-latency path.
|
||||
|
||||
### Collection retirement and bulk event moves
|
||||
|
||||
Collection deletion accepts two explicit, non-destructive external actions for
|
||||
`event_action="move"`:
|
||||
|
||||
- `detach_keep_remote` applies only when the source collection is synchronized
|
||||
and the target is local. It moves the local event projections, clears their
|
||||
sync-owned source kind, href, ETag, and CalDAV projection metadata, retires
|
||||
the source locally, and cancels undelivered outbox state. An active delivery
|
||||
lease blocks the transaction. The action never enqueues a remote DELETE, so
|
||||
the remote collection and remote events remain unchanged.
|
||||
- `copy_to_remote` applies only when the source is local and the target has an
|
||||
active, enabled, two-way CalDAV source. It moves the local events and commits
|
||||
destination PUT desired states in the durable outbox in the same database
|
||||
transaction. Remote failures therefore remain visible and retryable without
|
||||
rolling back or hiding the local move.
|
||||
|
||||
Local-to-local moves retain their existing behavior and do not accept an
|
||||
`external_action`. Implicit or mismatched actions, inbound-only destinations,
|
||||
and synchronized-to-synchronized moves are rejected. `remote_move` is a known
|
||||
but deliberately unsupported action: implementing it requires a separately
|
||||
approved saga for destination reconciliation, conditional source deletion,
|
||||
collision handling, and concurrent-edit policy. The WebUI does not offer that
|
||||
destructive mode.
|
||||
|
||||
Resolved terminal rows (`succeeded`, `superseded`, and `cancelled`) are removed
|
||||
in bounded batches after `CALENDAR_OUTBOX_TERMINAL_RETENTION_DAYS` (90 days by
|
||||
default; `0` disables cleanup). `conflict` and `dead` rows are never removed by
|
||||
this cleanup because they still carry unresolved local desired state. Each
|
||||
periodic or after-commit dispatch also performs one bounded cleanup batch for
|
||||
the same tenant scope.
|
||||
|
||||
## Integration Points
|
||||
|
||||
### Scheduling
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@govoplan/calendar-webui",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "webui/src/index.ts",
|
||||
@@ -19,7 +19,7 @@
|
||||
"LICENSE"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"@govoplan/core-webui": "^0.1.7",
|
||||
"@govoplan/core-webui": "^0.1.9",
|
||||
"lucide-react": "^1.23.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
|
||||
@@ -4,15 +4,16 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "govoplan-calendar"
|
||||
version = "0.1.7"
|
||||
version = "0.1.8"
|
||||
description = "GovOPlaN calendar module with VEVENT storage and WebUI integration."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
license = { file = "LICENSE" }
|
||||
authors = [{ name = "GovOPlaN" }]
|
||||
dependencies = [
|
||||
"govoplan-core>=0.1.7",
|
||||
"govoplan-access>=0.1.7",
|
||||
"govoplan-core>=0.1.9",
|
||||
"govoplan-access>=0.1.8",
|
||||
"defusedxml>=0.7,<1",
|
||||
"icalendar>=7.2",
|
||||
"python-dateutil>=2.9",
|
||||
]
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
__all__ = ["__version__"]
|
||||
|
||||
__version__ = "0.1.4"
|
||||
__version__ = "0.1.8"
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import posixpath
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Mapping, Protocol
|
||||
from xml.etree import ElementTree
|
||||
from typing import Any, Mapping, Protocol
|
||||
|
||||
from defusedxml import ElementTree as SafeElementTree
|
||||
from govoplan_core.security.outbound_http import (
|
||||
OutboundHttpError,
|
||||
bounded_response_bytes,
|
||||
build_outbound_http_opener,
|
||||
validate_outbound_http_url,
|
||||
)
|
||||
|
||||
|
||||
class CalDAVError(RuntimeError):
|
||||
@@ -75,6 +83,18 @@ class _DAVDiscoveryResponse:
|
||||
supported_components: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _DAVDiscoveryDraft:
|
||||
display_name: str | None = None
|
||||
color: str | None = None
|
||||
ctag: str | None = None
|
||||
sync_token: str | None = None
|
||||
is_calendar: bool = False
|
||||
principal_hrefs: list[str] = field(default_factory=list)
|
||||
calendar_home_set_hrefs: list[str] = field(default_factory=list)
|
||||
supported_components: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class CalDAVClient:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -228,8 +248,23 @@ class CalDAVClient:
|
||||
return parse_multistatus(payload)
|
||||
|
||||
def fetch_object(self, href: str) -> str:
|
||||
payload = self.request("GET", self.object_url(href), body=None, depth=None, expected={200})
|
||||
return payload.decode("utf-8")
|
||||
return self.fetch_object_state(href).calendar_data or ""
|
||||
|
||||
def fetch_object_state(self, href: str) -> CalDAVObject:
|
||||
"""Fetch a resource together with its ETag for outbox reconciliation."""
|
||||
|
||||
_status, headers, payload = self.request_raw(
|
||||
"GET",
|
||||
self.object_url(href),
|
||||
body=None,
|
||||
depth=None,
|
||||
expected={200},
|
||||
)
|
||||
return CalDAVObject(
|
||||
href=href,
|
||||
etag=response_etag(headers),
|
||||
calendar_data=payload.decode("utf-8"),
|
||||
)
|
||||
|
||||
def put_object(self, href: str, ics: str, *, etag: str | None = None, create: bool = False, overwrite: bool = False) -> CalDAVWriteResult:
|
||||
headers = {"Content-Type": "text/calendar; charset=utf-8"}
|
||||
@@ -266,7 +301,21 @@ class CalDAVClient:
|
||||
return CalDAVWriteResult(href=href, etag=response_etag(response_headers), status=status)
|
||||
|
||||
def object_url(self, href: str) -> str:
|
||||
return urllib.parse.urljoin(self.collection_url, href)
|
||||
candidate = same_origin_dav_url(
|
||||
self.collection_url,
|
||||
href,
|
||||
label="CalDAV object href",
|
||||
)
|
||||
collection_parts = urllib.parse.urlparse(self.collection_url)
|
||||
candidate_parts = urllib.parse.urlparse(candidate)
|
||||
collection_path = posixpath.normpath(urllib.parse.unquote(collection_parts.path))
|
||||
candidate_path = posixpath.normpath(urllib.parse.unquote(candidate_parts.path))
|
||||
collection_prefix = collection_path.rstrip("/") + "/"
|
||||
if not candidate_path.startswith(collection_prefix) or candidate_path == collection_path:
|
||||
raise CalDAVError("CalDAV object href must remain inside the configured collection path")
|
||||
if candidate_parts.query or candidate_parts.fragment:
|
||||
raise CalDAVError("CalDAV object href must not contain a query or fragment")
|
||||
return urllib.parse.urlunparse(candidate_parts)
|
||||
|
||||
def request(self, method: str, url: str, *, body: bytes | None, depth: str | None, expected: set[int]) -> bytes:
|
||||
_status, _headers, payload = self.request_raw(method, url, body=body, depth=depth, expected=expected)
|
||||
@@ -308,22 +357,40 @@ class CalDAVClient:
|
||||
|
||||
|
||||
def urllib_transport(method: str, url: str, headers: Mapping[str, str], body: bytes | None, timeout: int) -> tuple[int, Mapping[str, str], bytes]:
|
||||
url = validate_http_url(url)
|
||||
try:
|
||||
request = urllib.request.Request(url, data=body, headers=dict(headers), method=method)
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return response.status, dict(response.headers.items()), response.read()
|
||||
url = validate_outbound_http_url(url, label="CalDAV URL")
|
||||
request = urllib.request.Request( # noqa: S310 - URL is validated and origin-confined.
|
||||
url,
|
||||
data=body,
|
||||
headers=dict(headers),
|
||||
method=method,
|
||||
)
|
||||
opener = build_outbound_http_opener(_SameOriginRedirectHandler(url))
|
||||
with opener.open(request, timeout=timeout) as response: # noqa: S310 - validated CalDAV URL; redirects remain on origin. # nosec B310 # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected
|
||||
response_headers = dict(response.headers.items())
|
||||
return response.status, response_headers, bounded_response_bytes(
|
||||
response,
|
||||
headers=response_headers,
|
||||
label="CalDAV response",
|
||||
)
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, dict(exc.headers.items()), exc.read()
|
||||
response_headers = dict(exc.headers.items())
|
||||
try:
|
||||
payload = bounded_response_bytes(exc, headers=response_headers, label="CalDAV error response")
|
||||
except OutboundHttpError as policy_exc:
|
||||
raise CalDAVError(f"{method} {url} failed: {policy_exc}") from policy_exc
|
||||
return exc.code, response_headers, payload
|
||||
except urllib.error.URLError as exc:
|
||||
raise CalDAVError(f"{method} {url} failed: {exc.reason}") from exc
|
||||
except ValueError as exc:
|
||||
except (OutboundHttpError, ValueError) as exc:
|
||||
raise CalDAVError(f"{method} {url} failed: {exc}") from exc
|
||||
|
||||
|
||||
def parse_multistatus(payload: bytes) -> CalDAVReportResult:
|
||||
try:
|
||||
root = ElementTree.fromstring(payload)
|
||||
except ElementTree.ParseError as exc:
|
||||
root = SafeElementTree.fromstring(payload)
|
||||
except SafeElementTree.ParseError as exc:
|
||||
raise CalDAVError(f"Invalid CalDAV XML response: {exc}") from exc
|
||||
objects: list[CalDAVObject] = []
|
||||
sync_token = first_child_text(root, "sync-token")
|
||||
@@ -355,76 +422,167 @@ def parse_multistatus(payload: bytes) -> CalDAVReportResult:
|
||||
|
||||
def parse_discovery_multistatus(payload: bytes) -> list[_DAVDiscoveryResponse]:
|
||||
try:
|
||||
root = ElementTree.fromstring(payload)
|
||||
except ElementTree.ParseError as exc:
|
||||
root = SafeElementTree.fromstring(payload)
|
||||
except SafeElementTree.ParseError as exc:
|
||||
raise CalDAVError(f"Invalid CalDAV XML response: {exc}") from exc
|
||||
responses: list[_DAVDiscoveryResponse] = []
|
||||
for response in child_elements(root, "response"):
|
||||
href = first_child_text(response, "href")
|
||||
if not href:
|
||||
return [
|
||||
parsed
|
||||
for response in child_elements(root, "response")
|
||||
if (parsed := _parse_discovery_response(response)) is not None
|
||||
]
|
||||
|
||||
|
||||
def _parse_discovery_response(response: Any) -> _DAVDiscoveryResponse | None:
|
||||
href = first_child_text(response, "href")
|
||||
if not href:
|
||||
return None
|
||||
draft = _DAVDiscoveryDraft()
|
||||
for propstat in child_elements(response, "propstat"):
|
||||
_apply_discovery_propstat(draft, propstat)
|
||||
return _DAVDiscoveryResponse(
|
||||
href=href,
|
||||
display_name=draft.display_name,
|
||||
color=draft.color,
|
||||
ctag=draft.ctag,
|
||||
sync_token=draft.sync_token,
|
||||
is_calendar=draft.is_calendar,
|
||||
principal_hrefs=dedupe_tuple(draft.principal_hrefs),
|
||||
calendar_home_set_hrefs=dedupe_tuple(draft.calendar_home_set_hrefs),
|
||||
supported_components=dedupe_tuple(draft.supported_components),
|
||||
)
|
||||
|
||||
|
||||
def _apply_discovery_propstat(draft: _DAVDiscoveryDraft, propstat: Any) -> None:
|
||||
if not discovery_propstat_is_success(propstat):
|
||||
return
|
||||
prop = first_child(propstat, "prop")
|
||||
if prop is None:
|
||||
return
|
||||
for item in prop:
|
||||
_apply_discovery_property(draft, item)
|
||||
|
||||
|
||||
def discovery_propstat_is_success(propstat: Any) -> bool:
|
||||
status = first_child_text(propstat, "status") or ""
|
||||
return not status or " 200 " in status or status.endswith(" 200") or " 207 " in status
|
||||
|
||||
|
||||
def _apply_discovery_property(draft: _DAVDiscoveryDraft, item: Any) -> None:
|
||||
name = local_name(item.tag)
|
||||
text = item.text.strip() if item.text else ""
|
||||
if name == "displayname" and text:
|
||||
draft.display_name = text or draft.display_name
|
||||
elif name == "calendar-color" and text:
|
||||
draft.color = text or draft.color
|
||||
elif name == "getctag" and text:
|
||||
draft.ctag = text or draft.ctag
|
||||
elif name == "sync-token" and text:
|
||||
draft.sync_token = text or draft.sync_token
|
||||
elif name == "resourcetype":
|
||||
draft.is_calendar = draft.is_calendar or discovery_resource_is_calendar(item)
|
||||
elif name in {"current-user-principal", "principal-URL"}:
|
||||
draft.principal_hrefs.extend(nested_href_texts(item))
|
||||
elif name == "calendar-home-set":
|
||||
draft.calendar_home_set_hrefs.extend(nested_href_texts(item))
|
||||
elif name == "supported-calendar-component-set":
|
||||
draft.supported_components.extend(supported_calendar_component_names(item))
|
||||
|
||||
|
||||
def discovery_resource_is_calendar(item: Any) -> bool:
|
||||
return any(local_name(child.tag) == "calendar" for child in item)
|
||||
|
||||
|
||||
def supported_calendar_component_names(item: Any) -> list[str]:
|
||||
names: list[str] = []
|
||||
for component in item:
|
||||
if local_name(component.tag) != "comp":
|
||||
continue
|
||||
display_name = None
|
||||
color = None
|
||||
ctag = None
|
||||
sync_token = None
|
||||
is_calendar = False
|
||||
principal_hrefs: list[str] = []
|
||||
calendar_home_set_hrefs: list[str] = []
|
||||
supported_components: list[str] = []
|
||||
for propstat in child_elements(response, "propstat"):
|
||||
status = first_child_text(propstat, "status") or ""
|
||||
if status and " 200 " not in status and not status.endswith(" 200") and " 207 " not in status:
|
||||
continue
|
||||
prop = first_child(propstat, "prop")
|
||||
if prop is None:
|
||||
continue
|
||||
for item in prop:
|
||||
name = local_name(item.tag)
|
||||
if name == "displayname" and item.text:
|
||||
display_name = item.text.strip() or display_name
|
||||
elif name == "calendar-color" and item.text:
|
||||
color = item.text.strip() or color
|
||||
elif name == "getctag" and item.text:
|
||||
ctag = item.text.strip() or ctag
|
||||
elif name == "sync-token" and item.text:
|
||||
sync_token = item.text.strip() or sync_token
|
||||
elif name == "resourcetype":
|
||||
is_calendar = is_calendar or any(local_name(child.tag) == "calendar" for child in item)
|
||||
elif name in {"current-user-principal", "principal-URL"}:
|
||||
principal_hrefs.extend(nested_href_texts(item))
|
||||
elif name == "calendar-home-set":
|
||||
calendar_home_set_hrefs.extend(nested_href_texts(item))
|
||||
elif name == "supported-calendar-component-set":
|
||||
for component in item:
|
||||
if local_name(component.tag) == "comp":
|
||||
component_name = (component.attrib.get("name") or "").strip().upper()
|
||||
if component_name:
|
||||
supported_components.append(component_name)
|
||||
responses.append(
|
||||
_DAVDiscoveryResponse(
|
||||
href=href,
|
||||
display_name=display_name,
|
||||
color=color,
|
||||
ctag=ctag,
|
||||
sync_token=sync_token,
|
||||
is_calendar=is_calendar,
|
||||
principal_hrefs=tuple(dict.fromkeys(principal_hrefs)),
|
||||
calendar_home_set_hrefs=tuple(dict.fromkeys(calendar_home_set_hrefs)),
|
||||
supported_components=tuple(dict.fromkeys(supported_components)),
|
||||
)
|
||||
)
|
||||
return responses
|
||||
component_name = (component.attrib.get("name") or "").strip().upper()
|
||||
if component_name:
|
||||
names.append(component_name)
|
||||
return names
|
||||
|
||||
|
||||
def dedupe_tuple(values: list[str]) -> tuple[str, ...]:
|
||||
return tuple(dict.fromkeys(values))
|
||||
|
||||
|
||||
def ensure_collection_url(value: str) -> str:
|
||||
value = value.strip()
|
||||
if value and "://" not in value and not value.startswith("/"):
|
||||
value = f"https://{value}"
|
||||
return value if value.endswith("/") else f"{value}/"
|
||||
url = validate_http_url(value)
|
||||
return url if url.endswith("/") else f"{url}/"
|
||||
|
||||
|
||||
def validate_http_url(value: str) -> str:
|
||||
parsed = urllib.parse.urlparse(value.strip())
|
||||
if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc or not parsed.hostname:
|
||||
raise CalDAVError("CalDAV URL must be an absolute HTTP(S) URL")
|
||||
if parsed.username or parsed.password:
|
||||
raise CalDAVError("CalDAV URL must not include embedded credentials")
|
||||
if parsed.query or parsed.fragment:
|
||||
raise CalDAVError("CalDAV URL must not include a query or fragment")
|
||||
_url_origin(parsed)
|
||||
return urllib.parse.urlunparse(parsed)
|
||||
|
||||
|
||||
def absolute_dav_url(base_url: str, href: str) -> str:
|
||||
return urllib.parse.urljoin(ensure_collection_url(base_url), href)
|
||||
return same_origin_dav_url(base_url, href, label="CalDAV discovery href")
|
||||
|
||||
|
||||
def same_origin_dav_url(base_url: str, href: str, *, label: str) -> str:
|
||||
base = ensure_collection_url(base_url)
|
||||
candidate = validate_http_url(urllib.parse.urljoin(base, href))
|
||||
if _url_origin(urllib.parse.urlparse(candidate)) != _url_origin(urllib.parse.urlparse(base)):
|
||||
raise CalDAVError(f"{label} must use the configured collection origin")
|
||||
return candidate
|
||||
|
||||
|
||||
def _url_origin(parsed: urllib.parse.ParseResult) -> tuple[str, str, int]:
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError as exc:
|
||||
raise CalDAVError("CalDAV URL has an invalid port") from exc
|
||||
scheme = parsed.scheme.lower()
|
||||
if port is None:
|
||||
port = 443 if scheme == "https" else 80
|
||||
return scheme, (parsed.hostname or "").lower(), port
|
||||
|
||||
|
||||
class _SameOriginRedirectHandler(urllib.request.HTTPRedirectHandler):
|
||||
def __init__(self, source_url: str) -> None:
|
||||
super().__init__()
|
||||
self._source_origin = _url_origin(urllib.parse.urlparse(validate_http_url(source_url)))
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
|
||||
del fp, msg, headers
|
||||
try:
|
||||
candidate = validate_http_url(newurl)
|
||||
candidate = validate_outbound_http_url(candidate, label="CalDAV redirect URL")
|
||||
except (CalDAVError, OutboundHttpError):
|
||||
return None
|
||||
if _url_origin(urllib.parse.urlparse(candidate)) != self._source_origin:
|
||||
return None
|
||||
method = req.get_method()
|
||||
data = req.data
|
||||
if code == 303 and method != "HEAD":
|
||||
method, data = "GET", None
|
||||
elif code in {301, 302} and method == "POST":
|
||||
method, data = "GET", None
|
||||
forwarded_headers = {
|
||||
key: value
|
||||
for key, value in req.header_items()
|
||||
if key.casefold() not in {"host", "content-length"}
|
||||
}
|
||||
return urllib.request.Request( # noqa: S310 - candidate is validated and same-origin.
|
||||
candidate,
|
||||
data=data,
|
||||
headers=forwarded_headers,
|
||||
origin_req_host=req.origin_req_host,
|
||||
unverifiable=True,
|
||||
method=method,
|
||||
)
|
||||
|
||||
|
||||
def strip_weak_etag(value: str | None) -> str | None:
|
||||
@@ -444,25 +602,25 @@ def xml_escape(value: str) -> str:
|
||||
return value.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
|
||||
|
||||
def first_child(element: ElementTree.Element, name: str) -> ElementTree.Element | None:
|
||||
def first_child(element: Any, name: str) -> Any | None:
|
||||
for child in element:
|
||||
if local_name(child.tag) == name:
|
||||
return child
|
||||
return None
|
||||
|
||||
|
||||
def first_child_text(element: ElementTree.Element, name: str) -> str | None:
|
||||
def first_child_text(element: Any, name: str) -> str | None:
|
||||
found = first_child(element, name)
|
||||
if found is None or found.text is None:
|
||||
return None
|
||||
return found.text.strip()
|
||||
|
||||
|
||||
def child_elements(element: ElementTree.Element, name: str) -> list[ElementTree.Element]:
|
||||
def child_elements(element: Any, name: str) -> list[Any]:
|
||||
return [child for child in element if local_name(child.tag) == name]
|
||||
|
||||
|
||||
def nested_href_texts(element: ElementTree.Element) -> list[str]:
|
||||
def nested_href_texts(element: Any) -> list[str]:
|
||||
hrefs: list[str] = []
|
||||
for child in element.iter():
|
||||
if local_name(child.tag) == "href" and child.text and child.text.strip():
|
||||
|
||||
82
src/govoplan_calendar/backend/capabilities.py
Normal file
82
src/govoplan_calendar/backend/capabilities.py
Normal file
@@ -0,0 +1,82 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import datetime
|
||||
|
||||
from govoplan_core.core.calendar import (
|
||||
CalendarCapabilityError,
|
||||
CalendarEventRef,
|
||||
CalendarEventRequest,
|
||||
CalendarSchedulingProvider,
|
||||
)
|
||||
from govoplan_calendar.backend.schemas import CalendarEventCreateRequest
|
||||
from govoplan_calendar.backend.service import CalendarError, create_event, list_freebusy
|
||||
|
||||
|
||||
class SqlCalendarSchedulingProvider(CalendarSchedulingProvider):
|
||||
def list_freebusy(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
tenant_id: str,
|
||||
start_at: datetime,
|
||||
end_at: datetime,
|
||||
calendar_ids: Sequence[str] | None = None,
|
||||
) -> tuple[Mapping[str, object], ...]:
|
||||
try:
|
||||
blocks = list_freebusy(
|
||||
session,
|
||||
tenant_id=tenant_id,
|
||||
start_at=start_at,
|
||||
end_at=end_at,
|
||||
calendar_ids=list(calendar_ids) if calendar_ids is not None else None,
|
||||
)
|
||||
except CalendarError as exc:
|
||||
raise CalendarCapabilityError(str(exc)) from exc
|
||||
return tuple(blocks)
|
||||
|
||||
def create_event(
|
||||
self,
|
||||
session: object,
|
||||
*,
|
||||
tenant_id: str,
|
||||
user_id: str | None,
|
||||
request: CalendarEventRequest,
|
||||
) -> CalendarEventRef:
|
||||
try:
|
||||
payload = CalendarEventCreateRequest(
|
||||
calendar_id=request.calendar_id,
|
||||
summary=request.summary,
|
||||
description=request.description,
|
||||
location=request.location,
|
||||
status=request.status,
|
||||
transparency=request.transparency,
|
||||
classification=request.classification,
|
||||
start_at=request.start_at,
|
||||
end_at=request.end_at,
|
||||
timezone=request.timezone,
|
||||
attendees=[dict(item) for item in request.attendees],
|
||||
categories=list(request.categories),
|
||||
related_to=[dict(item) for item in request.related_to],
|
||||
metadata=dict(request.metadata),
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise CalendarCapabilityError(str(exc)) from exc
|
||||
try:
|
||||
event = create_event(session, tenant_id=tenant_id, user_id=user_id, payload=payload)
|
||||
except CalendarError as exc:
|
||||
raise CalendarCapabilityError(str(exc)) from exc
|
||||
caldav_metadata = (event.metadata_ or {}).get("caldav")
|
||||
external_state = "local"
|
||||
outbox_operation_id = None
|
||||
if isinstance(caldav_metadata, dict):
|
||||
external_state = str(caldav_metadata.get("external_state") or "queued")
|
||||
raw_operation_id = caldav_metadata.get("outbox_operation_id")
|
||||
outbox_operation_id = str(raw_operation_id) if raw_operation_id else None
|
||||
return CalendarEventRef(
|
||||
id=event.id,
|
||||
calendar_id=event.calendar_id,
|
||||
uid=event.uid,
|
||||
external_state=external_state,
|
||||
outbox_operation_id=outbox_operation_id,
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
@@ -151,4 +151,69 @@ class CalendarSyncCredential(Base, TimestampMixin):
|
||||
metadata_: Mapped[dict[str, Any] | None] = mapped_column("metadata", JSON, nullable=True)
|
||||
|
||||
|
||||
__all__ = ["CalendarCollection", "CalendarEvent", "CalendarSyncCredential", "CalendarSyncSource", "new_uuid"]
|
||||
class CalendarOutboxOperation(Base, TimestampMixin):
|
||||
"""Durable desired state for one external CalDAV resource.
|
||||
|
||||
Rows are inserted in the same transaction as the local event mutation. A
|
||||
dispatcher leases and commits the row before performing network I/O, so a
|
||||
worker crash can be detected and reconciled without repeating a blind
|
||||
write.
|
||||
"""
|
||||
|
||||
__tablename__ = "calendar_outbox_operations"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("idempotency_key", name="uq_calendar_outbox_operations_idempotency_key"),
|
||||
Index("ix_calendar_outbox_due", "status", "available_at", "created_at"),
|
||||
Index("ix_calendar_outbox_tenant_status", "tenant_id", "status"),
|
||||
Index("ix_calendar_outbox_resource", "source_id", "resource_href", "created_at"),
|
||||
Index("ix_calendar_outbox_lease", "status", "lease_expires_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=new_uuid)
|
||||
tenant_id: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
|
||||
source_id: Mapped[str] = mapped_column(
|
||||
ForeignKey("calendar_sync_sources.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
event_id: Mapped[str | None] = mapped_column(
|
||||
ForeignKey("calendar_events.id", ondelete="SET NULL"),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
operation_kind: Mapped[str] = mapped_column(String(20), nullable=False, index=True)
|
||||
resource_href: Mapped[str] = mapped_column(String(1000), nullable=False)
|
||||
payload_ics: Mapped[str | None] = mapped_column(Text)
|
||||
payload_fingerprint: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
expected_etag: Mapped[str | None] = mapped_column(String(255))
|
||||
idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(30), default="pending", nullable=False, index=True)
|
||||
attempt_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
max_attempts: Mapped[int] = mapped_column(Integer, default=8, nullable=False)
|
||||
available_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
default=lambda: datetime.now(timezone.utc),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
last_attempt_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
lease_token: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
|
||||
lease_expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
|
||||
completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
reconciled_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
remote_etag: Mapped[str | None] = mapped_column(String(255))
|
||||
last_error: Mapped[str | None] = mapped_column(Text)
|
||||
metadata_: Mapped[dict[str, Any] | None] = mapped_column("metadata", JSON, nullable=True)
|
||||
|
||||
source: Mapped[CalendarSyncSource] = relationship()
|
||||
event: Mapped[CalendarEvent | None] = relationship()
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CalendarCollection",
|
||||
"CalendarEvent",
|
||||
"CalendarOutboxOperation",
|
||||
"CalendarSyncCredential",
|
||||
"CalendarSyncSource",
|
||||
"new_uuid",
|
||||
]
|
||||
|
||||
@@ -153,6 +153,18 @@ def events_to_ics(events: list[Any]) -> str:
|
||||
|
||||
def event_to_component(event: Any) -> Event:
|
||||
component = Event()
|
||||
add_event_identity_and_time(component, event)
|
||||
add_event_status_fields(component, event)
|
||||
add_event_optional_text_fields(component, event)
|
||||
add_event_recurrence_and_parties(component, event)
|
||||
add_event_raw_records(component, event)
|
||||
add_preserved_properties(component, getattr(event, "icalendar", None) or {})
|
||||
for alarm in alarms_for_export(event):
|
||||
component.add_component(alarm)
|
||||
return component
|
||||
|
||||
|
||||
def add_event_identity_and_time(component: Event, event: Any) -> None:
|
||||
component.add("uid", event.uid)
|
||||
component.add("dtstamp", datetime.now(timezone.utc))
|
||||
component.add("dtstart", event_temporal_value(event.start_at, all_day=event.all_day, timezone_id=event.timezone))
|
||||
@@ -164,23 +176,35 @@ def event_to_component(event: Any) -> Event:
|
||||
component.add("duration", timedelta(seconds=int(event.duration_seconds)))
|
||||
if getattr(event, "recurrence_id", None):
|
||||
add_recurrence_id(component, str(event.recurrence_id))
|
||||
|
||||
|
||||
def add_event_status_fields(component: Event, event: Any) -> None:
|
||||
component.add("summary", event.summary)
|
||||
component.add("sequence", int(event.sequence or 0))
|
||||
component.add("status", event.status)
|
||||
component.add("transp", event.transparency)
|
||||
component.add("class", event.classification)
|
||||
|
||||
|
||||
def add_event_optional_text_fields(component: Event, event: Any) -> None:
|
||||
if event.description:
|
||||
component.add("description", event.description)
|
||||
if event.location:
|
||||
component.add("location", event.location)
|
||||
if event.categories:
|
||||
component.add("categories", list(event.categories))
|
||||
|
||||
|
||||
def add_event_recurrence_and_parties(component: Event, event: Any) -> None:
|
||||
if event.rrule:
|
||||
component.add("rrule", normalized_rrule_for_export(event.rrule))
|
||||
if event.organizer:
|
||||
component.add("organizer", party_for_export(event.organizer))
|
||||
for attendee in event.attendees or []:
|
||||
component.add("attendee", party_for_export(attendee))
|
||||
|
||||
|
||||
def add_event_raw_records(component: Event, event: Any) -> None:
|
||||
for record in getattr(event, "rdate", None) or []:
|
||||
add_raw_property(component, "RDATE", record)
|
||||
for record in getattr(event, "exdate", None) or []:
|
||||
@@ -190,11 +214,6 @@ def event_to_component(event: Any) -> Event:
|
||||
for record in getattr(event, "related_to", None) or []:
|
||||
add_raw_property(component, "RELATED-TO", record)
|
||||
|
||||
add_preserved_properties(component, getattr(event, "icalendar", None) or {})
|
||||
for alarm in alarms_for_export(event):
|
||||
component.add_component(alarm)
|
||||
return component
|
||||
|
||||
|
||||
def expand_event_occurrences(event: Any, range_start: datetime, range_end: datetime, *, limit: int = 1000) -> list[dict[str, Any]]:
|
||||
"""Expand an event's recurrence primitives within a range.
|
||||
|
||||
@@ -1,14 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import inspect
|
||||
|
||||
from govoplan_calendar.backend.db import models as calendar_models # noqa: F401 - populate Calendar ORM metadata
|
||||
from govoplan_core.core.access import CAPABILITY_AUTH_PERMISSION_EVALUATOR, CAPABILITY_AUTH_PRINCIPAL_RESOLVER
|
||||
from govoplan_core.core.calendar import (
|
||||
CALENDAR_AVAILABILITY_READ_SCOPE,
|
||||
CALENDAR_EVENT_WRITE_SCOPE,
|
||||
CAPABILITY_CALENDAR_OUTBOX,
|
||||
CAPABILITY_CALENDAR_SCHEDULING,
|
||||
)
|
||||
from govoplan_core.core.module_guards import drop_table_retirement_provider, persistent_table_uninstall_guard
|
||||
from govoplan_core.core.modules import FrontendModule, MigrationSpec, ModuleContext, ModuleManifest, NavItem, PermissionDefinition, RoleTemplate
|
||||
from govoplan_core.core.modules import (
|
||||
FrontendModule,
|
||||
FrontendRoute,
|
||||
MigrationSpec,
|
||||
ModuleContext,
|
||||
ModuleInterfaceProvider,
|
||||
ModuleManifest,
|
||||
NavItem,
|
||||
PermissionDefinition,
|
||||
RoleTemplate,
|
||||
)
|
||||
from govoplan_core.core.views import ViewSurface
|
||||
from govoplan_core.db.base import Base
|
||||
|
||||
|
||||
_calendar_table_retirement_provider = drop_table_retirement_provider(
|
||||
calendar_models.CalendarCollection,
|
||||
calendar_models.CalendarEvent,
|
||||
calendar_models.CalendarOutboxOperation,
|
||||
calendar_models.CalendarSyncCredential,
|
||||
calendar_models.CalendarSyncSource,
|
||||
label="Calendar",
|
||||
)
|
||||
|
||||
|
||||
def _calendar_retirement_provider(session: object | None, module_id: str):
|
||||
plan = _calendar_table_retirement_provider(session, module_id)
|
||||
base_executor = plan.destroy_data_executor
|
||||
if base_executor is None:
|
||||
return plan
|
||||
|
||||
def executor(execute_session: object, execute_module_id: str) -> None:
|
||||
if not hasattr(execute_session, "get_bind") or not hasattr(execute_session, "query"):
|
||||
raise RuntimeError("No database session is available for Calendar credential retirement.")
|
||||
if inspect(execute_session.get_bind()).has_table(calendar_models.CalendarSyncCredential.__tablename__):
|
||||
from govoplan_calendar.backend.service import delete_calendar_credentials_for_retirement
|
||||
|
||||
delete_calendar_credentials_for_retirement(execute_session)
|
||||
base_executor(execute_session, execute_module_id)
|
||||
|
||||
return replace(
|
||||
plan,
|
||||
destroy_data_warnings=(
|
||||
*plan.destroy_data_warnings,
|
||||
"Calendar-owned credentials are deleted immediately before tables are dropped; retirement fails if an external secret provider is unavailable.",
|
||||
),
|
||||
destroy_data_executor=executor,
|
||||
)
|
||||
|
||||
|
||||
def _permission(scope: str, label: str, description: str) -> PermissionDefinition:
|
||||
module_id, resource, action = scope.split(":", 2)
|
||||
return PermissionDefinition(
|
||||
@@ -28,11 +83,11 @@ PERMISSIONS = (
|
||||
_permission("calendar:calendar:write", "Manage calendars", "Create and edit tenant calendar collections."),
|
||||
_permission("calendar:calendar:admin", "Administer calendars", "Delete calendars and manage tenant-level calendar settings."),
|
||||
_permission("calendar:event:read", "View calendar events", "List and inspect calendar events."),
|
||||
_permission("calendar:event:write", "Manage calendar events", "Create and edit calendar events."),
|
||||
_permission(CALENDAR_EVENT_WRITE_SCOPE, "Manage calendar events", "Create and edit calendar events."),
|
||||
_permission("calendar:event:delete", "Delete calendar events", "Delete or cancel calendar events where policy allows it."),
|
||||
_permission("calendar:event:import", "Import iCalendar events", "Import VEVENT data from iCalendar sources."),
|
||||
_permission("calendar:event:export", "Export iCalendar events", "Export events as text/calendar VEVENT data."),
|
||||
_permission("calendar:availability:read", "Read availability", "Read free/busy and availability data for integrations."),
|
||||
_permission(CALENDAR_AVAILABILITY_READ_SCOPE, "Read availability", "Read free/busy and availability data for integrations."),
|
||||
)
|
||||
|
||||
ROLE_TEMPLATES = (
|
||||
@@ -44,11 +99,11 @@ ROLE_TEMPLATES = (
|
||||
"calendar:calendar:read",
|
||||
"calendar:calendar:write",
|
||||
"calendar:event:read",
|
||||
"calendar:event:write",
|
||||
CALENDAR_EVENT_WRITE_SCOPE,
|
||||
"calendar:event:delete",
|
||||
"calendar:event:import",
|
||||
"calendar:event:export",
|
||||
"calendar:availability:read",
|
||||
CALENDAR_AVAILABILITY_READ_SCOPE,
|
||||
),
|
||||
),
|
||||
RoleTemplate(
|
||||
@@ -59,20 +114,32 @@ ROLE_TEMPLATES = (
|
||||
"calendar:calendar:read",
|
||||
"calendar:event:read",
|
||||
"calendar:event:export",
|
||||
"calendar:availability:read",
|
||||
CALENDAR_AVAILABILITY_READ_SCOPE,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _tenant_summary(session, tenant_id: str) -> dict[str, int]:
|
||||
from govoplan_calendar.backend.db.models import CalendarCollection, CalendarEvent, CalendarSyncCredential, CalendarSyncSource
|
||||
from govoplan_calendar.backend.db.models import (
|
||||
CalendarCollection,
|
||||
CalendarEvent,
|
||||
CalendarOutboxOperation,
|
||||
CalendarSyncCredential,
|
||||
CalendarSyncSource,
|
||||
)
|
||||
|
||||
return {
|
||||
"calendars": session.query(CalendarCollection).filter(CalendarCollection.tenant_id == tenant_id, CalendarCollection.deleted_at.is_(None)).count(),
|
||||
"calendar_events": session.query(CalendarEvent).filter(CalendarEvent.tenant_id == tenant_id, CalendarEvent.deleted_at.is_(None)).count(),
|
||||
"calendar_sync_sources": session.query(CalendarSyncSource).filter(CalendarSyncSource.tenant_id == tenant_id, CalendarSyncSource.deleted_at.is_(None)).count(),
|
||||
"calendar_sync_credentials": session.query(CalendarSyncCredential).filter(CalendarSyncCredential.tenant_id == tenant_id, CalendarSyncCredential.deleted_at.is_(None)).count(),
|
||||
"calendar_outbox_pending": session.query(CalendarOutboxOperation)
|
||||
.filter(
|
||||
CalendarOutboxOperation.tenant_id == tenant_id,
|
||||
CalendarOutboxOperation.status.in_(("pending", "retry", "in_progress")),
|
||||
)
|
||||
.count(),
|
||||
}
|
||||
|
||||
|
||||
@@ -85,40 +152,82 @@ def _calendar_router(context: ModuleContext):
|
||||
return router
|
||||
|
||||
|
||||
def _calendar_scheduling_provider(context: ModuleContext) -> object:
|
||||
del context
|
||||
from govoplan_calendar.backend.capabilities import SqlCalendarSchedulingProvider
|
||||
|
||||
return SqlCalendarSchedulingProvider()
|
||||
|
||||
|
||||
def _calendar_outbox_provider(context: ModuleContext) -> object:
|
||||
from govoplan_calendar.backend.outbox import (
|
||||
OUTBOX_DEFAULT_TERMINAL_RETENTION_DAYS,
|
||||
SqlCalendarOutboxProvider,
|
||||
)
|
||||
|
||||
return SqlCalendarOutboxProvider(
|
||||
terminal_retention_days=getattr(
|
||||
context.settings,
|
||||
"calendar_outbox_terminal_retention_days",
|
||||
OUTBOX_DEFAULT_TERMINAL_RETENTION_DAYS,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
manifest = ModuleManifest(
|
||||
id="calendar",
|
||||
name="Calendar",
|
||||
version="0.1.7",
|
||||
version="0.1.8",
|
||||
required_capabilities=(CAPABILITY_AUTH_PRINCIPAL_RESOLVER, CAPABILITY_AUTH_PERMISSION_EVALUATOR),
|
||||
optional_dependencies=("mail", "tasks", "scheduling", "appointments", "workflow", "notifications", "dms", "connectors"),
|
||||
provides_interfaces=(
|
||||
ModuleInterfaceProvider(name="calendar.outbox", version="0.1.8"),
|
||||
ModuleInterfaceProvider(name="calendar.scheduling", version="0.1.8"),
|
||||
),
|
||||
permissions=PERMISSIONS,
|
||||
route_factory=_calendar_router,
|
||||
role_templates=ROLE_TEMPLATES,
|
||||
tenant_summary_providers=(_tenant_summary,),
|
||||
capability_factories={
|
||||
CAPABILITY_CALENDAR_OUTBOX: _calendar_outbox_provider,
|
||||
CAPABILITY_CALENDAR_SCHEDULING: _calendar_scheduling_provider,
|
||||
},
|
||||
nav_items=(NavItem(path="/calendar", label="Calendar", icon="calendar", required_any=("calendar:event:read",), order=55),),
|
||||
frontend=FrontendModule(
|
||||
module_id="calendar",
|
||||
package_name="@govoplan/calendar-webui",
|
||||
routes=(
|
||||
FrontendRoute(
|
||||
path="/calendar",
|
||||
component="CalendarPage",
|
||||
required_any=("calendar:event:read",),
|
||||
order=55,
|
||||
),
|
||||
),
|
||||
nav_items=(NavItem(path="/calendar", label="Calendar", icon="calendar", required_any=("calendar:event:read",), order=55),),
|
||||
view_surfaces=(
|
||||
ViewSurface(
|
||||
id="calendar.widget.upcoming",
|
||||
module_id="calendar",
|
||||
kind="section",
|
||||
label="Upcoming events widget",
|
||||
order=40,
|
||||
),
|
||||
),
|
||||
),
|
||||
migration_spec=MigrationSpec(
|
||||
module_id="calendar",
|
||||
metadata=Base.metadata,
|
||||
script_location=str(Path(__file__).with_name("migrations") / "versions"),
|
||||
retirement_supported=True,
|
||||
retirement_provider=drop_table_retirement_provider(
|
||||
calendar_models.CalendarCollection,
|
||||
calendar_models.CalendarEvent,
|
||||
calendar_models.CalendarSyncCredential,
|
||||
calendar_models.CalendarSyncSource,
|
||||
label="Calendar",
|
||||
),
|
||||
retirement_provider=_calendar_retirement_provider,
|
||||
retirement_notes="Destructive retirement drops calendar-owned database tables after the installer captures a database snapshot.",
|
||||
),
|
||||
uninstall_guard_providers=(
|
||||
persistent_table_uninstall_guard(
|
||||
calendar_models.CalendarCollection,
|
||||
calendar_models.CalendarEvent,
|
||||
calendar_models.CalendarOutboxOperation,
|
||||
calendar_models.CalendarSyncCredential,
|
||||
calendar_models.CalendarSyncSource,
|
||||
label="Calendar",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Calendar Alembic revisions."""
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Add the durable CalDAV desired-state outbox on the development track.
|
||||
|
||||
Revision ID: af1b2c3d4e5f
|
||||
Revises: 9e0f1a2b3c4d
|
||||
Create Date: 2026-07-20 00:00:00.000000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from govoplan_calendar.backend.migrations.versions.af1b2c3d4e5f_calendar_caldav_outbox import (
|
||||
downgrade as _downgrade,
|
||||
)
|
||||
from govoplan_calendar.backend.migrations.versions.af1b2c3d4e5f_calendar_caldav_outbox import (
|
||||
upgrade as _upgrade,
|
||||
)
|
||||
|
||||
|
||||
revision = "af1b2c3d4e5f"
|
||||
down_revision = "9e0f1a2b3c4d"
|
||||
branch_labels = None
|
||||
depends_on = "4f2a9c8e7b6d"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
_upgrade()
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
_downgrade()
|
||||
@@ -0,0 +1,174 @@
|
||||
"""v0.1.7 calendar baseline
|
||||
|
||||
Revision ID: 9e0f1a2b3c4d
|
||||
Revises: None
|
||||
Create Date: 2026-07-11 00:00:00.000000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '9e0f1a2b3c4d'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = '4f2a9c8e7b6d'
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('calendar_collections',
|
||||
sa.Column('id', sa.String(length=36), nullable=False),
|
||||
sa.Column('tenant_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('slug', sa.String(length=100), nullable=False),
|
||||
sa.Column('name', sa.String(length=255), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('timezone', sa.String(length=100), nullable=False),
|
||||
sa.Column('color', sa.String(length=20), nullable=True),
|
||||
sa.Column('owner_type', sa.String(length=20), nullable=False),
|
||||
sa.Column('owner_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('visibility', sa.String(length=20), nullable=False),
|
||||
sa.Column('is_default', sa.Boolean(), nullable=False),
|
||||
sa.Column('created_by_user_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('metadata', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['created_by_user_id'], ['access_users.id'], name=op.f('fk_calendar_collections_created_by_user_id_access_users'), ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['tenant_id'], ['core_scopes.id'], name=op.f('fk_calendar_collections_tenant_id_scopes'), ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_calendar_collections'))
|
||||
)
|
||||
op.create_index(op.f('ix_calendar_collections_created_by_user_id'), 'calendar_collections', ['created_by_user_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_collections_deleted_at'), 'calendar_collections', ['deleted_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_collections_is_default'), 'calendar_collections', ['is_default'], unique=False)
|
||||
op.create_index('ix_calendar_collections_owner', 'calendar_collections', ['tenant_id', 'owner_type', 'owner_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_collections_owner_id'), 'calendar_collections', ['owner_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_collections_owner_type'), 'calendar_collections', ['owner_type'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_collections_tenant_id'), 'calendar_collections', ['tenant_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_collections_visibility'), 'calendar_collections', ['visibility'], unique=False)
|
||||
op.create_index('uq_calendar_collections_active_slug', 'calendar_collections', ['tenant_id', 'slug'], unique=True, sqlite_where=sa.text('deleted_at IS NULL'), postgresql_where=sa.text('deleted_at IS NULL'))
|
||||
op.create_table('calendar_sync_credentials',
|
||||
sa.Column('id', sa.String(length=36), nullable=False),
|
||||
sa.Column('tenant_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('credential_kind', sa.String(length=30), nullable=False),
|
||||
sa.Column('label', sa.String(length=255), nullable=True),
|
||||
sa.Column('secret_encrypted', sa.Text(), nullable=True),
|
||||
sa.Column('created_by_user_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('metadata', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['created_by_user_id'], ['access_users.id'], name=op.f('fk_calendar_sync_credentials_created_by_user_id_access_users'), ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['tenant_id'], ['core_scopes.id'], name=op.f('fk_calendar_sync_credentials_tenant_id_scopes'), ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_calendar_sync_credentials'))
|
||||
)
|
||||
op.create_index(op.f('ix_calendar_sync_credentials_created_by_user_id'), 'calendar_sync_credentials', ['created_by_user_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_credentials_credential_kind'), 'calendar_sync_credentials', ['credential_kind'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_credentials_deleted_at'), 'calendar_sync_credentials', ['deleted_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_credentials_tenant_id'), 'calendar_sync_credentials', ['tenant_id'], unique=False)
|
||||
op.create_index('ix_calendar_sync_credentials_tenant_kind', 'calendar_sync_credentials', ['tenant_id', 'credential_kind'], unique=False)
|
||||
op.create_table('calendar_events',
|
||||
sa.Column('id', sa.String(length=36), nullable=False),
|
||||
sa.Column('tenant_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('calendar_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('uid', sa.String(length=255), nullable=False),
|
||||
sa.Column('recurrence_id', sa.String(length=255), nullable=True),
|
||||
sa.Column('sequence', sa.Integer(), nullable=False),
|
||||
sa.Column('summary', sa.String(length=500), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('location', sa.String(length=500), nullable=True),
|
||||
sa.Column('status', sa.String(length=40), nullable=False),
|
||||
sa.Column('transparency', sa.String(length=20), nullable=False),
|
||||
sa.Column('classification', sa.String(length=20), nullable=False),
|
||||
sa.Column('start_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('end_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('duration_seconds', sa.Integer(), nullable=True),
|
||||
sa.Column('all_day', sa.Boolean(), nullable=False),
|
||||
sa.Column('timezone', sa.String(length=100), nullable=True),
|
||||
sa.Column('organizer', sa.JSON(), nullable=True),
|
||||
sa.Column('attendees', sa.JSON(), nullable=False),
|
||||
sa.Column('categories', sa.JSON(), nullable=False),
|
||||
sa.Column('rrule', sa.JSON(), nullable=True),
|
||||
sa.Column('rdate', sa.JSON(), nullable=False),
|
||||
sa.Column('exdate', sa.JSON(), nullable=False),
|
||||
sa.Column('reminders', sa.JSON(), nullable=False),
|
||||
sa.Column('attachments', sa.JSON(), nullable=False),
|
||||
sa.Column('related_to', sa.JSON(), nullable=False),
|
||||
sa.Column('source_kind', sa.String(length=30), nullable=False),
|
||||
sa.Column('source_href', sa.String(length=1000), nullable=True),
|
||||
sa.Column('etag', sa.String(length=255), nullable=True),
|
||||
sa.Column('icalendar', sa.JSON(), nullable=False),
|
||||
sa.Column('raw_ics', sa.Text(), nullable=True),
|
||||
sa.Column('created_by_user_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('updated_by_user_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('metadata', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['calendar_id'], ['calendar_collections.id'], name=op.f('fk_calendar_events_calendar_id_calendar_collections'), ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['created_by_user_id'], ['access_users.id'], name=op.f('fk_calendar_events_created_by_user_id_access_users'), ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['tenant_id'], ['core_scopes.id'], name=op.f('fk_calendar_events_tenant_id_scopes'), ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['updated_by_user_id'], ['access_users.id'], name=op.f('fk_calendar_events_updated_by_user_id_access_users'), ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_calendar_events')),
|
||||
sa.UniqueConstraint('calendar_id', 'uid', 'recurrence_id', name='uq_calendar_events_calendar_uid_recurrence')
|
||||
)
|
||||
op.create_index(op.f('ix_calendar_events_all_day'), 'calendar_events', ['all_day'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_calendar_id'), 'calendar_events', ['calendar_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_created_by_user_id'), 'calendar_events', ['created_by_user_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_deleted_at'), 'calendar_events', ['deleted_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_end_at'), 'calendar_events', ['end_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_etag'), 'calendar_events', ['etag'], unique=False)
|
||||
op.create_index('ix_calendar_events_range', 'calendar_events', ['tenant_id', 'calendar_id', 'start_at', 'end_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_recurrence_id'), 'calendar_events', ['recurrence_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_source_kind'), 'calendar_events', ['source_kind'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_start_at'), 'calendar_events', ['start_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_status'), 'calendar_events', ['status'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_tenant_id'), 'calendar_events', ['tenant_id'], unique=False)
|
||||
op.create_index('ix_calendar_events_tenant_status', 'calendar_events', ['tenant_id', 'status'], unique=False)
|
||||
op.create_index('ix_calendar_events_tenant_uid', 'calendar_events', ['tenant_id', 'uid'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_uid'), 'calendar_events', ['uid'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_events_updated_by_user_id'), 'calendar_events', ['updated_by_user_id'], unique=False)
|
||||
op.create_table('calendar_sync_sources',
|
||||
sa.Column('id', sa.String(length=36), nullable=False),
|
||||
sa.Column('tenant_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('calendar_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('source_kind', sa.String(length=30), nullable=False),
|
||||
sa.Column('collection_url', sa.String(length=1000), nullable=False),
|
||||
sa.Column('display_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('auth_type', sa.String(length=30), nullable=False),
|
||||
sa.Column('username', sa.String(length=255), nullable=True),
|
||||
sa.Column('credential_ref', sa.String(length=255), nullable=True),
|
||||
sa.Column('sync_enabled', sa.Boolean(), nullable=False),
|
||||
sa.Column('sync_interval_seconds', sa.Integer(), nullable=False),
|
||||
sa.Column('sync_direction', sa.String(length=30), nullable=False),
|
||||
sa.Column('conflict_policy', sa.String(length=30), nullable=False),
|
||||
sa.Column('sync_token', sa.Text(), nullable=True),
|
||||
sa.Column('ctag', sa.String(length=255), nullable=True),
|
||||
sa.Column('last_attempt_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('last_synced_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('next_sync_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('last_status', sa.String(length=30), nullable=True),
|
||||
sa.Column('last_error', sa.Text(), nullable=True),
|
||||
sa.Column('deleted_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('metadata', sa.JSON(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['calendar_id'], ['calendar_collections.id'], name=op.f('fk_calendar_sync_sources_calendar_id_calendar_collections'), ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['tenant_id'], ['core_scopes.id'], name=op.f('fk_calendar_sync_sources_tenant_id_scopes'), ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_calendar_sync_sources'))
|
||||
)
|
||||
op.create_index('ix_calendar_sync_sources_calendar', 'calendar_sync_sources', ['tenant_id', 'calendar_id', 'source_kind'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_sources_calendar_id'), 'calendar_sync_sources', ['calendar_id'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_sources_deleted_at'), 'calendar_sync_sources', ['deleted_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_sources_next_sync_at'), 'calendar_sync_sources', ['next_sync_at'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_sources_source_kind'), 'calendar_sync_sources', ['source_kind'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_sources_sync_enabled'), 'calendar_sync_sources', ['sync_enabled'], unique=False)
|
||||
op.create_index(op.f('ix_calendar_sync_sources_tenant_id'), 'calendar_sync_sources', ['tenant_id'], unique=False)
|
||||
op.create_index('uq_calendar_sync_sources_active_url', 'calendar_sync_sources', ['tenant_id', 'source_kind', 'collection_url'], unique=True, sqlite_where=sa.text('deleted_at IS NULL'), postgresql_where=sa.text('deleted_at IS NULL'))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table('calendar_sync_sources')
|
||||
op.drop_table('calendar_events')
|
||||
op.drop_table('calendar_sync_credentials')
|
||||
op.drop_table('calendar_collections')
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Add the durable CalDAV desired-state outbox.
|
||||
|
||||
Revision ID: af1b2c3d4e5f
|
||||
Revises: 9e0f1a2b3c4d
|
||||
Create Date: 2026-07-20 00:00:00.000000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "af1b2c3d4e5f"
|
||||
down_revision = "9e0f1a2b3c4d"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"calendar_outbox_operations",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("source_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("event_id", sa.String(length=36), nullable=True),
|
||||
sa.Column("operation_kind", sa.String(length=20), nullable=False),
|
||||
sa.Column("resource_href", sa.String(length=1000), nullable=False),
|
||||
sa.Column("payload_ics", sa.Text(), nullable=True),
|
||||
sa.Column("payload_fingerprint", sa.String(length=64), nullable=True),
|
||||
sa.Column("expected_etag", sa.String(length=255), nullable=True),
|
||||
sa.Column("idempotency_key", sa.String(length=64), nullable=False),
|
||||
sa.Column("status", sa.String(length=30), nullable=False),
|
||||
sa.Column("attempt_count", sa.Integer(), nullable=False),
|
||||
sa.Column("max_attempts", sa.Integer(), nullable=False),
|
||||
sa.Column("available_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("last_attempt_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("lease_token", sa.String(length=36), nullable=True),
|
||||
sa.Column("lease_expires_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("completed_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("reconciled_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("remote_etag", sa.String(length=255), nullable=True),
|
||||
sa.Column("last_error", sa.Text(), nullable=True),
|
||||
sa.Column("metadata", sa.JSON(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["event_id"],
|
||||
["calendar_events.id"],
|
||||
name=op.f("fk_calendar_outbox_operations_event_id_calendar_events"),
|
||||
ondelete="SET NULL",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["source_id"],
|
||||
["calendar_sync_sources.id"],
|
||||
name=op.f("fk_calendar_outbox_operations_source_id_calendar_sync_sources"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["tenant_id"],
|
||||
["core_scopes.id"],
|
||||
name=op.f("fk_calendar_outbox_operations_tenant_id_scopes"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_calendar_outbox_operations")),
|
||||
sa.UniqueConstraint(
|
||||
"idempotency_key",
|
||||
name="uq_calendar_outbox_operations_idempotency_key",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_calendar_outbox_due",
|
||||
"calendar_outbox_operations",
|
||||
["status", "available_at", "created_at"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_calendar_outbox_lease",
|
||||
"calendar_outbox_operations",
|
||||
["status", "lease_expires_at"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_calendar_outbox_resource",
|
||||
"calendar_outbox_operations",
|
||||
["source_id", "resource_href", "created_at"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
"ix_calendar_outbox_tenant_status",
|
||||
"calendar_outbox_operations",
|
||||
["tenant_id", "status"],
|
||||
unique=False,
|
||||
)
|
||||
for column in (
|
||||
"available_at",
|
||||
"event_id",
|
||||
"lease_expires_at",
|
||||
"lease_token",
|
||||
"operation_kind",
|
||||
"payload_fingerprint",
|
||||
"source_id",
|
||||
"status",
|
||||
"tenant_id",
|
||||
):
|
||||
op.create_index(
|
||||
op.f(f"ix_calendar_outbox_operations_{column}"),
|
||||
"calendar_outbox_operations",
|
||||
[column],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("calendar_outbox_operations")
|
||||
1641
src/govoplan_calendar/backend/outbox.py
Normal file
1641
src/govoplan_calendar/backend/outbox.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,7 @@ from sqlalchemy.orm import Session
|
||||
|
||||
from govoplan_core.auth import ApiPrincipal, get_api_principal, has_scope
|
||||
from govoplan_core.api.v1.schemas import DeltaDeletedItem
|
||||
from govoplan_core.core.calendar import CALENDAR_AVAILABILITY_READ_SCOPE, CALENDAR_EVENT_WRITE_SCOPE
|
||||
from govoplan_core.core.change_sequence import decode_sequence_watermark, encode_sequence_watermark, max_sequence_id, sequence_entries_since, sequence_watermark_is_expired
|
||||
from govoplan_calendar.backend.db.models import CalendarEvent
|
||||
from govoplan_calendar.backend.ical import ICalendarError, event_to_ics, http_last_modified
|
||||
@@ -27,6 +28,8 @@ from govoplan_calendar.backend.schemas import (
|
||||
CalendarCollectionListResponse,
|
||||
CalendarCollectionResponse,
|
||||
CalendarCollectionUpdateRequest,
|
||||
CalendarCredentialEnvelopeListResponse,
|
||||
CalendarCredentialEnvelopeResponse,
|
||||
CalendarEventCreateRequest,
|
||||
CalendarEventDeltaResponse,
|
||||
CalendarEventListResponse,
|
||||
@@ -35,6 +38,9 @@ from govoplan_calendar.backend.schemas import (
|
||||
CalendarFreeBusyRequest,
|
||||
CalendarFreeBusyResponse,
|
||||
CalendarIcsImportRequest,
|
||||
CalendarOutboxDispatchResponse,
|
||||
CalendarOutboxOperationListResponse,
|
||||
CalendarOutboxOperationResponse,
|
||||
CalendarSyncDueSyncItemResponse,
|
||||
CalendarSyncDueSyncResponse,
|
||||
CalendarSyncSourceCreateRequest,
|
||||
@@ -44,11 +50,20 @@ from govoplan_calendar.backend.schemas import (
|
||||
CalendarSyncSourceSyncResponse,
|
||||
CalendarSyncSourceUpdateRequest,
|
||||
)
|
||||
from govoplan_calendar.backend.outbox import (
|
||||
calendar_outbox_operation_response,
|
||||
discard_calendar_outbox_operation,
|
||||
dispatch_calendar_outbox,
|
||||
list_calendar_outbox_operations,
|
||||
reconcile_calendar_outbox_operation,
|
||||
retry_calendar_outbox_operation,
|
||||
)
|
||||
from govoplan_calendar.backend.service import (
|
||||
CALENDAR_EVENTS_COLLECTION,
|
||||
CALENDAR_EVENT_RESOURCE,
|
||||
CALENDAR_MODULE_ID,
|
||||
CalendarError,
|
||||
available_calendar_credentials,
|
||||
caldav_source_response,
|
||||
caldav_sync_response,
|
||||
calendar_response,
|
||||
@@ -62,7 +77,6 @@ from govoplan_calendar.backend.service import (
|
||||
delete_event,
|
||||
discover_caldav_calendars,
|
||||
event_response,
|
||||
get_caldav_source,
|
||||
get_event,
|
||||
import_ics_event,
|
||||
list_freebusy,
|
||||
@@ -85,6 +99,15 @@ from govoplan_core.db.session import get_session
|
||||
router = APIRouter(prefix="/calendar", tags=["calendar"])
|
||||
|
||||
|
||||
def _caldav_discovery_http_error(
|
||||
exc: CalendarError | CalDAVError,
|
||||
) -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
|
||||
detail=str(exc),
|
||||
)
|
||||
|
||||
|
||||
def _require_scope(principal: ApiPrincipal, scope: str) -> None:
|
||||
if not has_scope(principal, scope):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Missing scope: {scope}")
|
||||
@@ -118,6 +141,25 @@ def _parse_payload_datetime(value) -> datetime | None:
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/credentials", response_model=CalendarCredentialEnvelopeListResponse)
|
||||
def api_list_calendar_credentials(
|
||||
source_id: str | None = None,
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
return CalendarCredentialEnvelopeListResponse(
|
||||
credentials=[
|
||||
CalendarCredentialEnvelopeResponse.model_validate(item)
|
||||
for item in available_calendar_credentials(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
source_id=source_id,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def _event_interval_overlaps(payload: dict, *, prefix: str, start_at: datetime | None, end_at: datetime | None) -> bool:
|
||||
event_start = _parse_payload_datetime(payload.get(f"{prefix}start_at"))
|
||||
event_end = _parse_payload_datetime(payload.get(f"{prefix}end_at")) or event_start
|
||||
@@ -220,13 +262,25 @@ def _sync_source_response(source) -> CalendarSyncSourceResponse:
|
||||
return CalendarSyncSourceResponse.model_validate(caldav_source_response(source))
|
||||
|
||||
|
||||
def _outbox_operation_response(operation) -> CalendarOutboxOperationResponse:
|
||||
return CalendarOutboxOperationResponse.model_validate(
|
||||
calendar_outbox_operation_response(operation)
|
||||
)
|
||||
|
||||
|
||||
@router.get("/calendars", response_model=CalendarCollectionListResponse)
|
||||
def api_list_calendars(
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:read")
|
||||
calendars = list_calendars(session, tenant_id=principal.tenant_id, user_id=principal.user.id)
|
||||
calendars = list_calendars(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
user_id=principal.user.id,
|
||||
group_ids=principal.group_ids,
|
||||
can_admin=principal.has("calendar:calendar:admin"),
|
||||
)
|
||||
session.commit()
|
||||
return CalendarCollectionListResponse(calendars=[_calendar_response(calendar) for calendar in calendars])
|
||||
|
||||
@@ -275,7 +329,14 @@ def api_delete_calendar(
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
delete_calendar(session, tenant_id=principal.tenant_id, calendar_id=calendar_id, payload=payload)
|
||||
delete_calendar(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
calendar_id=calendar_id,
|
||||
payload=payload,
|
||||
user_id=principal.user.id,
|
||||
api_key_id=principal.api_key_id,
|
||||
)
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
except CalendarError as exc:
|
||||
@@ -321,7 +382,14 @@ def api_update_sync_source(
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
source = update_sync_source(session, tenant_id=principal.tenant_id, source_id=source_id, payload=payload)
|
||||
source = update_sync_source(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
source_id=source_id,
|
||||
payload=payload,
|
||||
user_id=principal.user.id,
|
||||
api_key_id=principal.api_key_id,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(source)
|
||||
return _sync_source_response(source)
|
||||
@@ -338,12 +406,23 @@ def api_delete_sync_source(
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
delete_sync_source(session, tenant_id=principal.tenant_id, source_id=source_id)
|
||||
delete_sync_source(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
source_id=source_id,
|
||||
user_id=principal.user.id,
|
||||
api_key_id=principal.api_key_id,
|
||||
)
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
except CalendarError as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
||||
error_status = (
|
||||
status.HTTP_404_NOT_FOUND
|
||||
if "not found" in str(exc).lower()
|
||||
else status.HTTP_409_CONFLICT
|
||||
)
|
||||
raise HTTPException(status_code=error_status, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/sync-sources/{source_id}/sync", response_model=CalendarSyncSourceSyncResponse)
|
||||
@@ -422,7 +501,7 @@ def api_discover_caldav_calendars(
|
||||
calendars = discover_caldav_calendars(session, tenant_id=principal.tenant_id, payload=payload)
|
||||
return CalendarCalDavDiscoveryResponse(calendars=calendars)
|
||||
except (CalendarError, CalDAVError) as exc:
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
|
||||
raise _caldav_discovery_http_error(exc) from exc
|
||||
|
||||
|
||||
@router.post("/caldav/sources", response_model=CalendarCalDavSourceResponse, status_code=status.HTTP_201_CREATED)
|
||||
@@ -451,7 +530,14 @@ def api_update_caldav_source(
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
source = update_caldav_source(session, tenant_id=principal.tenant_id, source_id=source_id, payload=payload)
|
||||
source = update_caldav_source(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
source_id=source_id,
|
||||
payload=payload,
|
||||
user_id=principal.user.id,
|
||||
api_key_id=principal.api_key_id,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(source)
|
||||
return _caldav_source_response(source)
|
||||
@@ -468,12 +554,23 @@ def api_delete_caldav_source(
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
delete_caldav_source(session, tenant_id=principal.tenant_id, source_id=source_id)
|
||||
delete_caldav_source(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
source_id=source_id,
|
||||
user_id=principal.user.id,
|
||||
api_key_id=principal.api_key_id,
|
||||
)
|
||||
session.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
except CalendarError as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
|
||||
error_status = (
|
||||
status.HTTP_404_NOT_FOUND
|
||||
if "not found" in str(exc).lower()
|
||||
else status.HTTP_409_CONFLICT
|
||||
)
|
||||
raise HTTPException(status_code=error_status, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/caldav/sources/{source_id}/sync", response_model=CalendarCalDavSyncResponse)
|
||||
@@ -530,6 +627,117 @@ def api_sync_due_caldav_sources(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/caldav/outbox", response_model=CalendarOutboxOperationListResponse)
|
||||
def api_list_caldav_outbox(
|
||||
operation_status: str | None = Query(default=None, alias="status"),
|
||||
source_id: str | None = None,
|
||||
limit: int = Query(default=100, ge=1, le=500),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
operations = list_calendar_outbox_operations(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
status=operation_status,
|
||||
source_id=source_id,
|
||||
limit=limit,
|
||||
)
|
||||
return CalendarOutboxOperationListResponse(
|
||||
operations=[_outbox_operation_response(operation) for operation in operations]
|
||||
)
|
||||
|
||||
|
||||
@router.post("/caldav/outbox/dispatch", response_model=CalendarOutboxDispatchResponse)
|
||||
def api_dispatch_caldav_outbox(
|
||||
limit: int = Query(default=50, ge=1, le=200),
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
return CalendarOutboxDispatchResponse.model_validate(
|
||||
dispatch_calendar_outbox(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/caldav/outbox/{operation_id}/retry",
|
||||
response_model=CalendarOutboxOperationResponse,
|
||||
)
|
||||
def api_retry_caldav_outbox_operation(
|
||||
operation_id: str,
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
operation = retry_calendar_outbox_operation(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(operation)
|
||||
return _outbox_operation_response(operation)
|
||||
except ValueError as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/caldav/outbox/{operation_id}/reconcile",
|
||||
response_model=CalendarOutboxOperationResponse,
|
||||
)
|
||||
def api_reconcile_caldav_outbox_operation(
|
||||
operation_id: str,
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
operation = reconcile_calendar_outbox_operation(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(operation)
|
||||
return _outbox_operation_response(operation)
|
||||
except (ValueError, CalDAVError, CalendarError) as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/caldav/outbox/{operation_id}/discard",
|
||||
response_model=CalendarOutboxOperationResponse,
|
||||
)
|
||||
def api_discard_caldav_outbox_operation(
|
||||
operation_id: str,
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
"""Abandon local desired state and allow the next sync to accept remote."""
|
||||
|
||||
_require_scope(principal, "calendar:calendar:admin")
|
||||
try:
|
||||
operation = discard_calendar_outbox_operation(
|
||||
session,
|
||||
tenant_id=principal.tenant_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
session.commit()
|
||||
session.refresh(operation)
|
||||
return _outbox_operation_response(operation)
|
||||
except ValueError as exc:
|
||||
session.rollback()
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/events", response_model=CalendarEventListResponse)
|
||||
def api_list_events(
|
||||
calendar_id: str | None = None,
|
||||
@@ -600,7 +808,7 @@ def api_create_event(
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:event:write")
|
||||
_require_scope(principal, CALENDAR_EVENT_WRITE_SCOPE)
|
||||
try:
|
||||
event = create_event(session, tenant_id=principal.tenant_id, user_id=principal.user.id, payload=payload)
|
||||
session.commit()
|
||||
@@ -631,7 +839,7 @@ def api_update_event(
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:event:write")
|
||||
_require_scope(principal, CALENDAR_EVENT_WRITE_SCOPE)
|
||||
try:
|
||||
event = update_event(session, tenant_id=principal.tenant_id, user_id=principal.user.id, event_id=event_id, payload=payload)
|
||||
session.commit()
|
||||
@@ -648,7 +856,7 @@ def api_delete_event(
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_any_scope(principal, "calendar:event:delete", "calendar:event:write")
|
||||
_require_any_scope(principal, "calendar:event:delete", CALENDAR_EVENT_WRITE_SCOPE)
|
||||
try:
|
||||
delete_event(session, tenant_id=principal.tenant_id, event_id=event_id, user_id=principal.user.id)
|
||||
session.commit()
|
||||
@@ -713,7 +921,7 @@ def api_freebusy(
|
||||
principal: ApiPrincipal = Depends(get_api_principal),
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
_require_scope(principal, "calendar:availability:read")
|
||||
_require_scope(principal, CALENDAR_AVAILABILITY_READ_SCOPE)
|
||||
try:
|
||||
busy = list_freebusy(
|
||||
session,
|
||||
|
||||
@@ -1,36 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from govoplan_core.core.runtime import ModuleRuntimeState
|
||||
|
||||
_runtime_registry: object | None = None
|
||||
_runtime_settings: object | None = None
|
||||
_runtime = ModuleRuntimeState("Calendar")
|
||||
|
||||
|
||||
def configure_runtime(*, registry: object | None = None, settings: object | None = None) -> None:
|
||||
global _runtime_registry, _runtime_settings
|
||||
if registry is not None:
|
||||
_runtime_registry = registry
|
||||
if settings is not None:
|
||||
_runtime_settings = settings
|
||||
|
||||
|
||||
def get_registry() -> object | None:
|
||||
return _runtime_registry
|
||||
|
||||
|
||||
def get_settings() -> object:
|
||||
if _runtime_settings is not None:
|
||||
return _runtime_settings
|
||||
try:
|
||||
from govoplan_core.settings import settings as legacy_settings
|
||||
except ModuleNotFoundError as exc:
|
||||
raise RuntimeError("GovOPlaN Calendar runtime settings are not configured") from exc
|
||||
return legacy_settings
|
||||
|
||||
|
||||
class SettingsProxy:
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
return getattr(get_settings(), name)
|
||||
|
||||
|
||||
settings = SettingsProxy()
|
||||
configure_runtime = _runtime.configure_runtime
|
||||
get_registry = _runtime.get_registry
|
||||
get_settings = _runtime.get_settings
|
||||
settings = _runtime.settings
|
||||
|
||||
@@ -11,6 +11,11 @@ from govoplan_core.api.v1.schemas import DeltaDeletedItem
|
||||
CalendarOwnerType = Literal["tenant", "user", "group", "resource"]
|
||||
CalendarVisibility = Literal["private", "tenant", "shared", "public"]
|
||||
CalendarDeleteEventAction = Literal["delete", "move"]
|
||||
CalendarBulkMoveExternalAction = Literal[
|
||||
"detach_keep_remote",
|
||||
"copy_to_remote",
|
||||
"remote_move",
|
||||
]
|
||||
CalendarSyncAuthType = Literal["none", "basic", "bearer"]
|
||||
CalendarSyncDirection = Literal["inbound", "two_way"]
|
||||
CalendarSyncSourceKind = Literal["caldav", "ics", "webcal", "graph", "ews"]
|
||||
@@ -50,6 +55,7 @@ class CalendarCollectionDeleteRequest(BaseModel):
|
||||
event_action: CalendarDeleteEventAction = "delete"
|
||||
target_calendar_id: str | None = None
|
||||
make_target_default: bool = False
|
||||
external_action: CalendarBulkMoveExternalAction | None = None
|
||||
|
||||
|
||||
class CalendarCollectionResponse(BaseModel):
|
||||
@@ -130,6 +136,7 @@ class CalendarSyncSourceResponse(BaseModel):
|
||||
auth_type: str
|
||||
username: str | None = None
|
||||
credential_ref: str | None = None
|
||||
credential_envelope_id: str | None = None
|
||||
has_credential: bool = False
|
||||
sync_enabled: bool
|
||||
sync_interval_seconds: int
|
||||
@@ -159,6 +166,26 @@ class CalendarCalDavSourceListResponse(BaseModel):
|
||||
sources: list[CalendarCalDavSourceResponse] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CalendarCredentialEnvelopeResponse(BaseModel):
|
||||
id: str
|
||||
scope_type: str
|
||||
scope_id: str | None = None
|
||||
name: str
|
||||
description: str | None = None
|
||||
credential_kind: str
|
||||
public_data: dict[str, Any] = Field(default_factory=dict)
|
||||
secret_keys: list[str] = Field(default_factory=list)
|
||||
secret_configured: bool = False
|
||||
allowed_modules: list[str] = Field(default_factory=list)
|
||||
inherit_to_lower_scopes: bool = False
|
||||
is_active: bool = True
|
||||
revision: str
|
||||
|
||||
|
||||
class CalendarCredentialEnvelopeListResponse(BaseModel):
|
||||
credentials: list[CalendarCredentialEnvelopeResponse] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CalendarCalDavDiscoveryRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
@@ -238,6 +265,50 @@ class CalendarCalDavDueSyncResponse(BaseModel):
|
||||
results: list[CalendarCalDavDueSyncItemResponse] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CalendarOutboxOperationResponse(BaseModel):
|
||||
id: str
|
||||
tenant_id: str
|
||||
source_id: str
|
||||
event_id: str | None = None
|
||||
operation_kind: str
|
||||
resource_href: str
|
||||
payload_fingerprint: str | None = None
|
||||
expected_etag: str | None = None
|
||||
idempotency_key: str
|
||||
status: str
|
||||
attempt_count: int
|
||||
max_attempts: int
|
||||
available_at: datetime
|
||||
last_attempt_at: datetime | None = None
|
||||
lease_expires_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
reconciled_at: datetime | None = None
|
||||
remote_etag: str | None = None
|
||||
last_error: str | None = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
metadata: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class CalendarOutboxOperationListResponse(BaseModel):
|
||||
operations: list[CalendarOutboxOperationResponse] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CalendarOutboxDispatchItemResponse(BaseModel):
|
||||
id: str
|
||||
status: str
|
||||
attempt_count: int
|
||||
last_error: str | None = None
|
||||
|
||||
|
||||
class CalendarOutboxDispatchResponse(BaseModel):
|
||||
processed: int = 0
|
||||
succeeded: int = 0
|
||||
retrying: int = 0
|
||||
failed: int = 0
|
||||
operations: list[CalendarOutboxDispatchItemResponse] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CalendarEventCreateRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,32 +2,63 @@ from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import create_engine, inspect
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from govoplan_access.backend.db import models as access_models # noqa: F401 - populate users/accounts tables
|
||||
from govoplan_calendar.backend.caldav import CalDAVClient, CalDAVError, CalDAVNotFound, CalDAVObject, CalDAVPreconditionFailed, CalDAVReportResult, CalDAVWriteResult, parse_multistatus
|
||||
from govoplan_calendar.backend.db.models import CalendarEvent, CalendarSyncCredential, CalendarSyncSource
|
||||
from govoplan_calendar.backend.schemas import CalendarCalDavSourceCreateRequest, CalendarCollectionCreateRequest, CalendarEventCreateRequest, CalendarEventUpdateRequest
|
||||
from govoplan_calendar.backend.caldav import (
|
||||
CalDAVClient,
|
||||
CalDAVDiscoveryCalendar,
|
||||
CalDAVError,
|
||||
CalDAVNotFound,
|
||||
CalDAVObject,
|
||||
CalDAVPreconditionFailed,
|
||||
CalDAVReportResult,
|
||||
CalDAVWriteResult,
|
||||
parse_discovery_multistatus,
|
||||
parse_multistatus,
|
||||
)
|
||||
from govoplan_calendar.backend.db.models import CalendarEvent, CalendarOutboxOperation, CalendarSyncCredential
|
||||
from govoplan_calendar.backend.manifest import manifest
|
||||
from govoplan_calendar.backend.outbox import dispatch_calendar_outbox
|
||||
from govoplan_calendar.backend.schemas import (
|
||||
CalendarCalDavDiscoveryRequest,
|
||||
CalendarCalDavSourceCreateRequest,
|
||||
CalendarCalDavSourceUpdateRequest,
|
||||
CalendarCollectionCreateRequest,
|
||||
CalendarEventCreateRequest,
|
||||
CalendarEventUpdateRequest,
|
||||
)
|
||||
from govoplan_calendar.backend.service import (
|
||||
CALDAV_INTERNAL_CREDENTIAL_PREFIX,
|
||||
CalendarError,
|
||||
_CalDAVDiscoveryAuth,
|
||||
_caldav_discovery_client,
|
||||
_caldav_discovery_response,
|
||||
_plan_sync_source_creation,
|
||||
caldav_client_for_source,
|
||||
caldav_source_response,
|
||||
create_calendar,
|
||||
create_caldav_source,
|
||||
create_event,
|
||||
delete_caldav_source,
|
||||
delete_calendar,
|
||||
delete_event,
|
||||
discover_caldav_calendars,
|
||||
list_caldav_sources,
|
||||
list_freebusy,
|
||||
resolve_caldav_credential_ref,
|
||||
resolve_trusted_deployment_caldav_credential_ref,
|
||||
sync_caldav_source,
|
||||
sync_due_caldav_sources,
|
||||
update_caldav_source,
|
||||
update_event,
|
||||
)
|
||||
from govoplan_calendar.backend.router import _caldav_discovery_http_error
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_core.security.credential_envelopes import create_credential_envelope
|
||||
from govoplan_core.tenancy.scope import create_scope_tables
|
||||
from govoplan_tenancy.backend.db.models import Tenant
|
||||
|
||||
@@ -84,7 +115,93 @@ class FakeCalDAVClient:
|
||||
return CalDAVWriteResult(href=href, status=204)
|
||||
|
||||
|
||||
class FakeNotificationProvider:
|
||||
def __init__(self) -> None:
|
||||
self.requests: list[object] = []
|
||||
|
||||
def enqueue_notification(self, _session, request, **_kwargs) -> None:
|
||||
self.requests.append(request)
|
||||
|
||||
|
||||
class CalDAVParsingTests(unittest.TestCase):
|
||||
def test_discovery_parser_is_independent_from_transport(self) -> None:
|
||||
result = parse_discovery_multistatus(
|
||||
b"""<?xml version="1.0" encoding="utf-8"?>
|
||||
<D:multistatus xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
|
||||
<D:response>
|
||||
<D:href>/calendars/ada/work/</D:href>
|
||||
<D:propstat>
|
||||
<D:prop>
|
||||
<D:displayname>Work</D:displayname>
|
||||
<D:resourcetype><D:collection/><C:calendar/></D:resourcetype>
|
||||
<C:supported-calendar-component-set>
|
||||
<C:comp name="VEVENT"/>
|
||||
</C:supported-calendar-component-set>
|
||||
</D:prop>
|
||||
<D:status>HTTP/1.1 200 OK</D:status>
|
||||
</D:propstat>
|
||||
</D:response>
|
||||
</D:multistatus>"""
|
||||
)
|
||||
|
||||
self.assertEqual(1, len(result))
|
||||
self.assertEqual("Work", result[0].display_name)
|
||||
self.assertTrue(result[0].is_calendar)
|
||||
self.assertEqual(("VEVENT",), result[0].supported_components)
|
||||
|
||||
def test_discovery_auth_client_and_response_do_not_expose_secret(self) -> None:
|
||||
auth = _CalDAVDiscoveryAuth(
|
||||
auth_type="basic",
|
||||
username="ada",
|
||||
credential_ref=None,
|
||||
secret="calendar-secret",
|
||||
)
|
||||
client = _caldav_discovery_client(
|
||||
"https://dav.example.test/cal",
|
||||
auth,
|
||||
)
|
||||
response = _caldav_discovery_response(
|
||||
(
|
||||
CalDAVDiscoveryCalendar(
|
||||
collection_url="https://dav.example.test/cal/work/",
|
||||
href="/cal/work/",
|
||||
display_name="Work",
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
self.assertNotIn("calendar-secret", repr(auth))
|
||||
self.assertEqual("calendar-secret", client.password)
|
||||
self.assertEqual("Work", response[0]["display_name"])
|
||||
self.assertNotIn("password", response[0])
|
||||
self.assertNotIn("credential_ref", response[0])
|
||||
|
||||
def test_discovery_error_translation_is_stable(self) -> None:
|
||||
error = _caldav_discovery_http_error(
|
||||
CalDAVError("CalDAV endpoint rejected PROPFIND")
|
||||
)
|
||||
|
||||
self.assertEqual(422, error.status_code)
|
||||
self.assertEqual(
|
||||
"CalDAV endpoint rejected PROPFIND",
|
||||
error.detail,
|
||||
)
|
||||
|
||||
def test_sync_source_creation_plan_is_secret_free(self) -> None:
|
||||
plan = _plan_sync_source_creation(
|
||||
CalendarCalDavSourceCreateRequest(
|
||||
calendar_id="calendar-1",
|
||||
collection_url="dav.example.test/cal",
|
||||
auth_type="basic",
|
||||
username="ada",
|
||||
password="calendar-secret",
|
||||
)
|
||||
)
|
||||
|
||||
self.assertEqual("https://dav.example.test/cal/", plan.collection_url)
|
||||
self.assertTrue(plan.has_inline_secret)
|
||||
self.assertNotIn("calendar-secret", repr(plan))
|
||||
|
||||
def test_parse_multistatus_extracts_objects_sync_token_and_deletions(self) -> None:
|
||||
result = parse_multistatus(
|
||||
b"""<?xml version="1.0" encoding="utf-8"?>
|
||||
@@ -216,10 +333,20 @@ END:VCALENDAR</C:calendar-data>
|
||||
self.assertEqual(calendars[0].collection_url, "https://cloud.example.test/remote.php/dav/calendars/ada/personal/")
|
||||
|
||||
def test_discovery_reports_relative_url_as_caldav_error(self) -> None:
|
||||
client = CalDAVClient(collection_url="/remote.php/dav")
|
||||
with self.assertRaisesRegex(CalDAVError, "absolute HTTP"):
|
||||
CalDAVClient(collection_url="/remote.php/dav")
|
||||
|
||||
with self.assertRaisesRegex(CalDAVError, "unknown url type"):
|
||||
client.discover_calendars()
|
||||
def test_object_url_rejects_off_origin_and_cross_collection_hrefs(self) -> None:
|
||||
client = CalDAVClient(collection_url="https://dav.example.test/cal")
|
||||
|
||||
with self.assertRaisesRegex(CalDAVError, "collection origin"):
|
||||
client.object_url("https://evil.example.test/steal.ics")
|
||||
with self.assertRaisesRegex(CalDAVError, "collection path"):
|
||||
client.object_url("https://dav.example.test/other/steal.ics")
|
||||
self.assertEqual(
|
||||
client.object_url("/cal/event.ics"),
|
||||
"https://dav.example.test/cal/event.ics",
|
||||
)
|
||||
|
||||
|
||||
class CalDAVSyncTests(unittest.TestCase):
|
||||
@@ -228,12 +355,21 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
create_scope_tables(self.engine)
|
||||
Base.metadata.create_all(bind=self.engine)
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
self.sessions = []
|
||||
|
||||
def tearDown(self) -> None:
|
||||
for session in reversed(self.sessions):
|
||||
session.close()
|
||||
Base.metadata.drop_all(bind=self.engine)
|
||||
self.engine.dispose()
|
||||
|
||||
def session(self):
|
||||
session = self.Session()
|
||||
self.sessions.append(session)
|
||||
return session
|
||||
|
||||
def test_source_creation_encrypts_credential_and_resolves_client_secret(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
|
||||
@@ -259,8 +395,261 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
self.assertEqual(client.username, "ada")
|
||||
self.assertEqual(client.password, "secret")
|
||||
|
||||
def test_source_can_resolve_reusable_core_credential(self) -> None:
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
credential = create_credential_envelope(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
scope_type="tenant",
|
||||
scope_id="tenant-1",
|
||||
name="Shared DAV login",
|
||||
credential_kind="username_password",
|
||||
public_data={"username": "ada"},
|
||||
secret_data={"password": "secret"},
|
||||
allowed_modules=["calendar"],
|
||||
inherit_to_lower_scopes=True,
|
||||
)
|
||||
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/cal",
|
||||
auth_type="basic",
|
||||
credential_ref=f"credential-envelope:{credential.id}",
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
|
||||
client = caldav_client_for_source(session, source)
|
||||
response = caldav_source_response(source)
|
||||
|
||||
self.assertEqual(client.username, "ada")
|
||||
self.assertEqual(client.password, "secret")
|
||||
self.assertEqual(response["credential_envelope_id"], credential.id)
|
||||
self.assertEqual(session.query(CalendarSyncCredential).count(), 0)
|
||||
|
||||
def test_api_source_and_discovery_reject_caller_selected_credential_references(self) -> None:
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(CalendarError, "Caller-supplied credential references"):
|
||||
create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://attacker.example.test/cal",
|
||||
auth_type="bearer",
|
||||
credential_ref="env:MASTER_KEY_B64",
|
||||
),
|
||||
)
|
||||
with self.assertRaisesRegex(CalendarError, "Caller-supplied credential references"):
|
||||
discover_caldav_calendars(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
payload=CalendarCalDavDiscoveryRequest(
|
||||
url="https://attacker.example.test/cal",
|
||||
auth_type="bearer",
|
||||
credential_ref="vault:another-tenant",
|
||||
),
|
||||
)
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/cal",
|
||||
),
|
||||
)
|
||||
with self.assertRaisesRegex(CalendarError, "Caller-supplied credential references"):
|
||||
update_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
source_id=source.id,
|
||||
payload=CalendarCalDavSourceUpdateRequest(
|
||||
credential_ref="env:MASTER_KEY_B64",
|
||||
),
|
||||
)
|
||||
|
||||
def test_provider_credentials_are_wrapped_in_tenant_and_source_owned_rows(self) -> None:
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.values: dict[str, str] = {}
|
||||
self.deleted: list[str] = []
|
||||
|
||||
def store_secret(self, *, scope: str, name: str, value: str) -> str:
|
||||
reference = f"vault:{scope}:{name}"
|
||||
self.values[reference] = value
|
||||
return reference
|
||||
|
||||
def read_secret(self, secret_ref: str) -> str | None:
|
||||
return self.values.get(secret_ref)
|
||||
|
||||
def delete_secret(self, secret_ref: str) -> None:
|
||||
self.deleted.append(secret_ref)
|
||||
self.values.pop(secret_ref, None)
|
||||
|
||||
provider = Provider()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=provider):
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/cal",
|
||||
auth_type="basic",
|
||||
username="ada",
|
||||
password="secret",
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
credential = session.query(CalendarSyncCredential).one()
|
||||
provider_ref = str((credential.metadata_ or {})["provider_ref"])
|
||||
|
||||
self.assertTrue(source.credential_ref.startswith(CALDAV_INTERNAL_CREDENTIAL_PREFIX))
|
||||
self.assertNotEqual(source.credential_ref, provider_ref)
|
||||
self.assertEqual(caldav_client_for_source(session, source).password, "secret")
|
||||
self.assertIsNone(caldav_source_response(source)["credential_ref"])
|
||||
self.assertTrue(caldav_source_response(source)["has_credential"])
|
||||
self.assertIsNone(
|
||||
resolve_caldav_credential_ref(
|
||||
session,
|
||||
tenant_id="another-tenant",
|
||||
source_id=source.id,
|
||||
credential_ref=source.credential_ref,
|
||||
)
|
||||
)
|
||||
self.assertIsNone(
|
||||
resolve_caldav_credential_ref(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
source_id="another-source",
|
||||
credential_ref=source.credential_ref,
|
||||
)
|
||||
)
|
||||
|
||||
other_calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Other remote"),
|
||||
)
|
||||
other_source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=other_calendar.id,
|
||||
collection_url="https://dav.example.test/other-cal",
|
||||
),
|
||||
)
|
||||
other_source.auth_type = "basic"
|
||||
other_source.username = "mallory"
|
||||
other_source.credential_ref = source.credential_ref
|
||||
with self.assertRaisesRegex(CalendarError, "not a server-owned credential"):
|
||||
caldav_client_for_source(session, other_source)
|
||||
delete_calendar(session, tenant_id="tenant-1", calendar_id=other_calendar.id)
|
||||
self.assertEqual(provider.deleted, [])
|
||||
|
||||
with patch("govoplan_calendar.backend.service.audit_event") as audit:
|
||||
delete_calendar(session, tenant_id="tenant-1", calendar_id=calendar.id)
|
||||
|
||||
self.assertEqual(provider.deleted, [provider_ref])
|
||||
self.assertNotIn(provider_ref, provider.values)
|
||||
self.assertIsNone(source.credential_ref)
|
||||
self.assertIsNone(credential.secret_encrypted)
|
||||
self.assertNotIn("provider_ref", credential.metadata_ or {})
|
||||
audit.assert_called_once()
|
||||
audit_call = audit.call_args.kwargs
|
||||
self.assertEqual(audit_call["action"], "calendar.sync_credential_deleted")
|
||||
self.assertEqual(audit_call["object_id"], credential.id)
|
||||
self.assertEqual(audit_call["details"]["storage_backend"], "external_secret_provider")
|
||||
self.assertEqual(audit_call["details"]["deletion_reason"], "calendar_deleted")
|
||||
self.assertNotIn("credential_ref", audit_call["details"])
|
||||
self.assertNotIn("provider_ref", audit_call["details"])
|
||||
self.assertNotIn(provider_ref, repr(audit_call["details"]))
|
||||
|
||||
def test_legacy_unowned_refs_are_neither_read_nor_deleted(self) -> None:
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.read: list[str] = []
|
||||
self.deleted: list[str] = []
|
||||
|
||||
def read_secret(self, secret_ref: str) -> str | None:
|
||||
self.read.append(secret_ref)
|
||||
return "other-tenant-secret"
|
||||
|
||||
def delete_secret(self, secret_ref: str) -> None:
|
||||
self.deleted.append(secret_ref)
|
||||
|
||||
provider = Provider()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/cal",
|
||||
),
|
||||
)
|
||||
source.auth_type = "bearer"
|
||||
source.credential_ref = "vault:another-tenant"
|
||||
session.commit()
|
||||
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=provider):
|
||||
with self.assertRaisesRegex(CalendarError, "not a server-owned credential"):
|
||||
caldav_client_for_source(session, source)
|
||||
delete_calendar(session, tenant_id="tenant-1", calendar_id=calendar.id)
|
||||
|
||||
self.assertEqual(provider.read, [])
|
||||
self.assertEqual(provider.deleted, [])
|
||||
|
||||
def test_trusted_deployment_env_resolution_is_explicit_and_separate(self) -> None:
|
||||
with patch.dict("os.environ", {"CALDAV_DEPLOYMENT_TOKEN": "trusted-token"}):
|
||||
self.assertEqual(
|
||||
resolve_trusted_deployment_caldav_credential_ref("env:CALDAV_DEPLOYMENT_TOKEN"),
|
||||
"trusted-token",
|
||||
)
|
||||
with self.assertRaisesRegex(CalendarError, "must use the env: prefix"):
|
||||
resolve_trusted_deployment_caldav_credential_ref("vault:token")
|
||||
|
||||
def test_delete_calendar_retires_caldav_source_and_credential(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
source = create_caldav_source(
|
||||
@@ -282,11 +671,319 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
|
||||
credential = session.query(CalendarSyncCredential).one()
|
||||
self.assertIsNotNone(source.deleted_at)
|
||||
self.assertIsNone(source.credential_ref)
|
||||
self.assertIsNotNone(credential.deleted_at)
|
||||
self.assertIsNone(credential.secret_encrypted)
|
||||
self.assertEqual(credential.metadata_, {"source_id": source.id})
|
||||
self.assertEqual(list_caldav_sources(session, tenant_id="tenant-1"), [])
|
||||
|
||||
def test_external_credential_deletion_fails_closed_when_provider_is_unavailable(self) -> None:
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.values: dict[str, str] = {}
|
||||
|
||||
def store_secret(self, *, scope: str, name: str, value: str) -> str:
|
||||
reference = f"vault:{scope}:{name}"
|
||||
self.values[reference] = value
|
||||
return reference
|
||||
|
||||
def read_secret(self, secret_ref: str) -> str | None:
|
||||
return self.values.get(secret_ref)
|
||||
|
||||
def delete_secret(self, secret_ref: str) -> None:
|
||||
self.values.pop(secret_ref, None)
|
||||
|
||||
provider = Provider()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=provider):
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/provider-down",
|
||||
auth_type="bearer",
|
||||
bearer_token="do-not-log-this",
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
credential = session.query(CalendarSyncCredential).one()
|
||||
provider_ref = str((credential.metadata_ or {})["provider_ref"])
|
||||
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=None), self.assertRaisesRegex(
|
||||
CalendarError,
|
||||
"secret provider is unavailable",
|
||||
):
|
||||
delete_caldav_source(session, tenant_id="tenant-1", source_id=source.id)
|
||||
session.rollback()
|
||||
|
||||
self.assertIsNone(source.deleted_at)
|
||||
self.assertEqual(source.credential_ref, f"{CALDAV_INTERNAL_CREDENTIAL_PREFIX}{credential.id}")
|
||||
self.assertIsNone(credential.deleted_at)
|
||||
self.assertEqual((credential.metadata_ or {})["provider_ref"], provider_ref)
|
||||
self.assertIn(provider_ref, provider.values)
|
||||
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=provider), patch.object(
|
||||
provider,
|
||||
"delete_secret",
|
||||
side_effect=RuntimeError(f"provider failed for {provider_ref}"),
|
||||
):
|
||||
with self.assertRaises(CalendarError) as raised:
|
||||
delete_caldav_source(session, tenant_id="tenant-1", source_id=source.id)
|
||||
self.assertNotIn(provider_ref, str(raised.exception))
|
||||
session.rollback()
|
||||
self.assertIsNone(source.deleted_at)
|
||||
self.assertIsNone(credential.deleted_at)
|
||||
|
||||
def test_disabling_auth_immediately_scrubs_and_audits_database_credential(self) -> None:
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/disable-auth",
|
||||
auth_type="basic",
|
||||
username="ada",
|
||||
password="do-not-log-this",
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
credential = session.query(CalendarSyncCredential).one()
|
||||
self.assertIsNotNone(credential.secret_encrypted)
|
||||
|
||||
with patch("govoplan_calendar.backend.service.audit_event") as audit:
|
||||
update_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
source_id=source.id,
|
||||
payload=CalendarCalDavSourceUpdateRequest(auth_type="none"),
|
||||
)
|
||||
session.commit()
|
||||
|
||||
self.assertIsNone(source.credential_ref)
|
||||
self.assertIsNone(credential.secret_encrypted)
|
||||
self.assertIsNotNone(credential.deleted_at)
|
||||
audit.assert_called_once()
|
||||
self.assertEqual(
|
||||
audit.call_args.kwargs["details"]["deletion_reason"],
|
||||
"authentication_disabled",
|
||||
)
|
||||
self.assertNotIn("do-not-log-this", repr(audit.call_args))
|
||||
|
||||
def test_external_credential_replacement_fails_closed_when_provider_is_unavailable(self) -> None:
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.values: dict[str, str] = {}
|
||||
|
||||
def store_secret(self, *, scope: str, name: str, value: str) -> str:
|
||||
reference = f"vault:{scope}:{name}"
|
||||
self.values[reference] = value
|
||||
return reference
|
||||
|
||||
def read_secret(self, secret_ref: str) -> str | None:
|
||||
return self.values.get(secret_ref)
|
||||
|
||||
def delete_secret(self, secret_ref: str) -> None:
|
||||
self.values.pop(secret_ref, None)
|
||||
|
||||
provider = Provider()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=provider):
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/replacement-provider-down",
|
||||
auth_type="bearer",
|
||||
bearer_token="old-secret",
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
credential = session.query(CalendarSyncCredential).one()
|
||||
provider_ref = str((credential.metadata_ or {})["provider_ref"])
|
||||
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=None), self.assertRaisesRegex(
|
||||
CalendarError,
|
||||
"cannot be replaced.*provider is unavailable",
|
||||
):
|
||||
update_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
source_id=source.id,
|
||||
payload=CalendarCalDavSourceUpdateRequest(bearer_token="new-secret"),
|
||||
)
|
||||
session.rollback()
|
||||
|
||||
self.assertEqual(source.credential_ref, f"{CALDAV_INTERNAL_CREDENTIAL_PREFIX}{credential.id}")
|
||||
self.assertEqual((credential.metadata_ or {})["provider_ref"], provider_ref)
|
||||
self.assertEqual(provider.values[provider_ref], "old-secret")
|
||||
|
||||
def test_external_credential_delete_is_retryable_after_database_rollback(self) -> None:
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.values: dict[str, str] = {}
|
||||
self.deletes: list[str] = []
|
||||
|
||||
def store_secret(self, *, scope: str, name: str, value: str) -> str:
|
||||
reference = f"vault:{scope}:{name}"
|
||||
self.values[reference] = value
|
||||
return reference
|
||||
|
||||
def read_secret(self, secret_ref: str) -> str | None:
|
||||
return self.values.get(secret_ref)
|
||||
|
||||
def delete_secret(self, secret_ref: str) -> None:
|
||||
self.deletes.append(secret_ref)
|
||||
if secret_ref not in self.values:
|
||||
raise KeyError("already deleted")
|
||||
self.values.pop(secret_ref, None)
|
||||
|
||||
provider = Provider()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=provider):
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/retry-delete",
|
||||
auth_type="basic",
|
||||
username="ada",
|
||||
password="do-not-log-this",
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
credential = session.query(CalendarSyncCredential).one()
|
||||
provider_ref = str((credential.metadata_ or {})["provider_ref"])
|
||||
|
||||
with patch("govoplan_calendar.backend.service.audit_event"):
|
||||
delete_caldav_source(session, tenant_id="tenant-1", source_id=source.id)
|
||||
self.assertNotIn(provider_ref, provider.values)
|
||||
self.assertIsNotNone(credential.deleted_at)
|
||||
self.assertIsNone(source.credential_ref)
|
||||
session.rollback()
|
||||
|
||||
self.assertIsNone(source.deleted_at)
|
||||
session.refresh(credential)
|
||||
self.assertIsNone(credential.deleted_at)
|
||||
self.assertEqual((credential.metadata_ or {})["provider_ref"], provider_ref)
|
||||
self.assertIsNone(resolve_caldav_credential_ref(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
source_id=source.id,
|
||||
credential_ref=source.credential_ref,
|
||||
))
|
||||
|
||||
with patch("govoplan_calendar.backend.service.audit_event") as audit:
|
||||
delete_caldav_source(session, tenant_id="tenant-1", source_id=source.id)
|
||||
session.commit()
|
||||
|
||||
self.assertEqual(provider.deletes, [provider_ref, provider_ref])
|
||||
self.assertIsNotNone(source.deleted_at)
|
||||
self.assertIsNone(source.credential_ref)
|
||||
self.assertIsNotNone(credential.deleted_at)
|
||||
self.assertEqual(audit.call_count, 1)
|
||||
|
||||
def test_destructive_module_retirement_deletes_external_credentials_before_tables(self) -> None:
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.values: dict[str, str] = {}
|
||||
self.deleted: list[str] = []
|
||||
|
||||
def store_secret(self, *, scope: str, name: str, value: str) -> str:
|
||||
reference = f"vault:{scope}:{name}"
|
||||
self.values[reference] = value
|
||||
return reference
|
||||
|
||||
def read_secret(self, secret_ref: str) -> str | None:
|
||||
return self.values.get(secret_ref)
|
||||
|
||||
def delete_secret(self, secret_ref: str) -> None:
|
||||
self.deleted.append(secret_ref)
|
||||
self.values.pop(secret_ref, None)
|
||||
|
||||
provider = Provider()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCollectionCreateRequest(name="Remote"),
|
||||
)
|
||||
with patch("govoplan_calendar.backend.service.secret_provider", return_value=provider):
|
||||
create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://dav.example.test/module-retirement",
|
||||
auth_type="bearer",
|
||||
bearer_token="do-not-log-this",
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
credential = session.query(CalendarSyncCredential).one()
|
||||
provider_ref = str((credential.metadata_ or {})["provider_ref"])
|
||||
retirement_provider = manifest.migration_spec.retirement_provider
|
||||
assert retirement_provider is not None
|
||||
plan = retirement_provider(session, "calendar")
|
||||
assert plan.destroy_data_executor is not None
|
||||
with patch("govoplan_calendar.backend.service.audit_event") as audit:
|
||||
plan.destroy_data_executor(session, "calendar")
|
||||
# Retirement intentionally participates in the caller's database
|
||||
# transaction. Commit before inspecting through a new Engine
|
||||
# connection; otherwise SQLite rolls back the uncommitted DDL when
|
||||
# the temporary inspector connection is returned to the pool.
|
||||
session.commit()
|
||||
|
||||
self.assertEqual(provider.deleted, [provider_ref])
|
||||
self.assertEqual(provider.values, {})
|
||||
self.assertEqual(audit.call_count, 1)
|
||||
self.assertEqual(
|
||||
audit.call_args.kwargs["details"]["deletion_reason"],
|
||||
"module_data_retired",
|
||||
)
|
||||
self.assertFalse(inspect(self.engine).has_table("calendar_sync_credentials"))
|
||||
self.assertFalse(inspect(self.engine).has_table("calendar_sync_sources"))
|
||||
|
||||
def test_create_source_retires_orphaned_source_for_deleted_calendar(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
old_calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Old"))
|
||||
old_source = create_caldav_source(
|
||||
@@ -312,7 +1009,7 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
self.assertEqual([source.id for source in list_caldav_sources(session, tenant_id="tenant-1")], [new_source.id])
|
||||
|
||||
def test_create_source_reports_active_duplicate_as_calendar_error(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
first = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="First"))
|
||||
second = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Second"))
|
||||
@@ -333,7 +1030,7 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
)
|
||||
|
||||
def test_due_sync_runs_due_sources_and_reschedules(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
source = create_caldav_source(
|
||||
@@ -359,40 +1056,71 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
next_sync_at = source.next_sync_at if source.next_sync_at.tzinfo else source.next_sync_at.replace(tzinfo=timezone.utc)
|
||||
self.assertGreater(next_sync_at, datetime(2026, 7, 7, 8, 1, tzinfo=timezone.utc))
|
||||
|
||||
def test_create_and_update_event_puts_caldav_resource_with_etag(self) -> None:
|
||||
session = self.Session()
|
||||
def test_due_sync_emits_recovery_notification_after_previous_error(self) -> None:
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
source = create_caldav_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarCalDavSourceCreateRequest(calendar_id=calendar.id, collection_url="https://dav.example.test/cal"),
|
||||
)
|
||||
source.last_status = "error"
|
||||
source.next_sync_at = datetime(2026, 7, 7, 8, 0, tzinfo=timezone.utc)
|
||||
session.commit()
|
||||
|
||||
provider = FakeNotificationProvider()
|
||||
fake = FakeCalDAVClient(list_result=CalDAVReportResult(sync_token="token-1"))
|
||||
with patch("govoplan_calendar.backend.service.notification_dispatch_provider", return_value=provider):
|
||||
results = sync_due_caldav_sources(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
now=datetime(2026, 7, 7, 8, 1, tzinfo=timezone.utc),
|
||||
client_factory=lambda _source: fake,
|
||||
)
|
||||
|
||||
self.assertEqual(results[0].status, "ok")
|
||||
self.assertEqual(len(provider.requests), 1)
|
||||
self.assertEqual(provider.requests[0].event_kind, "calendar.sync.ok")
|
||||
|
||||
def test_create_and_update_event_coalesce_to_committed_outbox_state(self) -> None:
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
create_caldav_source(session, tenant_id="tenant-1", user_id=None, payload=CalendarCalDavSourceCreateRequest(calendar_id=calendar.id, collection_url="https://dav.example.test/cal"))
|
||||
session.commit()
|
||||
|
||||
fake = FakeCalDAVClient(put_etags=['"etag-1"', '"etag-2"'])
|
||||
with patch("govoplan_calendar.backend.service.caldav_client_for_source", return_value=fake):
|
||||
event = create_event(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarEventCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
uid="event-1@example.test",
|
||||
summary="Planning",
|
||||
start_at=datetime(2026, 7, 8, 9, 0, tzinfo=timezone.utc),
|
||||
end_at=datetime(2026, 7, 8, 10, 0, tzinfo=timezone.utc),
|
||||
),
|
||||
)
|
||||
update_event(session, tenant_id="tenant-1", user_id=None, event_id=event.id, payload=CalendarEventUpdateRequest(summary="Updated"))
|
||||
fake = FakeCalDAVClient(put_etags=['"etag-1"'])
|
||||
event = create_event(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarEventCreateRequest(
|
||||
calendar_id=calendar.id,
|
||||
uid="event-1@example.test",
|
||||
summary="Planning",
|
||||
start_at=datetime(2026, 7, 8, 9, 0, tzinfo=timezone.utc),
|
||||
end_at=datetime(2026, 7, 8, 10, 0, tzinfo=timezone.utc),
|
||||
),
|
||||
)
|
||||
update_event(session, tenant_id="tenant-1", user_id=None, event_id=event.id, payload=CalendarEventUpdateRequest(summary="Updated"))
|
||||
self.assertEqual(fake.puts, [])
|
||||
session.commit()
|
||||
|
||||
self.assertEqual(len(fake.puts), 2)
|
||||
operations = session.query(CalendarOutboxOperation).all()
|
||||
self.assertCountEqual([operation.status for operation in operations], ["superseded", "pending"])
|
||||
dispatch_calendar_outbox(session, tenant_id="tenant-1", client_factory=lambda _session, _source: fake)
|
||||
|
||||
self.assertEqual(len(fake.puts), 1)
|
||||
self.assertTrue(fake.puts[0]["create"])
|
||||
self.assertEqual(fake.puts[1]["etag"], '"etag-1"')
|
||||
self.assertFalse(fake.puts[1]["create"])
|
||||
self.assertIn("SUMMARY:Updated", fake.puts[0]["ics"])
|
||||
self.assertEqual(event.source_kind, "caldav")
|
||||
self.assertEqual(event.etag, '"etag-2"')
|
||||
self.assertEqual(event.etag, '"etag-1"')
|
||||
self.assertIn("SUMMARY:Updated", event.raw_ics or "")
|
||||
|
||||
def test_update_event_reports_remote_etag_conflict(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
create_caldav_source(session, tenant_id="tenant-1", user_id=None, payload=CalendarCalDavSourceCreateRequest(calendar_id=calendar.id, collection_url="https://dav.example.test/cal"))
|
||||
@@ -400,13 +1128,25 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
session.add(event)
|
||||
session.commit()
|
||||
|
||||
fake = FakeCalDAVClient(fail_precondition=True)
|
||||
with patch("govoplan_calendar.backend.service.caldav_client_for_source", return_value=fake):
|
||||
with self.assertRaisesRegex(CalendarError, "changed remotely"):
|
||||
update_event(session, tenant_id="tenant-1", user_id=None, event_id=event.id, payload=CalendarEventUpdateRequest(summary="Updated"))
|
||||
fake = FakeCalDAVClient(
|
||||
fail_precondition=True,
|
||||
objects={event.source_href: recurring_resource()},
|
||||
)
|
||||
update_event(session, tenant_id="tenant-1", user_id=None, event_id=event.id, payload=CalendarEventUpdateRequest(summary="Updated"))
|
||||
session.commit()
|
||||
result = dispatch_calendar_outbox(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
client_factory=lambda _session, _source: fake,
|
||||
)
|
||||
|
||||
self.assertEqual(result["failed"], 1)
|
||||
operation = session.query(CalendarOutboxOperation).one()
|
||||
self.assertEqual(operation.status, "conflict")
|
||||
self.assertIn("changed remotely", operation.last_error or "")
|
||||
|
||||
def test_delete_one_component_puts_remaining_resource_instead_of_deleting_object(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
create_caldav_source(session, tenant_id="tenant-1", user_id=None, payload=CalendarCalDavSourceCreateRequest(calendar_id=calendar.id, collection_url="https://dav.example.test/cal"))
|
||||
@@ -417,9 +1157,9 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
session.commit()
|
||||
|
||||
fake = FakeCalDAVClient(put_etags=['"etag-2"'])
|
||||
with patch("govoplan_calendar.backend.service.caldav_client_for_source", return_value=fake):
|
||||
delete_event(session, tenant_id="tenant-1", event_id=override.id)
|
||||
delete_event(session, tenant_id="tenant-1", event_id=override.id)
|
||||
session.commit()
|
||||
dispatch_calendar_outbox(session, tenant_id="tenant-1", client_factory=lambda _session, _source: fake)
|
||||
|
||||
self.assertEqual(len(fake.puts), 1)
|
||||
self.assertEqual(fake.deletes, [])
|
||||
@@ -429,7 +1169,7 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
self.assertIsNotNone(override.deleted_at)
|
||||
|
||||
def test_freebusy_expands_recurring_events_and_skips_transparent_items(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Local"))
|
||||
create_event(
|
||||
@@ -471,7 +1211,7 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
self.assertEqual(busy[0]["start_at"], datetime(2026, 7, 8, 9, 0, tzinfo=timezone.utc))
|
||||
|
||||
def test_full_sync_imports_multi_vevent_resource_and_fetches_missing_calendar_data(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
tenant = Tenant(id="tenant-1", slug="tenant-1", name="Tenant")
|
||||
session.add(tenant)
|
||||
calendar = create_calendar(
|
||||
@@ -512,7 +1252,7 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
self.assertEqual(calendar.metadata_["source_kind"], "caldav")
|
||||
|
||||
def test_sync_token_deletion_soft_deletes_remote_resource_events(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
tenant = Tenant(id="tenant-1", slug="tenant-1", name="Tenant")
|
||||
session.add(tenant)
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
@@ -561,7 +1301,7 @@ class CalDAVSyncTests(unittest.TestCase):
|
||||
self.assertIsNotNone(event.deleted_at)
|
||||
|
||||
def test_missing_resource_during_fetch_is_treated_as_remote_delete(self) -> None:
|
||||
session = self.Session()
|
||||
session = self.session()
|
||||
tenant = Tenant(id="tenant-1", slug="tenant-1", name="Tenant")
|
||||
session.add(tenant)
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
|
||||
142
tests/test_caldav_security.py
Normal file
142
tests/test_caldav_security.py
Normal file
@@ -0,0 +1,142 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import threading
|
||||
import unittest
|
||||
from collections.abc import Iterator
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from unittest.mock import patch
|
||||
|
||||
from govoplan_calendar.backend.caldav import (
|
||||
CalDAVClient,
|
||||
CalDAVError,
|
||||
absolute_dav_url,
|
||||
urllib_transport,
|
||||
)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def running_http_server(handler: type[BaseHTTPRequestHandler]) -> Iterator[str]:
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
host, port = server.server_address
|
||||
yield f"http://{host}:{port}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=2)
|
||||
|
||||
|
||||
class CalDAVUrlSecurityTests(unittest.TestCase):
|
||||
def test_transport_revalidates_dns_at_connection_time(self) -> None:
|
||||
public = [(2, 1, 6, "", ("93.184.216.34", 443))]
|
||||
private = [(2, 1, 6, "", ("127.0.0.1", 443))]
|
||||
with patch.dict(
|
||||
"os.environ",
|
||||
{"APP_ENV": "production", "GOVOPLAN_CONNECTOR_ALLOW_PRIVATE_NETWORKS": "false"},
|
||||
), patch(
|
||||
"govoplan_core.security.outbound_http.socket.getaddrinfo",
|
||||
side_effect=(public, private),
|
||||
), patch("govoplan_core.security.outbound_http.socket.socket") as socket_factory, self.assertRaisesRegex(
|
||||
CalDAVError,
|
||||
"non-public network",
|
||||
):
|
||||
urllib_transport("GET", "https://dav.example.test/event.ics", {}, None, 2)
|
||||
socket_factory.assert_not_called()
|
||||
|
||||
def test_discovery_href_must_remain_on_configured_origin(self) -> None:
|
||||
base_url = "https://dav.example.test/calendars/ada/"
|
||||
|
||||
self.assertEqual(
|
||||
absolute_dav_url(base_url, "/principals/users/ada/"),
|
||||
"https://dav.example.test/principals/users/ada/",
|
||||
)
|
||||
with self.assertRaisesRegex(CalDAVError, "configured collection origin"):
|
||||
absolute_dav_url(base_url, "https://evil.example.test/steal/")
|
||||
with self.assertRaisesRegex(CalDAVError, "query or fragment"):
|
||||
absolute_dav_url(base_url, "/principals/users/ada/?token=secret")
|
||||
|
||||
def test_object_href_rejects_userinfo_query_and_fragment(self) -> None:
|
||||
client = CalDAVClient(collection_url="https://dav.example.test/calendars/ada")
|
||||
|
||||
with self.assertRaisesRegex(CalDAVError, "embedded credentials"):
|
||||
client.object_url("https://user:secret@dav.example.test/calendars/ada/event.ics")
|
||||
with self.assertRaisesRegex(CalDAVError, "query or fragment"):
|
||||
client.object_url("/calendars/ada/event.ics?download=1")
|
||||
with self.assertRaisesRegex(CalDAVError, "query or fragment"):
|
||||
client.object_url("/calendars/ada/event.ics#fragment")
|
||||
self.assertEqual(
|
||||
client.object_url("/calendars/ada/event.ics"),
|
||||
"https://dav.example.test/calendars/ada/event.ics",
|
||||
)
|
||||
|
||||
def test_transport_refuses_redirect_before_forwarding_authorization(self) -> None:
|
||||
forwarded_authorization: list[str | None] = []
|
||||
|
||||
class TargetHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
forwarded_authorization.append(self.headers.get("Authorization"))
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, _format: str, *_args: object) -> None:
|
||||
return
|
||||
|
||||
with running_http_server(TargetHandler) as target_url:
|
||||
class RedirectHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
self.send_response(302)
|
||||
self.send_header("Location", f"{target_url}/stolen.ics")
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, _format: str, *_args: object) -> None:
|
||||
return
|
||||
|
||||
with running_http_server(RedirectHandler) as redirect_url:
|
||||
status, _headers, _body = urllib_transport(
|
||||
"GET",
|
||||
f"{redirect_url}/event.ics",
|
||||
{"Authorization": "Bearer top-secret"},
|
||||
None,
|
||||
2,
|
||||
)
|
||||
|
||||
self.assertEqual(status, 302)
|
||||
self.assertEqual(forwarded_authorization, [])
|
||||
|
||||
def test_transport_preserves_same_origin_redirects(self) -> None:
|
||||
forwarded_authorization: list[str | None] = []
|
||||
|
||||
class RedirectHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
if self.path == "/event.ics":
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "/redirected.ics")
|
||||
self.end_headers()
|
||||
return
|
||||
forwarded_authorization.append(self.headers.get("Authorization"))
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"calendar")
|
||||
|
||||
def log_message(self, _format: str, *_args: object) -> None:
|
||||
return
|
||||
|
||||
with running_http_server(RedirectHandler) as source_url:
|
||||
status, _headers, body = urllib_transport(
|
||||
"GET",
|
||||
f"{source_url}/event.ics",
|
||||
{"Authorization": "Bearer expected"},
|
||||
None,
|
||||
2,
|
||||
)
|
||||
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body, b"calendar")
|
||||
self.assertEqual(forwarded_authorization, ["Bearer expected"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
27
tests/test_capabilities.py
Normal file
27
tests/test_capabilities.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from govoplan_calendar.backend.capabilities import SqlCalendarSchedulingProvider
|
||||
from govoplan_core.core.calendar import CalendarCapabilityError, CalendarEventRequest
|
||||
|
||||
|
||||
class CalendarSchedulingCapabilityTests(unittest.TestCase):
|
||||
def test_event_request_validation_is_exposed_as_capability_error(self) -> None:
|
||||
provider = SqlCalendarSchedulingProvider()
|
||||
|
||||
with self.assertRaises(CalendarCapabilityError):
|
||||
provider.create_event(
|
||||
object(),
|
||||
tenant_id="tenant-1",
|
||||
user_id="user-1",
|
||||
request=CalendarEventRequest(
|
||||
summary="x" * 501,
|
||||
start_at=datetime(2026, 7, 20, 9, tzinfo=timezone.utc),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
90
tests/test_http_security.py
Normal file
90
tests/test_http_security.py
Normal file
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import threading
|
||||
import unittest
|
||||
from collections.abc import Iterator
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from govoplan_calendar.backend.service import CalendarError, http_request
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def running_http_server(handler: type[BaseHTTPRequestHandler]) -> Iterator[str]:
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
host, port = server.server_address
|
||||
yield f"http://{host}:{port}"
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=2)
|
||||
|
||||
|
||||
class CalendarHttpSecurityTests(unittest.TestCase):
|
||||
def test_cross_origin_redirect_does_not_forward_authorization(self) -> None:
|
||||
forwarded_authorization: list[str | None] = []
|
||||
|
||||
class TargetHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
forwarded_authorization.append(self.headers.get("Authorization"))
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, _format: str, *_args: object) -> None:
|
||||
return
|
||||
|
||||
with running_http_server(TargetHandler) as target_url:
|
||||
class RedirectHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
self.send_response(302)
|
||||
self.send_header("Location", f"{target_url}/stolen")
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, _format: str, *_args: object) -> None:
|
||||
return
|
||||
|
||||
with running_http_server(RedirectHandler) as source_url:
|
||||
with self.assertRaisesRegex(CalendarError, "HTTP 302"):
|
||||
http_request(
|
||||
f"{source_url}/feed",
|
||||
headers={"Authorization": "Bearer top-secret"},
|
||||
timeout=2,
|
||||
)
|
||||
|
||||
self.assertEqual(forwarded_authorization, [])
|
||||
|
||||
def test_same_origin_redirect_remains_supported(self) -> None:
|
||||
forwarded_authorization: list[str | None] = []
|
||||
|
||||
class RedirectHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API
|
||||
if self.path == "/feed":
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "/calendar.ics")
|
||||
self.end_headers()
|
||||
return
|
||||
forwarded_authorization.append(self.headers.get("Authorization"))
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"calendar")
|
||||
|
||||
def log_message(self, _format: str, *_args: object) -> None:
|
||||
return
|
||||
|
||||
with running_http_server(RedirectHandler) as source_url:
|
||||
status, _headers, body = http_request(
|
||||
f"{source_url}/feed",
|
||||
headers={"Authorization": "Bearer expected"},
|
||||
timeout=2,
|
||||
)
|
||||
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body, "calendar")
|
||||
self.assertEqual(forwarded_authorization, ["Bearer expected"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
1819
tests/test_outbox.py
Normal file
1819
tests/test_outbox.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -6,7 +6,7 @@ from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from govoplan_calendar.backend.schemas import CalendarCollectionDeleteRequest, CalendarEventResponse
|
||||
from govoplan_calendar.backend.service import delete_calendar, event_response
|
||||
from govoplan_calendar.backend.service import calendar_is_visible_to_principal, delete_calendar, event_response
|
||||
|
||||
|
||||
class FakeSession:
|
||||
@@ -65,6 +65,67 @@ class CalendarServiceResponseTests(unittest.TestCase):
|
||||
self.assertEqual(response.start_at.tzinfo, timezone.utc)
|
||||
|
||||
|
||||
class CalendarVisibilityTests(unittest.TestCase):
|
||||
@staticmethod
|
||||
def calendar(**overrides):
|
||||
values = {
|
||||
"visibility": "private",
|
||||
"owner_type": "user",
|
||||
"owner_id": "owner-1",
|
||||
"created_by_user_id": "creator-1",
|
||||
}
|
||||
values.update(overrides)
|
||||
return SimpleNamespace(**values)
|
||||
|
||||
def test_tenant_shared_and_public_calendars_are_visible_to_readers(self) -> None:
|
||||
for visibility in ("tenant", "shared", "public"):
|
||||
with self.subTest(visibility=visibility):
|
||||
self.assertTrue(
|
||||
calendar_is_visible_to_principal(
|
||||
self.calendar(visibility=visibility),
|
||||
user_id="reader-1",
|
||||
)
|
||||
)
|
||||
|
||||
def test_private_calendar_is_visible_to_user_owner_creator_or_group_member(self) -> None:
|
||||
self.assertTrue(
|
||||
calendar_is_visible_to_principal(
|
||||
self.calendar(),
|
||||
user_id="owner-1",
|
||||
)
|
||||
)
|
||||
self.assertTrue(
|
||||
calendar_is_visible_to_principal(
|
||||
self.calendar(),
|
||||
user_id="creator-1",
|
||||
)
|
||||
)
|
||||
self.assertTrue(
|
||||
calendar_is_visible_to_principal(
|
||||
self.calendar(owner_type="group", owner_id="group-1"),
|
||||
user_id="member-1",
|
||||
group_ids=("group-1",),
|
||||
)
|
||||
)
|
||||
|
||||
def test_private_calendar_is_hidden_from_other_readers_but_visible_to_admin(self) -> None:
|
||||
calendar = self.calendar()
|
||||
self.assertFalse(
|
||||
calendar_is_visible_to_principal(
|
||||
calendar,
|
||||
user_id="other-1",
|
||||
group_ids=("group-2",),
|
||||
)
|
||||
)
|
||||
self.assertTrue(
|
||||
calendar_is_visible_to_principal(
|
||||
calendar,
|
||||
user_id="other-1",
|
||||
can_admin=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class CalendarServiceDeleteTests(unittest.TestCase):
|
||||
def test_delete_default_calendar_soft_deletes_calendar_and_events(self) -> None:
|
||||
session = FakeSession()
|
||||
|
||||
@@ -11,7 +11,7 @@ from sqlalchemy.orm import sessionmaker
|
||||
from govoplan_access.backend.db import models as access_models # noqa: F401 - populate users/accounts tables
|
||||
from govoplan_calendar.backend.db.models import CalendarEvent
|
||||
from govoplan_calendar.backend.schemas import CalendarCollectionCreateRequest, CalendarEventCreateRequest, CalendarSyncSourceCreateRequest
|
||||
from govoplan_calendar.backend.service import CalendarError, create_calendar, create_event, create_sync_source, sync_source
|
||||
from govoplan_calendar.backend.service import CalendarError, create_calendar, create_event, create_sync_source, soft_delete_unseen_source_events, sync_source
|
||||
from govoplan_core.db.base import Base
|
||||
from govoplan_core.tenancy.scope import create_scope_tables
|
||||
from govoplan_tenancy.backend.db.models import Tenant
|
||||
@@ -23,12 +23,17 @@ class CalendarSyncSourceTests(unittest.TestCase):
|
||||
create_scope_tables(self.engine)
|
||||
Base.metadata.create_all(bind=self.engine)
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
self.sessions = []
|
||||
|
||||
def tearDown(self) -> None:
|
||||
for session in reversed(self.sessions):
|
||||
session.close()
|
||||
Base.metadata.drop_all(bind=self.engine)
|
||||
self.engine.dispose()
|
||||
|
||||
def session_with_calendar(self):
|
||||
session = self.Session()
|
||||
self.sessions.append(session)
|
||||
session.add(Tenant(id="tenant-1", slug="tenant-1", name="Tenant"))
|
||||
calendar = create_calendar(session, tenant_id="tenant-1", user_id=None, payload=CalendarCollectionCreateRequest(name="Remote"))
|
||||
session.flush()
|
||||
@@ -78,6 +83,55 @@ END:VCALENDAR
|
||||
),
|
||||
)
|
||||
|
||||
def test_ics_not_modified_sync_clears_error_and_reschedules(self) -> None:
|
||||
session, calendar = self.session_with_calendar()
|
||||
source = create_sync_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarSyncSourceCreateRequest(
|
||||
source_kind="ics",
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://calendar.example.test/feed.ics",
|
||||
),
|
||||
)
|
||||
source.ctag = '"feed-1"'
|
||||
source.last_status = "error"
|
||||
source.last_error = "previous failure"
|
||||
|
||||
with patch("govoplan_calendar.backend.service.http_request", return_value=(304, {}, "")):
|
||||
refreshed, stats = sync_source(session, tenant_id="tenant-1", user_id=None, source_id=source.id)
|
||||
|
||||
self.assertEqual(refreshed.last_status, "ok")
|
||||
self.assertIsNone(refreshed.last_error)
|
||||
self.assertIsNotNone(refreshed.last_synced_at)
|
||||
self.assertIsNotNone(refreshed.next_sync_at)
|
||||
self.assertEqual(stats.created, 0)
|
||||
self.assertEqual(stats.updated, 0)
|
||||
self.assertEqual(stats.deleted, 0)
|
||||
|
||||
def test_ics_sync_failure_records_error_and_reschedules(self) -> None:
|
||||
session, calendar = self.session_with_calendar()
|
||||
source = create_sync_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarSyncSourceCreateRequest(
|
||||
source_kind="ics",
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://calendar.example.test/feed.ics",
|
||||
),
|
||||
)
|
||||
|
||||
with patch("govoplan_calendar.backend.service.http_request", side_effect=RuntimeError("network down")):
|
||||
with self.assertRaisesRegex(RuntimeError, "network down"):
|
||||
sync_source(session, tenant_id="tenant-1", user_id=None, source_id=source.id)
|
||||
|
||||
self.assertEqual(source.last_status, "error")
|
||||
self.assertIn("network down", source.last_error or "")
|
||||
self.assertIsNotNone(source.last_attempt_at)
|
||||
self.assertIsNotNone(source.next_sync_at)
|
||||
|
||||
def test_graph_sync_imports_delta_events(self) -> None:
|
||||
session, calendar = self.session_with_calendar()
|
||||
source = create_sync_source(
|
||||
@@ -117,6 +171,74 @@ END:VCALENDAR
|
||||
self.assertEqual(event.summary, "Graph item")
|
||||
self.assertIn("Bearer graph-token", request.call_args.kwargs["headers"]["Authorization"])
|
||||
|
||||
def test_graph_sync_rejects_cross_origin_continuation_url(self) -> None:
|
||||
session, calendar = self.session_with_calendar()
|
||||
source = create_sync_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarSyncSourceCreateRequest(
|
||||
source_kind="graph",
|
||||
calendar_id=calendar.id,
|
||||
collection_url="me/calendar",
|
||||
auth_type="bearer",
|
||||
bearer_token="graph-token",
|
||||
),
|
||||
)
|
||||
payload = {
|
||||
"value": [],
|
||||
"@odata.nextLink": "https://attacker.example.test/collect?token=secret",
|
||||
}
|
||||
|
||||
with patch(
|
||||
"govoplan_calendar.backend.service.http_request",
|
||||
return_value=(200, {}, json.dumps(payload)),
|
||||
) as request:
|
||||
with self.assertRaisesRegex(CalendarError, "configured source origin"):
|
||||
sync_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
source_id=source.id,
|
||||
)
|
||||
|
||||
self.assertEqual(request.call_count, 1)
|
||||
self.assertEqual(source.last_status, "error")
|
||||
|
||||
def test_graph_sync_rejects_cross_origin_delta_url(self) -> None:
|
||||
session, calendar = self.session_with_calendar()
|
||||
source = create_sync_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarSyncSourceCreateRequest(
|
||||
source_kind="graph",
|
||||
calendar_id=calendar.id,
|
||||
collection_url="me/calendar",
|
||||
auth_type="bearer",
|
||||
bearer_token="graph-token",
|
||||
),
|
||||
)
|
||||
payload = {
|
||||
"value": [],
|
||||
"@odata.deltaLink": "https://attacker.example.test/collect?token=secret",
|
||||
}
|
||||
|
||||
with patch(
|
||||
"govoplan_calendar.backend.service.http_request",
|
||||
return_value=(200, {}, json.dumps(payload)),
|
||||
) as request:
|
||||
with self.assertRaisesRegex(CalendarError, "configured source origin"):
|
||||
sync_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
source_id=source.id,
|
||||
)
|
||||
|
||||
self.assertEqual(request.call_count, 1)
|
||||
self.assertEqual(source.last_status, "error")
|
||||
|
||||
def test_ews_sync_imports_calendar_view_items(self) -> None:
|
||||
session, calendar = self.session_with_calendar()
|
||||
source = create_sync_source(
|
||||
@@ -168,6 +290,59 @@ END:VCALENDAR
|
||||
self.assertEqual(event.summary, "EWS item")
|
||||
self.assertTrue(request.call_args.kwargs["body"].startswith("<?xml"))
|
||||
|
||||
def test_full_sync_cleanup_soft_deletes_unseen_events_in_batches(self) -> None:
|
||||
session, calendar = self.session_with_calendar()
|
||||
source = create_sync_source(
|
||||
session,
|
||||
tenant_id="tenant-1",
|
||||
user_id=None,
|
||||
payload=CalendarSyncSourceCreateRequest(
|
||||
source_kind="ics",
|
||||
calendar_id=calendar.id,
|
||||
collection_url="https://calendar.example.test/events.ics",
|
||||
),
|
||||
)
|
||||
for index in range(3):
|
||||
session.add(
|
||||
CalendarEvent(
|
||||
tenant_id="tenant-1",
|
||||
calendar_id=calendar.id,
|
||||
uid=f"event-{index}@example.test",
|
||||
recurrence_id=None,
|
||||
summary=f"Event {index}",
|
||||
status="CONFIRMED",
|
||||
transparency="OPAQUE",
|
||||
classification="PUBLIC",
|
||||
start_at=datetime(2026, 7, 8, 9 + index, tzinfo=timezone.utc),
|
||||
all_day=False,
|
||||
attendees=[],
|
||||
categories=[],
|
||||
rdate=[],
|
||||
exdate=[],
|
||||
reminders=[],
|
||||
attachments=[],
|
||||
related_to=[],
|
||||
source_kind="ics",
|
||||
source_href=f"ics-event-{index}",
|
||||
icalendar={},
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
|
||||
deleted = soft_delete_unseen_source_events(
|
||||
session,
|
||||
source=source,
|
||||
seen_hrefs={"ics-event-1"},
|
||||
batch_size=1,
|
||||
)
|
||||
|
||||
active_hrefs = {
|
||||
event.source_href
|
||||
for event in session.query(CalendarEvent).filter(CalendarEvent.deleted_at.is_(None)).all()
|
||||
}
|
||||
self.assertEqual(deleted, 2)
|
||||
self.assertEqual(active_hrefs, {"ics-event-1"})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@govoplan/calendar-webui",
|
||||
"version": "0.1.7",
|
||||
"version": "0.1.8",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
@@ -13,12 +13,16 @@
|
||||
},
|
||||
"./styles/calendar.css": "./src/styles/calendar.css"
|
||||
},
|
||||
"scripts": {
|
||||
"test:calendar-picker": "rm -rf .calendar-picker-test-build && mkdir -p .calendar-picker-test-build && printf '{\"type\":\"commonjs\"}\\n' > .calendar-picker-test-build/package.json && tsc -p tsconfig.calendar-picker-tests.json && node .calendar-picker-test-build/tests/calendar-picker.test.js && node tests/calendar-picker-structure.test.mjs",
|
||||
"test:calendar-page": "tsc -p tsconfig.calendar-page-tests.json && node --experimental-strip-types tests/calendar-view-model.test.ts && node tests/calendar-page-structure.test.mjs"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@govoplan/core-webui": "^0.1.7",
|
||||
"@govoplan/core-webui": "^0.1.9",
|
||||
"lucide-react": "^1.23.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-router-dom": "^7.1.1",
|
||||
"react-router-dom": ">=7.18.2 <8",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^6.0.6"
|
||||
|
||||
@@ -78,7 +78,7 @@ export type CalendarSyncSource = {
|
||||
display_name?: string | null;
|
||||
auth_type: CalendarCalDavAuthType;
|
||||
username?: string | null;
|
||||
credential_ref?: string | null;
|
||||
credential_envelope_id?: string | null;
|
||||
has_credential: boolean;
|
||||
sync_enabled: boolean;
|
||||
sync_interval_seconds: number;
|
||||
@@ -143,6 +143,26 @@ export type CalendarCalDavSourceCreatePayload = CalendarSyncSourceCreatePayload;
|
||||
export type CalendarCalDavSourceUpdatePayload = Partial<CalendarCalDavSourceCreatePayload>;
|
||||
export type CalendarSyncSourceUpdatePayload = Partial<CalendarSyncSourceCreatePayload>;
|
||||
|
||||
export type CalendarCredentialEnvelope = {
|
||||
id: string;
|
||||
scope_type: string;
|
||||
scope_id?: string | null;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
credential_kind: string;
|
||||
public_data: Record<string, unknown>;
|
||||
secret_keys: string[];
|
||||
secret_configured: boolean;
|
||||
allowed_modules: string[];
|
||||
inherit_to_lower_scopes: boolean;
|
||||
is_active: boolean;
|
||||
revision: string;
|
||||
};
|
||||
|
||||
export type CalendarCredentialEnvelopeListResponse = {
|
||||
credentials: CalendarCredentialEnvelope[];
|
||||
};
|
||||
|
||||
export type CalendarSyncSourceSyncPayload = {
|
||||
password?: string | null;
|
||||
bearer_token?: string | null;
|
||||
@@ -182,10 +202,12 @@ export type CalendarCollectionCreatePayload = {
|
||||
|
||||
export type CalendarCollectionUpdatePayload = Partial<CalendarCollectionCreatePayload>;
|
||||
export type CalendarDeleteEventAction = "delete" | "move";
|
||||
export type CalendarBulkMoveExternalAction = "detach_keep_remote" | "copy_to_remote" | "remote_move";
|
||||
export type CalendarCollectionDeletePayload = {
|
||||
event_action?: CalendarDeleteEventAction;
|
||||
target_calendar_id?: string | null;
|
||||
make_target_default?: boolean;
|
||||
external_action?: CalendarBulkMoveExternalAction | null;
|
||||
};
|
||||
|
||||
export type CalendarEventCreatePayload = {
|
||||
@@ -253,6 +275,13 @@ export function listCalDavSources(settings: ApiSettings, params: { calendar_id?:
|
||||
return apiFetch<CalendarCalDavSourceListResponse>(settings, `/api/v1/calendar/caldav/sources${suffix}`);
|
||||
}
|
||||
|
||||
export function listCalendarCredentials(settings: ApiSettings, sourceId?: string | null): Promise<CalendarCredentialEnvelopeListResponse> {
|
||||
const search = new URLSearchParams();
|
||||
if (sourceId) search.set("source_id", sourceId);
|
||||
const suffix = search.toString() ? `?${search.toString()}` : "";
|
||||
return apiFetch<CalendarCredentialEnvelopeListResponse>(settings, `/api/v1/calendar/credentials${suffix}`);
|
||||
}
|
||||
|
||||
export function discoverCalDavCalendars(settings: ApiSettings, payload: CalendarCalDavDiscoveryPayload): Promise<CalendarCalDavDiscoveryResponse> {
|
||||
return apiFetch<CalendarCalDavDiscoveryResponse>(settings, "/api/v1/calendar/caldav/discover", { method: "POST", body: JSON.stringify(payload) });
|
||||
}
|
||||
|
||||
827
webui/src/features/calendar/CalendarCollectionDialogs.tsx
Normal file
827
webui/src/features/calendar/CalendarCollectionDialogs.tsx
Normal file
@@ -0,0 +1,827 @@
|
||||
import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ChangeEvent,
|
||||
type FormEvent,
|
||||
} from "react";
|
||||
import { RefreshCw, Trash2 } from "lucide-react";
|
||||
import {
|
||||
Button,
|
||||
ColorPickerField,
|
||||
Dialog,
|
||||
PasswordField,
|
||||
SegmentedControl,
|
||||
ToggleSwitch,
|
||||
i18nMessage,
|
||||
useUnsavedDraftGuard,
|
||||
type ApiSettings,
|
||||
} from "@govoplan/core-webui";
|
||||
import {
|
||||
listCalendarCredentials,
|
||||
type CalendarBulkMoveExternalAction,
|
||||
type CalendarCalDavAuthType,
|
||||
type CalendarCalDavConflictPolicy,
|
||||
type CalendarCalDavDiscoveryCandidate,
|
||||
type CalendarCalDavDiscoveryPayload,
|
||||
type CalendarCalDavSyncDirection,
|
||||
type CalendarCollection,
|
||||
type CalendarCollectionDeletePayload,
|
||||
type CalendarCredentialEnvelope,
|
||||
type CalendarDeleteEventAction,
|
||||
type CalendarSyncSource,
|
||||
type CalendarSyncSourceCreatePayload,
|
||||
type CalendarSyncSourceKind,
|
||||
type CalendarSyncSourceUpdatePayload,
|
||||
} from "../../api/calendar";
|
||||
import {
|
||||
DEFAULT_CALENDAR_COLOR,
|
||||
calendarDraftKey,
|
||||
dateTimeLabel,
|
||||
errorText,
|
||||
normalizeHexColor,
|
||||
} from "./calendarViewModel";
|
||||
|
||||
export type CalendarSourceMode = "local" | CalendarSyncSourceKind;
|
||||
type CalendarSourceSwitchMode =
|
||||
| "local"
|
||||
| "caldav"
|
||||
| "ics"
|
||||
| "graph"
|
||||
| "ews";
|
||||
export type CalendarCollectionDialogState =
|
||||
| { kind: "create" }
|
||||
| {
|
||||
kind: "edit";
|
||||
calendar: CalendarCollection;
|
||||
eventCount: number | null;
|
||||
loadingEventCount: boolean;
|
||||
};
|
||||
export type CalendarDeleteDialogState = {
|
||||
calendar: CalendarCollection;
|
||||
eventCount: number | null;
|
||||
loadingEventCount: boolean;
|
||||
};
|
||||
export type CalendarCalDavFormPayload = {
|
||||
collection_url: string;
|
||||
dav_url: string;
|
||||
display_name: string;
|
||||
auth_type: CalendarCalDavAuthType;
|
||||
username: string;
|
||||
credential_envelope_id: string;
|
||||
password: string;
|
||||
bearer_token: string;
|
||||
sync_enabled: boolean;
|
||||
sync_interval_seconds: number;
|
||||
sync_direction: CalendarCalDavSyncDirection;
|
||||
conflict_policy: CalendarCalDavConflictPolicy;
|
||||
};
|
||||
export type CalendarCollectionFormPayload = {
|
||||
sourceMode: CalendarSourceMode;
|
||||
name: string;
|
||||
color: string;
|
||||
caldav: CalendarCalDavFormPayload;
|
||||
};
|
||||
|
||||
export function CalendarCollectionDialog({
|
||||
state,
|
||||
settings,
|
||||
source,
|
||||
saving,
|
||||
syncingSourceId,
|
||||
canWrite,
|
||||
canDelete,
|
||||
canManageSources,
|
||||
canSyncSources,
|
||||
onCancel,
|
||||
onSave,
|
||||
onRequestDelete,
|
||||
onSync,
|
||||
onDiscover
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}: {state: CalendarCollectionDialogState;settings: ApiSettings;source: CalendarSyncSource | null;saving: boolean;syncingSourceId: string;canWrite: boolean;canDelete: boolean;canManageSources: boolean;canSyncSources: boolean;onCancel: () => void;onSave: (payload: CalendarCollectionFormPayload) => Promise<boolean>;onRequestDelete: (calendar: CalendarCollection, eventCount: number | null, loadingEventCount: boolean) => void;onSync: (source: CalendarSyncSource, payload?: {password?: string | null;bearer_token?: string | null;force_full?: boolean;}) => Promise<void>;onDiscover: (payload: CalendarCalDavDiscoveryPayload) => Promise<{calendars: CalendarCalDavDiscoveryCandidate[];}>;}) {
|
||||
const calendar = state.kind === "edit" ? state.calendar : null;
|
||||
const isEdit = Boolean(calendar);
|
||||
const [sourceMode, setSourceMode] = useState<CalendarSourceMode>(source ? source.source_kind : "local");
|
||||
const [name, setName] = useState(calendar?.name ?? "");
|
||||
const [color, setColor] = useState(normalizeHexColor(calendar?.color) || DEFAULT_CALENDAR_COLOR);
|
||||
const [davUrl, setDavUrl] = useState(source?.collection_url ?? "");
|
||||
const [collectionUrl, setCollectionUrl] = useState(source?.collection_url ?? "");
|
||||
const [displayName, setDisplayName] = useState(source?.display_name ?? "");
|
||||
const [authType, setAuthType] = useState<CalendarCalDavAuthType>(source?.auth_type ?? "basic");
|
||||
const [username, setUsername] = useState(source?.username ?? "");
|
||||
const [credentialEnvelopeId, setCredentialEnvelopeId] = useState(source?.credential_envelope_id ?? "");
|
||||
const [availableCredentials, setAvailableCredentials] = useState<CalendarCredentialEnvelope[]>([]);
|
||||
const [credentialsError, setCredentialsError] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [bearerToken, setBearerToken] = useState("");
|
||||
const [syncEnabled, setSyncEnabled] = useState(source?.sync_enabled ?? true);
|
||||
const [syncIntervalMinutes, setSyncIntervalMinutes] = useState(Math.max(1, Math.round((source?.sync_interval_seconds ?? 900) / 60)));
|
||||
const [syncDirection, setSyncDirection] = useState<CalendarCalDavSyncDirection>(source?.sync_direction ?? "two_way");
|
||||
const [conflictPolicy, setConflictPolicy] = useState<CalendarCalDavConflictPolicy>(source?.conflict_policy ?? "etag");
|
||||
const [discoveredCalendars, setDiscoveredCalendars] = useState<CalendarCalDavDiscoveryCandidate[]>([]);
|
||||
const [selectedDiscoveredUrl, setSelectedDiscoveredUrl] = useState(source?.collection_url ?? "");
|
||||
const [discovering, setDiscovering] = useState(false);
|
||||
const [discoveryError, setDiscoveryError] = useState("");
|
||||
const formId = "calendar-collection-form";
|
||||
const isExistingSyncSource = isEdit && Boolean(source);
|
||||
const canEditSource = canManageSources;
|
||||
const canEditMutableSourceSettings = canEditSource && !isExistingSyncSource;
|
||||
const effectiveCollectionUrl = (collectionUrl || davUrl).trim();
|
||||
const effectiveAuthType = sourceMode === "graph" ? "bearer" : authType;
|
||||
const needsSourceSecret = sourceMode !== "local" && (
|
||||
effectiveAuthType === "basic" && !source?.has_credential && !credentialEnvelopeId && !password.trim() ||
|
||||
effectiveAuthType === "bearer" && !source?.has_credential && !credentialEnvelopeId && !bearerToken.trim());
|
||||
|
||||
const sourceDetailsInvalid = sourceMode !== "local" && (
|
||||
!isExistingSyncSource && !canEditSource ||
|
||||
canEditSource && (!effectiveCollectionUrl || effectiveAuthType === "basic" && !username.trim() || needsSourceSecret));
|
||||
|
||||
const saveDisabled =
|
||||
saving ||
|
||||
!canWrite ||
|
||||
!name.trim() ||
|
||||
sourceDetailsInvalid;
|
||||
|
||||
const syncing = source ? syncingSourceId === source.id : false;
|
||||
|
||||
const collectionDraft = {
|
||||
sourceMode,
|
||||
name,
|
||||
color,
|
||||
davUrl,
|
||||
collectionUrl,
|
||||
displayName,
|
||||
authType,
|
||||
username,
|
||||
credentialEnvelopeId,
|
||||
password,
|
||||
bearerToken,
|
||||
syncEnabled,
|
||||
syncIntervalMinutes,
|
||||
syncDirection,
|
||||
conflictPolicy
|
||||
};
|
||||
const initialCollectionDraftKey = useMemo(() => calendarDraftKey(collectionDraft), []);
|
||||
const collectionDirty = calendarDraftKey(collectionDraft) !== initialCollectionDraftKey;
|
||||
|
||||
useUnsavedDraftGuard({
|
||||
dirty: collectionDirty,
|
||||
onSave: saveCurrent,
|
||||
onDiscard: onCancel
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (sourceMode === "local" || !canManageSources) {
|
||||
setAvailableCredentials([]);
|
||||
setCredentialsError("");
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
listCalendarCredentials(settings, source?.id)
|
||||
.then((response) => {
|
||||
if (active) setAvailableCredentials(response.credentials);
|
||||
})
|
||||
.catch((err) => {
|
||||
if (active) {
|
||||
setAvailableCredentials([]);
|
||||
setCredentialsError(errorText(err));
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [canManageSources, settings.accessToken, settings.apiBaseUrl, settings.apiKey, source?.id, sourceMode]);
|
||||
|
||||
function currentPayload(): CalendarCollectionFormPayload {
|
||||
return {
|
||||
sourceMode,
|
||||
name,
|
||||
color,
|
||||
caldav: {
|
||||
collection_url: effectiveCollectionUrl,
|
||||
dav_url: davUrl,
|
||||
display_name: displayName,
|
||||
auth_type: effectiveAuthType,
|
||||
username,
|
||||
credential_envelope_id: credentialEnvelopeId,
|
||||
password,
|
||||
bearer_token: bearerToken,
|
||||
sync_enabled: syncEnabled,
|
||||
sync_interval_seconds: syncIntervalMinutes * 60,
|
||||
sync_direction: syncDirection,
|
||||
conflict_policy: conflictPolicy
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function saveCurrent(): Promise<boolean> {
|
||||
if (saveDisabled) return false;
|
||||
return onSave(currentPayload());
|
||||
}
|
||||
|
||||
function submit(formEvent: FormEvent<HTMLFormElement>) {
|
||||
formEvent.preventDefault();
|
||||
void saveCurrent();
|
||||
}
|
||||
|
||||
function selectSourceMode(next: CalendarSourceMode) {
|
||||
setSourceMode(next);
|
||||
setDiscoveryError("");
|
||||
setDiscoveredCalendars([]);
|
||||
if (next === "graph") {
|
||||
setAuthType("bearer");
|
||||
setSyncDirection("inbound");
|
||||
if (!davUrl.trim()) handleDavUrlChange("me/calendar");
|
||||
return;
|
||||
}
|
||||
if (next === "ews") {
|
||||
setAuthType("basic");
|
||||
setSyncDirection("inbound");
|
||||
if (!davUrl.trim()) handleDavUrlChange("https://exchange.example.org/EWS/Exchange.asmx");
|
||||
return;
|
||||
}
|
||||
if (next === "ics" || next === "webcal") {
|
||||
setAuthType("none");
|
||||
setSyncDirection("inbound");
|
||||
return;
|
||||
}
|
||||
if (next === "caldav") {
|
||||
setSyncDirection("two_way");
|
||||
}
|
||||
}
|
||||
|
||||
function handleDavUrlChange(next: string) {
|
||||
setDavUrl(next);
|
||||
setCollectionUrl(next);
|
||||
setSelectedDiscoveredUrl("");
|
||||
setDiscoveredCalendars([]);
|
||||
setDiscoveryError("");
|
||||
}
|
||||
|
||||
function applyDiscoveredCalendar(candidate: CalendarCalDavDiscoveryCandidate) {
|
||||
setSelectedDiscoveredUrl(candidate.collection_url);
|
||||
setCollectionUrl(candidate.collection_url);
|
||||
if (candidate.display_name) {
|
||||
if (!isExistingSyncSource) setDisplayName(candidate.display_name);
|
||||
if (!isEdit && !name.trim()) setName(candidate.display_name);
|
||||
}
|
||||
const discoveredColor = normalizeHexColor(candidate.color);
|
||||
if (!isEdit && discoveredColor) setColor(discoveredColor);
|
||||
}
|
||||
|
||||
function handleDiscoveredCalendarChange(event: ChangeEvent<HTMLSelectElement>) {
|
||||
const candidate = discoveredCalendars.find((item) => item.collection_url === event.target.value);
|
||||
if (candidate) applyDiscoveredCalendar(candidate);
|
||||
}
|
||||
|
||||
async function handleDiscover() {
|
||||
const url = davUrl.trim();
|
||||
if (!url) return;
|
||||
setDiscovering(true);
|
||||
setDiscoveryError("");
|
||||
try {
|
||||
const payload: CalendarCalDavDiscoveryPayload = {
|
||||
url,
|
||||
source_id: source?.id ?? null,
|
||||
auth_type: authType,
|
||||
username: authType === "basic" ? username.trim() || null : null
|
||||
};
|
||||
if (credentialEnvelopeId) payload.credential_ref = credentialEnvelopeRef(credentialEnvelopeId);
|
||||
if (!credentialEnvelopeId && authType === "basic" && password.trim()) payload.password = password;
|
||||
if (!credentialEnvelopeId && authType === "bearer" && bearerToken.trim()) payload.bearer_token = bearerToken;
|
||||
const response = await onDiscover(payload);
|
||||
setDiscoveredCalendars(response.calendars);
|
||||
if (response.calendars.length > 0) {
|
||||
applyDiscoveredCalendar(response.calendars[0]);
|
||||
} else {
|
||||
setDiscoveryError("i18n:govoplan-calendar.no_calendar_collections_found.6453624a");
|
||||
}
|
||||
} catch (err) {
|
||||
setDiscoveryError(errorText(err));
|
||||
} finally {
|
||||
setDiscovering(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title={isEdit ? "i18n:govoplan-calendar.edit_calendar.a47a2a7a" : "i18n:govoplan-calendar.add_calendar.8fadb5bc"}
|
||||
className="calendar-event-dialog"
|
||||
footerClassName="calendar-event-dialog-footer"
|
||||
closeDisabled={saving}
|
||||
onClose={onCancel}
|
||||
footer={
|
||||
<>
|
||||
<div>
|
||||
{calendar && canDelete &&
|
||||
<Button type="button" variant="danger" onClick={() => onRequestDelete(calendar, state.kind === "edit" ? state.eventCount : null, state.kind === "edit" ? state.loadingEventCount : true)} disabled={saving}>
|
||||
<Trash2 size={16} /> {calendarDeleteActionLabel(calendar)}
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
<div className="calendar-dialog-actions">
|
||||
<Button type="button" onClick={onCancel} disabled={saving}>i18n:govoplan-calendar.cancel.77dfd213</Button>
|
||||
<Button type="submit" form={formId} variant="primary" disabled={saveDisabled}>{saving ? "i18n:govoplan-calendar.saving.ae7e8875" : isEdit ? "i18n:govoplan-calendar.save.efc007a3" : "i18n:govoplan-calendar.add.61cc55aa"}</Button>
|
||||
</div>
|
||||
</>
|
||||
}>
|
||||
|
||||
<form id={formId} className="calendar-dialog-form" onSubmit={submit}>
|
||||
{sourceMode !== "local" && !canManageSources && <p className="calendar-form-note">i18n:govoplan-calendar.managing_sync_sources_requires_calendar_administ.835e29fa</p>}
|
||||
{!isEdit &&
|
||||
<SegmentedControl
|
||||
className="calendar-source-switch"
|
||||
size="equal"
|
||||
width="fill"
|
||||
ariaLabel="i18n:govoplan-calendar.calendar_source_type.92cdb42f"
|
||||
value={sourceSwitchMode(sourceMode)}
|
||||
disabled={saving}
|
||||
onChange={selectSourceMode}
|
||||
options={[
|
||||
{ id: "local", label: "i18n:govoplan-calendar.local.dc99d54d" },
|
||||
{ id: "caldav", label: "i18n:govoplan-calendar.caldav.64f9720e", disabled: !canManageSources },
|
||||
{ id: "ics", label: "i18n:govoplan-calendar.ics_webcal.9c55b570", disabled: !canManageSources },
|
||||
{ id: "graph", label: "i18n:govoplan-calendar.graph.9a7405eb", disabled: !canManageSources },
|
||||
{ id: "ews", label: "i18n:govoplan-calendar.exchange.5b13eac7", disabled: !canManageSources }
|
||||
]}
|
||||
/>
|
||||
}
|
||||
<div className="calendar-dialog-name-color-row">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.name.709a2322</span>
|
||||
<input value={name} onChange={(item) => setName(item.target.value)} required maxLength={255} autoFocus disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label className="calendar-dialog-color-label">
|
||||
<span>i18n:govoplan-calendar.color.1d0c8304</span>
|
||||
<ColorPickerField value={color} onChange={setColor} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
{sourceMode === "local" ?
|
||||
<section className="calendar-source-pane">
|
||||
<h3>i18n:govoplan-calendar.local_calendar.ed3f72f8</h3>
|
||||
<p className="calendar-form-note">i18n:govoplan-calendar.events_are_stored_in_govoplan_and_are_not_synced.3660e504</p>
|
||||
</section> :
|
||||
|
||||
<section className="calendar-source-pane">
|
||||
<div className="calendar-source-pane-heading">
|
||||
<h3>{calendarSourcePaneTitle(sourceMode)}</h3>
|
||||
{source &&
|
||||
<span className={[
|
||||
"calendar-sync-status",
|
||||
syncing ? "is-syncing" : "",
|
||||
source.last_status === "error" && !syncing ? "is-error" : ""].
|
||||
filter(Boolean).join(" ")}>
|
||||
{syncing ? "i18n:govoplan-calendar.syncing.4ae6fa22" : source.last_status || "i18n:govoplan-calendar.not_synced.4c205136"}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
<div className="calendar-caldav-setup">
|
||||
<label className="calendar-dialog-wide">
|
||||
<span>{calendarSourceUrlLabel(sourceMode)}</span>
|
||||
<input
|
||||
value={davUrl}
|
||||
onChange={(item) => handleDavUrlChange(item.target.value)}
|
||||
placeholder={calendarSourceUrlPlaceholder(sourceMode)}
|
||||
required
|
||||
maxLength={1000}
|
||||
disabled={saving || !canEditSource} />
|
||||
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.authentication.ee1acfa5</span>
|
||||
<select value={effectiveAuthType} onChange={(item) => setAuthType(item.target.value as CalendarCalDavAuthType)} disabled={saving || !canEditSource || sourceMode === "graph"}>
|
||||
{sourceMode !== "graph" && <option value="basic">i18n:govoplan-calendar.basic.aa2c96da</option>}
|
||||
{sourceMode !== "graph" && sourceMode !== "ews" && <option value="none">i18n:govoplan-calendar.none.6eef6648</option>}
|
||||
<option value="bearer">i18n:govoplan-calendar.bearer_token.ffa64bcf</option>
|
||||
</select>
|
||||
</label>
|
||||
{effectiveAuthType !== "none" &&
|
||||
<label>
|
||||
<span>Reusable credential</span>
|
||||
<select
|
||||
value={credentialEnvelopeId}
|
||||
disabled={saving || !canEditSource}
|
||||
onChange={(event) => {
|
||||
const credentialId = event.target.value;
|
||||
setCredentialEnvelopeId(credentialId);
|
||||
setPassword("");
|
||||
setBearerToken("");
|
||||
const credential = availableCredentials.find((item) => item.id === credentialId);
|
||||
const credentialUsername = credential?.public_data?.username;
|
||||
if (credentialUsername) setUsername(String(credentialUsername));
|
||||
}}>
|
||||
<option value="">{source?.has_credential && !source.credential_envelope_id ? "Keep source-specific credential" : "Enter credentials below"}</option>
|
||||
{availableCredentials.map((credential) =>
|
||||
<option key={credential.id} value={credential.id}>
|
||||
{credential.name}{credential.public_data?.username ? ` (${String(credential.public_data.username)})` : ""}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
}
|
||||
{credentialsError && <p className="calendar-form-error calendar-dialog-wide">{credentialsError}</p>}
|
||||
{effectiveAuthType === "basic" &&
|
||||
<>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.username.84c29015</span>
|
||||
<input value={username} onChange={(item) => setUsername(item.target.value)} required maxLength={255} disabled={saving || !canEditSource || Boolean(credentialEnvelopeId)} />
|
||||
</label>
|
||||
{!credentialEnvelopeId &&
|
||||
<label>
|
||||
<span>{source?.has_credential ? "i18n:govoplan-calendar.replace_password.3f912c9c" : "i18n:govoplan-calendar.password.8be3c943"}</span>
|
||||
<PasswordField value={password} onValueChange={setPassword} disabled={saving || !canEditSource} autoComplete="new-password" />
|
||||
</label>
|
||||
}
|
||||
</>
|
||||
}
|
||||
{effectiveAuthType === "bearer" && !credentialEnvelopeId &&
|
||||
<label>
|
||||
<span>{source?.has_credential ? "i18n:govoplan-calendar.replace_token.bbeee6a9" : "i18n:govoplan-calendar.bearer_token.ffa64bcf"}</span>
|
||||
<PasswordField value={bearerToken} onValueChange={setBearerToken} disabled={saving || !canEditSource} autoComplete="new-password" />
|
||||
</label>
|
||||
}
|
||||
<div className={sourceMode === "caldav" ? "calendar-discovery-actions" : "calendar-discovery-actions is-readonly"}>
|
||||
{sourceMode === "caldav" &&
|
||||
<Button type="button" onClick={() => void handleDiscover()} disabled={saving || discovering || !canEditSource || !davUrl.trim() || effectiveAuthType === "basic" && !username.trim()}>
|
||||
<RefreshCw size={16} /> {discovering ? "i18n:govoplan-calendar.discovering.1884f689" : "i18n:govoplan-calendar.discover.4827ea22"}
|
||||
</Button>
|
||||
}
|
||||
{effectiveCollectionUrl && <span>{effectiveCollectionUrl}</span>}
|
||||
</div>
|
||||
</div>
|
||||
{discoveryError && <p className="calendar-form-error">{discoveryError}</p>}
|
||||
{sourceMode === "caldav" && discoveredCalendars.length > 0 &&
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.calendar.adab5090</span>
|
||||
<select value={selectedDiscoveredUrl} onChange={handleDiscoveredCalendarChange} disabled={saving || !canEditSource}>
|
||||
{discoveredCalendars.map((candidate) =>
|
||||
<option key={candidate.collection_url} value={candidate.collection_url}>
|
||||
{candidate.display_name || candidate.collection_url}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
}
|
||||
<details className="calendar-advanced-settings">
|
||||
<summary>i18n:govoplan-calendar.advanced.4d064726</summary>
|
||||
<div className="calendar-dialog-grid-two">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.display_name.c7874aaa</span>
|
||||
<input value={displayName} onChange={(item) => setDisplayName(item.target.value)} maxLength={255} disabled={saving || !canEditMutableSourceSettings} />
|
||||
</label>
|
||||
</div>
|
||||
<div className="calendar-sync-settings">
|
||||
<ToggleSwitch label="i18n:govoplan-calendar.automatic_sync.084644b2" checked={syncEnabled} disabled={saving || !canEditMutableSourceSettings} onChange={setSyncEnabled} />
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.interval.011efcd5</span>
|
||||
<input type="number" min={1} step={1} value={syncIntervalMinutes} onChange={(item) => setSyncIntervalMinutes(Math.max(1, Number(item.target.value) || 1))} disabled={saving || !canEditMutableSourceSettings} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.direction.fd8e45ba</span>
|
||||
<select value={sourceMode === "caldav" ? syncDirection : "inbound"} onChange={(item) => setSyncDirection(item.target.value as CalendarCalDavSyncDirection)} disabled={saving || !canEditMutableSourceSettings || sourceMode !== "caldav"}>
|
||||
<option value="two_way">i18n:govoplan-calendar.two_way.ee50a3e6</option>
|
||||
<option value="inbound">i18n:govoplan-calendar.inbound_only.bf4269b0</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.conflict_policy.5810e150</span>
|
||||
<select value={conflictPolicy} onChange={(item) => setConflictPolicy(item.target.value as CalendarCalDavConflictPolicy)} disabled={saving || !canEditMutableSourceSettings || sourceMode !== "caldav"}>
|
||||
<option value="etag">i18n:govoplan-calendar.require_matching_etag.0ab1ffe1</option>
|
||||
<option value="overwrite">i18n:govoplan-calendar.overwrite_remote.39625e32</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</details>
|
||||
{source &&
|
||||
<div className="calendar-sync-status-panel">
|
||||
<dl>
|
||||
<div><dt>i18n:govoplan-calendar.last_attempt.82aee111</dt><dd>{source.last_attempt_at ? dateTimeLabel(new Date(source.last_attempt_at)) : "i18n:govoplan-calendar.never.80c3052d"}</dd></div>
|
||||
<div><dt>i18n:govoplan-calendar.last_sync.ef0ef267</dt><dd>{source.last_synced_at ? dateTimeLabel(new Date(source.last_synced_at)) : "i18n:govoplan-calendar.never.80c3052d"}</dd></div>
|
||||
<div><dt>i18n:govoplan-calendar.next_sync.88c7af72</dt><dd>{source.next_sync_at && source.sync_enabled ? dateTimeLabel(new Date(source.next_sync_at)) : "i18n:govoplan-calendar.not_scheduled.9c367369"}</dd></div>
|
||||
<div><dt>i18n:govoplan-calendar.credential.8bede3ea</dt><dd>{source.has_credential ? "i18n:govoplan-calendar.configured.668c5fff" : "i18n:govoplan-calendar.not_configured.811931bb"}</dd></div>
|
||||
</dl>
|
||||
{source.last_error && <p className="calendar-form-error">{source.last_error}</p>}
|
||||
<div className="calendar-sync-actions">
|
||||
<Button
|
||||
type="button"
|
||||
className={syncing ? "calendar-sync-button is-syncing" : "calendar-sync-button"}
|
||||
onClick={() => void onSync(source, syncTransientPayload(effectiveAuthType, password, bearerToken))}
|
||||
disabled={saving || syncing || !canSyncSources}>
|
||||
|
||||
<RefreshCw size={16} className={syncing ? "calendar-sync-spin" : undefined} /> {syncing ? "i18n:govoplan-calendar.syncing.e5c7727a" : "i18n:govoplan-calendar.sync_now.2b7d938e"}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => void onSync(source, { ...syncTransientPayload(effectiveAuthType, password, bearerToken), force_full: true })} disabled={saving || syncing || !canSyncSources}>
|
||||
i18n:govoplan-calendar.full_sync.21b89c76
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
{needsSourceSecret && <p className="calendar-form-note">i18n:govoplan-calendar.enter_a_password_or_token_for_this_source.74c09a54</p>}
|
||||
</section>
|
||||
}
|
||||
</form>
|
||||
</Dialog>);
|
||||
|
||||
}
|
||||
|
||||
export function CalendarCollectionDeleteDialog({
|
||||
state,
|
||||
calendars,
|
||||
syncSources,
|
||||
saving,
|
||||
onCancel,
|
||||
onDelete
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}: {state: CalendarDeleteDialogState;calendars: CalendarCollection[];syncSources: CalendarSyncSource[];saving: boolean;onCancel: () => void;onDelete: (calendar: CalendarCollection, payload: CalendarCollectionDeletePayload) => Promise<void>;}) {
|
||||
const { calendar, eventCount, loadingEventCount } = state;
|
||||
const syncSourceByCalendarId = new Map(syncSources.map((source) => [source.calendar_id, source]));
|
||||
const source = syncSourceByCalendarId.get(calendar.id) ?? null;
|
||||
const moveTargets = calendars.filter((item) =>
|
||||
item.id !== calendar.id && calendarMoveTargetIsSupported(source, syncSourceByCalendarId.get(item.id) ?? null)
|
||||
);
|
||||
const firstMoveTargetId = moveTargets[0]?.id || "";
|
||||
const hasEvents = (eventCount ?? 0) > 0;
|
||||
const canMoveEvents = hasEvents && moveTargets.length > 0;
|
||||
const [eventAction, setEventAction] = useState<CalendarDeleteEventAction>("delete");
|
||||
const [targetCalendarId, setTargetCalendarId] = useState(firstMoveTargetId);
|
||||
const [makeTargetDefault, setMakeTargetDefault] = useState(calendar.is_default && Boolean(firstMoveTargetId));
|
||||
const effectiveEventAction: CalendarDeleteEventAction = canMoveEvents ? eventAction : "delete";
|
||||
const confirmDisabled = saving || loadingEventCount || canMoveEvents && effectiveEventAction === "move" && !targetCalendarId;
|
||||
const actionLabel = calendarDeleteActionLabel(calendar);
|
||||
const targetSource = syncSourceByCalendarId.get(targetCalendarId) ?? null;
|
||||
const externalAction = calendarBulkMoveExternalAction(source, targetSource);
|
||||
|
||||
function confirm() {
|
||||
void onDelete(calendar, {
|
||||
event_action: effectiveEventAction,
|
||||
target_calendar_id: effectiveEventAction === "move" ? targetCalendarId : null,
|
||||
make_target_default: effectiveEventAction === "move" && calendar.is_default && makeTargetDefault,
|
||||
external_action: effectiveEventAction === "move" ? externalAction : null
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
role="alertdialog"
|
||||
title={`${actionLabel} calendar`}
|
||||
className="calendar-delete-dialog"
|
||||
footerClassName="calendar-event-dialog-footer"
|
||||
closeDisabled={saving}
|
||||
onClose={onCancel}
|
||||
footer={
|
||||
<>
|
||||
<Button type="button" onClick={onCancel} disabled={saving}>i18n:govoplan-calendar.cancel.77dfd213</Button>
|
||||
<Button type="button" variant="danger" onClick={confirm} disabled={confirmDisabled}>
|
||||
<Trash2 size={16} /> {saving ? "i18n:govoplan-calendar.working.049ac820" : actionLabel}
|
||||
</Button>
|
||||
</>
|
||||
}>
|
||||
|
||||
<div className="calendar-delete-dialog-body">
|
||||
<p className="calendar-delete-warning">
|
||||
{loadingEventCount ?
|
||||
"i18n:govoplan-calendar.loading_event_count.716ad3c2" :
|
||||
calendarDeleteWarning(calendar, eventCount ?? 0, effectiveEventAction, targetCalendarId, moveTargets)}
|
||||
</p>
|
||||
{!loadingEventCount && eventCount === null && <p className="calendar-form-note">i18n:govoplan-calendar.event_count_could_not_be_loaded_the_backend_will.163ff055</p>}
|
||||
{canMoveEvents &&
|
||||
<fieldset className="calendar-delete-options" disabled={saving || loadingEventCount}>
|
||||
<legend>{eventCount} event{eventCount === 1 ? "" : "s"}</legend>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
name="calendar-delete-event-action"
|
||||
value="delete"
|
||||
checked={eventAction === "delete"}
|
||||
onChange={() => setEventAction("delete")} />
|
||||
|
||||
<span>{calendarEventDeleteOptionLabel(calendar)}</span>
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
name="calendar-delete-event-action"
|
||||
value="move"
|
||||
checked={eventAction === "move"}
|
||||
onChange={() => setEventAction("move")} />
|
||||
|
||||
<span>{calendarBulkMoveOptionLabel(externalAction)}</span>
|
||||
</label>
|
||||
{eventAction === "move" &&
|
||||
<>
|
||||
<label className="calendar-delete-target-label">
|
||||
<span>i18n:govoplan-calendar.target_calendar.e533fe1d</span>
|
||||
<select value={targetCalendarId} onChange={(item) => setTargetCalendarId(item.target.value)} required>
|
||||
{moveTargets.map((item) =>
|
||||
<option key={item.id} value={item.id}>{item.name}</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{calendar.is_default &&
|
||||
<ToggleSwitch label="i18n:govoplan-calendar.make_target_calendar_the_default.10a3977b" checked={makeTargetDefault} onChange={setMakeTargetDefault} />
|
||||
}
|
||||
<p className="calendar-form-note">{calendarBulkMoveConsequence(externalAction)}</p>
|
||||
</>
|
||||
}
|
||||
</fieldset>
|
||||
}
|
||||
{!loadingEventCount && hasEvents && moveTargets.length === 0 &&
|
||||
<p className="calendar-form-note">{source ?
|
||||
"i18n:govoplan-calendar.no_local_target_calendar_is_available_add_a_local_.fad3cb65" :
|
||||
"i18n:govoplan-calendar.no_compatible_target_calendar_is_available_add_a_l.1cf6e47b"}</p>
|
||||
}
|
||||
</div>
|
||||
</Dialog>);
|
||||
|
||||
}
|
||||
|
||||
|
||||
export function syncSourceCreatePayload(sourceMode: CalendarSourceMode, payload: CalendarCalDavFormPayload): Omit<CalendarSyncSourceCreatePayload, "calendar_id"> {
|
||||
const sourceKind = syncSourceKindForMode(sourceMode, payload.collection_url);
|
||||
const result: Omit<CalendarSyncSourceCreatePayload, "calendar_id"> = {
|
||||
source_kind: sourceKind,
|
||||
collection_url: payload.collection_url.trim(),
|
||||
display_name: payload.display_name.trim() || null,
|
||||
auth_type: sourceKind === "graph" ? "bearer" : payload.auth_type,
|
||||
username: sourceKind !== "graph" && payload.auth_type === "basic" ? payload.username.trim() || null : null,
|
||||
sync_enabled: payload.sync_enabled,
|
||||
sync_interval_seconds: Math.max(60, payload.sync_interval_seconds),
|
||||
sync_direction: sourceKind === "caldav" ? payload.sync_direction : "inbound",
|
||||
conflict_policy: payload.conflict_policy,
|
||||
metadata: {}
|
||||
};
|
||||
if (payload.credential_envelope_id) {
|
||||
result.credential_ref = credentialEnvelopeRef(payload.credential_envelope_id);
|
||||
} else if (result.auth_type === "basic" && payload.password.trim()) {
|
||||
result.password = payload.password;
|
||||
} else if (result.auth_type === "bearer" && payload.bearer_token.trim()) {
|
||||
result.bearer_token = payload.bearer_token;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function syncSourceConnectionUpdatePayload(payload: CalendarCalDavFormPayload): CalendarSyncSourceUpdatePayload {
|
||||
const result: CalendarSyncSourceUpdatePayload = {
|
||||
collection_url: payload.collection_url.trim(),
|
||||
auth_type: payload.auth_type,
|
||||
username: payload.auth_type === "basic" ? payload.username.trim() || null : null
|
||||
};
|
||||
if (payload.credential_envelope_id) {
|
||||
result.credential_ref = credentialEnvelopeRef(payload.credential_envelope_id);
|
||||
} else if (payload.auth_type === "basic" && payload.password.trim()) {
|
||||
result.password = payload.password;
|
||||
} else if (payload.auth_type === "bearer" && payload.bearer_token.trim()) {
|
||||
result.bearer_token = payload.bearer_token;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function credentialEnvelopeRef(credentialId: string): string {
|
||||
return `credential-envelope:${credentialId}`;
|
||||
}
|
||||
|
||||
function syncSourceKindForMode(sourceMode: CalendarSourceMode, collectionUrl: string): CalendarSyncSourceKind {
|
||||
if (sourceMode === "ics" && collectionUrl.trim().toLowerCase().startsWith("webcal://")) return "webcal";
|
||||
return sourceMode === "local" ? "caldav" : sourceMode;
|
||||
}
|
||||
|
||||
function sourceSwitchMode(sourceMode: CalendarSourceMode): CalendarSourceSwitchMode {
|
||||
return sourceMode === "webcal" ? "ics" : sourceMode;
|
||||
}
|
||||
|
||||
function syncTransientPayload(authType: CalendarCalDavAuthType, password: string, bearerToken: string) {
|
||||
if (authType === "basic" && password.trim()) return { password };
|
||||
if (authType === "bearer" && bearerToken.trim()) return { bearer_token: bearerToken };
|
||||
return {};
|
||||
}
|
||||
|
||||
function calendarSourcePaneTitle(sourceMode: CalendarSourceMode): string {
|
||||
if (sourceMode === "caldav") return "i18n:govoplan-calendar.caldav_source.459ed16a";
|
||||
if (sourceMode === "ics" || sourceMode === "webcal") return "i18n:govoplan-calendar.ics_webcal_subscription.03bc0d63";
|
||||
if (sourceMode === "graph") return "i18n:govoplan-calendar.microsoft_graph_source.ec4f1383";
|
||||
if (sourceMode === "ews") return "i18n:govoplan-calendar.exchange_web_services_source.53caabf3";
|
||||
return "i18n:govoplan-calendar.local_calendar.ed3f72f8";
|
||||
}
|
||||
|
||||
function calendarSourceUrlLabel(sourceMode: CalendarSourceMode): string {
|
||||
if (sourceMode === "caldav") return "i18n:govoplan-calendar.dav_url.4205e180";
|
||||
if (sourceMode === "graph") return "i18n:govoplan-calendar.graph_calendar_url.e59607f3";
|
||||
if (sourceMode === "ews") return "i18n:govoplan-calendar.ews_endpoint.a3273983";
|
||||
return "i18n:govoplan-calendar.subscription_url.b8b6a1a0";
|
||||
}
|
||||
|
||||
function calendarSourceUrlPlaceholder(sourceMode: CalendarSourceMode): string {
|
||||
if (sourceMode === "caldav") return "https://cloud.example.org/remote.php/dav";
|
||||
if (sourceMode === "graph") return "me/calendar or https://graph.microsoft.com/v1.0/me/calendar/events/delta";
|
||||
if (sourceMode === "ews") return "https://exchange.example.org/EWS/Exchange.asmx";
|
||||
return "webcal://example.org/calendar.ics or https://example.org/calendar.ics";
|
||||
}
|
||||
|
||||
function calendarDeleteActionLabel(calendar: CalendarCollection): string {
|
||||
return calendarIsExternal(calendar) ? "i18n:govoplan-calendar.remove.e963907d" : "i18n:govoplan-calendar.delete.f6fdbe48";
|
||||
}
|
||||
|
||||
function calendarEventDeleteOptionLabel(calendar: CalendarCollection): string {
|
||||
return calendarIsExternal(calendar) ? "i18n:govoplan-calendar.remove_local_events_with_this_calendar.fb8831e1" : "i18n:govoplan-calendar.delete_events_with_this_calendar.cc0e1287";
|
||||
}
|
||||
|
||||
function calendarMoveTargetIsSupported(
|
||||
source: CalendarSyncSource | null,
|
||||
targetSource: CalendarSyncSource | null)
|
||||
: boolean {
|
||||
if (source) return targetSource === null;
|
||||
return targetSource === null || calendarSyncSourceAcceptsCopies(targetSource);
|
||||
}
|
||||
|
||||
function calendarSyncSourceAcceptsCopies(source: CalendarSyncSource): boolean {
|
||||
return source.source_kind === "caldav" && source.sync_enabled && source.sync_direction === "two_way";
|
||||
}
|
||||
|
||||
function calendarBulkMoveExternalAction(
|
||||
source: CalendarSyncSource | null,
|
||||
targetSource: CalendarSyncSource | null)
|
||||
: CalendarBulkMoveExternalAction | undefined {
|
||||
if (source && !targetSource) return "detach_keep_remote";
|
||||
if (!source && targetSource && calendarSyncSourceAcceptsCopies(targetSource)) return "copy_to_remote";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function calendarBulkMoveOptionLabel(action: CalendarBulkMoveExternalAction | undefined): string {
|
||||
if (action === "detach_keep_remote") return "i18n:govoplan-calendar.detach_local_events_and_keep_remote_events.c58ad4e7";
|
||||
if (action === "copy_to_remote") return "i18n:govoplan-calendar.move_and_copy_events_to_the_external_calendar.23c3a004";
|
||||
return "i18n:govoplan-calendar.move_events_to_another_calendar.830c7b09";
|
||||
}
|
||||
|
||||
function calendarBulkMoveConsequence(action: CalendarBulkMoveExternalAction | undefined): string {
|
||||
if (action === "detach_keep_remote") return "i18n:govoplan-calendar.govoplan_moves_the_local_event_copies_to_the_targe.4863e46b";
|
||||
if (action === "copy_to_remote") return "i18n:govoplan-calendar.govoplan_moves_the_events_locally_and_queues_durab.da075b16";
|
||||
return "i18n:govoplan-calendar.events_remain_in_govoplan_no_external_calendar_is_.62cb5937";
|
||||
}
|
||||
|
||||
function calendarDeleteWarning(
|
||||
calendar: CalendarCollection,
|
||||
eventCount: number,
|
||||
eventAction: CalendarDeleteEventAction,
|
||||
targetCalendarId: string,
|
||||
moveTargets: CalendarCollection[])
|
||||
: string {
|
||||
const action = calendarIsExternal(calendar) ? "i18n:govoplan-calendar.removing.b7d2c38b" : "i18n:govoplan-calendar.deleting.2cda36c9";
|
||||
const eventWord = eventCount === 1 ? "i18n:govoplan-calendar.event" : "i18n:govoplan-calendar.events";
|
||||
if (eventAction === "move") {
|
||||
const target = moveTargets.find((item) => item.id === targetCalendarId);
|
||||
return i18nMessage("i18n:govoplan-calendar.value_this_calendar_will_move_value_value_to_val.6c87e1c1", { value0: action, value1: eventCount, value2: eventWord, value3: target?.name || "i18n:govoplan-calendar.the_selected_calendar.67caa12f" });
|
||||
}
|
||||
if (calendarIsExternal(calendar)) {
|
||||
return i18nMessage("i18n:govoplan-calendar.value_this_calendar_will_remove_value_local_valu.8f21a59e", { value0: action, value1: eventCount, value2: eventWord });
|
||||
}
|
||||
return i18nMessage("i18n:govoplan-calendar.value_this_calendar_will_delete_value_value.7869d1f1", { value0: action, value1: eventCount, value2: eventWord });
|
||||
}
|
||||
|
||||
function calendarIsExternal(calendar: CalendarCollection): boolean {
|
||||
const metadata = calendar.metadata;
|
||||
if (!metadata || typeof metadata !== "object") return false;
|
||||
const sourceKind = metadataText(metadata, "source_kind") || metadataText(metadata, "sourceKind") || metadataText(metadata, "connector_kind") || metadataText(metadata, "connectorKind");
|
||||
if (sourceKind && sourceKind !== "local") return true;
|
||||
const connectionKind = metadataText(metadata, "connection_kind") || metadataText(metadata, "connectionKind");
|
||||
if (connectionKind && connectionKind !== "local") return true;
|
||||
return Boolean(
|
||||
metadataFlag(metadata, "external") ||
|
||||
metadataFlag(metadata, "remote") ||
|
||||
metadataFlag(metadata, "sync") ||
|
||||
metadataFlag(metadata, "caldav") ||
|
||||
metadataText(metadata, "connector_id") ||
|
||||
metadataText(metadata, "connectorId") ||
|
||||
metadataText(metadata, "sync_href") ||
|
||||
metadataText(metadata, "syncHref")
|
||||
);
|
||||
}
|
||||
|
||||
function metadataText(metadata: Record<string, unknown>, key: string): string {
|
||||
const value = metadata[key];
|
||||
return typeof value === "string" ? value.trim().toLowerCase() : "";
|
||||
}
|
||||
|
||||
function metadataFlag(metadata: Record<string, unknown>, key: string): boolean {
|
||||
return metadata[key] === true;
|
||||
}
|
||||
562
webui/src/features/calendar/CalendarEventDialog.tsx
Normal file
562
webui/src/features/calendar/CalendarEventDialog.tsx
Normal file
@@ -0,0 +1,562 @@
|
||||
import {
|
||||
useMemo,
|
||||
useState,
|
||||
type FormEvent,
|
||||
} from "react";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import {
|
||||
Button,
|
||||
DateField,
|
||||
Dialog,
|
||||
TimeField,
|
||||
ToggleSwitch,
|
||||
useUnsavedDraftGuard,
|
||||
} from "@govoplan/core-webui";
|
||||
import type {
|
||||
CalendarCollection,
|
||||
CalendarEvent,
|
||||
CalendarEventCreatePayload,
|
||||
} from "../../api/calendar";
|
||||
import {
|
||||
addDays,
|
||||
addHours,
|
||||
addMinutesToTime,
|
||||
calendarDraftKey,
|
||||
errorText,
|
||||
localDateTime,
|
||||
startOfDay,
|
||||
toInputDate,
|
||||
toInputTime,
|
||||
} from "./calendarViewModel";
|
||||
|
||||
type CalendarEventEndMode = "end" | "duration";
|
||||
type CalendarEventAdvancedPayload = Pick<
|
||||
CalendarEventCreatePayload,
|
||||
| "organizer"
|
||||
| "attendees"
|
||||
| "categories"
|
||||
| "rrule"
|
||||
| "rdate"
|
||||
| "exdate"
|
||||
| "reminders"
|
||||
| "attachments"
|
||||
| "related_to"
|
||||
| "icalendar"
|
||||
| "metadata"
|
||||
>;
|
||||
|
||||
export function CalendarEventDialog({
|
||||
calendars,
|
||||
defaultCalendarId,
|
||||
event,
|
||||
focusDate,
|
||||
saving,
|
||||
canWrite,
|
||||
canDelete,
|
||||
onCancel,
|
||||
onSave,
|
||||
onDelete
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}: {calendars: CalendarCollection[];defaultCalendarId: string;event: CalendarEvent | null;focusDate: Date;saving: boolean;canWrite: boolean;canDelete: boolean;onCancel: () => void;onSave: (payload: CalendarEventCreatePayload, event: CalendarEvent | null) => Promise<boolean>;onDelete: (event: CalendarEvent) => Promise<void>;}) {
|
||||
const initialStart = event ? new Date(event.start_at) : focusDate;
|
||||
const initialEnd = event?.end_at ? new Date(event.end_at) : addHours(initialStart, 1);
|
||||
const initialAllDayEnd = event?.all_day && event.end_at ? addDays(startOfDay(initialEnd), -1) : initialEnd;
|
||||
const initialDurationSeconds = event?.duration_seconds ?? Math.max(3600, Math.round((initialEnd.getTime() - initialStart.getTime()) / 1000));
|
||||
const [summary, setSummary] = useState(event?.summary ?? "");
|
||||
const [calendarId, setCalendarId] = useState(event?.calendar_id ?? defaultCalendarId);
|
||||
const [description, setDescription] = useState(event?.description ?? "");
|
||||
const [location, setLocation] = useState(event?.location ?? "");
|
||||
const [startDate, setStartDate] = useState(toInputDate(initialStart));
|
||||
const [endDate, setEndDate] = useState(toInputDate(initialAllDayEnd < initialStart ? initialStart : initialAllDayEnd));
|
||||
const [startTime, setStartTime] = useState(toInputTime(initialStart));
|
||||
const [endTime, setEndTime] = useState(toInputTime(initialEnd));
|
||||
const [allDay, setAllDay] = useState(event?.all_day ?? false);
|
||||
const [endMode, setEndMode] = useState<CalendarEventEndMode>(event && eventUsesDuration(event) ? "duration" : "end");
|
||||
const [durationSeconds, setDurationSeconds] = useState(String(initialDurationSeconds));
|
||||
const [uid, setUid] = useState(event?.uid ?? "");
|
||||
const [recurrenceId, setRecurrenceId] = useState(event?.recurrence_id ?? "");
|
||||
const [sequence, setSequence] = useState(String(event?.sequence ?? 0));
|
||||
const [status, setStatus] = useState(event?.status ?? "CONFIRMED");
|
||||
const [transparency, setTransparency] = useState(event?.transparency ?? "OPAQUE");
|
||||
const [classification, setClassification] = useState(event?.classification ?? "PUBLIC");
|
||||
const [timezone, setTimezone] = useState(event?.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "UTC");
|
||||
const [categoriesText, setCategoriesText] = useState((event?.categories ?? []).join(", "));
|
||||
const [organizerJson, setOrganizerJson] = useState(jsonTextareaValue(event?.organizer ?? null));
|
||||
const [attendeesJson, setAttendeesJson] = useState(jsonTextareaValue(event?.attendees ?? []));
|
||||
const [rruleText, setRruleText] = useState(event?.rrule ? serializeRRuleText(event.rrule) : "");
|
||||
const [rdateJson, setRdateJson] = useState(jsonTextareaValue(event?.rdate ?? []));
|
||||
const [exdateJson, setExdateJson] = useState(jsonTextareaValue(event?.exdate ?? []));
|
||||
const [remindersJson, setRemindersJson] = useState(jsonTextareaValue(event?.reminders ?? []));
|
||||
const [attachmentsJson, setAttachmentsJson] = useState(jsonTextareaValue(event?.attachments ?? []));
|
||||
const [relatedToJson, setRelatedToJson] = useState(jsonTextareaValue(event?.related_to ?? []));
|
||||
const [sourceKind, setSourceKind] = useState(event?.source_kind ?? "local");
|
||||
const [sourceHref, setSourceHref] = useState(event?.source_href ?? "");
|
||||
const [etag, setEtag] = useState(event?.etag ?? "");
|
||||
const [icalendarJson, setICalendarJson] = useState(jsonTextareaValue(event?.icalendar ?? {}));
|
||||
const [metadataJson, setMetadataJson] = useState(jsonTextareaValue(event?.metadata ?? {}));
|
||||
const [formError, setFormError] = useState("");
|
||||
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
||||
const formId = "calendar-event-form";
|
||||
const eventDraft = {
|
||||
summary,
|
||||
calendarId,
|
||||
description,
|
||||
location,
|
||||
startDate,
|
||||
endDate,
|
||||
startTime,
|
||||
endTime,
|
||||
allDay,
|
||||
endMode,
|
||||
durationSeconds,
|
||||
uid,
|
||||
recurrenceId,
|
||||
sequence,
|
||||
status,
|
||||
transparency,
|
||||
classification,
|
||||
timezone,
|
||||
categoriesText,
|
||||
organizerJson,
|
||||
attendeesJson,
|
||||
rruleText,
|
||||
rdateJson,
|
||||
exdateJson,
|
||||
remindersJson,
|
||||
attachmentsJson,
|
||||
relatedToJson,
|
||||
sourceKind,
|
||||
sourceHref,
|
||||
etag,
|
||||
icalendarJson,
|
||||
metadataJson
|
||||
};
|
||||
const initialEventDraftKey = useMemo(() => calendarDraftKey(eventDraft), []);
|
||||
const eventDirty = calendarDraftKey(eventDraft) !== initialEventDraftKey;
|
||||
|
||||
useUnsavedDraftGuard({
|
||||
dirty: eventDirty,
|
||||
onSave: saveCurrent,
|
||||
onDiscard: onCancel
|
||||
});
|
||||
|
||||
function handleAllDayChange(next: boolean) {
|
||||
setAllDay(next);
|
||||
if (next) {
|
||||
setStartTime("00:00");
|
||||
setEndTime("00:00");
|
||||
} else if (startTime === "00:00" && endTime === "00:00") {
|
||||
setStartTime("09:00");
|
||||
setEndTime("10:00");
|
||||
}
|
||||
}
|
||||
|
||||
function handleStartDateChange(next: string) {
|
||||
setStartDate(next);
|
||||
if (endDate < next) setEndDate(next);
|
||||
}
|
||||
|
||||
function handleStartTimeChange(next: string) {
|
||||
setStartTime(next);
|
||||
if (startDate === endDate && endTime <= next) setEndTime(addMinutesToTime(next, 60));
|
||||
}
|
||||
|
||||
async function saveCurrent(): Promise<boolean> {
|
||||
setFormError("");
|
||||
const startAt = allDay ? localDateTime(startDate, "00:00") : localDateTime(startDate, startTime);
|
||||
const parsedDurationSeconds = Math.max(0, Number(durationSeconds) || 0);
|
||||
const usesDuration = !allDay && endMode === "duration";
|
||||
const endAt = allDay ?
|
||||
addDays(localDateTime(endDate, "00:00"), 1) :
|
||||
usesDuration ?
|
||||
new Date(startAt.getTime() + parsedDurationSeconds * 1000) :
|
||||
localDateTime(endDate, endTime);
|
||||
if (usesDuration && parsedDurationSeconds <= 0) {
|
||||
setFormError("i18n:govoplan-calendar.duration_must_be_greater_than_zero.519292f7");
|
||||
return false;
|
||||
}
|
||||
if (endAt <= startAt) {
|
||||
setFormError(allDay ? "i18n:govoplan-calendar.end_date_must_be_on_or_after_start_date.a2518865" : "i18n:govoplan-calendar.end_date_and_time_must_be_after_start_date_and_t.daf31831");
|
||||
return false;
|
||||
}
|
||||
let advanced: CalendarEventAdvancedPayload;
|
||||
try {
|
||||
advanced = {
|
||||
organizer: parseJsonObjectOrNull(organizerJson, "i18n:govoplan-calendar.organizer.debd1720"),
|
||||
attendees: parseJsonArray(attendeesJson, "i18n:govoplan-calendar.attendees.a45a0962"),
|
||||
categories: commaSeparatedValues(categoriesText),
|
||||
rrule: parseRRuleInput(rruleText),
|
||||
rdate: parseJsonArray(rdateJson, "RDATE"),
|
||||
exdate: parseJsonArray(exdateJson, "EXDATE"),
|
||||
reminders: parseJsonArray(remindersJson, "i18n:govoplan-calendar.reminders.ae8c3939"),
|
||||
attachments: parseJsonArray(attachmentsJson, "i18n:govoplan-calendar.attachments.6771ade6"),
|
||||
related_to: parseJsonArray(relatedToJson, "i18n:govoplan-calendar.related_to.0e7989ff"),
|
||||
icalendar: withDurationMode(parseJsonObject(icalendarJson, "i18n:govoplan-calendar.icalendar.f388476d"), usesDuration),
|
||||
metadata: parseJsonObject(metadataJson, "i18n:govoplan-calendar.metadata.251edc0e")
|
||||
};
|
||||
} catch (err) {
|
||||
setFormError(errorText(err));
|
||||
return false;
|
||||
}
|
||||
const payload: CalendarEventCreatePayload = {
|
||||
calendar_id: calendarId,
|
||||
summary,
|
||||
description: description || null,
|
||||
location: location || null,
|
||||
sequence: Math.max(0, Number(sequence) || 0),
|
||||
status,
|
||||
transparency,
|
||||
classification,
|
||||
start_at: startAt.toISOString(),
|
||||
end_at: endAt.toISOString(),
|
||||
duration_seconds: usesDuration ? parsedDurationSeconds : null,
|
||||
all_day: allDay,
|
||||
timezone: timezone.trim() || null,
|
||||
source_kind: sourceKind.trim() || "local",
|
||||
source_href: sourceHref.trim() || null,
|
||||
etag: etag.trim() || null,
|
||||
...advanced
|
||||
};
|
||||
if (!event) {
|
||||
if (uid.trim()) payload.uid = uid.trim();
|
||||
if (recurrenceId.trim()) payload.recurrence_id = recurrenceId.trim();
|
||||
}
|
||||
return onSave(payload, event);
|
||||
}
|
||||
|
||||
function submit(formEvent: FormEvent<HTMLFormElement>) {
|
||||
formEvent.preventDefault();
|
||||
void saveCurrent();
|
||||
}
|
||||
|
||||
function requestDelete() {
|
||||
if (!event) return;
|
||||
if (!confirmingDelete) {
|
||||
setConfirmingDelete(true);
|
||||
return;
|
||||
}
|
||||
void onDelete(event);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title={event ? "i18n:govoplan-calendar.edit_event.a7028454" : "i18n:govoplan-calendar.new_event.2ef3795c"}
|
||||
className="calendar-event-dialog calendar-vevent-dialog"
|
||||
footerClassName="calendar-event-dialog-footer"
|
||||
closeDisabled={saving}
|
||||
onClose={onCancel}
|
||||
footer={
|
||||
<>
|
||||
<div>
|
||||
{event && canDelete &&
|
||||
<Button type="button" variant="danger" onClick={requestDelete} disabled={saving}>
|
||||
<Trash2 size={16} /> {confirmingDelete ? "i18n:govoplan-calendar.confirm_delete.c9f2829e" : "i18n:govoplan-calendar.delete.f6fdbe48"}
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
<div className="calendar-dialog-actions">
|
||||
<Button type="button" onClick={onCancel} disabled={saving}>i18n:govoplan-calendar.cancel.77dfd213</Button>
|
||||
<Button type="submit" form={formId} variant="primary" disabled={saving || !canWrite}>{saving ? "i18n:govoplan-calendar.saving.ae7e8875" : "i18n:govoplan-calendar.save.efc007a3"}</Button>
|
||||
</div>
|
||||
</>
|
||||
}>
|
||||
|
||||
<form id={formId} className="calendar-dialog-form" onSubmit={submit}>
|
||||
{formError && <p className="calendar-form-error">{formError}</p>}
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.title.768e0c1c</span>
|
||||
<input value={summary} onChange={(item) => setSummary(item.target.value)} required maxLength={500} autoFocus disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.calendar.adab5090</span>
|
||||
<select value={calendarId} onChange={(item) => setCalendarId(item.target.value)} required disabled={saving || !canWrite}>
|
||||
{calendars.map((calendar) =>
|
||||
<option key={calendar.id} value={calendar.id}>{calendar.name}</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.description.55f8ebc8</span>
|
||||
<textarea value={description} onChange={(item) => setDescription(item.target.value)} rows={4} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.location.d219c681</span>
|
||||
<input value={location} onChange={(item) => setLocation(item.target.value)} maxLength={500} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<ToggleSwitch label="i18n:govoplan-calendar.whole_day.951c82d1" checked={allDay} disabled={saving || !canWrite} onChange={handleAllDayChange} />
|
||||
<div className="calendar-dialog-date-row">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.start_date.ff99f5b5</span>
|
||||
<DateField value={startDate} onChange={handleStartDateChange} required disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.start_time.88d8206d</span>
|
||||
<TimeField value={startTime} onChange={handleStartTimeChange} disabled={saving || !canWrite || allDay} />
|
||||
</label>
|
||||
</div>
|
||||
{!allDay &&
|
||||
<div className="calendar-dialog-date-row">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.end_mode.5a06de37</span>
|
||||
<select value={endMode} onChange={(item) => setEndMode(item.target.value as CalendarEventEndMode)} disabled={saving || !canWrite}>
|
||||
<option value="end">i18n:govoplan-calendar.end_time.cd7800da</option>
|
||||
<option value="duration">i18n:govoplan-calendar.duration.1370004d</option>
|
||||
</select>
|
||||
</label>
|
||||
{endMode === "duration" &&
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.duration_seconds.19d42eeb</span>
|
||||
<input type="number" min={1} step={60} value={durationSeconds} onChange={(item) => setDurationSeconds(item.target.value)} required disabled={saving || !canWrite} />
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
{(allDay || endMode === "end") &&
|
||||
<div className="calendar-dialog-date-row">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.end_date.89d10cd6</span>
|
||||
<DateField value={endDate} min={startDate} onChange={setEndDate} required disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.end_time.cd7800da</span>
|
||||
<TimeField value={endTime} min={!allDay && startDate === endDate ? startTime : undefined} onChange={setEndTime} disabled={saving || !canWrite || allDay} />
|
||||
</label>
|
||||
</div>
|
||||
}
|
||||
<details className="calendar-advanced-settings calendar-vevent-details">
|
||||
<summary>i18n:govoplan-calendar.vevent.9cf5be75</summary>
|
||||
<section className="calendar-vevent-section">
|
||||
<h3>i18n:govoplan-calendar.identity.7e5a975b</h3>
|
||||
<div className="calendar-dialog-grid-three">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.uid.d946adf5</span>
|
||||
<input value={uid} onChange={(item) => setUid(item.target.value)} maxLength={255} disabled={saving || !canWrite || Boolean(event)} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.recurrence_id.e0b780ba</span>
|
||||
<input value={recurrenceId} onChange={(item) => setRecurrenceId(item.target.value)} maxLength={255} disabled={saving || !canWrite || Boolean(event)} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.sequence.5c8f4e0e</span>
|
||||
<input type="number" min={0} step={1} value={sequence} onChange={(item) => setSequence(item.target.value)} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
<section className="calendar-vevent-section">
|
||||
<h3>i18n:govoplan-calendar.state.a7250206</h3>
|
||||
<div className="calendar-dialog-grid-three">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.status.bae7d5be</span>
|
||||
<select value={status} onChange={(item) => setStatus(item.target.value)} disabled={saving || !canWrite}>
|
||||
<option value="CONFIRMED">i18n:govoplan-calendar.confirmed.0542404a</option>
|
||||
<option value="TENTATIVE">i18n:govoplan-calendar.tentative.d19f9022</option>
|
||||
<option value="CANCELLED">i18n:govoplan-calendar.cancelled.5587b0af</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.transparency.7cb338a9</span>
|
||||
<select value={transparency} onChange={(item) => setTransparency(item.target.value)} disabled={saving || !canWrite}>
|
||||
<option value="OPAQUE">i18n:govoplan-calendar.opaque.3e1d0194</option>
|
||||
<option value="TRANSPARENT">i18n:govoplan-calendar.transparent.ea4efcae</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.class.41ff354b</span>
|
||||
<select value={classification} onChange={(item) => setClassification(item.target.value)} disabled={saving || !canWrite}>
|
||||
<option value="PUBLIC">i18n:govoplan-calendar.public.d1785ca2</option>
|
||||
<option value="PRIVATE">i18n:govoplan-calendar.private.b0b7ba46</option>
|
||||
<option value="CONFIDENTIAL">i18n:govoplan-calendar.confidential.84c9cc88</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.timezone.d1f7dc89</span>
|
||||
<input value={timezone} onChange={(item) => setTimezone(item.target.value)} maxLength={100} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label className="calendar-dialog-wide">
|
||||
<span>i18n:govoplan-calendar.categories.6ccb6007</span>
|
||||
<input value={categoriesText} onChange={(item) => setCategoriesText(item.target.value)} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
<section className="calendar-vevent-section">
|
||||
<h3>i18n:govoplan-calendar.participants.cd56e083</h3>
|
||||
<div className="calendar-dialog-grid-two">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.organizer_json.3add6f9f</span>
|
||||
<textarea value={organizerJson} onChange={(item) => setOrganizerJson(item.target.value)} rows={5} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.attendees_json.aeb487bb</span>
|
||||
<textarea value={attendeesJson} onChange={(item) => setAttendeesJson(item.target.value)} rows={5} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
<section className="calendar-vevent-section">
|
||||
<h3>i18n:govoplan-calendar.recurrence.f7ad40f5</h3>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.rrule.c7b2f8a3</span>
|
||||
<input value={rruleText} onChange={(item) => setRruleText(item.target.value)} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<div className="calendar-dialog-grid-two">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.rdate_json.5b51fca4</span>
|
||||
<textarea value={rdateJson} onChange={(item) => setRdateJson(item.target.value)} rows={5} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.exdate_json.7d0c538d</span>
|
||||
<textarea value={exdateJson} onChange={(item) => setExdateJson(item.target.value)} rows={5} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
<section className="calendar-vevent-section">
|
||||
<h3>i18n:govoplan-calendar.related.917df91e</h3>
|
||||
<div className="calendar-dialog-grid-three">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.reminders_json.ca25e08f</span>
|
||||
<textarea value={remindersJson} onChange={(item) => setRemindersJson(item.target.value)} rows={5} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.attachments_json.d91abf3c</span>
|
||||
<textarea value={attachmentsJson} onChange={(item) => setAttachmentsJson(item.target.value)} rows={5} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.related_to_json.2d4e8f59</span>
|
||||
<textarea value={relatedToJson} onChange={(item) => setRelatedToJson(item.target.value)} rows={5} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
<section className="calendar-vevent-section">
|
||||
<h3>i18n:govoplan-calendar.source.6da13add</h3>
|
||||
<div className="calendar-dialog-grid-three">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.source_kind.7eda9bc4</span>
|
||||
<input value={sourceKind} onChange={(item) => setSourceKind(item.target.value)} maxLength={30} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.source_href.819fa147</span>
|
||||
<input value={sourceHref} onChange={(item) => setSourceHref(item.target.value)} maxLength={1000} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.etag.11d00f6e</span>
|
||||
<input value={etag} onChange={(item) => setEtag(item.target.value)} maxLength={255} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
<section className="calendar-vevent-section">
|
||||
<h3>i18n:govoplan-calendar.raw.da433cd4</h3>
|
||||
<div className="calendar-dialog-grid-two">
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.icalendar_json.fb6cc33e</span>
|
||||
<textarea value={icalendarJson} onChange={(item) => setICalendarJson(item.target.value)} rows={8} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
<label>
|
||||
<span>i18n:govoplan-calendar.metadata_json.b0e4c283</span>
|
||||
<textarea value={metadataJson} onChange={(item) => setMetadataJson(item.target.value)} rows={8} disabled={saving || !canWrite} />
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
</details>
|
||||
</form>
|
||||
</Dialog>);
|
||||
|
||||
}
|
||||
|
||||
function jsonTextareaValue(value: unknown): string {
|
||||
return JSON.stringify(value, null, 2);
|
||||
}
|
||||
|
||||
function parseJsonObject(text: string, label: string): Record<string, unknown> {
|
||||
const value = parseJsonText(text, label, {});
|
||||
if (!isPlainObject(value)) throw new Error(`${label} must be a JSON object.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseJsonObjectOrNull(text: string, label: string): Record<string, unknown> | null {
|
||||
if (!text.trim()) return null;
|
||||
const value = parseJsonText(text, label, null);
|
||||
if (value === null) return null;
|
||||
if (!isPlainObject(value)) throw new Error(`${label} must be a JSON object or null.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseJsonArray(text: string, label: string): Record<string, unknown>[] {
|
||||
const value = parseJsonText(text, label, []);
|
||||
if (!Array.isArray(value)) throw new Error(`${label} must be a JSON array.`);
|
||||
return value.map((item, index) => {
|
||||
if (!isPlainObject(item)) throw new Error(`${label} item ${index + 1} must be a JSON object.`);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
function parseJsonText(text: string, label: string, fallback: unknown): unknown {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) return fallback;
|
||||
try {
|
||||
return JSON.parse(trimmed) as unknown;
|
||||
} catch (err) {
|
||||
throw new Error(`${label} contains invalid JSON: ${errorText(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseRRuleInput(text: string): Record<string, unknown> | null {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) return null;
|
||||
if (trimmed.startsWith("{")) return parseJsonObject(trimmed, "RRULE");
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const item of trimmed.split(";")) {
|
||||
const [rawKey, ...rawValueParts] = item.split("=");
|
||||
const key = rawKey.trim().toUpperCase();
|
||||
const rawValue = rawValueParts.join("=").trim();
|
||||
if (!key || !rawValue) continue;
|
||||
const values = rawValue.split(",").map((value) => value.trim()).filter(Boolean);
|
||||
result[key] = values.length > 1 ? values : values[0] ?? rawValue;
|
||||
}
|
||||
return Object.keys(result).length ? result : null;
|
||||
}
|
||||
|
||||
function serializeRRuleText(value: Record<string, unknown>): string {
|
||||
return Object.entries(value).
|
||||
map(([key, item]) => `${key.toUpperCase()}=${Array.isArray(item) ? item.join(",") : String(item)}`).
|
||||
join(";");
|
||||
}
|
||||
|
||||
function commaSeparatedValues(text: string): string[] {
|
||||
return text.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function withDurationMode(value: Record<string, unknown>, usesDuration: boolean): Record<string, unknown> {
|
||||
const next = { ...value };
|
||||
const standard = isPlainObject(next.standard) ? { ...next.standard } : {};
|
||||
if (usesDuration) {
|
||||
standard.uses_duration = true;
|
||||
} else {
|
||||
delete standard.uses_duration;
|
||||
}
|
||||
if (Object.keys(standard).length > 0) {
|
||||
next.standard = standard;
|
||||
} else {
|
||||
delete next.standard;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function eventUsesDuration(event: CalendarEvent): boolean {
|
||||
const standard = isPlainObject(event.icalendar?.standard) ? event.icalendar.standard : null;
|
||||
return standard?.uses_duration === true;
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
114
webui/src/features/calendar/CalendarPicker.tsx
Normal file
114
webui/src/features/calendar/CalendarPicker.tsx
Normal file
@@ -0,0 +1,114 @@
|
||||
import { useEffect, useId, useMemo, useState } from "react";
|
||||
import {
|
||||
FormField,
|
||||
hasScope,
|
||||
type CalendarPickerProps
|
||||
} from "@govoplan/core-webui";
|
||||
import { listCalendars, type CalendarCollection } from "../../api/calendar";
|
||||
import {
|
||||
CALENDAR_PICKER_READ_SCOPE,
|
||||
calendarPickerOptions,
|
||||
calendarPickerTenantId
|
||||
} from "./calendarPickerLogic";
|
||||
|
||||
const LABEL = "i18n:govoplan-calendar.calendar.adab5090";
|
||||
const SELECT_CALENDAR = "i18n:govoplan-calendar.select_calendar.f38b5ba2";
|
||||
const LOADING_CALENDARS = "i18n:govoplan-calendar.loading_calendars.afbb957b";
|
||||
const CALENDARS_UNAVAILABLE = "i18n:govoplan-calendar.calendars_are_unavailable.f074c862";
|
||||
const NO_CALENDARS_AVAILABLE = "i18n:govoplan-calendar.no_calendars_are_available.711d2cf3";
|
||||
const SELECTED_CALENDAR_UNAVAILABLE = "i18n:govoplan-calendar.the_selected_calendar_is_no_longer_available.39f0f1f5";
|
||||
|
||||
export default function CalendarPicker({
|
||||
settings,
|
||||
auth,
|
||||
value,
|
||||
onChange,
|
||||
id,
|
||||
name,
|
||||
label = LABEL,
|
||||
emptyLabel = SELECT_CALENDAR,
|
||||
disabled = false,
|
||||
required = false,
|
||||
className
|
||||
}: CalendarPickerProps) {
|
||||
const generatedId = useId();
|
||||
const selectId = id ?? `calendar-picker-${generatedId.replace(/:/g, "")}`;
|
||||
const statusId = `${selectId}-status`;
|
||||
const [calendars, setCalendars] = useState<CalendarCollection[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const canRead = hasScope(auth, CALENDAR_PICKER_READ_SCOPE);
|
||||
const tenantId = calendarPickerTenantId(auth);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!canRead) {
|
||||
setCalendars([]);
|
||||
setLoading(false);
|
||||
setFailed(true);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setFailed(false);
|
||||
listCalendars(settings)
|
||||
.then((response) => {
|
||||
if (!cancelled) setCalendars(response.calendars);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
setCalendars([]);
|
||||
setFailed(true);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [canRead, settings.accessToken, settings.apiBaseUrl, settings.apiKey, tenantId]);
|
||||
|
||||
const options = useMemo(() => calendarPickerOptions(calendars), [calendars]);
|
||||
const selectedUnavailable = Boolean(value) && !loading && !options.some((calendar) => calendar.id === value);
|
||||
const status = failed
|
||||
? CALENDARS_UNAVAILABLE
|
||||
: !loading && options.length === 0
|
||||
? NO_CALENDARS_AVAILABLE
|
||||
: selectedUnavailable
|
||||
? SELECTED_CALENDAR_UNAVAILABLE
|
||||
: "";
|
||||
const placeholder = loading
|
||||
? LOADING_CALENDARS
|
||||
: failed
|
||||
? CALENDARS_UNAVAILABLE
|
||||
: options.length === 0
|
||||
? NO_CALENDARS_AVAILABLE
|
||||
: emptyLabel;
|
||||
|
||||
return (
|
||||
<div className={["calendar-picker", className].filter(Boolean).join(" ")}>
|
||||
<FormField label={label}>
|
||||
<select
|
||||
id={selectId}
|
||||
name={name}
|
||||
value={value}
|
||||
required={required}
|
||||
disabled={disabled || loading || failed || options.length === 0}
|
||||
aria-busy={loading || undefined}
|
||||
aria-describedby={status ? statusId : undefined}
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
>
|
||||
<option value="">{placeholder}</option>
|
||||
{selectedUnavailable ? <option value={value} disabled>{SELECTED_CALENDAR_UNAVAILABLE}</option> : null}
|
||||
{options.map((calendar) => (
|
||||
<option key={calendar.id} value={calendar.id}>{calendar.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</FormField>
|
||||
{status ? <div id={statusId} className="muted small-note" role={failed ? "alert" : "status"}>{status}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
666
webui/src/features/calendar/CalendarViews.tsx
Normal file
666
webui/src/features/calendar/CalendarViews.tsx
Normal file
@@ -0,0 +1,666 @@
|
||||
import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type DragEvent as ReactDragEvent,
|
||||
} from "react";
|
||||
|
||||
import { i18nMessage } from "@govoplan/core-webui";
|
||||
|
||||
import type { CalendarEvent } from "../../api/calendar";
|
||||
import {
|
||||
HOUR_ROW_HEIGHT,
|
||||
INITIAL_SCROLL_HOUR,
|
||||
calendarEventColorStyle,
|
||||
chunk,
|
||||
continuousVirtualWindow,
|
||||
dayKey,
|
||||
dayMonthLabel,
|
||||
dropSlotMinuteOfDay,
|
||||
eventTimeLabel,
|
||||
isWeekend,
|
||||
layoutTimedEventsForDay,
|
||||
minuteOfDayLabel,
|
||||
monthYearLabel,
|
||||
sameDay,
|
||||
sameMonth,
|
||||
timedEventStyle,
|
||||
timedOverflowStyle,
|
||||
timeGridStyle,
|
||||
weekdayLong,
|
||||
type CalendarDropTarget,
|
||||
type CalendarMode,
|
||||
type CalendarResizeEdge,
|
||||
type CalendarTimeDropTarget,
|
||||
type CalendarViewPreferences,
|
||||
type ContinuousViewport,
|
||||
} from "./calendarViewModel";
|
||||
|
||||
type CalendarViewCallbacks = {
|
||||
onEventSelect: (event: CalendarEvent) => void;
|
||||
onEventHover: (eventId: string) => void;
|
||||
onEventDragStart: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
event: CalendarEvent,
|
||||
) => void;
|
||||
onEventDragEnd: () => void;
|
||||
onEventDragOverDay: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
day: Date,
|
||||
) => void;
|
||||
onDropTargetLeave: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
) => void;
|
||||
onEventDropOnDay: (
|
||||
dropEvent: ReactDragEvent<HTMLElement>,
|
||||
day: Date,
|
||||
) => void;
|
||||
};
|
||||
|
||||
type CalendarWeekRowsProps = CalendarViewCallbacks & {
|
||||
days: Date[];
|
||||
eventsByDay: Map<string, CalendarEvent[]>;
|
||||
calendarColorById: Map<string, string>;
|
||||
focusDate: Date;
|
||||
variant: "month" | "continuous";
|
||||
preferences: CalendarViewPreferences;
|
||||
canWrite: boolean;
|
||||
draggingEventId: string;
|
||||
hoveredEventId: string;
|
||||
dropTarget: CalendarDropTarget;
|
||||
viewport?: ContinuousViewport;
|
||||
};
|
||||
|
||||
export function CalendarWeekRows({
|
||||
days,
|
||||
eventsByDay,
|
||||
calendarColorById,
|
||||
focusDate,
|
||||
variant,
|
||||
preferences,
|
||||
canWrite,
|
||||
draggingEventId,
|
||||
hoveredEventId,
|
||||
dropTarget,
|
||||
viewport,
|
||||
onEventSelect,
|
||||
onEventHover,
|
||||
onEventDragStart,
|
||||
onEventDragEnd,
|
||||
onEventDragOverDay,
|
||||
onDropTargetLeave,
|
||||
onEventDropOnDay,
|
||||
}: CalendarWeekRowsProps) {
|
||||
const weeks = chunk(days, 7);
|
||||
const virtualWindow =
|
||||
variant === "continuous" && preferences.continuousVirtualization
|
||||
? continuousVirtualWindow(
|
||||
weeks.length,
|
||||
viewport ?? { scrollTop: 0, height: 0 },
|
||||
preferences.continuousOverscanWeeks,
|
||||
)
|
||||
: {
|
||||
start: 0,
|
||||
end: weeks.length,
|
||||
topSpacerHeight: 0,
|
||||
bottomSpacerHeight: 0,
|
||||
};
|
||||
const visibleWeeks = weeks.slice(
|
||||
virtualWindow.start,
|
||||
virtualWindow.end,
|
||||
);
|
||||
const eventLimit = variant === "month" ? 5 : 3;
|
||||
|
||||
return (
|
||||
<div className={`calendar-week-rows is-${variant}`}>
|
||||
<div className="calendar-weekday-header">
|
||||
{[
|
||||
"i18n:govoplan-calendar.mon.24b2a099",
|
||||
"i18n:govoplan-calendar.tue.529541bb",
|
||||
"i18n:govoplan-calendar.wed.23408b19",
|
||||
"i18n:govoplan-calendar.thu.3593ccd9",
|
||||
"i18n:govoplan-calendar.fri.bbd6e32e",
|
||||
"i18n:govoplan-calendar.sat.6b782d41",
|
||||
"i18n:govoplan-calendar.sun.48c98cab",
|
||||
].map((label) => (
|
||||
<span key={label}>{label}</span>
|
||||
))}
|
||||
</div>
|
||||
{virtualWindow.topSpacerHeight > 0 && (
|
||||
<div
|
||||
className="calendar-week-spacer"
|
||||
style={{ height: virtualWindow.topSpacerHeight }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
{visibleWeeks.map((week) => (
|
||||
<div className="calendar-week-row" key={dayKey(week[0])}>
|
||||
{week.map((day) => {
|
||||
const key = dayKey(day);
|
||||
const dayEvents = eventsByDay.get(key) ?? [];
|
||||
const outsideFocusMonth =
|
||||
variant === "month" && !sameMonth(day, focusDate);
|
||||
return (
|
||||
<section
|
||||
key={key}
|
||||
className={[
|
||||
"calendar-day-cell",
|
||||
outsideFocusMonth ? "is-muted" : "",
|
||||
sameDay(day, new Date()) ? "is-today" : "",
|
||||
dropTarget?.kind === "day" &&
|
||||
dropTarget.key === key
|
||||
? "is-drop-target"
|
||||
: "",
|
||||
variant === "continuous" &&
|
||||
preferences.alternateContinuousMonths
|
||||
? day.getMonth() % 2 === 0
|
||||
? "is-even-month"
|
||||
: "is-odd-month"
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
onDragOver={
|
||||
canWrite
|
||||
? (event) => onEventDragOverDay(event, day)
|
||||
: undefined
|
||||
}
|
||||
onDragLeave={
|
||||
canWrite ? onDropTargetLeave : undefined
|
||||
}
|
||||
onDrop={
|
||||
canWrite
|
||||
? (event) => onEventDropOnDay(event, day)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<header>
|
||||
<span className="calendar-day-number">
|
||||
{day.getDate()}
|
||||
</span>
|
||||
{day.getDate() === 1 && (
|
||||
<small>{monthYearLabel(day)}</small>
|
||||
)}
|
||||
</header>
|
||||
<div className="calendar-event-stack">
|
||||
{dayEvents.slice(0, eventLimit).map((event) => (
|
||||
<CalendarEventChip
|
||||
key={event.id}
|
||||
event={event}
|
||||
color={calendarColorById.get(event.calendar_id)}
|
||||
canDrag={canWrite}
|
||||
dragging={draggingEventId === event.id}
|
||||
linkedHover={hoveredEventId === event.id}
|
||||
onSelect={onEventSelect}
|
||||
onHover={onEventHover}
|
||||
onDragStart={onEventDragStart}
|
||||
onDragEnd={onEventDragEnd}
|
||||
/>
|
||||
))}
|
||||
{dayEvents.length > eventLimit && (
|
||||
<span className="calendar-more-events">
|
||||
+{dayEvents.length - eventLimit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
{virtualWindow.bottomSpacerHeight > 0 && (
|
||||
<div
|
||||
className="calendar-week-spacer"
|
||||
style={{ height: virtualWindow.bottomSpacerHeight }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type CalendarTimeGridProps = CalendarViewCallbacks & {
|
||||
days: Date[];
|
||||
eventsByDay: Map<string, CalendarEvent[]>;
|
||||
calendarColorById: Map<string, string>;
|
||||
mode: CalendarMode;
|
||||
preferences: CalendarViewPreferences;
|
||||
canWrite: boolean;
|
||||
draggingEventId: string;
|
||||
hoveredEventId: string;
|
||||
dropTarget: CalendarDropTarget;
|
||||
onEventResizeDragStart: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
event: CalendarEvent,
|
||||
edge: CalendarResizeEdge,
|
||||
) => void;
|
||||
onEventDragOverTime: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
day: Date,
|
||||
) => void;
|
||||
onEventDropOnTime: (
|
||||
dropEvent: ReactDragEvent<HTMLElement>,
|
||||
day: Date,
|
||||
minuteOfDay: number,
|
||||
) => void;
|
||||
};
|
||||
|
||||
export function CalendarTimeGrid({
|
||||
days,
|
||||
eventsByDay,
|
||||
calendarColorById,
|
||||
mode,
|
||||
preferences,
|
||||
canWrite,
|
||||
draggingEventId,
|
||||
hoveredEventId,
|
||||
dropTarget,
|
||||
onEventSelect,
|
||||
onEventHover,
|
||||
onEventDragStart,
|
||||
onEventResizeDragStart,
|
||||
onEventDragEnd,
|
||||
onEventDragOverDay,
|
||||
onEventDragOverTime,
|
||||
onDropTargetLeave,
|
||||
onEventDropOnDay,
|
||||
onEventDropOnTime,
|
||||
}: CalendarTimeGridProps) {
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const hours = Array.from({ length: 24 }, (_item, index) => index);
|
||||
const columns = `72px repeat(${days.length}, minmax(132px, 1fr))`;
|
||||
const dimWeekends = preferences.dimWeekends && mode === "week";
|
||||
const gridStyle = timeGridStyle(columns, preferences);
|
||||
const allDayEventsByDay = days.map((day) => ({
|
||||
key: dayKey(day),
|
||||
date: day,
|
||||
events: (eventsByDay.get(dayKey(day)) ?? []).filter(
|
||||
(event) => event.all_day,
|
||||
),
|
||||
}));
|
||||
const hasAllDayEvents = allDayEventsByDay.some(
|
||||
(day) => day.events.length > 0,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop =
|
||||
INITIAL_SCROLL_HOUR * HOUR_ROW_HEIGHT;
|
||||
}
|
||||
}, [days.length, days[0]?.getTime()]);
|
||||
|
||||
return (
|
||||
<div className="calendar-time-view">
|
||||
<div
|
||||
className="calendar-time-header"
|
||||
style={{ gridTemplateColumns: columns }}
|
||||
>
|
||||
<div className="calendar-time-corner" />
|
||||
{days.map((day) => (
|
||||
<header
|
||||
key={dayKey(day)}
|
||||
className={[
|
||||
sameDay(day, new Date()) ? "is-today" : "",
|
||||
dimWeekends && isWeekend(day) ? "is-weekend" : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
>
|
||||
<strong>{weekdayLong(day)}</strong>
|
||||
<span>{dayMonthLabel(day)}</span>
|
||||
</header>
|
||||
))}
|
||||
</div>
|
||||
{hasAllDayEvents && (
|
||||
<div
|
||||
className="calendar-all-day-strip"
|
||||
style={{ gridTemplateColumns: columns }}
|
||||
>
|
||||
<div className="calendar-all-day-label">
|
||||
i18n:govoplan-calendar.all_day.11457433
|
||||
</div>
|
||||
{allDayEventsByDay.map((day) => (
|
||||
<div
|
||||
key={day.key}
|
||||
className={[
|
||||
"calendar-all-day-cell",
|
||||
dimWeekends && isWeekend(day.date)
|
||||
? "is-weekend"
|
||||
: "",
|
||||
dropTarget?.kind === "day" &&
|
||||
dropTarget.key === day.key
|
||||
? "is-drop-target"
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
onDragOver={
|
||||
canWrite
|
||||
? (event) => onEventDragOverDay(event, day.date)
|
||||
: undefined
|
||||
}
|
||||
onDragLeave={
|
||||
canWrite ? onDropTargetLeave : undefined
|
||||
}
|
||||
onDrop={
|
||||
canWrite
|
||||
? (event) => onEventDropOnDay(event, day.date)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{day.events.map((event) => (
|
||||
<CalendarEventChip
|
||||
key={event.id}
|
||||
event={event}
|
||||
color={calendarColorById.get(event.calendar_id)}
|
||||
compact
|
||||
canDrag={canWrite}
|
||||
dragging={draggingEventId === event.id}
|
||||
linkedHover={hoveredEventId === event.id}
|
||||
onSelect={onEventSelect}
|
||||
onHover={onEventHover}
|
||||
onDragStart={onEventDragStart}
|
||||
onDragEnd={onEventDragEnd}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="calendar-time-scroll" ref={scrollRef}>
|
||||
<div className="calendar-time-grid" style={gridStyle}>
|
||||
<div className="calendar-hour-label-column">
|
||||
{hours.map((hour) => (
|
||||
<div className="calendar-hour-label" key={hour}>
|
||||
{String(hour).padStart(2, "0")}:00
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{days.map((day) => (
|
||||
<TimedDayColumn
|
||||
key={dayKey(day)}
|
||||
day={day}
|
||||
events={eventsByDay.get(dayKey(day)) ?? []}
|
||||
calendarColorById={calendarColorById}
|
||||
dimWeekend={dimWeekends && isWeekend(day)}
|
||||
canWrite={canWrite}
|
||||
draggingEventId={draggingEventId}
|
||||
hoveredEventId={hoveredEventId}
|
||||
dropTarget={
|
||||
dropTarget?.kind === "time" &&
|
||||
dropTarget.key === dayKey(day)
|
||||
? dropTarget
|
||||
: null
|
||||
}
|
||||
onEventSelect={onEventSelect}
|
||||
onEventHover={onEventHover}
|
||||
onEventDragStart={onEventDragStart}
|
||||
onEventResizeDragStart={onEventResizeDragStart}
|
||||
onEventDragEnd={onEventDragEnd}
|
||||
onEventDragOverTime={onEventDragOverTime}
|
||||
onDropTargetLeave={onDropTargetLeave}
|
||||
onEventDropOnTime={onEventDropOnTime}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type TimedDayColumnProps = {
|
||||
day: Date;
|
||||
events: CalendarEvent[];
|
||||
calendarColorById: Map<string, string>;
|
||||
dimWeekend: boolean;
|
||||
canWrite: boolean;
|
||||
draggingEventId: string;
|
||||
hoveredEventId: string;
|
||||
dropTarget: CalendarTimeDropTarget | null;
|
||||
onEventSelect: (event: CalendarEvent) => void;
|
||||
onEventHover: (eventId: string) => void;
|
||||
onEventDragStart: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
event: CalendarEvent,
|
||||
) => void;
|
||||
onEventResizeDragStart: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
event: CalendarEvent,
|
||||
edge: CalendarResizeEdge,
|
||||
) => void;
|
||||
onEventDragEnd: () => void;
|
||||
onEventDragOverTime: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
day: Date,
|
||||
) => void;
|
||||
onDropTargetLeave: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
) => void;
|
||||
onEventDropOnTime: (
|
||||
dropEvent: ReactDragEvent<HTMLElement>,
|
||||
day: Date,
|
||||
minuteOfDay: number,
|
||||
) => void;
|
||||
};
|
||||
|
||||
function TimedDayColumn({
|
||||
day,
|
||||
events,
|
||||
calendarColorById,
|
||||
dimWeekend,
|
||||
canWrite,
|
||||
draggingEventId,
|
||||
hoveredEventId,
|
||||
dropTarget,
|
||||
onEventSelect,
|
||||
onEventHover,
|
||||
onEventDragStart,
|
||||
onEventResizeDragStart,
|
||||
onEventDragEnd,
|
||||
onEventDragOverTime,
|
||||
onDropTargetLeave,
|
||||
onEventDropOnTime,
|
||||
}: TimedDayColumnProps) {
|
||||
const layout = useMemo(
|
||||
() => layoutTimedEventsForDay(events, day),
|
||||
[day, events],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[
|
||||
"calendar-day-time-column",
|
||||
dimWeekend ? "is-weekend" : "",
|
||||
dropTarget ? "is-drop-target" : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
onDragOver={
|
||||
canWrite
|
||||
? (event) => onEventDragOverTime(event, day)
|
||||
: undefined
|
||||
}
|
||||
onDragLeave={canWrite ? onDropTargetLeave : undefined}
|
||||
onDrop={
|
||||
canWrite
|
||||
? (event) =>
|
||||
onEventDropOnTime(event, day, dropSlotMinuteOfDay(event))
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{dropTarget && (
|
||||
<div
|
||||
className="calendar-time-drop-marker"
|
||||
style={{
|
||||
top: `${
|
||||
(dropTarget.minuteOfDay / 60) * HOUR_ROW_HEIGHT
|
||||
}px`,
|
||||
}}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span>{minuteOfDayLabel(dropTarget.minuteOfDay)}</span>
|
||||
</div>
|
||||
)}
|
||||
{layout.items.map((item) => (
|
||||
<div
|
||||
key={item.event.id}
|
||||
className={[
|
||||
"calendar-timed-event",
|
||||
draggingEventId === item.event.id ? "is-dragging" : "",
|
||||
hoveredEventId === item.event.id
|
||||
? "is-linked-hover"
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
style={timedEventStyle(
|
||||
item,
|
||||
calendarColorById.get(item.event.calendar_id),
|
||||
)}
|
||||
draggable={canWrite}
|
||||
onMouseEnter={() => onEventHover(item.event.id)}
|
||||
onMouseLeave={() => onEventHover("")}
|
||||
onDragStart={
|
||||
canWrite
|
||||
? (event) => onEventDragStart(event, item.event)
|
||||
: undefined
|
||||
}
|
||||
onDragEnd={canWrite ? onEventDragEnd : undefined}
|
||||
title={i18nMessage(
|
||||
"i18n:govoplan-calendar.edit_value.fad75899",
|
||||
{ value0: item.event.summary },
|
||||
)}
|
||||
>
|
||||
{canWrite && (
|
||||
<span
|
||||
className="calendar-event-resize-handle is-start"
|
||||
draggable
|
||||
title="i18n:govoplan-calendar.change_start_time.06eea3d3"
|
||||
onDragStart={(event) =>
|
||||
onEventResizeDragStart(event, item.event, "start")
|
||||
}
|
||||
onDragEnd={onEventDragEnd}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="calendar-timed-event-content"
|
||||
onClick={() => onEventSelect(item.event)}
|
||||
onFocus={() => onEventHover(item.event.id)}
|
||||
onBlur={() => onEventHover("")}
|
||||
title={i18nMessage(
|
||||
"i18n:govoplan-calendar.edit_value.fad75899",
|
||||
{ value0: item.event.summary },
|
||||
)}
|
||||
>
|
||||
<EventInlineLabel event={item.event} />
|
||||
</button>
|
||||
{canWrite && (
|
||||
<span
|
||||
className="calendar-event-resize-handle is-end"
|
||||
draggable
|
||||
title="i18n:govoplan-calendar.change_end_time.db66ef4b"
|
||||
onDragStart={(event) =>
|
||||
onEventResizeDragStart(event, item.event, "end")
|
||||
}
|
||||
onDragEnd={onEventDragEnd}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{layout.overflows.map((overflow) => (
|
||||
<button
|
||||
key={overflow.key}
|
||||
type="button"
|
||||
className="calendar-timed-overflow"
|
||||
style={timedOverflowStyle(overflow)}
|
||||
title={overflow.events
|
||||
.map((event) => event.summary)
|
||||
.join(", ")}
|
||||
onClick={() => onEventSelect(overflow.events[0])}
|
||||
>
|
||||
+{overflow.events.length}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type CalendarEventChipProps = {
|
||||
event: CalendarEvent;
|
||||
color?: string | null;
|
||||
compact?: boolean;
|
||||
canDrag?: boolean;
|
||||
dragging?: boolean;
|
||||
linkedHover?: boolean;
|
||||
onSelect: (event: CalendarEvent) => void;
|
||||
onHover?: (eventId: string) => void;
|
||||
onDragStart?: (
|
||||
dragEvent: ReactDragEvent<HTMLElement>,
|
||||
event: CalendarEvent,
|
||||
) => void;
|
||||
onDragEnd?: () => void;
|
||||
};
|
||||
|
||||
function CalendarEventChip({
|
||||
event,
|
||||
color,
|
||||
compact = false,
|
||||
canDrag = false,
|
||||
dragging = false,
|
||||
linkedHover = false,
|
||||
onSelect,
|
||||
onHover,
|
||||
onDragStart,
|
||||
onDragEnd,
|
||||
}: CalendarEventChipProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={[
|
||||
compact
|
||||
? "calendar-event-chip is-compact"
|
||||
: "calendar-event-chip",
|
||||
dragging ? "is-dragging" : "",
|
||||
linkedHover ? "is-linked-hover" : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")}
|
||||
style={calendarEventColorStyle(color)}
|
||||
draggable={canDrag}
|
||||
onClick={() => onSelect(event)}
|
||||
onMouseEnter={onHover ? () => onHover(event.id) : undefined}
|
||||
onMouseLeave={onHover ? () => onHover("") : undefined}
|
||||
onFocus={onHover ? () => onHover(event.id) : undefined}
|
||||
onBlur={onHover ? () => onHover("") : undefined}
|
||||
onDragStart={
|
||||
canDrag && onDragStart
|
||||
? (dragEvent) => onDragStart(dragEvent, event)
|
||||
: undefined
|
||||
}
|
||||
onDragEnd={canDrag ? onDragEnd : undefined}
|
||||
title={i18nMessage(
|
||||
"i18n:govoplan-calendar.edit_value.fad75899",
|
||||
{ value0: event.summary },
|
||||
)}
|
||||
>
|
||||
<EventInlineLabel event={event} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function EventInlineLabel({
|
||||
event,
|
||||
}: {
|
||||
event: CalendarEvent;
|
||||
}) {
|
||||
return (
|
||||
<span className="calendar-event-line">
|
||||
<span className="calendar-event-time">
|
||||
{eventTimeLabel(event)}
|
||||
</span>
|
||||
<span className="calendar-event-separator">-</span>
|
||||
<strong>{event.summary}</strong>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
110
webui/src/features/calendar/UpcomingEventsWidget.tsx
Normal file
110
webui/src/features/calendar/UpcomingEventsWidget.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
import { useCallback } from "react";
|
||||
import { CalendarDays, MapPin } from "lucide-react";
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
DashboardWidgetList,
|
||||
DismissibleAlert,
|
||||
LoadingFrame,
|
||||
useDashboardWidgetData,
|
||||
type ApiSettings,
|
||||
type DashboardWidgetConfiguration
|
||||
} from "@govoplan/core-webui";
|
||||
import {
|
||||
listCalendarEvents,
|
||||
type CalendarEvent
|
||||
} from "../../api/calendar";
|
||||
|
||||
export default function UpcomingEventsWidget({
|
||||
settings,
|
||||
refreshKey,
|
||||
configuration
|
||||
}: {
|
||||
settings: ApiSettings;
|
||||
refreshKey: number;
|
||||
configuration: DashboardWidgetConfiguration;
|
||||
}) {
|
||||
const maxItems = numberSetting(configuration.maxItems, 5, 1, 12);
|
||||
const daysAhead = numberSetting(configuration.daysAhead, 14, 1, 90);
|
||||
const showLocation = configuration.showLocation !== false;
|
||||
const load = useCallback(async () => {
|
||||
const start = new Date();
|
||||
const end = new Date(start);
|
||||
end.setDate(end.getDate() + daysAhead);
|
||||
const response = await listCalendarEvents(settings, {
|
||||
start_at: start.toISOString(),
|
||||
end_at: end.toISOString()
|
||||
});
|
||||
return [...response.events]
|
||||
.filter((event) => event.status !== "cancelled")
|
||||
.sort(
|
||||
(left, right) =>
|
||||
new Date(left.start_at).getTime() - new Date(right.start_at).getTime()
|
||||
)
|
||||
.slice(0, maxItems);
|
||||
}, [daysAhead, maxItems, settings]);
|
||||
const { data: events, loading, error } = useDashboardWidgetData(
|
||||
load,
|
||||
refreshKey
|
||||
);
|
||||
|
||||
return (
|
||||
<LoadingFrame loading={loading} label="Loading upcoming calendar events">
|
||||
{error && (
|
||||
<DismissibleAlert tone="warning" resetKey={error}>
|
||||
{error}
|
||||
</DismissibleAlert>
|
||||
)}
|
||||
<DashboardWidgetList
|
||||
emptyText={`No events in the next ${daysAhead} days.`}
|
||||
items={(events ?? []).map((event) => ({
|
||||
id: event.id,
|
||||
title: event.summary,
|
||||
detail:
|
||||
showLocation && event.location ? (
|
||||
<>
|
||||
<MapPin size={12} aria-hidden="true" /> {event.location}
|
||||
</>
|
||||
) : undefined,
|
||||
meta: eventTimeLabel(event),
|
||||
leading: <CalendarDays size={17} aria-hidden="true" />,
|
||||
to: "/calendar"
|
||||
}))}
|
||||
/>
|
||||
<div className="dashboard-contribution-footer">
|
||||
<Link className="btn btn-secondary" to="/calendar">
|
||||
Open calendar
|
||||
</Link>
|
||||
</div>
|
||||
</LoadingFrame>
|
||||
);
|
||||
}
|
||||
|
||||
function eventTimeLabel(event: CalendarEvent): string {
|
||||
const start = new Date(event.start_at);
|
||||
if (event.all_day) {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
weekday: "short",
|
||||
day: "2-digit",
|
||||
month: "short"
|
||||
}).format(start);
|
||||
}
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
weekday: "short",
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit"
|
||||
}).format(start);
|
||||
}
|
||||
|
||||
function numberSetting(
|
||||
value: unknown,
|
||||
fallback: number,
|
||||
minimum: number,
|
||||
maximum: number
|
||||
): number {
|
||||
const numeric = typeof value === "number" ? value : Number(value);
|
||||
return Number.isFinite(numeric)
|
||||
? Math.max(minimum, Math.min(maximum, Math.floor(numeric)))
|
||||
: fallback;
|
||||
}
|
||||
24
webui/src/features/calendar/calendarPickerLogic.ts
Normal file
24
webui/src/features/calendar/calendarPickerLogic.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
type CalendarPickerAuth = {
|
||||
tenant: { id: string };
|
||||
active_tenant?: { id: string };
|
||||
};
|
||||
|
||||
export type CalendarPickerOption = {
|
||||
id: string;
|
||||
name: string;
|
||||
is_default: boolean;
|
||||
};
|
||||
|
||||
export const CALENDAR_PICKER_READ_SCOPE = "calendar:calendar:read";
|
||||
|
||||
export function calendarPickerOptions<TCalendar extends CalendarPickerOption>(calendars: TCalendar[]): TCalendar[] {
|
||||
return [...calendars].sort((left, right) => {
|
||||
if (left.is_default !== right.is_default) return left.is_default ? -1 : 1;
|
||||
const nameDelta = left.name.localeCompare(right.name, undefined, { sensitivity: "base" });
|
||||
return nameDelta !== 0 ? nameDelta : left.id.localeCompare(right.id);
|
||||
});
|
||||
}
|
||||
|
||||
export function calendarPickerTenantId(auth: CalendarPickerAuth): string {
|
||||
return (auth.active_tenant ?? auth.tenant).id;
|
||||
}
|
||||
889
webui/src/features/calendar/calendarViewModel.ts
Normal file
889
webui/src/features/calendar/calendarViewModel.ts
Normal file
@@ -0,0 +1,889 @@
|
||||
import type {
|
||||
CSSProperties,
|
||||
DragEvent as ReactDragEvent,
|
||||
} from "react";
|
||||
|
||||
import type {
|
||||
CalendarEvent,
|
||||
CalendarEventDeltaResponse,
|
||||
} from "../../api/calendar";
|
||||
|
||||
export type CalendarMode =
|
||||
| "continuous"
|
||||
| "month"
|
||||
| "week"
|
||||
| "workweek"
|
||||
| "day";
|
||||
export type Range = { start: Date; end: Date };
|
||||
export type AgendaGroup = {
|
||||
key: string;
|
||||
date: Date;
|
||||
events: CalendarEvent[];
|
||||
};
|
||||
export type ContinuousViewport = { scrollTop: number; height: number };
|
||||
export type CalendarDayDropTarget = { kind: "day"; key: string };
|
||||
export type CalendarTimeDropTarget = {
|
||||
kind: "time";
|
||||
key: string;
|
||||
minuteOfDay: number;
|
||||
};
|
||||
export type CalendarDropTarget =
|
||||
| CalendarDayDropTarget
|
||||
| CalendarTimeDropTarget
|
||||
| null;
|
||||
export type CalendarDragAction =
|
||||
| { kind: "move"; event: CalendarEvent }
|
||||
| { kind: "resize-start"; event: CalendarEvent }
|
||||
| { kind: "resize-end"; event: CalendarEvent };
|
||||
export type CalendarResizeEdge = "start" | "end";
|
||||
export type CalendarViewPreferences = {
|
||||
dimWeekends: boolean;
|
||||
dimOffHours: boolean;
|
||||
workdayStartHour: number;
|
||||
workdayEndHour: number;
|
||||
continuousVirtualization: boolean;
|
||||
continuousOverscanWeeks: number;
|
||||
alternateContinuousMonths: boolean;
|
||||
};
|
||||
|
||||
export type TimedEventLayoutItem = TimedEventSegment & {
|
||||
column: number;
|
||||
columns: number;
|
||||
};
|
||||
export type TimedOverflowLayoutItem = {
|
||||
key: string;
|
||||
top: number;
|
||||
column: number;
|
||||
columns: number;
|
||||
events: CalendarEvent[];
|
||||
};
|
||||
|
||||
type TimedEventSegment = {
|
||||
event: CalendarEvent;
|
||||
start: Date;
|
||||
end: Date;
|
||||
top: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
export const HOUR_ROW_HEIGHT = 64;
|
||||
export const INITIAL_SCROLL_HOUR = 7;
|
||||
export const CONTINUOUS_WEEK_ROW_HEIGHT = 92;
|
||||
export const DEFAULT_CALENDAR_COLOR = "#5aa99b";
|
||||
const MAX_TIMED_EVENT_COLUMNS = 3;
|
||||
const CALENDAR_MODE_STORAGE_KEY = "govoplan.calendar.mode";
|
||||
const CALENDAR_VIEW_PREFERENCES_STORAGE_KEY =
|
||||
"govoplan.calendar.viewPreferences";
|
||||
const DEFAULT_CALENDAR_VIEW_PREFERENCES: CalendarViewPreferences = {
|
||||
dimWeekends: true,
|
||||
dimOffHours: true,
|
||||
workdayStartHour: 6,
|
||||
workdayEndHour: 20,
|
||||
continuousVirtualization: true,
|
||||
continuousOverscanWeeks: 6,
|
||||
alternateContinuousMonths: true,
|
||||
};
|
||||
|
||||
export function rangeForMode(
|
||||
mode: CalendarMode,
|
||||
focusDate: Date,
|
||||
continuousWeeks: { before: number; after: number },
|
||||
): Range {
|
||||
if (mode === "month") {
|
||||
const start = startOfWeek(startOfMonth(focusDate));
|
||||
return { start, end: addDays(start, 42) };
|
||||
}
|
||||
if (mode === "day") {
|
||||
return {
|
||||
start: startOfDay(focusDate),
|
||||
end: addDays(startOfDay(focusDate), 1),
|
||||
};
|
||||
}
|
||||
if (mode === "continuous") {
|
||||
const start = addDays(
|
||||
startOfWeek(focusDate),
|
||||
-continuousWeeks.before * 7,
|
||||
);
|
||||
const end = addDays(
|
||||
startOfWeek(focusDate),
|
||||
continuousWeeks.after * 7,
|
||||
);
|
||||
return { start, end };
|
||||
}
|
||||
const start = startOfWeek(focusDate);
|
||||
return { start, end: addDays(start, mode === "workweek" ? 5 : 7) };
|
||||
}
|
||||
|
||||
export function daysForMode(
|
||||
mode: CalendarMode,
|
||||
focusDate: Date,
|
||||
continuousWeeks: { before: number; after: number },
|
||||
): Date[] {
|
||||
const range = rangeForMode(mode, focusDate, continuousWeeks);
|
||||
return daysBetween(range.start, range.end);
|
||||
}
|
||||
|
||||
export function groupEventsByDay(
|
||||
events: CalendarEvent[],
|
||||
): Map<string, CalendarEvent[]> {
|
||||
const grouped = new Map<string, CalendarEvent[]>();
|
||||
for (const event of events) {
|
||||
const start = new Date(event.start_at);
|
||||
const end = event.end_at ? new Date(event.end_at) : start;
|
||||
let cursor = startOfDay(start);
|
||||
let last =
|
||||
event.all_day && event.end_at
|
||||
? addDays(startOfDay(end), -1)
|
||||
: startOfDay(end);
|
||||
if (last < cursor) last = cursor;
|
||||
while (cursor <= last) {
|
||||
const key = dayKey(cursor);
|
||||
grouped.set(key, [...(grouped.get(key) ?? []), event]);
|
||||
cursor = addDays(cursor, 1);
|
||||
}
|
||||
}
|
||||
for (const [key, items] of grouped.entries()) {
|
||||
grouped.set(
|
||||
key,
|
||||
items.sort(
|
||||
(left, right) =>
|
||||
left.start_at.localeCompare(right.start_at) ||
|
||||
left.summary.localeCompare(right.summary),
|
||||
),
|
||||
);
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
|
||||
export function agendaGroupsForDays(
|
||||
days: Date[],
|
||||
eventsByDay: Map<string, CalendarEvent[]>,
|
||||
): AgendaGroup[] {
|
||||
const groups: AgendaGroup[] = [];
|
||||
for (const day of days) {
|
||||
const key = dayKey(day);
|
||||
const events = (eventsByDay.get(key) ?? [])
|
||||
.slice()
|
||||
.sort(compareAgendaEvents);
|
||||
if (events.length > 0) groups.push({ key, date: day, events });
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function eventTimeLabel(event: CalendarEvent): string {
|
||||
if (event.all_day) return "i18n:govoplan-calendar.all_day.11457433";
|
||||
const start = new Date(event.start_at);
|
||||
const end = event.end_at ? new Date(event.end_at) : null;
|
||||
return end ? `${timeLabel(start)}-${timeLabel(end)}` : timeLabel(start);
|
||||
}
|
||||
|
||||
export function dateTimeLabel(value: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
export function headingForMode(
|
||||
mode: CalendarMode,
|
||||
focusDate: Date,
|
||||
range: Range,
|
||||
): string {
|
||||
if (mode === "day") return dayMonthYearLabel(focusDate);
|
||||
if (mode === "month") return monthYearLabel(focusDate);
|
||||
return `${dayMonthYearLabel(range.start)} - ${dayMonthYearLabel(
|
||||
addDays(range.end, -1),
|
||||
)}`;
|
||||
}
|
||||
|
||||
export function chunk<T>(items: T[], size: number): T[][] {
|
||||
const rows: T[][] = [];
|
||||
for (let index = 0; index < items.length; index += size) {
|
||||
rows.push(items.slice(index, index + size));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function startOfDay(value: Date): Date {
|
||||
return new Date(value.getFullYear(), value.getMonth(), value.getDate());
|
||||
}
|
||||
|
||||
export function startOfWeek(value: Date): Date {
|
||||
const day = value.getDay() || 7;
|
||||
return addDays(startOfDay(value), 1 - day);
|
||||
}
|
||||
|
||||
export function startOfMonth(value: Date): Date {
|
||||
return new Date(value.getFullYear(), value.getMonth(), 1);
|
||||
}
|
||||
|
||||
export function addDays(value: Date, days: number): Date {
|
||||
const next = new Date(value);
|
||||
next.setDate(next.getDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function addMonths(value: Date, months: number): Date {
|
||||
const next = new Date(value);
|
||||
next.setMonth(next.getMonth() + months);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function addHours(value: Date, hours: number): Date {
|
||||
const next = new Date(value);
|
||||
next.setHours(next.getHours() + hours);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function addMinutes(value: Date, minutes: number): Date {
|
||||
const next = new Date(value);
|
||||
next.setMinutes(next.getMinutes() + minutes);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function daysBetween(start: Date, end: Date): Date[] {
|
||||
const days: Date[] = [];
|
||||
for (
|
||||
let cursor = startOfDay(start);
|
||||
cursor < end;
|
||||
cursor = addDays(cursor, 1)
|
||||
) {
|
||||
days.push(cursor);
|
||||
}
|
||||
return days;
|
||||
}
|
||||
|
||||
export function dayKey(value: Date): string {
|
||||
return toInputDate(value);
|
||||
}
|
||||
|
||||
export function sameDay(left: Date, right: Date): boolean {
|
||||
return (
|
||||
left.getFullYear() === right.getFullYear() &&
|
||||
left.getMonth() === right.getMonth() &&
|
||||
left.getDate() === right.getDate()
|
||||
);
|
||||
}
|
||||
|
||||
export function sameMonth(left: Date, right: Date): boolean {
|
||||
return (
|
||||
left.getFullYear() === right.getFullYear() &&
|
||||
left.getMonth() === right.getMonth()
|
||||
);
|
||||
}
|
||||
|
||||
export function toInputDate(value: Date): string {
|
||||
return `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(
|
||||
2,
|
||||
"0",
|
||||
)}-${String(value.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function toInputTime(value: Date): string {
|
||||
return `${String(value.getHours()).padStart(2, "0")}:${String(
|
||||
value.getMinutes(),
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function localDateTime(date: string, time: string): Date {
|
||||
return new Date(`${date}T${time || "00:00"}:00`);
|
||||
}
|
||||
|
||||
export function loadCalendarViewPreferences(): CalendarViewPreferences {
|
||||
if (typeof window === "undefined") return DEFAULT_CALENDAR_VIEW_PREFERENCES;
|
||||
try {
|
||||
const raw = window.localStorage.getItem(
|
||||
CALENDAR_VIEW_PREFERENCES_STORAGE_KEY,
|
||||
);
|
||||
if (!raw) return DEFAULT_CALENDAR_VIEW_PREFERENCES;
|
||||
const parsed = JSON.parse(raw) as Partial<CalendarViewPreferences>;
|
||||
let workdayStartHour = clampNumber(
|
||||
parsed.workdayStartHour,
|
||||
0,
|
||||
23,
|
||||
DEFAULT_CALENDAR_VIEW_PREFERENCES.workdayStartHour,
|
||||
);
|
||||
let workdayEndHour = clampNumber(
|
||||
parsed.workdayEndHour,
|
||||
1,
|
||||
24,
|
||||
DEFAULT_CALENDAR_VIEW_PREFERENCES.workdayEndHour,
|
||||
);
|
||||
if (workdayEndHour <= workdayStartHour) {
|
||||
workdayStartHour =
|
||||
DEFAULT_CALENDAR_VIEW_PREFERENCES.workdayStartHour;
|
||||
workdayEndHour = DEFAULT_CALENDAR_VIEW_PREFERENCES.workdayEndHour;
|
||||
}
|
||||
return {
|
||||
dimWeekends:
|
||||
typeof parsed.dimWeekends === "boolean"
|
||||
? parsed.dimWeekends
|
||||
: DEFAULT_CALENDAR_VIEW_PREFERENCES.dimWeekends,
|
||||
dimOffHours:
|
||||
typeof parsed.dimOffHours === "boolean"
|
||||
? parsed.dimOffHours
|
||||
: DEFAULT_CALENDAR_VIEW_PREFERENCES.dimOffHours,
|
||||
workdayStartHour,
|
||||
workdayEndHour,
|
||||
continuousVirtualization:
|
||||
typeof parsed.continuousVirtualization === "boolean"
|
||||
? parsed.continuousVirtualization
|
||||
: DEFAULT_CALENDAR_VIEW_PREFERENCES.continuousVirtualization,
|
||||
continuousOverscanWeeks: clampNumber(
|
||||
parsed.continuousOverscanWeeks,
|
||||
2,
|
||||
20,
|
||||
DEFAULT_CALENDAR_VIEW_PREFERENCES.continuousOverscanWeeks,
|
||||
),
|
||||
alternateContinuousMonths:
|
||||
typeof parsed.alternateContinuousMonths === "boolean"
|
||||
? parsed.alternateContinuousMonths
|
||||
: DEFAULT_CALENDAR_VIEW_PREFERENCES.alternateContinuousMonths,
|
||||
};
|
||||
} catch {
|
||||
return DEFAULT_CALENDAR_VIEW_PREFERENCES;
|
||||
}
|
||||
}
|
||||
|
||||
export function loadCalendarMode(): CalendarMode {
|
||||
if (typeof window === "undefined") return "continuous";
|
||||
try {
|
||||
const storedMode = window.localStorage.getItem(
|
||||
CALENDAR_MODE_STORAGE_KEY,
|
||||
);
|
||||
return isCalendarMode(storedMode) ? storedMode : "continuous";
|
||||
} catch {
|
||||
return "continuous";
|
||||
}
|
||||
}
|
||||
|
||||
export function saveCalendarMode(mode: CalendarMode): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(CALENDAR_MODE_STORAGE_KEY, mode);
|
||||
} catch {
|
||||
// Storage can be unavailable in locked-down browsers.
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeHexColor(
|
||||
value: string | null | undefined,
|
||||
): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
if (/^#[0-9a-fA-F]{8}$/.test(trimmed)) {
|
||||
return trimmed.slice(0, 7).toLowerCase();
|
||||
}
|
||||
return /^#[0-9a-fA-F]{6}$/.test(trimmed)
|
||||
? trimmed.toLowerCase()
|
||||
: null;
|
||||
}
|
||||
|
||||
export function calendarEventColorStyle(
|
||||
color: string | null | undefined,
|
||||
): CSSProperties {
|
||||
const normalizedColor =
|
||||
normalizeHexColor(color) || DEFAULT_CALENDAR_COLOR;
|
||||
return {
|
||||
"--calendar-event-color": normalizedColor,
|
||||
"--calendar-event-bg": mixHexWithWhite(normalizedColor, 0.88),
|
||||
"--calendar-event-border": mixHexWithWhite(normalizedColor, 0.58),
|
||||
} as CSSProperties;
|
||||
}
|
||||
|
||||
export function continuousVirtualWindow(
|
||||
weekCount: number,
|
||||
viewport: ContinuousViewport,
|
||||
overscanWeeks: number,
|
||||
): {
|
||||
start: number;
|
||||
end: number;
|
||||
topSpacerHeight: number;
|
||||
bottomSpacerHeight: number;
|
||||
} {
|
||||
if (weekCount === 0) {
|
||||
return {
|
||||
start: 0,
|
||||
end: 0,
|
||||
topSpacerHeight: 0,
|
||||
bottomSpacerHeight: 0,
|
||||
};
|
||||
}
|
||||
const visibleStart = Math.floor(
|
||||
viewport.scrollTop / CONTINUOUS_WEEK_ROW_HEIGHT,
|
||||
);
|
||||
const visibleCount = Math.max(
|
||||
1,
|
||||
Math.ceil(
|
||||
(viewport.height || CONTINUOUS_WEEK_ROW_HEIGHT * 8) /
|
||||
CONTINUOUS_WEEK_ROW_HEIGHT,
|
||||
),
|
||||
);
|
||||
const start = Math.max(0, visibleStart - overscanWeeks);
|
||||
const end = Math.min(
|
||||
weekCount,
|
||||
visibleStart + visibleCount + overscanWeeks,
|
||||
);
|
||||
return {
|
||||
start,
|
||||
end,
|
||||
topSpacerHeight: start * CONTINUOUS_WEEK_ROW_HEIGHT,
|
||||
bottomSpacerHeight: Math.max(
|
||||
0,
|
||||
(weekCount - end) * CONTINUOUS_WEEK_ROW_HEIGHT,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function timeGridStyle(
|
||||
columns: string,
|
||||
preferences: CalendarViewPreferences,
|
||||
): CSSProperties {
|
||||
return {
|
||||
gridTemplateColumns: columns,
|
||||
"--calendar-work-start-y": `${
|
||||
preferences.workdayStartHour * HOUR_ROW_HEIGHT
|
||||
}px`,
|
||||
"--calendar-work-end-y": `${
|
||||
preferences.workdayEndHour * HOUR_ROW_HEIGHT
|
||||
}px`,
|
||||
"--calendar-off-hours-opacity": preferences.dimOffHours ? "1" : "0",
|
||||
} as CSSProperties;
|
||||
}
|
||||
|
||||
export function moveEventToDay(
|
||||
event: CalendarEvent,
|
||||
day: Date,
|
||||
): { startAt: Date; endAt: Date | null; allDay: boolean } {
|
||||
const start = new Date(event.start_at);
|
||||
const end = event.end_at ? new Date(event.end_at) : null;
|
||||
if (event.all_day) {
|
||||
const durationDays = Math.max(
|
||||
1,
|
||||
Math.round(
|
||||
daysBetweenCount(
|
||||
startOfDay(start),
|
||||
end ? startOfDay(end) : addDays(startOfDay(start), 1),
|
||||
),
|
||||
),
|
||||
);
|
||||
const startAt = startOfDay(day);
|
||||
return {
|
||||
startAt,
|
||||
endAt: addDays(startAt, durationDays),
|
||||
allDay: true,
|
||||
};
|
||||
}
|
||||
const startAt = new Date(
|
||||
day.getFullYear(),
|
||||
day.getMonth(),
|
||||
day.getDate(),
|
||||
start.getHours(),
|
||||
start.getMinutes(),
|
||||
);
|
||||
const durationMs = eventDurationMs(event, 60 * 60 * 1000);
|
||||
return {
|
||||
startAt,
|
||||
endAt: new Date(startAt.getTime() + durationMs),
|
||||
allDay: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function moveEventToTime(
|
||||
event: CalendarEvent,
|
||||
day: Date,
|
||||
minuteOfDay: number,
|
||||
): { startAt: Date; endAt: Date | null; allDay: boolean } {
|
||||
const snappedMinute = Math.min(
|
||||
23 * 60 + 45,
|
||||
Math.max(0, snapMinute(minuteOfDay)),
|
||||
);
|
||||
const startAt = dateAtMinuteOfDay(day, snappedMinute);
|
||||
const durationMs = event.all_day
|
||||
? 60 * 60 * 1000
|
||||
: eventDurationMs(event, 60 * 60 * 1000);
|
||||
return {
|
||||
startAt,
|
||||
endAt: new Date(startAt.getTime() + durationMs),
|
||||
allDay: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function resizeEventToTime(
|
||||
event: CalendarEvent,
|
||||
edge: CalendarResizeEdge,
|
||||
day: Date,
|
||||
minuteOfDay: number,
|
||||
): { startAt: Date; endAt: Date | null; allDay: boolean } {
|
||||
const target = dateAtMinuteOfDay(
|
||||
day,
|
||||
Math.min(23 * 60 + 45, Math.max(0, snapMinute(minuteOfDay))),
|
||||
);
|
||||
const currentStart = new Date(event.start_at);
|
||||
const fallbackEnd = addMinutes(currentStart, 30);
|
||||
const currentEnd =
|
||||
event.end_at && new Date(event.end_at) > currentStart
|
||||
? new Date(event.end_at)
|
||||
: fallbackEnd;
|
||||
const minimumDurationMs = 15 * 60_000;
|
||||
if (edge === "start") {
|
||||
const latestStart = new Date(
|
||||
currentEnd.getTime() - minimumDurationMs,
|
||||
);
|
||||
return {
|
||||
startAt: target < latestStart ? target : latestStart,
|
||||
endAt: currentEnd,
|
||||
allDay: false,
|
||||
};
|
||||
}
|
||||
const earliestEnd = new Date(
|
||||
currentStart.getTime() + minimumDurationMs,
|
||||
);
|
||||
return {
|
||||
startAt: currentStart,
|
||||
endAt: target > earliestEnd ? target : earliestEnd,
|
||||
allDay: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function dropMinuteOfDay(
|
||||
event: ReactDragEvent<HTMLElement>,
|
||||
): number {
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
const offset = Math.min(
|
||||
Math.max(event.clientY - rect.top, 0),
|
||||
HOUR_ROW_HEIGHT * 24,
|
||||
);
|
||||
return Math.floor((offset / HOUR_ROW_HEIGHT) * 60);
|
||||
}
|
||||
|
||||
export function dropSlotMinuteOfDay(
|
||||
event: ReactDragEvent<HTMLElement>,
|
||||
): number {
|
||||
return Math.min(
|
||||
23 * 60 + 45,
|
||||
Math.max(0, snapMinute(dropMinuteOfDay(event))),
|
||||
);
|
||||
}
|
||||
|
||||
export function minuteOfDayLabel(value: number): string {
|
||||
const minute = Math.min(23 * 60 + 45, Math.max(0, value));
|
||||
return `${String(Math.floor(minute / 60)).padStart(2, "0")}:${String(
|
||||
minute % 60,
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function isWeekend(value: Date): boolean {
|
||||
const day = value.getDay();
|
||||
return day === 0 || day === 6;
|
||||
}
|
||||
|
||||
export function daysBetweenCount(start: Date, end: Date): number {
|
||||
return Math.round(
|
||||
(startOfDay(end).getTime() - startOfDay(start).getTime()) / 86_400_000,
|
||||
);
|
||||
}
|
||||
|
||||
export function addMinutesToTime(
|
||||
time: string,
|
||||
minutes: number,
|
||||
): string {
|
||||
const [hourPart, minutePart] = time.split(":");
|
||||
const total = Math.min(
|
||||
23 * 60 + 59,
|
||||
Math.max(
|
||||
0,
|
||||
Number(hourPart || 0) * 60 + Number(minutePart || 0) + minutes,
|
||||
),
|
||||
);
|
||||
return `${String(Math.floor(total / 60)).padStart(2, "0")}:${String(
|
||||
total % 60,
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function layoutTimedEventsForDay(
|
||||
events: CalendarEvent[],
|
||||
day: Date,
|
||||
): {
|
||||
items: TimedEventLayoutItem[];
|
||||
overflows: TimedOverflowLayoutItem[];
|
||||
} {
|
||||
const segments = timedSegmentsForDay(events, day);
|
||||
const clusters = clusterTimedSegments(segments);
|
||||
const items: TimedEventLayoutItem[] = [];
|
||||
const overflows: TimedOverflowLayoutItem[] = [];
|
||||
|
||||
for (const cluster of clusters) {
|
||||
const columnEnds: Date[] = [];
|
||||
const assigned = cluster.map((segment) => {
|
||||
let column = columnEnds.findIndex((end) => end <= segment.start);
|
||||
if (column === -1) column = columnEnds.length;
|
||||
columnEnds[column] = segment.end;
|
||||
return { ...segment, column };
|
||||
});
|
||||
const totalColumns = Math.max(1, columnEnds.length);
|
||||
const visibleColumns =
|
||||
totalColumns > MAX_TIMED_EVENT_COLUMNS
|
||||
? MAX_TIMED_EVENT_COLUMNS
|
||||
: totalColumns;
|
||||
const overflowColumn = MAX_TIMED_EVENT_COLUMNS - 1;
|
||||
const hidden =
|
||||
totalColumns > MAX_TIMED_EVENT_COLUMNS
|
||||
? assigned.filter((item) => item.column >= overflowColumn)
|
||||
: [];
|
||||
|
||||
for (const item of assigned) {
|
||||
if (hidden.includes(item)) continue;
|
||||
items.push({ ...item, columns: visibleColumns });
|
||||
}
|
||||
if (hidden.length > 0) {
|
||||
overflows.push({
|
||||
key: `${dayKey(day)}-${hidden[0].event.id}-overflow`,
|
||||
top: Math.min(...hidden.map((item) => item.top)),
|
||||
column: overflowColumn,
|
||||
columns: MAX_TIMED_EVENT_COLUMNS,
|
||||
events: hidden.map((item) => item.event),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { items, overflows };
|
||||
}
|
||||
|
||||
export function timedEventStyle(
|
||||
item: TimedEventLayoutItem,
|
||||
color?: string | null,
|
||||
): CSSProperties {
|
||||
return {
|
||||
top: `${item.top}px`,
|
||||
height: `${item.height}px`,
|
||||
left: `calc(${(item.column * 100) / item.columns}% + 4px)`,
|
||||
width: `calc(${100 / item.columns}% - 8px)`,
|
||||
...calendarEventColorStyle(color),
|
||||
};
|
||||
}
|
||||
|
||||
export function timedOverflowStyle(
|
||||
item: TimedOverflowLayoutItem,
|
||||
): CSSProperties {
|
||||
return {
|
||||
top: `${item.top}px`,
|
||||
left: `calc(${(item.column * 100) / item.columns}% + 4px)`,
|
||||
width: `calc(${100 / item.columns}% - 8px)`,
|
||||
};
|
||||
}
|
||||
|
||||
export function monthYearLabel(value: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
export function dayMonthLabel(value: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
export function dayMonthYearLabel(value: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
export function agendaDateLabel(value: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
weekday: "short",
|
||||
day: "2-digit",
|
||||
month: "short",
|
||||
year: "numeric",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
export function weekdayLong(value: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
weekday: "short",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
export function calendarDraftKey(value: unknown): string {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export function mergeCalendarEventDelta(
|
||||
current: CalendarEvent[],
|
||||
response: CalendarEventDeltaResponse,
|
||||
): CalendarEvent[] {
|
||||
if (response.full) {
|
||||
return response.events.slice().sort(compareCalendarEvents);
|
||||
}
|
||||
const rows = new Map(current.map((event) => [event.id, event]));
|
||||
for (const deleted of response.deleted) {
|
||||
if (
|
||||
!deleted.resource_type ||
|
||||
deleted.resource_type === "calendar_event"
|
||||
) {
|
||||
rows.delete(deleted.id);
|
||||
}
|
||||
}
|
||||
for (const event of response.events) rows.set(event.id, event);
|
||||
return Array.from(rows.values()).sort(compareCalendarEvents);
|
||||
}
|
||||
|
||||
export function errorText(error: unknown): string {
|
||||
if (error instanceof Error) return error.message;
|
||||
return "i18n:govoplan-calendar.calendar_request_failed.ae8a54f4";
|
||||
}
|
||||
|
||||
function isCalendarMode(value: unknown): value is CalendarMode {
|
||||
return (
|
||||
value === "continuous" ||
|
||||
value === "month" ||
|
||||
value === "week" ||
|
||||
value === "workweek" ||
|
||||
value === "day"
|
||||
);
|
||||
}
|
||||
|
||||
function mixHexWithWhite(hex: string, whiteRatio: number): string {
|
||||
const normalized = normalizeHexColor(hex) || DEFAULT_CALENDAR_COLOR;
|
||||
const ratio = Math.min(1, Math.max(0, whiteRatio));
|
||||
const red = Number.parseInt(normalized.slice(1, 3), 16);
|
||||
const green = Number.parseInt(normalized.slice(3, 5), 16);
|
||||
const blue = Number.parseInt(normalized.slice(5, 7), 16);
|
||||
return `rgb(${Math.round(red * (1 - ratio) + 255 * ratio)}, ${Math.round(
|
||||
green * (1 - ratio) + 255 * ratio,
|
||||
)}, ${Math.round(blue * (1 - ratio) + 255 * ratio)})`;
|
||||
}
|
||||
|
||||
function eventDurationMs(event: CalendarEvent, fallback: number): number {
|
||||
if (!event.end_at) return fallback;
|
||||
const start = new Date(event.start_at);
|
||||
const end = new Date(event.end_at);
|
||||
return Math.max(30 * 60 * 1000, end.getTime() - start.getTime());
|
||||
}
|
||||
|
||||
function dateAtMinuteOfDay(day: Date, minuteOfDay: number): Date {
|
||||
return new Date(
|
||||
day.getFullYear(),
|
||||
day.getMonth(),
|
||||
day.getDate(),
|
||||
Math.floor(minuteOfDay / 60),
|
||||
minuteOfDay % 60,
|
||||
);
|
||||
}
|
||||
|
||||
function snapMinute(value: number): number {
|
||||
return Math.round(value / 15) * 15;
|
||||
}
|
||||
|
||||
function clampNumber(
|
||||
value: unknown,
|
||||
min: number,
|
||||
max: number,
|
||||
fallback: number,
|
||||
): number {
|
||||
if (typeof value !== "number" || Number.isNaN(value)) return fallback;
|
||||
return Math.min(max, Math.max(min, Math.round(value)));
|
||||
}
|
||||
|
||||
function timedSegmentsForDay(
|
||||
events: CalendarEvent[],
|
||||
day: Date,
|
||||
): TimedEventSegment[] {
|
||||
const dayStart = startOfDay(day);
|
||||
const dayEnd = addDays(dayStart, 1);
|
||||
return events
|
||||
.filter((event) => !event.all_day)
|
||||
.map((event): TimedEventSegment | null => {
|
||||
const eventStart = new Date(event.start_at);
|
||||
const rawEventEnd = event.end_at
|
||||
? new Date(event.end_at)
|
||||
: addMinutes(eventStart, 30);
|
||||
const eventEnd =
|
||||
rawEventEnd > eventStart ? rawEventEnd : addMinutes(eventStart, 30);
|
||||
const start = eventStart < dayStart ? dayStart : eventStart;
|
||||
const end = eventEnd > dayEnd ? dayEnd : eventEnd;
|
||||
if (end <= start) return null;
|
||||
const startMinutes = minutesBetween(dayStart, start);
|
||||
const durationMinutes = minutesBetween(start, end);
|
||||
return {
|
||||
event,
|
||||
start,
|
||||
end,
|
||||
top: Math.max(0, (startMinutes / 60) * HOUR_ROW_HEIGHT),
|
||||
height: Math.max(
|
||||
26,
|
||||
(durationMinutes / 60) * HOUR_ROW_HEIGHT,
|
||||
),
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(segment): segment is TimedEventSegment => segment !== null,
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.start.getTime() - right.start.getTime() ||
|
||||
right.end.getTime() - left.end.getTime(),
|
||||
);
|
||||
}
|
||||
|
||||
function clusterTimedSegments(
|
||||
segments: TimedEventSegment[],
|
||||
): TimedEventSegment[][] {
|
||||
const clusters: TimedEventSegment[][] = [];
|
||||
let current: TimedEventSegment[] = [];
|
||||
let currentEnd: Date | null = null;
|
||||
for (const segment of segments) {
|
||||
if (!current.length || (currentEnd && segment.start < currentEnd)) {
|
||||
current.push(segment);
|
||||
if (!currentEnd || segment.end.getTime() > currentEnd.getTime()) {
|
||||
currentEnd = segment.end;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
clusters.push(current);
|
||||
current = [segment];
|
||||
currentEnd = segment.end;
|
||||
}
|
||||
if (current.length) clusters.push(current);
|
||||
return clusters;
|
||||
}
|
||||
|
||||
function minutesBetween(start: Date, end: Date): number {
|
||||
return Math.max(0, (end.getTime() - start.getTime()) / 60_000);
|
||||
}
|
||||
|
||||
function compareAgendaEvents(
|
||||
left: CalendarEvent,
|
||||
right: CalendarEvent,
|
||||
): number {
|
||||
if (left.all_day !== right.all_day) return left.all_day ? -1 : 1;
|
||||
return (
|
||||
left.start_at.localeCompare(right.start_at) ||
|
||||
left.summary.localeCompare(right.summary)
|
||||
);
|
||||
}
|
||||
|
||||
function timeLabel(value: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
function compareCalendarEvents(
|
||||
left: CalendarEvent,
|
||||
right: CalendarEvent,
|
||||
): number {
|
||||
return (
|
||||
new Date(left.start_at).getTime() -
|
||||
new Date(right.start_at).getTime() ||
|
||||
left.summary.localeCompare(right.summary) ||
|
||||
left.id.localeCompare(right.id)
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.calendar_source_type.92cdb42f": "Calendar source type",
|
||||
"i18n:govoplan-calendar.calendar_views.9e6b9c2b": "Calendar views",
|
||||
"i18n:govoplan-calendar.calendar.adab5090": "Calendar",
|
||||
"i18n:govoplan-calendar.calendars_are_unavailable.f074c862": "Calendars are unavailable.",
|
||||
"i18n:govoplan-calendar.calendars.94445018": "Calendars",
|
||||
"i18n:govoplan-calendar.cancel.77dfd213": "Cancel",
|
||||
"i18n:govoplan-calendar.cancelled.5587b0af": "CANCELLED",
|
||||
@@ -38,7 +39,6 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.confirmed.0542404a": "CONFIRMED",
|
||||
"i18n:govoplan-calendar.conflict_policy.5810e150": "Conflict policy",
|
||||
"i18n:govoplan-calendar.continuous.04f2ccda": "Continuous",
|
||||
"i18n:govoplan-calendar.credential_reference.a7e92de5": "Credential reference",
|
||||
"i18n:govoplan-calendar.credential.8bede3ea": "Credential",
|
||||
"i18n:govoplan-calendar.dav_url.4205e180": "DAV URL",
|
||||
"i18n:govoplan-calendar.day.987b9ced": "Day",
|
||||
@@ -46,6 +46,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.delete.f6fdbe48": "Delete",
|
||||
"i18n:govoplan-calendar.deleting.2cda36c9": "Deleting",
|
||||
"i18n:govoplan-calendar.description.55f8ebc8": "Description",
|
||||
"i18n:govoplan-calendar.detach_local_events_and_keep_remote_events.c58ad4e7": "Detach local events and keep remote events",
|
||||
"i18n:govoplan-calendar.direction.fd8e45ba": "Direction",
|
||||
"i18n:govoplan-calendar.discover.4827ea22": "Discover",
|
||||
"i18n:govoplan-calendar.discovering.1884f689": "Discovering...",
|
||||
@@ -61,18 +62,21 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.end_date.89d10cd6": "End date",
|
||||
"i18n:govoplan-calendar.end_mode.5a06de37": "End mode",
|
||||
"i18n:govoplan-calendar.end_time.cd7800da": "End time",
|
||||
"i18n:govoplan-calendar.enter_a_secret_now_or_use_an_environment_referen.6db0e6ce": "Enter a secret now or use an environment reference such as",
|
||||
"i18n:govoplan-calendar.enter_a_password_or_token_for_this_source.74c09a54": "Enter a password or token for this source.",
|
||||
"i18n:govoplan-calendar.etag.11d00f6e": "ETag",
|
||||
"i18n:govoplan-calendar.event": "event",
|
||||
"i18n:govoplan-calendar.event_count_could_not_be_loaded_the_backend_will.163ff055": "Event count could not be loaded. The backend will still apply the selected delete action.",
|
||||
"i18n:govoplan-calendar.events": "events",
|
||||
"i18n:govoplan-calendar.events_are_stored_in_govoplan_and_are_not_synced.3660e504": "Events are stored in GovOPlaN and are not synced to an external calendar source.",
|
||||
"i18n:govoplan-calendar.events_remain_in_govoplan_no_external_calendar_is_.62cb5937": "Events remain in GovOPlaN; no external calendar is changed.",
|
||||
"i18n:govoplan-calendar.ews_endpoint.a3273983": "EWS endpoint",
|
||||
"i18n:govoplan-calendar.exchange_web_services_source.53caabf3": "Exchange Web Services source",
|
||||
"i18n:govoplan-calendar.exchange.5b13eac7": "Exchange",
|
||||
"i18n:govoplan-calendar.exdate_json.7d0c538d": "EXDATE JSON",
|
||||
"i18n:govoplan-calendar.fri.bbd6e32e": "Fri",
|
||||
"i18n:govoplan-calendar.full_sync.21b89c76": "Full sync",
|
||||
"i18n:govoplan-calendar.govoplan_moves_the_events_locally_and_queues_durab.da075b16": "GovOPlaN moves the events locally and queues durable CalDAV copies. Delivery failures remain visible and retryable.",
|
||||
"i18n:govoplan-calendar.govoplan_moves_the_local_event_copies_to_the_targe.4863e46b": "GovOPlaN moves the local event copies to the target calendar and unlinks this source. The remote calendar and its events remain unchanged.",
|
||||
"i18n:govoplan-calendar.graph_calendar_url.e59607f3": "Graph calendar URL",
|
||||
"i18n:govoplan-calendar.graph.9a7405eb": "Graph",
|
||||
"i18n:govoplan-calendar.icalendar_json.fb6cc33e": "iCalendar JSON",
|
||||
@@ -85,6 +89,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.last_attempt.82aee111": "Last attempt",
|
||||
"i18n:govoplan-calendar.last_sync.ef0ef267": "Last sync",
|
||||
"i18n:govoplan-calendar.loading_calendar.7eb8f548": "Loading calendar...",
|
||||
"i18n:govoplan-calendar.loading_calendars.afbb957b": "Loading calendars...",
|
||||
"i18n:govoplan-calendar.loading_event_count.716ad3c2": "Loading event count...",
|
||||
"i18n:govoplan-calendar.local_calendar.ed3f72f8": "Local calendar",
|
||||
"i18n:govoplan-calendar.local.dc99d54d": "Local",
|
||||
@@ -96,6 +101,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.microsoft_graph_source.ec4f1383": "Microsoft Graph source",
|
||||
"i18n:govoplan-calendar.mon.24b2a099": "Mon",
|
||||
"i18n:govoplan-calendar.month.082bc378": "Month",
|
||||
"i18n:govoplan-calendar.move_and_copy_events_to_the_external_calendar.23c3a004": "Move and copy events to the external calendar",
|
||||
"i18n:govoplan-calendar.move_events_to_another_calendar.830c7b09": "Move events to another calendar",
|
||||
"i18n:govoplan-calendar.name.709a2322": "Name",
|
||||
"i18n:govoplan-calendar.never.80c3052d": "Never",
|
||||
@@ -103,9 +109,12 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.new.6403f2b7": "New",
|
||||
"i18n:govoplan-calendar.next_sync.88c7af72": "Next sync",
|
||||
"i18n:govoplan-calendar.next.bc981983": "Next",
|
||||
"i18n:govoplan-calendar.no_compatible_target_calendar_is_available_add_a_l.1cf6e47b": "No compatible target calendar is available. Add a local calendar or an active two-way CalDAV calendar.",
|
||||
"i18n:govoplan-calendar.no_calendar_collections_found.6453624a": "No calendar collections found.",
|
||||
"i18n:govoplan-calendar.no_calendars_are_available.711d2cf3": "No calendars are available.",
|
||||
"i18n:govoplan-calendar.no_calendars.3a7e4a7a": "No calendars",
|
||||
"i18n:govoplan-calendar.no_events.e339ba73": "No events",
|
||||
"i18n:govoplan-calendar.no_local_target_calendar_is_available_add_a_local_.fad3cb65": "No local target calendar is available. Add a local calendar to detach these events without changing the remote calendar.",
|
||||
"i18n:govoplan-calendar.none.6eef6648": "None",
|
||||
"i18n:govoplan-calendar.not_configured.811931bb": "Not configured",
|
||||
"i18n:govoplan-calendar.not_scheduled.9c367369": "Not scheduled",
|
||||
@@ -140,6 +149,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.save.efc007a3": "Save",
|
||||
"i18n:govoplan-calendar.saving.ae7e8875": "Saving...",
|
||||
"i18n:govoplan-calendar.sequence.5c8f4e0e": "Sequence",
|
||||
"i18n:govoplan-calendar.select_calendar.f38b5ba2": "Select calendar",
|
||||
"i18n:govoplan-calendar.show_value.60e2ce8e": "Show {value0}",
|
||||
"i18n:govoplan-calendar.source_href.819fa147": "Source href",
|
||||
"i18n:govoplan-calendar.source_kind.7eda9bc4": "Source kind",
|
||||
@@ -158,6 +168,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.target_calendar.e533fe1d": "Target calendar",
|
||||
"i18n:govoplan-calendar.tentative.d19f9022": "TENTATIVE",
|
||||
"i18n:govoplan-calendar.the_selected_calendar.67caa12f": "the selected calendar",
|
||||
"i18n:govoplan-calendar.the_selected_calendar_is_no_longer_available.39f0f1f5": "The selected calendar is no longer available.",
|
||||
"i18n:govoplan-calendar.thu.3593ccd9": "Thu",
|
||||
"i18n:govoplan-calendar.timezone.d1f7dc89": "Timezone",
|
||||
"i18n:govoplan-calendar.title.768e0c1c": "Title",
|
||||
@@ -201,6 +212,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.calendar_source_type.92cdb42f": "Calendar source type",
|
||||
"i18n:govoplan-calendar.calendar_views.9e6b9c2b": "Calendar views",
|
||||
"i18n:govoplan-calendar.calendar.adab5090": "Kalender",
|
||||
"i18n:govoplan-calendar.calendars_are_unavailable.f074c862": "Kalender sind nicht verfügbar.",
|
||||
"i18n:govoplan-calendar.calendars.94445018": "Calendars",
|
||||
"i18n:govoplan-calendar.cancel.77dfd213": "Abbrechen",
|
||||
"i18n:govoplan-calendar.cancelled.5587b0af": "CANCELLED",
|
||||
@@ -215,7 +227,6 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.confirmed.0542404a": "CONFIRMED",
|
||||
"i18n:govoplan-calendar.conflict_policy.5810e150": "Conflict policy",
|
||||
"i18n:govoplan-calendar.continuous.04f2ccda": "Continuous",
|
||||
"i18n:govoplan-calendar.credential_reference.a7e92de5": "Credential reference",
|
||||
"i18n:govoplan-calendar.credential.8bede3ea": "Credential",
|
||||
"i18n:govoplan-calendar.dav_url.4205e180": "DAV URL",
|
||||
"i18n:govoplan-calendar.day.987b9ced": "Tag",
|
||||
@@ -223,6 +234,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.delete.f6fdbe48": "Löschen",
|
||||
"i18n:govoplan-calendar.deleting.2cda36c9": "Deleting",
|
||||
"i18n:govoplan-calendar.description.55f8ebc8": "Beschreibung",
|
||||
"i18n:govoplan-calendar.detach_local_events_and_keep_remote_events.c58ad4e7": "Lokale Termine abtrennen und entfernte Termine beibehalten",
|
||||
"i18n:govoplan-calendar.direction.fd8e45ba": "Direction",
|
||||
"i18n:govoplan-calendar.discover.4827ea22": "Discover",
|
||||
"i18n:govoplan-calendar.discovering.1884f689": "Discovering...",
|
||||
@@ -238,18 +250,21 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.end_date.89d10cd6": "End date",
|
||||
"i18n:govoplan-calendar.end_mode.5a06de37": "End mode",
|
||||
"i18n:govoplan-calendar.end_time.cd7800da": "End time",
|
||||
"i18n:govoplan-calendar.enter_a_secret_now_or_use_an_environment_referen.6db0e6ce": "Enter a secret now or use an environment reference such as",
|
||||
"i18n:govoplan-calendar.enter_a_password_or_token_for_this_source.74c09a54": "Geben Sie ein Passwort oder Token für diese Quelle ein.",
|
||||
"i18n:govoplan-calendar.etag.11d00f6e": "ETag",
|
||||
"i18n:govoplan-calendar.event": "event",
|
||||
"i18n:govoplan-calendar.event_count_could_not_be_loaded_the_backend_will.163ff055": "Event count could not be loaded. The backend will still apply the selected delete action.",
|
||||
"i18n:govoplan-calendar.events": "events",
|
||||
"i18n:govoplan-calendar.events_are_stored_in_govoplan_and_are_not_synced.3660e504": "Events are stored in GovOPlaN and are not synced to an external calendar source.",
|
||||
"i18n:govoplan-calendar.events_remain_in_govoplan_no_external_calendar_is_.62cb5937": "Die Termine bleiben in GovOPlaN; kein externer Kalender wird geändert.",
|
||||
"i18n:govoplan-calendar.ews_endpoint.a3273983": "EWS endpoint",
|
||||
"i18n:govoplan-calendar.exchange_web_services_source.53caabf3": "Exchange Web Services source",
|
||||
"i18n:govoplan-calendar.exchange.5b13eac7": "Exchange",
|
||||
"i18n:govoplan-calendar.exdate_json.7d0c538d": "EXDATE JSON",
|
||||
"i18n:govoplan-calendar.fri.bbd6e32e": "Fri",
|
||||
"i18n:govoplan-calendar.full_sync.21b89c76": "Full sync",
|
||||
"i18n:govoplan-calendar.govoplan_moves_the_events_locally_and_queues_durab.da075b16": "GovOPlaN verschiebt die Termine lokal und reiht dauerhafte CalDAV-Kopien ein. Zustellfehler bleiben sichtbar und können erneut versucht werden.",
|
||||
"i18n:govoplan-calendar.govoplan_moves_the_local_event_copies_to_the_targe.4863e46b": "GovOPlaN verschiebt die lokalen Terminkopien in den Zielkalender und trennt diese Quelle. Der entfernte Kalender und seine Termine bleiben unverändert.",
|
||||
"i18n:govoplan-calendar.graph_calendar_url.e59607f3": "Graph calendar URL",
|
||||
"i18n:govoplan-calendar.graph.9a7405eb": "Graph",
|
||||
"i18n:govoplan-calendar.icalendar_json.fb6cc33e": "iCalendar JSON",
|
||||
@@ -262,6 +277,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.last_attempt.82aee111": "Last attempt",
|
||||
"i18n:govoplan-calendar.last_sync.ef0ef267": "Last sync",
|
||||
"i18n:govoplan-calendar.loading_calendar.7eb8f548": "Loading calendar...",
|
||||
"i18n:govoplan-calendar.loading_calendars.afbb957b": "Kalender werden geladen...",
|
||||
"i18n:govoplan-calendar.loading_event_count.716ad3c2": "Loading event count...",
|
||||
"i18n:govoplan-calendar.local_calendar.ed3f72f8": "Local calendar",
|
||||
"i18n:govoplan-calendar.local.dc99d54d": "Local",
|
||||
@@ -273,16 +289,20 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.microsoft_graph_source.ec4f1383": "Microsoft Graph source",
|
||||
"i18n:govoplan-calendar.mon.24b2a099": "Mon",
|
||||
"i18n:govoplan-calendar.month.082bc378": "Monat",
|
||||
"i18n:govoplan-calendar.move_events_to_another_calendar.830c7b09": "Move events to another calendar",
|
||||
"i18n:govoplan-calendar.move_and_copy_events_to_the_external_calendar.23c3a004": "Termine verschieben und in den externen Kalender kopieren",
|
||||
"i18n:govoplan-calendar.move_events_to_another_calendar.830c7b09": "Termine in einen anderen Kalender verschieben",
|
||||
"i18n:govoplan-calendar.name.709a2322": "Name",
|
||||
"i18n:govoplan-calendar.never.80c3052d": "Never",
|
||||
"i18n:govoplan-calendar.new_event.2ef3795c": "New event",
|
||||
"i18n:govoplan-calendar.new.6403f2b7": "New",
|
||||
"i18n:govoplan-calendar.next_sync.88c7af72": "Next sync",
|
||||
"i18n:govoplan-calendar.next.bc981983": "Weiter",
|
||||
"i18n:govoplan-calendar.no_compatible_target_calendar_is_available_add_a_l.1cf6e47b": "Kein kompatibler Zielkalender ist verfügbar. Fügen Sie einen lokalen Kalender oder einen aktiven CalDAV-Kalender mit bidirektionaler Synchronisierung hinzu.",
|
||||
"i18n:govoplan-calendar.no_calendar_collections_found.6453624a": "No calendar collections found.",
|
||||
"i18n:govoplan-calendar.no_calendars_are_available.711d2cf3": "Es sind keine Kalender verfügbar.",
|
||||
"i18n:govoplan-calendar.no_calendars.3a7e4a7a": "No calendars",
|
||||
"i18n:govoplan-calendar.no_events.e339ba73": "No events",
|
||||
"i18n:govoplan-calendar.no_local_target_calendar_is_available_add_a_local_.fad3cb65": "Kein lokaler Zielkalender ist verfügbar. Fügen Sie einen lokalen Kalender hinzu, um diese Termine abzutrennen, ohne den entfernten Kalender zu ändern.",
|
||||
"i18n:govoplan-calendar.none.6eef6648": "Keine",
|
||||
"i18n:govoplan-calendar.not_configured.811931bb": "Nicht konfiguriert",
|
||||
"i18n:govoplan-calendar.not_scheduled.9c367369": "Not scheduled",
|
||||
@@ -317,6 +337,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.save.efc007a3": "Speichern",
|
||||
"i18n:govoplan-calendar.saving.ae7e8875": "Saving...",
|
||||
"i18n:govoplan-calendar.sequence.5c8f4e0e": "Sequence",
|
||||
"i18n:govoplan-calendar.select_calendar.f38b5ba2": "Kalender auswählen",
|
||||
"i18n:govoplan-calendar.show_value.60e2ce8e": "Show {value0}",
|
||||
"i18n:govoplan-calendar.source_href.819fa147": "Source href",
|
||||
"i18n:govoplan-calendar.source_kind.7eda9bc4": "Source kind",
|
||||
@@ -335,6 +356,7 @@ export const generatedTranslations: PlatformTranslations = {
|
||||
"i18n:govoplan-calendar.target_calendar.e533fe1d": "Target calendar",
|
||||
"i18n:govoplan-calendar.tentative.d19f9022": "TENTATIVE",
|
||||
"i18n:govoplan-calendar.the_selected_calendar.67caa12f": "the selected calendar",
|
||||
"i18n:govoplan-calendar.the_selected_calendar_is_no_longer_available.39f0f1f5": "Der ausgewählte Kalender ist nicht mehr verfügbar.",
|
||||
"i18n:govoplan-calendar.thu.3593ccd9": "Thu",
|
||||
"i18n:govoplan-calendar.timezone.d1f7dc89": "Timezone",
|
||||
"i18n:govoplan-calendar.title.768e0c1c": "Title",
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
export { calendarModule as default, calendarModule } from "./module";
|
||||
export * from "./api/calendar";
|
||||
export { default as CalendarPicker } from "./features/calendar/CalendarPicker";
|
||||
export * from "./features/calendar/calendarPickerLogic";
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { createElement, lazy } from "react";
|
||||
import type { PlatformWebModule } from "@govoplan/core-webui";
|
||||
import type {
|
||||
CalendarPickerUiCapability,
|
||||
DashboardWidgetsUiCapability,
|
||||
PlatformWebModule
|
||||
} from "@govoplan/core-webui";
|
||||
import "./styles/calendar.css";
|
||||
import { generatedTranslations } from "./i18n/generatedTranslations";
|
||||
import CalendarPicker from "./features/calendar/CalendarPicker";
|
||||
import UpcomingEventsWidget from "./features/calendar/UpcomingEventsWidget";
|
||||
|
||||
const CalendarPage = lazy(() => import("./features/calendar/CalendarPage"));
|
||||
|
||||
@@ -11,6 +17,62 @@ const translations = {
|
||||
de: generatedTranslations.de
|
||||
};
|
||||
|
||||
const calendarPicker: CalendarPickerUiCapability = { CalendarPicker };
|
||||
const calendarDashboardWidgets: DashboardWidgetsUiCapability = {
|
||||
widgets: [
|
||||
{
|
||||
id: "calendar.upcoming",
|
||||
surfaceId: "calendar.widget.upcoming",
|
||||
title: "Upcoming events",
|
||||
description: "The next events across visible calendars.",
|
||||
moduleId: "calendar",
|
||||
category: "Planning",
|
||||
order: 40,
|
||||
defaultVisible: false,
|
||||
defaultSize: "medium",
|
||||
supportedSizes: ["medium", "wide"],
|
||||
anyOf: eventRead,
|
||||
refreshIntervalMs: 60_000,
|
||||
defaultConfiguration: {
|
||||
maxItems: 5,
|
||||
daysAhead: 14,
|
||||
showLocation: true
|
||||
},
|
||||
configurationFields: [
|
||||
{
|
||||
id: "maxItems",
|
||||
label: "Maximum events",
|
||||
kind: "number",
|
||||
min: 1,
|
||||
max: 12,
|
||||
step: 1,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
id: "daysAhead",
|
||||
label: "Days ahead",
|
||||
kind: "number",
|
||||
min: 1,
|
||||
max: 90,
|
||||
step: 1,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
id: "showLocation",
|
||||
label: "Show locations",
|
||||
kind: "boolean"
|
||||
}
|
||||
],
|
||||
render: ({ settings, refreshKey, configuration }) =>
|
||||
createElement(UpcomingEventsWidget, {
|
||||
settings,
|
||||
refreshKey,
|
||||
configuration
|
||||
})
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
export const calendarModule: PlatformWebModule = {
|
||||
id: "calendar",
|
||||
label: "i18n:govoplan-calendar.calendar.adab5090",
|
||||
@@ -18,10 +80,23 @@ export const calendarModule: PlatformWebModule = {
|
||||
dependencies: ["access"],
|
||||
optionalDependencies: ["mail", "tasks", "scheduling", "appointments", "workflow", "notifications", "dms", "connectors"],
|
||||
translations,
|
||||
viewSurfaces: [
|
||||
{
|
||||
id: "calendar.widget.upcoming",
|
||||
moduleId: "calendar",
|
||||
kind: "section",
|
||||
label: "Upcoming events widget",
|
||||
order: 40
|
||||
}
|
||||
],
|
||||
navItems: [{ to: "/calendar", label: "i18n:govoplan-calendar.calendar.adab5090", iconName: "calendar", anyOf: eventRead, order: 55 }],
|
||||
routes: [
|
||||
{ path: "/calendar", anyOf: eventRead, order: 55, render: ({ settings, auth }) => createElement(CalendarPage, { settings, auth }) }]
|
||||
{ path: "/calendar", anyOf: eventRead, order: 55, render: ({ settings, auth }) => createElement(CalendarPage, { settings, auth }) }],
|
||||
uiCapabilities: {
|
||||
"calendar.picker": calendarPicker,
|
||||
"dashboard.widgets": calendarDashboardWidgets
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
export default calendarModule;
|
||||
export default calendarModule;
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
display: grid;
|
||||
grid-template-columns: minmax(240px, 300px) minmax(0, 1fr);
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
border: var(--border-line);
|
||||
border-radius: 0;
|
||||
background: var(--panel);
|
||||
}
|
||||
@@ -51,7 +51,7 @@
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-bottom: var(--border-line);
|
||||
background: var(--panel-header);
|
||||
}
|
||||
|
||||
@@ -89,21 +89,6 @@
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.calendar-icon-button.btn {
|
||||
width: 36px;
|
||||
min-width: 36px;
|
||||
height: 36px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.calendar-icon-button.btn:disabled {
|
||||
opacity: .42;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.calendar-mode-switch {
|
||||
flex: 0 1 520px;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
@@ -121,14 +106,14 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
border-right: 1px solid var(--line);
|
||||
border-right: var(--border-line);
|
||||
background: linear-gradient(180deg, var(--panel-soft), var(--panel));
|
||||
}
|
||||
|
||||
.calendar-sidebar-heading {
|
||||
flex: 0 0 auto;
|
||||
padding: 13px 14px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-bottom: var(--border-line);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
@@ -137,7 +122,7 @@
|
||||
}
|
||||
|
||||
.calendar-sidebar-heading.is-secondary {
|
||||
border-top: 1px solid var(--line);
|
||||
border-top: var(--border-line);
|
||||
}
|
||||
|
||||
.calendar-list,
|
||||
@@ -201,9 +186,9 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px;
|
||||
border: 1px solid #c9c3b9;
|
||||
border: 1px solid var(--control-border);
|
||||
border-radius: 999px;
|
||||
background: #d8d3cb;
|
||||
background: var(--calendar-switch-bg);
|
||||
cursor: pointer;
|
||||
transition: background .16s ease, border-color .16s ease;
|
||||
}
|
||||
@@ -217,8 +202,8 @@
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, .18);
|
||||
background: var(--surface);
|
||||
box-shadow: var(--shadow-thumb);
|
||||
transform: translateX(0);
|
||||
transition: transform .16s ease;
|
||||
}
|
||||
@@ -250,40 +235,7 @@
|
||||
}
|
||||
|
||||
.calendar-list-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 2px;
|
||||
min-width: 28px;
|
||||
}
|
||||
|
||||
.calendar-row-icon-button.btn {
|
||||
width: 28px;
|
||||
min-width: 28px;
|
||||
height: 28px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
opacity: .72;
|
||||
}
|
||||
|
||||
.calendar-row-icon-button.btn:hover,
|
||||
.calendar-row-icon-button.btn:focus-visible {
|
||||
border-color: var(--line-dark);
|
||||
background: var(--surface);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.calendar-row-icon-button.btn.is-syncing,
|
||||
.calendar-row-icon-button.btn.is-syncing:disabled {
|
||||
border-color: var(--green);
|
||||
background: var(--surface);
|
||||
color: var(--green);
|
||||
opacity: 1;
|
||||
cursor: progress;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.calendar-sync-spin {
|
||||
@@ -306,7 +258,7 @@
|
||||
min-width: 0;
|
||||
margin-top: 6px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--line);
|
||||
border-top: var(--border-line);
|
||||
}
|
||||
|
||||
.calendar-create-action .btn {
|
||||
@@ -331,7 +283,7 @@
|
||||
.calendar-agenda-group + .calendar-agenda-group {
|
||||
margin-top: 8px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--line);
|
||||
border-top: var(--border-line);
|
||||
}
|
||||
|
||||
.calendar-agenda-group h3 {
|
||||
@@ -346,15 +298,15 @@
|
||||
|
||||
.calendar-agenda-item {
|
||||
--calendar-event-color: var(--green);
|
||||
--calendar-event-bg: #edf8f5;
|
||||
--calendar-event-border: #b9d7d0;
|
||||
--calendar-event-bg: var(--calendar-event-bg-default);
|
||||
--calendar-event-border: var(--calendar-event-border-default);
|
||||
display: block;
|
||||
min-height: 28px;
|
||||
padding: 5px 7px;
|
||||
border: 1px solid var(--calendar-event-border);
|
||||
border-left: 4px solid var(--calendar-event-color, var(--green));
|
||||
background: var(--calendar-event-bg);
|
||||
color: #21453e;
|
||||
color: var(--calendar-event-text);
|
||||
}
|
||||
|
||||
.calendar-agenda-item strong {
|
||||
@@ -369,7 +321,7 @@
|
||||
.calendar-agenda-item .calendar-event-separator,
|
||||
.calendar-agenda p {
|
||||
margin: 0;
|
||||
color: #4d6764;
|
||||
color: var(--calendar-event-muted-text);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@@ -401,9 +353,9 @@
|
||||
inset: 0 auto auto 0;
|
||||
z-index: 4;
|
||||
padding: 10px;
|
||||
border-right: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
border-right: var(--border-line);
|
||||
border-bottom: var(--border-line);
|
||||
background: var(--panel-glass-bright);
|
||||
}
|
||||
|
||||
.calendar-week-rows {
|
||||
@@ -439,7 +391,7 @@
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
flex: 0 0 auto;
|
||||
border-bottom: 1px solid var(--line-dark);
|
||||
border-bottom: var(--border-line-dark);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
@@ -459,7 +411,7 @@
|
||||
|
||||
.calendar-week-row {
|
||||
min-height: 132px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-bottom: var(--border-line);
|
||||
}
|
||||
|
||||
.calendar-week-rows.is-continuous .calendar-week-row {
|
||||
@@ -476,22 +428,22 @@
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
border-right: 1px solid var(--line);
|
||||
border-right: var(--border-line);
|
||||
background: var(--surface);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.calendar-day-cell.is-even-month {
|
||||
background: #ffffff;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.calendar-day-cell.is-odd-month {
|
||||
background: #f8f6f2;
|
||||
background: var(--calendar-grid-bg);
|
||||
}
|
||||
|
||||
.calendar-day-cell.is-muted {
|
||||
color: #8a8278;
|
||||
background: #f1efeb;
|
||||
color: var(--muted);
|
||||
background: var(--control-gradient-end-muted);
|
||||
}
|
||||
|
||||
.calendar-day-cell.is-today {
|
||||
@@ -499,7 +451,7 @@
|
||||
}
|
||||
|
||||
.calendar-day-cell.is-drop-target {
|
||||
background: #e3f3ef;
|
||||
background: var(--calendar-today-bg);
|
||||
box-shadow: inset 0 0 0 2px var(--green);
|
||||
}
|
||||
|
||||
@@ -535,8 +487,8 @@
|
||||
|
||||
.calendar-event-chip {
|
||||
--calendar-event-color: var(--green);
|
||||
--calendar-event-bg: #edf8f5;
|
||||
--calendar-event-border: #b9d7d0;
|
||||
--calendar-event-bg: var(--calendar-event-bg-default);
|
||||
--calendar-event-border: var(--calendar-event-border-default);
|
||||
min-width: 0;
|
||||
min-height: 26px;
|
||||
display: block;
|
||||
@@ -545,7 +497,7 @@
|
||||
border-left: 4px solid var(--calendar-event-color);
|
||||
border-radius: 4px;
|
||||
background: var(--calendar-event-bg);
|
||||
color: #21453e;
|
||||
color: var(--calendar-event-text);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
@@ -597,7 +549,7 @@
|
||||
.calendar-event-time,
|
||||
.calendar-event-separator {
|
||||
flex: 0 0 auto;
|
||||
color: #4d6764;
|
||||
color: var(--calendar-event-muted-text);
|
||||
}
|
||||
|
||||
.calendar-more-events {
|
||||
@@ -635,8 +587,8 @@
|
||||
.calendar-time-corner,
|
||||
.calendar-all-day-label,
|
||||
.calendar-all-day-cell {
|
||||
border-bottom: 1px solid var(--line-dark);
|
||||
border-right: 1px solid var(--line);
|
||||
border-bottom: var(--border-line-dark);
|
||||
border-right: var(--border-line);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
@@ -649,12 +601,12 @@
|
||||
}
|
||||
|
||||
.calendar-time-header > header.is-today {
|
||||
background: #e0f0ea;
|
||||
background: var(--calendar-selected-bg);
|
||||
}
|
||||
|
||||
.calendar-time-header > header.is-weekend,
|
||||
.calendar-all-day-cell.is-weekend {
|
||||
background: #f1efeb;
|
||||
background: var(--control-gradient-end-muted);
|
||||
}
|
||||
|
||||
.calendar-time-header > header span {
|
||||
@@ -665,7 +617,7 @@
|
||||
.calendar-all-day-strip {
|
||||
flex: 0 0 auto;
|
||||
min-height: 42px;
|
||||
border-bottom: 1px solid var(--line-dark);
|
||||
border-bottom: var(--border-line-dark);
|
||||
}
|
||||
|
||||
.calendar-all-day-label {
|
||||
@@ -683,7 +635,7 @@
|
||||
}
|
||||
|
||||
.calendar-all-day-cell.is-drop-target {
|
||||
background: #e3f3ef;
|
||||
background: var(--calendar-today-bg);
|
||||
box-shadow: inset 0 0 0 2px var(--green);
|
||||
}
|
||||
|
||||
@@ -712,8 +664,8 @@
|
||||
|
||||
.calendar-hour-label {
|
||||
min-height: 64px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-right: 1px solid var(--line);
|
||||
border-bottom: var(--border-line);
|
||||
border-right: var(--border-line);
|
||||
padding: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
@@ -724,17 +676,17 @@
|
||||
position: relative;
|
||||
height: 1536px;
|
||||
min-height: 1536px;
|
||||
border-right: 1px solid var(--line);
|
||||
border-right: var(--border-line);
|
||||
background:
|
||||
linear-gradient(to bottom, var(--calendar-day-shade), var(--calendar-day-shade)),
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
rgba(241, 239, 235, var(--calendar-off-hours-opacity)) 0,
|
||||
rgba(241, 239, 235, var(--calendar-off-hours-opacity)) var(--calendar-work-start-y),
|
||||
rgba(var(--calendar-off-hours-rgb), var(--calendar-off-hours-opacity)) 0,
|
||||
rgba(var(--calendar-off-hours-rgb), var(--calendar-off-hours-opacity)) var(--calendar-work-start-y),
|
||||
transparent var(--calendar-work-start-y),
|
||||
transparent var(--calendar-work-end-y),
|
||||
rgba(241, 239, 235, var(--calendar-off-hours-opacity)) var(--calendar-work-end-y),
|
||||
rgba(241, 239, 235, var(--calendar-off-hours-opacity)) 100%
|
||||
rgba(var(--calendar-off-hours-rgb), var(--calendar-off-hours-opacity)) var(--calendar-work-end-y),
|
||||
rgba(var(--calendar-off-hours-rgb), var(--calendar-off-hours-opacity)) 100%
|
||||
),
|
||||
repeating-linear-gradient(
|
||||
to bottom,
|
||||
@@ -746,11 +698,11 @@
|
||||
}
|
||||
|
||||
.calendar-day-time-column.is-weekend {
|
||||
--calendar-day-shade: rgba(241, 239, 235, .74);
|
||||
--calendar-day-shade: var(--calendar-day-shade);
|
||||
}
|
||||
|
||||
.calendar-day-time-column.is-drop-target {
|
||||
box-shadow: inset 0 0 0 2px rgba(90, 169, 155, .55);
|
||||
box-shadow: var(--calendar-focus-inset);
|
||||
}
|
||||
|
||||
.calendar-time-drop-marker {
|
||||
@@ -778,10 +730,10 @@
|
||||
top: -13px;
|
||||
left: 10px;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid #4f9489;
|
||||
border: 1px solid var(--calendar-success-border);
|
||||
border-radius: 4px;
|
||||
background: var(--green);
|
||||
color: #fff;
|
||||
color: var(--on-accent);
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
@@ -799,15 +751,15 @@
|
||||
|
||||
.calendar-timed-event {
|
||||
--calendar-event-color: var(--green);
|
||||
--calendar-event-bg: #edf8f5;
|
||||
--calendar-event-border: #b9d7d0;
|
||||
--calendar-event-bg: var(--calendar-event-bg-default);
|
||||
--calendar-event-border: var(--calendar-event-border-default);
|
||||
display: block;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--calendar-event-border);
|
||||
border-left: 4px solid var(--calendar-event-color);
|
||||
background: var(--calendar-event-bg);
|
||||
color: #21453e;
|
||||
color: var(--calendar-event-text);
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -817,8 +769,8 @@
|
||||
.calendar-timed-event.is-linked-hover,
|
||||
.calendar-timed-overflow:hover,
|
||||
.calendar-timed-overflow:focus-visible {
|
||||
border-color: var(--calendar-event-color, #5aa99b);
|
||||
background: var(--calendar-event-bg, #e3f3ef);
|
||||
border-color: var(--calendar-event-color, var(--success-border));
|
||||
background: var(--calendar-event-bg, var(--calendar-today-bg));
|
||||
outline: none;
|
||||
}
|
||||
|
||||
@@ -837,7 +789,7 @@
|
||||
}
|
||||
|
||||
.calendar-timed-event-content:focus-visible {
|
||||
outline: 2px solid rgba(90, 169, 155, .35);
|
||||
outline: var(--calendar-focus-outline);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
@@ -864,7 +816,7 @@
|
||||
width: 34px;
|
||||
height: 2px;
|
||||
border-radius: 999px;
|
||||
background: rgba(33, 69, 62, .46);
|
||||
background: var(--calendar-overlay);
|
||||
content: "";
|
||||
opacity: 0;
|
||||
transform: translateX(-50%);
|
||||
@@ -890,7 +842,7 @@
|
||||
height: 28px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border: 1px solid var(--line-dark);
|
||||
border: var(--border-line-dark);
|
||||
background: var(--panel-soft);
|
||||
color: var(--text-strong);
|
||||
cursor: pointer;
|
||||
@@ -963,7 +915,7 @@
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--line);
|
||||
border: var(--border-line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel-soft);
|
||||
}
|
||||
@@ -1051,7 +1003,7 @@
|
||||
}
|
||||
|
||||
.calendar-vevent-details {
|
||||
border-top: 1px solid var(--line);
|
||||
border-top: var(--border-line);
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
@@ -1059,7 +1011,7 @@
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 12px 0;
|
||||
border-top: 1px solid var(--line);
|
||||
border-top: var(--border-line);
|
||||
}
|
||||
|
||||
.calendar-vevent-section:first-of-type {
|
||||
@@ -1085,7 +1037,7 @@
|
||||
|
||||
.calendar-sync-status {
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--line-dark);
|
||||
border: var(--border-line-dark);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
color: var(--muted);
|
||||
@@ -1094,8 +1046,8 @@
|
||||
}
|
||||
|
||||
.calendar-sync-status.is-error {
|
||||
border-color: #f0b8b2;
|
||||
background: #fff2f0;
|
||||
border-color: var(--calendar-danger-border);
|
||||
background: var(--calendar-danger-bg);
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
@@ -1115,7 +1067,7 @@
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--line);
|
||||
border: var(--border-line);
|
||||
border-radius: 6px;
|
||||
background: var(--surface);
|
||||
}
|
||||
@@ -1150,9 +1102,9 @@
|
||||
.calendar-form-error {
|
||||
margin: 0;
|
||||
padding: 9px 10px;
|
||||
border: 1px solid #f0b8b2;
|
||||
border: 1px solid var(--calendar-danger-border);
|
||||
border-radius: 4px;
|
||||
background: #fff2f0;
|
||||
background: var(--calendar-danger-bg);
|
||||
color: var(--red);
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -1166,13 +1118,13 @@
|
||||
}
|
||||
|
||||
.calendar-delete-warning {
|
||||
border: 1px solid #f0b8b2;
|
||||
background: #fff2f0;
|
||||
border: 1px solid var(--calendar-danger-border);
|
||||
background: var(--calendar-danger-bg);
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.calendar-form-note {
|
||||
border: 1px solid var(--line);
|
||||
border: var(--border-line);
|
||||
background: var(--panel-soft);
|
||||
color: var(--muted);
|
||||
}
|
||||
@@ -1182,7 +1134,7 @@
|
||||
gap: 10px;
|
||||
margin: 0;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--line);
|
||||
border: var(--border-line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel-soft);
|
||||
}
|
||||
@@ -1275,7 +1227,7 @@
|
||||
|
||||
.calendar-sidebar {
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
border-bottom: var(--border-line);
|
||||
}
|
||||
|
||||
.calendar-mode-switch {
|
||||
|
||||
78
webui/tests/calendar-page-structure.test.mjs
Normal file
78
webui/tests/calendar-page-structure.test.mjs
Normal file
@@ -0,0 +1,78 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
function assert(condition, message) {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
const page = fs.readFileSync(
|
||||
new URL(
|
||||
"../src/features/calendar/CalendarPage.tsx",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
const views = fs.readFileSync(
|
||||
new URL(
|
||||
"../src/features/calendar/CalendarViews.tsx",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
const model = fs.readFileSync(
|
||||
new URL(
|
||||
"../src/features/calendar/calendarViewModel.ts",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
const collectionDialogs = fs.readFileSync(
|
||||
new URL(
|
||||
"../src/features/calendar/CalendarCollectionDialogs.tsx",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
const eventDialog = fs.readFileSync(
|
||||
new URL(
|
||||
"../src/features/calendar/CalendarEventDialog.tsx",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
assert(
|
||||
page.includes('from "./CalendarViews"'),
|
||||
"CalendarPage must compose the focused calendar view components",
|
||||
);
|
||||
assert(
|
||||
!page.includes("function CalendarWeekRows("),
|
||||
"CalendarPage must not own month/continuous rendering",
|
||||
);
|
||||
assert(
|
||||
!page.includes("function CalendarTimeGrid("),
|
||||
"CalendarPage must not own time-grid rendering",
|
||||
);
|
||||
assert(
|
||||
views.includes("export function CalendarWeekRows(") &&
|
||||
views.includes("export function CalendarTimeGrid("),
|
||||
"CalendarViews must own both view families",
|
||||
);
|
||||
assert(
|
||||
model.includes("export function layoutTimedEventsForDay(") &&
|
||||
model.includes("export function continuousVirtualWindow("),
|
||||
"calendar layout and virtualization must remain independently testable",
|
||||
);
|
||||
assert(
|
||||
!page.includes("function CalendarCollectionDialog(") &&
|
||||
!page.includes("function CalendarEventDialog("),
|
||||
"CalendarPage must not own source or event form dialogs",
|
||||
);
|
||||
assert(
|
||||
collectionDialogs.includes(
|
||||
"export function CalendarCollectionDialog(",
|
||||
) &&
|
||||
eventDialog.includes("export function CalendarEventDialog("),
|
||||
"calendar dialogs must remain focused components",
|
||||
);
|
||||
|
||||
console.log("Calendar page decomposition checks passed.");
|
||||
20
webui/tests/calendar-picker-structure.test.mjs
Normal file
20
webui/tests/calendar-picker-structure.test.mjs
Normal file
@@ -0,0 +1,20 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
function assert(condition, message) {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
const picker = fs.readFileSync(new URL("../src/features/calendar/CalendarPicker.tsx", import.meta.url), "utf8");
|
||||
const moduleSource = fs.readFileSync(new URL("../src/module.ts", import.meta.url), "utf8");
|
||||
const coreTypes = fs.readFileSync(new URL("../../../govoplan-core/webui/src/types.ts", import.meta.url), "utf8");
|
||||
|
||||
assert(moduleSource.includes('"calendar.picker": calendarPicker'), "Calendar must register the named picker capability");
|
||||
assert(coreTypes.includes("export type CalendarPickerUiCapability"), "Core must expose the narrow cross-module contract");
|
||||
assert(picker.includes("listCalendars(settings)"), "Picker must use Calendar's authenticated list API");
|
||||
assert(picker.includes("hasScope(auth, CALENDAR_PICKER_READ_SCOPE)"), "Picker must avoid loading without read permission");
|
||||
assert(picker.includes("value={value}"), "Picker must remain controlled by its consumer");
|
||||
assert(picker.includes("onChange={(event) => onChange(event.target.value)}"), "Picker must return the chosen calendar id");
|
||||
assert(picker.includes("aria-busy={loading || undefined}"), "Picker must expose loading state accessibly");
|
||||
assert(picker.includes("aria-describedby={status ? statusId : undefined}"), "Picker must associate availability feedback");
|
||||
|
||||
console.log("Calendar picker capability structure checks passed.");
|
||||
37
webui/tests/calendar-picker.test.ts
Normal file
37
webui/tests/calendar-picker.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
calendarPickerOptions,
|
||||
calendarPickerTenantId,
|
||||
type CalendarPickerOption
|
||||
} from "../src/features/calendar/calendarPickerLogic";
|
||||
|
||||
function assert(condition: unknown, message: string): void {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
function calendar(id: string, name: string, isDefault = false): CalendarPickerOption {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
is_default: isDefault
|
||||
};
|
||||
}
|
||||
|
||||
const input = [
|
||||
calendar("z", "Zulu"),
|
||||
calendar("b", "Bravo", true),
|
||||
calendar("a", "alpha")
|
||||
];
|
||||
const ordered = calendarPickerOptions(input);
|
||||
|
||||
assert(ordered.map((item) => item.id).join(",") === "b,a,z", "default calendar should lead, followed by names");
|
||||
assert(input.map((item) => item.id).join(",") === "z,b,a", "picker sorting must not mutate API data");
|
||||
assert(
|
||||
calendarPickerTenantId({ tenant: { id: "fallback" }, active_tenant: { id: "active" } }) === "active",
|
||||
"active tenant should partition picker requests"
|
||||
);
|
||||
assert(
|
||||
calendarPickerTenantId({ tenant: { id: "fallback" } }) === "fallback",
|
||||
"legacy tenant should remain a supported fallback"
|
||||
);
|
||||
|
||||
console.log("Calendar picker behavior checks passed.");
|
||||
96
webui/tests/calendar-view-model.test.ts
Normal file
96
webui/tests/calendar-view-model.test.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import {
|
||||
continuousVirtualWindow,
|
||||
groupEventsByDay,
|
||||
layoutTimedEventsForDay,
|
||||
moveEventToDay,
|
||||
rangeForMode,
|
||||
resizeEventToTime,
|
||||
} from "../src/features/calendar/calendarViewModel.ts";
|
||||
|
||||
function assert(condition: unknown, message: string): void {
|
||||
if (!condition) throw new Error(message);
|
||||
}
|
||||
|
||||
function event(
|
||||
id: string,
|
||||
start: Date,
|
||||
end: Date,
|
||||
allDay = false,
|
||||
) {
|
||||
return {
|
||||
id,
|
||||
calendar_id: "calendar-1",
|
||||
summary: id,
|
||||
start_at: start.toISOString(),
|
||||
end_at: end.toISOString(),
|
||||
all_day: allDay,
|
||||
} as never;
|
||||
}
|
||||
|
||||
const focus = new Date(2026, 6, 15, 12);
|
||||
const month = rangeForMode("month", focus, {
|
||||
before: 8,
|
||||
after: 12,
|
||||
});
|
||||
assert(
|
||||
(month.end.getTime() - month.start.getTime()) / 86_400_000 === 42,
|
||||
"month view should retain its six-week window",
|
||||
);
|
||||
|
||||
const virtual = continuousVirtualWindow(
|
||||
100,
|
||||
{ scrollTop: 20 * 92, height: 8 * 92 },
|
||||
3,
|
||||
);
|
||||
assert(virtual.start === 17, "virtualization should retain overscan above");
|
||||
assert(virtual.end === 31, "virtualization should retain overscan below");
|
||||
assert(
|
||||
virtual.topSpacerHeight + virtual.bottomSpacerHeight > 0,
|
||||
"virtualization should preserve offscreen geometry",
|
||||
);
|
||||
|
||||
const day = new Date(2026, 6, 7);
|
||||
const parallel = [0, 1, 2, 3].map((index) =>
|
||||
event(
|
||||
`event-${index}`,
|
||||
new Date(2026, 6, 7, 9),
|
||||
new Date(2026, 6, 7, 10),
|
||||
),
|
||||
);
|
||||
const layout = layoutTimedEventsForDay(parallel, day);
|
||||
assert(
|
||||
layout.items.length === 2 && layout.overflows.length === 1,
|
||||
"parallel events should use bounded columns plus one overflow control",
|
||||
);
|
||||
assert(
|
||||
layout.overflows[0].events.length === 2,
|
||||
"overflow should retain every hidden event",
|
||||
);
|
||||
|
||||
const allDay = event(
|
||||
"all-day",
|
||||
new Date(2026, 6, 7),
|
||||
new Date(2026, 6, 9),
|
||||
true,
|
||||
);
|
||||
const grouped = groupEventsByDay([allDay]);
|
||||
assert(grouped.size === 2, "all-day end dates should remain exclusive");
|
||||
const moved = moveEventToDay(allDay, new Date(2026, 6, 20));
|
||||
assert(
|
||||
moved.endAt?.getDate() === 22,
|
||||
"moving an all-day event should preserve its duration",
|
||||
);
|
||||
|
||||
const timed = event(
|
||||
"timed",
|
||||
new Date(2026, 6, 7, 10),
|
||||
new Date(2026, 6, 7, 11),
|
||||
);
|
||||
const resized = resizeEventToTime(timed, "end", day, 9 * 60);
|
||||
assert(
|
||||
resized.endAt !== null &&
|
||||
resized.endAt.getTime() > resized.startAt.getTime(),
|
||||
"resizing must not invert an event",
|
||||
);
|
||||
|
||||
console.log("Calendar view model interaction checks passed.");
|
||||
38
webui/tsconfig.calendar-page-tests.json
Normal file
38
webui/tsconfig.calendar-page-tests.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@govoplan/core-webui": [
|
||||
"../../govoplan-core/webui/src/index.ts"
|
||||
],
|
||||
"lucide-react": [
|
||||
"../../govoplan-core/webui/node_modules/lucide-react/dist/lucide-react.d.ts"
|
||||
],
|
||||
"react": [
|
||||
"../../govoplan-core/webui/node_modules/@types/react/index.d.ts"
|
||||
],
|
||||
"react/jsx-runtime": [
|
||||
"../../govoplan-core/webui/node_modules/@types/react/jsx-runtime.d.ts"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"../../govoplan-core/webui/src/vite-env.d.ts",
|
||||
"src/api/calendar.ts",
|
||||
"src/features/calendar/CalendarPage.tsx",
|
||||
"src/features/calendar/CalendarViews.tsx",
|
||||
"src/features/calendar/CalendarCollectionDialogs.tsx",
|
||||
"src/features/calendar/CalendarEventDialog.tsx",
|
||||
"src/features/calendar/calendarViewModel.ts"
|
||||
]
|
||||
}
|
||||
18
webui/tsconfig.calendar-picker-tests.json
Normal file
18
webui/tsconfig.calendar-picker-tests.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["ES2020", "DOM"],
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "Node",
|
||||
"noEmit": false,
|
||||
"outDir": ".calendar-picker-test-build",
|
||||
"rootDir": "."
|
||||
},
|
||||
"include": [
|
||||
"tests/calendar-picker.test.ts",
|
||||
"src/features/calendar/calendarPickerLogic.ts"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user