@startsimpli/integrations 0.2.67 → 0.2.69

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.
@@ -0,0 +1,269 @@
1
+ /**
2
+ * The ONE query vocabulary for the tenant's generic `GET api/v1/entities/`
3
+ * (and `/entities/facets/`, `/relationships/`), as pure functions.
4
+ *
5
+ * Every list screen — web composer or native tab — asks the server for its page,
6
+ * its order and its filters; nothing loads a full list and narrows it locally
7
+ * (CLAUDE.md rule 8). This module is the shared place that spelling lives, so the
8
+ * web adapter (`client.ts`) and the native adapter cannot drift apart.
9
+ *
10
+ * Server contract: start-simpli-api `tenant-starter/apps/api/filters.py`.
11
+ * page, page_size (max 200), search, order=recent|oldest|relevance|[-]attr.<name>,
12
+ * type, id, id__in (comma list), external_id, external_id__in (REPEATED param),
13
+ * source, party, scope, occurred_after/before, created_after/before,
14
+ * related_to + related_via/related_direction/related_depth,
15
+ * attr.<name>[__op] (op: in gt gte lt lte icontains isnull isblank startswith
16
+ * istartswith under).
17
+ * Every parameter is either applied (named in `applied_filters`) or reported in
18
+ * `ignored_filters`; `reconcileFilters` turns that report into a verdict a screen
19
+ * can show, so a filter the server ignored is never presented as applied.
20
+ */
21
+ import { MAX_ID_LIST } from './entities';
22
+
23
+ export type EntityOrder =
24
+ | 'recent'
25
+ | 'oldest'
26
+ | 'relevance'
27
+ | `attr.${string}`
28
+ | `-attr.${string}`;
29
+
30
+ export type AttrValue = string | number | boolean | null | undefined;
31
+
32
+ export interface EntityFilters {
33
+ id?: string;
34
+ idIn?: string[];
35
+ externalId?: string;
36
+ /** Sent as a REPEATED parameter: the server never splits these on a comma. */
37
+ externalIdIn?: string[];
38
+ source?: string;
39
+ party?: string;
40
+ scope?: string;
41
+ occurredAfter?: string;
42
+ occurredBefore?: string;
43
+ createdAfter?: string;
44
+ createdBefore?: string;
45
+ relatedTo?: string;
46
+ relatedVia?: string | string[];
47
+ relatedDirection?: 'out' | 'in' | 'any';
48
+ relatedDepth?: 1 | 2;
49
+ }
50
+
51
+ export interface EntityQuery {
52
+ type: string;
53
+ search?: string;
54
+ order?: EntityOrder;
55
+ filters?: EntityFilters;
56
+ /**
57
+ * Attribute filters keyed by `<name>` or `<name>__<op>` (no `attr.` prefix):
58
+ * `{ status: 'open' }`, `{ status__in: ['open', 'blocked'], due_at__lte: iso }`.
59
+ * Arrays under an `__in` key are comma-joined.
60
+ */
61
+ attr?: Record<string, AttrValue | AttrValue[]>;
62
+ page?: number;
63
+ pageSize?: number;
64
+ }
65
+
66
+ export const MAX_PAGE_SIZE = 200;
67
+ export const TEXT_FILTER_MAX = 500;
68
+ const NOT_A_FILTER = new Set(['page', 'page_size', 'format']);
69
+
70
+ function idList(key: string, ids: string[]): string {
71
+ if (ids.length > MAX_ID_LIST) {
72
+ throw new Error(`${key}: at most ${MAX_ID_LIST} ids per request — page the ids.`);
73
+ }
74
+ return ids.join(',');
75
+ }
76
+
77
+ function put(out: Record<string, unknown>, key: string, value: unknown): void {
78
+ if (value === undefined || value === null || value === '') return;
79
+ out[key] = value;
80
+ }
81
+
82
+ /** Filters that are common to the list and to facets. */
83
+ export function entityFilterParams(filters: EntityFilters = {}): Record<string, unknown> {
84
+ const out: Record<string, unknown> = {};
85
+ put(out, 'id', filters.id);
86
+ if (filters.idIn?.length) out.id__in = idList('id__in', filters.idIn);
87
+ put(out, 'external_id', filters.externalId);
88
+ if (filters.externalIdIn?.length) {
89
+ if (filters.externalIdIn.length > MAX_ID_LIST) {
90
+ throw new Error(`external_id__in: at most ${MAX_ID_LIST} values per request.`);
91
+ }
92
+ out.external_id__in = filters.externalIdIn;
93
+ }
94
+ put(out, 'source', filters.source);
95
+ put(out, 'party', filters.party);
96
+ put(out, 'scope', filters.scope);
97
+ put(out, 'occurred_after', filters.occurredAfter);
98
+ put(out, 'occurred_before', filters.occurredBefore);
99
+ put(out, 'created_after', filters.createdAfter);
100
+ put(out, 'created_before', filters.createdBefore);
101
+ if (filters.relatedTo) {
102
+ out.related_to = filters.relatedTo;
103
+ // Companions only ride along with a target: alone the server ignores them.
104
+ const via = Array.isArray(filters.relatedVia) ? filters.relatedVia.join(',') : filters.relatedVia;
105
+ put(out, 'related_via', via);
106
+ put(out, 'related_direction', filters.relatedDirection);
107
+ put(out, 'related_depth', filters.relatedDepth);
108
+ }
109
+ return out;
110
+ }
111
+
112
+ export function attrParams(attr: EntityQuery['attr'] = {}): Record<string, unknown> {
113
+ const out: Record<string, unknown> = {};
114
+ for (const [name, raw] of Object.entries(attr)) {
115
+ if (raw === undefined || raw === null) continue;
116
+ if (Array.isArray(raw)) {
117
+ const items = raw.filter((v) => v !== undefined && v !== null);
118
+ if (items.length === 0) continue;
119
+ out[`attr.${name}`] = idList(`attr.${name}`, items.map(String));
120
+ } else if (raw !== '') {
121
+ out[`attr.${name}`] = raw;
122
+ }
123
+ }
124
+ return out;
125
+ }
126
+
127
+ /** `EntityQuery` -> the query string parameters of `GET api/v1/entities/`. */
128
+ export function entityParams(query: EntityQuery): Record<string, unknown> {
129
+ const out: Record<string, unknown> = { type: query.type, page: query.page ?? 1 };
130
+ if (query.pageSize) out.page_size = Math.min(Math.max(1, query.pageSize), MAX_PAGE_SIZE);
131
+ const search = query.search?.trim();
132
+ if (search) out.search = search.slice(0, TEXT_FILTER_MAX);
133
+ // `relevance` ranks a search; with no term there is nothing to be relevant TO.
134
+ if (query.order && (query.order !== 'relevance' || search)) out.order = query.order;
135
+ Object.assign(out, entityFilterParams(query.filters), attrParams(query.attr));
136
+ return out;
137
+ }
138
+
139
+ export interface FacetQuery extends Omit<EntityQuery, 'order' | 'search'> {
140
+ /** The attribute whose distinct values are enumerated (`attr=`). */
141
+ facetAttr: string;
142
+ /** Narrow to the subtree under this value (`under=`). */
143
+ under?: string;
144
+ }
145
+
146
+ /** The facet route's vocabulary: entity filters PLUS `attr` and `under`. */
147
+ export function facetParams(query: FacetQuery): Record<string, unknown> {
148
+ const out: Record<string, unknown> = { type: query.type, attr: query.facetAttr, page: query.page ?? 1 };
149
+ if (query.pageSize) out.page_size = Math.min(Math.max(1, query.pageSize), MAX_PAGE_SIZE);
150
+ if (query.under) out.under = query.under;
151
+ Object.assign(out, entityFilterParams(query.filters), attrParams(query.attr));
152
+ return out;
153
+ }
154
+
155
+ export interface RelationshipListQuery {
156
+ source?: string;
157
+ target?: string;
158
+ entity?: string;
159
+ sourceIn?: string[];
160
+ targetIn?: string[];
161
+ entityIn?: string[];
162
+ relType?: string | string[];
163
+ sourceType?: string;
164
+ targetType?: string;
165
+ page?: number;
166
+ pageSize?: number;
167
+ }
168
+
169
+ export function relationshipParams(query: RelationshipListQuery): Record<string, unknown> {
170
+ const out: Record<string, unknown> = { page: query.page ?? 1 };
171
+ if (query.pageSize) out.page_size = Math.min(Math.max(1, query.pageSize), MAX_PAGE_SIZE);
172
+ put(out, 'source', query.source);
173
+ put(out, 'target', query.target);
174
+ put(out, 'entity', query.entity);
175
+ if (query.sourceIn?.length) out.source__in = idList('source__in', query.sourceIn);
176
+ if (query.targetIn?.length) out.target__in = idList('target__in', query.targetIn);
177
+ if (query.entityIn?.length) out.entity__in = idList('entity__in', query.entityIn);
178
+ const rel = Array.isArray(query.relType) ? query.relType.join(',') : query.relType;
179
+ put(out, 'rel_type', rel);
180
+ put(out, 'source_type', query.sourceType);
181
+ put(out, 'target_type', query.targetType);
182
+ return out;
183
+ }
184
+
185
+ /** What the server says about the query it was handed. Both key spellings. */
186
+ export interface FilterReport {
187
+ applied_filters?: string[];
188
+ appliedFilters?: string[];
189
+ ignored_filters?: string[];
190
+ ignoredFilters?: string[];
191
+ }
192
+
193
+ export interface FilterVerdict {
194
+ /** Sent filters the server confirmed it applied. */
195
+ applied: string[];
196
+ /**
197
+ * Sent filters the server did NOT confirm: reported ignored, or absent from
198
+ * `applied_filters`, or the server reports nothing at all. A screen must say
199
+ * so rather than present the list as filtered/ordered.
200
+ */
201
+ ignored: string[];
202
+ /** False when the response carried no `applied_filters` (a fork older than the contract). */
203
+ reported: boolean;
204
+ }
205
+
206
+ /** `party` is confirmed under either spelling: the server labels a party walk `related_to`. */
207
+ const ALIASES: Record<string, string[]> = { party: ['related_to'] };
208
+
209
+ export function sentFilterNames(params: Record<string, unknown>): string[] {
210
+ return Object.keys(params).filter((key) => !NOT_A_FILTER.has(key));
211
+ }
212
+
213
+ export function reconcileFilters(params: Record<string, unknown>, report: FilterReport | undefined): FilterVerdict {
214
+ const sent = sentFilterNames(params);
215
+ const appliedRaw = report?.applied_filters ?? report?.appliedFilters;
216
+ const ignoredRaw = report?.ignored_filters ?? report?.ignoredFilters ?? [];
217
+ if (!Array.isArray(appliedRaw)) return { applied: [], ignored: sent, reported: false };
218
+ const confirmed = new Set(appliedRaw);
219
+ const refused = new Set(ignoredRaw);
220
+ const applied: string[] = [];
221
+ const ignored: string[] = [];
222
+ for (const key of sent) {
223
+ const names = [key, ...(ALIASES[key] ?? [])];
224
+ if (!refused.has(key) && names.some((n) => confirmed.has(n))) applied.push(key);
225
+ else ignored.push(key);
226
+ }
227
+ return { applied, ignored, reported: true };
228
+ }
229
+
230
+ export interface EntityPage<T> {
231
+ items: T[];
232
+ /** Total rows matching, from the server's own COUNT. */
233
+ count: number;
234
+ /** The server's `next` link, or null on the last page. */
235
+ next: string | null;
236
+ /** The page number to ask for next, or null on the last page. */
237
+ nextPage: number | null;
238
+ appliedFilters: string[];
239
+ ignoredFilters: string[];
240
+ /** False when the server did not report which filters it applied. */
241
+ filtersReported: boolean;
242
+ }
243
+
244
+ interface DrfEnvelope<R> extends FilterReport {
245
+ count?: number;
246
+ next?: string | null;
247
+ results?: R[];
248
+ }
249
+
250
+ /** Envelope -> typed page, with the server's filter report reconciled. */
251
+ export function toEntityPage<R, T>(
252
+ params: Record<string, unknown>,
253
+ response: DrfEnvelope<R>,
254
+ map: (row: R) => T,
255
+ ): EntityPage<T> {
256
+ const verdict = reconcileFilters(params, response);
257
+ const page = Number(params.page ?? 1) || 1;
258
+ const items = (response.results ?? []).map(map);
259
+ const next = response.next ?? null;
260
+ return {
261
+ items,
262
+ count: response.count ?? items.length,
263
+ next,
264
+ nextPage: next ? page + 1 : null,
265
+ appliedFilters: verdict.applied,
266
+ ignoredFilters: verdict.ignored,
267
+ filtersReported: verdict.reported,
268
+ };
269
+ }
@@ -170,7 +170,9 @@ export function rulesExtract(document: SourceDocument): CommitmentDraft[] {
170
170
  const flush = () => {
171
171
  if (!current) return;
172
172
  const draft = toDraft(document, current.line, current.detail.join('\n'));
173
- if (draft) drafts.push(focusId ? { ...draft, focusId } : draft);
173
+ if (draft) {
174
+ drafts.push({ ...draft, ...(focusId ? { focusId } : {}), ...(voice ? { section: section.heading } : {}) });
175
+ }
174
176
  current = null;
175
177
  };
176
178
  for (const line of section.body.split('\n')) {
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import type { CorpusHttp } from './client';
15
15
  import type { TenantEntity, TenantRelationship } from './entities';
16
- import { FOCUS_TYPE } from './planning';
16
+ import { FOCUS_TYPE, IN_FOCUS } from './planning';
17
17
 
18
18
  /** A document is ABOUT a focus — its own edge, never `in_focus`. */
19
19
  export const ABOUT_FOCUS = 'about_focus';
@@ -66,6 +66,34 @@ export async function fileDocument(
66
66
  }
67
67
  }
68
68
 
69
+ /**
70
+ * Replace, never add: a commitment lives in one project (bd startsim-23np6.1.1).
71
+ * Edges to other projects are deleted, an edge to `focusId` is kept or written
72
+ * (none for `null`, which unfiles). Idempotent: nothing is written when the item
73
+ * is already filed exactly there.
74
+ */
75
+ export async function setCommitmentFocus(
76
+ http: CorpusHttp,
77
+ commitmentId: string,
78
+ focusId: string | null,
79
+ paths: FilingPaths = {},
80
+ ): Promise<void> {
81
+ const relationships = paths.relationships ?? 'api/v1/relationships';
82
+ if (!http.post) throw new Error('This client is read-only.');
83
+ const existing = await http.get<Page<TenantRelationship>>(relationships, {
84
+ params: { rel_type: IN_FOCUS, source: commitmentId },
85
+ });
86
+ let kept = false;
87
+ for (const edge of existing.results ?? []) {
88
+ if (focusId !== null && String(edge.target) === focusId && !kept) { kept = true; continue; }
89
+ if (!http.delete) throw new Error('This planning client cannot unfile — no delete method was supplied.');
90
+ await http.delete(`${relationships}/${edge.id}`);
91
+ }
92
+ if (focusId !== null && !kept) {
93
+ await http.post(relationships, { rel_type: IN_FOCUS, source: commitmentId, target: focusId });
94
+ }
95
+ }
96
+
69
97
  /**
70
98
  * Make a document's `about_focus` edges exactly this set of projects — adding
71
99
  * the missing, deleting the ones nobody wants, leaving the rest untouched. The
@@ -261,3 +261,12 @@ export type {
261
261
  VoiceSubmission,
262
262
  VoiceTranscriber,
263
263
  } from './voice';
264
+
265
+ export {
266
+ attrParams, entityFilterParams, entityParams, facetParams, reconcileFilters, relationshipParams,
267
+ sentFilterNames, toEntityPage,
268
+ } from './entity-query';
269
+ export type {
270
+ AttrValue, EntityFilters, EntityOrder, EntityPage, EntityQuery, FacetQuery, FilterReport,
271
+ FilterVerdict, RelationshipListQuery,
272
+ } from './entity-query';
@@ -634,6 +634,12 @@ export interface CommitmentMention {
634
634
  quote: string;
635
635
  /** `rules` when the vendor's own structure produced it, `model` otherwise. */
636
636
  extractor: 'rules' | 'model';
637
+ /**
638
+ * The voice-note section heading the bullet was spoken under — the stored link
639
+ * from a to-do back to its section, so moving the section can move the to-do
640
+ * (bd startsim-23np6.1.1). Absent on rows written before this, and on other sources.
641
+ */
642
+ section?: string;
637
643
  }
638
644
 
639
645
  /** A trackable thing that came out of a conversation. */
@@ -742,6 +748,8 @@ export interface CommitmentDraft {
742
748
  extractor: 'rules' | 'model';
743
749
  /** The project of the voice-note section this bullet sits in, when that section is filed. */
744
750
  focusId?: string;
751
+ /** That section's heading (voice notes only), kept on the mention. */
752
+ section?: string;
745
753
  }
746
754
 
747
755
  /**
@@ -0,0 +1,142 @@
1
+ /**
2
+ * RE-FILING A VOICE NOTE'S TO-DOS WHEN ITS PROJECT MOVES (bd startsim-23np6.1.1).
3
+ *
4
+ * Extraction files each commitment under the project of the section it was
5
+ * spoken in (`in_focus`, commitment -> focus). Moving a section (or the whole
6
+ * note) changes `about_focus` and `voice_sections`; without this, the section's
7
+ * existing to-dos stayed under the old project.
8
+ *
9
+ * WHICH TO-DOS BELONG TO WHICH SECTION. The mention a commitment keeps of this
10
+ * note carries the section heading it was spoken under (`mention.section`, set
11
+ * at extraction). Rows written before that field existed are placed by their
12
+ * mention's `quote` — the verbatim bullet — found under its `## heading` in the
13
+ * note's own summary. A to-do that neither says nor can be found is left alone.
14
+ *
15
+ * WHAT MOVES. A to-do follows its section only while it still sits where the
16
+ * section used to be filed (an edge to the old project, or no edge when the
17
+ * section was unfiled). One a person has since filed somewhere else is theirs:
18
+ * the extractor never overwrites a person's edit (see `reconcile`), and neither
19
+ * does this. Only the old edge is removed, so a second project a person added
20
+ * is not lost. Idempotent: a retry after a half-finished move converges.
21
+ */
22
+ import type { CorpusHttp } from './client';
23
+ import { DEFAULT_TYPE_KEYS, toCommitment } from './entities';
24
+ import type { TenantEntity, TenantRelationship } from './entities';
25
+ import type { FilingPaths } from './filing';
26
+ import { ABOUT_FOCUS } from './filing';
27
+ import { IN_FOCUS } from './planning';
28
+ import type { CorpusScope } from './types';
29
+ import { sectionKey } from './voice-sections';
30
+
31
+ /** One section changing project. `label` null = the whole of a note that has no sections. */
32
+ export interface FilingMove {
33
+ label: string | null;
34
+ from: string | null;
35
+ to: string | null;
36
+ }
37
+
38
+ type Page<T> = { results?: T[]; next?: string | null };
39
+
40
+ const MAX_PAGES = 50;
41
+ const EDGE_CHUNK = 25;
42
+
43
+ const HEADING = /^\s*#{1,6}\s+(.+?)\s*$/;
44
+
45
+ /** The `## heading` a verbatim bullet sits under in the note's summary, or null. */
46
+ export function sectionOfQuote(summary: string, quote: string): string | null {
47
+ const wanted = quote.trim();
48
+ if (!wanted) return null;
49
+ let heading: string | null = null;
50
+ for (const line of (summary ?? '').split('\n')) {
51
+ const h = HEADING.exec(line);
52
+ if (h) { heading = h[1]; continue; }
53
+ const flat = line.trim();
54
+ if (heading !== null && flat && (flat === wanted || flat.slice(0, wanted.length) === wanted)) return heading;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** The project a note without sections is filed under now (its first `about_focus` edge). */
60
+ export async function currentNoteFocus(
61
+ http: CorpusHttp,
62
+ noteId: string,
63
+ paths: FilingPaths = {},
64
+ ): Promise<string | null> {
65
+ const edges = await http.get<Page<TenantRelationship>>(paths.relationships ?? 'api/v1/relationships', {
66
+ params: { rel_type: ABOUT_FOCUS, source: noteId },
67
+ });
68
+ const first = edges.results?.[0];
69
+ return first ? String(first.target) : null;
70
+ }
71
+
72
+ /** Every voice-sourced commitment row (paged). The tenant cannot filter inside `mentions`, so the note is picked out here. */
73
+ async function voiceCommitments(http: CorpusHttp, entities: string): Promise<TenantEntity[]> {
74
+ const out: TenantEntity[] = [];
75
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
76
+ const response = await http.get<Page<TenantEntity>>(entities, {
77
+ params: { type: DEFAULT_TYPE_KEYS.commitment, 'attr.source': 'voice', page, page_size: 200 },
78
+ });
79
+ out.push(...(response.results ?? []));
80
+ if (!response.next) break;
81
+ }
82
+ return out;
83
+ }
84
+
85
+ export async function refileVoiceCommitments(
86
+ http: CorpusHttp,
87
+ note: { id: string; summary: string },
88
+ scope: CorpusScope,
89
+ moves: FilingMove[],
90
+ paths: FilingPaths = {},
91
+ ): Promise<void> {
92
+ const real = moves.filter((m) => m.from !== m.to);
93
+ if (!real.length) return;
94
+ if (!http.post) throw new Error('This client is read-only.');
95
+ const entities = paths.entities ?? 'api/v1/entities';
96
+ const relationships = paths.relationships ?? 'api/v1/relationships';
97
+
98
+ // 1. this note's commitments, each with the move that applies to it.
99
+ const matched: Array<{ id: string; move: FilingMove }> = [];
100
+ for (const entity of await voiceCommitments(http, entities)) {
101
+ const item = toCommitment(entity, scope);
102
+ const mention = item.mentions.find((m) => m.documentId === note.id);
103
+ if (!mention) continue;
104
+ const move = real.find((m) => m.label === null)
105
+ ?? real.find((m) => {
106
+ const label = mention.section ?? sectionOfQuote(note.summary, mention.quote);
107
+ return label !== null && sectionKey(label) === sectionKey(m.label as string);
108
+ });
109
+ if (move) matched.push({ id: item.id, move });
110
+ }
111
+ if (!matched.length) return;
112
+
113
+ // 2. where each one is filed now.
114
+ const edgesOf = new Map<string, TenantRelationship[]>();
115
+ for (let i = 0; i < matched.length; i += EDGE_CHUNK) {
116
+ const ids = matched.slice(i, i + EDGE_CHUNK).map((m) => m.id);
117
+ const page = await http.get<Page<TenantRelationship>>(relationships, {
118
+ params: { rel_type: IN_FOCUS, entity__in: ids.join(','), page_size: 200 },
119
+ });
120
+ for (const edge of page.results ?? []) {
121
+ const source = String(edge.source);
122
+ if (!ids.includes(source)) continue;
123
+ edgesOf.set(source, [...(edgesOf.get(source) ?? []), edge]);
124
+ }
125
+ }
126
+
127
+ // 3. move the ones still where the section used to be. New edge first, so a
128
+ // crash between the two writes leaves it in both places (a retry fixes that),
129
+ // never in neither.
130
+ for (const { id, move } of matched) {
131
+ const edges = edgesOf.get(id) ?? [];
132
+ const follows = move.from === null ? edges.length === 0 : edges.some((e) => String(e.target) === move.from);
133
+ if (!follows) continue;
134
+ if (move.to !== null && !edges.some((e) => String(e.target) === move.to)) {
135
+ await http.post(relationships, { rel_type: IN_FOCUS, source: id, target: move.to });
136
+ }
137
+ if (move.from !== null) {
138
+ if (!http.delete) throw new Error('This client cannot move a note — no delete method was supplied.');
139
+ for (const edge of edges) if (String(edge.target) === move.from) await http.delete(`${relationships}/${edge.id}`);
140
+ }
141
+ }
142
+ }
@@ -30,6 +30,8 @@ import type { TenantEntity, TenantRelationship } from './entities';
30
30
  import type { CorpusScope } from './types';
31
31
  import { ABOUT_FOCUS, fileDocument, listFocusChoices, setDocumentFocuses } from './filing';
32
32
  import { filingsFromRow, filingsToRow, uniqueFocusIds } from './voice-sections';
33
+ import { currentNoteFocus, refileVoiceCommitments } from './voice-refile';
34
+ import type { FilingMove } from './voice-refile';
33
35
  import type { SectionFiling, VoiceSection } from './voice-sections';
34
36
  import type { FocusChoice } from './filing';
35
37
 
@@ -416,21 +418,29 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
416
418
  const submit = options.server?.upload ?? options.upload;
417
419
  if (!submit) throw new Error('createVoiceApi needs an upload function or a server client.');
418
420
 
419
- async function readFilings(noteId: string): Promise<{ row: TenantEntity; filings: SectionFiling[] }> {
421
+ async function readFilings(noteId: string): Promise<{ row: TenantEntity; filings: SectionFiling[]; summary: string }> {
420
422
  const row = await http.get<TenantEntity>(`api/v1/entities/${encodeURIComponent(noteId)}`);
421
423
  const data = (row?.data ?? {}) as Record<string, unknown>;
422
- return { row, filings: filingsFromRow(data.voice_sections ?? data.voiceSections) };
424
+ return { row, filings: filingsFromRow(data.voice_sections ?? data.voiceSections), summary: text(data.summary) };
423
425
  }
424
- /** The ONE writer of section filing: the sections on the row, then the edges as their union. */
425
- async function writeFilings(noteId: string, row: TenantEntity, filings: SectionFiling[]): Promise<void> {
426
+ /**
427
+ * The ONE writer of section filing: the to-dos those sections produced, then
428
+ * the sections on the row, then the edges as their union. To-dos go first so a
429
+ * failure part-way leaves the row as it was and a retry finishes the job.
430
+ */
431
+ async function writeFilings(
432
+ noteId: string, row: TenantEntity, summary: string, before: SectionFiling[], after: SectionFiling[],
433
+ ): Promise<void> {
426
434
  if (!http.post) throw new Error('This client is read-only.');
435
+ const moves: FilingMove[] = after.map((f, i) => ({ label: f.label, from: before[i]?.focusId ?? null, to: f.focusId }));
436
+ await refileVoiceCommitments(http, { id: noteId, summary }, options.scope, moves);
427
437
  await http.post('api/v1/entities/upsert', {
428
438
  entity_type: 'source_document',
429
439
  external_id: row.external_id ?? row.externalId,
430
440
  name: row.name,
431
- data: { voice_sections: filingsToRow(filings) },
441
+ data: { voice_sections: filingsToRow(after) },
432
442
  });
433
- await setDocumentFocuses(http, noteId, uniqueFocusIds(filings));
443
+ await setDocumentFocuses(http, noteId, uniqueFocusIds(after));
434
444
  }
435
445
 
436
446
  return {
@@ -465,17 +475,21 @@ export function createVoiceApi(options: CreateVoiceApiOptions): VoiceNotesApi {
465
475
 
466
476
  // Replace, never add. A note with sections moves every section to the one
467
477
  // project (the sections are what say where it lives); one without keeps the
468
- // plain single-edge move.
478
+ // plain single-edge move. Either way the note's existing to-dos follow.
469
479
  async file(noteId, focusId) {
470
- const { row, filings } = await readFilings(noteId);
471
- if (!filings.length) return fileDocument(http, noteId, focusId);
472
- await writeFilings(noteId, row, filings.map((f) => ({ ...f, focusId })));
480
+ const { row, filings, summary } = await readFilings(noteId);
481
+ if (!filings.length) {
482
+ const from = await currentNoteFocus(http, noteId);
483
+ await refileVoiceCommitments(http, { id: noteId, summary }, options.scope, [{ label: null, from, to: focusId }]);
484
+ return fileDocument(http, noteId, focusId);
485
+ }
486
+ await writeFilings(noteId, row, summary, filings, filings.map((f) => ({ ...f, focusId })));
473
487
  },
474
488
 
475
489
  async fileSection(noteId, sectionIndex, focusId) {
476
- const { row, filings } = await readFilings(noteId);
490
+ const { row, filings, summary } = await readFilings(noteId);
477
491
  if (!filings[sectionIndex]) throw new Error('That section no longer exists.');
478
- await writeFilings(noteId, row, filings.map((f, i) => (i === sectionIndex ? { ...f, focusId } : f)));
492
+ await writeFilings(noteId, row, summary, filings, filings.map((f, i) => (i === sectionIndex ? { ...f, focusId } : f)));
479
493
  },
480
494
  };
481
495
  }
@@ -0,0 +1,81 @@
1
+ import { useMemo, useSyncExternalStore, type ReactNode } from 'react';
2
+ import { View } from 'react-native';
3
+ import { useSafeAreaInsets } from 'react-native-safe-area-context';
4
+ import { TabBar, useTheme, type TabItem } from '@startsimpli/ui-native';
5
+ import { createTabsNavigator, type Route, type TabsNavigator } from '../shell/navigator';
6
+
7
+ /** What a tab's `render` is given. */
8
+ export interface TabContext {
9
+ tab: string;
10
+ /** True while this tab is the one on screen (a visited tab stays mounted, hidden, when it is not). */
11
+ active: boolean;
12
+ /** The detail open on this tab, or null while its list shows. */
13
+ route: Route | null;
14
+ /** list -> detail. */
15
+ push(id: string, params?: Record<string, unknown>): void;
16
+ /** detail -> list. */
17
+ back(): void;
18
+ /** Jump to another tab, optionally straight onto a detail. */
19
+ openTab(key: string, detailId?: string): void;
20
+ }
21
+
22
+ export interface FoundryTab {
23
+ key: string;
24
+ label: string;
25
+ icon?: TabItem['icon'];
26
+ render(ctx: TabContext): ReactNode;
27
+ /** Pad the top safe area for this tab. Default true; a screen that draws under the status bar sets false. */
28
+ safeArea?: boolean;
29
+ /** Pop to the list when the user leaves the tab. Default: keep state. */
30
+ resetOnLeave?: boolean;
31
+ }
32
+
33
+ export interface FoundryTabsShellProps {
34
+ tabs: FoundryTab[];
35
+ initialTab?: string;
36
+ /** Open straight on one detail (implies its tab). From a launch arg or deep link. */
37
+ initialDetail?: { tab: string; id: string; params?: Record<string, unknown> };
38
+ /** Drive the shell from outside (warm deep links): `navigator.open(tab, {id})`. */
39
+ navigator?: TabsNavigator;
40
+ }
41
+
42
+ /**
43
+ * Generic bottom-tab shell. Each tab owns a stack (list -> detail with Back); a
44
+ * tab is mounted the first time it is shown and then kept mounted (hidden) so
45
+ * its state - and a recording on the GO tab - survives switching away.
46
+ */
47
+ export function FoundryTabsShell({ tabs, initialTab, initialDetail, navigator }: FoundryTabsShellProps) {
48
+ const theme = useTheme();
49
+ const insets = useSafeAreaInsets();
50
+ const nav = useMemo(
51
+ () => navigator ?? createTabsNavigator({ tabs, initialTab, initialDetail }),
52
+ // The config is read once; tabs are expected to be a stable array.
53
+ // eslint-disable-next-line react-hooks/exhaustive-deps
54
+ [navigator],
55
+ );
56
+ const state = useSyncExternalStore(nav.subscribe, nav.getState, nav.getState);
57
+ return (
58
+ <View style={{ flex: 1, backgroundColor: theme.colors.background }}>
59
+ {tabs.filter((t) => state.visited.includes(t.key)).map((t) => {
60
+ const active = t.key === state.activeKey;
61
+ const route = state.stacks[t.key]?.slice(-1)[0] ?? null;
62
+ const ctx: TabContext = {
63
+ tab: t.key, active, route,
64
+ push: (id, params) => nav.push({ id, ...(params ? { params } : {}) }, t.key),
65
+ back: () => nav.pop(t.key),
66
+ openTab: (key, detailId) => (detailId ? nav.open(key, { id: detailId }) : nav.select(key)),
67
+ };
68
+ return (
69
+ <View key={t.key} style={{ flex: 1, display: active ? 'flex' : 'none', paddingTop: t.safeArea === false ? 0 : insets.top }}>
70
+ {t.render(ctx)}
71
+ </View>
72
+ );
73
+ })}
74
+ <TabBar
75
+ items={tabs.map(({ key, label, icon }) => ({ key, label, icon }))}
76
+ activeKey={state.activeKey}
77
+ onChange={(key) => nav.select(key)}
78
+ />
79
+ </View>
80
+ );
81
+ }