@startsimpli/integrations 0.2.104 → 0.2.106

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 (37) hide show
  1. package/package.json +5 -5
  2. package/src/native/app/FoundryApp.tsx +38 -14
  3. package/src/native/app/__tests__/haptics.test.tsx +48 -0
  4. package/src/native/app/__tests__/hapticsExpo.test.ts +27 -0
  5. package/src/native/app/__tests__/registry.test.tsx +14 -1
  6. package/src/native/app/__tests__/schemaLoad.test.ts +28 -0
  7. package/src/native/app/config/__tests__/schema.test.ts +96 -0
  8. package/src/native/app/config/__tests__/validate.test.ts +12 -2
  9. package/src/native/app/config/defaults.ts +11 -11
  10. package/src/native/app/config/index.ts +1 -0
  11. package/src/native/app/config/schema.ts +62 -0
  12. package/src/native/app/config/types.ts +2 -0
  13. package/src/native/app/config/validate.ts +7 -1
  14. package/src/native/app/device.ts +5 -0
  15. package/src/native/app/entity/EntityTab.tsx +50 -19
  16. package/src/native/app/entity/__tests__/EntityTab.test.tsx +61 -0
  17. package/src/native/app/entity/__tests__/format.test.ts +42 -0
  18. package/src/native/app/entity/format.ts +38 -12
  19. package/src/native/app/haptics.ts +30 -0
  20. package/src/native/app/index.ts +1 -0
  21. package/src/native/app/registry.tsx +5 -2
  22. package/src/native/app/schemaLoad.ts +37 -0
  23. package/src/native/app/screens/ShellBanners.tsx +11 -6
  24. package/src/native/app/screens/SignInScreen.tsx +2 -2
  25. package/src/native/components/NoteDetailScreen.tsx +3 -2
  26. package/src/native/components/usePullRefresh.tsx +4 -2
  27. package/src/native/corpus/__tests__/display.test.ts +36 -1
  28. package/src/native/corpus/api.ts +12 -8
  29. package/src/native/corpus/display.ts +37 -1
  30. package/src/native/corpus/fake-tenant.ts +2 -1
  31. package/src/native/home/HomeScreen.tsx +7 -5
  32. package/src/native/home/__tests__/controller.test.ts +32 -0
  33. package/src/native/home/controller.ts +11 -6
  34. package/src/native/home/tab.tsx +2 -2
  35. package/src/native/recording/__tests__/recovery.test.ts +12 -0
  36. package/src/native/recording/recovery.ts +5 -2
  37. package/src/native/screens/shared/displayView.ts +19 -0
@@ -32,6 +32,9 @@ export interface RowDisplay {
32
32
 
33
33
  export interface SchemaTypeRow { key: string; label?: string; config?: { display?: TypeDisplayConfig } | null }
34
34
 
35
+ /** One declared type as the app reads it: key, what it is called, and how a row reads (when declared). */
36
+ export interface SchemaTypeInfo { key: string; label?: string; display?: TypeDisplayConfig }
37
+
35
38
  const dataOf = (e: TenantEntity): Record<string, unknown> => (e.data ?? {}) as Record<string, unknown>;
36
39
 
37
40
  function text(entity: TenantEntity, attribute: string | undefined): string | null {
@@ -41,15 +44,19 @@ function text(entity: TenantEntity, attribute: string | undefined): string | nul
41
44
  return String(raw);
42
45
  }
43
46
 
47
+ /** `on_track` -> `onTrack`: a client that camelCases response keys also rewrites the keys of `tones`. */
48
+ const camel = (v: string): string => v.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase());
49
+
44
50
  /** `config.display` (may be absent) + a row -> what to show. */
45
51
  export function resolveDisplay(config: TypeDisplayConfig | undefined | null, entity: TenantEntity): RowDisplay {
46
52
  const title = text(entity, config?.title) ?? (entity.name || String(entity.external_id ?? entity.externalId ?? entity.id));
47
53
  const status = text(entity, config?.status);
54
+ const tones = config?.tones;
48
55
  return {
49
56
  title,
50
57
  subtitle: text(entity, config?.subtitle),
51
58
  date: text(entity, config?.date),
52
- status: status ? { value: status, tone: config?.tones?.[status] ?? 'neutral' } : null,
59
+ status: status ? { value: status, tone: tones?.[status] ?? tones?.[camel(status)] ?? 'neutral' } : null,
53
60
  icon: config?.icon ?? null,
54
61
  };
55
62
  }
@@ -60,3 +67,32 @@ export function displaysFrom(rows: SchemaTypeRow[]): Record<string, TypeDisplayC
60
67
  for (const row of rows) if (row.config?.display) out[row.key] = row.config.display;
61
68
  return out;
62
69
  }
70
+
71
+ /** `schema/types` rows -> the declared types, in the order the tenant lists them. */
72
+ export function typesFrom(rows: SchemaTypeRow[]): SchemaTypeInfo[] {
73
+ return rows.filter((r) => r.key && r.key !== '*').map((r) => ({
74
+ key: r.key,
75
+ ...(r.label ? { label: r.label } : {}),
76
+ ...(r.config?.display ? { display: r.config.display } : {}),
77
+ }));
78
+ }
79
+
80
+ const OPEN_TONES: Record<string, DisplayTone> = { open: 'info', done: 'good', blocked: 'warn', dropped: 'neutral' };
81
+
82
+ /**
83
+ * What a row of a well-known type reads as when the tenant has not declared a display yet. Data, not a switch:
84
+ * a tenant that declares a display for the same type replaces it whole, and a type with neither reads as its name.
85
+ */
86
+ export const DEFAULT_DISPLAYS: Record<string, TypeDisplayConfig> = {
87
+ commitment: { title: 'title', subtitle: 'owner_name', date: 'due_at', status: 'status', tones: OPEN_TONES, icon: 'check' },
88
+ source_document: { title: 'title', subtitle: 'subtype', date: 'occurred_at', icon: 'note' },
89
+ focus: {
90
+ title: 'title', subtitle: 'category', date: 'end_date', status: 'status', icon: 'planning',
91
+ tones: { active: 'info', on_track: 'good', at_risk: 'warn', off_track: 'bad', completed: 'good' },
92
+ },
93
+ };
94
+
95
+ /** The tenant's declarations over the built-in defaults, per type. */
96
+ export function layerDisplays(declared: Record<string, TypeDisplayConfig> | undefined | null): Record<string, TypeDisplayConfig> {
97
+ return { ...DEFAULT_DISPLAYS, ...(declared ?? {}) };
98
+ }
@@ -89,7 +89,8 @@ function pageOf<T>(rows: T[], params: Params, fallback: number) {
89
89
 
90
90
  const SAMPLE_SCHEMA_TYPES = [
91
91
  { key: 'commitment', label: 'To-do', config: { display: { title: 'title', subtitle: 'owner_name', date: 'due_at', status: 'status', tones: { done: 'good', blocked: 'bad', open: 'info' }, icon: 'check-circle' } } },
92
- { key: 'focus', label: 'Project', config: {} },
92
+ { key: 'focus', label: 'Project', config: { display: { title: 'title', subtitle: 'category', date: 'end_date', status: 'status', tones: { active: 'info', on_track: 'good', at_risk: 'warn', off_track: 'bad', completed: 'good' }, icon: 'planning' } } },
93
+ { key: 'source_document', label: 'Document', config: { display: { title: 'title', subtitle: 'subtype', date: 'occurred_at', icon: 'note' } } },
93
94
  ];
94
95
 
95
96
  export interface FakeTenant {
@@ -1,6 +1,7 @@
1
1
  import { useEffect } from 'react';
2
2
  import { FlatList, Pressable, RefreshControl, View } from 'react-native';
3
- import { Alert, Button, EmptyState, Header, IconTile, ListRow, SectionHeader, Skeleton, StatTile, useTheme, type IconName } from '@startsimpli/ui-native';
3
+ import { Alert, Button, EmptyState, Header, IconTile, ListRow, SectionHeader, Skeleton, StatTile, StatusChip, useHaptics, useTheme } from '@startsimpli/ui-native';
4
+ import { iconName, toneKey } from '../screens/shared/displayView';
4
5
  import { useControllerState } from '../components/useControllerState';
5
6
  import { timeAgo, type HomeArrival, type HomeController } from './controller';
6
7
 
@@ -22,6 +23,7 @@ export interface HomeScreenProps {
22
23
  /** The front door, as the web Home draws it: brand, "What has come in" counts, "Latest arrivals". */
23
24
  export function HomeScreen({ controller, brand, tagline, onRecord, onOpenType, onOpenArrival, active = true, now = Date.now }: HomeScreenProps) {
24
25
  const theme = useTheme();
26
+ const haptic = useHaptics();
25
27
  const s = useControllerState(controller);
26
28
  useEffect(() => { if (active) void controller.load(); }, [controller, active]);
27
29
  return (
@@ -31,7 +33,7 @@ export function HomeScreen({ controller, brand, tagline, onRecord, onOpenType, o
31
33
  testID="home-list"
32
34
  data={s.arrivals}
33
35
  keyExtractor={(a) => `${a.type}-${a.id}`}
34
- refreshControl={<RefreshControl refreshing={false} onRefresh={() => { void controller.refresh(); }} tintColor={theme.colors.mutedForeground} />}
36
+ refreshControl={<RefreshControl refreshing={false} onRefresh={() => { haptic('light'); void controller.refresh(); }} tintColor={theme.colors.mutedForeground} />}
35
37
  contentContainerStyle={{ paddingHorizontal: theme.layout.gutter, paddingBottom: theme.spacing.xl, flexGrow: 1 }}
36
38
  ListHeaderComponent={
37
39
  <View style={{ gap: theme.spacing.xs, paddingBottom: theme.spacing.xs }}>
@@ -55,9 +57,11 @@ export function HomeScreen({ controller, brand, tagline, onRecord, onOpenType, o
55
57
  ListEmptyComponent={s.loading ? null : <EmptyState icon="note" title="No records yet" description="Record a note to get started." />}
56
58
  renderItem={({ item }) => (
57
59
  <ListRow
58
- leading={<IconTile icon={ARRIVAL_ICON[item.type] ?? 'dot'} tone={item.type === 'commitment' ? 'success' : item.type === 'focus' ? 'warning' : 'info'} />}
60
+ leading={<IconTile icon={iconName(item.display.icon)} tone={item.display.status ? toneKey(item.display.status.tone) : 'info'} />}
59
61
  eyebrow={item.typeLabel || undefined}
60
62
  title={item.title}
63
+ subtitle={item.display.subtitle ?? undefined}
64
+ trailing={item.display.status ? <StatusChip status={item.display.status.value} tone={toneKey(item.display.status.tone)} /> : undefined}
61
65
  meta={timeAgo(item.createdAt, now())}
62
66
  onPress={onOpenArrival ? () => onOpenArrival(item) : undefined}
63
67
  />
@@ -66,5 +70,3 @@ export function HomeScreen({ controller, brand, tagline, onRecord, onOpenType, o
66
70
  </View>
67
71
  );
68
72
  }
69
-
70
- const ARRIVAL_ICON: Record<string, IconName> = { commitment: 'check', source_document: 'note', focus: 'planning' };
@@ -9,6 +9,38 @@ const types = [
9
9
  { key: 'focus', label: 'Projects' },
10
10
  ];
11
11
 
12
+ describe('home controller: arrivals read from the type display', () => {
13
+ it('the tenant declaration drives each arrival (title, subtitle, status tone, icon); a type it does not declare falls back to the built-in default', async () => {
14
+ const api = createFakeNativeCorpusApi();
15
+ const c = createHomeController({
16
+ api, types, limit: 8, now: () => NOW,
17
+ displays: async () => ({ commitment: { title: 'dedupe_key', subtitle: 'source', status: 'status', tones: { open: 'bad' }, icon: 'alert' } }),
18
+ });
19
+ await c.load();
20
+ const item = c.getState().arrivals.find((a) => a.type === 'commitment')!;
21
+ expect(item.display.icon).toBe('alert');
22
+ expect(item.display.status).toMatchObject({ tone: item.display.status?.value === 'open' ? 'bad' : 'neutral' });
23
+ expect(item.title).toBe(item.display.title);
24
+ const focus = c.getState().arrivals.find((a) => a.type === 'focus');
25
+ if (focus) expect(focus.display.icon).toBe('planning');
26
+ });
27
+
28
+ it('a failed schema read still renders every arrival (name only where nothing is known)', async () => {
29
+ const api = createFakeNativeCorpusApi();
30
+ const c = createHomeController({ api, types, now: () => NOW, displays: async () => { throw new Error('offline'); } });
31
+ await c.load();
32
+ expect(c.getState().arrivals.length).toBeGreaterThan(0);
33
+ expect(c.getState().error).toBeNull();
34
+ });
35
+
36
+ it('a type with no declaration and no default reads as its name', async () => {
37
+ const api = createFakeNativeCorpusApi();
38
+ const c = createHomeController({ api, types: [{ key: 'commitment', label: 'x' }], now: () => NOW, displays: async () => ({}) });
39
+ await c.load();
40
+ expect(c.getState().arrivals.every((a) => a.title === a.display.title)).toBe(true);
41
+ });
42
+ });
43
+
12
44
  describe('home controller: what has come in', () => {
13
45
  it('every type count comes from ONE grouped read', async () => {
14
46
  const api = createFakeNativeCorpusApi();
@@ -8,6 +8,7 @@
8
8
  import type { TenantEntity } from '../../corpus/entities';
9
9
  import type { NativeCorpusApi } from '../corpus/api';
10
10
  import { countsBy } from '../corpus/counts';
11
+ import { layerDisplays, resolveDisplay, type RowDisplay, type TypeDisplayConfig } from '../corpus/display';
11
12
 
12
13
  export interface HomeType { key: string; label: string }
13
14
 
@@ -17,6 +18,8 @@ export interface HomeArrival {
17
18
  type: string;
18
19
  typeLabel: string;
19
20
  title: string;
21
+ /** How the row reads, from the type's declared display (tenant schema over the built-in default). */
22
+ display: RowDisplay;
20
23
  createdAt: string;
21
24
  /** The entity's own data bag, for the app's tap routing (source, subtype ...). */
22
25
  entity: TenantEntity;
@@ -43,6 +46,8 @@ export interface HomeControllerOptions {
43
46
  /** How many arrivals to show (web: 8). */
44
47
  limit?: number;
45
48
  now?: () => number;
49
+ /** The tenant's per-type display declarations (`api.schema.displays`). A failed read leaves the built-in defaults. */
50
+ displays?: () => Promise<Record<string, TypeDisplayConfig>>;
46
51
  }
47
52
 
48
53
  const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
@@ -61,7 +66,7 @@ export function timeAgo(iso: string, now: number): string {
61
66
 
62
67
  const stamp = (e: TenantEntity) => String(e.created_at ?? e.createdAt ?? '');
63
68
 
64
- export function createHomeController({ api, types, limit = 8 }: HomeControllerOptions): HomeController {
69
+ export function createHomeController({ api, types, limit = 8, displays }: HomeControllerOptions): HomeController {
65
70
  let state: HomeState = { loading: true, metrics: types.map((t) => ({ key: t.key, label: t.label, count: null })), arrivals: [], error: null };
66
71
  const listeners = new Set<() => void>();
67
72
  const set = (patch: Partial<HomeState>) => { state = { ...state, ...patch }; listeners.forEach((l) => l()); };
@@ -69,19 +74,19 @@ export function createHomeController({ api, types, limit = 8 }: HomeControllerOp
69
74
  async function load() {
70
75
  // TWO reads for the whole screen, however many types it summarises: the count
71
76
  // per type (one grouped read) and the newest rows across those types.
72
- const [counts, recent] = await Promise.all([
77
+ const [counts, recent, declared] = await Promise.all([
73
78
  api.entities.counts({ groupBy: ['type'], filters: { typeIn: types.map((t) => t.key) } })
74
79
  .then((p) => countsBy(p.items, 'type')).catch(() => null),
75
80
  api.entities.list({ filters: { typeIn: types.map((t) => t.key) }, order: 'recent', pageSize: limit })
76
81
  .then((p) => p.items).catch(() => null),
82
+ displays ? displays().catch(() => null) : Promise.resolve(null),
77
83
  ]);
84
+ const display = layerDisplays(declared);
78
85
  const label = new Map(types.map((t) => [t.key, t.label]));
79
86
  const arrivals = (recent ?? []).map((entity): HomeArrival => {
80
87
  const type = String(entity.entity_type ?? entity.entityType ?? '');
81
- return {
82
- id: String(entity.id), type, typeLabel: label.get(type) ?? type,
83
- title: entity.name || entity.external_id || `#${entity.id}`, createdAt: stamp(entity), entity,
84
- };
88
+ const shown = resolveDisplay(display[type], entity);
89
+ return { id: String(entity.id), type, typeLabel: label.get(type) ?? type, title: shown.title, display: shown, createdAt: stamp(entity), entity };
85
90
  });
86
91
  set({
87
92
  loading: false,
@@ -4,7 +4,7 @@ import { createHomeController, type HomeController, type HomeType } from './cont
4
4
  import { HomeScreen } from './HomeScreen';
5
5
 
6
6
  export interface HomeTabOptions {
7
- api: Pick<NativeCorpusApi, 'entities'>;
7
+ api: Pick<NativeCorpusApi, 'entities'> & Partial<Pick<NativeCorpusApi, 'schema'>>;
8
8
  brand: string;
9
9
  tagline?: string;
10
10
  key?: string;
@@ -19,7 +19,7 @@ export interface HomeTabOptions {
19
19
  }
20
20
 
21
21
  /** The Home tab as one `FoundryTabsShell` entry. */
22
- export function homeTab({ api, brand, tagline, key = 'home', label = 'Home', types, controller = createHomeController({ api, types }), tabs = {}, recordKey }: HomeTabOptions): FoundryTab {
22
+ export function homeTab({ api, brand, tagline, key = 'home', label = 'Home', types, controller = createHomeController({ api, types, displays: api.schema ? () => api.schema!.displays() : undefined }), tabs = {}, recordKey }: HomeTabOptions): FoundryTab {
23
23
  return {
24
24
  key, label,
25
25
  render: ({ openTab, active }) => (
@@ -37,6 +37,18 @@ describe('orphan recovery (app killed mid-recording)', () => {
37
37
  expect(ids[0]).toBe(ids[1]);
38
38
  });
39
39
 
40
+ it('queues the recovered file with the duration the device read from it (startsim-150po.9)', async () => {
41
+ const enqueue = vi.fn().mockResolvedValue('queued');
42
+ const log = vi.fn();
43
+ await recoverOrphans({
44
+ list: async () => [{ uri: 'file:///docs/AAAA-1111-bbbb.m4a', bytes: 5000, durationMs: 13781 }, { uri: 'file:///docs/CCCC-2222-dddd.m4a', bytes: 9000 }],
45
+ enqueue, log,
46
+ });
47
+ expect(enqueue.mock.calls[0][0]).toMatchObject({ id: 'AAAA-1111-bbbb', durationMs: 13781 });
48
+ expect(enqueue.mock.calls[1][0]).toMatchObject({ id: 'CCCC-2222-dddd', durationMs: 0 });
49
+ expect(log).toHaveBeenCalledWith('orphan.recovered', expect.objectContaining({ id: 'AAAA-1111-bbbb', durationMs: 13781 }));
50
+ });
51
+
40
52
  it('excludes the file being recorded right now', async () => {
41
53
  const enqueue = vi.fn().mockResolvedValue('queued');
42
54
  await recoverOrphans({ list: async () => files, enqueue, log: vi.fn(), isActive: (uri) => uri.includes('AAAA') });
@@ -3,6 +3,8 @@ import type { QueuedUpload } from '@startsimpli/utils';
3
3
  export interface RecordingFile {
4
4
  uri: string;
5
5
  bytes: number;
6
+ /** Read from the finalized file by the device (a recording killed mid-write has no stored duration). */
7
+ durationMs?: number;
6
8
  }
7
9
 
8
10
  /** Same file name -> same id, in the charset and length the server accepts. */
@@ -32,8 +34,9 @@ export async function recoverOrphans(deps: {
32
34
  deps.log('orphan.skipped', { id, uri: file.uri, bytes: file.bytes });
33
35
  continue;
34
36
  }
35
- deps.log('orphan.recovered', { id, uri: file.uri, bytes: file.bytes });
36
- await deps.enqueue({ id, uri: file.uri, durationMs: 0 });
37
+ const durationMs = file.durationMs && file.durationMs > 0 ? Math.round(file.durationMs) : 0;
38
+ deps.log('orphan.recovered', { id, uri: file.uri, bytes: file.bytes, durationMs });
39
+ await deps.enqueue({ id, uri: file.uri, durationMs });
37
40
  recovered += 1;
38
41
  }
39
42
  return { recovered, skipped };
@@ -0,0 +1,19 @@
1
+ import { ICON_PATHS, type IconName, type ToneKey } from '@startsimpli/ui-native';
2
+ import type { DisplayTone } from '../../corpus/display';
3
+ import { shortDate } from './format';
4
+
5
+ const TONES: Record<DisplayTone, ToneKey> = { good: 'success', warn: 'warning', bad: 'danger', info: 'info', neutral: 'neutral' };
6
+
7
+ /** A declared tone (`good|warn|bad|info|neutral`) as the design system's tone. */
8
+ export const toneKey = (tone: DisplayTone | undefined | null): ToneKey => (tone ? TONES[tone] : undefined) ?? 'neutral';
9
+
10
+ /** A declared icon token as an icon the app draws: the shared icon set, else `fallback`. */
11
+ export function iconName(token: string | null | undefined, fallback: IconName = 'dot'): IconName {
12
+ return token && token in ICON_PATHS ? (token as IconName) : fallback;
13
+ }
14
+
15
+ /** A declared date attribute as a short date; a value that is not a date shows as written. */
16
+ export const whenText = (value: string | null | undefined, now = Date.now()): string | undefined => {
17
+ if (!value) return undefined;
18
+ return shortDate(value, now) || value;
19
+ };