Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add my hours time logs, project tasks and members tables (#115421)

Tom Owers771f7b70ef84
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index b86a6a6a2cd9..a6773c74f2cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5757,10 +5757,10 @@ Today (4): `clients`, `projects`, `tags`, `users`
Diffed against: <https://documenter.gw.postman.com/api/collections/8879268/TVmV4YYU>
-- [ ] `GET /api/Logs?date=&step=` — time logs are the entire point of a time tracker — the central fact table is missing, so hours cannot be queried at all (high)
-- [ ] `PUT /api/Reports/activitydx` — bulk time-log report over a date range with client/project/user filters — the practical backfill path for logs (high)
-- [ ] `GET /api/Projects/{projectId}/tasklist` — project task lookup resolving the task each time log is booked against (high)
-- [ ] `GET /api/Projects/{projectId}/userlist` — project-to-team-member assignment join table (medium)
+- ~~`GET /api/Logs?date=&step=`~~ — not added: it returns only the API key owner's recent time logs, not the account's. The account-wide time logs come from `PUT /api/Reports/activitydx` (the `time_logs` table).
+- [x] `PUT /api/Reports/activitydx` — bulk time-log report over a date range with client/project/user filters — the practical backfill path for logs (high). Added as `time_logs` (31-day date windows, incremental on `date`).
+- [x] `GET /api/Projects/{projectId}/tasklist` — project task lookup resolving the task each time log is booked against (high). Added as `project_tasks` (fan-out over `projects`, one row per task across every task list).
+- [x] `GET /api/Projects/{projectId}/userlist` — project-to-team-member assignment join table (medium). Added as `project_members` (fan-out over `projects`).
- [ ] `GET /api/Teams/{teamId}/teammembers` — team membership for grouping users in reporting (medium)
- [ ] `GET /api/Projects/{projectId}/overview` — project detail including budget/rate fields not on the list response (low)
- [ ] `GET /api/Reports/dashboardOptimized` — pre-aggregated dashboard totals by client/project/user (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/canonical_descriptions.py
index de1051f06de6..80951b07cce9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/canonical_descriptions.py
@@ -77,4 +77,66 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"dateArchived": "When the user was archived, if applicable.",
},
},
+ "time_logs": {
+ "description": "A time log: time a team member booked against a project and task on a given date, from the activity report.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "logId": "The unique ID of the time log.",
+ "date": "The date the time was logged for.",
+ "logDuration": "The logged duration, in seconds.",
+ "billable": "Whether the time log is billable.",
+ "running": "Whether the time log's timer is still running.",
+ "note": "The note attached to the time log.",
+ "startTime": "When the logged time started, if recorded.",
+ "status": "The approval status of the time log.",
+ "invoiced": "Whether the time log has been invoiced.",
+ "invoiceId": "The ID of the invoice the time log is on, if any.",
+ "userId": "The ID of the team member who logged the time.",
+ "userName": "The name of the team member who logged the time.",
+ "projectId": "The ID of the project the time is logged against.",
+ "projectName": "The name of the project the time is logged against.",
+ "clientName": "The name of the project's client.",
+ "taskListName": "The name of the task list the task belongs to.",
+ "taskName": "The name of the task the time is logged against.",
+ "tagsData": "The tags assigned to the time log.",
+ "monthOfYear": "The year and month of the log date, as YYYY-MM.",
+ "weekOfYear": "The year and week number of the log date, as YYYY-WW.",
+ "weekNo": "The week number of the log date.",
+ },
+ },
+ "project_tasks": {
+ "description": "A task on a project, which time logs can be booked against.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the task.",
+ "projectId": "The ID of the project the task belongs to.",
+ "name": "The task name.",
+ "description": "The task description.",
+ "taskListName": "The name of the task list the task belongs to.",
+ "taskListNo": "The position of the task list within the project.",
+ "completed": "Whether the task is completed.",
+ "archived": "Whether the task has been archived.",
+ "dueDate": "When the task is due, if set.",
+ "rate": "The task's billable rate.",
+ "budgetValue": "The task's budget value.",
+ "totalTimeLogged": "The total time logged against the task.",
+ "totalAmountLogged": "The total billable amount logged against the task.",
+ "projectTaskUserIds": "The IDs of the team members assigned to the task.",
+ "customId": "A user-defined external identifier for the task.",
+ },
+ },
+ "project_members": {
+ "description": "A team member assigned to a project. One row per project and team member.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "projectId": "The ID of the project.",
+ "userId": "The ID of the assigned team member.",
+ "userName": "The team member's name.",
+ "userArchived": "Whether the team member has been archived.",
+ "userRate": "The team member's default rate.",
+ "rate": "The team member's rate on this project, if it overrides the default.",
+ "userAdmin": "Whether the team member is an account administrator.",
+ "userIsProjectManager": "Whether the team member is a manager of this project.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/my_hours.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/my_hours.py
index ff47d57cef29..852a0893641c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/my_hours.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/my_hours.py
@@ -1,18 +1,35 @@
-from typing import Optional
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional, cast
from requests import PreparedRequest
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.safe_point import reach_safe_point
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.settings import MY_HOURS_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.settings import (
+ MY_HOURS_ENDPOINTS,
+ PROJECT_TASKS_ENDPOINT,
+ TIME_LOGS_ENDPOINT,
+ TIME_LOGS_FIRST_DATE,
+ TIME_LOGS_WINDOW_DAYS,
+)
MY_HOURS_BASE_URL = "https://api2.myhours.com/api"
# Cheap list endpoint used to confirm an API key is genuine. The key is account-wide, so one probe
@@ -41,22 +58,142 @@ def _headers() -> dict[str, str]:
return {"Accept": "application/json"}
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": MY_HOURS_BASE_URL,
+ "headers": _headers(),
+ "auth": MyHoursApiKeyAuth(api_key),
+ # The list endpoints are unpaginated: a single request returns the whole collection.
+ "paginator": SinglePagePaginator(),
+ }
+
+
+@frozen
+class _TimeLogWindow:
+ date_from: date
+ date_to: date
+
+
+def _start_date(last_value: Any) -> date:
+ if isinstance(last_value, datetime):
+ return last_value.date()
+ if isinstance(last_value, date):
+ return last_value
+ if isinstance(last_value, str):
+ return datetime.fromisoformat(last_value).date()
+ return TIME_LOGS_FIRST_DATE
+
+
+def _time_log_windows(start: date, today: date) -> Iterator[_TimeLogWindow]:
+ # A watermark past today (a log booked ahead) still re-reads the current window.
+ start = max(min(start, today), TIME_LOGS_FIRST_DATE)
+ while start <= today:
+ end = min(start + timedelta(days=TIME_LOGS_WINDOW_DAYS - 1), today)
+ yield _TimeLogWindow(date_from=start, date_to=end)
+ start = end + timedelta(days=1)
+
+
+def _time_log_pages(client: RESTClient, start: date) -> Iterator[list[dict[str, Any]]]:
+ # One day past today in UTC covers accounts in timezones already on the next day.
+ today = datetime.now(UTC).date() + timedelta(days=1)
+ for window in _time_log_windows(start, today):
+ rows: list[dict[str, Any]] = []
+ for page in client.paginate(
+ path=MY_HOURS_ENDPOINTS[TIME_LOGS_ENDPOINT].path,
+ method="put",
+ json={
+ "options": {
+ "dateFrom": window.date_from.isoformat(),
+ "dateTo": window.date_to.isoformat(),
+ "logType": "Time",
+ "userIds": [],
+ "clientIds": [],
+ "projectIds": [],
+ "taskNames": [],
+ "tagNames": [],
+ "statuses": [],
+ }
+ },
+ data_selector="data",
+ data_selector_malformed_retryable=True,
+ ):
+ rows.extend(page)
+ if not rows:
+ reach_safe_point()
+ continue
+ # The report's row order is not documented. Sorting each window keeps the incremental
+ # watermark ascending across batches.
+ rows.sort(key=lambda row: row.get("date") or "")
+ yield rows
+
+
+def _flatten_task_lists(task_list: dict[str, Any]) -> list[dict[str, Any]]:
+ shared = {
+ "projectId": task_list.get("projectId"),
+ "taskListName": task_list.get("listName"),
+ "taskListNo": task_list.get("listNo"),
+ }
+ tasks = [
+ *(task_list.get("incompletedTasks") or []),
+ *(task_list.get("completedTasks") or []),
+ *(task_list.get("archivedTasks") or []),
+ ]
+ return [{**task, **shared} for task in tasks]
+
+
def my_hours_source(
api_key: str,
endpoint: str,
team_id: int,
job_id: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
) -> SourceResponse:
config = MY_HOURS_ENDPOINTS[endpoint]
+ if endpoint == TIME_LOGS_ENDPOINT:
+ client = RESTClient(
+ base_url=MY_HOURS_BASE_URL,
+ headers=_headers(),
+ auth=MyHoursApiKeyAuth(api_key),
+ paginator=SinglePagePaginator(),
+ )
+ start = _start_date(db_incremental_field_last_value if should_use_incremental_field else None)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _time_log_pages(client, start),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+ if config.fanout is not None:
+ resource = cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=MY_HOURS_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ page_size_param=None,
+ ),
+ )
+ if endpoint == PROJECT_TASKS_ENDPOINT:
+ resource = resource.add_map(_flatten_task_lists)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": MY_HOURS_BASE_URL,
- "headers": _headers(),
- "auth": MyHoursApiKeyAuth(api_key),
- # The list endpoints are unpaginated: a single request returns the whole collection.
- "paginator": SinglePagePaginator(),
- },
+ "client": _client_config(api_key),
"resource_defaults": {},
"resources": [
{
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py
index 2886d0b81a7b..51efc9e24c14 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py
@@ -1,27 +1,81 @@
from dataclasses import dataclass, field
+from datetime import date
+from typing import Any
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class MyHoursEndpointConfig:
name: str
path: str
# My Hours object IDs are unique within an account, so `id` is a safe primary key.
primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ fanout: DependentEndpointConfig | None = None
+ # Read by the shared fan-out helper. My Hours list endpoints are unpaginated, so no page size is sent.
+ incremental_fields: list[Any] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ page_size: int = 0
-# My Hours REST API list endpoints. All are full-refresh only: the API exposes no row-level
-# pagination and no updated-since cursor, so there is no incremental cursor to advance. The
-# per-user activity report (`Reports/activity`) is intentionally excluded — it requires a
-# mandatory `DateFrom`/`DateTo` window rather than being a plain top-level list.
+TIME_LOGS_ENDPOINT = "time_logs"
+PROJECT_TASKS_ENDPOINT = "project_tasks"
+
+# The activity report needs an explicit date window and returns the whole window in one response,
+# so a full sync walks fixed windows from this floor to today.
+TIME_LOGS_FIRST_DATE = date(2010, 1, 1)
+TIME_LOGS_WINDOW_DAYS = 31
+# Time logs are routinely back-dated (weekly timesheets, late edits), so incremental syncs re-read
+# this window behind the watermark. Merge on `logId` dedupes the overlap.
+TIME_LOGS_LOOKBACK_SECONDS = 30 * 24 * 60 * 60
+
+_PROJECT_FANOUT = DependentEndpointConfig(
+ parent_name="projects",
+ resolve_param="project_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "projectId"},
+ # A project deleted between the project listing and its child request.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+)
+
+# My Hours REST API list endpoints. The plain list endpoints are full refresh only: they expose no
+# row-level pagination and no updated-since cursor. `time_logs` reads the account-wide activity
+# report, which filters server-side by log date.
MY_HOURS_ENDPOINTS: dict[str, MyHoursEndpointConfig] = {
"clients": MyHoursEndpointConfig(name="clients", path="/Clients"),
"projects": MyHoursEndpointConfig(name="projects", path="/Projects/getAll"),
"tags": MyHoursEndpointConfig(name="tags", path="/Tags"),
"users": MyHoursEndpointConfig(name="users", path="/Users/getAll"),
+ TIME_LOGS_ENDPOINT: MyHoursEndpointConfig(
+ name=TIME_LOGS_ENDPOINT, path="/Reports/activitydx", primary_keys=["logId"]
+ ),
+ PROJECT_TASKS_ENDPOINT: MyHoursEndpointConfig(
+ name=PROJECT_TASKS_ENDPOINT,
+ path="/Projects/{project_id}/tasklist",
+ primary_keys=["projectId", "id"],
+ fanout=_PROJECT_FANOUT,
+ ),
+ "project_members": MyHoursEndpointConfig(
+ name="project_members",
+ path="/Projects/{project_id}/userlist",
+ primary_keys=["projectId", "userId"],
+ fanout=_PROJECT_FANOUT,
+ ),
}
ENDPOINTS = tuple(MY_HOURS_ENDPOINTS.keys())
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ TIME_LOGS_ENDPOINT: [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py
index bf4563d63df5..dda12870a1f9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py
@@ -28,6 +28,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.s
ENDPOINTS,
INCREMENTAL_FIELDS,
MY_HOURS_ENDPOINTS,
+ TIME_LOGS_ENDPOINT,
+ TIME_LOGS_LOOKBACK_SECONDS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -51,7 +53,7 @@ class MyHoursSource(SimpleSource[MyHoursSourceConfig]):
releaseStatus=ReleaseStatus.ALPHA,
caption="""Enter your My Hours API key to pull your time-tracking data into the PostHog Data warehouse.
-API keys are available on paid plans. Create one under **Settings → Integrations → API keys** in your [My Hours account](https://app.myhours.com/). The key is tied to the user who created it, so it stops working if that user is archived or removed. The key grants read access to your clients, projects, tags, and users.
+API keys are available on paid plans. Create one under **Settings → Integrations → API keys** in your [My Hours account](https://app.myhours.com/). The key is tied to the user who created it, so it stops working if that user is archived or removed. The key grants read access to your clients, projects, project tasks and members, tags, users, and time logs.
""",
iconPath="/static/services/my_hours.png",
docsUrl="https://posthog.com/docs/cdp/sources/my-hours",
@@ -92,9 +94,14 @@ API keys are available on paid plans. Create one under **Settings → Integratio
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Every endpoint is full refresh only — My Hours list endpoints expose no server-side
- # timestamp filter, so there is no incremental cursor to advance (INCREMENTAL_FIELDS is empty).
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ # Only `time_logs` is incremental — the other My Hours list endpoints expose no server-side
+ # timestamp filter, so there is no incremental cursor to advance.
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ default_incremental_lookback_seconds={TIME_LOGS_ENDPOINT: TIME_LOGS_LOOKBACK_SECONDS},
+ )
def validate_credentials(
self,
@@ -120,4 +127,6 @@ API keys are available on paid plans. Create one under **Settings → Integratio
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours.py
index 9ae6291f4839..a57ece1f5a20 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours.py
@@ -1,7 +1,9 @@
import json
+from datetime import datetime
from typing import Any
import pytest
+import time_machine
from unittest import mock
import requests
@@ -54,8 +56,12 @@ def _wire(responses: list[Response]) -> tuple[requests.Session, list[Any]]:
return session, sent
+def _pages(source_response: Any) -> list[list[dict[str, Any]]]:
+ return list(source_response.items())
+
+
def _rows(source_response: Any) -> list[dict[str, Any]]:
- return [row for page in source_response.items() for row in page]
+ return [row for page in _pages(source_response) for row in page]
class TestSync:
@@ -149,10 +155,118 @@ class TestMyHoursSourceResponse:
mock_session.return_value = mock.MagicMock()
response = my_hours_source(api_key="mh-key", endpoint=endpoint, team_id=1, job_id="j")
assert response.name == endpoint
- assert response.primary_keys == ["id"]
+ assert response.primary_keys == MY_HOURS_ENDPOINTS[endpoint].primary_keys
# The list endpoints carry no stable timestamp, so we don't partition.
assert response.partition_mode is None
- def test_every_endpoint_uses_id_primary_key(self) -> None:
- assert all(config.primary_keys == ["id"] for config in MY_HOURS_ENDPOINTS.values())
- assert set(MY_HOURS_ENDPOINTS) == set(ENDPOINTS)
+
+class TestTimeLogs:
+ @parameterized.expand(
+ [
+ ("full_refresh", False, None, [("2010-01-01", "2010-01-31"), ("2010-02-01", "2010-02-21")]),
+ ("incremental_from_watermark", True, datetime(2010, 2, 5), [("2010-02-05", "2010-02-21")]),
+ ("incremental_watermark_after_today", True, datetime(2010, 3, 10), [("2010-02-21", "2010-02-21")]),
+ ]
+ )
+ @time_machine.travel("2010-02-20 12:00:00", tick=False)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_date_windows(
+ self,
+ _name: str,
+ incremental: bool,
+ last_value: datetime | None,
+ expected_windows: list[tuple[str, str]],
+ mock_session: mock.MagicMock,
+ ) -> None:
+ session, sent = _wire([_response({"data": []}) for _ in expected_windows])
+ mock_session.return_value = session
+
+ _rows(
+ my_hours_source(
+ api_key="mh-key",
+ endpoint="time_logs",
+ team_id=1,
+ job_id="j",
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ assert all(p.method == "PUT" and p.url == f"{MY_HOURS_BASE_URL}/Reports/activitydx" for p in sent)
+ options = [json.loads(p.body)["options"] for p in sent]
+ assert [(o["dateFrom"], o["dateTo"]) for o in options] == expected_windows
+
+ @time_machine.travel("2010-02-20 12:00:00", tick=False)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_yields_each_non_empty_window_sorted_by_date(self, mock_session: mock.MagicMock) -> None:
+ session, _sent = _wire(
+ [
+ _response(
+ {
+ "data": [
+ {"logId": 2, "date": "2010-01-20T00:00:00"},
+ {"logId": 1, "date": "2010-01-03T00:00:00"},
+ ],
+ "totalCount": -1,
+ }
+ ),
+ _response({"data": [], "totalCount": -1}),
+ ]
+ )
+ mock_session.return_value = session
+
+ pages = _pages(my_hours_source(api_key="mh-key", endpoint="time_logs", team_id=1, job_id="j"))
+
+ assert pages == [[{"logId": 1, "date": "2010-01-03T00:00:00"}, {"logId": 2, "date": "2010-01-20T00:00:00"}]]
+
+
+class TestProjectFanout:
+ @mock.patch(RETRY_ATTEMPTS_PATCH, 1)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_project_tasks_flattens_every_task_list(self, mock_session: mock.MagicMock) -> None:
+ session, sent = _wire(
+ [
+ _response([{"id": 11}, {"id": 12}]),
+ _response(
+ [
+ {
+ "listName": "Task list",
+ "listNo": 0,
+ "incompletedTasks": [{"id": 1}],
+ "completedTasks": [{"id": 2}],
+ "archivedTasks": [{"id": 3}],
+ }
+ ]
+ ),
+ _response([]),
+ ]
+ )
+ mock_session.return_value = session
+
+ rows = _rows(my_hours_source(api_key="mh-key", endpoint="project_tasks", team_id=1, job_id="j"))
+
+ assert [p.url for p in sent] == [
+ f"{MY_HOURS_BASE_URL}/Projects/getAll",
+ f"{MY_HOURS_BASE_URL}/Projects/11/tasklist",
+ f"{MY_HOURS_BASE_URL}/Projects/12/tasklist",
+ ]
+ assert rows == [
+ {"id": task_id, "projectId": 11, "taskListName": "Task list", "taskListNo": 0} for task_id in (1, 2, 3)
+ ]
+
+ @mock.patch(RETRY_ATTEMPTS_PATCH, 1)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_project_members_carry_project_id_and_skip_deleted_projects(self, mock_session: mock.MagicMock) -> None:
+ session, sent = _wire(
+ [
+ _response([{"id": 11}, {"id": 12}]),
+ _response([{"id": 5, "userId": 5, "userName": "A"}]),
+ _response({"error": "not found"}, status=404),
+ ]
+ )
+ mock_session.return_value = session
+
+ rows = _rows(my_hours_source(api_key="mh-key", endpoint="project_members", team_id=1, job_id="j"))
+
+ assert sent[1].url == f"{MY_HOURS_BASE_URL}/Projects/11/userlist"
+ assert rows == [{"id": 5, "userId": 5, "userName": "A", "projectId": 11}]