@adminide-stack/yantra-mobile 12.0.98 → 12.0.99-alpha.0
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.
- package/lib/bridge/handlers/SurfaceHostBridgeHandler.js +9 -2
- package/lib/bridge/handlers/SurfaceHostBridgeHandler.js.map +1 -1
- package/lib/compute.js +109 -1
- package/lib/compute.js.map +1 -1
- package/lib/config/env-config.js +11 -1
- package/lib/config/env-config.js.map +1 -1
- package/lib/features/agent-chat/NativeAgentChat.js.map +1 -1
- package/lib/features/apps/AppsCatalog.js +10 -0
- package/lib/features/apps/AppsCatalog.js.map +1 -1
- package/lib/features/apps/appArt.js +2 -1
- package/lib/features/apps/appArt.js.map +1 -1
- package/lib/features/apps/mobileAppCatalog.js +10 -0
- package/lib/features/apps/mobileAppCatalog.js.map +1 -1
- package/lib/features/apps/nativeAppHandoff.js +2 -1
- package/lib/features/apps/nativeAppHandoff.js.map +1 -1
- package/lib/features/apps/resolveSurfaceUrl.js +1 -2
- package/lib/features/apps/resolveSurfaceUrl.js.map +1 -1
- package/lib/features/attachments/useImageAttachments.js +8 -5
- package/lib/features/attachments/useImageAttachments.js.map +1 -1
- package/lib/features/chat/AssistantMarkdown.js +7 -6
- package/lib/features/chat/AssistantMarkdown.js.map +1 -1
- package/lib/features/chat/ChatTranscript.js +12 -2
- package/lib/features/chat/ChatTranscript.js.map +1 -1
- package/lib/features/devices/bleTransport.js +141 -0
- package/lib/features/devices/bleTransport.js.map +1 -0
- package/lib/features/devices/catalog.js +59 -0
- package/lib/features/devices/catalog.js.map +1 -0
- package/lib/features/devices/deviceStore.js +292 -0
- package/lib/features/devices/deviceStore.js.map +1 -0
- package/lib/features/devices/devices.js +68 -0
- package/lib/features/devices/devices.js.map +1 -0
- package/lib/features/devices/drivers.js +378 -0
- package/lib/features/devices/drivers.js.map +1 -0
- package/lib/features/devices/gatt/bytes.js +103 -0
- package/lib/features/devices/gatt/bytes.js.map +1 -0
- package/lib/features/devices/gatt/dateTime.js +23 -0
- package/lib/features/devices/gatt/dateTime.js.map +1 -0
- package/lib/features/devices/gatt/measurements.js +210 -0
- package/lib/features/devices/gatt/measurements.js.map +1 -0
- package/lib/features/devices/gatt/userData.js +57 -0
- package/lib/features/devices/gatt/userData.js.map +1 -0
- package/lib/features/devices/gatt/uuids.js +41 -0
- package/lib/features/devices/gatt/uuids.js.map +1 -0
- package/lib/features/devices/link.js +8 -0
- package/lib/features/devices/link.js.map +1 -0
- package/lib/features/devices/readings.js +158 -0
- package/lib/features/devices/readings.js.map +1 -0
- package/lib/features/devices/session.js +334 -0
- package/lib/features/devices/session.js.map +1 -0
- package/lib/features/expenses/ExpensesAgentChatPane.js +50 -0
- package/lib/features/expenses/ExpensesAgentChatPane.js.map +1 -0
- package/lib/features/expenses/ExpensesExperience.js +646 -0
- package/lib/features/expenses/ExpensesExperience.js.map +1 -0
- package/lib/features/expenses/claimFilters.js +94 -0
- package/lib/features/expenses/claimFilters.js.map +1 -0
- package/lib/features/expenses/components/AccountsPanel.js +464 -0
- package/lib/features/expenses/components/AccountsPanel.js.map +1 -0
- package/lib/features/expenses/components/BudgetsPanel.js +320 -0
- package/lib/features/expenses/components/BudgetsPanel.js.map +1 -0
- package/lib/features/expenses/components/CategoriesSheet.js +181 -0
- package/lib/features/expenses/components/CategoriesSheet.js.map +1 -0
- package/lib/features/expenses/components/ClaimDetail.js +309 -0
- package/lib/features/expenses/components/ClaimDetail.js.map +1 -0
- package/lib/features/expenses/components/ClaimForm.js +375 -0
- package/lib/features/expenses/components/ClaimForm.js.map +1 -0
- package/lib/features/expenses/components/ClaimRow.js +77 -0
- package/lib/features/expenses/components/ClaimRow.js.map +1 -0
- package/lib/features/expenses/components/ClaimsPanel.js +388 -0
- package/lib/features/expenses/components/ClaimsPanel.js.map +1 -0
- package/lib/features/expenses/components/DateSheet.js +214 -0
- package/lib/features/expenses/components/DateSheet.js.map +1 -0
- package/lib/features/expenses/components/ExpensesStates.js +274 -0
- package/lib/features/expenses/components/ExpensesStates.js.map +1 -0
- package/lib/features/expenses/components/ExpensesTabBar.js +83 -0
- package/lib/features/expenses/components/ExpensesTabBar.js.map +1 -0
- package/lib/features/expenses/components/FiltersSheet.js +137 -0
- package/lib/features/expenses/components/FiltersSheet.js.map +1 -0
- package/lib/features/expenses/components/InsightsPanel.js +362 -0
- package/lib/features/expenses/components/InsightsPanel.js.map +1 -0
- package/lib/features/expenses/components/RecurringPanel.js +370 -0
- package/lib/features/expenses/components/RecurringPanel.js.map +1 -0
- package/lib/features/expenses/components/Sheets.js +220 -0
- package/lib/features/expenses/components/Sheets.js.map +1 -0
- package/lib/features/expenses/components/ui.js +496 -0
- package/lib/features/expenses/components/ui.js.map +1 -0
- package/lib/features/expenses/expensesClient.js +398 -0
- package/lib/features/expenses/expensesClient.js.map +1 -0
- package/lib/features/expenses/expensesContext.js +30 -0
- package/lib/features/expenses/expensesContext.js.map +1 -0
- package/lib/features/expenses/expensesEndpoint.js +12 -0
- package/lib/features/expenses/expensesEndpoint.js.map +1 -0
- package/lib/features/expenses/expensesFormat.js +360 -0
- package/lib/features/expenses/expensesFormat.js.map +1 -0
- package/lib/features/expenses/expensesOperations.js +136 -0
- package/lib/features/expenses/expensesOperations.js.map +1 -0
- package/lib/features/expenses/expensesPrompts.js +81 -0
- package/lib/features/expenses/expensesPrompts.js.map +1 -0
- package/lib/features/expenses/expensesTheme.js +107 -0
- package/lib/features/expenses/expensesTheme.js.map +1 -0
- package/lib/features/expenses/nativeExpensesRegistry.js +15 -0
- package/lib/features/expenses/nativeExpensesRegistry.js.map +1 -0
- package/lib/features/expenses/receiptScan.js +242 -0
- package/lib/features/expenses/receiptScan.js.map +1 -0
- package/lib/features/expenses/useClaimsList.js +159 -0
- package/lib/features/expenses/useClaimsList.js.map +1 -0
- package/lib/features/expenses/useExpensesResource.js +68 -0
- package/lib/features/expenses/useExpensesResource.js.map +1 -0
- package/lib/features/health/HealthSyncRunner.js +24 -10
- package/lib/features/health/HealthSyncRunner.js.map +1 -1
- package/lib/features/health/buildDays.js +52 -5
- package/lib/features/health/buildDays.js.map +1 -1
- package/lib/features/health/fitnessClient.js +30 -3
- package/lib/features/health/fitnessClient.js.map +1 -1
- package/lib/features/health/healthConnectMapping.js +65 -2
- package/lib/features/health/healthConnectMapping.js.map +1 -1
- package/lib/features/health/healthConnectReader.js +23 -5
- package/lib/features/health/healthConnectReader.js.map +1 -1
- package/lib/features/health/healthConnectWriter.js +49 -0
- package/lib/features/health/healthConnectWriter.js.map +1 -0
- package/lib/features/health/healthkitMapping.js +58 -2
- package/lib/features/health/healthkitMapping.js.map +1 -1
- package/lib/features/health/healthkitReader.js +29 -7
- package/lib/features/health/healthkitReader.js.map +1 -1
- package/lib/features/health/healthkitWriter.js +55 -0
- package/lib/features/health/healthkitWriter.js.map +1 -0
- package/lib/features/health/model.js +8 -1
- package/lib/features/health/model.js.map +1 -1
- package/lib/features/health/ownSource.js +6 -0
- package/lib/features/health/ownSource.js.map +1 -0
- package/lib/features/health/reader.js +21 -0
- package/lib/features/health/reader.js.map +1 -1
- package/lib/features/health/types.js +15 -3
- package/lib/features/health/types.js.map +1 -1
- package/lib/features/health/writeMapping.js +218 -0
- package/lib/features/health/writeMapping.js.map +1 -0
- package/lib/features/links/ChatLinkOpenerProvider.js +56 -0
- package/lib/features/links/ChatLinkOpenerProvider.js.map +1 -0
- package/lib/features/links/chatLinkOpener.js +8 -0
- package/lib/features/links/chatLinkOpener.js.map +1 -0
- package/lib/features/links/openInApp.js +25 -0
- package/lib/features/links/openInApp.js.map +1 -0
- package/lib/features/messaging/ChatComponents.js +25 -6
- package/lib/features/messaging/ChatComponents.js.map +1 -1
- package/lib/features/messaging/LinkPreviewCard.js +103 -0
- package/lib/features/messaging/LinkPreviewCard.js.map +1 -0
- package/lib/features/messaging/NativeChatExperience.js +20 -7
- package/lib/features/messaging/NativeChatExperience.js.map +1 -1
- package/lib/features/messaging/ThreadScreen.js +4 -2
- package/lib/features/messaging/ThreadScreen.js.map +1 -1
- package/lib/features/messaging/chatLinks.js +64 -0
- package/lib/features/messaging/chatLinks.js.map +1 -0
- package/lib/features/messaging/linkPreview.js +64 -0
- package/lib/features/messaging/linkPreview.js.map +1 -0
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/routes.json +54 -0
- package/lib/screens/Account/index.js +39 -14
- package/lib/screens/Account/index.js.map +1 -1
- package/lib/screens/Chat/index.js +4 -3
- package/lib/screens/Chat/index.js.map +1 -1
- package/lib/screens/Devices/index.js +1055 -0
- package/lib/screens/Devices/index.js.map +1 -0
- package/lib/screens/ExpensesNative/index.js +98 -0
- package/lib/screens/ExpensesNative/index.js.map +1 -0
- package/lib/screens/ExpensesNative/useExpensesHostChat.js +63 -0
- package/lib/screens/ExpensesNative/useExpensesHostChat.js.map +1 -0
- package/lib/screens/Health/index.js +40 -7
- package/lib/screens/Health/index.js.map +1 -1
- package/lib/screens/WebBuilder/index.js +20 -0
- package/lib/screens/WebBuilder/index.js.map +1 -1
- package/lib/utils/hasNativeModule.js +9 -0
- package/lib/utils/hasNativeModule.js.map +1 -0
- package/package.json +5 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"expensesPrompts.js","sources":["../../../src/features/expenses/expensesPrompts.ts"],"sourcesContent":["/** The Expenses agent pane's starters: plain questions a person would ask about what is on screen. */\nimport type { AgentChatSuggestion } from '../agent-chat/types';\nimport type { ExpensesView } from './expensesContext';\n\nexport function expensesAgentSuggestions(view: ExpensesView, claimMerchant: string | null): AgentChatSuggestion[] {\n if (claimMerchant) {\n return [\n {\n id: 'policy',\n label: 'Is this within policy?',\n prompt: `Is the ${claimMerchant} expense within our policy? Check its category and receipt rules.`,\n },\n {\n id: 'category',\n label: 'Pick the right category',\n prompt: `Which category should the ${claimMerchant} expense be filed under?`,\n },\n {\n id: 'describe',\n label: 'Write a description',\n prompt: `Write a short, clear description for the ${claimMerchant} expense and save it.`,\n },\n ];\n }\n switch (view) {\n case 'insights':\n return [\n {\n id: 'month',\n label: 'Summarise this month',\n prompt: 'Summarise my spend this month and flag anything unusual.',\n },\n {\n id: 'compare',\n label: 'Compare with last month',\n prompt: 'How does this month compare with last month, by category?',\n },\n { id: 'save', label: 'Where can we save?', prompt: 'Where could we cut spend next month?' },\n ];\n case 'budgets':\n return [\n {\n id: 'at-risk',\n label: 'Which budgets are at risk?',\n prompt: 'Which budgets are close to or over their limit?',\n },\n {\n id: 'suggest',\n label: 'Suggest budgets',\n prompt: 'Suggest monthly budgets by category based on what we have spent so far, then set them up.',\n },\n ];\n case 'recurring':\n return [\n {\n id: 'due',\n label: \"What's due this week?\",\n prompt: 'Which recurring payments are due this week, and how much in total?',\n },\n {\n id: 'find',\n label: 'Find subscriptions',\n prompt: 'Look through my expenses for repeat charges that are not set up as recurring payments yet.',\n },\n ];\n case 'accounts':\n return [\n {\n id: 'by-account',\n label: 'Spend by account',\n prompt: 'How much has been spent on each account this month?',\n },\n {\n id: 'balances',\n label: 'Card balances',\n prompt: 'What are my card balances, and how close is each to its limit?',\n },\n ];\n default:\n return [\n {\n id: 'summary',\n label: 'Summarise my spend',\n prompt: 'Summarise my spend this month and flag anything unusual.',\n },\n {\n id: 'approvals',\n label: 'What needs approval?',\n prompt: 'Which expenses are waiting for approval, and what is the total?',\n },\n {\n id: 'receipts',\n label: 'Missing receipts',\n prompt: 'Which expenses still need a receipt?',\n },\n {\n id: 'file',\n label: 'File an expense',\n prompt: 'Help me file an expense. Ask me for the merchant, amount and date.',\n },\n ];\n }\n}\n"],"names":[],"mappings":"AAGgB,SAAA,wBAAA,CAAyB,MAAoB,aAAqD,EAAA;AAChH,EAAA,IAAI,aAAe,EAAA;AACjB,IAAA,OAAO,CAAC;AAAA,MACN,EAAI,EAAA,QAAA;AAAA,MACJ,KAAO,EAAA,wBAAA;AAAA,MACP,MAAA,EAAQ,UAAU,aAAa,CAAA,iEAAA;AAAA,KAC9B,EAAA;AAAA,MACD,EAAI,EAAA,UAAA;AAAA,MACJ,K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ACP,EAAA;AAAA,QACD,EAAI,EAAA,UAAA;AAAA,QACJ,KAAO,EAAA,eAAA;AAAA,QACP,MAAQ,EAAA;AAAA,OACT,CAAA;AAAA,IACH;AACE,MAAA,OAAO,CAAC;AAAA,QACN,EAAI,EAAA,SAAA;AAAA,QACJ,KAAO,EAAA,oBAAA;AAAA,QACP,MAAQ,EAAA;AAAA,OACP,EAAA;AAAA,QACD,EAAI,EAAA,WAAA;AAAA,QACJ,KAAO,EAAA,sBAAA;AAAA,QACP,MAAQ,EAAA;AAAA,OACP,EAAA;AAAA,QACD,EAAI,EAAA,UAAA;AAAA,QACJ,KAAO,EAAA,kBAAA;AAAA,QACP,MAAQ,EAAA;AAAA,OACP,EAAA;AAAA,QACD,EAAI,EAAA,MAAA;AAAA,QACJ,KAAO,EAAA,iBAAA;AAAA,QACP,MAAQ,EAAA;AAAA,OACT,CAAA;AAAA;AAEP"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
function expensesTheme(isDark) {
|
|
2
|
+
if (isDark) {
|
|
3
|
+
return {
|
|
4
|
+
isDark: true,
|
|
5
|
+
screen: "#0b0f17",
|
|
6
|
+
card: "#141a24",
|
|
7
|
+
chip: "#1e2633",
|
|
8
|
+
border: "rgba(148,163,184,0.16)",
|
|
9
|
+
ink: "#e8edf5",
|
|
10
|
+
muted: "#9aa5b8",
|
|
11
|
+
faint: "#687489",
|
|
12
|
+
accent: "#5b9cf6",
|
|
13
|
+
accentInk: "#ffffff",
|
|
14
|
+
accentSoft: "rgba(91,156,246,0.16)",
|
|
15
|
+
track: "rgba(91,156,246,0.22)",
|
|
16
|
+
good: "#4ade80",
|
|
17
|
+
goodSoft: "rgba(74,222,128,0.14)",
|
|
18
|
+
warn: "#fab219",
|
|
19
|
+
warnInk: "#fcd34d",
|
|
20
|
+
warnSoft: "rgba(250,178,25,0.14)",
|
|
21
|
+
crit: "#f87171",
|
|
22
|
+
critSoft: "rgba(248,113,113,0.14)",
|
|
23
|
+
progress: "#a78bfa",
|
|
24
|
+
progressSoft: "rgba(167,139,250,0.16)",
|
|
25
|
+
backdrop: "rgba(0,0,0,0.6)",
|
|
26
|
+
toast: "#e8edf5",
|
|
27
|
+
toastInk: "#0b0f17"
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
isDark: false,
|
|
32
|
+
screen: "#f6f7f9",
|
|
33
|
+
card: "#ffffff",
|
|
34
|
+
chip: "#eef1f5",
|
|
35
|
+
border: "#e4e7ec",
|
|
36
|
+
ink: "#0f172a",
|
|
37
|
+
muted: "#5b6474",
|
|
38
|
+
faint: "#8e98a9",
|
|
39
|
+
accent: "#1a73e8",
|
|
40
|
+
accentInk: "#ffffff",
|
|
41
|
+
accentSoft: "#e8f0fe",
|
|
42
|
+
track: "#d2e3fc",
|
|
43
|
+
good: "#0f7a3a",
|
|
44
|
+
goodSoft: "#e6f4ea",
|
|
45
|
+
warn: "#fab219",
|
|
46
|
+
warnInk: "#92400e",
|
|
47
|
+
warnSoft: "#fef3c7",
|
|
48
|
+
crit: "#d03b3b",
|
|
49
|
+
critSoft: "#fdecec",
|
|
50
|
+
progress: "#6d28d9",
|
|
51
|
+
progressSoft: "#efe9fd",
|
|
52
|
+
backdrop: "rgba(15,23,42,0.42)",
|
|
53
|
+
toast: "#0f172a",
|
|
54
|
+
toastInk: "#ffffff"
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function toneColors(theme, tone) {
|
|
58
|
+
switch (tone) {
|
|
59
|
+
case "info":
|
|
60
|
+
return {
|
|
61
|
+
ink: theme.accent,
|
|
62
|
+
fill: theme.accentSoft
|
|
63
|
+
};
|
|
64
|
+
case "progress":
|
|
65
|
+
return {
|
|
66
|
+
ink: theme.progress,
|
|
67
|
+
fill: theme.progressSoft
|
|
68
|
+
};
|
|
69
|
+
case "good":
|
|
70
|
+
return {
|
|
71
|
+
ink: theme.good,
|
|
72
|
+
fill: theme.goodSoft
|
|
73
|
+
};
|
|
74
|
+
case "warn":
|
|
75
|
+
return {
|
|
76
|
+
ink: theme.warnInk,
|
|
77
|
+
fill: theme.warnSoft
|
|
78
|
+
};
|
|
79
|
+
case "crit":
|
|
80
|
+
return {
|
|
81
|
+
ink: theme.crit,
|
|
82
|
+
fill: theme.critSoft
|
|
83
|
+
};
|
|
84
|
+
default:
|
|
85
|
+
return {
|
|
86
|
+
ink: theme.muted,
|
|
87
|
+
fill: theme.chip
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function severityColors(theme, severity) {
|
|
92
|
+
if (severity === "over") return {
|
|
93
|
+
fill: theme.crit,
|
|
94
|
+
ink: theme.crit
|
|
95
|
+
};
|
|
96
|
+
if (severity === "warn") return {
|
|
97
|
+
fill: theme.warn,
|
|
98
|
+
ink: theme.warnInk
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
fill: theme.accent,
|
|
102
|
+
ink: theme.muted
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const TABULAR = {
|
|
106
|
+
fontVariant: ["tabular-nums"]
|
|
107
|
+
};export{TABULAR,expensesTheme,severityColors,toneColors};//# sourceMappingURL=expensesTheme.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"expensesTheme.js","sources":["../../../src/features/expenses/expensesTheme.ts"],"sourcesContent":["/**\n * Expenses visual tokens. Light mode is the web Expenses surface's palette\n * (tailwind `accent` #1a73e8 on the `plane` #f8f9fb, `good` / `warn` / `crit`\n * status inks), so the phone and the web read as one product. Dark mode keeps\n * the same roles on a night ledger. Amounts use tabular figures throughout so\n * a column of them lines up.\n */\nimport type { TextStyle } from 'react-native';\nimport type { Severity, Tone } from './expensesFormat';\n\nexport type ExpensesTheme = {\n isDark: boolean;\n screen: string;\n /** Raised cards, sheets, the tab bar. */\n card: string;\n /** Inputs, chips, pressed rows, skeleton blocks. */\n chip: string;\n border: string;\n ink: string;\n muted: string;\n faint: string;\n accent: string;\n accentInk: string;\n accentSoft: string;\n /** Meter track: a lighter step of the accent ramp that still reads on a card. */\n track: string;\n good: string;\n goodSoft: string;\n warn: string;\n /** Amber that reads as text (the fill colour is too light for words). */\n warnInk: string;\n warnSoft: string;\n crit: string;\n critSoft: string;\n progress: string;\n progressSoft: string;\n backdrop: string;\n toast: string;\n toastInk: string;\n};\n\nexport function expensesTheme(isDark: boolean): ExpensesTheme {\n if (isDark) {\n return {\n isDark: true,\n screen: '#0b0f17',\n card: '#141a24',\n chip: '#1e2633',\n border: 'rgba(148,163,184,0.16)',\n ink: '#e8edf5',\n muted: '#9aa5b8',\n faint: '#687489',\n accent: '#5b9cf6',\n accentInk: '#ffffff',\n accentSoft: 'rgba(91,156,246,0.16)',\n track: 'rgba(91,156,246,0.22)',\n good: '#4ade80',\n goodSoft: 'rgba(74,222,128,0.14)',\n warn: '#fab219',\n warnInk: '#fcd34d',\n warnSoft: 'rgba(250,178,25,0.14)',\n crit: '#f87171',\n critSoft: 'rgba(248,113,113,0.14)',\n progress: '#a78bfa',\n progressSoft: 'rgba(167,139,250,0.16)',\n backdrop: 'rgba(0,0,0,0.6)',\n toast: '#e8edf5',\n toastInk: '#0b0f17',\n };\n }\n return {\n isDark: false,\n screen: '#f6f7f9',\n card: '#ffffff',\n chip: '#eef1f5',\n border: '#e4e7ec',\n ink: '#0f172a',\n muted: '#5b6474',\n faint: '#8e98a9',\n accent: '#1a73e8',\n accentInk: '#ffffff',\n accentSoft: '#e8f0fe',\n track: '#d2e3fc',\n good: '#0f7a3a',\n goodSoft: '#e6f4ea',\n warn: '#fab219',\n warnInk: '#92400e',\n warnSoft: '#fef3c7',\n crit: '#d03b3b',\n critSoft: '#fdecec',\n progress: '#6d28d9',\n progressSoft: '#efe9fd',\n backdrop: 'rgba(15,23,42,0.42)',\n toast: '#0f172a',\n toastInk: '#ffffff',\n };\n}\n\n/** Ink and fill for a status chip. */\nexport function toneColors(theme: ExpensesTheme, tone: Tone): { ink: string; fill: string } {\n switch (tone) {\n case 'info':\n return { ink: theme.accent, fill: theme.accentSoft };\n case 'progress':\n return { ink: theme.progress, fill: theme.progressSoft };\n case 'good':\n return { ink: theme.good, fill: theme.goodSoft };\n case 'warn':\n return { ink: theme.warnInk, fill: theme.warnSoft };\n case 'crit':\n return { ink: theme.crit, fill: theme.critSoft };\n default:\n return { ink: theme.muted, fill: theme.chip };\n }\n}\n\n/** Meter fill, and the ink for the words beside it. */\nexport function severityColors(theme: ExpensesTheme, severity: Severity): { fill: string; ink: string } {\n if (severity === 'over') return { fill: theme.crit, ink: theme.crit };\n if (severity === 'warn') return { fill: theme.warn, ink: theme.warnInk };\n return { fill: theme.accent, ink: theme.muted };\n}\n\n/** Figures that line up in a column. */\nexport const TABULAR: TextStyle = { fontVariant: ['tabular-nums'] };\n"],"names":[],"mappings":"AAuCO,SAAS,cAAc,MAAgC,EAAA;AAC5D,EAAA,IAAI,MAAQ,EAAA;AACV,IAAO,OAAA;AAAA,MACL,MAAQ,EAAA,IAAA;AAAA,MACR,MAAQ,EAAA,SAAA;AAAA,MACR,IAAM,EAAA,SAAA;AAAA,MACN,IAAM,EAAA,SAAA;AAAA,MACN,MAAQ,EAAA,wBAAA;AAAA,MACR,GAAK,EAAA,SAAA;AAAA,MACL,KAAO,EAAA,SAAA;AAAA,MACP,KAAO,EAAA,SAAA;AAAA,MACP,MAAQ,EAAA,SAAA;AAAA,MACR,SAAW,EAAA,SAAA;AAAA,MACX,UAAY,EAAA,uBAAA;AAAA,MACZ,KAAO,EAAA,uBAAA;AAAA,MACP,IAAM,EAAA,SAAA;AAAA,MACN,QAAU,EAAA,uBAAA;AAAA,MACV,IAAM,EAAA,SAAA;AAAA,MACN,OAAS,EAAA,SAAA;AAAA,MACT,QAAU,EAAA,uBAAA;AAAA,MACV,IAAM,EAAA,SAAA;AAAA,MACN,QAAU,EAAA,wBAAA;AAAA,MACV,QAAU,EAAA,SAAA;AAAA,MACV,YAAc,EAAA,wBAAA;AAAA,MACd,QAAU,EAAA,iBAAA;AAAA,MACV,KAAO,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AA;AAAA,QACL,KAAK,KAAM,CAAA,OAAA;AAAA,QACX,MAAM,KAAM,CAAA;AAAA,OACd;AAAA,IACF,KAAK,MAAA;AACH,MAAO,OAAA;AAAA,QACL,KAAK,KAAM,CAAA,IAAA;AAAA,QACX,MAAM,KAAM,CAAA;AAAA,OACd;AAAA,IACF;AACE,MAAO,OAAA;AAAA,QACL,KAAK,KAAM,CAAA,KAAA;AAAA,QACX,MAAM,KAAM,CAAA;AAAA,OACd;AAAA;AAEN;AAGgB,SAAA,cAAA,CAAe,OAAsB,QAGnD,EAAA;AACA,EAAI,IAAA,QAAA,KAAa,QAAe,OAAA;AAAA,IAC9B,MAAM,KAAM,CAAA,IAAA;AAAA,IACZ,KAAK,KAAM,CAAA;AAAA,GACb;AACA,EAAI,IAAA,QAAA,KAAa,QAAe,OAAA;AAAA,IAC9B,MAAM,KAAM,CAAA,IAAA;AAAA,IACZ,KAAK,KAAM,CAAA;AAAA,GACb;AACA,EAAO,OAAA;AAAA,IACL,MAAM,KAAM,CAAA,MAAA;AAAA,IACZ,KAAK,KAAM,CAAA;AAAA,GACb;AACF;AAGO,MAAM,OAAqB,GAAA;AAAA,EAChC,WAAA,EAAa,CAAC,cAAc;AAC9B"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
let experience = null;
|
|
2
|
+
let experiencePreload = null;
|
|
3
|
+
function registerNativeExpensesExperience(component) {
|
|
4
|
+
experience = component;
|
|
5
|
+
}
|
|
6
|
+
function getNativeExpensesExperience() {
|
|
7
|
+
return experience;
|
|
8
|
+
}
|
|
9
|
+
function registerExpensesExperiencePreload(fn) {
|
|
10
|
+
experiencePreload = fn;
|
|
11
|
+
}
|
|
12
|
+
function preloadNativeExpensesExperience() {
|
|
13
|
+
var _a;
|
|
14
|
+
return (_a = experiencePreload == null ? void 0 : experiencePreload()) != null ? _a : Promise.resolve();
|
|
15
|
+
}export{getNativeExpensesExperience,preloadNativeExpensesExperience,registerExpensesExperiencePreload,registerNativeExpensesExperience};//# sourceMappingURL=nativeExpensesRegistry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nativeExpensesRegistry.js","sources":["../../../src/features/expenses/nativeExpensesRegistry.ts"],"sourcesContent":["/**\n * Seam between the app shell and this package for the FEDERATED expenses\n * experience. Same inversion as movies / study / inbox: the loader\n * (`import('expenses_native/Expenses')`) lives in the app so rollup never sees\n * the bare specifier; the ExpensesNative screen reads it back here.\n */\nimport type { ComponentType } from 'react';\nimport type { ExpensesExperienceProps } from './ExpensesExperience';\n\nexport type ExpensesExperienceComponent = ComponentType<ExpensesExperienceProps>;\n\nlet experience: ExpensesExperienceComponent | null = null;\nlet experiencePreload: (() => Promise<void>) | null = null;\n\nexport function registerNativeExpensesExperience(component: ExpensesExperienceComponent): void {\n experience = component;\n}\n\nexport function getNativeExpensesExperience(): ExpensesExperienceComponent | null {\n return experience;\n}\n\nexport function registerExpensesExperiencePreload(fn: () => Promise<void>): void {\n experiencePreload = fn;\n}\n\nexport function preloadNativeExpensesExperience(): Promise<void> {\n return experiencePreload?.() ?? Promise.resolve();\n}\n"],"names":[],"mappings":"AASA,IAAI,UAAiD,GAAA,IAAA;AACrD,IAAI,iBAAkD,GAAA,IAAA;AAC/C,SAAS,iCAAiC,SAA8C,EAAA;AAC7F,EAAa,UAAA,GAAA,SAAA;AACf;AACO,SAAS,2BAAkE,GAAA;AAChF,EAAO,OAAA,UAAA;AACT;AACO,SAAS,kCAAkC,EAA+B,EAAA;AAC/E,EAAoB,iBAAA,GAAA,EAAA;AACtB;AACO,SAAS,+BAAiD,GAAA;AApBjE,EAAA,IAAA,EAAA;AAqBE,EAAO,OAAA,CAAA,EAAA,GAAA,iBAAA,IAAA,IAAA,GAAA,MAAA,GAAA,iBAAA,EAAA,KAAA,IAAA,GAAA,EAAA,GAAyB,QAAQ,OAAQ,EAAA;AAClD"}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import {hasNativeModule}from'../../utils/hasNativeModule.js';import {dayOf}from'./expensesFormat.js';var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
|
|
21
|
+
const EXPENSES_CONNECTOR = "yantra-expenses";
|
|
22
|
+
const SCAN_RECEIPT_ACTION = "YANTRA_EXPENSES_SCAN_RECEIPT";
|
|
23
|
+
const UPLOAD_EDGE = 2e3;
|
|
24
|
+
const UPLOAD_QUALITY = 0.82;
|
|
25
|
+
const INLINE_MAX_CHARS = 96e3;
|
|
26
|
+
const INLINE_PASSES = [{
|
|
27
|
+
edge: 1280,
|
|
28
|
+
quality: 0.55
|
|
29
|
+
}, {
|
|
30
|
+
edge: 1024,
|
|
31
|
+
quality: 0.5
|
|
32
|
+
}, {
|
|
33
|
+
edge: 800,
|
|
34
|
+
quality: 0.45
|
|
35
|
+
}, {
|
|
36
|
+
edge: 640,
|
|
37
|
+
quality: 0.4
|
|
38
|
+
}];
|
|
39
|
+
const SCAN_TIMEOUT_MS = 12e4;
|
|
40
|
+
class ReceiptScanError extends Error {
|
|
41
|
+
constructor(kind, message) {
|
|
42
|
+
super(message);
|
|
43
|
+
__publicField(this, "kind");
|
|
44
|
+
this.name = "ReceiptScanError";
|
|
45
|
+
this.kind = kind;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function receiptScanErrorText(err) {
|
|
49
|
+
const kind = err instanceof ReceiptScanError ? err.kind : "failed";
|
|
50
|
+
console.warn("[expenses] receipt scan failed:", err instanceof Error ? err.message.slice(0, 300) : err);
|
|
51
|
+
switch (kind) {
|
|
52
|
+
case "permission":
|
|
53
|
+
return err instanceof Error ? err.message : "Allow access in Settings to scan a receipt.";
|
|
54
|
+
case "unreadable":
|
|
55
|
+
return "Couldn't open that photo. Try another one.";
|
|
56
|
+
case "unavailable":
|
|
57
|
+
return "Receipt scanning isn't available right now. Fill the details in by hand.";
|
|
58
|
+
default:
|
|
59
|
+
return "Couldn't read the receipt. Try a sharper photo, or fill the details in by hand.";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function loadPicker() {
|
|
63
|
+
if (!hasNativeModule("ExponentImagePicker")) return null;
|
|
64
|
+
return require("expo-image-picker");
|
|
65
|
+
}
|
|
66
|
+
function loadManipulator() {
|
|
67
|
+
if (!hasNativeModule("ExpoImageManipulator")) return null;
|
|
68
|
+
try {
|
|
69
|
+
return require("expo-image-manipulator");
|
|
70
|
+
} catch (e) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async function pickReceipt(source, picker = loadPicker()) {
|
|
75
|
+
var _a, _b, _c, _d, _e;
|
|
76
|
+
if (!picker) throw new ReceiptScanError("unavailable", "This app build has no image picker.");
|
|
77
|
+
const permission = source === "camera" ? await picker.requestCameraPermissionsAsync() : await picker.requestMediaLibraryPermissionsAsync();
|
|
78
|
+
if (!permission.granted) {
|
|
79
|
+
throw new ReceiptScanError("permission", source === "camera" ? "Camera access is off for Yantra. Turn it on in Settings to scan a receipt." : "Photo access is off for Yantra. Turn it on in Settings to scan a receipt.");
|
|
80
|
+
}
|
|
81
|
+
const options = __spreadValues({
|
|
82
|
+
mediaTypes: ["images"],
|
|
83
|
+
allowsMultipleSelection: false,
|
|
84
|
+
exif: false,
|
|
85
|
+
base64: false
|
|
86
|
+
}, source === "camera" ? {
|
|
87
|
+
quality: 0.9
|
|
88
|
+
} : {
|
|
89
|
+
preferredAssetRepresentationMode: (_b = (_a = picker.UIImagePickerPreferredAssetRepresentationMode) == null ? void 0 : _a.Current) != null ? _b : "current"
|
|
90
|
+
});
|
|
91
|
+
const result = source === "camera" ? await picker.launchCameraAsync(options) : await picker.launchImageLibraryAsync(options);
|
|
92
|
+
if (result.canceled) return null;
|
|
93
|
+
const asset = (_c = result.assets) == null ? void 0 : _c[0];
|
|
94
|
+
if (!(asset == null ? void 0 : asset.uri)) throw new ReceiptScanError("unreadable", "The picker returned no image.");
|
|
95
|
+
return {
|
|
96
|
+
uri: asset.uri,
|
|
97
|
+
width: (_d = asset.width) != null ? _d : 0,
|
|
98
|
+
height: (_e = asset.height) != null ? _e : 0
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
async function encode(manipulator, picked, edge, quality, base64) {
|
|
102
|
+
var _a, _b, _c;
|
|
103
|
+
const manipulate = manipulator.manipulateAsync;
|
|
104
|
+
if (typeof manipulate !== "function") throw new ReceiptScanError("unreadable", "No image resizer in this build.");
|
|
105
|
+
const longEdge = Math.max(picked.width, picked.height);
|
|
106
|
+
const capped = longEdge > 0 ? Math.min(edge, longEdge) : edge;
|
|
107
|
+
const resize = picked.height > picked.width ? {
|
|
108
|
+
height: capped
|
|
109
|
+
} : {
|
|
110
|
+
width: capped
|
|
111
|
+
};
|
|
112
|
+
const out = await manipulate(picked.uri, [{
|
|
113
|
+
resize
|
|
114
|
+
}], {
|
|
115
|
+
compress: quality,
|
|
116
|
+
format: (_b = (_a = manipulator.SaveFormat) == null ? void 0 : _a.JPEG) != null ? _b : "jpeg",
|
|
117
|
+
base64
|
|
118
|
+
});
|
|
119
|
+
if (!out.uri) throw new ReceiptScanError("unreadable", "The resize returned no image.");
|
|
120
|
+
return {
|
|
121
|
+
uri: out.uri,
|
|
122
|
+
base64: ((_c = out.base64) == null ? void 0 : _c.trim()) || null
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
async function inlineReceiptImage(picked, manipulator = loadManipulator()) {
|
|
126
|
+
if (!manipulator) return null;
|
|
127
|
+
for (const pass of INLINE_PASSES) {
|
|
128
|
+
const out = await encode(manipulator, picked, pass.edge, pass.quality, true);
|
|
129
|
+
if (out.base64 && out.base64.length <= INLINE_MAX_CHARS) return out.base64;
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
function asRecord(value) {
|
|
134
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
135
|
+
}
|
|
136
|
+
function unwrapScanResult(raw) {
|
|
137
|
+
var _a;
|
|
138
|
+
const layers = [];
|
|
139
|
+
let current = asRecord(raw);
|
|
140
|
+
for (let depth = 0; current && depth < 6; depth += 1) {
|
|
141
|
+
layers.push(current);
|
|
142
|
+
if (asRecord(current.draft)) return asRecord(current.draft);
|
|
143
|
+
current = (_a = asRecord(current.data)) != null ? _a : asRecord(current.result);
|
|
144
|
+
}
|
|
145
|
+
const reason = layers.flatMap((layer) => [layer.error, layer.message, layer.stderr]).find((value) => typeof value === "string" && value.trim().length > 0);
|
|
146
|
+
throw new Error(reason != null ? reason : "The receipt scan returned no draft.");
|
|
147
|
+
}
|
|
148
|
+
function str(value) {
|
|
149
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
150
|
+
}
|
|
151
|
+
function num(value) {
|
|
152
|
+
const n = typeof value === "string" ? Number(value.replace(/[^\d.-]/g, "")) : value;
|
|
153
|
+
return typeof n === "number" && Number.isFinite(n) ? Math.round(n * 100) / 100 : null;
|
|
154
|
+
}
|
|
155
|
+
function normalizeReceiptDraft(raw, categories) {
|
|
156
|
+
var _a, _b, _c, _d, _e, _f;
|
|
157
|
+
const amount = num(raw.amount);
|
|
158
|
+
const day = dayOf(str(raw.date));
|
|
159
|
+
const currency = (_b = (_a = str(raw.currency)) == null ? void 0 : _a.toUpperCase()) != null ? _b : null;
|
|
160
|
+
const categoryId = str(raw.categoryId);
|
|
161
|
+
const categoryName = str(raw.categoryName);
|
|
162
|
+
const byId = categoryId ? categories.find((c) => c.id === categoryId) : void 0;
|
|
163
|
+
const byName = !byId && categoryName ? categories.find((c) => c.name.toLowerCase() === categoryName.toLowerCase()) : void 0;
|
|
164
|
+
const confidence = raw.confidence === "high" || raw.confidence === "medium" ? raw.confidence : "low";
|
|
165
|
+
const last4 = (_d = (_c = str(raw.paymentLast4)) == null ? void 0 : _c.replace(/\D/g, "").slice(-4)) != null ? _d : null;
|
|
166
|
+
return {
|
|
167
|
+
merchant: str(raw.merchant),
|
|
168
|
+
date: day && !Number.isNaN(Date.parse(`${day}T00:00:00Z`)) ? day : null,
|
|
169
|
+
amount: amount !== null && amount > 0 ? amount : null,
|
|
170
|
+
currency: currency && /^[A-Z]{3}$/.test(currency) ? currency : null,
|
|
171
|
+
description: str(raw.description),
|
|
172
|
+
categoryId: (_f = (_e = byId != null ? byId : byName) == null ? void 0 : _e.id) != null ? _f : null,
|
|
173
|
+
subtotal: num(raw.subtotal),
|
|
174
|
+
taxAmount: num(raw.taxAmount),
|
|
175
|
+
tipAmount: num(raw.tipAmount),
|
|
176
|
+
paymentLast4: last4 && last4.length === 4 ? last4 : null,
|
|
177
|
+
confidence,
|
|
178
|
+
warnings: Array.isArray(raw.warnings) ? raw.warnings.filter((w) => typeof w === "string" && w.trim().length > 0).slice(0, 4) : []
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
const NEEDS_INLINE = /imageBase64 is required/i;
|
|
182
|
+
const NOT_DEPLOYED = /unknown action|action not found|not found in registry|not installed/i;
|
|
183
|
+
async function scanReceipt(picked, categories, deps, onStage = () => void 0) {
|
|
184
|
+
const manipulator = deps.manipulator === void 0 ? loadManipulator() : deps.manipulator;
|
|
185
|
+
const choices = categories.map((c) => ({
|
|
186
|
+
id: c.id,
|
|
187
|
+
name: c.name
|
|
188
|
+
}));
|
|
189
|
+
const run = async (image) => {
|
|
190
|
+
try {
|
|
191
|
+
return await deps.exec(EXPENSES_CONNECTOR, SCAN_RECEIPT_ACTION, __spreadProps(__spreadValues({}, image), {
|
|
192
|
+
mimeType: "image/jpeg",
|
|
193
|
+
categories: choices
|
|
194
|
+
}), {
|
|
195
|
+
timeoutMs: SCAN_TIMEOUT_MS
|
|
196
|
+
});
|
|
197
|
+
} catch (err) {
|
|
198
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
199
|
+
if (NOT_DEPLOYED.test(message)) throw new ReceiptScanError("unavailable", message);
|
|
200
|
+
throw err;
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
onStage("Preparing the photo\u2026");
|
|
204
|
+
let fullUri = picked.uri;
|
|
205
|
+
if (manipulator) {
|
|
206
|
+
try {
|
|
207
|
+
fullUri = (await encode(manipulator, picked, UPLOAD_EDGE, UPLOAD_QUALITY, false)).uri;
|
|
208
|
+
} catch (e) {
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
let raw;
|
|
212
|
+
try {
|
|
213
|
+
onStage("Uploading the receipt\u2026");
|
|
214
|
+
const imageUrl = await deps.upload(fullUri);
|
|
215
|
+
onStage("Reading the receipt\u2026");
|
|
216
|
+
raw = await run({
|
|
217
|
+
imageUrl
|
|
218
|
+
});
|
|
219
|
+
} catch (err) {
|
|
220
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
221
|
+
if (!NEEDS_INLINE.test(message)) {
|
|
222
|
+
if (err instanceof ReceiptScanError) throw err;
|
|
223
|
+
throw new ReceiptScanError("failed", message);
|
|
224
|
+
}
|
|
225
|
+
const inline = await inlineReceiptImage(picked, manipulator);
|
|
226
|
+
if (!inline) throw new ReceiptScanError("unavailable", "No inline copy of the receipt fits the agent.");
|
|
227
|
+
onStage("Reading the receipt\u2026");
|
|
228
|
+
try {
|
|
229
|
+
raw = await run({
|
|
230
|
+
imageBase64: inline
|
|
231
|
+
});
|
|
232
|
+
} catch (retryErr) {
|
|
233
|
+
if (retryErr instanceof ReceiptScanError) throw retryErr;
|
|
234
|
+
throw new ReceiptScanError("failed", retryErr instanceof Error ? retryErr.message : String(retryErr));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
return normalizeReceiptDraft(unwrapScanResult(raw), categories);
|
|
239
|
+
} catch (err) {
|
|
240
|
+
throw new ReceiptScanError("failed", err instanceof Error ? err.message : String(err));
|
|
241
|
+
}
|
|
242
|
+
}export{EXPENSES_CONNECTOR,INLINE_MAX_CHARS,ReceiptScanError,SCAN_RECEIPT_ACTION,inlineReceiptImage,normalizeReceiptDraft,pickReceipt,receiptScanErrorText,scanReceipt,unwrapScanResult};//# sourceMappingURL=receiptScan.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"receiptScan.js","sources":["../../../src/features/expenses/receiptScan.ts"],"sourcesContent":["/**\n * A photographed receipt in, a claim draft out - through the yantra-expenses\n * connector's YANTRA_EXPENSES_SCAN_RECEIPT on the agent. It FILES NOTHING: the\n * form is filled and the person still presses Save, because a misread total\n * must never become a claim nobody looked at.\n *\n * How the photo reaches the connector:\n * - The agent runs a connector with its params as ONE command-line argument,\n * and Linux refuses an argument over 128 KB. A legible receipt photo is far\n * bigger than that as base64, so the photo is uploaded to the agent's file\n * store first and the connector is handed `imageUrl`.\n * - A connector that predates `imageUrl` answers \"imageBase64 is required\".\n * Then the scan is asked again once with a small inline JPEG that fits the\n * argument (`INLINE_MAX_CHARS`) - less legible, but a draft the person\n * checks beats no draft.\n * The category list goes along, so the connector matches one of THIS\n * workspace's categories and never invents one (and never has to look them up).\n */\nimport type { RemoteConnectorExec } from '../canvas/videoEditor/remoteMediaClient';\nimport { hasNativeModule } from '../../utils/hasNativeModule';\nimport { dayOf } from './expensesFormat';\nimport type { ExpenseCategory, ReceiptDraft } from './types';\n\nexport const EXPENSES_CONNECTOR = 'yantra-expenses';\nexport const SCAN_RECEIPT_ACTION = 'YANTRA_EXPENSES_SCAN_RECEIPT';\n\n/** Long edge of the uploaded copy: past this, receipt text stops getting more legible. */\nconst UPLOAD_EDGE = 2000;\nconst UPLOAD_QUALITY = 0.82;\n/**\n * Ceiling on inline base64, leaving room under the 131,072-byte argument limit\n * for the rest of the params JSON (categories, mime type).\n */\nexport const INLINE_MAX_CHARS = 96_000;\nconst INLINE_PASSES: Array<{ edge: number; quality: number }> = [\n { edge: 1280, quality: 0.55 },\n { edge: 1024, quality: 0.5 },\n { edge: 800, quality: 0.45 },\n { edge: 640, quality: 0.4 },\n];\n/** Claude reads first on the agent and Gemini is the fallback; both well inside this. */\nconst SCAN_TIMEOUT_MS = 120_000;\n\nexport type ReceiptSource = 'camera' | 'library';\n\nexport type ReceiptScanErrorKind = 'permission' | 'unreadable' | 'unavailable' | 'failed';\n\nexport class ReceiptScanError extends Error {\n readonly kind: ReceiptScanErrorKind;\n\n constructor(kind: ReceiptScanErrorKind, message: string) {\n super(message);\n this.name = 'ReceiptScanError';\n this.kind = kind;\n }\n}\n\n/** One sentence for the form. */\nexport function receiptScanErrorText(err: unknown): string {\n const kind = err instanceof ReceiptScanError ? err.kind : 'failed';\n console.warn('[expenses] receipt scan failed:', err instanceof Error ? err.message.slice(0, 300) : err);\n switch (kind) {\n case 'permission':\n return err instanceof Error ? err.message : 'Allow access in Settings to scan a receipt.';\n case 'unreadable':\n return \"Couldn't open that photo. Try another one.\";\n case 'unavailable':\n return \"Receipt scanning isn't available right now. Fill the details in by hand.\";\n default:\n return \"Couldn't read the receipt. Try a sharper photo, or fill the details in by hand.\";\n }\n}\n\nexport interface PickedReceipt {\n uri: string;\n width: number;\n height: number;\n}\n\ntype ImagePicker = typeof import('expo-image-picker');\n\ntype Manipulator = {\n manipulateAsync?: (\n uri: string,\n actions: Array<{ resize: { width?: number; height?: number } }>,\n options: { compress?: number; format?: unknown; base64?: boolean },\n ) => Promise<{ uri?: string; base64?: string | null; width?: number; height?: number }>;\n SaveFormat?: { JPEG?: string };\n};\n\n/** Lazily required: a test or a bundle without the native module must still import this file. */\nfunction loadPicker(): ImagePicker | null {\n if (!hasNativeModule('ExponentImagePicker')) return null;\n // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require\n return require('expo-image-picker') as ImagePicker;\n}\n\n/** Null on a binary built before the resizer became a dependency (see hasNativeModule). */\nfunction loadManipulator(): Manipulator | null {\n if (!hasNativeModule('ExpoImageManipulator')) return null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require, import/no-unresolved\n return require('expo-image-manipulator') as Manipulator;\n } catch {\n return null;\n }\n}\n\n/** The camera or the photo library, one image. Null when the person backs out. */\nexport async function pickReceipt(\n source: ReceiptSource,\n picker: ImagePicker | null = loadPicker(),\n): Promise<PickedReceipt | null> {\n if (!picker) throw new ReceiptScanError('unavailable', 'This app build has no image picker.');\n const permission =\n source === 'camera'\n ? await picker.requestCameraPermissionsAsync()\n : await picker.requestMediaLibraryPermissionsAsync();\n if (!permission.granted) {\n throw new ReceiptScanError(\n 'permission',\n source === 'camera'\n ? 'Camera access is off for Yantra. Turn it on in Settings to scan a receipt.'\n : 'Photo access is off for Yantra. Turn it on in Settings to scan a receipt.',\n );\n }\n const options: import('expo-image-picker').ImagePickerOptions = {\n mediaTypes: ['images'],\n allowsMultipleSelection: false,\n exif: false,\n base64: false,\n // Library picks must not ask for JPEG: an HEIC or iCloud original then fails\n // to load (\"Cannot load representation of type public.jpeg\"). The resize\n // below transcodes to JPEG anyway.\n ...(source === 'camera'\n ? { quality: 0.9 }\n : {\n preferredAssetRepresentationMode:\n picker.UIImagePickerPreferredAssetRepresentationMode?.Current ?? ('current' as never),\n }),\n };\n const result =\n source === 'camera' ? await picker.launchCameraAsync(options) : await picker.launchImageLibraryAsync(options);\n if (result.canceled) return null;\n const asset = result.assets?.[0];\n if (!asset?.uri) throw new ReceiptScanError('unreadable', 'The picker returned no image.');\n return { uri: asset.uri, width: asset.width ?? 0, height: asset.height ?? 0 };\n}\n\n/** A JPEG copy with its long edge at most `edge`; never upscaled. */\nasync function encode(\n manipulator: Manipulator,\n picked: PickedReceipt,\n edge: number,\n quality: number,\n base64: boolean,\n): Promise<{ uri: string; base64: string | null }> {\n const manipulate = manipulator.manipulateAsync;\n if (typeof manipulate !== 'function') throw new ReceiptScanError('unreadable', 'No image resizer in this build.');\n const longEdge = Math.max(picked.width, picked.height);\n const capped = longEdge > 0 ? Math.min(edge, longEdge) : edge;\n const resize = picked.height > picked.width ? { height: capped } : { width: capped };\n const out = await manipulate(picked.uri, [{ resize }], {\n compress: quality,\n format: manipulator.SaveFormat?.JPEG ?? 'jpeg',\n base64,\n });\n if (!out.uri) throw new ReceiptScanError('unreadable', 'The resize returned no image.');\n return { uri: out.uri, base64: out.base64?.trim() || null };\n}\n\n/** The smallest-necessary inline JPEG that fits one command-line argument, or null if none does. */\nexport async function inlineReceiptImage(\n picked: PickedReceipt,\n manipulator: Manipulator | null = loadManipulator(),\n): Promise<string | null> {\n if (!manipulator) return null;\n for (const pass of INLINE_PASSES) {\n // Sequential: each pass only runs because the one before came out too heavy.\n // eslint-disable-next-line no-await-in-loop\n const out = await encode(manipulator, picked, pass.edge, pass.quality, true);\n if (out.base64 && out.base64.length <= INLINE_MAX_CHARS) return out.base64;\n }\n return null;\n}\n\ntype Json = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Json | null {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : null;\n}\n\n/**\n * The connector's `{ draft, filed: false }`, found by shape through the exec\n * result, the ApiResult (`{successful, data}`) and any runtime wrapper. A\n * `success: false` on any layer is the failure, with its one-line reason.\n */\nexport function unwrapScanResult(raw: unknown): Json {\n const layers: Json[] = [];\n let current = asRecord(raw);\n for (let depth = 0; current && depth < 6; depth += 1) {\n layers.push(current);\n if (asRecord(current.draft)) return asRecord(current.draft) as Json;\n current = asRecord(current.data) ?? asRecord(current.result);\n }\n const reason = layers\n .flatMap((layer) => [layer.error, layer.message, layer.stderr])\n .find((value): value is string => typeof value === 'string' && value.trim().length > 0);\n throw new Error(reason ?? 'The receipt scan returned no draft.');\n}\n\nfunction str(value: unknown): string | null {\n return typeof value === 'string' && value.trim() ? value.trim() : null;\n}\n\nfunction num(value: unknown): number | null {\n const n = typeof value === 'string' ? Number(value.replace(/[^\\d.-]/g, '')) : value;\n return typeof n === 'number' && Number.isFinite(n) ? Math.round(n * 100) / 100 : null;\n}\n\n/**\n * The draft with every field checked: a date that is a real calendar day, a\n * positive total, a three-letter currency, a category that is one of the\n * workspace's own. Anything else becomes null, which the form shows as empty.\n */\nexport function normalizeReceiptDraft(\n raw: Json,\n categories: Array<Pick<ExpenseCategory, 'id' | 'name'>>,\n): ReceiptDraft {\n const amount = num(raw.amount);\n const day = dayOf(str(raw.date));\n const currency = str(raw.currency)?.toUpperCase() ?? null;\n const categoryId = str(raw.categoryId);\n const categoryName = str(raw.categoryName);\n const byId = categoryId ? categories.find((c) => c.id === categoryId) : undefined;\n const byName =\n !byId && categoryName ? categories.find((c) => c.name.toLowerCase() === categoryName.toLowerCase()) : undefined;\n const confidence = raw.confidence === 'high' || raw.confidence === 'medium' ? raw.confidence : 'low';\n const last4 = str(raw.paymentLast4)?.replace(/\\D/g, '').slice(-4) ?? null;\n return {\n merchant: str(raw.merchant),\n date: day && !Number.isNaN(Date.parse(`${day}T00:00:00Z`)) ? day : null,\n amount: amount !== null && amount > 0 ? amount : null,\n currency: currency && /^[A-Z]{3}$/.test(currency) ? currency : null,\n description: str(raw.description),\n categoryId: (byId ?? byName)?.id ?? null,\n subtotal: num(raw.subtotal),\n taxAmount: num(raw.taxAmount),\n tipAmount: num(raw.tipAmount),\n paymentLast4: last4 && last4.length === 4 ? last4 : null,\n confidence,\n warnings: Array.isArray(raw.warnings)\n ? raw.warnings.filter((w): w is string => typeof w === 'string' && w.trim().length > 0).slice(0, 4)\n : [],\n };\n}\n\nconst NEEDS_INLINE = /imageBase64 is required/i;\nconst NOT_DEPLOYED = /unknown action|action not found|not found in registry|not installed/i;\n\nexport interface ScanReceiptDeps {\n exec: RemoteConnectorExec;\n /** file:// -> a URL the connector can fetch (the agent's `/v1/files/upload`). */\n upload: (localUri: string) => Promise<string>;\n manipulator?: Manipulator | null;\n}\n\n/**\n * Read a picked receipt. `onStage` reports what is happening, for the form's\n * one-line progress (\"Uploading…\", \"Reading the receipt…\").\n */\nexport async function scanReceipt(\n picked: PickedReceipt,\n categories: Array<Pick<ExpenseCategory, 'id' | 'name'>>,\n deps: ScanReceiptDeps,\n onStage: (stage: string) => void = () => undefined,\n): Promise<ReceiptDraft> {\n const manipulator = deps.manipulator === undefined ? loadManipulator() : deps.manipulator;\n const choices = categories.map((c) => ({ id: c.id, name: c.name }));\n const run = async (image: { imageUrl: string } | { imageBase64: string }) => {\n try {\n return await deps.exec(\n EXPENSES_CONNECTOR,\n SCAN_RECEIPT_ACTION,\n { ...image, mimeType: 'image/jpeg', categories: choices },\n { timeoutMs: SCAN_TIMEOUT_MS },\n );\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (NOT_DEPLOYED.test(message)) throw new ReceiptScanError('unavailable', message);\n throw err;\n }\n };\n\n onStage('Preparing the photo…');\n let fullUri = picked.uri;\n if (manipulator) {\n try {\n fullUri = (await encode(manipulator, picked, UPLOAD_EDGE, UPLOAD_QUALITY, false)).uri;\n } catch {\n // The original still uploads; a resize is an optimisation here.\n }\n }\n\n let raw: Record<string, unknown>;\n try {\n onStage('Uploading the receipt…');\n const imageUrl = await deps.upload(fullUri);\n onStage('Reading the receipt…');\n raw = await run({ imageUrl });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (!NEEDS_INLINE.test(message)) {\n if (err instanceof ReceiptScanError) throw err;\n throw new ReceiptScanError('failed', message);\n }\n // A connector from before `imageUrl`: send a copy small enough to ride inline.\n const inline = await inlineReceiptImage(picked, manipulator);\n // No resizer in this build, or nothing small enough: the photo cannot reach this connector.\n if (!inline) throw new ReceiptScanError('unavailable', 'No inline copy of the receipt fits the agent.');\n onStage('Reading the receipt…');\n try {\n raw = await run({ imageBase64: inline });\n } catch (retryErr) {\n if (retryErr instanceof ReceiptScanError) throw retryErr;\n throw new ReceiptScanError('failed', retryErr instanceof Error ? retryErr.message : String(retryErr));\n }\n }\n try {\n return normalizeReceiptDraft(unwrapScanResult(raw), categories);\n } catch (err) {\n throw new ReceiptScanError('failed', err instanceof Error ? err.message : String(err));\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBO,MAAM,kBAAqB,GAAA;AAC3B,MAAM,mBAAsB,GAAA;AAGnC,MAAM,WAAc,GAAA,GAAA;AACpB,MAAM,cAAiB,GAAA,IAAA;AAKhB,MAAM,gBAAmB,GAAA;AAChC,MAAM,gBAGD,CAAC;AAAA,EACJ,IAAM,EAAA,IAAA;AAAA,EACN,OAAS,EAAA;AACX,CAAG,EAAA;AAAA,EACD,IAAM,EAAA,IAAA;AAAA,EACN,OAAS,EAAA;AACX,CAAG,EAAA;AAAA,EACD,IAAM,EAAA,GAAA;AAAA,EACN,OAAS,EAAA;AACX,CAAG,EAAA;AAAA,EACD,IAAM,EAAA,GAAA;AAAA,EACN,OAAS,EAAA;AACX,CAAC,CAAA;AAED,MAAM,eAAkB,GAAA,IAAA;AAGjB,MAAM,yBAAyB,KAAM,CAAA;AAAA,EAE1C,WAAA,CAAY,MAA4B,OAAiB,EAAA;AACvD,IAAA,KAAA,CAAM,OAAO,CAAA;AAFf,IAAS,aAAA,CAAA,IAAA,EAAA,MAAA,CAAA;AAGP,IAAA,IAAA,CAAK,IAAO,GAAA,kBAAA;AACZ,IAAA,IAAA,CAAK,IAAO,GAAA,IAAA;AAAA;AAEhB;AAGO,SAAS,qBAAqB,GAAsB,EA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GAAA;AAC3C,MAAM,MAAA,IAAI,gBAAiB,CAAA,QAAA,EAAU,OAAO,CAAA;AAAA;AAG9C,IAAA,MAAM,MAAS,GAAA,MAAM,kBAAmB,CAAA,MAAA,EAAQ,WAAW,CAAA;AAE3D,IAAA,IAAI,CAAC,MAAQ,EAAA,MAAM,IAAI,gBAAA,CAAiB,eAAe,+CAA+C,CAAA;AACtG,IAAA,OAAA,CAAQ,2BAAsB,CAAA;AAC9B,IAAI,IAAA;AACF,MAAA,GAAA,GAAM,MAAM,GAAI,CAAA;AAAA,QACd,WAAa,EAAA;AAAA,OACd,CAAA;AAAA,aACM,QAAU,EAAA;AACjB,MAAI,IAAA,QAAA,YAAoB,kBAAwB,MAAA,QAAA;AAChD,MAAM,MAAA,IAAI,iBAAiB,QAAU,EAAA,QAAA,YAAoB,QAAQ,QAAS,CAAA,OAAA,GAAU,MAAO,CAAA,QAAQ,CAAC,CAAA;AAAA;AACtG;AAEF,EAAI,IAAA;AACF,IAAA,OAAO,qBAAsB,CAAA,gBAAA,CAAiB,GAAG,CAAA,EAAG,UAAU,CAAA;AAAA,WACvD,GAAK,EAAA;AACZ,IAAM,MAAA,IAAI,iBAAiB,QAAU,EAAA,GAAA,YAAe,QAAQ,GAAI,CAAA,OAAA,GAAU,MAAO,CAAA,GAAG,CAAC,CAAA;AAAA;AAEzF"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import {useState,useRef,useCallback,useEffect,useMemo}from'react';var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
const CLAIMS_PAGE_SIZE = 50;
|
|
21
|
+
const firstPageCache = /* @__PURE__ */ new Map();
|
|
22
|
+
function sortClaims(claims, sort) {
|
|
23
|
+
const byDate = (a, b) => {
|
|
24
|
+
var _a, _b;
|
|
25
|
+
return a.date === b.date ? ((_a = b.createdAt) != null ? _a : "").localeCompare((_b = a.createdAt) != null ? _b : "") : b.date.localeCompare(a.date);
|
|
26
|
+
};
|
|
27
|
+
const sorted = [...claims];
|
|
28
|
+
switch (sort) {
|
|
29
|
+
case "oldest":
|
|
30
|
+
return sorted.sort((a, b) => -byDate(a, b));
|
|
31
|
+
case "largest":
|
|
32
|
+
return sorted.sort((a, b) => b.amount - a.amount || byDate(a, b));
|
|
33
|
+
case "smallest":
|
|
34
|
+
return sorted.sort((a, b) => a.amount - b.amount || byDate(a, b));
|
|
35
|
+
default:
|
|
36
|
+
return sorted.sort(byDate);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function useClaimsList(client, filter) {
|
|
40
|
+
const filterKey = JSON.stringify(filter);
|
|
41
|
+
const isDefault = filterKey === "{}";
|
|
42
|
+
const cacheKey = client && isDefault ? client.orgName : "";
|
|
43
|
+
const cached = cacheKey ? firstPageCache.get(cacheKey) : void 0;
|
|
44
|
+
const [claims, setClaims] = useState(() => {
|
|
45
|
+
var _a;
|
|
46
|
+
return (_a = cached == null ? void 0 : cached.claims) != null ? _a : [];
|
|
47
|
+
});
|
|
48
|
+
const [totalCount, setTotalCount] = useState(() => {
|
|
49
|
+
var _a;
|
|
50
|
+
return (_a = cached == null ? void 0 : cached.totalCount) != null ? _a : 0;
|
|
51
|
+
});
|
|
52
|
+
const [status, setStatus] = useState(() => cached ? "ready" : "idle");
|
|
53
|
+
const [error, setError] = useState(null);
|
|
54
|
+
const [refreshing, setRefreshing] = useState(false);
|
|
55
|
+
const [loadingMore, setLoadingMore] = useState(false);
|
|
56
|
+
const requestId = useRef(0);
|
|
57
|
+
const loaded = useRef(claims.length > 0 || Boolean(cached));
|
|
58
|
+
const claimsRef = useRef(claims);
|
|
59
|
+
claimsRef.current = claims;
|
|
60
|
+
const filterRef = useRef(filter);
|
|
61
|
+
filterRef.current = filter;
|
|
62
|
+
const fetchFirst = useCallback(async (quiet) => {
|
|
63
|
+
if (!client) return;
|
|
64
|
+
requestId.current += 1;
|
|
65
|
+
const id = requestId.current;
|
|
66
|
+
if (loaded.current) {
|
|
67
|
+
if (!quiet) setRefreshing(true);
|
|
68
|
+
} else {
|
|
69
|
+
setStatus("loading");
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const page = await client.listClaims(__spreadProps(__spreadValues({}, filterRef.current), {
|
|
73
|
+
offset: 0,
|
|
74
|
+
limit: CLAIMS_PAGE_SIZE
|
|
75
|
+
}));
|
|
76
|
+
if (id !== requestId.current) return;
|
|
77
|
+
loaded.current = true;
|
|
78
|
+
setClaims(page.claims);
|
|
79
|
+
setTotalCount(page.totalCount);
|
|
80
|
+
setError(null);
|
|
81
|
+
setStatus("ready");
|
|
82
|
+
if (cacheKey) firstPageCache.set(cacheKey, page);
|
|
83
|
+
} catch (err) {
|
|
84
|
+
if (id !== requestId.current) return;
|
|
85
|
+
setError(err);
|
|
86
|
+
setStatus(loaded.current ? "ready" : "error");
|
|
87
|
+
} finally {
|
|
88
|
+
if (id === requestId.current) setRefreshing(false);
|
|
89
|
+
}
|
|
90
|
+
}, [client, cacheKey]);
|
|
91
|
+
useEffect(() => {
|
|
92
|
+
var _a, _b;
|
|
93
|
+
const known = cacheKey ? firstPageCache.get(cacheKey) : void 0;
|
|
94
|
+
loaded.current = Boolean(known);
|
|
95
|
+
setClaims((_a = known == null ? void 0 : known.claims) != null ? _a : []);
|
|
96
|
+
setTotalCount((_b = known == null ? void 0 : known.totalCount) != null ? _b : 0);
|
|
97
|
+
setStatus(known ? "ready" : "idle");
|
|
98
|
+
setError(null);
|
|
99
|
+
void fetchFirst(true);
|
|
100
|
+
}, [filterKey, cacheKey, fetchFirst]);
|
|
101
|
+
const hasMore = claims.length < totalCount;
|
|
102
|
+
const loadMore = useCallback(async () => {
|
|
103
|
+
if (!client || loadingMore || !hasMore || status !== "ready") return;
|
|
104
|
+
const id = requestId.current;
|
|
105
|
+
setLoadingMore(true);
|
|
106
|
+
try {
|
|
107
|
+
const page = await client.listClaims(__spreadProps(__spreadValues({}, filterRef.current), {
|
|
108
|
+
offset: claimsRef.current.length,
|
|
109
|
+
limit: CLAIMS_PAGE_SIZE
|
|
110
|
+
}));
|
|
111
|
+
if (id !== requestId.current) return;
|
|
112
|
+
setClaims((prev) => {
|
|
113
|
+
const seen = new Set(prev.map((c) => c.id));
|
|
114
|
+
return [...prev, ...page.claims.filter((c) => !seen.has(c.id))];
|
|
115
|
+
});
|
|
116
|
+
setTotalCount(page.totalCount);
|
|
117
|
+
} catch (err) {
|
|
118
|
+
if (id === requestId.current) setError(err);
|
|
119
|
+
} finally {
|
|
120
|
+
setLoadingMore(false);
|
|
121
|
+
}
|
|
122
|
+
}, [client, loadingMore, hasMore, status]);
|
|
123
|
+
const patch = useCallback((change) => {
|
|
124
|
+
const prev = claimsRef.current;
|
|
125
|
+
const present = prev.some((c) => c.id === change.id);
|
|
126
|
+
let next;
|
|
127
|
+
if ("removed" in change) {
|
|
128
|
+
next = prev.filter((c) => c.id !== change.id);
|
|
129
|
+
if (present) setTotalCount((n) => Math.max(0, n - 1));
|
|
130
|
+
} else if (present) {
|
|
131
|
+
next = prev.map((c) => c.id === change.id ? change : c);
|
|
132
|
+
} else {
|
|
133
|
+
next = [change, ...prev];
|
|
134
|
+
setTotalCount((n) => n + 1);
|
|
135
|
+
}
|
|
136
|
+
claimsRef.current = next;
|
|
137
|
+
setClaims(next);
|
|
138
|
+
if (cacheKey) {
|
|
139
|
+
const known = firstPageCache.get(cacheKey);
|
|
140
|
+
if (known) firstPageCache.set(cacheKey, {
|
|
141
|
+
claims: next,
|
|
142
|
+
totalCount: known.totalCount
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
}, [cacheKey]);
|
|
146
|
+
const reload = useCallback((opts) => fetchFirst(Boolean(opts == null ? void 0 : opts.quiet)), [fetchFirst]);
|
|
147
|
+
return useMemo(() => ({
|
|
148
|
+
claims,
|
|
149
|
+
totalCount,
|
|
150
|
+
status,
|
|
151
|
+
error,
|
|
152
|
+
refreshing,
|
|
153
|
+
loadingMore,
|
|
154
|
+
hasMore,
|
|
155
|
+
reload,
|
|
156
|
+
loadMore,
|
|
157
|
+
patch
|
|
158
|
+
}), [claims, totalCount, status, error, refreshing, loadingMore, hasMore, reload, loadMore, patch]);
|
|
159
|
+
}export{CLAIMS_PAGE_SIZE,sortClaims,useClaimsList};//# sourceMappingURL=useClaimsList.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useClaimsList.js","sources":["../../../src/features/expenses/useClaimsList.ts"],"sourcesContent":["/**\n * The claims list: filtered on the server (status, search, category, payment,\n * source, dates), newest first, a page at a time as the person scrolls. The\n * first page of the unfiltered list is kept for the app session so the\n * screen paints at once on reopen; a filter change asks fresh, and an answer\n * for a filter that has since changed is dropped.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ExpensesClient } from './expensesClient';\nimport type { ExpenseClaim, ExpenseClaimFilter } from './types';\n\nexport const CLAIMS_PAGE_SIZE = 50;\n\nexport type ClaimSort = 'newest' | 'oldest' | 'largest' | 'smallest';\n\nexport interface ClaimsList {\n claims: ExpenseClaim[];\n totalCount: number;\n status: 'idle' | 'loading' | 'ready' | 'error';\n error: unknown;\n refreshing: boolean;\n loadingMore: boolean;\n hasMore: boolean;\n reload: (opts?: { quiet?: boolean }) => Promise<void>;\n loadMore: () => Promise<void>;\n /** Replace or drop one claim in place, after an edit made on this screen. */\n patch: (claim: ExpenseClaim | { id: string; removed: true }) => void;\n}\n\nconst firstPageCache = new Map<string, { claims: ExpenseClaim[]; totalCount: number }>();\n\nexport function clearClaimsSessionCache(): void {\n firstPageCache.clear();\n}\n\n/** Server order is by date; the sort here only reorders what has loaded. */\nexport function sortClaims(claims: ExpenseClaim[], sort: ClaimSort): ExpenseClaim[] {\n const byDate = (a: ExpenseClaim, b: ExpenseClaim) =>\n a.date === b.date ? (b.createdAt ?? '').localeCompare(a.createdAt ?? '') : b.date.localeCompare(a.date);\n const sorted = [...claims];\n switch (sort) {\n case 'oldest':\n return sorted.sort((a, b) => -byDate(a, b));\n case 'largest':\n return sorted.sort((a, b) => b.amount - a.amount || byDate(a, b));\n case 'smallest':\n return sorted.sort((a, b) => a.amount - b.amount || byDate(a, b));\n default:\n return sorted.sort(byDate);\n }\n}\n\nexport function useClaimsList(client: ExpensesClient | null, filter: ExpenseClaimFilter): ClaimsList {\n const filterKey = JSON.stringify(filter);\n const isDefault = filterKey === '{}';\n const cacheKey = client && isDefault ? client.orgName : '';\n const cached = cacheKey ? firstPageCache.get(cacheKey) : undefined;\n\n const [claims, setClaims] = useState<ExpenseClaim[]>(() => cached?.claims ?? []);\n const [totalCount, setTotalCount] = useState(() => cached?.totalCount ?? 0);\n const [status, setStatus] = useState<ClaimsList['status']>(() => (cached ? 'ready' : 'idle'));\n const [error, setError] = useState<unknown>(null);\n const [refreshing, setRefreshing] = useState(false);\n const [loadingMore, setLoadingMore] = useState(false);\n const requestId = useRef(0);\n const loaded = useRef(claims.length > 0 || Boolean(cached));\n const claimsRef = useRef(claims);\n claimsRef.current = claims;\n const filterRef = useRef(filter);\n filterRef.current = filter;\n\n const fetchFirst = useCallback(\n async (quiet: boolean) => {\n if (!client) return;\n requestId.current += 1;\n const id = requestId.current;\n if (loaded.current) {\n if (!quiet) setRefreshing(true);\n } else {\n setStatus('loading');\n }\n try {\n const page = await client.listClaims({ ...filterRef.current, offset: 0, limit: CLAIMS_PAGE_SIZE });\n if (id !== requestId.current) return;\n loaded.current = true;\n setClaims(page.claims);\n setTotalCount(page.totalCount);\n setError(null);\n setStatus('ready');\n if (cacheKey) firstPageCache.set(cacheKey, page);\n } catch (err) {\n if (id !== requestId.current) return;\n setError(err);\n setStatus(loaded.current ? 'ready' : 'error');\n } finally {\n if (id === requestId.current) setRefreshing(false);\n }\n },\n [client, cacheKey],\n );\n\n // A new filter starts from what is known for it (the session's first page for\n // the unfiltered list, nothing otherwise) and asks the server.\n useEffect(() => {\n const known = cacheKey ? firstPageCache.get(cacheKey) : undefined;\n loaded.current = Boolean(known);\n setClaims(known?.claims ?? []);\n setTotalCount(known?.totalCount ?? 0);\n setStatus(known ? 'ready' : 'idle');\n setError(null);\n void fetchFirst(true);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [filterKey, cacheKey, fetchFirst]);\n\n const hasMore = claims.length < totalCount;\n\n const loadMore = useCallback(async () => {\n if (!client || loadingMore || !hasMore || status !== 'ready') return;\n const id = requestId.current;\n setLoadingMore(true);\n try {\n const page = await client.listClaims({\n ...filterRef.current,\n offset: claimsRef.current.length,\n limit: CLAIMS_PAGE_SIZE,\n });\n if (id !== requestId.current) return;\n setClaims((prev) => {\n const seen = new Set(prev.map((c) => c.id));\n return [...prev, ...page.claims.filter((c) => !seen.has(c.id))];\n });\n setTotalCount(page.totalCount);\n } catch (err) {\n if (id === requestId.current) setError(err);\n } finally {\n setLoadingMore(false);\n }\n }, [client, loadingMore, hasMore, status]);\n\n const patch = useCallback(\n (change: ExpenseClaim | { id: string; removed: true }) => {\n const prev = claimsRef.current;\n const present = prev.some((c) => c.id === change.id);\n let next: ExpenseClaim[];\n if ('removed' in change) {\n next = prev.filter((c) => c.id !== change.id);\n if (present) setTotalCount((n) => Math.max(0, n - 1));\n } else if (present) {\n next = prev.map((c) => (c.id === change.id ? change : c));\n } else {\n next = [change, ...prev];\n setTotalCount((n) => n + 1);\n }\n claimsRef.current = next;\n setClaims(next);\n if (cacheKey) {\n const known = firstPageCache.get(cacheKey);\n if (known) firstPageCache.set(cacheKey, { claims: next, totalCount: known.totalCount });\n }\n },\n [cacheKey],\n );\n\n const reload = useCallback((opts?: { quiet?: boolean }) => fetchFirst(Boolean(opts?.quiet)), [fetchFirst]);\n\n return useMemo(\n () => ({ claims, totalCount, status, error, refreshing, loadingMore, hasMore, reload, loadMore, patch }),\n [claims, totalCount, status, error, refreshing, loadingMore, hasMore, reload, loadMore, patch],\n );\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAUO,MAAM,gBAAmB,GAAA;AAoBhC,MAAM,cAAA,uBAAqB,GAGxB,EAAA;AAMa,SAAA,UAAA,CAAW,QAAwB,IAAiC,EAAA;AAClF,EAAM,MAAA,MAAA,GAAS,CAAC,CAAA,EAAiB,CAAiB,KAAA;AAxCpD,IAAA,IAAA,EAAA,EAAA,EAAA;AAwCuD,IAAA,OAAA,CAAA,CAAE,SAAS,CAAE,CAAA,IAAA,GAAA,CAAA,CAAQ,EAAE,GAAA,CAAA,CAAA,SAAA,KAAF,YAAe,EAAI,EAAA,aAAA,CAAA,CAAc,EAAE,GAAA,CAAA,CAAA,SAAA,KAAF,YAAe,EAAE,CAAA,GAAI,EAAE,IAAK,CAAA,aAAA,CAAc,EAAE,IAAI,CAAA;AAAA,GAAA;AAC3J,EAAM,MAAA,MAAA,GAAS,CAAC,GAAG,MAAM,CAAA;AACzB,EAAA,QAAQ,IAAM;AAAA,IACZ,KAAK,QAAA;AACH,MAAO,OAAA,MAAA,CAAO,KAAK,CAAC,CAAA,EAAG,MAAM,CAAC,MAAA,CAAO,CAAG,EAAA,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