@startsimpli/integrations 0.2.76 → 0.2.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +6 -1
  2. package/package.json +3 -3
  3. package/src/__tests__/api-fetch-factories.test.ts +81 -0
  4. package/src/api/_fetch.ts +93 -61
  5. package/src/api/connections.ts +162 -152
  6. package/src/api/mcp-tokens.ts +25 -15
  7. package/src/components/pages/ConnectClaudePage.tsx +1 -14
  8. package/src/components/pages/MemberConnectionRoster.tsx +2 -5
  9. package/src/components/pages/PlanningPage.tsx +3 -15
  10. package/src/components/pages/connect-claude-format.ts +24 -0
  11. package/src/components/pages/connection-format.ts +20 -0
  12. package/src/components/pages/work-items.tsx +4 -51
  13. package/src/corpus/planning.ts +21 -0
  14. package/src/corpus/work-item-logic.ts +59 -0
  15. package/src/native/corpus/api.ts +2 -3
  16. package/src/native/index.ts +16 -0
  17. package/src/native/screens/connect-claude/ConnectClaudeScreen.tsx +102 -0
  18. package/src/native/screens/connect-claude/__tests__/controller.test.ts +116 -0
  19. package/src/native/screens/connect-claude/controller.ts +108 -0
  20. package/src/native/screens/connect-claude/fake.ts +57 -0
  21. package/src/native/screens/connect-claude/tab.tsx +19 -0
  22. package/src/native/screens/connections/ConnectionsScreens.tsx +108 -0
  23. package/src/native/screens/connections/__tests__/controller.test.ts +66 -0
  24. package/src/native/screens/connections/controller.ts +93 -0
  25. package/src/native/screens/connections/fake.ts +69 -0
  26. package/src/native/screens/connections/tab.tsx +15 -0
  27. package/src/native/screens/planning/PlanningScreens.tsx +178 -0
  28. package/src/native/screens/planning/__tests__/controller.test.ts +145 -0
  29. package/src/native/screens/planning/__tests__/format.test.ts +29 -0
  30. package/src/native/screens/planning/controller.ts +173 -0
  31. package/src/native/screens/planning/fake.ts +16 -0
  32. package/src/native/screens/planning/format.ts +49 -0
  33. package/src/native/screens/planning/tab.tsx +26 -0
  34. package/src/native/screens/shared/PressableCard.tsx +14 -0
  35. package/src/native/screens/shared/format.ts +10 -0
@@ -0,0 +1,178 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { View } from 'react-native';
3
+ import { DataList, Header, Progress, SegmentedControl, StatusChip, Text, useTheme } from '@startsimpli/ui-native';
4
+ import { standingLabel } from '../../../corpus/planning';
5
+ import type { Commitment, Focus, FocusStanding, SourceDocument } from '../../../corpus/types';
6
+ import { PressableCard } from '../shared/PressableCard';
7
+ import { useControllerState } from '../../components/useControllerState';
8
+ import {
9
+ createFocusDetailController, createPlanningController,
10
+ type FocusDetailController, type PlanningScreenApi, type PlanningController,
11
+ } from './controller';
12
+ import { documentLine, focusChipStatus, focusMeta, focusStatusLabel, itemLine, progressPercent, targetLine } from './format';
13
+
14
+ /** The standing, progress bar and facts for one focus. Shared by the list row and the detail header. */
15
+ function FocusSummary({ focus, standing }: { focus: Focus; standing: FocusStanding | null }) {
16
+ const theme = useTheme();
17
+ const percent = progressPercent(focus, standing);
18
+ const meta = focusMeta(focus);
19
+ const target = targetLine(focus);
20
+ return (
21
+ <View style={{ gap: theme.spacing.xs }}>
22
+ <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: theme.spacing.sm }}>
23
+ <Text variant="heading" style={{ flex: 1, fontSize: theme.fontSizes.base }} numberOfLines={2}>{focus.title}</Text>
24
+ <StatusChip status={focusChipStatus(focus.status)} label={focusStatusLabel(focus.status)} />
25
+ </View>
26
+ {meta ? <Text variant="caption">{meta}</Text> : null}
27
+ {percent !== null ? <Progress value={percent} /> : null}
28
+ <Text variant="muted">{[standingLabel(standing), target].filter(Boolean).join(' · ')}</Text>
29
+ </View>
30
+ );
31
+ }
32
+
33
+ export interface PlanningListScreenProps { controller: PlanningController; onOpen: (focus: Focus) => void }
34
+
35
+ /** Projects (focuses), worst-off first from the server, each with its done/overdue counts. */
36
+ export function PlanningListScreen({ controller, onOpen }: PlanningListScreenProps) {
37
+ const state = useControllerState(controller);
38
+ const theme = useTheme();
39
+ const [text, setText] = useState(state.search);
40
+ const f = state.focuses;
41
+ return (
42
+ <View style={{ flex: 1 }}>
43
+ <Header title="Planning" subtitle={f.count !== null ? `${f.count} project${f.count === 1 ? '' : 's'}` : undefined} />
44
+ <DataList
45
+ testID="planning-list"
46
+ data={f.items}
47
+ keyExtractor={(x: Focus) => x.id}
48
+ loading={f.loading}
49
+ error={f.error}
50
+ onRetry={() => { void controller.refresh(); }}
51
+ onRefresh={() => { void controller.refresh(); }}
52
+ hasMore={f.hasMore}
53
+ loadingMore={f.loadingMore}
54
+ onLoadMore={() => { void controller.loadMore(); }}
55
+ search={{ value: text, onChange: setText, onSearch: (q) => { void controller.setSearch(q); }, placeholder: 'Search projects' }}
56
+ onClearFilters={() => { setText(''); void controller.setSearch(''); }}
57
+ emptyTitle="No projects yet"
58
+ emptyDescription="A project is something you are trying to achieve. Create one on the web and it shows up here."
59
+ noResultsTitle="No matching projects"
60
+ ItemSeparatorComponent={() => <View style={{ height: theme.spacing.sm }} />}
61
+ renderItem={({ item }: { item: Focus }) => (
62
+ <PressableCard testID={`focus-${item.id}`} onPress={() => onOpen(item)}>
63
+ <FocusSummary focus={item} standing={state.standings[item.id] ?? null} />
64
+ </PressableCard>
65
+ )}
66
+ />
67
+ </View>
68
+ );
69
+ }
70
+
71
+ type Mode = 'open' | 'closed' | 'notes';
72
+
73
+ export interface PlanningDetailScreenProps {
74
+ api: PlanningScreenApi;
75
+ focusId: string;
76
+ onBack: () => void;
77
+ /** Open a filed document (the Library tab). Without it, documents are not tappable. */
78
+ onOpenDocument?: (documentId: string) => void;
79
+ now?: () => number;
80
+ }
81
+
82
+ /** One project: its standing, then the items filed under it (open / closed) or its notes and documents. */
83
+ export function PlanningDetailScreen({ api, focusId, onBack, onOpenDocument, now = Date.now }: PlanningDetailScreenProps) {
84
+ const controller = useMemo(() => createFocusDetailController({ api, focusId, now }), [api, focusId, now]);
85
+ useEffect(() => () => controller.stop(), [controller]);
86
+ return <DetailBody controller={controller} onBack={onBack} onOpenDocument={onOpenDocument} now={now} />;
87
+ }
88
+
89
+ export function DetailBody({ controller, onBack, onOpenDocument, now = Date.now }: {
90
+ controller: FocusDetailController; onBack: () => void; onOpenDocument?: (id: string) => void; now?: () => number;
91
+ }) {
92
+ const state = useControllerState(controller);
93
+ const items = useControllerState(controller.items);
94
+ const docs = useControllerState(controller.documents);
95
+ const theme = useTheme();
96
+ const [mode, setMode] = useState<Mode>('open');
97
+ const pick = (next: Mode) => {
98
+ setMode(next);
99
+ if (next !== 'notes') void controller.setShowClosed(next === 'closed');
100
+ };
101
+ const clock = now();
102
+ const header = (
103
+ <View style={{ gap: theme.spacing.sm, paddingBottom: theme.spacing.sm }}>
104
+ {state.focus ? <FocusSummary focus={state.focus} standing={state.standing} /> : null}
105
+ {state.focus?.detail ? <Text variant="muted">{state.focus.detail}</Text> : null}
106
+ <SegmentedControl<Mode>
107
+ testID="planning-mode"
108
+ value={mode}
109
+ onChange={pick}
110
+ options={[{ value: 'open', label: 'Open' }, { value: 'closed', label: 'Closed' }, { value: 'notes', label: 'Notes' }]}
111
+ />
112
+ </View>
113
+ );
114
+ const common = {
115
+ onRefresh: () => { void controller.refresh(); },
116
+ ListHeaderComponent: header,
117
+ ItemSeparatorComponent: () => <View style={{ height: theme.spacing.sm }} />,
118
+ };
119
+ return (
120
+ <View style={{ flex: 1 }} testID="planning-detail">
121
+ <Header testID="planning-header" title={state.focus?.title ?? 'Project'} onBack={onBack} />
122
+ {state.error ? (
123
+ <View style={{ padding: theme.spacing.lg, gap: theme.spacing.sm }}>
124
+ <Text variant="muted">{state.error}</Text>
125
+ </View>
126
+ ) : mode === 'notes' ? (
127
+ <DataList
128
+ {...common}
129
+ testID="planning-documents"
130
+ data={docs.items}
131
+ keyExtractor={(d: SourceDocument) => d.id}
132
+ loading={docs.loading}
133
+ error={docs.error}
134
+ onRetry={() => { void controller.documents.refresh(); }}
135
+ hasMore={docs.hasMore}
136
+ loadingMore={docs.loadingMore}
137
+ onLoadMore={() => { void controller.documents.loadMore(); }}
138
+ emptyTitle="No notes yet"
139
+ emptyDescription="Notes and documents filed under this project appear here."
140
+ renderItem={({ item }: { item: SourceDocument }) => (
141
+ <PressableCard testID={`doc-${item.id}`} onPress={onOpenDocument ? () => onOpenDocument(item.id) : undefined}>
142
+ <Text variant="heading" style={{ fontSize: theme.fontSizes.base }}>{item.title}</Text>
143
+ <Text variant="caption">{documentLine(item, clock)}</Text>
144
+ </PressableCard>
145
+ )}
146
+ />
147
+ ) : (
148
+ <DataList
149
+ {...common}
150
+ testID="planning-items"
151
+ data={items.items}
152
+ keyExtractor={(c: Commitment) => c.id}
153
+ loading={items.loading}
154
+ error={items.error}
155
+ onRetry={() => { void controller.items.refresh(); }}
156
+ hasMore={items.hasMore}
157
+ loadingMore={items.loadingMore}
158
+ onLoadMore={() => { void controller.items.loadMore(); }}
159
+ emptyTitle={mode === 'closed' ? 'Nothing closed yet' : 'Nothing open'}
160
+ emptyDescription={mode === 'closed' ? 'Finished items filed under this project appear here.' : 'Nothing is filed under this project yet.'}
161
+ renderItem={({ item }: { item: Commitment }) => (
162
+ <PressableCard testID={`item-${item.id}`}>
163
+ <Text variant="heading" style={{ fontSize: theme.fontSizes.base }}>{item.title}</Text>
164
+ {itemLine(item, clock) ? <Text variant="caption">{itemLine(item, clock)}</Text> : null}
165
+ </PressableCard>
166
+ )}
167
+ />
168
+ )}
169
+ </View>
170
+ );
171
+ }
172
+
173
+ /** Build the controller for the list tab once and stop it with the tab. */
174
+ export function usePlanningController(api: PlanningScreenApi): PlanningController {
175
+ const controller = useMemo(() => createPlanningController({ api }), [api]);
176
+ useEffect(() => () => controller.stop(), [controller]);
177
+ return controller;
178
+ }
@@ -0,0 +1,145 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { sampleTenantEntities, sampleTenantRelationships } from '../../../corpus/fake-data';
3
+ import { createFakePlanningApi } from '../fake';
4
+ import { createFakeNativeCorpusApi } from '../../../corpus/fake';
5
+ import { createFocusDetailController, createPlanningController } from '../controller';
6
+ import { focusStatusLabel, standingLabel } from '../../../../corpus/planning';
7
+
8
+ const NOW = Date.parse('2026-11-04T18:00:00Z');
9
+ const tick = () => new Promise((r) => setTimeout(r, 0));
10
+ async function settle(check: () => boolean) {
11
+ for (let i = 0; i < 50 && !check(); i += 1) await tick();
12
+ }
13
+
14
+ const fakeApi = () => createFakePlanningApi();
15
+
16
+ describe('planning list: focuses with counts from the server', () => {
17
+ it('loads focuses worst-off first from the server, one page, and never the whole list', async () => {
18
+ const api = fakeApi();
19
+ const c = createPlanningController({ api, now: () => NOW });
20
+ await settle(() => !c.getState().focuses.loading);
21
+ const s = c.getState();
22
+ expect(s.focuses.items.map((f) => f.title)).toEqual(['Debug', '287A', 'Marketing agents']);
23
+ const focusRequests = api.tenant.requests.filter((r) => r.params?.type === 'focus');
24
+ expect(focusRequests[0].params).toMatchObject({ page_size: 25, page: 1 });
25
+ c.stop();
26
+ });
27
+
28
+ it('walks the in_focus edges for open/done/overdue counts, as the web card does', async () => {
29
+ const api = fakeApi();
30
+ const c = createPlanningController({ api, now: () => NOW });
31
+ await settle(() => Object.keys(c.getState().standings).length === 3);
32
+ const st = c.getState().standings;
33
+ expect(st.f287).toMatchObject({ total: 3, done: 0, overdue: 1 });
34
+ expect(st.fma).toMatchObject({ total: 2, done: 1, overdue: 0 });
35
+ expect(st.fdbg).toMatchObject({ total: 0, done: 0 });
36
+ const counts = api.tenant.requests.filter((r) => r.params?.related_via === 'in_focus');
37
+ expect(counts.length).toBeGreaterThanOrEqual(9);
38
+ expect(counts.every((r) => r.params?.page_size === 1)).toBe(true);
39
+ c.stop();
40
+ });
41
+
42
+ it('fetches at most four standings at once', async () => {
43
+ const api = fakeApi();
44
+ let running = 0; let peak = 0;
45
+ const real = api.corpus.focusStanding!.bind(api.corpus);
46
+ api.corpus.focusStanding = async (id, now) => {
47
+ running += 1; peak = Math.max(peak, running);
48
+ await tick();
49
+ try { return await real(id, now); } finally { running -= 1; }
50
+ };
51
+ const entities = sampleTenantEntities();
52
+ for (let i = 0; i < 10; i += 1) entities.push({ id: `x${i}`, entity_type: 'focus', external_id: `focus:x${i}`, name: `X${i}`, created_at: '2026-09-10T00:00:00Z', org_id: 'tandem', data: { title: `X${i}`, status: 'active' } } as never);
53
+ const many = createFakeNativeCorpusApi({ entities, relationships: sampleTenantRelationships() });
54
+ many.corpus.focusStanding = api.corpus.focusStanding;
55
+ const c = createPlanningController({ api: many, now: () => NOW });
56
+ await settle(() => Object.keys(c.getState().standings).length === 13);
57
+ expect(Object.keys(c.getState().standings)).toHaveLength(13);
58
+ expect(peak).toBeLessThanOrEqual(4);
59
+ c.stop();
60
+ });
61
+
62
+ it('returns the same state object until something changes (a screen subscribes with useSyncExternalStore)', async () => {
63
+ const api = fakeApi();
64
+ const c = createPlanningController({ api, now: () => NOW });
65
+ await settle(() => Object.keys(c.getState().standings).length === 3);
66
+ expect(c.getState()).toBe(c.getState());
67
+ c.stop();
68
+ });
69
+
70
+ it('a standing that fails leaves that card uncounted instead of failing the list', async () => {
71
+ const api = fakeApi();
72
+ const real = api.corpus.focusStanding!.bind(api.corpus);
73
+ api.corpus.focusStanding = async (id, now) => { if (id === 'fma') throw new Error('boom'); return real(id, now); };
74
+ const c = createPlanningController({ api, now: () => NOW });
75
+ await settle(() => Object.keys(c.getState().standings).length === 2);
76
+ expect(c.getState().focuses.error).toBeNull();
77
+ expect(c.getState().standings.fma).toBeUndefined();
78
+ c.stop();
79
+ });
80
+
81
+ it('searches by sending the term to the server and starts over', async () => {
82
+ const api = fakeApi();
83
+ const c = createPlanningController({ api, now: () => NOW });
84
+ await settle(() => !c.getState().focuses.loading);
85
+ await c.setSearch('debug');
86
+ expect(api.tenant.requests.filter((r) => r.params?.type === 'focus').at(-1)?.params).toMatchObject({ search: 'debug', page: 1 });
87
+ c.stop();
88
+ });
89
+ });
90
+
91
+ describe('project detail: its items and documents, server-side', () => {
92
+ it('loads the project, its open items by the in_focus edge walk and its documents by about_focus', async () => {
93
+ const api = fakeApi();
94
+ const d = createFocusDetailController({ api, focusId: 'f287', now: () => NOW });
95
+ await settle(() => d.getState().focus !== null && !d.items.getState().loading && !d.documents.getState().loading);
96
+ expect(d.getState().focus?.title).toBe('287A');
97
+ expect(d.items.getState().items.map((i) => i.id).sort()).toEqual(['c1', 'c2', 'c6']);
98
+ expect(d.documents.getState().items.map((x) => x.id)).toEqual(['d1']);
99
+ const item = api.tenant.requests.find((r) => r.params?.type === 'commitment' && r.params?.related_to === 'f287');
100
+ expect(item?.params).toMatchObject({ related_via: 'in_focus', related_direction: 'out' });
101
+ const doc = api.tenant.requests.find((r) => r.params?.related_via === 'about_focus');
102
+ expect(doc?.params).toMatchObject({ related_to: 'f287', related_direction: 'out' });
103
+ d.stop();
104
+ });
105
+
106
+ it('switches to closed items with a server query, not a local filter', async () => {
107
+ const api = fakeApi();
108
+ const d = createFocusDetailController({ api, focusId: 'fma', now: () => NOW });
109
+ await settle(() => !d.items.getState().loading);
110
+ expect(d.items.getState().items.map((i) => i.id)).toEqual(['c3']);
111
+ await d.setShowClosed(true);
112
+ expect(d.getState().showClosed).toBe(true);
113
+ expect(d.items.getState().items.map((i) => i.id)).toEqual(['c5']);
114
+ const last = api.tenant.requests.filter((r) => r.params?.related_to === 'fma' && r.params?.type === 'commitment').at(-1);
115
+ expect(String(JSON.stringify(last?.params))).toMatch(/done/);
116
+ d.stop();
117
+ });
118
+
119
+ it('reports a missing project as an error, not an empty page', async () => {
120
+ const api = fakeApi();
121
+ const d = createFocusDetailController({ api, focusId: 'nope', now: () => NOW });
122
+ await settle(() => d.getState().error !== null);
123
+ expect(d.getState().error).toBeTruthy();
124
+ expect(d.getState().focus).toBeNull();
125
+ d.stop();
126
+ });
127
+
128
+ it('shows the project standing', async () => {
129
+ const api = fakeApi();
130
+ const d = createFocusDetailController({ api, focusId: 'f287', now: () => NOW });
131
+ await settle(() => d.getState().standing !== null);
132
+ expect(d.getState().standing).toMatchObject({ total: 3, done: 0, overdue: 1 });
133
+ d.stop();
134
+ });
135
+ });
136
+
137
+ describe('planning labels (shared with the web card)', () => {
138
+ it('names a status and a standing the way the web card does', () => {
139
+ expect(focusStatusLabel('on_track')).toBe('on track');
140
+ expect(standingLabel(null)).toBe('Counting…');
141
+ expect(standingLabel({ focusId: 'a', total: 0, done: 0, overdue: 0 })).toBe('Nothing filed under this yet');
142
+ expect(standingLabel({ focusId: 'a', total: 40, done: 12, overdue: 3 })).toBe('12 of 40 done · 3 overdue');
143
+ expect(standingLabel({ focusId: 'a', total: 4, done: 4, overdue: 0 })).toBe('4 of 4 done');
144
+ });
145
+ });
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { Commitment, Focus } from '../../../../corpus/types';
3
+ import { focusMeta, focusChipStatus, itemLine, progressPercent, targetLine } from '../format';
4
+
5
+ const NOW = Date.parse('2026-11-04T18:00:00Z');
6
+ const item = (over: Partial<Commitment>) => ({ id: 'c', title: 't', status: 'open', ...over }) as Commitment;
7
+ const focus = (over: Partial<Focus>) => ({ id: 'f', title: 'F', status: 'active', ...over }) as Focus;
8
+
9
+ describe('planning formatting', () => {
10
+ it('marks a past-due open item overdue and leaves a closed one alone', () => {
11
+ expect(itemLine(item({ dueAt: '2026-11-04T17:00:00Z', ownerName: 'Quinn', priority: 1 }), NOW)).toBe('Overdue · Nov 4 · Quinn · High');
12
+ expect(itemLine(item({ dueAt: '2026-11-04T17:00:00Z', status: 'done' }), NOW)).toBe('Due Nov 4');
13
+ expect(itemLine(item({ status: 'blocked', statusReason: 'Clerk silent' }), NOW)).toBe('Blocked: Clerk silent');
14
+ });
15
+ it('shows no progress bar when there is nothing to measure, not an empty one', () => {
16
+ expect(progressPercent(focus({}), null)).toBeNull();
17
+ expect(progressPercent(focus({ progress: 0.4 }), null)).toBe(40);
18
+ expect(progressPercent(focus({}), { focusId: 'f', total: 4, done: 1, overdue: 0 })).toBe(25);
19
+ });
20
+ it('colours focus status by how it is going', () => {
21
+ expect(focusChipStatus('at_risk')).toBe('warning');
22
+ expect(focusChipStatus('off_track')).toBe('failed');
23
+ });
24
+ it('describes a measurable focus and its frame', () => {
25
+ expect(targetLine(focus({ targetValue: 10, currentValue: 5, unit: 'pages' }))).toBe('5 / 10 pages');
26
+ expect(targetLine(focus({}))).toBeNull();
27
+ expect(focusMeta(focus({ category: 'product', timeFrame: 'Q4', year: 2026, ownerName: 'Rae' }))).toBe('product · Q4 2026 · Rae');
28
+ });
29
+ });
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Planning (projects/focuses) as framework-free controllers over the shared
3
+ * native corpus api - the same adapters the web `PlanningPage` uses.
4
+ *
5
+ * Server-side only: the focus list is one server page at a time (worst-off first,
6
+ * the order the stored `progress` buys), each card's counts are `focusStanding`
7
+ * (three count-only reads walking the `in_focus` edge, exactly the web card's),
8
+ * and a project's items and documents are server-paged queries filtered by the
9
+ * focus edge. Nothing loads a list to narrow, sort or page it on the phone.
10
+ */
11
+ import { toFocus } from '../../../corpus/planning';
12
+ import type { Commitment, Focus, FocusQuery, FocusStanding, SourceDocument } from '../../../corpus/types';
13
+ import type { NativeCorpusApi } from '../../corpus/api';
14
+ import type { PagedList, PagedListState } from '../../corpus/paged';
15
+ import { createStore, errorMessage } from '../store';
16
+
17
+ export type PlanningScreenApi = Pick<NativeCorpusApi, 'lists' | 'corpus' | 'entities' | 'scope'>;
18
+
19
+ /** How many standings are fetched at once - each is three reads, and the tenant pays for every one. */
20
+ export const STANDING_CONCURRENCY = 4;
21
+ export const FOCUS_PAGE_SIZE = 25;
22
+ export const DOCUMENT_PAGE_SIZE = 10;
23
+ export const ITEM_PAGE_SIZE = 25;
24
+
25
+ type FocusListQuery = Omit<FocusQuery, 'page' | 'pageSize'>;
26
+
27
+ export interface PlanningState {
28
+ focuses: PagedListState<Focus>;
29
+ /** By focus id. A focus whose count failed or has not arrived is simply absent. */
30
+ standings: Record<string, FocusStanding>;
31
+ search: string;
32
+ }
33
+
34
+ export interface PlanningController {
35
+ getState(): PlanningState;
36
+ subscribe(listener: () => void): () => void;
37
+ refresh(): Promise<void>;
38
+ loadMore(): Promise<void>;
39
+ setSearch(text: string): Promise<void>;
40
+ stop(): void;
41
+ }
42
+
43
+ export interface PlanningDeps {
44
+ api: PlanningScreenApi;
45
+ /** Injected so "overdue" is testable and not a fresh `Date.now()` per call. */
46
+ now?: () => number;
47
+ }
48
+
49
+ /** Worker pool that runs standing reads `STANDING_CONCURRENCY` at a time. */
50
+ function createStandingFetcher(api: PlanningScreenApi, now: () => number, onResult: (s: FocusStanding) => void) {
51
+ const requested = new Set<string>();
52
+ const queue: string[] = [];
53
+ let running = 0;
54
+ let stopped = false;
55
+
56
+ function pump() {
57
+ while (!stopped && running < STANDING_CONCURRENCY && queue.length) {
58
+ const id = queue.shift() as string;
59
+ running += 1;
60
+ Promise.resolve()
61
+ .then(() => api.corpus.focusStanding!(id, now()))
62
+ .then((s) => { if (!stopped) onResult(s); }, () => { /* uncounted, not a failed list */ })
63
+ .finally(() => { running -= 1; pump(); });
64
+ }
65
+ }
66
+
67
+ return {
68
+ request(ids: string[]) {
69
+ if (!api.corpus.focusStanding) return;
70
+ for (const id of ids) if (!requested.has(id)) { requested.add(id); queue.push(id); }
71
+ pump();
72
+ },
73
+ forget() { requested.clear(); },
74
+ stop() { stopped = true; queue.length = 0; },
75
+ };
76
+ }
77
+
78
+ export function createPlanningController({ api, now = Date.now }: PlanningDeps): PlanningController {
79
+ const list = api.lists.focuses({ orderBy: 'progress' } as FocusListQuery, FOCUS_PAGE_SIZE);
80
+ const store = createStore<{ standings: Record<string, FocusStanding>; search: string }>({ standings: {}, search: '' });
81
+ const listeners = new Set<() => void>();
82
+ const notify = () => listeners.forEach((l) => l());
83
+ const counts = createStandingFetcher(api, now, (s) => store.set({ standings: { ...store.getState().standings, [s.focusId]: s } }));
84
+
85
+ // One cached snapshot, rebuilt only when a part changes: `useSyncExternalStore` loops on a getState that returns a new object each call.
86
+ let snapshot: PlanningState = { focuses: list.getState(), standings: store.getState().standings, search: store.getState().search };
87
+ const rebuild = () => {
88
+ snapshot = { focuses: list.getState(), standings: store.getState().standings, search: store.getState().search };
89
+ notify();
90
+ };
91
+ const offList = list.subscribe(() => { counts.request(list.getState().items.map((f) => f.id)); rebuild(); });
92
+ const offStore = store.subscribe(rebuild);
93
+ void list.refresh();
94
+
95
+ return {
96
+ getState: () => snapshot,
97
+ subscribe(l) { listeners.add(l); return () => { listeners.delete(l); }; },
98
+ async refresh() { counts.forget(); store.set({ standings: {} }); await list.refresh(); },
99
+ loadMore: () => list.loadMore(),
100
+ async setSearch(text) {
101
+ store.set({ search: text });
102
+ const q = text.trim();
103
+ await list.setQuery({ orderBy: 'progress', ...(q ? { search: q } : {}) } as FocusListQuery);
104
+ },
105
+ stop() { counts.stop(); offList(); offStore(); },
106
+ };
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+
111
+ export interface FocusDetailState {
112
+ focus: Focus | null;
113
+ standing: FocusStanding | null;
114
+ showClosed: boolean;
115
+ error: string | null;
116
+ }
117
+
118
+ export interface FocusDetailController {
119
+ getState(): FocusDetailState;
120
+ subscribe(listener: () => void): () => void;
121
+ /** Items filed under the project (open/blocked, or done/dropped when `showClosed`). */
122
+ items: PagedList<Commitment, { status: string[]; focus: string }>;
123
+ /** Notes and documents filed under the project, most recent first. */
124
+ documents: PagedList<SourceDocument, { focus: string; order: 'recent' }>;
125
+ setShowClosed(closed: boolean): Promise<void>;
126
+ refresh(): Promise<void>;
127
+ stop(): void;
128
+ }
129
+
130
+ const OPEN = ['open', 'blocked'];
131
+ const CLOSED = ['done', 'dropped'];
132
+
133
+ export function createFocusDetailController(
134
+ { api, focusId, now = Date.now }: PlanningDeps & { focusId: string },
135
+ ): FocusDetailController {
136
+ const store = createStore<FocusDetailState>({ focus: null, standing: null, showClosed: false, error: null });
137
+ const items = api.lists.commitments({ status: OPEN as never, focus: focusId }, ITEM_PAGE_SIZE) as unknown as FocusDetailController['items'];
138
+ const documents = api.lists.documents({ focus: focusId, order: 'recent' }, DOCUMENT_PAGE_SIZE) as unknown as FocusDetailController['documents'];
139
+ let stopped = false;
140
+
141
+ async function loadFocus() {
142
+ try {
143
+ const entity = await api.entities.get(focusId);
144
+ if (stopped) return;
145
+ store.set({ focus: toFocus(entity, api.scope), error: null });
146
+ } catch (e) {
147
+ if (!stopped) store.set({ focus: null, error: errorMessage(e, 'This project could not be loaded.') });
148
+ }
149
+ try {
150
+ const standing = await api.corpus.focusStanding?.(focusId, now());
151
+ if (!stopped && standing) store.set({ standing });
152
+ } catch { /* the header shows no count rather than a wrong one */ }
153
+ }
154
+
155
+ void loadFocus();
156
+ void items.refresh();
157
+ void documents.refresh();
158
+
159
+ return {
160
+ getState: store.getState,
161
+ subscribe: store.subscribe,
162
+ items,
163
+ documents,
164
+ async setShowClosed(closed) {
165
+ store.set({ showClosed: closed });
166
+ await items.setQuery({ status: closed ? CLOSED : OPEN, focus: focusId });
167
+ },
168
+ async refresh() {
169
+ await Promise.all([loadFocus(), items.refresh(), documents.refresh()]);
170
+ },
171
+ stop() { stopped = true; },
172
+ };
173
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The sample tenant for Planning screens: the shared Tandem fake plus one closed
3
+ * item filed under "Marketing agents", so a project with finished work (and a
4
+ * "done" count) exists for simulators and tests. Reads an in-memory tenant only.
5
+ */
6
+ import { createFakeNativeCorpusApi, type FakeNativeCorpusApi } from '../../corpus/fake';
7
+ import { sampleTenantEntities, sampleTenantRelationships } from '../../corpus/fake-data';
8
+ import type { FakeTenantOptions } from '../../corpus/fake-tenant';
9
+
10
+ export function createFakePlanningApi(options: FakeTenantOptions = {}): FakeNativeCorpusApi {
11
+ return createFakeNativeCorpusApi({
12
+ entities: sampleTenantEntities(),
13
+ relationships: [...sampleTenantRelationships(), { id: 'e8', rel_type: 'in_focus', source: 'c5', target: 'fma' }],
14
+ ...options,
15
+ });
16
+ }
@@ -0,0 +1,49 @@
1
+ import { displayProgress, focusStatusLabel } from '../../../corpus/planning';
2
+ import type { Commitment, Focus, FocusStanding, FocusStatus, SourceDocument } from '../../../corpus/types';
3
+ import { isOverdue, priorityLabel } from '../../../corpus/work-item-logic';
4
+ import { shortDate } from '../shared/format';
5
+
6
+ /** The StatusChip status word that gives a focus status its colour. */
7
+ export function focusChipStatus(status: FocusStatus): string {
8
+ return ({
9
+ draft: 'draft', active: 'active', on_track: 'success', at_risk: 'warning', off_track: 'failed', completed: 'completed', cancelled: 'paused',
10
+ } as const)[status] ?? 'draft';
11
+ }
12
+
13
+ export { focusStatusLabel };
14
+
15
+ /** 0-100 for the Progress bar, or null when the focus has nothing to show (a bar at 0 would say "no progress"). */
16
+ export function progressPercent(focus: Focus, standing: FocusStanding | null): number | null {
17
+ const p = displayProgress(focus, standing);
18
+ return p === null ? null : Math.round(p * 100);
19
+ }
20
+
21
+ /** "5 / 10 pages" for a measurable focus. */
22
+ export function targetLine(focus: Focus): string | null {
23
+ if (focus.targetValue === undefined || focus.targetValue === null) return null;
24
+ return `${focus.currentValue ?? 0} / ${focus.targetValue}${focus.unit ? ` ${focus.unit}` : ''}`;
25
+ }
26
+
27
+ /** The facts under a focus title: category, time frame, owner. */
28
+ export function focusMeta(focus: Focus): string {
29
+ return [
30
+ focus.category,
31
+ focus.timeFrame ? `${focus.timeFrame}${focus.year ? ` ${focus.year}` : ''}` : null,
32
+ focus.ownerName,
33
+ ].filter(Boolean).join(' · ');
34
+ }
35
+
36
+ /** One line under an item: overdue/due, owner, priority, why it is blocked. */
37
+ export function itemLine(item: Commitment, now: number): string {
38
+ const due = shortDate(item.dueAt, now);
39
+ return [
40
+ due ? `${isOverdue(item, now) ? 'Overdue · ' : 'Due '}${due}` : null,
41
+ item.ownerName || null,
42
+ priorityLabel(item.priority),
43
+ item.status === 'blocked' ? (item.statusReason ? `Blocked: ${item.statusReason}` : 'Blocked') : null,
44
+ ].filter(Boolean).join(' · ');
45
+ }
46
+
47
+ export function documentLine(doc: SourceDocument, now: number): string {
48
+ return [doc.sourceLabel || doc.source, shortDate(doc.occurredAt, now)].filter(Boolean).join(' · ');
49
+ }
@@ -0,0 +1,26 @@
1
+ import type { FoundryTab, TabContext } from '../../components/FoundryTabsShell';
2
+ import type { PlanningScreenApi } from './controller';
3
+ import { PlanningDetailScreen, PlanningListScreen, usePlanningController } from './PlanningScreens';
4
+
5
+ /** One list controller for the tab's lifetime, so Back from a project does not re-read every project and count. */
6
+ function PlanningTab({ api, ctx, documentTab }: { api: PlanningScreenApi; ctx: TabContext; documentTab?: string }) {
7
+ const controller = usePlanningController(api);
8
+ return ctx.route
9
+ ? (
10
+ <PlanningDetailScreen
11
+ api={api} focusId={ctx.route.id} onBack={ctx.back}
12
+ onOpenDocument={documentTab ? (id) => ctx.openTab(documentTab, id) : undefined}
13
+ />
14
+ )
15
+ : <PlanningListScreen controller={controller} onOpen={(f) => ctx.push(f.id)} />;
16
+ }
17
+
18
+ /**
19
+ * The Planning tab: projects with counts, then a project's items and notes.
20
+ * `documentTab` (the Library tab's key) makes a filed note tappable.
21
+ */
22
+ export function createPlanningTab({ api, documentTab, key = 'planning', label = 'Planning' }: {
23
+ api: PlanningScreenApi; documentTab?: string; key?: string; label?: string;
24
+ }): FoundryTab {
25
+ return { key, label, render: (ctx) => <PlanningTab api={api} ctx={ctx} documentTab={documentTab} /> };
26
+ }
@@ -0,0 +1,14 @@
1
+ import type { ReactNode } from 'react';
2
+ import { Pressable } from 'react-native';
3
+ import { Card } from '@startsimpli/ui-native';
4
+
5
+ /** A `Card` that can be tapped. (ui-native has no pressable card yet; this wraps its `Card`.) */
6
+ export function PressableCard({ onPress, testID, children }: { onPress?: () => void; testID?: string; children: ReactNode }) {
7
+ const body = <Card>{children}</Card>;
8
+ if (!onPress) return <Pressable testID={testID} disabled>{body}</Pressable>;
9
+ return (
10
+ <Pressable testID={testID} accessibilityRole="button" onPress={onPress} style={({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })}>
11
+ {body}
12
+ </Pressable>
13
+ );
14
+ }
@@ -0,0 +1,10 @@
1
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
2
+
3
+ /** "Nov 5", with the year when it is not the current one. Empty for a missing or bad stamp. */
4
+ export function shortDate(iso: string | null | undefined, now: number): string {
5
+ if (!iso) return '';
6
+ const d = new Date(iso);
7
+ if (Number.isNaN(d.getTime())) return '';
8
+ const year = d.getUTCFullYear() === new Date(now).getUTCFullYear() ? '' : `, ${d.getUTCFullYear()}`;
9
+ return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}${year}`;
10
+ }