feat/fix: implement chatbot session persistence, resolve auth redirect loops, and polish UI

This commit is contained in:
Atharv1705
2026-08-25 15:30:16 +05:30
parent bf1a019d6c
commit e0f6167d14
69 changed files with 2106 additions and 394 deletions
+5 -4
View File
@@ -2,14 +2,15 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/webp" href="/images/bookkeeppro-logo.webp" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BookKeepPro</title> <meta name="description" content="BookKeepPro — Professional bookkeeping, payroll and tax preparation services for growing businesses across the US and India. 27 years of accounting excellence." />
<title>BookKeepPro — Bookkeeping, Payroll &amp; Tax Services</title>
<link rel="stylesheet" href="/css/base.css"/> <link rel="stylesheet" href="/css/base.css"/>
<link rel="stylesheet" href="/css/components.css"/> <link rel="stylesheet" href="/css/components.css"/>
<link rel="stylesheet" href="/css/animations.css"/>
<link rel="stylesheet" href="/css/chatbot.css"/>
<link rel="stylesheet" href="/css/marketing.css"/> <link rel="stylesheet" href="/css/marketing.css"/>
<link rel="stylesheet" href="/css/chatbot.css" media="print" onload="this.media='all'" />
<link rel="stylesheet" href="/css/animations.css" media="print" onload="this.media='all'" />
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+945
View File
@@ -16,12 +16,14 @@
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.3.2", "@tailwindcss/postcss": "^4.3.2",
"@tailwindcss/vite": "^4.3.3",
"@types/react": "^19.2.17", "@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.3", "@vitejs/plugin-react": "^6.0.3",
"autoprefixer": "^10.5.3", "autoprefixer": "^10.5.3",
"oxlint": "^1.71.0", "oxlint": "^1.71.0",
"postcss": "^8.5.19", "postcss": "^8.5.19",
"sharp": "^0.35.3",
"tailwindcss": "^4.3.2", "tailwindcss": "^4.3.2",
"vite": "^8.1.1" "vite": "^8.1.1"
} }
@@ -73,6 +75,581 @@
"tslib": "^2.4.0" "tslib": "^2.4.0"
} }
}, },
"node_modules/@img/colour": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@img/sharp-darwin-arm64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.3.tgz",
"integrity": "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.3.2"
}
},
"node_modules/@img/sharp-darwin-x64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.3.tgz",
"integrity": "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-x64": "1.3.2"
}
},
"node_modules/@img/sharp-freebsd-wasm32": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.3.tgz",
"integrity": "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==",
"dev": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"freebsd"
],
"dependencies": {
"@img/sharp-wasm32": "0.35.3"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-darwin-arm64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.2.tgz",
"integrity": "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-darwin-x64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.2.tgz",
"integrity": "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==",
"cpu": [
"x64"
],
"dev": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-arm": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.2.tgz",
"integrity": "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==",
"cpu": [
"arm"
],
"dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-arm64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.2.tgz",
"integrity": "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-ppc64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.2.tgz",
"integrity": "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==",
"cpu": [
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-riscv64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.2.tgz",
"integrity": "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==",
"cpu": [
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-s390x": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.2.tgz",
"integrity": "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==",
"cpu": [
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.2.tgz",
"integrity": "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.2.tgz",
"integrity": "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.2.tgz",
"integrity": "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-linux-arm": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.3.tgz",
"integrity": "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==",
"cpu": [
"arm"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm": "1.3.2"
}
},
"node_modules/@img/sharp-linux-arm64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.3.tgz",
"integrity": "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm64": "1.3.2"
}
},
"node_modules/@img/sharp-linux-ppc64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.3.tgz",
"integrity": "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==",
"cpu": [
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-ppc64": "1.3.2"
}
},
"node_modules/@img/sharp-linux-riscv64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.3.tgz",
"integrity": "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==",
"cpu": [
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-riscv64": "1.3.2"
}
},
"node_modules/@img/sharp-linux-s390x": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.3.tgz",
"integrity": "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==",
"cpu": [
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-s390x": "1.3.2"
}
},
"node_modules/@img/sharp-linux-x64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.3.tgz",
"integrity": "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-x64": "1.3.2"
}
},
"node_modules/@img/sharp-linuxmusl-arm64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.3.tgz",
"integrity": "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-arm64": "1.3.2"
}
},
"node_modules/@img/sharp-linuxmusl-x64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.3.tgz",
"integrity": "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-x64": "1.3.2"
}
},
"node_modules/@img/sharp-wasm32": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.3.tgz",
"integrity": "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==",
"dev": true,
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
"dependencies": {
"@emnapi/runtime": "^1.11.1"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-webcontainers-wasm32": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.3.tgz",
"integrity": "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==",
"cpu": [
"wasm32"
],
"dev": true,
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"@img/sharp-wasm32": "0.35.3"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-arm64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.3.tgz",
"integrity": "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-ia32": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.3.tgz",
"integrity": "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==",
"cpu": [
"ia32"
],
"dev": true,
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-x64": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.3.tgz",
"integrity": "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@jridgewell/gen-mapping": { "node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -1064,6 +1641,311 @@
"tailwindcss": "4.3.2" "tailwindcss": "4.3.2"
} }
}, },
"node_modules/@tailwindcss/vite": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/vite/-/vite-4.3.3.tgz",
"integrity": "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@tailwindcss/node": "4.3.3",
"@tailwindcss/oxide": "4.3.3",
"tailwindcss": "4.3.3"
},
"peerDependencies": {
"vite": "^5.2.0 || ^6 || ^7 || ^8"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/node": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz",
"integrity": "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/remapping": "^2.3.5",
"enhanced-resolve": "^5.24.1",
"jiti": "^2.7.0",
"lightningcss": "1.32.0",
"magic-string": "^0.30.21",
"source-map-js": "^1.2.1",
"tailwindcss": "4.3.3"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.3.tgz",
"integrity": "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 20"
},
"optionalDependencies": {
"@tailwindcss/oxide-android-arm64": "4.3.3",
"@tailwindcss/oxide-darwin-arm64": "4.3.3",
"@tailwindcss/oxide-darwin-x64": "4.3.3",
"@tailwindcss/oxide-freebsd-x64": "4.3.3",
"@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3",
"@tailwindcss/oxide-linux-arm64-gnu": "4.3.3",
"@tailwindcss/oxide-linux-arm64-musl": "4.3.3",
"@tailwindcss/oxide-linux-x64-gnu": "4.3.3",
"@tailwindcss/oxide-linux-x64-musl": "4.3.3",
"@tailwindcss/oxide-wasm32-wasi": "4.3.3",
"@tailwindcss/oxide-win32-arm64-msvc": "4.3.3",
"@tailwindcss/oxide-win32-x64-msvc": "4.3.3"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-android-arm64": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.3.tgz",
"integrity": "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-darwin-arm64": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.3.tgz",
"integrity": "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-darwin-x64": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.3.tgz",
"integrity": "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-freebsd-x64": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.3.tgz",
"integrity": "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.3.tgz",
"integrity": "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-arm64-gnu": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.3.tgz",
"integrity": "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-arm64-musl": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.3.tgz",
"integrity": "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-x64-gnu": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.3.tgz",
"integrity": "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-linux-x64-musl": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.3.tgz",
"integrity": "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-wasm32-wasi": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.3.tgz",
"integrity": "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==",
"bundleDependencies": [
"@napi-rs/wasm-runtime",
"@emnapi/core",
"@emnapi/runtime",
"@tybys/wasm-util",
"@emnapi/wasi-threads",
"tslib"
],
"cpu": [
"wasm32"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "^1.11.1",
"@emnapi/runtime": "^1.11.1",
"@emnapi/wasi-threads": "^1.2.2",
"@napi-rs/wasm-runtime": "^1.1.4",
"@tybys/wasm-util": "^0.10.2",
"tslib": "^2.8.1"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",
"integrity": "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/@tailwindcss/oxide-win32-x64-msvc": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.3.tgz",
"integrity": "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 20"
}
},
"node_modules/@tailwindcss/vite/node_modules/enhanced-resolve": {
"version": "5.24.5",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz",
"integrity": "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==",
"dev": true,
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.4",
"tapable": "^2.3.3"
},
"engines": {
"node": ">=10.13.0"
}
},
"node_modules/@tailwindcss/vite/node_modules/tailwindcss": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz",
"integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@tybys/wasm-util": { "node_modules/@tybys/wasm-util": {
"version": "0.10.3", "version": "0.10.3",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
@@ -2207,12 +3089,75 @@
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/semver": {
"version": "7.8.5",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/set-cookie-parser": { "node_modules/set-cookie-parser": {
"version": "2.7.2", "version": "2.7.2",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/sharp": {
"version": "0.35.3",
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.3.tgz",
"integrity": "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@img/colour": "^1.1.0",
"detect-libc": "^2.1.2",
"semver": "^7.8.5"
},
"engines": {
"node": ">=20.9.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-darwin-arm64": "0.35.3",
"@img/sharp-darwin-x64": "0.35.3",
"@img/sharp-freebsd-wasm32": "0.35.3",
"@img/sharp-libvips-darwin-arm64": "1.3.2",
"@img/sharp-libvips-darwin-x64": "1.3.2",
"@img/sharp-libvips-linux-arm": "1.3.2",
"@img/sharp-libvips-linux-arm64": "1.3.2",
"@img/sharp-libvips-linux-ppc64": "1.3.2",
"@img/sharp-libvips-linux-riscv64": "1.3.2",
"@img/sharp-libvips-linux-s390x": "1.3.2",
"@img/sharp-libvips-linux-x64": "1.3.2",
"@img/sharp-libvips-linuxmusl-arm64": "1.3.2",
"@img/sharp-libvips-linuxmusl-x64": "1.3.2",
"@img/sharp-linux-arm": "0.35.3",
"@img/sharp-linux-arm64": "0.35.3",
"@img/sharp-linux-ppc64": "0.35.3",
"@img/sharp-linux-riscv64": "0.35.3",
"@img/sharp-linux-s390x": "0.35.3",
"@img/sharp-linux-x64": "0.35.3",
"@img/sharp-linuxmusl-arm64": "0.35.3",
"@img/sharp-linuxmusl-x64": "0.35.3",
"@img/sharp-webcontainers-wasm32": "0.35.3",
"@img/sharp-win32-arm64": "0.35.3",
"@img/sharp-win32-ia32": "0.35.3",
"@img/sharp-win32-x64": "0.35.3"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
}
}
},
"node_modules/source-map-js": { "node_modules/source-map-js": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+2
View File
@@ -18,12 +18,14 @@
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.3.2", "@tailwindcss/postcss": "^4.3.2",
"@tailwindcss/vite": "^4.3.3",
"@types/react": "^19.2.17", "@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.3", "@vitejs/plugin-react": "^6.0.3",
"autoprefixer": "^10.5.3", "autoprefixer": "^10.5.3",
"oxlint": "^1.71.0", "oxlint": "^1.71.0",
"postcss": "^8.5.19", "postcss": "^8.5.19",
"sharp": "^0.35.3",
"tailwindcss": "^4.3.2", "tailwindcss": "^4.3.2",
"vite": "^8.1.1" "vite": "^8.1.1"
} }
-1
View File
@@ -1,6 +1,5 @@
export default { export default {
plugins: { plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {}, autoprefixer: {},
}, },
} }
+4 -31
View File
@@ -1,6 +1,5 @@
@import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,1,0'); @import url('https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,1,0');
@import url('https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,500;0,9..144,600;0,9..144,700;1,9..144,500&family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,400;0,9..144,500;0,9..144,600;0,9..144,700;1,9..144,500&family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap');
@import "tailwindcss";
/* ============================================================ /* ============================================================
base.css — BookKeepPro Design System · "Ledger" base.css — BookKeepPro Design System · "Ledger"
@@ -295,34 +294,8 @@ textarea:focus {
transition: border-color 0.2s ease, box-shadow 0.2s ease; transition: border-color 0.2s ease, box-shadow 0.2s ease;
} }
/* ── Dark Mode Overrides ─────────────────────────────────── */ /* AI Summary — analyzing spinner */
.dark-theme { @keyframes spin {
--bg: #10160F; from { transform: rotate(0deg); }
--card: #1A2119; to { transform: rotate(360deg); }
--navy: #F2EFE4;
--ink: #F2EFE4;
--muted: #A6AC9F;
--border: #2B3529;
--header-bg: #182018;
--footer-bot: #10160F;
--blue-light: rgba(90, 168, 138, 0.16);
--orange-light: rgba(196, 150, 82, 0.16);
--emerald-light:rgba(90, 168, 138, 0.16);
--brass-light: rgba(196, 150, 82, 0.16);
--success-bg: rgba(90, 168, 138, 0.14);
--error-bg: rgba(214, 110, 110, 0.14);
--warn-bg: rgba(196, 150, 82, 0.16);
--shadow-xs: 0 1px 4px rgba(0,0,0,0.35);
--shadow-sm: 0 2px 10px rgba(0,0,0,0.4);
--shadow-md: 0 6px 24px rgba(0,0,0,0.5);
--shadow-lg: 0 16px 48px rgba(0,0,0,0.6);
} }
body.dark-theme {
background-color: var(--bg);
color: var(--ink);
}
.dark-theme .input, .dark-theme .select-input { background: var(--card); color: var(--ink); border-color: var(--border); }
+1 -10
View File
@@ -186,13 +186,4 @@
.chatbot-fab { bottom: 16px; right: 16px; width: 50px; height: 50px; font-size: 22px; } .chatbot-fab { bottom: 16px; right: 16px; width: 50px; height: 50px; font-size: 22px; }
} }
.dark-theme .chatbot-window { background: var(--card); }
.dark-theme .chatbot-messages { background: var(--bg); }
.dark-theme .chat-msg.bot { background: var(--card); border-color: var(--border); color: var(--navy); }
.dark-theme .quick-reply-btn { background: var(--card); border-color: var(--border); color: var(--navy); }
.dark-theme .quick-reply-btn:hover { background: var(--blue-light); border-color: var(--blue); }
.dark-theme .doc-status-card { background: var(--card); border-color: var(--border); }
.dark-theme .doc-status-card .doc-name { color: var(--navy); }
.dark-theme .faq-question { background: var(--card); border-color: var(--border); color: var(--navy); }
.dark-theme .faq-question:hover { background: var(--blue-light); border-color: var(--blue); }
.dark-theme .summary-item { background: var(--card); }
+17 -18
View File
@@ -19,7 +19,7 @@
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 16px;
} }
.app-header .logo { height: 34px; cursor: pointer; transition: opacity var(--transition); } .app-header .logo { height: 34px; width: auto; object-fit: contain; cursor: pointer; transition: opacity var(--transition); }
.app-header .logo:hover { opacity: 0.85; } .app-header .logo:hover { opacity: 0.85; }
.header-actions { display: flex; align-items: center; gap: 10px; } .header-actions { display: flex; align-items: center; gap: 10px; }
@@ -79,13 +79,7 @@
.auth-box .auth-subtitle { color: var(--muted); font-size: 14px; margin-bottom: 32px; } .auth-box .auth-subtitle { color: var(--muted); font-size: 14px; margin-bottom: 32px; }
.auth-links { margin-top: 20px; font-size: 13px; color: var(--muted); text-align: center; line-height: 2; } .auth-links { margin-top: 20px; font-size: 13px; color: var(--muted); text-align: center; line-height: 2; }
body.dark-theme .auth-shell { background: var(--bg); }
body.dark-theme .auth-form-side { background: var(--bg); }
body.dark-theme .auth-box h1 { color: var(--navy); }
body.dark-theme .auth-box .auth-subtitle { color: var(--muted); }
body.dark-theme .auth-box .form-label { color: var(--muted); }
body.dark-theme .auth-box .input { background: var(--card); color: var(--navy); border-color: var(--border); }
body.dark-theme .auth-links a { color: var(--blue); }
@media (max-width: 768px) { @media (max-width: 768px) {
.auth-shell { flex-direction: column; } .auth-shell { flex-direction: column; }
@@ -126,15 +120,26 @@ body.dark-theme .auth-links a { color: var(--blue); }
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
position: relative;
overflow: hidden;
transition: box-shadow var(--transition), transform var(--transition); transition: box-shadow var(--transition), transform var(--transition);
} }
.stat-card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); } .stat-card:hover { box-shadow: var(--shadow-md); transform: translateY(-2px); }
.stat-card .stat-icon { font-size: 22px; margin-bottom: 4px; color: var(--muted); } .stat-card .stat-icon { font-size: 22px; margin-bottom: 4px; color: var(--muted); }
.stat-card .stat-value, .stat-card .stat-val { font-family: var(--font-mono); font-size: 27px; font-weight: 600; color: var(--ink); line-height: 1; font-variant-numeric: tabular-nums; } .stat-card .stat-value, .stat-card .stat-val { font-family: var(--font-mono); font-size: 27px; font-weight: 600; color: var(--ink); line-height: 1; font-variant-numeric: tabular-nums; }
.stat-card .stat-label, .stat-card .stat-title { font-size: 11.5px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; } .stat-card .stat-label, .stat-card .stat-title { font-size: 11.5px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
.stat-card.accent-blue { border-left: 3px solid var(--emerald); }
.stat-card.accent-orange{ border-left: 3px solid var(--brass); } .stat-card::before {
.stat-card.accent-green { border-left: 3px solid var(--success); } content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 4px;
}
.stat-card.accent-blue::before { background: var(--emerald); }
.stat-card.accent-orange::before{ background: var(--brass); }
.stat-card.accent-green::before { background: var(--success); }
/* ── Tab Bar ─────────────────────────────────────────────── */ /* ── Tab Bar ─────────────────────────────────────────────── */
.tab-bar { .tab-bar {
@@ -373,13 +378,7 @@ body.dark-theme .auth-links a { color: var(--blue); }
.btn-upload-pill { background: var(--brass); color: #fff; border: none; border-radius: var(--radius-sm); font-weight: 500; cursor: pointer; padding: 8px 16px; display: inline-flex; align-items: center; gap: 8px; } .btn-upload-pill { background: var(--brass); color: #fff; border: none; border-radius: var(--radius-sm); font-weight: 500; cursor: pointer; padding: 8px 16px; display: inline-flex; align-items: center; gap: 8px; }
.btn-upload-pill:hover { opacity: 0.9; } .btn-upload-pill:hover { opacity: 0.9; }
/* ── Dark theme overrides for the above ─────────────────── */
body.dark-theme .app-header { background: var(--header-bg); border-color: var(--border); }
body.dark-theme .admin-table th { background: var(--card); }
body.dark-theme .chatbot-footer { background: var(--card); border-color: var(--border); }
body.dark-theme .doc-row, body.dark-theme .stat-card, body.dark-theme .user-card { background: var(--card); }
body.dark-theme .search-bar, body.dark-theme .role-select { background: var(--card); color: var(--navy); }
body.dark-theme .search-bar input { color: var(--navy); }
/* ============================================================ /* ============================================================
+9 -28
View File
@@ -33,7 +33,7 @@ body { background: var(--bg); overflow-x: hidden; }
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
} }
#logos { height: clamp(34px, 4.4vw, 44px); object-fit: contain; } #logos { height: clamp(34px, 4.4vw, 44px); width: auto; object-fit: contain; }
.nav-menu { display: flex; gap: 30px; align-items: center; } .nav-menu { display: flex; gap: 30px; align-items: center; }
.nav-menu a { .nav-menu a {
@@ -57,7 +57,7 @@ body { background: var(--bg); overflow-x: hidden; }
.login-btn { .login-btn {
padding: 10px 20px; padding: 10px 20px;
background: var(--brass); background: var(--brass-dark, #8F6528);
color: #fff; color: #fff;
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
border: none; border: none;
@@ -66,7 +66,7 @@ body { background: var(--bg); overflow-x: hidden; }
cursor: pointer; cursor: pointer;
transition: background var(--transition), transform 0.12s ease; transition: background var(--transition), transform 0.12s ease;
} }
.login-btn:hover { background: var(--brass-dark); } .login-btn:hover { background: #7A5520; }
.login-btn:active { transform: translateY(1px) scale(0.96); } .login-btn:active { transform: translateY(1px) scale(0.96); }
.desktop-login { display: inline-block; } .desktop-login { display: inline-block; }
@@ -116,7 +116,7 @@ body { background: var(--bg); overflow-x: hidden; }
color: #fff; color: #fff;
background: background:
linear-gradient(180deg, rgba(15,20,17,0.55) 0%, rgba(15,20,17,0.78) 100%), linear-gradient(180deg, rgba(15,20,17,0.55) 0%, rgba(15,20,17,0.78) 100%),
url("/images/home-background.jpg"); url("/images/home-background.webp");
background-size: cover; background-size: cover;
background-position: center; background-position: center;
overflow: hidden; overflow: hidden;
@@ -299,15 +299,15 @@ body { background: var(--bg); overflow-x: hidden; }
text-align: center; text-align: center;
background: background:
linear-gradient(180deg, rgba(15,20,17,0.5) 0%, rgba(15,20,17,0.8) 100%), linear-gradient(180deg, rgba(15,20,17,0.5) 0%, rgba(15,20,17,0.8) 100%),
var(--hero-img, url("/images/home-background.jpg")); var(--hero-img, url("/images/home-background.webp"));
background-size: cover; background-size: cover;
background-position: center; background-position: center;
} }
.page-hero::before { content: ''; position: absolute; inset: 0; background-image: var(--ruled); opacity: 0.4; } .page-hero::before { content: ''; position: absolute; inset: 0; background-image: var(--ruled); opacity: 0.4; }
.page-hero-inner { position: relative; z-index: 2; } .page-hero-inner { position: relative; z-index: 2; }
.page-hero .eyebrow { color: #E4C98A; justify-content: center; } .page-hero .eyebrow { color: #E4C98A; justify-content: center; }
.page-hero h1, body.dark-theme .page-hero h1 { font-size: clamp(26px, 4.6vw, 44px); font-weight: 500; color: #fff !important; margin-top: 14px; } .page-hero h1 { font-size: clamp(26px, 4.6vw, 44px); font-weight: 500; color: #fff !important; margin-top: 14px; }
.page-hero p, body.dark-theme .page-hero p { color: rgba(255,255,255,0.78) !important; margin-top: 12px; max-width: 520px; margin-left: auto; margin-right: auto; } .page-hero p { color: rgba(255,255,255,0.78) !important; margin-top: 12px; max-width: 520px; margin-left: auto; margin-right: auto; }
/* ================= ABOUT PAGE ================= */ /* ================= ABOUT PAGE ================= */
.about-wrapper { width: min(1200px, 92%); margin: 90px auto; display: flex; flex-direction: column; gap: 46px; } .about-wrapper { width: min(1200px, 92%); margin: 90px auto; display: flex; flex-direction: column; gap: 46px; }
@@ -413,11 +413,11 @@ body { background: var(--bg); overflow-x: hidden; }
flex-wrap: wrap; flex-wrap: wrap;
} }
.footer-left { flex: 1 1 260px; } .footer-left { flex: 1 1 260px; }
.footer-logo, .mkt-footer-logo { width: 190px; opacity: 0.9; margin-bottom: 14px; } .footer-logo, .mkt-footer-logo { width: 190px; height: auto; object-fit: contain; opacity: 0.9; margin-bottom: 14px; }
.footer-left p { color: rgba(255,255,255,0.6); font-size: 14px; max-width: 280px; } .footer-left p { color: rgba(255,255,255,0.6); font-size: 14px; max-width: 280px; }
.footer-links, .mkt-footer-links { display: flex; flex-direction: column; gap: 10px; } .footer-links, .mkt-footer-links { display: flex; flex-direction: column; gap: 10px; }
.footer-links h4, .footer-contact h4, .mkt-footer-links h4 { .footer-links h3, .footer-contact h3, .mkt-footer-links h3 {
color: #E4C98A; margin-bottom: 6px; font-size: 12.5px; color: #E4C98A; margin-bottom: 6px; font-size: 12.5px;
text-transform: uppercase; letter-spacing: 0.1em; font-family: var(--font-mono); font-weight: 600; text-transform: uppercase; letter-spacing: 0.1em; font-family: var(--font-mono); font-weight: 600;
} }
@@ -442,22 +442,3 @@ body { background: var(--bg); overflow-x: hidden; }
.hero-stats { margin-top: 46px; } .hero-stats { margin-top: 46px; }
} }
/* ================= DARK THEME ================= */
body.dark-theme .about-block,
body.dark-theme .service-block,
body.dark-theme .contact-form,
body.dark-theme .service-card { background: var(--card); border-color: var(--border); }
body.dark-theme .hero-stats { background: rgba(26,33,25,0.97); }
body.dark-theme .stat-block { border-color: var(--border); }
body.dark-theme .stat-block .stat-figure, body.dark-theme .stat-block .stat-caption { color: var(--navy); }
body.dark-theme p, body.dark-theme .service-text p, body.dark-theme .list-items li,
body.dark-theme .about-copy p, body.dark-theme .footer-left p { color: var(--muted) !important; }
body.dark-theme .hero p.hero-sub { color: rgba(255,255,255,0.78) !important; }
body.dark-theme h1, body.dark-theme h2, body.dark-theme h3 { color: var(--navy) !important; }
body.dark-theme .contact-form input, body.dark-theme .contact-form textarea {
background: var(--bg); color: var(--navy); border-color: var(--border);
}
body.dark-theme .navbar-solid { background: var(--ink) !important; }
body.dark-theme .footer, body.dark-theme .mkt-footer, body.dark-theme .cta-band {
background: #182018 !important;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

+27
View File
@@ -0,0 +1,27 @@
# BookKeepPro
> Professional bookkeeping, payroll and tax preparation services for growing businesses across the US and India.
## About
BookKeepPro handles the books, the payroll and the filings for growing businesses, so nothing slips between the cracks of a busy quarter. Founded in 1998, we bring 27 years of accounting expertise.
## Pages
- [Home](https://aiindiacpa.duckdns.org/)
- [About Us](https://aiindiacpa.duckdns.org/about-us)
- [Services](https://aiindiacpa.duckdns.org/services)
- [Contact Us](https://aiindiacpa.duckdns.org/contact)
## Services
- **Bookkeeping** — Monthly books, closed clean and on time
- **Payroll** — Payroll runs your team can set a clock by
- **Tax** — Tax planning and prep built around your entity
## Contact
- USA: 2520 Indigo Dr, McKinney, TX 75072
- India: 508 White Square, Hinjewadi Road, Pune 411057
- Email: atharvg.aiindia@gmail.com
- Phone: +91 8275367267
+17
View File
@@ -0,0 +1,17 @@
User-agent: *
Allow: /
Disallow: /api/
Disallow: /dashboard
Disallow: /admin-dashboard
Disallow: /admin-user-detail
Disallow: /upload-personal
Disallow: /upload-business
Disallow: /profile
Disallow: /login
Disallow: /signup
Disallow: /forgot-password
Disallow: /reset-password
Disallow: /verify-email
Disallow: /resend-verification
Sitemap: https://aiindiacpa.duckdns.org/sitemap.xml
+33
View File
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://aiindiacpa.duckdns.org/</loc>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>https://aiindiacpa.duckdns.org/about</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://aiindiacpa.duckdns.org/services</loc>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://aiindiacpa.duckdns.org/contact</loc>
<changefreq>monthly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://aiindiacpa.duckdns.org/login</loc>
<changefreq>yearly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://aiindiacpa.duckdns.org/signup</loc>
<changefreq>yearly</changefreq>
<priority>0.5</priority>
</url>
</urlset>
+33
View File
@@ -0,0 +1,33 @@
// Image optimization script using sharp
// Run: node optimize-images.mjs
import sharp from 'sharp';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const IMG_DIR = path.join(__dirname, '..', 'public', 'images');
const conversions = [
{ src: 'home-background.jpg', out: 'home-background.webp', width: 1400, quality: 80 },
{ src: 'home-about.jpg', out: 'home-about.webp', width: 800, quality: 80 },
{ src: 'services-1.jpg', out: 'services-1.webp', width: 600, quality: 80 },
{ src: 'services-2.jpg', out: 'services-2.webp', width: 600, quality: 80 },
{ src: 'services-3.jpg', out: 'services-3.webp', width: 600, quality: 80 },
];
for (const { src, out, width, quality } of conversions) {
const inPath = path.join(IMG_DIR, src);
const outPath = path.join(IMG_DIR, out);
try {
const info = await sharp(inPath)
.resize({ width, withoutEnlargement: true })
.webp({ quality })
.toFile(outPath);
console.log(`✅ ${src} → ${out} (${(info.size / 1024).toFixed(0)} KB, ${info.width}x${info.height})`);
} catch (err) {
console.error(`❌ ${src}: ${err.message}`);
}
}
console.log('\nDone! You can now delete the original .jpg files if desired.');
-3
View File
@@ -1,6 +1,5 @@
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'; import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext'; import { AuthProvider, useAuth } from './context/AuthContext';
import { ThemeProvider } from './context/ThemeContext';
import { ToastProvider } from './context/ToastContext'; import { ToastProvider } from './context/ToastContext';
// Layouts // Layouts
@@ -133,13 +132,11 @@ function AppRoutes() {
function App() { function App() {
return ( return (
<BrowserRouter> <BrowserRouter>
<ThemeProvider>
<ToastProvider> <ToastProvider>
<AuthProvider> <AuthProvider>
<AppRoutes /> <AppRoutes />
</AuthProvider> </AuthProvider>
</ToastProvider> </ToastProvider>
</ThemeProvider>
</BrowserRouter> </BrowserRouter>
); );
} }
+29 -18
View File
@@ -2,8 +2,7 @@ import { useState, useRef, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
import { useLocation } from 'react-router-dom'; import { useLocation } from 'react-router-dom';
const STORAGE_KEY = 'admin_chat_history'; const STORAGE_KEY = 'admin_chat_session_id';
const MAX_HISTORY = 40; // messages to persist
const FAQ_DATA = { const FAQ_DATA = {
"Document Review": [ "Document Review": [
@@ -43,26 +42,41 @@ export default function AdminChatbot() {
const [pendingBulk, setPendingBulk] = useState(null); // bulk action awaiting confirmation const [pendingBulk, setPendingBulk] = useState(null); // bulk action awaiting confirmation
const chatEndRef = useRef(null); const chatEndRef = useRef(null);
// ── Conversation memory via localStorage ────────────────────────────────── const [messages, setMessages] = useState([]);
const [messages, setMessages] = useState(() => { const [sessionId, setSessionId] = useState(null);
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? JSON.parse(saved) : [];
} catch { return []; }
});
// Persist messages to localStorage whenever they change
useEffect(() => { useEffect(() => {
if (!user) return;
async function loadHistory() {
const savedSession = localStorage.getItem(STORAGE_KEY);
const url = savedSession ? `/api/chatbot/history?session_id=${savedSession}` : '/api/chatbot/history';
try { try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.slice(-MAX_HISTORY))); const res = await authFetch(url);
} catch { /* storage full — ignore */ } if (res.ok) {
}, [messages]); const data = await res.json();
setSessionId(data.session_id);
localStorage.setItem(STORAGE_KEY, data.session_id);
const loaded = data.messages.map(m => ({
type: m.role === 'user' ? 'user' : 'bot',
role: m.role,
text: m.content || '',
...m
})).filter(m => m.role === 'user' || m.role === 'assistant');
setMessages(loaded);
}
} catch (e) {
console.error("Failed to load admin chat history", e);
}
}
loadHistory();
}, [authFetch, user]);
useEffect(() => { setIsOpen(false); }, [location.pathname]); useEffect(() => { setIsOpen(false); }, [location.pathname]);
useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, view]); useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, view]);
const clearHistory = () => { const clearHistory = () => {
setMessages([]); setMessages([]);
setSessionId(null);
localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(STORAGE_KEY);
}; };
@@ -121,11 +135,8 @@ export default function AdminChatbot() {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
stream: false, stream: false,
messages: allMessages.map(m => ({ session_id: sessionId,
role: m.role || (m.type === 'bot' ? 'assistant' : 'user'), message: text,
content: m.text,
reasoning_details: null,
})),
}), }),
}); });
+30 -18
View File
@@ -2,8 +2,7 @@ import { useState, useRef, useEffect, useCallback } from 'react';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
import { useLocation, useNavigate } from 'react-router-dom'; import { useLocation, useNavigate } from 'react-router-dom';
const STORAGE_KEY = 'user_chat_history'; const STORAGE_KEY = 'user_chat_session_id';
const MAX_HISTORY = 30;
const FAQ_DATA = { const FAQ_DATA = {
"Account": [ "Account": [
@@ -48,23 +47,39 @@ export default function Chatbot() {
const [isTyping, setIsTyping] = useState(false); const [isTyping, setIsTyping] = useState(false);
const chatEndRef = useRef(null); const chatEndRef = useRef(null);
// ── Conversation memory via localStorage ────────────────────────────────── const [messages, setMessages] = useState([]);
const [messages, setMessages] = useState(() => { const [sessionId, setSessionId] = useState(null);
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved ? JSON.parse(saved) : [];
} catch { return []; }
});
useEffect(() => { useEffect(() => {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.slice(-MAX_HISTORY))); } if (!user) return;
catch { /* storage full */ } async function loadHistory() {
}, [messages]); const savedSession = localStorage.getItem(STORAGE_KEY);
const url = savedSession ? `/api/chatbot/history?session_id=${savedSession}` : '/api/chatbot/history';
try {
const res = await authFetch(url);
if (res.ok) {
const data = await res.json();
setSessionId(data.session_id);
localStorage.setItem(STORAGE_KEY, data.session_id);
const loaded = data.messages.map(m => ({
type: m.role === 'user' ? 'user' : 'bot',
role: m.role,
text: m.content || '',
...m
})).filter(m => m.role === 'user' || m.role === 'assistant');
setMessages(loaded);
}
} catch (e) {
console.error("Failed to load chat history", e);
}
}
loadHistory();
}, [authFetch, user]);
useEffect(() => { setIsOpen(false); }, [location.pathname]); useEffect(() => { setIsOpen(false); }, [location.pathname]);
useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, view]); useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, view]);
const clearHistory = () => { setMessages([]); localStorage.removeItem(STORAGE_KEY); }; const clearHistory = () => { setMessages([]); setSessionId(null); localStorage.removeItem(STORAGE_KEY); };
// ── Document status quick-check ──────────────────────────────────────────── // ── Document status quick-check ────────────────────────────────────────────
const handleDocStatusCheck = async () => { const handleDocStatusCheck = async () => {
@@ -127,11 +142,8 @@ export default function Chatbot() {
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body: JSON.stringify({
stream: false, stream: false,
messages: allMessages.map(m => ({ session_id: sessionId,
role: m.role || (m.type === 'bot' ? 'assistant' : 'user'), message: text,
content: m.text,
reasoning_details: null,
})),
}), }),
}); });
if (res.ok) { if (res.ok) {
@@ -8,14 +8,18 @@ const CONFIDENCE_STYLES = {
unknown: { icon: '⚪', color: 'var(--muted)', bg: 'var(--paper)' }, unknown: { icon: '⚪', color: 'var(--muted)', bg: 'var(--paper)' },
}; };
export default function ExpandableSummaryBlock({ extractedData }) { export default function ExpandableSummaryBlock({ extractedData, onSave }) {
const [expanded, setExpanded] = useState(false); const [expanded, setExpanded] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [editValue, setEditValue] = useState("");
const [saveError, setSaveError] = useState("");
const [isSaving, setIsSaving] = useState(false);
// Separate _meta from the actual data fields // Separate _meta from the actual data fields
const { _meta, ...dataFields } = extractedData || {}; const { _meta, ...dataFields } = extractedData || {};
const entries = Object.entries(dataFields); const entries = Object.entries(dataFields);
if (entries.length === 0) { if (entries.length === 0 && !isEditing) {
return ( return (
<div style={{ fontSize: '12px', color: 'var(--muted)', fontStyle: 'italic' }}> <div style={{ fontSize: '12px', color: 'var(--muted)', fontStyle: 'italic' }}>
Blank form / No user data found. Blank form / No user data found.
@@ -23,15 +27,117 @@ export default function ExpandableSummaryBlock({ extractedData }) {
); );
} }
const handleEditClick = () => {
setEditValue(JSON.stringify(extractedData || {}, null, 2));
setSaveError("");
setIsEditing(true);
};
const handleCancelEdit = () => {
setIsEditing(false);
setSaveError("");
};
const handleSave = async () => {
setSaveError("");
let parsed = null;
try {
parsed = JSON.parse(editValue);
} catch (err) { console.error(err);
setSaveError("Invalid JSON format");
return;
}
if (onSave) {
setIsSaving(true);
try {
await onSave(parsed);
setIsEditing(false);
} catch (err) { console.error(err);
setSaveError("Failed to save changes");
} finally {
setIsSaving(false);
}
}
};
const handleExport = () => {
// Convert extracted data into a 2-column CSV (Field, Value)
const { _meta, ...dataFields } = extractedData || {};
const escapeCsv = (str) => {
const s = String(str);
if (s.includes(',') || s.includes('"') || s.includes('\n')) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
};
const csvRows = ['Field,Value'];
Object.entries(dataFields).forEach(([key, val]) => {
let valStr = val;
if (Array.isArray(val)) {
valStr = val.join('; ');
} else if (typeof val === 'object' && val !== null) {
valStr = JSON.stringify(val);
}
csvRows.push(`${escapeCsv(key)},${escapeCsv(valStr)}`);
});
const csvContent = csvRows.join('\n');
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `extracted_data.csv`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const showToggle = entries.length > 3; const showToggle = entries.length > 3;
const entriesToShow = expanded ? entries : entries.slice(0, 3); const entriesToShow = expanded ? entries : entries.slice(0, 3);
const confidenceStyle = CONFIDENCE_STYLES[_meta?.tier] || CONFIDENCE_STYLES.unknown; const confidenceStyle = CONFIDENCE_STYLES[_meta?.tier] || CONFIDENCE_STYLES.unknown;
if (isEditing) {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<div style={{ fontSize: '12px', fontWeight: 600, color: 'var(--navy)' }}>Edit Extracted Data (JSON)</div>
<textarea
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
style={{
width: '100%',
height: '200px',
fontFamily: 'var(--font-mono)',
fontSize: '12px',
padding: '10px',
borderRadius: 'var(--radius-sm)',
border: '1px solid var(--border)',
background: '#fff',
resize: 'vertical'
}}
/>
{saveError && <div style={{ fontSize: '12px', color: 'var(--error)' }}>{saveError}</div>}
<div style={{ display: 'flex', gap: '8px' }}>
<button onClick={handleSave} disabled={isSaving} className="btn btn-primary btn-sm" style={{borderRadius: 'var(--radius-sm)'}}>
{isSaving ? "Saving..." : "Save Changes"}
</button>
<button onClick={handleCancelEdit} disabled={isSaving} className="btn btn-secondary btn-sm" style={{borderRadius: 'var(--radius-sm)'}}>
Cancel
</button>
</div>
</div>
);
}
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{/* Confidence tier badge */} {/* Top action bar: Confidence tier + Edit/Export */}
{_meta && ( <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
{_meta ? (
<div <div
title={_meta.description} title={_meta.description}
style={{ style={{
@@ -45,14 +151,23 @@ export default function ExpandableSummaryBlock({ extractedData }) {
background: confidenceStyle.bg, background: confidenceStyle.bg,
padding: '2px 8px', padding: '2px 8px',
borderRadius: 'var(--radius-xs)', borderRadius: 'var(--radius-xs)',
alignSelf: 'flex-start',
cursor: 'help', cursor: 'help',
letterSpacing: '0.3px', letterSpacing: '0.3px',
}} }}
> >
{confidenceStyle.icon} {_meta.label} {confidenceStyle.icon} {_meta.label}
</div> </div>
)} ) : <div />}
<div style={{ display: 'flex', gap: '6px' }}>
<button onClick={handleExport} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: '11px', color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: '4px', padding: '2px' }} title="Export CSV">
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>download</span> Export CSV
</button>
<button onClick={handleEditClick} style={{ border: 'none', background: 'transparent', cursor: 'pointer', fontSize: '11px', color: 'var(--emerald)', display: 'flex', alignItems: 'center', gap: '4px', padding: '2px', fontWeight: 600 }} title="Edit Summary">
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>edit</span> Edit
</button>
</div>
</div>
{/* Field rows */} {/* Field rows */}
{entriesToShow.map(([key, value]) => ( {entriesToShow.map(([key, value]) => (
+3 -3
View File
@@ -5,12 +5,12 @@ export default function Footer() {
<footer className="footer"> <footer className="footer">
<div className="footer-top"> <div className="footer-top">
<div className="footer-left"> <div className="footer-left">
<img src="/images/bookkeeppro-logo.webp" className="footer-logo" alt="BookKeepPro" /> <img src="/images/bookkeeppro-logo.webp" className="footer-logo" alt="BookKeepPro" width="190" height="64" />
<p>Bookkeeping, payroll and tax preparation for growing businesses — kept precise, kept compliant.</p> <p>Bookkeeping, payroll and tax preparation for growing businesses — kept precise, kept compliant.</p>
</div> </div>
<div className="footer-links"> <div className="footer-links">
<h4>Navigate</h4> <h3>Navigate</h3>
<Link to="/">Home</Link> <Link to="/">Home</Link>
<Link to="/about-us">About Us</Link> <Link to="/about-us">About Us</Link>
<Link to="/services">Services</Link> <Link to="/services">Services</Link>
@@ -18,7 +18,7 @@ export default function Footer() {
</div> </div>
<div className="footer-contact"> <div className="footer-contact">
<h4>Reach us</h4> <h3>Reach us</h3>
<p>USA · 2520 Indigo Dr, McKinney, TX 75072</p> <p>USA · 2520 Indigo Dr, McKinney, TX 75072</p>
<p>India · 508 White Square, Hinjewadi Road, Pune 411057</p> <p>India · 508 White Square, Hinjewadi Road, Pune 411057</p>
<p>atharvg.aiindia@gmail.com</p> <p>atharvg.aiindia@gmail.com</p>
+1 -14
View File
@@ -1,17 +1,15 @@
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { useState } from 'react'; import { useState } from 'react';
import { useTheme } from '../context/ThemeContext';
export default function Navbar({ solid = false }) { export default function Navbar({ solid = false }) {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
const { theme, toggleTheme } = useTheme();
return ( return (
<div className={`navbar ${solid ? 'navbar-solid' : ''}`}> <div className={`navbar ${solid ? 'navbar-solid' : ''}`}>
<div className="nav-container"> <div className="nav-container">
<Link to="/"> <Link to="/">
<img id="logos" src="/images/bookkeeppro-logo.webp" alt="BookKeepPro" /> <img id="logos" src="/images/bookkeeppro-logo.webp" alt="BookKeepPro" width="190" height="64" />
</Link> </Link>
<nav id="navMenu" className={`nav-menu ${isOpen ? 'active' : ''}`}> <nav id="navMenu" className={`nav-menu ${isOpen ? 'active' : ''}`}>
@@ -20,17 +18,6 @@ export default function Navbar({ solid = false }) {
<Link to="/services" onClick={() => setIsOpen(false)}>Services</Link> <Link to="/services" onClick={() => setIsOpen(false)}>Services</Link>
<Link to="/contact" onClick={() => setIsOpen(false)}>Contact Us</Link> <Link to="/contact" onClick={() => setIsOpen(false)}>Contact Us</Link>
<button
className="theme-toggle"
onClick={toggleTheme}
style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '8px' }}
aria-label="Toggle Theme"
>
<span className="material-symbols-outlined" style={{ fontSize: '22px' }}>
{theme === 'dark' ? 'light_mode' : 'dark_mode'}
</span>
</button>
<button className="login-btn desktop-login" onClick={() => navigate('/login')}> <button className="login-btn desktop-login" onClick={() => navigate('/login')}>
Sign in Sign in
</button> </button>
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useState, useEffect, useCallback } from 'react'; import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
-33
View File
@@ -1,33 +0,0 @@
import { createContext, useContext, useState, useEffect } from 'react';
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(() => {
return localStorage.getItem('theme') || 'light';
});
useEffect(() => {
if (theme === 'dark') {
document.documentElement.classList.add('dark-theme');
document.body.classList.add('dark-theme');
localStorage.setItem('theme', 'dark');
} else {
document.documentElement.classList.remove('dark-theme');
document.body.classList.remove('dark-theme');
localStorage.setItem('theme', 'light');
}
}, [theme]);
const toggleTheme = () => {
setTheme(prev => prev === 'dark' ? 'light' : 'dark');
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
}
export const useTheme = () => useContext(ThemeContext);
+1
View File
@@ -1,3 +1,4 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useState, useCallback } from 'react'; import { createContext, useContext, useState, useCallback } from 'react';
const ToastContext = createContext(); const ToastContext = createContext();
-16
View File
@@ -50,23 +50,7 @@
--green: #10b981; --green: #10b981;
} }
.dark-theme, body.dark-theme {
--color-brand-ink: #F2EFE4;
--color-brand-ink-soft: #D5D1C3;
--color-brand-paper: #10160F;
--color-brand-card: #1A2119;
--color-brand-muted: #A6AC9F;
--color-brand-border: #2B3529;
--color-brand-emerald-light: rgba(90, 168, 138, 0.16);
--color-brand-brass-light: rgba(196, 150, 82, 0.16);
--color-status-success-bg: rgba(90, 168, 138, 0.14);
--color-status-error-bg: rgba(214, 110, 110, 0.14);
--color-status-warn-bg: rgba(196, 150, 82, 0.16);
}
/* -------------------------------- */ /* -------------------------------- */
/* Global and Base Elements */ /* Global and Base Elements */
+1 -14
View File
@@ -1,30 +1,17 @@
import { Outlet, Link, useNavigate } from 'react-router-dom'; import { Outlet, Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext'; import { useAuth } from '../context/AuthContext';
import { useTheme } from '../context/ThemeContext';
export default function DashboardLayout() { export default function DashboardLayout() {
const { user, logout } = useAuth(); const { user, logout } = useAuth();
const navigate = useNavigate(); const navigate = useNavigate();
const { theme, toggleTheme } = useTheme();
return ( return (
<div className="app-body"> <div className="app-body">
<header className="app-header"> <header className="app-header">
<Link to={(user?.role === 'admin' || user?.role === 'super_admin') ? '/admin-dashboard' : '/dashboard'}> <Link to={(user?.role === 'admin' || user?.role === 'super_admin') ? '/admin-dashboard' : '/dashboard'}>
<img className="logo" src="/images/bookkeeppro-logo.webp" alt="BookKeepPro" /> <img className="logo" src="/images/bookkeeppro-logo.webp" alt="BookKeepPro" width="190" height="64" />
</Link> </Link>
<div className="header-actions"> <div className="header-actions">
<button
className="theme-toggle"
onClick={toggleTheme}
style={{background:'none', border:'none', color:'inherit', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', padding:'8px'}}
aria-label="Toggle Theme"
>
<span className="material-symbols-outlined theme-toggle-icon" style={{fontSize: '24px'}}>
{theme === 'dark' ? 'light_mode' : 'dark_mode'}
</span>
</button>
<button className="btn btn-secondary btn-sm" onClick={() => navigate('/profile')}> <button className="btn btn-secondary btn-sm" onClick={() => navigate('/profile')}>
My Profile My Profile
</button> </button>
+2
View File
@@ -6,7 +6,9 @@ export default function MarketingLayout() {
return ( return (
<> <>
<Navbar /> <Navbar />
<main>
<Outlet /> <Outlet />
</main>
<Footer /> <Footer />
</> </>
); );
+1 -1
View File
@@ -50,7 +50,7 @@ export default function AboutUs() {
operations support. operations support.
</p> </p>
</div> </div>
<img className="about-img" src="/images/young-business-people-using-computer-in-office.jpg" alt="About BookKeepPro" /> <img className="about-img" src="/images/young-business-people-using-computer-in-office.webp" alt="About BookKeepPro" width="800" height="533" loading="lazy" />
</div> </div>
</div> </div>
+1 -1
View File
@@ -198,7 +198,7 @@ export default function AdminDashboard() {
<div className="stat-value">{stats.total_users}</div> <div className="stat-value">{stats.total_users}</div>
<div className="stat-label">Total Users</div> <div className="stat-label">Total Users</div>
</div> </div>
<div className="stat-card"> <div className="stat-card accent-green">
<div className="stat-icon"><span className="material-symbols-outlined">security</span></div> <div className="stat-icon"><span className="material-symbols-outlined">security</span></div>
<div className="stat-value">{stats.admins}</div> <div className="stat-value">{stats.admins}</div>
<div className="stat-label">Admin Accounts</div> <div className="stat-label">Admin Accounts</div>
+36 -9
View File
@@ -108,7 +108,7 @@ export default function AdminUserDetail() {
} else { } else {
alert("Failed to delete user"); alert("Failed to delete user");
} }
} catch (err) { } catch (err) { console.error(err);
console.error("Error deleting user", err); console.error("Error deleting user", err);
} }
}; };
@@ -128,7 +128,7 @@ export default function AdminUserDetail() {
const data = await res.json(); const data = await res.json();
showToast(data.detail || "Failed to change role", "error"); showToast(data.detail || "Failed to change role", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Network error", "error"); showToast("Network error", "error");
} }
}; };
@@ -147,7 +147,7 @@ export default function AdminUserDetail() {
} else { } else {
showToast("Failed to save review status", "error"); showToast("Failed to save review status", "error");
} }
} catch (err) { } catch (err) { console.error(err);
console.error("Approval error", err); console.error("Approval error", err);
showToast("Approval error", "error"); showToast("Approval error", "error");
} }
@@ -185,7 +185,7 @@ export default function AdminUserDetail() {
} else { } else {
showToast("Failed to upload admin document", "error"); showToast("Failed to upload admin document", "error");
} }
} catch(err) { } catch (err) { console.error(err);
showToast("Upload failed", "error"); showToast("Upload failed", "error");
} }
}; };
@@ -199,11 +199,32 @@ export default function AdminUserDetail() {
} else { } else {
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
}; };
const handleUpdateExtractedData = async (docId, type, newData) => {
try {
const res = await authFetch(`/api/upload/${type}-documents/${docId}/extracted-data`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ extracted_data: newData })
});
if (res.ok) {
showToast("AI Summary updated successfully", "success");
fetchUserDetails();
} else {
showToast("Failed to update AI Summary", "error");
throw new Error("Failed to update");
}
} catch (err) {
console.error(err);
showToast("Network error while updating", "error");
throw err;
}
};
const sendEmail = async (type) => { const sendEmail = async (type) => {
const docsToReview = documents.filter(d => d.type === type); const docsToReview = documents.filter(d => d.type === type);
const approved = docsToReview.filter(d => d.review_status === "approved").map(d => d.doc_type); const approved = docsToReview.filter(d => d.review_status === "approved").map(d => d.doc_type);
@@ -232,7 +253,7 @@ export default function AdminUserDetail() {
} else { } else {
showToast("Failed to send email", "error"); showToast("Failed to send email", "error");
} }
} catch(err) { } catch (err) { console.error(err);
showToast("Error sending email", "error"); showToast("Error sending email", "error");
} }
}; };
@@ -250,7 +271,7 @@ export default function AdminUserDetail() {
} else { } else {
showToast("Failed to submit", "error"); showToast("Failed to submit", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Error submitting documents", "error"); showToast("Error submitting documents", "error");
} }
}; };
@@ -390,7 +411,10 @@ export default function AdminUserDetail() {
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span> <span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span>
AI Summary AI Summary
</div> </div>
<ExpandableSummaryBlock extractedData={doc.extracted_data} /> <ExpandableSummaryBlock
extractedData={doc.extracted_data}
onSave={(newData) => handleUpdateExtractedData(doc.id, doc.type, newData)}
/>
</div> </div>
) : doc.extracted_data === null ? ( ) : doc.extracted_data === null ? (
<div className="ai-summary-block" style={{ opacity: 0.6 }}> <div className="ai-summary-block" style={{ opacity: 0.6 }}>
@@ -465,7 +489,10 @@ export default function AdminUserDetail() {
<span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span> <span className="material-symbols-outlined" style={{ fontSize: '14px', verticalAlign: 'middle', marginRight: '4px' }}>auto_awesome</span>
AI Summary AI Summary
</div> </div>
<ExpandableSummaryBlock extractedData={doc.extracted_data} /> <ExpandableSummaryBlock
extractedData={doc.extracted_data}
onSave={(newData) => handleUpdateExtractedData(doc.id, doc.type, newData)}
/>
</div> </div>
) : doc.extracted_data === null ? ( ) : doc.extracted_data === null ? (
<div className="ai-summary-block" style={{ opacity: 0.6 }}> <div className="ai-summary-block" style={{ opacity: 0.6 }}>
+2 -2
View File
@@ -29,7 +29,7 @@ export default function Contact() {
phone: '', phone: '',
message: '' message: ''
}); });
} catch (err) { } catch (err) { console.error(err);
alert("Failed to send message"); alert("Failed to send message");
} finally { } finally {
setLoading(false); setLoading(false);
@@ -42,7 +42,7 @@ export default function Contact() {
return ( return (
<> <>
<div className="page-hero" style={{ '--hero-img': 'url("/images/home-background.jpg")' }}> <div className="page-hero" style={{ '--hero-img': 'url("/images/home-background.webp")' }}>
<div className="page-hero-inner"> <div className="page-hero-inner">
<span className="eyebrow">Get in touch</span> <span className="eyebrow">Get in touch</span>
<h1>Let's talk about your books</h1> <h1>Let's talk about your books</h1>
+5 -5
View File
@@ -4,17 +4,17 @@ const SERVICES = [
{ {
label: 'Bookkeeping', label: 'Bookkeeping',
title: 'Monthly books, closed clean and on time', title: 'Monthly books, closed clean and on time',
img: '/images/services-1.jpg', img: '/images/services-1.webp',
}, },
{ {
label: 'Payroll', label: 'Payroll',
title: 'Payroll runs your team can set a clock by', title: 'Payroll runs your team can set a clock by',
img: '/images/services-2.jpg', img: '/images/services-2.webp',
}, },
{ {
label: 'Tax', label: 'Tax',
title: 'Tax planning and prep built around your entity', title: 'Tax planning and prep built around your entity',
img: '/images/services-3.jpg', img: '/images/services-3.webp',
}, },
]; ];
@@ -71,7 +71,7 @@ export default function Home() {
<p className="note">— Our people are passionate about what we do</p> <p className="note">— Our people are passionate about what we do</p>
</div> </div>
<div className="about-media"> <div className="about-media">
<img src="/images/home-about.jpg" alt="BookKeepPro team at work" /> <img src="/images/home-about.webp" alt="BookKeepPro team at work" width="800" height="533" loading="lazy" />
</div> </div>
</section> </section>
@@ -85,7 +85,7 @@ export default function Home() {
{SERVICES.map((s) => ( {SERVICES.map((s) => (
<div className="service-card fade-up" key={s.label}> <div className="service-card fade-up" key={s.label}>
<div className="service-media"> <div className="service-media">
<img src={s.img} alt={s.title} /> <img src={s.img} alt={s.title} width="600" height="400" loading="lazy" />
</div> </div>
<div className="service-body"> <div className="service-body">
<span className="service-label">{s.label}</span> <span className="service-label">{s.label}</span>
+11 -1
View File
@@ -29,7 +29,17 @@ export default function Login() {
setError("EMAIL_NOT_VERIFIED"); setError("EMAIL_NOT_VERIFIED");
return; return;
} }
throw new Error(errData.detail || "Invalid credentials"); let errorMsg = "Invalid credentials";
if (errData.detail) {
if (typeof errData.detail === 'string') {
errorMsg = errData.detail;
} else if (Array.isArray(errData.detail)) {
errorMsg = errData.detail.map(err => err.msg).join(", ");
} else {
errorMsg = JSON.stringify(errData.detail);
}
}
throw new Error(errorMsg);
} }
const data = await res.json(); const data = await res.json();
+11 -1
View File
@@ -37,7 +37,17 @@ export default function Profile() {
if (!res.ok) { if (!res.ok) {
const data = await res.json(); const data = await res.json();
throw new Error(data.detail || "Failed to update profile"); let errorMsg = "Failed to update profile";
if (data.detail) {
if (typeof data.detail === 'string') {
errorMsg = data.detail;
} else if (Array.isArray(data.detail)) {
errorMsg = data.detail.map(err => err.msg).join(", ");
} else {
errorMsg = JSON.stringify(data.detail);
}
}
throw new Error(errorMsg);
} }
alert("Profile updated successfully. Please log in again if you changed your password."); alert("Profile updated successfully. Please log in again if you changed your password.");
+11 -1
View File
@@ -33,7 +33,17 @@ export default function ResetPassword() {
const data = await res.json(); const data = await res.json();
if (!res.ok) { if (!res.ok) {
throw new Error(data.detail || "Password reset failed"); let errorMsg = "Password reset failed";
if (data.detail) {
if (typeof data.detail === 'string') {
errorMsg = data.detail;
} else if (Array.isArray(data.detail)) {
errorMsg = data.detail.map(err => err.msg).join(", ");
} else {
errorMsg = JSON.stringify(data.detail);
}
}
throw new Error(errorMsg);
} }
setMessage("Password reset! Redirecting to sign in..."); setMessage("Password reset! Redirecting to sign in...");
+3 -3
View File
@@ -25,7 +25,7 @@ export default function Services() {
benefits to global accounting firms and businesses. benefits to global accounting firms and businesses.
</p> </p>
</div> </div>
<img className="service-img" src="/images/services-3.jpg" alt="Accounting Outsourcing" /> <img className="service-img" src="/images/services-3.webp" alt="Accounting Outsourcing" width="600" height="400" loading="lazy" />
</div> </div>
<div className="service-block reverse reveal"> <div className="service-block reverse reveal">
@@ -43,7 +43,7 @@ export default function Services() {
background so yours doesn't have to. background so yours doesn't have to.
</p> </p>
</div> </div>
<img className="service-img-bl-3" src="/images/services-2.jpg" alt="Outsourced Accounting Team" /> <img className="service-img-bl-3" src="/images/services-2.webp" alt="Outsourced Accounting Team" width="600" height="400" loading="lazy" />
</div> </div>
<div className="service-block reveal"> <div className="service-block reveal">
@@ -68,7 +68,7 @@ export default function Services() {
cash flow — the foundation of a proactive, confident tax plan. cash flow — the foundation of a proactive, confident tax plan.
</p> </p>
</div> </div>
<img className="service-img" src="/images/services-1.jpg" alt="Tax Services" /> <img className="service-img" src="/images/services-1.webp" alt="Tax Services" width="600" height="400" loading="lazy" />
</div> </div>
</div> </div>
</> </>
+11 -1
View File
@@ -22,7 +22,17 @@ export default function Signup() {
if (!res.ok) { if (!res.ok) {
const data = await res.json(); const data = await res.json();
throw new Error(data.detail || "Signup failed"); let errorMsg = "Signup failed";
if (data.detail) {
if (typeof data.detail === 'string') {
errorMsg = data.detail;
} else if (Array.isArray(data.detail)) {
errorMsg = data.detail.map(err => err.msg).join(", ");
} else {
errorMsg = JSON.stringify(data.detail);
}
}
throw new Error(errorMsg);
} }
// Success, route to login with message // Success, route to login with message
+6 -4
View File
@@ -57,7 +57,7 @@ export default function UploadBusiness() {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
showToast(data.detail || "Upload failed", "error"); showToast(data.detail || "Upload failed", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Upload failed due to network error", "error"); showToast("Upload failed due to network error", "error");
} }
}; };
@@ -72,7 +72,7 @@ export default function UploadBusiness() {
} else { } else {
showToast("Delete failed", "error"); showToast("Delete failed", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Delete failed", "error"); showToast("Delete failed", "error");
} }
}; };
@@ -86,7 +86,7 @@ export default function UploadBusiness() {
} else { } else {
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
}; };
@@ -123,7 +123,7 @@ export default function UploadBusiness() {
} else { } else {
showToast("Failed to notify admin", "error"); showToast("Failed to notify admin", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Error notifying admin", "error"); showToast("Error notifying admin", "error");
} }
}; };
@@ -169,6 +169,8 @@ export default function UploadBusiness() {
<div className="doc-slot-status"> <div className="doc-slot-status">
{uploaded.length ? ( {uploaded.length ? (
<span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span> <span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span>
) : dt.download ? (
<a href={dt.download} target="_blank" rel="noopener noreferrer" className="btn-link" style={{ fontSize: '14px', color: 'var(--brand)', textDecoration: 'underline' }}>View Template</a>
) : ( ) : (
"Missing" "Missing"
)} )}
+6 -4
View File
@@ -59,7 +59,7 @@ export default function UploadPersonal() {
const data = await res.json().catch(() => ({})); const data = await res.json().catch(() => ({}));
showToast(data.detail || "Upload failed", "error"); showToast(data.detail || "Upload failed", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Upload failed due to network error", "error"); showToast("Upload failed due to network error", "error");
} }
}; };
@@ -74,7 +74,7 @@ export default function UploadPersonal() {
} else { } else {
showToast("Delete failed", "error"); showToast("Delete failed", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Delete failed", "error"); showToast("Delete failed", "error");
} }
}; };
@@ -88,7 +88,7 @@ export default function UploadPersonal() {
} else { } else {
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
}; };
@@ -125,7 +125,7 @@ export default function UploadPersonal() {
} else { } else {
showToast("Failed to notify admin", "error"); showToast("Failed to notify admin", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Error notifying admin", "error"); showToast("Error notifying admin", "error");
} }
}; };
@@ -171,6 +171,8 @@ export default function UploadPersonal() {
<div className="doc-slot-status"> <div className="doc-slot-status">
{uploaded.length ? ( {uploaded.length ? (
<span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span> <span className="pill-pending"><span className="material-symbols-outlined">pending</span> Pending Review</span>
) : dt.download ? (
<a href={dt.download} target="_blank" rel="noopener noreferrer" className="btn-link" style={{ fontSize: '14px', color: 'var(--brand)', textDecoration: 'underline' }}>View Template</a>
) : ( ) : (
"Missing" "Missing"
)} )}
+137 -4
View File
@@ -12,6 +12,8 @@ export default function UserDashboard() {
const [adminDocs, setAdminDocs] = useState([]); const [adminDocs, setAdminDocs] = useState([]);
const [loadingDocs, setLoadingDocs] = useState(false); const [loadingDocs, setLoadingDocs] = useState(false);
const [docLoading, setDocLoading] = useState(false); const [docLoading, setDocLoading] = useState(false);
// Track which doc rows have the AI summary panel open
const [expandedSummary, setExpandedSummary] = useState({});
// ── declare callbacks BEFORE the effects that reference them ── // ── declare callbacks BEFORE the effects that reference them ──
@@ -49,6 +51,14 @@ export default function UserDashboard() {
loadAdminDocs(); loadAdminDocs();
}, [checkEngagement, loadAdminDocs]); }, [checkEngagement, loadAdminDocs]);
// Poll every 15s while any doc still has ai_summary === null (backend still processing)
useEffect(() => {
const hasPending = adminDocs.some(d => d.ai_summary === null);
if (!hasPending) return;
const timer = setInterval(loadAdminDocs, 15000);
return () => clearInterval(timer);
}, [adminDocs, loadAdminDocs]);
const handleEngagementChange = async (e) => { const handleEngagementChange = async (e) => {
const isChecked = e.target.checked; const isChecked = e.target.checked;
if (!isChecked) { if (!isChecked) {
@@ -64,7 +74,7 @@ export default function UserDashboard() {
} else { } else {
setEngagementChecked(false); setEngagementChecked(false);
} }
} catch (err) { } catch (err) { console.error(err);
setEngagementChecked(false); setEngagementChecked(false);
} }
}; };
@@ -78,7 +88,7 @@ export default function UserDashboard() {
} else { } else {
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Could not generate view link", "error"); showToast("Could not generate view link", "error");
} }
}; };
@@ -102,13 +112,17 @@ export default function UserDashboard() {
} else { } else {
showToast("Failed to submit response", "error"); showToast("Failed to submit response", "error");
} }
} catch (err) { } catch (err) { console.error(err);
showToast("Network error", "error"); showToast("Network error", "error");
} finally { } finally {
setDocLoading(false); setDocLoading(false);
} }
}; };
const toggleSummary = (docId) => {
setExpandedSummary(prev => ({ ...prev, [docId]: !prev[docId] }));
};
return ( return (
<div> <div>
<div className="page-heading"> <div className="page-heading">
@@ -192,6 +206,7 @@ export default function UserDashboard() {
</thead> </thead>
<tbody> <tbody>
{adminDocs.map(doc => ( {adminDocs.map(doc => (
<>
<tr key={doc.id}> <tr key={doc.id}>
<td> <td>
<div style={{fontWeight: 500, color: 'var(--navy)'}}>{doc.doc_label}</div> <div style={{fontWeight: 500, color: 'var(--navy)'}}>{doc.doc_label}</div>
@@ -199,13 +214,131 @@ export default function UserDashboard() {
</td> </td>
<td>{new Date(doc.created_at).toLocaleDateString()}</td> <td>{new Date(doc.created_at).toLocaleDateString()}</td>
<td> <td>
<div style={{display:'flex', gap:'8px'}}> <div style={{display:'flex', gap:'8px', flexWrap:'wrap', alignItems:'center'}}>
<button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button> <button className="btn btn-secondary btn-sm" onClick={() => viewDoc(doc.storage_key)}>View</button>
<button className="btn btn-primary btn-sm" onClick={() => respondDoc(doc.id, true)} disabled={docLoading}>Approve</button> <button className="btn btn-primary btn-sm" onClick={() => respondDoc(doc.id, true)} disabled={docLoading}>Approve</button>
<button className="btn btn-danger btn-sm" onClick={() => respondDoc(doc.id, false)} disabled={docLoading}>Reject</button> <button className="btn btn-danger btn-sm" onClick={() => respondDoc(doc.id, false)} disabled={docLoading}>Reject</button>
{/* AI Summary badge / button */}
{doc.ai_summary === null ? (
<span style={{
display: 'inline-flex', alignItems: 'center', gap: '6px',
fontSize: '11.5px', fontWeight: 500,
color: 'var(--brass-dark)',
padding: '5px 12px', borderRadius: 'var(--radius-pill)',
background: 'var(--brass-light)',
border: '1px solid rgba(176,128,61,0.25)',
letterSpacing: '0.01em',
}}>
<span style={{display:'inline-block', animation:'spin 1.5s linear infinite', fontSize:'13px'}}>✦</span>
Analyzing…
</span>
) : doc.ai_summary ? (
<button
onClick={() => toggleSummary(doc.id)}
style={{
display: 'inline-flex', alignItems: 'center', gap: '6px',
fontSize: '11.5px', fontWeight: 600,
padding: '5px 14px', borderRadius: 'var(--radius-pill)',
border: expandedSummary[doc.id]
? '1px solid var(--accent)'
: '1px solid rgba(44,122,91,0.35)',
cursor: 'pointer',
background: expandedSummary[doc.id]
? 'var(--accent)'
: 'linear-gradient(135deg, rgba(44,122,91,0.10) 0%, rgba(31,93,70,0.06) 100%)',
color: expandedSummary[doc.id] ? '#fff' : 'var(--accent)',
boxShadow: expandedSummary[doc.id] ? 'var(--shadow-sm)' : 'none',
transition: 'all 0.22s ease',
letterSpacing: '0.01em',
}}
>
<span style={{fontSize:'13px'}}>✨</span>
{expandedSummary[doc.id] ? 'Hide Summary' : 'AI Summary'}
</button>
) : null}
</div> </div>
</td> </td>
</tr> </tr>
{/* Expanded AI Summary panel — spans full row width */}
{expandedSummary[doc.id] && doc.ai_summary && (
<tr key={`${doc.id}-summary`}>
<td colSpan={3} style={{padding: '0 0 14px'}}>
<div style={{
display: 'flex',
borderRadius: 'var(--radius-md)',
overflow: 'hidden',
border: '1px solid rgba(44,122,91,0.20)',
boxShadow: '0 4px 20px -6px rgba(44,122,91,0.18)',
background: 'linear-gradient(135deg, rgba(44,122,91,0.07) 0%, rgba(31,93,70,0.03) 100%)',
backdropFilter: 'blur(8px)',
animation: 'fadeUp 0.2s ease',
}}>
{/* Left accent strip */}
<div style={{
width: '4px', flexShrink: 0,
background: 'linear-gradient(180deg, var(--accent) 0%, var(--brass) 100%)',
}} />
<div style={{padding: '16px 20px', flex: 1}}>
{/* Header row */}
<div style={{
display: 'flex', alignItems: 'center', gap: '8px',
marginBottom: '10px'
}}>
<div style={{
width: '28px', height: '28px', borderRadius: 'var(--radius-xs)',
background: 'linear-gradient(135deg, var(--accent) 0%, var(--emerald-dark) 100%)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: '14px', flexShrink: 0,
boxShadow: '0 2px 8px rgba(44,122,91,0.30)',
}}>
✨
</div>
<div>
<div style={{
fontSize: '10px', fontWeight: 700,
letterSpacing: '0.08em', textTransform: 'uppercase',
color: 'var(--accent)',
}}>AI Document Summary</div>
<div style={{
fontSize: '11px', color: 'var(--muted)', marginTop: '1px'
}}>Generated by BookKeepPro AI</div>
</div>
</div>
{/* Summary text */}
<p style={{
fontSize: '13.5px', lineHeight: '1.7',
color: 'var(--ink)',
margin: 0,
fontFamily: 'var(--font-body)',
}}>
{doc.ai_summary}
</p>
{/* Footer disclaimer */}
<div style={{
display: 'flex', alignItems: 'center', gap: '6px',
marginTop: '12px',
paddingTop: '10px',
borderTop: '1px solid rgba(44,122,91,0.12)',
}}>
<span style={{fontSize:'11px', color:'var(--muted)'}}>⚠</span>
<span style={{
fontSize: '11px', color: 'var(--muted)',
fontStyle: 'italic',
}}>
AI-generated summary — always review the original document for authoritative information.
</span>
</div>
</div>
</div>
</td>
</tr>
)}
</>
))} ))}
</tbody> </tbody>
</table> </table>
+1 -1
View File
@@ -26,7 +26,7 @@ export default function VerifyEmail() {
setStatus('failed'); setStatus('failed');
setMessage(data.detail || "This link is invalid or has expired."); setMessage(data.detail || "This link is invalid or has expired.");
} }
} catch (err) { } catch (err) { console.error(err);
setStatus('failed'); setStatus('failed');
setMessage("Could not connect to the server. Please try again later."); setMessage("Could not connect to the server. Please try again later.");
} }
+5 -1
View File
@@ -1,9 +1,13 @@
import { defineConfig } from 'vite' import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [
tailwindcss(),
react(),
],
server: { server: {
proxy: { proxy: {
'/api': { '/api': {
+46 -6
View File
@@ -1,9 +1,10 @@
import os import os
import logging import logging
from pathlib import Path
from fastapi import FastAPI, HTTPException from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse from fastapi.responses import FileResponse, PlainTextResponse
from slowapi import _rate_limit_exceeded_handler from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded from slowapi.errors import RateLimitExceeded
from app.limiter import limiter from app.limiter import limiter
@@ -85,15 +86,34 @@ DIST_DIR = os.path.join(FRONTEND_DIR, "dist")
SPA_INDEX = os.path.join(DIST_DIR, "index.html") SPA_INDEX = os.path.join(DIST_DIR, "index.html")
def _mount_if_exists(route: str, path: str, name: str) -> None: class CachedStaticFiles(StaticFiles):
"""StaticFiles subclass that injects Cache-Control headers."""
def __init__(self, *args, max_age: int = 86400, immutable: bool = False, **kwargs):
super().__init__(*args, **kwargs)
parts = [f"public, max-age={max_age}"]
if immutable:
parts.append("immutable")
self._cache_control = ", ".join(parts)
async def get_response(self, path, scope): # type: ignore[override]
resp = await super().get_response(path, scope)
resp.headers["Cache-Control"] = self._cache_control
return resp
def _mount_cached(route: str, path: str, name: str, **kwargs) -> None:
if os.path.isdir(path): if os.path.isdir(path):
app.mount(route, StaticFiles(directory=path), name=name) app.mount(route, CachedStaticFiles(directory=path, **kwargs), name=name)
log.info("Mounted static %s → %s", route, path) log.info("Mounted static %s → %s", route, path)
_mount_if_exists("/css", os.path.join(DIST_DIR, "css"), "css") # Hashed filenames — cache forever
_mount_if_exists("/assets", os.path.join(DIST_DIR, "assets"), "assets") _mount_cached("/assets", os.path.join(DIST_DIR, "assets"), "assets",
_mount_if_exists("/images", os.path.join(DIST_DIR, "images"), "images") max_age=31_536_000, immutable=True)
# Images & CSS — cache for 1 day
_mount_cached("/css", os.path.join(DIST_DIR, "css"), "css", max_age=86_400)
_mount_cached("/images", os.path.join(DIST_DIR, "images"), "images", max_age=86_400)
# Ensure uploads directory exists # Ensure uploads directory exists
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads")) UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
@@ -113,6 +133,26 @@ def logout():
return {"message": "Logged out"} return {"message": "Logged out"}
# ─────────────────────────────────────────────
# Crawler files — must be served BEFORE the SPA catch-all
# ─────────────────────────────────────────────
@app.get("/robots.txt", tags=["seo"])
def robots_txt():
robots_path = os.path.join(DIST_DIR, "robots.txt")
if os.path.isfile(robots_path):
return FileResponse(robots_path, media_type="text/plain")
return PlainTextResponse("User-agent: *\nAllow: /\n")
@app.get("/llms.txt", tags=["seo"])
def llms_txt():
llms_path = os.path.join(DIST_DIR, "llms.txt")
if os.path.isfile(llms_path):
return FileResponse(llms_path, media_type="text/plain")
return PlainTextResponse("# BookKeepPro\n")
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
# SPA catch-all — serve index.html for all non-API routes # SPA catch-all — serve index.html for all non-API routes
# React Router handles client-side navigation # React Router handles client-side navigation
+40 -1
View File
@@ -7,6 +7,7 @@ from sqlalchemy import (
Index, Index,
Integer, Integer,
String, String,
Text,
JSON, JSON,
UniqueConstraint, UniqueConstraint,
func, func,
@@ -121,6 +122,9 @@ class AdminDocument(Base):
uploaded_by = Column(Integer, ForeignKey("users.id"), nullable=False) # admin user uploaded_by = Column(Integer, ForeignKey("users.id"), nullable=False) # admin user
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) # target client user_id = Column(Integer, ForeignKey("users.id"), nullable=False) # target client
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None) deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
# AI-generated plain-English summary — populated by background task after upload
# None = still processing, non-null = ready to display
ai_summary = Column(Text, nullable=True)
admin = relationship("User", foreign_keys=[uploaded_by]) admin = relationship("User", foreign_keys=[uploaded_by])
user = relationship("User", foreign_keys=[user_id]) user = relationship("User", foreign_keys=[user_id])
@@ -177,9 +181,44 @@ class RequiredDocumentTemplate(Base):
category = Column(String(50), nullable=False) # 'personal' or 'business' category = Column(String(50), nullable=False) # 'personal' or 'business'
tax_year = Column(Integer, nullable=False) tax_year = Column(Integer, nullable=False)
name = Column(String(200), nullable=False) name = Column(String(200), nullable=False)
file_url = Column(String(500), nullable=True) # Null if there is no template file to download # storage_key: raw filename on disk (e.g. "abc123.pdf"). Fresh presigned URLs
# are generated on every read from this key. Replaces the old file_url pattern
# that baked an expiring JWT into the stored value.
storage_key = Column(String(500), nullable=True)
# file_url kept for backward-compat; self-healed at read time if storage_key is missing
file_url = Column(String(500), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now()) created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = ( __table_args__ = (
UniqueConstraint("category", "tax_year", "name", name="uq_template_cat_year_name"), UniqueConstraint("category", "tax_year", "name", name="uq_template_cat_year_name"),
) )
# ─────────────────────────────────────────────
# Chat Models
# ─────────────────────────────────────────────
class ChatSession(Base):
__tablename__ = "chat_sessions"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
session_id = Column(String(100), unique=True, index=True, nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan", order_by="ChatMessage.created_at")
class ChatMessage(Base):
__tablename__ = "chat_messages"
id = Column(Integer, primary_key=True, index=True)
session_id = Column(Integer, ForeignKey("chat_sessions.id"), nullable=False)
role = Column(String(50), nullable=False) # 'user', 'assistant', 'system', 'tool'
content = Column(Text, nullable=True)
tool_calls = Column(JSON, nullable=True)
tool_call_id = Column(String(200), nullable=True)
name = Column(String(200), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
session = relationship("ChatSession", back_populates="messages")
+226 -75
View File
@@ -1,5 +1,6 @@
import logging import logging
import json import json
import uuid
from datetime import datetime, date from datetime import datetime, date
from fastapi import APIRouter, Depends, Request, Query from fastapi import APIRouter, Depends, Request, Query
from fastapi.responses import StreamingResponse from fastapi.responses import StreamingResponse
@@ -10,7 +11,7 @@ import os
import requests import requests
from pydantic import BaseModel, field_validator from pydantic import BaseModel, field_validator
from fastapi import HTTPException from fastapi import HTTPException
from app.models import PersonalDocument, BusinessDocument, User, AuditLog from app.models import PersonalDocument, BusinessDocument, User, AuditLog, ChatSession, ChatMessage as DBChatMessage
from app.db import get_db from app.db import get_db
from app.auth.security import get_current_user, require_admin from app.auth.security import get_current_user, require_admin
@@ -20,7 +21,6 @@ router = APIRouter(prefix="/api/chatbot", tags=["chatbot"])
CHAT_MODEL = os.getenv("CHAT_MODEL", "meta-llama/llama-3.3-70b-instruct") CHAT_MODEL = os.getenv("CHAT_MODEL", "meta-llama/llama-3.3-70b-instruct")
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# User: doc status (also includes extracted data so user can ask about fields) # User: doc status (also includes extracted data so user can ask about fields)
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@@ -45,7 +45,6 @@ def get_doc_status(
personal_list = [ personal_list = [
{"doc_type": d.doc_type, "status": d.review_status, "note": d.review_note, {"doc_type": d.doc_type, "status": d.review_status, "note": d.review_note,
"tax_year": d.tax_year, "filename": d.filename, "tax_year": d.tax_year, "filename": d.filename,
# Include extracted data summary so chatbot can answer field-level questions
"extracted_summary": _summarize_extracted(d.extracted_data)} "extracted_summary": _summarize_extracted(d.extracted_data)}
for d in personal for d in personal
] ]
@@ -81,7 +80,6 @@ def get_doc_status(
def _summarize_extracted(extracted_data: dict | None) -> str: def _summarize_extracted(extracted_data: dict | None) -> str:
"""Convert extracted_data dict to a compact string for chatbot context."""
if not extracted_data: if not extracted_data:
return "" return ""
skip = {"_meta", "status"} skip = {"_meta", "status"}
@@ -93,7 +91,7 @@ def _summarize_extracted(extracted_data: dict | None) -> str:
parts.append(f"{k}: {', '.join(str(i) for i in v[:3])}") parts.append(f"{k}: {', '.join(str(i) for i in v[:3])}")
else: else:
parts.append(f"{k}: {v}") parts.append(f"{k}: {v}")
return " | ".join(parts[:8]) # cap at 8 fields to keep context small return " | ".join(parts[:8])
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
@@ -132,7 +130,7 @@ def get_admin_status(
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] + "uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_personal] +
[{"user_id": d.user_id, "doc": d.business_type, "type": "business", [{"user_id": d.user_id, "doc": d.business_type, "type": "business",
"uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business], "uploaded_at": d.uploaded_at, "status": d.review_status} for d in recent_business],
key=lambda x: x["uploaded_at"], reverse=True key=lambda x: x["uploaded_at"].isoformat() if x["uploaded_at"] else "", reverse=True
)[:10] )[:10]
user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()} user_map = {u.id: u for u in db.query(User).filter(User.id.in_([r["user_id"] for r in recent_uploads])).all()}
@@ -163,25 +161,18 @@ def get_admin_status(
} }
# ─────────────────────────────────────────────────────────────────────────────
# Admin: daily digest (new)
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/daily-digest") @router.get("/daily-digest")
def get_daily_digest( def get_daily_digest(
db: Session = Depends(get_db), db: Session = Depends(get_db),
current_user=Depends(get_current_user), current_user=Depends(get_current_user),
_=Depends(require_admin), _=Depends(require_admin),
): ):
"""Generate an AI plain-English summary of today's activity."""
from app.utils.doc_intelligence import build_daily_digest from app.utils.doc_intelligence import build_daily_digest
stats = get_admin_status(db=db, current_user=current_user, _=None) stats = get_admin_status(db=db, current_user=current_user, _=None)
digest_html = build_daily_digest(stats) digest_html = build_daily_digest(stats)
return {"digest": digest_html, "generated_at": datetime.now().isoformat()} return {"digest": digest_html, "generated_at": datetime.now().isoformat()}
# ─────────────────────────────────────────────────────────────────────────────
# Admin: user context lookup
# ─────────────────────────────────────────────────────────────────────────────
@router.get("/admin-user-context") @router.get("/admin-user-context")
def get_admin_user_context( def get_admin_user_context(
query: str = Query(...), query: str = Query(...),
@@ -224,14 +215,10 @@ def get_admin_user_context(
} }
# ─────────────────────────────────────────────────────────────────────────────
# Admin: bulk action executor (approve/reject all docs for a user)
# Requires explicit confirm=true to execute — safety gate
# ─────────────────────────────────────────────────────────────────────────────
class BulkActionRequest(BaseModel): class BulkActionRequest(BaseModel):
user_id: int user_id: int
action: str # "approve_personal" | "approve_business" | "reject_personal" | "reject_business" action: str
confirm: bool # must be True to execute — prevents accidental execution confirm: bool
@router.post("/admin-bulk-action") @router.post("/admin-bulk-action")
def admin_bulk_action( def admin_bulk_action(
@@ -240,10 +227,6 @@ def admin_bulk_action(
current_user=Depends(get_current_user), current_user=Depends(get_current_user),
_=Depends(require_admin), _=Depends(require_admin),
): ):
"""
Execute a bulk approve/reject action on all pending docs for a user.
Requires confirm=true — the frontend must show a confirmation dialog first.
"""
if not payload.confirm: if not payload.confirm:
return {"status": "pending_confirm", return {"status": "pending_confirm",
"message": "Action not executed. Set confirm=true to proceed."} "message": "Action not executed. Set confirm=true to proceed."}
@@ -252,10 +235,10 @@ def admin_bulk_action(
if not user: if not user:
raise HTTPException(status_code=404, detail="User not found") raise HTTPException(status_code=404, detail="User not found")
action_parts = payload.action.split("_") # e.g. ["approve", "personal"] action_parts = payload.action.split("_")
if len(action_parts) != 2 or action_parts[0] not in ("approve", "reject") \ if len(action_parts) != 2 or action_parts[0] not in ("approve", "reject") \
or action_parts[1] not in ("personal", "business"): or action_parts[1] not in ("personal", "business"):
raise HTTPException(status_code=400, detail="Invalid action. Use approve_personal, reject_personal, approve_business, or reject_business.") raise HTTPException(status_code=400, detail="Invalid action.")
verb, doc_type = action_parts verb, doc_type = action_parts
new_status = "approved" if verb == "approve" else "rejected" new_status = "approved" if verb == "approve" else "rejected"
@@ -284,24 +267,27 @@ def admin_bulk_action(
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
# Shared chat — streaming (new) + conversation memory via messages[] # Shared chat — streaming (new) + conversation memory via DB
# ───────────────────────────────────────────────────────────────────────────── # ─────────────────────────────────────────────────────────────────────────────
class ChatMessage(BaseModel): class ChatMessageInput(BaseModel):
role: str role: str
content: str content: str | None = None
reasoning_details: list | None = None tool_calls: list | None = None
tool_call_id: str | None = None
name: str | None = None
@field_validator("content") @field_validator("content")
@classmethod @classmethod
def cap_content(cls, v: str) -> str: def cap_content(cls, v: str | None) -> str | None:
if len(v) > 4000: if v and len(v) > 4000:
raise ValueError("Message must be 4000 characters or fewer") raise ValueError("Message must be 4000 characters or fewer")
return v return v
class ChatRequest(BaseModel): class ChatRequest(BaseModel):
messages: list[ChatMessage] message: str | None = None
stream: bool = False # client opts into streaming messages: list[ChatMessageInput] | None = None
stream: bool = False
session_id: str | None = None
def _build_admin_context(db: Session, current_user) -> str: def _build_admin_context(db: Session, current_user) -> str:
status = get_admin_status(db=db, current_user=current_user, _=None) status = get_admin_status(db=db, current_user=current_user, _=None)
@@ -318,6 +304,37 @@ def _build_admin_context(db: Session, current_user) -> str:
f"'{r['doc']}' on {r['uploaded_at']} [{r['status']}]\n") f"'{r['doc']}' on {r['uploaded_at']} [{r['status']}]\n")
return ctx return ctx
@router.get("/history")
def get_chat_history(
session_id: str | None = None,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
if not session_id:
return {"session_id": str(uuid.uuid4()), "messages": []}
session = db.query(ChatSession).filter(
ChatSession.session_id == session_id,
ChatSession.user_id == current_user.id
).first()
if not session:
return {"session_id": session_id, "messages": []}
msgs = []
for m in session.messages:
if m.role == "system":
continue
msg = {"role": m.role, "content": m.content}
if m.tool_calls:
msg["tool_calls"] = m.tool_calls
if m.tool_call_id:
msg["tool_call_id"] = m.tool_call_id
if m.name:
msg["name"] = m.name
msgs.append(msg)
return {"session_id": session_id, "messages": msgs}
@router.post("/ask") @router.post("/ask")
@limiter.limit("10/minute") @limiter.limit("10/minute")
@@ -335,40 +352,15 @@ def ask_chatbot(
if is_admin: if is_admin:
context = _build_admin_context(db, current_user) context = _build_admin_context(db, current_user)
last_user_msg = next((m.content for m in reversed(req.messages) if m.role == "user"), "")
user_context_addon = ""
if any(kw in last_user_msg.lower() for kw in ["user", "who", "activity", "uploaded", "registered", "recent"]):
words = last_user_msg.replace(",", " ").replace("?", " ").split()
for word in words:
if "@" in word or len(word) > 4:
result = get_admin_user_context(query=word, db=db, current_user=current_user, _=None)
if result.get("found"):
u = result["user"]
docs = result["documents"]
audit = result["audit_log"]
user_context_addon = f"\n\n=== USER DETAIL: {u['name']} ({u['email']}) ===\n"
user_context_addon += f"Role: {u['role']} | Joined: {u['joined']} | Engagement: {u['engagement_acknowledged']}\n"
if docs["personal"]:
user_context_addon += "Personal: " + "; ".join(
f"{d['doc_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["personal"]) + "\n"
if docs["business"]:
user_context_addon += "Business: " + "; ".join(
f"{d['business_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["business"]) + "\n"
if audit:
user_context_addon += "Activity:\n" + "\n".join(
f" [{a['at']}] {a['action']} — {a['detail'] or ''}"
for a in audit[:8]) + "\n"
break
system_prompt = ( system_prompt = (
"You are the BookKeepPro Admin Assistant with live access to system data.\n\n" "You are the BookKeepPro Admin Assistant with live access to system data.\n\n"
"CAPABILITIES: Answer questions about uploads, user activity, pending docs, registration counts.\n" "CAPABILITIES: Answer questions about uploads, user activity, pending docs, registration counts.\n"
"BULK ACTIONS: When asked to approve/reject all docs for a user, respond with a structured " "BULK ACTIONS: When asked to approve/reject all docs for a user, respond with a structured "
"JSON action block like: {\"bulk_action\": {\"user_id\": N, \"action\": \"approve_personal\", \"confirm\": false}} " "JSON action block like: {\"bulk_action\": {\"user_id\": N, \"action\": \"approve_personal\", \"confirm\": false}} "
"— the frontend will show a confirmation dialog before executing.\n" "— the frontend will show a confirmation dialog before executing.\n"
"TOOLS: Use the lookup_user tool to fetch details about a specific user if their name or email is mentioned.\n"
"RULES: Only answer BookKeepPro, accounting, or tax questions. Use live data. Be concise.\n\n" "RULES: Only answer BookKeepPro, accounting, or tax questions. Use live data. Be concise.\n\n"
f"{context}{user_context_addon}" f"{context}"
) )
else: else:
doc_status = get_doc_status(db=db, current_user=current_user) doc_status = get_doc_status(db=db, current_user=current_user)
@@ -400,24 +392,124 @@ def ask_chatbot(
f"=== LIVE DATA for {current_user.name or current_user.email} ===\n{context}" f"=== LIVE DATA for {current_user.name or current_user.email} ===\n{context}"
) )
# Conversation memory: messages[] from request already contains full history # DB Persistence setup
# The frontend persists this in localStorage and replays it on each call session_id = req.session_id or str(uuid.uuid4())
messages = [{"role": "system", "content": system_prompt}] chat_session = db.query(ChatSession).filter(ChatSession.session_id == session_id).first()
for m in req.messages:
messages.append({"role": m.role, "content": m.content}) if not chat_session:
chat_session = ChatSession(session_id=session_id, user_id=current_user.id)
db.add(chat_session)
sys_msg = DBChatMessage(role="system", content=system_prompt)
chat_session.messages.append(sys_msg)
db.commit()
# Determine incoming user messages
incoming_messages = []
if req.message:
incoming_messages.append({"role": "user", "content": req.message})
elif req.messages:
# Backward compatibility for old frontend: just grab the last message
last_msg = req.messages[-1]
incoming_messages.append({"role": last_msg.role, "content": last_msg.content})
for m in incoming_messages:
db.add(DBChatMessage(
session_id=chat_session.id,
role=m["role"],
content=m.get("content")
))
db.commit()
# Load full conversation history from DB for the LLM
messages = []
for m in chat_session.messages:
msg = {"role": m.role, "content": m.content}
if m.tool_calls:
msg["tool_calls"] = m.tool_calls
if m.tool_call_id:
msg["tool_call_id"] = m.tool_call_id
if m.name:
msg["name"] = m.name
messages.append(msg)
def _get_payload(current_messages, stream=False):
payload = {"model": CHAT_MODEL, "messages": current_messages, "stream": stream}
if is_admin:
payload["tools"] = [{
"type": "function",
"function": {
"name": "lookup_user",
"description": "Lookup a specific user's details, recent activity, and document uploads using their name or email.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The name or email of the user to search for."
}
},
"required": ["query"],
"additionalProperties": False
}
}
}]
return payload
def _execute_tools(tool_calls, current_messages):
for tc in tool_calls:
if tc.get("function", {}).get("name") == "lookup_user":
try:
args = json.loads(tc["function"]["arguments"])
except:
args = {}
result = get_admin_user_context(query=args.get("query", ""), db=db, current_user=current_user, _=None)
tool_result_str = ""
if result.get("found"):
u = result["user"]
docs = result["documents"]
audit = result["audit_log"]
tool_result_str = f"USER DETAIL: {u['name']} ({u['email']})\nRole: {u['role']} | Joined: {u['joined']}\n"
if docs["personal"]:
tool_result_str += "Personal: " + "; ".join(f"{d['doc_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["personal"]) + "\n"
if docs["business"]:
tool_result_str += "Business: " + "; ".join(f"{d['business_type']} ({d['tax_year']}) [{d['status']}]" for d in docs["business"]) + "\n"
if audit:
tool_result_str += "Activity:\n" + "\n".join(f"[{a['at']}] {a['action']} - {a['detail'] or ''}" for a in audit[:5])
else:
tool_result_str = "User not found."
tool_msg = {
"role": "tool",
"tool_call_id": tc["id"],
"name": tc["function"]["name"],
"content": tool_result_str
}
current_messages.append(tool_msg)
db.add(DBChatMessage(
session_id=chat_session.id,
role="tool",
tool_call_id=tc["id"],
name=tc["function"]["name"],
content=tool_result_str
))
db.commit()
# ── Streaming path ────────────────────────────────────────────────────────
if req.stream: if req.stream:
def _stream(): def _stream(current_messages):
try: try:
resp = requests.post( resp = requests.post(
url="https://openrouter.ai/api/v1/chat/completions", url="https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json={"model": CHAT_MODEL, "messages": messages, "stream": True}, json=_get_payload(current_messages, stream=True),
stream=True, stream=True,
timeout=60, timeout=60,
) )
resp.raise_for_status() resp.raise_for_status()
tool_calls_buffer = {}
is_tool_call = False
for line in resp.iter_lines(): for line in resp.iter_lines():
if line and line != b"data: [DONE]": if line and line != b"data: [DONE]":
raw = line.decode("utf-8") raw = line.decode("utf-8")
@@ -426,25 +518,67 @@ def ask_chatbot(
try: try:
chunk = json.loads(raw) chunk = json.loads(raw)
delta = chunk["choices"][0].get("delta", {}) delta = chunk["choices"][0].get("delta", {})
if "tool_calls" in delta:
is_tool_call = True
for tc in delta["tool_calls"]:
idx = tc["index"]
if idx not in tool_calls_buffer:
tool_calls_buffer[idx] = tc
else:
if "function" in tc and "arguments" in tc["function"]:
if "arguments" not in tool_calls_buffer[idx]["function"]:
tool_calls_buffer[idx]["function"]["arguments"] = ""
tool_calls_buffer[idx]["function"]["arguments"] += tc["function"]["arguments"]
token = delta.get("content", "") token = delta.get("content", "")
if token: if token:
# Send SSE event if not hasattr(_stream, "full_content"):
_stream.full_content = ""
_stream.full_content += token
yield f"data: {json.dumps({'token': token})}\n\n" yield f"data: {json.dumps({'token': token})}\n\n"
except Exception: except Exception:
pass pass
if is_tool_call:
tool_calls = list(tool_calls_buffer.values())
tool_msg = {
"role": "assistant",
"content": None,
"tool_calls": tool_calls
}
current_messages.append(tool_msg)
db.add(DBChatMessage(
session_id=chat_session.id,
role="assistant",
content=None,
tool_calls=tool_calls
))
db.commit()
_execute_tools(tool_calls, current_messages)
yield from _stream(current_messages)
else:
if hasattr(_stream, "full_content") and _stream.full_content:
db.add(DBChatMessage(
session_id=chat_session.id,
role="assistant",
content=_stream.full_content
))
db.commit()
_stream.full_content = ""
yield "data: [DONE]\n\n" yield "data: [DONE]\n\n"
except Exception as e: except Exception as e:
logger.error(f"Streaming error: {e}") logger.error(f"Streaming error: {e}")
yield f"data: {json.dumps({'error': str(e)})}\n\n" yield f"data: {json.dumps({'error': str(e)})}\n\n"
return StreamingResponse(_stream(), media_type="text/event-stream") return StreamingResponse(_stream(messages), media_type="text/event-stream")
# ── Non-streaming path (default) ───────────────────────────────────────── def _non_stream(current_messages):
try:
response = requests.post( response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions", url="https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json={"model": CHAT_MODEL, "messages": messages}, json=_get_payload(current_messages, stream=False),
timeout=30, timeout=30,
) )
response.raise_for_status() response.raise_for_status()
@@ -455,8 +589,25 @@ def ask_chatbot(
if "choices" not in data: if "choices" not in data:
raise HTTPException(status_code=502, detail="Unexpected AI response.") raise HTTPException(status_code=502, detail="Unexpected AI response.")
return data["choices"][0]["message"] message = data["choices"][0]["message"]
current_messages.append(message)
db.add(DBChatMessage(
session_id=chat_session.id,
role=message["role"],
content=message.get("content"),
tool_calls=message.get("tool_calls")
))
db.commit()
if "tool_calls" in message:
_execute_tools(message["tool_calls"], current_messages)
return _non_stream(current_messages)
return message
try:
return _non_stream(messages)
except HTTPException: except HTTPException:
raise raise
except Exception as e: except Exception as e:
+104 -15
View File
@@ -16,8 +16,8 @@ from app.db import get_db, SessionLocal
import app.crud as crud import app.crud as crud
from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM
from app.utils.emailer import send_email from app.utils.emailer import send_email
from app.utils.ai import extract_document_data from app.utils.ai import extract_document_data, summarize_admin_document
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate from app.schemas import UploadCompleteNotify, ReviewStatusUpdate, ExtractedDataUpdate
from app.limiter import limiter from app.limiter import limiter
from fastapi import Request from fastapi import Request
@@ -277,6 +277,28 @@ async def upload_admin_document(
crud.log_action(db, "upload_admin_doc", user_id=current_user.id, target=f"admin_doc:{record.id}", detail=f"for user {user_id}") crud.log_action(db, "upload_admin_doc", user_id=current_user.id, target=f"admin_doc:{record.id}", detail=f"for user {user_id}")
# Background task 1: AI summary generation
def _generate_summary(doc_id: int, file_path: str, label: str):
summary = summarize_admin_document(str(file_path), label)
if summary:
_db = SessionLocal()
try:
doc = _db.query(AdminDocument).filter_by(id=doc_id).first()
if doc:
doc.ai_summary = summary
_db.commit()
logger.info(f"[Summary] Saved summary for admin_doc:{doc_id}")
finally:
_db.close()
background.add_task(
_generate_summary,
record.id,
str(UPLOAD_DIR / storage_key),
doc_label,
)
# Background task 2: Notify client by email
background.add_task( background.add_task(
send_email, send_email,
to=target_user.email, to=target_user.email,
@@ -330,6 +352,8 @@ def list_admin_documents(
"filename": d.filename, "filename": d.filename,
"storage_key": d.storage_key, "storage_key": d.storage_key,
"created_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None, "created_at": d.uploaded_at.isoformat() + "Z" if d.uploaded_at else None,
# None = AI still processing; string = ready to show
"ai_summary": d.ai_summary,
} }
for d in docs for d in docs
] ]
@@ -663,6 +687,46 @@ def set_business_review_status(
return {"id": doc_id, "review_status": payload.status} return {"id": doc_id, "review_status": payload.status}
@router.patch("/personal-documents/{doc_id}/extracted-data")
def update_personal_extracted_data(
doc_id: int,
payload: ExtractedDataUpdate,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Admin updates the AI extracted data (JSON) for a personal document."""
doc = db.query(PersonalDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
doc.extracted_data = payload.extracted_data
db.commit()
crud.log_action(db, "update_extracted_data", user_id=current_user.id, target=f"personal_doc:{doc_id}")
return {"id": doc_id, "extracted_data": doc.extracted_data}
@router.patch("/business-documents/{doc_id}/extracted-data")
def update_business_extracted_data(
doc_id: int,
payload: ExtractedDataUpdate,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Admin updates the AI extracted data (JSON) for a business document."""
doc = db.query(BusinessDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
doc.extracted_data = payload.extracted_data
db.commit()
crud.log_action(db, "update_extracted_data", user_id=current_user.id, target=f"business_doc:{doc_id}")
return {"id": doc_id, "extracted_data": doc.extracted_data}
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
# Admin — all documents for one user # Admin — all documents for one user
# ───────────────────────────────────────────── # ─────────────────────────────────────────────
@@ -929,14 +993,31 @@ def list_templates(
.order_by(RequiredDocumentTemplate.id.asc()) .order_by(RequiredDocumentTemplate.id.asc())
.all() .all()
) )
return [
{ results = []
for t in templates:
# Resolve the raw storage key, self-healing old rows that stored a
# pre-baked presigned URL in file_url instead of a bare filename.
raw_key = t.storage_key
if not raw_key and t.file_url:
# Legacy row: extract the filename from a URL like
# "/api/upload/file/abc123.pdf?token=..."
try:
raw_key = t.file_url.split("/api/upload/file/")[1].split("?")[0]
# Persist the self-healed key so next read skips this path
t.storage_key = raw_key
db.commit()
except (IndexError, AttributeError):
raw_key = None
results.append({
"id": t.id, "id": t.id,
"name": t.name, "name": t.name,
"download": get_presigned_url(t.file_url) if t.file_url else None, # Fresh presigned URL generated on every read — never stale
} # Fallback to legacy file_url for static paths like /images/...
for t in templates "download": get_presigned_url(raw_key) if raw_key else t.file_url,
] })
return results
@router.post("/admin/templates") @router.post("/admin/templates")
async def upload_template( async def upload_template(
@@ -952,16 +1033,16 @@ async def upload_template(
if current_user.role != UserRole.super_admin: if current_user.role != UserRole.super_admin:
raise HTTPException(status_code=403, detail="Only super admins can manage templates") raise HTTPException(status_code=403, detail="Only super admins can manage templates")
file_url = None raw_key = None
if file and file.filename: if file and file.filename:
storage_key = await upload_to_storage(file) raw_key = await upload_to_storage(file) # raw filename, e.g. "abc123.pdf"
file_url = storage_key # Store raw key; presigned URLs are generated on-demand in GET
record = RequiredDocumentTemplate( record = RequiredDocumentTemplate(
category=category, category=category,
tax_year=tax_year, tax_year=tax_year,
name=name, name=name,
file_url=file_url, storage_key=raw_key, # store raw key; fresh URLs generated on every read
file_url=None, # no longer used for new rows
) )
try: try:
@@ -975,7 +1056,7 @@ async def upload_template(
return { return {
"id": record.id, "id": record.id,
"name": record.name, "name": record.name,
"download": get_presigned_url(record.file_url) if record.file_url else None, "download": get_presigned_url(record.storage_key) if record.storage_key else None,
} }
@router.delete("/admin/templates/{template_id}") @router.delete("/admin/templates/{template_id}")
@@ -992,8 +1073,16 @@ def delete_template(
if not record: if not record:
raise HTTPException(status_code=404, detail="Template not found") raise HTTPException(status_code=404, detail="Template not found")
if record.file_url: # Delete the physical file — prefer storage_key, fall back to legacy file_url path
delete_from_storage(record.file_url) key_to_delete = record.storage_key
if not key_to_delete and record.file_url:
try:
key_to_delete = record.file_url.split("/api/upload/file/")[1].split("?")[0]
except (IndexError, AttributeError):
key_to_delete = None
if key_to_delete:
delete_from_storage(key_to_delete)
db.delete(record) db.delete(record)
db.commit() db.commit()
+5
View File
@@ -146,6 +146,11 @@ class ReviewStatusUpdate(BaseModel):
return v return v
class ExtractedDataUpdate(BaseModel):
"""Body for PATCH /api/upload/{personal,business}-documents/{id}/extracted-data"""
extracted_data: dict
class PersonalDocumentOut(BaseModel): class PersonalDocumentOut(BaseModel):
+111
View File
@@ -419,3 +419,114 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
except Exception as e: except Exception as e:
logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}") logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}")
return None return None
# ─────────────────────────────────────────────────────────────────────────────
# Admin document summarizer
# ─────────────────────────────────────────────────────────────────────────────
_SUMMARY_SYSTEM_PROMPT = (
"You are a professional CPA's assistant. "
"Your job is to write a short, plain-English summary of a tax or financial document "
"that will be shown to the client on their secure online portal. "
"Be professional, friendly, and concise. "
"Never include sensitive numbers or personally identifiable information in the summary. "
"Respond with ONLY the summary text — no headers, no bullet points, no markdown."
)
def _extract_text_from_file(file_path: str) -> str:
"""Extract raw text from a PDF or image file. Returns empty string on failure."""
try:
if file_path.lower().endswith(".pdf"):
text = ""
try:
reader = PdfReader(file_path)
for page in reader.pages[:5]:
t = page.extract_text()
if t:
text += t + "\n"
except Exception:
pass
if len(text.strip()) < MIN_TEXT_CHARS:
try:
doc = fitz.open(file_path)
mu = "".join(doc[i].get_text() for i in range(min(5, len(doc))))
doc.close()
if len(mu.strip()) > len(text.strip()):
text = mu
except Exception:
pass
if len(text.strip()) < MIN_TEXT_CHARS:
rendered = _render_pdf_page(file_path)
if rendered:
text = _tesseract_text(rendered)
return text.strip()
elif file_path.lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
img = Image.open(file_path)
return _tesseract_text(img).strip()
except Exception as e:
logger.warning(f"[Summary] Text extraction failed for {file_path}: {e}")
return ""
def summarize_admin_document(file_path: str, doc_label: str) -> str | None:
"""
Generate a 2-3 sentence plain-English summary of an admin-uploaded document.
Reuses the existing text extraction pipeline (native PDF text → Tesseract OCR).
Calls the LLM with a client-facing summary prompt instead of a JSON extraction prompt.
Returns:
str — summary text if successful
None — if OPENROUTER_API_KEY not set, file unreadable, or LLM call fails
"""
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
logger.warning("[Summary] OPENROUTER_API_KEY not set — skipping summary")
return None
text = _extract_text_from_file(file_path)
if not text:
logger.info(f"[Summary] No extractable text from {file_path} — skipping")
return "Summary not available for this document type."
prompt = (
f"Document name: {doc_label}\n\n"
f"Document content (first 4000 characters):\n{text[:4000]}\n\n"
"Write a 2-3 sentence plain-English summary of this document for the client. "
"Explain what it is and what they should know about it. "
"Do NOT include any specific dollar amounts, SSNs, EINs, or other sensitive numbers."
)
try:
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": MODEL_TEXT,
"messages": [
{"role": "system", "content": _SUMMARY_SYSTEM_PROMPT},
{"role": "user", "content": prompt},
],
},
timeout=60,
)
response.raise_for_status()
summary = response.json()["choices"][0]["message"]["content"].strip()
logger.info(f"[Summary] Generated {len(summary)} char summary for {doc_label}")
return summary
except Exception as e:
logger.error(f"[Summary] LLM call failed for {doc_label}: {e}")
return None
+4
View File
@@ -75,6 +75,10 @@ def upgrade():
else: else:
print(f" [WARN] Index {table}: {e}") print(f" [WARN] Index {table}: {e}")
# ── v5: Required Document Templates ───────────────────────────────
_add_column(conn, "required_document_templates", "storage_key",
"VARCHAR(500) NULL DEFAULT NULL")
print("\nAll migrations complete.") print("\nAll migrations complete.")
except Exception as e: except Exception as e:
print(f"Migration error: {e}") print(f"Migration error: {e}")